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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@afjs/bark-sdk

v1.0.1

Published

Bark推送服务的Node.js SDK

Readme

Bark SDK

npm version TypeScript License: MIT

一个功能完整的 Bark 推送服务 Node.js SDK,支持 TypeScript,提供简洁易用的 API 接口。

特性

  • 🚀 简单易用 - 提供便捷函数和类实例两种使用方式
  • 📱 功能完整 - 支持 Bark 的所有推送功能和参数
  • 🔧 TypeScript - 完整的类型定义,提供优秀的开发体验
  • 🎵 声音支持 - 内置所有系统声音常量,支持自定义声音
  • 🔗 链接推送 - 支持带链接的推送消息
  • 📊 批量推送 - 支持批量发送多条消息
  • ⚙️ 灵活配置 - 支持自定义服务器地址和默认选项
  • 🏠 自部署支持 - 完美支持自建 Bark 服务器,保护数据隐私
  • 🛡️ 错误处理 - 完善的错误处理和验证机制

安装

# 使用 npm
npm install @afjs/bark-sdk

# 使用 yarn
yarn add @afjs/bark-sdk

# 使用 pnpm
pnpm add @afjs/bark-sdk

快速开始

基础使用

import { BarkClient, quickPush } from '@afjs/bark-sdk';

// 方法 1: 使用便捷函数(推荐用于简单场景)
await quickPush('your-device-key', 'Hello Bark!', '测试标题');

// 方法 2: 使用客户端实例(推荐用于复杂场景)
const client = new BarkClient({
  deviceKey: 'your-device-key'
});

await client.sendText('Hello Bark!', '测试标题');

使用自建服务器

如果您部署了自己的 Bark 服务器,可以通过 serverUrl 参数指定:

// 使用便捷函数指定自建服务器
await quickPush(
  'your-device-key',
  'Hello Bark!',
  '测试标题',
  'https://your-bark-server.com'  // 自建服务器地址
);

// 使用客户端实例指定自建服务器
const client = new BarkClient({
  deviceKey: 'your-device-key',
  serverUrl: 'https://your-bark-server.com'  // 自建服务器地址
});

await client.sendText('Hello from self-hosted server!', '自建服务器');

💡 提示: 使用自建 Bark 服务器可以更好地保护您的数据隐私,避免推送内容经过第三方服务器。

获取设备密钥

  1. 在 App Store 下载 Bark 应用
  2. 打开应用,复制显示的设备密钥(通常是 22 位字符串)
  3. 将密钥用于 SDK 配置

API 文档

BarkClient 类

构造函数

const client = new BarkClient(config: BarkConfig);

BarkConfig 接口:

interface BarkConfig {
  /** 设备密钥(必需) */
  deviceKey: string;
  /**
   * Bark 服务器地址(可选,默认为官方服务器)
   * 如果您部署了自己的 Bark 服务器,请在此指定完整的服务器地址
   * 例如: 'https://your-bark-server.com'
   */
  serverUrl?: string;
  /** 默认推送选项(可选) */
  defaultOptions?: Partial<BarkOptions>;
}

主要方法

push(options: BarkOptions)

发送自定义推送消息,支持所有 Bark 参数。

await client.push({
  title: '系统通知',
  body: '这是推送内容',
  level: 'timeSensitive',
  sound: 'bell',
  url: 'https://example.com',
  badge: 5
});
sendText(text: string, title?: string)

发送简单文本消息。

await client.sendText('消息内容', '可选标题');
sendLink(text: string, url: string, title?: string)

发送带链接的消息。

await client.sendLink('点击查看详情', 'https://example.com', '链接通知');
sendWithSound(text: string, sound: string, title?: string)

发送带自定义声音的消息。

import { BarkSounds } from '@afjs/bark-sdk';

await client.sendWithSound('重要通知', BarkSounds.ALARM, '警报');
sendUrgent(text: string, title?: string)

发送重要消息(时间敏感级别)。

await client.sendUrgent('紧急情况!', '紧急通知');
sendSilent(text: string, title?: string)

发送静默消息(被动级别)。

await client.sendSilent('后台任务完成', '系统通知');
test()

发送测试消息,用于验证配置是否正确。

await client.test();

BarkOptions 接口

完整的推送选项配置:

interface BarkOptions {
  /** 推送标题 */
  title?: string;
  /** 推送内容(必需) */
  body: string;
  /** 推送分组,默认为应用名称 */
  group?: string;
  /** 推送图标,可以是 URL */
  icon?: string;
  /** 推送声音,可以指定系统声音名称 */
  sound?: string;
  /** 推送链接,点击推送时打开的 URL */
  url?: string;
  /** 是否自动复制推送内容,默认为 0 */
  automaticallyCopy?: 0 | 1;
  /** 是否复制推送内容,默认为 0 */
  copy?: 0 | 1;
  /** 推送中断等级 */
  level?: "active" | "timeSensitive" | "passive";
  /** 推送角标数量 */
  badge?: number;
  /** 是否归档推送,默认为 1 */
  isArchive?: 0 | 1;
}

便捷函数

quickPush

快速发送推送消息的便捷函数。

import { quickPush } from '@afjs/bark-sdk';

await quickPush(
  'your-device-key',
  '消息内容',
  '可选标题',
  'https://custom-server.com' // 可选的自定义服务器
);

createBarkClient

创建 BarkClient 实例的便捷函数。

import { createBarkClient } from '@afjs/bark-sdk';

const client = createBarkClient('your-device-key', 'https://custom-server.com');

validateDeviceKey

验证设备密钥格式是否正确。

import { validateDeviceKey } from '@afjs/bark-sdk';

if (validateDeviceKey('your-device-key')) {
  console.log('设备密钥格式正确');
}

内置声音常量

SDK 提供了所有 iOS 系统声音的常量:

import { BarkSounds } from '@afjs/bark-sdk';

// 使用预定义声音
await client.sendWithSound('测试消息', BarkSounds.BELL);
await client.sendWithSound('警报消息', BarkSounds.ALARM);
await client.sendWithSound('邮件通知', BarkSounds.NEWMAIL);

// 可用的声音常量
BarkSounds.DEFAULT      // 默认
BarkSounds.BELL         // 铃声
BarkSounds.BIRDSONG     // 鸟鸣
BarkSounds.BLOOM        // 绽放
BarkSounds.CALYPSO      // 卡利普索
BarkSounds.CHIME        // 钟声
BarkSounds.CHOO         // 火车
BarkSounds.DESCENT      // 下降
BarkSounds.ELECTRONIC   // 电子音
BarkSounds.FANFARE      // 号角
BarkSounds.GLASS        // 玻璃
BarkSounds.GOTOSLEEP    // 睡眠
BarkSounds.HEALTHNOTIFICATION // 健康通知
BarkSounds.HORN         // 喇叭
BarkSounds.LADDER       // 梯子
BarkSounds.MAILSENT     // 邮件发送
BarkSounds.MINUET       // 小步舞曲
BarkSounds.MULTIWAYINVITATION // 多方邀请
BarkSounds.NEWMAIL      // 新邮件
BarkSounds.NEWSFLASH    // 新闻快报
BarkSounds.NOIR         // 黑色
BarkSounds.PAYMENTSUCCESS // 支付成功
BarkSounds.SHAKE        // 摇动
BarkSounds.SHERWOODFOREST // 舍伍德森林
BarkSounds.SILENCE      // 静音
BarkSounds.SPELL        // 咒语
BarkSounds.SUSPENSE     // 悬疑
BarkSounds.TELEGRAPH    // 电报
BarkSounds.TIPTOES      // 踮脚
BarkSounds.TYPEWRITERS  // 打字机
BarkSounds.UPDATE       // 更新

使用示例

基础示例

import { BarkClient, quickPush, BarkSounds } from '@afjs/bark-sdk';

const DEVICE_KEY = 'your-device-key-here';

async function basicExample() {
  // 方法 1: 使用便捷函数
  await quickPush(DEVICE_KEY, '这是一条测试消息', 'Bark SDK');

  // 方法 2: 使用客户端实例
  const client = new BarkClient({
    deviceKey: DEVICE_KEY,
    defaultOptions: {
      group: 'Bark SDK Examples',
      sound: BarkSounds.BELL,
    },
  });

  // 简单文本消息
  await client.sendText('Hello from Bark SDK!', '问候');

  // 带链接的消息
  await client.sendLink(
    '点击查看 Bark SDK 文档',
    'https://github.com/tinsfox/fox-server',
    '文档链接'
  );

  // 重要消息
  await client.sendUrgent('这是一条重要消息', '紧急通知');

  // 静默消息
  await client.sendSilent('这是一条静默消息', '静默通知');
}

高级示例

import { BarkClient, BarkSounds, validateDeviceKey } from '@afjs/bark-sdk';

const DEVICE_KEY = 'your-device-key-here';

async function advancedExample() {
  // 验证设备密钥格式
  if (!validateDeviceKey(DEVICE_KEY)) {
    throw new Error('设备密钥格式不正确');
  }

  const client = new BarkClient({
    deviceKey: DEVICE_KEY,
    defaultOptions: {
      group: 'Advanced Examples',
      isArchive: 1,
    },
  });

  // 高级推送选项
  await client.push({
    title: '系统监控警报',
    body: 'CPU 使用率超过 90%,请及时处理',
    level: 'timeSensitive',
    sound: BarkSounds.ALARM,
    badge: 5,
    url: 'https://monitor.example.com',
    automaticallyCopy: 1,
    icon: 'https://example.com/warning-icon.png',
  });

  // 批量推送
  const notifications = [
    {
      title: '任务完成',
      body: '数据备份已完成',
      sound: BarkSounds.CHIME,
    },
    {
      title: '新用户注册',
      body: '[email protected] 已注册',
      sound: BarkSounds.NEWMAIL,
    },
    {
      title: '服务器状态',
      body: '所有服务运行正常',
      level: 'passive' as const,
    },
  ];

  const results = await Promise.allSettled(
    notifications.map(notification => client.push(notification))
  );

  results.forEach((result, index) => {
    if (result.status === 'fulfilled') {
      console.log(`通知 ${index + 1} 发送成功`);
    } else {
      console.error(`通知 ${index + 1} 发送失败:`, result.reason.message);
    }
  });
}

定时推送示例

import { BarkClient } from '@afjs/bark-sdk';

const client = new BarkClient({
  deviceKey: 'your-device-key'
});

// 定时推送函数
function scheduleNotification(delay: number, message: string) {
  setTimeout(async () => {
    try {
      await client.sendText(message, '定时通知');
      console.log(`定时消息发送成功: ${message}`);
    } catch (error) {
      console.error('定时消息发送失败:', error.message);
    }
  }, delay);
}

// 设置多个定时推送
scheduleNotification(2000, '2秒后的消息');
scheduleNotification(4000, '4秒后的消息');
scheduleNotification(6000, '6秒后的消息');

错误处理示例

import { BarkClient } from '@afjs/bark-sdk';

const client = new BarkClient({
  deviceKey: 'your-device-key'
});

async function handleErrors() {
  try {
    await client.sendText('测试消息', '测试');
    console.log('消息发送成功');
  } catch (error) {
    if (error.message.includes('设备密钥')) {
      console.error('设备密钥错误,请检查配置');
    } else if (error.message.includes('网络')) {
      console.error('网络连接失败,请检查网络');
    } else {
      console.error('发送失败:', error.message);
    }
  }
}

配置选项

自定义服务器

如果您使用自建的 Bark 服务器,可以指定自定义服务器地址:

const client = new BarkClient({
  deviceKey: 'your-device-key',
  serverUrl: 'https://your-bark-server.com'
});

默认选项

可以为客户端设置默认的推送选项,这些选项会应用到所有推送消息:

const client = new BarkClient({
  deviceKey: 'your-device-key',
  defaultOptions: {
    group: 'MyApp',
    sound: BarkSounds.CHIME,
    isArchive: 1,
    level: 'active'
  }
});

// 这条消息会自动应用上述默认选项
await client.sendText('使用默认配置的消息');

推送级别说明

  • active:默认级别,正常显示推送
  • timeSensitive:时间敏感,即使在勿扰模式下也会显示
  • passive:被动级别,不会点亮屏幕或播放声音

声音配置

// 使用预定义声音常量
await client.sendWithSound('消息', BarkSounds.BELL);

// 使用自定义声音名称
await client.sendWithSound('消息', 'custom-sound');

// 静音推送
await client.sendWithSound('消息', BarkSounds.SILENCE);

最佳实践

1. 错误处理

始终使用 try-catch 包装推送操作:

try {
  await client.sendText('重要消息');
} catch (error) {
  // 记录错误日志
  console.error('推送失败:', error.message);
  // 可以考虑重试或使用备用通知方式
}

2. 批量推送

对于多条消息,使用 Promise.allSettled 确保部分失败不影响其他消息:

const messages = ['消息1', '消息2', '消息3'];
const results = await Promise.allSettled(
  messages.map(msg => client.sendText(msg))
);

3. 频率控制

避免短时间内发送大量推送,建议添加延迟:

for (const message of messages) {
  await client.sendText(message);
  await new Promise(resolve => setTimeout(resolve, 1000)); // 1秒延迟
}

4. 设备密钥验证

在使用前验证设备密钥格式:

import { validateDeviceKey } from '@afjs/bark-sdk';

if (!validateDeviceKey(deviceKey)) {
  throw new Error('设备密钥格式不正确');
}

5. 环境配置

在生产环境中,将设备密钥等敏感信息存储在环境变量中:

const client = new BarkClient({
  deviceKey: process.env.BARK_DEVICE_KEY!,
  serverUrl: process.env.BARK_SERVER_URL
});

故障排除

常见问题

  1. 推送发送失败

    • 检查设备密钥是否正确
    • 确认网络连接正常
    • 验证服务器地址是否可访问
  2. 收不到推送

    • 确认 Bark 应用已安装并正确配置
    • 检查 iOS 通知权限设置
    • 验证设备密钥是否匹配
  3. 声音不播放

    • 检查设备静音模式设置
    • 确认声音名称拼写正确
    • 验证推送级别设置

调试技巧

启用详细日志输出:

const client = new BarkClient({
  deviceKey: 'your-device-key'
});

// 测试连接
try {
  const result = await client.test();
  console.log('测试成功:', result);
} catch (error) {
  console.error('测试失败:', error.message);
}

更新日志

v1.0.0

  • 初始版本发布
  • 支持所有 Bark 推送功能
  • 提供 TypeScript 类型定义
  • 包含完整的示例和文档

许可证

MIT License - 详见 LICENSE 文件。

贡献

欢迎提交 Issue 和 Pull Request!

相关链接


如果这个 SDK 对您有帮助,请给项目一个 ⭐️ Star!