@watchtowerobservability/activity-render 0.1.0 → 0.2.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/CHANGELOG.md +41 -0
- package/README.md +43 -4
- package/dist/format.d.cts +16 -0
- package/dist/format.d.ts +16 -0
- package/dist/index.cjs +151 -32
- package/dist/index.d.cts +6 -1
- package/dist/index.d.ts +6 -1
- package/dist/index.js +149 -32
- package/dist/vectors.d.cts +33 -0
- package/dist/vectors.d.ts +33 -0
- package/package.json +7 -4
- package/vectors.json +3127 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to `@watchtowerobservability/activity-render` are documented here, in the [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) format (`## [x.y.z] - YYYY-MM-DD`; Added, Changed, Fixed, Deprecated, Removed).
|
|
4
|
+
|
|
5
|
+
## Versioning policy
|
|
6
|
+
|
|
7
|
+
This package follows [Semantic Versioning](https://semver.org/). A patch release (`0.y.Z`) fixes bugs and changes nothing else. A minor release adds API surface and may deprecate; while the version is `0.y.z` it may also change behaviour, and every such change is listed under **Changed** with what to do about it. From `1.0.0` a minor release is additive only, and a removal needs a major release, preceded by at least one minor release that lists the API under **Deprecated**. How long a deprecated field or endpoint of the HTTP API keeps working, and the `Deprecation` and `Sunset` response headers: [versioning and deprecation](https://watchtowerops.net/docs/activity-versioning).
|
|
8
|
+
|
|
9
|
+
`CHANGELOG.md` and `vectors.json` are inside every published tarball (a test packs the package and checks).
|
|
10
|
+
|
|
11
|
+
## [0.2.0] - 2026-11-25
|
|
12
|
+
|
|
13
|
+
### Added
|
|
14
|
+
|
|
15
|
+
- **`timeZone` is honoured.** `render(event, theme, { timeZone: 'America/New_York' })` prints `{x|date}`, `{x|time}` and `{x|datetime}` as the wall clock of that IANA zone, the same text the server's `display` has for a viewer session minted with `time_zone` (or a read with `time_zone=`). New formatter `time` (`10:15`). Applies to RFC 3339 instants of 1970 to 2037; anything else, no zone, or a zone this runtime does not know prints as written. `Intl` is used only to read the zone's UTC offset; the text is built by the package. New `supportsTimeZone(zone)`.
|
|
16
|
+
- **Conformance vectors ship in the package:** `@watchtowerobservability/activity-render/vectors.json` (`cases[]: { name, event, theme, options, display, verified }`, the same file the server tests run) and `runVectors(render, vectors)`, which returns the cases a renderer gets wrong. Every case is verified against the server's renderer (its test over the shared file passes in CI).
|
|
17
|
+
- `CHANGELOG.md` and `vectors.json` are in the tarball.
|
|
18
|
+
|
|
19
|
+
### Changed
|
|
20
|
+
|
|
21
|
+
- **One published rounding rule, used by the server and this package:** `money` and `count` round the exact binary value of the double half to even (`0.125` is `0.12`, `2.5|count` is `2`), computed with BigInt arithmetic instead of `toFixed`, so every finite double matches. A number placeholder without a formatter prints as the server's JSON prints it (`1e-7`, `1e21`, `-0.0`, whole numbers to 64 bits in full) instead of JavaScript's `String(n)`. The rule and the unavoidable differences (`5.0`, float-literal `1e16`, integers above 2^53) are in the README. Exponent text matches the server (`e+NN`).
|
|
22
|
+
- The vectors file no longer carries one global "unverified" flag: each case says whether the server is known to produce it (`verified`), and `expected` is now `display`.
|
|
23
|
+
- `CHANGELOG.md` follows Keep a Changelog, with the versioning policy at the top.
|
|
24
|
+
|
|
25
|
+
### Fixed
|
|
26
|
+
|
|
27
|
+
- `npm pack` and `npm publish` work after a plain `npm ci` under `NODE_ENV=production` (or `--omit=dev`): `prepack` installs the dev dependencies the build needs from the lockfile first.
|
|
28
|
+
|
|
29
|
+
## [0.1.0] - 2026-11-25
|
|
30
|
+
|
|
31
|
+
### Added
|
|
32
|
+
|
|
33
|
+
- First release: `render(event, theme, { locale, timeZone })`, the renderer of the Activity API's `display=1` in TypeScript with no dependencies. Placeholders and formatters (`money`, `count`, `date`, `datetime`), outcome variants, locales (`pt-BR`, then `pt`), prefix templates, `fallbackTemplate` (`{action.noun}`, `{action.verb}`) and `failure_reason` from the theme's `failureReasons`. Checked against `testdata/activity-render-vectors.json`, which the server's tests read too. The server-side counterpart is `crates/wt-domain-activity` (`render.rs`, `failure.rs`, `templates.rs`); the vectors also cover the open-event fields (`progress`, `abandoned`, `imported`, `detail_ref`), the advice for an abandoned event and the fallback template for an action the theme does not know yet.
|
|
34
|
+
|
|
35
|
+
### Changed
|
|
36
|
+
|
|
37
|
+
- `failure_reason` follows the server: an event that is abandoned (`abandoned: true`, or `ext.abandoned` in a stored document) gets the theme's `abandoned` reason, with no `failureReasonPath` needed; otherwise the path decides as before. Four shared vectors in `testdata/activity-render-vectors.json` cover it.
|
|
38
|
+
|
|
39
|
+
### Fixed
|
|
40
|
+
|
|
41
|
+
- The `.d.cts` declarations are real CommonJS declarations (relative imports end in `.cjs`); `scripts/check-pack.mjs` installs the packed tarball outside the repository and compiles an import under `nodenext`, `node16` and `bundler` with `skipLibCheck: false`.
|
package/README.md
CHANGED
|
@@ -15,18 +15,57 @@ What it does, in this order: the action's template (exact key, else the longest
|
|
|
15
15
|
|
|
16
16
|
The event's own fields are all available as placeholders, the open-event ones too: `{progress.done}` of `{progress.total}`, `{abandoned}`, `{imported}`, `{label}`, `{detail_ref.bytes|count}`, `{metadata.error_code}`. The `failure_reason` is the advice of the theme's `failureReasons` for the code at `failureReasonPath` (for example `metadata.error_code`), rendered with the same placeholders and locales, `fallbackTemplate` reads a new action as a sentence (`{action.noun}`, `{action.verb}`) until the theme has a template for it.
|
|
17
17
|
|
|
18
|
-
|
|
18
|
+
## Time zones
|
|
19
|
+
|
|
20
|
+
`timeZone` is an IANA zone name written as the tz database spells it (`America/New_York`, `Asia/Kolkata`, `UTC`). It is what a viewer session minted with `time_zone` (and a server-key read with `time_zone=`) gives the server, and both sides then print the same text.
|
|
21
|
+
|
|
22
|
+
- `{x|date}` is `2026-11-24`, `{x|time}` is `10:15` and `{x|datetime}` is `2026-11-24 10:15`: the wall clock of the zone, to the minute.
|
|
23
|
+
- The value must be an RFC 3339 timestamp with an offset (`2026-11-24T10:15:30Z`, `...T10:15:30.5+02:00`). An offset in the text is honoured: it names an instant, which is then read in the zone.
|
|
24
|
+
- Text that is not such a timestamp (a date alone, a timestamp without an offset, a date that is not on the calendar, `Tuesday`), a UTC year before 1970 or after 2037 (the tz database has no rule past 2037, so a later instant is not guessed), no `timeZone` at all, or a zone this runtime does not know, prints as written: the first 10 or 16 characters of an ISO date, anything else unchanged. `supportsTimeZone(zone)` says whether the zone is known here.
|
|
25
|
+
- The zone's UTC offset at the instant is read with `Intl.DateTimeFormat(...).formatToParts` and nothing else; the text is built by this package, so output does not depend on the runtime's locale data. Without `Intl` (or without a zone's data) the fallback above applies: the text prints as written, which for the usual `...Z` timestamps is UTC.
|
|
26
|
+
- Both sides use the tz database of their runtime. A zone whose rules changed after one side's database was built (rare) can differ for the instants that moved; the vectors cover New York across both 2026 transitions, Asia/Kolkata (+05:30), Australia/Lord_Howe (30 minute DST) and UTC.
|
|
27
|
+
|
|
28
|
+
## Rounding and number text
|
|
29
|
+
|
|
30
|
+
The server is the reference; this package computes the same text for every finite double, with BigInt arithmetic on the exact value of the double (no `toFixed`).
|
|
31
|
+
|
|
32
|
+
- **`money` and `count`** read the placeholder's text as a number the way Rust's `f64` parser does (an optional sign, digits with an optional `.` and exponent; `inf`, `NaN`, hex, spaces and `1_0` are not numbers and print unchanged; a value that overflows to infinity prints unchanged). They then print the exact decimal expansion of the double rounded to 2 places (`money`; `JPY` has 0) or 0 places (`count`). Rounding is **half to even on the exact binary value**: `0.125` is `0.12`, `0.375` is `0.38`, `2.5|count` is `2`, `3.5|count` is `4`, `0.5|count` is `0`. A value that only looks like a tie in decimal is not one: `1.005` is `1.00`, `2.675` is `2.67`, `8.345` is `8.35`, because those doubles sit below or above the tie.
|
|
33
|
+
- **Sign.** `count` keeps the sign of the double: `-0.4|count` and `-0|count` are `-0`. `money` puts the minus before the symbol only when the value is below zero: `-0.001|money:USD` is `-$0.00` and `-0.0|money:USD` is `$0.00`.
|
|
34
|
+
- **Grouping.** Thousands are separated by `,` on the integer part; `USD`, `EUR`, `GBP` and `JPY` take `$`, `€`, `£` and `¥` before the digits, any other code follows them (`1,234.50 CHF`), no code prints the bare number. Amounts are in major units. A double of any size prints all its digits (`1e21|count` is `1,000,000,000,000,000,000,000`).
|
|
35
|
+
- **A number placeholder without a formatter** prints the way the server's JSON prints it: a whole number up to 64 bits prints its digits (`5`, `10000000000000000`), `-0` is `-0.0`, any other double prints its shortest round-trip digits as the server's JSON library does, with a sign on positive exponents: `0.1`, `1234.5`, `0.0001`, `1e-7`, `1.5e-7`, `1e+21`, `2.5e+20`. The exponent form is used from 1e16 up (for floats) and from 1e-6 down.
|
|
36
|
+
|
|
37
|
+
JSON numbers that cannot match, because JavaScript has lost the text: `5.0` (the server prints `5.0` for a float literal, this package prints `5`), `1e16` as a float literal (server `1e+16`, here `10000000000000000`), integers above 2^53 (`9007199254740993` arrives as `9007199254740992`), and integer literals beyond 64 bits (the server reads them as a double with its own parser and can differ in the last digit). They agree under `money` and `count`, which read the value, not the text. Send a number as a string when its exact text matters.
|
|
38
|
+
|
|
39
|
+
Values are cut at 200 code points after formatting, so the first 200 characters of a very long number are what both print.
|
|
40
|
+
|
|
41
|
+
## Conformance vectors
|
|
42
|
+
|
|
43
|
+
`vectors.json` ships in this package (`@watchtowerobservability/activity-render/vectors.json`) and is the file the server's test suite runs: one source of truth, copied from `testdata/activity-render-vectors.json` by the build, with a test that fails when the two differ.
|
|
44
|
+
|
|
45
|
+
```json
|
|
46
|
+
{ "cases": [ { "name": "...", "event": {}, "theme": {}, "options": { "locale": "de", "timeZone": "America/New_York" }, "display": {}, "verified": true } ] }
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Render `event` with `theme` and `options`; the result, serialized with `JSON.stringify`, must equal `display` (key order and omitted keys count). `verified` is `true` when the server's renderer is known to produce `display` (its unit test passed on it), `false` when the expectation was traced by hand and is awaiting its first server run.
|
|
50
|
+
|
|
51
|
+
```ts
|
|
52
|
+
import { runVectors, render } from '@watchtowerobservability/activity-render';
|
|
53
|
+
import vectors from '@watchtowerobservability/activity-render/vectors.json' with { type: 'json' };
|
|
54
|
+
|
|
55
|
+
expect(runVectors(render, vectors)).toEqual([]); // [{ name, expected, actual }] for each case that differs
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
`runVectors(yourRender, vectors)` accepts any function with the signature of `render`, so an app that wraps or reimplements the renderer can prove it still conforms.
|
|
19
59
|
|
|
20
60
|
## Parity
|
|
21
61
|
|
|
22
|
-
`testdata/activity-render-vectors.json` in the repository holds
|
|
62
|
+
`testdata/activity-render-vectors.json` in the repository holds the same cases. The Rust renderer (`crates/wt-domain-activity`) and this package both run it; the test here compares `JSON.stringify`, so key order and omitted keys must match too.
|
|
23
63
|
|
|
24
64
|
### Not guaranteed
|
|
25
65
|
|
|
26
66
|
Everything outside the vectors is the same algorithm but is not proven byte for byte. Known differences:
|
|
27
67
|
|
|
28
|
-
- **
|
|
29
|
-
- **Rounding of exact ties.** Rust rounds half to even on the exact binary value (`2.5|count` is `2`), and this package does it by hand. No shared vector covers a tie, so `0.125|money:USD` is the first thing to check if a mismatch is reported.
|
|
68
|
+
- **JSON number text and the 64-bit boundary.** See "Rounding and number text": `5.0`, a float-literal `1e16` and integers above 2^53 reach JavaScript already changed.
|
|
30
69
|
- **Digits.** Rust's `\d` in the ISO date check matches Unicode digits (a date written in Arabic-Indic digits is cut by bytes there and left alone here); this package matches ASCII digits only.
|
|
31
70
|
- **Characters.** Values are cut at 200 Unicode code points in both (a surrogate pair counts once here); control characters are the Unicode `Cc` set in both.
|
|
32
71
|
- **Theme merge.** The server merges the org default theme under the project's. `render` takes the theme you give it: pass the effective theme.
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `format!("{:.dec$}", n)` of Rust for a finite `n >= 0`: the exact decimal expansion of the double, rounded to `dec`
|
|
3
|
+
* places, an exact tie to the even digit. Pure BigInt arithmetic, no `toFixed`.
|
|
4
|
+
*/
|
|
5
|
+
export declare function fixed(n: number, dec: number): string;
|
|
6
|
+
/**
|
|
7
|
+
* The text of a JSON number, as the server prints it. Whole numbers in the range of a 64-bit integer print their digits
|
|
8
|
+
* (`5`, `10000000000000000`); negative zero is `-0.0`; every other double prints as serde_json does (`0.1`, `1e-7`, `1e+21`).
|
|
9
|
+
* A JavaScript number has lost whether the JSON text said `5` or `5.0` (the server prints `5.0` for the second): see README.
|
|
10
|
+
*/
|
|
11
|
+
export declare function numberText(n: number): string;
|
|
12
|
+
export type TimeKind = 'date' | 'datetime' | 'time';
|
|
13
|
+
/** Whether this runtime can convert times to `zone` (an IANA name written as the database spells it, such as `America/New_York`). */
|
|
14
|
+
export declare function supportsTimeZone(zone: string): boolean;
|
|
15
|
+
/** `v` as `kind`: in `zone` when it names a zone this runtime knows and `v` is an RFC 3339 timestamp, else as written. */
|
|
16
|
+
export declare function formatTime(v: string, kind: TimeKind, zone: string | null | undefined): string;
|
package/dist/format.d.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `format!("{:.dec$}", n)` of Rust for a finite `n >= 0`: the exact decimal expansion of the double, rounded to `dec`
|
|
3
|
+
* places, an exact tie to the even digit. Pure BigInt arithmetic, no `toFixed`.
|
|
4
|
+
*/
|
|
5
|
+
export declare function fixed(n: number, dec: number): string;
|
|
6
|
+
/**
|
|
7
|
+
* The text of a JSON number, as the server prints it. Whole numbers in the range of a 64-bit integer print their digits
|
|
8
|
+
* (`5`, `10000000000000000`); negative zero is `-0.0`; every other double prints as serde_json does (`0.1`, `1e-7`, `1e+21`).
|
|
9
|
+
* A JavaScript number has lost whether the JSON text said `5` or `5.0` (the server prints `5.0` for the second): see README.
|
|
10
|
+
*/
|
|
11
|
+
export declare function numberText(n: number): string;
|
|
12
|
+
export type TimeKind = 'date' | 'datetime' | 'time';
|
|
13
|
+
/** Whether this runtime can convert times to `zone` (an IANA name written as the database spells it, such as `America/New_York`). */
|
|
14
|
+
export declare function supportsTimeZone(zone: string): boolean;
|
|
15
|
+
/** `v` as `kind`: in `zone` when it names a zone this runtime knows and `v` is an RFC 3339 timestamp, else as written. */
|
|
16
|
+
export declare function formatTime(v: string, kind: TimeKind, zone: string | null | undefined): string;
|
package/dist/index.cjs
CHANGED
|
@@ -20,12 +20,147 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
20
20
|
// src/index.ts
|
|
21
21
|
var index_exports = {};
|
|
22
22
|
__export(index_exports, {
|
|
23
|
-
render: () => render
|
|
23
|
+
render: () => render,
|
|
24
|
+
runVectors: () => runVectors,
|
|
25
|
+
supportsTimeZone: () => supportsTimeZone
|
|
24
26
|
});
|
|
25
27
|
module.exports = __toCommonJS(index_exports);
|
|
28
|
+
|
|
29
|
+
// src/format.ts
|
|
30
|
+
function decompose(n) {
|
|
31
|
+
const view = new DataView(new ArrayBuffer(8));
|
|
32
|
+
view.setFloat64(0, n);
|
|
33
|
+
const hi = view.getUint32(0);
|
|
34
|
+
const mantissa = BigInt(hi & 1048575) << 32n | BigInt(view.getUint32(4));
|
|
35
|
+
const biased = hi >>> 20 & 2047;
|
|
36
|
+
return biased === 0 ? [mantissa, -1074] : [mantissa | 1n << 52n, biased - 1075];
|
|
37
|
+
}
|
|
38
|
+
function fixed(n, dec) {
|
|
39
|
+
const [m, e] = decompose(n);
|
|
40
|
+
const scale = 10n ** BigInt(dec);
|
|
41
|
+
let q;
|
|
42
|
+
if (e >= 0) {
|
|
43
|
+
q = (m << BigInt(e)) * scale;
|
|
44
|
+
} else {
|
|
45
|
+
const num = m * scale;
|
|
46
|
+
const den = 1n << BigInt(-e);
|
|
47
|
+
q = num / den;
|
|
48
|
+
const twice = num % den * 2n;
|
|
49
|
+
if (twice > den || twice === den && (q & 1n) === 1n) q += 1n;
|
|
50
|
+
}
|
|
51
|
+
const s = q.toString().padStart(dec + 1, "0");
|
|
52
|
+
return dec > 0 ? `${s.slice(0, s.length - dec)}.${s.slice(s.length - dec)}` : s;
|
|
53
|
+
}
|
|
54
|
+
function ryu(n) {
|
|
55
|
+
if (n === 0) return Object.is(n, -0) ? "-0.0" : "0.0";
|
|
56
|
+
const [mant, ex] = Math.abs(n).toExponential().split("e");
|
|
57
|
+
const digits = mant.replace(".", "");
|
|
58
|
+
const kk = Number(ex) + 1;
|
|
59
|
+
const pad = kk - digits.length;
|
|
60
|
+
let out;
|
|
61
|
+
if (pad >= 0 && kk <= 16) out = `${digits}${"0".repeat(pad)}.0`;
|
|
62
|
+
else if (kk > 0 && kk <= 16) out = `${digits.slice(0, kk)}.${digits.slice(kk)}`;
|
|
63
|
+
else if (kk > -5 && kk <= 0) out = `0.${"0".repeat(-kk)}${digits}`;
|
|
64
|
+
else {
|
|
65
|
+
const e = kk - 1 > 0 ? `e+${kk - 1}` : `e${kk - 1}`;
|
|
66
|
+
out = digits.length === 1 ? `${digits}${e}` : `${digits.slice(0, 1)}.${digits.slice(1)}${e}`;
|
|
67
|
+
}
|
|
68
|
+
return n < 0 ? `-${out}` : out;
|
|
69
|
+
}
|
|
70
|
+
function numberText(n) {
|
|
71
|
+
if (!Number.isFinite(n)) return String(n);
|
|
72
|
+
if (Object.is(n, -0)) return "-0.0";
|
|
73
|
+
if (Number.isInteger(n) && n >= -(2 ** 63) && n < 2 ** 64) return BigInt(n).toString();
|
|
74
|
+
return ryu(n);
|
|
75
|
+
}
|
|
76
|
+
var ISO = /^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2})?/;
|
|
77
|
+
var STAMP = /^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})$/;
|
|
78
|
+
function asWritten(v, kind) {
|
|
79
|
+
const m = ISO.exec(v);
|
|
80
|
+
const cut = (n) => m && m[0].length >= n ? v.slice(0, n) : v;
|
|
81
|
+
if (kind === "date") return cut(10);
|
|
82
|
+
if (kind === "datetime") return cut(16).split("T").join(" ");
|
|
83
|
+
const t = m?.[1];
|
|
84
|
+
return t !== void 0 ? t.slice(1) : v;
|
|
85
|
+
}
|
|
86
|
+
var zones = /* @__PURE__ */ new Map();
|
|
87
|
+
function zoneClock(zone) {
|
|
88
|
+
let f = zones.get(zone);
|
|
89
|
+
if (f === void 0) {
|
|
90
|
+
try {
|
|
91
|
+
f = new Intl.DateTimeFormat("en-US", {
|
|
92
|
+
timeZone: zone,
|
|
93
|
+
hourCycle: "h23",
|
|
94
|
+
year: "numeric",
|
|
95
|
+
month: "numeric",
|
|
96
|
+
day: "numeric",
|
|
97
|
+
hour: "numeric",
|
|
98
|
+
minute: "numeric",
|
|
99
|
+
second: "numeric"
|
|
100
|
+
});
|
|
101
|
+
} catch {
|
|
102
|
+
f = null;
|
|
103
|
+
}
|
|
104
|
+
zones.set(zone, f);
|
|
105
|
+
}
|
|
106
|
+
return f;
|
|
107
|
+
}
|
|
108
|
+
function supportsTimeZone(zone) {
|
|
109
|
+
return zoneClock(zone) !== null;
|
|
110
|
+
}
|
|
111
|
+
function offsetSeconds(clock, utcMs) {
|
|
112
|
+
const p = {};
|
|
113
|
+
for (const part of clock.formatToParts(new Date(utcMs))) if (part.type !== "literal") p[part.type] = Number(part.value);
|
|
114
|
+
const wall = Date.UTC(p.year, p.month - 1, p.day, p.hour % 24, p.minute, p.second);
|
|
115
|
+
return (wall - utcMs) / 1e3;
|
|
116
|
+
}
|
|
117
|
+
var two = (n) => String(n).padStart(2, "0");
|
|
118
|
+
function inZone(v, kind, zone) {
|
|
119
|
+
const clock = zoneClock(zone);
|
|
120
|
+
const m = STAMP.exec(v);
|
|
121
|
+
if (clock === null || m === null) return void 0;
|
|
122
|
+
const [year = 0, month = 0, day = 0, hour = 0, minute = 0, second = 0] = [1, 2, 3, 4, 5, 6].map((i) => Number(m[i]));
|
|
123
|
+
const stamp = Date.UTC(year, month - 1, day, hour, minute, second);
|
|
124
|
+
const check = new Date(stamp);
|
|
125
|
+
if (check.getUTCFullYear() !== year || check.getUTCMonth() + 1 !== month || check.getUTCDate() !== day || hour > 23 || minute > 59 || second > 59) return void 0;
|
|
126
|
+
const zoneText = m[7];
|
|
127
|
+
let shift = 0;
|
|
128
|
+
if (zoneText !== "Z") {
|
|
129
|
+
const [oh, om] = [Number(zoneText.slice(1, 3)), Number(zoneText.slice(4, 6))];
|
|
130
|
+
if (oh > 23 || om > 59) return void 0;
|
|
131
|
+
shift = (zoneText.startsWith("-") ? -1 : 1) * (oh * 3600 + om * 60);
|
|
132
|
+
}
|
|
133
|
+
const utcMs = stamp - shift * 1e3;
|
|
134
|
+
const utcYear = new Date(utcMs).getUTCFullYear();
|
|
135
|
+
if (utcYear < 1970 || utcYear > 2037) return void 0;
|
|
136
|
+
const local = new Date(utcMs + offsetSeconds(clock, utcMs) * 1e3);
|
|
137
|
+
const ymd = `${String(local.getUTCFullYear()).padStart(4, "0")}-${two(local.getUTCMonth() + 1)}-${two(local.getUTCDate())}`;
|
|
138
|
+
const hm = `${two(local.getUTCHours())}:${two(local.getUTCMinutes())}`;
|
|
139
|
+
return kind === "date" ? ymd : kind === "time" ? hm : `${ymd} ${hm}`;
|
|
140
|
+
}
|
|
141
|
+
function formatTime(v, kind, zone) {
|
|
142
|
+
return (zone ? inZone(v, kind, zone) : void 0) ?? asWritten(v, kind);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// src/vectors.ts
|
|
146
|
+
function runVectors(render2, vectors) {
|
|
147
|
+
const failures = [];
|
|
148
|
+
for (const c of vectors.cases) {
|
|
149
|
+
const expected = JSON.stringify(c.display);
|
|
150
|
+
let actual;
|
|
151
|
+
try {
|
|
152
|
+
actual = JSON.stringify(render2(c.event, c.theme, c.options));
|
|
153
|
+
} catch (e) {
|
|
154
|
+
actual = `threw ${String(e)}`;
|
|
155
|
+
}
|
|
156
|
+
if (actual !== expected) failures.push({ name: c.name, expected, actual });
|
|
157
|
+
}
|
|
158
|
+
return failures;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// src/index.ts
|
|
26
162
|
var MAX_VALUE_CHARS = 200;
|
|
27
163
|
var HOLE = /\{([A-Za-z0-9_.\-]+)((?:\|[a-z]+(?::[A-Za-z0-9_ .\-]*)?)*)\}/g;
|
|
28
|
-
var ISO = /^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2})?/;
|
|
29
164
|
var NUMBER = /^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/;
|
|
30
165
|
var CONTROL = /^[\u0000-\u001f\u007f-\u009f]$/;
|
|
31
166
|
var isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
@@ -36,7 +171,8 @@ function actionParts(action) {
|
|
|
36
171
|
}
|
|
37
172
|
function text(v) {
|
|
38
173
|
if (typeof v === "string") return v;
|
|
39
|
-
if (typeof v === "number"
|
|
174
|
+
if (typeof v === "number") return numberText(v);
|
|
175
|
+
if (typeof v === "boolean") return String(v);
|
|
40
176
|
return void 0;
|
|
41
177
|
}
|
|
42
178
|
function lookup(e, path) {
|
|
@@ -80,18 +216,6 @@ function parseNumber(s) {
|
|
|
80
216
|
const n = Number(s);
|
|
81
217
|
return Number.isFinite(n) ? n : void 0;
|
|
82
218
|
}
|
|
83
|
-
function fixed(n, dec) {
|
|
84
|
-
if (n >= 1e21) return BigInt(n).toString() + (dec > 0 ? "." + "0".repeat(dec) : "");
|
|
85
|
-
const full = n.toFixed(100);
|
|
86
|
-
const dot = full.indexOf(".");
|
|
87
|
-
const frac = full.slice(dot + 1);
|
|
88
|
-
const tie = frac[dec] === "5" && /^0*$/.test(frac.slice(dec + 1));
|
|
89
|
-
if (!tie) return n.toFixed(dec);
|
|
90
|
-
let digits = BigInt(full.slice(0, dot) + frac.slice(0, dec));
|
|
91
|
-
if (digits % 2n === 1n) digits += 1n;
|
|
92
|
-
const s = digits.toString().padStart(dec + 1, "0");
|
|
93
|
-
return dec > 0 ? `${s.slice(0, s.length - dec)}.${s.slice(s.length - dec)}` : s;
|
|
94
|
-
}
|
|
95
219
|
function group(s) {
|
|
96
220
|
const neg = s.startsWith("-");
|
|
97
221
|
const body = neg ? s.slice(1) : s;
|
|
@@ -119,11 +243,7 @@ function count(v) {
|
|
|
119
243
|
if (n === void 0) return v;
|
|
120
244
|
return group(`${n < 0 || Object.is(n, -0) ? "-" : ""}${fixed(Math.abs(n), 0)}`);
|
|
121
245
|
}
|
|
122
|
-
function
|
|
123
|
-
const m = ISO.exec(v);
|
|
124
|
-
return m && m[0].length >= n ? v.slice(0, n) : v;
|
|
125
|
-
}
|
|
126
|
-
function interpolate(tpl, event) {
|
|
246
|
+
function interpolate(tpl, event, zone) {
|
|
127
247
|
return tpl.replace(HOLE, (_m, path, fmts) => {
|
|
128
248
|
let v = lookup(event, path) ?? "";
|
|
129
249
|
for (const f of fmts.split("|")) {
|
|
@@ -133,8 +253,7 @@ function interpolate(tpl, event) {
|
|
|
133
253
|
const arg = c >= 0 ? f.slice(c + 1) : "";
|
|
134
254
|
if (name === "money") v = money(v, arg);
|
|
135
255
|
else if (name === "count") v = count(v);
|
|
136
|
-
else if (name === "date") v =
|
|
137
|
-
else if (name === "datetime") v = date(v, 16).split("T").join(" ");
|
|
256
|
+
else if (name === "date" || name === "datetime" || name === "time") v = formatTime(v, name, zone);
|
|
138
257
|
}
|
|
139
258
|
return clean(v);
|
|
140
259
|
});
|
|
@@ -163,7 +282,7 @@ function fallbackTitle(e) {
|
|
|
163
282
|
function tags(locale) {
|
|
164
283
|
return locale == null ? [] : [locale, locale.split("-")[0] ?? locale];
|
|
165
284
|
}
|
|
166
|
-
function renderTemplate(tpl, event, locale) {
|
|
285
|
+
function renderTemplate(tpl, event, locale, zone) {
|
|
167
286
|
if (!tpl) return { title: fallbackTitle(event) };
|
|
168
287
|
const chain = [];
|
|
169
288
|
for (const k of tags(locale)) if (tpl.locales && has(tpl.locales, k)) chain.push(tpl.locales[k]);
|
|
@@ -177,17 +296,17 @@ function renderTemplate(tpl, event, locale) {
|
|
|
177
296
|
break;
|
|
178
297
|
}
|
|
179
298
|
}
|
|
180
|
-
const out = { title: label === void 0 ? fallbackTitle(event) : interpolate(label, event) };
|
|
299
|
+
const out = { title: label === void 0 ? fallbackTitle(event) : interpolate(label, event, zone) };
|
|
181
300
|
const subtitle = chain.find((l) => l.subtitle != null)?.subtitle;
|
|
182
|
-
if (subtitle != null) out.subtitle = interpolate(subtitle, event);
|
|
301
|
+
if (subtitle != null) out.subtitle = interpolate(subtitle, event, zone);
|
|
183
302
|
const fields = (chain.find((l) => l.fields != null)?.fields ?? []).map((f) => ({
|
|
184
|
-
label: interpolate(f.label, event),
|
|
185
|
-
value: interpolate(f.value, event)
|
|
303
|
+
label: interpolate(f.label, event, zone),
|
|
304
|
+
value: interpolate(f.value, event, zone)
|
|
186
305
|
}));
|
|
187
306
|
if (fields.length > 0) out.fields = fields;
|
|
188
307
|
return out;
|
|
189
308
|
}
|
|
190
|
-
function failureReason(theme, event, locale) {
|
|
309
|
+
function failureReason(theme, event, locale, zone) {
|
|
191
310
|
if (!isObj(event) || event.outcome !== "failure") return void 0;
|
|
192
311
|
const path = theme.failureReasonPath ?? theme.failure_reason_path;
|
|
193
312
|
const reasons = theme.failureReasons ?? theme.failure_reasons;
|
|
@@ -203,15 +322,15 @@ function failureReason(theme, event, locale) {
|
|
|
203
322
|
for (const k of tags(locale)) if (r.locales && has(r.locales, k)) chain.push(r.locales[k]);
|
|
204
323
|
const t = chain.find((l) => l.text != null)?.text ?? r.text;
|
|
205
324
|
const a = chain.find((l) => l.action != null)?.action ?? r.action;
|
|
206
|
-
const out = { code, text: interpolate(t, event) };
|
|
207
|
-
if (a != null) out.action = { label: interpolate(a.label, event), url: a.url };
|
|
325
|
+
const out = { code, text: interpolate(t, event, zone) };
|
|
326
|
+
if (a != null) out.action = { label: interpolate(a.label, event, zone), url: a.url };
|
|
208
327
|
return out;
|
|
209
328
|
}
|
|
210
329
|
function render(event, theme, options = {}) {
|
|
211
330
|
const action = isObj(event) && typeof event.action === "string" ? event.action : void 0;
|
|
212
331
|
const found = action !== void 0 && theme.actions ? templateFor(theme.actions, action) : void 0;
|
|
213
|
-
const out = renderTemplate(found ?? theme.fallbackTemplate ?? theme.fallback_template ?? void 0, event, options.locale);
|
|
214
|
-
const reason = failureReason(theme, event, options.locale);
|
|
332
|
+
const out = renderTemplate(found ?? theme.fallbackTemplate ?? theme.fallback_template ?? void 0, event, options.locale, options.timeZone);
|
|
333
|
+
const reason = failureReason(theme, event, options.locale, options.timeZone);
|
|
215
334
|
if (reason) out.failure_reason = reason;
|
|
216
335
|
return out;
|
|
217
336
|
}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
export { supportsTimeZone } from './format.cjs';
|
|
2
|
+
export { runVectors, type VectorCase, type VectorFailure, type VectorFile } from './vectors.cjs';
|
|
1
3
|
export interface DisplayField {
|
|
2
4
|
label: string;
|
|
3
5
|
value: string;
|
|
@@ -52,7 +54,10 @@ export interface Display {
|
|
|
52
54
|
export interface RenderOptions {
|
|
53
55
|
/** Tag such as `pt-BR`; `pt-BR`, then `pt`, then the template's own copy. */
|
|
54
56
|
locale?: string | null;
|
|
55
|
-
/**
|
|
57
|
+
/**
|
|
58
|
+
* IANA zone (`America/New_York`) the `date`, `time` and `datetime` formatters print an RFC 3339 timestamp in, as the API does for a session
|
|
59
|
+
* minted with `time_zone`. Without it, with a zone `supportsTimeZone` refuses, or for text that is not such a timestamp, they print the text as written.
|
|
60
|
+
*/
|
|
56
61
|
timeZone?: string | null;
|
|
57
62
|
}
|
|
58
63
|
/**
|
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
export { supportsTimeZone } from './format.js';
|
|
2
|
+
export { runVectors, type VectorCase, type VectorFailure, type VectorFile } from './vectors.js';
|
|
1
3
|
export interface DisplayField {
|
|
2
4
|
label: string;
|
|
3
5
|
value: string;
|
|
@@ -52,7 +54,10 @@ export interface Display {
|
|
|
52
54
|
export interface RenderOptions {
|
|
53
55
|
/** Tag such as `pt-BR`; `pt-BR`, then `pt`, then the template's own copy. */
|
|
54
56
|
locale?: string | null;
|
|
55
|
-
/**
|
|
57
|
+
/**
|
|
58
|
+
* IANA zone (`America/New_York`) the `date`, `time` and `datetime` formatters print an RFC 3339 timestamp in, as the API does for a session
|
|
59
|
+
* minted with `time_zone`. Without it, with a zone `supportsTimeZone` refuses, or for text that is not such a timestamp, they print the text as written.
|
|
60
|
+
*/
|
|
56
61
|
timeZone?: string | null;
|
|
57
62
|
}
|
|
58
63
|
/**
|