Skip to content

OpenReel Video - Professional browser-based video editor. Open source CapCut alternative. 100% browser-based, no installation, no cloud uploads, no watermarks.

TypeScript

feat(kieai): add KieAI service folder with file upload API

lvalics25e1dbdc6cb4
diff --git a/apps/web/src/services/kieai/client.ts b/apps/web/src/services/kieai/client.ts
new file mode 100644
index 00000000..68be627e
--- /dev/null
+++ b/apps/web/src/services/kieai/client.ts
@@ -0,0 +1,77 @@
+/**
+ * KieAI base client
+ *
+ * Retrieves the API key from secure-storage (encrypted IndexedDB) and
+ * provides a typed fetch wrapper used by every KieAI service module.
+ *
+ * The session must be unlocked (master password entered) before any call.
+ * API key is stored under the id "kieai-api-key".
+ */
+
+import { getSecret } from "../secure-storage";
+import { KieAIError } from "./types";
+import type { KieAIResponse } from "./types";
+
+export const KIEAI_BASE_URL = "https://kieai.redpandaai.co";
+export const KIEAI_SECRET_ID = "kieai-api-key";
+
+async function getApiKey(): Promise<string> {
+ const key = await getSecret(KIEAI_SECRET_ID);
+ if (!key) {
+ throw new KieAIError(
+ 401,
+ "KieAI API key not configured. Add it in Settings → API Keys.",
+ );
+ }
+ return key;
+}
+
+/** POST JSON — used by URL upload and Base64 upload */
+export async function kieaiPostJson<TBody extends object, TData>(
+ path: string,
+ body: TBody,
+): Promise<TData> {
+ const apiKey = await getApiKey();
+
+ const res = await fetch(`${KIEAI_BASE_URL}${path}`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${apiKey}`,
+ },
+ body: JSON.stringify(body),
+ });
+
+ const json = (await res.json()) as KieAIResponse<TData>;
+
+ if (!json.success) {
+ throw new KieAIError(json.code, json.msg);
+ }
+
+ return json.data;
+}
+
+/** POST multipart/form-data — used by stream upload */
+export async function kieaiPostForm<TData>(
+ path: string,
+ form: FormData,
+): Promise<TData> {
+ const apiKey = await getApiKey();
+
+ const res = await fetch(`${KIEAI_BASE_URL}${path}`, {
+ method: "POST",
+ headers: {
+ // Do NOT set Content-Type here — browser sets it with the correct boundary
+ Authorization: `Bearer ${apiKey}`,
+ },
+ body: form,
+ });
+
+ const json = (await res.json()) as KieAIResponse<TData>;
+
+ if (!json.success) {
+ throw new KieAIError(json.code, json.msg);
+ }
+
+ return json.data;
+}
diff --git a/apps/web/src/services/kieai/file-upload.ts b/apps/web/src/services/kieai/file-upload.ts
new file mode 100644
index 00000000..f35722f6
--- /dev/null
+++ b/apps/web/src/services/kieai/file-upload.ts
@@ -0,0 +1,124 @@
+/**
+ * KieAI File Upload API
+ *
+ * Three upload strategies, each suited to different use-cases:
+ *
+ * uploadFileByUrl — remote URL → KieAI storage (≤100 MB, 30 s timeout)
+ * uploadFileStream — local File/Blob binary stream (best for >10 MB)
+ * uploadFileBase64 — base64-encoded string (≤10 MB, JSON-friendly)
+ *
+ * All methods return an `UploadedFile` describing the stored file.
+ * Files are temporary: KieAI auto-deletes them after 3 days.
+ *
+ * Docs: https://docs.kie.ai/file-upload-api/quickstart
+ */
+
+import { kieaiPostJson, kieaiPostForm } from "./client";
+import type {
+ UploadedFile,
+ UrlUploadOptions,
+ UploadOptions,
+ Base64UploadOptions,
+} from "./types";
+
+const UPLOAD_URL_PATH = "/api/file-url-upload";
+const UPLOAD_STREAM_PATH = "/api/file-stream-upload";
+const UPLOAD_BASE64_PATH = "/api/file-base64-upload";
+
+/**
+ * Upload a file from a publicly accessible URL.
+ *
+ * KieAI downloads the remote file and stores it on its servers.
+ * Suitable for remote assets already on the internet.
+ *
+ * @param options.fileUrl - Publicly accessible URL of the file (required)
+ * @param options.uploadPath - Server-side directory (optional)
+ * @param options.fileName - Custom server filename (optional, overwrites existing)
+ *
+ * @example
+ * const file = await uploadFileByUrl({
+ * fileUrl: "https://example.com/photo.jpg",
+ * });
+ * console.log(file.fileUrl); // KieAI-hosted URL
+ */
+export async function uploadFileByUrl(
+ options: UrlUploadOptions,
+): Promise<UploadedFile> {
+ return kieaiPostJson<UrlUploadOptions, UploadedFile>(
+ UPLOAD_URL_PATH,
+ options,
+ );
+}
+
+/**
+ * Upload a local File or Blob as a binary stream (multipart/form-data).
+ *
+ * Most efficient for large files (>10 MB). No base64 overhead.
+ *
+ * @param file - The File or Blob to upload
+ * @param options - Optional uploadPath / fileName
+ *
+ * @example
+ * const input = document.querySelector('input[type="file"]');
+ * const file = await uploadFileStream(input.files[0]);
+ * console.log(file.downloadUrl);
+ */
+export async function uploadFileStream(
+ file: File | Blob,
+ options: UploadOptions = {},
+): Promise<UploadedFile> {
+ const form = new FormData();
+ form.append("file", file);
+ if (options.uploadPath) form.append("uploadPath", options.uploadPath);
+ if (options.fileName) form.append("fileName", options.fileName);
+
+ return kieaiPostForm<UploadedFile>(UPLOAD_STREAM_PATH, form);
+}
+
+/**
+ * Upload a file as a base64-encoded string.
+ *
+ * Convenient when the file is already in base64 form (e.g. canvas export).
+ * Keep files under 10 MB — base64 expands size by ~33%.
+ *
+ * The `base64Data` string must include the MIME type prefix:
+ * `data:image/jpeg;base64,<data>`
+ *
+ * @param options.base64Data - Base64 string with MIME prefix (required)
+ * @param options.uploadPath - Server-side directory (optional)
+ * @param options.fileName - Custom server filename (optional)
+ *
+ * @example
+ * const canvas = document.querySelector("canvas");
+ * const base64Data = canvas.toDataURL("image/png");
+ * const file = await uploadFileBase64({ base64Data, fileName: "frame.png" });
+ */
+export async function uploadFileBase64(
+ options: Base64UploadOptions,
+): Promise<UploadedFile> {
+ return kieaiPostJson<Base64UploadOptions, UploadedFile>(
+ UPLOAD_BASE64_PATH,
+ options,
+ );
+}
+
+/**
+ * Convenience: choose the best upload strategy automatically.
+ *
+ * - Blob/File with size > 10 MB → stream upload
+ * - Blob/File with size ≤ 10 MB → stream upload (still most efficient)
+ * - string starting with "data:" → base64 upload
+ * - string starting with "http" → URL upload
+ */
+export async function uploadFile(
+ source: File | Blob | string,
+ options: UploadOptions = {},
+): Promise<UploadedFile> {
+ if (typeof source === "string") {
+ if (source.startsWith("data:")) {
+ return uploadFileBase64({ ...options, base64Data: source });
+ }
+ return uploadFileByUrl({ ...options, fileUrl: source });
+ }
+ return uploadFileStream(source, options);
+}
diff --git a/apps/web/src/services/kieai/index.ts b/apps/web/src/services/kieai/index.ts
new file mode 100644
index 00000000..71505b20
--- /dev/null
+++ b/apps/web/src/services/kieai/index.ts
@@ -0,0 +1,29 @@
+/**
+ * KieAI service — public API
+ *
+ * Usage:
+ * import { uploadFile, uploadFileStream, KieAIError } from "@/services/kieai";
+ *
+ * Requires the KieAI API key to be stored in secure-storage under the id
+ * "kieai-api-key" and the session to be unlocked.
+ */
+
+export { KIEAI_BASE_URL, KIEAI_SECRET_ID } from "./client";
+
+export type {
+ KieAIResponse,
+ UploadedFile,
+ FileUploadResponse,
+ UploadOptions,
+ UrlUploadOptions,
+ Base64UploadOptions,
+} from "./types";
+
+export { KieAIError } from "./types";
+
+export {
+ uploadFile,
+ uploadFileByUrl,
+ uploadFileStream,
+ uploadFileBase64,
+} from "./file-upload";
diff --git a/apps/web/src/services/kieai/types.ts b/apps/web/src/services/kieai/types.ts
new file mode 100644
index 00000000..9d430ff3
--- /dev/null
+++ b/apps/web/src/services/kieai/types.ts
@@ -0,0 +1,71 @@
+/**
+ * KieAI API — shared types
+ * Base URL: https://kieai.redpandaai.co
+ */
+
+// ─── Common response wrapper ────────────────────────────────────────────────
+
+export interface KieAIResponse<T> {
+ readonly success: boolean;
+ readonly code: number;
+ readonly msg: string;
+ readonly data: T;
+}
+
+// ─── File upload ─────────────────────────────────────────────────────────────
+
+export interface UploadedFile {
+ readonly fileId: string;
+ readonly fileName: string;
+ readonly originalName: string;
+ readonly fileSize: number;
+ readonly mimeType: string;
+ readonly uploadPath: string;
+ readonly fileUrl: string;
+ readonly downloadUrl: string;
+ readonly uploadTime: string; // ISO 8601
+ readonly expiresAt: string; // ISO 8601 — files auto-deleted after 3 days
+}
+
+export type FileUploadResponse = KieAIResponse<UploadedFile>;
+
+/** Shared optional parameters for all upload methods */
+export interface UploadOptions {
+ /** Server-side directory to place the file in (optional) */
+ uploadPath?: string;
+ /**
+ * Custom filename on the server. Omit to auto-generate.
+ * Warning: overwrites any existing file with the same name.
+ */
+ fileName?: string;
+}
+
+/** Options for URL-based upload */
+export interface UrlUploadOptions extends UploadOptions {
+ /** Publicly accessible URL of the file to download and store */
+ fileUrl: string;
+}
+
+/** Options for Base64 upload */
+export interface Base64UploadOptions extends UploadOptions {
+ /**
+ * Base64-encoded file content.
+ * Must include MIME type prefix, e.g. `data:image/jpeg;base64,<data>`
+ * Recommended max size: 10 MB (expands ~33% in transit).
+ */
+ base64Data: string;
+}
+
+// ─── Error ───────────────────────────────────────────────────────────────────
+
+export class KieAIError extends Error {
+ readonly code: number;
+ readonly msg: string;
+
+ constructor(code: number, msg: string) {
+ super(`KieAI error ${code}: ${msg}`);
+ this.name = "KieAIError";
+ this.code = code;
+ this.msg = msg;
+ }
+}