@n-dream/builders-sdk 0.3.1 → 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 +10 -12
- package/dist/index.d.ts +3 -52
- package/dist/index.js +44 -642
- package/package.json +2 -4
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,
|
|
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.
|
|
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 {
|
|
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
|
-
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
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,
|
|
167
|
-
export type { AiModel, AskOptions, Attachment, ChatResult,
|
|
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
|
|
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 =
|
|
196
|
-
var ContentPartSchema =
|
|
197
|
-
|
|
198
|
-
|
|
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 =
|
|
201
|
-
role:
|
|
202
|
-
content:
|
|
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 =
|
|
205
|
-
var MessagesRequestSchema =
|
|
66
|
+
var ModelChoice = z.enum(AI_MODEL_CHOICES);
|
|
67
|
+
var MessagesRequestSchema = z.object({
|
|
206
68
|
model: ModelChoice.default("balanced"),
|
|
207
|
-
system:
|
|
208
|
-
messages:
|
|
209
|
-
maxTokens:
|
|
210
|
-
temperature:
|
|
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:
|
|
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:
|
|
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 =
|
|
220
|
-
prompt:
|
|
221
|
-
aspectRatio:
|
|
222
|
-
size:
|
|
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:
|
|
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 =
|
|
237
|
-
text:
|
|
238
|
-
voice:
|
|
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:
|
|
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 =
|
|
244
|
-
mediaType:
|
|
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:
|
|
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 =
|
|
250
|
-
var EmailRequestSchema =
|
|
251
|
-
to:
|
|
252
|
-
subject:
|
|
253
|
-
text:
|
|
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,346 +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
|
-
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
132
|
// src/ai.ts
|
|
606
|
-
import { z as
|
|
133
|
+
import { z as z2 } from "zod";
|
|
607
134
|
|
|
608
135
|
// src/platform.ts
|
|
609
|
-
import { readFileSync
|
|
136
|
+
import { readFileSync, statSync } from "node:fs";
|
|
610
137
|
var METADATA = "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default";
|
|
611
138
|
var idTokens = /* @__PURE__ */ new Map();
|
|
612
139
|
var accessToken;
|
|
@@ -656,7 +183,7 @@ function devToken(env = process.env) {
|
|
|
656
183
|
if (!path) throw new BuildersError(`The dev preview has no Builders token (${DEV_ENV.tokenFile} is not set). ${NO_DEV_TOKEN}`, 401);
|
|
657
184
|
let st;
|
|
658
185
|
try {
|
|
659
|
-
st =
|
|
186
|
+
st = statSync(path);
|
|
660
187
|
} catch {
|
|
661
188
|
throw new BuildersError(`The dev preview's Builders token file is missing. ${NO_DEV_TOKEN}`, 401);
|
|
662
189
|
}
|
|
@@ -664,7 +191,7 @@ function devToken(env = process.env) {
|
|
|
664
191
|
if (c && c.path === path && c.mtimeMs === st.mtimeMs && c.size === st.size) return c.token;
|
|
665
192
|
let token;
|
|
666
193
|
try {
|
|
667
|
-
token = (
|
|
194
|
+
token = (readFileSync(path, "utf8").split("\n")[0] ?? "").trim();
|
|
668
195
|
} catch {
|
|
669
196
|
throw new BuildersError(`The dev preview's Builders token file cannot be read. ${NO_DEV_TOKEN}`, 401);
|
|
670
197
|
}
|
|
@@ -726,126 +253,6 @@ async function gatewayJson(addOn, path, body, o = {}) {
|
|
|
726
253
|
return await res.json();
|
|
727
254
|
}
|
|
728
255
|
|
|
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
256
|
// src/ai.ts
|
|
850
257
|
var MODELS = new Set(AI_MODEL_CHOICES);
|
|
851
258
|
function model(m) {
|
|
@@ -854,7 +261,6 @@ function model(m) {
|
|
|
854
261
|
return v;
|
|
855
262
|
}
|
|
856
263
|
async function base64(a) {
|
|
857
|
-
if ("storagePath" in a) return (await storage.download(a.storagePath)).toString("base64");
|
|
858
264
|
return typeof a.data === "string" ? a.data : Buffer.from(a.data).toString("base64");
|
|
859
265
|
}
|
|
860
266
|
async function content(text, attachments = []) {
|
|
@@ -878,7 +284,7 @@ function toJsonSchema(schema) {
|
|
|
878
284
|
}
|
|
879
285
|
let js;
|
|
880
286
|
try {
|
|
881
|
-
js =
|
|
287
|
+
js = z2.toJSONSchema(schema, { io: "input", unrepresentable: "throw" });
|
|
882
288
|
} catch (e) {
|
|
883
289
|
throw new BuildersError(
|
|
884
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().`,
|
|
@@ -974,7 +380,7 @@ var ai = {
|
|
|
974
380
|
},
|
|
975
381
|
// Speech to text, for audio up to one minute.
|
|
976
382
|
async transcribe(audio, opts) {
|
|
977
|
-
const data =
|
|
383
|
+
const data = Buffer.from(audio).toString("base64");
|
|
978
384
|
const r = await gatewayJson("ai", "/v1/transcribe", { mediaType: opts.mediaType, data, ...opts.languages ? { languages: opts.languages } : {} }, { signal: opts.signal, timeoutMs: 12e4 });
|
|
979
385
|
return { text: r.text, seconds: r.seconds };
|
|
980
386
|
}
|
|
@@ -991,7 +397,7 @@ var notify = {
|
|
|
991
397
|
};
|
|
992
398
|
|
|
993
399
|
// src/secrets.ts
|
|
994
|
-
var
|
|
400
|
+
var cache = /* @__PURE__ */ new Map();
|
|
995
401
|
var TTL_MS = 5 * 6e4;
|
|
996
402
|
var secrets = {
|
|
997
403
|
async get(name) {
|
|
@@ -1006,7 +412,7 @@ var secrets = {
|
|
|
1006
412
|
if (v) return v;
|
|
1007
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.`);
|
|
1008
414
|
}
|
|
1009
|
-
const hit =
|
|
415
|
+
const hit = cache.get(name);
|
|
1010
416
|
if (hit && Date.now() - hit.at < TTL_MS) return hit.value;
|
|
1011
417
|
const url = `https://secretmanager.googleapis.com/v1/projects/${encodeURIComponent(project)}/secrets/${name}/versions/latest:access`;
|
|
1012
418
|
let res;
|
|
@@ -1019,29 +425,25 @@ var secrets = {
|
|
|
1019
425
|
if (!res.ok) throw new BuildersError(`Could not read the secret ${name} (${res.status}).`, 502);
|
|
1020
426
|
const j = await res.json();
|
|
1021
427
|
const value = Buffer.from(j.payload?.data ?? "", "base64").toString("utf8");
|
|
1022
|
-
|
|
428
|
+
cache.set(name, { value, at: Date.now() });
|
|
1023
429
|
return value;
|
|
1024
430
|
},
|
|
1025
431
|
// For tests.
|
|
1026
432
|
clearCache() {
|
|
1027
|
-
|
|
433
|
+
cache.clear();
|
|
1028
434
|
}
|
|
1029
435
|
};
|
|
1030
436
|
export {
|
|
1031
437
|
AddOnNotEnabledError,
|
|
1032
438
|
BuildersError,
|
|
1033
439
|
IDENTITY_HEADER,
|
|
1034
|
-
MAX_QUERY_LIMIT,
|
|
1035
440
|
NotFoundError,
|
|
1036
441
|
NotOnBuildersError,
|
|
1037
442
|
NotSignedInError,
|
|
1038
443
|
SIGN_OUT_PATH,
|
|
1039
444
|
ai,
|
|
1040
|
-
db,
|
|
1041
|
-
dbMode,
|
|
1042
445
|
getUser,
|
|
1043
446
|
nameFromEmail,
|
|
1044
447
|
notify,
|
|
1045
|
-
secrets
|
|
1046
|
-
storage
|
|
448
|
+
secrets
|
|
1047
449
|
};
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@n-dream/builders-sdk",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Builders platform helpers for app code: signed-in user,
|
|
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
|
},
|