valtech-components 4.0.33 → 4.0.35
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/esm2022/lib/components/organisms/edit-org-modal/edit-org-modal.component.mjs +41 -4
- package/esm2022/lib/components/organisms/edit-org-modal/edit-org-modal.i18n.mjs +5 -1
- package/esm2022/lib/components/organisms/organization-view/organization-view.component.mjs +8 -5
- package/esm2022/lib/components/organisms/switch-org-modal/switch-org-modal.component.mjs +18 -9
- package/esm2022/lib/services/auth/auth.service.mjs +28 -20
- package/esm2022/lib/services/auth/oauth-callback.component.mjs +13 -1
- package/esm2022/lib/services/auth/oauth.service.mjs +83 -8
- package/esm2022/lib/services/auth/storage.service.mjs +7 -11
- package/esm2022/lib/services/auth/types.mjs +1 -1
- package/esm2022/lib/services/link-processor.service.mjs +27 -5
- package/esm2022/lib/services/org/types.mjs +1 -1
- package/esm2022/lib/services/requests/request-visibility.mjs +41 -0
- package/esm2022/lib/services/requests/types.mjs +1 -1
- package/esm2022/lib/version.mjs +2 -2
- package/esm2022/public-api.mjs +2 -1
- package/fesm2022/valtech-components.mjs +263 -56
- package/fesm2022/valtech-components.mjs.map +1 -1
- package/lib/components/atoms/rights-footer/rights-footer.component.d.ts +2 -2
- package/lib/components/molecules/username-input/username-input.component.d.ts +1 -1
- package/lib/components/organisms/article/article.component.d.ts +3 -3
- package/lib/components/organisms/edit-org-modal/edit-org-modal.component.d.ts +2 -0
- package/lib/components/organisms/landing-steps/landing-steps.component.d.ts +1 -1
- package/lib/components/organisms/notification-preferences-view/notification-preferences-view.component.d.ts +1 -1
- package/lib/components/organisms/organization-view/organization-view.component.d.ts +2 -0
- package/lib/components/organisms/switch-org-modal/switch-org-modal.component.d.ts +5 -0
- package/lib/services/auth/oauth-callback.component.d.ts +6 -0
- package/lib/services/auth/oauth.service.d.ts +28 -0
- package/lib/services/auth/storage.service.d.ts +1 -1
- package/lib/services/auth/types.d.ts +6 -0
- package/lib/services/link-processor.service.d.ts +12 -0
- package/lib/services/org/types.d.ts +2 -0
- package/lib/services/requests/request-visibility.d.ts +35 -0
- package/lib/services/requests/types.d.ts +7 -2
- package/lib/version.d.ts +1 -1
- package/package.json +1 -1
- package/public-api.d.ts +1 -0
- package/src/lib/services/firebase/firebase-messaging-sw.js +145 -0
|
@@ -39,11 +39,11 @@ export declare class RightsFooterComponent {
|
|
|
39
39
|
/**
|
|
40
40
|
* Computed helper for align prop in template.
|
|
41
41
|
*/
|
|
42
|
-
propsAlign: import("@angular/core").Signal<"
|
|
42
|
+
propsAlign: import("@angular/core").Signal<"center" | "left" | "right">;
|
|
43
43
|
/**
|
|
44
44
|
* Computed helper for color prop in template.
|
|
45
45
|
*/
|
|
46
|
-
propsColor: import("@angular/core").Signal<"
|
|
46
|
+
propsColor: import("@angular/core").Signal<"light" | "dark" | "medium" | "success" | "warning" | "danger" | "primary" | "secondary" | "tertiary">;
|
|
47
47
|
/**
|
|
48
48
|
* Computed helper for withMargin prop in template.
|
|
49
49
|
*/
|
|
@@ -35,7 +35,7 @@ export declare class UsernameInputComponent implements OnInit, OnDestroy {
|
|
|
35
35
|
availabilityStatus: import("@angular/core").WritableSignal<UsernameAvailabilityStatus>;
|
|
36
36
|
hasError: import("@angular/core").Signal<boolean>;
|
|
37
37
|
showStatusMessage: import("@angular/core").Signal<boolean>;
|
|
38
|
-
statusColor: import("@angular/core").Signal<"
|
|
38
|
+
statusColor: import("@angular/core").Signal<"danger" | "success">;
|
|
39
39
|
statusMessage: import("@angular/core").Signal<"" | "Username disponible" | "Username ya está en uso">;
|
|
40
40
|
errorMessage: import("@angular/core").Signal<string>;
|
|
41
41
|
ngOnInit(): void;
|
|
@@ -57,7 +57,7 @@ export declare class ArticleComponent implements OnInit {
|
|
|
57
57
|
linkConfig?: import("valtech-components").LinkProcessorConfig;
|
|
58
58
|
allowPartialBold?: boolean;
|
|
59
59
|
authorColor?: import("@ionic/core").Color;
|
|
60
|
-
alignment?: "
|
|
60
|
+
alignment?: "center" | "left" | "right";
|
|
61
61
|
showQuoteMark?: boolean;
|
|
62
62
|
};
|
|
63
63
|
getHighlightTextProps(element: ArticleElement): {
|
|
@@ -76,7 +76,7 @@ export declare class ArticleComponent implements OnInit {
|
|
|
76
76
|
getHighlightColor(element: ArticleElement): string;
|
|
77
77
|
getButtonProps(element: ArticleElement): {
|
|
78
78
|
actionType?: import("valtech-components").ActionType;
|
|
79
|
-
expand?: "
|
|
79
|
+
expand?: "block" | "full";
|
|
80
80
|
link?: string;
|
|
81
81
|
href?: string;
|
|
82
82
|
routerLink?: string | any[];
|
|
@@ -92,7 +92,7 @@ export declare class ArticleComponent implements OnInit {
|
|
|
92
92
|
icon?: import("valtech-components").IconMetada;
|
|
93
93
|
shape?: "round";
|
|
94
94
|
size?: "default" | "small" | "large";
|
|
95
|
-
fill?: "default" | "
|
|
95
|
+
fill?: "default" | "outline" | "clear" | "solid";
|
|
96
96
|
type: "reset" | "submit" | "button";
|
|
97
97
|
token?: string;
|
|
98
98
|
ref?: any;
|
|
@@ -37,6 +37,7 @@ export declare class EditOrgModalComponent implements OnInit {
|
|
|
37
37
|
i18nNamespace: string;
|
|
38
38
|
private readonly saving;
|
|
39
39
|
protected readonly logoUrl: WritableSignal<string>;
|
|
40
|
+
protected readonly removingLogo: WritableSignal<boolean>;
|
|
40
41
|
readonly formMeta: WritableSignal<FormMetadata>;
|
|
41
42
|
protected readonly orgInitials: import("@angular/core").Signal<string>;
|
|
42
43
|
constructor();
|
|
@@ -46,6 +47,7 @@ export declare class EditOrgModalComponent implements OnInit {
|
|
|
46
47
|
onFormSubmit(event: FormSubmit): void;
|
|
47
48
|
private save;
|
|
48
49
|
onLogoUploaded(result: AvatarUploadResult): Promise<void>;
|
|
50
|
+
onRemoveLogo(): Promise<void>;
|
|
49
51
|
dismiss(): void;
|
|
50
52
|
t(key: string): string;
|
|
51
53
|
static ɵfac: i0.ɵɵFactoryDeclaration<EditOrgModalComponent, never>;
|
|
@@ -4,7 +4,7 @@ export declare class LandingStepsComponent {
|
|
|
4
4
|
private readonly props_;
|
|
5
5
|
set props(v: LandingStepsMetadata);
|
|
6
6
|
readonly p: import("@angular/core").Signal<LandingStepsMetadata>;
|
|
7
|
-
readonly cols: import("@angular/core").Signal<
|
|
7
|
+
readonly cols: import("@angular/core").Signal<4 | 2 | 3>;
|
|
8
8
|
readonly accentColor: import("@angular/core").Signal<string>;
|
|
9
9
|
static ɵfac: i0.ɵɵFactoryDeclaration<LandingStepsComponent, never>;
|
|
10
10
|
static ɵcmp: i0.ɵɵComponentDeclaration<LandingStepsComponent, "val-landing-steps", never, { "props": { "alias": "props"; "required": false; }; }, {}, never, never, true, never>;
|
|
@@ -90,7 +90,7 @@ export declare class NotificationPreferencesViewComponent implements OnInit, OnD
|
|
|
90
90
|
readonly busyLabel: import("@angular/core").Signal<string>;
|
|
91
91
|
readonly contextMessage: import("@angular/core").Signal<string>;
|
|
92
92
|
readonly alertVariant: import("@angular/core").Signal<"warning" | "danger" | "info">;
|
|
93
|
-
readonly alertIcon: import("@angular/core").Signal<"
|
|
93
|
+
readonly alertIcon: import("@angular/core").Signal<"close-circle-outline" | "alert-circle-outline">;
|
|
94
94
|
readonly toggleProps: import("@angular/core").Signal<ToggleInputMetadata>;
|
|
95
95
|
readonly retryButtonProps: import("@angular/core").Signal<Partial<ButtonMetadata>>;
|
|
96
96
|
readonly tokenPreview: import("@angular/core").Signal<string>;
|
|
@@ -54,6 +54,8 @@ export declare class OrganizationViewComponent {
|
|
|
54
54
|
/** Namespace i18n resuelto (capturado para llamadas no-reactivas). */
|
|
55
55
|
private get ns();
|
|
56
56
|
readonly org: import("@angular/core").WritableSignal<Organization>;
|
|
57
|
+
/** Logo de org que falló al cargar → oculta el bloque (cae a la card sin logo). */
|
|
58
|
+
readonly logoFailed: import("@angular/core").WritableSignal<boolean>;
|
|
57
59
|
readonly loading: import("@angular/core").WritableSignal<boolean>;
|
|
58
60
|
readonly leaving: import("@angular/core").WritableSignal<boolean>;
|
|
59
61
|
readonly permissionsOpen: import("@angular/core").WritableSignal<boolean>;
|
|
@@ -37,6 +37,11 @@ export declare class SwitchOrgModalComponent {
|
|
|
37
37
|
readonly query: import("@angular/core").WritableSignal<string>;
|
|
38
38
|
readonly switchingId: import("@angular/core").WritableSignal<string>;
|
|
39
39
|
protected readonly user: import("@angular/core").Signal<import("valtech-components").AuthUser>;
|
|
40
|
+
/** Avatar de usuario que falló al cargar → cae a iniciales. */
|
|
41
|
+
protected readonly userAvatarFailed: import("@angular/core").WritableSignal<boolean>;
|
|
42
|
+
/** IDs de orgs cuyo logo falló al cargar → caen al ícono business-outline. */
|
|
43
|
+
protected readonly failedLogos: import("@angular/core").WritableSignal<Set<string>>;
|
|
44
|
+
protected onLogoError(orgId: string): void;
|
|
40
45
|
protected readonly userInitials: import("@angular/core").Signal<string>;
|
|
41
46
|
readonly activeOrgId: import("@angular/core").Signal<string>;
|
|
42
47
|
readonly filteredOrgs: import("@angular/core").Signal<Organization[]>;
|
|
@@ -25,6 +25,12 @@ import * as i0 from "@angular/core";
|
|
|
25
25
|
*/
|
|
26
26
|
export declare class OAuthCallbackComponent implements OnInit {
|
|
27
27
|
message: string;
|
|
28
|
+
/**
|
|
29
|
+
* Nonce que el opener generó y pasó por el flujo (round-trip backend). Se
|
|
30
|
+
* reenvía al opener en cada mensaje para que verifique el origen del callback
|
|
31
|
+
* y rechace un oauth_callback_data forjado en localStorage por XSS (M-07).
|
|
32
|
+
*/
|
|
33
|
+
private clientNonce;
|
|
28
34
|
ngOnInit(): void;
|
|
29
35
|
private processCallback;
|
|
30
36
|
private sendToParent;
|
|
@@ -44,6 +44,13 @@ export declare class OAuthService {
|
|
|
44
44
|
private popup;
|
|
45
45
|
private messageHandler;
|
|
46
46
|
private checkClosedInterval;
|
|
47
|
+
/**
|
|
48
|
+
* Nonce del flujo OAuth en curso (M-07). Vive SOLO en memoria — un XSS no lo
|
|
49
|
+
* puede leer de localStorage/sessionStorage. Viaja al backend (client_nonce),
|
|
50
|
+
* vuelve en el callback, y se verifica acá → rechaza un oauth_callback_data
|
|
51
|
+
* forjado por XSS.
|
|
52
|
+
*/
|
|
53
|
+
private expectedNonce;
|
|
47
54
|
constructor(config: ValtechAuthConfig | null, http: HttpClient, ngZone: NgZone);
|
|
48
55
|
/**
|
|
49
56
|
* Inicia flujo OAuth en popup.
|
|
@@ -94,6 +101,27 @@ export declare class OAuthService {
|
|
|
94
101
|
* Limpia recursos del popup.
|
|
95
102
|
*/
|
|
96
103
|
private cleanup;
|
|
104
|
+
/**
|
|
105
|
+
* Genera un nonce aleatorio (CSPRNG) url-safe para el flujo OAuth (M-07).
|
|
106
|
+
*/
|
|
107
|
+
private generateNonce;
|
|
108
|
+
/**
|
|
109
|
+
* Verifica que el callback traiga el nonce del flujo actual (M-07).
|
|
110
|
+
*
|
|
111
|
+
* Estricto: si el opener generó un nonce (siempre, en clientes nuevos) exige
|
|
112
|
+
* que el callback lo traiga y coincida. Un payload forjado en localStorage por
|
|
113
|
+
* XSS no conoce el nonce (vive solo en memoria) → se rechaza.
|
|
114
|
+
*
|
|
115
|
+
* ⚠️ Requiere que el backend ya eche `client_nonce` en el callback. Deploy:
|
|
116
|
+
* backend ANTES que el frontend, si no este check rechaza callbacks legítimos
|
|
117
|
+
* (sin nonce) durante la ventana de transición.
|
|
118
|
+
*/
|
|
119
|
+
private isNonceValid;
|
|
120
|
+
/**
|
|
121
|
+
* Valida la forma del payload del callback (M-07): debe ser un error o tokens
|
|
122
|
+
* como objeto. Bloquea inyecciones malformadas (primitivos, shapes basura).
|
|
123
|
+
*/
|
|
124
|
+
private isCallbackShapeValid;
|
|
97
125
|
static ɵfac: i0.ɵɵFactoryDeclaration<OAuthService, [{ optional: true; }, null, null]>;
|
|
98
126
|
static ɵprov: i0.ɵɵInjectableDeclaration<OAuthService>;
|
|
99
127
|
}
|
|
@@ -852,6 +852,12 @@ export interface OAuthCallbackData {
|
|
|
852
852
|
tokens?: OAuthResult;
|
|
853
853
|
/** Error (si falló) */
|
|
854
854
|
error?: OAuthError;
|
|
855
|
+
/**
|
|
856
|
+
* Nonce del opener (M-07). El popup lo recibe del backend (round-trip por el
|
|
857
|
+
* OAuthState firmado) y lo reenvía; el opener lo verifica contra el que generó
|
|
858
|
+
* en memoria → rechaza un oauth_callback_data forjado en localStorage por XSS.
|
|
859
|
+
*/
|
|
860
|
+
nonce?: string;
|
|
855
861
|
}
|
|
856
862
|
/**
|
|
857
863
|
* Proveedor OAuth vinculado al usuario.
|
|
@@ -65,6 +65,18 @@ export declare class LinkProcessorService {
|
|
|
65
65
|
* ```
|
|
66
66
|
*/
|
|
67
67
|
processLinks(text: string, config?: LinkProcessorConfig): SafeHtml | string;
|
|
68
|
+
/**
|
|
69
|
+
* Devuelve un valor seguro para el atributo href. Como processLinks usa
|
|
70
|
+
* bypassSecurityTrustHtml (desactiva la sanitización automática de Angular),
|
|
71
|
+
* cada URL se valida explícitamente: el sanitizador de Angular neutraliza
|
|
72
|
+
* esquemas peligrosos (javascript:, data:, vbscript:) prefijándolos con
|
|
73
|
+
* `unsafe:`, y luego se escapa el resultado para el contexto de atributo —
|
|
74
|
+
* evitando que una URL como `[x](javascript:alert(1))` o `http://a" onx="..."`
|
|
75
|
+
* inyecte script o atributos.
|
|
76
|
+
*/
|
|
77
|
+
private safeHref;
|
|
78
|
+
/** Escapa los caracteres especiales de HTML (texto y valores de atributo). */
|
|
79
|
+
private escapeHtml;
|
|
68
80
|
/**
|
|
69
81
|
* Detecta si un texto contiene enlaces (URLs, rutas internas o enlaces Markdown).
|
|
70
82
|
*
|
|
@@ -31,6 +31,8 @@ export interface UpdateOrgRequest {
|
|
|
31
31
|
name?: string;
|
|
32
32
|
description?: string;
|
|
33
33
|
logoUrl?: string;
|
|
34
|
+
/** Borra el logo de la org. Distinto de logoUrl vacío (= "no cambiar"). */
|
|
35
|
+
clearLogo?: boolean;
|
|
34
36
|
}
|
|
35
37
|
export interface InviteUserRequest {
|
|
36
38
|
email?: string;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { RequestTypeConfig } from './types';
|
|
2
|
+
/**
|
|
3
|
+
* Contexto del viewer para decidir qué tipos de solicitud puede ver/enviar.
|
|
4
|
+
* Lo arma la app desde su estado de auth (AuthService).
|
|
5
|
+
*/
|
|
6
|
+
export interface RequestViewerContext {
|
|
7
|
+
/** Hay sesión activa. */
|
|
8
|
+
isAuthenticated: boolean;
|
|
9
|
+
/**
|
|
10
|
+
* Usuario activo/verificado (claim `verified` del token = Status ACTIVE).
|
|
11
|
+
* Solo relevante si isAuthenticated. Si se omite, se asume verificado
|
|
12
|
+
* (en la práctica el signin solo emite tokens a cuentas ACTIVE).
|
|
13
|
+
*/
|
|
14
|
+
isVerified?: boolean;
|
|
15
|
+
/** Org activa del usuario (para tipos ORG/INTERNAL). */
|
|
16
|
+
activeOrg?: string;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* ¿Este viewer puede ENVIAR una solicitud de este tipo? Espeja el gate
|
|
20
|
+
* server-side (`backend/.../request: submissionTargetOrg`). Es solo UX — el
|
|
21
|
+
* backend siempre valida —, pero evita que cada app reimplemente (mal) el filtro:
|
|
22
|
+
*
|
|
23
|
+
* - PUBLIC → cualquiera (anónimo solo si allowAnonymous).
|
|
24
|
+
* - AUTHENTICATED → logueado + verificado (cross-org).
|
|
25
|
+
* - ORG/INTERNAL → miembro de la org dueña (activeOrg === type.orgId).
|
|
26
|
+
*/
|
|
27
|
+
export declare function canSubmitRequestType(type: RequestTypeConfig, ctx: RequestViewerContext): boolean;
|
|
28
|
+
/** Filtra el catálogo a los tipos que el viewer puede enviar. */
|
|
29
|
+
export declare function selectableRequestTypes(types: RequestTypeConfig[], ctx: RequestViewerContext): RequestTypeConfig[];
|
|
30
|
+
/**
|
|
31
|
+
* Modo de envío a usar: `'anonymous'` solo para tipos PUBLIC + allowAnonymous sin
|
|
32
|
+
* sesión; en el resto `'authenticated'`. Mapea a
|
|
33
|
+
* `RequestService.createAnonymousRequest` vs `createRequest`.
|
|
34
|
+
*/
|
|
35
|
+
export declare function requestSubmitMode(type: RequestTypeConfig, ctx: RequestViewerContext): 'anonymous' | 'authenticated';
|
|
@@ -49,7 +49,7 @@ export interface FieldSchemaDef {
|
|
|
49
49
|
order: number;
|
|
50
50
|
}
|
|
51
51
|
/** Quién puede leer un tipo de solicitud (y sus solicitudes públicas). */
|
|
52
|
-
export type RequestVisibility = 'PUBLIC' | 'ORG' | 'INTERNAL';
|
|
52
|
+
export type RequestVisibility = 'PUBLIC' | 'AUTHENTICATED' | 'ORG' | 'INTERNAL';
|
|
53
53
|
export interface RequestTypeConfig {
|
|
54
54
|
typeId: string;
|
|
55
55
|
appId: string;
|
|
@@ -58,7 +58,12 @@ export interface RequestTypeConfig {
|
|
|
58
58
|
labelEn: string;
|
|
59
59
|
fieldSchema: FieldSchemaDef[];
|
|
60
60
|
allowAnonymous: boolean;
|
|
61
|
-
/**
|
|
61
|
+
/**
|
|
62
|
+
* Quién puede leer/enviar este tipo (debe coincidir con el backend):
|
|
63
|
+
* - PUBLIC cualquiera, incluso sin login (anónimo si allowAnonymous).
|
|
64
|
+
* - AUTHENTICATED cualquier usuario logueado + verificado, cross-org.
|
|
65
|
+
* - ORG/INTERNAL solo miembros de la org dueña. Default ORG.
|
|
66
|
+
*/
|
|
62
67
|
visibility?: RequestVisibility;
|
|
63
68
|
createdAt: string;
|
|
64
69
|
updatedAt: string;
|
package/lib/version.d.ts
CHANGED
package/package.json
CHANGED
package/public-api.d.ts
CHANGED
|
@@ -429,6 +429,7 @@ export * from './lib/services/requests/types';
|
|
|
429
429
|
export * from './lib/services/requests/request.service';
|
|
430
430
|
export * from './lib/services/requests/request-form-builder.service';
|
|
431
431
|
export * from './lib/services/requests/request-firestore.service';
|
|
432
|
+
export * from './lib/services/requests/request-visibility';
|
|
432
433
|
export * from './lib/components/organisms/article-strip/article-strip.component';
|
|
433
434
|
export * from './lib/components/organisms/article-strip/types';
|
|
434
435
|
export * from './lib/components/molecules/metric-card/metric-card.component';
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Firebase Messaging Service Worker
|
|
3
|
+
*
|
|
4
|
+
* Service Worker estático para Firebase Cloud Messaging.
|
|
5
|
+
* Carga la configuración dinámicamente desde /firebase-config.js.
|
|
6
|
+
*
|
|
7
|
+
* CONFIGURACIÓN:
|
|
8
|
+
* 1. Crea firebase.config.json con tu configuración de Firebase
|
|
9
|
+
* 2. Ejecuta: npm run generate:firebase-config
|
|
10
|
+
* Esto genera /firebase-config.js con: self.FIREBASE_CONFIG = {...}
|
|
11
|
+
* 3. Agrega este SW y firebase-config.js a los assets de angular.json
|
|
12
|
+
*
|
|
13
|
+
* Ver README.md para documentación completa.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
// Importar Firebase scripts
|
|
17
|
+
importScripts('https://www.gstatic.com/firebasejs/10.7.0/firebase-app-compat.js');
|
|
18
|
+
importScripts('https://www.gstatic.com/firebasejs/10.7.0/firebase-messaging-compat.js');
|
|
19
|
+
|
|
20
|
+
// Importar configuración desde archivo externo (generado en build)
|
|
21
|
+
// Este archivo define: self.FIREBASE_CONFIG = { ... }
|
|
22
|
+
try {
|
|
23
|
+
importScripts('/firebase-config.js');
|
|
24
|
+
} catch (e) {
|
|
25
|
+
console.error('[SW] No se pudo cargar firebase-config.js:', e);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// Verificar que la configuración existe
|
|
29
|
+
if (!self.FIREBASE_CONFIG) {
|
|
30
|
+
console.error('[SW] FIREBASE_CONFIG no está definido.');
|
|
31
|
+
console.error('[SW] Ejecuta: npm run generate:firebase-config');
|
|
32
|
+
} else {
|
|
33
|
+
// Inicializar Firebase
|
|
34
|
+
firebase.initializeApp(self.FIREBASE_CONFIG);
|
|
35
|
+
|
|
36
|
+
// Obtener instancia de messaging
|
|
37
|
+
const messaging = firebase.messaging();
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Handler para mensajes en background.
|
|
41
|
+
*/
|
|
42
|
+
messaging.onBackgroundMessage((payload) => {
|
|
43
|
+
console.log('[SW] Mensaje recibido en background:', payload);
|
|
44
|
+
|
|
45
|
+
// Web push usa mensajes data-only (sin bloque `notification`) para que el
|
|
46
|
+
// navegador NO auto-muestre una notificación duplicada — el SW es el único
|
|
47
|
+
// que la pinta. Title/body/icon llegan dentro de `data`. Se mantiene el
|
|
48
|
+
// fallback a `payload.notification` por compatibilidad con mensajes
|
|
49
|
+
// legacy o nativos que sí traen el bloque.
|
|
50
|
+
const data = payload.data || {};
|
|
51
|
+
const notificationTitle =
|
|
52
|
+
payload.notification?.title || data.title || 'Nueva notificación';
|
|
53
|
+
const notificationBody = payload.notification?.body || data.body || '';
|
|
54
|
+
const notificationIcon =
|
|
55
|
+
payload.notification?.icon || data.icon || '/assets/icon/favicon.ico';
|
|
56
|
+
|
|
57
|
+
const notificationOptions = {
|
|
58
|
+
body: notificationBody,
|
|
59
|
+
icon: notificationIcon,
|
|
60
|
+
image: payload.notification?.image,
|
|
61
|
+
badge: '/assets/icon/badge.png',
|
|
62
|
+
tag: payload.messageId || data.messageId || 'default',
|
|
63
|
+
data: {
|
|
64
|
+
...data,
|
|
65
|
+
messageId: payload.messageId || data.messageId,
|
|
66
|
+
title: notificationTitle,
|
|
67
|
+
body: notificationBody,
|
|
68
|
+
},
|
|
69
|
+
vibrate: [200, 100, 200],
|
|
70
|
+
requireInteraction: data.require_interaction === 'true',
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
return self.registration.showNotification(notificationTitle, notificationOptions);
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Handler para clicks en notificaciones.
|
|
78
|
+
*/
|
|
79
|
+
self.addEventListener('notificationclick', (event) => {
|
|
80
|
+
console.log('[SW] Click en notificación:', event);
|
|
81
|
+
event.notification.close();
|
|
82
|
+
|
|
83
|
+
const data = event.notification.data || {};
|
|
84
|
+
let targetUrl = '/';
|
|
85
|
+
|
|
86
|
+
if (data.route) {
|
|
87
|
+
targetUrl = data.route;
|
|
88
|
+
} else if (data.url) {
|
|
89
|
+
targetUrl = data.url;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
if (data.query_params) {
|
|
93
|
+
const separator = targetUrl.includes('?') ? '&' : '?';
|
|
94
|
+
targetUrl += separator + data.query_params;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const notificationPayload = {
|
|
98
|
+
type: 'NOTIFICATION_CLICK',
|
|
99
|
+
notification: {
|
|
100
|
+
title: data.title,
|
|
101
|
+
body: data.body,
|
|
102
|
+
data: data,
|
|
103
|
+
messageId: data.messageId,
|
|
104
|
+
},
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
event.waitUntil(
|
|
108
|
+
clients
|
|
109
|
+
.matchAll({ type: 'window', includeUncontrolled: true })
|
|
110
|
+
.then((clientList) => {
|
|
111
|
+
// Siempre enviar postMessage para que la app pueda reaccionar
|
|
112
|
+
for (const client of clientList) {
|
|
113
|
+
client.postMessage(notificationPayload);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// Navegar si hay route o url
|
|
117
|
+
if (targetUrl !== '/') {
|
|
118
|
+
for (const client of clientList) {
|
|
119
|
+
if ('navigate' in client) {
|
|
120
|
+
return client.navigate(targetUrl).then((c) => c?.focus());
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
// Si no hay cliente abierto, abrir nueva ventana
|
|
124
|
+
if (clients.openWindow) {
|
|
125
|
+
return clients.openWindow(targetUrl);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// Solo hacer focus si no hay navegación
|
|
130
|
+
for (const client of clientList) {
|
|
131
|
+
if ('focus' in client) {
|
|
132
|
+
return client.focus();
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
if (clients.openWindow) {
|
|
136
|
+
return clients.openWindow('/');
|
|
137
|
+
}
|
|
138
|
+
})
|
|
139
|
+
);
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
self.addEventListener('notificationclose', (event) => {
|
|
143
|
+
console.log('[SW] Notificación cerrada:', event.notification.tag);
|
|
144
|
+
});
|
|
145
|
+
}
|