tonnage 0.1.2 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +2 -0
- package/CHANGELOG.md +12 -0
- package/README.md +109 -0
- package/README.mdx +143 -0
- package/dist/cli.mjs +25 -7
- package/dist/cli.mjs.map +1 -1
- package/dist/galley.d.mts +12 -0
- package/dist/galley.d.mts.map +1 -0
- package/dist/galley.mjs +12 -0
- package/dist/galley.mjs.map +1 -0
- package/dist/index.d.mts +11 -56
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +2 -1
- package/dist/index.mjs.map +1 -1
- package/dist/{run-CZ_FO4C7.mjs → report-B3HrJ4UQ.mjs} +85 -112
- package/dist/report-B3HrJ4UQ.mjs.map +1 -0
- package/dist/run-BJN1MXRf.mjs +44 -0
- package/dist/run-BJN1MXRf.mjs.map +1 -0
- package/dist/types-Ddtp95Z3.d.mts +49 -0
- package/dist/types-Ddtp95Z3.d.mts.map +1 -0
- package/package.json +33 -27
- package/src/cli.ts +15 -2
- package/src/command-line.ts +24 -6
- package/src/galley.ts +25 -0
- package/src/report-content.ts +122 -0
- package/src/report.ts +11 -111
- package/src/run.ts +1 -1
- package/dist/run-CZ_FO4C7.mjs.map +0 -1
|
@@ -1,30 +1,10 @@
|
|
|
1
1
|
import fs from "node:fs/promises";
|
|
2
2
|
import path from "node:path";
|
|
3
|
+
import { renderMarkdown } from "galley.md";
|
|
3
4
|
import { gzipSync } from "node:zlib";
|
|
4
5
|
import { build } from "esbuild";
|
|
5
6
|
import os from "node:os";
|
|
6
|
-
|
|
7
|
-
function tonnageMarkers(marker = `default`) {
|
|
8
|
-
validateMarker(marker);
|
|
9
|
-
return {
|
|
10
|
-
end: `<!-- tonnage:${marker}:end -->`,
|
|
11
|
-
start: `<!-- tonnage:${marker}:start -->`
|
|
12
|
-
};
|
|
13
|
-
}
|
|
14
|
-
function updateGeneratedSection(readme, markdown, marker) {
|
|
15
|
-
const { end, start } = tonnageMarkers(marker);
|
|
16
|
-
const startIndex = readme.indexOf(start);
|
|
17
|
-
const endIndex = readme.indexOf(end);
|
|
18
|
-
if (startIndex === -1 || endIndex === -1) throw new Error(`README must contain exactly one ${start} and one ${end} marker.`);
|
|
19
|
-
if (readme.slice(startIndex + start.length).includes(start) || readme.slice(endIndex + end.length).includes(end)) throw new Error(`README must contain exactly one ${start} and one ${end} marker.`);
|
|
20
|
-
if (endIndex < startIndex) throw new Error(`${end} must appear after ${start}.`);
|
|
21
|
-
const contentStart = startIndex + start.length;
|
|
22
|
-
return `${readme.slice(0, contentStart)}\n\n${markdown.trim()}\n\n${readme.slice(endIndex)}`;
|
|
23
|
-
}
|
|
24
|
-
function validateMarker(marker) {
|
|
25
|
-
if (!/^[a-z0-9][a-z0-9._-]*$/i.test(marker)) throw new Error(`Tonnage marker names may contain letters, numbers, dots, underscores, and hyphens.`);
|
|
26
|
-
}
|
|
27
|
-
//#endregion
|
|
7
|
+
import { jsx } from "galley.md/jsx-runtime";
|
|
28
8
|
//#region src/measure.ts
|
|
29
9
|
async function measureEntry(entry, options) {
|
|
30
10
|
return measureEntryWithPlugins(entry, options);
|
|
@@ -107,6 +87,80 @@ function escapeRegExp(value) {
|
|
|
107
87
|
return value.replace(/[.*+?^${}()|[\]\\]/g, `\\$&`);
|
|
108
88
|
}
|
|
109
89
|
//#endregion
|
|
90
|
+
//#region src/report-content.ts
|
|
91
|
+
/** Use Galley's JSX runtime directly so the source CLI stays executable by Node. */
|
|
92
|
+
function reportContent(report, config = {}) {
|
|
93
|
+
const hasExports = report.exports.length > 0;
|
|
94
|
+
const hasRecipes = report.recipes.length > 0;
|
|
95
|
+
const hasMultipleSections = hasExports && hasRecipes;
|
|
96
|
+
const content = [jsx("h2", { children: config.heading ?? "Bundle size" })];
|
|
97
|
+
if (hasExports) content.push(jsx("p", { children: "Package export sizes include complete runtime export surfaces." }));
|
|
98
|
+
if (hasRecipes) content.push(jsx("p", { children: "Usage example sizes bundle their entry files and tree-shake unused exports." }));
|
|
99
|
+
content.push(jsx("p", { children: "Sizes are exact minified and level-9 gzip JavaScript byte counts. Declarations, source maps, CSS, and other assets are excluded. Peer dependencies stay external, and shared modules are counted once per bundle." }));
|
|
100
|
+
if (hasExports) {
|
|
101
|
+
if (hasMultipleSections) content.push(jsx("h3", { children: "Package exports" }));
|
|
102
|
+
content.push(table([
|
|
103
|
+
{ title: "Import" },
|
|
104
|
+
{
|
|
105
|
+
title: "Minified JS",
|
|
106
|
+
align: "right"
|
|
107
|
+
},
|
|
108
|
+
{
|
|
109
|
+
title: "Gzip JS",
|
|
110
|
+
align: "right"
|
|
111
|
+
}
|
|
112
|
+
], report.exports.map((row) => [
|
|
113
|
+
code(row.name),
|
|
114
|
+
formatBytes(row.rawBytes),
|
|
115
|
+
formatBytes(row.gzipBytes)
|
|
116
|
+
])));
|
|
117
|
+
}
|
|
118
|
+
if (hasRecipes) {
|
|
119
|
+
if (hasMultipleSections) content.push(jsx("h3", { children: "Usage examples" }));
|
|
120
|
+
content.push(table([
|
|
121
|
+
{ title: "Recipe" },
|
|
122
|
+
{ title: "Entry" },
|
|
123
|
+
{
|
|
124
|
+
title: "Minified JS",
|
|
125
|
+
align: "right"
|
|
126
|
+
},
|
|
127
|
+
{
|
|
128
|
+
title: "Gzip JS",
|
|
129
|
+
align: "right"
|
|
130
|
+
}
|
|
131
|
+
], report.recipes.map((row) => [
|
|
132
|
+
row.name,
|
|
133
|
+
code(row.entry),
|
|
134
|
+
formatBytes(row.rawBytes),
|
|
135
|
+
formatBytes(row.gzipBytes)
|
|
136
|
+
])));
|
|
137
|
+
}
|
|
138
|
+
content.push(jsx("p", { children: [
|
|
139
|
+
"Report maintained with ",
|
|
140
|
+
jsx("a", {
|
|
141
|
+
href: "https://github.com/jeremybanka/tonnage",
|
|
142
|
+
children: "tonnage"
|
|
143
|
+
}),
|
|
144
|
+
"."
|
|
145
|
+
] }));
|
|
146
|
+
return content;
|
|
147
|
+
}
|
|
148
|
+
function code(value) {
|
|
149
|
+
return {
|
|
150
|
+
type: "inlineCode",
|
|
151
|
+
value
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
function formatBytes(bytes) {
|
|
155
|
+
return `${new Intl.NumberFormat("en-US").format(bytes)} B`;
|
|
156
|
+
}
|
|
157
|
+
function table(columns, rows) {
|
|
158
|
+
return jsx("table", { children: [jsx("thead", { children: jsx("tr", { children: columns.map(({ title, align }) => jsx("th", {
|
|
159
|
+
children: title,
|
|
160
|
+
align
|
|
161
|
+
})) }) }), jsx("tbody", { children: rows.map((cells) => jsx("tr", { children: cells.map((children) => jsx("td", { children })) })) })] });
|
|
162
|
+
}
|
|
163
|
+
//#endregion
|
|
110
164
|
//#region src/report.ts
|
|
111
165
|
async function createTonnageReport(config, configDirectory) {
|
|
112
166
|
const packageJsonPath = path.resolve(configDirectory, config.packageJson ?? `package.json`);
|
|
@@ -147,56 +201,13 @@ async function createTonnageReport(config, configDirectory) {
|
|
|
147
201
|
recipes: recipeRows
|
|
148
202
|
};
|
|
149
203
|
}
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
const
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
...methodologyLines({
|
|
158
|
-
hasExports,
|
|
159
|
-
hasRecipes
|
|
160
|
-
})
|
|
161
|
-
];
|
|
162
|
-
if (hasExports) lines.push(``, ...hasMultipleSections ? [`### Package exports`, ``] : [], ...markdownTable([
|
|
163
|
-
`Import`,
|
|
164
|
-
`Minified JS`,
|
|
165
|
-
`Gzip JS`
|
|
166
|
-
], report.exports.map((row) => [
|
|
167
|
-
code(row.name),
|
|
168
|
-
formatBytes(row.rawBytes),
|
|
169
|
-
formatBytes(row.gzipBytes)
|
|
170
|
-
]), [
|
|
171
|
-
`left`,
|
|
172
|
-
`right`,
|
|
173
|
-
`right`
|
|
174
|
-
]));
|
|
175
|
-
if (hasRecipes) lines.push(``, ...hasMultipleSections ? [`### Usage examples`, ``] : [], ...markdownTable([
|
|
176
|
-
`Recipe`,
|
|
177
|
-
`Entry`,
|
|
178
|
-
`Minified JS`,
|
|
179
|
-
`Gzip JS`
|
|
180
|
-
], report.recipes.map((row) => [
|
|
181
|
-
escapeCell(row.name),
|
|
182
|
-
code(row.entry),
|
|
183
|
-
formatBytes(row.rawBytes),
|
|
184
|
-
formatBytes(row.gzipBytes)
|
|
185
|
-
]), [
|
|
186
|
-
`left`,
|
|
187
|
-
`left`,
|
|
188
|
-
`right`,
|
|
189
|
-
`right`
|
|
190
|
-
]));
|
|
191
|
-
lines.push(``, `Report maintained with [tonnage](https://github.com/jeremybanka/tonnage).`);
|
|
192
|
-
return lines.join(`\n`);
|
|
193
|
-
}
|
|
194
|
-
function methodologyLines({ hasExports, hasRecipes }) {
|
|
195
|
-
const lines = [];
|
|
196
|
-
if (hasExports) lines.push(`Package export sizes include complete runtime export surfaces.`);
|
|
197
|
-
if (hasRecipes) lines.push(`Usage example sizes bundle their entry files and tree-shake unused exports.`);
|
|
198
|
-
lines.push(`Sizes are exact minified and level-9 gzip JavaScript byte counts. Declarations, source maps, CSS, and other assets are excluded. Peer dependencies stay external, and shared modules are counted once per bundle.`);
|
|
199
|
-
return lines;
|
|
204
|
+
/** Serialize a report with the same Galley elements used by the document component. */
|
|
205
|
+
async function renderTonnageMarkdown(report, config = {}) {
|
|
206
|
+
const directory = process.cwd();
|
|
207
|
+
return renderMarkdown(reportContent(report, config), {
|
|
208
|
+
directory,
|
|
209
|
+
path: path.resolve(directory, config.readme ?? "README.md")
|
|
210
|
+
});
|
|
200
211
|
}
|
|
201
212
|
function selectExportImports(packageName, exportsValue, selection) {
|
|
202
213
|
if (selection === false) return [];
|
|
@@ -217,48 +228,10 @@ function toPackageImport(packageName, exportKey) {
|
|
|
217
228
|
if (!exportKey.startsWith(`./`)) throw new Error(`Invalid package export key: ${exportKey}`);
|
|
218
229
|
return `${packageName}/${exportKey.slice(2)}`;
|
|
219
230
|
}
|
|
220
|
-
function formatBytes(bytes) {
|
|
221
|
-
return `${new Intl.NumberFormat(`en-US`).format(bytes)} B`;
|
|
222
|
-
}
|
|
223
|
-
function code(value) {
|
|
224
|
-
return `<code>${escapeCell(value)}</code>`;
|
|
225
|
-
}
|
|
226
|
-
function escapeCell(value) {
|
|
227
|
-
return value.replaceAll(`&`, `&`).replaceAll(`|`, `|`);
|
|
228
|
-
}
|
|
229
231
|
function unique(values) {
|
|
230
232
|
return [...new Set(values)];
|
|
231
233
|
}
|
|
232
|
-
function markdownTable(headings, rows, alignments) {
|
|
233
|
-
const widths = headings.map((heading, column) => Math.max(heading.length, ...rows.map((row) => row[column]?.length ?? 0), 3));
|
|
234
|
-
const renderRow = (cells) => `| ${cells.map((cell, column) => padCell(cell, widths[column] ?? 3, alignments[column] ?? `left`)).join(` | `)} |`;
|
|
235
|
-
const separator = widths.map((width, column) => alignments[column] === `right` ? `${`-`.repeat(width - 1)}:` : `-`.repeat(width));
|
|
236
|
-
return [
|
|
237
|
-
renderRow(headings),
|
|
238
|
-
renderRow(separator),
|
|
239
|
-
...rows.map(renderRow)
|
|
240
|
-
];
|
|
241
|
-
}
|
|
242
|
-
function padCell(cell, width, alignment) {
|
|
243
|
-
return alignment === `right` ? cell.padStart(width) : cell.padEnd(width);
|
|
244
|
-
}
|
|
245
|
-
//#endregion
|
|
246
|
-
//#region src/run.ts
|
|
247
|
-
async function runTonnage(config, options) {
|
|
248
|
-
const configDirectory = path.resolve(options.configDirectory ?? process.cwd());
|
|
249
|
-
const readmePath = path.resolve(configDirectory, config.readme ?? `README.md`);
|
|
250
|
-
const oldReadme = await fs.readFile(readmePath, `utf8`);
|
|
251
|
-
const report = await createTonnageReport(config, configDirectory);
|
|
252
|
-
const newReadme = updateGeneratedSection(oldReadme, renderTonnageMarkdown(report, config), config.marker);
|
|
253
|
-
const changed = oldReadme !== newReadme;
|
|
254
|
-
if (options.mode === `write` && changed) await fs.writeFile(readmePath, newReadme);
|
|
255
|
-
return {
|
|
256
|
-
changed,
|
|
257
|
-
readmePath,
|
|
258
|
-
report
|
|
259
|
-
};
|
|
260
|
-
}
|
|
261
234
|
//#endregion
|
|
262
|
-
export { measureImports as a, measureEntry as i,
|
|
235
|
+
export { measureImports as a, measureEntry as i, renderTonnageMarkdown as n, reportContent as r, createTonnageReport as t };
|
|
263
236
|
|
|
264
|
-
//# sourceMappingURL=
|
|
237
|
+
//# sourceMappingURL=report-B3HrJ4UQ.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"report-B3HrJ4UQ.mjs","names":[],"sources":["../src/measure.ts","../src/package-resolution.ts","../src/report-content.ts","../src/report.ts"],"sourcesContent":["import path from \"node:path\"\nimport { gzipSync } from \"node:zlib\"\n\nimport { build, type BuildOptions, type Plugin } from \"esbuild\"\n\nimport type { BundleMeasurement, BundlePlatform } from \"./types.ts\"\n\nexport type MeasureImportsOptions = {\n\texternal?: readonly string[] | undefined\n\tplatform?: BundlePlatform | undefined\n\tresolveDirectory: string\n\ttarget?: string | undefined\n}\n\nexport type MeasureEntryOptions = MeasureImportsOptions\n\ntype InternalMeasureOptions = MeasureImportsOptions & {\n\tplugins?: readonly Plugin[]\n}\n\nexport async function measureEntry(\n\tentry: string,\n\toptions: MeasureEntryOptions,\n): Promise<BundleMeasurement> {\n\treturn measureEntryWithPlugins(entry, options)\n}\n\nexport async function measureEntryWithPlugins(\n\tentry: string,\n\toptions: InternalMeasureOptions,\n): Promise<BundleMeasurement> {\n\treturn measureBuild(\n\t\t{ entryPoints: [path.resolve(options.resolveDirectory, entry)] },\n\t\toptions,\n\t)\n}\n\nexport async function measureImports(\n\timports: readonly string[],\n\toptions: MeasureImportsOptions,\n): Promise<BundleMeasurement> {\n\treturn measureImportsWithPlugins(imports, options)\n}\n\nexport async function measureImportsWithPlugins(\n\timports: readonly string[],\n\toptions: InternalMeasureOptions,\n): Promise<BundleMeasurement> {\n\tif (imports.length === 0) {\n\t\tthrow new Error(`A tonnage entry must import at least one module.`)\n\t}\n\n\tconst entry = imports\n\t\t.map(\n\t\t\t(specifier, index) =>\n\t\t\t\t`export * as entry${index} from ${JSON.stringify(specifier)}`,\n\t\t)\n\t\t.join(`\\n`)\n\treturn measureBuild(\n\t\t{\n\t\t\tstdin: {\n\t\t\t\tcontents: entry,\n\t\t\t\tloader: `js`,\n\t\t\t\tresolveDir: options.resolveDirectory,\n\t\t\t\tsourcefile: `tonnage-entry.js`,\n\t\t\t},\n\t\t},\n\t\toptions,\n\t)\n}\n\nasync function measureBuild(\n\tentry: Pick<BuildOptions, `entryPoints` | `stdin`>,\n\toptions: InternalMeasureOptions,\n): Promise<BundleMeasurement> {\n\tconst platform = options.platform ?? `neutral`\n\n\tconst result = await build({\n\t\tbundle: true,\n\t\tcharset: `utf8`,\n\t\texternal: [\n\t\t\t...(options.external ?? []),\n\t\t\t...(platform === `browser` ? [] : [`node:*`]),\n\t\t],\n\t\tformat: `esm`,\n\t\tlegalComments: `none`,\n\t\tlogLevel: `silent`,\n\t\t...(platform === `neutral` ? { mainFields: [`module`, `main`] } : {}),\n\t\tminify: true,\n\t\toutdir: `out`,\n\t\tplatform,\n\t\tplugins: [...(options.plugins ?? [])],\n\t\t...entry,\n\t\ttarget: options.target ?? `es2022`,\n\t\ttreeShaking: true,\n\t\twrite: false,\n\t})\n\n\tconst outputFiles = [...(result.outputFiles ?? [])]\n\t\t.filter((output) => output.path.endsWith(`.js`))\n\t\t.sort((left, right) => left.path.localeCompare(right.path))\n\tif (outputFiles.length === 0) {\n\t\tthrow new Error(`The tonnage entry did not emit any runtime JavaScript.`)\n\t}\n\tconst rawBytes = outputFiles.reduce(\n\t\t(total, output) => total + output.contents.byteLength,\n\t\t0,\n\t)\n\tconst gzipBytes = outputFiles.reduce(\n\t\t(total, output) =>\n\t\t\ttotal + gzipSync(output.contents, { level: 9 }).byteLength,\n\t\t0,\n\t)\n\n\treturn { gzipBytes, rawBytes }\n}\n","import fs from \"node:fs/promises\"\nimport os from \"node:os\"\nimport path from \"node:path\"\n\nimport type { Plugin } from \"esbuild\"\n\nexport async function withPackageResolver<Result>(\n\tpackageName: string,\n\tpackageDirectory: string,\n\tuseResolver: (plugin: Plugin) => Promise<Result>,\n): Promise<Result> {\n\tconst temporaryDirectory = await fs.mkdtemp(\n\t\tpath.join(os.tmpdir(), `tonnage-package-`),\n\t)\n\ttry {\n\t\tconst nodeModulesDirectory = path.join(temporaryDirectory, `node_modules`)\n\t\tconst packageLinkPath = path.resolve(nodeModulesDirectory, packageName)\n\t\tif (!packageLinkPath.startsWith(`${nodeModulesDirectory}${path.sep}`)) {\n\t\t\tthrow new Error(`Invalid package name: ${packageName}`)\n\t\t}\n\n\t\tawait fs.mkdir(path.dirname(packageLinkPath), { recursive: true })\n\t\tawait fs.symlink(\n\t\t\tpackageDirectory,\n\t\t\tpackageLinkPath,\n\t\t\tprocess.platform === `win32` ? `junction` : `dir`,\n\t\t)\n\n\t\tconst filter = new RegExp(`^${escapeRegExp(packageName)}(?:/.*)?$`)\n\t\tconst plugin: Plugin = {\n\t\t\tname: `tonnage-package-resolution`,\n\t\t\tsetup(build) {\n\t\t\t\tbuild.onResolve({ filter }, async (args) => {\n\t\t\t\t\tif (args.resolveDir === temporaryDirectory) {\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\n\t\t\t\t\treturn build.resolve(args.path, {\n\t\t\t\t\t\timporter: args.importer,\n\t\t\t\t\t\tkind: args.kind,\n\t\t\t\t\t\tnamespace: args.namespace,\n\t\t\t\t\t\tresolveDir: temporaryDirectory,\n\t\t\t\t\t\twith: args.with,\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t},\n\t\t}\n\n\t\treturn await useResolver(plugin)\n\t} finally {\n\t\tawait fs.rm(temporaryDirectory, { force: true, recursive: true })\n\t}\n}\n\nfunction escapeRegExp(value: string): string {\n\treturn value.replace(/[.*+?^${}()|[\\]\\\\]/g, `\\\\$&`)\n}\n","import type { Content, Element } from \"galley.md\"\nimport { jsx } from \"galley.md/jsx-runtime\"\n\nimport type { TonnageConfig, TonnageReport } from \"./types.ts\"\n\n/** Use Galley's JSX runtime directly so the source CLI stays executable by Node. */\nexport function reportContent(\n\treport: TonnageReport,\n\tconfig: TonnageConfig = {},\n): Element[] {\n\tconst hasExports = report.exports.length > 0\n\tconst hasRecipes = report.recipes.length > 0\n\tconst hasMultipleSections = hasExports && hasRecipes\n\tconst content = [jsx(\"h2\", { children: config.heading ?? \"Bundle size\" })]\n\n\tif (hasExports)\n\t\tcontent.push(\n\t\t\tjsx(\"p\", {\n\t\t\t\tchildren:\n\t\t\t\t\t\"Package export sizes include complete runtime export surfaces.\",\n\t\t\t}),\n\t\t)\n\tif (hasRecipes)\n\t\tcontent.push(\n\t\t\tjsx(\"p\", {\n\t\t\t\tchildren:\n\t\t\t\t\t\"Usage example sizes bundle their entry files and tree-shake unused exports.\",\n\t\t\t}),\n\t\t)\n\tcontent.push(\n\t\tjsx(\"p\", {\n\t\t\tchildren:\n\t\t\t\t\"Sizes are exact minified and level-9 gzip JavaScript byte counts. Declarations, source maps, CSS, and other assets are excluded. Peer dependencies stay external, and shared modules are counted once per bundle.\",\n\t\t}),\n\t)\n\n\tif (hasExports) {\n\t\tif (hasMultipleSections)\n\t\t\tcontent.push(jsx(\"h3\", { children: \"Package exports\" }))\n\t\tcontent.push(\n\t\t\ttable(\n\t\t\t\t[\n\t\t\t\t\t{ title: \"Import\" },\n\t\t\t\t\t{ title: \"Minified JS\", align: \"right\" },\n\t\t\t\t\t{ title: \"Gzip JS\", align: \"right\" },\n\t\t\t\t],\n\t\t\t\treport.exports.map((row) => [\n\t\t\t\t\tcode(row.name),\n\t\t\t\t\tformatBytes(row.rawBytes),\n\t\t\t\t\tformatBytes(row.gzipBytes),\n\t\t\t\t]),\n\t\t\t),\n\t\t)\n\t}\n\n\tif (hasRecipes) {\n\t\tif (hasMultipleSections)\n\t\t\tcontent.push(jsx(\"h3\", { children: \"Usage examples\" }))\n\t\tcontent.push(\n\t\t\ttable(\n\t\t\t\t[\n\t\t\t\t\t{ title: \"Recipe\" },\n\t\t\t\t\t{ title: \"Entry\" },\n\t\t\t\t\t{ title: \"Minified JS\", align: \"right\" },\n\t\t\t\t\t{ title: \"Gzip JS\", align: \"right\" },\n\t\t\t\t],\n\t\t\t\treport.recipes.map((row) => [\n\t\t\t\t\trow.name,\n\t\t\t\t\tcode(row.entry),\n\t\t\t\t\tformatBytes(row.rawBytes),\n\t\t\t\t\tformatBytes(row.gzipBytes),\n\t\t\t\t]),\n\t\t\t),\n\t\t)\n\t}\n\n\tcontent.push(\n\t\tjsx(\"p\", {\n\t\t\tchildren: [\n\t\t\t\t\"Report maintained with \",\n\t\t\t\tjsx(\"a\", {\n\t\t\t\t\thref: \"https://github.com/jeremybanka/tonnage\",\n\t\t\t\t\tchildren: \"tonnage\",\n\t\t\t\t}),\n\t\t\t\t\".\",\n\t\t\t],\n\t\t}),\n\t)\n\treturn content\n}\n\nfunction code(value: string): Content {\n\treturn { type: \"inlineCode\", value }\n}\n\nfunction formatBytes(bytes: number): string {\n\treturn `${new Intl.NumberFormat(\"en-US\").format(bytes)} B`\n}\n\nfunction table(\n\tcolumns: readonly { title: string; align?: \"right\" }[],\n\trows: readonly (readonly Content[])[],\n): Element {\n\treturn jsx(\"table\", {\n\t\tchildren: [\n\t\t\tjsx(\"thead\", {\n\t\t\t\tchildren: jsx(\"tr\", {\n\t\t\t\t\tchildren: columns.map(({ title, align }) =>\n\t\t\t\t\t\tjsx(\"th\", { children: title, align }),\n\t\t\t\t\t),\n\t\t\t\t}),\n\t\t\t}),\n\t\t\tjsx(\"tbody\", {\n\t\t\t\tchildren: rows.map((cells) =>\n\t\t\t\t\tjsx(\"tr\", {\n\t\t\t\t\t\tchildren: cells.map((children) => jsx(\"td\", { children })),\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t}),\n\t\t],\n\t})\n}\n","import fs from \"node:fs/promises\"\nimport path from \"node:path\"\n\nimport { renderMarkdown } from \"galley.md\"\n\nimport {\n\tmeasureEntryWithPlugins,\n\tmeasureImportsWithPlugins,\n} from \"./measure.ts\"\nimport { withPackageResolver } from \"./package-resolution.ts\"\nimport { reportContent } from \"./report-content.ts\"\nimport type {\n\tTonnageConfig,\n\tTonnageExports,\n\tTonnageReport,\n\tTonnageRow,\n} from \"./types.ts\"\n\ntype PackageJson = {\n\texports?: unknown\n\tname?: string\n\tpeerDependencies?: Record<string, string>\n}\n\nexport async function createTonnageReport(\n\tconfig: TonnageConfig,\n\tconfigDirectory: string,\n): Promise<TonnageReport> {\n\tconst packageJsonPath = path.resolve(\n\t\tconfigDirectory,\n\t\tconfig.packageJson ?? `package.json`,\n\t)\n\tconst packageJson = JSON.parse(\n\t\tawait fs.readFile(packageJsonPath, `utf8`),\n\t) as PackageJson\n\tif (!packageJson.name) {\n\t\tthrow new Error(`${packageJsonPath} does not declare a package name.`)\n\t}\n\n\tconst resolveDirectory = path.dirname(packageJsonPath)\n\tconst peerDependencies = Object.keys(packageJson.peerDependencies ?? {})\n\tconst external = unique([...peerDependencies, ...(config.external ?? [])])\n\tconst exportImports = selectExportImports(\n\t\tpackageJson.name,\n\t\tpackageJson.exports,\n\t\tconfig.exports,\n\t)\n\n\tconst { exportRows, recipeRows } = await withPackageResolver(\n\t\tpackageJson.name,\n\t\tresolveDirectory,\n\t\tasync (packageResolver) => {\n\t\t\tconst exportRows = await Promise.all(\n\t\t\t\texportImports.map(async (specifier): Promise<TonnageRow> => ({\n\t\t\t\t\t...(await measureImportsWithPlugins([specifier], {\n\t\t\t\t\t\texternal,\n\t\t\t\t\t\tplatform: config.platform,\n\t\t\t\t\t\tplugins: [packageResolver],\n\t\t\t\t\t\tresolveDirectory,\n\t\t\t\t\t\ttarget: config.target,\n\t\t\t\t\t})),\n\t\t\t\t\timports: [specifier],\n\t\t\t\t\tname: specifier,\n\t\t\t\t})),\n\t\t\t)\n\t\t\tconst recipeRows = await Promise.all(\n\t\t\t\t(config.recipes ?? []).map(async (recipe) => ({\n\t\t\t\t\t...(await measureEntryWithPlugins(recipe.entry, {\n\t\t\t\t\t\texternal: unique([...external, ...(recipe.external ?? [])]),\n\t\t\t\t\t\tplatform: recipe.platform ?? config.platform,\n\t\t\t\t\t\tplugins: [packageResolver],\n\t\t\t\t\t\tresolveDirectory,\n\t\t\t\t\t\ttarget: config.target,\n\t\t\t\t\t})),\n\t\t\t\t\tentry: recipe.entry,\n\t\t\t\t\tname: recipe.name,\n\t\t\t\t})),\n\t\t\t)\n\n\t\t\treturn { exportRows, recipeRows }\n\t\t},\n\t)\n\n\treturn {\n\t\texports: exportRows,\n\t\tpackageName: packageJson.name,\n\t\trecipes: recipeRows,\n\t}\n}\n\n/** Serialize a report with the same Galley elements used by the document component. */\nexport async function renderTonnageMarkdown(\n\treport: TonnageReport,\n\tconfig: TonnageConfig = {},\n): Promise<string> {\n\tconst directory = process.cwd()\n\treturn renderMarkdown(reportContent(report, config), {\n\t\tdirectory,\n\t\tpath: path.resolve(directory, config.readme ?? \"README.md\"),\n\t})\n}\n\nfunction selectExportImports(\n\tpackageName: string,\n\texportsValue: unknown,\n\tselection: TonnageConfig[`exports`],\n): string[] {\n\tif (selection === false) {\n\t\treturn []\n\t}\n\n\tconst exportKeys = getExportKeys(exportsValue)\n\tconst options: TonnageExports = typeof selection === `object` ? selection : {}\n\tconst included = options.include\n\t\t? [...options.include]\n\t\t: exportKeys.filter((exportKey) => exportKey !== `./package.json`)\n\tconst excluded = new Set(options.exclude ?? [])\n\n\treturn included\n\t\t.filter((exportKey) => !excluded.has(exportKey))\n\t\t.map((exportKey) => toPackageImport(packageName, exportKey))\n}\n\nfunction getExportKeys(exportsValue: unknown): string[] {\n\tif (typeof exportsValue === `string` || Array.isArray(exportsValue)) {\n\t\treturn [`.`]\n\t}\n\tif (!exportsValue || typeof exportsValue !== `object`) {\n\t\treturn [`.`]\n\t}\n\n\tconst keys = Object.keys(exportsValue)\n\treturn keys.some((key) => key.startsWith(`.`)) ? keys : [`.`]\n}\n\nfunction toPackageImport(packageName: string, exportKey: string): string {\n\tif (exportKey === `.`) {\n\t\treturn packageName\n\t}\n\tif (!exportKey.startsWith(`./`)) {\n\t\tthrow new Error(`Invalid package export key: ${exportKey}`)\n\t}\n\treturn `${packageName}/${exportKey.slice(2)}`\n}\n\nfunction unique(values: readonly string[]): string[] {\n\treturn [...new Set(values)]\n}\n"],"mappings":";;;;;;;;AAoBA,eAAsB,aACrB,OACA,SAC6B;CAC7B,OAAO,wBAAwB,OAAO,OAAO;AAC9C;AAEA,eAAsB,wBACrB,OACA,SAC6B;CAC7B,OAAO,aACN,EAAE,aAAa,CAAC,KAAK,QAAQ,QAAQ,kBAAkB,KAAK,CAAC,EAAE,GAC/D,OACD;AACD;AAEA,eAAsB,eACrB,SACA,SAC6B;CAC7B,OAAO,0BAA0B,SAAS,OAAO;AAClD;AAEA,eAAsB,0BACrB,SACA,SAC6B;CAC7B,IAAI,QAAQ,WAAW,GACtB,MAAM,IAAI,MAAM,kDAAkD;CASnE,OAAO,aACN,EACC,OAAO;EACN,UATW,QACZ,KACC,WAAW,UACX,oBAAoB,MAAM,QAAQ,KAAK,UAAU,SAAS,GAC5D,CAAC,CACA,KAAK,IAIU;EACd,QAAQ;EACR,YAAY,QAAQ;EACpB,YAAY;CACb,EACD,GACA,OACD;AACD;AAEA,eAAe,aACd,OACA,SAC6B;CAC7B,MAAM,WAAW,QAAQ,YAAY;CAuBrC,MAAM,cAAc,CAAC,IAAI,MArBJ,MAAM;EAC1B,QAAQ;EACR,SAAS;EACT,UAAU,CACT,GAAI,QAAQ,YAAY,CAAC,GACzB,GAAI,aAAa,YAAY,CAAC,IAAI,CAAC,QAAQ,CAC5C;EACA,QAAQ;EACR,eAAe;EACf,UAAU;EACV,GAAI,aAAa,YAAY,EAAE,YAAY,CAAC,UAAU,MAAM,EAAE,IAAI,CAAC;EACnE,QAAQ;EACR,QAAQ;EACR;EACA,SAAS,CAAC,GAAI,QAAQ,WAAW,CAAC,CAAE;EACpC,GAAG;EACH,QAAQ,QAAQ,UAAU;EAC1B,aAAa;E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B;CAClE,MAAM,WAAW,IAAI,IAAI,QAAQ,WAAW,CAAC,CAAC;CAE9C,OAAO,SACL,QAAQ,cAAc,CAAC,SAAS,IAAI,SAAS,CAAC,CAAC,CAC/C,KAAK,cAAc,gBAAgB,aAAa,SAAS,CAAC;AAC7D;AAEA,SAAS,cAAc,cAAiC;CACvD,IAAI,OAAO,iBAAiB,YAAY,MAAM,QAAQ,YAAY,GACjE,OAAO,CAAC,GAAG;CAEZ,IAAI,CAAC,gBAAgB,OAAO,iBAAiB,UAC5C,OAAO,CAAC,GAAG;CAGZ,MAAM,OAAO,OAAO,KAAK,YAAY;CACrC,OAAO,KAAK,MAAM,QAAQ,IAAI,WAAW,GAAG,CAAC,IAAI,OAAO,CAAC,GAAG;AAC7D;AAEA,SAAS,gBAAgB,aAAqB,WAA2B;CACxE,IAAI,cAAc,KACjB,OAAO;CAER,IAAI,CAAC,UAAU,WAAW,IAAI,GAC7B,MAAM,IAAI,MAAM,+BAA+B,WAAW;CAE3D,OAAO,GAAG,YAAY,GAAG,UAAU,MAAM,CAAC;AAC3C;AAEA,SAAS,OAAO,QAAqC;CACpD,OAAO,CAAC,GAAG,IAAI,IAAI,MAAM,CAAC;AAC3B"}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { n as renderTonnageMarkdown, t as createTonnageReport } from "./report-B3HrJ4UQ.mjs";
|
|
2
|
+
import fs from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
//#region src/readme.ts
|
|
5
|
+
function tonnageMarkers(marker = `default`) {
|
|
6
|
+
validateMarker(marker);
|
|
7
|
+
return {
|
|
8
|
+
end: `<!-- tonnage:${marker}:end -->`,
|
|
9
|
+
start: `<!-- tonnage:${marker}:start -->`
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
function updateGeneratedSection(readme, markdown, marker) {
|
|
13
|
+
const { end, start } = tonnageMarkers(marker);
|
|
14
|
+
const startIndex = readme.indexOf(start);
|
|
15
|
+
const endIndex = readme.indexOf(end);
|
|
16
|
+
if (startIndex === -1 || endIndex === -1) throw new Error(`README must contain exactly one ${start} and one ${end} marker.`);
|
|
17
|
+
if (readme.slice(startIndex + start.length).includes(start) || readme.slice(endIndex + end.length).includes(end)) throw new Error(`README must contain exactly one ${start} and one ${end} marker.`);
|
|
18
|
+
if (endIndex < startIndex) throw new Error(`${end} must appear after ${start}.`);
|
|
19
|
+
const contentStart = startIndex + start.length;
|
|
20
|
+
return `${readme.slice(0, contentStart)}\n\n${markdown.trim()}\n\n${readme.slice(endIndex)}`;
|
|
21
|
+
}
|
|
22
|
+
function validateMarker(marker) {
|
|
23
|
+
if (!/^[a-z0-9][a-z0-9._-]*$/i.test(marker)) throw new Error(`Tonnage marker names may contain letters, numbers, dots, underscores, and hyphens.`);
|
|
24
|
+
}
|
|
25
|
+
//#endregion
|
|
26
|
+
//#region src/run.ts
|
|
27
|
+
async function runTonnage(config, options) {
|
|
28
|
+
const configDirectory = path.resolve(options.configDirectory ?? process.cwd());
|
|
29
|
+
const readmePath = path.resolve(configDirectory, config.readme ?? `README.md`);
|
|
30
|
+
const oldReadme = await fs.readFile(readmePath, `utf8`);
|
|
31
|
+
const report = await createTonnageReport(config, configDirectory);
|
|
32
|
+
const newReadme = updateGeneratedSection(oldReadme, await renderTonnageMarkdown(report, config), config.marker);
|
|
33
|
+
const changed = oldReadme !== newReadme;
|
|
34
|
+
if (options.mode === `write` && changed) await fs.writeFile(readmePath, newReadme);
|
|
35
|
+
return {
|
|
36
|
+
changed,
|
|
37
|
+
readmePath,
|
|
38
|
+
report
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
//#endregion
|
|
42
|
+
export { tonnageMarkers as n, updateGeneratedSection as r, runTonnage as t };
|
|
43
|
+
|
|
44
|
+
//# sourceMappingURL=run-BJN1MXRf.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"run-BJN1MXRf.mjs","names":[],"sources":["../src/readme.ts","../src/run.ts"],"sourcesContent":["export function tonnageMarkers(marker = `default`): {\n\tend: string\n\tstart: string\n} {\n\tvalidateMarker(marker)\n\treturn {\n\t\tend: `<!-- tonnage:${marker}:end -->`,\n\t\tstart: `<!-- tonnage:${marker}:start -->`,\n\t}\n}\n\nexport function updateGeneratedSection(\n\treadme: string,\n\tmarkdown: string,\n\tmarker?: string,\n): string {\n\tconst { end, start } = tonnageMarkers(marker)\n\tconst startIndex = readme.indexOf(start)\n\tconst endIndex = readme.indexOf(end)\n\n\tif (startIndex === -1 || endIndex === -1) {\n\t\tthrow new Error(\n\t\t\t`README must contain exactly one ${start} and one ${end} marker.`,\n\t\t)\n\t}\n\tif (\n\t\treadme.slice(startIndex + start.length).includes(start) ||\n\t\treadme.slice(endIndex + end.length).includes(end)\n\t) {\n\t\tthrow new Error(\n\t\t\t`README must contain exactly one ${start} and one ${end} marker.`,\n\t\t)\n\t}\n\tif (endIndex < startIndex) {\n\t\tthrow new Error(`${end} must appear after ${start}.`)\n\t}\n\n\tconst contentStart = startIndex + start.length\n\treturn `${readme.slice(0, contentStart)}\\n\\n${markdown.trim()}\\n\\n${readme.slice(endIndex)}`\n}\n\nfunction validateMarker(marker: string): void {\n\tif (!/^[a-z0-9][a-z0-9._-]*$/i.test(marker)) {\n\t\tthrow new Error(\n\t\t\t`Tonnage marker names may contain letters, numbers, dots, underscores, and hyphens.`,\n\t\t)\n\t}\n}\n","import fs from \"node:fs/promises\"\nimport path from \"node:path\"\n\nimport { updateGeneratedSection } from \"./readme.ts\"\nimport { createTonnageReport, renderTonnageMarkdown } from \"./report.ts\"\nimport type { TonnageConfig, TonnageMode, TonnageRunResult } from \"./types.ts\"\n\nexport async function runTonnage(\n\tconfig: TonnageConfig,\n\toptions: {\n\t\tconfigDirectory?: string\n\t\tmode: TonnageMode\n\t},\n): Promise<TonnageRunResult> {\n\tconst configDirectory = path.resolve(options.configDirectory ?? process.cwd())\n\tconst readmePath = path.resolve(configDirectory, config.readme ?? `README.md`)\n\tconst oldReadme = await fs.readFile(readmePath, `utf8`)\n\tconst report = await createTonnageReport(config, configDirectory)\n\tconst markdown = await renderTonnageMarkdown(report, config)\n\tconst newReadme = updateGeneratedSection(oldReadme, markdown, config.marker)\n\tconst changed = oldReadme !== newReadme\n\n\tif (options.mode === `write` && changed) {\n\t\tawait fs.writeFile(readmePath, newReadme)\n\t}\n\n\treturn { changed, readmePath, report }\n}\n"],"mappings":";;;;AAAA,SAAgB,eAAe,SAAS,WAGtC;CACD,eAAe,MAAM;CACrB,OAAO;EACN,KAAK,gBAAgB,OAAO;EAC5B,OAAO,gBAAgB,OAAO;CAC/B;AACD;AAEA,SAAgB,uBACf,QACA,UACA,QACS;CACT,MAAM,EAAE,KAAK,UAAU,eAAe,MAAM;CAC5C,MAAM,aAAa,OAAO,QAAQ,KAAK;CACvC,MAAM,WAAW,OAAO,QAAQ,GAAG;CAEnC,IAAI,eAAe,MAAM,aAAa,IACrC,MAAM,IAAI,MACT,mCAAmC,MAAM,WAAW,IAAI,SACzD;CAED,IACC,OAAO,MAAM,aAAa,MAAM,MAAM,CAAC,CAAC,SAAS,KAAK,KACtD,OAAO,MAAM,WAAW,IAAI,MAAM,CAAC,CAAC,SAAS,GAAG,GAEhD,MAAM,IAAI,MACT,mCAAmC,MAAM,WAAW,IAAI,SACzD;CAED,IAAI,WAAW,YACd,MAAM,IAAI,MAAM,GAAG,IAAI,qBAAqB,MAAM,EAAE;CAGrD,MAAM,eAAe,aAAa,MAAM;CACxC,OAAO,GAAG,OAAO,MAAM,GAAG,YAAY,EAAE,MAAM,SAAS,KAAK,EAAE,MAAM,OAAO,MAAM,QAAQ;AAC1F;AAEA,SAAS,eAAe,QAAsB;CAC7C,IAAI,CAAC,0BAA0B,KAAK,MAAM,GACzC,MAAM,IAAI,MACT,oFACD;AAEF;;;ACxCA,eAAsB,WACrB,QACA,SAI4B;CAC5B,MAAM,kBAAkB,KAAK,QAAQ,QAAQ,mBAAmB,QAAQ,IAAI,CAAC;CAC7E,MAAM,aAAa,KAAK,QAAQ,iBAAiB,OAAO,UAAU,WAAW;CAC7E,MAAM,YAAY,MAAM,GAAG,SAAS,YAAY,MAAM;CACtD,MAAM,SAAS,MAAM,oBAAoB,QAAQ,eAAe;CAEhE,MAAM,YAAY,uBAAuB,WAAW,MAD7B,sBAAsB,QAAQ,MAAM,GACG,OAAO,MAAM;CAC3E,MAAM,UAAU,cAAc;CAE9B,IAAI,QAAQ,SAAS,WAAW,SAC/B,MAAM,GAAG,UAAU,YAAY,SAAS;CAGzC,OAAO;EAAE;EAAS;EAAY;CAAO;AACtC"}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
//#region src/types.d.ts
|
|
2
|
+
type BundlePlatform = `browser` | `neutral` | `node`;
|
|
3
|
+
type TonnageExports = {
|
|
4
|
+
exclude?: readonly string[];
|
|
5
|
+
include?: readonly string[];
|
|
6
|
+
};
|
|
7
|
+
type TonnageRecipe = {
|
|
8
|
+
entry: string;
|
|
9
|
+
external?: readonly string[];
|
|
10
|
+
name: string;
|
|
11
|
+
platform?: BundlePlatform;
|
|
12
|
+
};
|
|
13
|
+
type TonnageConfig = {
|
|
14
|
+
exports?: boolean | TonnageExports;
|
|
15
|
+
external?: readonly string[];
|
|
16
|
+
heading?: string;
|
|
17
|
+
marker?: string;
|
|
18
|
+
packageJson?: string;
|
|
19
|
+
platform?: BundlePlatform;
|
|
20
|
+
readme?: string;
|
|
21
|
+
recipes?: readonly TonnageRecipe[];
|
|
22
|
+
target?: string;
|
|
23
|
+
};
|
|
24
|
+
type BundleMeasurement = {
|
|
25
|
+
gzipBytes: number;
|
|
26
|
+
rawBytes: number;
|
|
27
|
+
};
|
|
28
|
+
type TonnageRow = BundleMeasurement & {
|
|
29
|
+
imports: readonly string[];
|
|
30
|
+
name: string;
|
|
31
|
+
};
|
|
32
|
+
type TonnageRecipeRow = BundleMeasurement & {
|
|
33
|
+
entry: string;
|
|
34
|
+
name: string;
|
|
35
|
+
};
|
|
36
|
+
type TonnageReport = {
|
|
37
|
+
exports: readonly TonnageRow[];
|
|
38
|
+
packageName: string;
|
|
39
|
+
recipes: readonly TonnageRecipeRow[];
|
|
40
|
+
};
|
|
41
|
+
type TonnageMode = `check` | `write`;
|
|
42
|
+
type TonnageRunResult = {
|
|
43
|
+
changed: boolean;
|
|
44
|
+
readmePath: string;
|
|
45
|
+
report: TonnageReport;
|
|
46
|
+
};
|
|
47
|
+
//#endregion
|
|
48
|
+
export { TonnageMode as a, TonnageReport as c, TonnageExports as i, TonnageRow as l, BundlePlatform as n, TonnageRecipe as o, TonnageConfig as r, TonnageRecipeRow as s, BundleMeasurement as t, TonnageRunResult as u };
|
|
49
|
+
//# sourceMappingURL=types-Ddtp95Z3.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types-Ddtp95Z3.d.mts","names":[],"sources":["../src/types.ts"],"mappings":";KAAY;KAEA;EACX;EACA;;KAGW;EACX;EACA;EACA;EACA,WAAW;;KAGA;EACX,oBAAoB;EACpB;EACA;EACA;EACA;EACA,WAAW;EACX;EACA,mBAAmB;EACnB;;KAGW;EACX;EACA;;KAGW,aAAa;EACxB;EACA;;KAGW,mBAAmB;EAC9B;EACA;;KAGW;EACX,kBAAkB;EAClB;EACA,kBAAkB;;KAGP;KAEA;EACX;EACA;EACA,QAAQ"}
|
package/package.json
CHANGED
|
@@ -1,33 +1,19 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tonnage",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Keep deterministic bundle size reports in README files and CI.",
|
|
5
|
-
"type": "module",
|
|
6
|
-
"license": "MPL-2.0",
|
|
7
|
-
"author": "Jeremy Banka",
|
|
8
|
-
"engines": {
|
|
9
|
-
"node": ">=22.18.0"
|
|
10
|
-
},
|
|
11
|
-
"publishConfig": {
|
|
12
|
-
"access": "public"
|
|
13
|
-
},
|
|
14
5
|
"repository": {
|
|
15
6
|
"type": "git",
|
|
16
7
|
"url": "git+https://github.com/jeremybanka/tonnage.git"
|
|
17
8
|
},
|
|
18
|
-
"
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
"dist",
|
|
22
|
-
"src",
|
|
23
|
-
"examples",
|
|
24
|
-
"README.md",
|
|
25
|
-
"LICENSE"
|
|
26
|
-
],
|
|
27
|
-
"bin": {
|
|
28
|
-
"tonnage": "dist/cli.mjs"
|
|
29
|
-
},
|
|
9
|
+
"license": "MPL-2.0",
|
|
10
|
+
"author": "Jeremy Banka",
|
|
11
|
+
"type": "module",
|
|
30
12
|
"exports": {
|
|
13
|
+
"./galley": {
|
|
14
|
+
"types": "./dist/galley.d.mts",
|
|
15
|
+
"import": "./dist/galley.mjs"
|
|
16
|
+
},
|
|
31
17
|
".": {
|
|
32
18
|
"import": "./dist/index.mjs",
|
|
33
19
|
"types": "./dist/index.d.mts"
|
|
@@ -36,16 +22,36 @@
|
|
|
36
22
|
},
|
|
37
23
|
"main": "./dist/index.mjs",
|
|
38
24
|
"types": "./dist/index.d.mts",
|
|
25
|
+
"bin": {
|
|
26
|
+
"tonnage": "dist/cli.mjs"
|
|
27
|
+
},
|
|
28
|
+
"files": [
|
|
29
|
+
"AGENTS.md",
|
|
30
|
+
"CHANGELOG.md",
|
|
31
|
+
"dist",
|
|
32
|
+
"src",
|
|
33
|
+
"examples",
|
|
34
|
+
"README.md",
|
|
35
|
+
"LICENSE"
|
|
36
|
+
],
|
|
39
37
|
"dependencies": {
|
|
40
|
-
"comline": "0.
|
|
41
|
-
"esbuild": "0.28.2"
|
|
38
|
+
"comline": "0.9.0",
|
|
39
|
+
"esbuild": "0.28.2",
|
|
40
|
+
"galley.md": "0.1.1"
|
|
42
41
|
},
|
|
43
42
|
"devDependencies": {
|
|
44
|
-
"@types/node": "26.
|
|
45
|
-
"
|
|
43
|
+
"@types/node": "26.6.5",
|
|
44
|
+
"typescript": "7.1.0-dev.20261020.3"
|
|
45
|
+
},
|
|
46
|
+
"engines": {
|
|
47
|
+
"node": ">=22.18.0"
|
|
48
|
+
},
|
|
49
|
+
"publishConfig": {
|
|
50
|
+
"access": "public"
|
|
46
51
|
},
|
|
47
52
|
"scripts": {
|
|
48
53
|
"build": "vp pack",
|
|
49
|
-
"test": "vp test"
|
|
54
|
+
"test": "vp test",
|
|
55
|
+
"test:watch": "vp test watch"
|
|
50
56
|
}
|
|
51
57
|
}
|
package/src/cli.ts
CHANGED
|
@@ -4,7 +4,13 @@ import fs from "node:fs/promises"
|
|
|
4
4
|
import path from "node:path"
|
|
5
5
|
import { pathToFileURL } from "node:url"
|
|
6
6
|
|
|
7
|
-
import {
|
|
7
|
+
import { logWarnings } from "comline"
|
|
8
|
+
|
|
9
|
+
import {
|
|
10
|
+
completeTonnageCli,
|
|
11
|
+
parseTonnageCli,
|
|
12
|
+
renderTonnageCliHelp,
|
|
13
|
+
} from "./command-line.ts"
|
|
8
14
|
import { runTonnage } from "./run.ts"
|
|
9
15
|
import type { TonnageConfig } from "./types.ts"
|
|
10
16
|
|
|
@@ -15,7 +21,14 @@ const DEFAULT_CONFIG_FILES = [
|
|
|
15
21
|
]
|
|
16
22
|
|
|
17
23
|
async function main(): Promise<void> {
|
|
18
|
-
const
|
|
24
|
+
const completion = await completeTonnageCli(process.argv)
|
|
25
|
+
if (completion !== undefined) {
|
|
26
|
+
process.stdout.write(completion)
|
|
27
|
+
return
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const invocation = parseTonnageCli(process.argv)
|
|
31
|
+
logWarnings(invocation.warnings)
|
|
19
32
|
if (invocation.kind === `help`) {
|
|
20
33
|
process.stdout.write(renderTonnageCliHelp())
|
|
21
34
|
return
|
package/src/command-line.ts
CHANGED
|
@@ -1,4 +1,11 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
type CliWarning,
|
|
3
|
+
cli,
|
|
4
|
+
completionResponse,
|
|
5
|
+
help,
|
|
6
|
+
helpOption,
|
|
7
|
+
optional,
|
|
8
|
+
} from "comline"
|
|
2
9
|
|
|
3
10
|
import type { TonnageMode } from "./types.ts"
|
|
4
11
|
|
|
@@ -22,18 +29,29 @@ const tonnageCli = cli({
|
|
|
22
29
|
write: WRITE_MANUAL,
|
|
23
30
|
"write/$configPath": WRITE_MANUAL,
|
|
24
31
|
},
|
|
32
|
+
positionalCompletions: {
|
|
33
|
+
"check/$configPath": { fileSystem: `files` },
|
|
34
|
+
"write/$configPath": { fileSystem: `files` },
|
|
35
|
+
},
|
|
25
36
|
discoverConfigPath: () => undefined,
|
|
26
37
|
})
|
|
27
38
|
|
|
28
|
-
export type TonnageCliInvocation =
|
|
39
|
+
export type TonnageCliInvocation = { warnings: CliWarning[] } & (
|
|
29
40
|
| { kind: `help` }
|
|
30
41
|
| { configArgument?: string; kind: `run`; mode: TonnageMode }
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
export function completeTonnageCli(
|
|
45
|
+
args: string[],
|
|
46
|
+
): Promise<string | undefined> {
|
|
47
|
+
return completionResponse(tonnageCli.definition, args)
|
|
48
|
+
}
|
|
31
49
|
|
|
32
50
|
export function parseTonnageCli(args: string[]): TonnageCliInvocation {
|
|
33
|
-
const { inputs } = tonnageCli(args)
|
|
51
|
+
const { inputs, warnings } = tonnageCli(args)
|
|
34
52
|
|
|
35
53
|
if (inputs.case === `` || inputs.opts.help) {
|
|
36
|
-
return { kind: `help
|
|
54
|
+
return { kind: `help`, warnings }
|
|
37
55
|
}
|
|
38
56
|
|
|
39
57
|
const mode =
|
|
@@ -43,8 +61,8 @@ export function parseTonnageCli(args: string[]): TonnageCliInvocation {
|
|
|
43
61
|
const configArgument = inputs.path[1]
|
|
44
62
|
|
|
45
63
|
return configArgument === undefined
|
|
46
|
-
? { kind: `run`, mode }
|
|
47
|
-
: { configArgument, kind: `run`, mode }
|
|
64
|
+
? { kind: `run`, mode, warnings }
|
|
65
|
+
: { configArgument, kind: `run`, mode, warnings }
|
|
48
66
|
}
|
|
49
67
|
|
|
50
68
|
export function renderTonnageCliHelp(): string {
|
package/src/galley.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import path from "node:path"
|
|
2
|
+
|
|
3
|
+
import type { DocumentContext, Element } from "galley.md"
|
|
4
|
+
|
|
5
|
+
import { createTonnageReport } from "./report.ts"
|
|
6
|
+
import { reportContent } from "./report-content.ts"
|
|
7
|
+
import type { TonnageConfig } from "./types.ts"
|
|
8
|
+
|
|
9
|
+
export type TonnageProps = {
|
|
10
|
+
config?: TonnageConfig
|
|
11
|
+
/** Override the document directory when measuring a different package. */
|
|
12
|
+
directory?: string
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Measure bundles and include the report in a galley.md document. */
|
|
16
|
+
export async function Tonnage(
|
|
17
|
+
{ config = {}, directory }: TonnageProps,
|
|
18
|
+
context: DocumentContext,
|
|
19
|
+
): Promise<Element[]> {
|
|
20
|
+
const report = await createTonnageReport(
|
|
21
|
+
config,
|
|
22
|
+
path.resolve(context.directory, directory ?? "."),
|
|
23
|
+
)
|
|
24
|
+
return reportContent(report, config)
|
|
25
|
+
}
|