nanoodle 0.1.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/src/io.mjs ADDED
@@ -0,0 +1,312 @@
1
+ import { NanoodleError } from "./errors.mjs";
2
+ import { NODE_TYPES, displayName, topoSort } from "./graph.mjs";
3
+
4
+ /* ============================== INPUTS ============================== */
5
+
6
+ /** Which node types contribute user inputs, and with what fields (mirrors play.html INPUT_SPECS). */
7
+ export const INPUT_SPECS = {
8
+ text: [{ f: "text", label: "Text", kind: "textarea" }],
9
+ upload: [{ f: "image", label: "Image", kind: "image" }],
10
+ aupload: [{ f: "audio", label: "Audio", kind: "audio" }],
11
+ vupload: [{ f: "video", label: "Video", kind: "video" }],
12
+ llm: [{ f: "prompt", label: "Prompt", kind: "textarea" },
13
+ { f: "system", label: "System prompt", kind: "textarea", optional: true, def: "You are a helpful, concise assistant." }],
14
+ image: [{ f: "prompt", label: "Image prompt", kind: "textarea" }],
15
+ draw: [{ f: "prompt", label: "Prompt", kind: "textarea" },
16
+ { f: "system", label: "System prompt", kind: "textarea", optional: true }],
17
+ tvideo: [{ f: "prompt", label: "Video prompt", kind: "textarea" }],
18
+ music: [{ f: "prompt", label: "Style / prompt", kind: "textarea" }],
19
+ remix: [{ f: "prompt", label: "Style / direction", kind: "textarea" }],
20
+ tts: [{ f: "prompt", label: "Text to speak", kind: "textarea" }],
21
+ };
22
+
23
+ /**
24
+ * Derive the workflow's user inputs: INPUT_SPECS fields not fed by a wire, plus the
25
+ * inpaint / choice special cases. Each entry gets a unique friendly `key`.
26
+ * @returns [{ key, nodeId, field, kind, label, optional, def, options?, title }]
27
+ */
28
+ export function deriveInputs(graph) {
29
+ const fed = (id, port) => graph.links.some((l) => l.to.node === id && l.to.port === port);
30
+ const entries = [];
31
+ const mk = (n, field, label, kind, optional, specDef) => {
32
+ const cur = n.fields[field];
33
+ return {
34
+ nodeId: n.id, field, label, kind, optional: !!optional,
35
+ def: cur != null && String(cur) !== "" ? cur : specDef,
36
+ title: displayName(n), _node: n,
37
+ };
38
+ };
39
+ for (const n of graph.nodes) {
40
+ if (n.unknown) continue;
41
+ if (n.type === "inpaint") {
42
+ if (!fed(n.id, "prompt")) entries.push(mk(n, "prompt", "What to paint in", "textarea", false));
43
+ // image and/or mask surface whenever not wired (SPEC-io). The app's combined brush widget
44
+ // captures both at once when neither is wired; the library derives two plain image inputs —
45
+ // dropping the mask half would make such graphs un-runnable (the sink needs a mask, and
46
+ // "n.mask" wouldn't even resolve as an input key).
47
+ const imgFed = fed(n.id, "image"), maskFed = fed(n.id, "mask");
48
+ if (!imgFed) entries.push(mk(n, "image", maskFed ? "Image" : "Image — the picture to repaint", "image", false));
49
+ if (!maskFed) entries.push(mk(n, "mask", "Mask (white = repaint)", "image", false));
50
+ continue;
51
+ }
52
+ if (n.type === "choice") {
53
+ const options = String(n.fields.options || "").split("\n").map((s) => s.trim()).filter(Boolean);
54
+ const e = { ...mk(n, "selected", "Choice", "choice", false), options };
55
+ // The play page renders this input as a <select>, which always holds a value: an unset or
56
+ // stale `selected` shows (and submits) the FIRST option — mirror that here, matching the
57
+ // choice runner's own fallback, instead of tripping the upfront required-input check.
58
+ if (e.def == null || !options.includes(String(e.def))) e.def = options[0];
59
+ entries.push(e);
60
+ continue;
61
+ }
62
+ const specs = INPUT_SPECS[n.type];
63
+ if (!specs) continue;
64
+ for (const s of specs) {
65
+ if (fed(n.id, s.f)) continue;
66
+ entries.push(mk(n, s.f, s.label, s.kind, s.optional, s.def));
67
+ }
68
+ }
69
+ // Friendly keys: a node's custom name labels its input when it contributes exactly one
70
+ // REQUIRED input (app PR #138); otherwise the generic spec label. Dedupe with " 2", " 3".
71
+ const used = new Map();
72
+ for (const e of entries) {
73
+ const nodeEntries = entries.filter((x) => x.nodeId === e.nodeId);
74
+ const required = nodeEntries.filter((x) => !x.optional);
75
+ const custom = (e._node.name || "").trim();
76
+ let key = custom && required.length === 1 && required[0] === e ? custom : e.label;
77
+ const lower = key.toLowerCase();
78
+ const count = (used.get(lower) || 0) + 1;
79
+ used.set(lower, count);
80
+ if (count > 1) key = key + " " + count;
81
+ e.key = key;
82
+ }
83
+ for (const e of entries) delete e._node;
84
+ return entries;
85
+ }
86
+
87
+ function ambiguous(userKey, candidates) {
88
+ return new NanoodleError(
89
+ `input "${userKey}" is ambiguous — matches ${candidates.map((c) => `${c.nodeId}.${c.field} ("${c.key}")`).join(", ")}; ` +
90
+ "use the nodeId.field form to disambiguate");
91
+ }
92
+
93
+ /**
94
+ * Resolve a user-supplied input name to a derived input entry (case-insensitive, trimmed).
95
+ * Order: derived key → exact node custom name → nodeId.field / bare nodeId → label/field if unique.
96
+ */
97
+ export function resolveInputKey(graph, inputs, userKey) {
98
+ const norm = String(userKey).trim().toLowerCase();
99
+ const byKey = inputs.filter((i) => i.key.toLowerCase() === norm);
100
+ if (byKey.length === 1) return byKey[0];
101
+
102
+ const named = graph.nodes.filter((n) => (n.name || "").trim().toLowerCase() === norm);
103
+ if (named.length) {
104
+ const cand = inputs.filter((i) => named.some((n) => n.id === i.nodeId));
105
+ if (cand.length === 1) return cand[0];
106
+ if (cand.length > 1) throw ambiguous(userKey, cand);
107
+ }
108
+
109
+ const dot = norm.lastIndexOf(".");
110
+ if (dot > 0) {
111
+ const nid = norm.slice(0, dot), field = norm.slice(dot + 1);
112
+ const hit = inputs.find((i) => i.nodeId.toLowerCase() === nid && i.field.toLowerCase() === field);
113
+ if (hit) return hit;
114
+ const node = graph.nodes.find((n) => n.id.toLowerCase() === nid);
115
+ if (node && graph.links.some((l) => l.to.node === node.id && l.to.port.toLowerCase() === field)) {
116
+ throw new NanoodleError(`"${userKey}" is wired from another node in this workflow and can't be supplied as an input`);
117
+ }
118
+ }
119
+ const byNode = inputs.filter((i) => i.nodeId.toLowerCase() === norm);
120
+ if (byNode.length === 1) return byNode[0];
121
+ if (byNode.length > 1) throw ambiguous(userKey, byNode);
122
+
123
+ const byLabel = inputs.filter((i) => i.label.toLowerCase() === norm || i.field.toLowerCase() === norm);
124
+ if (byLabel.length === 1) return byLabel[0];
125
+ if (byLabel.length > 1) throw ambiguous(userKey, byLabel);
126
+
127
+ const avail = inputs.map((i) => `"${i.key}"`).join(", ") || "(none)";
128
+ throw new NanoodleError(`unknown input "${userKey}" — available inputs: ${avail}`);
129
+ }
130
+
131
+ /* ============================== OUTPUTS ============================== */
132
+
133
+ /**
134
+ * Output nodes = nodes with outputs and no outgoing link (sinks).
135
+ * Keyed by display name; duplicates suffixed " 2", " 3" in topological order. Always also
136
+ * addressable by node id (handled at result-build time).
137
+ * @returns [{ key, nodeId, type, ports }]
138
+ */
139
+ export function deriveOutputs(graph) {
140
+ let ordered;
141
+ try { ordered = topoSort(graph); } catch { ordered = graph.nodes; } // cyclic graphs still get keys; run() errors properly
142
+ const sinks = ordered.filter((n) => {
143
+ if (n.unknown) return false;
144
+ const t = NODE_TYPES[n.type];
145
+ if (!t.outputs || !t.outputs.length) return false;
146
+ return !graph.links.some((l) => l.from.node === n.id);
147
+ });
148
+ const used = new Map();
149
+ return sinks.map((n) => {
150
+ let key = displayName(n);
151
+ const lower = key.toLowerCase();
152
+ const count = (used.get(lower) || 0) + 1;
153
+ used.set(lower, count);
154
+ if (count > 1) key = key + " " + count;
155
+ return { key, nodeId: n.id, type: n.type, ports: NODE_TYPES[n.type].outputs.map((p) => ({ ...p })) };
156
+ });
157
+ }
158
+
159
+ /* ============================== SETTINGS ============================== */
160
+
161
+ // Option lists verbatim from play.html (SIZES line 897, DURATIONS line 3232).
162
+ const SIZES = ["1024x1024", "1024x1536", "1536x1024", "auto"];
163
+ const DURATIONS = ["5", "10"];
164
+
165
+ /** Per-node knobs that are not part of the IO shape (mirrors play.html SETTING_SPECS). */
166
+ export const SETTING_SPECS = {
167
+ llm: [
168
+ { f: "model", label: "Model", kind: "model" },
169
+ { f: "temperature", label: "Temperature", kind: "number", def: "0.8" },
170
+ { f: "maxTokens", label: "Max tokens", kind: "number" },
171
+ { f: "format", label: "Output format", kind: "select", options: ["Text", "JSON"], def: "Text" },
172
+ { f: "reasoningEffort", label: "Reasoning effort", kind: "select", options: ["default", "low", "medium", "high"], def: "default" },
173
+ { f: "showThinking", label: "Show thinking", kind: "boolean" },
174
+ ],
175
+ vision: [
176
+ { f: "model", label: "Model", kind: "model" },
177
+ { f: "q", label: "Question", kind: "textarea", def: "Describe this image." },
178
+ ],
179
+ image: [
180
+ { f: "model", label: "Model", kind: "model" },
181
+ { f: "size", label: "Image size", kind: "select", options: SIZES, def: "1024x1024" },
182
+ { f: "variations", label: "Variations", kind: "number", def: "1" },
183
+ { f: "seed", label: "Seed", kind: "number" },
184
+ ],
185
+ edit: [
186
+ { f: "model", label: "Model", kind: "model" },
187
+ { f: "prompt", label: "Edit instruction", kind: "textarea" },
188
+ { f: "size", label: "Image size", kind: "select", options: SIZES, def: "1024x1024" },
189
+ { f: "seed", label: "Seed", kind: "number" },
190
+ ],
191
+ draw: [
192
+ { f: "model", label: "Model", kind: "model" },
193
+ { f: "showThinking", label: "Show thinking", kind: "boolean", def: true },
194
+ ],
195
+ tvideo: [
196
+ { f: "model", label: "Model", kind: "model" },
197
+ { f: "resolution", label: "Resolution", kind: "select", def: "" },
198
+ { f: "aspect", label: "Aspect ratio", kind: "select", options: ["16:9", "9:16", "1:1", "4:3", "3:4"], def: "16:9" },
199
+ { f: "duration", label: "Duration", kind: "select", options: DURATIONS, def: "5" },
200
+ ],
201
+ ivideo: [
202
+ { f: "model", label: "Model", kind: "model" },
203
+ { f: "prompt", label: "Motion prompt", kind: "textarea" },
204
+ { f: "resolution", label: "Resolution", kind: "select", def: "" },
205
+ { f: "aspect", label: "Aspect ratio", kind: "select", options: ["16:9", "9:16", "1:1", "4:3", "3:4"], def: "16:9" },
206
+ { f: "duration", label: "Duration", kind: "select", options: DURATIONS, def: "5" },
207
+ ],
208
+ vedit: [
209
+ { f: "model", label: "Model", kind: "model" },
210
+ { f: "prompt", label: "Edit instruction", kind: "textarea" },
211
+ { f: "resolution", label: "Resolution", kind: "select", def: "" },
212
+ ],
213
+ lipsync: [
214
+ { f: "model", label: "Model", kind: "model" },
215
+ { f: "prompt", label: "Guidance prompt", kind: "textarea" },
216
+ { f: "resolution", label: "Resolution", kind: "select", def: "" },
217
+ ],
218
+ music: [
219
+ { f: "model", label: "Model", kind: "model" },
220
+ { f: "lyrics", label: "Lyrics", kind: "textarea" },
221
+ { f: "instrumental", label: "Instrumental", kind: "boolean" },
222
+ { f: "duration", label: "Duration (s)", kind: "number" },
223
+ { f: "negative_prompt", label: "Negative prompt", kind: "textarea" },
224
+ { f: "seed", label: "Seed", kind: "number" },
225
+ ],
226
+ remix: [
227
+ { f: "model", label: "Model", kind: "model" },
228
+ { f: "lyrics", label: "Lyrics", kind: "textarea" },
229
+ { f: "duration", label: "Duration (s)", kind: "number" },
230
+ ],
231
+ tts: [
232
+ { f: "model", label: "Model", kind: "model" },
233
+ { f: "voice", label: "Voice", kind: "text" },
234
+ { f: "speed", label: "Speed", kind: "number", def: "1" },
235
+ { f: "instructions", label: "Voice instructions", kind: "textarea" },
236
+ ],
237
+ transcribe: [
238
+ { f: "model", label: "Model", kind: "model" },
239
+ { f: "language", label: "Language", kind: "text", def: "auto" },
240
+ ],
241
+ join: [{ f: "sep", label: "Separator (use \\n for a line break)", kind: "text", def: " " }],
242
+ inpaint: [
243
+ { f: "model", label: "Model", kind: "model" },
244
+ { f: "size", label: "Image size", kind: "select", options: SIZES, def: "1024x1024" },
245
+ { f: "seed", label: "Seed", kind: "number" },
246
+ ],
247
+ };
248
+
249
+ /**
250
+ * Derive overridable settings: SETTING_SPECS fields that aren't wired.
251
+ * @returns [{ key, nodeId, field, kind, label, def, options?, title }]
252
+ */
253
+ export function deriveSettings(graph) {
254
+ const out = [];
255
+ for (const n of graph.nodes) {
256
+ if (n.unknown) continue;
257
+ const specs = SETTING_SPECS[n.type];
258
+ if (!specs) continue;
259
+ for (const s of specs) {
260
+ if (graph.links.some((l) => l.to.node === n.id && l.to.port === s.f)) continue; // wired knob is decided upstream
261
+ const cur = n.fields[s.f];
262
+ out.push({
263
+ key: `${n.id}.${s.f}`, nodeId: n.id, field: s.f, kind: s.kind, label: s.label,
264
+ def: cur != null && String(cur) !== "" ? cur : s.def,
265
+ ...(s.options ? { options: [...s.options] } : {}),
266
+ title: displayName(n),
267
+ });
268
+ }
269
+ if (n.type === "image" && n.fields && n.fields.model === "custom-civitai") {
270
+ out.push({ key: `${n.id}.customCivitaiAir`, nodeId: n.id, field: "customCivitaiAir", kind: "text", label: "CivitAI model", def: n.fields.customCivitaiAir || "", title: displayName(n) });
271
+ }
272
+ }
273
+ return out;
274
+ }
275
+
276
+ /**
277
+ * Resolve a settings key: "nodeId.field" → "customName.field" / "Title.field" → bare field/label if unique.
278
+ * Refuses wired fields with a clear error.
279
+ */
280
+ export function resolveSettingKey(graph, settings, userKey) {
281
+ const norm = String(userKey).trim().toLowerCase();
282
+ const exact = settings.find((s) => s.key.toLowerCase() === norm);
283
+ if (exact) return exact;
284
+
285
+ const dot = norm.lastIndexOf(".");
286
+ if (dot > 0) {
287
+ const head = norm.slice(0, dot), field = norm.slice(dot + 1);
288
+ const nodes = graph.nodes.filter((n) =>
289
+ n.id.toLowerCase() === head ||
290
+ (n.name || "").trim().toLowerCase() === head ||
291
+ displayName(n).toLowerCase() === head);
292
+ const cand = settings.filter((s) => nodes.some((n) => n.id === s.nodeId) && s.field.toLowerCase() === field);
293
+ if (cand.length === 1) return cand[0];
294
+ if (cand.length > 1) {
295
+ throw new NanoodleError(`setting "${userKey}" is ambiguous — matches ${cand.map((c) => c.key).join(", ")}`);
296
+ }
297
+ for (const n of nodes) {
298
+ if (graph.links.some((l) => l.to.node === n.id && l.to.port.toLowerCase() === field)) {
299
+ throw new NanoodleError(`setting "${userKey}": that field is wired from another node and can't be overridden`);
300
+ }
301
+ }
302
+ }
303
+
304
+ const byField = settings.filter((s) => s.field.toLowerCase() === norm || s.label.toLowerCase() === norm);
305
+ if (byField.length === 1) return byField[0];
306
+ if (byField.length > 1) {
307
+ throw new NanoodleError(`setting "${userKey}" is ambiguous — matches ${byField.map((c) => c.key).join(", ")}`);
308
+ }
309
+
310
+ const avail = settings.map((s) => s.key).join(", ") || "(none)";
311
+ throw new NanoodleError(`unknown setting "${userKey}" — available settings: ${avail}`);
312
+ }
package/src/media.mjs ADDED
@@ -0,0 +1,157 @@
1
+ import { readFile, writeFile } from "node:fs/promises";
2
+ import { extname } from "node:path";
3
+ import { NanoodleError } from "./errors.mjs";
4
+
5
+ /** NanoGPT's edge rejects request bodies over ~4.5 MB; media rides inline as base64 (no upload endpoint). */
6
+ export const MEDIA_INLINE_MAX = 4.4 * 1024 * 1024;
7
+
8
+ /** Sniff an image's format from its base64 magic bytes (mirrors the nanoodle app runtime). */
9
+ export function b64ImageMime(b64) {
10
+ if (b64.startsWith("/9j/")) return "image/jpeg";
11
+ if (b64.startsWith("iVBOR")) return "image/png";
12
+ if (b64.startsWith("R0lG")) return "image/gif";
13
+ if (b64.startsWith("UklG")) return "image/webp";
14
+ return "image/png";
15
+ }
16
+
17
+ const EXT_MIME = {
18
+ ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".gif": "image/gif",
19
+ ".webp": "image/webp", ".bmp": "image/bmp",
20
+ ".mp3": "audio/mpeg", ".wav": "audio/wav", ".ogg": "audio/ogg", ".opus": "audio/ogg",
21
+ ".aac": "audio/aac", ".flac": "audio/flac", ".m4a": "audio/mp4",
22
+ ".mp4": "video/mp4", ".webm": "video/webm", ".mov": "video/quicktime", ".mkv": "video/x-matroska",
23
+ ".txt": "text/plain", ".json": "application/json",
24
+ };
25
+
26
+ const MIME_EXT = {
27
+ "image/png": "png", "image/jpeg": "jpg", "image/gif": "gif", "image/webp": "webp",
28
+ "audio/mpeg": "mp3", "audio/wav": "wav", "audio/ogg": "ogg", "audio/aac": "aac",
29
+ "audio/flac": "flac", "audio/mp4": "m4a",
30
+ "video/mp4": "mp4", "video/webm": "webm", "video/quicktime": "mov",
31
+ "text/plain": "txt", "application/json": "json",
32
+ };
33
+
34
+ /** Best-effort file extension for a MIME type (used by the CLI --out saver). */
35
+ export function extForMime(mime) {
36
+ return MIME_EXT[String(mime || "").split(";")[0].trim().toLowerCase()] || "bin";
37
+ }
38
+
39
+ /** Sniff a MIME type from magic bytes of common media containers. */
40
+ export function sniffMime(bytes) {
41
+ const b = bytes;
42
+ const ascii = (off, s) => {
43
+ for (let i = 0; i < s.length; i++) if (b[off + i] !== s.charCodeAt(i)) return false;
44
+ return true;
45
+ };
46
+ if (b.length >= 8 && b[0] === 0x89 && ascii(1, "PNG")) return "image/png";
47
+ if (b.length >= 3 && b[0] === 0xff && b[1] === 0xd8) return "image/jpeg";
48
+ if (ascii(0, "GIF8")) return "image/gif";
49
+ if (ascii(0, "RIFF") && b.length >= 12 && ascii(8, "WEBP")) return "image/webp";
50
+ if (ascii(0, "RIFF") && b.length >= 12 && ascii(8, "WAVE")) return "audio/wav";
51
+ if (ascii(0, "ID3") || (b.length >= 2 && b[0] === 0xff && (b[1] & 0xe0) === 0xe0)) return "audio/mpeg";
52
+ if (ascii(0, "OggS")) return "audio/ogg";
53
+ if (ascii(0, "fLaC")) return "audio/flac";
54
+ if (b.length >= 12 && ascii(4, "ftyp")) return "video/mp4";
55
+ if (b.length >= 4 && b[0] === 0x1a && b[1] === 0x45 && b[2] === 0xdf && b[3] === 0xa3) return "video/webm";
56
+ return "application/octet-stream";
57
+ }
58
+
59
+ /** Encode bytes as a data: URL, sniffing the MIME when not given. */
60
+ export function bytesToDataUrl(bytes, mime) {
61
+ const u8 = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
62
+ return "data:" + (mime || sniffMime(u8)) + ";base64," + Buffer.from(u8).toString("base64");
63
+ }
64
+
65
+ /** Decode a data: URL into { bytes, mime }. */
66
+ export function dataUrlBytes(url) {
67
+ const comma = url.indexOf(",");
68
+ if (!url.startsWith("data:") || comma < 0) throw new NanoodleError("not a data: URL");
69
+ const head = url.slice(5, comma);
70
+ const mime = (head.split(";")[0] || "application/octet-stream") || "application/octet-stream";
71
+ const body = url.slice(comma + 1);
72
+ const bytes = /;base64$/i.test(head) || /;base64;/i.test(head + ";")
73
+ ? new Uint8Array(Buffer.from(body, "base64"))
74
+ : new Uint8Array(Buffer.from(decodeURIComponent(body), "utf8"));
75
+ return { bytes, mime };
76
+ }
77
+
78
+ /**
79
+ * A media output value: a data: or https URL plus lazy byte access.
80
+ * String-coerces to the URL so it drops into templates / JSON naturally.
81
+ */
82
+ export class MediaRef {
83
+ /**
84
+ * @param {string} url data: or http(s) URL
85
+ * @param {{ mime?: string, fetch?: typeof fetch }} [opts]
86
+ */
87
+ constructor(url, opts = {}) {
88
+ this.url = url;
89
+ this._mime = opts.mime || null;
90
+ this._fetch = opts.fetch || globalThis.fetch;
91
+ if (!this._mime && url.startsWith("data:")) {
92
+ const head = url.slice(5, url.indexOf(","));
93
+ this._mime = head.split(";")[0] || null;
94
+ }
95
+ }
96
+
97
+ get mime() { return this._mime; }
98
+
99
+ toString() { return this.url; }
100
+ toJSON() { return this.url; }
101
+
102
+ /** @returns {Promise<Uint8Array>} the raw media bytes (decodes data:, fetches http(s)). */
103
+ async bytes() {
104
+ if (this.url.startsWith("data:")) return dataUrlBytes(this.url).bytes;
105
+ const r = await this._fetch(this.url);
106
+ if (!r.ok) throw new NanoodleError("couldn't download media (" + r.status + "): " + this.url);
107
+ if (!this._mime) {
108
+ const ct = r.headers && r.headers.get && r.headers.get("content-type");
109
+ if (ct) this._mime = ct.split(";")[0].trim();
110
+ }
111
+ return new Uint8Array(await r.arrayBuffer());
112
+ }
113
+
114
+ /** Write the media bytes to `path`; resolves to the path. */
115
+ async save(path) {
116
+ await writeFile(path, await this.bytes());
117
+ return path;
118
+ }
119
+ }
120
+
121
+ /**
122
+ * Read a local file as a media input value: `{ data, mime }`.
123
+ * MIME comes from the extension, else magic-byte sniffing.
124
+ */
125
+ export async function mediaFromFile(path, mime) {
126
+ const data = await readFile(path);
127
+ return { data: new Uint8Array(data), mime: mime || EXT_MIME[extname(path).toLowerCase()] || sniffMime(data) };
128
+ }
129
+
130
+ /**
131
+ * Coerce a user-supplied media input into a URL string (data: or http(s)).
132
+ * Accepts: data:/https URL strings, MediaRef, Uint8Array/Buffer, { data, mime }.
133
+ */
134
+ export function coerceMediaInput(value, what) {
135
+ let url;
136
+ if (value instanceof MediaRef) url = value.url;
137
+ else if (typeof value === "string") {
138
+ if (/^data:/i.test(value) || /^https?:/i.test(value)) url = value;
139
+ else {
140
+ throw new NanoodleError(
141
+ what + ": expected a data: URL, an http(s) URL, bytes, or mediaFromFile(path) — got a plain string. " +
142
+ "For a local file use mediaFromFile(\"" + value.slice(0, 60) + "\").");
143
+ }
144
+ } else if (value instanceof Uint8Array) url = bytesToDataUrl(value);
145
+ else if (value && typeof value === "object" && value.data != null) {
146
+ const data = typeof value.data === "string" ? new Uint8Array(Buffer.from(value.data, "base64")) : new Uint8Array(value.data);
147
+ url = bytesToDataUrl(data, value.mime);
148
+ } else {
149
+ throw new NanoodleError(what + ": unsupported media value (" + typeof value + ")");
150
+ }
151
+ if (url.startsWith("data:") && url.length > MEDIA_INLINE_MAX) {
152
+ throw new NanoodleError(
153
+ what + ": media is too large to send inline (~4 MB max). nanoodle sends media as base64 in the request body " +
154
+ "(NanoGPT has no upload endpoint) — use a smaller file.");
155
+ }
156
+ return url;
157
+ }