@beweco/utils-js

中文文档
0.0.23发布于 2026/10/07MITTypeScriptCommonJS近 30 天下载 2663

Utilidades de validación para BeWe

原始使用文档
文档目录17 节
  1. Installation
  2. Usage
  3. Phone Validation
  4. Tolgee Localization
  5. API Reference
  6. Phone Validation
  7. Tolgee Localization
  8. HTTP client
  9. Voice recording core ( @beweco/utils-js/voice )
  10. Development
  11. Prerequisites
  12. Available Scripts
  13. Publishing
  14. Manual Release
  15. First-time Setup
  16. Contributing
  17. License

@beweco/utils

Utility library for phone number validation and Tolgee localization management.

Installation

npm install @beweco/utils-js

Usage

Phone Validation

import { validatePhone } from '@beweco/utils-js';

// Validate a Chilean mobile number
const { isValid, formattedNumber, error } = validatePhone('912345678');
if (isValid) {
  console.log(formattedNumber); // '+56912345678'
} else {
  console.log(error);
}

// Validate with different country code
const result = validatePhone('912345678', '+1');

Tolgee Localization

import { 
  getAllKeysTolgee, 
  downloadTranslations, 
  uploadOnlyNewKeysToTolgee, 
  uploadToTolgee,
  getAvailableLanguages 
} from '@beweco/utils-js';

// Configuration
const config = {
  apiKey: 'your-tolgee-api-key',
  projectId: 'your-project-id',
  baseUrl: 'https://app.tolgee.io' // optional, defaults to this value
};

// Get all available languages
const languages = await getAvailableLanguages(config);

// Get all keys from project
const keys = await getAllKeysTolgee(config);

// Download all translations
const translations = await downloadTranslations(config);

// Upload new keys only
const uploadResult = await uploadOnlyNewKeysToTolgee({
  ...config,
  language: 'es-AR',
  namespace: 'common',
  data: {
    'welcome': 'Bienvenido',
    'hello': 'Hola'
  }
});

// Upload all keys (including duplicates)
const uploadAllResult = await uploadToTolgee({
  ...config,
  language: 'es-AR',
  namespace: 'common',
  data: {
    'welcome': 'Bienvenido',
    'hello': 'Hola'
  }
});

API Reference

Phone Validation

validatePhone(phone: string, countryCode?: string): PhoneValidationResult

Validates and formats a phone number.

Parameters:

  • phone - The phone number to validate
  • countryCode - Optional country code (default: '+56' for Chile)

Returns: PhoneValidationResult

interface PhoneValidationResult {
  isValid: boolean;
  formattedNumber?: string;
  error?: string;
}

Validation Rules:

  • Must be a mobile number (starts with 9)
  • Must be 9 digits long (excluding country code)
  • Can be provided with or without country code
  • Automatically formats to international format (e.g., '+56912345678')

Tolgee Localization

Types

interface TolgeeConfig {
  apiKey: string;
  projectId: string;
  baseUrl?: string;
}

interface Language {
  tag: string;
  name: string;
  originalName: string;
}

interface TranslationData {
  [key: string]: string;
}

interface DownloadTranslationsResult {
  languages: Language[];
  translations: {
    [language: string]: {
      [namespace: string]: {
        [key: string]: string;
      };
    };
  };
}

interface UploadResult {
  uploaded?: number;
  [key: string]: unknown;
}

Functions

getAvailableLanguages(config: TolgeeConfig): Promise<Language[]>

Gets all available languages in the Tolgee project.

getAllKeysTolgee(config: TolgeeConfig): Promise<string[]>

Gets all keys from the Tolgee project with pagination support.

downloadTranslations(config: TolgeeConfig & { namespace?: string }): Promise

Downloads all translations organized by language and namespace.

Parameters:

  • config - Tolgee configuration
  • namespace - Optional namespace filter
uploadOnlyNewKeysToTolgee(config: TolgeeConfig & { language: string; namespace: string; data: TranslationData }): Promise

Uploads only new keys that don't exist in the project.

Parameters:

  • config - Tolgee configuration
  • language - Target language (e.g., 'es-AR')
  • namespace - Namespace (e.g., 'common')
  • data - Translation data object
uploadToTolgee(config: TolgeeConfig & { language: string; namespace: string; data: TranslationData }): Promise

Uploads all keys without checking for duplicates.

Parameters:

  • config - Tolgee configuration
  • language - Target language (e.g., 'es-AR')
  • namespace - Namespace (e.g., 'common')
  • data - Translation data object

Constants

const DEFAULT_BASE_URL = 'https://app.tolgee.io';
const DEFAULT_PAGE_SIZE = 1000;

HTTP client

createHttpClient(baseURL, options) returns an axios instance that unwraps response.data. Failed requests do not reject: they resolve with error.response.data (the gateway error envelope, or undefined when no response is received, e.g. network error or timeout).

401 handling:

  • A 401 triggers a token refresh against refreshPath and retries the original request with the new access token. Concurrent 401s share a single refresh.
  • A 401 whose envelope has error.code (or top-level message) equal to access_denied is an account access denial (e.g. an expired free trial), not an expired token: it is returned as-is, with no refresh and no retry.
  • onAuthError is called only when the refresh endpoint rejects the credentials (any 4xx). On network errors, timeouts and 5xx the reactive refresh retries once and keeps the session.

Voice recording core (@beweco/utils-js/voice)

Framework-agnostic (no React, no UI framework) core for batch voice recording with MediaRecorder. It is a separate subpath export on purpose — consumers who only need to record audio should not pull in axios, cookies or locale handling.

import { createVoiceRecorder, toTranscriptionFormData } from '@beweco/utils-js/voice';

const recorder = createVoiceRecorder();
const unsubscribe = recorder.subscribe(() => {
  // re-read recorder.state / recorder.stream (e.g. from useSyncExternalStore)
});

const result = await recorder.start(); // "ok" | "denied" | "unavailable" | "unsupported" | "busy"
// ... later
const blob = await recorder.stop(); // Blob | null
if (blob) {
  const formData = toTranscriptionFormData(blob); // File "audio.<ext>" under field "audio"
}

recorder.dispose(); // release the microphone for good (e.g. on unmount)

This module only owns the recording primitive: it does not transcribe, upload, debounce clicks or invalidate stale starts across multiple calls to start() on a screen. The React hook, the record button and the HTTP adapter that talks to a transcription service live in each consuming app.

Level meter for a decorative waveform (Web Audio; returns 0 without it):

import { createAudioLevelMeter } from '@beweco/utils-js/voice';

const meter = createAudioLevelMeter(recorder.stream!); // after start() === "ok"
const level = meter.getLevel(); // RMS 0..1, read it from your own rAF loop
meter.dispose(); // disconnects and closes the AudioContext; idempotent

Note: the exports field in package.json restricts imports to @beweco/utils-js and @beweco/utils-js/voice — deep paths like @beweco/utils-js/dist/... no longer resolve. No current consumer uses them.

Development

Prerequisites

  • Node.js >= 24
  • npm

Important: This project requires Node.js version 24 or later. You can use .nvmrc file with:

nvm use

Available Scripts

  • npm run clean - Removes the dist directory
  • npm run build - Compiles TypeScript code
  • npm test - Runs Jest tests
  • npm run lint - Runs ESLint
  • npm run dev - Runs TypeScript compiler in watch mode

Publishing

This package uses automated publishing to NPM through GitHub Actions.

Manual Release

  1. Go to Actions → Publish NPM in GitHub
  2. Click Run workflow
  3. Select version bump type:
    • patch: Bug fixes (0.0.11 → 0.0.12)
    • minor: New features (0.0.11 → 0.1.0)
    • major: Breaking changes (0.0.11 → 1.0.0)

The workflow will automatically:

  • Run tests and build
  • Bump version in package.json
  • Create git tag and commit
  • Publish to NPM
  • Push changes back to repository

First-time Setup

Repository admins need to configure the "production" environment with NPM_TOKEN. See .github/DEPLOYMENT.md for detailed instructions.

Contributing

  1. Create a new branch from main
  2. Make your changes
  3. Write/update tests if necessary
  4. Run linting and tests: npm run lint && npm test
  5. Create a pull request
  6. After merge, use GitHub Actions to publish new version

License

MIT

版本与发布记录

@beweco/utils-js 共发布 21 个版本,首次发布于 2025/07/01;过去 12 个月发布了 14 个版本。

版本发布日期距今
0.0.23latest2026/10/071 个月前
0.0.19-qa.19qa2026/09/301 个月前
0.0.19-qa.182026/09/291 个月前
0.0.222026/09/231 个月前
0.0.19-qa.162026/09/211 个月前
0.0.212026/09/161 个月前

关于 @beweco/utils-js 的常见问题

@beweco/utils-js 是什么?

Utilidades de validación para BeWe

如何安装 @beweco/utils-js?

在项目目录运行 npm install @beweco/utils-js,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:typescript(>=4.5.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@beweco/utils-js 支持 TypeScript 吗?

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

@beweco/utils-js 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@beweco/utils-js 需要什么版本的 Node.js?

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

@beweco/utils-js 可以商用吗?

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

@beweco/utils-js 的下载量有多少?

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

@beweco/utils-js 还在维护吗?

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