feat: port the client to MyGo native UI (0.3.0)

Switch from Asuka to MyGo, keeping the API client and the feature set:

- servers: saved servers, passwordless and password login, proxy,
  self-signed certificates, per-server device tokens (Keystore), connect
  form, instance list sheet with switch/disconnect
- sessions: virtualized list, search, new session, rename/archive/delete,
  running indicator, event stream keeps it live
- chat: pushed window with system back bar, streaming Markdown via
  ui/markdown, reasoning and tool rows with image previews, footer menu
  (read aloud via a Kotlin TTS plugin, copy, fork), user message menu
  (copy, revert, fork), context usage ring and detail sheet, attachments
  (photos/files via the document picker), permissions
- release builds allow plain http:// LAN servers (Go's net/http dials
  directly, no cleartext manifest needed)
- a local fork of MyGo (third_party/mygo) lowers the Android host's
  minSdk to 24 (Android 7.0); Go 1.27.4 via mise

Version 0.3.0.
This commit is contained in:
OpenChamber committed 2026-11-18 13:22:59 +08:00
1 parent 2fb4a8ea79
commit 6c0ee61750
2538 files changed
+675779 -4792

No files matched your search

+120
View File
@@ -0,0 +1,120 @@
import { describe, expect, test } from "bun:test";
import { mkdtemp, readFile, readdir, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { type Latest, type Run, latestCommits, merge, parse } from "./bench.ts";
const output = `goos: darwin
goarch: arm64
pkg: github.com/egoist/mygo
cpu: Apple M5
BenchmarkCallNoop-10 43904 27364 ns/op 2.89 MB/s 719 B/op 14 allocs/op
BenchmarkCallNoop-10 43000 27000 ns/op 2.91 MB/s 720 B/op 14 allocs/op
BenchmarkCallNoop-10 44000 29000 ns/op 2.80 MB/s 721 B/op 14 allocs/op
PASS
ok github.com/egoist/mygo 9.634s
skipping e2e tests; set MYGO_E2E=1 to run them in a desktop session
ok github.com/egoist/mygo/internal/e2e 0.376s
goos: darwin
goarch: arm64
pkg: github.com/egoist/mygo/ui
cpu: Apple M5
BenchmarkTextAreaType/1000-10 3018 1258632 ns/op 199799 B/op 248 allocs/op
BenchmarkTextAreaType/1000-10 3018 1258000 ns/op 199801 B/op 250 allocs/op
BenchmarkLogs-10
2026/10/05 12:00:00 a log line
100 0.5 ns/op
--- SKIP: BenchmarkOutput
bench_test.go:15: no library
BenchmarkDiff-10 1 123 patch-bytes 456 file-bytes
PASS
`;
describe("parse", () => {
const { cpu, results } = parse(output);
test("takes the median of each metric, without MB/s", () => {
expect(cpu).toBe("Apple M5");
expect(results["."]).toEqual({ CallNoop: { "ns/op": 27360, "B/op": 720, "allocs/op": 14 } });
});
test("names benchmarks without Benchmark and GOMAXPROCS, sub-benchmarks included", () => {
expect(results.ui?.["TextAreaType/1000"]).toEqual({ "ns/op": 1258000, "B/op": 199800, "allocs/op": 249 });
});
test("reads results printed after a benchmark's logs", () => {
expect(results.ui?.Logs).toEqual({ "ns/op": 0.5 });
});
test("keeps custom metrics", () => {
expect(results.ui?.Diff).toEqual({ "patch-bytes": 123, "file-bytes": 456 });
});
test("leaves out skipped benchmarks", () => {
expect(results.ui?.Output).toBeUndefined();
});
});
function run(sha: string, date: string, os: string, ns: number): Run {
return {
sha,
date,
message: `commit ${sha}`,
os,
arch: "arm64",
cpu: "Apple M5",
go: "go1.27.1",
count: 6,
results: { ".": { CallNoop: { "ns/op": ns, "B/op": 720 } }, size: { hello: { bytes: 8e6 } } },
};
}
async function mergeRuns(dir: string, runs: Run[]): Promise<void> {
const files = await Promise.all(
runs.map(async (r, i) => {
const file = join(dir, `run-${i}.json`);
await writeFile(file, JSON.stringify(r));
return file;
}),
);
await merge(join(dir, "data"), files);
}
async function readLatest(dir: string): Promise<Latest> {
return JSON.parse(await readFile(join(dir, "data", "latest.json"), "utf8"));
}
describe("merge", () => {
test("keeps each commit's runs by OS and day, and their series", async () => {
const dir = await mkdtemp(join(tmpdir(), "bench-test-"));
await mergeRuns(dir, [run("b", "2026-10-02T00:00:00Z", "linux", 200), run("b", "2026-10-02T00:00:00Z", "darwin", 100)]);
// An older commit measured later, another OS's run of a commit, and a
// run measured again.
await mergeRuns(dir, [
run("a", "2026-09-30T23:00:00-02:00", "darwin", 90),
run("c", "2026-10-03T00:00:00Z", "darwin", 110),
run("b", "2026-10-02T00:00:00Z", "darwin", 105),
]);
expect((await readdir(join(dir, "data", "history"))).sort()).toEqual(["2026-10-01.json", "2026-10-02.json", "2026-10-03.json"]);
const data = await readLatest(dir);
expect(data.commits.map((c) => c.sha)).toEqual(["a", "b", "c"]);
expect(data.series.darwin?.["."]?.CallNoop?.["ns/op"]).toEqual([90, 105, 110]);
expect(data.series.linux?.["."]?.CallNoop?.["ns/op"]).toEqual([null, 200, null]);
expect(data.series.darwin?.size?.hello?.bytes).toEqual([8e6, 8e6, 8e6]);
expect(data.runners.linux).toEqual([null, { arch: "arm64", cpu: "Apple M5", go: "go1.27.1" }, null]);
});
test("keeps the last commits in latest.json, and every day in history", async () => {
const dir = await mkdtemp(join(tmpdir(), "bench-test-"));
const runs = Array.from({ length: latestCommits + 5 }, (_, i) =>
run(`c${i}`, new Date(Date.UTC(2026, 8, 1) + i * 3_600_000 * 4).toISOString(), "linux", i),
);
await mergeRuns(dir, runs);
// Six commits a day from September 1st.
expect((await readdir(join(dir, "data", "history"))).length).toBe(Math.ceil((latestCommits + 5) / 6));
const data = await readLatest(dir);
expect(data.commits.length).toBe(latestCommits);
expect(data.commits[0]?.sha).toBe("c5");
expect(data.series.linux?.["."]?.CallNoop?.["ns/op"]?.at(-1)).toBe(latestCommits + 4);
});
});
+392
View File
@@ -0,0 +1,392 @@
// Runs MyGo's benchmarks and keeps their history, which the website's
// /measures page shows. .github/workflows/bench.yml runs them on every
// push to main, on macOS, Linux and Windows:
//
// bun scripts/bench.ts run [--e2e] [--count 6] [--benchtime 500ms] [--out file] [packages...]
// bun scripts/bench.ts merge <data dir> <result files...>
//
// run measures the checkout it runs in: the Go benchmarks of every package
// that has some (or of the packages given), those of internal/e2e with
// --e2e, which need a desktop session, the size of release builds of two
// examples, and with --e2e their memory once idle (internal/idlemem).
// Packages run one at a time, each benchmark --count times, as each app,
// and the median of each metric is kept.
//
// merge adds results to a checkout of the benchmarks branch:
// history/<yyyy-mm-dd>.json keeps every commit of a day (UTC), small files
// that each push rewrites one of, and latest.json the last commits, by
// series, which the website fetches.
import { existsSync } from "node:fs";
import { mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, relative } from "node:path";
const module = "github.com/egoist/mygo";
/** Values by unit, such as "ns/op", "B/op", "allocs/op" or "bytes". */
export type Metrics = Record<string, number>;
/** Metrics by package ("." for the root, "size" and "memory" for apps'), then benchmark. */
export type Results = Record<string, Record<string, Metrics>>;
/** The machine a run measured on. */
export interface Runner {
arch: string;
cpu: string;
go: string;
}
/** What run measured: the results of one commit on one OS. */
export interface Run extends Runner {
sha: string;
date: string;
message: string;
os: string;
count: number;
results: Results;
}
/** A commit of history/<yyyy-mm-dd>.json, with the runs of each OS. */
export interface Commit {
sha: string;
date: string;
message: string;
runs: Record<string, Runner & { count: number; results: Results }>;
}
/** latest.json: the last commits, oldest first, and their values by series. */
export interface Latest {
version: 1;
commits: { sha: string; date: string; message: string }[];
/** By OS: the runner of each commit, null where the OS has no run. */
runners: Record<string, (Runner | null)[]>;
/** By OS, package, benchmark and unit: the value at each commit, or null. */
series: Record<string, Record<string, Record<string, Record<string, (number | null)[]>>>>;
}
/** How many commits latest.json keeps. */
export const latestCommits = 300;
/** The examples whose release builds are measured. */
const apps = ["hello", "counter-native"];
/** The apps with a webview, whose own process's memory counts apart from its processes' too. */
const webviewApps = new Set(["hello"]);
async function run(args: string[]): Promise<void> {
let e2e = false;
let count = 6;
let benchtime = "500ms";
let out = "";
const pkgs: string[] = [];
for (let i = 0; i < args.length; i++) {
const arg = args[i]!;
if (arg === "--e2e") e2e = true;
else if (arg === "--count") count = Number(args[++i]);
else if (arg === "--benchtime") benchtime = args[++i]!;
else if (arg === "--out") out = args[++i]!;
else pkgs.push(arg);
}
if (!pkgs.length) pkgs.push(...(await benchmarkPackages(e2e)));
const [goVersion, goos, goarch] = output(["go", "env", "GOVERSION", "GOOS", "GOARCH"]).split("\n");
const [sha, date, message] = output(["git", "log", "-1", "--format=%H%n%cI%n%s"]).split("\n");
// -p 1: packages run one at a time, or they would measure each other.
const test = await goTest(
["-p", "1", "-run", "^$", "-bench", ".", "-benchmem", "-count", String(count), "-benchtime", benchtime, "-timeout", "60m", ...pkgs],
e2e ? { MYGO_E2E: "1" } : {},
);
const { cpu, results } = parse(test.output);
const measured = await measureApps(goos!, e2e, count);
results.size = measured.size;
if (measured.memory) results.memory = measured.memory;
const result: Run = {
sha: sha!,
date: date!,
message: message!,
os: goos!,
arch: goarch!,
cpu,
go: goVersion!,
count,
results,
};
if (out) await writeFile(out, JSON.stringify(result, null, 2) + "\n");
print(results);
// What did run is kept, and the failure shows.
if (test.code !== 0) console.error(`go test exited with ${test.code}`);
if (test.code !== 0 || measured.failed) process.exit(1);
}
/**
* Returns the directories of the packages that have benchmarks on this
* platform: those of internal/gpu/metal, say, only build on macOS.
*/
async function benchmarkPackages(e2e: boolean): Promise<string[]> {
const dirs = new Set<string>();
// Untracked files too, as the benchmarks being written.
for (const file of output(["git", "ls-files", "--cached", "--others", "--exclude-standard", "*_test.go"]).split("\n")) {
if (!file) continue;
const dir = file.includes("/") ? file.slice(0, file.lastIndexOf("/")) : ".";
if (!e2e && dir === "internal/e2e") continue;
dirs.add(dir);
}
const pkgs = [...dirs].sort().map((dir) => (dir === "." ? "." : "./" + dir));
// The test files that build here, by package; go list rather than ./...,
// which skips testdata directories.
const listed = output(["go", "list", "-e", "-f", '{{.Dir}}|{{join .TestGoFiles ","}},{{join .XTestGoFiles ","}}', ...pkgs]);
const benchmarked: string[] = [];
for (const line of listed.split("\n")) {
const [dir, files] = line.split("|");
for (const file of files!.split(",")) {
if (file && /^func Benchmark/m.test(await readFile(join(dir!, file), "utf8"))) {
const rel = relative(process.cwd(), dir!);
benchmarked.push(rel ? "./" + rel : ".");
break;
}
}
}
return benchmarked.sort();
}
/** Runs go test, showing its output as it comes. */
async function goTest(args: string[], env: Record<string, string>): Promise<{ output: string; code: number }> {
console.log(`go test ${args.join(" ")}`);
const proc = Bun.spawn(["go", "test", ...args], { stdout: "pipe", stderr: "inherit", env: { ...process.env, ...env } });
const decoder = new TextDecoder();
let text = "";
for await (const chunk of proc.stdout) {
const s = decoder.decode(chunk, { stream: true });
text += s;
process.stdout.write(s);
}
return { output: text, code: await proc.exited };
}
/**
* Parses the output of go test -bench: the median of each metric over the
* runs of each benchmark, named without "Benchmark" and GOMAXPROCS, and the
* CPU go test reports. MB/s is left out: it follows from ns/op.
*/
export function parse(text: string): { cpu: string; results: Results } {
const samples: Record<string, Record<string, Record<string, number[]>>> = {};
let pkg = "";
let cpu = "";
let pending = "";
for (const line of text.split(/\r?\n/)) {
let m: RegExpExecArray | null;
if ((m = /^pkg: (\S+)/.exec(line))) {
pkg = m[1] === module ? "." : m[1]!.replace(module + "/", "");
pending = "";
continue;
}
if ((m = /^cpu: (.+)/.exec(line))) {
cpu ||= m[1]!.trim();
continue;
}
const fields = line.trim().split(/\s+/);
let name = "";
let values: string[];
if (/^Benchmark\S/.test(fields[0]!)) {
// A benchmark that logs has its name on a line of its own.
if (fields.length === 1) {
pending = fields[0]!;
continue;
}
name = fields[0]!;
values = fields.slice(1);
} else if (pending && /^\d+$/.test(fields[0]!)) {
name = pending;
values = fields;
} else continue;
pending = "";
// The iterations, then pairs of a value and its unit.
if (!/^\d+$/.test(values[0]!) || values.length < 3) continue;
name = name.replace(/^Benchmark/, "").replace(/-\d+$/, "");
const metrics = ((samples[pkg] ??= {})[name] ??= {});
for (let i = 1; i + 1 < values.length; i += 2) {
const value = Number(values[i]);
const unit = values[i + 1]!;
if (unit === "MB/s" || !Number.isFinite(value)) continue;
(metrics[unit] ??= []).push(value);
}
}
const results: Results = {};
for (const [pkg, benchmarks] of Object.entries(samples)) {
for (const [name, units] of Object.entries(benchmarks)) {
const metrics: Metrics = {};
for (const [unit, values] of Object.entries(units)) metrics[unit] = round(median(values));
(results[pkg] ??= {})[name] = metrics;
}
}
return { cpu, results };
}
export function median(values: number[]): number {
const s = [...values].sort((a, b) => a - b);
const mid = s.length >> 1;
return s.length % 2 ? s[mid]! : (s[mid - 1]! + s[mid]!) / 2;
}
/** Rounds to 4 significant digits, more than the noise of any runner. */
function round(v: number): number {
return Number(v.toPrecision(4));
}
/**
* Builds the examples as mygo build does for a release, and returns their
* sizes and, with e2e, their memory once idle, in "B": an app with its
* processes, and a webview app's own process as "<app>/app". A failure
* to measure memory leaves it out.
*/
async function measureApps(
goos: string,
e2e: boolean,
count: number,
): Promise<{ size: Record<string, Metrics>; memory?: Record<string, Metrics>; failed?: boolean }> {
const dir = await mkdtemp(join(tmpdir(), "mygo-bench-"));
const size: Record<string, Metrics> = {};
try {
const bins: string[] = [];
for (const app of apps) {
if (!existsSync(join("examples", app))) continue;
const bin = join(dir, goos === "windows" ? app + ".exe" : app);
const ldflags = "-s -w -X github.com/egoist/mygo.production=1" + (goos === "windows" ? " -H=windowsgui" : "");
output(["go", "build", "-trimpath", "-tags", "mygo_noinspector", "-ldflags", ldflags, "-o", bin, "./examples/" + app]);
size[app] = { bytes: (await stat(bin)).size };
bins.push(bin);
}
if (!e2e || !existsSync(join("internal", "idlemem"))) return { size };
console.log(`go run ./internal/idlemem -count ${count}`);
const proc = Bun.spawnSync(["go", "run", "./internal/idlemem", "-count", String(count), ...bins], { stderr: "inherit" });
if (proc.exitCode !== 0) {
console.error(`idlemem exited with ${proc.exitCode}`);
return { size, failed: true };
}
const memory: Record<string, Metrics> = {};
const idle: Record<string, { app: number; total: number }> = JSON.parse(proc.stdout.toString());
for (const [app, m] of Object.entries(idle)) {
memory[app] = { B: round(m.total) };
if (webviewApps.has(app)) memory[`${app}/app`] = { B: round(m.app) };
}
return { size, memory };
} finally {
await rm(dir, { recursive: true, force: true });
}
}
function output(cmd: string[]): string {
const proc = Bun.spawnSync(cmd, { stderr: "inherit" });
if (proc.exitCode !== 0) throw new Error(`${cmd.join(" ")} exited with ${proc.exitCode}`);
return proc.stdout.toString().trim();
}
function print(results: Results): void {
const rows = [["benchmark", "time/op", "B/op", "allocs/op"]];
for (const [pkg, benchmarks] of Object.entries(results)) {
for (const [name, m] of Object.entries(benchmarks)) {
const bytes = m.bytes ?? m.B;
const time = m["ns/op"] !== undefined ? formatNs(m["ns/op"]) : bytes !== undefined ? `${(bytes / 1e6).toFixed(2)} MB` : "";
rows.push([`${pkg}/${name}`, time, String(m["B/op"] ?? ""), String(m["allocs/op"] ?? "")]);
}
}
const widths = rows[0]!.map((_, i) => Math.max(...rows.map((r) => r[i]!.length)));
for (const r of rows) console.log(r.map((c, i) => (i ? c.padStart(widths[i]!) : c.padEnd(widths[i]!))).join(" "));
}
function formatNs(ns: number): string {
if (ns >= 1e9) return `${(ns / 1e9).toPrecision(3)} s`;
if (ns >= 1e6) return `${(ns / 1e6).toPrecision(3)} ms`;
if (ns >= 1e3) return `${(ns / 1e3).toPrecision(3)} µs`;
return `${ns.toPrecision(3)} ns`;
}
/** Adds runs to the history in dir, and writes latest.json anew. */
export async function merge(dir: string, files: string[]): Promise<void> {
const runs: Run[] = await Promise.all(files.map(async (f) => JSON.parse(await readFile(f, "utf8"))));
const history = join(dir, "history");
await mkdir(history, { recursive: true });
const days = new Map<string, Commit[]>();
for (const r of runs) {
const day = new Date(r.date).toISOString().slice(0, 10);
let commits = days.get(day);
if (!commits) {
commits = await readShard(join(history, day + ".json"));
days.set(day, commits);
}
let commit = commits.find((c) => c.sha === r.sha);
if (!commit) {
commit = { sha: r.sha, date: r.date, message: r.message, runs: {} };
commits.push(commit);
}
// A run measured again replaces the earlier one.
commit.runs[r.os] = { arch: r.arch, cpu: r.cpu, go: r.go, count: r.count, results: r.results };
}
for (const [day, commits] of days) {
commits.sort((a, b) => Date.parse(a.date) - Date.parse(b.date));
// A commit a line, for readable diffs.
await writeFile(join(history, day + ".json"), "[\n" + commits.map((c) => JSON.stringify(c)).join(",\n") + "\n]\n");
}
const recent: Commit[] = [];
const shards = (await readdir(history)).filter((f) => /^\d{4}-\d{2}-\d{2}\.json$/.test(f)).sort().reverse();
for (const shard of shards) {
recent.unshift(...(await readShard(join(history, shard))));
if (recent.length >= latestCommits) break;
}
await writeFile(join(dir, "latest.json"), JSON.stringify(latest(recent.slice(-latestCommits))));
await writeFile(join(dir, "README.md"), readme);
}
async function readShard(file: string): Promise<Commit[]> {
return existsSync(file) ? JSON.parse(await readFile(file, "utf8")) : [];
}
/** Turns commits, oldest first, into the series of latest.json. */
export function latest(commits: Commit[]): Latest {
const data: Latest = {
version: 1,
commits: commits.map(({ sha, date, message }) => ({ sha, date, message })),
runners: {},
series: {},
};
const n = commits.length;
commits.forEach((c, i) => {
for (const [os, r] of Object.entries(c.runs)) {
(data.runners[os] ??= Array(n).fill(null))[i] = { arch: r.arch, cpu: r.cpu, go: r.go };
const byPkg = (data.series[os] ??= {});
for (const [pkg, benchmarks] of Object.entries(r.results)) {
for (const [name, metrics] of Object.entries(benchmarks)) {
const byUnit = ((byPkg[pkg] ??= {})[name] ??= {});
for (const [unit, value] of Object.entries(metrics)) (byUnit[unit] ??= Array(n).fill(null))[i] = value;
}
}
}
});
return data;
}
const readme = `# MyGo's benchmarks
The results of MyGo's benchmarks, which .github/workflows/bench.yml of the
main branch measures on every push, written by scripts/bench.ts and shown at
https://mygo.egoist.dev/measures.
- history/<yyyy-mm-dd>.json: every commit measured that day (UTC), with each OS's runner and results.
- latest.json: the last ${latestCommits} commits, by series, which the website fetches.
Its commits skip CI ([skip ci]), the website's builds included.
`;
// Last, once the module's constants are set.
if (import.meta.main) {
const [command, ...args] = process.argv.slice(2);
if (command === "run") await run(args);
else if (command === "merge" && args.length >= 2) await merge(args[0]!, args.slice(1));
else {
console.error("usage: bun scripts/bench.ts run [--e2e] [--count n] [--benchtime d] [--out file] [packages...]");
console.error(" bun scripts/bench.ts merge <data dir> <result files...>");
process.exit(2);
}
}
+43
View File
@@ -0,0 +1,43 @@
// Reproduce the chart scales' reference without adding an app dependency:
// npm install --prefix /tmp/mygo-chart-reference --ignore-scripts --no-audit --no-fund d3-scale@4.0.2
// node scripts/chart-scales-golden.ts /tmp/mygo-chart-reference
import { readFile, writeFile, mkdir } from "node:fs/promises";
import { resolve, join } from "node:path";
import { pathToFileURL } from "node:url";
import { gzipSync } from "node:zlib";
const root = process.argv[2];
if (!root) throw new Error("Pass the directory containing node_modules/d3-scale@4.0.2");
const pkg = resolve(root, "node_modules/d3-scale");
const { version } = JSON.parse(await readFile(join(pkg, "package.json"), "utf8"));
if (version !== "4.0.2") throw new Error(`Expected d3-scale 4.0.2, found ${version}`);
const { scaleLog, scaleSymlog } = await import(pathToFileURL(join(pkg, "src/index.js")).href);
const fractions = [-0.5, 0, 0.1, 0.25, 0.5, 0.75, 0.9, 1, 1.5].map(Math.fround);
const cases: object[] = [];
const logDomains = [[1, 1000], [0.001, 1], [0.3, 1.2], [30, 90], [1, 1], [1e-12, 1e12], [1e6, 3.4e6],
[Number.MIN_VALUE, 1], [1e-320, 1e-300]];
const domains = (ds: number[][]) => ds.flatMap(([lo, hi]) => [[lo!, hi!], [hi!, lo!]]);
for (const kind of ["log", "symlog"]) {
const ranges = kind === "log" ? domains(logDomains.flatMap(([lo, hi]) => [[lo!, hi!], [-hi!, -lo!]]))
: domains([[0, 100], [-100, 100], [-100, -1], [-1e6, 1e6], [3.2, 7.9], [0, 0]]);
for (const domain of ranges) for (const parameter of kind === "log" ? [2, Math.E, 10, 16, 100] : [0.01, 1, 10, 100]) {
for (const count of [1, 2, 5, 10]) for (const clamp of [false, true]) {
const scale = kind === "log" ? scaleLog().base(parameter) : scaleSymlog().constant(parameter);
scale.domain(domain).clamp(clamp);
const raw = scale.copy().clamp(false);
// Extrapolating subnormal domains can underflow or overflow. Keep
// these reference samples inside the representable domain.
const fs = domain.some((v) => Math.abs(v) < 1e-300 && v !== 0)
? fractions.filter((f) => f >= 0 && f <= 1) : fractions;
const values = fs.map((f) => raw.invert(f));
cases.push({ kind, domain, parameter, count, clamp,
values, positions: values.map((v) => scale(v)),
fractions: fs, inversions: fs.map((f) => scale.invert(f)),
ticks: scale.ticks(count), nice: scale.copy().nice(count).domain() });
}
}
}
const dir = resolve(import.meta.dirname, "../ui/chart/testdata");
await mkdir(dir, { recursive: true });
await writeFile(join(dir, "nonlinear_d3.json.gz"), gzipSync(JSON.stringify({ version, cases }) + "\n", { level: 9 }));
console.log(`${cases.length} cases from d3-scale ${version}`);
+240
View File
@@ -0,0 +1,240 @@
// Writes i18n/testdata/format_icu.json: how ICU (Intl.NumberFormat,
// Intl.DateTimeFormat, Intl.DisplayNames, Intl.Locale) writes numbers,
// compact ones and amounts of money too, dates and times, ranges of them
// (formatRange), the
// first day of the week and the hour cycle, and
// the names of languages in themselves, in every locale package i18n has formatting
// data of, which TestFormatMatchesICU checks package i18n against. Run it
// again after updating CLDR, with a Node.js whose ICU has the same CLDR
// (`node -p process.versions.cldr`):
//
// node scripts/format-golden.ts
//
// Node.js, not Bun: Bun on macOS uses the system's ICU, whose data Apple
// changes.
//
// Dates are in the Gregorian calendar (-u-ca-gregory), which package i18n
// formats in, and in UTC unless a case names a zone. The locales are those
// of i18n/testdata/format_locales.json, which `go generate ./i18n` writes.
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
const dir = join(import.meta.dirname, "..", "i18n", "testdata");
const { locales, autonyms } = JSON.parse(await readFile(join(dir, "format_locales.json"), "utf8")) as {
locales: string[];
autonyms: string[];
};
type NumberCase = { kind: "number"; value: string; options: Intl.NumberFormatOptions & { roundingMode?: string } };
type DateCase = { kind: "date"; time: string; zone?: string; options: Intl.DateTimeFormatOptions };
type NamesCase = { kind: "names"; times: string[]; options: Intl.DateTimeFormatOptions };
type RangeCase = { kind: "range"; time: string; end: string; options: Intl.DateTimeFormatOptions };
type Case = NumberCase | DateCase | NamesCase | RangeCase | { kind: "firstDay" | "hourCycle" };
const cases: Case[] = [];
// Numbers.
const decimals = ["0", "1", "-1", "1.5", "0.001234", "1234.5", "-1234567.891", "12345", "123456789", "1000000",
"0.5", "2.5", "1.0005", "99999.9999", "123456789012345680000", "-0.0001"];
for (const value of decimals) cases.push({ kind: "number", value, options: {} });
for (const value of ["0", "0.256", "-0.5", "1.5", "12.345", "1234.56"]) cases.push({ kind: "number", value, options: { style: "percent" } });
for (const value of ["1", "1234.5", "-0.125"]) {
cases.push({ kind: "number", value, options: { minimumFractionDigits: 2, maximumFractionDigits: 2 } });
}
for (const value of ["2.5", "3.5", "-2.5"]) {
cases.push({ kind: "number", value, options: { maximumFractionDigits: 0, roundingMode: "halfEven" } });
}
cases.push({ kind: "number", value: "1234567.891", options: { useGrouping: false } });
cases.push({ kind: "number", value: "1234.5", options: { minimumFractionDigits: 3 } });
// Compact numbers, as a chart's axis labels them.
const compacts = ["0", "999.9", "1234", "-1234", "12345", "123456", "999999", "1234567", "-2500000", "1000000000",
"123456789012", "1000000000000000", "0.001234"];
for (const compactDisplay of ["short", "long"] as const) {
for (const value of compacts) cases.push({ kind: "number", value, options: { notation: "compact", compactDisplay } });
}
cases.push({ kind: "number", value: "1234567", options: { notation: "compact", maximumFractionDigits: 2 } });
cases.push({ kind: "number", value: "1000", options: { notation: "compact", minimumFractionDigits: 2 } });
// Amounts of money, as a price, a total or a balance shows them: of
// currencies whose fraction digits CLDR and ISO 4217 agree on, as
// JavaScriptCore takes ISO 4217's where V8 takes CLDR's.
const amounts: [string, string[]][] = [
["USD", ["1842", "-1842", "0", "1234567.891", "0.005", "-0.001"]],
["EUR", ["1842", "-1842.5"]],
["JPY", ["1842.5", "-1842"]],
["GBP", ["1842"]],
["CAD", ["1842"]],
["INR", ["1234567"]],
["BHD", ["1842.5"]],
["CHF", ["-1842.53"]],
["XYZ", ["1842"]],
];
for (const [currency, values] of amounts) {
for (const value of values) cases.push({ kind: "number", value, options: { style: "currency", currency } });
}
for (const currency of ["USD", "CAD", "GBP"]) {
cases.push({ kind: "number", value: "1842", options: { style: "currency", currency, currencyDisplay: "narrowSymbol" } });
}
for (const value of ["1842", "-1842"]) {
cases.push({ kind: "number", value, options: { style: "currency", currency: "EUR", currencyDisplay: "code" } });
}
for (const value of ["1", "2", "3", "11", "100", "1.5", "-1842", "1000000"]) {
cases.push({ kind: "number", value, options: { style: "currency", currency: "USD", currencyDisplay: "name" } });
}
cases.push({ kind: "number", value: "1", options: { style: "currency", currency: "EUR", currencyDisplay: "name" } });
for (const currency of ["USD", "EUR", "JPY"]) {
cases.push({ kind: "number", value: "-1842", options: { style: "currency", currency, currencySign: "accounting" } });
}
cases.push({ kind: "number", value: "-1842", options: { style: "currency", currency: "EUR", currencyDisplay: "code", currencySign: "accounting" } });
cases.push({ kind: "number", value: "-1842", options: { style: "currency", currency: "USD", currencyDisplay: "name", currencySign: "accounting" } });
cases.push({ kind: "number", value: "1842.5", options: { style: "currency", currency: "USD", maximumFractionDigits: 0 } });
cases.push({ kind: "number", value: "1842.56", options: { style: "currency", currency: "USD", maximumFractionDigits: 1 } });
cases.push({ kind: "number", value: "1842.5", options: { style: "currency", currency: "USD", minimumFractionDigits: 3 } });
cases.push({ kind: "number", value: "1842.5", options: { style: "currency", currency: "JPY", minimumFractionDigits: 1 } });
cases.push({ kind: "number", value: "1234567", options: { style: "currency", currency: "USD", useGrouping: false } });
// Compact amounts, as a chart of money labels its axis.
for (const value of ["999", "1234", "4200000", "-4200000", "1234567890", "1000000000000000"]) {
cases.push({ kind: "number", value, options: { style: "currency", currency: "USD", notation: "compact" } });
}
cases.push({ kind: "number", value: "4200000", options: { style: "currency", currency: "USD", notation: "compact", compactDisplay: "long" } });
cases.push({ kind: "number", value: "123456789", options: { style: "currency", currency: "JPY", notation: "compact" } });
cases.push({ kind: "number", value: "4200000", options: { style: "currency", currency: "EUR", notation: "compact", currencyDisplay: "code" } });
cases.push({ kind: "number", value: "-123", options: { style: "currency", currency: "EUR", notation: "compact", currencySign: "accounting" } });
for (const compactDisplay of ["short", "long"] as const) {
for (const value of ["1000000", "4200000"]) {
cases.push({ kind: "number", value, options: { style: "currency", currency: "EUR", notation: "compact", compactDisplay, currencyDisplay: "name" } });
}
}
// Dates and times.
const times = ["2026-01-05T13:07:09Z", "2025-12-29T00:07:09Z", "2024-07-14T12:00:00Z", "1999-10-31T06:30:05Z"];
const styles = ["full", "long", "medium", "short"] as const;
for (const time of times.slice(0, 2)) {
for (const s of styles) cases.push({ kind: "date", time, options: { dateStyle: s } });
}
for (const time of times) {
for (const s of styles) cases.push({ kind: "date", time, options: { timeStyle: s } });
}
for (const s of styles) cases.push({ kind: "date", time: times[0]!, options: { dateStyle: s, timeStyle: s } });
cases.push({ kind: "date", time: times[0]!, options: { dateStyle: "full", timeStyle: "short" } });
cases.push({ kind: "date", time: times[0]!, options: { dateStyle: "short", timeStyle: "medium" } });
for (const hourCycle of ["h12", "h23"] as const) {
for (const time of [times[0]!, times[1]!]) {
for (const s of ["short", "medium"] as const) cases.push({ kind: "date", time, options: { timeStyle: s, hourCycle } });
cases.push({ kind: "date", time, options: { hour: "numeric", minute: "2-digit", hourCycle } });
cases.push({ kind: "date", time, options: { hour: "numeric", minute: "2-digit", second: "2-digit", hourCycle } });
}
}
// The skeletons the controls and messages use, as Intl's options.
const skeletons: Intl.DateTimeFormatOptions[] = [
{ year: "numeric", month: "long" }, // yMMMM, a calendar's title
{ year: "numeric", month: "short" }, // yMMM
{ month: "short", day: "numeric" }, // MMMd
{ month: "long", day: "numeric" }, // MMMMd
{ year: "numeric", month: "numeric", day: "numeric" }, // yMd
{ year: "numeric", month: "short", day: "numeric" }, // yMMMd
{ year: "numeric", month: "long", day: "numeric", weekday: "long" }, // yMMMMEEEEd
{ year: "numeric", month: "short", day: "numeric", weekday: "short" }, // yMMMEEEd
{ year: "numeric", month: "2-digit", day: "2-digit" }, // yMMdd
{ year: "numeric", month: "numeric" }, // yM
{ month: "short", day: "numeric", weekday: "short" }, // MMMEEEd
{ day: "numeric", weekday: "short" }, // EEEd
{ weekday: "long" }, // EEEE
{ month: "long" }, // MMMM
{ year: "numeric" }, // y
{ day: "numeric" }, // d
{ hour: "numeric", minute: "2-digit" }, // jmm
{ hour: "numeric", minute: "2-digit", second: "2-digit" }, // jmmss
{ hour: "numeric" }, // j
{ minute: "2-digit", second: "2-digit" }, // mmss
{ year: "numeric", month: "short", day: "numeric", hour: "numeric", minute: "2-digit" }, // yMMMdjmm
{ year: "numeric", month: "long", day: "numeric", hour: "numeric", minute: "2-digit" }, // yMMMMdjmm
{ hour: "numeric", minute: "2-digit", timeZoneName: "short" }, // jmmz
];
for (const options of skeletons) {
for (const time of times) cases.push({ kind: "date", time, options });
}
// Offsets from GMT.
for (const zone of ["Etc/GMT-8", "Etc/GMT+5"]) {
for (const s of ["full", "long"] as const) cases.push({ kind: "date", time: times[0]!, zone, options: { timeStyle: s } });
}
// Ranges, as a date-range picker labels them: from a time to one of the
// same minute, hour, half of the day, day, month and year, and others.
const rangeStart = "2026-01-05T09:30:00Z";
const rangeEnds = ["2026-01-05T09:30:40Z", "2026-01-05T09:45:00Z", "2026-01-05T11:00:00Z", "2026-01-05T13:07:09Z",
"2026-01-09T10:00:00Z", "2026-02-09T10:00:00Z", "2027-03-02T10:00:00Z"];
const rangeOptions: Intl.DateTimeFormatOptions[] = [
{ dateStyle: "full" }, { dateStyle: "medium" }, { dateStyle: "short" }, { timeStyle: "short" },
{ dateStyle: "medium", timeStyle: "short" },
{ year: "numeric", month: "short", day: "numeric" }, // yMMMd
{ year: "numeric", month: "long" }, // yMMMM
{ month: "short", day: "numeric", weekday: "short" }, // MMMEEEd
{ hour: "numeric", minute: "2-digit" }, // jmm
{ hour: "numeric", minute: "2-digit", hourCycle: "h23" },
{ hour: "numeric", minute: "2-digit", second: "2-digit" }, // jmmss
{ year: "numeric", month: "short", day: "numeric", hour: "numeric", minute: "2-digit" }, // yMMMdjmm
];
for (const options of rangeOptions) {
for (const end of rangeEnds) cases.push({ kind: "range", time: rangeStart, end, options });
}
// The names of months and weekdays, as dates of every month and weekday
// write them: Intl gives no list of them but its patterns'.
const monthTimes = Array.from({ length: 12 }, (_, m) => new Date(Date.UTC(2023, m, 15)).toISOString());
const dayTimes = Array.from({ length: 7 }, (_, d) => new Date(Date.UTC(2023, 0, 1 + d)).toISOString());
for (const month of ["long", "short", "narrow"] as const) {
cases.push({ kind: "names", times: monthTimes, options: { month } });
cases.push({ kind: "names", times: monthTimes, options: { month, day: "numeric" } });
}
for (const weekday of ["long", "short", "narrow"] as const) {
cases.push({ kind: "names", times: dayTimes, options: { weekday } });
}
cases.push({ kind: "names", times: dayTimes, options: { weekday: "long", year: "numeric", month: "long", day: "numeric" } });
cases.push({ kind: "firstDay" }, { kind: "hourCycle" });
const hourCycles: Record<string, number> = { h11: 12, h12: 12, h23: 24, h24: 24 };
const out: Record<string, string[]> = {};
for (const locale of locales) {
const row: string[] = [];
for (const c of cases) {
switch (c.kind) {
case "number":
row.push(new Intl.NumberFormat(locale, c.options).format(c.value as unknown as number));
break;
case "date":
row.push(new Intl.DateTimeFormat(`${locale}-u-ca-gregory`, { timeZone: c.zone ?? "UTC", ...c.options }).format(new Date(c.time)));
break;
case "range":
row.push(new Intl.DateTimeFormat(`${locale}-u-ca-gregory`, { timeZone: "UTC", ...c.options }).formatRange(new Date(c.time), new Date(c.end)));
break;
case "names": {
const f = new Intl.DateTimeFormat(`${locale}-u-ca-gregory`, { timeZone: "UTC", ...c.options });
row.push(c.times.map((t) => f.format(new Date(t))).join("|"));
break;
}
case "firstDay": {
const info = (new Intl.Locale(locale) as Intl.Locale & { getWeekInfo(): { firstDay: number } }).getWeekInfo();
row.push(String(info.firstDay % 7));
break;
}
case "hourCycle":
row.push(String(hourCycles[new Intl.DateTimeFormat(locale, { hour: "numeric" }).resolvedOptions().hourCycle!]));
break;
}
}
out[locale] = row;
}
const names_: Record<string, string> = {};
for (const tag of autonyms) names_[tag] = new Intl.DisplayNames([tag], { type: "language" }).of(tag) ?? "";
const versions = process.versions as Record<string, string | undefined>;
const icu = `${versions.icu ?? "unknown"} (CLDR ${versions.cldr ?? "unknown"})`;
const lines = (m: Record<string, unknown>) =>
"{\n" + Object.entries(m).map(([k, v]) => ` ${JSON.stringify(k)}: ${JSON.stringify(v)}`).join(",\n") + "\n }";
const file = join(dir, "format_icu.json");
await writeFile(
file,
`{\n "icu": ${JSON.stringify(icu)},\n "cases": [\n${cases.map((c) => " " + JSON.stringify(c)).join(",\n")}\n ],\n "locales": ${lines(out)},\n "autonyms": ${lines(names_)}\n}\n`,
);
console.log(`wrote ${file}: ICU ${icu}, ${locales.length} locales, ${cases.length} cases`);
+90
View File
@@ -0,0 +1,90 @@
import { afterEach, expect, test } from "bun:test"
import fs from "node:fs/promises"
import os from "node:os"
import path from "node:path"
import { docsAssets } from "../website/llms"
import { rewriteHref } from "../website/src/lib/markdown-source"
const temporary: string[] = []
afterEach(async () => {
for (const dir of temporary.splice(0)) await fs.rm(dir, { recursive: true, force: true })
})
test("publishes every doc, with nested README paths and no repository-only instructions", async () => {
const repo = await fs.mkdtemp(path.join(os.tmpdir(), "mygo-llms-"))
temporary.push(repo)
await fs.mkdir(path.join(repo, "docs/ui"), { recursive: true })
await fs.mkdir(path.join(repo, "docs/plugins"), { recursive: true })
const sources = {
"README.md": "# Introduction\n\nOverview.\n\n[Native UI](ui/README.md)\n",
"ui/README.md": "# Native UI\n\nNative overview.\n\n[Home](../README.md)\n",
"plugins/fetch.md": `# Fetch
Fetch data.
[UI](../ui/README.md#input) and [Go file](../../app.go).
[External](https://example.com) and [Local](#options).
[Reference][ui]
[ui]: ../ui/README.md?view=all#input
<!-- repository-only:start -->
## Private instructions
Never publish this.
<!-- repository-only:end -->
## Options
| Option | Value |
| --- | --- |
| Method | GET |
~~~html
<!-- repository-only:start -->
This is a code example.
<!-- repository-only:end -->
~~~
`,
}
for (const [file, source] of Object.entries(sources)) await fs.writeFile(path.join(repo, "docs", file), source)
const assets = await docsAssets(repo)
expect([...assets.keys()]).toEqual(["/docs.md", "/docs/plugins/fetch.md", "/docs/ui.md", "/llms.txt", "/llms-full.txt"])
const index = assets.get("/llms.txt")!
expect(index).toStartWith("# MyGo\n\n> ")
for (const file of ["/docs.md", "/docs/plugins/fetch.md", "/docs/ui.md"]) {
expect(index).toContain(`https://mygo.egoist.dev${file}`)
expect(assets.get("/llms-full.txt")).toContain(assets.get(file)!.trimEnd())
}
const fetch = assets.get("/docs/plugins/fetch.md")!
expect(fetch).toContain("https://mygo.egoist.dev/docs/ui.md#input")
expect(fetch).toContain("https://mygo.egoist.dev/docs/ui.md?view=all#input")
expect(fetch).toContain("https://github.com/egoist/mygo/blob/main/app.go")
expect(fetch).toContain("[External](https://example.com)")
expect(fetch).toContain("[Local](#options)")
expect(fetch).toContain("| Method | GET")
expect(fetch).toContain("```html\n<!-- repository-only:start -->\nThis is a code example.")
for (const text of assets.values()) {
expect(text).not.toContain("Private instructions")
expect(text).not.toContain("Never publish this")
}
expect(assets.get("/docs/ui.md")).toContain("https://mygo.egoist.dev/docs.md")
// The dev server and subsequent builds read the current source each time.
await fs.writeFile(path.join(repo, "docs/new.md"), "# New page\n\nNew content.\n")
expect((await docsAssets(repo)).get("/llms.txt")).toContain("[New page](https://mygo.egoist.dev/docs/new.md)")
})
test("shared link rules keep HTML docs URLs and repository links intact", () => {
const links = { docsDir: "/repo/docs", repoDir: "/repo", repoUrl: "https://github.com/egoist/mygo" }
const file = "/repo/docs/ui/button.md"
expect(rewriteHref("README.md#views", file, links)).toBe("/docs/ui#views")
expect(rewriteHref("../README.md", file, links)).toBe("/docs")
expect(rewriteHref("../../ui/button.go", file, links)).toBe("https://github.com/egoist/mygo/blob/main/ui/button.go")
expect(rewriteHref("../../examples", file, links)).toBe("https://github.com/egoist/mygo/tree/main/examples")
for (const href of ["#input", "/docs/ui", "https://example.com", "//example.com", "mailto:hello@example.com"]) {
expect(rewriteHref(href, file, links)).toBe(href)
}
})
+79
View File
@@ -0,0 +1,79 @@
// Writes i18n/testdata/plurals_icu.json: the plural categories ICU
// (Intl.PluralRules) gives numbers in every language of CLDR's plural rules,
// cardinal and ordinal, which TestPluralsMatchICU checks package i18n's
// compiled rules against. Run it again after updating CLDR, with a Node.js
// whose ICU has the same CLDR (`node -p process.versions.cldr`):
//
// node scripts/plurals-golden.ts
//
// Node.js, not Bun: Bun on macOS uses the system's ICU, whose data Apple
// changes (it gives bg, af and es ordinal categories CLDR does not have).
//
// The languages are those of i18n/testdata/plural_samples.txt, which
// `go generate ./i18n` writes; the numbers are integers and decimals
// written with zero to three fraction digits, whose trailing zeros count.
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
const dir = join(import.meta.dirname, "..", "i18n", "testdata");
/** The numbers, as written: their fraction digits are visible ones. */
export const numbers: string[] = [];
for (let i = 0; i <= 120; i++) numbers.push(String(i));
for (const n of [
200, 201, 202, 203, 205, 211, 212, 1000, 1001, 1002, 1011, 1100, 10000, 20000, 40000, 100000, 100001,
1000000, 1000001, 2000000, 10000000, 100000000, 1000000000,
]) {
numbers.push(String(n));
}
for (let i = 0; i <= 30; i++) numbers.push((i / 10).toFixed(1));
for (const s of ["0.00", "0.01", "0.05", "0.10", "0.11", "0.25", "1.00", "1.01", "1.10", "1.25", "1.50", "2.00",
"2.05", "3.00", "5.30", "10.10", "11.00", "21.00", "101.01", "0.000", "1.000", "1.005", "2.500", "1000000.0"]) {
numbers.push(s);
}
const initials: Record<string, string> = { zero: "z", one: "o", two: "t", few: "f", many: "m", other: "x" };
const samples = await readFile(join(dir, "plural_samples.txt"), "utf8");
const langs = { cardinal: new Set<string>(), ordinal: new Set<string>() };
for (const line of samples.split("\n")) {
if (line === "" || line.startsWith("#")) continue;
const [kind, list] = line.split(" ") as [keyof typeof langs, string];
for (const l of list.split(",")) langs[kind].add(l);
}
const out: Record<string, Record<string, string>> = { cardinal: {}, ordinal: {} };
for (const kind of ["cardinal", "ordinal"] as const) {
for (const lang of [...langs[kind]].sort()) {
// Languages ICU does not have would get the root's rules.
if (Intl.PluralRules.supportedLocalesOf([lang]).length === 0) continue;
const rules = new Map<number, Intl.PluralRules>();
let cats = "";
for (const n of numbers) {
const v = n.includes(".") ? n.split(".")[1]!.length : 0;
let pr = rules.get(v);
if (!pr) {
pr = new Intl.PluralRules(lang, {
type: kind,
minimumFractionDigits: v,
maximumFractionDigits: v,
});
rules.set(v, pr);
}
cats += initials[pr.select(Number(n))];
}
out[kind]![lang] = cats;
}
}
const file = join(dir, "plurals_icu.json");
const versions = process.versions as Record<string, string | undefined>;
const icu = `${versions.icu ?? "unknown"} (CLDR ${versions.cldr ?? "unknown"})`;
// A language a line, the numbers on one.
const map = (m: Record<string, string>) =>
"{\n" + Object.entries(m).map(([k, v]) => ` ${JSON.stringify(k)}: ${JSON.stringify(v)}`).join(",\n") + "\n }";
await writeFile(
file,
`{\n "icu": ${JSON.stringify(icu)},\n "numbers": ${JSON.stringify(numbers)},\n "cardinal": ${map(out.cardinal!)},\n "ordinal": ${map(out.ordinal!)}\n}\n`,
);
console.log(`wrote ${file}: ICU ${icu}, ${Object.keys(out.cardinal!).length} cardinal and ${Object.keys(out.ordinal!).length} ordinal languages`);
+88
View File
@@ -0,0 +1,88 @@
// Publishes the npm packages of a release: mygo-runtime, the official
// plugins' packages (@mygo-plugins/*), the platform
// packages of mygo-cli with freshly built binaries, then mygo-cli, which
// depends on them, once npm serves them. Versions already on npm are
// skipped, so a release that failed halfway can run again, and prereleases
// get the next dist-tag. Arguments go to npm publish, e.g. --dry-run or
// --provenance.
import { readFile } from "node:fs/promises";
import { join } from "node:path";
import { buildBinary, dir as cliDir, platformDir, version, writeManifests } from "../packages/cli/build.ts";
import { platforms } from "../packages/cli/index.js";
import { pluginPackages } from "./version.ts";
const root = join(import.meta.dir, "..");
const flags = process.argv.slice(2);
// npm serves a package minutes after accepting it (one to five for 0.2.11),
// so each package goes out as soon as it can, alongside the others: the
// runtime and the plugins while the binaries build, and each platform
// package once its binary is built.
await writeManifests(await version());
const libraries = [join(root, "packages", "runtime"), ...pluginPackages.map((p) => join(root, p))];
const publishing = libraries.map(publish);
for (const platform of platforms) {
await buildBinary(platform);
publishing.push(publish(platformDir(platform)));
}
if (!(await Promise.all(publishing)).every(Boolean)) process.exit(1);
// A package manager installs mygo-cli without the platform packages it
// cannot fetch: bun then keeps them out of later installs while its lockfile
// lacks them. The projects mygo init creates depend on mygo-runtime too.
if (!flags.includes("--dry-run")) {
for (const pkg of [...libraries, ...platforms.map(platformDir)]) await waitUntilServed(await manifest(pkg));
}
if (!(await publish(cliDir))) process.exit(1);
async function manifest(pkg: string): Promise<{ name: string; version: string }> {
return JSON.parse(await readFile(join(pkg, "package.json"), "utf8"));
}
/**
* Publishes a package unless npm has its version, and reports whether that
* went well. It prints npm's output once done, so that packages published
* together don't mix theirs.
*/
async function publish(pkg: string): Promise<boolean> {
const { name, version } = await manifest(pkg);
const view = Bun.spawn(["npm", "view", `${name}@${version}`, "version"], { stderr: "ignore" });
if ((await new Response(view.stdout).text()).trim() === version) {
console.log(`${name}@${version} is already published`);
return true;
}
const tag = version.includes("-") ? ["--tag", "next"] : [];
const npm = Bun.spawn(["npm", "publish", "--access", "public", ...tag, ...flags], {
cwd: pkg,
stdout: "pipe",
stderr: "pipe",
});
const [stdout, stderr, code] = await Promise.all([
new Response(npm.stdout).text(),
new Response(npm.stderr).text(),
npm.exited,
]);
process.stdout.write(stderr + stdout);
if (code !== 0) console.error(`publishing ${name}@${version} failed`);
return code === 0;
}
/** Waits until npm serves name@version to package managers. */
async function waitUntilServed({ name, version }: { name: string; version: string }): Promise<void> {
const deadline = Date.now() + 10 * 60_000;
for (;;) {
try {
const res = await fetch(`https://registry.npmjs.org/${name.replace("/", "%2f")}`, {
// The abbreviated metadata package managers install from.
headers: { accept: "application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*" },
});
const doc = res.ok ? ((await res.json()) as { versions?: Record<string, unknown> }) : {};
if (doc.versions?.[version]) return;
} catch {}
if (Date.now() > deadline) {
console.error(`npm does not serve ${name}@${version}: run the release again later`);
process.exit(1);
}
console.log(`waiting for npm to serve ${name}@${version}`);
await Bun.sleep(10_000);
}
}
+33
View File
@@ -0,0 +1,33 @@
// Writes i18n/testdata/relative_time_icu.json.gz with Node's upstream ICU.
// Run after updating CLDR: node scripts/relative-time-golden.ts
// Bun on macOS uses Apple's ICU; use Node with CLDR matching i18n's.
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { gzipSync } from "node:zlib";
const dir = join(import.meta.dirname, "..", "i18n", "testdata");
const { locales } = JSON.parse(await readFile(join(dir, "format_locales.json"), "utf8")) as { locales: string[] };
const units = ["second", "minute", "hour", "day", "week", "month", "quarter", "year"] as const;
const cases: { value: string; unit: number; style: number; auto: boolean }[] = [];
const styles = ["long", "short", "narrow"] as const;
for (const [style] of styles.entries()) {
for (const auto of [false, true]) {
for (const [unit] of units.entries()) {
for (const value of ["-12345.6", "-1.2345", "-21", "-11", "-5", "-2", "-1", "-0.005", "-0.0049", "-0.0001", "-0", "0", "0.0001", "0.0049", "0.005", "0.5", "0.995", "1", "1.0001", "1.2345", "1.2355", "1.0049", "1.005", "2", "3", "5", "11", "21", "1234", "12345.6"]) {
cases.push({ value, unit, style, auto });
}
}
}
}
const rows: Record<string, string[]> = {};
// Extensions check the same digit selection as the number formatter;
// unknown and POSIX locales are covered on the Go side.
for (const locale of [...locales, "ar-u-nu-latn", "fa-u-nu-latn", "bn-u-nu-latn", "en-AU", "zh-TW"]) {
const formatters = styles.flatMap((style) => [false, true].map((auto) =>
new Intl.RelativeTimeFormat(locale, { style, numeric: auto ? "auto" : "always" })));
rows[locale] = cases.map((c) => formatters[c.style * 2 + Number(c.auto)]!.format(Number(c.value), units[c.unit]!));
}
const golden = { icu: process.versions.icu, cldr: process.versions.cldr, cases, locales: rows };
// The full cross-product is compressed to keep the fixture small.
await writeFile(join(dir, "relative_time_icu.json.gz"), gzipSync(JSON.stringify(golden) + "\n", { level: 9 }));
console.log(`${Object.keys(rows).length} locales, ${cases.length} cases each`);
+112
View File
@@ -0,0 +1,112 @@
// Sets or checks the version MyGo is released with, which the Go module
// (mygo.Version), the CLI and the npm packages share:
//
// bun scripts/version.ts 0.2.0 # set it everywhere, bun.lock too
// bun scripts/version.ts --check v0.2.0 # check that everything has it
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { platformDir, platformName, writeManifests } from "../packages/cli/build.ts";
import { platforms } from "../packages/cli/index.js";
const root = join(import.meta.dir, "..");
/** Go files declaring the version. */
const goFiles = [
{ path: "mygo.go", pattern: /^const Version = "([^"]*)"$/m, decl: "const Version" },
{ path: "cmd/mygo/main.go", pattern: /^const version = "([^"]*)"$/m, decl: "const version" },
];
/** The official plugins' JavaScript packages, whose peer mygo-runtime is. */
export const pluginPackages = ["plugins/fetch", "plugins/websocket", "plugins/sqlite", "plugins/watch"];
/** package.json files of the npm packages. */
const packages = [
"packages/runtime",
...pluginPackages,
"packages/cli",
...platforms.map((p) => platformDir(p).slice(root.length + 1)),
];
/**
* Matches the version that mygo-cli's optionalDependencies give a platform
* package in bun.lock, the only entry of its name with a string value.
*/
function lockedPlatform(platform: string): RegExp {
return new RegExp(`("${platformName(platform)}": )"([^"]*)"`);
}
/**
* Updates bun.lock to the versions of the packages. bun install keeps the
* versions of mygo-cli's optionalDependencies, which are workspaces, so
* they are set here.
*/
async function updateLockfile(v: string): Promise<void> {
const install = Bun.spawnSync([process.execPath, "install", "--lockfile-only"], {
cwd: root,
stdout: "inherit",
stderr: "inherit",
});
if (!install.success) throw new Error("bun install --lockfile-only failed");
const file = join(root, "bun.lock");
let lock = await readFile(file, "utf8");
for (const p of platforms) {
if (!lockedPlatform(p).test(lock)) throw new Error(`bun.lock has no version of ${platformName(p)}`);
lock = lock.replace(lockedPlatform(p), `$1"${v}"`);
}
await writeFile(file, lock);
}
async function versions(): Promise<Map<string, string>> {
const found = new Map<string, string>();
for (const { path, pattern } of goFiles) {
found.set(path, (await readFile(join(root, path), "utf8")).match(pattern)?.[1] ?? "(none)");
}
for (const dir of packages) {
const pkg = JSON.parse(await readFile(join(root, dir, "package.json"), "utf8"));
found.set(`${dir}/package.json`, pkg.version);
for (const [name, v] of Object.entries<string>(pkg.optionalDependencies ?? {})) {
found.set(`${dir}/package.json: ${name}`, v);
}
for (const deps of ["peerDependencies", "devDependencies"]) {
const runtime = pkg[deps]?.["mygo-runtime"];
if (runtime) found.set(`${dir}/package.json: ${deps} mygo-runtime`, runtime.replace(/^\^/, ""));
}
}
const lock = await readFile(join(root, "bun.lock"), "utf8");
for (const p of platforms) {
found.set(`bun.lock: ${platformName(p)}`, lock.match(lockedPlatform(p))?.[2] ?? "(none)");
}
return found;
}
if (import.meta.main) {
const args = process.argv.slice(2);
if (args[0] === "--check" && args[1]) {
const want = args[1].replace(/^v/, "");
const wrong = [...(await versions())].filter(([, v]) => v !== want);
for (const [where, v] of wrong) console.error(`${where} has ${v}, not ${want}`);
if (wrong.length > 0) process.exit(1);
console.log(`everything is at ${want}`);
} else if (args.length === 1 && /^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/.test(args[0]!)) {
const v = args[0]!;
for (const { path, pattern, decl } of goFiles) {
const file = join(root, path);
await writeFile(file, (await readFile(file, "utf8")).replace(pattern, `${decl} = "${v}"`));
}
for (const dir of ["packages/runtime", ...pluginPackages]) {
const file = join(root, dir, "package.json");
const pkg = JSON.parse(await readFile(file, "utf8"));
pkg.version = v;
for (const deps of [pkg.peerDependencies, pkg.devDependencies]) {
if (deps?.["mygo-runtime"]) deps["mygo-runtime"] = `^${v}`;
}
await writeFile(file, JSON.stringify(pkg, null, 2) + "\n");
}
await writeManifests(v);
await updateLockfile(v);
console.log(`set the version to ${v}: commit, then push the tag v${v} to release`);
} else {
console.error("usage: bun scripts/version.ts <version> | --check <tag>");
process.exit(2);
}
}