@ntropix/file-service 0.0.0-stage → 1.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/dist/index.js ADDED
@@ -0,0 +1,461 @@
1
+ /**
2
+ * SDK de servidor del File Service de ntropix.
3
+ *
4
+ * Se usa SOLO en el backend del proyecto: la API key nunca debe llegar al navegador. El navegador
5
+ * recibe únicamente las instrucciones de subida (URLs firmadas) — ver `@ntropix/file-service/browser`.
6
+ */
7
+ import { createHmac, timingSafeEqual } from "node:crypto";
8
+ import { toFileInfo, toUploadInstructions, } from "./types.js";
9
+ /** Error devuelto por la API. `code` es estable y sirve para decidir qué hacer. */
10
+ export class FileServiceError extends Error {
11
+ status;
12
+ code;
13
+ requestId;
14
+ constructor(message,
15
+ /** Status HTTP (0 si no hubo respuesta). */
16
+ status,
17
+ /**
18
+ * `unauthorized` · `forbidden` · `project_disabled` · `not_found` · `validation` ·
19
+ * `invalid_state` · `no_bytes` · `too_large` · `type_not_allowed` · `quota_exceeded` ·
20
+ * `storage_full` · `rate_limited` · `internal` · `network` · `timeout`
21
+ */
22
+ code,
23
+ /**
24
+ * `X-Request-ID` de la respuesta: incluilo al reportar un problema. `undefined` si no hubo
25
+ * respuesta del File Service (`network`, `timeout`).
26
+ */
27
+ requestId) {
28
+ super(message);
29
+ this.status = status;
30
+ this.code = code;
31
+ this.requestId = requestId;
32
+ this.name = "FileServiceError";
33
+ }
34
+ }
35
+ /** El archivo se subió pero el servicio lo rechazó al verificarlo (FAILED o QUARANTINED). */
36
+ export class FileRejectedError extends FileServiceError {
37
+ file;
38
+ constructor(file) {
39
+ super(file.status === "QUARANTINED"
40
+ ? `el archivo quedó en cuarentena: su tipo real (${file.mimeType}) no está permitido`
41
+ : "el archivo no pasó la verificación (corrupto o incompleto)", 422, file.status === "QUARANTINED" ? "quarantined" : "failed");
42
+ this.file = file;
43
+ this.name = "FileRejectedError";
44
+ }
45
+ }
46
+ /** La firma del webhook no es válida, o el evento es demasiado viejo. */
47
+ export class WebhookSignatureError extends Error {
48
+ constructor(message) {
49
+ super(message);
50
+ this.name = "WebhookSignatureError";
51
+ }
52
+ }
53
+ /**
54
+ * Endpoint de subida listo para frameworks con Request/Response estándar: Next.js (App Router),
55
+ * Hono, Remix, SvelteKit, Bun, Deno.
56
+ *
57
+ * // app/api/files/route.ts
58
+ * export const { POST } = createUploadRoute(fs, { auth: async () => (await getSession())?.user.id });
59
+ */
60
+ export function createUploadRoute(fs, opts) {
61
+ return {
62
+ async POST(req) {
63
+ let ownerRef;
64
+ try {
65
+ ownerRef = await opts.auth(req);
66
+ }
67
+ catch {
68
+ ownerRef = undefined;
69
+ }
70
+ if (!ownerRef)
71
+ return Response.json({ error: { code: "unauthorized", message: "no autenticado" } }, { status: 401 });
72
+ const body = await req.json().catch(() => undefined);
73
+ const { auth: _a, onComplete, ...handleOpts } = opts;
74
+ const r = await fs.handleUpload(body, { ...handleOpts, ownerRef });
75
+ if (r.file && onComplete) {
76
+ const custom = await onComplete(r.file, { ownerRef, req });
77
+ if (custom !== undefined)
78
+ return Response.json(custom, { status: 200 });
79
+ }
80
+ return Response.json(r.body, { status: r.status });
81
+ },
82
+ };
83
+ }
84
+ function uploadError(status, code, message) {
85
+ return { status, body: { error: { code, message } } };
86
+ }
87
+ function parseBody(body) {
88
+ if (typeof body === "string" || body instanceof Uint8Array) {
89
+ try {
90
+ body = JSON.parse(typeof body === "string" ? body : Buffer.from(body).toString("utf8"));
91
+ }
92
+ catch {
93
+ return undefined;
94
+ }
95
+ }
96
+ return isPlainObject(body) ? body : undefined;
97
+ }
98
+ function isPlainObject(v) {
99
+ return typeof v === "object" && v !== null && !Array.isArray(v);
100
+ }
101
+ function uploadTokenSig(apiKey, id, ownerRef, exp) {
102
+ return createHmac("sha256", apiKey).update(`fs-upload-token.v1:${id}:${ownerRef}:${exp}`).digest("hex");
103
+ }
104
+ /** @internal Exportado para los tests de vectores compartidos. */
105
+ export function verifyUploadToken(apiKey, id, ownerRef, token, nowSec = Date.now() / 1000) {
106
+ if (typeof token !== "string")
107
+ return false;
108
+ const dot = token.indexOf(".");
109
+ const exp = Number(token.slice(0, dot));
110
+ if (dot < 1 || !Number.isInteger(exp) || exp <= nowSec)
111
+ return false;
112
+ const given = Buffer.from(token.slice(dot + 1), "hex");
113
+ const expected = Buffer.from(uploadTokenSig(apiKey, id, ownerRef, exp), "hex");
114
+ return given.length === expected.length && timingSafeEqual(given, expected);
115
+ }
116
+ /** @internal Exportado para los tests de vectores compartidos. */
117
+ export function makeUploadToken(apiKey, id, ownerRef, exp) {
118
+ return `${exp}.${uploadTokenSig(apiKey, id, ownerRef, exp)}`;
119
+ }
120
+ const sleep = (ms, signal) => new Promise((resolve, reject) => {
121
+ if (signal?.aborted)
122
+ return reject(signal.reason);
123
+ const t = setTimeout(resolve, ms);
124
+ signal?.addEventListener("abort", () => (clearTimeout(t), reject(signal.reason)), { once: true });
125
+ });
126
+ export class FileService {
127
+ apiKey;
128
+ baseUrl;
129
+ timeoutMs;
130
+ retries;
131
+ fetchImpl;
132
+ constructor(opts) {
133
+ if (!opts?.apiKey)
134
+ throw new Error("FileService: falta apiKey");
135
+ if (!opts?.baseUrl)
136
+ throw new Error("FileService: falta baseUrl");
137
+ if (typeof window !== "undefined" && typeof window.document !== "undefined") {
138
+ throw new Error("FileService: este SDK es solo para servidor — la API key no debe llegar al navegador");
139
+ }
140
+ this.apiKey = opts.apiKey;
141
+ this.baseUrl = opts.baseUrl.replace(/\/+$/, "");
142
+ this.timeoutMs = opts.timeoutMs ?? 30_000;
143
+ this.retries = opts.retries ?? 2;
144
+ this.fetchImpl = opts.fetch ?? fetch;
145
+ }
146
+ /**
147
+ * Inicia una subida. Devuelve el `id` del archivo y las instrucciones que el navegador necesita
148
+ * para subir los bytes directo al storage. Después hay que llamar a `complete()`.
149
+ */
150
+ async createUpload(input, opts = {}) {
151
+ const raw = await this.request("POST", "/files", {
152
+ body: {
153
+ original_name: input.name,
154
+ mime_type: input.mimeType,
155
+ size_bytes: input.size,
156
+ owner_ref: input.ownerRef,
157
+ visibility: input.visibility,
158
+ metadata: input.metadata,
159
+ },
160
+ ...opts,
161
+ });
162
+ return { id: raw.id, status: raw.status, upload: toUploadInstructions(raw.upload) };
163
+ }
164
+ /** Subida multipart: firma las URLs de un lote de partes (hasta 100 por llamada). */
165
+ async signParts(id, partNumbers, opts = {}) {
166
+ const raw = await this.request("POST", `/files/${id}/parts`, { body: { part_numbers: partNumbers }, idempotent: true, ...opts });
167
+ return raw.urls.map((u) => ({ partNumber: u.part_number, url: u.url }));
168
+ }
169
+ /**
170
+ * Cierra la subida: el servicio comprueba que los bytes estén en el storage y encola la
171
+ * verificación. Es idempotente. Con `wait`, espera a que el archivo quede `AVAILABLE`.
172
+ */
173
+ async complete(id, opts = {}) {
174
+ const body = opts.parts?.length
175
+ ? { parts: opts.parts.map((p) => ({ part_number: p.partNumber, etag: p.etag.replace(/^"|"$/g, "") })) }
176
+ : undefined;
177
+ const file = toFileInfo(await this.request("POST", `/files/${id}/complete`, { body, idempotent: true, ...opts }));
178
+ if (!opts.wait)
179
+ return file;
180
+ return this.waitUntilAvailable(id, { signal: opts.signal, ...(opts.wait === true ? {} : opts.wait) });
181
+ }
182
+ /**
183
+ * Metadatos del archivo y, si está disponible, una URL firmada de descarga de vida corta.
184
+ * `inline: true` pide que el navegador lo muestre en vez de bajarlo (solo imágenes, video,
185
+ * audio y PDF; el resto siempre baja como adjunto).
186
+ */
187
+ async get(id, opts = {}) {
188
+ const query = opts.inline ? "?disposition=inline" : "";
189
+ return toFileInfo(await this.request("GET", `/files/${id}${query}`, { idempotent: true, ...opts }));
190
+ }
191
+ /** Atajo: la URL firmada de descarga. Lanza si el archivo no está disponible. */
192
+ async getDownloadUrl(id, opts = {}) {
193
+ const file = await this.get(id, opts);
194
+ if (!file.download) {
195
+ throw new FileServiceError(`el archivo no está disponible para descarga (estado ${file.status})`, 409, "invalid_state");
196
+ }
197
+ return file.download.url;
198
+ }
199
+ /** Espera a que el worker termine de verificar el archivo. Lanza `FileRejectedError` si lo rechaza. */
200
+ async waitUntilAvailable(id, opts = {}) {
201
+ const deadline = Date.now() + (opts.timeoutMs ?? 30_000);
202
+ let interval = opts.intervalMs ?? 500;
203
+ for (;;) {
204
+ const file = await this.get(id, { signal: opts.signal });
205
+ if (file.status === "AVAILABLE")
206
+ return file;
207
+ if (file.status === "FAILED" || file.status === "QUARANTINED")
208
+ throw new FileRejectedError(file);
209
+ if (Date.now() + interval > deadline) {
210
+ throw new FileServiceError(`el archivo sigue en ${file.status}: la verificación no terminó a tiempo (sigue en curso; consultá más tarde o usá el webhook)`, 0, "timeout");
211
+ }
212
+ await sleep(interval, opts.signal);
213
+ interval = Math.min(interval * 1.5, 3_000);
214
+ }
215
+ }
216
+ /** Lista los archivos del proyecto, del más nuevo al más viejo. No incluye URLs de descarga. */
217
+ async list(opts = {}) {
218
+ const q = new URLSearchParams();
219
+ if (opts.ownerRef)
220
+ q.set("owner_ref", opts.ownerRef);
221
+ if (opts.status)
222
+ q.set("status", opts.status);
223
+ if (opts.trashed)
224
+ q.set("trashed", "true");
225
+ if (opts.cursor)
226
+ q.set("cursor", opts.cursor);
227
+ if (opts.limit)
228
+ q.set("limit", String(opts.limit));
229
+ const qs = q.toString();
230
+ const raw = await this.request("GET", `/files${qs ? `?${qs}` : ""}`, { idempotent: true, signal: opts.signal });
231
+ return { files: raw.files.map(toFileInfo), nextCursor: raw.next_cursor || undefined };
232
+ }
233
+ /** Recorre todas las páginas de `list()`. */
234
+ async *listAll(opts = {}) {
235
+ let cursor;
236
+ do {
237
+ const page = await this.list({ ...opts, cursor });
238
+ yield* page.files;
239
+ cursor = page.nextCursor;
240
+ } while (cursor);
241
+ }
242
+ /** Cambia la visibilidad y/o el nombre. Hacer público o privado un archivo es instantáneo. */
243
+ async update(id, changes, opts = {}) {
244
+ return toFileInfo(await this.request("PATCH", `/files/${id}`, {
245
+ body: { visibility: changes.visibility, original_name: changes.name },
246
+ idempotent: true,
247
+ ...opts,
248
+ }));
249
+ }
250
+ /** Manda el archivo a la papelera. Se puede recuperar con `restore()` durante el período de retención. */
251
+ async delete(id, opts = {}) {
252
+ await this.request("DELETE", `/files/${id}`, { idempotent: true, ...opts });
253
+ }
254
+ /** Recupera un archivo de la papelera. */
255
+ async restore(id, opts = {}) {
256
+ return toFileInfo(await this.request("POST", `/files/${id}/restore`, { idempotent: true, ...opts }));
257
+ }
258
+ /**
259
+ * Sube un archivo desde el servidor (por ejemplo, uno generado por el backend) y espera a que
260
+ * quede disponible. Para archivos del usuario, preferí `createUpload()` + subida directa desde
261
+ * el navegador: así los bytes no pasan por tu backend.
262
+ */
263
+ async upload(input, opts = {}) {
264
+ const blob = input.data instanceof Blob ? input.data : new Blob([input.data]);
265
+ const { data: _omit, ...meta } = input;
266
+ const created = await this.createUpload({ ...meta, size: blob.size }, opts);
267
+ const up = created.upload;
268
+ let parts;
269
+ if (up.mode === "simple") {
270
+ await this.put(up.url, blob, up.headers, opts.signal);
271
+ }
272
+ else {
273
+ parts = [];
274
+ const numbers = Array.from({ length: up.partCount }, (_, i) => i + 1);
275
+ for (let i = 0; i < numbers.length; i += 100) {
276
+ for (const p of await this.signParts(created.id, numbers.slice(i, i + 100), opts)) {
277
+ const chunk = blob.slice((p.partNumber - 1) * up.partSize, p.partNumber * up.partSize);
278
+ const etag = await this.put(p.url, chunk, undefined, opts.signal);
279
+ parts.push({ partNumber: p.partNumber, etag });
280
+ }
281
+ }
282
+ }
283
+ return this.complete(created.id, { ...opts, parts, wait: opts.wait ?? true });
284
+ }
285
+ /**
286
+ * Verifica la firma de un webhook y devuelve el evento. Pasá el body CRUDO (texto o bytes, sin
287
+ * parsear) y el header `FS-Signature`. Lanza `WebhookSignatureError` si la firma no coincide o
288
+ * el evento tiene más de `toleranceSec` segundos (default 300): protege contra reenvíos.
289
+ */
290
+ static verifyWebhook(args) {
291
+ const { payload, signature, secret } = args;
292
+ if (!signature)
293
+ throw new WebhookSignatureError("falta el header FS-Signature");
294
+ const fields = new Map(signature.split(",").map((kv) => kv.split("=", 2)));
295
+ const t = Number(fields.get("t"));
296
+ const v1 = fields.get("v1");
297
+ if (!Number.isFinite(t) || !v1)
298
+ throw new WebhookSignatureError("FS-Signature con formato inválido");
299
+ const body = typeof payload === "string" ? Buffer.from(payload, "utf8") : Buffer.from(payload);
300
+ const expected = createHmac("sha256", secret).update(`${t}.`).update(body).digest();
301
+ const given = Buffer.from(v1, "hex");
302
+ if (given.length !== expected.length || !timingSafeEqual(given, expected)) {
303
+ throw new WebhookSignatureError("la firma del webhook no coincide");
304
+ }
305
+ if (Math.abs(Date.now() / 1000 - t) > (args.toleranceSec ?? 300)) {
306
+ throw new WebhookSignatureError("el evento es demasiado viejo");
307
+ }
308
+ const raw = JSON.parse(body.toString("utf8"));
309
+ return { id: raw.id, type: raw.type, data: { file: toFileInfo(raw.data.file) } };
310
+ }
311
+ /**
312
+ * Implementa el endpoint de subida que usa `upload()` de `@ntropix/file-service/browser`
313
+ * (protocolo en sdk/PROTOCOL.md). Tu backend autentica al usuario y le pasa su id como
314
+ * `ownerRef`; el resto (crear, firmar partes, completar y esperar la verificación) lo resuelve
315
+ * esto. Nunca lanza: los errores vuelven como `{ status, body: { error } }`.
316
+ *
317
+ * const r = await fs.handleUpload(await req.json(), { ownerRef: user.id });
318
+ * if (r.file) await guardarEnMiBase(r.file); // solo en el `complete` exitoso
319
+ * return Response.json(r.body, { status: r.status });
320
+ */
321
+ async handleUpload(body, opts) {
322
+ try {
323
+ if (!opts?.ownerRef)
324
+ return uploadError(401, "unauthorized", "falta el usuario autenticado (ownerRef)");
325
+ const b = parseBody(body);
326
+ if (!b)
327
+ return uploadError(400, "validation", "body JSON inválido");
328
+ const actor = opts.ownerRef;
329
+ switch (b.action) {
330
+ case "create": {
331
+ if (typeof b.name !== "string" || typeof b.mimeType !== "string" || typeof b.size !== "number") {
332
+ return uploadError(400, "validation", "create requiere name, mimeType y size");
333
+ }
334
+ const clientMeta = isPlainObject(b.metadata) ? b.metadata : {};
335
+ const created = await this.createUpload({
336
+ name: b.name,
337
+ mimeType: b.mimeType,
338
+ size: b.size,
339
+ ownerRef: opts.ownerRef,
340
+ visibility: opts.visibility,
341
+ metadata: { ...clientMeta, ...(opts.metadata ?? {}) },
342
+ }, { actor });
343
+ const token = this.uploadToken(created.id, opts.ownerRef);
344
+ return { status: 200, body: { id: created.id, token, upload: created.upload } };
345
+ }
346
+ case "parts": {
347
+ if (typeof b.id !== "string" || !b.id)
348
+ return uploadError(400, "validation", "falta id");
349
+ if (!this.checkUploadToken(b, opts.ownerRef))
350
+ return uploadError(403, "forbidden", "token de subida inválido o vencido");
351
+ const nums = b.partNumbers;
352
+ if (!Array.isArray(nums) || nums.length === 0 || nums.length > 100 || !nums.every(Number.isInteger)) {
353
+ return uploadError(400, "validation", "partNumbers debe ser una lista de 1 a 100 enteros");
354
+ }
355
+ return { status: 200, body: { urls: await this.signParts(b.id, nums, { actor }) } };
356
+ }
357
+ case "complete": {
358
+ if (typeof b.id !== "string" || !b.id)
359
+ return uploadError(400, "validation", "falta id");
360
+ if (!this.checkUploadToken(b, opts.ownerRef))
361
+ return uploadError(403, "forbidden", "token de subida inválido o vencido");
362
+ const parts = Array.isArray(b.parts)
363
+ ? b.parts.map((p) => ({ partNumber: Number(p?.partNumber), etag: String(p?.etag ?? "") }))
364
+ : undefined;
365
+ let file;
366
+ try {
367
+ file = await this.complete(b.id, { parts, actor, wait: { timeoutMs: opts.waitTimeoutMs ?? 30_000 } });
368
+ }
369
+ catch (err) {
370
+ // La verificación sigue en curso: se devuelve el file como está (READY).
371
+ if (err instanceof FileServiceError && err.code === "timeout" && !(err instanceof FileRejectedError)) {
372
+ file = await this.get(b.id, { actor });
373
+ }
374
+ else
375
+ throw err;
376
+ }
377
+ return { status: 200, body: file, file };
378
+ }
379
+ default:
380
+ return uploadError(400, "validation", "action desconocida: se espera create, parts o complete");
381
+ }
382
+ }
383
+ catch (err) {
384
+ if (err instanceof FileServiceError) {
385
+ // 401/403 de la API = la key del BACKEND fue rechazada: no es culpa del usuario (→ 502).
386
+ const status = err.status === 0 || err.status === 401 || err.status === 403 ? 502 : err.status;
387
+ return uploadError(status, err.code, err.message);
388
+ }
389
+ return uploadError(500, "internal", "error interno del endpoint de subida");
390
+ }
391
+ }
392
+ /** Token de subida (sdk/PROTOCOL.md): prueba sin estado de que `id` lo creó `ownerRef`. */
393
+ uploadToken(id, ownerRef, exp = Math.floor(Date.now() / 1000) + 86_400) {
394
+ return `${exp}.${uploadTokenSig(this.apiKey, id, ownerRef, exp)}`;
395
+ }
396
+ checkUploadToken(b, ownerRef) {
397
+ return typeof b.id === "string" && verifyUploadToken(this.apiKey, b.id, ownerRef, b.token);
398
+ }
399
+ // ─── Internos ──────────────────────────────────────────────────────────────
400
+ /** PUT de bytes a una URL firmada del storage. Devuelve el ETag. */
401
+ async put(url, body, headers, signal) {
402
+ let res;
403
+ try {
404
+ res = await this.fetchImpl(url, { method: "PUT", body, headers, signal });
405
+ }
406
+ catch (err) {
407
+ throw new FileServiceError(`no se pudo subir al storage: ${err.message}`, 0, "network");
408
+ }
409
+ if (!res.ok)
410
+ throw new FileServiceError(`el storage rechazó la subida (HTTP ${res.status})`, res.status, "storage_rejected");
411
+ return (res.headers.get("etag") ?? "").replace(/^"|"$/g, "");
412
+ }
413
+ async request(method, path, opts = {}) {
414
+ const headers = { Authorization: `Bearer ${this.apiKey}`, Accept: "application/json" };
415
+ if (opts.actor)
416
+ headers["FS-Actor"] = opts.actor;
417
+ const body = opts.body === undefined ? undefined : JSON.stringify(opts.body);
418
+ if (body !== undefined)
419
+ headers["Content-Type"] = "application/json";
420
+ // Solo se reintenta lo que es seguro repetir: crear un archivo dos veces dejaría uno huérfano.
421
+ const attempts = opts.idempotent ? this.retries + 1 : 1;
422
+ let lastError;
423
+ for (let attempt = 1; attempt <= attempts; attempt++) {
424
+ const timeout = AbortSignal.timeout(this.timeoutMs);
425
+ const signal = opts.signal ? AbortSignal.any([opts.signal, timeout]) : timeout;
426
+ let res;
427
+ try {
428
+ res = await this.fetchImpl(this.baseUrl + path, { method, headers, body, signal });
429
+ }
430
+ catch (err) {
431
+ if (opts.signal?.aborted)
432
+ throw err;
433
+ lastError = timeout.aborted
434
+ ? new FileServiceError(`el File Service no respondió en ${this.timeoutMs} ms`, 0, "timeout")
435
+ : new FileServiceError(`no se pudo conectar con el File Service: ${err.message}`, 0, "network");
436
+ if (attempt < attempts)
437
+ await sleep(250 * 2 ** (attempt - 1), opts.signal);
438
+ continue;
439
+ }
440
+ if (res.status === 204)
441
+ return undefined;
442
+ const text = await res.text();
443
+ let json;
444
+ try {
445
+ json = text ? JSON.parse(text) : undefined;
446
+ }
447
+ catch {
448
+ json = undefined;
449
+ }
450
+ if (res.ok)
451
+ return json;
452
+ lastError = new FileServiceError(json?.error?.message ?? `respuesta inesperada del File Service (HTTP ${res.status})`, res.status, json?.error?.code ?? "internal", res.headers.get("x-request-id") ?? undefined);
453
+ const retryable = res.status === 429 || res.status >= 500;
454
+ if (!retryable || attempt === attempts)
455
+ throw lastError;
456
+ const retryAfter = Number(res.headers.get("retry-after"));
457
+ await sleep(retryAfter > 0 ? retryAfter * 1000 : 250 * 2 ** (attempt - 1), opts.signal);
458
+ }
459
+ throw lastError;
460
+ }
461
+ }
@@ -0,0 +1,70 @@
1
+ /** Estados del ciclo de vida de un archivo. Solo `AVAILABLE` es descargable. */
2
+ export type FileStatus = "PENDING" | "UPLOADING" | "READY" | "AVAILABLE" | "FAILED" | "QUARANTINED";
3
+ export type Visibility = "private" | "public";
4
+ /** Un archivo tal como lo ve el proyecto. */
5
+ export interface FileInfo {
6
+ id: string;
7
+ /** Slug del proyecto dueño. */
8
+ project: string;
9
+ status: FileStatus;
10
+ name: string;
11
+ /** Tipo declarado al subir; una vez `AVAILABLE`, el tipo REAL detectado por el servicio. */
12
+ mimeType: string;
13
+ size: number;
14
+ /** SHA-256 del contenido (cuando ya fue verificado). */
15
+ contentHash?: string;
16
+ /** Id del usuario final en tu sistema, si lo informaste al subir. */
17
+ ownerRef?: string;
18
+ visibility: Visibility;
19
+ /** URL estable para archivos públicos y disponibles: se puede usar directo en un `<img src>`. */
20
+ publicUrl?: string;
21
+ metadata: Record<string, unknown>;
22
+ createdAt: string;
23
+ /** Presente si el archivo está en la papelera. */
24
+ deletedAt?: string;
25
+ /** URL firmada de descarga de vida corta. Solo viene en `get()` y si el archivo está disponible. */
26
+ download?: {
27
+ url: string;
28
+ expiresAt: string;
29
+ };
30
+ }
31
+ /** Instrucciones para que el navegador suba los bytes directo al storage. */
32
+ export interface UploadInstructions {
33
+ mode: "simple" | "multipart";
34
+ /** simple: URL firmada para un único PUT. */
35
+ url?: string;
36
+ /** simple: headers que el PUT debe llevar. */
37
+ headers?: Record<string, string>;
38
+ /** multipart: tamaño de cada parte (la última puede ser menor). */
39
+ partSize?: number;
40
+ /** multipart: cantidad de partes. */
41
+ partCount?: number;
42
+ expiresAt: string;
43
+ }
44
+ export interface CreatedUpload {
45
+ id: string;
46
+ status: FileStatus;
47
+ upload: UploadInstructions;
48
+ }
49
+ /** Una parte ya subida: su número y el ETag que devolvió el storage. */
50
+ export interface CompletedPart {
51
+ partNumber: number;
52
+ etag: string;
53
+ }
54
+ export interface PartUrl {
55
+ partNumber: number;
56
+ url: string;
57
+ }
58
+ export type WebhookEventType = "file.available" | "file.failed" | "file.quarantined";
59
+ /** Evento que el File Service envía al webhook del proyecto. */
60
+ export interface WebhookEvent {
61
+ /** Id único del evento: usalo para descartar duplicados (la entrega es at-least-once). */
62
+ id: string;
63
+ type: WebhookEventType;
64
+ data: {
65
+ file: FileInfo;
66
+ };
67
+ }
68
+ /** snake_case de la API → camelCase del SDK. */
69
+ export declare function toFileInfo(raw: any): FileInfo;
70
+ export declare function toUploadInstructions(raw: any): UploadInstructions;
package/dist/types.js ADDED
@@ -0,0 +1,29 @@
1
+ /** snake_case de la API → camelCase del SDK. */
2
+ export function toFileInfo(raw) {
3
+ return {
4
+ id: raw.id,
5
+ project: raw.project,
6
+ status: raw.status,
7
+ name: raw.original_name,
8
+ mimeType: raw.mime_type,
9
+ size: raw.size_bytes,
10
+ contentHash: raw.content_hash ?? undefined,
11
+ ownerRef: raw.owner_ref ?? undefined,
12
+ visibility: raw.visibility,
13
+ publicUrl: raw.public_url || undefined,
14
+ metadata: raw.metadata ?? {},
15
+ createdAt: raw.created_at,
16
+ deletedAt: raw.deleted_at ?? undefined,
17
+ download: raw.download ? { url: raw.download.url, expiresAt: raw.download.expires_at } : undefined,
18
+ };
19
+ }
20
+ export function toUploadInstructions(raw) {
21
+ return {
22
+ mode: raw.mode,
23
+ url: raw.url || undefined,
24
+ headers: raw.headers ?? undefined,
25
+ partSize: raw.part_size || undefined,
26
+ partCount: raw.part_count || undefined,
27
+ expiresAt: raw.expires_at,
28
+ };
29
+ }
package/package.json CHANGED
@@ -1,6 +1,78 @@
1
1
  {
2
2
  "name": "@ntropix/file-service",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.1.0",
4
+ "description": "SDK del File Service de ntropix: subir, consultar y servir archivos. Cliente de servidor (Node, Next.js, NestJS) y helper de navegador.",
5
+ "keywords": [
6
+ "file-upload",
7
+ "storage",
8
+ "s3",
9
+ "presigned-url",
10
+ "multipart",
11
+ "nextjs",
12
+ "nestjs",
13
+ "ntropix"
14
+ ],
15
+ "license": "MIT",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/marcanii/file-service-sdk.git",
19
+ "directory": "js"
20
+ },
21
+ "homepage": "https://github.com/marcanii/file-service-sdk/tree/main/js#readme",
22
+ "type": "module",
23
+ "sideEffects": false,
24
+ "engines": {
25
+ "node": ">=18"
26
+ },
27
+ "exports": {
28
+ ".": {
29
+ "import": {
30
+ "types": "./dist/index.d.ts",
31
+ "default": "./dist/index.js"
32
+ },
33
+ "require": {
34
+ "types": "./dist/cjs/index.d.ts",
35
+ "default": "./dist/cjs/index.js"
36
+ }
37
+ },
38
+ "./browser": {
39
+ "import": {
40
+ "types": "./dist/browser.d.ts",
41
+ "default": "./dist/browser.js"
42
+ },
43
+ "require": {
44
+ "types": "./dist/cjs/browser.d.ts",
45
+ "default": "./dist/cjs/browser.js"
46
+ }
47
+ },
48
+ "./package.json": "./package.json"
49
+ },
50
+ "main": "./dist/cjs/index.js",
51
+ "module": "./dist/index.js",
52
+ "types": "./dist/cjs/index.d.ts",
53
+ "typesVersions": {
54
+ "*": {
55
+ "browser": [
56
+ "./dist/cjs/browser.d.ts"
57
+ ]
58
+ }
59
+ },
60
+ "files": [
61
+ "dist",
62
+ "README.md"
63
+ ],
64
+ "publishConfig": {
65
+ "access": "public"
66
+ },
67
+ "scripts": {
68
+ "build": "tsc -p tsconfig.json && tsc -p tsconfig.cjs.json && node -e \"require('fs').writeFileSync('dist/cjs/package.json', JSON.stringify({ type: 'commonjs' }) + '\\n')\"",
69
+ "test": "node --test test/unit.test.mjs",
70
+ "test:e2e": "node test/e2e.mjs",
71
+ "test:browser-e2e": "node test/browser-e2e.mjs",
72
+ "prepublishOnly": "pnpm build && pnpm test"
73
+ },
74
+ "devDependencies": {
75
+ "@types/node": "^22.0.0",
76
+ "typescript": "^5.6.0"
77
+ }
78
+ }