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 🙏

© 2024 – Pkg Stats / Ryan Hefner

@artegoser/fluent

v1.0.0

Published

Better Fluent integration for JavaScript

Downloads

4

Readme

@artegoser/fluent

Better Fluent integration for JavaScript.

The library is fork of @moebius/fluent

Features

  • Simplifies usage of Fluent,

  • Allows you to specify translations as text or load them from the filesystem,

  • Supports automatic language negotiation and fallback based on the registered locales and the locales supported by the client,

  • Supports attributes out of the box,

  • All LTS Node.js versions are supported (starting from Node 12),

  • Written completely in TypeScript from scratch in a very strict manner with 100% type coverage (and no any's), ensuring that the library code is correct (type safe) by itself and also provides high quality typing declarations to make sure that your code is also correct and type safe,

  • Enables amazing type completion for your IDE (even if you are not using TypeScript) thanks to the provided typing declarations,

  • Minimal possible dependencies (all are high quality ones) updated to the latest versions,

  • Source maps for the library is generated and provided to you for easier debugging,

  • warning handling and logging are fully customizable to suit your individual needs.

Install

Install the library:

npm install --save @artegoser/fluent

Usage

Add translations

import { Fluent } from "@artegoser/fluent";

// Instantiate a Fluent class
const fluent = new Fluent();

// Add as many translations as you need fo your Fluent instance
await fluent.addTranslation({
  locales: "en",
  source: `
-brand-name = Super Project

welcome =
  Welcome, {$name}, to the {-brand-name}!
  Your balance is: {
    NUMBER($value, maximumFractionDigits: 2)
  }
  You have { NUMBER($applesCount) ->
    [0] no apples
    [one] {$applesCount} apple
    *[other] {$applesCount} apples
  }

  `,
});

await fluent.addTranslation({
  locales: "ru",
  source: `
-brand-name = Супер Проект

welcome =
  Добро пожаловать, {$name}, в {-brand-name}!
  У Вас на счету: {
    NUMBER($value, maximumFractionDigits: 2)
  }
  У вас { NUMBER($applesCount) ->
    [0] нет яблок
    [one] {$applesCount} яблоко
    [few] {$applesCount} яблока
    *[other] {$applesCount} яблок
  }
  `,
});

Use the Fluent instance directly

const output = fluent.translate("ru", "welcome", {
  name: "Slava",
  value: 100.12345,
  applesCount: 5,
});

console.log(output);

Bind the locale

You can use a helper-method to bind the specified locale for you:

// Use `withLocale()` method to create
// translation function bound
// to the specified locale:
const translate = fluent.withLocale("ru");

// You can also use a shorthand syntax:
const t = fluent.withLocale("ru");

output = translate("welcome", {
  name: "Slava",
  value: 100.12345,
  applesCount: 5,
});

output = t("hello");

Load translations from file system

await fluent.addTranslation({
  locales: "ru",
  filePath: `${__dirname}/translation.ru.ftl`,
});

You can specify multiple files via an array.

If later files would contain messages with the previously used IDs they will overwrite previous messages:

await fluent.addTranslation({
  locales: "ru",
  filePath: [
    `${__dirname}/feature-1/translation.ru.ftl`,
    `${__dirname}/feature-2/translation.ru.ftl`,
  ],
});

Specify bundle options

await fluent.addTranslation({
  locales: "ru",
  source: `…`,
  bundleOptions: {
    // This will disable appearance of "space"
    // characters around placeables
    useIsolating: false,
  },
});

Language negotiation and fallback

This library implements smart language negotiation and a fallback logic. It works the following way:

  1. You add translations and specify supported locale(s) for each translation.

  2. When calling translate() you specify locale(s) supported by your user.

  3. The library will automatically match requested locale(s) with the registered translations and will build a prioritized list of translations that could be used.

  4. The library will then try to find requested message in the best possible translation and if it's not available it will try another translation in set.

  5. If all matched translations doesn't have the specified message, then the generic placeholder will be returned instead (e.g. {message-id}). The library will also generate warning messages in the console to let you know when any specific translation doesn't have the specified message (so you can fix it). Warning handling and logging could be easily customized.

Warning handling

By default, Fluent will log all the warnings using console.warn. However, this could easily be customized.

Using custom logging function

import { Fluent, LoggingWarningHandler } from "@artegoser/fluent";

// Instructing Fluent to use custom logging function
const fluent = new Fluent({
  warningHandler: new LoggingWarningHandler({
    logFunction: (...args) => {
      // @todo: implement your custom logging function
    },
  }),
});

See the custom-logger example.

Using custom warning handler

import { Fluent, WarningHandler, Warning } from "@artegoser/fluent";

class MyWarningHandler implements WarningHandler {
  public handleWarning(warning: Warning): void {
    // @todo: implement your custom warning handling,
    //        the `warning` object contains useful exception details
  }
}

const fluent = new Fluent({
  warningHandler: new MyWarningHandler(),
});

See the warning-handler example.

Examples

You can find various usage examples in the examples directory of the library.

Running examples

In order to run any example on your machine, do the following:

  1. Clone the repository:

    git clone https://github.com/artegoser/fluent.git
    cd ./fluent
  2. Install all the dependencies:

    npm install
  3. Run the following command:

    npx ts-node \
      -P ./tsconfig.examples.json \
      -r tsconfig-paths/register \
      {PATH TO EXAMPLE}

    Example:

    npx ts-node \
      -P ./tsconfig.examples.json \
      -r tsconfig-paths/register \
      ./examples/general.ts

    Output of the executed requests will be logged to the terminal.

License (MIT)

Copyright © 2021 Slava Fomin II

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.