libreria-astro-lefebvre 0.0.35 → 0.0.38

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.
@@ -0,0 +1,174 @@
1
+ /**
2
+ * Limbo Integration Module for libreria-astro-lefebvre
3
+ *
4
+ * Este módulo gestiona la inicialización y configuración de limbo-component
5
+ * para ser usado en cualquier portal que consuma esta librería.
6
+ */
7
+
8
+ export interface LimboConfig {
9
+ publicKey: string;
10
+ prod?: boolean;
11
+ selector?: string;
12
+ defaultReturnType?: 'url' | 'assetId' | 'object' | 'json' | 'base64';
13
+ sizeModal?: 'small' | 'medium' | 'large' | 'xlarge' | 'fullscreen';
14
+ onSelect?: (data: any) => void;
15
+ onError?: (error: Error) => void;
16
+ }
17
+
18
+ export interface LimboInitOptions extends LimboConfig {
19
+ autoInit?: boolean;
20
+ }
21
+
22
+ /**
23
+ * Genera el script de inicialización de Limbo como string
24
+ * para ser inyectado en el HTML
25
+ */
26
+ export function generateLimboInitScript(config: LimboConfig): string {
27
+ const {
28
+ publicKey,
29
+ prod = false,
30
+ selector = '.js-limbo',
31
+ defaultReturnType = 'json',
32
+ sizeModal = 'xlarge'
33
+ } = config;
34
+
35
+ // URL del proxy para evitar CORS (usa endpoint local del portal)
36
+ // El proxy está en /api/limbo-token del portal que consume la librería
37
+ const tokenProxyUrl = '/api/limbo-token';
38
+
39
+ return `
40
+ (function() {
41
+ // Estado del token
42
+ var cachedToken = null;
43
+ var tokenExpiry = null;
44
+
45
+ // Función para obtener token JWT (usa proxy local para evitar CORS)
46
+ async function getToken() {
47
+ // Si tenemos un token válido en caché, usarlo
48
+ if (cachedToken && tokenExpiry && Date.now() < tokenExpiry) {
49
+ return cachedToken;
50
+ }
51
+
52
+ try {
53
+ // Usamos el proxy local para evitar problemas de CORS
54
+ // Solo enviamos public_key - NO se requiere api_key
55
+ var response = await fetch('${tokenProxyUrl}', {
56
+ method: 'POST',
57
+ headers: {
58
+ 'Content-Type': 'application/json',
59
+ },
60
+ body: JSON.stringify({
61
+ public_key: '${publicKey}'
62
+ })
63
+ });
64
+
65
+ if (!response.ok) {
66
+ var errorData = await response.json().catch(function() { return {}; });
67
+ throw new Error('Error obteniendo token: ' + response.status + ' - ' + (errorData.error || ''));
68
+ }
69
+
70
+ var data = await response.json();
71
+ cachedToken = data.token;
72
+ // Guardar expiración con 30 segundos de margen
73
+ tokenExpiry = Date.now() + ((data.expires_in || 3600) * 1000) - 30000;
74
+ console.log('[Limbo] Token JWT obtenido correctamente');
75
+ return cachedToken;
76
+ } catch (error) {
77
+ console.error('[Limbo] Error en tokenProvider:', error);
78
+ throw error;
79
+ }
80
+ }
81
+
82
+ // Esperamos a que Limbo esté disponible
83
+ function initLimbo() {
84
+ if (typeof Limbo === 'undefined') {
85
+ console.warn('[Limbo] Limbo no está cargado. Reintentando...');
86
+ setTimeout(initLimbo, 100);
87
+ return;
88
+ }
89
+
90
+ console.log('[Limbo] Inicializando integración con Page Builder...');
91
+
92
+ // Configurar Limbo globalmente con tokenProvider como función
93
+ // IMPORTANTE: tokenProvider va en el nivel superior, no dentro de auth
94
+ Limbo.configure({
95
+ prod: ${prod},
96
+ publicKey: '${publicKey}',
97
+ authMode: 'jwt',
98
+ tokenProvider: getToken,
99
+ modal: {
100
+ size: '${sizeModal}'
101
+ }
102
+ });
103
+
104
+ // Configurar auto-inputs para detectar elementos con el selector
105
+ Limbo.configureAutoInputs({
106
+ selector: '${selector}',
107
+ buttonText: 'Seleccionar imagen',
108
+ returnType: '${defaultReturnType}',
109
+
110
+ // Parsear configuración del input desde datasets
111
+ parseInputConfig: function(input) {
112
+ var config = {};
113
+
114
+ // Parsear mandatoryCrops si existe
115
+ if (input.dataset.mandatorycrops) {
116
+ try {
117
+ config.mandatoryCrops = JSON.parse(input.dataset.mandatorycrops);
118
+ } catch (e) {
119
+ console.warn('[Limbo] Error parseando mandatoryCrops:', e);
120
+ }
121
+ }
122
+
123
+ // Parsear returnType específico del input
124
+ if (input.dataset.returntype) {
125
+ config.returnType = input.dataset.returntype;
126
+ }
127
+
128
+ // Parsear modo UI
129
+ if (input.dataset.modeui) {
130
+ config.modeUI = input.dataset.modeui;
131
+ }
132
+
133
+ return config;
134
+ }
135
+ });
136
+
137
+ console.log('[Limbo] Integración configurada. Buscando inputs con selector: ${selector}');
138
+ }
139
+
140
+ // Iniciar cuando el DOM esté listo
141
+ if (document.readyState === 'loading') {
142
+ document.addEventListener('DOMContentLoaded', initLimbo);
143
+ } else {
144
+ initLimbo();
145
+ }
146
+ })();
147
+ `;
148
+ }
149
+
150
+ /**
151
+ * Genera las URLs de los assets de Limbo (CSS y JS)
152
+ */
153
+ export function getLimboAssetUrls(options: { prod?: boolean; version?: string } = {}) {
154
+ const { prod = false, version = 'latest' } = options;
155
+
156
+ // En producción, usar CDN de npm o URL de producción
157
+ if (prod) {
158
+ return {
159
+ css: `https://unpkg.com/limbo-component@${version}/dist/limbo.css`,
160
+ js: `https://unpkg.com/limbo-component@${version}/dist/limbo.min.js`
161
+ };
162
+ }
163
+
164
+ // En desarrollo, usar el build local (npm link)
165
+ return {
166
+ css: '/node_modules/limbo-component/dist/limbo.css',
167
+ js: '/node_modules/limbo-component/dist/limbo.min.js'
168
+ };
169
+ }
170
+
171
+ export default {
172
+ generateLimboInitScript,
173
+ getLimboAssetUrls
174
+ };