npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@jysperu/browser-alert

v1.0.2

Published

Utilidades modernas para gestión de alertas y diálogos en el navegador usando SweetAlert2

Downloads

3

Readme

@jysperu/browser-alert

npm version npm downloads License: MIT TypeScript Bundle Size

Utilidades modernas para gestión de alertas y diálogos en el navegador usando SweetAlert2.

🚀 Características

  • 🎨 SweetAlert2 integrado con configuración optimizada
  • 🔧 TypeScript completamente tipado
  • Interfaces robustas para configuración
  • 🛡️ Manejo de errores comprehensivo

📦 Instalación

npm install @jysperu/browser-alert

SweetAlert2 se instala automáticamente como dependencia del paquete.

⚡ Inicio Rápido

import { alert_success, alert_confirm, alert_loading } from "@jysperu/browser-alert";

// Mensaje de éxito
await alert_success("¡Operación completada exitosamente!");

// Confirmación
const confirmed = await alert_confirm("¿Estás seguro de eliminar este elemento?");
if (confirmed) {
  console.log("Usuario confirmó la acción");
}

// Indicador de carga
alert_loading("Procesando", "Por favor espere...");

// Acceso directo a SweetAlert2
import { Swal } from "@jysperu/browser-alert";

await Swal.fire({
  title: "Configuración personalizada",
  html: "Usa Swal directamente para casos complejos",
  icon: "info",
});

📚 API Reference

🎯 alert_loading

Muestra un diálogo de carga con spinner.

function alert_loading(title?: string, html?: string, config?: AlertMessageConfig): Promise<void>;

Parámetros:

  • title - Título del diálogo (por defecto: "Guardando datos")
  • html - Contenido HTML del mensaje
  • config - Configuración adicional

Ejemplos:

// Carga básica
alert_loading();

// Carga personalizada
alert_loading("Subiendo archivo", "Procesando imagen, por favor espere...");

// Con configuración adicional
alert_loading("Conectando", "Estableciendo conexión con el servidor...", {
  position: "top",
  toast: false,
});

✅ alert_confirm

Muestra un diálogo de confirmación.

interface AlertConfirmOptions {
  icon?: "question" | "warning" | "info";
  confirmButtonText?: string;
  cancelButtonText?: string;
  hideCancelButton?: boolean;
}

function alert_confirm(html: string, title?: string, options?: AlertConfirmOptions, config?: AlertMessageConfig): Promise<boolean>;

Retorna: true si se confirmó, false si se canceló

Ejemplos:

// Confirmación básica
const result = await alert_confirm("¿Desea continuar?");

// Confirmación personalizada
const result = await alert_confirm("Se eliminarán todos los datos. Esta acción no se puede deshacer.", "Confirmar eliminación", {
  icon: "warning",
  confirmButtonText: "Sí, eliminar",
  cancelButtonText: "Cancelar",
});

// Sin botón de cancelar
const result = await alert_confirm("Por favor confirme que ha leído los términos", "Aceptar términos", {
  hideCancelButton: true,
  confirmButtonText: "He leído y acepto",
});

💬 alert_message

Muestra un mensaje con icono específico.

function alert_message(icon: "success" | "error" | "warning" | "info", html: string, title?: string, config?: AlertMessageConfig): Promise<void>;

Ejemplos:

// Mensaje informativo
await alert_message("info", "El sistema se actualizará en 5 minutos");

// Mensaje de advertencia
await alert_message("warning", "Memoria baja disponible", "Advertencia del sistema");

// Mensaje personalizado
await alert_message("success", "Datos guardados", "Éxito", {
  timer: 3000,
  position: "top-end",
  toast: true,
});

🎉 alert_success

Muestra un mensaje de éxito.

function alert_success(html: string, title?: string, config?: AlertMessageConfig): Promise<void>;

Ejemplos:

// Éxito básico
await alert_success("Usuario creado correctamente");

// Éxito personalizado
await alert_success("Perfil actualizado con éxito", "Cambios guardados", { timer: 1500 });

❌ alert_error

Muestra un mensaje de error.

function alert_error(html: string, title?: string, config?: AlertMessageConfig): Promise<void>;

Ejemplos:

// Error básico
await alert_error("No se pudo conectar con el servidor");

// Error detallado
await alert_error("El archivo es demasiado grande. Máximo permitido: 10MB", "Error de validación", { timer: 8000 });

⚠️ alert_warning

Muestra un mensaje de advertencia.

function alert_warning(html: string, title?: string, config?: AlertMessageConfig): Promise<void>;

Ejemplo:

await alert_warning("La sesión expirará en 5 minutos", "Sesión por expirar");

ℹ️ alert_info

Muestra un mensaje informativo.

function alert_info(html: string, title?: string, config?: AlertMessageConfig): Promise<void>;

Ejemplo:

await alert_info("Nueva funcionalidad disponible en el menú principal");

❌ alert_close

Cierra cualquier diálogo activo.

function alert_close(): void;

Ejemplo:

// Cerrar después de 3 segundos
setTimeout(() => {
  alert_close();
}, 3000);

🔧 Configuración Avanzada

AlertMessageConfig Interface

interface AlertMessageConfig {
  timer?: number; // Tiempo en ms para auto-cerrar
  showConfirmButton?: boolean; // Mostrar botón de confirmación
  position?: "top" | "top-start" | "top-end" | "center" | "center-start" | "center-end" | "bottom" | "bottom-start" | "bottom-end";
  toast?: boolean; // Modo toast (esquina de pantalla)
  [key: string]: any; // Cualquier opción adicional de SweetAlert2
}

🎯 Casos de Uso Prácticos

Sistema de Autenticación

import { alert_loading, alert_success, alert_error, alert_confirm } from "@jysperu/browser-alert";

class AuthManager {
  static async login(email: string, password: string) {
    // Mostrar indicador de carga
    alert_loading("Iniciando sesión", "Verificando credenciales...");

    try {
      const response = await fetch("/api/login", {
        method: "POST",
        body: JSON.stringify({ email, password }),
        headers: { "Content-Type": "application/json" },
      });

      if (response.ok) {
        await alert_success("¡Bienvenido!", "Inicio de sesión exitoso");
        // Redirigir al dashboard
      } else {
        await alert_error("Credenciales incorrectas", "Error de autenticación");
      }
    } catch (error) {
      await alert_error("No se pudo conectar con el servidor", "Error de conexión");
    }
  }

  static async logout() {
    const confirmed = await alert_confirm("¿Estás seguro de que deseas cerrar sesión?", "Confirmar cierre de sesión", {
      icon: "question",
      confirmButtonText: "Sí, cerrar sesión",
      cancelButtonText: "Cancelar",
    });

    if (confirmed) {
      alert_loading("Cerrando sesión...");
      // Lógica de logout
      await alert_success("Sesión cerrada correctamente");
    }
  }
}

📦 Build y Distribución

# Construir el proyecto
npm run build

# Genera automáticamente:
# └── dist/
#     ├── alert.esm.js      # ES Modules
#     ├── alert.cjs.js      # CommonJS
#     ├── alert.umd.js      # UMD
#     └── alert.d.ts        # TypeScript definitions

🌐 Compatibilidad

  • ✅ Todos los navegadores modernos
  • ✅ Compatible con frameworks (React, Vue, Angular)
  • ✅ SSR friendly
  • ✅ TypeScript nativo

🔗 Enlaces y Recursos

📄 Licencia

MIT License - Consulta el archivo LICENSE para detalles completos.

MIT License - Copyright (c) 2025 JYS Perú

Desarrollado con ❤️ por JYS Perú