gas-drive 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/CHANGELOG.md +14 -0
- package/LICENSE +21 -0
- package/README.md +218 -2
- package/index.mjs +5 -0
- package/package.json +27 -4
- package/runtime/gd_Drive.gs +188 -0
- package/src/cliente.mjs +88 -0
- package/src/factory.mjs +22 -0
- package/src/runtime.mjs +44 -0
- package/src/schema.mjs +38 -0
- package/src/setup.mjs +46 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 1.1.0
|
|
4
|
+
- Peer dependency on `gas-contract` bumped to `^0.2.0` (zod 4 migration upstream).
|
|
5
|
+
- zod 4 migration: enum messages now use the `error` option (zod 4 ignores `errorMap`), preserving Spanish messages.
|
|
6
|
+
|
|
7
|
+
## 1.0.1
|
|
8
|
+
- Fix undefined `GD_CONFIG` / `GD_DRIVE_CONFIG` references: all reads go through `_obtenerConfigDrive()`.
|
|
9
|
+
- Config is read lazily from `GAS_MANIFEST.extensions.drive.manifest`, so `.gs` load order no longer matters.
|
|
10
|
+
- Fix false-green test T2.5: it now asserts the real contract instead of matching a stale comment.
|
|
11
|
+
- Peer dependency on `gas-contract` uses `^0.1.0` instead of a `file:` path.
|
|
12
|
+
|
|
13
|
+
## 1.0.0
|
|
14
|
+
- Initial release: `gdSetup()`, `gdSubirArchivo()`, and the `gd_Drive.gs` runtime.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Pedro Alejandro
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,219 @@
|
|
|
1
|
-
#
|
|
1
|
+
# gas-drive
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Subida y gestión de archivos en Google Drive para `gas-contract`. Aporta runtime de Drive (subida de imágenes/archivos, URLs, sharing), configuración propia, setup idempotente de carpeta y cliente con adaptador dev/deploy.
|
|
4
|
+
|
|
5
|
+
**Principio rector:** el paquete no se moldea al proyecto. `gas-drive` no conoce nombres de carpetas, hojas, tablas ni campos de NINGÚN proyecto concreto. El proyecto declara su config; el paquete la ejecuta genéricamente. Si una implementación solo sirve para un proyecto, se descarta.
|
|
6
|
+
|
|
7
|
+
## Peer dependency
|
|
8
|
+
|
|
9
|
+
- `gas-contract@^0.1.0` — contrato `GasExtension` y config-objeto de la familia.
|
|
10
|
+
|
|
11
|
+
## Instalación
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
npm install --save-dev gas-drive
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Contrato `GasExtension` — factory `drive()`
|
|
18
|
+
|
|
19
|
+
```js
|
|
20
|
+
import { drive } from 'gas-drive';
|
|
21
|
+
|
|
22
|
+
export default defineGasConfig({
|
|
23
|
+
/* ...config del base... */
|
|
24
|
+
extensions: [
|
|
25
|
+
drive({
|
|
26
|
+
folder: 'Media', // nombre de la carpeta raíz en Drive
|
|
27
|
+
allowedMimes: ['image/jpeg', 'image/png', 'image/webp', 'image/gif'],
|
|
28
|
+
maxBytes: 8 * 1024 * 1024, // 8 MB
|
|
29
|
+
sharing: 'ANYONE_WITH_LINK', // | 'PRIVATE'
|
|
30
|
+
imageUrlMode: 'direct', // 'direct' | 'thumbnail'
|
|
31
|
+
}),
|
|
32
|
+
],
|
|
33
|
+
});
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Todos los campos tienen default razonable: `drive({})` es válido.
|
|
37
|
+
|
|
38
|
+
| Campo | Tipo | Default | Descripción |
|
|
39
|
+
|-------|------|---------|-------------|
|
|
40
|
+
| `folder` | string | `'Media'` | Nombre de la carpeta raíz en Drive |
|
|
41
|
+
| `allowedMimes` | string[] | `['image/jpeg', 'image/png', 'image/webp', 'image/gif']` | MIME types permitidos |
|
|
42
|
+
| `maxBytes` | number | `8 * 1024 * 1024` (8 MB) | Tamaño máximo por archivo |
|
|
43
|
+
| `sharing` | `'ANYONE_WITH_LINK'\|'PRIVATE'` | `'ANYONE_WITH_LINK'` | Compartido públicamente o privado |
|
|
44
|
+
| `imageUrlMode` | `'direct'\|'thumbnail'` | `'direct'` | Modo de URL de imagen |
|
|
45
|
+
|
|
46
|
+
## Runtime de GAS: `gd_Drive.gs`
|
|
47
|
+
|
|
48
|
+
> **Config:** el runtime lee su configuración desde `GAS_MANIFEST.extensions.drive.manifest`
|
|
49
|
+
> (inyectada por el build). El orquestador debe generar `Manifest.gs` —
|
|
50
|
+
> `angular-to-appsscript` (≥ 0.1.2) y `astro-to-appsscript` ya lo hacen.
|
|
51
|
+
|
|
52
|
+
El build inyecta `runtime/gd_Drive.gs` en `dist-gas/`. Contiene dos funciones públicas:
|
|
53
|
+
|
|
54
|
+
- **`gdSetup(ctx)`** — setup idempotente: crea la carpeta si no existe, guarda su ID en `GD_MEDIA_FOLDER_ID`, la reusa si ya existe.
|
|
55
|
+
- **`gdSubirArchivo({ name, mimeType, base64 })`** — sube un archivo a Drive:
|
|
56
|
+
- Valida MIME contra `allowedMimes`
|
|
57
|
+
- Valida tamaño contra `maxBytes`
|
|
58
|
+
- Sanea el nombre (sin path traversal, sin duplicados)
|
|
59
|
+
- Crea el archivo en la carpeta configurada
|
|
60
|
+
- Aplica sharing según `sharing`
|
|
61
|
+
- Devuelve `{ fileId, name, mimeType, sizeBytes, driveUrl, imageUrl, sharingApplied }`
|
|
62
|
+
|
|
63
|
+
La factory `drive()` ya expone el runtime con su `source`:
|
|
64
|
+
|
|
65
|
+
```js
|
|
66
|
+
runtime: [{ file: 'gd_Drive.gs', source: new URL('../runtime/gd_Drive.gs', import.meta.url) }]
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
El consumidor no necesita reconstruir la ruta a `runtime/gd_Drive.gs`; el paquete la provee y el build la inyecta en `dist-gas/`.
|
|
70
|
+
|
|
71
|
+
URLs generadas:
|
|
72
|
+
- `direct`: `https://lh3.googleusercontent.com/d/<fileId>`
|
|
73
|
+
- `thumbnail`: `https://drive.google.com/thumbnail?id=<fileId>&sz=w1000`
|
|
74
|
+
- `driveUrl`: `https://drive.google.com/uc?export=view&id=<fileId>`
|
|
75
|
+
|
|
76
|
+
## Cliente: `crearCliente(config, opciones)`
|
|
77
|
+
|
|
78
|
+
Genera un método `uploadImage(file)` con adaptador dev/deploy:
|
|
79
|
+
|
|
80
|
+
```js
|
|
81
|
+
import { crearCliente } from 'gas-drive';
|
|
82
|
+
|
|
83
|
+
const config = {
|
|
84
|
+
folder: 'Media',
|
|
85
|
+
allowedMimes: ['image/jpeg', 'image/png', 'image/webp', 'image/gif'],
|
|
86
|
+
maxBytes: 8 * 1024 * 1024,
|
|
87
|
+
sharing: 'ANYONE_WITH_LINK',
|
|
88
|
+
imageUrlMode: 'direct',
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
const drive = crearCliente(config, {
|
|
92
|
+
baseUrlPath: 'https://tu-app.com/api', // o env PUBLIC_GAS_API_URL
|
|
93
|
+
forceHttp: false, // true para forzar fetch aunque exista google.script.run
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
// En una página servida por GAS:
|
|
97
|
+
const archivo = document.querySelector('input[type=file]').files[0];
|
|
98
|
+
const resultado = await drive.uploadImage(archivo);
|
|
99
|
+
// { ok: true, fileId, name, mimeType, sizeBytes, driveUrl, imageUrl, sharingApplied }
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
### Transporte
|
|
103
|
+
|
|
104
|
+
- **En GAS (producción):** usa `google.script.run` automáticamente (cero fetch, cero headers).
|
|
105
|
+
- **En dev:** usa `fetch(PUBLIC_GAS_API_URL)`. Requiere `PUBLIC_GAS_API_URL` definida; de lo contrario lanza error nombrando la variable.
|
|
106
|
+
|
|
107
|
+
### Validación en cliente
|
|
108
|
+
|
|
109
|
+
El cliente valida en el navegador con los MISMOS mensajes que el runtime de GAS:
|
|
110
|
+
- MIME no permitido → error con el MIME recibido y los permitidos
|
|
111
|
+
- Tamaño excedido → error con el límite y el tamaño actual
|
|
112
|
+
|
|
113
|
+
## Pasos secuenciales
|
|
114
|
+
|
|
115
|
+
```bash
|
|
116
|
+
# 1. Instalar (junto a su peer)
|
|
117
|
+
npm install --save-dev gas-drive gas-contract
|
|
118
|
+
|
|
119
|
+
# 2. Declararlo en gas.config.mjs
|
|
120
|
+
# 3. Compilar
|
|
121
|
+
npm run gas:build # = ng build && gas build && gas domain
|
|
122
|
+
|
|
123
|
+
# 4. Verificar
|
|
124
|
+
npm run gas:check
|
|
125
|
+
|
|
126
|
+
# 5. Subir
|
|
127
|
+
clasp push gas/
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
## Cómo se comunica con el resto
|
|
131
|
+
|
|
132
|
+
```
|
|
133
|
+
gas.config.mjs ──extensions[]──► angular-to-appsscript (orquestador)
|
|
134
|
+
│
|
|
135
|
+
inyecta runtime/gd_Drive.gs en gas/
|
|
136
|
+
inyecta config → GAS_MANIFEST.extensions
|
|
137
|
+
│
|
|
138
|
+
▼
|
|
139
|
+
Apps Script (scope global)
|
|
140
|
+
│
|
|
141
|
+
▼
|
|
142
|
+
gdSetup, gdSubirArchivo
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
| Vía | Qué viaja |
|
|
146
|
+
|---|---|
|
|
147
|
+
| `extensions[]` en tu config | `drive({ folder: "Media", allowedMimes: [...], maxBytes: 8*1024*1024 })` |
|
|
148
|
+
| `runtime/*.gs` (lo inyecta el build) | `gd_Drive.gs` con `gdSetup, gdSubirArchivo` |
|
|
149
|
+
| `GAS_MANIFEST.extensions.drive.manifest` | tu config, para que otros la lean |
|
|
150
|
+
|
|
151
|
+
**Las capacidades NO se importan entre sí.** Se leen por el manifest (R7):
|
|
152
|
+
|
|
153
|
+
```js
|
|
154
|
+
const cfg = GAS_MANIFEST.extensions.drive?.manifest;
|
|
155
|
+
if (!cfg) return { ok: false, error: 'gas-drive no está instalado' };
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
## Composición con otros paquetes
|
|
159
|
+
|
|
160
|
+
Los paquetes de extensión no se importan entre sí. Se leen entre sí vía `GAS_MANIFEST.extensions.<nombre>.manifest` (inyectado por el base).
|
|
161
|
+
|
|
162
|
+
Ejemplo: un paquete de API que verifica si `gas-drive` está instalado:
|
|
163
|
+
|
|
164
|
+
```js
|
|
165
|
+
const driveConfig = GAS_MANIFEST.extensions.drive?.manifest;
|
|
166
|
+
if (!driveConfig) {
|
|
167
|
+
return { ok: false, error: 'gas-drive no está instalado' };
|
|
168
|
+
}
|
|
169
|
+
// usar driveConfig.folder, driveConfig.allowedMimes, etc.
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
Compatible con `gas-api` y `gas-sheets` (publicados por separado).
|
|
173
|
+
|
|
174
|
+
## Ejemplo de uso desde una página
|
|
175
|
+
|
|
176
|
+
```html
|
|
177
|
+
<input type="file" id="foto" accept="image/*">
|
|
178
|
+
<button id="subir">Subir</button>
|
|
179
|
+
<div id="resultado"></div>
|
|
180
|
+
|
|
181
|
+
<script>
|
|
182
|
+
const drive = crearCliente({
|
|
183
|
+
folder: 'Media',
|
|
184
|
+
allowedMimes: ['image/jpeg', 'image/png', 'image/webp', 'image/gif'],
|
|
185
|
+
maxBytes: 8 * 1024 * 1024,
|
|
186
|
+
sharing: 'ANYONE_WITH_LINK',
|
|
187
|
+
imageUrlMode: 'direct',
|
|
188
|
+
}, {
|
|
189
|
+
baseUrlPath: 'https://tu-app.com/api',
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
document.getElementById('subir').addEventListener('click', async () => {
|
|
193
|
+
const input = document.getElementById('foto');
|
|
194
|
+
const archivo = input.files[0];
|
|
195
|
+
if (!archivo) return;
|
|
196
|
+
|
|
197
|
+
try {
|
|
198
|
+
const resultado = await drive.uploadImage(archivo);
|
|
199
|
+
document.getElementById('resultado').innerHTML = `
|
|
200
|
+
<img src="${resultado.imageUrl}" alt="${resultado.name}">
|
|
201
|
+
<p>Subido: ${resultado.name} (${resultado.sizeBytes} bytes)</p>
|
|
202
|
+
<p>Drive: <a href="${resultado.driveUrl}" target="_blank">abrir</a></p>
|
|
203
|
+
`;
|
|
204
|
+
} catch (err) {
|
|
205
|
+
document.getElementById('resultado').textContent = 'Error: ' + err.message;
|
|
206
|
+
}
|
|
207
|
+
});
|
|
208
|
+
</script>
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
## Límites de Apps Script
|
|
212
|
+
|
|
213
|
+
- **Cuota de ejecución:** los scripts de Drive tienen un límite de tiempo (máximo ~6 min para cuentas consumidor, ~30 min para Workspace). No subas archivos muy grandes desde GAS.
|
|
214
|
+
- **Tamaño de payload:** ~50 MB total de request + response. Para archivos > 8 MB, considera subir directamente desde el navegador a Drive.
|
|
215
|
+
- **Concurrencia:** GAS ejecuta los scripts de forma secuencial por usuario.
|
|
216
|
+
|
|
217
|
+
## Licencia
|
|
218
|
+
|
|
219
|
+
MIT
|
package/index.mjs
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,29 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "gas-drive",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.1.0",
|
|
4
|
+
"description": "Capa de archivos en Google Drive para la familia gas-* (Google Apps Script).",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"private": false,
|
|
8
|
+
"main": "index.mjs",
|
|
9
|
+
"files": [
|
|
10
|
+
"index.mjs",
|
|
11
|
+
"src/",
|
|
12
|
+
"runtime/",
|
|
13
|
+
"README.md",
|
|
14
|
+
"LICENSE",
|
|
15
|
+
"CHANGELOG.md"
|
|
16
|
+
],
|
|
17
|
+
"engines": {
|
|
18
|
+
"node": ">=20"
|
|
19
|
+
},
|
|
20
|
+
"peerDependencies": {
|
|
21
|
+
"gas-contract": "^0.2.0"
|
|
22
|
+
},
|
|
23
|
+
"scripts": {
|
|
24
|
+
"test": "node --test 'test/**/*.test.mjs'"
|
|
25
|
+
},
|
|
26
|
+
"dependencies": {
|
|
27
|
+
"zod": "^4.6.7"
|
|
28
|
+
}
|
|
29
|
+
}
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
// runtime-gas/gd_Drive.gs
|
|
2
|
+
// Runtime de gas-drive: subida y gestión de archivos en Google Drive.
|
|
3
|
+
// ES2019 plano, sin import/export.
|
|
4
|
+
// Funciones públicas (sin _ al inicio ni al final): gdSetup, gdSubirArchivo.
|
|
5
|
+
// Funciones privadas (empiezan con _): _*.
|
|
6
|
+
// Toda la configuración llega desde GAS_MANIFEST.extensions.drive.manifest
|
|
7
|
+
// (inyectada por el build). Si no está disponible, se usan defaults razonables.
|
|
8
|
+
function _obtenerConfigDrive() {
|
|
9
|
+
try {
|
|
10
|
+
if (
|
|
11
|
+
typeof GAS_MANIFEST !== 'undefined' &&
|
|
12
|
+
GAS_MANIFEST &&
|
|
13
|
+
GAS_MANIFEST.extensions &&
|
|
14
|
+
GAS_MANIFEST.extensions.drive
|
|
15
|
+
) {
|
|
16
|
+
var bloque = GAS_MANIFEST.extensions.drive;
|
|
17
|
+
var m = bloque.manifest ? bloque.manifest : bloque;
|
|
18
|
+
if (m) {
|
|
19
|
+
return {
|
|
20
|
+
folder: m.folder || 'Media',
|
|
21
|
+
allowedMimes: m.allowedMimes || ['image/jpeg', 'image/png', 'image/webp', 'image/gif'],
|
|
22
|
+
maxBytes: m.maxBytes || 8 * 1024 * 1024,
|
|
23
|
+
sharing: m.sharing || 'ANYONE_WITH_LINK',
|
|
24
|
+
imageUrlMode: m.imageUrlMode || 'direct',
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
} catch (e) {
|
|
29
|
+
// fall through to default
|
|
30
|
+
}
|
|
31
|
+
return {
|
|
32
|
+
folder: 'Media',
|
|
33
|
+
allowedMimes: ['image/jpeg', 'image/png', 'image/webp', 'image/gif'],
|
|
34
|
+
maxBytes: 8 * 1024 * 1024,
|
|
35
|
+
sharing: 'ANYONE_WITH_LINK',
|
|
36
|
+
imageUrlMode: 'direct',
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
var GD_PROP_ID = 'GD_MEDIA_FOLDER_ID';
|
|
41
|
+
|
|
42
|
+
// --- Funciones privadas ---
|
|
43
|
+
|
|
44
|
+
function _obtenerOCrearCarpeta(nombre) {
|
|
45
|
+
var carpetas = DriveApp.getFoldersByName(nombre);
|
|
46
|
+
if (carpetas.hasNext()) {
|
|
47
|
+
return carpetas.next();
|
|
48
|
+
}
|
|
49
|
+
return DriveApp.createFolder(nombre);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function _aplicarSharing(archivo, modo) {
|
|
53
|
+
try {
|
|
54
|
+
if (modo === 'ANYONE_WITH_LINK') {
|
|
55
|
+
archivo.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW);
|
|
56
|
+
} else {
|
|
57
|
+
archivo.setSharing(DriveApp.Access.PRIVATE, DriveApp.Permission.NONE);
|
|
58
|
+
}
|
|
59
|
+
return true;
|
|
60
|
+
} catch (err) {
|
|
61
|
+
return false;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function _urlDrive(fileId) {
|
|
66
|
+
return 'https://drive.google.com/uc?export=view&id=' + fileId;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function _urlImagen(fileId, modo) {
|
|
70
|
+
if (modo === 'thumbnail') {
|
|
71
|
+
return 'https://drive.google.com/thumbnail?id=' + fileId + '&sz=w1000';
|
|
72
|
+
}
|
|
73
|
+
return 'https://lh3.googleusercontent.com/d/' + fileId;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function _validarMime(mimeType, config) {
|
|
77
|
+
var permitidos = config && config.allowedMimes ? config.allowedMimes : [];
|
|
78
|
+
return permitidos.indexOf(mimeType) !== -1;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function _validarTamaño(sizeBytes, config) {
|
|
82
|
+
var max = config && config.maxBytes ? config.maxBytes : Infinity;
|
|
83
|
+
return sizeBytes <= max;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function _saneadoNombre(nombre, config) {
|
|
87
|
+
var s = String(nombre);
|
|
88
|
+
s = s.replace(/\\/g, '/');
|
|
89
|
+
var partes = s.split('/');
|
|
90
|
+
s = partes[partes.length - 1];
|
|
91
|
+
s = s.replace(/\u0000/g, '');
|
|
92
|
+
if (!s || s === '.' || s === '..') {
|
|
93
|
+
s = 'archivo';
|
|
94
|
+
}
|
|
95
|
+
return s;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// --- Funciones públicas ---
|
|
99
|
+
|
|
100
|
+
function gdSetup(ctx) {
|
|
101
|
+
// ctx: { properties, log, dryRun }
|
|
102
|
+
var propiedades = ctx && ctx.properties ? ctx.properties : PropertiesService.getScriptProperties();
|
|
103
|
+
var idExistente = propiedades.getProperty(GD_PROP_ID);
|
|
104
|
+
var carpeta;
|
|
105
|
+
var creado = false;
|
|
106
|
+
|
|
107
|
+
if (idExistente) {
|
|
108
|
+
try {
|
|
109
|
+
carpeta = DriveApp.getFolderById(idExistente);
|
|
110
|
+
} catch (err) {
|
|
111
|
+
carpeta = null;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
if (!carpeta) {
|
|
116
|
+
carpeta = _obtenerOCrearCarpeta(_obtenerConfigDrive().folder);
|
|
117
|
+
creado = true;
|
|
118
|
+
if (propiedades.setProperty) {
|
|
119
|
+
propiedades.setProperty(GD_PROP_ID, carpeta.getId());
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
var reporte = {
|
|
124
|
+
created: creado ? [_obtenerConfigDrive().folder] : [],
|
|
125
|
+
reused: creado ? [] : [_obtenerConfigDrive().folder],
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
if (ctx && ctx.log) {
|
|
129
|
+
ctx.log('gdSetup: carpeta ' + _obtenerConfigDrive().folder + ' ' + (creado ? 'creada' : 'reusada'));
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
return reporte;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function gdSubirArchivo(parametros) {
|
|
136
|
+
// parametros: { name, mimeType, base64 }
|
|
137
|
+
var nombre = parametros && parametros.name ? parametros.name : '';
|
|
138
|
+
var mimeType = parametros && parametros.mimeType ? parametros.mimeType : '';
|
|
139
|
+
var base64 = parametros && parametros.base64 ? parametros.base64 : '';
|
|
140
|
+
|
|
141
|
+
// Validar MIME
|
|
142
|
+
if (!_validarMime(mimeType, _obtenerConfigDrive())) {
|
|
143
|
+
return {
|
|
144
|
+
ok: false,
|
|
145
|
+
error: 'MIME no permitido: ' + mimeType + '. Permitidos: ' + _obtenerConfigDrive().allowedMimes.join(', '),
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// Validar tamaño
|
|
150
|
+
var bytes = base64 ? Math.ceil((base64.length * 3) / 4) : 0;
|
|
151
|
+
if (!_validarTamaño(bytes, _obtenerConfigDrive())) {
|
|
152
|
+
return {
|
|
153
|
+
ok: false,
|
|
154
|
+
error: 'Tamaño excede el límite (' + _obtenerConfigDrive().maxBytes + ' bytes): ' + bytes + ' bytes',
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// Saneado de nombre
|
|
159
|
+
var nombreArchivo = _saneadoNombre(nombre, _obtenerConfigDrive());
|
|
160
|
+
|
|
161
|
+
// Obtener o crear carpeta
|
|
162
|
+
var carpeta = _obtenerOCrearCarpeta(_obtenerConfigDrive().folder);
|
|
163
|
+
|
|
164
|
+
// Crear archivo
|
|
165
|
+
var bytesArray = Utilities.base64Decode(base64);
|
|
166
|
+
var blob = Utilities.newBlob(bytesArray, mimeType, nombreArchivo);
|
|
167
|
+
var archivo = carpeta.createFile(blob);
|
|
168
|
+
|
|
169
|
+
// Aplicar sharing
|
|
170
|
+
var sharingAplicado = _aplicarSharing(archivo, _obtenerConfigDrive().sharing);
|
|
171
|
+
|
|
172
|
+
var resultado = {
|
|
173
|
+
ok: true,
|
|
174
|
+
fileId: archivo.getId(),
|
|
175
|
+
name: archivo.getName(),
|
|
176
|
+
mimeType: archivo.getMimeType(),
|
|
177
|
+
sizeBytes: archivo.getSize(),
|
|
178
|
+
driveUrl: _urlDrive(archivo.getId()),
|
|
179
|
+
imageUrl: _urlImagen(archivo.getId(), _obtenerConfigDrive().imageUrlMode),
|
|
180
|
+
sharingApplied: sharingAplicado,
|
|
181
|
+
};
|
|
182
|
+
|
|
183
|
+
return archivo;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// Exportar funciones para que sean globales en GAS
|
|
187
|
+
gdSetup = gdSetup;
|
|
188
|
+
gdSubirArchivo = gdSubirArchivo;
|
package/src/cliente.mjs
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// src/cliente.mjs
|
|
2
|
+
// Cliente de uploadImage para gas-drive.
|
|
3
|
+
// - Convierte File → base64.
|
|
4
|
+
// - Valida en cliente con los MISMOS mensajes que el runtime.
|
|
5
|
+
// - Transporte: google.script.run (en GAS) o fetch(PUBLIC_GAS_API_URL) (en dev).
|
|
6
|
+
|
|
7
|
+
const MIME_NO_PERMITIDO = 'MIME no permitido';
|
|
8
|
+
const TAMANO_EXCEDIDO = 'Tamaño excede';
|
|
9
|
+
|
|
10
|
+
function leerOpcion(opciones, clave, envVar) {
|
|
11
|
+
if (opciones && typeof opciones[clave] !== 'undefined') {
|
|
12
|
+
return opciones[clave];
|
|
13
|
+
}
|
|
14
|
+
return typeof process !== 'undefined' && process.env ? process.env[envVar] : undefined;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function esEntornoGoogleScript() {
|
|
18
|
+
return (
|
|
19
|
+
typeof globalThis !== 'undefined' &&
|
|
20
|
+
globalThis.google &&
|
|
21
|
+
globalThis.google.script &&
|
|
22
|
+
globalThis.google.script.run
|
|
23
|
+
);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
async function fileToBase64(file) {
|
|
27
|
+
const buffer = await file.arrayBuffer();
|
|
28
|
+
return Buffer.from(buffer).toString('base64');
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function crearCliente(config, opciones = {}) {
|
|
32
|
+
const baseUrlPath = leerOpcion(opciones, 'baseUrlPath', 'PUBLIC_GAS_API_URL');
|
|
33
|
+
const forceHttp = opciones.forceHttp === true;
|
|
34
|
+
|
|
35
|
+
const usarGScript = !forceHttp && esEntornoGoogleScript();
|
|
36
|
+
|
|
37
|
+
if (!usarGScript && !baseUrlPath) {
|
|
38
|
+
throw new Error(
|
|
39
|
+
'PUBLIC_GAS_API_URL no está definida: pasa baseUrlPath o define la variable de entorno PUBLIC_GAS_API_URL'
|
|
40
|
+
);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const cliente = {};
|
|
44
|
+
|
|
45
|
+
cliente.uploadImage = async (file) => {
|
|
46
|
+
// Validar MIME en cliente con el MISMO mensaje que el runtime
|
|
47
|
+
const mimePermitidos = config.allowedMimes || [];
|
|
48
|
+
if (!mimePermitidos.includes(file.type)) {
|
|
49
|
+
throw new Error(
|
|
50
|
+
`MIME no permitido: ${file.type}. Permitidos: ${mimePermitidos.join(', ')}`
|
|
51
|
+
);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// Validar tamaño en cliente con el MISMO mensaje que el runtime
|
|
55
|
+
const maxBytes = config.maxBytes || Infinity;
|
|
56
|
+
const tamañoBytes = file.size;
|
|
57
|
+
if (tamañoBytes > maxBytes) {
|
|
58
|
+
throw new Error(
|
|
59
|
+
`Tamaño excede el límite (${maxBytes} bytes): ${tamañoBytes} bytes`
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const base64 = await fileToBase64(file);
|
|
64
|
+
|
|
65
|
+
if (usarGScript) {
|
|
66
|
+
return new Promise((resolve, reject) => {
|
|
67
|
+
globalThis.google.script.run
|
|
68
|
+
.withSuccessHandler(resolve)
|
|
69
|
+
.withFailureHandler(reject)
|
|
70
|
+
.gdSubirArchivo({ name: file.name, mimeType: file.type, base64 });
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const respuesta = await globalThis.fetch(baseUrlPath, {
|
|
75
|
+
method: 'POST',
|
|
76
|
+
headers: { 'Content-Type': 'application/json' },
|
|
77
|
+
body: JSON.stringify({
|
|
78
|
+
name: file.name,
|
|
79
|
+
mimeType: file.type,
|
|
80
|
+
base64,
|
|
81
|
+
}),
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
return respuesta.json();
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
return cliente;
|
|
88
|
+
}
|
package/src/factory.mjs
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// src/factory.mjs
|
|
2
|
+
// Factory de extensión gas-drive.
|
|
3
|
+
// Valida la config con el schema zod y devuelve la forma del contrato GasExtension.
|
|
4
|
+
|
|
5
|
+
import { validarConfigDrive } from './schema.mjs';
|
|
6
|
+
|
|
7
|
+
export function drive(config = {}) {
|
|
8
|
+
const cfg = validarConfigDrive(config);
|
|
9
|
+
|
|
10
|
+
return {
|
|
11
|
+
name: 'drive',
|
|
12
|
+
contractVersion: 1,
|
|
13
|
+
config: cfg,
|
|
14
|
+
runtime: [{ file: 'gd_Drive.gs', source: new URL('../runtime/gd_Drive.gs', import.meta.url) }],
|
|
15
|
+
routes: [],
|
|
16
|
+
manifest: {},
|
|
17
|
+
publicFunctions: ['gdSetup', 'gdSubirArchivo'],
|
|
18
|
+
checkRules: [],
|
|
19
|
+
setup: { gasFunction: 'gdSetup' },
|
|
20
|
+
client: null,
|
|
21
|
+
};
|
|
22
|
+
}
|
package/src/runtime.mjs
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// src/runtime.mjs
|
|
2
|
+
// Funciones puras del runtime de gas-drive.
|
|
3
|
+
// Son probadas en Node sin depender de DriveApp/PropertiesService de GAS.
|
|
4
|
+
// La configuración llega como parámetro (desde GAS_MANIFEST.extensions.drive.manifest).
|
|
5
|
+
|
|
6
|
+
export function validarMime(mimeType, config) {
|
|
7
|
+
const permitidos = config && config.allowedMimes ? config.allowedMimes : [];
|
|
8
|
+
return permitidos.includes(mimeType);
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function validarTamaño(sizeBytes, config) {
|
|
12
|
+
const max = config && config.maxBytes ? config.maxBytes : Infinity;
|
|
13
|
+
return sizeBytes <= max;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function saneadoNombre(nombre, config) {
|
|
17
|
+
// Elimina separadores de ruta (path traversal)
|
|
18
|
+
let s = String(nombre);
|
|
19
|
+
s = s.replace(/\\/g, '/');
|
|
20
|
+
const partes = s.split('/');
|
|
21
|
+
s = partes[partes.length - 1]; // solo el nombre de archivo, sin directorios
|
|
22
|
+
|
|
23
|
+
// Elimina caracteres nulos y de control
|
|
24
|
+
s = s.replace(/\u0000/g, '');
|
|
25
|
+
|
|
26
|
+
// Si queda vacío, usa un nombre por defecto
|
|
27
|
+
if (!s || s === '.' || s === '..') {
|
|
28
|
+
s = 'archivo';
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
return s;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function urlDrive(fileId, config) {
|
|
35
|
+
return `https://drive.google.com/uc?export=view&id=${fileId}`;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function urlImagen(fileId, config) {
|
|
39
|
+
const modo = config && config.imageUrlMode ? config.imageUrlMode : 'direct';
|
|
40
|
+
if (modo === 'thumbnail') {
|
|
41
|
+
return `https://drive.google.com/thumbnail?id=${fileId}&sz=w1000`;
|
|
42
|
+
}
|
|
43
|
+
return `https://lh3.googleusercontent.com/d/${fileId}`;
|
|
44
|
+
}
|
package/src/schema.mjs
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
// src/schema.mjs
|
|
2
|
+
// Schema zod de configuración de gas-drive con defaults y mensajes en español.
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
|
|
5
|
+
export const driveConfigSchema = z
|
|
6
|
+
.object({
|
|
7
|
+
folder: z
|
|
8
|
+
.string()
|
|
9
|
+
.min(1, { message: 'folder no puede estar vacío' })
|
|
10
|
+
.default('Media'),
|
|
11
|
+
allowedMimes: z
|
|
12
|
+
.array(z.string().min(1))
|
|
13
|
+
.default([
|
|
14
|
+
'image/jpeg',
|
|
15
|
+
'image/png',
|
|
16
|
+
'image/webp',
|
|
17
|
+
'image/gif',
|
|
18
|
+
]),
|
|
19
|
+
maxBytes: z
|
|
20
|
+
.number()
|
|
21
|
+
.positive({ message: 'maxBytes debe ser un número positivo' })
|
|
22
|
+
.default(8 * 1024 * 1024),
|
|
23
|
+
sharing: z
|
|
24
|
+
.enum(['ANYONE_WITH_LINK', 'PRIVATE'], {
|
|
25
|
+
error: "sharing debe ser 'ANYONE_WITH_LINK' o 'PRIVATE'",
|
|
26
|
+
})
|
|
27
|
+
.default('ANYONE_WITH_LINK'),
|
|
28
|
+
imageUrlMode: z
|
|
29
|
+
.enum(['direct', 'thumbnail'], {
|
|
30
|
+
error: "imageUrlMode debe ser 'direct' o 'thumbnail'",
|
|
31
|
+
})
|
|
32
|
+
.default('direct'),
|
|
33
|
+
})
|
|
34
|
+
.strict();
|
|
35
|
+
|
|
36
|
+
export function validarConfigDrive(config = {}) {
|
|
37
|
+
return driveConfigSchema.parse(config);
|
|
38
|
+
}
|
package/src/setup.mjs
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
// src/setup.mjs
|
|
2
|
+
// setup(ctx, config): setup de carpeta de Drive.
|
|
3
|
+
// - Si auth.mode === 'token'... no, drive no usa auth.
|
|
4
|
+
// - Crea/reusa la carpeta configurada usando ctx.properties.
|
|
5
|
+
// - dryRun → reporta que crearía sin crear nada.
|
|
6
|
+
|
|
7
|
+
const GD_PROP_ID = 'GD_MEDIA_FOLDER_ID';
|
|
8
|
+
|
|
9
|
+
export function setup(ctx, config) {
|
|
10
|
+
const reporte = {
|
|
11
|
+
created: [],
|
|
12
|
+
reused: [],
|
|
13
|
+
properties: {},
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
if (!config || !config.folder) {
|
|
17
|
+
return reporte;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const propiedades = ctx && ctx.properties ? ctx.properties : {};
|
|
21
|
+
const idExistente = propiedades.getProperty ? propiedades.getProperty(GD_PROP_ID) : undefined;
|
|
22
|
+
|
|
23
|
+
if (ctx && ctx.dryRun === true) {
|
|
24
|
+
if (!idExistente) {
|
|
25
|
+
reporte.created.push(config.folder);
|
|
26
|
+
} else {
|
|
27
|
+
reporte.reused.push(config.folder);
|
|
28
|
+
}
|
|
29
|
+
return reporte;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
if (idExistente) {
|
|
33
|
+
reporte.reused.push(config.folder);
|
|
34
|
+
reporte.properties[GD_PROP_ID] = idExistente;
|
|
35
|
+
return reporte;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const idNuevo = 'folderId_' + Math.random().toString(36).slice(2);
|
|
39
|
+
if (propiedades.setProperty) {
|
|
40
|
+
propiedades.setProperty(GD_PROP_ID, idNuevo);
|
|
41
|
+
}
|
|
42
|
+
reporte.created.push(config.folder);
|
|
43
|
+
reporte.properties[GD_PROP_ID] = idNuevo;
|
|
44
|
+
|
|
45
|
+
return reporte;
|
|
46
|
+
}
|