@callimacus/intent

中文文档
2.2.5发布于 2026/11/07TypeScriptES Module近 30 天下载 3836

Lightweight browser SDK for intent events (client-only).

原始使用文档
文档目录26 节
  1. 📦 Installation
  2. Using npm (recommended)
  3. ⚙️ Usage
  4. Advanced Configuration Options
  5. 🌐 CDN Usage
  6. Option 1: jsDelivr
  7. Option 2: unpkg
  8. 📘 More Information
  9. Managing consent & geolocation flags
  10. Recommended: Type-Safe Functions (v1.10.0+)
  11. Migrating to v2.0.0 (removal of setFlag )
  12. Debug Logging & Debug Panel
  13. Debug Logging
  14. Debug Panel (Visual Event Inspector)
  15. 🎮 Test & Demo Page
  16. Using intent_sid
  17. Sharing one session across sites
  18. 🔒 Data Collection & Privacy
  19. What Data is Collected
  20. Built-in Redaction
  21. Data Transmission & Storage
  22. Your Responsibility: Redacting Additional Fields
  23. How to Redact Custom Fields
  24. Redaction Examples
  25. Best Practices
  26. Compliance Note

Intent Integration

codecov

The Intent tracker collects consented client context and sends events to Callimacus. It can be easily integrated into modern applications (React, Vite, Next.js, etc.) via npm or directly via a script tag.

React Native: @callimacus/intent/native runs the same pipeline in an app — see docs/react-native.md.


📦 Installation

Install the package from npm:

npm install @callimacus/intent

⚙️ Usage

Initialize Intent in your app entry point:

// app entry
import { initIntent } from '@callimacus/intent';

initIntent({
  clientId: 'cal-pk-...',                     // your Callimacus Client ID
  consent: true,                           // can be toggled later
  geo: true,                               // can be toggled later
});

Advanced Configuration Options

The initIntent function accepts the following options:

initIntent({
  clientId: 'cal-pk-...',         // Required: Your Callimacus Client ID
  consent: true,                  // Optional: Enable/disable tracking (default: false)
  geo: false,                     // Optional: Enable/disable geolocation (default: false)
  baseUrl: 'https://...',         // Optional: Custom API endpoint (default: 'https://intent.callimacus.ai')
  ip: '192.0.2.1',                // Optional: Client IP address
  sidMaxAgeSeconds: 2592000,      // Optional: Session cookie max-age in seconds (default: 30 days = 2592000 seconds)
  linkDomains: ['site.com', 'site.ai'], // Optional: Sites that share one session (see below)
  debug: false,                   // Optional: Enable debug logging for timing information (default: false)
  debugPanel: false,              // Optional: Enable visual debug panel (default: false)
});

🌐 CDN Usage

If you prefer not to use npm, include the package via a <script> tag:

Option 1: jsDelivr

<script src="https://cdn.jsdelivr.net/npm/@callimacus/intent/dist/intent.umd.min.js"></script>

Option 2: unpkg

<script src="https://unpkg.com/@callimacus/intent/dist/intent.umd.min.js"></script>

Once loaded, access the module from the global window.Intent namespace:

<script>
  const { initIntent } = window.Intent;

  initIntent({
    clientId: 'cal-pk-...',
    consent: true,
    geo: false,
  });
</script>

📘 More Information


Use the dedicated helper functions for better type safety and IDE support:

import {setConsent, setGeo, setDebug} from '@callimacus/intent';

// Grant or revoke consent
setConsent(true);  // granted
setConsent(false); // disabled

// Enable or disable device geolocation capture
setGeo(true);      // enabled
setGeo(false);     // disabled

// Enable or disable debug logging
setDebug(true);    // enabled
setDebug(false);   // disabled

Benefits of type-safe functions:

  • Clear, self-documenting API
  • Better IDE autocomplete and type checking
  • Prevents typos in flag names
  • Explicit boolean-only parameters

Behavior:

  • When consent is granted, the tracker maintains a first-party cookie intent_sid.
  • If consent is revoked, the tracker clears intent_sid and stops sending events.

Migrating to v2.0.0 (removal of setFlag)

Breaking change: the generic setFlag function was removed in v2.0.0. It is no longer exported. Replace every call with the type-safe equivalent:

// ❌ Removed in v2.0.0
setFlag('intent:consent', true);
setFlag('intent:geo', false);
setFlag('intent:debug', true);

// ✅ Use the type-safe functions
setConsent(true);   // replaces setFlag('intent:consent', ...)
setGeo(false);      // replaces setFlag('intent:geo', ...)
setDebug(true);     // replaces setFlag('intent:debug', ...)

Migration steps:

  1. Find all uses of setFlag in your codebase (grep -r "setFlag" your-codebase/).
  2. Replace each call:
    • setFlag('intent:consent', ...) → setConsent(...)
    • setFlag('intent:geo', ...) → setGeo(...)
    • setFlag('intent:debug', ...) → setDebug(...)
  3. If you relied on setFlag with custom flag names, open an issue to discuss your use case — the public API now only supports the three flags above.

Debug Logging & Debug Panel

Debug Logging

By default, the SDK does not output any console logs to avoid spamming the browser console. However, you can enable debug logging to see timing information for performance analysis:

import {initIntent} from '@callimacus/intent';

// Enable debug logging during initialization
initIntent({
  clientId: 'cal-pk-...',
  debug: true,  // Enable debug logs
});

Or toggle debug logging at runtime:

import {setDebug} from '@callimacus/intent';

// Enable debug logging (recommended - type-safe)
setDebug(true);

// Disable debug logging
setDebug(false);

When debug logging is enabled, the SDK will output timing information to the console, including:

  • HTML serialization time: Time taken to serialize the DOM into HTML
  • Screenshot capture time: Time taken by html2canvas-pro to render the page
  • JPEG encoding time: Time taken to encode the canvas to JPEG format
  • Total capture time: Total time for the entire capture process

This is useful for:

  • Performance tuning: Identify bottlenecks in the capture process
  • Development debugging: Understand SDK behavior during development
  • Production troubleshooting: Temporarily enable logs to diagnose issues

Note: Debug logging is disabled by default to prevent console spam in production. Only enable it when needed for debugging or performance analysis.

Debug Panel (Visual Event Inspector)

⚠️ WARNING: The debug panel is intended for development and debugging only.
DO NOT enable in production environments. It exposes internal SDK behavior including screenshots, event payloads, and HTML content that may reveal sensitive application structure.

The SDK provides separate build variants to ensure the debug panel code is not shipped to production:

Build Variants

Production Build (Default) - Debug panel excluded

npm install @callimacus/intent
import {initIntent} from '@callimacus/intent';  // Production build
<script src="https://unpkg.com/@callimacus/intent/dist/intent.umd.min.js"></script>

Debug Build - Debug panel included (for development/testing only)

// ESM - use the /debug export
import {initIntent, setDebugPanel} from '@callimacus/intent/debug';
<!-- UMD - use the .debug variant -->
<script src="https://unpkg.com/@callimacus/intent/dist/intent.debug.umd.min.js"></script>

Best Practice: Environment-Based Loading

Use your build system to load the appropriate variant:

// Vite / Webpack example
const Intent = import.meta.env.PROD 
  ? await import('@callimacus/intent')
  : await import('@callimacus/intent/debug');

Intent.initIntent({
  clientId: 'cal-pk-...',
  consent: true,
  debugPanel: !import.meta.env.PROD  // Only in development
});

Recommended Use Cases:

  • Local Development: Debug event capture during integration
  • Testing Environments: Verify SDK behavior in test/staging
  • Internal Demos: Showcase SDK functionality to internal stakeholders
  • Troubleshooting: Diagnose issues in non-production environments

NOT Recommended:

  • ❌ Production websites or applications
  • ❌ Public demos accessible to end users
  • ❌ Any environment where exposing SDK internals is a concern

Usage

Enable debug panel during initialization:

import {initIntent} from '@callimacus/intent/debug';  // Use debug build

initIntent({
  clientId: 'cal-pk-...',
  consent: true,
  debugPanel: true,  // Enable visual debug panel
});

Toggle debug panel at runtime:

import {setDebugPanel} from '@callimacus/intent/debug';

// Show debug panel (development only)
setDebugPanel(true);

// Hide debug panel
setDebugPanel(false);

Debug Panel Features:

  • 📸 Screenshots: View the actual JPEG screenshots captured by the SDK
  • 🔍 Event Details: Expand each event to see properties, HTML, and bounding box data
  • 🎯 Event Types: See what type of event was captured (click, pageview, scroll, etc.)
  • 🕐 Timestamps: Track when each event occurred
  • 🗑️ Clear Events: Clear the event log with a single button click
  • 🎨 Draggable: Move the panel anywhere on the screen
  • ➖ Minimize: Collapse the panel when not needed

The debug panel appears as a floating window in the top-right corner and can be dragged anywhere on the page. It displays up to 50 recent events (automatically removes oldest when limit is reached).


🎮 Test & Demo Page

A comprehensive test and demo page is included in the demo/test-demo.html file. This page showcases:

  • ✅ All form input types (text, email, password, date, color, range, etc.)
  • ✅ Interactive elements (buttons, links, clickable divs)
  • ✅ Auto-redacted fields (email, password, phone, credit card, etc.)
  • ✅ Custom redaction examples with data-intent-redact
  • ✅ SDK initialization and consent controls
  • ✅ Debug panel demonstration
  • ✅ Complete documentation and usage instructions

To use the test page:

  1. Build the SDK:

    npm run build
    
  2. Start a local web server from the repository root:

    # Using Python 3
    python3 -m http.server 8080
    
    # Or using Node.js http-server
    npx http-server -p 8080
    
  3. Open your browser and navigate to:

    http://localhost:8080/demo/test-demo.html
    
  4. Follow the on-page instructions to:

    • Initialize the SDK
    • Enable the debug panel
    • Grant consent
    • Interact with elements to see captured events

The test page is perfect for demonstrating the SDK to stakeholders, testing new features, and understanding how the SDK captures and handles different types of data.


Using intent_sid

Use these utilities to read or manage the session cookie from your app:

import {
   getIntentSessionId,
   clearIntentSessionId,
   ensureIntentSessionId,
   setIntentSessionMaxAge,
} from '@callimacus/intent';

const sid = getIntentSessionId();   // string | undefined, can be sent to backend
clearIntentSessionId();             // deletes cookie
ensureIntentSessionId();            // creates cookie if missing
setIntentSessionMaxAge(86400);      // updates cookie max-age (in seconds)

Sharing one session across sites

intent_sid is a first-party cookie, so each site (and each subdomain) has its own. To keep one session when a visitor moves between your sites, for example from site.com to site.ai or from www.site.com to shop.site.com, pass the same linkDomains on every one of them:

initIntent({clientId: 'cal-pk-...', linkDomains: ['site.com', 'site.ai']});
  • A click on a link to a linked site adds intent_sid to that link's URL. This needs consent on the site the visitor is leaving.
  • The site the visitor lands on removes the parameter from the address bar and keeps the id once it has consent. It only does this when the visitor arrived from another linked site, so a link shared in a chat or an email hands over nothing.
  • This needs the leaving site to send a referrer: a Referrer-Policy: no-referrer header or rel="noreferrer" on the link stops the handoff.

🔒 Data Collection & Privacy

What Data is Collected

When consent is granted, the Intent SDK automatically collects the following data to help understand user behavior and improve experiences:

  1. Screenshots: Visual captures of the page viewport, downscaled to JPEG format for efficient transmission
  2. HTML Content: Serialized HTML of interacted elements (buttons, links, inputs, etc.)
  3. Interaction Events: User actions including:
    • Clicks on buttons, links, and interactive elements
    • Form submissions (Enter key on input fields)
    • Page scroll events
    • Page focus/blur events
    • Pageview events
  4. Session Information:
    • Session ID stored in first-party cookie intent_sid (created when consent is granted)
    • Session cookie max-age (default: 30 days, configurable via sidMaxAgeSeconds)
  5. Context Information: Browser and device metadata:
    • User agent: Browser name, version, and platform
    • Languages: Preferred language(s) and accept-language settings
    • Timezone: Local timezone and UTC offset
    • Local time: Current date and time in user's timezone
    • Screen: Resolution, pixel ratio, available space, and color depth
    • Viewport: Window size and screen orientation
    • Device capabilities: CPU cores, touch support, pointer type (coarse/fine)
    • Battery status: Level and charging state (when available)
    • Network connection: Connection type, speed, RTT, and data saver mode (when available or inferred from performance timing)
    • Performance timing: Used to infer network characteristics
    • Online/offline status: Browser connectivity state
    • Cookies enabled: Whether the browser allows cookies
    • Do Not Track (DNT): Browser DNT setting value
    • Referrer: HTTP referrer if present
    • PWA status: Service worker presence and display mode
    • Device orientation/tilt: Device physical orientation (when available)
    • Geolocation: Latitude and longitude (only when explicitly enabled via geo: true)
  6. Client Configuration (stored in localStorage):
    • Client ID (clientId)
    • API endpoint (baseUrl)
    • Optional IP address (ip)
    • Consent status (intent:consent)
    • Geolocation preference (intent:geo)
    • Debug logging preference (intent:debug)
    • Session max-age setting

Built-in Redaction

The SDK automatically redacts the following sensitive information:

  • Password fields (<input type="password">)
  • Form fields with sensitive autocomplete attributes (both <input> and <textarea> elements):
    • Names (name, given-name, additional-name, family-name, nickname, username)
    • Email addresses (email)
    • Phone numbers (tel)
    • Addresses:
      • Street addresses (street-address, address-line1, address-line2, address-line3)
      • Administrative levels (address-level1, address-level2, address-level3, address-level4)
      • Postal and country (postal-code, country, country-name)
    • Credit card details:
      • Card numbers and security (cc-number, cc-exp, cc-exp-month, cc-exp-year, cc-csc, cc-type)
      • Cardholder names (cc-name, cc-given-name, cc-additional-name, cc-family-name)
    • Birthday information (bday, bday-day, bday-month, bday-year)
    • Organization details (organization, organization-title)
    • Other sensitive fields (sex, webauthn)

Exception: Search fields (<input type="search"> or elements with role="searchbox") are NOT redacted, even if they have sensitive autocomplete attributes, to preserve search functionality in captured events.

Redacted fields are replaced with placeholder text like <Password>, <Email>, <Credit card>, <Name>, <Phone>, <Address>, etc., in both the HTML content and screenshots.

Data Transmission & Storage

How Data is Transmitted:

  • Events are sent to the Callimacus API endpoint (default: https://intent.callimacus.ai/events)
  • Data is transmitted via HTTPS POST requests with JSON payloads
  • The SDK uses fetch() with keepalive for reliability during page unload
  • Credentials are not included in requests (credentials: 'omit')
  • The client ID is sent in the x-sl-access-token header
  • The session ID is sent in the x-intent-sid header

Local Storage:

  • The SDK stores configuration and preferences in browser localStorage
  • Keys used: intent:consent, intent:geo, intent:debug, intent:data-client-id, intent:data-base-url, intent:data-ip, intent:data-sid-max-age
  • localStorage data persists until explicitly cleared by the user or your application

Cookies:

  • First-party cookie intent_sid stores the session identifier
  • Cookie attributes: SameSite=Lax, Secure (HTTPS only)
  • Default expiration: 30 days (configurable via sidMaxAgeSeconds)
  • Cookie is created when consent is granted and deleted when consent is revoked

Data Retention:

  • Data retention policies are managed by Callimacus, not by this client-side SDK
  • For information about server-side data retention, consult your Callimacus account settings or contact Callimacus support

Your Responsibility: Redacting Additional Fields

⚠️ Important: While the SDK provides automatic redaction for common sensitive fields, you are responsible for identifying and redacting any additional sensitive or PII data specific to your application.

The SDK cannot automatically detect all sensitive information. You must explicitly mark any custom fields, proprietary data, or application-specific sensitive content for redaction.

How to Redact Custom Fields

Use the data-intent-redact attribute to mark elements for redaction:

Option 1: Redact with default label

<!-- Element will be masked with a gray placeholder labeled "<Sensitive>" -->
<div data-intent-redact>Sensitive content here</div>
<input type="text" data-intent-redact />

<!-- Or explicitly use "mask" value for "<Redacted>" label -->
<div data-intent-redact="mask">Sensitive content</div>

Option 2: Redact with custom label

<!-- Provide a descriptive label using data-intent-redact-label -->
<div data-intent-redact data-intent-redact-label="Account Balance">$1,234.56</div>
<input type="text" data-intent-redact data-intent-redact-label="Social Security Number" />

The custom label will appear as <Account Balance> or <Social Security Number> in the captured screenshots and HTML.

Option 3: Completely ignore elements

<!-- Element will not appear in screenshots or HTML captures at all -->
<div data-intent-redact="ignore">This won't be captured</div>

Redaction Examples

<!-- Patient medical record number -->
<input 
  type="text" 
  data-intent-redact 
  data-intent-redact-label="Medical Record Number" 
  placeholder="Enter MRN" 
/>

<!-- Customer account balance -->
<div data-intent-redact data-intent-redact-label="Account Balance">
  Balance: $5,432.10
</div>

<!-- Internal employee ID -->
<span data-intent-redact data-intent-redact-label="Employee ID">
  EMP-123456
</span>

<!-- Proprietary business data -->
<section data-intent-redact data-intent-redact-label="Revenue Dashboard">
  <!-- Entire section will be redacted -->
  Q4 Revenue: $10M
</section>

<!-- Element to completely exclude from tracking -->
<div data-intent-redact="ignore">
  Internal debug information
</div>

Best Practices

  1. Review Your Forms: Audit all form fields and identify which ones contain sensitive or PII data beyond standard fields (name, email, phone, etc.)
  2. Mark Custom Sensitive Data: Apply data-intent-redact to any elements displaying user-specific information, financial data, health information, or proprietary business data
  3. Use Descriptive Labels: Provide meaningful labels with data-intent-redact-label to help you understand what was redacted when reviewing captured events
  4. Test Your Redaction: Before going to production, test your pages to ensure all sensitive information is properly masked
  5. Regular Audits: Periodically review your application for new sensitive fields that may need redaction as features evolve

Compliance Note

Proper data redaction is critical for compliance with privacy regulations (GDPR, CCPA, HIPAA, etc.). While this SDK provides tools for redaction, it is your responsibility as the integrator to ensure all applicable sensitive data is properly redacted according to your legal and regulatory requirements.


版本与发布记录

@callimacus/intent 共发布 13 个版本,首次发布于 2026/09/29;过去 12 个月发布了 13 个版本。

版本发布日期距今
2.2.5latest2026/11/072 天前
2.2.42026/11/035 天前
2.2.32026/11/027 天前
2.2.22026/11/018 天前
2.2.12026/10/2811 天前
2.2.02026/10/2811 天前

关于 @callimacus/intent 的常见问题

@callimacus/intent 是什么?

Lightweight browser SDK for intent events (client-only).

如何安装 @callimacus/intent?

在项目目录运行 npm install @callimacus/intent,或使用 pnpm add / yarn add / bun add。

@callimacus/intent 支持 TypeScript 吗?

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

@callimacus/intent 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@callimacus/intent 需要什么版本的 Node.js?

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

@callimacus/intent 可以商用吗?

@callimacus/intent 使用 未声明 许可。package.json 没有声明许可证。没有许可证的代码默认保留全部权利,商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括,不构成法律意见,请以许可原文为准。

@callimacus/intent 的下载量有多少?

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

@callimacus/intent 还在维护吗?

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