@dataemergencia/emergency

中文文档
0.7.0发布于 2026/11/10MITTypeScriptESM + CJS构建来源已验证近 30 天下载 1971

Framework-agnostic emergency client for DataEmergencia, with a mountable React panel and an IIFE build.

原始使用文档
文档目录14 节
  1. Documentation
  2. Requirements
  3. Install
  4. React / ESM quickstart
  5. Vanilla / IIFE quickstart
  6. Mount options
  7. Client API
  8. Events
  9. BFF contract
  10. Theming and visual contract
  11. Accessibility
  12. Development
  13. Releasing
  14. License

@dataemergencia/emergency

Client for the DataEmergencia emergency flow. It owns everything that happens after the SOS trigger: the panel, the emergency lifecycle, the public realtime updates and the geolocation fallback feedback.

The upstream DataEmergencia API is never called from the browser. The only backend contract is the emergency BFF (/de-bff/emergency), which validates the identity code, sends the WhatsApp messages and proxies the upstream state.

  • Framework-agnostic TypeScript core (types, state machine, BFF client, store).
  • React 19 presentation layer with accessible panel components.
  • Mountable IIFE bundle for vanilla pages: no host React or build step.
  • ESM/CJS bundles for React applications, with React kept external.
  • No localStorage: the BFF is the source of truth and resume uses GET /current.

Documentation

The BFF is a separate package: dataemergencia/emergency-bff.

Requirements

  • Node.js 22 or newer. CI and releases use the pinned LTS from .nvmrc (24.22.2).
  • pnpm 10+ (the monorepo currently runs pnpm 12.8.1).
  • Vite+ 1.4.0 for this package's build and test commands.

React 19 is a peer dependency for the ESM/CJS entry points. The IIFE entry bundles React, so vanilla consumers need nothing.

Install

pnpm add @dataemergencia/emergency

React / ESM quickstart

import { mount } from '@dataemergencia/emergency';
import '@dataemergencia/emergency/styles.css';

const client = mount({
  root: '#emergency-root',
  bffBaseUrl: 'https://api.dataemergencia.com/de-bff/emergency',
  code: 'DABC12',
  trigger: '#sos-button', // selector, element, or callback receiving open()
  fallback: {
    phone: '+57 300 123 4567',
    label: 'Línea de emergencia',
  },
  onEvent: (event, payload) => {
    console.log(event, payload);
  },
});

// Later, or from your own UI:
client.open();
client.destroy();

mount() never auto-opens the panel. The host decides when to call open() or wires a trigger. destroy() unmounts React, removes the trigger listener, cancels in-flight requests, disconnects Pusher and clears the store.

Vanilla / IIFE quickstart

<div id="emergency-root"></div>
<button id="sos">SOS</button>

<!-- Pin the version in production; see docs/client/installation.md for SRI. -->
<script src="https://cdn.jsdelivr.net/npm/@dataemergencia/[email protected]/dist/iife/emergency.iife.global.js"></script>
<script>
  window.DataEmergenciaEmergency.mount({
    root: '#emergency-root',
    bffBaseUrl: 'https://api.dataemergencia.com/de-bff/emergency',
    code: 'DABC12',
    trigger: '#sos',
    fallback: { phone: '+57 300 123 4567', label: 'Línea de emergencia' },
    realtime: { key: 'your-public-pusher-key', cluster: 'us2' },
  });
</script>

The IIFE exposes window.DataEmergenciaEmergency.mount. React and ReactDOM are included in the bundle; the host page does not need a build step.

For state-by-state review there is a lab page that imports the source through Vite (HMR, CSS Modules) instead of the built IIFE. It drives every fixture against the mock BFF: see examples/vanilla/README.md.

Mount options

OptionTypeNotes
rootHTMLElement | stringHost container. Validated at mount.
bffBaseUrlstringFull BFF route prefix, including /de-bff/emergency.
codestring6-character identity code supplied by the host.
triggerstring | HTMLElement | (open) => void | (() => void)Optional. Click opens the panel.
fallback{ phone, label }Optional. Emitted in emergency:fallback for host UI.
themeEmergencyThemeCSS variable overrides (see Theming).
localestringDefaults to es; used for time formatting.
geolocationTimeoutMsnumberDefaults to 8000.
requestTimeoutMsnumberDefaults to 15000.
realtime{ key, cluster, channelPattern? }Public Pusher settings supplied by the host.
onEvent(name, payload) => voidTyped lifecycle events.

Realtime is optional. Pass the public Pusher key and cluster (plus an optional channelPattern, defaulting to whatsapp.{phone}) to subscribe directly to the API's channels; omit the block to stay in pull mode. The API publishes the events, and the BFF never holds Pusher credentials.

Invalid roots or codes do not throw into the host page. mount() reports a configuration error through onEvent('emergency:failed', …), logs it, and returns an inert client.

Client API

client.open(reason?)     // Opens the panel
client.close(reason?)    // Closes the panel
client.ensureSession()   // POST /session once; safe to repeat
client.resume()          // GET /current and exposes resumeAvailable
client.activate()        // Requests geolocation, then POST /activate
client.simulate()        // Requests geolocation, then POST /simulacrum
client.refresh()         // POST /{id}/refresh
client.abort()           // DELETE /{id} after confirmation
client.getState()
client.subscribe(listener)
client.on(event, handler)
client.destroy()

Activation opens the panel immediately, requests geolocation and only reports success after the BFF confirms. If geolocation is denied, unavailable, times out or is unsupported, the client shows a dismissable error feedback card for five seconds and never implies that an emergency was sent without a location.

Simulation also requests geolocation before POST /simulacrum. If the capture fails, it follows the same fallback path as activation and does not call the BFF. A successful capture is announced through emergency:location, and both emergency:activated and emergency:simulated include the captured coordinates.

Abort requires confirmation: requestAbortConfirmation() sets the state that the UI uses for the "keep active / cancel emergency" step, and abort() acts on it.

Simulation is disabled while a real emergency is active.

Events

session:ready, emergency:location, emergency:activated, emergency:simulated, emergency:resumed, emergency:updated, emergency:aborted, emergency:failed, emergency:fallback, panel:opened, panel:closed.

Events are typed in EmergencyEventMap (src/core/types.ts) and emitted by the client's own emitter, not DOM custom events.

BFF contract

The client expects the emergency BFF documented in packages/emergency-bff:

MethodRoutePurpose
GET/configInitial CSRF token.
POST/session{ code } → session + rotated CSRF token.
GET/currentActive emergency for the session, if any.
POST/activate{ geolocation: { latitude, longitude } }.
POST/simulacrum{ geolocation: { latitude, longitude } }, no emergency created.
POST/{id}/refreshReconcile snapshot and responder statuses.
DELETE/{id}Abort and notify contacts.

Every mutating request sends the CSRF token in X-CSRF-Token. The default strategy keeps the token in memory and updates it from /config and /session. For a Laravel-compatible XSRF-TOKEN cookie, pass createCookieCsrfStrategy() through createBffClient() (advanced use).

createBffClient() normalizes errors into EmergencyError while preserving the HTTP status, BFF error code, message and request_id.

Theming and visual contract

The panel reproduces the bp.scaem.app emergency surface. It is plain CSS Modules: React and vanilla integrators do not need Tailwind, PostCSS, FontAwesome or an icon package.

Local class names keep the original BEM names, for example .emergency-panel, .emergency-panel__header, .emergency-panel__button--emergency, .emergency-status__row and .emergency-resume-notification-overlay. CSS Modules prefixes them at build time (de-emergency-emergency-panel-<hash>), so target the stable BEM suffix in overrides rather than the generated hash.

All themeable values are CSS custom properties in src/styles/tokens.css, and every rule carries a literal fallback:

:root {
  --de-emergency-red: #ff0000;
  --de-emergency-red-hover: #ff3535;
  --de-emergency-blue: #00adf6;
  --de-emergency-blue-hover: #29bfff;
  --de-emergency-primary: #007bff;
  --de-emergency-text: #3d4461;
  --de-emergency-white: #fff;
  --de-emergency-white-soft: #f7f7f7;
  --de-emergency-gray: #555;
  --de-emergency-radius: 0.75rem;
  --de-emergency-font: 'Poppins', ui-sans-serif, system-ui, sans-serif;
}

The theme option maps accent, accentContrast, surface, text, muted and radius onto --de-emergency-red, --de-emergency-on-red, --de-emergency-white, --de-emergency-text, --de-emergency-text-secondary and --de-emergency-radius.

The client injects the Google Fonts stylesheet for Google Sans, Montserrat and Poppins at mount time, in both the ESM/CJS and IIFE builds, so the host does not add font <link> tags. Use the fontLoading mount option to disable loading or select families; see Configuration.

The IIFE bundle embeds this stylesheet in a single injected <style> tag and removes it when the last mount is destroyed. Hosts using the IIFE must not load a second copy of the CSS. ESM/CJS consumers import styles.css once.

Accessibility

The panel renders as role="dialog" with aria-modal, aria-labelledby, a focus trap, Escape-to-close and focus restoration to the trigger. Confirmation steps are explicit dialogs with cancel and confirm actions. All controls are native buttons with visible focus, icons are inline SVG with aria-hidden, and status surfaces use role="status" or role="alert".

Development

pnpm install
pnpm run check      # format + lint + type checks
pnpm run lint
pnpm run fmt
pnpm run typecheck
pnpm run test
pnpm run build
pnpm run pack       # npm pack --dry-run

Examples and the visual lab:

# Terminal 1: deterministic mock BFF on :8787
pnpm run example:vanilla:mock

# Terminal 2: build, copy the IIFE and serve the vanilla demo
pnpm run example:vanilla

# Or the HMR lab only (serves the package root)
pnpm run lab

Build outputs:

PathContents
dist/index.js / dist/index.cjsESM/CJS bundles, React external.
dist/index.d.ts / dist/index.d.ctsDeclarations.
dist/styles.cssExtracted CSS Modules for ESM/CJS consumers.
dist/iife/emergency.iife.global.jsIIFE with React bundled and CSS injected.

The IIFE gzip budget is 150 KB (current build: ~115 KB).

Releasing

This package lives at libs/emergency in the DataEmergencia monorepo and is published from the public split repository The-BoxHead-Guy/emergency as @dataemergencia/emergency (npm org dataemergencia).

The full runbook is Releasing the client. The short version:

cd libs/emergency
pnpm bump 0.2.1                 # package.json only; commit the bump
pnpm run check && pnpm run test && pnpm run build
git tag -a emergency-client-v0.2.1 -m "release: 0.2.1"
git push origin emergency-client-v0.2.1

The tag push runs the split workflow, which mirrors this directory to the split root, regenerates a standalone pnpm-lock.yaml, and pushes the split tag. Then run Publish to npm from the split repository.

  • Monorepo tags are project-scoped: emergency-client-v0.2.1.
  • Split repository tags: v0.2.1.
  • scripts/split.sh <version> [--push] [--publish] performs the same mirror manually and is the fallback when Actions is unavailable.
  • scripts/release.sh <version> [--publish] verifies the committed version and the changelog entry, then runs check, tests and build through npm before publishing.
  • Publishing uses npm Trusted Publishing from the split repository; the original 0.1.0 was published manually.

The published tarball contains dist/, README.md, LICENSE and package.json; dist/**/*.map files are excluded. Source maps stay in the repository and in the CI artifacts.

See Releasing the client and CHANGELOG.md.

License

MIT

版本与发布记录

@dataemergencia/emergency 共发布 11 个版本,首次发布于 2026/10/30;过去 12 个月发布了 11 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.7.0latest2026/11/106 天前
0.6.22026/11/079 天前
0.6.12026/11/079 天前
0.6.02026/11/079 天前
0.5.02026/11/0610 天前
0.4.02026/11/0511 天前

关于 @dataemergencia/emergency 的常见问题

@dataemergencia/emergency 是什么?

Framework-agnostic emergency client for DataEmergencia, with a mountable React panel and an IIFE build.

如何安装 @dataemergencia/emergency?

在项目目录运行 npm install @dataemergencia/emergency,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(^19.0.0)、react-dom(^19.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@dataemergencia/emergency 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@dataemergencia/emergency 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@dataemergencia/emergency 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=22.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@dataemergencia/emergency 可以商用吗?

@dataemergencia/emergency 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@dataemergencia/emergency 的下载量有多少?

根据 npm 官方下载统计,@dataemergencia/emergency 在 2026/10/12 – 2026/11/10 这 30 天内被下载 1,971 次,日均约 66 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@dataemergencia/emergency 还在维护吗?

最新版本 0.7.0 发布于 2026/11/10(6 天前);至今共发布 11 个版本,其中过去 12 个月发布了 11 个;首次发布于 2026/10/30。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。