astro-gas-api 0.0.0-stage → 0.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 +145 -2
- package/index.mjs +15 -0
- package/package.json +19 -4
- package/src/api.mjs +53 -0
- package/src/auth.mjs +54 -0
- package/src/cliente.mjs +92 -0
- package/src/composicion.mjs +16 -0
- package/src/dispatch.mjs +66 -0
- package/src/endpoint.mjs +42 -0
- package/src/manifest.mjs +18 -0
- package/src/response.mjs +30 -0
- package/src/setup.mjs +60 -0
- package/src/validate.mjs +19 -0
package/README.md
CHANGED
|
@@ -1,3 +1,146 @@
|
|
|
1
|
-
#
|
|
1
|
+
# astro-gas-api
|
|
2
2
|
|
|
3
|
-
|
|
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 (`astro-to-appsscript`), expone un cliente tipado con adaptador dev/deploy, y compone con `astro-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
|
+
- `astro-to-appsscript@0.5.0` — contrato `GasExtension` con F3 (hook de despacho en `Router.gs`) y F4 (setup) obligatorios.
|
|
10
|
+
|
|
11
|
+
## Instalación
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
npm install --save-dev astro-gas-api
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Contrato `GasExtension` — factory `api()`
|
|
18
|
+
|
|
19
|
+
```js
|
|
20
|
+
import api, { endpoint } from 'astro-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
|
+
## Autenticación
|
|
75
|
+
|
|
76
|
+
`astro-gas-api` no implementa OAuth ni sesiones de Google. El contrato de auth es el que declares:
|
|
77
|
+
|
|
78
|
+
- `auth: 'public'` — sin chequeo de token.
|
|
79
|
+
- `auth: 'protected'` — exige el token **en el payload**:
|
|
80
|
+
- `GET`: query `?token=...`
|
|
81
|
+
- `POST/PUT/DELETE`: campo `token` del body JSON
|
|
82
|
+
|
|
83
|
+
**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.
|
|
84
|
+
|
|
85
|
+
## Cliente tipado y adaptador dev/deploy
|
|
86
|
+
|
|
87
|
+
`crearCliente(endpoints, opciones)` genera un método por endpoint declarado:
|
|
88
|
+
|
|
89
|
+
```js
|
|
90
|
+
import { crearCliente, endpoint } from 'astro-gas-api';
|
|
91
|
+
|
|
92
|
+
const endpoints = [
|
|
93
|
+
endpoint('GET /ping', { auth: 'public', response: {} }),
|
|
94
|
+
endpoint('POST /items', { auth: 'protected', request: {}, response: {} }),
|
|
95
|
+
];
|
|
96
|
+
|
|
97
|
+
const api = crearCliente(endpoints, {
|
|
98
|
+
baseUrlPath: 'https://tu-app.com/api', // o env PUBLIC_GAS_API_URL
|
|
99
|
+
token: 'MI_TOKEN_SECRETO', // o env PUBLIC_GAS_API_TOKEN
|
|
100
|
+
forceHttp: false, // true para forzar fetch aunque exista google.script.run
|
|
101
|
+
});
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
### Transporte
|
|
105
|
+
|
|
106
|
+
- **En GAS (producción):** usa `google.script.run` automáticamente (cero fetch, cero headers).
|
|
107
|
+
- **En dev:** usa `fetch(PUBLIC_GAS_API_URL + path)`. Requiere `PUBLIC_GAS_API_URL` definida; de lo contrario lanza error nombrando la variable.
|
|
108
|
+
|
|
109
|
+
### Token en el cliente
|
|
110
|
+
|
|
111
|
+
- Endpoint `public`: no envía token.
|
|
112
|
+
- Endpoint `protected`: envía el token en query (GET) o en el body JSON (POST/PUT/DELETE). Nunca en headers.
|
|
113
|
+
- El token **no aparece en logs ni en errores**.
|
|
114
|
+
|
|
115
|
+
## Composición con otros paquetes
|
|
116
|
+
|
|
117
|
+
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`).
|
|
118
|
+
|
|
119
|
+
Ejemplo: un endpoint de `astro-gas-api` que verifica si `astro-gas-drive` está instalado:
|
|
120
|
+
|
|
121
|
+
```js
|
|
122
|
+
handler: (payload, ctx) => {
|
|
123
|
+
const driveConfig = GAS_MANIFEST.extensions.drive?.manifest;
|
|
124
|
+
if (!driveConfig) {
|
|
125
|
+
return { ok: false, error: 'astro-gas-drive no está instalado' };
|
|
126
|
+
}
|
|
127
|
+
// usar driveConfig.folder, driveConfig.allowedMimes, etc.
|
|
128
|
+
}
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
Compatible con `astro-gas-drive` y `astro-gas-sheets` (publicados por separado).
|
|
132
|
+
|
|
133
|
+
## Límites de Apps Script
|
|
134
|
+
|
|
135
|
+
- **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.
|
|
136
|
+
- **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.
|
|
137
|
+
- **Timeouts:** `google.script.run` y `fetch` tienen sus propios timeouts. Diseña endpoints que respondan rápido.
|
|
138
|
+
- **Concurrencia:** GAS ejecuta los endpoints de forma secuencial por usuario; no asumas paralelismo.
|
|
139
|
+
|
|
140
|
+
## Ejemplo completo
|
|
141
|
+
|
|
142
|
+
Véase `test/f6/` para tests de ejemplo y el comportamiento esperado.
|
|
143
|
+
|
|
144
|
+
## Licencia
|
|
145
|
+
|
|
146
|
+
MIT
|
package/index.mjs
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// index.mjs — punto de entrada del paquete astro-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,21 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "astro-gas-api",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.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
|
+
"engines": {
|
|
10
|
+
"node": ">=20"
|
|
11
|
+
},
|
|
12
|
+
"peerDependencies": {
|
|
13
|
+
"astro-to-appsscript": "0.5.0"
|
|
14
|
+
},
|
|
15
|
+
"dependencies": {
|
|
16
|
+
"zod": "^3.24.0"
|
|
17
|
+
},
|
|
18
|
+
"scripts": {
|
|
19
|
+
"test": "node --test 'test/**/*.test.mjs'"
|
|
20
|
+
}
|
|
21
|
+
}
|
package/src/api.mjs
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// src/api.mjs
|
|
2
|
+
// Factory de extensión astro-gas-api.
|
|
3
|
+
// Valida auth.mode, unicidad de method+path y devuelve la forma del contrato GasExtension.
|
|
4
|
+
|
|
5
|
+
import { z } from 'zod';
|
|
6
|
+
|
|
7
|
+
const AUTH_MODES = new Set(['token', 'none']);
|
|
8
|
+
|
|
9
|
+
export function api(config = {}) {
|
|
10
|
+
const auth = config.auth || { mode: 'none' };
|
|
11
|
+
|
|
12
|
+
if (!AUTH_MODES.has(auth.mode)) {
|
|
13
|
+
throw new Error(`auth.mode inválido: '${auth.mode}'. Debe ser 'token' o 'none'.`);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const endpoints = Array.isArray(config.endpoints) ? config.endpoints : [];
|
|
17
|
+
const routes = [];
|
|
18
|
+
const seen = new Set();
|
|
19
|
+
|
|
20
|
+
for (const ep of endpoints) {
|
|
21
|
+
const key = `${ep.method}|${ep.path}`;
|
|
22
|
+
if (seen.has(key)) {
|
|
23
|
+
throw new Error(`ruta duplicada: ${ep.method} ${ep.path} (ya declarada previamente)`);
|
|
24
|
+
}
|
|
25
|
+
seen.add(key);
|
|
26
|
+
routes.push({
|
|
27
|
+
method: ep.method,
|
|
28
|
+
path: ep.path,
|
|
29
|
+
auth: ep.auth,
|
|
30
|
+
handler: ep.handler,
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const publicFunctions = ['apiSetup'];
|
|
35
|
+
for (const ep of endpoints) {
|
|
36
|
+
if (ep.handler) {
|
|
37
|
+
publicFunctions.push(ep.handler);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
return {
|
|
42
|
+
name: 'api',
|
|
43
|
+
contractVersion: 1,
|
|
44
|
+
config: config.config || {},
|
|
45
|
+
runtime: [],
|
|
46
|
+
routes,
|
|
47
|
+
manifest: {},
|
|
48
|
+
publicFunctions,
|
|
49
|
+
checkRules: [],
|
|
50
|
+
setup: { gasFunction: 'apiSetup' },
|
|
51
|
+
client: null,
|
|
52
|
+
};
|
|
53
|
+
}
|
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
|
+
}
|
package/src/cliente.mjs
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
// src/cliente.mjs
|
|
2
|
+
// Cliente tipado y adaptador dev/deploy para astro-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
|
+
}
|
package/src/dispatch.mjs
ADDED
|
@@ -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
|
+
}
|
package/src/endpoint.mjs
ADDED
|
@@ -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
|
+
}
|
package/src/manifest.mjs
ADDED
|
@@ -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
|
+
}
|
package/src/response.mjs
ADDED
|
@@ -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
|
+
}
|
package/src/validate.mjs
ADDED
|
@@ -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
|
+
}
|