gas-api 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 ADDED
@@ -0,0 +1,11 @@
1
+ # Changelog
2
+
3
+ ## 1.1.0
4
+ - Peer dependency on `gas-contract` bumped to `^0.2.0` (zod 4 migration upstream).
5
+ - Removed the unused `zod` import and dependency (the factory never validated with zod).
6
+
7
+ ## 1.0.1
8
+ - Peer dependency on `gas-contract` uses `^0.1.0` instead of a `file:` path.
9
+
10
+ ## 1.0.0
11
+ - Initial release: API token setup (`api_Setup.gs`) and the `api` extension factory.
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,213 @@
1
- # Temporary Holding Version
1
+ # gas-api
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ API declarativa en el mismo proyecto Apps Script que las vistas HTML. Define endpoints por schema (request/response, auth), los despacha desde el hook del Router del base (`gas-contract`), expone un cliente tipado con adaptador dev/deploy, y compone con `gas-sheets` para persistencia.
4
+
5
+ **Principio rector:** el paquete no se moldea al proyecto. No conoce endpoints, tablas ni flujos de ningún proyecto concreto: ejecuta lo que el consumidor declara en su config. Prohibido implementar "el endpoint del diario" o cualquier caso concreto.
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-api
15
+ ```
16
+
17
+ ## Contrato `GasExtension` — factory `api()`
18
+
19
+ ```js
20
+ import { api, endpoint } from 'gas-api';
21
+
22
+ export default defineGasConfig({
23
+ /* ...config del base... */
24
+ extensions: [
25
+ api({
26
+ auth: { mode: 'token', property: 'API_TOKEN' }, // 'token' | 'none'
27
+ baseUrlPath: '/api', // prefijo de rutas
28
+ endpoints: [
29
+ endpoint('GET /ping', {
30
+ auth: 'public',
31
+ response: z.object({ ok: z.boolean(), version: z.string() }),
32
+ handler: () => ({ ok: true, version: '1' }),
33
+ }),
34
+ endpoint('POST /items', {
35
+ auth: 'protected',
36
+ request: z.object({
37
+ nombre: z.string().min(1),
38
+ }),
39
+ response: z.object({ ok: z.boolean(), id: z.string() }),
40
+ handler: (payload) => ({ ok: true, id: 'item-1' }),
41
+ }),
42
+ ],
43
+ }),
44
+ ],
45
+ });
46
+ ```
47
+
48
+ ## Modelo resource / schema
49
+
50
+ ```
51
+ RESOURCE (almacenamiento) SCHEMA DE API (transporte)
52
+ defineTable → pestaña en Sheets defineApi → endpoints HTTP
53
+ - columnas, tipos, key - method, path, auth
54
+ - qué EXISTE - request/response (validación)
55
+ │ │
56
+ └──── endpoint mapea request → resource ops → response ────┘
57
+ ```
58
+
59
+ - El **resource** dice qué se guarda (estructura).
60
+ - El **schema de API** dice qué se acepta y qué se devuelve (contrato público).
61
+ - Son capas independientes: un endpoint puede no tocar Sheets (ping, cálculo); una tabla puede no tener endpoints expuestos.
62
+
63
+ ## Campos de `endpoint(methodPath, spec)`
64
+
65
+ | Campo | Tipo | Obligatorio | Descripción |
66
+ |-------|------|-------------|-------------|
67
+ | `method` | `'GET'\|'POST'\|'PUT'\|'DELETE'` | sí | Método HTTP |
68
+ | `path` | string que empieza con `/` | sí | Ruta del endpoint (ej. `/api/ping`) |
69
+ | `auth` | `'public'\|'protected'` | sí | Nivel de autenticación |
70
+ | `request` | schema zod | no | Validación del body/query entrante |
71
+ | `response` | schema zod | no | Validación/schema de la respuesta |
72
+ | `handler` | función | sí | Lógica del endpoint: `(payload, ctx) => respuesta` |
73
+
74
+ ## Setup: `apiSetup`
75
+
76
+ El paquete aporta su propio runtime `runtime/api_Setup.gs` que define la función global `apiSetup(ctx)`, declarada en `setup.gasFunction` de la factory. Se ejecuta cuando corresponda el flujo de setup del proyecto (`gas setup` / `astroGasSetup()` en Apps Script).
77
+
78
+ `apiSetup` lee la configuración del manifest inyectado por el core (`GAS_MANIFEST.extensions.api.manifest`) y actúa según `auth.mode`:
79
+
80
+ - `auth.mode === 'token'`: si falta el token en Script Properties, lo genera y lo guarda (respetando `ctx.dryRun`); si ya existe, lo reusa sin rotar. Nunca imprime el token en logs.
81
+ - `auth.mode === 'none'` o desconocido: no muta nada.
82
+
83
+ El setup nunca debe fallar: si no puede determinar `auth.mode`, sale sin hacer cambios.
84
+
85
+ ### Ejemplo de uso en config
86
+
87
+ ```js
88
+ extensions: [
89
+ api({
90
+ auth: { mode: 'token', property: 'API_TOKEN' },
91
+ endpoints: [],
92
+ }),
93
+ ],
94
+ ```
95
+
96
+ ## Autenticación
97
+
98
+ `gas-api` no implementa OAuth ni sesiones de Google. El contrato de auth es el que declares:
99
+
100
+ - `auth: 'public'` — sin chequeo de token.
101
+ - `auth: 'protected'` — exige el token **en el payload**:
102
+ - `GET`: query `?token=...`
103
+ - `POST/PUT/DELETE`: campo `token` del body JSON
104
+
105
+ **Importante:** GAS no entrega los headers de la request al handler (`e.parameter` y `e.postData.contents` solo). Un `fetch` del navegador puede enviar headers, pero GAS los descarta. Por eso **el token nunca viaja en headers**; siempre viaja en el payload.
106
+
107
+ ## Cliente tipado y adaptador dev/deploy
108
+
109
+ `crearCliente(endpoints, opciones)` genera un método por endpoint declarado:
110
+
111
+ ```js
112
+ import { crearCliente, endpoint } from 'gas-api';
113
+
114
+ const endpoints = [
115
+ endpoint('GET /ping', { auth: 'public', response: {} }),
116
+ endpoint('POST /items', { auth: 'protected', request: {}, response: {} }),
117
+ ];
118
+
119
+ const api = crearCliente(endpoints, {
120
+ baseUrlPath: 'https://tu-app.com/api', // o env PUBLIC_GAS_API_URL
121
+ token: 'MI_TOKEN_SECRETO', // o env PUBLIC_GAS_API_TOKEN
122
+ forceHttp: false, // true para forzar fetch aunque exista google.script.run
123
+ });
124
+ ```
125
+
126
+ ### Transporte
127
+
128
+ - **En GAS (producción):** usa `google.script.run` automáticamente (cero fetch, cero headers).
129
+ - **En dev:** usa `fetch(PUBLIC_GAS_API_URL + path)`. Requiere `PUBLIC_GAS_API_URL` definida; de lo contrario lanza error nombrando la variable.
130
+
131
+ ### Token en el cliente
132
+
133
+ - Endpoint `public`: no envía token.
134
+ - Endpoint `protected`: envía el token en query (GET) o en el body JSON (POST/PUT/DELETE). Nunca en headers.
135
+ - El token **no aparece en logs ni en errores**.
136
+
137
+ ## Pasos secuenciales
138
+
139
+ ```bash
140
+ # 1. Instalar (junto a su peer)
141
+ npm install --save-dev gas-api gas-contract
142
+
143
+ # 2. Declararlo en gas.config.mjs
144
+ # 3. Compilar
145
+ npm run gas:build # = ng build && gas build && gas domain
146
+
147
+ # 4. Verificar
148
+ npm run gas:check
149
+
150
+ # 5. Subir
151
+ clasp push gas/
152
+ ```
153
+
154
+ ## Cómo se comunica con el resto
155
+
156
+ ```
157
+ gas.config.mjs ──extensions[]──► angular-to-appsscript (orquestador)
158
+ │
159
+ inyecta runtime/api_Setup.gs en gas/
160
+ inyecta config → GAS_MANIFEST.extensions
161
+ │
162
+ ▼
163
+ Apps Script (scope global)
164
+ │
165
+ ▼
166
+ apiSetup + despacho de endpoints
167
+ ```
168
+
169
+ | Vía | Qué viaja |
170
+ |---|---|
171
+ | `extensions[]` en tu config | `api({ auth: { mode: "token" }, endpoints: [endpoint("GET /ping", {...})] })` |
172
+ | `runtime/*.gs` (lo inyecta el build) | `api_Setup.gs` con `apiSetup + despacho de endpoints` |
173
+ | `GAS_MANIFEST.extensions.api.manifest` | tu config, para que otros la lean |
174
+
175
+ **Las capacidades NO se importan entre sí.** Se leen por el manifest (R7):
176
+
177
+ ```js
178
+ const cfg = GAS_MANIFEST.extensions.api?.manifest;
179
+ if (!cfg) return { ok: false, error: 'gas-api no está instalado' };
180
+ ```
181
+
182
+ ## Composición con otros paquetes
183
+
184
+ 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 en `Router.gs`).
185
+
186
+ Ejemplo: un endpoint de `gas-api` que verifica si `gas-drive` está instalado:
187
+
188
+ ```js
189
+ handler: (payload, ctx) => {
190
+ const driveConfig = GAS_MANIFEST.extensions.drive?.manifest;
191
+ if (!driveConfig) {
192
+ return { ok: false, error: 'gas-drive no está instalado' };
193
+ }
194
+ // usar driveConfig.folder, driveConfig.allowedMimes, etc.
195
+ }
196
+ ```
197
+
198
+ Compatible con `gas-drive` y `gas-sheets` (publicados por separado).
199
+
200
+ ## Límites de Apps Script
201
+
202
+ - **Cuota de ejecución:** los endpoints tienen un límite de tiempo de ejecución (máximo ~6 minutos para cuentas consumidor, ~30 min para cuentas de Workspace). No uses endpoints para jobs largos.
203
+ - **Tamaño de payload:** ~50 MB total de request + response. Los uploads de archivos grandes van base64 por el endpoint; considera subir a Drive directamente desde el navegador para archivos > 8 MB.
204
+ - **Timeouts:** `google.script.run` y `fetch` tienen sus propios timeouts. Diseña endpoints que respondan rápido.
205
+ - **Concurrencia:** GAS ejecuta los endpoints de forma secuencial por usuario; no asumas paralelismo.
206
+
207
+ ## Ejemplo completo
208
+
209
+ Véase `test/f6/` para tests de ejemplo y el comportamiento esperado.
210
+
211
+ ## Licencia
212
+
213
+ MIT
package/index.mjs ADDED
@@ -0,0 +1,15 @@
1
+ // index.mjs — punto de entrada del paquete gas-api.
2
+ // Exporta la API pública: api(), endpoint(), serializeZodError(),
3
+ // apiDispatch(), verificarAuth(), responderOk(), responderError(),
4
+ // mapearARouter(), crearCliente(), setup(), leeManifestExtension().
5
+
6
+ export { api } from './src/api.mjs';
7
+ export { endpoint } from './src/endpoint.mjs';
8
+ export { serializeZodError } from './src/validate.mjs';
9
+ export { apiDispatch } from './src/dispatch.mjs';
10
+ export { verificarAuth } from './src/auth.mjs';
11
+ export { responderOk, responderError } from './src/response.mjs';
12
+ export { mapearARouter } from './src/manifest.mjs';
13
+ export { crearCliente } from './src/cliente.mjs';
14
+ export { setup } from './src/setup.mjs';
15
+ export { leeManifestExtension } from './src/composicion.mjs';
package/package.json CHANGED
@@ -1,6 +1,26 @@
1
1
  {
2
2
  "name": "gas-api",
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": "API declarativa en el mismo proyecto Apps Script que las vistas.",
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
+ }
@@ -0,0 +1,81 @@
1
+ // runtime/api_Setup.gs
2
+ // Runtime de gas-api: setup del token de API en Script Properties.
3
+ // ES2019 plano, sin import/export.
4
+ // Función pública (sin sufijo _): apiSetup.
5
+ // Toda la configuración llega desde GAS_MANIFEST.extensions.api.manifest
6
+ // (inyectada por el build). Si no hay config disponible, no falla.
7
+
8
+ var API_CONFIG = {
9
+ auth: { mode: 'none' },
10
+ };
11
+
12
+ // --- Función pública ---
13
+
14
+ function apiSetup(ctx) {
15
+ // ctx: { properties, log, dryRun }
16
+ var reporte = {
17
+ created: [],
18
+ reused: [],
19
+ };
20
+
21
+ // Obtener auth.mode de forma segura desde el manifest; si no se puede determinar, no hacer nada.
22
+ var manifest =
23
+ typeof GAS_MANIFEST !== 'undefined' && GAS_MANIFEST && GAS_MANIFEST.extensions
24
+ ? GAS_MANIFEST.extensions.api
25
+ : undefined;
26
+ var config = manifest && manifest.manifest ? manifest.manifest : API_CONFIG;
27
+ var auth = config && config.auth ? config.auth : { mode: 'none' };
28
+ var mode = auth && auth.mode ? auth.mode : 'none';
29
+
30
+ // Sin modo token: no mutar nada.
31
+ if (mode !== 'token') {
32
+ if (ctx && ctx.log) {
33
+ ctx.log('apiSetup: auth.mode no es "token", no se crea ni reusa token.');
34
+ }
35
+ return reporte;
36
+ }
37
+
38
+ var property = auth.property || 'API_TOKEN';
39
+ var propiedades =
40
+ ctx && ctx.properties ? ctx.properties : PropertiesService.getScriptProperties();
41
+ var tokenExistente = propiedades.getProperty ? propiedades.getProperty(property) : undefined;
42
+
43
+ if (ctx && ctx.dryRun === true) {
44
+ if (!tokenExistente) {
45
+ reporte.created.push(property);
46
+ } else {
47
+ reporte.reused.push(property);
48
+ }
49
+ return reporte;
50
+ }
51
+
52
+ if (tokenExistente) {
53
+ reporte.reused.push(property);
54
+ return reporte;
55
+ }
56
+
57
+ // Generar y guardar token (nunca imprimirlo en logs).
58
+ var tokenNuevo = _generarToken();
59
+ if (propiedades.setProperty) {
60
+ propiedades.setProperty(property, tokenNuevo);
61
+ }
62
+ reporte.created.push(property);
63
+
64
+ return reporte;
65
+ }
66
+
67
+ // --- Funciones privadas ---
68
+
69
+ function _generarToken(longitud) {
70
+ longitud = longitud || 43;
71
+ var caracteres =
72
+ 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.';
73
+ var token = '';
74
+ for (var i = 0; i < longitud; i++) {
75
+ token += caracteres.charAt(Math.floor(Math.random() * caracteres.length));
76
+ }
77
+ return token;
78
+ }
79
+
80
+ // apiSetup() es la única función pública de este archivo (sin _);
81
+ // las que empiezan con _ son privadas (convención del ecosistema).
package/src/api.mjs ADDED
@@ -0,0 +1,51 @@
1
+ // src/api.mjs
2
+ // Factory de extensión gas-api.
3
+ // Valida auth.mode, unicidad de method+path y devuelve la forma del contrato GasExtension.
4
+
5
+ const AUTH_MODES = new Set(['token', 'none']);
6
+
7
+ export function api(config = {}) {
8
+ const auth = config.auth || { mode: 'none' };
9
+
10
+ if (!AUTH_MODES.has(auth.mode)) {
11
+ throw new Error(`auth.mode inválido: '${auth.mode}'. Debe ser 'token' o 'none'.`);
12
+ }
13
+
14
+ const endpoints = Array.isArray(config.endpoints) ? config.endpoints : [];
15
+ const routes = [];
16
+ const seen = new Set();
17
+
18
+ for (const ep of endpoints) {
19
+ const key = `${ep.method}|${ep.path}`;
20
+ if (seen.has(key)) {
21
+ throw new Error(`ruta duplicada: ${ep.method} ${ep.path} (ya declarada previamente)`);
22
+ }
23
+ seen.add(key);
24
+ routes.push({
25
+ method: ep.method,
26
+ path: ep.path,
27
+ auth: ep.auth,
28
+ handler: ep.handler,
29
+ });
30
+ }
31
+
32
+ const publicFunctions = ['apiSetup'];
33
+ for (const ep of endpoints) {
34
+ if (ep.handler) {
35
+ publicFunctions.push(ep.handler);
36
+ }
37
+ }
38
+
39
+ return {
40
+ name: 'api',
41
+ contractVersion: 1,
42
+ config: config.config || {},
43
+ runtime: [{ file: 'api_Setup.gs', source: new URL('../runtime/api_Setup.gs', import.meta.url) }],
44
+ routes,
45
+ manifest: {},
46
+ publicFunctions,
47
+ checkRules: [],
48
+ setup: { gasFunction: 'apiSetup' },
49
+ client: null,
50
+ };
51
+ }
package/src/auth.mjs ADDED
@@ -0,0 +1,54 @@
1
+ // src/auth.mjs
2
+ // Verifica auth de una ruta.
3
+ // verificarAuth(ruta, request, tokenEsperado, opciones) → { ok, status? }
4
+
5
+ function leerTokenDeQuery(request) {
6
+ if (!request || !request.parameter) {
7
+ return undefined;
8
+ }
9
+ return request.parameter.token;
10
+ }
11
+
12
+ function leerTokenDeBody(request) {
13
+ if (!request || !request.postData || !request.postData.contents) {
14
+ return undefined;
15
+ }
16
+ try {
17
+ const cuerpo = JSON.parse(request.postData.contents);
18
+ return cuerpo && cuerpo.token ? cuerpo.token : undefined;
19
+ } catch {
20
+ return undefined;
21
+ }
22
+ }
23
+
24
+ export function verificarAuth(ruta, request, tokenEsperado, opciones = {}) {
25
+ const auth = ruta && ruta.auth ? String(ruta.auth) : 'public';
26
+
27
+ if (opciones.mode === 'none') {
28
+ return { ok: true };
29
+ }
30
+
31
+ if (auth === 'public') {
32
+ return { ok: true };
33
+ }
34
+
35
+ if (auth === 'protected') {
36
+ if (!tokenEsperado) {
37
+ return { ok: false, status: 401 };
38
+ }
39
+
40
+ const tokenQuery = leerTokenDeQuery(request);
41
+ if (tokenQuery && String(tokenQuery) === String(tokenEsperado)) {
42
+ return { ok: true };
43
+ }
44
+
45
+ const tokenBody = leerTokenDeBody(request);
46
+ if (tokenBody && String(tokenBody) === String(tokenEsperado)) {
47
+ return { ok: true };
48
+ }
49
+
50
+ return { ok: false, status: 401 };
51
+ }
52
+
53
+ return { ok: false, status: 401 };
54
+ }
@@ -0,0 +1,92 @@
1
+ // src/cliente.mjs
2
+ // Cliente tipado y adaptador dev/deploy para gas-api.
3
+ // Genera un método por endpoint declarado.
4
+ // Transporte: google.script.run (en GAS) o fetch(PUBLIC_GAS_API_URL) (en dev).
5
+ // El token viaja en el payload (query GET / body POST-PUT), nunca en headers.
6
+
7
+ function leerOpcion(opciones, clave, envVar) {
8
+ if (opciones && typeof opciones[clave] !== 'undefined') {
9
+ return opciones[clave];
10
+ }
11
+ return typeof process !== 'undefined' && process.env ? process.env[envVar] : undefined;
12
+ }
13
+
14
+ function esEntornoGoogleScript() {
15
+ return (
16
+ typeof globalThis !== 'undefined' &&
17
+ globalThis.google &&
18
+ globalThis.google.script &&
19
+ globalThis.google.script.run
20
+ );
21
+ }
22
+
23
+ export function crearCliente(endpoints, opciones = {}) {
24
+ const baseUrlPath = leerOpcion(opciones, 'baseUrlPath', 'PUBLIC_GAS_API_URL');
25
+ const token = leerOpcion(opciones, 'token', 'PUBLIC_GAS_API_TOKEN');
26
+ const forceHttp = opciones.forceHttp === true;
27
+
28
+ const usarGScript = !forceHttp && esEntornoGoogleScript();
29
+
30
+ if (!usarGScript && !baseUrlPath) {
31
+ throw new Error(
32
+ 'PUBLIC_GAS_API_URL no está definida: pasa baseUrlPath o define la variable de entorno PUBLIC_GAS_API_URL'
33
+ );
34
+ }
35
+
36
+ const cliente = {};
37
+
38
+ for (const ep of endpoints) {
39
+ const handlerNombre = ep.handler;
40
+ cliente[handlerNombre] = async (payload) => {
41
+ if (usarGScript) {
42
+ return new Promise((resolve, reject) => {
43
+ globalThis.google.script.run
44
+ .withSuccessHandler(resolve)
45
+ .withFailureHandler(reject)[handlerNombre](payload);
46
+ });
47
+ }
48
+
49
+ // Transporte fetch (dev / sin google.script.run)
50
+ const metodo = ep.method;
51
+ let url = `${baseUrlPath}${ep.path}`;
52
+ let cuerpo = undefined;
53
+ const cabeceras = {};
54
+
55
+ if (metodo === 'GET') {
56
+ const params = new URLSearchParams();
57
+ if (token && ep.auth === 'protected') {
58
+ params.set('token', token);
59
+ }
60
+ if (payload && typeof payload === 'object') {
61
+ for (const [k, v] of Object.entries(payload)) {
62
+ if (v !== undefined) {
63
+ params.set(k, String(v));
64
+ }
65
+ }
66
+ }
67
+ const qs = params.toString();
68
+ if (qs) {
69
+ url += '?' + qs;
70
+ }
71
+ } else {
72
+ // POST / PUT / DELETE con cuerpo
73
+ const datos = { ...payload };
74
+ if (token && ep.auth === 'protected') {
75
+ datos.token = token;
76
+ }
77
+ cuerpo = JSON.stringify(datos);
78
+ cabeceras['Content-Type'] = 'application/json';
79
+ }
80
+
81
+ const respuesta = await globalThis.fetch(url, {
82
+ method: metodo,
83
+ headers: cabeceras,
84
+ body: cuerpo,
85
+ });
86
+
87
+ return respuesta.json();
88
+ };
89
+ }
90
+
91
+ return cliente;
92
+ }
@@ -0,0 +1,16 @@
1
+ // src/composicion.mjs
2
+ // Lectura de manifest de otras extensiones vía GAS_MANIFEST.
3
+ // Los paquetes no se importan entre sí; se leen vía GAS_MANIFEST.extensions.<nombre>.manifest.
4
+
5
+ export function leeManifestExtension(GAS_MANIFEST, nombre) {
6
+ if (!GAS_MANIFEST || !GAS_MANIFEST.extensions) {
7
+ return undefined;
8
+ }
9
+
10
+ const bloque = GAS_MANIFEST.extensions[nombre];
11
+ if (!bloque || !bloque.manifest) {
12
+ return undefined;
13
+ }
14
+
15
+ return bloque.manifest;
16
+ }
@@ -0,0 +1,66 @@
1
+ // src/dispatch.mjs
2
+ // Busca una ruta declarada que coincida con method + path.
3
+ // apiDispatch(request, manifest) → ruta declarada o null.
4
+
5
+ function normalizarPath(p) {
6
+ let s = String(p);
7
+ while (s.charAt(0) === '/') {
8
+ s = s.slice(1);
9
+ }
10
+ while (s.length > 0 && s.charAt(s.length - 1) === '/') {
11
+ s = s.slice(0, -1);
12
+ }
13
+ return s;
14
+ }
15
+
16
+ function obtenerPathDeRuta(ruta) {
17
+ // Forma mapeada (Router.gs): { match: { type: 'path', value: '/api/ping' } }
18
+ if (ruta && ruta.match && typeof ruta.match.value === 'string') {
19
+ return ruta.match.value;
20
+ }
21
+ // Forma original de la extensión api: { path: '/api/ping' }
22
+ if (ruta && typeof ruta.path === 'string') {
23
+ return ruta.path;
24
+ }
25
+ return undefined;
26
+ }
27
+
28
+ export function apiDispatch(request, manifest) {
29
+ const extensiones =
30
+ manifest && manifest.extensions ? manifest.extensions : null;
31
+ if (!extensiones) {
32
+ return null;
33
+ }
34
+
35
+ const bloqueApi = extensiones.api;
36
+ if (!bloqueApi) {
37
+ return null;
38
+ }
39
+
40
+ const rutas = Array.isArray(bloqueApi.routes) ? bloqueApi.routes : [];
41
+ if (rutas.length === 0) {
42
+ return null;
43
+ }
44
+
45
+ const metodo = (request && request.method) ? String(request.method).toUpperCase() : '';
46
+ const pathInfo =
47
+ request && request.pathInfo !== undefined && request.pathInfo !== null
48
+ ? String(request.pathInfo)
49
+ : '';
50
+ const esperado = normalizarPath(pathInfo);
51
+ if (esperado === '') {
52
+ return null;
53
+ }
54
+
55
+ for (let i = 0; i < rutas.length; i++) {
56
+ const ruta = rutas[i];
57
+ if (!ruta) continue;
58
+ if (String(ruta.method).toUpperCase() !== metodo) continue;
59
+ const rutaPath = obtenerPathDeRuta(ruta);
60
+ if (rutaPath !== undefined && normalizarPath(rutaPath) === esperado) {
61
+ return ruta;
62
+ }
63
+ }
64
+
65
+ return null;
66
+ }
@@ -0,0 +1,42 @@
1
+ // src/endpoint.mjs
2
+ // Describe un endpoint declarativamente.
3
+ // endpoint('METHOD /ruta', { auth, request, response, handler })
4
+ // Devuelve { method, path, auth, request, response, handler }.
5
+
6
+ const METODOS_VALIDOS = new Set(['GET', 'POST', 'PUT', 'DELETE']);
7
+ const AUTH_VALIDOS = new Set(['public', 'protected']);
8
+
9
+ export function endpoint(methodPath, spec = {}) {
10
+ const partes = String(methodPath).trim().split(/\s+/);
11
+ const metodo = partes[0];
12
+ const rutaCruda = partes[1];
13
+
14
+ const metodoUpper = metodo.toUpperCase();
15
+
16
+ if (!METODOS_VALIDOS.has(metodoUpper)) {
17
+ throw new Error(`método inválido: '${metodo}'. Debe ser GET, POST, PUT o DELETE.`);
18
+ }
19
+
20
+ if (!rutaCruda) {
21
+ throw new Error('ruta requerida: usa el formato "METHOD /ruta".');
22
+ }
23
+
24
+ if (!rutaCruda.startsWith('/')) {
25
+ throw new Error(`ruta inválida: '${rutaCruda}'. La ruta debe empezar con '/'.`);
26
+ }
27
+
28
+ const ruta = rutaCruda;
29
+
30
+ const auth = spec.auth && AUTH_VALIDOS.has(spec.auth) ? spec.auth : (() => {
31
+ throw new Error(`auth inválido: '${spec.auth}'. Debe ser 'public' o 'protected'.`);
32
+ })();
33
+
34
+ return {
35
+ method: metodoUpper,
36
+ path: ruta,
37
+ auth,
38
+ request: spec.request,
39
+ response: spec.response,
40
+ handler: spec.handler,
41
+ };
42
+ }
@@ -0,0 +1,18 @@
1
+ // src/manifest.mjs
2
+ // Mapea las routes[] de una extensión api a la forma que consume Router.gs del base.
3
+ // {method, path, auth, handler} → {method, match: {type: 'path', value: path}, handler}
4
+
5
+ export function mapearARouter(rutas) {
6
+ if (!Array.isArray(rutas)) {
7
+ return [];
8
+ }
9
+
10
+ return rutas.map((ruta) => ({
11
+ method: ruta.method,
12
+ match: {
13
+ type: 'path',
14
+ value: ruta.path,
15
+ },
16
+ handler: ruta.handler,
17
+ }));
18
+ }
@@ -0,0 +1,30 @@
1
+ // src/response.mjs
2
+ // Construye respuestas HTTP JSON con status code real.
3
+ // responderOk(datos) → { status: 200, body: JSON }
4
+ // responderError(status, mensaje, issues?) → { status, body: JSON }
5
+
6
+ function serializar(datos) {
7
+ return JSON.stringify(datos);
8
+ }
9
+
10
+ export function responderOk(datos) {
11
+ return {
12
+ status: 200,
13
+ body: serializar({ ok: true, ...datos }),
14
+ };
15
+ }
16
+
17
+ export function responderError(status, mensaje, issues = []) {
18
+ const cuerpo = {
19
+ ok: false,
20
+ error: String(mensaje),
21
+ };
22
+ if (issues.length > 0) {
23
+ cuerpo.issues = issues;
24
+ }
25
+
26
+ return {
27
+ status,
28
+ body: serializar(cuerpo),
29
+ };
30
+ }
package/src/setup.mjs ADDED
@@ -0,0 +1,60 @@
1
+ // src/setup.mjs
2
+ // setup(ctx, config): setup de token de API.
3
+ // - Si auth.mode === 'token' y falta la Property → genera token aleatorio, lo guarda, reporta en created.
4
+ // - Si ya existe → reporta en reused (no rota).
5
+ // - dryRun → reporta que crearía sin generar nada.
6
+ // - auth mode none → sin created de token.
7
+ // Nunca imprime el token en logs de build; el usuario lo ve una vez en el reporte de setup.
8
+
9
+ const CARACTERES =
10
+ 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.';
11
+
12
+ function generarToken(longitud = 43) {
13
+ let token = '';
14
+ for (let i = 0; i < longitud; i++) {
15
+ token += CARACTERES.charAt(Math.floor(Math.random() * CARACTERES.length));
16
+ }
17
+ return token;
18
+ }
19
+
20
+ export function setup(ctx, config) {
21
+ const auth = config && config.auth ? config.auth : { mode: 'none' };
22
+ const reporte = {
23
+ created: [],
24
+ reused: [],
25
+ properties: {},
26
+ };
27
+
28
+ if (!auth || auth.mode !== 'token') {
29
+ return reporte;
30
+ }
31
+
32
+ const property = auth.property || 'API_TOKEN';
33
+ const propiedades = ctx && ctx.properties ? ctx.properties : {};
34
+ const tokenExistente = propiedades.getItem ? propiedades.getItem(property) : undefined;
35
+
36
+ if (ctx && ctx.dryRun === true) {
37
+ if (!tokenExistente) {
38
+ reporte.created.push(property);
39
+ reporte.properties[property] = '<se generaría en corrida real>';
40
+ } else {
41
+ reporte.reused.push(property);
42
+ }
43
+ return reporte;
44
+ }
45
+
46
+ if (tokenExistente) {
47
+ reporte.reused.push(property);
48
+ reporte.properties[property] = tokenExistente;
49
+ return reporte;
50
+ }
51
+
52
+ const tokenNuevo = generarToken();
53
+ if (propiedades.setItem) {
54
+ propiedades.setItem(property, tokenNuevo);
55
+ }
56
+ reporte.created.push(property);
57
+ reporte.properties[property] = tokenNuevo;
58
+
59
+ return reporte;
60
+ }
@@ -0,0 +1,19 @@
1
+ // src/validate.mjs
2
+ // Serializa un ZodError a una forma usable en respuestas HTTP 400.
3
+ // { ok: false, error, issues: [{ path, message }] } en español.
4
+
5
+ export function serializeZodError(zodError) {
6
+ const issues = (zodError.issues || []).map((issue) => {
7
+ const path = issue.path.length > 0 ? issue.path.join('.') : '<raíz>';
8
+ return {
9
+ path,
10
+ message: issue.message || 'valor inválido',
11
+ };
12
+ });
13
+
14
+ return {
15
+ ok: false,
16
+ error: 'error de validación',
17
+ issues,
18
+ };
19
+ }