@akanjs/devkit 3.3.0-rc.59 → 3.3.0-rc.60
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/akanApp/akanApp.host.test.ts +3 -1
- package/app/dictionarySizes.test.ts +40 -0
- package/app/dictionarySizes.ts +6 -2
- package/codeAgent/skills/akan-page/SKILL.md +1 -1
- package/docs/apiReference.ts +1 -1
- package/frontendBuild/dictionaryAssetBuilder.test.ts +79 -0
- package/frontendBuild/dictionaryAssetBuilder.ts +35 -16
- package/frontendBuild/dictionaryOwnParts.ts +88 -0
- package/frontendBuild/dictionaryPackState.ts +131 -0
- package/frontendBuild/dictionaryPacking.test.ts +77 -12
- package/frontendBuild/dictionaryPacking.ts +88 -63
- package/frontendBuild/precompressArtifacts.ts +12 -0
- package/package.json +8 -5
- package/tunnel/createTunnel.ts +5 -1
- package/tunnel/ssh2Module.test.ts +37 -0
- package/tunnel/ssh2Module.ts +32 -0
- package/tunnel/sshTunnel.ts +4 -2
|
@@ -406,8 +406,10 @@ describe("a stop while the builder is starting", () => {
|
|
|
406
406
|
const starting = host.start();
|
|
407
407
|
await Bun.sleep(50);
|
|
408
408
|
expect(builder.started).toBe(1);
|
|
409
|
+
//? Read before the stop: stop() takes real time with a backend alive, and Bun fails a test on an unread rejection.
|
|
410
|
+
const outcome = settled(starting);
|
|
409
411
|
await host.stop();
|
|
410
|
-
expect(await
|
|
412
|
+
expect(await outcome).toBe("dev server stopped before the builder was ready");
|
|
411
413
|
exitLate?.();
|
|
412
414
|
await Bun.sleep(50);
|
|
413
415
|
expect({ creates, stopped: builder.stopped }).toEqual({ creates: 1, stopped: 1 });
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test";
|
|
2
|
+
import { mkdir, writeFile } from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { tempDirs } from "../test/testHelpers";
|
|
5
|
+
import { DictionarySizes } from "./dictionarySizes";
|
|
6
|
+
|
|
7
|
+
const tempRoot = tempDirs("akan-devkit-dict-sizes-");
|
|
8
|
+
|
|
9
|
+
describe("DictionarySizes", () => {
|
|
10
|
+
test("counts a route whose files would cost more than the whole page file at the whole, the API file on top", async () => {
|
|
11
|
+
const artifactDir = await tempRoot();
|
|
12
|
+
await mkdir(path.join(artifactDir, "dict"), { recursive: true });
|
|
13
|
+
const sized = { "en-page": 1000, "en-0": 600, "en-1": 500, "en-api": 200 };
|
|
14
|
+
for (const [stem, bytes] of Object.entries(sized)) {
|
|
15
|
+
await writeFile(path.join(artifactDir, `dict/${stem}.js`), "x".repeat(bytes * 4));
|
|
16
|
+
await writeFile(path.join(artifactDir, `dict/${stem}.js.br`), "x".repeat(bytes));
|
|
17
|
+
}
|
|
18
|
+
const fileOf = (stem: string) => ({ url: `/_akan/dict/${stem}.js`, relPath: `dict/${stem}.js` });
|
|
19
|
+
const artifact = {
|
|
20
|
+
dictAssets: {
|
|
21
|
+
en: {
|
|
22
|
+
...fileOf("en-page"),
|
|
23
|
+
parts: { api: fileOf("en-api") },
|
|
24
|
+
routeParts: { table: fileOf("en-groups"), files: [fileOf("en-0"), fileOf("en-1"), fileOf("en-api")] },
|
|
25
|
+
},
|
|
26
|
+
},
|
|
27
|
+
dictRoutes: { "/:lang/light": [0], "/:lang/wide": [0, 1, 2] },
|
|
28
|
+
};
|
|
29
|
+
await writeFile(path.join(artifactDir, "base-artifact.json"), JSON.stringify(artifact));
|
|
30
|
+
|
|
31
|
+
expect(DictionarySizes.of(artifactDir)).toEqual([
|
|
32
|
+
{
|
|
33
|
+
lang: "en",
|
|
34
|
+
pageBrotliBytes: 1000,
|
|
35
|
+
apiBrotliBytes: 200,
|
|
36
|
+
routeBrotliBytes: { lightest: 600, median: 600, largest: 1200 },
|
|
37
|
+
},
|
|
38
|
+
]);
|
|
39
|
+
});
|
|
40
|
+
});
|
package/app/dictionarySizes.ts
CHANGED
|
@@ -51,7 +51,7 @@ export class DictionarySizes {
|
|
|
51
51
|
return `Dictionary ${lang}: first visit ${visit} brotli on the lightest / median / largest route (whole ${formatBytes(pageBrotliBytes)})${api}`;
|
|
52
52
|
}
|
|
53
53
|
|
|
54
|
-
//? A route the build could not read
|
|
54
|
+
//? A route the build could not read, or whose files would cost the whole or more, is served the whole page file.
|
|
55
55
|
static #routes(
|
|
56
56
|
asset: DictAsset,
|
|
57
57
|
pageBytes: number,
|
|
@@ -62,10 +62,14 @@ export class DictionarySizes {
|
|
|
62
62
|
const files = asset.routeParts?.files;
|
|
63
63
|
if (!files) return null;
|
|
64
64
|
const fileBytes = files.map(({ relPath }) => brotliOf(relPath));
|
|
65
|
+
const apiIdx = files.findIndex(({ url }) => url === asset.parts?.api?.url);
|
|
65
66
|
const sizes = routeIds
|
|
66
67
|
.map((routeId) => {
|
|
67
68
|
const parts = dictRoutes[routeId];
|
|
68
|
-
|
|
69
|
+
if (!parts) return pageBytes;
|
|
70
|
+
const api = parts.includes(apiIdx) ? (fileBytes[apiIdx] ?? 0) : 0;
|
|
71
|
+
const page = parts.reduce((total, idx) => total + (idx === apiIdx ? 0 : (fileBytes[idx] ?? 0)), 0);
|
|
72
|
+
return Math.min(page, pageBytes) + api;
|
|
69
73
|
})
|
|
70
74
|
.sort((a, b) => a - b);
|
|
71
75
|
const at = (idx: number) => sizes[idx] ?? 0;
|
|
@@ -75,7 +75,7 @@ File names, stages, the `.render()` order and what a route file must never do ar
|
|
|
75
75
|
- An SSR page still loading: `pendingClassName` / `data-pending` on its `Link`, and `usePendingNavigation()`
|
|
76
76
|
(`akanjs/client`) for its `{ path, searchParams }`, `null` once the page is drawn.
|
|
77
77
|
- From a handler: `router.push(href)` / `router.replace(href)`; in a server stage, `router.redirect(href)`.
|
|
78
|
-
- A page state a push opens in the query (a record in `?id=`): close it with `router.
|
|
78
|
+
- A page state a push opens in the query (a record in `?id=`): close it with `router.backOrReplace(href)`, never
|
|
79
79
|
`router.back()` or a `renderMode` branch. A CSR or native stack rewrites a push that keeps the pathname rather than
|
|
80
80
|
stacking it, and the address may be opened directly.
|
|
81
81
|
- A client filter kept in the URL without reloading the page: ``router.replace(`/books?q=${q}`, { shallow: true,
|
package/docs/apiReference.ts
CHANGED
|
@@ -5,6 +5,7 @@ import path from "node:path";
|
|
|
5
5
|
import type { App } from "../commandDecorators";
|
|
6
6
|
import { tempDirs } from "../test/testHelpers";
|
|
7
7
|
import { DictionaryAssetBuilder } from "./dictionaryAssetBuilder";
|
|
8
|
+
import { dictionaryBrotliBytesOf } from "./precompressArtifacts";
|
|
8
9
|
|
|
9
10
|
const tempRoot = tempDirs("akan-devkit-dict-asset-");
|
|
10
11
|
|
|
@@ -381,6 +382,84 @@ describe("DictionaryAssetBuilder", () => {
|
|
|
381
382
|
expect(api.default).toEqual({ memo: { signal: { getMemo: { desc: { t: "Reads a memo" } } } } });
|
|
382
383
|
});
|
|
383
384
|
|
|
385
|
+
test("records what each page file of a build costs a browser, in every locale, and nothing in development", async () => {
|
|
386
|
+
const { app, artifactDir } = await makeApp(dictSourceOf(routedDictionary));
|
|
387
|
+
const built = await new DictionaryAssetBuilder(app, path.join(artifactDir, "build")).buildAll(i18n, {
|
|
388
|
+
splitApi: true,
|
|
389
|
+
routes,
|
|
390
|
+
});
|
|
391
|
+
const dev = await new DictionaryAssetBuilder(app, path.join(artifactDir, "dev")).buildAll(i18n, {
|
|
392
|
+
splitApi: true,
|
|
393
|
+
everyGroupAlone: true,
|
|
394
|
+
});
|
|
395
|
+
|
|
396
|
+
for (const lang of i18n.locales) {
|
|
397
|
+
const asset = built.assets[lang];
|
|
398
|
+
const pageFiles = (asset?.routeParts?.files ?? []).filter(({ url }) => url !== asset?.parts?.api?.url);
|
|
399
|
+
expect(pageFiles.length).toBeGreaterThan(1);
|
|
400
|
+
for (const file of [asset, ...pageFiles]) {
|
|
401
|
+
const source = await Bun.file(path.join(artifactDir, "build", file?.relPath ?? "")).bytes();
|
|
402
|
+
const brotli = dictionaryBrotliBytesOf(new TextDecoder().decode(source));
|
|
403
|
+
expect(file?.bytes).toBe(Math.min(source.byteLength, brotli));
|
|
404
|
+
}
|
|
405
|
+
expect(dev.assets[lang]?.bytes).toBeUndefined();
|
|
406
|
+
for (const file of dev.assets[lang]?.routeParts?.files ?? []) expect(file.bytes).toBeUndefined();
|
|
407
|
+
}
|
|
408
|
+
});
|
|
409
|
+
|
|
410
|
+
test("gives a route past the bound a file of its own, which the table never names, and records what each file costs", async () => {
|
|
411
|
+
let seed = 3;
|
|
412
|
+
const word = () => {
|
|
413
|
+
seed = (seed * 48271) % 2147483647;
|
|
414
|
+
return seed.toString(36);
|
|
415
|
+
};
|
|
416
|
+
const textOf = () => Array.from({ length: 400 }, word).join(" ");
|
|
417
|
+
const modules = Array.from({ length: 6 }, (_, idx) => idx);
|
|
418
|
+
const en = Object.fromEntries(
|
|
419
|
+
modules.flatMap((idx) => [
|
|
420
|
+
[`g${idx}`, { t: textOf() }],
|
|
421
|
+
[`h${idx}`, { t: textOf() }],
|
|
422
|
+
]),
|
|
423
|
+
);
|
|
424
|
+
const heavy = "/:lang/heavy";
|
|
425
|
+
const wide = new Map([
|
|
426
|
+
[heavy, modules.map((idx) => `g${idx}`)],
|
|
427
|
+
...modules.map((idx) => [`/:lang/light${idx}`, [`g${idx}`, `h${idx}`]] as [string, string[]]),
|
|
428
|
+
]);
|
|
429
|
+
const { app, artifactDir } = await makeApp(dictSourceOf({ en, ko: en }));
|
|
430
|
+
const built = await new DictionaryAssetBuilder(app, path.join(artifactDir, "build")).buildAll(i18n, {
|
|
431
|
+
routes: wide,
|
|
432
|
+
});
|
|
433
|
+
const dev = await new DictionaryAssetBuilder(app, path.join(artifactDir, "dev")).buildAll(i18n, {
|
|
434
|
+
everyGroupAlone: true,
|
|
435
|
+
});
|
|
436
|
+
|
|
437
|
+
const held = built.routes?.[heavy] ?? [];
|
|
438
|
+
expect(held).toHaveLength(4);
|
|
439
|
+
for (const lang of i18n.locales) {
|
|
440
|
+
const asset = built.assets[lang];
|
|
441
|
+
const files = asset?.routeParts?.files ?? [];
|
|
442
|
+
const table = await importOf<{ default: Record<string, number> }>(
|
|
443
|
+
path.join(artifactDir, "build"),
|
|
444
|
+
asset?.routeParts?.table.url ?? "",
|
|
445
|
+
);
|
|
446
|
+
const own = held.at(-1) ?? -1;
|
|
447
|
+
expect(Object.values(table.default)).not.toContain(own);
|
|
448
|
+
for (const [routeId, shown] of wide) {
|
|
449
|
+
const merged: Record<string, unknown> = {};
|
|
450
|
+
for (const idx of built.routes?.[routeId] ?? []) {
|
|
451
|
+
const part = await importOf<PartModule>(path.join(artifactDir, "build"), files[idx]?.url ?? "");
|
|
452
|
+
Object.assign(merged, part.default);
|
|
453
|
+
}
|
|
454
|
+
expect(new Set(Object.keys(merged))).toEqual(new Set(shown));
|
|
455
|
+
}
|
|
456
|
+
expect(asset?.bytes).toBeGreaterThan(0);
|
|
457
|
+
for (const file of files) expect(file.bytes).toBeGreaterThan(0);
|
|
458
|
+
expect(dev.assets[lang]?.bytes).toBeUndefined();
|
|
459
|
+
for (const file of dev.assets[lang]?.routeParts?.files ?? []) expect(file.bytes).toBeUndefined();
|
|
460
|
+
}
|
|
461
|
+
});
|
|
462
|
+
|
|
384
463
|
test("development writes one file per group and the index of each, as each route's groups are read when it builds", async () => {
|
|
385
464
|
const { app, artifactDir } = await makeApp(dictSourceOf(routedDictionary));
|
|
386
465
|
const built = await new DictionaryAssetBuilder(app, artifactDir).buildAll(i18n, { everyGroupAlone: true });
|
|
@@ -3,8 +3,8 @@ import { type AllDictionary, type Dictionary, Translator } from "akanjs/client";
|
|
|
3
3
|
import type { AkanI18nConfig } from "akanjs/common";
|
|
4
4
|
import type { DictAsset } from "akanjs/server";
|
|
5
5
|
import type { App } from "../commandDecorators";
|
|
6
|
-
import { DictionaryPacking } from "./dictionaryPacking";
|
|
7
|
-
import { dictionaryBrotliBytesOf } from "./precompressArtifacts";
|
|
6
|
+
import { type DictionaryPack, DictionaryPacking } from "./dictionaryPacking";
|
|
7
|
+
import { dictionaryBrotliBytesOf, dictionaryServedBytesOf } from "./precompressArtifacts";
|
|
8
8
|
|
|
9
9
|
export interface DictionaryAssetBuildOptions {
|
|
10
10
|
/** Each locale's API descriptions go to a file of their own, loaded where shown. */
|
|
@@ -62,13 +62,18 @@ export class DictionaryAssetBuilder {
|
|
|
62
62
|
this.#app.verbose(
|
|
63
63
|
`[dictionary] ${packed.wholeRoutes.length} route(s) load the whole page dictionary: their own files would not be smaller. Routes: ${packed.wholeRoutes.join(", ")}`,
|
|
64
64
|
);
|
|
65
|
-
|
|
65
|
+
if (packed?.ownParts.length)
|
|
66
|
+
this.#app.verbose(
|
|
67
|
+
`[dictionary] ${packed.ownParts.length} file(s) hold the texts of a route past its ${DictionaryPacking.bound} files`,
|
|
68
|
+
);
|
|
69
|
+
const pack: DictionaryPack | null =
|
|
66
70
|
packed && Object.keys(packed.partsByRoute).length
|
|
67
71
|
? packed
|
|
68
72
|
: everyGroupAlone
|
|
69
|
-
? { parts: groups.map((group) => [group]), partsByRoute: {} }
|
|
73
|
+
? { parts: groups.map((group) => [group]), ownParts: [], partsByRoute: {} }
|
|
70
74
|
: null;
|
|
71
|
-
const
|
|
75
|
+
const measured = !!packed && pack === packed;
|
|
76
|
+
const assets = await Promise.all(locales.map((locale) => this.#writeLocale(locale, pack, measured)));
|
|
72
77
|
const files = assets.flatMap(([, asset]) => [
|
|
73
78
|
asset,
|
|
74
79
|
...Object.values(asset.parts ?? {}),
|
|
@@ -77,7 +82,8 @@ export class DictionaryAssetBuilder {
|
|
|
77
82
|
this.#app.verbose(`[base-artifact] dictionaries -> ${files.map((asset) => asset.relPath).join(", ")}`);
|
|
78
83
|
if (!pack?.parts.length) return { assets: Object.fromEntries(assets) };
|
|
79
84
|
const { apiPart, apiGroup } = DictionaryAssetBuilder;
|
|
80
|
-
const
|
|
85
|
+
const fileCount = pack.parts.length + pack.ownParts.length;
|
|
86
|
+
const apiFile = assets.every(([, asset]) => asset.parts?.[apiPart]) ? fileCount : null;
|
|
81
87
|
if (!everyGroupAlone || routes?.size) {
|
|
82
88
|
const withApi = (routeId: string, files: number[]) =>
|
|
83
89
|
apiFile !== null && routes?.get(routeId)?.includes(apiGroup) ? [...files, apiFile] : files;
|
|
@@ -100,9 +106,13 @@ export class DictionaryAssetBuilder {
|
|
|
100
106
|
) {
|
|
101
107
|
const { lang = defaultLocale, page: sizing = {} } =
|
|
102
108
|
locales.find((locale) => locale.lang === defaultLocale) ?? locales[0] ?? {};
|
|
109
|
+
//? The exports a file carries are counted too, its table's name at its longest: the build's names are not known yet.
|
|
110
|
+
const table = `${DictionaryAssetBuilder.urlPrefix}/${lang}-groups-${"x".repeat(13)}.js`;
|
|
103
111
|
const servedBytesOf = (held: readonly string[]) => {
|
|
104
112
|
const texts = Object.fromEntries(held.flatMap((group) => (sizing[group] ? [[group, sizing[group]]] : [])));
|
|
105
|
-
|
|
113
|
+
const whole = held.length === groups.length;
|
|
114
|
+
const exports = whole ? { table } : { table, groups: [...held] };
|
|
115
|
+
return dictionaryBrotliBytesOf(DictionaryAssetBuilder.source(lang, texts, undefined, exports));
|
|
106
116
|
};
|
|
107
117
|
const bytesOf = (group: string) => JSON.stringify(sizing[group] ?? {}).length;
|
|
108
118
|
return DictionaryPacking.packUnderWhole(routes, bytesOf, groups, servedBytesOf);
|
|
@@ -116,35 +126,44 @@ export class DictionaryAssetBuilder {
|
|
|
116
126
|
return getAllDictionary ? getAllDictionary() : null;
|
|
117
127
|
}
|
|
118
128
|
|
|
119
|
-
async #writeLocale(
|
|
129
|
+
async #writeLocale(
|
|
130
|
+
{ lang, page, api }: LocalePages,
|
|
131
|
+
pack: DictionaryPack | null,
|
|
132
|
+
measured: boolean,
|
|
133
|
+
): Promise<readonly [string, DictAsset]> {
|
|
120
134
|
const { source, apiPart } = DictionaryAssetBuilder;
|
|
121
|
-
const
|
|
135
|
+
const packed = pack?.parts.length ? [...pack.parts, ...pack.ownParts] : null;
|
|
136
|
+
const apiSource = source(lang, api, undefined, packed ? { part: apiPart } : {});
|
|
122
137
|
const apiAsset = Object.keys(api).length ? await this.#write(`${lang}-api`, apiSource) : null;
|
|
123
138
|
const parts = apiAsset ? { [apiPart]: apiAsset.url } : undefined;
|
|
124
139
|
const withParts = apiAsset ? { parts: { [apiPart]: apiAsset } } : {};
|
|
125
|
-
if (!packed
|
|
140
|
+
if (!pack || !packed) return [lang, { ...(await this.#write(lang, source(lang, page, parts))), ...withParts }];
|
|
126
141
|
//? Named for what decides every file it lists, not for their names: each part names the table it belongs to.
|
|
127
142
|
const tableName = `${lang}-groups-${Bun.hash(JSON.stringify([page, packed, parts ?? null])).toString(36)}.js`;
|
|
128
143
|
const table = `${DictionaryAssetBuilder.urlPrefix}/${tableName}`;
|
|
129
144
|
const groupFiles = await Promise.all(
|
|
130
145
|
packed.map((groups, idx) => {
|
|
131
146
|
const held = Object.fromEntries(groups.flatMap((group) => (page[group] ? [[group, page[group]]] : [])));
|
|
132
|
-
return this.#write(`${lang}-${idx}`, source(lang, held, parts, { table, groups }));
|
|
147
|
+
return this.#write(`${lang}-${idx}`, source(lang, held, parts, { table, groups }), undefined, measured);
|
|
133
148
|
}),
|
|
134
149
|
);
|
|
135
150
|
const files = apiAsset ? [...groupFiles, apiAsset] : groupFiles;
|
|
136
|
-
|
|
151
|
+
//? A route's own file holds groups a shared file holds too: a group missed is fetched from the shared one.
|
|
152
|
+
const groupIndex = Object.fromEntries(pack.parts.flatMap((groups, idx) => groups.map((group) => [group, idx])));
|
|
137
153
|
const tableSource = `export const lang = ${JSON.stringify(lang)};\nexport const files = ${JSON.stringify(files.map(({ url }) => url))};\nexport default ${JSON.stringify(groupIndex)};\n`;
|
|
138
154
|
const tableAsset = await this.#write(lang, tableSource, tableName);
|
|
139
|
-
const whole = await this.#write(lang, source(lang, page, parts, { table }));
|
|
155
|
+
const whole = await this.#write(lang, source(lang, page, parts, { table }), undefined, measured);
|
|
140
156
|
return [lang, { ...whole, ...withParts, routeParts: { table: tableAsset, files } }];
|
|
141
157
|
}
|
|
142
158
|
|
|
143
|
-
async #write(stem: string, source: string, fileName?: string): Promise<DictAsset> {
|
|
159
|
+
async #write(stem: string, source: string, fileName?: string, measured = false): Promise<DictAsset> {
|
|
144
160
|
const name = fileName ?? `${stem}-${Bun.hash(source).toString(36)}.js`;
|
|
145
161
|
const relPath = `dict/${name}`;
|
|
146
|
-
await
|
|
147
|
-
|
|
162
|
+
const [bytes] = await Promise.all([
|
|
163
|
+
measured ? dictionaryServedBytesOf(source) : undefined,
|
|
164
|
+
Bun.write(path.join(this.#absArtifactDir, relPath), source),
|
|
165
|
+
]);
|
|
166
|
+
return { url: `${DictionaryAssetBuilder.urlPrefix}/${name}`, relPath, ...(bytes === undefined ? {} : { bytes }) };
|
|
148
167
|
}
|
|
149
168
|
|
|
150
169
|
//? An endpoint's own label stays with the page: apps show `l("<model>.signal.<endpoint>")` as a button's text.
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
export interface DictionaryOwnNeed {
|
|
2
|
+
routeId: string;
|
|
3
|
+
groups: string[];
|
|
4
|
+
//? What the route may still download of texts it does not show, after the shared files it keeps.
|
|
5
|
+
left: number;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
interface OwnCluster {
|
|
9
|
+
groups: Set<string>;
|
|
10
|
+
bytes: number;
|
|
11
|
+
members: { routeId: string; left: number }[];
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
//? Two own files become one where that adds their routes fewer bytes than the files share, so neighbouring pages reuse it.
|
|
15
|
+
export class DictionaryOwnParts {
|
|
16
|
+
static share(
|
|
17
|
+
needs: readonly DictionaryOwnNeed[],
|
|
18
|
+
bytesOf: (group: string) => number,
|
|
19
|
+
): { parts: string[][]; partOf: Map<string, number> } {
|
|
20
|
+
const byKey = new Map<string, OwnCluster>();
|
|
21
|
+
for (const { routeId, groups, left } of needs) {
|
|
22
|
+
const key = groups.join("\n");
|
|
23
|
+
const cluster = byKey.get(key) ?? {
|
|
24
|
+
groups: new Set(groups),
|
|
25
|
+
bytes: groups.reduce((sum, group) => sum + bytesOf(group), 0),
|
|
26
|
+
members: [],
|
|
27
|
+
};
|
|
28
|
+
cluster.members.push({ routeId, left });
|
|
29
|
+
byKey.set(key, cluster);
|
|
30
|
+
}
|
|
31
|
+
const clusters = [...byKey.values()];
|
|
32
|
+
const shared = clusters.map((a) => clusters.map((b) => DictionaryOwnParts.#sharedBytes(a, b, bytesOf)));
|
|
33
|
+
for (;;) {
|
|
34
|
+
const pair = DictionaryOwnParts.#bestPair(clusters, shared);
|
|
35
|
+
if (!pair) break;
|
|
36
|
+
DictionaryOwnParts.#merge(clusters, shared, pair, bytesOf);
|
|
37
|
+
}
|
|
38
|
+
const live = clusters.filter(({ members }) => members.length);
|
|
39
|
+
const parts = live.map(({ groups }) => [...groups].sort());
|
|
40
|
+
const partOf = new Map(live.flatMap(({ members }, idx) => members.map(({ routeId }) => [routeId, idx] as const)));
|
|
41
|
+
return { parts, partOf };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
static #bestPair(clusters: OwnCluster[], shared: number[][]): { p: number; q: number } | null {
|
|
45
|
+
let best: { p: number; q: number; saved: number } | null = null;
|
|
46
|
+
for (let p = 0; p < clusters.length; p++)
|
|
47
|
+
for (let q = p + 1; q < clusters.length; q++) {
|
|
48
|
+
const [a, b] = [clusters[p] as OwnCluster, clusters[q] as OwnCluster];
|
|
49
|
+
if (!a.members.length || !b.members.length) continue;
|
|
50
|
+
const both = shared[p]?.[q] ?? 0;
|
|
51
|
+
const [toA, toB] = [b.bytes - both, a.bytes - both];
|
|
52
|
+
if (a.members.some(({ left }) => left < toA) || b.members.some(({ left }) => left < toB)) continue;
|
|
53
|
+
if (toA * a.members.length + toB * b.members.length >= both) continue;
|
|
54
|
+
if (!best || both > best.saved) best = { p, q, saved: both };
|
|
55
|
+
}
|
|
56
|
+
return best;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
static #merge(
|
|
60
|
+
clusters: OwnCluster[],
|
|
61
|
+
shared: number[][],
|
|
62
|
+
{ p, q }: { p: number; q: number },
|
|
63
|
+
bytesOf: (group: string) => number,
|
|
64
|
+
) {
|
|
65
|
+
const [a, b] = [clusters[p] as OwnCluster, clusters[q] as OwnCluster];
|
|
66
|
+
const both = shared[p]?.[q] ?? 0;
|
|
67
|
+
const [toA, toB] = [b.bytes - both, a.bytes - both];
|
|
68
|
+
for (const member of a.members) member.left -= toA;
|
|
69
|
+
for (const member of b.members) member.left -= toB;
|
|
70
|
+
for (const group of b.groups) a.groups.add(group);
|
|
71
|
+
a.bytes += toA;
|
|
72
|
+
a.members.push(...b.members);
|
|
73
|
+
b.members = [];
|
|
74
|
+
b.groups = new Set();
|
|
75
|
+
b.bytes = 0;
|
|
76
|
+
clusters.forEach((other, idx) => {
|
|
77
|
+
const bytes = DictionaryOwnParts.#sharedBytes(a, other, bytesOf);
|
|
78
|
+
(shared[p] as number[])[idx] = bytes;
|
|
79
|
+
(shared[idx] as number[])[p] = bytes;
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
static #sharedBytes(a: OwnCluster, b: OwnCluster, bytesOf: (group: string) => number): number {
|
|
84
|
+
let bytes = 0;
|
|
85
|
+
for (const group of a.groups) if (b.groups.has(group)) bytes += bytesOf(group);
|
|
86
|
+
return bytes;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
interface PairCost {
|
|
2
|
+
p: number;
|
|
3
|
+
q: number;
|
|
4
|
+
cost: number;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export class DictionaryPackState {
|
|
8
|
+
readonly #routeCount: number;
|
|
9
|
+
readonly #words: number;
|
|
10
|
+
readonly #groups: string[][];
|
|
11
|
+
readonly #bytes: number[];
|
|
12
|
+
readonly #routes: Uint32Array[];
|
|
13
|
+
readonly #alive: boolean[];
|
|
14
|
+
readonly #overfetch: Float64Array;
|
|
15
|
+
readonly #budget: number;
|
|
16
|
+
//? |routes of p ∩ routes of q|, so a merge's cost needs no pass over the routes.
|
|
17
|
+
readonly #shared: Int32Array;
|
|
18
|
+
|
|
19
|
+
constructor(
|
|
20
|
+
routeCount: number,
|
|
21
|
+
parts: readonly (readonly [groups: string[], routes: number[]])[],
|
|
22
|
+
bytesOf: (group: string) => number,
|
|
23
|
+
budget: number,
|
|
24
|
+
) {
|
|
25
|
+
this.#routeCount = routeCount;
|
|
26
|
+
this.#words = Math.ceil(routeCount / 32);
|
|
27
|
+
this.#groups = parts.map(([groups]) => [...groups]);
|
|
28
|
+
this.#bytes = parts.map(([groups]) => groups.reduce((sum, group) => sum + bytesOf(group), 0));
|
|
29
|
+
this.#routes = parts.map(([, routes]) => {
|
|
30
|
+
const bits = new Uint32Array(this.#words);
|
|
31
|
+
for (const route of routes) bits[route >>> 5] = (bits[route >>> 5] ?? 0) | (1 << (route & 31));
|
|
32
|
+
return bits;
|
|
33
|
+
});
|
|
34
|
+
this.#alive = parts.map(() => true);
|
|
35
|
+
this.#overfetch = new Float64Array(routeCount);
|
|
36
|
+
this.#budget = budget;
|
|
37
|
+
this.#shared = new Int32Array(parts.length * parts.length);
|
|
38
|
+
for (let p = 0; p < parts.length; p++) this.#countRow(p);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
parts(): string[][] {
|
|
42
|
+
return this.#groups.filter((_, p) => this.#alive[p]);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
//? Only a pair whose merge pays for itself, the cheapest first, passing over one that puts a route over its budget.
|
|
46
|
+
mergeCheapest(requestBytes: number): boolean {
|
|
47
|
+
const alive = this.#groups.flatMap((_, p) => (this.#alive[p] ? [p] : []));
|
|
48
|
+
const pairs: PairCost[] = [];
|
|
49
|
+
let best: PairCost | null = null;
|
|
50
|
+
for (let x = 0; x < alive.length; x++)
|
|
51
|
+
for (let y = x + 1; y < alive.length; y++) {
|
|
52
|
+
const [p, q] = [alive[x] as number, alive[y] as number];
|
|
53
|
+
const both = this.#count(p, q);
|
|
54
|
+
const cost =
|
|
55
|
+
(this.#bytes[q] ?? 0) * (this.#count(p, p) - both) +
|
|
56
|
+
(this.#bytes[p] ?? 0) * (this.#count(q, q) - both) -
|
|
57
|
+
requestBytes * both;
|
|
58
|
+
if (cost >= 0) continue;
|
|
59
|
+
const pair = { p, q, cost };
|
|
60
|
+
pairs.push(pair);
|
|
61
|
+
if (!best || cost < best.cost) best = pair;
|
|
62
|
+
}
|
|
63
|
+
if (best && this.#fits(best)) return this.#merge(best);
|
|
64
|
+
pairs.sort((a, b) => a.cost - b.cost);
|
|
65
|
+
const fitting = pairs.find((pair) => pair !== best && this.#fits(pair));
|
|
66
|
+
return fitting ? this.#merge(fitting) : false;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
#fits({ p, q }: PairCost): boolean {
|
|
70
|
+
const [rp, rq] = [this.#routes[p] as Uint32Array, this.#routes[q] as Uint32Array];
|
|
71
|
+
const [bp, bq] = [this.#bytes[p] ?? 0, this.#bytes[q] ?? 0];
|
|
72
|
+
for (let word = 0; word < this.#words; word++) {
|
|
73
|
+
const [onlyP, onlyQ] = [(rp[word] ?? 0) & ~(rq[word] ?? 0), (rq[word] ?? 0) & ~(rp[word] ?? 0)];
|
|
74
|
+
if (!this.#within(word, onlyP, bq) || !this.#within(word, onlyQ, bp)) return false;
|
|
75
|
+
}
|
|
76
|
+
return true;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
#within(word: number, bits: number, added: number): boolean {
|
|
80
|
+
for (let set = bits >>> 0; set; set = (set & (set - 1)) >>> 0)
|
|
81
|
+
if ((this.#overfetch[word * 32 + 31 - Math.clz32(set & -set)] ?? 0) + added > this.#budget) return false;
|
|
82
|
+
return true;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
#merge({ p, q }: PairCost): true {
|
|
86
|
+
const [rp, rq] = [this.#routes[p] as Uint32Array, this.#routes[q] as Uint32Array];
|
|
87
|
+
const [bp, bq] = [this.#bytes[p] ?? 0, this.#bytes[q] ?? 0];
|
|
88
|
+
for (let word = 0; word < this.#words; word++) {
|
|
89
|
+
this.#add(word, (rp[word] ?? 0) & ~(rq[word] ?? 0), bq);
|
|
90
|
+
this.#add(word, (rq[word] ?? 0) & ~(rp[word] ?? 0), bp);
|
|
91
|
+
rp[word] = (rp[word] ?? 0) | (rq[word] ?? 0);
|
|
92
|
+
}
|
|
93
|
+
this.#groups[p] = [...(this.#groups[p] ?? []), ...(this.#groups[q] ?? [])].sort();
|
|
94
|
+
this.#bytes[p] = bp + bq;
|
|
95
|
+
this.#alive[q] = false;
|
|
96
|
+
this.#countRow(p);
|
|
97
|
+
return true;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
#add(word: number, bits: number, added: number) {
|
|
101
|
+
for (let set = bits >>> 0; set; set = (set & (set - 1)) >>> 0) {
|
|
102
|
+
const route = word * 32 + 31 - Math.clz32(set & -set);
|
|
103
|
+
if (route < this.#routeCount) this.#overfetch[route] = (this.#overfetch[route] ?? 0) + added;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
#countRow(p: number) {
|
|
108
|
+
const size = this.#groups.length;
|
|
109
|
+
const rp = this.#routes[p] as Uint32Array;
|
|
110
|
+
for (let q = 0; q < size; q++) {
|
|
111
|
+
if (!this.#alive[q]) continue;
|
|
112
|
+
const rq = this.#routes[q] as Uint32Array;
|
|
113
|
+
let count = 0;
|
|
114
|
+
for (let word = 0; word < this.#words; word++)
|
|
115
|
+
count += DictionaryPackState.#popcount((rp[word] ?? 0) & (rq[word] ?? 0));
|
|
116
|
+
this.#shared[p * size + q] = count;
|
|
117
|
+
this.#shared[q * size + p] = count;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
#count(p: number, q: number): number {
|
|
122
|
+
return this.#shared[p * this.#groups.length + q] ?? 0;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
static #popcount(value: number): number {
|
|
126
|
+
let v = value >>> 0;
|
|
127
|
+
v -= (v >>> 1) & 0x55555555;
|
|
128
|
+
v = (v & 0x33333333) + ((v >>> 2) & 0x33333333);
|
|
129
|
+
return (((v + (v >>> 4)) & 0x0f0f0f0f) * 0x01010101) >>> 24;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
@@ -19,8 +19,18 @@ const manyModules = () => {
|
|
|
19
19
|
return { groups: ["base", ...groups, "unshown"], routes, bytesOf: (group: string) => sizes.get(group) ?? 100 };
|
|
20
20
|
};
|
|
21
21
|
|
|
22
|
-
|
|
23
|
-
|
|
22
|
+
type Pack = ReturnType<typeof DictionaryPacking.pack>;
|
|
23
|
+
|
|
24
|
+
const filesOf = (routeId: string, { partsByRoute }: Pack) => partsByRoute[routeId] ?? [];
|
|
25
|
+
|
|
26
|
+
const heldOf = (routeId: string, pack: Pack) => {
|
|
27
|
+
const files = [...pack.parts, ...pack.ownParts];
|
|
28
|
+
return filesOf(routeId, pack).flatMap((idx) => files[idx] ?? []);
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
const overfetchOf = (routeId: string, pack: Pack, shown: readonly string[], bytesOf: (group: string) => number) =>
|
|
32
|
+
heldOf(routeId, pack).reduce((sum, group) => sum + bytesOf(group), 0) -
|
|
33
|
+
[...new Set(shown)].reduce((sum, group) => sum + bytesOf(group), 0);
|
|
24
34
|
|
|
25
35
|
describe("DictionaryPacking", () => {
|
|
26
36
|
test("loads every route's groups in at most four files, over a workspace of many modules", () => {
|
|
@@ -30,11 +40,63 @@ describe("DictionaryPacking", () => {
|
|
|
30
40
|
for (const [routeId, shown] of routes) {
|
|
31
41
|
const files = filesOf(routeId, pack);
|
|
32
42
|
expect(files.length).toBeLessThanOrEqual(DictionaryPacking.bound);
|
|
33
|
-
const held = new Set(
|
|
43
|
+
const held = new Set(heldOf(routeId, pack));
|
|
34
44
|
for (const group of shown) expect(held.has(group)).toBe(true);
|
|
35
45
|
}
|
|
36
46
|
});
|
|
37
47
|
|
|
48
|
+
test("no route downloads more than the over-fetch budget of texts it does not show", () => {
|
|
49
|
+
const { groups, routes, bytesOf } = manyModules();
|
|
50
|
+
const pack = DictionaryPacking.pack(routes, bytesOf, groups);
|
|
51
|
+
|
|
52
|
+
for (const [routeId, shown] of routes)
|
|
53
|
+
expect(overfetchOf(routeId, pack, shown, bytesOf)).toBeLessThanOrEqual(DictionaryPacking.overfetchBytes);
|
|
54
|
+
expect(pack.ownParts.length).toBeGreaterThan(0);
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
test("removing an unrelated route moves no other route's download by more than the over-fetch budget", () => {
|
|
58
|
+
const { groups, routes, bytesOf } = manyModules();
|
|
59
|
+
const before = DictionaryPacking.pack(routes, bytesOf, groups);
|
|
60
|
+
const downloadOf = (routeId: string, pack: Pack) =>
|
|
61
|
+
heldOf(routeId, pack).reduce((sum, group) => sum + bytesOf(group), 0);
|
|
62
|
+
for (const removed of ["/:lang/route3", "/:lang/route150", "/:lang/everything"]) {
|
|
63
|
+
const after = DictionaryPacking.pack(
|
|
64
|
+
new Map([...routes].filter(([routeId]) => routeId !== removed)),
|
|
65
|
+
bytesOf,
|
|
66
|
+
groups,
|
|
67
|
+
);
|
|
68
|
+
for (const routeId of routes.keys()) {
|
|
69
|
+
if (routeId === removed) continue;
|
|
70
|
+
const moved = Math.abs(downloadOf(routeId, after) - downloadOf(routeId, before));
|
|
71
|
+
expect(moved).toBeLessThanOrEqual(DictionaryPacking.overfetchBytes);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
test("a route past the bound takes the rest of its groups in one file, which a near-identical route shares", () => {
|
|
77
|
+
const modules = Array.from({ length: 6 }, (_, idx) => `module${idx}`);
|
|
78
|
+
const routes = new Map([
|
|
79
|
+
["/:lang/list", ["base", ...modules]],
|
|
80
|
+
["/:lang/detail", ["base", ...modules, "extra"]],
|
|
81
|
+
...modules.map((module) => [`/:lang/${module}`, [module]] as [string, string[]]),
|
|
82
|
+
]);
|
|
83
|
+
const bytesOf = () => 5000;
|
|
84
|
+
const groups = ["base", "extra", ...modules];
|
|
85
|
+
const pack = DictionaryPacking.pack(routes, bytesOf, groups);
|
|
86
|
+
const list = filesOf("/:lang/list", pack);
|
|
87
|
+
const detail = filesOf("/:lang/detail", pack);
|
|
88
|
+
|
|
89
|
+
expect(pack.ownParts.length).toBe(1);
|
|
90
|
+
expect(list.at(-1)).toBe(pack.parts.length);
|
|
91
|
+
expect(detail.at(-1)).toBe(pack.parts.length);
|
|
92
|
+
for (const [routeId, shown] of routes) {
|
|
93
|
+
expect(filesOf(routeId, pack).length).toBeLessThanOrEqual(DictionaryPacking.bound);
|
|
94
|
+
expect(new Set(heldOf(routeId, pack))).toEqual(new Set(shown));
|
|
95
|
+
expect(overfetchOf(routeId, pack, shown, bytesOf)).toBeLessThanOrEqual(DictionaryPacking.overfetchBytes);
|
|
96
|
+
}
|
|
97
|
+
for (const module of modules) expect(heldOf(`/:lang/${module}`, pack)).toEqual([module]);
|
|
98
|
+
});
|
|
99
|
+
|
|
38
100
|
test("puts each group in one file, and a group no route shows in the last, which no route loads", () => {
|
|
39
101
|
const { groups, routes, bytesOf } = manyModules();
|
|
40
102
|
const pack = DictionaryPacking.pack(routes, bytesOf, groups);
|
|
@@ -74,7 +136,7 @@ describe("DictionaryPacking", () => {
|
|
|
74
136
|
const servedOf = (bytesOf: (group: string) => number) => (held: readonly string[]) =>
|
|
75
137
|
fileOverhead + held.reduce((sum, group) => sum + bytesOf(group), 0);
|
|
76
138
|
|
|
77
|
-
test("a route whose files would not be smaller than the whole loads the whole file
|
|
139
|
+
test("a route whose files would not be smaller than the whole loads the whole file, the others their own texts", () => {
|
|
78
140
|
const modules = Array.from({ length: 8 }, (_, idx) => `module${idx}`);
|
|
79
141
|
const groups = ["base", ...modules];
|
|
80
142
|
const light = new Map(modules.map((module) => [`/:lang/${module}`, ["base", module]]));
|
|
@@ -85,13 +147,12 @@ describe("DictionaryPacking", () => {
|
|
|
85
147
|
|
|
86
148
|
expect(pack.wholeRoutes).toEqual(["/:lang/everything"]);
|
|
87
149
|
expect(pack.partsByRoute["/:lang/everything"]).toBeUndefined();
|
|
88
|
-
expect({ parts: pack.parts, partsByRoute: pack.partsByRoute }).toEqual(
|
|
150
|
+
expect({ parts: pack.parts, ownParts: pack.ownParts, partsByRoute: pack.partsByRoute }).toEqual(
|
|
89
151
|
DictionaryPacking.pack(light, bytesOf, groups),
|
|
90
152
|
);
|
|
91
153
|
for (const module of modules) {
|
|
92
|
-
|
|
93
|
-
expect(
|
|
94
|
-
expect(held(alone.partsByRoute[`/:lang/${module}`], alone.parts).length).toBeGreaterThan(2);
|
|
154
|
+
expect(heldOf(`/:lang/${module}`, pack).sort()).toEqual(["base", module]);
|
|
155
|
+
expect(heldOf(`/:lang/${module}`, alone).sort()).toEqual(["base", module]);
|
|
95
156
|
}
|
|
96
157
|
});
|
|
97
158
|
|
|
@@ -99,18 +160,22 @@ describe("DictionaryPacking", () => {
|
|
|
99
160
|
const { groups, routes, bytesOf } = manyModules();
|
|
100
161
|
const served = servedOf(bytesOf);
|
|
101
162
|
const whole = served(groups);
|
|
102
|
-
const costOf = ({ parts, partsByRoute }:
|
|
163
|
+
const costOf = ({ parts, ownParts, partsByRoute }: Pack) =>
|
|
103
164
|
[...routes.keys()].reduce((sum, routeId) => {
|
|
104
165
|
const files = partsByRoute[routeId];
|
|
105
|
-
const
|
|
166
|
+
const all = [...parts, ...ownParts];
|
|
167
|
+
const own = files?.reduce((bytes, idx) => bytes + served(all[idx] ?? []), 0) ?? whole;
|
|
106
168
|
return sum + Math.min(own, whole);
|
|
107
169
|
}, 0);
|
|
108
170
|
const pack = DictionaryPacking.packUnderWhole(routes, bytesOf, groups, served);
|
|
109
171
|
|
|
110
172
|
expect(pack.wholeRoutes).toContain("/:lang/everything");
|
|
111
173
|
expect(Object.keys(pack.partsByRoute).length).toBe(routes.size - pack.wholeRoutes.length);
|
|
112
|
-
|
|
113
|
-
|
|
174
|
+
const files = [...pack.parts, ...pack.ownParts];
|
|
175
|
+
for (const held of Object.values(pack.partsByRoute))
|
|
176
|
+
expect(held.reduce((sum, idx) => sum + served(files[idx] ?? []), 0)).toBeLessThan(whole);
|
|
177
|
+
for (const idx of pack.ownParts.keys())
|
|
178
|
+
expect(Object.values(pack.partsByRoute).some((held) => held.includes(pack.parts.length + idx))).toBe(true);
|
|
114
179
|
expect(costOf(pack)).toBeLessThanOrEqual(costOf(DictionaryPacking.pack(routes, bytesOf, groups)));
|
|
115
180
|
});
|
|
116
181
|
|
|
@@ -1,24 +1,40 @@
|
|
|
1
|
+
import { type DictionaryOwnNeed, DictionaryOwnParts } from "./dictionaryOwnParts";
|
|
2
|
+
import { DictionaryPackState } from "./dictionaryPackState";
|
|
3
|
+
|
|
1
4
|
export interface DictionaryPack {
|
|
2
5
|
//? Each file's groups. A group no route names sits in the last file, which only a translation miss asks for.
|
|
3
6
|
parts: string[][];
|
|
7
|
+
//? Files past `parts` in `partsByRoute`: each holds, for the routes naming it, the groups of their files past the bound.
|
|
8
|
+
ownParts: string[][];
|
|
4
9
|
partsByRoute: Record<string, number[]>;
|
|
5
10
|
}
|
|
6
11
|
|
|
12
|
+
export interface DictionaryPackOptions {
|
|
13
|
+
bound?: number;
|
|
14
|
+
requestBytes?: number;
|
|
15
|
+
overfetchBytes?: number;
|
|
16
|
+
}
|
|
17
|
+
|
|
7
18
|
//* Packs a page dictionary's groups into files so that a route loads at most `bound` of them. It starts from the
|
|
8
|
-
//* groups every route takes or leaves together
|
|
9
|
-
//*
|
|
10
|
-
//* needing the most files, merges the two whose merge adds the fewest bytes until every route is within the bound.
|
|
19
|
+
//* groups every route takes or leaves together and merges two files while the requests saved outweigh the bytes added,
|
|
20
|
+
//* never past a route's `overfetchBytes` of texts it does not show; a route past the bound takes the rest in its own file.
|
|
11
21
|
export class DictionaryPacking {
|
|
12
22
|
static readonly bound = 4;
|
|
13
23
|
//? What one more request costs a route in bytes of text: headers, a round trip's share, and the brotli window a
|
|
14
24
|
//? small file compresses without.
|
|
15
25
|
static readonly requestBytes = 1024;
|
|
26
|
+
//? About 2 KB brotli: what other routes showing other texts can add to a route's dictionary at most.
|
|
27
|
+
static readonly overfetchBytes = 8192;
|
|
16
28
|
|
|
17
29
|
static pack(
|
|
18
30
|
routes: ReadonlyMap<string, readonly string[]>,
|
|
19
31
|
bytesOf: (group: string) => number,
|
|
20
32
|
groups: readonly string[],
|
|
21
|
-
{
|
|
33
|
+
{
|
|
34
|
+
bound = DictionaryPacking.bound,
|
|
35
|
+
requestBytes = DictionaryPacking.requestBytes,
|
|
36
|
+
overfetchBytes = DictionaryPacking.overfetchBytes,
|
|
37
|
+
}: DictionaryPackOptions = {},
|
|
22
38
|
): DictionaryPack {
|
|
23
39
|
const known = new Set(groups);
|
|
24
40
|
const routeIds = [...routes.keys()].sort();
|
|
@@ -28,24 +44,63 @@ export class DictionaryPacking {
|
|
|
28
44
|
const signature = needs.flatMap((need, idx) => (need.includes(group) ? [idx] : [])).join(",");
|
|
29
45
|
if (signature) bySignature.set(signature, [...(bySignature.get(signature) ?? []), group]);
|
|
30
46
|
}
|
|
31
|
-
const
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
worst = DictionaryPacking.#widest(parts, needs, bound);
|
|
36
|
-
}
|
|
37
|
-
parts.sort((a, b) => ((a[0] ?? "") < (b[0] ?? "") ? -1 : 1));
|
|
47
|
+
const signed = [...bySignature].map(([signature, held]) => [held, signature.split(",").map(Number)] as const);
|
|
48
|
+
const state = new DictionaryPackState(routeIds.length, signed, bytesOf, overfetchBytes);
|
|
49
|
+
while (state.mergeCheapest(requestBytes));
|
|
50
|
+
const parts = state.parts().sort((a, b) => ((a[0] ?? "") < (b[0] ?? "") ? -1 : 1));
|
|
38
51
|
const used = new Set(parts.flat());
|
|
39
52
|
const rest = [...known].filter((group) => !used.has(group)).sort((a, b) => (a < b ? -1 : 1));
|
|
40
53
|
if (rest.length) parts.push(rest);
|
|
41
54
|
const partOf = new Map(parts.flatMap((part, idx) => part.map((group) => [group, idx] as const)));
|
|
55
|
+
const filesByRoute = new Map<string, number[]>();
|
|
56
|
+
const ownNeeds: DictionaryOwnNeed[] = [];
|
|
57
|
+
for (const [idx, routeId] of routeIds.entries()) {
|
|
58
|
+
const need = needs[idx] ?? [];
|
|
59
|
+
const files = [...new Set(need.map((group) => partOf.get(group) as number))].sort((a, b) => a - b);
|
|
60
|
+
if (files.length <= Math.max(1, bound)) {
|
|
61
|
+
filesByRoute.set(routeId, files);
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
const { kept, own, overfetch } = DictionaryPacking.#keepWithin(files, parts, new Set(need), bytesOf, bound);
|
|
65
|
+
filesByRoute.set(routeId, kept);
|
|
66
|
+
ownNeeds.push({ routeId, groups: own, left: overfetchBytes - overfetch });
|
|
67
|
+
}
|
|
68
|
+
const own = DictionaryOwnParts.share(ownNeeds, bytesOf);
|
|
42
69
|
const partsByRoute = Object.fromEntries(
|
|
43
|
-
routeIds.map((routeId
|
|
44
|
-
routeId
|
|
45
|
-
|
|
46
|
-
|
|
70
|
+
routeIds.map((routeId) => {
|
|
71
|
+
const files = filesByRoute.get(routeId) ?? [];
|
|
72
|
+
const ownIdx = own.partOf.get(routeId);
|
|
73
|
+
return [routeId, ownIdx === undefined ? files : [...files, parts.length + ownIdx]];
|
|
74
|
+
}),
|
|
47
75
|
);
|
|
48
|
-
return { parts, partsByRoute };
|
|
76
|
+
return { parts, ownParts: own.parts, partsByRoute };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
static #keepWithin(
|
|
80
|
+
files: number[],
|
|
81
|
+
parts: string[][],
|
|
82
|
+
need: Set<string>,
|
|
83
|
+
bytesOf: (group: string) => number,
|
|
84
|
+
bound: number,
|
|
85
|
+
): { kept: number[]; own: string[]; overfetch: number } {
|
|
86
|
+
const scored = files.map((idx) => ({
|
|
87
|
+
idx,
|
|
88
|
+
score: (parts[idx] ?? []).reduce((sum, group) => sum + (need.has(group) ? 1 : -1) * bytesOf(group), 0),
|
|
89
|
+
}));
|
|
90
|
+
scored.sort((a, b) => b.score - a.score || a.idx - b.idx);
|
|
91
|
+
const kept = scored
|
|
92
|
+
.slice(0, Math.max(1, bound) - 1)
|
|
93
|
+
.filter(({ score }) => score > 0)
|
|
94
|
+
.map(({ idx }) => idx);
|
|
95
|
+
const keptSet = new Set(kept);
|
|
96
|
+
const own = files
|
|
97
|
+
.filter((idx) => !keptSet.has(idx))
|
|
98
|
+
.flatMap((idx) => (parts[idx] ?? []).filter((group) => need.has(group)))
|
|
99
|
+
.sort();
|
|
100
|
+
const overfetch = kept
|
|
101
|
+
.flatMap((idx) => (parts[idx] ?? []).filter((group) => !need.has(group)))
|
|
102
|
+
.reduce((sum, group) => sum + bytesOf(group), 0);
|
|
103
|
+
return { kept: kept.sort((a, b) => a - b), own, overfetch };
|
|
49
104
|
}
|
|
50
105
|
|
|
51
106
|
//? Several files compress worse than one, so a route showing nearly every text is cheaper on the whole dictionary.
|
|
@@ -54,7 +109,7 @@ export class DictionaryPacking {
|
|
|
54
109
|
bytesOf: (group: string) => number,
|
|
55
110
|
groups: readonly string[],
|
|
56
111
|
servedBytesOf: (groups: readonly string[]) => number,
|
|
57
|
-
options:
|
|
112
|
+
options: DictionaryPackOptions = {},
|
|
58
113
|
): DictionaryPack & { wholeRoutes: string[] } {
|
|
59
114
|
const whole = servedBytesOf([...new Set(groups)].sort());
|
|
60
115
|
const served = new Map<string, number>();
|
|
@@ -70,9 +125,10 @@ export class DictionaryPacking {
|
|
|
70
125
|
let best: { pack: DictionaryPack; over: string[]; cost: number } | null = null;
|
|
71
126
|
for (;;) {
|
|
72
127
|
const pack = DictionaryPacking.pack(partial, bytesOf, groups, options);
|
|
73
|
-
const
|
|
128
|
+
const files = [...pack.parts, ...pack.ownParts];
|
|
129
|
+
const costs = Object.entries(pack.partsByRoute).map(([routeId, held]) => ({
|
|
74
130
|
routeId,
|
|
75
|
-
cost:
|
|
131
|
+
cost: held.reduce((sum, idx) => sum + servedOf(files[idx] ?? []), 0),
|
|
76
132
|
}));
|
|
77
133
|
const over = costs.filter(({ cost }) => cost >= whole).map(({ routeId }) => routeId);
|
|
78
134
|
const cost =
|
|
@@ -84,52 +140,21 @@ export class DictionaryPacking {
|
|
|
84
140
|
for (const routeId of over.slice(0, Math.ceil(over.length / 2))) partial.delete(routeId);
|
|
85
141
|
}
|
|
86
142
|
const dropped = new Set(best.over);
|
|
143
|
+
const kept = Object.entries(best.pack.partsByRoute).filter(([routeId]) => !dropped.has(routeId));
|
|
144
|
+
const { parts, ownParts } = best.pack;
|
|
145
|
+
const ownUsed = [...new Set(kept.flatMap(([, held]) => held.filter((idx) => idx >= parts.length)))].sort(
|
|
146
|
+
(a, b) => a - b,
|
|
147
|
+
);
|
|
148
|
+
const ownMoved = new Map(ownUsed.map((idx, at) => [idx, parts.length + at]));
|
|
87
149
|
const partsByRoute = Object.fromEntries(
|
|
88
|
-
|
|
150
|
+
kept.map(([routeId, held]) => [routeId, held.map((idx) => ownMoved.get(idx) ?? idx)]),
|
|
89
151
|
);
|
|
90
152
|
const wholeRoutes = [...routes.keys()].sort().filter((routeId) => !Object.hasOwn(partsByRoute, routeId));
|
|
91
|
-
return {
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
static #widest(parts: string[][], needs: string[][], bound: number): Set<number> | null {
|
|
100
|
-
let worst: Set<number> | null = null;
|
|
101
|
-
for (const set of DictionaryPacking.#setsOf(parts, needs))
|
|
102
|
-
if (set.size > Math.max(1, bound) && (!worst || set.size > worst.size)) worst = set;
|
|
103
|
-
return worst;
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
//? `within` set: any pair of its files merges, the cheapest first; otherwise only a pair whose merge pays for itself.
|
|
107
|
-
static #mergeCheapest(
|
|
108
|
-
parts: string[][],
|
|
109
|
-
needs: string[][],
|
|
110
|
-
bytesOf: (group: string) => number,
|
|
111
|
-
requestBytes: number,
|
|
112
|
-
within: Set<number> | null,
|
|
113
|
-
): boolean {
|
|
114
|
-
const sets = DictionaryPacking.#setsOf(parts, needs);
|
|
115
|
-
const bytes = parts.map((part) => part.reduce((sum, group) => sum + bytesOf(group), 0));
|
|
116
|
-
const candidates = within ? [...within].sort((a, b) => a - b) : parts.map((_, idx) => idx);
|
|
117
|
-
let best: { p: number; q: number; cost: number } | null = null;
|
|
118
|
-
for (let x = 0; x < candidates.length; x++)
|
|
119
|
-
for (let y = x + 1; y < candidates.length; y++) {
|
|
120
|
-
const [p, q] = [candidates[x] as number, candidates[y] as number];
|
|
121
|
-
let cost = 0;
|
|
122
|
-
for (const set of sets) {
|
|
123
|
-
const [hasP, hasQ] = [set.has(p), set.has(q)];
|
|
124
|
-
if (hasP && hasQ) cost -= requestBytes;
|
|
125
|
-
else if (hasP) cost += bytes[q] ?? 0;
|
|
126
|
-
else if (hasQ) cost += bytes[p] ?? 0;
|
|
127
|
-
}
|
|
128
|
-
if (!best || cost < best.cost) best = { p, q, cost };
|
|
129
|
-
}
|
|
130
|
-
if (!best || (!within && best.cost >= 0)) return false;
|
|
131
|
-
parts[best.p] = [...(parts[best.p] ?? []), ...(parts[best.q] ?? [])].sort();
|
|
132
|
-
parts.splice(best.q, 1);
|
|
133
|
-
return true;
|
|
153
|
+
return {
|
|
154
|
+
parts,
|
|
155
|
+
ownParts: ownUsed.map((idx) => ownParts[idx - parts.length] ?? []),
|
|
156
|
+
partsByRoute,
|
|
157
|
+
wholeRoutes,
|
|
158
|
+
};
|
|
134
159
|
}
|
|
135
160
|
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import fs from "node:fs";
|
|
2
2
|
import path from "node:path";
|
|
3
|
+
import { promisify } from "node:util";
|
|
3
4
|
import zlib from "node:zlib";
|
|
4
5
|
import type { App } from "../commandDecorators";
|
|
5
6
|
import { FontPruner } from "./fontPruner";
|
|
@@ -96,6 +97,17 @@ export function dictionaryBrotliBytesOf(source: string): number {
|
|
|
96
97
|
return brotliCompress(buffer, ROOT_BROTLI_QUALITY.dict ?? MAX_BROTLI_QUALITY).byteLength;
|
|
97
98
|
}
|
|
98
99
|
|
|
100
|
+
//? What a browser downloads of a `dict/` file once this phase has run: its `.br`, or the file when that is no smaller.
|
|
101
|
+
export async function dictionaryServedBytesOf(source: string): Promise<number> {
|
|
102
|
+
const bytes = new TextEncoder().encode(source);
|
|
103
|
+
const params = {
|
|
104
|
+
[zlib.constants.BROTLI_PARAM_QUALITY]: ROOT_BROTLI_QUALITY.dict ?? MAX_BROTLI_QUALITY,
|
|
105
|
+
[zlib.constants.BROTLI_PARAM_SIZE_HINT]: bytes.byteLength,
|
|
106
|
+
};
|
|
107
|
+
const encoded = await promisify(zlib.brotliCompress)(bytes, { params });
|
|
108
|
+
return Math.min(bytes.byteLength, encoded.byteLength);
|
|
109
|
+
}
|
|
110
|
+
|
|
99
111
|
function brotliCompress(buffer: ArrayBuffer, quality: number): Buffer {
|
|
100
112
|
return zlib.brotliCompressSync(buffer, {
|
|
101
113
|
params: {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@akanjs/devkit",
|
|
3
|
-
"version": "3.3.0-rc.
|
|
3
|
+
"version": "3.3.0-rc.60",
|
|
4
4
|
"sourceType": "module",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"publishConfig": {
|
|
@@ -50,7 +50,7 @@
|
|
|
50
50
|
"./workspace/getRelatedCnsts": "./workspace/getRelatedCnsts.ts"
|
|
51
51
|
},
|
|
52
52
|
"dependencies": {
|
|
53
|
-
"@akanjs/language": "3.3.0-rc.
|
|
53
|
+
"@akanjs/language": "3.3.0-rc.60",
|
|
54
54
|
"@earendil-works/pi-agent-core": "1.5.2",
|
|
55
55
|
"@earendil-works/pi-ai": "1.5.2",
|
|
56
56
|
"@earendil-works/pi-codemode": "1.5.2",
|
|
@@ -59,7 +59,7 @@
|
|
|
59
59
|
"@earendil-works/pi-tui": "1.5.2",
|
|
60
60
|
"@inquirer/prompts": "^8.7.3",
|
|
61
61
|
"@tailwindcss/node": "^4.3.3",
|
|
62
|
-
"akanjs": "3.3.0-rc.
|
|
62
|
+
"akanjs": "3.3.0-rc.60",
|
|
63
63
|
"chalk": "^6.0.1",
|
|
64
64
|
"commander": "^15.0.0",
|
|
65
65
|
"dayjs": "^1.11.23",
|
|
@@ -68,7 +68,6 @@
|
|
|
68
68
|
"ignore": "^7.0.12",
|
|
69
69
|
"ora": "^9.4.1",
|
|
70
70
|
"react-server-dom-webpack": "^19.3.1",
|
|
71
|
-
"ssh2": "^1.17.0",
|
|
72
71
|
"subset-font": "^2.9.0",
|
|
73
72
|
"tailwind-scrollbar": "^4.0.2",
|
|
74
73
|
"tailwindcss": "^4.3.3",
|
|
@@ -76,11 +75,15 @@
|
|
|
76
75
|
"typescript": "^6.0.3"
|
|
77
76
|
},
|
|
78
77
|
"peerDependencies": {
|
|
79
|
-
"react": "19.3.1"
|
|
78
|
+
"react": "19.3.1",
|
|
79
|
+
"ssh2": "^1.17.0"
|
|
80
80
|
},
|
|
81
81
|
"peerDependenciesMeta": {
|
|
82
82
|
"react": {
|
|
83
83
|
"optional": true
|
|
84
|
+
},
|
|
85
|
+
"ssh2": {
|
|
86
|
+
"optional": true
|
|
84
87
|
}
|
|
85
88
|
},
|
|
86
89
|
"devDependencies": {},
|
package/tunnel/createTunnel.ts
CHANGED
|
@@ -2,6 +2,7 @@ import { readFileSync } from "node:fs";
|
|
|
2
2
|
import type { ConnectConfig } from "ssh2";
|
|
3
3
|
import { type AppExecutor, WorkspaceExecutor } from "../executors";
|
|
4
4
|
import { ShellOnlyEnv } from "../util/shellOnlyEnv";
|
|
5
|
+
import { loadSsh2 } from "./ssh2Module";
|
|
5
6
|
import { SshHostKeys } from "./sshHostKeys";
|
|
6
7
|
import { createSshTunnel } from "./sshTunnel";
|
|
7
8
|
|
|
@@ -81,7 +82,9 @@ export const createTunnel = async (
|
|
|
81
82
|
const baseDevEnv = WorkspaceExecutor.getBaseDevEnv();
|
|
82
83
|
WorkspaceExecutor.assertDeployableEnv(baseDevEnv, environment, `The ${service} tunnel`);
|
|
83
84
|
for (const line of tunnelEnv.ignored()) app.logger.warn(line);
|
|
84
|
-
const
|
|
85
|
+
const purpose = `The ${service} tunnel for ${app.name}-${environment}`;
|
|
86
|
+
const ssh2 = await loadSsh2(purpose, app.workspace.workspaceRoot);
|
|
87
|
+
const auth = tunnelAuth(purpose);
|
|
85
88
|
const { serveDomain } = baseDevEnv;
|
|
86
89
|
const host = `${app.name}-${environment}.${serveDomain}`;
|
|
87
90
|
//? RFC 6761 makes *.localhost loopback, but only macOS resolves it; glibc without systemd-resolved and Windows answer ENOTFOUND
|
|
@@ -104,6 +107,7 @@ export const createTunnel = async (
|
|
|
104
107
|
srcPort: port,
|
|
105
108
|
dstHost,
|
|
106
109
|
dstPort,
|
|
110
|
+
ssh2,
|
|
107
111
|
sshOptions: {
|
|
108
112
|
host: sshHost,
|
|
109
113
|
port: sshPort,
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test";
|
|
2
|
+
import { mkdir, writeFile } from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { tempDirs } from "../test/testHelpers";
|
|
5
|
+
import { loadSsh2, ssh2InstallCommand } from "./ssh2Module";
|
|
6
|
+
|
|
7
|
+
const makeTempRoot = tempDirs("akan-ssh2-module-");
|
|
8
|
+
|
|
9
|
+
//? Bun resolves a bare specifier from its global cache when no node_modules sits above the importer, so each root has one.
|
|
10
|
+
const workspaceWithout = async (lockfile: string) => {
|
|
11
|
+
const root = await makeTempRoot();
|
|
12
|
+
await mkdir(path.join(root, "node_modules"));
|
|
13
|
+
await writeFile(path.join(root, "package.json"), JSON.stringify({ name: "ws", private: true }));
|
|
14
|
+
await writeFile(path.join(root, lockfile), "");
|
|
15
|
+
return root;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
describe("loadSsh2", () => {
|
|
19
|
+
test("names the bun install command when a Bun workspace lacks ssh2", async () => {
|
|
20
|
+
const root = await workspaceWithout("bun.lock");
|
|
21
|
+
await expect(loadSsh2("The redis tunnel for demo-debug", root, [root])).rejects.toThrow(
|
|
22
|
+
`The redis tunnel for demo-debug needs the ssh2 package, which an Akan workspace installs only to open a tunnel: run \`bun add -d ssh2\` in ${root}, then try again.`,
|
|
23
|
+
);
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
test("names the npm install command when only an npm lockfile is present", async () => {
|
|
27
|
+
const root = await workspaceWithout("package-lock.json");
|
|
28
|
+
expect(ssh2InstallCommand(root)).toBe("npm install -D ssh2");
|
|
29
|
+
await expect(loadSsh2("The postgres tunnel", root, [root])).rejects.toThrow("run `npm install -D ssh2`");
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
test("loads ssh2 from a later directory when an earlier one lacks it", async () => {
|
|
33
|
+
const root = await workspaceWithout("bun.lock");
|
|
34
|
+
const ssh2 = await loadSsh2("The redis tunnel", root, [root, import.meta.dir]);
|
|
35
|
+
expect(typeof ssh2.Client).toBe("function");
|
|
36
|
+
});
|
|
37
|
+
});
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
|
|
4
|
+
export type Ssh2 = typeof import("ssh2");
|
|
5
|
+
|
|
6
|
+
const resolveFrom = (dir: string) => {
|
|
7
|
+
try {
|
|
8
|
+
return Bun.resolveSync("ssh2", dir);
|
|
9
|
+
} catch {
|
|
10
|
+
return null;
|
|
11
|
+
}
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
export const ssh2InstallCommand = (workspaceRoot: string) =>
|
|
15
|
+
existsSync(path.join(workspaceRoot, "package-lock.json")) && !existsSync(path.join(workspaceRoot, "bun.lock"))
|
|
16
|
+
? "npm install -D ssh2"
|
|
17
|
+
: "bun add -d ssh2";
|
|
18
|
+
|
|
19
|
+
//? A global akan resolves packages from its own install, so the workspace root is searched as well.
|
|
20
|
+
export const loadSsh2 = async (
|
|
21
|
+
purpose: string,
|
|
22
|
+
workspaceRoot: string,
|
|
23
|
+
searchDirs = [import.meta.dir, workspaceRoot],
|
|
24
|
+
): Promise<Ssh2> => {
|
|
25
|
+
for (const dir of searchDirs) {
|
|
26
|
+
const entry = resolveFrom(dir);
|
|
27
|
+
if (entry) return (await import(entry)) as Ssh2;
|
|
28
|
+
}
|
|
29
|
+
throw new Error(
|
|
30
|
+
`${purpose} needs the ssh2 package, which an Akan workspace installs only to open a tunnel: run \`${ssh2InstallCommand(workspaceRoot)}\` in ${workspaceRoot}, then try again.`,
|
|
31
|
+
);
|
|
32
|
+
};
|
package/tunnel/sshTunnel.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { Channel, Client, ConnectConfig } from "ssh2";
|
|
2
|
+
import type { Ssh2 } from "./ssh2Module";
|
|
2
3
|
|
|
3
4
|
export interface SshTunnelOptions {
|
|
4
5
|
localHost?: string;
|
|
@@ -8,6 +9,7 @@ export interface SshTunnelOptions {
|
|
|
8
9
|
dstHost: string;
|
|
9
10
|
dstPort: number;
|
|
10
11
|
sshOptions: ConnectConfig;
|
|
12
|
+
ssh2: Pick<Ssh2, "Client">;
|
|
11
13
|
}
|
|
12
14
|
|
|
13
15
|
export interface SshTunnel {
|
|
@@ -32,7 +34,7 @@ const closeQuietly = (close: () => void) => {
|
|
|
32
34
|
|
|
33
35
|
const createSshClient = async (options: SshTunnelOptions) =>
|
|
34
36
|
new Promise<Client>((resolve, reject) => {
|
|
35
|
-
const client = new Client();
|
|
37
|
+
const client = new options.ssh2.Client();
|
|
36
38
|
|
|
37
39
|
const cleanup = () => {
|
|
38
40
|
client.off("ready", onReady);
|