@n-dream/builders-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.
package/README.md CHANGED
@@ -1,11 +1,14 @@
1
1
  # @n-dream/builders-sdk
2
2
 
3
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.
4
+ the signed-in user, AI, notifications and secrets.
5
5
 
6
6
  This package is for apps that the platform made. It does not work on other
7
7
  hosting. The platform sets the environment variables that it needs.
8
8
 
9
+ Since 0.4.0 the package has no database and no file storage. Apps use their
10
+ Firestore database and their bucket with `firebase-admin`, on the server.
11
+
9
12
  ## Install
10
13
 
11
14
  Apps import the package as `@builders/sdk`. Use an npm alias in
@@ -13,7 +16,7 @@ Apps import the package as `@builders/sdk`. Use an npm alias in
13
16
 
14
17
  ```json
15
18
  "dependencies": {
16
- "@builders/sdk": "npm:@n-dream/builders-sdk@^0.3.0"
19
+ "@builders/sdk": "npm:@n-dream/builders-sdk@^0.4.0"
17
20
  }
18
21
  ```
19
22
 
@@ -24,27 +27,22 @@ later.
24
27
 
25
28
  ```ts
26
29
  import { currentUser } from "@builders/sdk/next"; // server code only
27
- import { db, ai, storage, notify, secrets } from "@builders/sdk";
30
+ import { ai, notify, secrets } from "@builders/sdk";
28
31
  import { z } from "zod";
29
32
 
30
33
  const user = await currentUser(); // { email, name }
31
- const notes = db.collection<{ text: string; author: string }>("notes");
32
- await notes.add({ text: "Hello", author: user.email });
33
- await notes.where("author", "==", user.email).limit(20).list();
34
34
 
35
35
  await ai.ask("Summarise: ...", { model: "fast" }); // AI add-on
36
36
  await ai.json("Sort: ...", { schema: z.object({ tag: z.string() }) }); // a checked object
37
37
  await ai.image("A robot mascot"); // also ai.chat, ai.stream, ai.speak, ai.transcribe
38
- await storage.upload("files/a.pdf", bytes); // storage add-on
39
38
  await notify.slack("Done"); // notify add-on
40
39
  await secrets.get("HUBSPOT_API_KEY"); // set in the portal
41
40
  ```
42
41
 
43
- - `db` uses Firestore on the platform. In `next dev` and in tests, it uses
44
- a temporary database in memory. In the Builders dev preview, `ai` and
45
- `notify` work through the platform (notifications go only to you).
46
- - `ai`, `storage` and `notify` are add-ons. If an add-on is off, the call
47
- throws `AddOnNotEnabledError`.
42
+ - In the Builders dev preview, `ai` and `notify` work through the platform
43
+ (notifications go only to you).
44
+ - `ai` and `notify` are add-ons. If an add-on is off, the call throws
45
+ `AddOnNotEnabledError`.
48
46
 
49
47
  ## License
50
48
 
package/dist/index.d.ts CHANGED
@@ -18,41 +18,10 @@ type AiModelChoice = keyof typeof CLAUDE_MODELS;
18
18
  declare const ATTACHMENT_TYPES: readonly ["image/png", "image/jpeg", "image/gif", "image/webp", "application/pdf"];
19
19
  type AttachmentType = (typeof ATTACHMENT_TYPES)[number];
20
20
 
21
- declare function resetMemoryDb(): void;
22
-
23
- declare const MAX_QUERY_LIMIT = 500;
24
-
25
- type WhereOp = "==" | "!=" | "<" | "<=" | ">" | ">=" | "in" | "not-in" | "array-contains" | "array-contains-any";
26
- type Doc<T> = T & {
27
- id: string;
28
- };
29
- interface Query<T extends object> {
30
- where(field: keyof T & string, op: WhereOp, value: unknown): Query<T>;
31
- orderBy(field: keyof T & string, direction?: "asc" | "desc"): Query<T>;
32
- limit(n: number): Query<T>;
33
- list(): Promise<Doc<T>[]>;
34
- }
35
- interface Collection<T extends object> extends Query<T> {
36
- get(id: string): Promise<Doc<T> | null>;
37
- add(data: T): Promise<Doc<T>>;
38
- set(id: string, data: T): Promise<void>;
39
- update(id: string, patch: Partial<T>): Promise<void>;
40
- delete(id: string): Promise<void>;
41
- }
42
- type DbMode = "firestore" | "memory";
43
- declare function dbMode(env?: Record<string, string | undefined>): DbMode;
44
- declare const db: {
45
- collection<T extends object>(name: string): Collection<T>;
46
- reset: typeof resetMemoryDb;
47
- };
48
-
49
21
  type AiModel = AiModelChoice;
50
22
  type Attachment = {
51
23
  data: Uint8Array | string;
52
24
  mediaType: AttachmentType;
53
- } | {
54
- storagePath: string;
55
- mediaType: AttachmentType;
56
25
  };
57
26
  interface AskOptions {
58
27
  system?: string;
@@ -110,30 +79,12 @@ declare const ai: {
110
79
  mediaType: "audio/wav";
111
80
  data: Buffer;
112
81
  }>;
113
- transcribe(audio: Uint8Array | {
114
- storagePath: string;
115
- }, opts: TranscribeOptions): Promise<{
82
+ transcribe(audio: Uint8Array, opts: TranscribeOptions): Promise<{
116
83
  text: string;
117
84
  seconds: number;
118
85
  }>;
119
86
  };
120
87
 
121
- declare const storage: {
122
- upload(path: string, data: string | Uint8Array, opts?: {
123
- contentType?: string;
124
- }): Promise<{
125
- path: string;
126
- }>;
127
- download(path: string): Promise<Buffer>;
128
- signedUrl(path: string, opts?: {
129
- action?: "read" | "write";
130
- expiresInMinutes?: number;
131
- contentType?: string;
132
- }): Promise<string>;
133
- list(prefix?: string): Promise<string[]>;
134
- delete(path: string): Promise<void>;
135
- };
136
-
137
88
  declare const notify: {
138
89
  email(to: string | string[], subject: string, text: string): Promise<void>;
139
90
  slack(text: string): Promise<void>;
@@ -163,5 +114,5 @@ declare class NotOnBuildersError extends BuildersError {
163
114
  constructor(what: string);
164
115
  }
165
116
 
166
- export { AddOnNotEnabledError, BuildersError, IDENTITY_HEADER, MAX_QUERY_LIMIT, NotFoundError, NotOnBuildersError, NotSignedInError, SIGN_OUT_PATH, ai, db, dbMode, notify, secrets, storage };
167
- export type { AiModel, AskOptions, Attachment, ChatResult, Collection, DbMode, Doc, GeneratedImage, ImageOptions, JsonOptions, Message, Query, SpeakOptions, TranscribeOptions, WhereOp };
117
+ export { AddOnNotEnabledError, BuildersError, IDENTITY_HEADER, NotFoundError, NotOnBuildersError, NotSignedInError, SIGN_OUT_PATH, ai, notify, secrets };
118
+ export type { AiModel, AskOptions, Attachment, ChatResult, GeneratedImage, ImageOptions, JsonOptions, Message, SpeakOptions, TranscribeOptions };
package/dist/index.js CHANGED
@@ -21,146 +21,8 @@ var CLAUDE_MODELS = {
21
21
  var AI_MODEL_CHOICES = Object.keys(CLAUDE_MODELS);
22
22
  var PLATFORM_MODEL = CLAUDE_MODELS.balanced;
23
23
 
24
- // ../core/src/firestore-indexes.ts
25
- import { z } from "zod";
26
- var INDEXES_FILE = "firestore.indexes.json";
27
- var MAX_INDEXES_FILE_BYTES = 64 * 1024;
28
- var MAX_INDEXES = 100;
29
- var FIELD_PATH = /^[A-Za-z_][A-Za-z0-9_]{0,99}(\.[A-Za-z_][A-Za-z0-9_]{0,99}){0,4}$/;
30
- var COLLECTION = /^[A-Za-z0-9_-]{1,100}$/;
31
- var IndexFieldSchema = z.union([
32
- z.object({ fieldPath: z.string().regex(FIELD_PATH), order: z.enum(["ASCENDING", "DESCENDING"]) }).strict(),
33
- z.object({ fieldPath: z.string().regex(FIELD_PATH), arrayConfig: z.literal("CONTAINS") }).strict()
34
- ]);
35
- var FirestoreIndexSchema = z.object({
36
- collectionGroup: z.string().regex(COLLECTION),
37
- // The SDK has no collection group queries.
38
- queryScope: z.literal("COLLECTION").default("COLLECTION"),
39
- fields: z.array(IndexFieldSchema).min(2).max(10)
40
- }).strict().superRefine((ix, ctx) => {
41
- const paths = ix.fields.map((f) => f.fieldPath);
42
- if (new Set(paths).size !== paths.length) ctx.addIssue({ code: "custom", message: "a field is listed twice" });
43
- if (ix.fields.filter((f) => "arrayConfig" in f).length > 1) {
44
- ctx.addIssue({ code: "custom", message: "an index can have at most one array field" });
45
- }
46
- });
47
- var IndexesFileSchema = z.object({
48
- indexes: z.array(FirestoreIndexSchema).max(MAX_INDEXES),
49
- // Written by the Firebase CLI. The platform does not apply overrides.
50
- fieldOverrides: z.array(z.unknown()).max(0, "fieldOverrides are not supported; leave the list empty").optional()
51
- }).strict();
52
- var IndexesFileError = class extends Error {
53
- constructor(message) {
54
- super(message);
55
- this.name = "IndexesFileError";
56
- }
57
- };
58
- function parseIndexesFile(text) {
59
- if (new TextEncoder().encode(text).length > MAX_INDEXES_FILE_BYTES) {
60
- throw new IndexesFileError(`${INDEXES_FILE} is larger than ${MAX_INDEXES_FILE_BYTES / 1024} KB.`);
61
- }
62
- let json;
63
- try {
64
- json = JSON.parse(text);
65
- } catch (e) {
66
- throw new IndexesFileError(`${INDEXES_FILE} is not valid JSON: ${e.message}`);
67
- }
68
- const parsed = IndexesFileSchema.safeParse(json);
69
- if (!parsed.success) {
70
- const issues = parsed.error.issues.slice(0, 5).map((i) => `${i.path.join(".") || "(file)"}: ${i.message}`);
71
- throw new IndexesFileError(`${INDEXES_FILE} is not valid: ${issues.join("; ")}`);
72
- }
73
- const seen = /* @__PURE__ */ new Set();
74
- return parsed.data.indexes.filter((ix) => {
75
- const k = indexKey(ix);
76
- if (seen.has(k)) return false;
77
- seen.add(k);
78
- return true;
79
- });
80
- }
81
- var EQUALITY = ["==", "in"];
82
- var ARRAY = ["array-contains", "array-contains-any"];
83
- var order = (d) => d === "desc" ? "DESCENDING" : "ASCENDING";
84
- function requiredIndex(collection, q) {
85
- const equality = [...new Set(q.where.filter((w) => EQUALITY.includes(w.op)).map((w) => w.field))];
86
- const arrays = [...new Set(q.where.filter((w) => ARRAY.includes(w.op)).map((w) => w.field))];
87
- const inequality = [
88
- ...new Set(q.where.filter((w) => !EQUALITY.includes(w.op) && !ARRAY.includes(w.op)).map((w) => w.field))
89
- ];
90
- const sort = [];
91
- for (const o of q.orderBy) {
92
- if (equality.includes(o.field) && !inequality.includes(o.field)) continue;
93
- if (sort.some((s) => s.fieldPath === o.field)) continue;
94
- sort.push({ fieldPath: o.field, order: order(o.direction) });
95
- }
96
- const lastOrder = sort.at(-1)?.order ?? "ASCENDING";
97
- for (const f of [...inequality].sort()) {
98
- if (!sort.some((s) => s.fieldPath === f)) sort.push({ fieldPath: f, order: lastOrder });
99
- }
100
- const array = arrays[0];
101
- const eq = equality.filter((f) => f !== array && !sort.some((s) => s.fieldPath === f));
102
- const fieldCount = eq.length + (array ? 1 : 0) + sort.length;
103
- if (fieldCount <= 1) return null;
104
- if (sort.length === 0 && !array) return null;
105
- return {
106
- collectionGroup: collection,
107
- equality: eq,
108
- ...array ? { array } : {},
109
- sort,
110
- ...inequality.length ? { inequality: true } : {}
111
- };
112
- }
113
- function plainFields(ix) {
114
- const f = ix.fields;
115
- return f.length > 0 && f.at(-1).fieldPath === "__name__" ? f.slice(0, -1) : f;
116
- }
117
- function serves(ix, need, equality) {
118
- if (ix.collectionGroup !== need.collectionGroup || ix.queryScope !== "COLLECTION") return false;
119
- const fields = plainFields(ix);
120
- const head = fields.slice(0, fields.length - need.sort.length);
121
- const tail = fields.slice(fields.length - need.sort.length);
122
- if (tail.length !== need.sort.length) return false;
123
- if (!tail.every((f, i) => "order" in f && f.fieldPath === need.sort[i].fieldPath && f.order === need.sort[i].order)) return false;
124
- const arrays = head.filter((f) => "arrayConfig" in f).map((f) => f.fieldPath);
125
- if (arrays.length !== (need.array ? 1 : 0) || need.array && arrays[0] !== need.array) return false;
126
- const eq = head.filter((f) => "order" in f).map((f) => f.fieldPath);
127
- return eq.length === equality.length && eq.every((f) => equality.includes(f));
128
- }
129
- function indexesServe(declared, need) {
130
- if (declared.some((ix) => serves(ix, need, need.equality))) return true;
131
- if (need.array || need.inequality || need.equality.length < 2) return false;
132
- const covered = /* @__PURE__ */ new Set();
133
- for (const ix of declared) {
134
- const fields = plainFields(ix);
135
- const eq = fields.slice(0, fields.length - need.sort.length).map((f) => f.fieldPath);
136
- if (eq.length > 0 && eq.every((f) => need.equality.includes(f)) && serves(ix, need, eq)) {
137
- for (const f of eq) covered.add(f);
138
- }
139
- }
140
- return need.equality.every((f) => covered.has(f));
141
- }
142
- function indexFor(need) {
143
- return {
144
- collectionGroup: need.collectionGroup,
145
- queryScope: "COLLECTION",
146
- fields: [
147
- ...need.equality.map((fieldPath) => ({ fieldPath, order: "ASCENDING" })),
148
- ...need.array ? [{ fieldPath: need.array, arrayConfig: "CONTAINS" }] : [],
149
- ...need.sort
150
- ]
151
- };
152
- }
153
- function missingIndexMessage(need) {
154
- 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:
155
- ` + JSON.stringify(indexFor(need), null, 2);
156
- }
157
- function indexKey(ix) {
158
- const fields = plainFields(ix).map((f) => "order" in f ? `${f.fieldPath}:${f.order}` : `${f.fieldPath}:CONTAINS`);
159
- return `${ix.collectionGroup}|${ix.queryScope}|${fields.join(",")}`;
160
- }
161
-
162
24
  // ../core/src/app-ai.ts
163
- import { z as z2 } from "zod";
25
+ import { z } from "zod";
164
26
  var APP_HEADER = "x-builders-app";
165
27
  var APP_ENV = {
166
28
  tenant: "BUILDERS_TENANT",
@@ -192,36 +54,36 @@ var APP_AI_LIMITS = {
192
54
  maxEmailChars: 2e4
193
55
  };
194
56
  var ATTACHMENT_TYPES = ["image/png", "image/jpeg", "image/gif", "image/webp", "application/pdf"];
195
- var Base64 = z2.string().regex(/^[A-Za-z0-9+/]*={0,2}$/, "Not base64.");
196
- var ContentPartSchema = z2.discriminatedUnion("type", [
197
- z2.object({ type: z2.literal("text"), text: z2.string().min(1) }),
198
- z2.object({ type: z2.literal("file"), mediaType: z2.enum(ATTACHMENT_TYPES), data: Base64.min(1) })
57
+ var Base64 = z.string().regex(/^[A-Za-z0-9+/]*={0,2}$/, "Not base64.");
58
+ var ContentPartSchema = z.discriminatedUnion("type", [
59
+ z.object({ type: z.literal("text"), text: z.string().min(1) }),
60
+ z.object({ type: z.literal("file"), mediaType: z.enum(ATTACHMENT_TYPES), data: Base64.min(1) })
199
61
  ]);
200
- var ChatMessageSchema = z2.object({
201
- role: z2.enum(["user", "assistant"]),
202
- content: z2.union([z2.string().min(1), z2.array(ContentPartSchema).min(1).max(APP_AI_LIMITS.maxAttachments + 10)])
62
+ var ChatMessageSchema = z.object({
63
+ role: z.enum(["user", "assistant"]),
64
+ content: z.union([z.string().min(1), z.array(ContentPartSchema).min(1).max(APP_AI_LIMITS.maxAttachments + 10)])
203
65
  });
204
- var ModelChoice = z2.enum(AI_MODEL_CHOICES);
205
- var MessagesRequestSchema = z2.object({
66
+ var ModelChoice = z.enum(AI_MODEL_CHOICES);
67
+ var MessagesRequestSchema = z.object({
206
68
  model: ModelChoice.default("balanced"),
207
- system: z2.string().max(APP_AI_LIMITS.maxTextChars).optional(),
208
- messages: z2.array(ChatMessageSchema).min(1).max(APP_AI_LIMITS.maxMessages),
209
- maxTokens: z2.number().int().min(1).max(APP_AI_LIMITS.maxOutputTokens).default(1024),
210
- temperature: z2.number().min(0).max(1).optional(),
69
+ system: z.string().max(APP_AI_LIMITS.maxTextChars).optional(),
70
+ messages: z.array(ChatMessageSchema).min(1).max(APP_AI_LIMITS.maxMessages),
71
+ maxTokens: z.number().int().min(1).max(APP_AI_LIMITS.maxOutputTokens).default(1024),
72
+ temperature: z.number().min(0).max(1).optional(),
211
73
  // Structured output: Claude must answer with JSON for this JSON Schema
212
74
  // (an object schema). The SDK checks the answer with the app's zod schema.
213
- json: z2.object({ schema: z2.record(z2.string(), z2.unknown()), description: z2.string().max(1e3).optional() }).optional(),
75
+ json: z.object({ schema: z.record(z.string(), z.unknown()), description: z.string().max(1e3).optional() }).optional(),
214
76
  // Server-sent events: "text" deltas, then "done" (or "error").
215
- stream: z2.boolean().default(false)
77
+ stream: z.boolean().default(false)
216
78
  }).strict().refine((r) => r.messages[0].role === "user", "The first message must be from the user.").refine((r) => !(r.json && r.stream), "A JSON answer cannot stream.");
217
79
  var IMAGE_ASPECT_RATIOS = ["1:1", "3:2", "2:3", "3:4", "4:3", "4:5", "5:4", "9:16", "16:9", "21:9"];
218
80
  var IMAGE_SIZES = ["512", "1K", "2K"];
219
- var ImageRequestSchema = z2.object({
220
- prompt: z2.string().min(1).max(2e4),
221
- aspectRatio: z2.enum(IMAGE_ASPECT_RATIOS).default("1:1"),
222
- size: z2.enum(IMAGE_SIZES).default("1K"),
81
+ var ImageRequestSchema = z.object({
82
+ prompt: z.string().min(1).max(2e4),
83
+ aspectRatio: z.enum(IMAGE_ASPECT_RATIOS).default("1:1"),
84
+ size: z.enum(IMAGE_SIZES).default("1K"),
223
85
  // Images to edit or to use as a reference.
224
- images: z2.array(z2.object({ mediaType: z2.enum(["image/png", "image/jpeg", "image/webp"]), data: Base64.min(1) })).max(APP_AI_LIMITS.maxImageInputs).default([])
86
+ images: z.array(z.object({ mediaType: z.enum(["image/png", "image/jpeg", "image/webp"]), data: Base64.min(1) })).max(APP_AI_LIMITS.maxImageInputs).default([])
225
87
  }).strict();
226
88
  var SPEECH_VOICES = [
227
89
  "Kore",
@@ -233,24 +95,24 @@ var SPEECH_VOICES = [
233
95
  "Orus",
234
96
  "Zephyr"
235
97
  ];
236
- var SpeechRequestSchema = z2.object({
237
- text: z2.string().min(1).max(APP_AI_LIMITS.maxSpeechChars),
238
- voice: z2.enum(SPEECH_VOICES).default("Kore"),
98
+ var SpeechRequestSchema = z.object({
99
+ text: z.string().min(1).max(APP_AI_LIMITS.maxSpeechChars),
100
+ voice: z.enum(SPEECH_VOICES).default("Kore"),
239
101
  // How to speak, for example "Say cheerfully" (Gemini TTS follows it).
240
- style: z2.string().max(500).optional()
102
+ style: z.string().max(500).optional()
241
103
  }).strict();
242
104
  var AUDIO_TYPES = ["audio/wav", "audio/x-wav", "audio/mpeg", "audio/mp3", "audio/flac", "audio/ogg", "audio/webm", "audio/mp4", "audio/m4a"];
243
- var TranscribeRequestSchema = z2.object({
244
- mediaType: z2.enum(AUDIO_TYPES),
105
+ var TranscribeRequestSchema = z.object({
106
+ mediaType: z.enum(AUDIO_TYPES),
245
107
  data: Base64.min(1),
246
108
  // BCP-47 codes, for example ["de-CH", "en-US"]. Default: detect.
247
- languages: z2.array(z2.string().regex(/^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$/)).min(1).max(3).optional()
109
+ languages: z.array(z.string().regex(/^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$/)).min(1).max(3).optional()
248
110
  }).strict();
249
- var SlackRequestSchema = z2.object({ text: z2.string().min(1).max(APP_AI_LIMITS.maxSlackChars) }).strict();
250
- var EmailRequestSchema = z2.object({
251
- to: z2.array(z2.string().email().max(254)).min(1).max(APP_AI_LIMITS.maxEmailRecipients),
252
- subject: z2.string().min(1).max(200).refine((s) => !/[\r\n]/.test(s), "One line."),
253
- text: z2.string().min(1).max(APP_AI_LIMITS.maxEmailChars)
111
+ var SlackRequestSchema = z.object({ text: z.string().min(1).max(APP_AI_LIMITS.maxSlackChars) }).strict();
112
+ var EmailRequestSchema = z.object({
113
+ to: z.array(z.string().email().max(254)).min(1).max(APP_AI_LIMITS.maxEmailRecipients),
114
+ subject: z.string().min(1).max(200).refine((s) => !/[\r\n]/.test(s), "One line."),
115
+ text: z.string().min(1).max(APP_AI_LIMITS.maxEmailChars)
254
116
  }).strict();
255
117
  var SECRET_NAME = /^[A-Z][A-Z0-9_]{0,63}$/;
256
118
  var PLATFORM_SECRET_PREFIX = "BUILDERS_";
@@ -267,329 +129,11 @@ var DEV_ENV = {
267
129
  tokenFile: "BUILDERS_TUNNEL_TOKEN_FILE"
268
130
  };
269
131
 
270
- // ../core/src/dev-files.ts
271
- var DEV_FILES_PATH = "/_builders/dev-files/";
272
- var DEV_DATA_DIR_ENV = "BUILDERS_DEV_DATA_DIR";
273
- var DEV_FILES_SECRET_ENV = "BUILDERS_DEV_FILES_SECRET";
274
- var DEV_PREVIEW_URL_ENV = "BUILDERS_DEV_PREVIEW_URL";
275
- var enc = new TextEncoder();
276
- async function sign(secret, g2) {
277
- const key2 = await crypto.subtle.importKey("raw", enc.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
278
- const mac = await crypto.subtle.sign("HMAC", key2, enc.encode(`${g2.action}
279
- ${g2.path}
280
- ${g2.expires}
281
- ${g2.contentType}`));
282
- return [...new Uint8Array(mac)].map((b) => b.toString(16).padStart(2, "0")).join("");
283
- }
284
- async function devFileLink(secret, g2) {
285
- const q = new URLSearchParams({ a: g2.action, e: String(g2.expires), ...g2.contentType ? { ct: g2.contentType } : {} });
286
- q.set("s", await sign(secret, g2));
287
- return `${DEV_FILES_PATH}${g2.path.split("/").map(encodeURIComponent).join("/")}?${q}`;
288
- }
289
-
290
- // src/db-limit.ts
291
- var MAX_QUERY_LIMIT = 500;
292
- function checkLimit(n) {
293
- if (!Number.isInteger(n) || n < 1 || n > MAX_QUERY_LIMIT) {
294
- throw new BuildersError(`limit() must be a whole number from 1 to ${MAX_QUERY_LIMIT}, not ${n}.`);
295
- }
296
- return n;
297
- }
298
- var queryLimit = (spec) => spec.limit ?? MAX_QUERY_LIMIT;
299
-
300
- // src/db-indexes.ts
301
- import { readFileSync, statSync } from "node:fs";
302
- import { join } from "node:path";
303
- var cache = null;
304
- function indexesFilePath(env = process.env) {
305
- return env.BUILDERS_INDEXES_FILE || join(process.cwd(), INDEXES_FILE);
306
- }
307
- function declaredIndexes(path = indexesFilePath()) {
308
- let st;
309
- try {
310
- st = statSync(path);
311
- } catch {
312
- return [];
313
- }
314
- if (cache && cache.path === path && cache.mtimeMs === st.mtimeMs && cache.size === st.size) return cache.indexes;
315
- try {
316
- const indexes = parseIndexesFile(readFileSync(path, "utf8"));
317
- cache = { path, mtimeMs: st.mtimeMs, size: st.size, indexes };
318
- return indexes;
319
- } catch (e) {
320
- if (e instanceof IndexesFileError) throw new BuildersError(e.message);
321
- throw e;
322
- }
323
- }
324
- function checkIndex(collection, spec) {
325
- const declared = declaredIndexes();
326
- const need = requiredIndex(collection, spec);
327
- if (need && !indexesServe(declared, need)) throw new BuildersError(missingIndexMessage(need));
328
- }
329
- function missingIndexError(collection, spec, e) {
330
- const err = e;
331
- if (err?.code !== 9 || !/index/i.test(err.message ?? "")) return null;
332
- const need = requiredIndex(collection, spec);
333
- return need ? new BuildersError(`${missingIndexMessage(need)}
334
- Then push a new version: the platform creates the index before the preview.`) : null;
335
- }
336
-
337
- // src/db-firestore.ts
338
- var client;
339
- function firestore() {
340
- return client ??= import("@google-cloud/firestore").then((m) => {
341
- const env = process.env;
342
- const fs = new m.Firestore({
343
- ignoreUndefinedProperties: true,
344
- projectId: env.GOOGLE_CLOUD_PROJECT ?? (env.FIRESTORE_EMULATOR_HOST ? "demo-builders" : void 0),
345
- databaseId: env.FIRESTORE_DATABASE || void 0
346
- });
347
- return { fs, Timestamp: m.Timestamp };
348
- });
349
- }
350
- function firestoreCollection(name) {
351
- const ref = async () => (await firestore()).fs.collection(name);
352
- const query = (spec) => ({
353
- where: (field, op, value) => query({ ...spec, where: [...spec.where, { field, op, value }] }),
354
- orderBy: (field, direction = "asc") => query({ ...spec, orderBy: [...spec.orderBy, { field, direction }] }),
355
- limit: (n) => query({ ...spec, limit: checkLimit(n) }),
356
- async list() {
357
- const { Timestamp } = await firestore();
358
- let q = await ref();
359
- for (const w of spec.where) q = q.where(w.field, w.op, w.value);
360
- for (const o of spec.orderBy) q = q.orderBy(o.field, o.direction);
361
- q = q.limit(queryLimit(spec));
362
- let snap;
363
- try {
364
- snap = await q.get();
365
- } catch (e) {
366
- throw missingIndexError(name, spec, e) ?? e;
367
- }
368
- return snap.docs.map((d) => ({ ...toPlain(d.data(), Timestamp), id: d.id }));
369
- },
370
- async get(id) {
371
- const { Timestamp } = await firestore();
372
- const d = await (await ref()).doc(id).get();
373
- return d.exists ? { ...toPlain(d.data(), Timestamp), id: d.id } : null;
374
- },
375
- async add(data) {
376
- const body = withoutId(data);
377
- const r = await (await ref()).add(body);
378
- return { ...body, id: r.id };
379
- },
380
- async set(id, data) {
381
- await (await ref()).doc(id).set(withoutId(data));
382
- },
383
- async update(id, patch) {
384
- try {
385
- await (await ref()).doc(id).update(withoutId(patch));
386
- } catch (e) {
387
- if (e.code === 5) throw new NotFoundError(`No document "${id}" in "${name}".`);
388
- throw e;
389
- }
390
- },
391
- async delete(id) {
392
- await (await ref()).doc(id).delete();
393
- }
394
- });
395
- return query({ where: [], orderBy: [] });
396
- }
397
- function withoutId(data) {
398
- const { id: _id, ...rest } = data;
399
- return rest;
400
- }
401
- function toPlain(v, Timestamp) {
402
- if (v instanceof Timestamp) return v.toDate();
403
- if (Array.isArray(v)) return v.map((x) => toPlain(x, Timestamp));
404
- if (v && typeof v === "object" && Object.getPrototypeOf(v) === Object.prototype) {
405
- return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, toPlain(x, Timestamp)]));
406
- }
407
- return v;
408
- }
409
-
410
- // src/db-memory.ts
411
- import { randomBytes } from "node:crypto";
412
- import { mkdirSync, readFileSync as readFileSync2, renameSync, writeFileSync } from "node:fs";
413
- import { join as join2 } from "node:path";
414
- var warnedCap = /* @__PURE__ */ new Set();
415
- var g = globalThis;
416
- var store = () => g.__buildersMemoryDb ??= load();
417
- var SAVE_DELAY_MS = 100;
418
- var dbFile = () => {
419
- const dir = process.env[DEV_DATA_DIR_ENV];
420
- return dir ? join2(dir, "db.json") : null;
421
- };
422
- function load() {
423
- const file = dbFile();
424
- const s = /* @__PURE__ */ new Map();
425
- if (!file) return s;
426
- let raw;
427
- try {
428
- raw = JSON.parse(
429
- readFileSync2(file, "utf8"),
430
- (_k, v) => v && typeof v === "object" && typeof v.$date === "string" && Object.keys(v).length === 1 ? new Date(v.$date) : v
431
- );
432
- } catch {
433
- return s;
434
- }
435
- for (const [name, docs] of Object.entries(raw)) s.set(name, new Map(Object.entries(docs)));
436
- return s;
437
- }
438
- function saveSoon() {
439
- const file = dbFile();
440
- if (!file || g.__buildersMemoryDbSave) return;
441
- g.__buildersMemoryDbSave = setTimeout(() => {
442
- g.__buildersMemoryDbSave = void 0;
443
- const out = {};
444
- for (const [name, docs] of store()) out[name] = Object.fromEntries(docs);
445
- const text = JSON.stringify(out, function(k, v) {
446
- const raw = this[k];
447
- return raw instanceof Date ? { $date: raw.toISOString() } : v;
448
- });
449
- mkdirSync(join2(file, ".."), { recursive: true });
450
- writeFileSync(`${file}.tmp`, text);
451
- renameSync(`${file}.tmp`, file);
452
- }, SAVE_DELAY_MS);
453
- }
454
- function resetMemoryDb() {
455
- store().clear();
456
- saveSoon();
457
- }
458
- function memoryCollection(name) {
459
- const docs = () => {
460
- let m = store().get(name);
461
- if (!m) store().set(name, m = /* @__PURE__ */ new Map());
462
- return m;
463
- };
464
- const out = (id, data) => ({ ...structuredClone(data), id });
465
- const clean = (data) => {
466
- const copy = structuredClone(data);
467
- delete copy.id;
468
- for (const k of Object.keys(copy)) if (copy[k] === void 0) delete copy[k];
469
- return copy;
470
- };
471
- const query = (spec) => ({
472
- where: (field, op, value) => query({ ...spec, where: [...spec.where, { field, op, value }] }),
473
- orderBy: (field, direction = "asc") => query({ ...spec, orderBy: [...spec.orderBy, { field, direction }] }),
474
- limit: (n) => query({ ...spec, limit: checkLimit(n) }),
475
- async list() {
476
- checkIndex(name, spec);
477
- let rows = [...docs()].filter(([, d]) => spec.where.every((w) => matches(d[w.field], w.op, w.value)));
478
- rows = rows.filter(([, d]) => spec.orderBy.every((o) => d[o.field] !== void 0));
479
- rows.sort(([, a], [, b]) => {
480
- for (const o of spec.orderBy) {
481
- const c = compare(a[o.field], b[o.field]);
482
- if (c !== 0) return o.direction === "desc" ? -c : c;
483
- }
484
- return 0;
485
- });
486
- if (spec.limit === void 0 && rows.length > MAX_QUERY_LIMIT && !warnedCap.has(name)) {
487
- warnedCap.add(name);
488
- console.warn(`[builders] A query on "${name}" matched more than ${MAX_QUERY_LIMIT} documents; list() returns only the first ${MAX_QUERY_LIMIT}.`);
489
- }
490
- rows = rows.slice(0, queryLimit(spec));
491
- return rows.map(([id, d]) => out(id, d));
492
- },
493
- async get(id) {
494
- const d = docs().get(id);
495
- return d ? out(id, d) : null;
496
- },
497
- async add(data) {
498
- const id = autoId();
499
- docs().set(id, clean(data));
500
- saveSoon();
501
- return out(id, docs().get(id));
502
- },
503
- async set(id, data) {
504
- docs().set(id, clean(data));
505
- saveSoon();
506
- },
507
- async update(id, patch) {
508
- const d = docs().get(id);
509
- if (!d) throw new NotFoundError(`No document "${id}" in "${name}".`);
510
- docs().set(id, { ...d, ...clean(patch) });
511
- saveSoon();
512
- },
513
- async delete(id) {
514
- docs().delete(id);
515
- saveSoon();
516
- }
517
- });
518
- return query({ where: [], orderBy: [] });
519
- }
520
- function autoId() {
521
- const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
522
- return [...randomBytes(20)].map((b) => chars[b % chars.length]).join("");
523
- }
524
- function key(v) {
525
- return v instanceof Date ? v.getTime() : v;
526
- }
527
- function compare(a, b) {
528
- const x = key(a);
529
- const y = key(b);
530
- return x < y ? -1 : x > y ? 1 : 0;
531
- }
532
- function equal(a, b) {
533
- return key(a) === key(b);
534
- }
535
- function matches(v, op, target) {
536
- if (v === void 0) return false;
537
- const list = Array.isArray(target) ? target : [];
538
- switch (op) {
539
- case "==":
540
- return equal(v, target);
541
- case "!=":
542
- return !equal(v, target);
543
- case "<":
544
- return compare(v, target) < 0;
545
- case "<=":
546
- return compare(v, target) <= 0;
547
- case ">":
548
- return compare(v, target) > 0;
549
- case ">=":
550
- return compare(v, target) >= 0;
551
- case "in":
552
- return list.some((t) => equal(v, t));
553
- case "not-in":
554
- return !list.some((t) => equal(v, t));
555
- case "array-contains":
556
- return Array.isArray(v) && v.some((x) => equal(x, target));
557
- case "array-contains-any":
558
- return Array.isArray(v) && v.some((x) => list.some((t) => equal(x, t)));
559
- }
560
- }
561
-
562
- // src/db.ts
563
- function dbMode(env = process.env) {
564
- if (env.BUILDERS_DB === "memory" || env.BUILDERS_DB === "firestore") return env.BUILDERS_DB;
565
- if (env.FIRESTORE_EMULATOR_HOST || env.GOOGLE_APPLICATION_CREDENTIALS) return "firestore";
566
- if (env.NODE_ENV === "production" || env.K_SERVICE) return "firestore";
567
- return "memory";
568
- }
569
- var warned = false;
570
- var db = {
571
- collection(name) {
572
- if (!/^[A-Za-z0-9_-]{1,100}$/.test(name)) {
573
- throw new BuildersError(`"${name}" is not a valid collection name. Use letters, digits, "-" or "_".`);
574
- }
575
- if (dbMode() === "firestore") return firestoreCollection(name);
576
- if (!warned && process.env.NODE_ENV !== "test") {
577
- warned = true;
578
- console.info(
579
- process.env[DEV_DATA_DIR_ENV] ? `[builders] Using the local test database in ${process.env[DEV_DATA_DIR_ENV]}.` : "[builders] Using a temporary in-memory database. Data is lost when the dev server stops."
580
- );
581
- }
582
- return memoryCollection(name);
583
- },
584
- // Empties the in-memory database. For tests.
585
- reset: resetMemoryDb
586
- };
587
-
588
132
  // src/ai.ts
589
- import { z as z3 } from "zod";
133
+ import { z as z2 } from "zod";
590
134
 
591
135
  // src/platform.ts
592
- import { readFileSync as readFileSync3, statSync as statSync2 } from "node:fs";
136
+ import { readFileSync, statSync } from "node:fs";
593
137
  var METADATA = "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default";
594
138
  var idTokens = /* @__PURE__ */ new Map();
595
139
  var accessToken;
@@ -639,7 +183,7 @@ function devToken(env = process.env) {
639
183
  if (!path) throw new BuildersError(`The dev preview has no Builders token (${DEV_ENV.tokenFile} is not set). ${NO_DEV_TOKEN}`, 401);
640
184
  let st;
641
185
  try {
642
- st = statSync2(path);
186
+ st = statSync(path);
643
187
  } catch {
644
188
  throw new BuildersError(`The dev preview's Builders token file is missing. ${NO_DEV_TOKEN}`, 401);
645
189
  }
@@ -647,7 +191,7 @@ function devToken(env = process.env) {
647
191
  if (c && c.path === path && c.mtimeMs === st.mtimeMs && c.size === st.size) return c.token;
648
192
  let token;
649
193
  try {
650
- token = (readFileSync3(path, "utf8").split("\n")[0] ?? "").trim();
194
+ token = (readFileSync(path, "utf8").split("\n")[0] ?? "").trim();
651
195
  } catch {
652
196
  throw new BuildersError(`The dev preview's Builders token file cannot be read. ${NO_DEV_TOKEN}`, 401);
653
197
  }
@@ -709,123 +253,6 @@ async function gatewayJson(addOn, path, body, o = {}) {
709
253
  return await res.json();
710
254
  }
711
255
 
712
- // src/storage-local.ts
713
- import { mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
714
- import { dirname, join as join3, relative, sep } from "node:path";
715
- function localStorage(dir) {
716
- const file = (path) => join3(dir, "files", path);
717
- const meta = (path) => join3(dir, "files-meta", `${path}.json`);
718
- return {
719
- async upload(path, data, opts) {
720
- await mkdir(dirname(file(path)), { recursive: true });
721
- await mkdir(dirname(meta(path)), { recursive: true });
722
- await writeFile(file(path), typeof data === "string" ? data : Buffer.from(data));
723
- await writeFile(meta(path), JSON.stringify({ contentType: opts.contentType ?? "" }));
724
- },
725
- async download(path) {
726
- try {
727
- return await readFile(file(path));
728
- } catch {
729
- throw new NotFoundError(`No file "${path}".`);
730
- }
731
- },
732
- async signedUrl(path, action, expires, contentType) {
733
- const secret = process.env[DEV_FILES_SECRET_ENV];
734
- if (!secret) throw new BuildersError("File links work in the dev preview. Start it with the preview command from open_app.");
735
- const link = await devFileLink(secret, { path, action, expires, contentType: contentType ?? "" });
736
- const origin = process.env[DEV_PREVIEW_URL_ENV];
737
- return origin ? new URL(link, origin).toString() : link;
738
- },
739
- async list(prefix) {
740
- const root = join3(dir, "files");
741
- const out = [];
742
- const walk = async (d) => {
743
- let entries;
744
- try {
745
- entries = await readdir(d, { withFileTypes: true });
746
- } catch {
747
- return;
748
- }
749
- for (const e of entries) {
750
- const p = join3(d, e.name);
751
- if (e.isDirectory()) await walk(p);
752
- else out.push(relative(root, p).split(sep).join("/"));
753
- }
754
- };
755
- await walk(root);
756
- return out.filter((p) => p.startsWith(prefix)).sort();
757
- },
758
- async delete(path) {
759
- await rm(file(path), { force: true });
760
- await rm(meta(path), { force: true });
761
- }
762
- };
763
- }
764
-
765
- // src/storage.ts
766
- var cached;
767
- async function bucket() {
768
- const name = process.env.STORAGE_BUCKET;
769
- if (!name) throw new AddOnNotEnabledError("storage");
770
- if (cached?.name !== name) {
771
- cached = { name, bucket: import("@google-cloud/storage").then((m) => new m.Storage().bucket(name)) };
772
- }
773
- return cached.bucket;
774
- }
775
- function local() {
776
- const dir = process.env.STORAGE_BUCKET ? void 0 : process.env[DEV_DATA_DIR_ENV];
777
- return dir ? localStorage(dir) : null;
778
- }
779
- function checkPath(path) {
780
- if (!path || path.startsWith("/") || path.split("/").some((p) => p === ".." || p === "")) {
781
- throw new BuildersError(`"${path}" is not a valid file path. Use something like "photos/cat.jpg".`, 400);
782
- }
783
- return path;
784
- }
785
- var storage = {
786
- async upload(path, data, opts = {}) {
787
- const l = local();
788
- if (l) {
789
- await l.upload(checkPath(path), data, opts);
790
- return { path };
791
- }
792
- await (await bucket()).file(checkPath(path)).save(typeof data === "string" ? data : Buffer.from(data), {
793
- contentType: opts.contentType,
794
- resumable: false
795
- });
796
- return { path };
797
- },
798
- async download(path) {
799
- const l = local();
800
- if (l) return l.download(checkPath(path));
801
- const [buf] = await (await bucket()).file(checkPath(path)).download();
802
- return buf;
803
- },
804
- async signedUrl(path, opts = {}) {
805
- const minutes = Math.min(opts.expiresInMinutes ?? 15, 7 * 24 * 60);
806
- const l = local();
807
- if (l) return l.signedUrl(checkPath(path), opts.action ?? "read", Date.now() + minutes * 6e4, opts.contentType);
808
- const [url] = await (await bucket()).file(checkPath(path)).getSignedUrl({
809
- version: "v4",
810
- action: opts.action ?? "read",
811
- expires: Date.now() + minutes * 6e4,
812
- contentType: opts.contentType
813
- });
814
- return url;
815
- },
816
- async list(prefix = "") {
817
- const l = local();
818
- if (l) return l.list(prefix);
819
- const [files] = await (await bucket()).getFiles({ prefix });
820
- return files.map((f) => f.name);
821
- },
822
- async delete(path) {
823
- const l = local();
824
- if (l) return l.delete(checkPath(path));
825
- await (await bucket()).file(checkPath(path)).delete({ ignoreNotFound: true });
826
- }
827
- };
828
-
829
256
  // src/ai.ts
830
257
  var MODELS = new Set(AI_MODEL_CHOICES);
831
258
  function model(m) {
@@ -834,7 +261,6 @@ function model(m) {
834
261
  return v;
835
262
  }
836
263
  async function base64(a) {
837
- if ("storagePath" in a) return (await storage.download(a.storagePath)).toString("base64");
838
264
  return typeof a.data === "string" ? a.data : Buffer.from(a.data).toString("base64");
839
265
  }
840
266
  async function content(text, attachments = []) {
@@ -858,7 +284,7 @@ function toJsonSchema(schema) {
858
284
  }
859
285
  let js;
860
286
  try {
861
- js = z3.toJSONSchema(schema, { io: "input", unrepresentable: "throw" });
287
+ js = z2.toJSONSchema(schema, { io: "input", unrepresentable: "throw" });
862
288
  } catch (e) {
863
289
  throw new BuildersError(
864
290
  `ai.json cannot use this schema: ${e.message}. Use types that JSON can hold, for example z.iso.datetime() or z.coerce.date() instead of z.date().`,
@@ -954,7 +380,7 @@ var ai = {
954
380
  },
955
381
  // Speech to text, for audio up to one minute.
956
382
  async transcribe(audio, opts) {
957
- const data = "storagePath" in audio && !(audio instanceof Uint8Array) ? (await storage.download(audio.storagePath)).toString("base64") : Buffer.from(audio).toString("base64");
383
+ const data = Buffer.from(audio).toString("base64");
958
384
  const r = await gatewayJson("ai", "/v1/transcribe", { mediaType: opts.mediaType, data, ...opts.languages ? { languages: opts.languages } : {} }, { signal: opts.signal, timeoutMs: 12e4 });
959
385
  return { text: r.text, seconds: r.seconds };
960
386
  }
@@ -971,7 +397,7 @@ var notify = {
971
397
  };
972
398
 
973
399
  // src/secrets.ts
974
- var cache2 = /* @__PURE__ */ new Map();
400
+ var cache = /* @__PURE__ */ new Map();
975
401
  var TTL_MS = 5 * 6e4;
976
402
  var secrets = {
977
403
  async get(name) {
@@ -986,7 +412,7 @@ var secrets = {
986
412
  if (v) return v;
987
413
  throw new NotFoundError(`The secret ${name} is not available here. Secrets work in versions and the live app; for pnpm dev put ${name}=... in .env.local.`);
988
414
  }
989
- const hit = cache2.get(name);
415
+ const hit = cache.get(name);
990
416
  if (hit && Date.now() - hit.at < TTL_MS) return hit.value;
991
417
  const url = `https://secretmanager.googleapis.com/v1/projects/${encodeURIComponent(project)}/secrets/${name}/versions/latest:access`;
992
418
  let res;
@@ -999,29 +425,25 @@ var secrets = {
999
425
  if (!res.ok) throw new BuildersError(`Could not read the secret ${name} (${res.status}).`, 502);
1000
426
  const j = await res.json();
1001
427
  const value = Buffer.from(j.payload?.data ?? "", "base64").toString("utf8");
1002
- cache2.set(name, { value, at: Date.now() });
428
+ cache.set(name, { value, at: Date.now() });
1003
429
  return value;
1004
430
  },
1005
431
  // For tests.
1006
432
  clearCache() {
1007
- cache2.clear();
433
+ cache.clear();
1008
434
  }
1009
435
  };
1010
436
  export {
1011
437
  AddOnNotEnabledError,
1012
438
  BuildersError,
1013
439
  IDENTITY_HEADER,
1014
- MAX_QUERY_LIMIT,
1015
440
  NotFoundError,
1016
441
  NotOnBuildersError,
1017
442
  NotSignedInError,
1018
443
  SIGN_OUT_PATH,
1019
444
  ai,
1020
- db,
1021
- dbMode,
1022
445
  getUser,
1023
446
  nameFromEmail,
1024
447
  notify,
1025
- secrets,
1026
- storage
448
+ secrets
1027
449
  };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@n-dream/builders-sdk",
3
- "version": "0.3.0",
4
- "description": "Builders platform helpers for app code: signed-in user, database, AI, file storage, notifications.",
3
+ "version": "0.4.0",
4
+ "description": "Builders platform helpers for app code: signed-in user, AI, notifications, secrets.",
5
5
  "license": "UNLICENSED",
6
6
  "homepage": "https://builders.n-dream.com",
7
7
  "keywords": [
@@ -30,8 +30,6 @@
30
30
  "node": ">=22"
31
31
  },
32
32
  "dependencies": {
33
- "@google-cloud/firestore": "^9.4.0",
34
- "@google-cloud/storage": "^8.4.0",
35
33
  "jose": "^6.0.0",
36
34
  "zod": "^4.6.7"
37
35
  },