Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.
TypeScript 3dagent-skillsai-agentsai-videobevyclaude-codegame-enginegpulinuxmacosmotion-designmotion-graphicsreactrusttypescriptvideo-editingvideo-renderingwgpuwindows
Intl on QuickJS: a composition that formats a number works on Windows and Linux (#169)
shinyobjectz917bc94f5959
diff --git a/Cargo.lock b/Cargo.lockindex bb598681..7a25bb1b 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -15349,6 +15349,8 @@ dependencies = [name = "raea-runtime-jsengine"version = "0.1.0"dependencies = [+ "iana-time-zone",+ "miniz_oxide 0.8.9","objc2 0.6.5","raea-io-home","rquickjs",diff --git a/runtime/js/js/prelude.js b/runtime/js/js/prelude.jsindex 22a9f56f..ca5683c2 100644--- a/runtime/js/js/prelude.js+++ b/runtime/js/js/prelude.js@@ -79,8 +79,10 @@g.__ui_frame = 0;g.__ui_setFrame = (n) => void (g.__ui_frame = n);// Number's toLocaleString through one Intl.NumberFormat per locale and options, kept (JavaScriptCore made a- // formatter at every call: a counter formatted each frame was most of its frame). Only where there's an Intl- if (typeof Intl !== "undefined" && Intl.NumberFormat) {+ // formatter at every call: a counter formatted each frame was most of its frame). Only where there's an Intl, asked+ // with `in`: QuickJS's (raea-runtime-jsengine js/intl) is unpacked the first time it's read, and a page that never+ // formats shouldn't pay for it+ if ("Intl" in globalThis) {const formats = new Map();const toLocale = Number.prototype.toLocaleString;Object.defineProperty(Number.prototype, "toLocaleString", {diff --git a/runtime/jsengine/Cargo.toml b/runtime/jsengine/Cargo.tomlindex 64532869..90e5d614 100644--- a/runtime/jsengine/Cargo.toml+++ b/runtime/jsengine/Cargo.toml@@ -11,11 +11,14 @@ name = "raea_runtime_jsengine"[features]# QuickJS on Apple too, beside JavaScriptCore: how the portable path is tested on a Mac-portable = ["dep:rquickjs"]+portable = ["dep:rquickjs", "dep:miniz_oxide", "dep:iana-time-zone"][dependencies]raea-io-home = { path = "../../io/home" }rquickjs = { version = "0.14", optional = true, features = ["loader"] }+# QuickJS's Intl (js/intl): its pack's chunks are raw deflate, and the date polyfill's default zone is the system's+miniz_oxide = { version = "0.8", optional = true }+iana-time-zone = { version = "0.1", optional = true }[target.'cfg(target_vendor = "apple")'.dependencies]# JavaScriptCore's Objective-C module loader (JSScript, JSModuleLoaderDelegate): ES modules on the system engine@@ -23,3 +26,5 @@ objc2 = "0.6"[target.'cfg(not(target_vendor = "apple"))'.dependencies]rquickjs = { version = "0.14", features = ["loader"] }+miniz_oxide = "0.8"+iana-time-zone = "0.1"diff --git a/runtime/jsengine/js/intl.pack b/runtime/jsengine/js/intl.packnew file mode 100644index 00000000..aa407d52Binary files /dev/null and b/runtime/jsengine/js/intl.pack differdiff --git a/runtime/jsengine/js/intl/LICENSE-FormatJS.md b/runtime/jsengine/js/intl/LICENSE-FormatJS.mdnew file mode 100755index 00000000..127a3ec0--- /dev/null+++ b/runtime/jsengine/js/intl/LICENSE-FormatJS.md@@ -0,0 +1,56 @@+MIT License++Copyright (c) 2022, 2023, 2026 FormatJS (intl-supportedvaluesof 2022, the polyfills 2023, bigdecimal 2026)++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.++---++The locale data (each locale's entry in intl.pack, and the English in its core) is FormatJS's, made from the Unicode+Common Locale Data Repository (CLDR), under the Unicode License:++UNICODE LICENSE V3++COPYRIGHT AND PERMISSION NOTICE++Copyright © Unicode, Inc.++NOTICE TO USER: Carefully read the following legal agreement. BY+DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING DATA FILES, AND/OR+SOFTWARE, YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE+TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT+DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE.++Permission is hereby granted, free of charge, to any person obtaining a+copy of data files and any associated documentation (the "Data Files") or+software and any associated documentation (the "Software") to deal in the+Data Files or Software without restriction, including without limitation+the rights to use, copy, modify, merge, publish, distribute, and/or sell+copies of the Data Files or Software, and to permit persons to whom the+Data Files or Software are furnished to do so, provided that either (a)+this copyright and permission notice appear with all copies of the Data+Files or Software, or (b) this copyright and permission notice appear in+associated Documentation.++THE DATA FILES AND SOFTWARE ARE 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 OF+THIRD PARTY RIGHTS.++IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE+BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES,+OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,+WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,+ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA+FILES OR SOFTWARE.++Except as contained in this notice, the name of a copyright holder shall+not be used in advertising or otherwise to promote the sale, use or other+dealings in these Data Files or Software without prior written+authorization of the copyright holder.++SPDX-License-Identifier: Unicode-3.0diff --git a/runtime/jsengine/js/intl/build.ts b/runtime/jsengine/js/intl/build.tsnew file mode 100644index 00000000..3608b8fd--- /dev/null+++ b/runtime/jsengine/js/intl/build.ts@@ -0,0 +1,38 @@+// QuickJS's Intl, packed (docs/ports.feature PT0b): `bun install --frozen-lockfile && bun build.ts` here writes+// ../intl.pack, which raea-runtime-jsengine embeds (src/quickjs.rs) and loader.js reads. QuickJS has no Intl, so a+// composition that formatted a number threw "Intl is not defined" on Windows and Linux (#169) while JavaScriptCore,+// the Mac's, formatted it. The pack is entries of [name length u16][name][length u32][raw deflate], little-endian:+// "core" (core.js bundled: FormatJS's polyfills, English, the common time zones), "index" (the JSON list of the other+// locales) and one entry per locale, its data for each polyfill that has some. Uncompressed the 37 locales are 20 MB.+import { deflateRawSync } from "node:zlib";+import { existsSync, readFileSync, writeFileSync } from "node:fs";+import { join } from "node:path";++const here = import.meta.dir;+/** the locales besides English: the languages most of raea's people write in, and the regions that format apart */+export const LOCALES = ["en-GB", "en-AU", "en-CA", "en-IN", "de", "fr", "fr-CA", "es", "es-419", "es-MX", "it", "pt", "pt-PT", "nl", "sv", "da", "nb", "fi", "pl", "cs", "sk", "hu", "ro", "el", "tr", "ru", "uk", "he", "ar", "hi", "bn", "th", "id", "ms", "vi", "ja", "ko", "zh", "zh-Hant", "fil"];+const DATA = ["intl-pluralrules", "intl-numberformat", "intl-datetimeformat", "intl-relativetimeformat", "intl-listformat"];++const built = await Bun.build({ entrypoints: [join(here, "core.js")], minify: true, format: "iife", target: "browser" });+if (!built.success) throw new Error(built.logs.join("\n"));+const licence = readFileSync(join(here, "LICENSE-FormatJS.md"), "utf8").trim().split("\n").map((l) => ` * ${l}`.trimEnd()).join("\n");+const core = `/*\n * FormatJS's Intl polyfills, packed for raea's QuickJS (runtime/jsengine/js/intl):\n${licence}\n */\n${await built.outputs[0].text()}`;++const entries: [string, string][] = [["core", core], ["index", JSON.stringify(LOCALES)]];+for (const l of LOCALES) {+ const parts = DATA.map((p) => join(here, "node_modules/@formatjs", p, "locale-data", `${l}.js`)).filter(existsSync);+ if (parts.length < 4) throw new Error(`${l}: data for ${parts.length} of the ${DATA.length} polyfills`);+ entries.push([l, parts.map((f) => readFileSync(f, "utf8")).join(";\n")]);+}+const chunks: Buffer[] = [];+for (const [name, src] of entries) {+ const n = Buffer.from(name), z = deflateRawSync(Buffer.from(src), { level: 9 });+ const head = Buffer.alloc(6 + n.length);+ head.writeUInt16LE(n.length, 0);+ n.copy(head, 2);+ head.writeUInt32LE(z.length, 2 + n.length);+ chunks.push(head, z);+}+const pack = Buffer.concat(chunks);+writeFileSync(join(here, "..", "intl.pack"), pack);+console.log(`intl.pack: ${entries.length} entries, ${(pack.length / 1024).toFixed(0)} KB (core ${(core.length / 1024).toFixed(0)} KB before deflate)`);diff --git a/runtime/jsengine/js/intl/bun.lock b/runtime/jsengine/js/intl/bun.locknew file mode 100644index 00000000..21201d50--- /dev/null+++ b/runtime/jsengine/js/intl/bun.lock@@ -0,0 +1,41 @@+{+ "lockfileVersion": 2,+ "configVersion": 1,+ "workspaces": {+ "": {+ "name": "raea-intl",+ "dependencies": {+ "@formatjs/intl-datetimeformat": "8.0.2",+ "@formatjs/intl-getcanonicallocales": "3.3.0",+ "@formatjs/intl-listformat": "9.0.1",+ "@formatjs/intl-locale": "5.4.2",+ "@formatjs/intl-numberformat": "10.0.2",+ "@formatjs/intl-pluralrules": "7.0.2",+ "@formatjs/intl-relativetimeformat": "13.0.1",+ },+ },+ },+ "packages": {+ "@formatjs/bigdecimal": ["@formatjs/[email protected]", "", {}, "sha512-npIs6UARNOg5amJY5UOVsd6HUQQfzYjet0sa0SWIqzsnVhxLSpaIx2DjoIVrr/vqmjURjvroeW6dItjfy3Uf8A=="],++ "@formatjs/fast-memoize": ["@formatjs/[email protected]", "", {}, "sha512-zXfhLpvA6T7+efdt9JLbBwZ00tT7NsBMDVnDu8rpHeNNv8KfRZAMo2gkG0k9lK/Nzc//3kJ9pImsfuJxk3KhUA=="],++ "@formatjs/intl-datetimeformat": ["@formatjs/[email protected]", "", { "dependencies": { "@formatjs/bigdecimal": "0.2.10", "@formatjs/intl-localematcher": "0.10.1" } }, "sha512-isKDo8jeQ8VoYvrweku92ajF/Z9fJ76DDnw2eCmKBTJTwZa5GeGl4u40RJiFYPbR6ROluvN0CsbNtGtnd2NyIQ=="],++ "@formatjs/intl-getcanonicallocales": ["@formatjs/[email protected]", "", {}, "sha512-ndj9jw/LHAftSe34D/A6+lj3Y7GHVfPEZ6FZP2wjd8/beYeh3d1sjlSpZSBlzegSKS3U3mUEIzLCpI0+jKNT6w=="],++ "@formatjs/intl-listformat": ["@formatjs/[email protected]", "", { "dependencies": { "@formatjs/intl-localematcher": "0.10.1" } }, "sha512-V7kMddXDOLeyXAVCBEp8eBnllmPMBqu39U1GO/82xzlaUyK/Gkc3Qgal+9HJx6n1xfCvUn7XHK5t5dSlF7Y2lA=="],++ "@formatjs/intl-locale": ["@formatjs/[email protected]", "", { "dependencies": { "@formatjs/intl-getcanonicallocales": "3.3.0", "@formatjs/intl-supportedvaluesof": "3.0.0" } }, "sha512-2upVZtpzktEkLMffAk14T2HB62B7ytqrlppZuVX4StnbOHNc4qx5ovimMMMn8mkqvAwFlPX+UZygetny+quqIQ=="],++ "@formatjs/intl-localematcher": ["@formatjs/[email protected]", "", { "dependencies": { "@formatjs/fast-memoize": "3.1.7" } }, "sha512-gBqglQK9rXuHsLmM8wzTMBy4Xo4d0jamirIVKuEL8F1rwbskWdpMA1kZarSkny+uvr5q/K6GSzE0Rcq1wZLl3g=="],++ "@formatjs/intl-numberformat": ["@formatjs/[email protected]", "", { "dependencies": { "@formatjs/bigdecimal": "0.2.10", "@formatjs/intl-localematcher": "0.10.1" } }, "sha512-iLS3ly1lGZ/a/IVpcSUgC37RjQUZ2wN6zR9+Zbr2uXsxATfMLD+fBqggiXuFudLmZXpbPueCs4Mz3vDsaOVE9A=="],++ "@formatjs/intl-pluralrules": ["@formatjs/[email protected]", "", { "dependencies": { "@formatjs/bigdecimal": "0.2.10", "@formatjs/intl-localematcher": "0.10.1" } }, "sha512-PJ4+ldlqXlo3csmP02u2HqyXw09TDB/fatYpDCyWryfEQeVWl2EbMzij9SBksPaW2U//+q69lXR3IMnCRQAmrw=="],++ "@formatjs/intl-relativetimeformat": ["@formatjs/[email protected]", "", { "dependencies": { "@formatjs/intl-localematcher": "0.10.1" } }, "sha512-Gl5dCHb7elEC19tTzxIyllWLHaHnN+HpQYEaA9xxAt9rKgRLwC3vGty1w8bVGG7p2YcGSPIg5c4qn4KdkGcTqg=="],++ "@formatjs/intl-supportedvaluesof": ["@formatjs/[email protected]", "", { "dependencies": { "@formatjs/fast-memoize": "3.1.7" } }, "sha512-9rG37qcIBFyX+HSyPelJKpAatFaO+ElvnWYO/FFMERVZG9e9Wj51CWAvF7+ozYd7B1uKBL2ub6aLzrkWA0UBxA=="],+ }+}diff --git a/runtime/jsengine/js/intl/core.js b/runtime/jsengine/js/intl/core.jsnew file mode 100644index 00000000..2185cc23--- /dev/null+++ b/runtime/jsengine/js/intl/core.js@@ -0,0 +1,16 @@+// Generated into ../intl.pack by build.ts: the Intl QuickJS lacks, FormatJS's polyfills (MIT, LICENSE-FormatJS.md)+// in the order each needs the one before, with English's data and the common time zones. Every other locale's data is+// its own chunk in the pack, run the first time a script asks for that locale (loader.js).+import "@formatjs/intl-getcanonicallocales/polyfill.js";+import "@formatjs/intl-locale/polyfill.js";+import "@formatjs/intl-pluralrules/polyfill.js";+import "@formatjs/intl-pluralrules/locale-data/en.js";+import "@formatjs/intl-numberformat/polyfill.js";+import "@formatjs/intl-numberformat/locale-data/en.js";+import "@formatjs/intl-datetimeformat/polyfill.js";+import "@formatjs/intl-datetimeformat/locale-data/en.js";+import "@formatjs/intl-datetimeformat/add-golden-tz.js";+import "@formatjs/intl-relativetimeformat/polyfill.js";+import "@formatjs/intl-relativetimeformat/locale-data/en.js";+import "@formatjs/intl-listformat/polyfill.js";+import "@formatjs/intl-listformat/locale-data/en.js";diff --git a/runtime/jsengine/js/intl/loader.js b/runtime/jsengine/js/intl/loader.jsnew file mode 100644index 00000000..613b97cc--- /dev/null+++ b/runtime/jsengine/js/intl/loader.js@@ -0,0 +1,148 @@+// QuickJS's Intl (src/quickjs.rs runs this first in every context): JavaScriptCore, the Mac's engine, has Intl, and+// QuickJS, Windows' and Linux's, has none, so a composition that formatted a number threw there (#169). FormatJS's+// polyfills are the core of intl.pack (build.ts), unpacked and run the first time anything reads Intl or calls a+// toLocale* method, so a script that never formats pays nothing; a locale's data runs the first time something asks+// for that locale. FormatJS has no Collator: the small one here sorts by letter, then accent, then case (lower first),+// as ICU's root order does for words, and needs none of the core.+(() => {+ const g = globalThis;+ if (typeof g.Intl !== "undefined") return;+ const chunk = g.__raea_intl_chunk;+ const zone = g.__raea_intl_zone;+ delete g.__raea_intl_chunk;+ delete g.__raea_intl_zone;+ const run = (src) => (0, eval)(src);+ let intl;+ let packed = [];+ const loaded = new Set(["en"]);+ // the pack's locale for a tag: itself, else its language (zh-TW, zh-HK and zh-MO are written as zh-Hant)+ const packedFor = (tag) => {+ const t = String(tag);+ const traditional = /^zh-(Hant|TW|HK|MO)\b/i.test(t) ? "zh-Hant" : null;+ for (const c of [t, traditional, t.split("-")[0]]) {+ const hit = c && packed.find((p) => p.toLowerCase() === c.toLowerCase());+ if (hit) return hit;+ }+ return null;+ };+ const need = (locales) => {+ boot();+ const tags = locales === undefined || locales === null ? [] : typeof locales === "string" || typeof locales[Symbol.iterator] !== "function" ? [locales] : [...locales];+ for (const tag of tags) {+ const p = packedFor(tag);+ if (p && !loaded.has(p)) {+ loaded.add(p);+ run(chunk(p));+ }+ }+ };+ // a constructor that runs its locales' data first: the same prototype (instanceof holds), and its statics+ const wrap = (Native) => {+ function Intl(locales, options) {+ need(locales);+ return new.target ? Reflect.construct(Native, [locales, options], new.target === Intl ? Native : new.target) : Native(locales, options);+ }+ Object.setPrototypeOf(Intl, Native);+ Object.defineProperty(Intl, "name", { value: Native.name });+ Intl.prototype = Native.prototype;+ if (Native.supportedLocalesOf) Intl.supportedLocalesOf = (locales, options) => (need(locales), Native.supportedLocalesOf(locales, options));+ return Intl;+ };++ // the toLocale* methods: until the core runs, each is one of these, which runs it and then FormatJS's own+ // (impl); whatever wraps them later (raea-runtime-js's prelude keeps one NumberFormat per locale) is kept+ const METHODS = [[Number.prototype, "toLocaleString"], [Date.prototype, "toLocaleString"], [Date.prototype, "toLocaleDateString"], [Date.prototype, "toLocaleTimeString"]];+ if (typeof BigInt !== "undefined") METHODS.push([BigInt.prototype, "toLocaleString"]);+ const impl = METHODS.map(([proto, name]) => proto[name]);+ METHODS.forEach(([proto, name], i) => {+ const mine = { [name](locales, options) {+ need(locales);+ return impl[i].call(this, locales, options);+ } }[name];+ Object.defineProperty(proto, name, { value: mine, writable: true, configurable: true });+ });++ let booting = false;+ const boot = () => {+ if (intl) return intl;+ // the core asking for Intl while it runs gets what it has made so far, not a second core+ if (booting) return g.Intl;+ booting = true;+ const before = METHODS.map(([proto, name]) => proto[name]);+ delete g.Intl;+ run(chunk("core"));+ intl = g.Intl;+ packed = JSON.parse(chunk("index"));+ METHODS.forEach(([proto, name], i) => {+ if (proto[name] !== before[i]) impl[i] = proto[name];+ Object.defineProperty(proto, name, { value: before[i], writable: true, configurable: true });+ });+ if (zone) {+ try {+ intl.DateTimeFormat.__setDefaultTimeZone(zone);+ } catch {+ // a zone outside the common ones in the pack: UTC+ }+ }+ const put = (k, v) => Object.defineProperty(intl, k, { value: v, writable: true, configurable: true });+ for (const k of ["DateTimeFormat", "NumberFormat", "PluralRules", "RelativeTimeFormat", "ListFormat"]) if (intl[k]) put(k, wrap(intl[k]));+ put("Collator", Collator);+ return intl;+ };++ const plain = (s) => s.normalize("NFD").replace(/[̀-ͯ]/g, "");+ const cmp = (x, y) => (x < y ? -1 : x > y ? 1 : 0);+ // numbers in words by their value: "item 2" before "item 10"+ const nat = (x, y) => {+ const a = x.match(/\d+|\D+/g) ?? [];+ const b = y.match(/\d+|\D+/g) ?? [];+ for (let i = 0; i < Math.min(a.length, b.length); i++) {+ const d = /^\d/.test(a[i]) && /^\d/.test(b[i]) ? Number(a[i]) - Number(b[i]) : cmp(a[i], b[i]);+ if (d) return Math.sign(d);+ }+ return Math.sign(a.length - b.length);+ };+ class Collator {+ constructor(locales, o = {}) {+ const tag = (typeof locales === "string" ? locales : locales?.[0]) ?? "en";+ this.o = { locale: String(tag), usage: o.usage ?? "sort", sensitivity: o.sensitivity ?? "variant", ignorePunctuation: !!o.ignorePunctuation, collation: "default", numeric: !!o.numeric, caseFirst: o.caseFirst ?? "false" };+ const { sensitivity: s, caseFirst } = this.o;+ const by = this.o.numeric ? nat : cmp;+ const drop = this.o.ignorePunctuation ? (x) => x.replace(/[\p{P}\s]/gu, "") : (x) => x;+ this.compare = (a, b) => {+ const x = drop(String(a));+ const y = drop(String(b));+ const letters = by(plain(x).toLowerCase(), plain(y).toLowerCase());+ if (letters || s === "base") return letters;+ if (s !== "case") {+ const accents = by(x.toLowerCase(), y.toLowerCase());+ if (accents || s === "accent") return accents;+ }+ // "case": a and A differ, a and á don't+ const cased = s === "case" ? by(plain(x), plain(y)) : by(x, y);+ return caseFirst === "upper" ? cased : -cased;+ };+ }+ resolvedOptions() {+ return { ...this.o };+ }+ static supportedLocalesOf(locales) {+ return boot().getCanonicalLocales(locales ?? []);+ }+ }+ const collators = new Map();+ Object.defineProperty(String.prototype, "localeCompare", {+ value: function localeCompare(that, locales, options) {+ const key = options === undefined && (locales === undefined || typeof locales === "string") ? (locales ?? "") : null;+ let c = key === null ? undefined : collators.get(key);+ if (!c) {+ c = new Collator(locales, options);+ if (key !== null && collators.size < 32) collators.set(key, c);+ }+ return c.compare(String(this), String(that));+ },+ writable: true,+ configurable: true,+ });+ Object.defineProperty(g, "Intl", { get: boot, set: (v) => Object.defineProperty(g, "Intl", { value: v, writable: true, configurable: true }), configurable: true });+})();diff --git a/runtime/jsengine/js/intl/package.json b/runtime/jsengine/js/intl/package.jsonnew file mode 100644index 00000000..09d000dc--- /dev/null+++ b/runtime/jsengine/js/intl/package.json@@ -0,0 +1,18 @@+{+ "name": "raea-intl",+ "private": true,+ "description": "QuickJS's Intl (raea-runtime-jsengine): FormatJS's polyfills and their CLDR data, packed by build.ts into ../intl.pack",+ "license": "MIT",+ "scripts": {+ "build": "bun build.ts"+ },+ "dependencies": {+ "@formatjs/intl-getcanonicallocales": "3.3.0",+ "@formatjs/intl-locale": "5.4.2",+ "@formatjs/intl-pluralrules": "7.0.2",+ "@formatjs/intl-numberformat": "10.0.2",+ "@formatjs/intl-datetimeformat": "8.0.2",+ "@formatjs/intl-relativetimeformat": "13.0.1",+ "@formatjs/intl-listformat": "9.0.1"+ }+}diff --git a/runtime/jsengine/src/lib.rs b/runtime/jsengine/src/lib.rsindex 42149aae..faa49b06 100644--- a/runtime/jsengine/src/lib.rs+++ b/runtime/jsengine/src/lib.rs@@ -230,6 +230,52 @@ mod tests {assert!(stopped(&e), "{}: {e}", js.name());}+ /// What a composition formats, as JavaScriptCore formats it (#169: QuickJS had no Intl, so these threw on Windows+ /// and Linux): numbers, money, percents and compact counts, dates in a zone, plural rules, relative times, lists,+ /// and words sorted. Each case is [expression, JavaScriptCore's answer].+ const INTL: [(&str, &str); 14] = [+ ("(1234567.891).toLocaleString('en-US')", "1,234,567.891"),+ ("(1234567.891).toLocaleString('de-DE')", "1.234.567,891"),+ ("new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(12.5)", "$12.50"),+ ("new Intl.NumberFormat('en-US', { style: 'currency', currency: 'EUR' }).format(5000)", "\u{20ac}5,000.00"),+ ("new Intl.NumberFormat('en', { notation: 'compact' }).format(1234567)", "1.2M"),+ ("(0.256).toLocaleString('en-US', { style: 'percent' })", "26%"),+ ("new Intl.NumberFormat('zh-TW').format(1234.5)", "1,234.5"),+ ("new Intl.DateTimeFormat('en-GB', { dateStyle: 'long', timeZone: 'UTC' }).format(new Date(Date.UTC(2026, 10, 19)))", "19 November 2026"),+ ("new Intl.DateTimeFormat('fr-FR', { weekday: 'long', day: 'numeric', month: 'long', timeZone: 'UTC' }).format(new Date(Date.UTC(2026, 10, 19)))", "jeudi 19 novembre"),+ ("new Date(Date.UTC(2026, 10, 19, 15, 4)).toLocaleDateString('en-US', { timeZone: 'UTC' })", "11/19/2026"),+ ("[new Intl.PluralRules('en-US').select(2), new Intl.PluralRules('ru').select(3)].join(' ')", "other few"),+ ("new Intl.RelativeTimeFormat('en', { numeric: 'auto' }).format(-1, 'day')", "yesterday"),+ ("new Intl.ListFormat('en', { type: 'conjunction' }).format(['a', 'b', 'c'])", "a, b, and c"),+ ("['b', 'a', 'B', '\\u00e1'].sort((x, y) => x.localeCompare(y)).join(',')", "a,\u{e1},b,B"),+ ];++ /// Each INTL case's answer on `engine`, or what it threw+ fn intl(engine: Engine) -> Vec<String> {+ let mut js = engine.start().unwrap();+ let seen = Rc::new(RefCell::new(Vec::new()));+ let s = seen.clone();+ js.native("note", Box::new(move |a| {+ s.borrow_mut().push(a.join("|"));+ Ok(Ret::Undefined)+ }))+ .unwrap();+ for (expr, _) in INTL {+ js.eval(&format!("try {{ note({expr}) }} catch (e) {{ note('threw ' + e) }}"), "intl.js").unwrap();+ }+ seen.take()+ }++ #[cfg(any(feature = "portable", not(target_vendor = "apple")))]+ #[test]+ fn quickjs_formats_as_javascriptcore_does() {+ let got = intl(Engine::QuickJs);+ assert_eq!(got, INTL.map(|(_, want)| want.to_string()));+ // and on a Mac, as the engine there does+ #[cfg(target_vendor = "apple")]+ assert_eq!(got, intl(Engine::Jsc));+ }+#[cfg(target_vendor = "apple")]#[test]fn jsc() {diff --git a/runtime/jsengine/src/quickjs.rs b/runtime/jsengine/src/quickjs.rsindex 64575343..ef0dea3f 100644--- a/runtime/jsengine/src/quickjs.rs+++ b/runtime/jsengine/src/quickjs.rs@@ -24,7 +24,9 @@ impl Quick {// React's commit recurses through the tree; give it room (the host runs on the main thread's 8 MB stack)rt.set_max_stack_size(4 << 20);let ctx = Context::full(&rt).map_err(|e| e.to_string())?;- Ok(Quick { rt, ctx })+ let mut q = Quick { rt, ctx };+ intl(&mut q)?;+ Ok(q)}/// The promise jobs queued, run until none is left (one that throws is logged, as an unhandled rejection is).@@ -42,6 +44,35 @@ impl Quick {}}+/// FormatJS's Intl polyfills and their CLDR data (js/intl/build.ts): "core", "index" and one entry per locale, each+/// raw deflate. QuickJS has no Intl; JavaScriptCore has, so this is QuickJS's alone.+const INTL_PACK: &[u8] = include_bytes!("../js/intl.pack");++/// An entry of the Intl pack, inflated: its source (or the index's JSON), None when there's no such entry.+pub(crate) fn intl_chunk(name: &str) -> Option<String> {+ let mut at = 0;+ while at + 2 <= INTL_PACK.len() {+ let n = u16::from_le_bytes([INTL_PACK[at], INTL_PACK[at + 1]]) as usize;+ let key = INTL_PACK.get(at + 2..at + 2 + n)?;+ let len = u32::from_le_bytes(INTL_PACK.get(at + 2 + n..at + 6 + n)?.try_into().ok()?) as usize;+ let body = INTL_PACK.get(at + 6 + n..at + 6 + n + len)?;+ if key == name.as_bytes() {+ return String::from_utf8(miniz_oxide::inflate::decompress_to_vec(body).ok()?).ok();+ }+ at += 6 + n + len;+ }+ None+}++/// Intl in the context, the first time it's used (js/intl/loader.js): the pack's chunks through a native, and the+/// system's time zone as the date polyfill's default (JavaScriptCore formats dates in local time; TZ first, as there).+fn intl(q: &mut Quick) -> Result<(), String> {+ q.native("__raea_intl_chunk", Box::new(|a| intl_chunk(crate::arg(a, 0)).map(Ret::Str).ok_or_else(|| format!("no Intl data {:?}", crate::arg(a, 0)))))?;+ let zone = std::env::var("TZ").ok().filter(|z| z.contains('/')).or_else(|| iana_time_zone::get_timezone().ok()).unwrap_or_default();+ q.ctx.with(|ctx| ctx.globals().set("__raea_intl_zone", zone)).map_err(|e| e.to_string())?;+ q.eval(include_str!("../js/intl/loader.js"), "intl-loader.js")+}+/// Imports name their modules by URL already (the host rewrote them); one relative to its importer is joined to its folder.struct Urls;