@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/README.md +239 -2
- package/dist/browser.d.ts +77 -0
- package/dist/browser.js +131 -0
- package/dist/cjs/browser.d.ts +77 -0
- package/dist/cjs/browser.js +137 -0
- package/dist/cjs/index.d.ts +229 -0
- package/dist/cjs/index.js +471 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/types.d.ts +70 -0
- package/dist/cjs/types.js +33 -0
- package/dist/index.d.ts +229 -0
- package/dist/index.js +461 -0
- package/dist/types.d.ts +70 -0
- package/dist/types.js +29 -0
- package/package.json +76 -4
package/README.md
CHANGED
|
@@ -1,3 +1,240 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @ntropix/file-service
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
SDK del File Service de ntropix para Node (Next.js, NestJS, Express, Hono…) y el navegador. Sin
|
|
4
|
+
dependencias. Hay SDKs equivalentes para [Python](../python), [Go](../go) y [PHP](../php).
|
|
5
|
+
|
|
6
|
+
- **`@ntropix/file-service`** — cliente de servidor. Usa la API key del proyecto: va **solo** en
|
|
7
|
+
el backend.
|
|
8
|
+
- **`@ntropix/file-service/browser`** — helper de navegador. Sube los bytes directo al storage
|
|
9
|
+
(los bytes nunca pasan por tu backend). No conoce la API key.
|
|
10
|
+
|
|
11
|
+
```
|
|
12
|
+
Navegador ── upload(file, { endpoint }) ──▶ Tu backend: 1 endpoint con handleUpload() ──▶ File Service
|
|
13
|
+
└──────────── bytes directo, con URL firmada ─────────────────────────────────────▶ Storage
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## Instalación
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
npm install @ntropix/file-service # pnpm add · yarn add · bun add
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
Funciona con `import` (ESM: Next.js, Vite, Bun) y con `require` (CommonJS: NestJS por defecto),
|
|
23
|
+
en Node ≥ 18, con npm, pnpm, yarn (también Plug'n'Play) y bun. Tipos de TypeScript incluidos.
|
|
24
|
+
|
|
25
|
+
Variables de entorno del backend (la key se emite en el Panel del File Service):
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
FILE_SERVICE_URL=https://files.ntropix.dev
|
|
29
|
+
FILE_SERVICE_KEY=fsk_live_... # secreto: nunca con prefijo NEXT_PUBLIC_
|
|
30
|
+
FILE_SERVICE_WEBHOOK_SECRET=whsec_... # solo si usás webhooks
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## Integración en 2 pasos
|
|
34
|
+
|
|
35
|
+
Tu backend monta **un** endpoint de subida; el navegador llama a `upload()`. El SDK resuelve el
|
|
36
|
+
resto: subida directa al storage (simple o multipart), firma de partes, verificación y un token
|
|
37
|
+
que impide que un usuario complete subidas de otro.
|
|
38
|
+
|
|
39
|
+
### 1. Backend: un endpoint
|
|
40
|
+
|
|
41
|
+
**Next.js (App Router)**
|
|
42
|
+
|
|
43
|
+
```ts
|
|
44
|
+
// lib/files.ts
|
|
45
|
+
import "server-only";
|
|
46
|
+
import { FileService } from "@ntropix/file-service";
|
|
47
|
+
export const fs = new FileService({ apiKey: process.env.FILE_SERVICE_KEY!, baseUrl: process.env.FILE_SERVICE_URL! });
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
```ts
|
|
51
|
+
// app/api/files/route.ts
|
|
52
|
+
import { createUploadRoute } from "@ntropix/file-service";
|
|
53
|
+
import { fs } from "@/lib/files";
|
|
54
|
+
|
|
55
|
+
export const { POST } = createUploadRoute(fs, {
|
|
56
|
+
auth: async () => (await getSession())?.user.id, // TU autenticación; null → 401
|
|
57
|
+
onComplete: (file, { ownerRef }) => db.documents.create({ ownerRef, fileId: file.id }), // opcional
|
|
58
|
+
});
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
`createUploadRoute` sirve igual para Hono, Remix, SvelteKit, Bun y Deno (todo lo que use
|
|
62
|
+
`Request`/`Response` estándar).
|
|
63
|
+
|
|
64
|
+
**NestJS**
|
|
65
|
+
|
|
66
|
+
```ts
|
|
67
|
+
// files.controller.ts
|
|
68
|
+
import { Body, Controller, Post, Req, Res, UseGuards } from "@nestjs/common";
|
|
69
|
+
import { FileService } from "@ntropix/file-service";
|
|
70
|
+
|
|
71
|
+
const fs = new FileService({ apiKey: process.env.FILE_SERVICE_KEY!, baseUrl: process.env.FILE_SERVICE_URL! });
|
|
72
|
+
|
|
73
|
+
@Controller("api/files")
|
|
74
|
+
export class FilesController {
|
|
75
|
+
@Post()
|
|
76
|
+
@UseGuards(AuthGuard) // TU guard
|
|
77
|
+
async upload(@Body() body: unknown, @Req() req, @Res() res) {
|
|
78
|
+
const r = await fs.handleUpload(body, { ownerRef: req.user.id });
|
|
79
|
+
if (r.file) await this.documents.save({ ownerRef: req.user.id, fileId: r.file.id }); // opcional
|
|
80
|
+
res.status(r.status).json(r.body);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
**Express** (o cualquier otro framework): es lo mismo, `handleUpload(body, { ownerRef })` devuelve
|
|
86
|
+
`{ status, body, file? }` listo para responder.
|
|
87
|
+
|
|
88
|
+
```ts
|
|
89
|
+
app.post("/api/files", requireUser, async (req, res) => {
|
|
90
|
+
const r = await fs.handleUpload(req.body, { ownerRef: req.user.id });
|
|
91
|
+
res.status(r.status).json(r.body);
|
|
92
|
+
});
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
Opciones de `handleUpload` / `createUploadRoute`: `visibility` (la fija el backend, default
|
|
96
|
+
`private`), `metadata` (pisa la del navegador), `waitTimeoutMs` (espera de verificación, default 30 s).
|
|
97
|
+
|
|
98
|
+
### 2. Navegador: `upload()`
|
|
99
|
+
|
|
100
|
+
```tsx
|
|
101
|
+
"use client";
|
|
102
|
+
import { upload, UploadError } from "@ntropix/file-service/browser";
|
|
103
|
+
|
|
104
|
+
const file = await upload(input.files[0], {
|
|
105
|
+
endpoint: "/api/files",
|
|
106
|
+
onProgress: (p) => setPercent(p.percent),
|
|
107
|
+
});
|
|
108
|
+
// file.status === "AVAILABLE" → ya verificado (hash + tipo real). file.id es lo que guardás.
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
Si tu framework exige CSRF (Django, Laravel con rutas `web`), mandá el token con `headers`:
|
|
112
|
+
`upload(file, { endpoint, headers: { "X-CSRF-TOKEN": token } })`.
|
|
113
|
+
|
|
114
|
+
Errores: `UploadError` con `status` y `code` (`too_large`, `type_not_allowed`, `quota_exceeded`,
|
|
115
|
+
`quarantined`, `unauthorized`…). Sin bundler (ej. un backend PHP o Python con HTML plano):
|
|
116
|
+
|
|
117
|
+
```html
|
|
118
|
+
<script type="module">
|
|
119
|
+
import { upload } from "https://cdn.jsdelivr.net/npm/@ntropix/file-service@1/dist/browser.js";
|
|
120
|
+
const file = await upload(document.querySelector("input[type=file]").files[0], { endpoint: "/api/files" });
|
|
121
|
+
</script>
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
El endpoint habla el [protocolo de subida](../PROTOCOL.md), que es el mismo en los SDKs de Python,
|
|
125
|
+
Go y PHP: este helper funciona con cualquiera de esos backends.
|
|
126
|
+
|
|
127
|
+
### 3. Mostrar y descargar
|
|
128
|
+
|
|
129
|
+
```ts
|
|
130
|
+
// Privado (default): URL firmada de vida corta, pedida en el momento.
|
|
131
|
+
const url = await fs.getDownloadUrl(fileId, { actor: user.id }); // baja como adjunto
|
|
132
|
+
const preview = await fs.getDownloadUrl(fileId, { inline: true }); // se muestra en el navegador
|
|
133
|
+
|
|
134
|
+
// Público: URL estable, se guarda y se usa directo en <img src>.
|
|
135
|
+
const { publicUrl } = await fs.update(fileId, { visibility: "public" });
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
"Público" significa accesible para cualquiera que tenga el link. Para lo sensible, dejalo privado.
|
|
139
|
+
|
|
140
|
+
### Control fino (opcional)
|
|
141
|
+
|
|
142
|
+
Si necesitás manejar cada paso a mano, el cliente expone las operaciones de bajo nivel:
|
|
143
|
+
`createUpload` → (navegador: `uploadFile(file, upload, { signParts })`) → `signParts` → `complete`.
|
|
144
|
+
Ver la referencia abajo.
|
|
145
|
+
|
|
146
|
+
## Referencia
|
|
147
|
+
|
|
148
|
+
| Método | Qué hace |
|
|
149
|
+
|---|---|
|
|
150
|
+
| `fs.handleUpload(body, { ownerRef })` | Endpoint de subida completo → `{ status, body, file? }` |
|
|
151
|
+
| `createUploadRoute(fs, { auth, onComplete? })` | Lo mismo como `{ POST }` para Next.js / Request estándar |
|
|
152
|
+
| `fs.createUpload(input, opts?)` | Inicia una subida → `{ id, status, upload }` |
|
|
153
|
+
| `fs.signParts(id, partNumbers)` | Firma URLs de partes (multipart, hasta 100 por llamada) |
|
|
154
|
+
| `fs.complete(id, { parts?, wait? })` | Cierra la subida. Idempotente. Con `wait` espera a `AVAILABLE` |
|
|
155
|
+
| `fs.waitUntilAvailable(id, opts?)` | Espera la verificación; lanza `FileRejectedError` si se rechaza |
|
|
156
|
+
| `fs.get(id, { inline? })` | Metadatos + URL firmada de descarga (si está disponible) |
|
|
157
|
+
| `fs.getDownloadUrl(id, { inline? })` | Atajo: solo la URL firmada |
|
|
158
|
+
| `fs.list({ ownerRef?, status?, trashed?, cursor?, limit? })` | Una página → `{ files, nextCursor }` |
|
|
159
|
+
| `fs.listAll(opts?)` | Iterador asíncrono sobre todas las páginas |
|
|
160
|
+
| `fs.update(id, { visibility?, name? })` | Cambia visibilidad y/o nombre |
|
|
161
|
+
| `fs.delete(id)` | Manda a la papelera (recuperable) |
|
|
162
|
+
| `fs.restore(id)` | Recupera de la papelera |
|
|
163
|
+
| `fs.upload({ ...input, data })` | Sube desde el servidor en una llamada (ej. un PDF generado) |
|
|
164
|
+
| `FileService.verifyWebhook({ payload, signature, secret })` | Verifica la firma y devuelve el evento |
|
|
165
|
+
|
|
166
|
+
Todas las operaciones aceptan `{ actor, signal }`. `actor` es el id del usuario final que originó
|
|
167
|
+
la acción: solo queda en la auditoría del File Service.
|
|
168
|
+
|
|
169
|
+
### Estados
|
|
170
|
+
|
|
171
|
+
`PENDING` → `UPLOADING` (multipart) → `READY` (bytes confirmados, en verificación) → **`AVAILABLE`**
|
|
172
|
+
(descargable). Si la verificación lo rechaza: `FAILED` (corrupto) o `QUARANTINED` (el tipo real del
|
|
173
|
+
contenido no está permitido, sin importar la extensión o el tipo declarado).
|
|
174
|
+
|
|
175
|
+
### Errores
|
|
176
|
+
|
|
177
|
+
Todo error de la API es un `FileServiceError` con `status` (HTTP) y `code` estable:
|
|
178
|
+
|
|
179
|
+
| `code` | HTTP | Significado |
|
|
180
|
+
|---|---|---|
|
|
181
|
+
| `unauthorized` | 401 | API key inválida, vencida o revocada |
|
|
182
|
+
| `forbidden` | 403 | La key es de solo lectura |
|
|
183
|
+
| `project_disabled` | 403 | El proyecto fue desactivado |
|
|
184
|
+
| `not_found` | 404 | No existe (o es de otro proyecto) |
|
|
185
|
+
| `validation` | 400 | Datos inválidos |
|
|
186
|
+
| `invalid_state` / `no_bytes` | 409 | El estado no permite la operación / no se subieron los bytes |
|
|
187
|
+
| `too_large` | 413 | Supera el tamaño máximo del proyecto |
|
|
188
|
+
| `type_not_allowed` | 415 | El tipo no está en la lista permitida del proyecto |
|
|
189
|
+
| `quota_exceeded` / `storage_full` | 507 | Cuota del proyecto agotada / el servicio no tiene espacio |
|
|
190
|
+
| `rate_limited` | 429 | Demasiadas solicitudes (el SDK reintenta solo) |
|
|
191
|
+
| `network` / `timeout` | 0 | No se pudo conectar / no respondió a tiempo |
|
|
192
|
+
|
|
193
|
+
El SDK reintenta automáticamente (con backoff) errores de red, `429` y `5xx` en las operaciones que
|
|
194
|
+
son seguras de repetir. `createUpload` no se reintenta.
|
|
195
|
+
|
|
196
|
+
`err.requestId` trae el `X-Request-ID` de la respuesta (`undefined` en `network` / `timeout`):
|
|
197
|
+
logueálo e incluilo al reportar un problema, así se encuentra el request en los logs del servicio.
|
|
198
|
+
|
|
199
|
+
## Webhooks
|
|
200
|
+
|
|
201
|
+
En vez de (o además de) esperar con `wait`, el File Service puede avisarte cuando un archivo
|
|
202
|
+
termina de verificarse. Se configura en el Panel (URL + secret). Eventos: `file.available`,
|
|
203
|
+
`file.failed`, `file.quarantined`.
|
|
204
|
+
|
|
205
|
+
```ts
|
|
206
|
+
// app/api/webhooks/files/route.ts
|
|
207
|
+
import { FileService, WebhookSignatureError } from "@ntropix/file-service";
|
|
208
|
+
|
|
209
|
+
export async function POST(req: Request) {
|
|
210
|
+
const payload = await req.text(); // el body CRUDO: no usar req.json()
|
|
211
|
+
try {
|
|
212
|
+
const event = FileService.verifyWebhook({
|
|
213
|
+
payload,
|
|
214
|
+
signature: req.headers.get("fs-signature"),
|
|
215
|
+
secret: process.env.FILE_SERVICE_WEBHOOK_SECRET!,
|
|
216
|
+
});
|
|
217
|
+
// La entrega es at-least-once: descartá duplicados por event.id.
|
|
218
|
+
if (event.type === "file.available") await marcarListo(event.data.file.id);
|
|
219
|
+
else await marcarRechazado(event.data.file.id, event.type);
|
|
220
|
+
return new Response(null, { status: 204 });
|
|
221
|
+
} catch (err) {
|
|
222
|
+
if (err instanceof WebhookSignatureError) return new Response("firma inválida", { status: 400 });
|
|
223
|
+
throw err;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
Respondé `2xx` rápido; cualquier otra respuesta se reintenta con backoff durante ~24 horas.
|
|
229
|
+
|
|
230
|
+
## Desarrollo del SDK
|
|
231
|
+
|
|
232
|
+
`dist/` va versionado: después de tocar `src/`, correr `pnpm build` y commitear también `dist/`.
|
|
233
|
+
`npm publish` compila y corre los tests antes de publicar (`prepublishOnly`).
|
|
234
|
+
|
|
235
|
+
```bash
|
|
236
|
+
pnpm install && pnpm build
|
|
237
|
+
pnpm test # tests unitarios (sin red) + vectores compartidos (../testdata)
|
|
238
|
+
FS_KEY=fsk_test_... pnpm test:e2e # contra un File Service levantado (default http://localhost:8080)
|
|
239
|
+
FS_KEY=fsk_test_... pnpm test:browser-e2e # upload() del navegador contra createUploadRoute
|
|
240
|
+
```
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Helper de navegador. Lo normal es `upload(file, { endpoint })` contra el endpoint de tu backend
|
|
3
|
+
* (`handleUpload` / `createUploadRoute`). `uploadFile` es el paso de bajo nivel: sube con las instrucciones que tu backend
|
|
4
|
+
* obtuvo de `fs.createUpload()`. No usa ni conoce la API key.
|
|
5
|
+
*
|
|
6
|
+
* const { id, upload } = await fetch("/api/files", { method: "POST", body: ... }).then(r => r.json());
|
|
7
|
+
* const { parts } = await uploadFile(file, upload, { onProgress: (p) => setProgress(p.percent) });
|
|
8
|
+
* await fetch(`/api/files/${id}/complete`, { method: "POST", body: JSON.stringify({ parts }) });
|
|
9
|
+
*/
|
|
10
|
+
import type { CompletedPart, PartUrl, UploadInstructions } from "./types.js";
|
|
11
|
+
export type { CompletedPart, PartUrl, UploadInstructions } from "./types.js";
|
|
12
|
+
export interface UploadProgress {
|
|
13
|
+
loaded: number;
|
|
14
|
+
total: number;
|
|
15
|
+
/** 0 a 100. */
|
|
16
|
+
percent: number;
|
|
17
|
+
}
|
|
18
|
+
export interface UploadFileOptions {
|
|
19
|
+
onProgress?: (progress: UploadProgress) => void;
|
|
20
|
+
signal?: AbortSignal;
|
|
21
|
+
/**
|
|
22
|
+
* Requerido en subidas multipart: pide a TU backend las URLs firmadas de un lote de partes
|
|
23
|
+
* (el backend las obtiene con `fs.signParts(id, partNumbers)`).
|
|
24
|
+
*/
|
|
25
|
+
signParts?: (partNumbers: number[]) => Promise<PartUrl[]>;
|
|
26
|
+
/** Partes subidas en paralelo en multipart (default 3). */
|
|
27
|
+
concurrency?: number;
|
|
28
|
+
/** Reintentos por parte ante fallas de red (default 3). */
|
|
29
|
+
retries?: number;
|
|
30
|
+
}
|
|
31
|
+
export declare class UploadError extends Error {
|
|
32
|
+
readonly status: number;
|
|
33
|
+
/** `code` estable del error (too_large, type_not_allowed, quarantined…), si el endpoint lo informó. */
|
|
34
|
+
readonly code?: string | undefined;
|
|
35
|
+
constructor(message: string, status: number,
|
|
36
|
+
/** `code` estable del error (too_large, type_not_allowed, quarantined…), si el endpoint lo informó. */
|
|
37
|
+
code?: string | undefined);
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Sube `file` al storage. En multipart devuelve las partes con sus ETags: hay que enviarlas al
|
|
41
|
+
* backend para que llame a `fs.complete(id, { parts })`. En subida simple `parts` viene vacío.
|
|
42
|
+
*/
|
|
43
|
+
export declare function uploadFile(file: Blob, upload: UploadInstructions, opts?: UploadFileOptions): Promise<{
|
|
44
|
+
parts: CompletedPart[];
|
|
45
|
+
}>;
|
|
46
|
+
export interface UploadOptions extends Omit<UploadFileOptions, "signParts"> {
|
|
47
|
+
/** URL del endpoint de subida de TU backend (el que usa `handleUpload` / `createUploadRoute`). */
|
|
48
|
+
endpoint: string;
|
|
49
|
+
/** Headers extra para tu endpoint (ej. `Authorization` si tu app no usa cookies). */
|
|
50
|
+
headers?: Record<string, string>;
|
|
51
|
+
/** Metadata del cliente (tu backend puede pisarla). */
|
|
52
|
+
metadata?: Record<string, unknown>;
|
|
53
|
+
/** Nombre a usar en vez de `file.name`. */
|
|
54
|
+
name?: string;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Sube un archivo de punta a punta contra tu endpoint de subida (sdk/PROTOCOL.md) y devuelve el
|
|
58
|
+
* archivo ya verificado. Funciona con cualquier backend que use el SDK del File Service (Node,
|
|
59
|
+
* Python, Go, PHP).
|
|
60
|
+
*
|
|
61
|
+
* const file = await upload(input.files[0], { endpoint: "/api/files", onProgress: (p) => setPct(p.percent) });
|
|
62
|
+
*/
|
|
63
|
+
export declare function upload(file: File | Blob, opts: UploadOptions): Promise<UploadedFile>;
|
|
64
|
+
/** El archivo tal como lo devuelve el endpoint de subida (`FileInfo` del SDK). */
|
|
65
|
+
export interface UploadedFile {
|
|
66
|
+
id: string;
|
|
67
|
+
status: string;
|
|
68
|
+
name: string;
|
|
69
|
+
mimeType: string;
|
|
70
|
+
size: number;
|
|
71
|
+
visibility: "private" | "public";
|
|
72
|
+
publicUrl?: string;
|
|
73
|
+
ownerRef?: string;
|
|
74
|
+
metadata: Record<string, unknown>;
|
|
75
|
+
createdAt: string;
|
|
76
|
+
[key: string]: unknown;
|
|
77
|
+
}
|
package/dist/browser.js
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
export class UploadError extends Error {
|
|
2
|
+
status;
|
|
3
|
+
code;
|
|
4
|
+
constructor(message, status,
|
|
5
|
+
/** `code` estable del error (too_large, type_not_allowed, quarantined…), si el endpoint lo informó. */
|
|
6
|
+
code) {
|
|
7
|
+
super(message);
|
|
8
|
+
this.status = status;
|
|
9
|
+
this.code = code;
|
|
10
|
+
this.name = "UploadError";
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Sube `file` al storage. En multipart devuelve las partes con sus ETags: hay que enviarlas al
|
|
15
|
+
* backend para que llame a `fs.complete(id, { parts })`. En subida simple `parts` viene vacío.
|
|
16
|
+
*/
|
|
17
|
+
export async function uploadFile(file, upload, opts = {}) {
|
|
18
|
+
const total = file.size;
|
|
19
|
+
const report = (loaded) => opts.onProgress?.({ loaded, total, percent: total ? Math.min(100, Math.round((loaded / total) * 100)) : 100 });
|
|
20
|
+
if (upload.mode === "simple") {
|
|
21
|
+
if (!upload.url)
|
|
22
|
+
throw new UploadError("instrucciones de subida inválidas: falta la URL", 0);
|
|
23
|
+
await put(upload.url, file, upload.headers, opts.signal, report);
|
|
24
|
+
report(total);
|
|
25
|
+
return { parts: [] };
|
|
26
|
+
}
|
|
27
|
+
if (!opts.signParts)
|
|
28
|
+
throw new UploadError("la subida es multipart: falta la opción signParts", 0);
|
|
29
|
+
const { partSize, partCount } = upload;
|
|
30
|
+
if (!partSize || !partCount)
|
|
31
|
+
throw new UploadError("instrucciones de subida inválidas: faltan las partes", 0);
|
|
32
|
+
const parts = [];
|
|
33
|
+
const loadedByPart = new Map();
|
|
34
|
+
const progress = (n, loaded) => {
|
|
35
|
+
loadedByPart.set(n, loaded);
|
|
36
|
+
let sum = 0;
|
|
37
|
+
for (const v of loadedByPart.values())
|
|
38
|
+
sum += v;
|
|
39
|
+
report(sum);
|
|
40
|
+
};
|
|
41
|
+
const pending = Array.from({ length: partCount }, (_, i) => i + 1);
|
|
42
|
+
const worker = async () => {
|
|
43
|
+
for (;;) {
|
|
44
|
+
const n = pending.shift();
|
|
45
|
+
if (n === undefined)
|
|
46
|
+
return;
|
|
47
|
+
const chunk = file.slice((n - 1) * partSize, n * partSize);
|
|
48
|
+
const retries = opts.retries ?? 3;
|
|
49
|
+
for (let attempt = 0;; attempt++) {
|
|
50
|
+
try {
|
|
51
|
+
// La URL se firma justo antes de usarla: no caduca aunque la subida sea lenta.
|
|
52
|
+
const [signed] = await opts.signParts([n]);
|
|
53
|
+
const etag = await put(signed.url, chunk, undefined, opts.signal, (loaded) => progress(n, loaded));
|
|
54
|
+
parts.push({ partNumber: n, etag });
|
|
55
|
+
progress(n, chunk.size);
|
|
56
|
+
break;
|
|
57
|
+
}
|
|
58
|
+
catch (err) {
|
|
59
|
+
if (opts.signal?.aborted || attempt >= retries)
|
|
60
|
+
throw err;
|
|
61
|
+
await new Promise((r) => setTimeout(r, 500 * 2 ** attempt));
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
await Promise.all(Array.from({ length: Math.min(opts.concurrency ?? 3, partCount) }, worker));
|
|
67
|
+
parts.sort((a, b) => a.partNumber - b.partNumber);
|
|
68
|
+
return { parts };
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Sube un archivo de punta a punta contra tu endpoint de subida (sdk/PROTOCOL.md) y devuelve el
|
|
72
|
+
* archivo ya verificado. Funciona con cualquier backend que use el SDK del File Service (Node,
|
|
73
|
+
* Python, Go, PHP).
|
|
74
|
+
*
|
|
75
|
+
* const file = await upload(input.files[0], { endpoint: "/api/files", onProgress: (p) => setPct(p.percent) });
|
|
76
|
+
*/
|
|
77
|
+
export async function upload(file, opts) {
|
|
78
|
+
const call = async (body) => {
|
|
79
|
+
let res;
|
|
80
|
+
try {
|
|
81
|
+
res = await fetch(opts.endpoint, {
|
|
82
|
+
method: "POST",
|
|
83
|
+
headers: { "Content-Type": "application/json", Accept: "application/json", ...(opts.headers ?? {}) },
|
|
84
|
+
body: JSON.stringify(body),
|
|
85
|
+
signal: opts.signal,
|
|
86
|
+
credentials: "same-origin",
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
catch {
|
|
90
|
+
throw new UploadError("no se pudo conectar con el endpoint de subida", 0);
|
|
91
|
+
}
|
|
92
|
+
const json = await res.json().catch(() => undefined);
|
|
93
|
+
if (!res.ok) {
|
|
94
|
+
throw new UploadError(json?.error?.message ?? `el endpoint de subida respondió HTTP ${res.status}`, res.status, json?.error?.code);
|
|
95
|
+
}
|
|
96
|
+
return json;
|
|
97
|
+
};
|
|
98
|
+
const name = opts.name ?? file.name ?? "archivo";
|
|
99
|
+
const mimeType = file.type || "application/octet-stream";
|
|
100
|
+
const created = await call({ action: "create", name, mimeType, size: file.size, metadata: opts.metadata });
|
|
101
|
+
const { id, token } = created;
|
|
102
|
+
const { parts } = await uploadFile(file, created.upload, {
|
|
103
|
+
...opts,
|
|
104
|
+
signParts: async (partNumbers) => (await call({ action: "parts", id, token, partNumbers })).urls,
|
|
105
|
+
});
|
|
106
|
+
return call({ action: "complete", id, token, parts: parts.length ? parts : undefined });
|
|
107
|
+
}
|
|
108
|
+
/** PUT con progreso (XMLHttpRequest: fetch no informa el avance de una subida). Devuelve el ETag. */
|
|
109
|
+
function put(url, body, headers, signal, onLoaded) {
|
|
110
|
+
return new Promise((resolve, reject) => {
|
|
111
|
+
if (signal?.aborted)
|
|
112
|
+
return reject(new UploadError("subida cancelada", 0));
|
|
113
|
+
const xhr = new XMLHttpRequest();
|
|
114
|
+
xhr.open("PUT", url);
|
|
115
|
+
for (const [k, v] of Object.entries(headers ?? {}))
|
|
116
|
+
xhr.setRequestHeader(k, v);
|
|
117
|
+
xhr.upload.onprogress = (e) => onLoaded(e.loaded);
|
|
118
|
+
xhr.onload = () => {
|
|
119
|
+
if (xhr.status >= 200 && xhr.status < 300) {
|
|
120
|
+
resolve((xhr.getResponseHeader("ETag") ?? "").replace(/^"|"$/g, ""));
|
|
121
|
+
}
|
|
122
|
+
else {
|
|
123
|
+
reject(new UploadError(`el storage rechazó la subida (HTTP ${xhr.status})`, xhr.status));
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
xhr.onerror = () => reject(new UploadError("error de red durante la subida", 0));
|
|
127
|
+
xhr.onabort = () => reject(new UploadError("subida cancelada", 0));
|
|
128
|
+
signal?.addEventListener("abort", () => xhr.abort(), { once: true });
|
|
129
|
+
xhr.send(body);
|
|
130
|
+
});
|
|
131
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Helper de navegador. Lo normal es `upload(file, { endpoint })` contra el endpoint de tu backend
|
|
3
|
+
* (`handleUpload` / `createUploadRoute`). `uploadFile` es el paso de bajo nivel: sube con las instrucciones que tu backend
|
|
4
|
+
* obtuvo de `fs.createUpload()`. No usa ni conoce la API key.
|
|
5
|
+
*
|
|
6
|
+
* const { id, upload } = await fetch("/api/files", { method: "POST", body: ... }).then(r => r.json());
|
|
7
|
+
* const { parts } = await uploadFile(file, upload, { onProgress: (p) => setProgress(p.percent) });
|
|
8
|
+
* await fetch(`/api/files/${id}/complete`, { method: "POST", body: JSON.stringify({ parts }) });
|
|
9
|
+
*/
|
|
10
|
+
import type { CompletedPart, PartUrl, UploadInstructions } from "./types.js";
|
|
11
|
+
export type { CompletedPart, PartUrl, UploadInstructions } from "./types.js";
|
|
12
|
+
export interface UploadProgress {
|
|
13
|
+
loaded: number;
|
|
14
|
+
total: number;
|
|
15
|
+
/** 0 a 100. */
|
|
16
|
+
percent: number;
|
|
17
|
+
}
|
|
18
|
+
export interface UploadFileOptions {
|
|
19
|
+
onProgress?: (progress: UploadProgress) => void;
|
|
20
|
+
signal?: AbortSignal;
|
|
21
|
+
/**
|
|
22
|
+
* Requerido en subidas multipart: pide a TU backend las URLs firmadas de un lote de partes
|
|
23
|
+
* (el backend las obtiene con `fs.signParts(id, partNumbers)`).
|
|
24
|
+
*/
|
|
25
|
+
signParts?: (partNumbers: number[]) => Promise<PartUrl[]>;
|
|
26
|
+
/** Partes subidas en paralelo en multipart (default 3). */
|
|
27
|
+
concurrency?: number;
|
|
28
|
+
/** Reintentos por parte ante fallas de red (default 3). */
|
|
29
|
+
retries?: number;
|
|
30
|
+
}
|
|
31
|
+
export declare class UploadError extends Error {
|
|
32
|
+
readonly status: number;
|
|
33
|
+
/** `code` estable del error (too_large, type_not_allowed, quarantined…), si el endpoint lo informó. */
|
|
34
|
+
readonly code?: string | undefined;
|
|
35
|
+
constructor(message: string, status: number,
|
|
36
|
+
/** `code` estable del error (too_large, type_not_allowed, quarantined…), si el endpoint lo informó. */
|
|
37
|
+
code?: string | undefined);
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Sube `file` al storage. En multipart devuelve las partes con sus ETags: hay que enviarlas al
|
|
41
|
+
* backend para que llame a `fs.complete(id, { parts })`. En subida simple `parts` viene vacío.
|
|
42
|
+
*/
|
|
43
|
+
export declare function uploadFile(file: Blob, upload: UploadInstructions, opts?: UploadFileOptions): Promise<{
|
|
44
|
+
parts: CompletedPart[];
|
|
45
|
+
}>;
|
|
46
|
+
export interface UploadOptions extends Omit<UploadFileOptions, "signParts"> {
|
|
47
|
+
/** URL del endpoint de subida de TU backend (el que usa `handleUpload` / `createUploadRoute`). */
|
|
48
|
+
endpoint: string;
|
|
49
|
+
/** Headers extra para tu endpoint (ej. `Authorization` si tu app no usa cookies). */
|
|
50
|
+
headers?: Record<string, string>;
|
|
51
|
+
/** Metadata del cliente (tu backend puede pisarla). */
|
|
52
|
+
metadata?: Record<string, unknown>;
|
|
53
|
+
/** Nombre a usar en vez de `file.name`. */
|
|
54
|
+
name?: string;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Sube un archivo de punta a punta contra tu endpoint de subida (sdk/PROTOCOL.md) y devuelve el
|
|
58
|
+
* archivo ya verificado. Funciona con cualquier backend que use el SDK del File Service (Node,
|
|
59
|
+
* Python, Go, PHP).
|
|
60
|
+
*
|
|
61
|
+
* const file = await upload(input.files[0], { endpoint: "/api/files", onProgress: (p) => setPct(p.percent) });
|
|
62
|
+
*/
|
|
63
|
+
export declare function upload(file: File | Blob, opts: UploadOptions): Promise<UploadedFile>;
|
|
64
|
+
/** El archivo tal como lo devuelve el endpoint de subida (`FileInfo` del SDK). */
|
|
65
|
+
export interface UploadedFile {
|
|
66
|
+
id: string;
|
|
67
|
+
status: string;
|
|
68
|
+
name: string;
|
|
69
|
+
mimeType: string;
|
|
70
|
+
size: number;
|
|
71
|
+
visibility: "private" | "public";
|
|
72
|
+
publicUrl?: string;
|
|
73
|
+
ownerRef?: string;
|
|
74
|
+
metadata: Record<string, unknown>;
|
|
75
|
+
createdAt: string;
|
|
76
|
+
[key: string]: unknown;
|
|
77
|
+
}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.UploadError = void 0;
|
|
4
|
+
exports.uploadFile = uploadFile;
|
|
5
|
+
exports.upload = upload;
|
|
6
|
+
class UploadError extends Error {
|
|
7
|
+
status;
|
|
8
|
+
code;
|
|
9
|
+
constructor(message, status,
|
|
10
|
+
/** `code` estable del error (too_large, type_not_allowed, quarantined…), si el endpoint lo informó. */
|
|
11
|
+
code) {
|
|
12
|
+
super(message);
|
|
13
|
+
this.status = status;
|
|
14
|
+
this.code = code;
|
|
15
|
+
this.name = "UploadError";
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
exports.UploadError = UploadError;
|
|
19
|
+
/**
|
|
20
|
+
* Sube `file` al storage. En multipart devuelve las partes con sus ETags: hay que enviarlas al
|
|
21
|
+
* backend para que llame a `fs.complete(id, { parts })`. En subida simple `parts` viene vacío.
|
|
22
|
+
*/
|
|
23
|
+
async function uploadFile(file, upload, opts = {}) {
|
|
24
|
+
const total = file.size;
|
|
25
|
+
const report = (loaded) => opts.onProgress?.({ loaded, total, percent: total ? Math.min(100, Math.round((loaded / total) * 100)) : 100 });
|
|
26
|
+
if (upload.mode === "simple") {
|
|
27
|
+
if (!upload.url)
|
|
28
|
+
throw new UploadError("instrucciones de subida inválidas: falta la URL", 0);
|
|
29
|
+
await put(upload.url, file, upload.headers, opts.signal, report);
|
|
30
|
+
report(total);
|
|
31
|
+
return { parts: [] };
|
|
32
|
+
}
|
|
33
|
+
if (!opts.signParts)
|
|
34
|
+
throw new UploadError("la subida es multipart: falta la opción signParts", 0);
|
|
35
|
+
const { partSize, partCount } = upload;
|
|
36
|
+
if (!partSize || !partCount)
|
|
37
|
+
throw new UploadError("instrucciones de subida inválidas: faltan las partes", 0);
|
|
38
|
+
const parts = [];
|
|
39
|
+
const loadedByPart = new Map();
|
|
40
|
+
const progress = (n, loaded) => {
|
|
41
|
+
loadedByPart.set(n, loaded);
|
|
42
|
+
let sum = 0;
|
|
43
|
+
for (const v of loadedByPart.values())
|
|
44
|
+
sum += v;
|
|
45
|
+
report(sum);
|
|
46
|
+
};
|
|
47
|
+
const pending = Array.from({ length: partCount }, (_, i) => i + 1);
|
|
48
|
+
const worker = async () => {
|
|
49
|
+
for (;;) {
|
|
50
|
+
const n = pending.shift();
|
|
51
|
+
if (n === undefined)
|
|
52
|
+
return;
|
|
53
|
+
const chunk = file.slice((n - 1) * partSize, n * partSize);
|
|
54
|
+
const retries = opts.retries ?? 3;
|
|
55
|
+
for (let attempt = 0;; attempt++) {
|
|
56
|
+
try {
|
|
57
|
+
// La URL se firma justo antes de usarla: no caduca aunque la subida sea lenta.
|
|
58
|
+
const [signed] = await opts.signParts([n]);
|
|
59
|
+
const etag = await put(signed.url, chunk, undefined, opts.signal, (loaded) => progress(n, loaded));
|
|
60
|
+
parts.push({ partNumber: n, etag });
|
|
61
|
+
progress(n, chunk.size);
|
|
62
|
+
break;
|
|
63
|
+
}
|
|
64
|
+
catch (err) {
|
|
65
|
+
if (opts.signal?.aborted || attempt >= retries)
|
|
66
|
+
throw err;
|
|
67
|
+
await new Promise((r) => setTimeout(r, 500 * 2 ** attempt));
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
await Promise.all(Array.from({ length: Math.min(opts.concurrency ?? 3, partCount) }, worker));
|
|
73
|
+
parts.sort((a, b) => a.partNumber - b.partNumber);
|
|
74
|
+
return { parts };
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Sube un archivo de punta a punta contra tu endpoint de subida (sdk/PROTOCOL.md) y devuelve el
|
|
78
|
+
* archivo ya verificado. Funciona con cualquier backend que use el SDK del File Service (Node,
|
|
79
|
+
* Python, Go, PHP).
|
|
80
|
+
*
|
|
81
|
+
* const file = await upload(input.files[0], { endpoint: "/api/files", onProgress: (p) => setPct(p.percent) });
|
|
82
|
+
*/
|
|
83
|
+
async function upload(file, opts) {
|
|
84
|
+
const call = async (body) => {
|
|
85
|
+
let res;
|
|
86
|
+
try {
|
|
87
|
+
res = await fetch(opts.endpoint, {
|
|
88
|
+
method: "POST",
|
|
89
|
+
headers: { "Content-Type": "application/json", Accept: "application/json", ...(opts.headers ?? {}) },
|
|
90
|
+
body: JSON.stringify(body),
|
|
91
|
+
signal: opts.signal,
|
|
92
|
+
credentials: "same-origin",
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
catch {
|
|
96
|
+
throw new UploadError("no se pudo conectar con el endpoint de subida", 0);
|
|
97
|
+
}
|
|
98
|
+
const json = await res.json().catch(() => undefined);
|
|
99
|
+
if (!res.ok) {
|
|
100
|
+
throw new UploadError(json?.error?.message ?? `el endpoint de subida respondió HTTP ${res.status}`, res.status, json?.error?.code);
|
|
101
|
+
}
|
|
102
|
+
return json;
|
|
103
|
+
};
|
|
104
|
+
const name = opts.name ?? file.name ?? "archivo";
|
|
105
|
+
const mimeType = file.type || "application/octet-stream";
|
|
106
|
+
const created = await call({ action: "create", name, mimeType, size: file.size, metadata: opts.metadata });
|
|
107
|
+
const { id, token } = created;
|
|
108
|
+
const { parts } = await uploadFile(file, created.upload, {
|
|
109
|
+
...opts,
|
|
110
|
+
signParts: async (partNumbers) => (await call({ action: "parts", id, token, partNumbers })).urls,
|
|
111
|
+
});
|
|
112
|
+
return call({ action: "complete", id, token, parts: parts.length ? parts : undefined });
|
|
113
|
+
}
|
|
114
|
+
/** PUT con progreso (XMLHttpRequest: fetch no informa el avance de una subida). Devuelve el ETag. */
|
|
115
|
+
function put(url, body, headers, signal, onLoaded) {
|
|
116
|
+
return new Promise((resolve, reject) => {
|
|
117
|
+
if (signal?.aborted)
|
|
118
|
+
return reject(new UploadError("subida cancelada", 0));
|
|
119
|
+
const xhr = new XMLHttpRequest();
|
|
120
|
+
xhr.open("PUT", url);
|
|
121
|
+
for (const [k, v] of Object.entries(headers ?? {}))
|
|
122
|
+
xhr.setRequestHeader(k, v);
|
|
123
|
+
xhr.upload.onprogress = (e) => onLoaded(e.loaded);
|
|
124
|
+
xhr.onload = () => {
|
|
125
|
+
if (xhr.status >= 200 && xhr.status < 300) {
|
|
126
|
+
resolve((xhr.getResponseHeader("ETag") ?? "").replace(/^"|"$/g, ""));
|
|
127
|
+
}
|
|
128
|
+
else {
|
|
129
|
+
reject(new UploadError(`el storage rechazó la subida (HTTP ${xhr.status})`, xhr.status));
|
|
130
|
+
}
|
|
131
|
+
};
|
|
132
|
+
xhr.onerror = () => reject(new UploadError("error de red durante la subida", 0));
|
|
133
|
+
xhr.onabort = () => reject(new UploadError("subida cancelada", 0));
|
|
134
|
+
signal?.addEventListener("abort", () => xhr.abort(), { once: true });
|
|
135
|
+
xhr.send(body);
|
|
136
|
+
});
|
|
137
|
+
}
|