intl-formatter 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Gaurav Gorade
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,348 @@
1
+ # intl-formatter
2
+
3
+ [![npm version](https://img.shields.io/npm/v/intl-formatter.svg?style=flat-square)](https://www.npmjs.com/package/intl-formatter)
4
+ [![license](https://img.shields.io/npm/l/intl-formatter.svg?style=flat-square)](https://github.com/gauravgorade/intl-formatter/blob/main/LICENSE)
5
+ [![bundle size](https://img.shields.io/bundlephobia/minzip/intl-formatter?style=flat-square)](https://bundlephobia.com/package/intl-formatter)
6
+
7
+ Zero-dependency, isomorphic Intl formatting library for JavaScript and TypeScript. Seven synchronous, crash-safe methods for numbers, currency, percentages, durations, dates, and relative time. Identical output on server and client with no hydration mismatches, no framework lock-in, and built-in LRU caching of Intl instances. Under 3KB gzipped.
8
+
9
+ Works in Node.js, React, Next.js App Router, Express, Bun, Deno, and edge runtimes.
10
+
11
+ ## Installation
12
+
13
+ ```bash
14
+ npm install intl-formatter
15
+ yarn add intl-formatter
16
+ pnpm add intl-formatter
17
+ bun add intl-formatter
18
+ ```
19
+
20
+ ## Quick Start
21
+
22
+ Call `createFormatter` once and import the instance wherever you need it.
23
+
24
+ ```typescript
25
+ import { createFormatter } from "intl-formatter";
26
+
27
+ const fmt = createFormatter({
28
+ locale: "en-US",
29
+ currency: "USD",
30
+ rules: {
31
+ compactThreshold: 10000,
32
+ minimumFractionDigits: 0,
33
+ maximumFractionDigits: 2,
34
+ },
35
+ });
36
+
37
+ fmt.number(1500000); // "1.5M"
38
+ fmt.currency(49.9); // "$49.9"
39
+ fmt.percentage(12.5); // "12.5%"
40
+ fmt.duration(5400); // "1h 30m"
41
+ fmt.date(new Date()); // "Jan 15, 2024"
42
+ fmt.relativeTime(new Date(Date.now() - 60000)); // "1 minute ago"
43
+ ```
44
+
45
+ ## API
46
+
47
+ All methods are synchronous and crash-safe. Invalid inputs return the configured `fallback` value, which defaults to `"—"`.
48
+
49
+ | Method | Signature | Output |
50
+ | :--- | :--- | :--- |
51
+ | `number` | `number(value, options?)` | `"10.5K"` |
52
+ | `currency` | `currency(value, options?)` | `"$49.9K"` |
53
+ | `percentage` | `percentage(value, options?)` | `"12.5%"` |
54
+ | `duration` | `duration(value, options?)` | `"2m 30s"` |
55
+ | `date` | `date(value, options?)` | `"Jan 15, 2024"` |
56
+ | `dateTime` | `dateTime(value, options?)` | `"Jan 15, 2024, 2:30 PM"` |
57
+ | `relativeTime` | `relativeTime(value, now?)` | `"3 minutes ago"` |
58
+
59
+ ## Node.js / Express / Bun / Deno
60
+
61
+ ```javascript
62
+ import { createFormatter } from "intl-formatter";
63
+
64
+ const fmt = createFormatter({ locale: "de-DE", currency: "EUR" });
65
+
66
+ fmt.number(12500); // "12,5K"
67
+ fmt.currency(99.90); // "99,90 €"
68
+ ```
69
+
70
+ ## React
71
+
72
+ Define the config outside the component so the reference stays stable across renders.
73
+
74
+ ```tsx
75
+ import { createFormatter } from "intl-formatter";
76
+
77
+ const fmt = createFormatter({ locale: "en-US", currency: "USD" });
78
+
79
+ export function Price({ amount }: { amount: number }) {
80
+ return <span>{fmt.currency(amount)}</span>;
81
+ }
82
+ ```
83
+
84
+ For apps that need the formatter available across the component tree, copy this provider and hook into your project.
85
+
86
+ **`lib/formatter-provider.tsx`**
87
+
88
+ ```tsx
89
+ "use client";
90
+
91
+ import React, { createContext, useContext, useMemo } from "react";
92
+ import { createFormatter } from "intl-formatter";
93
+ import type { Formatter, FormatterConfig } from "intl-formatter";
94
+
95
+ const FormatterContext = createContext<Formatter | null>(null);
96
+
97
+ export function FormatterProvider({
98
+ config,
99
+ children,
100
+ }: {
101
+ config: FormatterConfig;
102
+ children: React.ReactNode;
103
+ }) {
104
+ const formatter = useMemo(
105
+ () => createFormatter(config),
106
+ // eslint-disable-next-line react-hooks/exhaustive-deps
107
+ [config.locale, config.currency, JSON.stringify(config.rules)]
108
+ );
109
+ return (
110
+ <FormatterContext.Provider value={formatter}>
111
+ {children}
112
+ </FormatterContext.Provider>
113
+ );
114
+ }
115
+
116
+ export function useFormatter() {
117
+ const ctx = useContext(FormatterContext);
118
+ if (!ctx) throw new Error("useFormatter must be used within a FormatterProvider");
119
+ return ctx;
120
+ }
121
+ ```
122
+
123
+ **`src/main.tsx`**
124
+
125
+ ```tsx
126
+ import { FormatterProvider } from "@/lib/formatter-provider";
127
+
128
+ const formatterConfig = { locale: "en-US", currency: "USD" };
129
+
130
+ ReactDOM.createRoot(document.getElementById("root")!).render(
131
+ <FormatterProvider config={formatterConfig}>
132
+ <App />
133
+ </FormatterProvider>
134
+ );
135
+ ```
136
+
137
+ **In any component**
138
+
139
+ ```tsx
140
+ import { useFormatter } from "@/lib/formatter-provider";
141
+
142
+ export function Price({ amount }: { amount: number }) {
143
+ const fmt = useFormatter();
144
+ return <span>{fmt.currency(amount)}</span>;
145
+ }
146
+ ```
147
+
148
+ ## Next.js App Router
149
+
150
+ Next.js requires separate handling for server and client. Server components call `getFormatter()` directly. Client components use `useFormatter()` from context. Both produce identical output.
151
+
152
+ **`lib/formatter/server.ts`**
153
+
154
+ ```typescript
155
+ import { headers } from "next/headers";
156
+ import { createFormatter } from "intl-formatter";
157
+ import type { FormatterConfig } from "intl-formatter";
158
+
159
+ export async function getFormatterConfig(): Promise<FormatterConfig> {
160
+ const headersList = await headers();
161
+ const locale = headersList.get("accept-language")?.split(",")[0] ?? "en-US";
162
+ return { locale, currency: "USD" };
163
+ }
164
+
165
+ export async function getFormatter() {
166
+ return createFormatter(await getFormatterConfig());
167
+ }
168
+ ```
169
+
170
+ > [!WARNING]
171
+ > Calling `headers()` opts the route out of static generation. If you need static pages, resolve locale via URL params (e.g. `/[locale]/page.tsx`) instead.
172
+
173
+ **`lib/formatter/client.tsx`**
174
+
175
+ ```tsx
176
+ "use client";
177
+
178
+ import React, { createContext, useContext, useMemo } from "react";
179
+ import { createFormatter } from "intl-formatter";
180
+ import type { Formatter, FormatterConfig } from "intl-formatter";
181
+
182
+ const FormatterContext = createContext<Formatter | null>(null);
183
+
184
+ export function FormatterProvider({
185
+ config,
186
+ children,
187
+ }: {
188
+ config: FormatterConfig;
189
+ children: React.ReactNode;
190
+ }) {
191
+ const formatter = useMemo(
192
+ () => createFormatter(config),
193
+ // eslint-disable-next-line react-hooks/exhaustive-deps
194
+ [config.locale, config.currency, JSON.stringify(config.rules)]
195
+ );
196
+ return (
197
+ <FormatterContext.Provider value={formatter}>
198
+ {children}
199
+ </FormatterContext.Provider>
200
+ );
201
+ }
202
+
203
+ export function useFormatter() {
204
+ const ctx = useContext(FormatterContext);
205
+ if (!ctx) throw new Error("useFormatter must be used within a FormatterProvider");
206
+ return ctx;
207
+ }
208
+ ```
209
+
210
+ **`app/layout.tsx`**
211
+
212
+ ```tsx
213
+ import { FormatterProvider } from "@/lib/formatter/client";
214
+ import { getFormatterConfig } from "@/lib/formatter/server";
215
+
216
+ export default async function RootLayout({ children }: { children: React.ReactNode }) {
217
+ const config = await getFormatterConfig();
218
+ return (
219
+ <html>
220
+ <body>
221
+ <FormatterProvider config={config}>{children}</FormatterProvider>
222
+ </body>
223
+ </html>
224
+ );
225
+ }
226
+ ```
227
+
228
+ **In any server component**
229
+
230
+ ```tsx
231
+ import { getFormatter } from "@/lib/formatter/server";
232
+
233
+ export default async function PricingPage() {
234
+ const fmt = await getFormatter();
235
+ return <h1>Total: {fmt.currency(12500)}</h1>;
236
+ }
237
+ ```
238
+
239
+ **In any client component**
240
+
241
+ ```tsx
242
+ "use client";
243
+
244
+ import { useFormatter } from "@/lib/formatter/client";
245
+
246
+ export function Price({ amount }: { amount: number }) {
247
+ const fmt = useFormatter();
248
+ return <span>{fmt.currency(amount)}</span>;
249
+ }
250
+ ```
251
+
252
+ ## Next.js Pages Router
253
+
254
+ ```tsx
255
+ import { FormatterProvider } from "@/lib/formatter/client";
256
+
257
+ const formatterConfig = { locale: "en-US", currency: "USD" };
258
+
259
+ export default function App({ Component, pageProps }) {
260
+ return (
261
+ <FormatterProvider config={formatterConfig}>
262
+ <Component {...pageProps} />
263
+ </FormatterProvider>
264
+ );
265
+ }
266
+ ```
267
+
268
+ ## Advanced
269
+
270
+ ### CLDR Pluralization Rules
271
+
272
+ For languages with complex plural rules such as Russian, Arabic, or Polish, pass a `PluralForm` object mapping Unicode CLDR categories (`one`, `few`, `many`, `two`, `zero`, `other`).
273
+
274
+ ```typescript
275
+ const ruFmt = createFormatter({ locale: "ru-RU" });
276
+
277
+ ruFmt.duration(7200, {
278
+ format: "verbose",
279
+ labels: {
280
+ hour: { one: "час", few: "часа", many: "часов", other: "часов" },
281
+ },
282
+ }); // "2 часа"
283
+ ```
284
+
285
+ ### High-Precision Duration Decimals
286
+
287
+ ```typescript
288
+ fmt.duration(1.543, { fractionalDigits: 2 }); // "1.54s"
289
+ ```
290
+
291
+ ### Specialized Fallback Hierarchies
292
+
293
+ ```typescript
294
+ const fmt = createFormatter({
295
+ rules: {
296
+ numberFallback: "No Number",
297
+ dateFallback: "No Date",
298
+ fallback: "N/A",
299
+ },
300
+ });
301
+
302
+ fmt.number(null); // "No Number"
303
+ fmt.percentage(null); // "N/A"
304
+ fmt.number(null, { fallback: "Override" }); // "Override"
305
+ ```
306
+
307
+ ### UNIX Timestamp Parsing
308
+
309
+ 10-digit numeric strings are treated as second-based UNIX timestamps and multiplied by 1000. Strings of 12 or more digits are used as milliseconds directly.
310
+
311
+ ```typescript
312
+ fmt.date("1705320000"); // "Jan 15, 2024"
313
+ fmt.date("1705320000000"); // "Jan 15, 2024"
314
+ ```
315
+
316
+ ## Types
317
+
318
+ ```typescript
319
+ import type {
320
+ Formatter,
321
+ FormatterConfig,
322
+ FormatterRules,
323
+ NumericInput,
324
+ DateInput,
325
+ NumberOptions,
326
+ CurrencyOptions,
327
+ PercentageOptions,
328
+ DurationOptions,
329
+ DateOptions,
330
+ DateTimeOptions,
331
+ } from "intl-formatter";
332
+ ```
333
+
334
+ ## Testing
335
+
336
+ `intl-formatter/testing` exports stable, non-localized mocks so snapshots do not break across environments.
337
+
338
+ ```typescript
339
+ import { mockFormatter } from "intl-formatter/testing";
340
+
341
+ vi.mock("intl-formatter", () => ({
342
+ createFormatter: () => mockFormatter,
343
+ }));
344
+ ```
345
+
346
+ ## License
347
+
348
+ MIT © [gauravgorade](https://github.com/gauravgorade)