@n-dream/builders-sdk 0.3.1 → 1.0.0-next.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/dist/index.js CHANGED
@@ -1,1047 +1,4 @@
1
- import {
2
- AddOnNotEnabledError,
3
- BuildersError,
4
- IDENTITY_HEADER,
5
- NotFoundError,
6
- NotSignedInError,
7
- SIGN_OUT_PATH,
8
- getUser,
9
- nameFromEmail
10
- } from "./chunks/chunk-RUOQMEEZ.js";
11
-
12
- // ../core/src/ai.ts
13
- var CLAUDE_MODELS = {
14
- fast: "claude-haiku-5-5",
15
- // simple, fast and cheap
16
- balanced: "claude-sonnet-5-5",
17
- // the default
18
- best: "claude-opus-5-5"
19
- // hard tasks only; it costs the most
20
- };
21
- var AI_MODEL_CHOICES = Object.keys(CLAUDE_MODELS);
22
- var PLATFORM_MODEL = CLAUDE_MODELS.balanced;
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
- // ../core/src/app-ai.ts
163
- import { z as z2 } from "zod";
164
- var APP_HEADER = "x-builders-app";
165
- var APP_ENV = {
166
- tenant: "BUILDERS_TENANT",
167
- app: "BUILDERS_APP",
168
- // The app's own GCP project (Secret Manager of `secrets`).
169
- project: "BUILDERS_GCP_PROJECT",
170
- aiGateway: "AI_GATEWAY_URL",
171
- // ai add-on and notify add-on
172
- bucket: "STORAGE_BUCKET",
173
- // storage add-on
174
- // "preview" (a v-<n> revision, no secrets) or "live" (core RevisionKind).
175
- revision: "BUILDERS_REVISION"
176
- };
177
- var APP_AI_LIMITS = {
178
- // The request body (attachments are base64 in it).
179
- maxBodyBytes: 20 * 1024 * 1024,
180
- maxMessages: 200,
181
- maxTextChars: 4e5,
182
- maxAttachments: 20,
183
- maxOutputTokens: 16e3,
184
- // JSON Schema of ai.json, as JSON text.
185
- maxSchemaChars: 64e3,
186
- maxImageInputs: 6,
187
- maxSpeechChars: 5e3,
188
- // Speech-to-Text "recognize" takes audio up to one minute.
189
- maxAudioBytes: 10 * 1024 * 1024,
190
- maxSlackChars: 3e3,
191
- maxEmailRecipients: 20,
192
- maxEmailChars: 2e4
193
- };
194
- 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) })
199
- ]);
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)])
203
- });
204
- var ModelChoice = z2.enum(AI_MODEL_CHOICES);
205
- var MessagesRequestSchema = z2.object({
206
- 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(),
211
- // Structured output: Claude must answer with JSON for this JSON Schema
212
- // (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(),
214
- // Server-sent events: "text" deltas, then "done" (or "error").
215
- stream: z2.boolean().default(false)
216
- }).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
- 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
- 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"),
223
- // 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([])
225
- }).strict();
226
- var SPEECH_VOICES = [
227
- "Kore",
228
- "Puck",
229
- "Charon",
230
- "Fenrir",
231
- "Aoede",
232
- "Leda",
233
- "Orus",
234
- "Zephyr"
235
- ];
236
- var SpeechRequestSchema = z2.object({
237
- text: z2.string().min(1).max(APP_AI_LIMITS.maxSpeechChars),
238
- voice: z2.enum(SPEECH_VOICES).default("Kore"),
239
- // How to speak, for example "Say cheerfully" (Gemini TTS follows it).
240
- style: z2.string().max(500).optional()
241
- }).strict();
242
- 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),
245
- data: Base64.min(1),
246
- // 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()
248
- }).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)
254
- }).strict();
255
- var SECRET_NAME = /^[A-Z][A-Z0-9_]{0,63}$/;
256
- var PLATFORM_SECRET_PREFIX = "BUILDERS_";
257
- var MAX_SECRET_BYTES = 16 * 1024;
258
- function secretNameError(name) {
259
- if (!SECRET_NAME.test(name)) return "Use capital letters, digits and _, starting with a letter (for example HUBSPOT_API_KEY).";
260
- if (name.startsWith(PLATFORM_SECRET_PREFIX)) return `Names that start with ${PLATFORM_SECRET_PREFIX} are for the platform.`;
261
- return null;
262
- }
263
-
264
- // ../core/src/dev-data.ts
265
- var DEV_ENV = {
266
- url: "BUILDERS_DEV_URL",
267
- tokenFile: "BUILDERS_TUNNEL_TOKEN_FILE"
268
- };
269
-
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
- function validDevFilePath(path) {
290
- return !!path && !path.startsWith("/") && !/[\\\u0000-\u001f\u007f]/.test(path) && path.split("/").every((p) => p !== "" && p !== "." && p !== "..");
291
- }
292
-
293
- // src/db-limit.ts
294
- var MAX_QUERY_LIMIT = 500;
295
- function checkLimit(n) {
296
- if (!Number.isInteger(n) || n < 1 || n > MAX_QUERY_LIMIT) {
297
- throw new BuildersError(`limit() must be a whole number from 1 to ${MAX_QUERY_LIMIT}, not ${n}.`);
298
- }
299
- return n;
300
- }
301
- var queryLimit = (spec) => spec.limit ?? MAX_QUERY_LIMIT;
302
-
303
- // src/db-indexes.ts
304
- import { readFileSync, statSync } from "node:fs";
305
- import { join } from "node:path";
306
- var cache = null;
307
- function indexesFilePath(env = process.env) {
308
- return env.BUILDERS_INDEXES_FILE || join(process.cwd(), INDEXES_FILE);
309
- }
310
- function declaredIndexes(path = indexesFilePath()) {
311
- let st;
312
- try {
313
- st = statSync(path);
314
- } catch {
315
- return [];
316
- }
317
- if (cache && cache.path === path && cache.mtimeMs === st.mtimeMs && cache.size === st.size) return cache.indexes;
318
- try {
319
- const indexes = parseIndexesFile(readFileSync(path, "utf8"));
320
- cache = { path, mtimeMs: st.mtimeMs, size: st.size, indexes };
321
- return indexes;
322
- } catch (e) {
323
- if (e instanceof IndexesFileError) throw new BuildersError(e.message);
324
- throw e;
325
- }
326
- }
327
- function checkIndex(collection, spec) {
328
- const declared = declaredIndexes();
329
- const need = requiredIndex(collection, spec);
330
- if (need && !indexesServe(declared, need)) throw new BuildersError(missingIndexMessage(need));
331
- }
332
- function missingIndexError(collection, spec, e) {
333
- const err = e;
334
- if (err?.code !== 9 || !/index/i.test(err.message ?? "")) return null;
335
- const need = requiredIndex(collection, spec);
336
- return need ? new BuildersError(`${missingIndexMessage(need)}
337
- Then push a new version: the platform creates the index before the preview.`) : null;
338
- }
339
-
340
- // src/db-firestore.ts
341
- var client;
342
- function firestore() {
343
- return client ??= import("@google-cloud/firestore").then((m) => {
344
- const env = process.env;
345
- const fs = new m.Firestore({
346
- ignoreUndefinedProperties: true,
347
- projectId: env.GOOGLE_CLOUD_PROJECT ?? (env.FIRESTORE_EMULATOR_HOST ? "demo-builders" : void 0),
348
- databaseId: env.FIRESTORE_DATABASE || void 0
349
- });
350
- return { fs, Timestamp: m.Timestamp };
351
- });
352
- }
353
- function firestoreCollection(name) {
354
- const ref = async () => (await firestore()).fs.collection(name);
355
- const query = (spec) => ({
356
- where: (field, op, value) => query({ ...spec, where: [...spec.where, { field, op, value }] }),
357
- orderBy: (field, direction = "asc") => query({ ...spec, orderBy: [...spec.orderBy, { field, direction }] }),
358
- limit: (n) => query({ ...spec, limit: checkLimit(n) }),
359
- async list() {
360
- const { Timestamp } = await firestore();
361
- let q = await ref();
362
- for (const w of spec.where) q = q.where(w.field, w.op, w.value);
363
- for (const o of spec.orderBy) q = q.orderBy(o.field, o.direction);
364
- q = q.limit(queryLimit(spec));
365
- let snap;
366
- try {
367
- snap = await q.get();
368
- } catch (e) {
369
- throw missingIndexError(name, spec, e) ?? e;
370
- }
371
- return snap.docs.map((d) => ({ ...toPlain(d.data(), Timestamp), id: d.id }));
372
- },
373
- async get(id) {
374
- const { Timestamp } = await firestore();
375
- const d = await (await ref()).doc(id).get();
376
- return d.exists ? { ...toPlain(d.data(), Timestamp), id: d.id } : null;
377
- },
378
- async add(data) {
379
- const body = withoutId(data);
380
- const r = await (await ref()).add(body);
381
- return { ...body, id: r.id };
382
- },
383
- async set(id, data) {
384
- await (await ref()).doc(id).set(withoutId(data));
385
- },
386
- async update(id, patch) {
387
- try {
388
- await (await ref()).doc(id).update(withoutId(patch));
389
- } catch (e) {
390
- if (e.code === 5) throw new NotFoundError(`No document "${id}" in "${name}".`);
391
- throw e;
392
- }
393
- },
394
- async delete(id) {
395
- await (await ref()).doc(id).delete();
396
- }
397
- });
398
- return query({ where: [], orderBy: [] });
399
- }
400
- function withoutId(data) {
401
- const { id: _id, ...rest } = data;
402
- return rest;
403
- }
404
- function toPlain(v, Timestamp) {
405
- if (v instanceof Timestamp) return v.toDate();
406
- if (Array.isArray(v)) return v.map((x) => toPlain(x, Timestamp));
407
- if (v && typeof v === "object" && Object.getPrototypeOf(v) === Object.prototype) {
408
- return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, toPlain(x, Timestamp)]));
409
- }
410
- return v;
411
- }
412
-
413
- // src/db-memory.ts
414
- import { randomBytes } from "node:crypto";
415
- import { mkdirSync, readFileSync as readFileSync2, renameSync, writeFileSync } from "node:fs";
416
- import { join as join2 } from "node:path";
417
- var warnedCap = /* @__PURE__ */ new Set();
418
- var g = globalThis;
419
- var store = () => g.__buildersMemoryDb ??= load();
420
- var SAVE_DELAY_MS = 100;
421
- var dbFile = () => {
422
- const dir = process.env[DEV_DATA_DIR_ENV];
423
- return dir ? join2(dir, "db.json") : null;
424
- };
425
- var TAG = "__builders";
426
- function revive(_k, v) {
427
- if (!v || typeof v !== "object" || Array.isArray(v)) return v;
428
- const t = v;
429
- if (Object.keys(t).length !== 2 || typeof t.value !== "string") return v;
430
- if (t[TAG] === "date") return new Date(t.value);
431
- if (t[TAG] === "bytes") return new Uint8Array(Buffer.from(t.value, "base64"));
432
- return v;
433
- }
434
- function load() {
435
- const file = dbFile();
436
- const s = /* @__PURE__ */ new Map();
437
- if (!file) return s;
438
- let raw;
439
- try {
440
- raw = JSON.parse(readFileSync2(file, "utf8"), revive);
441
- } catch {
442
- return s;
443
- }
444
- for (const [name, docs] of Object.entries(raw)) s.set(name, new Map(Object.entries(docs)));
445
- return s;
446
- }
447
- var warnedSave = false;
448
- function saveSoon() {
449
- const file = dbFile();
450
- if (!file || g.__buildersMemoryDbSave) return;
451
- g.__buildersMemoryDbSave = setTimeout(() => {
452
- g.__buildersMemoryDbSave = void 0;
453
- try {
454
- const out = {};
455
- for (const [name, docs] of store()) out[name] = Object.fromEntries(docs);
456
- const text = JSON.stringify(out, function(k, v) {
457
- const raw = this[k];
458
- if (raw instanceof Date) return { [TAG]: "date", value: Number.isNaN(raw.getTime()) ? "" : raw.toISOString() };
459
- if (raw instanceof Uint8Array) return { [TAG]: "bytes", value: Buffer.from(raw).toString("base64") };
460
- return typeof v === "bigint" ? v.toString() : v;
461
- });
462
- mkdirSync(join2(file, ".."), { recursive: true });
463
- writeFileSync(`${file}.tmp`, text);
464
- renameSync(`${file}.tmp`, file);
465
- } catch (e) {
466
- if (!warnedSave) console.warn(`[builders] The test database could not be saved to ${file}: ${e instanceof Error ? e.message : String(e)}`);
467
- warnedSave = true;
468
- }
469
- }, SAVE_DELAY_MS);
470
- }
471
- function resetMemoryDb() {
472
- store().clear();
473
- saveSoon();
474
- }
475
- function memoryCollection(name) {
476
- const docs = () => {
477
- let m = store().get(name);
478
- if (!m) store().set(name, m = /* @__PURE__ */ new Map());
479
- return m;
480
- };
481
- const out = (id, data) => ({ ...structuredClone(data), id });
482
- const clean = (data) => {
483
- const copy = structuredClone(data);
484
- delete copy.id;
485
- for (const k of Object.keys(copy)) if (copy[k] === void 0) delete copy[k];
486
- return copy;
487
- };
488
- const query = (spec) => ({
489
- where: (field, op, value) => query({ ...spec, where: [...spec.where, { field, op, value }] }),
490
- orderBy: (field, direction = "asc") => query({ ...spec, orderBy: [...spec.orderBy, { field, direction }] }),
491
- limit: (n) => query({ ...spec, limit: checkLimit(n) }),
492
- async list() {
493
- checkIndex(name, spec);
494
- let rows = [...docs()].filter(([, d]) => spec.where.every((w) => matches(d[w.field], w.op, w.value)));
495
- rows = rows.filter(([, d]) => spec.orderBy.every((o) => d[o.field] !== void 0));
496
- rows.sort(([, a], [, b]) => {
497
- for (const o of spec.orderBy) {
498
- const c = compare(a[o.field], b[o.field]);
499
- if (c !== 0) return o.direction === "desc" ? -c : c;
500
- }
501
- return 0;
502
- });
503
- if (spec.limit === void 0 && rows.length > MAX_QUERY_LIMIT && !warnedCap.has(name)) {
504
- warnedCap.add(name);
505
- console.warn(`[builders] A query on "${name}" matched more than ${MAX_QUERY_LIMIT} documents; list() returns only the first ${MAX_QUERY_LIMIT}.`);
506
- }
507
- rows = rows.slice(0, queryLimit(spec));
508
- return rows.map(([id, d]) => out(id, d));
509
- },
510
- async get(id) {
511
- const d = docs().get(id);
512
- return d ? out(id, d) : null;
513
- },
514
- async add(data) {
515
- const id = autoId();
516
- docs().set(id, clean(data));
517
- saveSoon();
518
- return out(id, docs().get(id));
519
- },
520
- async set(id, data) {
521
- docs().set(id, clean(data));
522
- saveSoon();
523
- },
524
- async update(id, patch) {
525
- const d = docs().get(id);
526
- if (!d) throw new NotFoundError(`No document "${id}" in "${name}".`);
527
- docs().set(id, { ...d, ...clean(patch) });
528
- saveSoon();
529
- },
530
- async delete(id) {
531
- docs().delete(id);
532
- saveSoon();
533
- }
534
- });
535
- return query({ where: [], orderBy: [] });
536
- }
537
- function autoId() {
538
- const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
539
- return [...randomBytes(20)].map((b) => chars[b % chars.length]).join("");
540
- }
541
- function key(v) {
542
- return v instanceof Date ? v.getTime() : v;
543
- }
544
- function compare(a, b) {
545
- const x = key(a);
546
- const y = key(b);
547
- return x < y ? -1 : x > y ? 1 : 0;
548
- }
549
- function equal(a, b) {
550
- return key(a) === key(b);
551
- }
552
- function matches(v, op, target) {
553
- if (v === void 0) return false;
554
- const list = Array.isArray(target) ? target : [];
555
- switch (op) {
556
- case "==":
557
- return equal(v, target);
558
- case "!=":
559
- return !equal(v, target);
560
- case "<":
561
- return compare(v, target) < 0;
562
- case "<=":
563
- return compare(v, target) <= 0;
564
- case ">":
565
- return compare(v, target) > 0;
566
- case ">=":
567
- return compare(v, target) >= 0;
568
- case "in":
569
- return list.some((t) => equal(v, t));
570
- case "not-in":
571
- return !list.some((t) => equal(v, t));
572
- case "array-contains":
573
- return Array.isArray(v) && v.some((x) => equal(x, target));
574
- case "array-contains-any":
575
- return Array.isArray(v) && v.some((x) => list.some((t) => equal(x, t)));
576
- }
577
- }
578
-
579
- // src/db.ts
580
- function dbMode(env = process.env) {
581
- if (env.BUILDERS_DB === "memory" || env.BUILDERS_DB === "firestore") return env.BUILDERS_DB;
582
- if (env.FIRESTORE_EMULATOR_HOST || env.GOOGLE_APPLICATION_CREDENTIALS) return "firestore";
583
- if (env.NODE_ENV === "production" || env.K_SERVICE) return "firestore";
584
- return "memory";
585
- }
586
- var warned = false;
587
- var db = {
588
- collection(name) {
589
- if (!/^[A-Za-z0-9_-]{1,100}$/.test(name)) {
590
- throw new BuildersError(`"${name}" is not a valid collection name. Use letters, digits, "-" or "_".`);
591
- }
592
- if (dbMode() === "firestore") return firestoreCollection(name);
593
- if (!warned && process.env.NODE_ENV !== "test") {
594
- warned = true;
595
- console.info(
596
- 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."
597
- );
598
- }
599
- return memoryCollection(name);
600
- },
601
- // Empties the in-memory database. For tests.
602
- reset: resetMemoryDb
603
- };
604
-
605
- // src/ai.ts
606
- import { z as z3 } from "zod";
607
-
608
- // src/platform.ts
609
- import { readFileSync as readFileSync3, statSync as statSync2 } from "node:fs";
610
- var METADATA = "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default";
611
- var idTokens = /* @__PURE__ */ new Map();
612
- var accessToken;
613
- function jwtExp(token) {
614
- try {
615
- const payload = JSON.parse(Buffer.from(token.split(".")[1] ?? "", "base64url").toString("utf8"));
616
- return typeof payload.exp === "number" ? payload.exp * 1e3 : 0;
617
- } catch {
618
- return 0;
619
- }
620
- }
621
- async function metadata(path) {
622
- let res;
623
- try {
624
- res = await fetch(`${METADATA}${path}`, { headers: { "Metadata-Flavor": "Google" }, signal: AbortSignal.timeout(5e3) });
625
- } catch {
626
- throw new NotOnBuildersError("This");
627
- }
628
- if (!res.ok) throw new BuildersError(`The app's identity is not available (${res.status}).`, 503);
629
- return res;
630
- }
631
- async function idToken(audience) {
632
- const hit = idTokens.get(audience);
633
- if (hit && hit.exp - Date.now() > 5 * 6e4) return hit.token;
634
- const res = await metadata(`/identity?audience=${encodeURIComponent(audience)}&format=full`);
635
- const token = (await res.text()).trim();
636
- idTokens.set(audience, { token, exp: jwtExp(token) });
637
- return token;
638
- }
639
- async function googleAccessToken() {
640
- if (accessToken && accessToken.exp - Date.now() > 6e4) return accessToken.token;
641
- const res = await metadata("/token");
642
- const j = await res.json();
643
- if (!j.access_token) throw new BuildersError("The app's identity gave no access token.", 503);
644
- accessToken = { token: j.access_token, exp: Date.now() + (j.expires_in ?? 300) * 1e3 };
645
- return accessToken.token;
646
- }
647
- function devUrl(env = process.env) {
648
- const url = env[DEV_ENV.url]?.trim();
649
- if (!url || env.NODE_ENV === "production" || env.K_SERVICE) return null;
650
- return url.replace(/\/+$/, "");
651
- }
652
- var devTokenCache;
653
- var NO_DEV_TOKEN = "Start the dev preview again with the preview command from open_app (it gives a new token).";
654
- function devToken(env = process.env) {
655
- const path = env[DEV_ENV.tokenFile]?.trim();
656
- if (!path) throw new BuildersError(`The dev preview has no Builders token (${DEV_ENV.tokenFile} is not set). ${NO_DEV_TOKEN}`, 401);
657
- let st;
658
- try {
659
- st = statSync2(path);
660
- } catch {
661
- throw new BuildersError(`The dev preview's Builders token file is missing. ${NO_DEV_TOKEN}`, 401);
662
- }
663
- const c = devTokenCache;
664
- if (c && c.path === path && c.mtimeMs === st.mtimeMs && c.size === st.size) return c.token;
665
- let token;
666
- try {
667
- token = (readFileSync3(path, "utf8").split("\n")[0] ?? "").trim();
668
- } catch {
669
- throw new BuildersError(`The dev preview's Builders token file cannot be read. ${NO_DEV_TOKEN}`, 401);
670
- }
671
- if (!token) throw new BuildersError(`The dev preview's Builders token file is empty. ${NO_DEV_TOKEN}`, 401);
672
- devTokenCache = { path, mtimeMs: st.mtimeMs, size: st.size, token };
673
- return token;
674
- }
675
- var NotOnBuildersError = class extends BuildersError {
676
- constructor(what) {
677
- super(
678
- `${what} works only on Builders: in the dev preview, a saved version and the live app. It does not work in pnpm dev without the Builders preview, or in tests. Start the dev preview with the commands from open_app, or show a short note here.`,
679
- 503
680
- );
681
- this.name = "NotOnBuildersError";
682
- }
683
- };
684
- var WHAT = { ai: "AI", notify: "Sending notifications" };
685
- function gateway(addOn) {
686
- const dev = devUrl();
687
- if (dev) return { url: dev, app: "", dev: true };
688
- const tenant = process.env[APP_ENV.tenant];
689
- const app = process.env[APP_ENV.app];
690
- if (!tenant || !app) throw new NotOnBuildersError(WHAT[addOn] ?? "This");
691
- const url = process.env[APP_ENV.aiGateway];
692
- if (!url) throw new AddOnNotEnabledError(addOn);
693
- return { url: url.replace(/\/+$/, ""), app: `${tenant}/${app}` };
694
- }
695
- function errorOf(status, body, fallback) {
696
- const msg = body?.error?.message ?? fallback;
697
- return new BuildersError(msg, status === 429 && body?.error?.code === "budget" ? 402 : status);
698
- }
699
- async function gatewayFetch(t, path, body, o = {}) {
700
- const headers = t.dev ? { "content-type": "application/json", authorization: `Bearer ${devToken()}` } : { "content-type": "application/json", authorization: `Bearer ${await idToken(t.url)}`, [APP_HEADER]: t.app };
701
- const url = t.dev ? `${t.url}${path.replace(/^\/v1(?=\/)/, "")}` : `${t.url}${path}`;
702
- let res;
703
- try {
704
- res = await fetch(url, {
705
- method: "POST",
706
- headers,
707
- body: JSON.stringify(body),
708
- signal: o.signal ?? AbortSignal.timeout(o.timeoutMs ?? 12e4)
709
- });
710
- } catch (e) {
711
- throw new BuildersError(`Could not reach the platform's ${t.dev ? "dev preview service" : "AI service"}: ${e.message}`, 502);
712
- }
713
- if (!res.ok) {
714
- const text = await res.text();
715
- let j;
716
- try {
717
- j = JSON.parse(text);
718
- } catch {
719
- }
720
- throw errorOf(res.status, j, `The platform's ${t.dev ? "dev preview service" : "AI service"} answered ${res.status}.`);
721
- }
722
- return res;
723
- }
724
- async function gatewayJson(addOn, path, body, o = {}) {
725
- const res = await gatewayFetch(gateway(addOn), path, body, o);
726
- return await res.json();
727
- }
728
-
729
- // src/storage-local.ts
730
- import { mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
731
- import { dirname, join as join3, relative, sep } from "node:path";
732
- function localStorage(dir) {
733
- const file = (path) => join3(dir, "files", path);
734
- const meta = (path) => join3(dir, "files-meta", `${path}.json`);
735
- return {
736
- async upload(path, data, opts) {
737
- await mkdir(dirname(file(path)), { recursive: true });
738
- await mkdir(dirname(meta(path)), { recursive: true });
739
- await writeFile(file(path), typeof data === "string" ? data : Buffer.from(data));
740
- await writeFile(meta(path), JSON.stringify({ contentType: opts.contentType ?? "" }));
741
- },
742
- async download(path) {
743
- try {
744
- return await readFile(file(path));
745
- } catch {
746
- throw new NotFoundError(`No file "${path}".`);
747
- }
748
- },
749
- async signedUrl(path, action, expires, contentType) {
750
- const secret = process.env[DEV_FILES_SECRET_ENV];
751
- if (!secret) throw new BuildersError("File links work in the dev preview. Start it with the preview command from open_app.");
752
- const link = await devFileLink(secret, { path, action, expires, contentType: contentType ?? "" });
753
- const origin = process.env[DEV_PREVIEW_URL_ENV];
754
- return origin ? new URL(link, origin).toString() : link;
755
- },
756
- async list(prefix) {
757
- const root = join3(dir, "files");
758
- const out = [];
759
- const walk = async (d) => {
760
- let entries;
761
- try {
762
- entries = await readdir(d, { withFileTypes: true });
763
- } catch {
764
- return;
765
- }
766
- for (const e of entries) {
767
- const p = join3(d, e.name);
768
- if (e.isDirectory()) await walk(p);
769
- else out.push(relative(root, p).split(sep).join("/"));
770
- }
771
- };
772
- await walk(root);
773
- return out.filter((p) => p.startsWith(prefix)).sort();
774
- },
775
- async delete(path) {
776
- await rm(file(path), { force: true });
777
- await rm(meta(path), { force: true });
778
- }
779
- };
780
- }
781
-
782
- // src/storage.ts
783
- var cached;
784
- async function bucket() {
785
- const name = process.env.STORAGE_BUCKET;
786
- if (!name) throw new AddOnNotEnabledError("storage");
787
- if (cached?.name !== name) {
788
- cached = { name, bucket: import("@google-cloud/storage").then((m) => new m.Storage().bucket(name)) };
789
- }
790
- return cached.bucket;
791
- }
792
- function local() {
793
- const dir = process.env.STORAGE_BUCKET ? void 0 : process.env[DEV_DATA_DIR_ENV];
794
- if (!dir) return null;
795
- const addOns = process.env.BUILDERS_DEV_ADDONS;
796
- if (addOns !== void 0 && !addOns.split(",").includes("storage")) throw new AddOnNotEnabledError("storage");
797
- return localStorage(dir);
798
- }
799
- function checkPath(path) {
800
- if (!validDevFilePath(path)) {
801
- throw new BuildersError(`"${path}" is not a valid file path. Use something like "photos/cat.jpg".`, 400);
802
- }
803
- return path;
804
- }
805
- var storage = {
806
- async upload(path, data, opts = {}) {
807
- const l = local();
808
- if (l) {
809
- await l.upload(checkPath(path), data, opts);
810
- return { path };
811
- }
812
- await (await bucket()).file(checkPath(path)).save(typeof data === "string" ? data : Buffer.from(data), {
813
- contentType: opts.contentType,
814
- resumable: false
815
- });
816
- return { path };
817
- },
818
- async download(path) {
819
- const l = local();
820
- if (l) return l.download(checkPath(path));
821
- const [buf] = await (await bucket()).file(checkPath(path)).download();
822
- return buf;
823
- },
824
- async signedUrl(path, opts = {}) {
825
- const minutes = Math.min(opts.expiresInMinutes ?? 15, 7 * 24 * 60);
826
- const l = local();
827
- if (l) return l.signedUrl(checkPath(path), opts.action ?? "read", Date.now() + minutes * 6e4, opts.contentType);
828
- const [url] = await (await bucket()).file(checkPath(path)).getSignedUrl({
829
- version: "v4",
830
- action: opts.action ?? "read",
831
- expires: Date.now() + minutes * 6e4,
832
- contentType: opts.contentType
833
- });
834
- return url;
835
- },
836
- async list(prefix = "") {
837
- const l = local();
838
- if (l) return l.list(prefix);
839
- const [files] = await (await bucket()).getFiles({ prefix });
840
- return files.map((f) => f.name);
841
- },
842
- async delete(path) {
843
- const l = local();
844
- if (l) return l.delete(checkPath(path));
845
- await (await bucket()).file(checkPath(path)).delete({ ignoreNotFound: true });
846
- }
847
- };
848
-
849
- // src/ai.ts
850
- var MODELS = new Set(AI_MODEL_CHOICES);
851
- function model(m) {
852
- const v = m ?? "balanced";
853
- if (!MODELS.has(v)) throw new BuildersError(`Unknown AI model "${v}". Use "fast", "balanced" or "best".`, 400);
854
- return v;
855
- }
856
- async function base64(a) {
857
- if ("storagePath" in a) return (await storage.download(a.storagePath)).toString("base64");
858
- return typeof a.data === "string" ? a.data : Buffer.from(a.data).toString("base64");
859
- }
860
- async function content(text, attachments = []) {
861
- if (!attachments.length) return text;
862
- const files = await Promise.all(attachments.map(async (a) => ({ type: "file", mediaType: a.mediaType, data: await base64(a) })));
863
- return [...files, { type: "text", text }];
864
- }
865
- async function request(messages, o, extra = {}) {
866
- return {
867
- model: model(o.model),
868
- ...o.system ? { system: o.system } : {},
869
- maxTokens: o.maxTokens ?? 1024,
870
- ...o.temperature !== void 0 ? { temperature: o.temperature } : {},
871
- messages: await Promise.all(messages.map(async (m) => ({ role: m.role, content: await content(m.content, m.attachments) }))),
872
- ...extra
873
- };
874
- }
875
- function toJsonSchema(schema) {
876
- if (!schema || typeof schema !== "object" || !("_zod" in schema)) {
877
- throw new BuildersError("ai.json needs a zod 4 schema, e.g. z.object({ city: z.string() }).", 400);
878
- }
879
- let js;
880
- try {
881
- js = z3.toJSONSchema(schema, { io: "input", unrepresentable: "throw" });
882
- } catch (e) {
883
- throw new BuildersError(
884
- `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().`,
885
- 400
886
- );
887
- }
888
- delete js.$schema;
889
- if (js.type !== "object") throw new BuildersError("ai.json needs an object schema (z.object({...})). Put a list in a field.", 400);
890
- return js;
891
- }
892
- var ai = {
893
- // One question, the answer as text.
894
- async ask(prompt, opts = {}) {
895
- return (await ai.chat([{ role: "user", content: prompt, ...opts.attachments ? { attachments: opts.attachments } : {} }], opts)).text;
896
- },
897
- // A conversation: the earlier messages, then the new question.
898
- async chat(messages, opts = {}) {
899
- const body = await request(messages, opts);
900
- const r = await gatewayJson("ai", "/v1/messages", body, { signal: opts.signal, timeoutMs: 3e5 });
901
- return { text: r.text, stopReason: r.stopReason, usage: r.usage };
902
- },
903
- // A typed object instead of text, checked with the schema. If the first
904
- // answer does not match, Claude gets the problem and tries once more.
905
- async json(prompt, opts) {
906
- const schema = toJsonSchema(opts.schema);
907
- const messages = [{ role: "user", content: prompt, ...opts.attachments ? { attachments: opts.attachments } : {} }];
908
- let last = "";
909
- for (let attempt = 0; attempt < 2; attempt++) {
910
- const body = await request(messages, { ...opts, maxTokens: opts.maxTokens ?? 4096 }, { json: { schema, ...opts.description ? { description: opts.description } : {} } });
911
- const r = await gatewayJson("ai", "/v1/messages", body, { signal: opts.signal, timeoutMs: 3e5 });
912
- if (r.stopReason === "max_tokens") {
913
- throw new BuildersError(`The AI answer was too long and was cut off. Raise maxTokens (now ${body.maxTokens}) or ask for less.`, 502);
914
- }
915
- const parsed = opts.schema.safeParse(r.json);
916
- if (parsed.success) return parsed.data;
917
- last = parsed.error.issues.slice(0, 5).map((i) => `${i.path.join(".") || "answer"}: ${i.message}`).join("; ");
918
- messages.push({ role: "assistant", content: JSON.stringify(r.json ?? null).slice(0, 2e4) }, { role: "user", content: `That answer does not match the schema (${last}). Answer again with the tool, matching the schema exactly.` });
919
- }
920
- throw new BuildersError(`The AI answer did not match the schema: ${last}`, 502);
921
- },
922
- // The answer as it is written, piece by piece:
923
- // for await (const piece of ai.stream("Write a poem")) send(piece);
924
- async *stream(prompt, opts = {}) {
925
- const messages = typeof prompt === "string" ? [{ role: "user", content: prompt, ...opts.attachments ? { attachments: opts.attachments } : {} }] : prompt;
926
- const body = await request(messages, opts, { stream: true });
927
- const res = await gatewayFetch(gateway("ai"), "/v1/messages", body, { signal: opts.signal, timeoutMs: 9e5 });
928
- const reader = res.body.getReader();
929
- const dec = new TextDecoder();
930
- let buf = "";
931
- let text = "";
932
- let ended = false;
933
- try {
934
- for (; ; ) {
935
- const { done, value } = await reader.read();
936
- if (done) break;
937
- buf += dec.decode(value, { stream: true });
938
- let i;
939
- while ((i = buf.indexOf("\n\n")) >= 0) {
940
- const block = buf.slice(0, i);
941
- buf = buf.slice(i + 2);
942
- const line = block.split("\n").find((l) => l.startsWith("data:"));
943
- if (!line) continue;
944
- const ev = JSON.parse(line.slice(5));
945
- if (ev.type === "text") {
946
- text += ev.text;
947
- yield ev.text;
948
- } else if (ev.type === "done") {
949
- ended = true;
950
- return { text, stopReason: ev.stopReason, usage: ev.usage };
951
- } else if (ev.type === "error") {
952
- throw new BuildersError(ev.message, 502);
953
- }
954
- }
955
- }
956
- throw new BuildersError("The AI answer stopped early. Try again.", 502);
957
- } finally {
958
- if (!ended) await reader.cancel().catch(() => {
959
- });
960
- }
961
- },
962
- // A new image from a prompt, or a changed image (opts.images).
963
- async image(prompt, opts = {}) {
964
- const images = await Promise.all((opts.images ?? []).map(async (a) => ({ mediaType: a.mediaType, data: await base64(a) })));
965
- const r = await gatewayJson("ai", "/v1/image", { prompt, ...opts.aspectRatio ? { aspectRatio: opts.aspectRatio } : {}, ...opts.size ? { size: opts.size } : {}, images }, { signal: opts.signal, timeoutMs: 3e5 });
966
- const first = r.images[0];
967
- if (!first) throw new BuildersError("The AI made no image. Change the prompt and try again.", 502);
968
- return { mediaType: first.mediaType, data: Buffer.from(first.data, "base64"), text: r.text };
969
- },
970
- // Text to speech, as WAV audio.
971
- async speak(text, opts = {}) {
972
- const r = await gatewayJson("ai", "/v1/speech", { text, ...opts.voice ? { voice: opts.voice } : {}, ...opts.style ? { style: opts.style } : {} }, { signal: opts.signal, timeoutMs: 3e5 });
973
- return { mediaType: "audio/wav", data: Buffer.from(r.data, "base64") };
974
- },
975
- // Speech to text, for audio up to one minute.
976
- async transcribe(audio, opts) {
977
- const data = "storagePath" in audio && !(audio instanceof Uint8Array) ? (await storage.download(audio.storagePath)).toString("base64") : Buffer.from(audio).toString("base64");
978
- const r = await gatewayJson("ai", "/v1/transcribe", { mediaType: opts.mediaType, data, ...opts.languages ? { languages: opts.languages } : {} }, { signal: opts.signal, timeoutMs: 12e4 });
979
- return { text: r.text, seconds: r.seconds };
980
- }
981
- };
982
-
983
- // src/notify.ts
984
- var notify = {
985
- async email(to, subject, text) {
986
- await gatewayJson("notify", "/v1/notify/email", { to: Array.isArray(to) ? to : [to], subject, text }, { timeoutMs: 3e4 });
987
- },
988
- async slack(text) {
989
- await gatewayJson("notify", "/v1/notify/slack", { text }, { timeoutMs: 3e4 });
990
- }
991
- };
992
-
993
- // src/secrets.ts
994
- var cache2 = /* @__PURE__ */ new Map();
995
- var TTL_MS = 5 * 6e4;
996
- var secrets = {
997
- async get(name) {
998
- const bad = secretNameError(name);
999
- if (bad) throw new BuildersError(`"${name}" is not a secret name. ${bad}`, 400);
1000
- if (process.env[APP_ENV.revision] === "preview") {
1001
- throw new BuildersError(`Secrets work only in the live app, not in a version preview. Make the version live to use ${name}; until then show a message instead.`, 503);
1002
- }
1003
- const project = process.env[APP_ENV.project];
1004
- if (!project) {
1005
- const v = process.env.NODE_ENV !== "production" ? process.env[name] : void 0;
1006
- if (v) return v;
1007
- 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.`);
1008
- }
1009
- const hit = cache2.get(name);
1010
- if (hit && Date.now() - hit.at < TTL_MS) return hit.value;
1011
- const url = `https://secretmanager.googleapis.com/v1/projects/${encodeURIComponent(project)}/secrets/${name}/versions/latest:access`;
1012
- let res;
1013
- try {
1014
- res = await fetch(url, { headers: { authorization: `Bearer ${await googleAccessToken()}` }, signal: AbortSignal.timeout(1e4) });
1015
- } catch (e) {
1016
- throw new BuildersError(`Could not read the secret ${name}: ${e.message}`, 502);
1017
- }
1018
- if (res.status === 404 || res.status === 403) throw new NotFoundError(`The secret ${name} is not set. The app owner or an admin can set it in the Builders portal (app page, Secrets).`);
1019
- if (!res.ok) throw new BuildersError(`Could not read the secret ${name} (${res.status}).`, 502);
1020
- const j = await res.json();
1021
- const value = Buffer.from(j.payload?.data ?? "", "base64").toString("utf8");
1022
- cache2.set(name, { value, at: Date.now() });
1023
- return value;
1024
- },
1025
- // For tests.
1026
- clearCache() {
1027
- cache2.clear();
1028
- }
1029
- };
1030
- export {
1031
- AddOnNotEnabledError,
1032
- BuildersError,
1033
- IDENTITY_HEADER,
1034
- MAX_QUERY_LIMIT,
1035
- NotFoundError,
1036
- NotOnBuildersError,
1037
- NotSignedInError,
1038
- SIGN_OUT_PATH,
1039
- ai,
1040
- db,
1041
- dbMode,
1042
- getUser,
1043
- nameFromEmail,
1044
- notify,
1045
- secrets,
1046
- storage
1047
- };
1
+ // @n-dream/builders-sdk (design 4.5, D13). Each later platform service
2
+ // adds one named export here (db, files, ai, ...).
3
+ export { appInfo, APP_INFO_PATH } from "./app-info.js";
4
+ export { BuildersError } from "./errors.js";