Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

Format the JS, TS and CSS that the formatter never reached (#82912)

Romeo Van Snickf1fbafd8d950
diff --git a/.github/actions/bundle-size-check/compare.js b/.github/actions/bundle-size-check/compare.js
index f245d1830a8..fef11c83996 100644
--- a/.github/actions/bundle-size-check/compare.js
+++ b/.github/actions/bundle-size-check/compare.js
@@ -13,15 +13,16 @@
// the step outputs / exit code.
const fs = require("fs");
-const pick = (rows, bundle, kind) => rows.find(row => row.bundle === bundle && row.kind === kind);
-const keyOf = row => `${row.bundle}/${row.kind}`;
-const mb = bytes => (bytes / 1024 / 1024).toFixed(2);
+const pick = (rows, bundle, kind) =>
+ rows.find((row) => row.bundle === bundle && row.kind === kind);
+const keyOf = (row) => `${row.bundle}/${row.kind}`;
+const mb = (bytes) => (bytes / 1024 / 1024).toFixed(2);
const percentOf = (currentBytes, baseBytes) =>
baseBytes ? Math.trunc(((currentBytes - baseBytes) * 100) / baseBytes) : 0;
// Output names are derived from the gate key, so the workflow reads
// `app_initial_status`, `embedding_sdk_chunked_total_status`, and so on.
-const outputPrefix = gateKey => gateKey.replace(/[^a-zA-Z0-9]+/g, "_");
+const outputPrefix = (gateKey) => gateKey.replace(/[^a-zA-Z0-9]+/g, "_");
/**
* Evaluate one gate. Returns the key plus exactly one of:
@@ -34,7 +35,10 @@ function evaluateGate({ current, base, threshold, gateKey }) {
const gateCurrent = pick(current, bundle, kind);
const gateBase = pick(base, bundle, kind);
if (!gateCurrent || !gateBase || !gateBase.gzipBytes) {
- return { gateKey, error: `Could not find ${bundle} ${kind} (gzip) in both builds` };
+ return {
+ gateKey,
+ error: `Could not find ${bundle} ${kind} (gzip) in both builds`,
+ };
}
// Both sides must measure the bundle the same way. A base ref built before the
@@ -52,7 +56,12 @@ function evaluateGate({ current, base, threshold, gateKey }) {
}
const percent = percentOf(gateCurrent.gzipBytes, gateBase.gzipBytes);
- const status = percent > threshold ? "increased" : percent < -threshold ? "decreased" : "stable";
+ const status =
+ percent > threshold
+ ? "increased"
+ : percent < -threshold
+ ? "decreased"
+ : "stable";
return { gateKey, status, percent };
}
@@ -68,15 +77,24 @@ function compareBundles({ current, base, threshold, gateKeys }) {
const currentRow = pick(current, bundle, kind);
const baseRow = pick(base, bundle, kind);
if (!currentRow || !baseRow) {
- report.push(`${key}: present only in ${currentRow ? "current" : "base"} build`);
+ report.push(
+ `${key}: present only in ${currentRow ? "current" : "base"} build`,
+ );
continue;
}
const diff = currentRow.gzipBytes - baseRow.gzipBytes;
const percent = percentOf(currentRow.gzipBytes, baseRow.gzipBytes);
- report.push(`${key}: ${mb(currentRow.gzipBytes)}MB vs ${mb(baseRow.gzipBytes)}MB (${percent}%, ${diff} bytes)`);
+ report.push(
+ `${key}: ${mb(currentRow.gzipBytes)}MB vs ${mb(baseRow.gzipBytes)}MB (${percent}%, ${diff} bytes)`,
+ );
}
- return { report, gates: gateKeys.map(gateKey => evaluateGate({ current, base, threshold, gateKey })) };
+ return {
+ report,
+ gates: gateKeys.map((gateKey) =>
+ evaluateGate({ current, base, threshold, gateKey }),
+ ),
+ };
}
module.exports = { compareBundles, outputPrefix };
@@ -90,12 +108,19 @@ const setOutput = (name, value) => {
function main() {
const [, , currentPath, basePath] = process.argv;
const threshold = Number(process.env.THRESHOLD ?? 2);
- const gateKeys = (process.env.GATES ?? "embedding-sdk-chunked/total").split(",").map(key => key.trim());
+ const gateKeys = (process.env.GATES ?? "embedding-sdk-chunked/total")
+ .split(",")
+ .map((key) => key.trim());
const current = JSON.parse(fs.readFileSync(currentPath, "utf8"));
const base = JSON.parse(fs.readFileSync(basePath, "utf8"));
- const { report, gates } = compareBundles({ current, base, threshold, gateKeys });
+ const { report, gates } = compareBundles({
+ current,
+ base,
+ threshold,
+ gateKeys,
+ });
console.log(report.join("\n"));
console.log("");
@@ -118,12 +143,14 @@ function main() {
continue;
}
- console.log(`Gate: ${gate.gateKey} ${gate.percent}% (threshold ${threshold}%) → ${gate.status}`);
+ console.log(
+ `Gate: ${gate.gateKey} ${gate.percent}% (threshold ${threshold}%) → ${gate.status}`,
+ );
setOutput(`${prefix}_status`, gate.status);
setOutput(`${prefix}_size_change_percent`, gate.percent);
}
- if (gates.some(gate => gate.error)) {
+ if (gates.some((gate) => gate.error)) {
process.exit(1);
}
}
diff --git a/.github/actions/bundle-size-check/compare.unit.spec.js b/.github/actions/bundle-size-check/compare.unit.spec.js
index 79868cefc33..c2c150bc686 100644
--- a/.github/actions/bundle-size-check/compare.unit.spec.js
+++ b/.github/actions/bundle-size-check/compare.unit.spec.js
@@ -11,7 +11,11 @@ const total = (gzipBytes, over = {}) => ({
...over,
});
-const appInitial = gzipBytes => ({ bundle: "app", kind: "initial", gzipBytes });
+const appInitial = (gzipBytes) => ({
+ bundle: "app",
+ kind: "initial",
+ gzipBytes,
+});
const compare = ({ current, base, threshold = 2, gateKeys = [SDK_GATE] }) =>
compareBundles({ current, base, threshold, gateKeys });
@@ -25,18 +29,27 @@ describe("outputPrefix", () => {
describe("compareBundles", () => {
it("gates on the chunked SDK total and flags an increase past the threshold", () => {
- const { gates, report } = compare({ current: [total(110)], base: [total(100)] });
+ const { gates, report } = compare({
+ current: [total(110)],
+ base: [total(100)],
+ });
- expect(gates).toEqual([{ gateKey: SDK_GATE, status: "increased", percent: 10 }]);
+ expect(gates).toEqual([
+ { gateKey: SDK_GATE, status: "increased", percent: 10 },
+ ]);
expect(report[0]).toContain("current vs base");
});
it("flags a decrease and stays stable within the threshold", () => {
- expect(compare({ current: [total(90)], base: [total(100)] }).gates[0]).toMatchObject({
+ expect(
+ compare({ current: [total(90)], base: [total(100)] }).gates[0],
+ ).toMatchObject({
status: "decreased",
percent: -10,
});
- expect(compare({ current: [total(101)], base: [total(100)] }).gates[0]).toMatchObject({
+ expect(
+ compare({ current: [total(101)], base: [total(100)] }).gates[0],
+ ).toMatchObject({
status: "stable",
percent: 1,
});
@@ -72,13 +85,22 @@ describe("compareBundles", () => {
gateKeys: [APP_GATE, SDK_GATE],
});
- expect(gates[0]).toEqual({ gateKey: APP_GATE, status: "stable", percent: 0 });
+ expect(gates[0]).toEqual({
+ gateKey: APP_GATE,
+ status: "stable",
+ percent: 0,
+ });
expect(gates[1].error).toContain("embedding-sdk-chunked total");
});
it("reports a bundle/kind present on only one side without erroring", () => {
- const { report } = compare({ current: [total(100), appInitial(50)], base: [total(100)] });
+ const { report } = compare({
+ current: [total(100), appInitial(50)],
+ base: [total(100)],
+ });
- expect(report.some(line => line.includes("present only in current build"))).toBe(true);
+ expect(
+ report.some((line) => line.includes("present only in current build")),
+ ).toBe(true);
});
});
diff --git a/.github/scripts/bundle-size-stats-prepare.ts b/.github/scripts/bundle-size-stats-prepare.ts
index 5c5de209870..df2ab5783f9 100644
--- a/.github/scripts/bundle-size-stats-prepare.ts
+++ b/.github/scripts/bundle-size-stats-prepare.ts
@@ -36,7 +36,10 @@ export interface Measurement {
* `brotliBytes` is optional because a point cached before brotli logging
* landed does not carry it — see buildStatsRows' per-row gzip fallback.
*/
-export type CacheRow = Pick<Measurement, "bundle" | "kind" | "rawBytes" | "gzipBytes"> & {
+export type CacheRow = Pick<
+ Measurement,
+ "bundle" | "kind" | "rawBytes" | "gzipBytes"
+> & {
brotliBytes?: number;
};
@@ -65,7 +68,10 @@ export interface BuildStatsRowsResult {
// null, not "", for an absent delta: the stats importer coerces values
// strictly and rejects "" for a numeric column.
-const deltaPercent = (current: number, base: number | undefined | null): number | null =>
+const deltaPercent = (
+ current: number,
+ base: number | undefined | null,
+): number | null =>
base ? Math.round(((current - base) * 10000) / base) / 100 : null;
/**
@@ -97,15 +103,26 @@ export function buildStatsRows({
// Non-null only when BOTH sides carry brotli: a point cached before brotli
// logging landed has none, and that row falls back to the gzip delta.
const baseBrotli =
- measurement.brotliBytes != null && base?.brotliBytes != null ? base.brotliBytes : null;
- const gzipDeltaPercent = deltaPercent(measurement.gzipBytes, base?.gzipBytes);
+ measurement.brotliBytes != null && base?.brotliBytes != null
+ ? base.brotliBytes
+ : null;
+ const gzipDeltaPercent = deltaPercent(
+ measurement.gzipBytes,
+ base?.gzipBytes,
+ );
const brotliDeltaPercent =
- baseBrotli != null ? deltaPercent(measurement.brotliBytes, baseBrotli) : null;
+ baseBrotli != null
+ ? deltaPercent(measurement.brotliBytes, baseBrotli)
+ : null;
if (!base) {
hasNewSeries = true;
} else {
- const servedDeltaPercent = baseBrotli != null ? brotliDeltaPercent : gzipDeltaPercent;
- maxServedDeltaPercent = Math.max(maxServedDeltaPercent, Math.abs(servedDeltaPercent ?? 0));
+ const servedDeltaPercent =
+ baseBrotli != null ? brotliDeltaPercent : gzipDeltaPercent;
+ maxServedDeltaPercent = Math.max(
+ maxServedDeltaPercent,
+ Math.abs(servedDeltaPercent ?? 0),
+ );
}
return {
Date: date,
@@ -122,7 +139,8 @@ export function buildStatsRows({
"File count": measurement.fileCount,
"Raw bytes delta": base ? measurement.rawBytes - base.rawBytes : null,
"Gzip bytes delta": base ? measurement.gzipBytes - base.gzipBytes : null,
- "Brotli bytes delta": baseBrotli != null ? measurement.brotliBytes - baseBrotli : null,
+ "Brotli bytes delta":
+ baseBrotli != null ? measurement.brotliBytes - baseBrotli : null,
"Raw delta %": deltaPercent(measurement.rawBytes, base?.rawBytes),
"Gzip delta %": gzipDeltaPercent,
"Brotli delta %": brotliDeltaPercent,
@@ -130,7 +148,8 @@ export function buildStatsRows({
});
const firstPoint = previous.length === 0;
- const significant = firstPoint || hasNewSeries || maxServedDeltaPercent >= threshold;
+ const significant =
+ firstPoint || hasNewSeries || maxServedDeltaPercent >= threshold;
// Slim rows the next run diffs against. The workflow only persists this to the
// cache when we actually push, so the cached reference always stays the last
@@ -162,8 +181,10 @@ export function buildStatsRows({
};
}
-const readJson = <T,>(filePath: string | undefined): T | null =>
- filePath && existsSync(filePath) ? (JSON.parse(readFileSync(filePath, "utf8")) as T) : null;
+const readJson = <T>(filePath: string | undefined): T | null =>
+ filePath && existsSync(filePath)
+ ? (JSON.parse(readFileSync(filePath, "utf8")) as T)
+ : null;
const writeJson = (filePath: string, value: unknown) => {
mkdirSync(dirname(filePath), { recursive: true });
@@ -181,7 +202,9 @@ const setOutput = (name: string, value: string) => {
function readVersion(versionPropsPath: string | undefined): string {
const raw =
versionPropsPath && existsSync(versionPropsPath)
- ? (readFileSync(versionPropsPath, "utf8").match(/^tag=(.*)$/m)?.[1]?.trim() ?? "")
+ ? (readFileSync(versionPropsPath, "utf8")
+ .match(/^tag=(.*)$/m)?.[1]
+ ?.trim() ?? "")
: "";
return raw === "vUNKNOWN" ? "" : raw;
}
@@ -216,7 +239,9 @@ export function main() {
setOutput("significant", result.significant ? "true" : "false");
setOutput(
"max_delta_percent",
- result.firstPoint || result.hasNewSeries ? "" : result.maxServedDeltaPercent.toFixed(2),
+ result.firstPoint || result.hasNewSeries
+ ? ""
+ : result.maxServedDeltaPercent.toFixed(2),
);
}
diff --git a/.github/scripts/bundle-size-stats-prepare.unit.spec.ts b/.github/scripts/bundle-size-stats-prepare.unit.spec.ts
index 0ed112aab44..8c1f04da00b 100644
--- a/.github/scripts/bundle-size-stats-prepare.unit.spec.ts
+++ b/.github/scripts/bundle-size-stats-prepare.unit.spec.ts
@@ -48,7 +48,15 @@ describe("buildStatsRows", () => {
const result = buildStatsRows({
...meta,
measurements: [measurement({ bundle: "app", kind: "initial" })],
- previous: [{ bundle: "app", kind: "total", rawBytes: 1, gzipBytes: 1, brotliBytes: 1 }],
+ previous: [
+ {
+ bundle: "app",
+ kind: "total",
+ rawBytes: 1,
+ gzipBytes: 1,
+ brotliBytes: 1,
+ },
+ ],
threshold: 99,
});
@@ -93,7 +101,14 @@ describe("buildStatsRows", () => {
...meta,
measurements: [measurement({ gzipBytes: 440, brotliBytes: 300 })], // gzip +10%
// No brotliBytes: this point was cached before brotli logging landed.
- previous: [{ bundle: "embedding-sdk-chunked", kind: "total", rawBytes: 1000, gzipBytes: 400 }],
+ previous: [
+ {
+ bundle: "embedding-sdk-chunked",
+ kind: "total",
+ rawBytes: 1000,
+ gzipBytes: 400,
+ },
+ ],
threshold: 1,
});
diff --git a/.github/scripts/handle-mochawesome-report.js b/.github/scripts/handle-mochawesome-report.js
index dcc61a2a921..f99b6bfec28 100644
--- a/.github/scripts/handle-mochawesome-report.js
+++ b/.github/scripts/handle-mochawesome-report.js
@@ -9,7 +9,7 @@ const collectTestsByType = ({ type, suite, path, cache = [] }) => {
const { [type]: typeList, suites, tests } = suite;
for (const uuid of typeList) {
- const foundTestByUuid = tests.find(test => test.uuid === uuid);
+ const foundTestByUuid = tests.find((test) => test.uuid === uuid);
if (!foundTestByUuid) {
logger.error(`Test with uuid ${uuid} not found`);
throw new Error(`Test with uuid ${uuid} not found`);
@@ -36,7 +36,7 @@ const extractTestResultsInfo = ({ results, stats }) => {
const testType = "failures";
- const failedTests = results.flatMap(result =>
+ const failedTests = results.flatMap((result) =>
collectTestsByType({
type: testType,
suite: result,
@@ -60,7 +60,7 @@ async function generateReport() {
exports.generateReport = generateReport;
function parseReport(report) {
- return extractTestResultsInfo(report).failedTests.map(test => ({
+ return extractTestResultsInfo(report).failedTests.map((test) => ({
title: test.fullTitle,
error: test.err?.message,
path: test.path,
@@ -69,7 +69,7 @@ function parseReport(report) {
exports.parseReport = parseReport;
-const groupTestsByPath = report => {
+const groupTestsByPath = (report) => {
return report.reduce((acc, item) => {
if (!acc[item.path]) {
acc[item.path] = [];
@@ -89,7 +89,7 @@ function formatSummary(report) {
summary += `| ${path} |\n`;
summary += "| :--- |\n";
- tests.forEach(test => {
+ tests.forEach((test) => {
summary += `| ${test.title}`;
summary += "<p></p>"; // adds extra space after title
summary += `<details>`;
diff --git a/.github/scripts/measure-bundle-sizes.js b/.github/scripts/measure-bundle-sizes.js
index c572a011190..a3a9b83ae82 100644
--- a/.github/scripts/measure-bundle-sizes.js
+++ b/.github/scripts/measure-bundle-sizes.js
@@ -22,7 +22,7 @@ const SDK_ROOT = "resources/frontend_client/app/embedding-sdk";
// The chunk runtime is inlined into the bootstrap, never sent as a standalone file.
const SDK_RUNTIME_RE = /embedding-sdk-chunk-runtime\./;
-const notRuntime = name => !SDK_RUNTIME_RE.test(name);
+const notRuntime = (name) => !SDK_RUNTIME_RE.test(name);
// One locale catalogue per chunk, named by the `webpackChunkName: "locale-[request]"`
// comment in localization.ts. A session loads exactly one and an English session
@@ -31,10 +31,10 @@ const notRuntime = name => !SDK_RUNTIME_RE.test(name);
// rather than any code change, so counting them makes every catalogue update look
// like a bundle regression.
const LOCALE_CHUNK_RE = /(^|\/)locale-/;
-const notLocale = name => !LOCALE_CHUNK_RE.test(name);
+const notLocale = (name) => !LOCALE_CHUNK_RE.test(name);
-const assetFiles = (root, names) => names.map(name => path.join(root, name));
-const unique = files => [...new Set(files)];
+const assetFiles = (root, names) => names.map((name) => path.join(root, name));
+const unique = (files) => [...new Set(files)];
// MEASURE_ROOT lets callers point at an extracted tree (e.g. the PR bundle-size
// check measures a current and a base-ref tree); defaults to cwd for the stats
@@ -42,13 +42,15 @@ const unique = files => [...new Set(files)];
// SDK_ASYNC_CHUNKS_LOADABLE (see selectChunkedSdkAssets) toggles whether async
// SDK chunks count toward "total".
function buildConfig(env) {
- const baseDir = env.MEASURE_ROOT ? path.resolve(env.MEASURE_ROOT) : process.cwd();
+ const baseDir = env.MEASURE_ROOT
+ ? path.resolve(env.MEASURE_ROOT)
+ : process.cwd();
const bundleFilter = env.MEASURE_BUNDLES
- ? new Set(env.MEASURE_BUNDLES.split(",").map(bundle => bundle.trim()))
+ ? new Set(env.MEASURE_BUNDLES.split(",").map((bundle) => bundle.trim()))
: null;
return {
resolve: (...relativeParts) => path.resolve(baseDir, ...relativeParts),
- isBundleWanted: bundle => !bundleFilter || bundleFilter.has(bundle),
+ isBundleWanted: (bundle) => !bundleFilter || bundleFilter.has(bundle),
// Async SDK chunks are reachable once output.publicPath is set so import()
// chunks are actually fetched at runtime — which landed in master. Defaults
// to true to match master; set SDK_ASYNC_CHUNKS_LOADABLE=false to measure an
@@ -89,7 +91,7 @@ function collectJsFiles(absolutePath) {
}
return fs
.readdirSync(absolutePath, { withFileTypes: true })
- .flatMap(entry => {
+ .flatMap((entry) => {
const childPath = path.join(absolutePath, entry.name);
if (entry.isDirectory()) {
return collectJsFiles(childPath);
@@ -100,7 +102,9 @@ function collectJsFiles(absolutePath) {
function readStats(config, statsFile) {
const statsPath = config.resolve(statsFile);
- return fs.existsSync(statsPath) ? JSON.parse(fs.readFileSync(statsPath, "utf8")) : null;
+ return fs.existsSync(statsPath)
+ ? JSON.parse(fs.readFileSync(statsPath, "utf8"))
+ : null;
}
// An entrypoint's .js assets for a given field: "assets" = its initial
@@ -111,7 +115,9 @@ function entrypointJsAssets(stats, name, field = "assets") {
if (!entry || !entry[field]) {
return null;
}
- return entry[field].map(asset => asset.name || asset).filter(assetName => assetName.endsWith(".js"));
+ return entry[field]
+ .map((asset) => asset.name || asset)
+ .filter((assetName) => assetName.endsWith(".js"));
}
/**
@@ -125,8 +131,15 @@ function selectAppAssets(stats) {
if (!initialAssets) {
throw new Error('app: stats-main.json / "app-main" entrypoint missing');
}
- const reachableAssets = entrypointJsAssets(stats, "app-main", "reachableAssets");
- return { initialAssets, reachableAssets: reachableAssets?.filter(notLocale) ?? null };
+ const reachableAssets = entrypointJsAssets(
+ stats,
+ "app-main",
+ "reachableAssets",
+ );
+ return {
+ initialAssets,
+ reachableAssets: reachableAssets?.filter(notLocale) ?? null,
+ };
}
/**
@@ -142,7 +155,9 @@ function selectLegacySdkAssets(stats, { sdkAsyncChunksLoadable }) {
if (!initialNames) {
return null;
}
- const reachableNames = entrypointJsAssets(stats, "embedding-sdk", "reachableAssets") || initialNames;
+ const reachableNames =
+ entrypointJsAssets(stats, "embedding-sdk", "reachableAssets") ||
+ initialNames;
const initial = unique(initialNames).filter(notRuntime);
return {
initialNames: initial,
@@ -163,20 +178,36 @@ function selectLegacySdkAssets(stats, { sdkAsyncChunksLoadable }) {
* against a collapsed one (an apples-to-oranges ~30% phantom).
*/
function selectChunkedSdkAssets(stats, { sdkAsyncChunksLoadable }) {
- const chunkedInitial = entrypointJsAssets(stats, "embedding-sdk-chunked", "assets");
+ const chunkedInitial = entrypointJsAssets(
+ stats,
+ "embedding-sdk-chunked",
+ "assets",
+ );
if (!chunkedInitial) {
- throw new Error('embedding-sdk-chunked: stats-embedding-sdk.json / "embedding-sdk-chunked" entrypoint missing');
+ throw new Error(
+ 'embedding-sdk-chunked: stats-embedding-sdk.json / "embedding-sdk-chunked" entrypoint missing',
+ );
}
- const bootstrapInitial = entrypointJsAssets(stats, "embedding-sdk-bootstrap", "assets") || [];
- const chunkedReachableAssets = entrypointJsAssets(stats, "embedding-sdk-chunked", "reachableAssets");
+ const bootstrapInitial =
+ entrypointJsAssets(stats, "embedding-sdk-bootstrap", "assets") || [];
+ const chunkedReachableAssets = entrypointJsAssets(
+ stats,
+ "embedding-sdk-chunked",
+ "reachableAssets",
+ );
const chunkedReachable = chunkedReachableAssets || chunkedInitial;
- const bootstrapReachable = entrypointJsAssets(stats, "embedding-sdk-bootstrap", "reachableAssets") || bootstrapInitial;
+ const bootstrapReachable =
+ entrypointJsAssets(stats, "embedding-sdk-bootstrap", "reachableAssets") ||
+ bootstrapInitial;
return {
- initialNames: unique([...bootstrapInitial, ...chunkedInitial]).filter(notRuntime),
+ initialNames: unique([...bootstrapInitial, ...chunkedInitial]).filter(
+ notRuntime,
+ ),
reachableNames: unique([...bootstrapReachable, ...chunkedReachable])
.filter(notRuntime)
.filter(notLocale),
- includesAsyncChunks: chunkedReachableAssets != null && sdkAsyncChunksLoadable,
+ includesAsyncChunks:
+ chunkedReachableAssets != null && sdkAsyncChunksLoadable,
};
}
@@ -185,33 +216,64 @@ function measureApp(config) {
if (!fs.existsSync(dist)) {
throw new Error(`Bundle output not found for "app": ${dist}`);
}
- const { initialAssets, reachableAssets } = selectAppAssets(readStats(config, "artifacts/stats-main.json"));
+ const { initialAssets, reachableAssets } = selectAppAssets(
+ readStats(config, "artifacts/stats-main.json"),
+ );
if (!reachableAssets) {
- console.warn("app: stats has no reachableAssets; app total falls back to the whole app/dist");
+ console.warn(
+ "app: stats has no reachableAssets; app total falls back to the whole app/dist",
+ );
}
- const totalFiles = reachableAssets ? assetFiles(dist, reachableAssets) : collectJsFiles(dist);
+ const totalFiles = reachableAssets
+ ? assetFiles(dist, reachableAssets)
+ : collectJsFiles(dist);
return [
- { bundle: "app", kind: "initial", ...sizeOf(assetFiles(dist, initialAssets)) },
+ {
+ bundle: "app",
+ kind: "initial",
+ ...sizeOf(assetFiles(dist, initialAssets)),
+ },
{ bundle: "app", kind: "total", ...sizeOf(totalFiles) },
];
}
function measureLegacySdk(config) {
const absRoot = config.resolve(SDK_ROOT);
- const selected = selectLegacySdkAssets(readStats(config, "artifacts/stats-embedding-sdk.json"), config);
+ const selected = selectLegacySdkAssets(
+ readStats(config, "artifacts/stats-embedding-sdk.json"),
+ config,
+ );
if (!selected) {
// No stats / older layout: fall back to whatever sits in the legacy dir.
const candidates = [`${SDK_ROOT}/legacy`, `${SDK_ROOT}.js`];
- const chosen = candidates.find(candidate => fs.existsSync(config.resolve(candidate)));
+ const chosen = candidates.find((candidate) =>
+ fs.existsSync(config.resolve(candidate)),
+ );
if (!chosen) {
- console.warn(`Skipping "embedding-sdk-legacy": output not found (${candidates.join(", ")})`);
+ console.warn(
+ `Skipping "embedding-sdk-legacy": output not found (${candidates.join(", ")})`,
+ );
return [];
}
- return [{ bundle: "embedding-sdk-legacy", kind: "total", ...sizeOf(collectJsFiles(config.resolve(chosen))) }];
+ return [
+ {
+ bundle: "embedding-sdk-legacy",
+ kind: "total",
+ ...sizeOf(collectJsFiles(config.resolve(chosen))),
+ },
+ ];
}
return [
- { bundle: "embedding-sdk-legacy", kind: "initial", ...sizeOf(assetFiles(absRoot, selected.initialNames)) },
- { bundle: "embedding-sdk-legacy", kind: "total", ...sizeOf(assetFiles(absRoot, selected.reachableNames)) },
+ {
+ bundle: "embedding-sdk-legacy",
+ kind: "initial",
+ ...sizeOf(assetFiles(absRoot, selected.initialNames)),
+ },
+ {
+ bundle: "embedding-sdk-legacy",
+ kind: "total",
+ ...sizeOf(assetFiles(absRoot, selected.reachableNames)),
+ },
];
}
@@ -222,34 +284,58 @@ function measureChunkedSdk(config) {
return [];
}
const absRoot = config.resolve(SDK_ROOT);
- const { initialNames, reachableNames, includesAsyncChunks } = selectChunkedSdkAssets(
- readStats(config, "artifacts/stats-embedding-sdk.json"),
- config,
- );
+ const { initialNames, reachableNames, includesAsyncChunks } =
+ selectChunkedSdkAssets(
+ readStats(config, "artifacts/stats-embedding-sdk.json"),
+ config,
+ );
const initial = sizeOf(assetFiles(absRoot, initialNames));
- const total = includesAsyncChunks ? sizeOf(assetFiles(absRoot, reachableNames)) : initial;
+ const total = includesAsyncChunks
+ ? sizeOf(assetFiles(absRoot, reachableNames))
+ : initial;
return [
{ bundle: "embedding-sdk-chunked", kind: "initial", ...initial },
- { bundle: "embedding-sdk-chunked", kind: "total", reachable: includesAsyncChunks, ...total },
+ {
+ bundle: "embedding-sdk-chunked",
+ kind: "total",
+ reachable: includesAsyncChunks,
+ ...total,
+ },
];
}
// Single-file/dir bundles loaded in one shot — total only.
function measureWholeDir(config, bundle, candidates) {
- const chosen = candidates.find(candidate => fs.existsSync(config.resolve(candidate)));
+ const chosen = candidates.find((candidate) =>
+ fs.existsSync(config.resolve(candidate)),
+ );
if (!chosen) {
- console.warn(`Skipping "${bundle}": output not found (${candidates.join(", ")})`);
+ console.warn(
+ `Skipping "${bundle}": output not found (${candidates.join(", ")})`,
+ );
return [];
}
- return [{ bundle, kind: "total", ...sizeOf(collectJsFiles(config.resolve(chosen))) }];
+ return [
+ {
+ bundle,
+ kind: "total",
+ ...sizeOf(collectJsFiles(config.resolve(chosen))),
+ },
+ ];
}
const bundles = {
app: measureApp,
"embedding-sdk-legacy": measureLegacySdk,
"embedding-sdk-chunked": measureChunkedSdk,
- "embedding-sdk-package": config => measureWholeDir(config, "embedding-sdk-package", ["resources/embedding-sdk/dist"]),
- "embed-js": config => measureWholeDir(config, "embed-js", ["resources/frontend_client/app/embed.js"]),
+ "embedding-sdk-package": (config) =>
+ measureWholeDir(config, "embedding-sdk-package", [
+ "resources/embedding-sdk/dist",
+ ]),
+ "embed-js": (config) =>
+ measureWholeDir(config, "embed-js", [
+ "resources/frontend_client/app/embed.js",
+ ]),
};
function measureBundleSizes(config) {
@@ -268,5 +354,7 @@ module.exports = {
};
if (require.main === module) {
- console.log(JSON.stringify(measureBundleSizes(buildConfig(process.env)), null, 2));
+ console.log(
+ JSON.stringify(measureBundleSizes(buildConfig(process.env)), null, 2),
+ );
}
diff --git a/.github/scripts/measure-bundle-sizes.unit.spec.js b/.github/scripts/measure-bundle-sizes.unit.spec.js
index d5bd3794768..b37c9c0594f 100644
--- a/.github/scripts/measure-bundle-sizes.unit.spec.js
+++ b/.github/scripts/measure-bundle-sizes.unit.spec.js
@@ -8,11 +8,13 @@ const {
const RUNTIME = "embedding-sdk-chunk-runtime.deadbeef.js";
const LOCALE = "chunks/locale-fr-json.deadbeef.js";
-const stats = entrypoints => ({ entrypoints });
+const stats = (entrypoints) => ({ entrypoints });
describe("entrypointJsAssets", () => {
it("returns the .js asset names for a field, accepting strings or {name}", () => {
- const s = stats({ app: { assets: [{ name: "a.js" }, "b.js", { name: "c.css" }] } });
+ const s = stats({
+ app: { assets: [{ name: "a.js" }, "b.js", { name: "c.css" }] },
+ });
expect(entrypointJsAssets(s, "app", "assets")).toEqual(["a.js", "b.js"]);
});
@@ -25,7 +27,10 @@ describe("entrypointJsAssets", () => {
describe("selectAppAssets", () => {
it("returns the initial set and a null reachable set on pre-enrichment stats", () => {
const s = stats({ "app-main": { assets: ["main.js"] } });
- expect(selectAppAssets(s)).toEqual({ initialAssets: ["main.js"], reachableAssets: null });
+ expect(selectAppAssets(s)).toEqual({
+ initialAssets: ["main.js"],
+ reachableAssets: null,
+ });
});
it("throws when the app-main entrypoint is missing", () => {
@@ -34,7 +39,10 @@ describe("selectAppAssets", () => {
it("leaves the locale catalogues out of the reachable total", () => {
const s = stats({
- "app-main": { assets: ["main.js"], reachableAssets: ["main.js", "locale-fr-json.abc.js"] },
+ "app-main": {
+ assets: ["main.js"],
+ reachableAssets: ["main.js", "locale-fr-json.abc.js"],
+ },
});
expect(selectAppAssets(s).reachableAssets).toEqual(["main.js"]);
});
@@ -42,52 +50,76 @@ describe("selectAppAssets", () => {
describe("selectChunkedSdkAssets", () => {
const base = {
- "embedding-sdk-chunked": { assets: ["a.js", RUNTIME], reachableAssets: ["a.js", "b.js", RUNTIME] },
- "embedding-sdk-bootstrap": { assets: ["boot.js"], reachableAssets: ["boot.js"] },
+ "embedding-sdk-chunked": {
+ assets: ["a.js", RUNTIME],
+ reachableAssets: ["a.js", "b.js", RUNTIME],
+ },
+ "embedding-sdk-bootstrap": {
+ assets: ["boot.js"],
+ reachableAssets: ["boot.js"],
+ },
};
it("merges bootstrap + chunked, drops the inlined runtime, and counts async chunks", () => {
- const result = selectChunkedSdkAssets(stats(base), { sdkAsyncChunksLoadable: true });
+ const result = selectChunkedSdkAssets(stats(base), {
+ sdkAsyncChunksLoadable: true,
+ });
expect(result.initialNames).toEqual(["boot.js", "a.js"]);
expect(result.reachableNames).toEqual(["boot.js", "a.js", "b.js"]);
expect(result.includesAsyncChunks).toBe(true);
});
it("collapses total to initial when async chunks are not loadable", () => {
- const result = selectChunkedSdkAssets(stats(base), { sdkAsyncChunksLoadable: false });
+ const result = selectChunkedSdkAssets(stats(base), {
+ sdkAsyncChunksLoadable: false,
+ });
expect(result.includesAsyncChunks).toBe(false);
});
it("leaves the locale catalogues out of the reachable total", () => {
const withLocale = {
...base,
- "embedding-sdk-chunked": { assets: ["a.js", RUNTIME], reachableAssets: ["a.js", "b.js", LOCALE, RUNTIME] },
+ "embedding-sdk-chunked": {
+ assets: ["a.js", RUNTIME],
+ reachableAssets: ["a.js", "b.js", LOCALE, RUNTIME],
+ },
};
- const result = selectChunkedSdkAssets(stats(withLocale), { sdkAsyncChunksLoadable: true });
+ const result = selectChunkedSdkAssets(stats(withLocale), {
+ sdkAsyncChunksLoadable: true,
+ });
expect(result.reachableNames).toEqual(["boot.js", "a.js", "b.js"]);
});
it("collapses total to initial when the stats carry no reachable graph", () => {
const noGraph = { "embedding-sdk-chunked": { assets: ["a.js"] } };
- const result = selectChunkedSdkAssets(stats(noGraph), { sdkAsyncChunksLoadable: true });
+ const result = selectChunkedSdkAssets(stats(noGraph), {
+ sdkAsyncChunksLoadable: true,
+ });
expect(result.reachableNames).toEqual(["a.js"]);
expect(result.includesAsyncChunks).toBe(false);
});
it("throws when the chunked entrypoint is missing", () => {
- expect(() => selectChunkedSdkAssets(stats({}), { sdkAsyncChunksLoadable: true })).toThrow(
- "embedding-sdk-chunked",
- );
+ expect(() =>
+ selectChunkedSdkAssets(stats({}), { sdkAsyncChunksLoadable: true }),
+ ).toThrow("embedding-sdk-chunked");
});
});
describe("selectLegacySdkAssets", () => {
it("returns null when the legacy entry is absent so the caller can fall back", () => {
- expect(selectLegacySdkAssets(stats({}), { sdkAsyncChunksLoadable: true })).toBeNull();
+ expect(
+ selectLegacySdkAssets(stats({}), { sdkAsyncChunksLoadable: true }),
+ ).toBeNull();
});
it("expands total to the reachable async set when loadable", () => {
- const s = stats({ "embedding-sdk": { assets: ["legacy.js"], reachableAssets: ["legacy.js", "chunk.js"] } });
+ const s = stats({
+ "embedding-sdk": {
+ assets: ["legacy.js"],
+ reachableAssets: ["legacy.js", "chunk.js"],
+ },
+ });
expect(selectLegacySdkAssets(s, { sdkAsyncChunksLoadable: true })).toEqual({
initialNames: ["legacy.js"],
reachableNames: ["legacy.js", "chunk.js"],
@@ -95,10 +127,17 @@ describe("selectLegacySdkAssets", () => {
});
it("collapses total to initial when async chunks are not loadable", () => {
- const s = stats({ "embedding-sdk": { assets: ["legacy.js"], reachableAssets: ["legacy.js", "chunk.js"] } });
- expect(selectLegacySdkAssets(s, { sdkAsyncChunksLoadable: false })).toEqual({
- initialNames: ["legacy.js"],
- reachableNames: ["legacy.js"],
+ const s = stats({
+ "embedding-sdk": {
+ assets: ["legacy.js"],
+ reachableAssets: ["legacy.js", "chunk.js"],
+ },
});
+ expect(selectLegacySdkAssets(s, { sdkAsyncChunksLoadable: false })).toEqual(
+ {
+ initialNames: ["legacy.js"],
+ reachableNames: ["legacy.js"],
+ },
+ );
});
});
diff --git a/.github/scripts/resolve-coverage-manifest.mjs b/.github/scripts/resolve-coverage-manifest.mjs
index 859fbb2a37f..836f775f747 100644
--- a/.github/scripts/resolve-coverage-manifest.mjs
+++ b/.github/scripts/resolve-coverage-manifest.mjs
@@ -36,7 +36,9 @@ export async function resolveCoverageManifest({
{ owner, repo, name: ARTIFACT_NAME, per_page: 100 },
);
const candidates = artifacts
- .filter((artifact) => !artifact.expired && artifact.workflow_run?.head_sha)
+ .filter(
+ (artifact) => !artifact.expired && artifact.workflow_run?.head_sha,
+ )
.sort(
(a, b) =>
new Date(b.created_at).getTime() - new Date(a.created_at).getTime(),
diff --git a/.github/scripts/stats-import.ts b/.github/scripts/stats-import.ts
index 9cb37ff70f3..1eb69a14308 100644
--- a/.github/scripts/stats-import.ts
+++ b/.github/scripts/stats-import.ts
@@ -64,7 +64,9 @@ async function attemptImport(
});
} catch (networkError) {
const message =
- networkError instanceof Error ? networkError.message : String(networkError);
+ networkError instanceof Error
+ ? networkError.message
+ : String(networkError);
throw new ImportError(message, { retryable: true });
}
@@ -84,7 +86,11 @@ async function attemptImport(
inserted?: number;
ignoredKeys?: string[];
};
- return { success: true, inserted: result.inserted, ignoredKeys: result.ignoredKeys };
+ return {
+ success: true,
+ inserted: result.inserted,
+ ignoredKeys: result.ignoredKeys,
+ };
}
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
@@ -116,7 +122,9 @@ export async function importStats({
}
if (!baseUrl) {
- throw new Error("ENG_STATS_URL is not set, so there is no importer to push to");
+ throw new Error(
+ "ENG_STATS_URL is not set, so there is no importer to push to",
+ );
}
// Tolerate a trailing slash: the origin comes from a hand-entered secret.
diff --git a/.github/scripts/stats-import.unit.spec.ts b/.github/scripts/stats-import.unit.spec.ts
index 5bef73ad531..47c769670c5 100644
--- a/.github/scripts/stats-import.unit.spec.ts
+++ b/.github/scripts/stats-import.unit.spec.ts
@@ -1,6 +1,9 @@
import { importStats } from "./stats-import";
-const ok = (body: unknown = { inserted: 1 }) => ({ ok: true, json: async () => body });
+const ok = (body: unknown = { inserted: 1 }) => ({
+ ok: true,
+ json: async () => body,
+});
const fail = (status: number) => ({
ok: false,
status,
@@ -52,7 +55,9 @@ describe("importStats requests", () => {
const fetchMock = jest.fn();
global.fetch = fetchMock;
- await expect(load({ baseUrl: undefined })).rejects.toThrow("ENG_STATS_URL is not set");
+ await expect(load({ baseUrl: undefined })).rejects.toThrow(
+ "ENG_STATS_URL is not set",
+ );
expect(fetchMock).not.toHaveBeenCalled();
});
@@ -81,7 +86,10 @@ describe("importStats requests", () => {
const fetchMock = jest.fn();
global.fetch = fetchMock;
- await expect(load({ rows: [] })).resolves.toEqual({ success: true, inserted: 0 });
+ await expect(load({ rows: [] })).resolves.toEqual({
+ success: true,
+ inserted: 0,
+ });
expect(fetchMock).not.toHaveBeenCalled();
});
@@ -111,15 +119,22 @@ describe("importStats retries", () => {
.mockResolvedValueOnce(ok());
global.fetch = fetchMock;
- await expect(load({ retries: 2 })).resolves.toMatchObject({ success: true });
+ await expect(load({ retries: 2 })).resolves.toMatchObject({
+ success: true,
+ });
expect(fetchMock).toHaveBeenCalledTimes(3);
});
it("retries throttling", async () => {
- const fetchMock = jest.fn().mockResolvedValueOnce(fail(429)).mockResolvedValueOnce(ok());
+ const fetchMock = jest
+ .fn()
+ .mockResolvedValueOnce(fail(429))
+ .mockResolvedValueOnce(ok());
global.fetch = fetchMock;
- await expect(load({ retries: 2 })).resolves.toMatchObject({ success: true });
+ await expect(load({ retries: 2 })).resolves.toMatchObject({
+ success: true,
+ });
expect(fetchMock).toHaveBeenCalledTimes(2);
});
@@ -130,7 +145,9 @@ describe("importStats retries", () => {
.mockResolvedValueOnce(ok());
global.fetch = fetchMock;
- await expect(load({ retries: 2 })).resolves.toMatchObject({ success: true });
+ await expect(load({ retries: 2 })).resolves.toMatchObject({
+ success: true,
+ });
expect(fetchMock).toHaveBeenCalledTimes(2);
});
diff --git a/.github/scripts/update-pr-with-issues.js b/.github/scripts/update-pr-with-issues.js
index ade915d2817..4b2192b5b22 100644
--- a/.github/scripts/update-pr-with-issues.js
+++ b/.github/scripts/update-pr-with-issues.js
@@ -1,4 +1,4 @@
-const https = require('https');
+const https = require("https");
function getLinkedIssues(body) {
const matches = body.match(
@@ -7,7 +7,7 @@ function getLinkedIssues(body) {
if (matches) {
console.log(`Matches: ${matches}`);
- return matches.map(m => {
+ return matches.map((m) => {
const numberMatch = m.match(/\d+/);
return numberMatch ? numberMatch[0] : null;
});
@@ -20,11 +20,11 @@ function getLinkedIssues(body) {
function httpsRequest(options, data = null) {
return new Promise((resolve, reject) => {
const req = https.request(options, (res) => {
- let responseData = '';
- res.on('data', (chunk) => {
+ let responseData = "";
+ res.on("data", (chunk) => {
responseData += chunk;
});
- res.on('end', () => {
+ res.on("end", () => {
if (res.statusCode >= 200 && res.statusCode < 300) {
try {
resolve(JSON.parse(responseData));
@@ -32,12 +32,16 @@ function httpsRequest(options, data = null) {
resolve(responseData);
}
} else {
- reject(new Error(`Request failed with status code ${res.statusCode}: ${responseData}`));
+ reject(
+ new Error(
+ `Request failed with status code ${res.statusCode}: ${responseData}`,
+ ),
+ );
}
});
});
- req.on('error', (error) => {
+ req.on("error", (error) => {
reject(error);
});
@@ -50,12 +54,13 @@ function httpsRequest(options, data = null) {
}
// Makes an HTTPS request with exponential backoff retry logic
-async function httpsRequestWithBackoff(options, data = null, backoffOptions = {}) {
+async function httpsRequestWithBackoff(
+ options,
+ data = null,
+ backoffOptions = {},
+) {
// Set default backoff options:
- const {
- maxRetries = 8,
- totalDurationSeconds = 60
- } = backoffOptions;
+ const { maxRetries = 8, totalDurationSeconds = 60 } = backoffOptions;
let retries = 0;
let delay = 500; // Start with a .5 second delay
@@ -68,13 +73,16 @@ async function httpsRequestWithBackoff(options, data = null, backoffOptions = {}
const startTime = Date.now();
// Ensure data is stringified if it's an object
- const requestData = data ? (typeof data === 'string' ? data : JSON.stringify(data)) : null;
+ const requestData = data
+ ? typeof data === "string"
+ ? data
+ : JSON.stringify(data)
+ : null;
while (true) {
try {
const response = await httpsRequest(options, requestData);
return response; // Success: Return the data
-
} catch (error) {
retries++;
@@ -83,23 +91,26 @@ async function httpsRequestWithBackoff(options, data = null, backoffOptions = {}
// Stop retrying if we've hit max retries or exceeded the total duration
if (retries >= maxRetries || timeRemaining <= 0) {
- console.error(`Failed after ${retries} retries (${Math.round(elapsedMs/1000)}s elapsed):`);
+ console.error(
+ `Failed after ${retries} retries (${Math.round(elapsedMs / 1000)}s elapsed):`,
+ );
throw error;
}
// Calculate the next delay with exponential backoff and jitter
delay = Math.min(delay * 2 * (0.8 + Math.random() * 0.4), timeRemaining);
- console.log(`Request failed (attempt ${retries}/${maxRetries}). Retrying in ${Math.round(delay)}ms... (${Math.round(timeRemaining/1000)}s remaining)`);
+ console.log(
+ `Request failed (attempt ${retries}/${maxRetries}). Retrying in ${Math.round(delay)}ms... (${Math.round(timeRemaining / 1000)}s remaining)`,
+ );
// Wait for the calculated delay before trying again
- await new Promise(resolve => setTimeout(resolve, delay));
+ await new Promise((resolve) => setTimeout(resolve, delay));
}
}
}
async function link_issues(github) {
-
try {
// Get environment variables
const githubToken = process.env.GITHUB_TOKEN;
@@ -109,25 +120,29 @@ async function link_issues(github) {
const repoName = process.env.REPO_NAME;
if (!githubToken || !linearApiKey || !prNumber || !repoOwner || !repoName) {
- console.error('Missing required environment variables');
+ console.error("Missing required environment variables");
process.exit(1);
}
// Get PR details from GitHub API
- const prInfo = await github.rest.issues.get({
- owner: repoOwner,
- repo: repoName,
- issue_number: prNumber
- }).catch((err) => {
- console.log("error getting prInfo:\n" + err);
- });
+ const prInfo = await github.rest.issues
+ .get({
+ owner: repoOwner,
+ repo: repoName,
+ issue_number: prNumber,
+ })
+ .catch((err) => {
+ console.log("error getting prInfo:\n" + err);
+ });
- console.log('PR Info:\n' + JSON.stringify(prInfo, null, 2) + "\n");
+ console.log("PR Info:\n" + JSON.stringify(prInfo, null, 2) + "\n");
- if (prInfo &&
- prInfo.data &&
- prInfo.data.labels &&
- prInfo.data.labels.some(label => label.name === "no-auto-issue-links")) {
+ if (
+ prInfo &&
+ prInfo.data &&
+ prInfo.data.labels &&
+ prInfo.data.labels.some((label) => label.name === "no-auto-issue-links")
+ ) {
console.log('PR has "no-auto-issue-links" label, skipping...');
return;
}
@@ -145,49 +160,59 @@ async function link_issues(github) {
id
identifier
attachments {
- nodes {url}}}}}}`});
+ nodes {url}}}}}}`,
+ });
- console.log('--- Linear API query ---');
+ console.log("--- Linear API query ---");
console.log(linearQuery);
- console.log('----- End of query -----');
-
- const linearData = await httpsRequestWithBackoff({
- hostname: 'api.linear.app',
- path: '/graphql',
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- 'Authorization': linearApiKey
- }
- },
- linearQuery,
- { maxRetries: 8, totalDurationSeconds: 60 });
-
- console.log('Linear API response:');
+ console.log("----- End of query -----");
+
+ const linearData = await httpsRequestWithBackoff(
+ {
+ hostname: "api.linear.app",
+ path: "/graphql",
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: linearApiKey,
+ },
+ },
+ linearQuery,
+ { maxRetries: 8, totalDurationSeconds: 60 },
+ );
+
+ console.log("Linear API response:");
console.log(JSON.stringify(linearData) + "\n");
- if (!linearData.data || !linearData.data.attachmentsForURL || linearData.data.attachmentsForURL.nodes.length === 0) {
- console.log('No Linear tasks linked to this PR');
+ if (
+ !linearData.data ||
+ !linearData.data.attachmentsForURL ||
+ linearData.data.attachmentsForURL.nodes.length === 0
+ ) {
+ console.log("No Linear tasks linked to this PR");
return;
} else {
- console.log(`Found ${linearData.data.attachmentsForURL.nodes.length} linked Linear tasks`);
+ console.log(
+ `Found ${linearData.data.attachmentsForURL.nodes.length} linked Linear tasks`,
+ );
}
-
// Extract GitHub issue numbers from all attachments in the linked Linear task
const issueNumbers = [];
for (const node of linearData.data.attachmentsForURL.nodes) {
- console.log(`checking node task: ${JSON.stringify(node)}`)
+ console.log(`checking node task: ${JSON.stringify(node)}`);
const linearIssue = node.issue;
for (const attachment of linearIssue.attachments.nodes) {
const url = attachment.url;
- console.log(`--> checking url: ${url}`)
- const match = url.match(/github\.com\/metabase\/metabase\/issues\/(\d+)/);
+ console.log(`--> checking url: ${url}`);
+ const match = url.match(
+ /github\.com\/metabase\/metabase\/issues\/(\d+)/,
+ );
if (match) {
- console.log(`--> found match: ${match[1]}`)
+ console.log(`--> found match: ${match[1]}`);
issueNumbers.push(match[1]);
- console.log("")
+ console.log("");
}
}
}
@@ -195,28 +220,34 @@ async function link_issues(github) {
console.log(`Found linked GitHub issues: ${JSON.stringify(issueNumbers)}`);
if (issueNumbers.length === 0) {
- console.log(`Found linked GitHub issues: ${JSON.stringify(issueNumbers)}`);
- console.log('No GitHub issues linked to the Linear task');
+ console.log(
+ `Found linked GitHub issues: ${JSON.stringify(issueNumbers)}`,
+ );
+ console.log("No GitHub issues linked to the Linear task");
return;
}
- let body = prInfo.data.body || '';
+ let body = prInfo.data.body || "";
let linked_issues = getLinkedIssues(body);
console.log(`Linked issues: ${linked_issues}`);
- let newBody = body || '';
+ let newBody = body || "";
- let issueNumbersToAdd = issueNumbers.filter(num => !linked_issues.includes(num));
+ let issueNumbersToAdd = issueNumbers.filter(
+ (num) => !linked_issues.includes(num),
+ );
console.log(`Issue numbers to add: ${issueNumbersToAdd}`);
if (issueNumbersToAdd.length > 0) {
-
// Generate closing references
- const closingRefs = issueNumbersToAdd.map(num => `closes #${num}`).join(' ');
+ const closingRefs = issueNumbersToAdd
+ .map((num) => `closes #${num}`)
+ .join(" ");
- const messagePreamble = "<!-- Added by 'Add Issue References to PR' GitHub Action. To disable linking, add 'no-auto-issue-links' label to your PR. -->"
+ const messagePreamble =
+ "<!-- Added by 'Add Issue References to PR' GitHub Action. To disable linking, add 'no-auto-issue-links' label to your PR. -->";
newBody = `${messagePreamble} ${closingRefs}\n` + newBody;
@@ -225,17 +256,19 @@ async function link_issues(github) {
owner: repoOwner,
repo: repoName,
issue_number: prNumber,
- body: newBody
+ body: newBody,
});
- console.log(`Updated PR #${prNumber} with issue references:\n ${closingRefs}`);
+ console.log(
+ `Updated PR #${prNumber} with issue references:\n ${closingRefs}`,
+ );
} else {
- console.log('PR already contains all closing references');
+ console.log("PR already contains all closing references");
}
} catch (error) {
- console.error('Error:', error.message);
+ console.error("Error:", error.message);
process.exit(1);
}
}
-module.exports = {link_issues};
+module.exports = { link_issues };
diff --git a/.github/scripts/upload-bundle-size-stats.ts b/.github/scripts/upload-bundle-size-stats.ts
index 47cec1ef15a..b1ad7b9f578 100644
--- a/.github/scripts/upload-bundle-size-stats.ts
+++ b/.github/scripts/upload-bundle-size-stats.ts
@@ -30,7 +30,9 @@ async function main() {
// saved on a successful upload, so this point is re-attempted on the next
// master build and nothing is silently dropped.
const message = error instanceof Error ? error.message : String(error);
- console.log(`::warning::Bundle-size upload failed after retries; leaving run green: ${message}`);
+ console.log(
+ `::warning::Bundle-size upload failed after retries; leaving run green: ${message}`,
+ );
setOutput("uploaded", "false");
}
}
diff --git a/.prettierignore b/.prettierignore
index e18bf239105..25356262e35 100644
--- a/.prettierignore
+++ b/.prettierignore
@@ -6,3 +6,12 @@ docs/api/*
docs/api-documentation.md
frontend/src/embedding-sdk-shared/.storybook/msw-public/mockServiceWorker.js
frontend/test/__support__/custom-viz-fixtures/**/*.js
+
+# typedoc's generated HTML site
+docs/embedding/sdk/api/
+
+# vendored third-party bundle
+resources/frontend_client/app/iframeResizer.js
+
+# a fixture whose exact bytes a test asserts
+test_resources/static_test/app.js
diff --git a/.typedoc/page-custom-styles.css b/.typedoc/page-custom-styles.css
index 9e16df24b1a..f05cfe287c5 100644
--- a/.typedoc/page-custom-styles.css
+++ b/.typedoc/page-custom-styles.css
@@ -48,13 +48,13 @@
}
}
-:root[data-theme='light'] {
+:root[data-theme="light"] {
--color-background: #fafbfe;
--color-background-secondary: #fff;
--color-accent: #e8e8e8;
}
-:root[data-theme='light'] .tsd-signature {
+:root[data-theme="light"] .tsd-signature {
/**
To display code in code-blocks with the same colors both on light and dark themes
*/
@@ -74,9 +74,7 @@
--color-ts-reference: var(--dark-color-ts-reference);
--color-ts-call-signature: var(--dark-color-ts-call-signature);
--color-ts-index-signature: var(--dark-color-ts-index-signature);
- --color-ts-constructor-signature: var(
- --dark-color-ts-constructor-signature
- );
+ --color-ts-constructor-signature: var(--dark-color-ts-constructor-signature);
--color-ts-parameter: var(--dark-color-ts-parameter);
--color-ts-type-parameter: var(--dark-color-ts-type-parameter);
--color-ts-accessor: var(--dark-color-ts-accessor);
@@ -91,7 +89,7 @@
.tsd-toolbar-contents > .title::before {
content: "";
display: inline-block;
- background-image: url('/images/logo.svg');
+ background-image: url("/images/logo.svg");
background-size: contain;
background-repeat: no-repeat;
height: 36px;
@@ -110,7 +108,7 @@
.tsd-signature {
background: #12436e;
- border-radius: .75rem;
+ border-radius: 0.75rem;
color: #fff;
font-family: "Roboto Mono", monospace;
padding: 1.5rem;
diff --git a/.typedoc/typedoc-plugin-not-exported.js b/.typedoc/typedoc-plugin-not-exported.js
index 381784a360a..c0525bf7f94 100644
--- a/.typedoc/typedoc-plugin-not-exported.js
+++ b/.typedoc/typedoc-plugin-not-exported.js
@@ -7,7 +7,9 @@ export function load(app) {
app.converter.on(Converter.EVENT_RESOLVE_END, (context) => {
const project = context.project;
- const intentional = new Set(app.options.getValue("intentionallyNotExported"));
+ const intentional = new Set(
+ app.options.getValue("intentionallyNotExported"),
+ );
for (const id in project.reflections) {
const ref = project.reflections[id];
diff --git a/bin/test-cljs.js b/bin/test-cljs.js
index ca0e7687df2..4dc001efb93 100644
--- a/bin/test-cljs.js
+++ b/bin/test-cljs.js
@@ -4,12 +4,18 @@ const namespace = process.argv[2];
const fs = require("fs");
const debounce = require("lodash.debounce");
-const { spawn } = require('child_process');
+const { spawn } = require("child_process");
const debouncedHandler = debounce((event, filename) => {
console.log(`Change detected: ${event} - ${filename}`);
- const child = spawn('node', namespace?['target/node-tests.js', "--test="+ namespace]:['target/node-tests.js'], { stdio: 'inherit' });
+ const child = spawn(
+ "node",
+ namespace
+ ? ["target/node-tests.js", "--test=" + namespace]
+ : ["target/node-tests.js"],
+ { stdio: "inherit" },
+ );
}, 300);
console.log("Watching target/node-tests.js");
diff --git a/dev/email-preview/sample-contexts.js b/dev/email-preview/sample-contexts.js
index 1ba5f93dcc3..520645482b8 100644
--- a/dev/email-preview/sample-contexts.js
+++ b/dev/email-preview/sample-contexts.js
@@ -59,7 +59,8 @@ window.SAMPLE_CONTEXTS = {
google: false,
nonGoogleSSO: false,
isActive: true,
- passwordResetUrl: "http://localhost:3000/auth/reset_password/a1b2c3d4-e5f6-7890-abcd-ef1234567890",
+ passwordResetUrl:
+ "http://localhost:3000/auth/reset_password/a1b2c3d4-e5f6-7890-abcd-ef1234567890",
adminEmail: "[email protected]",
adminEmailSet: true,
},
@@ -77,11 +78,14 @@ window.SAMPLE_CONTEXTS = {
context: NOTIFICATION_CONTEXT,
payload: {
event_info: {
- details: { invitor: { first_name: "Meredith", email: "[email protected]" } },
+ details: {
+ invitor: { first_name: "Meredith", email: "[email protected]" },
+ },
object: { is_from_setup: false },
},
custom: {
- user_invited_join_url: "http://localhost:3000/auth/join/a1b2c3d4-e5f6-7890",
+ user_invited_join_url:
+ "http://localhost:3000/auth/join/a1b2c3d4-e5f6-7890",
// Set a name here (and optionally invite_target_is_dashboard) to
// preview the "wants to share a question/dashboard" variant.
invite_target_name: "",
@@ -106,7 +110,8 @@ window.SAMPLE_CONTEXTS = {
emailType: "notification",
logoHeader: true,
heading: "We hope you've been enjoying Metabase.",
- callToAction: "Would you mind taking a quick 5 minute survey to tell us how it's going?",
+ callToAction:
+ "Would you mind taking a quick 5 minute survey to tell us how it's going?",
link: "https://metabase.com/feedback/active",
},
@@ -127,7 +132,8 @@ window.SAMPLE_CONTEXTS = {
dashboard: {
id: 12,
name: "Quarterly Revenue Overview",
- description: "<p>Key revenue metrics, refreshed daily for the leadership team.</p>",
+ description:
+ "<p>Key revenue metrics, refreshed daily for the leadership team.</p>",
},
parameters: [
{ id: "a1b2c3d4", name: "Date Range", value: "past30days" },
@@ -139,7 +145,9 @@ window.SAMPLE_CONTEXTS = {
computed: {
icon_cid: "dashboard-icon@metabase", // cid: inline attachment; shows broken in browser
dashboard_has_tabs: false,
- dashboard_content: CARD_PLACEHOLDER("Monthly Orders") + CARD_PLACEHOLDER("Revenue by Region"),
+ dashboard_content:
+ CARD_PLACEHOLDER("Monthly Orders") +
+ CARD_PLACEHOLDER("Revenue by Region"),
filters:
"<table cellpadding='0' cellspacing='0'><tr>" +
"<td style='font-size:12px;color:#949AAB;padding-right:12px;'><strong style='color:#696E7B;'>Date Range:</strong> Past 30 days</td>" +
@@ -155,7 +163,11 @@ window.SAMPLE_CONTEXTS = {
creator: { common_name: "Meredith Palmer" },
payload: {
card: { id: 42, name: "Monthly Orders" },
- notification_card: { send_condition: "goal_above", send_once: true, disable_links: false },
+ notification_card: {
+ send_condition: "goal_above",
+ send_once: true,
+ disable_links: false,
+ },
style: NOTIFICATION_STYLE,
},
computed: {
@@ -194,14 +206,22 @@ window.SAMPLE_CONTEXTS = {
notification_card_you_were_added: {
emailType: "notification",
logoHeader: true,
- payload: { card_id: 42, card: { name: "Monthly Orders" }, send_condition: "has_result" },
+ payload: {
+ card_id: 42,
+ card: { name: "Monthly Orders" },
+ send_condition: "has_result",
+ },
},
notification_card_you_were_removed: {
emailType: "notification",
logoHeader: true,
actor_name: "Meredith Palmer",
- payload: { card_id: 42, card: { name: "Monthly Orders" }, disable_links: false },
+ payload: {
+ card_id: 42,
+ card: { name: "Monthly Orders" },
+ disable_links: false,
+ },
},
card_notification_archived: {
@@ -231,8 +251,16 @@ window.SAMPLE_CONTEXTS = {
{ name: "Product Category", value: "Gadget" },
],
affectedUsers: [
- { "notification-type": "email", recipient: "Meredith Palmer", role: "Dashboard Creator" },
- { "notification-type": "email", recipient: "Oscar Nunez", role: "Subscription Creator" },
+ {
+ "notification-type": "email",
+ recipient: "Meredith Palmer",
+ role: "Dashboard Creator",
+ },
+ {
+ "notification-type": "email",
+ recipient: "Oscar Nunez",
+ role: "Subscription Creator",
+ },
],
},
@@ -260,8 +288,10 @@ window.SAMPLE_CONTEXTS = {
entity_title: "Q3 Planning Notes",
document_href: "/document/87",
comment_href: "/document/87?comment=214",
- parent_comment: "<p>Should we fold the churn analysis into this doc, or keep it separate?</p>",
- comment: "<p>Let's fold it in — I'll add a section under <strong>Retention</strong> this afternoon.</p>",
+ parent_comment:
+ "<p>Should we fold the churn analysis into this doc, or keep it separate?</p>",
+ comment:
+ "<p>Let's fold it in — I'll add a section under <strong>Retention</strong> this afternoon.</p>",
},
},
},
@@ -280,7 +310,8 @@ window.SAMPLE_CONTEXTS = {
severity_label: "Critical",
severity_color: "#E65050",
status_label: "Active",
- security_center_url: "http://localhost:3000/admin/tools/security-center",
+ security_center_url:
+ "http://localhost:3000/admin/tools/security-center",
},
event_info: {
object: {
@@ -288,8 +319,10 @@ window.SAMPLE_CONTEXTS = {
description:
"A vulnerability was identified that could allow specially crafted embedded question parameters " +
"to execute arbitrary SQL against connected databases. Your instance version matches the affected range.",
- remediation: "Upgrade to Metabase 55.8.2 or later, or disable static embedding until you can upgrade.",
- advisory_url: "https://www.metabase.com/security/advisories/MB-2026-0042",
+ remediation:
+ "Upgrade to Metabase 55.8.2 or later, or disable static embedding until you can upgrade.",
+ advisory_url:
+ "https://www.metabase.com/security/advisories/MB-2026-0042",
},
},
},
@@ -315,7 +348,8 @@ window.SAMPLE_CONTEXTS = {
"Investigating slow dashboard loads reported by the customer.\n" +
"Access limited to admin settings and query diagnostics.",
ticket_number: "SUP-18342",
- password_reset_url: "http://localhost:3000/auth/reset_password/a1b2c3d4-e5f6-7890-abcd-ef1234567890",
+ password_reset_url:
+ "http://localhost:3000/auth/reset_password/a1b2c3d4-e5f6-7890-abcd-ef1234567890",
},
},
},
@@ -325,7 +359,8 @@ window.SAMPLE_CONTEXTS = {
errors: [
{
"is-not-first": false,
- error: "Table 'orders_source' not found; it may have been renamed or dropped.",
+ error:
+ "Table 'orders_source' not found; it may have been renamed or dropped.",
"card-id": 42,
"card-name": "Monthly Orders",
"collection-name": "Finance",
@@ -333,7 +368,8 @@ window.SAMPLE_CONTEXTS = {
"last-run-trigger": "Scheduled",
"card-url": "http://localhost:3000/question/42",
"collection-url": "http://localhost:3000/collection/7",
- "caching-log-details-url": "http://localhost:3000/admin/tools/model-caching/101",
+ "caching-log-details-url":
+ "http://localhost:3000/admin/tools/model-caching/101",
},
{
"is-not-first": true,
@@ -345,7 +381,8 @@ window.SAMPLE_CONTEXTS = {
"last-run-trigger": "Scheduled",
"card-url": "http://localhost:3000/question/43",
"collection-url": "http://localhost:3000/collection/7",
- "caching-log-details-url": "http://localhost:3000/admin/tools/model-caching/102",
+ "caching-log-details-url":
+ "http://localhost:3000/admin/tools/model-caching/102",
},
],
},
@@ -362,7 +399,8 @@ window.SAMPLE_CONTEXTS = {
transform_name: "Orders Enriched",
transform_href: "http://localhost:3000/admin/transforms/15/runs",
message: {
- first_line: 'Column "discount_pct" does not exist in source table.',
+ first_line:
+ 'Column "discount_pct" does not exist in source table.',
details: [
"at stage 2 of 3 (join with promotions)",
"last successful run: July 9, 2026, 2:00 AM",
@@ -372,7 +410,10 @@ window.SAMPLE_CONTEXTS = {
{
transform_name: "Customer LTV Rollup",
transform_href: "http://localhost:3000/admin/transforms/16/runs",
- message: { first_line: "Query timed out after 600 seconds.", details: [] },
+ message: {
+ first_line: "Query timed out after 600 seconds.",
+ details: [],
+ },
},
],
},
@@ -391,7 +432,8 @@ window.SAMPLE_CONTEXTS = {
job_name: "Nightly Warehouse Refresh",
job_href: "http://localhost:3000/admin/transforms/jobs/7",
failure_count: 3,
- latest_error: 'Column "discount_pct" does not exist in source table.',
+ latest_error:
+ 'Column "discount_pct" does not exist in source table.',
},
{
job_name: "Hourly Events Rollup",
diff --git a/dev/email-preview/serve.ts b/dev/email-preview/serve.ts
index ee571c48cda..9b917ba34e6 100644
--- a/dev/email-preview/serve.ts
+++ b/dev/email-preview/serve.ts
@@ -49,12 +49,16 @@ const server = Bun.serve({
const url = `http://localhost:${server.port}/`;
console.log(`📧 Email template preview → ${url}`);
-console.log(` Templates: src/metabase/channel/email/*.hbs (edits reload live)`);
+console.log(
+ ` Templates: src/metabase/channel/email/*.hbs (edits reload live)`,
+);
if (!process.env.EMAIL_DEV_NO_OPEN) {
const opener =
- process.platform === "darwin" ? "open"
- : process.platform === "win32" ? "start"
- : "xdg-open";
+ process.platform === "darwin"
+ ? "open"
+ : process.platform === "win32"
+ ? "start"
+ : "xdg-open";
Bun.spawn([opener, url], { stdout: "ignore", stderr: "ignore" });
}
diff --git a/dev/resources/dev/module_explorer_state.js b/dev/resources/dev/module_explorer_state.js
index 7035e89e78b..4be9b01ee92 100644
--- a/dev/resources/dev/module_explorer_state.js
+++ b/dev/resources/dev/module_explorer_state.js
@@ -1,37 +1,47 @@
function encodeExplorerState(state) {
const params = new URLSearchParams();
- if (state.selected) params.set('m', state.selected);
- if (state.view !== 'tree') params.set('view', state.view);
- if (state.focus.size) params.set('focus', [...state.focus].sort().join(','));
- else if (state.view === 'graph') params.set('focus', '');
- if (state.degree !== 1) params.set('deg', state.degree);
- if (state.expanded.size) params.set('exp', [...state.expanded].sort().join(','));
- if (state.hidden.size) params.set('hide', [...state.hidden].sort().join(','));
- if (state.hideRe) params.set('hre', state.hideRe);
- for (const team of [...state.teams].sort()) params.append('team', team);
+ if (state.selected) params.set("m", state.selected);
+ if (state.view !== "tree") params.set("view", state.view);
+ if (state.focus.size) params.set("focus", [...state.focus].sort().join(","));
+ else if (state.view === "graph") params.set("focus", "");
+ if (state.degree !== 1) params.set("deg", state.degree);
+ if (state.expanded.size)
+ params.set("exp", [...state.expanded].sort().join(","));
+ if (state.hidden.size) params.set("hide", [...state.hidden].sort().join(","));
+ if (state.hideRe) params.set("hre", state.hideRe);
+ for (const team of [...state.teams].sort()) params.append("team", team);
return params.toString();
}
function decodeExplorerState(hash, validIds, validTeams) {
- const raw = hash.replace(/^#/, '');
- const params = new URLSearchParams(raw.includes('=') ? raw : (raw ? 'm=' + raw : ''));
- const ids = key => (params.get(key) || '').split(',').filter(id => validIds.has(id));
- const requestedView = params.get('view');
- const requestedDegree = Number.parseInt(params.get('deg'), 10);
- const selected = validIds.has(params.get('m')) ? params.get('m') : null;
+ const raw = hash.replace(/^#/, "");
+ const params = new URLSearchParams(
+ raw.includes("=") ? raw : raw ? "m=" + raw : "",
+ );
+ const ids = (key) =>
+ (params.get(key) || "").split(",").filter((id) => validIds.has(id));
+ const requestedView = params.get("view");
+ const requestedDegree = Number.parseInt(params.get("deg"), 10);
+ const selected = validIds.has(params.get("m")) ? params.get("m") : null;
return {
selected,
- view: ['hotspots', 'cycles', 'graph'].includes(requestedView) ? requestedView : 'tree',
- focus: new Set(ids('focus')),
- focusSpecified: params.has('focus'),
- degree: Number.isNaN(requestedDegree) ? 1 : Math.min(3, Math.max(0, requestedDegree)),
- expanded: new Set(ids('exp')),
- hidden: new Set(ids('hide')),
- hideRe: params.get('hre') || '',
- teams: new Set(params.getAll('team').filter(team => validTeams.has(team))),
+ view: ["hotspots", "cycles", "graph"].includes(requestedView)
+ ? requestedView
+ : "tree",
+ focus: new Set(ids("focus")),
+ focusSpecified: params.has("focus"),
+ degree: Number.isNaN(requestedDegree)
+ ? 1
+ : Math.min(3, Math.max(0, requestedDegree)),
+ expanded: new Set(ids("exp")),
+ hidden: new Set(ids("hide")),
+ hideRe: params.get("hre") || "",
+ teams: new Set(
+ params.getAll("team").filter((team) => validTeams.has(team)),
+ ),
};
}
-if (typeof module === 'object' && module.exports) {
- module.exports = {decodeExplorerState, encodeExplorerState};
+if (typeof module === "object" && module.exports) {
+ module.exports = { decodeExplorerState, encodeExplorerState };
}
diff --git a/docs/embedding/sdk/snippets/actions/basic.tsx b/docs/embedding/sdk/snippets/actions/basic.tsx
index 4906aa3ce67..922ae1680f7 100644
--- a/docs/embedding/sdk/snippets/actions/basic.tsx
+++ b/docs/embedding/sdk/snippets/actions/basic.tsx
@@ -1,10 +1,9 @@
-import { useState } from "react";
-
import {
MetabaseProvider,
defineMetabaseAuthConfig,
useAction,
} from "@metabase/embedding-sdk-react";
+import { useState } from "react";
const authConfig = defineMetabaseAuthConfig({
metabaseInstanceUrl: "https://your-metabase.example.com",
diff --git a/docs/embedding/sdk/snippets/actions/date-picker.tsx b/docs/embedding/sdk/snippets/actions/date-picker.tsx
index e272404ce6d..addcf22e652 100644
--- a/docs/embedding/sdk/snippets/actions/date-picker.tsx
+++ b/docs/embedding/sdk/snippets/actions/date-picker.tsx
@@ -1,10 +1,9 @@
-import { useState } from "react";
-
import {
MetabaseProvider,
defineMetabaseAuthConfig,
useAction,
} from "@metabase/embedding-sdk-react";
+import { useState } from "react";
const authConfig = defineMetabaseAuthConfig({
metabaseInstanceUrl: "https://your-metabase.example.com",
diff --git a/docs/embedding/sdk/snippets/actions/parallel-refresh.tsx b/docs/embedding/sdk/snippets/actions/parallel-refresh.tsx
index 6f73a5ce5d2..346b4ff69ab 100644
--- a/docs/embedding/sdk/snippets/actions/parallel-refresh.tsx
+++ b/docs/embedding/sdk/snippets/actions/parallel-refresh.tsx
@@ -1,11 +1,10 @@
-import { useState } from "react";
-
import {
InteractiveQuestion,
MetabaseProvider,
defineMetabaseAuthConfig,
useAction,
} from "@metabase/embedding-sdk-react";
+import { useState } from "react";
const authConfig = defineMetabaseAuthConfig({
metabaseInstanceUrl: "https://your-metabase.example.com",
diff --git a/docs/embedding/sdk/snippets/actions/parameter-values.tsx b/docs/embedding/sdk/snippets/actions/parameter-values.tsx
index 161a45dfdc1..2c55a8a9918 100644
--- a/docs/embedding/sdk/snippets/actions/parameter-values.tsx
+++ b/docs/embedding/sdk/snippets/actions/parameter-values.tsx
@@ -19,8 +19,9 @@ type CreatePersonParameters = {
};
function CreatePersonButton() {
- const { execute } =
- useAction<CreatePersonParameters>(CREATE_PERSON_ACTION_ID);
+ const { execute } = useAction<CreatePersonParameters>(
+ CREATE_PERSON_ACTION_ID,
+ );
const onClick = async () => {
// [<snippet primitives-and-dates>]
diff --git a/docs/embedding/sdk/snippets/actions/with-refresh.tsx b/docs/embedding/sdk/snippets/actions/with-refresh.tsx
index 8d70ece2cb9..033e47e26b5 100644
--- a/docs/embedding/sdk/snippets/actions/with-refresh.tsx
+++ b/docs/embedding/sdk/snippets/actions/with-refresh.tsx
@@ -1,11 +1,10 @@
-import { useState } from "react";
-
import {
InteractiveQuestion,
MetabaseProvider,
defineMetabaseAuthConfig,
useAction,
} from "@metabase/embedding-sdk-react";
+import { useState } from "react";
const authConfig = defineMetabaseAuthConfig({
metabaseInstanceUrl: "https://your-metabase.example.com",
diff --git a/docs/embedding/sdk/snippets/authentication/express-server.ts b/docs/embedding/sdk/snippets/authentication/express-server.ts
index a2c12d1bab0..4024f41c714 100644
--- a/docs/embedding/sdk/snippets/authentication/express-server.ts
+++ b/docs/embedding/sdk/snippets/authentication/express-server.ts
@@ -1,5 +1,5 @@
-import express from "express";
import cors from "cors";
+import express from "express";
import session from "express-session";
import jwt from "jsonwebtoken";
import fetch from "node-fetch";
diff --git a/docs/embedding/sdk/snippets/collections/collection-browser-click.tsx b/docs/embedding/sdk/snippets/collections/collection-browser-click.tsx
index 27b552935c0..a334f3e487b 100644
--- a/docs/embedding/sdk/snippets/collections/collection-browser-click.tsx
+++ b/docs/embedding/sdk/snippets/collections/collection-browser-click.tsx
@@ -1,10 +1,10 @@
-import React, { useState } from "react";
import {
CollectionBrowser,
InteractiveDashboard,
InteractiveQuestion,
type MetabaseCollectionItem,
} from "@metabase/embedding-sdk-react";
+import React, { useState } from "react";
export default function BrowseAndOpen() {
const [dashboardId, setDashboardId] = useState<number | null>(null);
diff --git a/docs/embedding/sdk/snippets/collections/collection-browser.tsx b/docs/embedding/sdk/snippets/collections/collection-browser.tsx
index badb4a7eecd..47dc4940b85 100644
--- a/docs/embedding/sdk/snippets/collections/collection-browser.tsx
+++ b/docs/embedding/sdk/snippets/collections/collection-browser.tsx
@@ -1,9 +1,9 @@
-import React from "react";
import {
CollectionBrowser,
MetabaseProvider,
defineMetabaseAuthConfig,
} from "@metabase/embedding-sdk-react";
+import React from "react";
const authConfig = defineMetabaseAuthConfig({
metabaseInstanceUrl: "https://your-metabase.example.com",
diff --git a/docs/embedding/sdk/snippets/config/config-base.tsx b/docs/embedding/sdk/snippets/config/config-base.tsx
index 3abdd007718..510b19c4289 100644
--- a/docs/embedding/sdk/snippets/config/config-base.tsx
+++ b/docs/embedding/sdk/snippets/config/config-base.tsx
@@ -1,9 +1,9 @@
-import React from "react";
import {
MetabaseProvider,
StaticDashboard,
defineMetabaseAuthConfig,
} from "@metabase/embedding-sdk-react";
+import React from "react";
const authConfig = defineMetabaseAuthConfig({
metabaseInstanceUrl: "https://your-metabase.example.com", // Required
diff --git a/docs/embedding/sdk/snippets/config/config-with-custom-visualizations.tsx b/docs/embedding/sdk/snippets/config/config-with-custom-visualizations.tsx
index eda95fe2444..2ced78aac93 100644
--- a/docs/embedding/sdk/snippets/config/config-with-custom-visualizations.tsx
+++ b/docs/embedding/sdk/snippets/config/config-with-custom-visualizations.tsx
@@ -1,8 +1,8 @@
-import type { PropsWithChildren } from "react";
import {
type MetabaseAuthConfig,
MetabaseProvider,
} from "@metabase/embedding-sdk-react";
+import type { PropsWithChildren } from "react";
const authConfig = {} as MetabaseAuthConfig;
diff --git a/docs/embedding/sdk/snippets/config/config-with-event-handlers.tsx b/docs/embedding/sdk/snippets/config/config-with-event-handlers.tsx
index 7b71ef81da2..71e22e866a5 100644
--- a/docs/embedding/sdk/snippets/config/config-with-event-handlers.tsx
+++ b/docs/embedding/sdk/snippets/config/config-with-event-handlers.tsx
@@ -1,9 +1,9 @@
-import type { PropsWithChildren } from "react";
import {
type MetabaseAuthConfig,
MetabaseProvider,
type SdkDashboardLoadEvent,
} from "@metabase/embedding-sdk-react";
+import type { PropsWithChildren } from "react";
const authConfig = {} as MetabaseAuthConfig;
diff --git a/docs/embedding/sdk/snippets/config/config-with-locale.tsx b/docs/embedding/sdk/snippets/config/config-with-locale.tsx
index dd5a263edfd..1e63966b987 100644
--- a/docs/embedding/sdk/snippets/config/config-with-locale.tsx
+++ b/docs/embedding/sdk/snippets/config/config-with-locale.tsx
@@ -1,8 +1,8 @@
-import type { PropsWithChildren } from "react";
import {
type MetabaseAuthConfig,
MetabaseProvider,
} from "@metabase/embedding-sdk-react";
+import type { PropsWithChildren } from "react";
const authConfig = {} as MetabaseAuthConfig;
diff --git a/docs/embedding/sdk/snippets/config/config-with-plugins.tsx b/docs/embedding/sdk/snippets/config/config-with-plugins.tsx
index 91c6f1e074e..d85c75c9122 100644
--- a/docs/embedding/sdk/snippets/config/config-with-plugins.tsx
+++ b/docs/embedding/sdk/snippets/config/config-with-plugins.tsx
@@ -1,8 +1,8 @@
-import type { PropsWithChildren } from "react";
import {
type MetabaseAuthConfig,
MetabaseProvider,
} from "@metabase/embedding-sdk-react";
+import type { PropsWithChildren } from "react";
const authConfig = {} as MetabaseAuthConfig;
diff --git a/docs/embedding/sdk/snippets/config/config-with-theme.tsx b/docs/embedding/sdk/snippets/config/config-with-theme.tsx
index 6be1df0c206..d0a87ed952e 100644
--- a/docs/embedding/sdk/snippets/config/config-with-theme.tsx
+++ b/docs/embedding/sdk/snippets/config/config-with-theme.tsx
@@ -1,9 +1,9 @@
-import type { PropsWithChildren } from "react";
import {
type MetabaseAuthConfig,
MetabaseProvider,
defineMetabaseTheme,
} from "@metabase/embedding-sdk-react";
+import type { PropsWithChildren } from "react";
const authConfig = {} as MetabaseAuthConfig;
diff --git a/docs/embedding/sdk/snippets/config/reload-metabase-provider.tsx b/docs/embedding/sdk/snippets/config/reload-metabase-provider.tsx
index 41e2a72dd06..1a3fa25bb69 100644
--- a/docs/embedding/sdk/snippets/config/reload-metabase-provider.tsx
+++ b/docs/embedding/sdk/snippets/config/reload-metabase-provider.tsx
@@ -1,5 +1,5 @@
-import { useState } from "react";
import { InteractiveQuestion } from "@metabase/embedding-sdk-react";
+import { useState } from "react";
const yourQuestionId = 1;
const order = {};
diff --git a/docs/embedding/sdk/snippets/dashboards/create-dashboard.tsx b/docs/embedding/sdk/snippets/dashboards/create-dashboard.tsx
index ee458e3f0c7..29438a02a94 100644
--- a/docs/embedding/sdk/snippets/dashboards/create-dashboard.tsx
+++ b/docs/embedding/sdk/snippets/dashboards/create-dashboard.tsx
@@ -1,10 +1,10 @@
-import { useState } from "react";
import {
CreateDashboardModal,
EditableDashboard,
type MetabaseDashboard,
useCreateDashboardApi,
} from "@metabase/embedding-sdk-react";
+import { useState } from "react";
const ExampleHook = () => {
const options = {
diff --git a/docs/embedding/sdk/snippets/dashboards/editable-dashboard-data-picker.tsx b/docs/embedding/sdk/snippets/dashboards/editable-dashboard-data-picker.tsx
index 30534295762..a44954b2b4b 100644
--- a/docs/embedding/sdk/snippets/dashboards/editable-dashboard-data-picker.tsx
+++ b/docs/embedding/sdk/snippets/dashboards/editable-dashboard-data-picker.tsx
@@ -1,5 +1,5 @@
-import React from "react";
import { EditableDashboard } from "@metabase/embedding-sdk-react";
+import React from "react";
export default function TablesOnlyDashboard() {
const dashboardId = 1; // This is the dashboard ID you want to embed
diff --git a/docs/embedding/sdk/snippets/dashboards/editable-dashboard.tsx b/docs/embedding/sdk/snippets/dashboards/editable-dashboard.tsx
index 0b2e6c44cb4..336c87b54e4 100644
--- a/docs/embedding/sdk/snippets/dashboards/editable-dashboard.tsx
+++ b/docs/embedding/sdk/snippets/dashboards/editable-dashboard.tsx
@@ -1,9 +1,9 @@
-import React from "react";
import {
EditableDashboard,
MetabaseProvider,
defineMetabaseAuthConfig,
} from "@metabase/embedding-sdk-react";
+import React from "react";
const authConfig = defineMetabaseAuthConfig({
metabaseInstanceUrl: "https://your-metabase.example.com",
diff --git a/docs/embedding/sdk/snippets/dashboards/interactive-dashboard.tsx b/docs/embedding/sdk/snippets/dashboards/interactive-dashboard.tsx
index d250c10ee67..0cf273d4a1b 100644
--- a/docs/embedding/sdk/snippets/dashboards/interactive-dashboard.tsx
+++ b/docs/embedding/sdk/snippets/dashboards/interactive-dashboard.tsx
@@ -1,9 +1,9 @@
-import React from "react";
import {
InteractiveDashboard,
MetabaseProvider,
defineMetabaseAuthConfig,
} from "@metabase/embedding-sdk-react";
+import React from "react";
const authConfig = defineMetabaseAuthConfig({
metabaseInstanceUrl: "https://your-metabase.example.com",
diff --git a/docs/embedding/sdk/snippets/dashboards/static-dashboard.tsx b/docs/embedding/sdk/snippets/dashboards/static-dashboard.tsx
index 6ec13b91cbf..48f20c88a13 100644
--- a/docs/embedding/sdk/snippets/dashboards/static-dashboard.tsx
+++ b/docs/embedding/sdk/snippets/dashboards/static-dashboard.tsx
@@ -1,9 +1,9 @@
-import React from "react";
import {
MetabaseProvider,
StaticDashboard,
defineMetabaseAuthConfig,
} from "@metabase/embedding-sdk-react";
+import React from "react";
const authConfig = defineMetabaseAuthConfig({
metabaseInstanceUrl: "https://your-metabase.example.com",
diff --git a/docs/embedding/sdk/snippets/next-js/pages-router-authentication-api-route.ts b/docs/embedding/sdk/snippets/next-js/pages-router-authentication-api-route.ts
index 1db32b7dac1..c86c3c28c31 100644
--- a/docs/embedding/sdk/snippets/next-js/pages-router-authentication-api-route.ts
+++ b/docs/embedding/sdk/snippets/next-js/pages-router-authentication-api-route.ts
@@ -1,6 +1,6 @@
+import jwt from "jsonwebtoken";
// [<snippet imports>]
import type { NextApiRequest, NextApiResponse } from "next";
-import jwt from "jsonwebtoken";
// [<endsnippet imports>]
const user = {
diff --git a/docs/embedding/sdk/snippets/plugins/global-plugins.tsx b/docs/embedding/sdk/snippets/plugins/global-plugins.tsx
index a1dedcceeaf..af7d598b3ef 100644
--- a/docs/embedding/sdk/snippets/plugins/global-plugins.tsx
+++ b/docs/embedding/sdk/snippets/plugins/global-plugins.tsx
@@ -1,9 +1,9 @@
-import type { PropsWithChildren } from "react";
import {
type MetabaseAuthConfig,
MetabaseProvider,
type MetabaseTheme,
} from "@metabase/embedding-sdk-react";
+import type { PropsWithChildren } from "react";
const authConfig = {} as MetabaseAuthConfig;
const theme = {} as MetabaseTheme;
diff --git a/docs/embedding/sdk/snippets/questions/ai-question.tsx b/docs/embedding/sdk/snippets/questions/ai-question.tsx
index 5ac0ac01b26..7ab80cc853e 100644
--- a/docs/embedding/sdk/snippets/questions/ai-question.tsx
+++ b/docs/embedding/sdk/snippets/questions/ai-question.tsx
@@ -1,9 +1,9 @@
-import React from "react";
import {
MetabotQuestion,
MetabaseProvider,
defineMetabaseAuthConfig,
} from "@metabase/embedding-sdk-react";
+import React from "react";
const authConfig = defineMetabaseAuthConfig({
metabaseInstanceUrl: "https://your-metabase.example.com",
@@ -16,4 +16,3 @@ export default function App() {
</MetabaseProvider>
);
}
-
diff --git a/docs/embedding/sdk/snippets/questions/disable-question-save.tsx b/docs/embedding/sdk/snippets/questions/disable-question-save.tsx
index 3b45f3d6d0b..668e9a34d27 100644
--- a/docs/embedding/sdk/snippets/questions/disable-question-save.tsx
+++ b/docs/embedding/sdk/snippets/questions/disable-question-save.tsx
@@ -1,9 +1,9 @@
-import React from "react";
import {
InteractiveQuestion,
MetabaseProvider,
defineMetabaseAuthConfig,
} from "@metabase/embedding-sdk-react";
+import React from "react";
const authConfig = defineMetabaseAuthConfig({
metabaseInstanceUrl: "https://your-metabase.example.com",
diff --git a/docs/embedding/sdk/snippets/questions/interactive-question.tsx b/docs/embedding/sdk/snippets/questions/interactive-question.tsx
index 826aad5ebb0..6cfb9a0a642 100644
--- a/docs/embedding/sdk/snippets/questions/interactive-question.tsx
+++ b/docs/embedding/sdk/snippets/questions/interactive-question.tsx
@@ -1,9 +1,9 @@
-import React from "react";
import {
InteractiveQuestion,
MetabaseProvider,
defineMetabaseAuthConfig,
} from "@metabase/embedding-sdk-react";
+import React from "react";
const authConfig = defineMetabaseAuthConfig({
metabaseInstanceUrl: "https://your-metabase.example.com",
diff --git a/docs/embedding/sdk/snippets/questions/new-native-question.tsx b/docs/embedding/sdk/snippets/questions/new-native-question.tsx
index b3e6575c6f2..6f79e5cc9b1 100644
--- a/docs/embedding/sdk/snippets/questions/new-native-question.tsx
+++ b/docs/embedding/sdk/snippets/questions/new-native-question.tsx
@@ -1,9 +1,9 @@
-import React from "react";
import {
InteractiveQuestion,
MetabaseProvider,
defineMetabaseAuthConfig,
} from "@metabase/embedding-sdk-react";
+import React from "react";
const authConfig = defineMetabaseAuthConfig({
metabaseInstanceUrl: "https://your-metabase.example.com",
@@ -15,4 +15,4 @@ export default function App() {
<InteractiveQuestion questionId="new-native" />
</MetabaseProvider>
);
-}
\ No newline at end of file
+}
diff --git a/docs/embedding/sdk/snippets/questions/new-question.tsx b/docs/embedding/sdk/snippets/questions/new-question.tsx
index 6420401ae1b..5e249b55d4e 100644
--- a/docs/embedding/sdk/snippets/questions/new-question.tsx
+++ b/docs/embedding/sdk/snippets/questions/new-question.tsx
@@ -1,9 +1,9 @@
-import React from "react";
import {
InteractiveQuestion,
MetabaseProvider,
defineMetabaseAuthConfig,
} from "@metabase/embedding-sdk-react";
+import React from "react";
const authConfig = defineMetabaseAuthConfig({
metabaseInstanceUrl: "https://your-metabase.example.com",
diff --git a/docs/embedding/sdk/snippets/questions/static-question.tsx b/docs/embedding/sdk/snippets/questions/static-question.tsx
index c1ec39ec872..5a4e4e59088 100644
--- a/docs/embedding/sdk/snippets/questions/static-question.tsx
+++ b/docs/embedding/sdk/snippets/questions/static-question.tsx
@@ -1,9 +1,9 @@
-import React from "react";
import {
MetabaseProvider,
StaticQuestion,
defineMetabaseAuthConfig,
} from "@metabase/embedding-sdk-react";
+import React from "react";
const authConfig = defineMetabaseAuthConfig({
metabaseInstanceUrl: "https://your-metabase.example.com",
diff --git a/docs/embedding/sdk/snippets/questions/use-metabot-dedicated-chart.tsx b/docs/embedding/sdk/snippets/questions/use-metabot-dedicated-chart.tsx
index 843d5dd8a93..01c7fc12a85 100644
--- a/docs/embedding/sdk/snippets/questions/use-metabot-dedicated-chart.tsx
+++ b/docs/embedding/sdk/snippets/questions/use-metabot-dedicated-chart.tsx
@@ -1,9 +1,9 @@
-import React, { useState } from "react";
import {
MetabaseProvider,
defineMetabaseAuthConfig,
useMetabot,
} from "@metabase/embedding-sdk-react";
+import React, { useState } from "react";
const authConfig = defineMetabaseAuthConfig({
metabaseInstanceUrl: "https://your-metabase.example.com",
diff --git a/docs/embedding/sdk/snippets/questions/use-metabot-inline-charts.tsx b/docs/embedding/sdk/snippets/questions/use-metabot-inline-charts.tsx
index daafb0dc236..16a45a855b7 100644
--- a/docs/embedding/sdk/snippets/questions/use-metabot-inline-charts.tsx
+++ b/docs/embedding/sdk/snippets/questions/use-metabot-inline-charts.tsx
@@ -1,9 +1,9 @@
-import React, { useState } from "react";
import {
MetabaseProvider,
defineMetabaseAuthConfig,
useMetabot,
} from "@metabase/embedding-sdk-react";
+import React, { useState } from "react";
const authConfig = defineMetabaseAuthConfig({
metabaseInstanceUrl: "https://your-metabase.example.com",
diff --git a/docs/util/generate-shortcuts-docs.ts b/docs/util/generate-shortcuts-docs.ts
index 563e3ed2e25..5153238e813 100644
--- a/docs/util/generate-shortcuts-docs.ts
+++ b/docs/util/generate-shortcuts-docs.ts
@@ -1,8 +1,9 @@
-import fs from 'fs';
-import path from 'path';
-import prettier from 'prettier';
+import fs from "fs";
+import path from "path";
-import { shortcuts } from '../../frontend/src/metabase/palette/shortcuts';
+import prettier from "prettier";
+
+import { shortcuts } from "../../frontend/src/metabase/palette/shortcuts";
interface Shortcut {
name: string;
@@ -19,50 +20,56 @@ interface DocsConfig {
function formatShortcutKey(key: string): string {
if (key.length === 3) {
- key = key.replace(" ", " > ")
+ key = key.replace(" ", " > ");
}
- return key.replace('$mod', 'Ctrl/Cmd');
+ return key.replace("$mod", "Ctrl/Cmd");
}
function formatShortcutDisplay(shortcut: Shortcut): string {
const keys = shortcut.shortcutDisplay || shortcut.shortcut;
- return keys.map(formatShortcutKey).join(', ');
+ return keys.map(formatShortcutKey).join(", ");
}
-function generateMarkdownTable(shortcuts: Record<string, Shortcut>, group: string): string {
+function generateMarkdownTable(
+ shortcuts: Record<string, Shortcut>,
+ group: string,
+): string {
const groupShortcuts = Object.entries(shortcuts)
.filter(([_, shortcut]) => shortcut.shortcutGroup === group)
.map(([_, shortcut]) => ({
name: shortcut.name,
- shortcut: formatShortcutDisplay(shortcut)
+ shortcut: formatShortcutDisplay(shortcut),
}));
- if (groupShortcuts.length === 0) return '';
+ if (groupShortcuts.length === 0) return "";
const groupTitle = group.charAt(0).toUpperCase() + group.slice(1);
-
+
const tableRows = groupShortcuts
.map(({ name, shortcut }) => `| ${name} | ${shortcut} |`)
- .join('\n');
+ .join("\n");
return `## ${groupTitle}\n\n| Action | Shortcut |\n| ------ | -------- |\n${tableRows}\n\n`;
}
function readIntroduction(introPath: string): string {
try {
- return fs.readFileSync(introPath, 'utf8');
+ return fs.readFileSync(introPath, "utf8");
} catch (error) {
throw new Error(`Failed to read introduction file: ${error.message}`);
}
}
-async function writeDocumentation(content: string, outputPath: string): Promise<void> {
+async function writeDocumentation(
+ content: string,
+ outputPath: string,
+): Promise<void> {
try {
const formattedContent = await prettier.format(content, {
- parser: 'markdown',
- proseWrap: 'always',
+ parser: "markdown",
+ proseWrap: "always",
});
-
+
fs.writeFileSync(outputPath, formattedContent);
} catch (error) {
throw new Error(`Failed to write documentation: ${error.message}`);
@@ -71,30 +78,33 @@ async function writeDocumentation(content: string, outputPath: string): Promise<
async function generateShortcutsDocs(): Promise<void> {
const config: DocsConfig = {
- groups: ['global', 'dashboard', 'collection', 'question', 'admin'],
- introPath: path.join(__dirname, 'resources/introduction.md'),
- outputPath: path.join(__dirname, '../exploration-and-organization/keyboard-shortcuts.md')
+ groups: ["global", "dashboard", "collection", "question", "admin"],
+ introPath: path.join(__dirname, "resources/introduction.md"),
+ outputPath: path.join(
+ __dirname,
+ "../exploration-and-organization/keyboard-shortcuts.md",
+ ),
};
try {
// Get the frontmatter and intro
const introContent = readIntroduction(config.introPath);
-
+
// Generate markdown content
const markdownContent = config.groups.reduce(
(content, group) => content + generateMarkdownTable(shortcuts, group),
- introContent + '\n\n'
+ introContent + "\n\n",
);
// Write to docs file
await writeDocumentation(markdownContent, config.outputPath);
-
- console.log('Shortcuts documentation generated successfully.');
+
+ console.log("Shortcuts documentation generated successfully.");
console.log(`File written to: ${config.outputPath}`);
} catch (error) {
- console.error('Failed to generate shortcuts documentation:', error.message);
+ console.error("Failed to generate shortcuts documentation:", error.message);
process.exit(1);
}
}
-generateShortcutsDocs();
\ No newline at end of file
+generateShortcutsDocs();
diff --git a/eslint.config.mjs b/eslint.config.mjs
index c9d95e6566c..be69b6fa9c1 100644
--- a/eslint.config.mjs
+++ b/eslint.config.mjs
@@ -1,28 +1,26 @@
-// @ts-check
-import { builtinRules } from "eslint/use-at-your-own-risk";
-import { aliasRules } from "./frontend/lint/oxlint/rule-aliases.mjs";
-
-import { fixupPluginRules } from "@eslint/compat";
-import tseslint from "typescript-eslint";
import * as babelParser from "@babel/eslint-parser";
-import reactPlugin from "eslint-plugin-react";
-import * as reactHooksPlugin from "eslint-plugin-react-hooks";
+import { fixupPluginRules } from "@eslint/compat";
+import boundaries from "eslint-plugin-boundaries";
+import chaiFriendlyPlugin from "eslint-plugin-chai-friendly";
+import cypressPlugin from "eslint-plugin-cypress";
+import * as dependPlugin from "eslint-plugin-depend";
+import i18nextPlugin from "eslint-plugin-i18next";
import importXPlugin from "eslint-plugin-import-x";
import jestPlugin from "eslint-plugin-jest";
import jestDomPlugin from "eslint-plugin-jest-dom";
-import testingLibraryPlugin from "eslint-plugin-testing-library";
-import cypressPlugin from "eslint-plugin-cypress";
-import chaiFriendlyPlugin from "eslint-plugin-chai-friendly";
import noOnlyTestsPlugin from "eslint-plugin-no-only-tests";
-import * as dependPlugin from "eslint-plugin-depend";
+import reactPlugin from "eslint-plugin-react";
+import * as reactHooksPlugin from "eslint-plugin-react-hooks";
import storybookPlugin from "eslint-plugin-storybook";
-import i18nextPlugin from "eslint-plugin-i18next";
+import testingLibraryPlugin from "eslint-plugin-testing-library";
import ttagPlugin from "eslint-plugin-ttag";
+// @ts-check
+import { builtinRules } from "eslint/use-at-your-own-risk";
+import tseslint from "typescript-eslint";
-import boundaries from "eslint-plugin-boundaries";
-
-import metabasePlugin from "./frontend/lint/eslint-plugin-metabase/index.js";
import policy from "./frontend/lint/config.mjs";
+import metabasePlugin from "./frontend/lint/eslint-plugin-metabase/index.js";
+import { aliasRules } from "./frontend/lint/oxlint/rule-aliases.mjs";
const shouldLintCssModules =
process.env.LINT_CSS_MODULES === "true" || process.env.CI;
diff --git a/frontend/lint/config.mjs b/frontend/lint/config.mjs
index b6ab90d3b29..96d3f691d53 100644
--- a/frontend/lint/config.mjs
+++ b/frontend/lint/config.mjs
@@ -1,20 +1,23 @@
// Shared lint policy. Keep ESLint and oxlint file scopes and options together.
import path from "node:path";
+
import globals from "globals";
-import presets from "./recommended-rules.json" with { type: "json" };
+
import {
SIDE_EFFECT_FREE_PATHS,
SIDE_EFFECT_PATHS,
} from "../build/shared/rspack/side-effect-free-modules.js";
-import {
- NO_MODULE_SIDE_EFFECTS_IGNORES,
- NO_MODULE_SIDE_EFFECTS_OPTIONS,
-} from "./no-module-side-effects-options.js";
+
import {
boundarySettings,
boundaryOptions,
getPublicApiModules,
} from "./module-boundaries.mjs";
+import {
+ NO_MODULE_SIDE_EFFECTS_IGNORES,
+ NO_MODULE_SIDE_EFFECTS_OPTIONS,
+} from "./no-module-side-effects-options.js";
+import presets from "./recommended-rules.json" with { type: "json" };
const __dirname = path.resolve(import.meta.dirname, "../..");
const TEST_FILES_NAME_PATTERN_ERROR_MESSAGE = `Please name your test setup and utils files with a ".spec.*" in the filename, or put them under "/tests", e.g. "setup.spec.ts", "MyComponent.setup.spec.ts", or "tests/setup.ts". This is to ensure they won't be imported in the SDK build.`;
@@ -111,7 +114,6 @@ const configs = [
ignores: [
"frontend/src/cljs/**",
"frontend/src/cljs_release/**",
- "**/*.d.ts",
"e2e/support/cypress_sample_database.js",
"e2e/support/cypress_sample_instance_data.js",
"e2e/support/assets/**",
@@ -129,7 +131,6 @@ const configs = [
"resources/**",
"**/__snapshots__/**",
".shadow-cljs/**",
- "!.storybook/**",
],
},
{ rules: presets.javascript },
diff --git a/frontend/lint/oxlint/plugins/chai-friendly.mjs b/frontend/lint/oxlint/plugins/chai-friendly.mjs
index b9b1f7dd539..64e9b7d197b 100644
--- a/frontend/lint/oxlint/plugins/chai-friendly.mjs
+++ b/frontend/lint/oxlint/plugins/chai-friendly.mjs
@@ -1,3 +1,4 @@
import plugin from "eslint-plugin-chai-friendly";
+
import { wrap } from "../plugin.mjs";
export default wrap("chai-friendly", plugin);
diff --git a/frontend/lint/oxlint/plugins/cypress.mjs b/frontend/lint/oxlint/plugins/cypress.mjs
index 15975f67905..26ded8fd23b 100644
--- a/frontend/lint/oxlint/plugins/cypress.mjs
+++ b/frontend/lint/oxlint/plugins/cypress.mjs
@@ -1,3 +1,4 @@
import plugin from "eslint-plugin-cypress";
+
import { wrap } from "../plugin.mjs";
export default wrap("cypress", plugin);
diff --git a/frontend/lint/oxlint/plugins/depend.mjs b/frontend/lint/oxlint/plugins/depend.mjs
index f26b4c3b9d6..479a2c3c18c 100644
--- a/frontend/lint/oxlint/plugins/depend.mjs
+++ b/frontend/lint/oxlint/plugins/depend.mjs
@@ -1,4 +1,5 @@
import * as imported from "eslint-plugin-depend";
+
import { wrap } from "../plugin.mjs";
const plugin = imported.default ?? imported;
export default wrap("depend", plugin);
diff --git a/frontend/lint/oxlint/plugins/eslint-js.mjs b/frontend/lint/oxlint/plugins/eslint-js.mjs
index a279fca8d9a..c7536d6dfbc 100644
--- a/frontend/lint/oxlint/plugins/eslint-js.mjs
+++ b/frontend/lint/oxlint/plugins/eslint-js.mjs
@@ -1,4 +1,5 @@
import { builtinRules } from "eslint/use-at-your-own-risk";
+
import { jsRules } from "../config.mjs";
import { moduleScopeContext } from "../module-scope.mjs";
import { wrap } from "../plugin.mjs";
diff --git a/frontend/lint/oxlint/plugins/i18next.mjs b/frontend/lint/oxlint/plugins/i18next.mjs
index ce29e27cc8c..c7cec874a74 100644
--- a/frontend/lint/oxlint/plugins/i18next.mjs
+++ b/frontend/lint/oxlint/plugins/i18next.mjs
@@ -1,4 +1,5 @@
import plugin from "eslint-plugin-i18next";
+
import { withDecodedJsxText } from "../jsx-text.mjs";
import { wrap } from "../plugin.mjs";
export default wrap("i18next", withDecodedJsxText(plugin));
diff --git a/frontend/lint/oxlint/plugins/import-js.mjs b/frontend/lint/oxlint/plugins/import-js.mjs
index ac8c3ad50fd..8ecfd500fe7 100644
--- a/frontend/lint/oxlint/plugins/import-js.mjs
+++ b/frontend/lint/oxlint/plugins/import-js.mjs
@@ -1,5 +1,7 @@
import { createRequire } from "node:module";
+
import plugin from "eslint-plugin-import-x";
+
import { wrap } from "../plugin.mjs";
import { resolver } from "../resolver.mjs";
diff --git a/frontend/lint/oxlint/plugins/jest-dom.mjs b/frontend/lint/oxlint/plugins/jest-dom.mjs
index bd97a618e51..0de60037685 100644
--- a/frontend/lint/oxlint/plugins/jest-dom.mjs
+++ b/frontend/lint/oxlint/plugins/jest-dom.mjs
@@ -1,3 +1,4 @@
import plugin from "eslint-plugin-jest-dom";
+
import { wrap } from "../plugin.mjs";
export default wrap("jest-dom", plugin);
diff --git a/frontend/lint/oxlint/plugins/jest-js.mjs b/frontend/lint/oxlint/plugins/jest-js.mjs
index 7936913823c..b2baa24d9b1 100644
--- a/frontend/lint/oxlint/plugins/jest-js.mjs
+++ b/frontend/lint/oxlint/plugins/jest-js.mjs
@@ -1,3 +1,4 @@
import plugin from "eslint-plugin-jest";
+
import { wrap } from "../plugin.mjs";
export default wrap("jest-js", plugin);
diff --git a/frontend/lint/oxlint/plugins/postcss-modules.mjs b/frontend/lint/oxlint/plugins/postcss-modules.mjs
index ff906cfdbe7..e32a1ca314c 100644
--- a/frontend/lint/oxlint/plugins/postcss-modules.mjs
+++ b/frontend/lint/oxlint/plugins/postcss-modules.mjs
@@ -1,5 +1,6 @@
import { fixupPluginRules } from "@eslint/compat";
import plugin from "eslint-plugin-postcss-modules";
+
import { wrap } from "../plugin.mjs";
export default wrap(
diff --git a/frontend/lint/oxlint/plugins/react-js.mjs b/frontend/lint/oxlint/plugins/react-js.mjs
index 013a142f292..909acf1ca17 100644
--- a/frontend/lint/oxlint/plugins/react-js.mjs
+++ b/frontend/lint/oxlint/plugins/react-js.mjs
@@ -1,3 +1,4 @@
import plugin from "eslint-plugin-react";
+
import { wrap } from "../plugin.mjs";
export default wrap("react-js", plugin);
diff --git a/frontend/lint/oxlint/plugins/storybook.mjs b/frontend/lint/oxlint/plugins/storybook.mjs
index ae402d1d9c3..75695cdee65 100644
--- a/frontend/lint/oxlint/plugins/storybook.mjs
+++ b/frontend/lint/oxlint/plugins/storybook.mjs
@@ -1,3 +1,4 @@
import plugin from "eslint-plugin-storybook";
+
import { wrap } from "../plugin.mjs";
export default wrap("storybook", plugin);
diff --git a/frontend/lint/oxlint/plugins/testing-library.mjs b/frontend/lint/oxlint/plugins/testing-library.mjs
index dab25bad80b..b8a7ffad2ff 100644
--- a/frontend/lint/oxlint/plugins/testing-library.mjs
+++ b/frontend/lint/oxlint/plugins/testing-library.mjs
@@ -1,3 +1,4 @@
import plugin from "eslint-plugin-testing-library";
+
import { wrap } from "../plugin.mjs";
export default wrap("testing-library", plugin);
diff --git a/frontend/lint/oxlint/plugins/ttag.mjs b/frontend/lint/oxlint/plugins/ttag.mjs
index 0e66d5e9819..afec4021f9c 100644
--- a/frontend/lint/oxlint/plugins/ttag.mjs
+++ b/frontend/lint/oxlint/plugins/ttag.mjs
@@ -1,4 +1,5 @@
+import { fixupPluginRules } from "@eslint/compat";
import plugin from "eslint-plugin-ttag";
+
import { wrap } from "../plugin.mjs";
-import { fixupPluginRules } from "@eslint/compat";
export default wrap("ttag", fixupPluginRules(plugin));
diff --git a/frontend/lint/oxlint/plugins/typescript-js.mjs b/frontend/lint/oxlint/plugins/typescript-js.mjs
index 728ffda5727..4bd0cec4178 100644
--- a/frontend/lint/oxlint/plugins/typescript-js.mjs
+++ b/frontend/lint/oxlint/plugins/typescript-js.mjs
@@ -1,3 +1,4 @@
import rules from "@typescript-eslint/eslint-plugin/use-at-your-own-risk/rules";
+
import { wrap } from "../plugin.mjs";
export default wrap("typescript-js", { rules });
diff --git a/frontend/lint/tests/oxlint-import-resolver.test.mjs b/frontend/lint/tests/oxlint-import-resolver.test.mjs
index 1257e31b963..bf5ccdde038 100644
--- a/frontend/lint/tests/oxlint-import-resolver.test.mjs
+++ b/frontend/lint/tests/oxlint-import-resolver.test.mjs
@@ -1,14 +1,13 @@
import assert from "node:assert/strict";
+import { execFileSync } from "node:child_process";
import fs from "node:fs";
import { createRequire } from "node:module";
-import { execFileSync } from "node:child_process";
import os from "node:os";
import path from "node:path";
import test from "node:test";
-import { ResolverFactory } from "oxc-resolver";
-
import { relative as upstreamImportX } from "eslint-plugin-import-x/utils/resolve";
+import { ResolverFactory } from "oxc-resolver";
import { createImportResolverService } from "../oxlint-import-resolver.mjs";
diff --git a/frontend/lint/update-recommended-rules.mjs b/frontend/lint/update-recommended-rules.mjs
index 2ab76078e6f..752ffef7de6 100644
--- a/frontend/lint/update-recommended-rules.mjs
+++ b/frontend/lint/update-recommended-rules.mjs
@@ -1,9 +1,12 @@
import fs from "node:fs";
import { pathToFileURL } from "node:url";
-import { builtinRules } from "eslint/use-at-your-own-risk";
+
import js from "@eslint/js";
+import { builtinRules } from "eslint/use-at-your-own-risk";
import tseslint from "typescript-eslint";
+
import configs from "../../eslint.config.mjs";
+
import ruleMap from "./oxlint/rule-map.json" with { type: "json" };
function stripConfig(config) {
diff --git a/frontend/src/embedding-sdk-bundle/types/globals.d.ts b/frontend/src/embedding-sdk-bundle/types/globals.d.ts
index c32034b18e8..b2340cdab6b 100644
--- a/frontend/src/embedding-sdk-bundle/types/globals.d.ts
+++ b/frontend/src/embedding-sdk-bundle/types/globals.d.ts
@@ -2,5 +2,9 @@ interface Window {
// The bundle writes this global (see embedding-sdk-bundle/index.ts) and the
// npm package reads it. The declaration lives here, next to the exports
// type, so that embedding-sdk-shared does not depend on bundle types.
+ //
+ // A top-level import would turn this file into a module, and `interface
+ // Window` would stop augmenting the global one, so the type is inlined.
+ // eslint-disable-next-line @typescript-eslint/consistent-type-imports
METABASE_EMBEDDING_SDK_BUNDLE?: import("embedding-sdk-bundle/types/sdk-bundle").MetabaseEmbeddingSdkBundleExports;
}
diff --git a/frontend/src/types/docs-snippets.d.ts b/frontend/src/types/docs-snippets.d.ts
index 61224582407..d4db4ce87fa 100644
--- a/frontend/src/types/docs-snippets.d.ts
+++ b/frontend/src/types/docs-snippets.d.ts
@@ -1,5 +1,4 @@
declare module "docs/embedding/sdk/snippets/*" {
const content: string;
- // eslint-disable-next-line import/no-default-export
export default content;
}
diff --git a/frontend/src/types/ee-overrides.d.ts b/frontend/src/types/ee-overrides.d.ts
index 95ccae45c4a..a83eeb7ddee 100644
--- a/frontend/src/types/ee-overrides.d.ts
+++ b/frontend/src/types/ee-overrides.d.ts
@@ -1,5 +1,4 @@
declare module "ee-overrides" {
const enterpriseOverrides: (() => void) | undefined;
- // eslint-disable-next-line import/no-default-export -- deprecated usage
export default enterpriseOverrides;
}
diff --git a/frontend/src/types/global.d.ts b/frontend/src/types/global.d.ts
index 0e3e56ddc34..c8c1846ddfc 100644
--- a/frontend/src/types/global.d.ts
+++ b/frontend/src/types/global.d.ts
@@ -67,14 +67,14 @@ interface Window {
// This allows importing static SVGs from TypeScript files
declare module "*.svg" {
const content: any;
- // eslint-disable-next-line import/no-default-export -- deprecated usage
+ // Default-importing this is the deprecated pattern.
export default content;
}
// This allows importing CSS from TypeScript files
declare module "*.css" {
const classes: { [key: string]: string };
- // eslint-disable-next-line import/no-default-export -- deprecated usage
+ // Default-importing this is the deprecated pattern.
export default classes;
}
@@ -84,7 +84,6 @@ declare module "simple-statistics" {
const ss: {
ckmeans: (data: number[], nClusters: number) => number[][];
};
- // eslint-disable-next-line import/no-default-export -- third-party module declaration
export default ss;
}
diff --git a/frontend/src/types/import-geojson.d.ts b/frontend/src/types/import-geojson.d.ts
index dd59da8621a..23324f13c07 100644
--- a/frontend/src/types/import-geojson.d.ts
+++ b/frontend/src/types/import-geojson.d.ts
@@ -6,6 +6,5 @@ declare module "assets/geojson/*.json" {
const data: FeatureCollection;
- // eslint-disable-next-line import/no-default-export
export default data;
}
diff --git a/frontend/src/types/import-image.d.ts b/frontend/src/types/import-image.d.ts
index 9bdd72bed66..d2b00043548 100644
--- a/frontend/src/types/import-image.d.ts
+++ b/frontend/src/types/import-image.d.ts
@@ -1,20 +1,17 @@
declare module "*.png" {
const value: string;
- // eslint-disable-next-line import/no-default-export
export default value;
}
declare module "*.png?url" {
const value: string;
- // eslint-disable-next-line import/no-default-export
export default value;
}
declare module "*.gif" {
const value: string;
- // eslint-disable-next-line import/no-default-export
export default value;
}
diff --git a/frontend/src/types/import-svg.d.ts b/frontend/src/types/import-svg.d.ts
index 2183ac77284..1993d2ec2b9 100644
--- a/frontend/src/types/import-svg.d.ts
+++ b/frontend/src/types/import-svg.d.ts
@@ -1,21 +1,18 @@
declare module "*.svg" {
const value: string;
- // eslint-disable-next-line import/no-default-export
export default value;
}
declare module "*.svg?url" {
const value: string;
- // eslint-disable-next-line import/no-default-export
export default value;
}
declare module "*.svg?source" {
const value: string;
- // eslint-disable-next-line import/no-default-export
export default value;
}
@@ -23,6 +20,5 @@ declare module "*.svg?component" {
import type React from "react";
const Component: React.VFC<React.SVGProps<SVGSVGElement>>;
- // eslint-disable-next-line import/no-default-export
export default Component;
}
diff --git a/frontend/src/types/markdown.d.ts b/frontend/src/types/markdown.d.ts
index f8c8012b38a..c94d67b1a26 100644
--- a/frontend/src/types/markdown.d.ts
+++ b/frontend/src/types/markdown.d.ts
@@ -1,5 +1,4 @@
declare module "*.md" {
const content: string;
- // eslint-disable-next-line import/no-default-export
export default content;
}
diff --git a/frontend/src/types/slugg.d.ts b/frontend/src/types/slugg.d.ts
index 6deef99f6c9..49e4bec3cd3 100644
--- a/frontend/src/types/slugg.d.ts
+++ b/frontend/src/types/slugg.d.ts
@@ -8,7 +8,6 @@ declare module "slugg" {
toLowerCase?: boolean;
};
- // eslint-disable-next-line import/no-default-export -- deprecated usage
export default function slugg(
str: string,
separatorOrOptions?: Separator | Options,
diff --git a/jest.base.conf.js b/jest.base.conf.js
index 83ffde42316..6b5edf3be26 100644
--- a/jest.base.conf.js
+++ b/jest.base.conf.js
@@ -55,7 +55,8 @@ const baseConfig = {
"^cljs/(.*)$": "<rootDir>/target/cljs_dev/$1",
// The real catalogues are a build artifact, so tests resolve a small fixture
// per locale instead.
- "^locales/(.*)\\.json$": "<rootDir>/frontend/test/__mocks__/locales/$1.json",
+ "^locales/(.*)\\.json$":
+ "<rootDir>/frontend/test/__mocks__/locales/$1.json",
"\\.svg\\?(component|source)":
"<rootDir>/frontend/test/__mocks__/svgMock.tsx",
"csv-parse/browser/esm/sync":
diff --git a/lint-staged.config.cjs b/lint-staged.config.cjs
index 70a00edd436..a664e7f46e5 100644
--- a/lint-staged.config.cjs
+++ b/lint-staged.config.cjs
@@ -24,8 +24,13 @@ module.exports = {
],
"e2e/test/scenarios/**/*.{js,ts}": ["node e2e/validate-e2e-test-files.js"],
"enterprise/frontend/src/embedding-sdk-package/README.md": ["oxfmt --write"],
- "+(.storybook|enterprise/frontend/src/embedding-sdk-shared/.storybook)/**/*.{js,jsx,ts,tsx,css}":
- ["oxfmt --write"],
+ "+(frontend|enterprise/frontend|e2e)/**/*.{mjs,cjs,mts,cts}": [
+ "oxfmt --write",
+ ],
+ "!(frontend|enterprise|e2e)/**/*.{js,jsx,ts,tsx,mjs,cjs,mts,cts,css}": [
+ "oxfmt --write",
+ ],
+ "*.{js,jsx,ts,tsx,mjs,cjs,mts,cts,css}": ["oxfmt --write"],
"**/*": [
/**
* Run mage token-scan for each staged file individually.
diff --git a/mage/test/mage/module_explorer_state_test.js b/mage/test/mage/module_explorer_state_test.js
index c448111a384..fa237e2415c 100644
--- a/mage/test/mage/module_explorer_state_test.js
+++ b/mage/test/mage/module_explorer_state_test.js
@@ -1,54 +1,63 @@
-'use strict';
+"use strict";
-const assert = require('node:assert/strict');
+const assert = require("node:assert/strict");
const {
decodeExplorerState,
encodeExplorerState,
-} = require('../../../dev/resources/dev/module_explorer_state.js');
+} = require("../../../dev/resources/dev/module_explorer_state.js");
-const validIds = new Set(['core', 'lib']);
-const validTeams = new Set(['DevEx', 'Querying']);
+const validIds = new Set(["core", "lib"]);
+const validTeams = new Set(["DevEx", "Querying"]);
const encoded = encodeExplorerState({
- selected: 'core',
- view: 'graph',
+ selected: "core",
+ view: "graph",
focus: new Set(),
degree: 2,
- expanded: new Set(['core']),
- hidden: new Set(['lib']),
- hideRe: 'enterprise/',
- teams: new Set(['Querying', 'DevEx']),
+ expanded: new Set(["core"]),
+ hidden: new Set(["lib"]),
+ hideRe: "enterprise/",
+ teams: new Set(["Querying", "DevEx"]),
});
-const decoded = decodeExplorerState('#' + encoded, validIds, validTeams);
+const decoded = decodeExplorerState("#" + encoded, validIds, validTeams);
-assert.equal(decoded.selected, 'core');
-assert.equal(decoded.view, 'graph');
+assert.equal(decoded.selected, "core");
+assert.equal(decoded.view, "graph");
assert.deepEqual(decoded.focus, new Set());
assert.equal(decoded.focusSpecified, true);
assert.equal(decoded.degree, 2);
-assert.deepEqual(decoded.expanded, new Set(['core']));
-assert.deepEqual(decoded.hidden, new Set(['lib']));
-assert.equal(decoded.hideRe, 'enterprise/');
-assert.deepEqual(decoded.teams, new Set(['DevEx', 'Querying']));
+assert.deepEqual(decoded.expanded, new Set(["core"]));
+assert.deepEqual(decoded.hidden, new Set(["lib"]));
+assert.equal(decoded.hideRe, "enterprise/");
+assert.deepEqual(decoded.teams, new Set(["DevEx", "Querying"]));
-const legacy = decodeExplorerState('#m=core&view=graph', validIds, validTeams);
+const legacy = decodeExplorerState("#m=core&view=graph", validIds, validTeams);
assert.equal(legacy.focusSpecified, false);
-const invalid = decodeExplorerState('#m=unknown&focus=core,unknown&team=Unknown', validIds, validTeams);
+const invalid = decodeExplorerState(
+ "#m=unknown&focus=core,unknown&team=Unknown",
+ validIds,
+ validTeams,
+);
assert.equal(invalid.selected, null);
-assert.deepEqual(invalid.focus, new Set(['core']));
+assert.deepEqual(invalid.focus, new Set(["core"]));
assert.deepEqual(invalid.teams, new Set());
-const cycleView = decodeExplorerState('#' + encodeExplorerState({
- selected: null,
- view: 'cycles',
- focus: new Set(['core', 'lib']),
- degree: 0,
- expanded: new Set(),
- hidden: new Set(),
- hideRe: '',
- teams: new Set(),
-}), validIds, validTeams);
-assert.equal(cycleView.view, 'cycles');
+const cycleView = decodeExplorerState(
+ "#" +
+ encodeExplorerState({
+ selected: null,
+ view: "cycles",
+ focus: new Set(["core", "lib"]),
+ degree: 0,
+ expanded: new Set(),
+ hidden: new Set(),
+ hideRe: "",
+ teams: new Set(),
+ }),
+ validIds,
+ validTeams,
+);
+assert.equal(cycleView.view, "cycles");
assert.equal(cycleView.degree, 0);
-assert.equal(decodeExplorerState('#m=core', validIds, validTeams).degree, 1);
+assert.equal(decodeExplorerState("#m=core", validIds, validTeams).degree, 1);
diff --git a/package.json b/package.json
index 091cddbeb20..a2bcf2e50e8 100644
--- a/package.json
+++ b/package.json
@@ -481,13 +481,13 @@
"lint-config-update": "node frontend/lint/update-recommended-rules.mjs && oxfmt frontend/lint/recommended-rules.json frontend/lint/oxlint/rule-defaults.json",
"module-boundaries": "eslint --config eslint.config.module-boundaries.mjs 'frontend/src/**/*.{ts,tsx}' 'enterprise/frontend/src/**/*.{ts,tsx}'",
"lint-format": "bun install && bun lint-format-pure",
- "lint-format-pure": "oxfmt --check '{frontend,enterprise/frontend,e2e}/**/*.{js,jsx,ts,tsx,css}'",
+ "lint-format-pure": "git ls-files -z '*.js' '*.jsx' '*.ts' '*.tsx' '*.mjs' '*.cjs' '*.mts' '*.cts' '*.css' | xargs -0 oxfmt --check",
"lint-yaml": "yamllint **/*.{yaml,yml} --ignore=node_modules/**/*.{yaml,yml}",
"postinstall": "if [ -z \"$CI\" ]; then patch-package; fi",
"precommit": "lint-staged",
"preinstall": "node -e \"if(!/bun/.test(process.env.npm_execpath || '')) { console.error('Please use Bun, not npm or yarn.'); process.exit(1); }\"",
"prepare": "husky",
- "format": "oxfmt --write '{frontend,enterprise/frontend,e2e}/**/*.{js,jsx,ts,tsx,css}'",
+ "format": "git ls-files -z '*.js' '*.jsx' '*.ts' '*.tsx' '*.mjs' '*.cjs' '*.mts' '*.cts' '*.css' | xargs -0 oxfmt --write",
"remove-webpack-cache": "rm -rf ./node_modules/.cache",
"storybook": "bun run build:cljs && storybook dev -p 6006",
"storybook-pure": "storybook dev -p 6006",
diff --git a/release/ci-conductor/src/adapters/backend.ts b/release/ci-conductor/src/adapters/backend.ts
index 12f27c0549c..f9d0a663419 100644
--- a/release/ci-conductor/src/adapters/backend.ts
+++ b/release/ci-conductor/src/adapters/backend.ts
@@ -24,7 +24,8 @@ const JUNIT_DIR = process.env.JUNIT_DIR || "target/junit";
const VAR_LESS_ERRORS_FILE = "mb_hawk_var_less_errors.xml";
const selectHawkJunit = (entries: string[]): string[] =>
entries.filter(
- (entry) => entry.endsWith("_test.xml") || entry.endsWith(VAR_LESS_ERRORS_FILE),
+ (entry) =>
+ entry.endsWith("_test.xml") || entry.endsWith(VAR_LESS_ERRORS_FILE),
);
/**
@@ -49,7 +50,9 @@ export function normalizeBackendJunit(
`scanned ${dir}: ${files.length} JUnit file(s), ${failures.length} ${ignorePassingTests ? "failing " : ""}test(s)`,
);
for (const test of failures) {
- log(` ${test.status ?? 'failure'}: ${test.path || "(no namespace)"} / ${test.name}`);
+ log(
+ ` ${test.status ?? "failure"}: ${test.path || "(no namespace)"} / ${test.name}`,
+ );
}
return failures;
}
diff --git a/release/ci-conductor/src/adapters/frontend.ts b/release/ci-conductor/src/adapters/frontend.ts
index b8a3a96354f..ef84547b95e 100644
--- a/release/ci-conductor/src/adapters/frontend.ts
+++ b/release/ci-conductor/src/adapters/frontend.ts
@@ -63,7 +63,9 @@ export function normalizeFrontendJunit(
`scanned ${dir}: ${files.length} JUnit file(s), ${failures.length} ${ignorePassingTests ? "failing " : ""}test(s)`,
);
for (const test of failures) {
- log(` ${test.status ?? 'failure'}: ${test.path || "(no describe path)"} / ${test.name}`);
+ log(
+ ` ${test.status ?? "failure"}: ${test.path || "(no describe path)"} / ${test.name}`,
+ );
}
return failures;
}
diff --git a/release/ci-conductor/src/collect-failed-backend.test.ts b/release/ci-conductor/src/collect-failed-backend.test.ts
index 33646b3ae2a..08f5af1c24c 100644
--- a/release/ci-conductor/src/collect-failed-backend.test.ts
+++ b/release/ci-conductor/src/collect-failed-backend.test.ts
@@ -3,7 +3,10 @@ import { describe, expect, it } from "bun:test";
import { buildOnlySelector } from "./collect-failed-backend.ts";
import type { NormalizedTest } from "./contract.ts";
-const failure = (path: string | null | undefined, name: string): NormalizedTest => ({
+const failure = (
+ path: string | null | undefined,
+ name: string,
+): NormalizedTest => ({
name,
path,
status: "failure",
@@ -16,14 +19,18 @@ describe("buildOnlySelector", () => {
failure("metabase.a-test", "alpha-test"),
failure("metabase.b-test", "beta-test"), // dup
]);
- expect(vector).toBe("[metabase.a-test/alpha-test metabase.b-test/beta-test]");
+ expect(vector).toBe(
+ "[metabase.a-test/alpha-test metabase.b-test/beta-test]",
+ );
});
it("keeps thread-arrow test names intact", () => {
const vector = buildOnlySelector([
failure("metabase.util.cron-test", "cron-string->schedule-map-test"),
]);
- expect(vector).toBe("[metabase.util.cron-test/cron-string->schedule-map-test]");
+ expect(vector).toBe(
+ "[metabase.util.cron-test/cron-string->schedule-map-test]",
+ );
});
it("returns null (full rerun) when there are no failures", () => {
diff --git a/release/ci-conductor/src/collect-failed-backend.ts b/release/ci-conductor/src/collect-failed-backend.ts
index 030654b2d7f..bfb3764d9a6 100644
--- a/release/ci-conductor/src/collect-failed-backend.ts
+++ b/release/ci-conductor/src/collect-failed-backend.ts
@@ -27,8 +27,8 @@
import { rmSync, writeFileSync } from "node:fs";
-import type { NormalizedTest } from "./contract.ts";
import { normalizeBackendJunit } from "./adapters/backend.ts";
+import type { NormalizedTest } from "./contract.ts";
import { log } from "./util.ts";
// hawk `:only` accepts a vector of `ns/var` symbols, so the file contents can be
@@ -66,7 +66,9 @@ function main(): void {
// the caller for the test step to read. "No confident set" has to mean "no
// file", or that stale set is what gets uploaded and narrowed on next time.
rmSync(OUTPUT_FILE, { force: true });
- log(`not writing ${OUTPUT_FILE}: no confident failed-test set — caller should rerun the full suite`);
+ log(
+ `not writing ${OUTPUT_FILE}: no confident failed-test set — caller should rerun the full suite`,
+ );
return;
}
writeFileSync(OUTPUT_FILE, vector);
diff --git a/release/ci-conductor/src/fetchWithRetry.ts b/release/ci-conductor/src/fetchWithRetry.ts
index 940bbc9b1f5..510e9a51c57 100644
--- a/release/ci-conductor/src/fetchWithRetry.ts
+++ b/release/ci-conductor/src/fetchWithRetry.ts
@@ -37,14 +37,21 @@ export async function fetchWithRetry(
? AbortSignal.any([init.signal, AbortSignal.timeout(timeout)])
: AbortSignal.timeout(timeout),
});
- if (!shouldRetry(res) || attempt === retries) {return res;}
+ if (!shouldRetry(res) || attempt === retries) {
+ return res;
+ }
res.body?.cancel().catch(() => {}); // don't leak the discarded stream
} catch (err) {
// caller cancelled, or we're out of attempts
- if (init.signal?.aborted || attempt === retries) {throw err;}
+ if (init.signal?.aborted || attempt === retries) {
+ throw err;
+ }
}
- await sleep(retryAfter(res) ?? backoff(attempt, baseDelay, maxDelay), init.signal);
+ await sleep(
+ retryAfter(res) ?? backoff(attempt, baseDelay, maxDelay),
+ init.signal,
+ );
}
}
@@ -54,16 +61,22 @@ function backoff(attempt: number, base: number, max: number): number {
}
function retryAfter(res: Response | undefined): number | null {
- const header = res?.headers.get('retry-after');
- if (!header) {return null;}
+ const header = res?.headers.get("retry-after");
+ if (!header) {
+ return null;
+ }
const seconds = Number(header);
- const ms = Number.isFinite(seconds) ? seconds * 1000 : Date.parse(header) - Date.now();
+ const ms = Number.isFinite(seconds)
+ ? seconds * 1000
+ : Date.parse(header) - Date.now();
return ms > 0 ? ms : null;
}
function sleep(ms: number, signal?: AbortSignal | null): Promise<void> {
return new Promise((resolve, reject) => {
- if (signal?.aborted) {return reject(signal.reason);}
+ if (signal?.aborted) {
+ return reject(signal.reason);
+ }
const onAbort = () => {
clearTimeout(timer);
@@ -71,9 +84,9 @@ function sleep(ms: number, signal?: AbortSignal | null): Promise<void> {
};
const timer = setTimeout(() => {
- signal?.removeEventListener('abort', onAbort);
+ signal?.removeEventListener("abort", onAbort);
resolve();
}, ms);
- signal?.addEventListener('abort', onAbort, { once: true });
+ signal?.addEventListener("abort", onAbort, { once: true });
});
}
diff --git a/release/ci-conductor/src/junit.test.ts b/release/ci-conductor/src/junit.test.ts
index b3bb0339fb6..54a3a4a4dd7 100644
--- a/release/ci-conductor/src/junit.test.ts
+++ b/release/ci-conductor/src/junit.test.ts
@@ -321,7 +321,9 @@ describe("parseJunit with ignorePassingTests: false", () => {
it("reports every test in a mostly-passing jest rerun, keeping `file`", () => {
const tests = parseJunit(JEST_MOSTLY_PASSING, false);
expect(
- tests.map((t) => [t.name, t.status]).sort((a, b) => a[0]!.localeCompare(b[0]!)),
+ tests
+ .map((t) => [t.name, t.status])
+ .sort((a, b) => a[0]!.localeCompare(b[0]!)),
).toEqual([
["Button explodes", "failure"],
["Button is disabled", "passed"],
diff --git a/release/ci-conductor/src/junit.ts b/release/ci-conductor/src/junit.ts
index 4e1d699f703..06a7ca99d29 100644
--- a/release/ci-conductor/src/junit.ts
+++ b/release/ci-conductor/src/junit.ts
@@ -67,7 +67,10 @@ function elementBody(inner: string): string {
* Pure (string → normalized), so it's the unit-tested core that each suite's
* adapter wraps with its own file discovery / labeling.
*/
-export function parseJunit(xml: string, ignorePassingTests: boolean = true): NormalizedTest[] {
+export function parseJunit(
+ xml: string,
+ ignorePassingTests: boolean = true,
+): NormalizedTest[] {
try {
const tests: NormalizedTest[] = [];
// <testcase ...>...</testcase> (failing) or <testcase .../> (passing,
@@ -102,7 +105,10 @@ export function parseJunit(xml: string, ignorePassingTests: boolean = true): Nor
const problems = [...inner.matchAll(problemRe)];
// Don't report a test to CI Conductor if the test has no failures and we are ignoring passing tests OR
// the test has no failures and a skipped tag.
- if (problems.length === 0 && ( ignorePassingTests || skippedRe.test(inner))) {
+ if (
+ problems.length === 0 &&
+ (ignorePassingTests || skippedRe.test(inner))
+ ) {
continue;
}
@@ -136,7 +142,8 @@ export function parseJunit(xml: string, ignorePassingTests: boolean = true): Nor
file: file || null,
message,
stack: stack || undefined,
- status: problems.length === 0 && !ignorePassingTests ? "passed" : "failure",
+ status:
+ problems.length === 0 && !ignorePassingTests ? "passed" : "failure",
});
}
return tests;
diff --git a/release/ci-conductor/src/quarantine.test.ts b/release/ci-conductor/src/quarantine.test.ts
index a4dea25eba6..dc0c0b4c4be 100644
--- a/release/ci-conductor/src/quarantine.test.ts
+++ b/release/ci-conductor/src/quarantine.test.ts
@@ -135,9 +135,9 @@ describe("matchKey", () => {
it("does not collide when a boundary between fields shifts", () => {
// ["a", "b", "c"] vs ["ab", "", "c"] must stay distinct.
- expect(
- matchKey({ filePath: "a", testPath: "b", testName: "c" }),
- ).not.toBe(matchKey({ filePath: "ab", testPath: "", testName: "c" }));
+ expect(matchKey({ filePath: "a", testPath: "b", testName: "c" })).not.toBe(
+ matchKey({ filePath: "ab", testPath: "", testName: "c" }),
+ );
});
});
@@ -233,7 +233,9 @@ describe("suiteMatchesGlob", () => {
});
it("expands `*` and `?`", () => {
- expect(suiteMatchesGlob("be-tests-java-21-mbql", "be-tests-*-mbql")).toBe(true);
+ expect(suiteMatchesGlob("be-tests-java-21-mbql", "be-tests-*-mbql")).toBe(
+ true,
+ );
expect(suiteMatchesGlob("e2e-3", "e2e-?")).toBe(true);
expect(suiteMatchesGlob("e2e-12", "e2e-?")).toBe(true); // unanchored
});
@@ -344,7 +346,8 @@ describe("fetchQuarantine", () => {
const okList = (entries: QuarantineEntry[], suites?: string[]) =>
new Response(JSON.stringify({ tests: entries, suites }), { status: 200 });
const errorStatus = (status: number) => new Response("", { status });
- const econnreset = () => new Error("The socket connection was closed unexpectedly");
+ const econnreset = () =>
+ new Error("The socket connection was closed unexpectedly");
const list = (entries: QuarantineEntry[], suites: string[] = []) => ({
tests: entries,
@@ -552,7 +555,9 @@ describe("checkQuarantineGate", () => {
): Promise<T> {
const originalFetch = globalThis.fetch;
globalThis.fetch = (async () =>
- new Response(JSON.stringify(body), { status: 200 })) as unknown as typeof fetch;
+ new Response(JSON.stringify(body), {
+ status: 200,
+ })) as unknown as typeof fetch;
try {
return await run();
} finally {
@@ -584,9 +589,8 @@ describe("checkQuarantineGate", () => {
});
it("still gates test by test when no suite rule matches", async () => {
- const { result } = await withList(
- { tests: [], suites: ["athena"] },
- () => gate("fe-tests-unit"),
+ const { result } = await withList({ tests: [], suites: ["athena"] }, () =>
+ gate("fe-tests-unit"),
);
expect(result).toEqual({
diff --git a/release/ci-conductor/src/quarantine.ts b/release/ci-conductor/src/quarantine.ts
index 9ecea5b6945..5d39df320dc 100644
--- a/release/ci-conductor/src/quarantine.ts
+++ b/release/ci-conductor/src/quarantine.ts
@@ -80,13 +80,14 @@ export function compareFailedToQuarantine(
quarantineEntries: QuarantineEntry[],
): { quarantined: QuarantineEntry[]; unquarantined: FailedTest[] } {
const quarantinedByKeys = new Map(
- quarantineEntries.map((q) =>
- [matchKey({
+ quarantineEntries.map((q) => [
+ matchKey({
filePath: q.file_path,
testPath: q.test_path,
testName: q.test_name,
- }), q],
- ),
+ }),
+ q,
+ ]),
);
const quarantined: QuarantineEntry[] = [];
const unquarantined: FailedTest[] = [];
@@ -98,7 +99,9 @@ export function compareFailedToQuarantine(
testName: test.test_name,
}),
);
- quarantineEntry ? quarantined.push(quarantineEntry) : unquarantined.push(test);
+ quarantineEntry
+ ? quarantined.push(quarantineEntry)
+ : unquarantined.push(test);
}
return { quarantined, unquarantined };
}
@@ -242,7 +245,9 @@ const RULE = "─".repeat(60);
/** `test_path › test_name`, or just the name when there's no path. */
function title(test: FailedTest): string {
- return test.test_path ? `${test.test_path} › ${test.test_name}` : test.test_name;
+ return test.test_path
+ ? `${test.test_path} › ${test.test_name}`
+ : test.test_name;
}
/**
@@ -313,11 +318,17 @@ export async function checkQuarantineGate(opts: {
if (failures.length === 0) {
log("✅ no failures this run — nothing to gate.");
log(RULE);
- return { shouldFail: false, enforced: false, reason: "no failures to gate" };
+ return {
+ shouldFail: false,
+ enforced: false,
+ reason: "no failures to gate",
+ };
}
if (!baseUrl) {
- log("⚠️ CI_CONDUCTOR_BASE_URL not set — can't fetch the quarantine list (local run or missing secret).");
+ log(
+ "⚠️ CI_CONDUCTOR_BASE_URL not set — can't fetch the quarantine list (local run or missing secret).",
+ );
return finish({
shouldFail: true,
reason: "could not fetch the quarantine list",
@@ -341,7 +352,9 @@ export async function checkQuarantineGate(opts: {
// and there's nothing to compare test by test.
const suiteGlob = quarantinedSuiteGlob(suite, list.suites);
if (suiteGlob) {
- log(`🏷️ suite rule "${suiteGlob}" covers this suite — no failure here gates.`);
+ log(
+ `🏷️ suite rule "${suiteGlob}" covers this suite — no failure here gates.`,
+ );
return finish({
shouldFail: false,
reason: `suite "${suite}" is quarantined by the rule "${suiteGlob}"`,
@@ -354,7 +367,9 @@ export async function checkQuarantineGate(opts: {
list.tests,
);
- log(`📋 quarantine list: ${list.tests.length} test(s) registered for "${suite}"`);
+ log(
+ `📋 quarantine list: ${list.tests.length} test(s) registered for "${suite}"`,
+ );
log(`💥 this run: ${failures.length} failure(s) to evaluate`);
for (const test of quarantined) {
log(` 🔒 quarantined ${title(test)}`);
@@ -365,7 +380,7 @@ export async function checkQuarantineGate(opts: {
}
for (const test of unquarantined) {
log(` 🚨 NOT quarantined ${title(test)}`);
- log(` ↳ ${test.file_path ?? "(no file)"}`);
+ log(` ↳ ${test.file_path ?? "(no file)"}`);
log(
` ↳ View test in CI Conductor: ${testSearchUrl(baseUrl, test)}`,
);
diff --git a/release/ci-conductor/src/report-backend.ts b/release/ci-conductor/src/report-backend.ts
index b203036d259..e18c5615ef2 100644
--- a/release/ci-conductor/src/report-backend.ts
+++ b/release/ci-conductor/src/report-backend.ts
@@ -25,7 +25,10 @@ async function main(): Promise<void> {
// If re-running tests we report failures AND passing tests so that ci-conductor can
// determine flaky tests. We should not ignore passing tests in this case.
const ignorePassingTests = env.IS_RERUN === "true" ? false : true;
- await reportTestFailures(normalizeBackendJunit(ignorePassingTests), testSuite);
+ await reportTestFailures(
+ normalizeBackendJunit(ignorePassingTests),
+ testSuite,
+ );
}
main().catch((error) => {
diff --git a/release/ci-conductor/src/report-frontend.ts b/release/ci-conductor/src/report-frontend.ts
index ce93dad0571..7490bb194b5 100644
--- a/release/ci-conductor/src/report-frontend.ts
+++ b/release/ci-conductor/src/report-frontend.ts
@@ -23,7 +23,10 @@ async function main(): Promise<void> {
// If re-running tests we report failures AND passing tests so that ci-conductor can
// determine flaky tests. We should not ignore passing tests in this case.
const ignorePassingTests = env.IS_RERUN === "true" ? false : true;
- await reportTestFailures(normalizeFrontendJunit(ignorePassingTests), testSuite);
+ await reportTestFailures(
+ normalizeFrontendJunit(ignorePassingTests),
+ testSuite,
+ );
}
main().catch((error) => {
diff --git a/release/generate-changelog.ts b/release/generate-changelog.ts
index 0121d060aa4..6c3d2614618 100644
--- a/release/generate-changelog.ts
+++ b/release/generate-changelog.ts
@@ -1,19 +1,14 @@
// changelog preview only, doesn't publish anything
import { Octokit } from "@octokit/rest";
-import {
- getChangelog,
- isValidVersionString,
-} from "./src";
+import { getChangelog, isValidVersionString } from "./src";
-const {
- GITHUB_TOKEN,
- GITHUB_OWNER,
- GITHUB_REPO,
-} = process.env as any;
+const { GITHUB_TOKEN, GITHUB_OWNER, GITHUB_REPO } = process.env as any;
if (!GITHUB_TOKEN || !GITHUB_OWNER || !GITHUB_REPO) {
- console.error("You must provide GITHUB_* environment variables in .env-template");
+ console.error(
+ "You must provide GITHUB_* environment variables in .env-template",
+ );
}
const github = new Octokit({ auth: GITHUB_TOKEN });
@@ -34,4 +29,3 @@ const notes = await getChangelog({
});
console.log(notes);
-
diff --git a/release/release-offline.ts b/release/release-offline.ts
index 63b52fdf523..5a3d534ff1b 100644
--- a/release/release-offline.ts
+++ b/release/release-offline.ts
@@ -22,9 +22,7 @@ import {
publishRelease,
versionRequirements,
} from "./src";
-import {
- publishVersionInfoFiles,
-} from "./version-info-s3";
+import { publishVersionInfoFiles } from "./version-info-s3";
const {
GITHUB_TOKEN,
@@ -62,10 +60,12 @@ function error(message) {
// need to force the user to set the latest tag from the command line if they are releasing without github
if (isWithoutGithub) {
if (!latestFlag) {
- error('If you are releasing without github you must pass --latest or --not-latest as the last argument');
+ error(
+ "If you are releasing without github you must pass --latest or --not-latest as the last argument",
+ );
}
- latestFlag = (latestFlag === "--latest") ? true : false;
+ latestFlag = latestFlag === "--latest" ? true : false;
}
const edition = isEnterpriseVersion(version) ? "ee" : "oss";
@@ -91,7 +91,7 @@ if (!step) {
// mostly for type checking
function getGithubCredentials() {
if (isWithoutGithub) {
- return { GITHUB_TOKEN: '', GITHUB_OWNER: '', GITHUB_REPO: '' };
+ return { GITHUB_TOKEN: "", GITHUB_OWNER: "", GITHUB_REPO: "" };
}
if (!GITHUB_TOKEN || !GITHUB_OWNER || !GITHUB_REPO) {
@@ -163,7 +163,7 @@ async function checkJar() {
`${JAR_PATH}/SHA256.sum`,
];
- requiredFiles.forEach(file => {
+ requiredFiles.forEach((file) => {
if (!fs.existsSync(file)) {
error(`You must build the jar first. ${file} does not exist`);
}
@@ -375,8 +375,11 @@ async function updateMilestones() {
if (step === "publish") {
log(`🚀 Publishing ${edition} ${version} 🚀`);
- if ( isWithoutGithub ) {
- log(`⚠️ Skipping github steps because --without-github was passed ⚠️`, "yellow");
+ if (isWithoutGithub) {
+ log(
+ `⚠️ Skipping github steps because --without-github was passed ⚠️`,
+ "yellow",
+ );
await s3();
await docker();
@@ -388,7 +391,9 @@ async function updateMilestones() {
"no milestones were updated",
].join("\n ❌ ");
- log(`Because you released without github the following steps were not completed:\n ❌ ${remainingSteps}`);
+ log(
+ `Because you released without github the following steps were not completed:\n ❌ ${remainingSteps}`,
+ );
return;
}
diff --git a/release/src/backports.ts b/release/src/backports.ts
index 0d77d863cd6..53473a8c593 100644
--- a/release/src/backports.ts
+++ b/release/src/backports.ts
@@ -1,6 +1,6 @@
import "dotenv/config";
import type { Octokit } from "@octokit/rest";
-import dayjs from 'dayjs';
+import dayjs from "dayjs";
import { sendBackportReminder } from "./slack";
import type { Issue } from "./types";
@@ -8,25 +8,32 @@ import type { Issue } from "./types";
const RECENT_BACKPORT_THRESHOLD_HOURS = 25;
/** check open backports and send slack reminders about stale ones */
-export const checkOpenBackports = async ({ github, owner, repo, channelName }: {
- github: Octokit,
- owner: string,
- repo: string,
- channelName: string,
+export const checkOpenBackports = async ({
+ github,
+ owner,
+ repo,
+ channelName,
+}: {
+ github: Octokit;
+ owner: string;
+ repo: string;
+ channelName: string;
}) => {
-
- const openBackports = await github.paginate(github.rest.issues.listForRepo, {
+ const openBackports = (await github.paginate(github.rest.issues.listForRepo, {
owner,
repo,
labels: "was-backported",
state: "open",
per_page: 100,
- }) as Issue[];
+ })) as Issue[];
console.log(`Found ${openBackports.length} open backports`);
- const staleBackports = openBackports
- .filter(issue => dayjs().diff(dayjs(issue.created_at), 'hours') > RECENT_BACKPORT_THRESHOLD_HOURS);
+ const staleBackports = openBackports.filter(
+ (issue) =>
+ dayjs().diff(dayjs(issue.created_at), "hours") >
+ RECENT_BACKPORT_THRESHOLD_HOURS,
+ );
if (!staleBackports.length) {
console.log("No recent backports to remind about");
@@ -39,5 +46,4 @@ export const checkOpenBackports = async ({ github, owner, repo, channelName }: {
channelName,
backports: staleBackports,
});
-}
-
+};
diff --git a/release/src/cross-version-helpers.ts b/release/src/cross-version-helpers.ts
index 328c6a5764f..2bdf1568cfe 100644
--- a/release/src/cross-version-helpers.ts
+++ b/release/src/cross-version-helpers.ts
@@ -23,7 +23,8 @@ export type VersionComparisonResult = "upgrade" | "downgrade" | "same";
export const isHead = (version: string): boolean => version === "HEAD";
-export const isRollingTag = (version: string): boolean => version.endsWith(".x");
+export const isRollingTag = (version: string): boolean =>
+ version.endsWith(".x");
// ============================================================================
// Pure helpers for HEAD versions
diff --git a/release/src/github.ts b/release/src/github.ts
index a81ddf84768..ed93d6aa37e 100644
--- a/release/src/github.ts
+++ b/release/src/github.ts
@@ -1,5 +1,5 @@
-import { Octokit } from "@octokit/rest";
import { paginateGraphQL } from "@octokit/plugin-paginate-graphql";
+import { Octokit } from "@octokit/rest";
import type { GithubCheck, GithubProps, Issue, ReleaseProps } from "./types";
import {
@@ -40,7 +40,8 @@ const getMilestoneItems = async ({
// The octokit injected by actions/github-script lacks the paginate-graphql
// plugin, so build our own plugin-enabled client from the token in env
const client = new PaginatingOctokit({ auth: process.env.GITHUB_TOKEN });
- const stateType = connection === "pullRequests" ? "PullRequestState" : "IssueState";
+ const stateType =
+ connection === "pullRequests" ? "PullRequestState" : "IssueState";
const { repository } = await client.graphql.paginate<{
repository: { milestone: Record<string, { nodes: MilestoneItemNode[] }> };
@@ -128,12 +129,12 @@ export const openNextMilestones = async ({
repo,
version,
}: ReleaseProps) => {
- const nextMilestones = getNextVersions(version).map(versionString =>
+ const nextMilestones = getNextVersions(version).map((versionString) =>
getMilestoneName(versionString),
);
await Promise.all(
- nextMilestones.map(milestoneName =>
+ nextMilestones.map((milestoneName) =>
github.rest.issues
.createMilestone({
owner,
@@ -198,7 +199,9 @@ export const getMilestoneIssues = async ({
pull_request: isPR ? { html_url: n.url } : undefined,
milestone,
labels: n.labels.nodes.map((l) => ({ name: l.name })),
- assignee: n.assignees.nodes[0] ? { login: n.assignees.nodes[0].login } : null,
+ assignee: n.assignees.nodes[0]
+ ? { login: n.assignees.nodes[0].login }
+ : null,
created_at: n.createdAt,
});
@@ -287,10 +290,12 @@ function checksPassed(checks: GithubCheck[]) {
const MIN_TOTAL_CHECKS = 95; // v49 has 96 checks, v50 has 99 checks
const failedChecks = checks.filter(
- check => !["success", "skipped"].includes(check.conclusion ?? ""),
+ (check) => !["success", "skipped"].includes(check.conclusion ?? ""),
);
- const pendingChecks = checks.filter(check => check.status === "in_progress");
+ const pendingChecks = checks.filter(
+ (check) => check.status === "in_progress",
+ );
const totalChecks = checks.length;
const sha = checks[0]?.head_sha;
@@ -409,7 +414,7 @@ export async function hasCommitBeenReleased({
basehead: `${lastTagSha}...refs/heads/release-x.${majorVersion}.x`,
});
- const isAheadOfLastRelease = data.commits.some(c => c.sha === ref);
+ const isAheadOfLastRelease = data.commits.some((c) => c.sha === ref);
console.log({ lastTag, lastTagSha, ref, isAheadOfLastRelease });
@@ -434,4 +439,3 @@ export async function getOpenBackportPrs({
return prs;
}
-
diff --git a/release/src/linked-issues.ts b/release/src/linked-issues.ts
index 8cd0c5f6da9..5ce2319a289 100644
--- a/release/src/linked-issues.ts
+++ b/release/src/linked-issues.ts
@@ -5,7 +5,7 @@ export function getLinkedIssues(body: string) {
);
if (matches) {
- return matches.map(m => {
+ return matches.map((m) => {
const numberMatch = m.match(/\d+/);
return numberMatch ? numberMatch[0] : null;
});
@@ -14,18 +14,18 @@ export function getLinkedIssues(body: string) {
return null;
}
-export const issueNumberRegex = /\(#(\d+)\)/g
+export const issueNumberRegex = /\(#(\d+)\)/g;
export function getPRsFromCommitMessage(message: string) {
if (!message) return null;
- const firstLine = message.split('\n\n')[0];
- const result = [ ...firstLine.matchAll(issueNumberRegex) ];
+ const firstLine = message.split("\n\n")[0];
+ const result = [...firstLine.matchAll(issueNumberRegex)];
if (!result.length) {
- console.log('No pr found in commit message', message);
+ console.log("No pr found in commit message", message);
return null;
}
- return result.map(r => Number(r[1]));
+ return result.map((r) => Number(r[1]));
}
// backport PRs just have a pr number in the body without a keyword
diff --git a/release/src/linked-issues.unit.spec.ts b/release/src/linked-issues.unit.spec.ts
index 31af62e1d1d..7bad7f3a95c 100644
--- a/release/src/linked-issues.unit.spec.ts
+++ b/release/src/linked-issues.unit.spec.ts
@@ -1,4 +1,8 @@
-import { getBackportSourcePRNumber, getLinkedIssues, getPRsFromCommitMessage } from "./linked-issues";
+import {
+ getBackportSourcePRNumber,
+ getLinkedIssues,
+ getPRsFromCommitMessage,
+} from "./linked-issues";
const closingKeywords = [
"Close",
@@ -54,12 +58,20 @@ describe("getLinkedIssues", () => {
});
it("should not match issues from other repositories", () => {
- expect(getLinkedIssues("closes https://github.com/metabase/metabase-fake/issues/123")).toBeNull();
- expect(getLinkedIssues("closes https://github.com/metabase/metabae/issues/123")).toBeNull();
+ expect(
+ getLinkedIssues(
+ "closes https://github.com/metabase/metabase-fake/issues/123",
+ ),
+ ).toBeNull();
+ expect(
+ getLinkedIssues(
+ "closes https://github.com/metabase/metabae/issues/123",
+ ),
+ ).toBeNull();
});
});
- describe.each(closingKeywords)("smoke tests", closingKeyword => {
+ describe.each(closingKeywords)("smoke tests", (closingKeyword) => {
describe("shorthand syntax", () => {
it(`should return the issue id for ${closingKeyword}`, () => {
expect(getLinkedIssues(`${closingKeyword} #123`)).toEqual(["123"]);
@@ -78,9 +90,9 @@ describe("getLinkedIssues", () => {
});
it(`should return the issue id for ${closingKeyword.toLowerCase()} with a colon`, () => {
- expect(getLinkedIssues(`${closingKeyword.toLowerCase()}: #123`)).toEqual(
- ["123"],
- );
+ expect(
+ getLinkedIssues(`${closingKeyword.toLowerCase()}: #123`),
+ ).toEqual(["123"]);
});
});
@@ -138,16 +150,30 @@ describe("getPRsFromCommitMessage", () => {
});
it("should return the PR id for a message with multiple backport PRs", () => {
- expect(getPRsFromCommitMessage("Backport (#123) (#456)")).toEqual([123, 456]);
- expect(getPRsFromCommitMessage("Backport (#1234) and (#4567)")).toEqual([1234, 4567]);
- expect(getPRsFromCommitMessage("Backport (#1234) and (#4567) (#8989)")).toEqual([1234, 4567, 8989]);
+ expect(getPRsFromCommitMessage("Backport (#123) (#456)")).toEqual([
+ 123, 456,
+ ]);
+ expect(getPRsFromCommitMessage("Backport (#1234) and (#4567)")).toEqual([
+ 1234, 4567,
+ ]);
+ expect(
+ getPRsFromCommitMessage("Backport (#1234) and (#4567) (#8989)"),
+ ).toEqual([1234, 4567, 8989]);
});
it("should ignore pr numbers outside the title", () => {
- expect(getPRsFromCommitMessage("Backport (#123) (#456)\n\n(#888) (#999)")).toEqual([123, 456]);
- expect(getPRsFromCommitMessage("Backport (#1234) and (#4567)\n\n(#888)")).toEqual([1234, 4567]);
- expect(getPRsFromCommitMessage("Backport (#1234)\n\n and (#4567) (#8989)")).toEqual([1234]);
- expect(getPRsFromCommitMessage("Backport\n\n (#1234)\n\n and (#4567) (#8989)")).toEqual(null);
+ expect(
+ getPRsFromCommitMessage("Backport (#123) (#456)\n\n(#888) (#999)"),
+ ).toEqual([123, 456]);
+ expect(
+ getPRsFromCommitMessage("Backport (#1234) and (#4567)\n\n(#888)"),
+ ).toEqual([1234, 4567]);
+ expect(
+ getPRsFromCommitMessage("Backport (#1234)\n\n and (#4567) (#8989)"),
+ ).toEqual([1234]);
+ expect(
+ getPRsFromCommitMessage("Backport\n\n (#1234)\n\n and (#4567) (#8989)"),
+ ).toEqual(null);
});
});
@@ -156,7 +182,6 @@ describe("getBackportSourcePRNumber", () => {
expect(getBackportSourcePRNumber("")).toBeNull();
expect(getBackportSourcePRNumber("Lorem ipsum dolor sit amet.")).toBeNull();
expect(getBackportSourcePRNumber("#yolo")).toBeNull();
-
});
it("should return the pr number when it is found", () => {
diff --git a/release/src/milestones.ts b/release/src/milestones.ts
index b1fce7a9f06..20fbac9719c 100644
--- a/release/src/milestones.ts
+++ b/release/src/milestones.ts
@@ -14,7 +14,13 @@ import {
getLinkedIssues,
getPRsFromCommitMessage,
} from "./linked-issues";
-import type { Commit, GithubProps, Issue, Milestone, ReleaseProps } from "./types";
+import type {
+ Commit,
+ GithubProps,
+ Issue,
+ Milestone,
+ ReleaseProps,
+} from "./types";
import {
getLastReleaseTag,
getMajorVersion,
@@ -27,7 +33,8 @@ import {
function isBackport(pullRequest: Issue) {
return (
- pullRequest.title.includes("backport") || hasLabel(pullRequest, "was-backport")
+ pullRequest.title.includes("backport") ||
+ hasLabel(pullRequest, "was-backport")
);
}
@@ -43,14 +50,16 @@ const isNotNull = <T>(value: T | null): value is T => value !== null;
const excludedLabels = [
...nonUserFacingLabels,
...hiddenLabels,
- '.Already Fixed',
+ ".Already Fixed",
];
function getExcludedLabels(issue: Issue) {
if (!Array.isArray(issue.labels)) {
return [];
}
- return issue.labels?.filter(label => label.name && excludedLabels.includes(label.name));
+ return issue.labels?.filter(
+ (label) => label.name && excludedLabels.includes(label.name),
+ );
}
function shouldExcludeIssueFromMilestone(issue: Issue) {
@@ -64,18 +73,22 @@ async function getIssuesWithExcludedTags({
issueNumbers,
}: GithubProps & { issueNumbers: number[] }) {
const issues = await Promise.all(
- issueNumbers.map((issueNumber) => getIssueWithCache({
- github,
- owner,
- repo,
- issueNumber,
- }))
+ issueNumbers.map((issueNumber) =>
+ getIssueWithCache({
+ github,
+ owner,
+ repo,
+ issueNumber,
+ }),
+ ),
);
- return new Set(issues
- .filter(isNotNull)
- .filter((issue) => shouldExcludeIssueFromMilestone(issue))
- .map((issue) => issue.number));
+ return new Set(
+ issues
+ .filter(isNotNull)
+ .filter((issue) => shouldExcludeIssueFromMilestone(issue))
+ .map((issue) => issue.number),
+ );
}
async function getIssuesWithOlderMilestones({
@@ -84,26 +97,37 @@ async function getIssuesWithOlderMilestones({
repo,
issueNumbers,
releaseMilestone,
-}: GithubProps & { issueNumbers: number[], releaseMilestone: Milestone }) {
+}: GithubProps & { issueNumbers: number[]; releaseMilestone: Milestone }) {
const issues = await Promise.all(
- issueNumbers.map((issueNumber) => getIssueWithCache({
- github,
- owner,
- repo,
- issueNumber,
- }))
+ issueNumbers.map((issueNumber) =>
+ getIssueWithCache({
+ github,
+ owner,
+ repo,
+ issueNumber,
+ }),
+ ),
);
- return new Set(issues
- .filter(isNotNull)
- .filter((issue) => {
- if (issue.milestone && versionSort(issue.milestone.title, releaseMilestone.title) < 0) {
- console.log(` Issue #${issue.number} is in an older milestone`, issue.milestone.title);
- return true;
- }
-
- return false;
- }).map((issue) => issue.number));
+ return new Set(
+ issues
+ .filter(isNotNull)
+ .filter((issue) => {
+ if (
+ issue.milestone &&
+ versionSort(issue.milestone.title, releaseMilestone.title) < 0
+ ) {
+ console.log(
+ ` Issue #${issue.number} is in an older milestone`,
+ issue.milestone.title,
+ );
+ return true;
+ }
+
+ return false;
+ })
+ .map((issue) => issue.number),
+ );
}
async function getOriginalIssues({
@@ -112,7 +136,7 @@ async function getOriginalIssues({
owner,
issueNumber,
}: GithubProps & { issueNumber: number }) {
- console.log('checking', issueNumber);
+ console.log("checking", issueNumber);
const issue = await getIssueWithCache({
github,
owner,
@@ -127,14 +151,14 @@ async function getOriginalIssues({
// if this isn't a pull request, we don't need to trace further
if (!issue.pull_request) {
- console.log(' Found an issue');
+ console.log(" Found an issue");
return [issue.number];
}
if (isBackport(issue)) {
const sourcePRNumber = getBackportSourcePRNumber(issue.body);
if (sourcePRNumber && sourcePRNumber !== issueNumber) {
- console.log(' found backport PR for ', sourcePRNumber);
+ console.log(" found backport PR for ", sourcePRNumber);
return getOriginalIssues({
github,
repo,
@@ -144,10 +168,10 @@ async function getOriginalIssues({
}
}
- const linkedIssues = await getLinkedIssues(issue.body ?? '');
+ const linkedIssues = await getLinkedIssues(issue.body ?? "");
if (linkedIssues) {
- console.log(' found linked issues', linkedIssues);
+ console.log(" found linked issues", linkedIssues);
return linkedIssues.map(Number);
}
@@ -155,7 +179,18 @@ async function getOriginalIssues({
return [issue.number];
}
-async function setMilestone({ github, owner, repo, issueNumber, milestone, ignoreExistingMilestones }: GithubProps & { issueNumber: number, milestone: Milestone, ignoreExistingMilestones?: boolean }) {
+async function setMilestone({
+ github,
+ owner,
+ repo,
+ issueNumber,
+ milestone,
+ ignoreExistingMilestones,
+}: GithubProps & {
+ issueNumber: number;
+ milestone: Milestone;
+ ignoreExistingMilestones?: boolean;
+}) {
// we can use this for both issues and PRs since they're the same for many purposes in github
const issue = await getIssueWithCache({
github,
@@ -165,7 +200,9 @@ async function setMilestone({ github, owner, repo, issueNumber, milestone, ignor
});
if (!issue?.milestone) {
- console.log(`Setting milestone ${milestone.title} for issue # ${issueNumber}`);
+ console.log(
+ `Setting milestone ${milestone.title} for issue # ${issueNumber}`,
+ );
return github.rest.issues.update({
owner,
repo,
@@ -181,15 +218,20 @@ async function setMilestone({ github, owner, repo, issueNumber, milestone, ignor
const existingMilestone = issue.milestone;
if (existingMilestone.number === milestone.number) {
- console.log(`Issue ${issueNumber} is already tagged with this ${milestone.title} milestone`);
+ console.log(
+ `Issue ${issueNumber} is already tagged with this ${milestone.title} milestone`,
+ );
return;
}
- const existingMilestoneIsNewer = versionSort(existingMilestone.title, milestone.title) > 0;
+ const existingMilestoneIsNewer =
+ versionSort(existingMilestone.title, milestone.title) > 0;
// if existing milestone is newer, change it
if (existingMilestoneIsNewer) {
- console.log(`Changing milestone from ${existingMilestone.title} to ${milestone.title}`);
+ console.log(
+ `Changing milestone from ${existingMilestone.title} to ${milestone.title}`,
+ );
await github.rest.issues.update({
owner,
@@ -199,19 +241,23 @@ async function setMilestone({ github, owner, repo, issueNumber, milestone, ignor
});
}
-
- console.log(`${issueNumber} is already part of ${existingMilestone.title}, no updates made.`);
+ console.log(
+ `${issueNumber} is already part of ${existingMilestone.title}, no updates made.`,
+ );
return;
}
// get the next open milestone (e.g. 0.57.8) for the given major version (e.g 57)
-export function getNextMilestone(
- { openMilestones, majorVersion }:
- { openMilestones: Milestone[], majorVersion: number | string }
-): Milestone | undefined {
+export function getNextMilestone({
+ openMilestones,
+ majorVersion,
+}: {
+ openMilestones: Milestone[];
+ majorVersion: number | string;
+}): Milestone | undefined {
const milestonesForThisMajorVersion = openMilestones
- .filter(milestone => milestone.title.startsWith(`0.${majorVersion}`))
- .filter(milestone => ignorePatches(milestone.title))
+ .filter((milestone) => milestone.title.startsWith(`0.${majorVersion}`))
+ .filter((milestone) => ignorePatches(milestone.title))
.sort((a, b) => versionSort(a.title, b.title));
const nextMilestone = milestonesForThisMajorVersion[0];
@@ -226,29 +272,38 @@ export async function setMilestoneForCommits({
branchName,
commitMessages,
ignoreExistingMilestones,
-}: GithubProps & { commitMessages: string[], branchName: string, ignoreExistingMilestones?: boolean }) {
+}: GithubProps & {
+ commitMessages: string[];
+ branchName: string;
+ ignoreExistingMilestones?: boolean;
+}) {
// figure out milestone
const branchVersion = getVersionFromReleaseBranch(branchName);
const majorVersion = getMajorVersion(branchVersion);
- const openMilestones = await getMilestones({ github, owner, repo, state: 'open' });
+ const openMilestones = await getMilestones({
+ github,
+ owner,
+ repo,
+ state: "open",
+ });
const nextMilestone = getNextMilestone({ openMilestones, majorVersion });
if (!nextMilestone) {
- throw new Error(`No open milestone found for major version ${majorVersion}`);
+ throw new Error(
+ `No open milestone found for major version ${majorVersion}`,
+ );
}
- console.log('Next milestone:', nextMilestone.title);
+ console.log("Next milestone:", nextMilestone.title);
// figure out issue or PR
const PRsToCheck = uniq(
- commitMessages
- .flatMap(getPRsFromCommitMessage)
- .filter(isNotNull)
+ commitMessages.flatMap(getPRsFromCommitMessage).filter(isNotNull),
);
if (!PRsToCheck.length) {
// Not every commit on a release branch is a squash-merged PR (e.g. the
// version-bump commit from cutting the branch). Nothing to backfill here.
- console.log('No PRs found in commit messages, skipping milestone backfill');
+ console.log("No PRs found in commit messages, skipping milestone backfill");
return;
}
@@ -256,20 +311,26 @@ export async function setMilestoneForCommits({
const issuesToTag = [];
- for (const prNumber of PRsToCheck) { // for loop to avoid rate limiting
- issuesToTag.push(...(await getOriginalIssues({
- github,
- owner,
- repo,
- issueNumber: prNumber,
- })));
+ for (const prNumber of PRsToCheck) {
+ // for loop to avoid rate limiting
+ issuesToTag.push(
+ ...(await getOriginalIssues({
+ github,
+ owner,
+ repo,
+ issueNumber: prNumber,
+ })),
+ );
}
const uniqueIssuesToTag = uniq(issuesToTag);
- console.log(`Tagging ${uniqueIssuesToTag.length} issues with milestone ${nextMilestone.title}`)
+ console.log(
+ `Tagging ${uniqueIssuesToTag.length} issues with milestone ${nextMilestone.title}`,
+ );
- for (const issueNumber of uniqueIssuesToTag) { // for loop to avoid rate limiting
+ for (const issueNumber of uniqueIssuesToTag) {
+ // for loop to avoid rate limiting
await setMilestone({
github,
owner,
@@ -281,10 +342,15 @@ export async function setMilestoneForCommits({
}
}
-const issueLink = (
- { owner, repo, issueNumber }:
- { owner: string, repo: string, issueNumber: number }
-) => `https://github.com/${owner}/${repo}/issues/${issueNumber}`;
+const issueLink = ({
+ owner,
+ repo,
+ issueNumber,
+}: {
+ owner: string;
+ repo: string;
+ issueNumber: number;
+}) => `https://github.com/${owner}/${repo}/issues/${issueNumber}`;
export async function checkMilestoneForRelease({
github,
@@ -292,7 +358,7 @@ export async function checkMilestoneForRelease({
repo,
version,
commitHash,
-}: GithubProps & { version: string, commitHash: string }) {
+}: GithubProps & { version: string; commitHash: string }) {
// Nothing to audit pre-release, for two reasons:
// - Patches don't have their own milestone — they share the parent minor's.
// - A major's `.0` is, by convention, only ever cut as a pre-release
@@ -319,21 +385,38 @@ export async function checkMilestoneForRelease({
// Safety net: by convention, a `.0` should never be a standalone release.
// If someone breaks that, this check exits early.
if (!lastTag) {
- console.log(`No prior release tag found for ${version}, skipping milestone check`);
+ console.log(
+ `No prior release tag found for ${version}, skipping milestone check`,
+ );
return;
}
- const releaseMilestone = await findMilestone({ github, owner, repo, version });
+ const releaseMilestone = await findMilestone({
+ github,
+ owner,
+ repo,
+ version,
+ });
if (!releaseMilestone) {
throw new Error(`No open milestone found for ${version}`);
}
const closedMilestoneIssues = await getMilestoneIssues({
- github, owner, repo, version, state: 'closed', milestoneStatus: 'open',
+ github,
+ owner,
+ repo,
+ version,
+ state: "closed",
+ milestoneStatus: "open",
});
const openMilestoneIssues = await getMilestoneIssues({
- github, owner, repo, version, state: 'open', milestoneStatus: 'open',
+ github,
+ owner,
+ repo,
+ version,
+ state: "open",
+ milestoneStatus: "open",
});
const compareResponse = await github.rest.repos.compareCommitsWithBasehead({
@@ -347,7 +430,9 @@ export async function checkMilestoneForRelease({
console.log(`Found ${commits.length} commits in release branch`);
console.log(`Found ${closedMilestoneIssues.length} issues in milestone`);
- const milestoneIssueSet = new Set(closedMilestoneIssues.map(issue => issue.number));
+ const milestoneIssueSet = new Set(
+ closedMilestoneIssues.map((issue) => issue.number),
+ );
const commitIssueSet = new Set<number>();
// make sure every commit in the release branch has a corresponding issue in the milestone
@@ -357,7 +442,7 @@ export async function checkMilestoneForRelease({
for (const commit of commits) {
const prNumbers = getPRsFromCommitMessage(commit.commit.message);
if (!prNumbers) {
- console.log('No PRs found in commit message', commit.commit.message);
+ console.log("No PRs found in commit message", commit.commit.message);
continue;
}
@@ -367,25 +452,28 @@ export async function checkMilestoneForRelease({
if (issueNumbers.includes(prNumber)) {
continue;
}
- issueNumbers.push(...(await getOriginalIssues({
- github,
- owner,
- repo,
- issueNumber: prNumber,
- })));
+ issueNumbers.push(
+ ...(await getOriginalIssues({
+ github,
+ owner,
+ repo,
+ issueNumber: prNumber,
+ })),
+ );
}
const uniqueIssues = uniq(issueNumbers.filter(isNotNull));
commitIssueMap[commit.sha] = uniqueIssues;
- uniqueIssues.forEach(issueNumber => {
+ uniqueIssues.forEach((issueNumber) => {
commitIssueSet.add(issueNumber);
issueCommitMap[issueNumber] = commit.sha;
});
}
- const allIssueNumbers = Array.from(commitIssueSet)
- .concat(Array.from(milestoneIssueSet));
+ const allIssueNumbers = Array.from(commitIssueSet).concat(
+ Array.from(milestoneIssueSet),
+ );
const issuesInOlderMilestones = await getIssuesWithOlderMilestones({
github,
@@ -402,19 +490,19 @@ export async function checkMilestoneForRelease({
issueNumbers: allIssueNumbers,
});
- const issuesInMilestoneNotInCommits = closedMilestoneIssues
- .filter(issue =>
+ const issuesInMilestoneNotInCommits = closedMilestoneIssues.filter(
+ (issue) =>
!commitIssueSet.has(issue.number) &&
!issuesWithExcludedTags.has(issue.number) &&
- !issuesInOlderMilestones.has(issue.number)
- );
+ !issuesInOlderMilestones.has(issue.number),
+ );
- const issuesInCommitsNotInMilestone = Array.from(commitIssueSet)
- .filter(issueNumber => (
+ const issuesInCommitsNotInMilestone = Array.from(commitIssueSet).filter(
+ (issueNumber) =>
!milestoneIssueSet.has(issueNumber) &&
!issuesInOlderMilestones.has(issueNumber) &&
- !issuesWithExcludedTags.has(issueNumber)
- ));
+ !issuesWithExcludedTags.has(issueNumber),
+ );
for (const issue of issuesInMilestoneNotInCommits) {
await addIssueToProject({
@@ -423,8 +511,10 @@ export async function checkMilestoneForRelease({
repo,
issueNumber: issue.number,
version,
- comment: 'Issue in milestone, cannot find commit',
- }).catch((e) => console.error(`error adding issue ${issue.number} to project`, e));
+ comment: "Issue in milestone, cannot find commit",
+ }).catch((e) =>
+ console.error(`error adding issue ${issue.number} to project`, e),
+ );
}
for (const issueNumber of issuesInCommitsNotInMilestone) {
@@ -434,8 +524,10 @@ export async function checkMilestoneForRelease({
repo,
issueNumber: issueNumber,
version,
- comment: 'Issue in release branch, needs milestone',
- }).catch((e) => console.error(`error adding issue ${issueNumber} to project`, e));
+ comment: "Issue in release branch, needs milestone",
+ }).catch((e) =>
+ console.error(`error adding issue ${issueNumber} to project`, e),
+ );
}
for (const issue of openMilestoneIssues) {
@@ -445,8 +537,10 @@ export async function checkMilestoneForRelease({
repo,
issueNumber: issue.number,
version,
- comment: 'Issue still open in milestone',
- }).catch((e) => console.error(`error adding issue ${issue.number} to project`, e));
+ comment: "Issue still open in milestone",
+ }).catch((e) =>
+ console.error(`error adding issue ${issue.number} to project`, e),
+ );
}
const logText = await generateLog({
@@ -492,43 +586,55 @@ async function generateLog({
openMilestoneIssues,
commitIssueMap,
}: ReleaseProps & {
- commits: Commit[],
- lastTag: string,
- commitHash: string,
- issuesInMilestoneNotInCommits: Issue[],
- issuesInCommitsNotInMilestone: number[],
- issuesWithExcludedTags: Set<number>,
- issuesInOlderMilestones: Set<number>,
- milestoneIssueSet: Set<number>,
- openMilestoneIssues: Issue[],
- commitIssueMap: Record<string, number[]>,
+ commits: Commit[];
+ lastTag: string;
+ commitHash: string;
+ issuesInMilestoneNotInCommits: Issue[];
+ issuesInCommitsNotInMilestone: number[];
+ issuesWithExcludedTags: Set<number>;
+ issuesInOlderMilestones: Set<number>;
+ milestoneIssueSet: Set<number>;
+ openMilestoneIssues: Issue[];
+ commitIssueMap: Record<string, number[]>;
}) {
let log = `# ${version} Milestone Audit Log\n\n`;
log += `Parsing from ${lastTag} to ${commitHash} \n`;
- log += '## Summary:\n';
+ log += "## Summary:\n";
- log += '\n‼️ Closed Issues in milestone but not in commits:' +
- issuesInMilestoneNotInCommits.map(
- issue => `\n #${issue.number} (${issueLink({ owner, repo, issueNumber: issue.number })})`)
- .join('');
-
- log += '\n‼️ Issues in commits but not in milestone:' +
- issuesInCommitsNotInMilestone.map(
- issueNumber => `\n #${issueNumber} (${issueLink({ owner, repo, issueNumber })})`)
- .join('');
-
- log += '\n‼️ Open issues in milestone:' +
- openMilestoneIssues.map(
- issue => `\n #${issue.number} (${issueLink({ owner, repo, issueNumber: issue.number })})`)
- .join('');
+ log +=
+ "\n‼️ Closed Issues in milestone but not in commits:" +
+ issuesInMilestoneNotInCommits
+ .map(
+ (issue) =>
+ `\n #${issue.number} (${issueLink({ owner, repo, issueNumber: issue.number })})`,
+ )
+ .join("");
+
+ log +=
+ "\n‼️ Issues in commits but not in milestone:" +
+ issuesInCommitsNotInMilestone
+ .map(
+ (issueNumber) =>
+ `\n #${issueNumber} (${issueLink({ owner, repo, issueNumber })})`,
+ )
+ .join("");
+
+ log +=
+ "\n‼️ Open issues in milestone:" +
+ openMilestoneIssues
+ .map(
+ (issue) =>
+ `\n #${issue.number} (${issueLink({ owner, repo, issueNumber: issue.number })})`,
+ )
+ .join("");
- log += '\n\n## Commits in release branch\n';
+ log += "\n\n## Commits in release branch\n";
for (const hash in commitIssueMap) {
- const msg = commits.find(commit => commit.sha === hash)?.commit.message;
- log += `\n➡️ ${msg?.split('\n')[0]} [${hash.slice(0, 7)}]\n`;
+ const msg = commits.find((commit) => commit.sha === hash)?.commit.message;
+ log += `\n➡️ ${msg?.split("\n")[0]} [${hash.slice(0, 7)}]\n`;
for (const issueNumber of commitIssueMap[hash]) {
if (milestoneIssueSet.has(issueNumber)) {
@@ -543,9 +649,9 @@ async function generateLog({
issueNumber,
});
const excludedTags = issue ? getExcludedLabels(issue) : [];
- log += ` ✅ Issue #${issueNumber} has excluded tags: ${excludedTags.map(l => l.name).join(',')}\n`;
+ log += ` ✅ Issue #${issueNumber} has excluded tags: ${excludedTags.map((l) => l.name).join(",")}\n`;
} else {
- log +=` ❌ Issue #${issueNumber} is not in milestone, but probably should be (${issueLink({ owner, repo, issueNumber })})\n`;
+ log += ` ❌ Issue #${issueNumber} is not in milestone, but probably should be (${issueLink({ owner, repo, issueNumber })})\n`;
}
}
}
@@ -554,9 +660,9 @@ async function generateLog({
}
const releaseIssueProject = {
- id: 'PVT_kwDOAKCINc4Ajw5A',
- commentColId: 'PVTF_lADOAKCINc4Ajw5AzgcE7NA',
- versionColId: 'PVTF_lADOAKCINc4Ajw5AzgcE7PY',
+ id: "PVT_kwDOAKCINc4Ajw5A",
+ commentColId: "PVTF_lADOAKCINc4Ajw5AzgcE7NA",
+ versionColId: "PVTF_lADOAKCINc4Ajw5AzgcE7PY",
};
async function addIssueToProject({
@@ -566,7 +672,7 @@ async function addIssueToProject({
issueNumber,
comment,
version,
-}: GithubProps & { issueNumber: number, comment: string, version: string }) {
+}: GithubProps & { issueNumber: number; comment: string; version: string }) {
console.log(`Possible problem issue: #${issueNumber} - ${comment}`);
const issue = await getIssueWithCache({
@@ -587,13 +693,13 @@ async function addIssueToProject({
},
});
- const response = await graphqlWithAuth(`mutation {
+ const response = (await graphqlWithAuth(`mutation {
addProjectV2ItemById(input: {
projectId: "${releaseIssueProject.id}",
contentId: "${issue?.node_id}"
})
{ item { id } }
- }`) as { addProjectV2ItemById: { item: { id: string } } };
+ }`)) as { addProjectV2ItemById: { item: { id: string } } };
const itemId = response.addProjectV2ItemById.item.id;
diff --git a/release/src/milestones.unit.spec.ts b/release/src/milestones.unit.spec.ts
index 8595decfc33..c172bceeb70 100644
--- a/release/src/milestones.unit.spec.ts
+++ b/release/src/milestones.unit.spec.ts
@@ -5,78 +5,94 @@ import {
} from "./milestones";
import type { Milestone } from "./types";
-describe('milestones', () => {
+describe("milestones", () => {
const testMilestones = [
- { number: 577, title: '0.57.7' },
- { number: 578, title: '0.57.8' },
- { number: 580, title: '0.58' },
- { number: 581, title: '0.58.1' },
- { number: 599, title: '0.59.9' },
- { number: 5910, title: '0.59.10' },
- { number: 600, title: '0.60' },
- { number: 6010, title: '0.60.10' },
- { number: 6111, title: '0.61.1.1' },
- { number: 612, title: '0.61.2' },
- { number: 613, title: '0.61.3'},
- { number: 621, title: '0.62.1'},
- { number: 6220, title: '0.62.20'},
- { number: 62300, title: '0.62.300'},
- { number: 630, title: '0.63'},
+ { number: 577, title: "0.57.7" },
+ { number: 578, title: "0.57.8" },
+ { number: 580, title: "0.58" },
+ { number: 581, title: "0.58.1" },
+ { number: 599, title: "0.59.9" },
+ { number: 5910, title: "0.59.10" },
+ { number: 600, title: "0.60" },
+ { number: 6010, title: "0.60.10" },
+ { number: 6111, title: "0.61.1.1" },
+ { number: 612, title: "0.61.2" },
+ { number: 613, title: "0.61.3" },
+ { number: 621, title: "0.62.1" },
+ { number: 6220, title: "0.62.20" },
+ { number: 62300, title: "0.62.300" },
+ { number: 630, title: "0.63" },
] as Milestone[];
- describe('getNextMilestone', () => {
- it('can detect the next milestone for minor versions', () => {
- expect(getNextMilestone({
- openMilestones: testMilestones,
- majorVersion: 57,
- })?.number).toBe(577);
-
- expect(getNextMilestone({
- openMilestones: testMilestones,
- majorVersion: 59,
- })?.number).toBe(599);
-
- expect(getNextMilestone({
- openMilestones: testMilestones,
- majorVersion: 62,
- })?.number).toBe(621);
+ describe("getNextMilestone", () => {
+ it("can detect the next milestone for minor versions", () => {
+ expect(
+ getNextMilestone({
+ openMilestones: testMilestones,
+ majorVersion: 57,
+ })?.number,
+ ).toBe(577);
+
+ expect(
+ getNextMilestone({
+ openMilestones: testMilestones,
+ majorVersion: 59,
+ })?.number,
+ ).toBe(599);
+
+ expect(
+ getNextMilestone({
+ openMilestones: testMilestones,
+ majorVersion: 62,
+ })?.number,
+ ).toBe(621);
});
- it('can detect the next milestone for major versions', () => {
- expect(getNextMilestone({
- openMilestones: testMilestones,
- majorVersion: 63,
- })?.number).toBe(630);
+ it("can detect the next milestone for major versions", () => {
+ expect(
+ getNextMilestone({
+ openMilestones: testMilestones,
+ majorVersion: 63,
+ })?.number,
+ ).toBe(630);
});
- it('can detect the next milestone for mixed major and minor versions', () => {
- expect(getNextMilestone({
- openMilestones: testMilestones,
- majorVersion: 58,
- })?.number).toBe(580);
-
- expect(getNextMilestone({
- openMilestones: testMilestones,
- majorVersion: 60,
- })?.number).toBe(600);
+ it("can detect the next milestone for mixed major and minor versions", () => {
+ expect(
+ getNextMilestone({
+ openMilestones: testMilestones,
+ majorVersion: 58,
+ })?.number,
+ ).toBe(580);
+
+ expect(
+ getNextMilestone({
+ openMilestones: testMilestones,
+ majorVersion: 60,
+ })?.number,
+ ).toBe(600);
});
- it('should return undefined when milestone is missing', () => {
- expect(getNextMilestone({
- openMilestones: testMilestones,
- majorVersion: 56,
- })?.number).toBe(undefined);
+ it("should return undefined when milestone is missing", () => {
+ expect(
+ getNextMilestone({
+ openMilestones: testMilestones,
+ majorVersion: 56,
+ })?.number,
+ ).toBe(undefined);
});
- it('should ignore patch versions', () => {
- expect(getNextMilestone({
- openMilestones: testMilestones,
- majorVersion: 61,
- })?.number).toBe(612);
+ it("should ignore patch versions", () => {
+ expect(
+ getNextMilestone({
+ openMilestones: testMilestones,
+ majorVersion: 61,
+ })?.number,
+ ).toBe(612);
});
});
- describe('setMilestoneForCommits', () => {
+ describe("setMilestoneForCommits", () => {
const buildGithub = () => ({
paginate: jest.fn().mockResolvedValue(testMilestones),
rest: {
@@ -87,30 +103,32 @@ describe('milestones', () => {
},
});
- it('is a no-op when no commit messages reference a PR', async () => {
+ it("is a no-op when no commit messages reference a PR", async () => {
const github = buildGithub();
// e.g. the version-bump commit created when cutting a release branch
- await expect(setMilestoneForCommits({
- github: github as any,
- owner: 'metabase',
- repo: 'metabase',
- branchName: 'release-x.57.x',
- commitMessages: ['Bump version to v0.57'],
- })).resolves.toBeUndefined();
+ await expect(
+ setMilestoneForCommits({
+ github: github as any,
+ owner: "metabase",
+ repo: "metabase",
+ branchName: "release-x.57.x",
+ commitMessages: ["Bump version to v0.57"],
+ }),
+ ).resolves.toBeUndefined();
expect(github.rest.issues.update).not.toHaveBeenCalled();
});
});
- describe('checkMilestoneForRelease', () => {
+ describe("checkMilestoneForRelease", () => {
// string sentinels so paginate can dispatch on which rest endpoint it got
- const listMilestones = 'listMilestones';
- const listForRepo = 'listForRepo';
- const listMatchingRefs = 'listMatchingRefs';
+ const listMilestones = "listMilestones";
+ const listForRepo = "listForRepo";
+ const listMatchingRefs = "listMatchingRefs";
const buildGithub = ({
- milestones = [{ number: 620, title: '0.62' }] as Milestone[],
+ milestones = [{ number: 620, title: "0.62" }] as Milestone[],
tags = [] as { ref: string }[],
} = {}) => {
const rest = {
@@ -126,46 +144,60 @@ describe('milestones', () => {
return { paginate, rest };
};
- it('is a no-op for a pre-release, bailing before any API calls (a major .0 is always cut as a beta/RC)', async () => {
+ it("is a no-op for a pre-release, bailing before any API calls (a major .0 is always cut as a beta/RC)", async () => {
const github = buildGithub();
- await expect(checkMilestoneForRelease({
- github: github as any,
- owner: 'metabase',
- repo: 'metabase',
- version: 'v0.62.0-beta',
- commitHash: 'b36890cda1b4bd8009b3c416c071937273fe87dc',
- })).resolves.toBeUndefined();
+ await expect(
+ checkMilestoneForRelease({
+ github: github as any,
+ owner: "metabase",
+ repo: "metabase",
+ version: "v0.62.0-beta",
+ commitHash: "b36890cda1b4bd8009b3c416c071937273fe87dc",
+ }),
+ ).resolves.toBeUndefined();
// never attempt the compare with an `undefined` base ref
- expect(github.rest.repos.compareCommitsWithBasehead).not.toHaveBeenCalled();
+ expect(
+ github.rest.repos.compareCommitsWithBasehead,
+ ).not.toHaveBeenCalled();
// and bail before touching the API at all — not even the tag list
expect(github.paginate).not.toHaveBeenCalled();
});
- it('safety net: skips when there is no prior stable tag in this major, without comparing against `undefined`', async () => {
+ it("safety net: skips when there is no prior stable tag in this major, without comparing against `undefined`", async () => {
// A stable .0 shouldn't happen by convention, but if one ever reaches
// here, getLastReleaseTag finds no stable base and we must not feed
// `undefined` into the compare API.
const github = buildGithub({
tags: [
- { ref: 'refs/tags/v0.62.0-beta' },
- { ref: 'refs/tags/v0.62.0-RC1' },
+ { ref: "refs/tags/v0.62.0-beta" },
+ { ref: "refs/tags/v0.62.0-RC1" },
],
});
- await expect(checkMilestoneForRelease({
- github: github as any,
- owner: 'metabase',
- repo: 'metabase',
- version: 'v0.62.0',
- commitHash: 'b36890cda1b4bd8009b3c416c071937273fe87dc',
- })).resolves.toBeUndefined();
-
- expect(github.rest.repos.compareCommitsWithBasehead).not.toHaveBeenCalled();
+ await expect(
+ checkMilestoneForRelease({
+ github: github as any,
+ owner: "metabase",
+ repo: "metabase",
+ version: "v0.62.0",
+ commitHash: "b36890cda1b4bd8009b3c416c071937273fe87dc",
+ }),
+ ).resolves.toBeUndefined();
+
+ expect(
+ github.rest.repos.compareCommitsWithBasehead,
+ ).not.toHaveBeenCalled();
// only the tag list was queried, then we bailed before milestone lookups
- expect(github.paginate).toHaveBeenCalledWith(listMatchingRefs, expect.anything());
- expect(github.paginate).not.toHaveBeenCalledWith(listMilestones, expect.anything());
+ expect(github.paginate).toHaveBeenCalledWith(
+ listMatchingRefs,
+ expect.anything(),
+ );
+ expect(github.paginate).not.toHaveBeenCalledWith(
+ listMilestones,
+ expect.anything(),
+ );
});
});
});
diff --git a/release/src/release-branch-commits.ts b/release/src/release-branch-commits.ts
index 2ef154c87c9..6d6502c6cd5 100644
--- a/release/src/release-branch-commits.ts
+++ b/release/src/release-branch-commits.ts
@@ -1,15 +1,19 @@
-import {$} from 'zx';
+import { $ } from "zx";
-export async function getReleaseBranchCommits(
- { versionNumber }: { versionNumber: number }
-) {
+export async function getReleaseBranchCommits({
+ versionNumber,
+}: {
+ versionNumber: number;
+}) {
const lastMajorVersion = versionNumber - 1;
// find where the last branch split off of master
- const { stdout: branchCommit } = await $`git merge-base origin/release-x.${lastMajorVersion}.x master`;
- const { stdout: commitMessages } = await $`git log ${branchCommit.trim()}..origin/release-x.${versionNumber}.x --pretty='format:%s'`;
+ const { stdout: branchCommit } =
+ await $`git merge-base origin/release-x.${lastMajorVersion}.x master`;
+ const { stdout: commitMessages } =
+ await $`git log ${branchCommit.trim()}..origin/release-x.${versionNumber}.x --pretty='format:%s'`;
- return commitMessages.split('\n')
+ return commitMessages.split("\n");
}
const versionNumber = Number(process.argv[2]);
diff --git a/release/src/release-log-run.ts b/release/src/release-log-run.ts
index 63d9e7d881f..51f677dd599 100644
--- a/release/src/release-log-run.ts
+++ b/release/src/release-log-run.ts
@@ -1,3 +1,3 @@
-import { generateReleaseLog } from './release-log';
+import { generateReleaseLog } from "./release-log";
console.log(await generateReleaseLog());
diff --git a/release/src/release-log.ts b/release/src/release-log.ts
index 7ffc757637c..d1aa158cf03 100644
--- a/release/src/release-log.ts
+++ b/release/src/release-log.ts
@@ -1,42 +1,46 @@
-import fs from 'fs';
+import fs from "fs";
-import { Octokit } from '@octokit/rest';
-import { $ } from 'zx';
+import { Octokit } from "@octokit/rest";
+import { $ } from "zx";
-import { getOpenBackportPrs } from './github';
-import { issueNumberRegex } from './linked-issues';
+import { getOpenBackportPrs } from "./github";
+import { issueNumberRegex } from "./linked-issues";
type CommitInfo = {
- versions: string[],
- message: string,
- hash: string,
- date: string,
-}
+ versions: string[];
+ message: string;
+ hash: string;
+ date: string;
+};
-const tablePageTemplate = fs.readFileSync('./src/tablePageTemplate.html', 'utf8');
+const tablePageTemplate = fs.readFileSync(
+ "./src/tablePageTemplate.html",
+ "utf8",
+);
export async function gitLog(majorVersion: number) {
const previousMajorVersion = majorVersion - 1; // we want to parse back to the prior major version to get everything in the .0 release.
- const { stdout: baseCommit } = await $`git merge-base origin/release-x.${previousMajorVersion}.x origin/master`;
- const { stdout } = await $`git log ${baseCommit.trim()}..origin/release-x.${majorVersion}.x --pretty='format:%(decorate:prefix=,suffix=)||%s||%H||%ah'`;
- const processedCommits = stdout.split('\n').map(processCommit);
+ const { stdout: baseCommit } =
+ await $`git merge-base origin/release-x.${previousMajorVersion}.x origin/master`;
+ const { stdout } =
+ await $`git log ${baseCommit.trim()}..origin/release-x.${majorVersion}.x --pretty='format:%(decorate:prefix=,suffix=)||%s||%H||%ah'`;
+ const processedCommits = stdout.split("\n").map(processCommit);
return buildTable(processedCommits);
}
export function processCommit(commitLine: string): CommitInfo {
- const [refs, message, hash, date] = commitLine.split('||');
- const tags = refs?.match(/tag: ([\w\d-_x\.]+)/g) ?? '';
+ const [refs, message, hash, date] = commitLine.split("||");
+ const tags = refs?.match(/tag: ([\w\d-_x\.]+)/g) ?? "";
- const versions = tags
- ? tags.map((v) => v.replace('tag: ', ''))
- : [''];
+ const versions = tags ? tags.map((v) => v.replace("tag: ", "")) : [""];
- return { versions, message, hash, date};
+ return { versions, message, hash, date };
}
-const issueLink = (issueNumber: string) => `https://github.com/metabase/metabase/issues/${issueNumber}`;
+const issueLink = (issueNumber: string) =>
+ `https://github.com/metabase/metabase/issues/${issueNumber}`;
-function escapeHtml(unsafe: string = '') {
+function escapeHtml(unsafe: string = "") {
return unsafe
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
@@ -46,21 +50,25 @@ function escapeHtml(unsafe: string = '') {
}
function linkifyIssueNumbers(message: string) {
- return escapeHtml(message)?.replace(issueNumberRegex, (_, issueNumber) => {
- return `<a href="${issueLink(issueNumber)}" target="_blank">(#${issueNumber})</a>`;
- }) ?? message ?? '';
+ return (
+ escapeHtml(message)?.replace(issueNumberRegex, (_, issueNumber) => {
+ return `<a href="${issueLink(issueNumber)}" target="_blank">(#${issueNumber})</a>`;
+ }) ??
+ message ??
+ ""
+ );
}
function tableRow(commit: CommitInfo) {
return `<tr>
- <td><strong>${commit.versions.join('<br>')}</strong></td>
+ <td><strong>${commit.versions.join("<br>")}</strong></td>
<td>${linkifyIssueNumbers(commit.message)}</td>
<td>${commit.date}</td>
</tr>`;
}
function buildTable(commits: CommitInfo[]) {
- const rows = commits.map(tableRow).join('\n');
+ const rows = commits.map(tableRow).join("\n");
const tableHtml = `
<table>
<thead>
@@ -79,23 +87,25 @@ function buildTable(commits: CommitInfo[]) {
}
type PullRequest = {
- html_url: string,
- number: number,
- title: string,
- assignee: { login: string },
- created_at: string,
-}
+ html_url: string;
+ number: number;
+ title: string;
+ assignee: { login: string };
+ created_at: string;
+};
function createBackportTable(prs: PullRequest[]) {
- const rows = prs.map(pr => {
- const assignee = pr.assignee ? pr.assignee.login : '?';
- return `<tr>
+ const rows = prs
+ .map((pr) => {
+ const assignee = pr.assignee ? pr.assignee.login : "?";
+ return `<tr>
<td><a href="${pr.html_url}" target="_blank">#${pr.number}</a></td>
<td>${linkifyIssueNumbers(pr.title)}</td>
<td>@${assignee}</td>
<td>${new Date(pr.created_at).toLocaleString()}</td>
</tr>`;
- }).join('\n');
+ })
+ .join("\n");
return `<table>
<thead>
@@ -112,12 +122,11 @@ function createBackportTable(prs: PullRequest[]) {
</table>`;
}
-
export async function generateReleaseLog() {
const version = Number(process.argv[2]);
if (!version) {
- console.error('Please provide a version number (e.g. 35, 57)');
+ console.error("Please provide a version number (e.g. 35, 57)");
process.exit(1);
}
@@ -127,8 +136,8 @@ export async function generateReleaseLog() {
const backportPRs = await getOpenBackportPrs({
github,
- owner: 'metabase',
- repo: 'metabase',
+ owner: "metabase",
+ repo: "metabase",
majorVersion: version,
});
diff --git a/release/src/release-log.unit.spec.ts b/release/src/release-log.unit.spec.ts
index 5b52565f33e..e0fcd8d7cef 100644
--- a/release/src/release-log.unit.spec.ts
+++ b/release/src/release-log.unit.spec.ts
@@ -1,45 +1,48 @@
-import { processCommit } from './release-log';
+import { processCommit } from "./release-log";
-describe('Release Log', () => {
- describe('processCommit', () => {
- it('should return an array of commit info objects with versions', () => {
- const commitLine = 'tag: v1.50.0-RC2, tag: v0.50.0-RC2||Show the columns for the correct stage when using combine/extract in the presence of an aggregation (#43226) (#43450)||7a8b73e298e0d658e2fcd6b1fbcac3e0d0770288||Mon Jun 3 03:31';
+describe("Release Log", () => {
+ describe("processCommit", () => {
+ it("should return an array of commit info objects with versions", () => {
+ const commitLine =
+ "tag: v1.50.0-RC2, tag: v0.50.0-RC2||Show the columns for the correct stage when using combine/extract in the presence of an aggregation (#43226) (#43450)||7a8b73e298e0d658e2fcd6b1fbcac3e0d0770288||Mon Jun 3 03:31";
const result = processCommit(commitLine);
expect(result).toEqual({
- versions: ['v1.50.0-RC2', 'v0.50.0-RC2'],
- message: 'Show the columns for the correct stage when using combine/extract in the presence of an aggregation (#43226) (#43450)',
- hash: '7a8b73e298e0d658e2fcd6b1fbcac3e0d0770288',
- date: 'Mon Jun 3 03:31',
+ versions: ["v1.50.0-RC2", "v0.50.0-RC2"],
+ message:
+ "Show the columns for the correct stage when using combine/extract in the presence of an aggregation (#43226) (#43450)",
+ hash: "7a8b73e298e0d658e2fcd6b1fbcac3e0d0770288",
+ date: "Mon Jun 3 03:31",
});
});
- it('should return an empty string in an array when there are no tags', () => {
- const commitLine = '||fix stacked data labels on ordinal charts (#43469) (#43508)||37c901325cdf9cdb96091e4c159c849fd65df9f5||Mon Jun 3 11:03';
+ it("should return an empty string in an array when there are no tags", () => {
+ const commitLine =
+ "||fix stacked data labels on ordinal charts (#43469) (#43508)||37c901325cdf9cdb96091e4c159c849fd65df9f5||Mon Jun 3 11:03";
const result = processCommit(commitLine);
expect(result).toEqual({
- versions: [''],
- message: 'fix stacked data labels on ordinal charts (#43469) (#43508)',
- hash: '37c901325cdf9cdb96091e4c159c849fd65df9f5',
- date: 'Mon Jun 3 11:03',
+ versions: [""],
+ message: "fix stacked data labels on ordinal charts (#43469) (#43508)",
+ hash: "37c901325cdf9cdb96091e4c159c849fd65df9f5",
+ date: "Mon Jun 3 11:03",
});
});
- it('should gracefully handle malformed logs', () => {
- const commitLine = ' foo bar baz | la dee da pikachu;\r\n$20 ';
+ it("should gracefully handle malformed logs", () => {
+ const commitLine = " foo bar baz | la dee da pikachu;\r\n$20 ";
const result = processCommit(commitLine);
expect(result).toEqual({
- versions: [''],
+ versions: [""],
message: undefined,
hash: undefined,
date: undefined,
});
});
- it('should gracefully handle empty logs', () => {
- const commitLine = '';
+ it("should gracefully handle empty logs", () => {
+ const commitLine = "";
const result = processCommit(commitLine);
expect(result).toEqual({
- versions: [''],
+ versions: [""],
message: undefined,
hash: undefined,
date: undefined,
diff --git a/release/src/release-notes-templates.ts b/release/src/release-notes-templates.ts
index 9b82a7535f6..99e0d2bb8ef 100644
--- a/release/src/release-notes-templates.ts
+++ b/release/src/release-notes-templates.ts
@@ -1,4 +1,3 @@
-
export const githubReleaseTemplate = `## Upgrading
> Before you upgrade, back up your Metabase application database!
diff --git a/release/src/release-notes.ts b/release/src/release-notes.ts
index b8e1ad3ff2f..b4e9c06bb27 100644
--- a/release/src/release-notes.ts
+++ b/release/src/release-notes.ts
@@ -3,7 +3,10 @@ import { match } from "ts-pattern";
import { hiddenLabels, nonUserFacingLabels } from "./constants";
import { getMilestoneIssues, hasBeenReleased } from "./github";
import { issueNumberRegex } from "./linked-issues";
-import { githubReleaseTemplate, websiteChangelogTemplate } from "./release-notes-templates";
+import {
+ githubReleaseTemplate,
+ websiteChangelogTemplate,
+} from "./release-notes-templates";
import type { Issue, ReleaseProps } from "./types";
import {
getDotXVersion,
@@ -17,12 +20,11 @@ import {
isValidVersionString,
} from "./version-helpers";
-
const hasLabel = (issue: Issue, label: string) => {
if (typeof issue.labels === "string") {
return issue.labels.includes(label);
}
- return issue.labels.some(tag => tag.name === label);
+ return issue.labels.some((tag) => tag.name === label);
};
const isBugIssue = (issue: Issue) => {
@@ -34,11 +36,11 @@ const isAlreadyFixedIssue = (issue: Issue) => {
};
const isNonUserFacingIssue = (issue: Issue) => {
- return nonUserFacingLabels.some(label => hasLabel(issue, label));
+ return nonUserFacingLabels.some((label) => hasLabel(issue, label));
};
const isHiddenIssue = (issue: Issue) => {
- return hiddenLabels.some(label => hasLabel(issue, label));
+ return hiddenLabels.some((label) => hasLabel(issue, label));
};
const formatIssue = (issue: Issue) =>
@@ -62,11 +64,11 @@ export const getDownloadUrl = (version: string) => {
}${dotXVersion}/metabase.jar`;
};
-export const getChangelogUrl = (version: string ) => {
+export const getChangelogUrl = (version: string) => {
const majorVersion = getMajorVersion(version);
const minorVersion = getMinorVersion(version);
- return `https://www.metabase.com/changelog/${majorVersion}#metabase-${majorVersion}${minorVersion}`
-}
+ return `https://www.metabase.com/changelog/${majorVersion}#metabase-${majorVersion}${minorVersion}`;
+};
export const getReleaseTitle = (version: string) => {
return `Metabase ${getGenericVersion(version)}`;
@@ -129,7 +131,7 @@ const getLabels = (issue: Issue): string[] => {
if (typeof issue.labels === "string") {
return issue.labels.split(",");
}
- return issue.labels.map(label => label.name || "");
+ return issue.labels.map((label) => label.name || "");
};
const hasCategory = (issue: Issue, labelPart: string): boolean => {
@@ -154,7 +156,10 @@ export const getProductCategory = (issue: Issue): ProductCategory => {
};
// Format issues for a single product category
-const formatIssueCategory = (categoryName: ProductCategory, issues: Issue[]): string => {
+const formatIssueCategory = (
+ categoryName: ProductCategory,
+ issues: Issue[],
+): string => {
return `**${categoryName}**\n\n${issues.map(formatIssue).join("\n")}`;
};
@@ -167,46 +172,46 @@ const sortCategories = (categories: ProductCategory[]) => {
.filter((cat) => cat !== otherProductCategory)
.sort((a, b) => a.localeCompare(b));
- return [
- ...sortedCategories,
- ...uncategorizedIssues,
- ];
+ return [...sortedCategories, ...uncategorizedIssues];
};
// For each issue category ("Enhancements", "Bug Fixes", etc.), we want to group issues by product category
const formatIssues = (issueMap: CategoryIssueMap): string => {
- const categories = sortCategories(
- Object.keys(issueMap) as ProductCategory[],
- );
+ const categories = sortCategories(Object.keys(issueMap) as ProductCategory[]);
return categories
- .map(categoryName => formatIssueCategory(categoryName, issueMap[categoryName]))
+ .map((categoryName) =>
+ formatIssueCategory(categoryName, issueMap[categoryName]),
+ )
.join("\n\n");
};
export const categorizeIssues = (issues: Issue[]) => {
return issues
- .filter(issue => !isHiddenIssue(issue))
- .reduce((issueMap: IssueMap, issue: Issue) => {
- const issueType = getIssueType(issue);
- const productCategory = getProductCategory(issue);
-
- return {
- ...issueMap,
- [issueType]: {
- ...issueMap[issueType],
- [productCategory]: [
- ...issueMap[issueType][productCategory] ?? [],
- issue,
- ],
- },
- };
- }, {
- [IssueType.bugFixes]: {},
- [IssueType.enhancements]: {},
- [IssueType.alreadyFixedIssues]: {},
- [IssueType.underTheHoodIssues]: {},
- } as IssueMap);
+ .filter((issue) => !isHiddenIssue(issue))
+ .reduce(
+ (issueMap: IssueMap, issue: Issue) => {
+ const issueType = getIssueType(issue);
+ const productCategory = getProductCategory(issue);
+
+ return {
+ ...issueMap,
+ [issueType]: {
+ ...issueMap[issueType],
+ [productCategory]: [
+ ...(issueMap[issueType][productCategory] ?? []),
+ issue,
+ ],
+ },
+ };
+ },
+ {
+ [IssueType.bugFixes]: {},
+ [IssueType.enhancements]: {},
+ [IssueType.alreadyFixedIssues]: {},
+ [IssueType.underTheHoodIssues]: {},
+ } as IssueMap,
+ );
};
export const generateReleaseNotes = ({
@@ -225,18 +230,9 @@ export const generateReleaseNotes = ({
return template
.replace("{{version}}", getGenericVersion(version))
- .replace(
- "{{enhancements}}",
- formatIssues(issuesByType.enhancements),
- )
- .replace(
- "{{bug-fixes}}",
- formatIssues(issuesByType.bugFixes),
- )
- .replace(
- "{{already-fixed}}",
- formatIssues(issuesByType.alreadyFixedIssues),
- )
+ .replace("{{enhancements}}", formatIssues(issuesByType.enhancements))
+ .replace("{{bug-fixes}}", formatIssues(issuesByType.bugFixes))
+ .replace("{{already-fixed}}", formatIssues(issuesByType.alreadyFixedIssues))
.replace(
"{{under-the-hood}}",
formatIssues(issuesByType.underTheHoodIssues),
@@ -275,18 +271,26 @@ export async function publishRelease({
return github.rest.repos.createRelease(payload);
}
-const issueLink = (issueNumber: string) => `https://github.com/metabase/metabase/issues/${issueNumber}`;
+const issueLink = (issueNumber: string) =>
+ `https://github.com/metabase/metabase/issues/${issueNumber}`;
export function markdownIssueLinks(text: string) {
- return text?.replaceAll(issueNumberRegex, (_, issueNumber) => {
- return `([#${issueNumber}](${issueLink(issueNumber)}))`;
- }) ?? text ?? '';
+ return (
+ text?.replaceAll(issueNumberRegex, (_, issueNumber) => {
+ return `([#${issueNumber}](${issueLink(issueNumber)}))`;
+ }) ??
+ text ??
+ ""
+ );
}
export function getWebsiteChangelog({
version,
issues,
-}: { version: string; issues: Issue[]; }) {
+}: {
+ version: string;
+ issues: Issue[];
+}) {
if (!isValidVersionString(version)) {
throw new Error(`Invalid version string: ${version}`);
}
@@ -329,4 +333,4 @@ export async function getChangelog({
version,
issues,
});
-}
\ No newline at end of file
+}
diff --git a/release/src/slack.ts b/release/src/slack.ts
index 26b9ed81d53..c3fb5b9804a 100644
--- a/release/src/slack.ts
+++ b/release/src/slack.ts
@@ -1,11 +1,11 @@
-import 'dotenv/config';
-import fs from 'fs';
+import "dotenv/config";
+import fs from "fs";
-import { WebClient } from '@slack/web-api';
-import type { Block, KnownBlock, MessageAttachment } from '@slack/web-api';
-import dayjs from 'dayjs';
-import relativeTime from 'dayjs/plugin/relativeTime';
-import fetch from 'node-fetch';
+import { WebClient } from "@slack/web-api";
+import type { Block, KnownBlock, MessageAttachment } from "@slack/web-api";
+import dayjs from "dayjs";
+import relativeTime from "dayjs/plugin/relativeTime";
+import fetch from "node-fetch";
dayjs.extend(relativeTime);
@@ -14,7 +14,7 @@ import _githubSlackMap from "../github-slack-map.json";
const githubSlackMap: Record<string, string> = _githubSlackMap;
import { findMilestone } from "./github";
-import type { Issue , ReleaseProps } from './types';
+import type { Issue, ReleaseProps } from "./types";
import { getGenericVersion } from "./version-helpers";
const slack = new WebClient(process.env.SLACK_BOT_TOKEN);
@@ -24,7 +24,7 @@ export function mentionUserByGithubLogin(githubLogin?: string | null) {
if (githubLogin && githubLogin in githubSlackMap) {
return `<@${githubSlackMap[githubLogin]}>`;
}
- return githubLogin ? `@${githubLogin}` : '@unassigned';
+ return githubLogin ? `@${githubLogin}` : "@unassigned";
}
export function mentionSlackTeam(teamName: string) {
@@ -32,126 +32,144 @@ export function mentionSlackTeam(teamName: string) {
}
export function getChannelTopic(channelName: string) {
- return slack.conversations.list({
- types: 'public_channel',
- }).then(response => {
- const channel = response?.channels?.find(channel => channel.name === channelName);
- return channel?.topic?.value;
- });
+ return slack.conversations
+ .list({
+ types: "public_channel",
+ })
+ .then((response) => {
+ const channel = response?.channels?.find(
+ (channel) => channel.name === channelName,
+ );
+ return channel?.topic?.value;
+ });
}
-function formatBackportItem(issue: Omit<Issue, 'labels'>,) {
+function formatBackportItem(issue: Omit<Issue, "labels">) {
const age = dayjs(issue.created_at).fromNow();
return `${mentionUserByGithubLogin(issue.assignee?.login)} - ${slackLink(issue.title, issue.html_url)} - ${age}`;
}
export async function sendBackportReminder({
- channelName, backports,
+ channelName,
+ backports,
}: {
- channelName: string,
- backports: Omit<Issue, 'labels'>[],
+ channelName: string;
+ backports: Omit<Issue, "labels">[];
}) {
- const text = backports
- .reverse()
- .map(formatBackportItem).join("\n");
-
- const blocks = [
- {
- "type": "header",
- "text": {
- "type": "plain_text",
- "text": `:shame-conga: ${backports.length} Open Backports :shame-conga:`,
- "emoji": true
- }
+ const text = backports.reverse().map(formatBackportItem).join("\n");
+
+ const blocks = [
+ {
+ type: "header",
+ text: {
+ type: "plain_text",
+ text: `:shame-conga: ${backports.length} Open Backports :shame-conga:`,
+ emoji: true,
},
- {
- "type": "section",
- "text": {
- "type": "mrkdwn",
- "text": `_${
- slackLink('See all open backports','https://github.com/metabase/metabase/pulls?q=is%3Aopen+is%3Apr+label%3Awas-backported')} | ${
- slackLink('Should I backport this?', 'https://www.notion.so/metabase/Metabase-Branching-Strategy-6eb577d5f61142aa960a626d6bbdfeb3?pvs=4#89f80d6f17714a0198aeb66c0efd1b71')}_`,
- }
+ },
+ {
+ type: "section",
+ text: {
+ type: "mrkdwn",
+ text: `_${slackLink(
+ "See all open backports",
+ "https://github.com/metabase/metabase/pulls?q=is%3Aopen+is%3Apr+label%3Awas-backported",
+ )} | ${slackLink(
+ "Should I backport this?",
+ "https://www.notion.so/metabase/Metabase-Branching-Strategy-6eb577d5f61142aa960a626d6bbdfeb3?pvs=4#89f80d6f17714a0198aeb66c0efd1b71",
+ )}_`,
},
- ];
-
- const MAX_CHARACTERS_PER_BLOCK = 2800;
- const chunks = Math.ceil(text.length / MAX_CHARACTERS_PER_BLOCK);
-
- const lines = text.split("\n");
- const chunkSize = Math.floor(lines.length / chunks);
- const chunkedLines = chunk(lines, chunkSize);
-
- const attachments = [{
- "color": "#F9841A",
- "blocks": chunkedLines.map(lines => ({
- "type": "section",
- "text": {
- "type": "mrkdwn",
- "text": lines.join("\n"),
+ },
+ ];
+
+ const MAX_CHARACTERS_PER_BLOCK = 2800;
+ const chunks = Math.ceil(text.length / MAX_CHARACTERS_PER_BLOCK);
+
+ const lines = text.split("\n");
+ const chunkSize = Math.floor(lines.length / chunks);
+ const chunkedLines = chunk(lines, chunkSize);
+
+ const attachments = [
+ {
+ color: "#F9841A",
+ blocks: chunkedLines.map((lines) => ({
+ type: "section",
+ text: {
+ type: "mrkdwn",
+ text: lines.join("\n"),
},
})),
- }];
+ },
+ ];
- return slack.chat.postMessage({
- channel: channelName,
- blocks,
- attachments,
- text: `${backports.length} open backports`,
- });
+ return slack.chat.postMessage({
+ channel: channelName,
+ blocks,
+ attachments,
+ text: `${backports.length} open backports`,
+ });
}
export async function sendPreReleaseStatus({
- channelName, version, date, openIssues, closedIssueCount, milestoneId
+ channelName,
+ version,
+ date,
+ openIssues,
+ closedIssueCount,
+ milestoneId,
}: {
- channelName: string,
- version: string,
- date: string,
- openIssues: Issue[],
- closedIssueCount: number,
- milestoneId: number,
+ channelName: string;
+ version: string;
+ date: string;
+ openIssues: Issue[];
+ closedIssueCount: number;
+ milestoneId: number;
}) {
- const blockerText = `* ${openIssues.length } Blockers*
- ${openIssues.map(issue => ` • <${issue.html_url}|#${issue.number} - ${issue.title}> - ${mentionUserByGithubLogin(issue.assignee?.login)}`).join("\n")}`;
+ const blockerText = `* ${openIssues.length} Blockers*
+ ${openIssues.map((issue) => ` • <${issue.html_url}|#${issue.number} - ${issue.title}> - ${mentionUserByGithubLogin(issue.assignee?.login)}`).join("\n")}`;
const blocks = [
{
- "type": "header",
- "text": {
- "type": "plain_text",
- "text": `:rocket: Upcoming ${version} Release Status`,
- "emoji": true
- }
- },
+ type: "header",
+ text: {
+ type: "plain_text",
+ text: `:rocket: Upcoming ${version} Release Status`,
+ emoji: true,
+ },
+ },
{
- "type": "section",
- "text": {
- "type": "mrkdwn",
- "text": `_<https://github.com/metabase/metabase/milestone/${milestoneId}|:direction-sign: Milestone> targeted for release on ${date}_ ${mentionSlackTeam('release-managers')}`,
- }
- },
+ type: "section",
+ text: {
+ type: "mrkdwn",
+ text: `_<https://github.com/metabase/metabase/milestone/${milestoneId}|:direction-sign: Milestone> targeted for release on ${date}_ ${mentionSlackTeam("release-managers")}`,
+ },
+ },
];
const attachments = [
{
- "color": "#32a852",
- "blocks": [{
- "type": "section",
- "text": {
- "type": "mrkdwn",
- "text": `*${closedIssueCount} Closed Issues*`,
- }
- }],
+ color: "#32a852",
+ blocks: [
+ {
+ type: "section",
+ text: {
+ type: "mrkdwn",
+ text: `*${closedIssueCount} Closed Issues*`,
+ },
+ },
+ ],
},
{
- "color": "#a83632",
- "blocks": [{
- "type": "section",
- "text": {
- "type": "mrkdwn",
- "text": blockerText,
- }
- }],
+ color: "#a83632",
+ blocks: [
+ {
+ type: "section",
+ text: {
+ type: "mrkdwn",
+ text: blockerText,
+ },
+ },
+ ],
},
];
@@ -163,11 +181,16 @@ export async function sendPreReleaseStatus({
});
}
-export function sendSlackMessage({ channelName = SLACK_CHANNEL_NAME, message, blocks, attachments }: {
- channelName?: string,
- message: string,
- blocks?: (Block | KnownBlock)[],
- attachments?: MessageAttachment[],
+export function sendSlackMessage({
+ channelName = SLACK_CHANNEL_NAME,
+ message,
+ blocks,
+ attachments,
+}: {
+ channelName?: string;
+ message: string;
+ blocks?: (Block | KnownBlock)[];
+ attachments?: MessageAttachment[];
}) {
return slack.chat.postMessage({
channel: channelName,
@@ -188,7 +211,7 @@ async function getSlackChannelId(
});
const maybeChannelId = response.channels?.find(
- channel => channel.name === channelName,
+ (channel) => channel.name === channelName,
)?.id;
const nextCursor = response.response_metadata?.next_cursor;
if (!maybeChannelId && nextCursor) {
@@ -198,10 +221,14 @@ async function getSlackChannelId(
return maybeChannelId;
}
-export async function findSlackMessage({ channelName, text, limit = 100 }: {
- channelName: string,
- text: string,
- limit?: number,
+export async function findSlackMessage({
+ channelName,
+ text,
+ limit = 100,
+}: {
+ channelName: string;
+ text: string;
+ limit?: number;
}) {
const channelId = await getSlackChannelId(channelName);
if (!channelId) {
@@ -213,8 +240,8 @@ export async function findSlackMessage({ channelName, text, limit = 100 }: {
limit,
});
- const existingMessage = response.messages?.find(
- message => message.text?.includes(text),
+ const existingMessage = response.messages?.find((message) =>
+ message.text?.includes(text),
);
if (!existingMessage) {
@@ -222,8 +249,8 @@ export async function findSlackMessage({ channelName, text, limit = 100 }: {
}
return {
- id: existingMessage.ts ?? '',
- body: existingMessage.text ?? '',
+ id: existingMessage.ts ?? "",
+ body: existingMessage.text ?? "",
};
}
@@ -231,14 +258,24 @@ function getExistingSlackMessage(version: string, channelName: string) {
return findSlackMessage({ channelName, text: getReleaseTitle(version) });
}
-export async function sendSlackReply({ channelName, message, messageId, broadcast }: {channelName: string, message: string, messageId?: string, broadcast?: boolean}) {
+export async function sendSlackReply({
+ channelName,
+ message,
+ messageId,
+ broadcast,
+}: {
+ channelName: string;
+ message: string;
+ messageId?: string;
+ broadcast?: boolean;
+}) {
const channelId = await getSlackChannelId(channelName);
if (!channelId) {
throw new Error(`Could not find channel ${channelName}`);
}
if (!messageId) {
- throw new Error('Message ID is not defined');
+ throw new Error("Message ID is not defined");
}
return slack.chat.postMessage({
@@ -249,32 +286,52 @@ export async function sendSlackReply({ channelName, message, messageId, broadcas
});
}
-export async function addSlackReaction({ channelName, messageId, emoji }: { channelName: string, messageId: string, emoji: string }) {
+export async function addSlackReaction({
+ channelName,
+ messageId,
+ emoji,
+}: {
+ channelName: string;
+ messageId: string;
+ emoji: string;
+}) {
const channelId = await getSlackChannelId(channelName);
if (!channelId) {
console.error(`Could not find channel ${channelName}`);
return;
}
- return slack.reactions.add({
- channel: channelId,
- name: emoji,
- timestamp: messageId,
- }).catch(console.warn);
+ return slack.reactions
+ .add({
+ channel: channelId,
+ name: emoji,
+ timestamp: messageId,
+ })
+ .catch(console.warn);
}
-export async function removeSlackReaction({ channelName, messageId, emoji }: { channelName: string, messageId: string, emoji: string }) {
+export async function removeSlackReaction({
+ channelName,
+ messageId,
+ emoji,
+}: {
+ channelName: string;
+ messageId: string;
+ emoji: string;
+}) {
const channelId = await getSlackChannelId(channelName);
if (!channelId) {
console.error(`Could not find channel ${channelName}`);
return;
}
- return slack.reactions.remove({
- channel: channelId,
- name: emoji,
- timestamp: messageId,
- }).catch(console.warn);
+ return slack.reactions
+ .remove({
+ channel: channelId,
+ name: emoji,
+ timestamp: messageId,
+ })
+ .catch(console.warn);
}
const getReleaseTitle = (version: string) =>
@@ -323,16 +380,18 @@ export function buildAutoReleaseSkipMessage({
const runLink = githubRunLink("workflow run", runId, owner, repo);
const label = kind === "patch" ? "Auto-patch" : "Auto-minor";
- const noNextVersion = kind === "patch"
- ? `:x: ${label} for *v${majorVersion}* skipped: could not determine next patch version. ${runLink}`
- : `:information_source: ${label} for *v${majorVersion}* skipped: no gold release yet — cut it manually. ${runLink}`;
+ const noNextVersion =
+ kind === "patch"
+ ? `:x: ${label} for *v${majorVersion}* skipped: could not determine next patch version. ${runLink}`
+ : `:information_source: ${label} for *v${majorVersion}* skipped: no gold release yet — cut it manually. ${runLink}`;
- const alreadyReleasedSuffix = kind === "patch" ? "nothing new to patch" : "nothing new to ship";
+ const alreadyReleasedSuffix =
+ kind === "patch" ? "nothing new to patch" : "nothing new to ship";
const messageByReason: Record<AutoReleaseSkipReason, string> = {
"no-green-commit": `:x: ${label} for *v${majorVersion}* skipped: no commit found suitable for the release. ${runLink}`,
"no-next-version": noNextVersion,
- "already-released": `:information_source: ${label} for *v${majorVersion}* skipped: latest green commit has already been released — ${alreadyReleasedSuffix}. ${mentionSlackTeam('release-managers')} monitor the v${majorVersion} branch and manually release the next green commit. ${runLink}`,
+ "already-released": `:information_source: ${label} for *v${majorVersion}* skipped: latest green commit has already been released — ${alreadyReleasedSuffix}. ${mentionSlackTeam("release-managers")} monitor the v${majorVersion} branch and manually release the next green commit. ${runLink}`,
};
return messageByReason[reason];
@@ -360,8 +419,8 @@ export async function sendPreReleaseMessage({
version: string;
runId: string;
releaseSha: string;
- channelName: string,
- userName: string,
+ channelName: string;
+ userName: string;
}) {
const title = getReleaseTitle(version);
@@ -385,8 +444,12 @@ export async function sendPreReleaseMessage({
releaseCommitLink,
milestoneLink,
githubBuildLink,
- userName ? `started from ${owner}/${repo} by ${mentionUserByGithubLogin(userName)}` : null
- ].filter(Boolean).join(" - ");
+ userName
+ ? `started from ${owner}/${repo} by ${mentionUserByGithubLogin(userName)}`
+ : null,
+ ]
+ .filter(Boolean)
+ .join(" - ");
const message = `${title}\n${preReleaseMessage}`;
@@ -401,23 +464,28 @@ export async function sendTestsCompleteMessage({
owner,
repo,
}: {
- channelName: string,
- version: string,
- runId: number,
- testStatus: 'success' | 'failure',
- owner: string,
- repo: string,
+ channelName: string;
+ version: string;
+ runId: number;
+ testStatus: "success" | "failure";
+ owner: string;
+ repo: string;
}) {
- const message = testStatus === 'success'
- ? `:very-green-check: ${getGenericVersion(version)} ${githubRunLink("Pre-release Tests Passed", runId.toString(), owner, repo)}`
- : `:x: ${getGenericVersion(version)} ${githubRunLink("Pre-release Tests Failed", runId.toString(), owner, repo)}`;
+ const message =
+ testStatus === "success"
+ ? `:very-green-check: ${getGenericVersion(version)} ${githubRunLink("Pre-release Tests Passed", runId.toString(), owner, repo)}`
+ : `:x: ${getGenericVersion(version)} ${githubRunLink("Pre-release Tests Failed", runId.toString(), owner, repo)}`;
const buildThread = await getExistingSlackMessage(version, channelName);
await sendSlackReply({ channelName, message, messageId: buildThread?.id });
- if (testStatus !== 'success' && buildThread?.id) {
- await addSlackReaction({ channelName, messageId: buildThread?.id, emoji: 'warning' });
+ if (testStatus !== "success" && buildThread?.id) {
+ await addSlackReaction({
+ channelName,
+ messageId: buildThread?.id,
+ emoji: "warning",
+ });
}
}
@@ -428,11 +496,11 @@ export async function sendPublishStartMessage({
owner,
repo,
}: {
- channelName: string,
- version: string,
- runId: number,
- owner: string,
- repo: string,
+ channelName: string;
+ version: string;
+ runId: number;
+ owner: string;
+ repo: string;
}) {
const message = `:loading: ${githubRunLink(`Publishing ${getGenericVersion(version)}`, runId.toString(), owner, repo)}`;
const buildThread = await getExistingSlackMessage(version, channelName);
@@ -447,12 +515,12 @@ export async function sendPublishFailureMessage({
repo,
details,
}: {
- channelName: string,
- version: string,
- runId: number,
- owner: string,
- repo: string,
- details: string,
+ channelName: string;
+ version: string;
+ runId: number;
+ owner: string;
+ repo: string;
+ details: string;
}) {
const message = `:x: ${githubRunLink(`Publishing ${getGenericVersion(version)} failed`, runId.toString(), owner, repo)}\n${details}`;
@@ -465,7 +533,11 @@ export async function sendPublishFailureMessage({
}
await sendSlackReply({ channelName, message, messageId: buildThread.id });
- await addSlackReaction({ channelName, messageId: buildThread.id, emoji: 'warning' });
+ await addSlackReaction({
+ channelName,
+ messageId: buildThread.id,
+ emoji: "warning",
+ });
}
export async function sendPublishCompleteMessage({
@@ -475,78 +547,92 @@ export async function sendPublishCompleteMessage({
owner,
repo,
}: {
- channelName: string,
- version: string,
- runId: number,
- owner: string,
- repo: string,
+ channelName: string;
+ version: string;
+ runId: number;
+ owner: string;
+ repo: string;
}) {
const baseMessage = `:partydeploy: *${githubRunLink(`${getGenericVersion(version)} Release is Complete`, runId.toString(), owner, repo)}* :partydeploy:`;
const fullMessage = `\n
- • ${slackLink("Ops Issues", `https://github.com/${owner}/metabase-ops/issues`)} - ${mentionSlackTeam('successengineers')}
- • ${slackLink("Release Notes", `https://github.com/${owner}/${repo}/releases`)} - ${mentionSlackTeam('tech-writers')}`;
+ • ${slackLink("Ops Issues", `https://github.com/${owner}/metabase-ops/issues`)} - ${mentionSlackTeam("successengineers")}
+ • ${slackLink("Release Notes", `https://github.com/${owner}/${repo}/releases`)} - ${mentionSlackTeam("tech-writers")}`;
- const isPatch = version.split('.').length > 3;
+ const isPatch = version.split(".").length > 3;
- const message = `${baseMessage}${isPatch ? '' : fullMessage}`;
+ const message = `${baseMessage}${isPatch ? "" : fullMessage}`;
const buildThread = await getExistingSlackMessage(version, channelName);
await sendSlackReply({ channelName, message, messageId: buildThread?.id });
if (buildThread?.id) {
- await removeSlackReaction({ channelName , messageId: buildThread?.id, emoji: 'warning' });
- await addSlackReaction({ channelName, messageId: buildThread?.id, emoji: 'very-green-check' });
+ await removeSlackReaction({
+ channelName,
+ messageId: buildThread?.id,
+ emoji: "warning",
+ });
+ await addSlackReaction({
+ channelName,
+ messageId: buildThread?.id,
+ emoji: "very-green-check",
+ });
}
}
export async function sendFlakeStatusReport({
- channelName, openFlakeInfo, closedFlakeInfo,
+ channelName,
+ openFlakeInfo,
+ closedFlakeInfo,
}: {
- channelName: string,
- openFlakeInfo: string,
- closedFlakeInfo: string,
+ channelName: string;
+ openFlakeInfo: string;
+ closedFlakeInfo: string;
}) {
- const blocks = [
- {
- "type": "header",
- "text": {
- "type": "plain_text",
- "text": `:croissant: Flaky Tests Status :croissant:`,
- "emoji": true
- }
- },
- ];
-
- const attachments = [
- {
- "color": "#46ad1a",
- "blocks": [{
- "type": "section",
- "text": {
- "type": "mrkdwn",
- "text": `:muscle: *Recently Closed Flakes*\n ${closedFlakeInfo}`,
- }
- }],
- },
- {
- "color": "#d9bb34",
- "blocks": [{
- "type": "section",
- "text": {
- "type": "mrkdwn",
- "text": `:clipboard: *Open Flakes*\n ${openFlakeInfo}`,
- }
- }],
+ const blocks = [
+ {
+ type: "header",
+ text: {
+ type: "plain_text",
+ text: `:croissant: Flaky Tests Status :croissant:`,
+ emoji: true,
},
- ];
+ },
+ ];
- return slack.chat.postMessage({
- channel: channelName,
- blocks,
- attachments,
- text: `Flaky issue summary`,
- });
+ const attachments = [
+ {
+ color: "#46ad1a",
+ blocks: [
+ {
+ type: "section",
+ text: {
+ type: "mrkdwn",
+ text: `:muscle: *Recently Closed Flakes*\n ${closedFlakeInfo}`,
+ },
+ },
+ ],
+ },
+ {
+ color: "#d9bb34",
+ blocks: [
+ {
+ type: "section",
+ text: {
+ type: "mrkdwn",
+ text: `:clipboard: *Open Flakes*\n ${openFlakeInfo}`,
+ },
+ },
+ ],
+ },
+ ];
+
+ return slack.chat.postMessage({
+ channel: channelName,
+ blocks,
+ attachments,
+ text: `Flaky issue summary`,
+ });
}
/**
@@ -562,11 +648,11 @@ export async function uploadFileToSlack({
file,
message,
}: {
- channelName: string,
- thread_ts?: string,
- fileName: string,
- file: Buffer,
- message: string,
+ channelName: string;
+ thread_ts?: string;
+ fileName: string;
+ file: Buffer;
+ message: string;
}) {
console.log(`Uploading file ${fileName} to slack`);
@@ -575,14 +661,18 @@ export async function uploadFileToSlack({
length: file.length,
});
- if (!uploadRequest.ok || !uploadRequest.upload_url || !uploadRequest.file_id) {
+ if (
+ !uploadRequest.ok ||
+ !uploadRequest.upload_url ||
+ !uploadRequest.file_id
+ ) {
throw new Error(`Failed to get upload URL: ${uploadRequest.error}`);
}
const uploadResult = await fetch(uploadRequest.upload_url, {
- method: 'POST',
+ method: "POST",
headers: {
- 'Content-Type': 'application/octet-stream',
+ "Content-Type": "application/octet-stream",
},
body: file,
});
@@ -605,25 +695,25 @@ export async function uploadFileToSlack({
});
}
-const milestoneCheckProjectUrl = 'https://github.com/orgs/metabase/projects/93';
+const milestoneCheckProjectUrl = "https://github.com/orgs/metabase/projects/93";
export async function sendMilestoneCheckMessage({
channelName,
issueCount,
version,
}: {
- channelName: string,
- issueCount: number,
- version: string,
+ channelName: string;
+ issueCount: number;
+ version: string;
}) {
- console.log('Sending milestone check slack message to ', channelName);
+ console.log("Sending milestone check slack message to ", channelName);
let buildThread = await getExistingSlackMessage(version, channelName);
// if we can't find a build thread, we'll make our own pre-build thread
if (!buildThread) {
const message = `:file_folder: *${getGenericVersion(version)} Pre-release milestone check*`;
const response = await sendSlackMessage({ channelName, message });
- buildThread = { id: response.ts ?? '', body: message };
+ buildThread = { id: response.ts ?? "", body: message };
}
const message = `:mag: ${getGenericVersion(version)} has ${slackLink(`${issueCount} issues that need to be checked`, milestoneCheckProjectUrl)}`;
@@ -631,7 +721,7 @@ export async function sendMilestoneCheckMessage({
await sendSlackReply({ message, channelName, messageId: buildThread.id });
const fileName = `milestone-audit-${version}.md`;
- const file = fs.readFileSync('./' + fileName);
+ const file = fs.readFileSync("./" + fileName);
const fileMessage = `:page_with_curl: ${getGenericVersion(version)} milestone audit`;
return uploadFileToSlack({
diff --git a/release/src/slack.unit.spec.ts b/release/src/slack.unit.spec.ts
index a2a5d886870..9c6e36d8bef 100644
--- a/release/src/slack.unit.spec.ts
+++ b/release/src/slack.unit.spec.ts
@@ -8,13 +8,17 @@ describe("buildAutoReleaseSkipMessage", () => {
repo: "metabase",
};
- const runLink = "<https://github.com/metabase/metabase/actions/runs/12345|workflow run>";
+ const runLink =
+ "<https://github.com/metabase/metabase/actions/runs/12345|workflow run>";
describe("patch", () => {
const patchArgs = { ...baseArgs, kind: "patch" as const };
it("uses a failure emoji for no-green-commit", () => {
- const message = buildAutoReleaseSkipMessage({ ...patchArgs, reason: "no-green-commit" });
+ const message = buildAutoReleaseSkipMessage({
+ ...patchArgs,
+ reason: "no-green-commit",
+ });
expect(message).toContain(":x:");
expect(message).toContain("Auto-patch");
@@ -24,7 +28,10 @@ describe("buildAutoReleaseSkipMessage", () => {
});
it("uses a failure emoji for no-next-version (patch can't fall back to manual)", () => {
- const message = buildAutoReleaseSkipMessage({ ...patchArgs, reason: "no-next-version" });
+ const message = buildAutoReleaseSkipMessage({
+ ...patchArgs,
+ reason: "no-next-version",
+ });
expect(message).toContain(":x:");
expect(message).toContain("Auto-patch");
@@ -33,7 +40,10 @@ describe("buildAutoReleaseSkipMessage", () => {
});
it("uses an info emoji (not a failure emoji) for already-released", () => {
- const message = buildAutoReleaseSkipMessage({ ...patchArgs, reason: "already-released" });
+ const message = buildAutoReleaseSkipMessage({
+ ...patchArgs,
+ reason: "already-released",
+ });
expect(message).toContain(":information_source:");
expect(message).not.toContain(":x:");
@@ -47,7 +57,10 @@ describe("buildAutoReleaseSkipMessage", () => {
const minorArgs = { ...baseArgs, kind: "minor" as const };
it("uses a failure emoji for no-green-commit", () => {
- const message = buildAutoReleaseSkipMessage({ ...minorArgs, reason: "no-green-commit" });
+ const message = buildAutoReleaseSkipMessage({
+ ...minorArgs,
+ reason: "no-green-commit",
+ });
expect(message).toContain(":x:");
expect(message).toContain("Auto-minor");
@@ -57,7 +70,10 @@ describe("buildAutoReleaseSkipMessage", () => {
});
it("uses an info emoji for no-next-version (gold release happens manually)", () => {
- const message = buildAutoReleaseSkipMessage({ ...minorArgs, reason: "no-next-version" });
+ const message = buildAutoReleaseSkipMessage({
+ ...minorArgs,
+ reason: "no-next-version",
+ });
expect(message).toContain(":information_source:");
expect(message).not.toContain(":x:");
@@ -67,7 +83,10 @@ describe("buildAutoReleaseSkipMessage", () => {
});
it("uses an info emoji (not a failure emoji) for already-released", () => {
- const message = buildAutoReleaseSkipMessage({ ...minorArgs, reason: "already-released" });
+ const message = buildAutoReleaseSkipMessage({
+ ...minorArgs,
+ reason: "already-released",
+ });
expect(message).toContain(":information_source:");
expect(message).not.toContain(":x:");
diff --git a/release/src/version-helpers.ts b/release/src/version-helpers.ts
index 4b409ae4a18..dd4cb4f5215 100644
--- a/release/src/version-helpers.ts
+++ b/release/src/version-helpers.ts
@@ -109,7 +109,8 @@ export const getVersionFromReleaseBranch = (branch: string) => {
// rolling tags like v0.56.x or v0.51.2.x aren't valid version strings,
// but we can still read a major version off of them
-const isDotXTag = (tagName: string) => /^(v0|v1)\.\d+(\.\d+)*\.x$/.test(tagName);
+const isDotXTag = (tagName: string) =>
+ /^(v0|v1)\.\d+(\.\d+)*\.x$/.test(tagName);
export const getMajorVersionFromRef = (ref: string) => {
if (ref.startsWith("refs/tags/")) {
@@ -125,7 +126,7 @@ export const getMajorVersionFromRef = (ref: string) => {
const getLtsTag = (version: string) => {
const pieces = version.replace(/-.+/, "").split("."); // ignore any -suffixes
return pieces.slice(0, 2).join(".") + "-lts";
-}
+};
export const getDotXs = (version: string, number: number) => {
const pieces = version.replace(/-.+/, "").split("."); // ignore any -suffixes
@@ -176,7 +177,9 @@ export const getExtraTagsForVersion = async ({
...baseTags,
...minorTags,
...(shouldAddLatestTag({ version, latestMajorVersion }) ? ["latest"] : []),
- ...(await isLtsVersion({ version }) ? [getLtsTag(ossVersion), getLtsTag(eeVersion)] : [])
+ ...((await isLtsVersion({ version }))
+ ? [getLtsTag(ossVersion), getLtsTag(eeVersion)]
+ : []),
];
};
diff --git a/release/src/version-helpers.unit.spec.ts b/release/src/version-helpers.unit.spec.ts
index 8a5d27176b4..50cea6ae227 100644
--- a/release/src/version-helpers.unit.spec.ts
+++ b/release/src/version-helpers.unit.spec.ts
@@ -856,17 +856,13 @@ describe("version-helpers", () => {
});
it("should return the correct extra tags for a beta version", async () => {
- expect(await getExtraTagsForVersion({ version: "v1.75.0-beta" })).toEqual([
- "v0.75.x",
- "v1.75.x",
- ]);
+ expect(await getExtraTagsForVersion({ version: "v1.75.0-beta" })).toEqual(
+ ["v0.75.x", "v1.75.x"],
+ );
- expect(await getExtraTagsForVersion({ version: "v1.75.1-beta" })).toEqual([
- "v0.75.x",
- "v1.75.x",
- "v0.75.1.x",
- "v1.75.1.x",
- ]);
+ expect(await getExtraTagsForVersion({ version: "v1.75.1-beta" })).toEqual(
+ ["v0.75.x", "v1.75.x", "v0.75.1.x", "v1.75.1.x"],
+ );
expect(
await getExtraTagsForVersion({ version: "v0.75.1.2-beta" }),
@@ -986,5 +982,4 @@ describe("version-helpers", () => {
expect(getMinorVersion(input)).toBe(expected);
});
});
-
});
diff --git a/release/src/version-info.ts b/release/src/version-info.ts
index a4738cc37c6..91bf3ef9e58 100644
--- a/release/src/version-info.ts
+++ b/release/src/version-info.ts
@@ -14,16 +14,12 @@ import {
isPatchVersion,
} from "./version-helpers";
-const generateVersionInfo = ({
- version,
-}: {
- version: string;
-}): VersionInfo => {
+const generateVersionInfo = ({ version }: { version: string }): VersionInfo => {
return {
version,
released: new Date().toISOString().slice(0, 10),
patch: ["patch", "minor"].includes(getVersionType(version)),
- highlights: [ `see ${getChangelogUrl(version)}` ],
+ highlights: [`see ${getChangelogUrl(version)}`],
};
};
@@ -71,7 +67,9 @@ export const updateVersionInfoLatestJson = ({
}
if (existingVersionInfo.latest.version === newLatestVersion) {
- console.warn(`Version ${newLatestVersion} already latest, updating rollout % only`);
+ console.warn(
+ `Version ${newLatestVersion} already latest, updating rollout % only`,
+ );
return {
...existingVersionInfo,
latest: {
@@ -81,8 +79,9 @@ export const updateVersionInfoLatestJson = ({
};
}
- const newLatestVersionInfo = existingVersionInfo.older
- .find((info: VersionInfo) => info.version === newLatestVersion);
+ const newLatestVersionInfo = existingVersionInfo.older.find(
+ (info: VersionInfo) => info.version === newLatestVersion,
+ );
if (!newLatestVersionInfo) {
throw new Error(`${newLatestVersion} not found version-info.json`);
@@ -113,11 +112,9 @@ export const getVersionInfoUrl = (version: string) => {
};
// for adding a new release to version info
-export async function getVersionInfo({
- version,
-}: ReleaseProps) {
+export async function getVersionInfo({ version }: ReleaseProps) {
const url = getVersionInfoUrl(version);
- const existingFile = (await fetch(url).then(r =>
+ const existingFile = (await fetch(url).then((r) =>
r.json(),
)) as VersionInfoFile;
@@ -147,7 +144,9 @@ export const getSupportedMajorVersions = (
}
const supported = [
- ...new Set(lines.filter(line => line.eol > today).map(line => line.major)),
+ ...new Set(
+ lines.filter((line) => line.eol > today).map((line) => line.major),
+ ),
].sort((a, b) => b - a);
if (supported.length === 0) {
@@ -165,7 +164,9 @@ export async function getSupportedMajors(
today: string = new Date().toISOString().slice(0, 10),
): Promise<number[]> {
const url = getVersionInfoUrl("v0"); // any non-`v1.` string picks the OSS file
- const versionInfo = (await fetch(url).then(r => r.json())) as VersionInfoFile;
+ const versionInfo = (await fetch(url).then((r) =>
+ r.json(),
+ )) as VersionInfoFile;
return getSupportedMajorVersions(versionInfo, today);
}
@@ -179,7 +180,7 @@ export async function updateVersionInfoLatest({
rollout?: number;
}) {
const url = getVersionInfoUrl(newVersion);
- const existingFile = (await fetch(url).then(r =>
+ const existingFile = (await fetch(url).then((r) =>
r.json(),
)) as VersionInfoFile;
@@ -194,10 +195,12 @@ export async function updateVersionInfoLatest({
export async function isLtsVersion({
version,
}: {
- version: string,
+ version: string;
}): Promise<boolean> {
const url = getVersionInfoUrl("v0"); // any non-`v1.` string picks the OSS file
- const versionInfo = (await fetch(url).then(r => r.json())) as VersionInfoFile;
+ const versionInfo = (await fetch(url).then((r) =>
+ r.json(),
+ )) as VersionInfoFile;
const majorVersions = versionInfo?.major_version_support;
if (!majorVersions || majorVersions.length === 0) {
@@ -205,7 +208,9 @@ export async function isLtsVersion({
}
const versionMajor = getMajorVersion(version);
- const match = majorVersions.find((v) => v?.lts && String(v.major) === versionMajor);
+ const match = majorVersions.find(
+ (v) => v?.lts && String(v.major) === versionMajor,
+ );
return match !== undefined;
}
diff --git a/release/src/version-info.unit.spec.ts b/release/src/version-info.unit.spec.ts
index 09d4ae94e8d..96bf61da003 100644
--- a/release/src/version-info.unit.spec.ts
+++ b/release/src/version-info.unit.spec.ts
@@ -1,7 +1,15 @@
import fetch from "node-fetch";
import type { VersionInfoFile } from "./types";
-import { generateVersionInfoJson, getSupportedMajorVersions, getSupportedMajors, getVersionInfoUrl, isLtsVersion, updateVersionInfoLatest, updateVersionInfoLatestJson } from "./version-info";
+import {
+ generateVersionInfoJson,
+ getSupportedMajorVersions,
+ getSupportedMajors,
+ getVersionInfoUrl,
+ isLtsVersion,
+ updateVersionInfoLatest,
+ updateVersionInfoLatestJson,
+} from "./version-info";
jest.mock("node-fetch", () => ({
__esModule: true,
@@ -28,12 +36,14 @@ describe("version-info", () => {
existingVersionInfo: oldJson,
});
- expect(generatedJson.older).toEqual([{
- version: "v0.3.0",
- released: expect.any(String),
- patch: false,
- highlights: ["see https://www.metabase.com/changelog/3#metabase-30"],
- }]);
+ expect(generatedJson.older).toEqual([
+ {
+ version: "v0.3.0",
+ released: expect.any(String),
+ patch: false,
+ highlights: ["see https://www.metabase.com/changelog/3#metabase-30"],
+ },
+ ]);
});
it("should leave old latest version intact", () => {
@@ -138,10 +148,12 @@ describe("version-info", () => {
});
it("should throw if new version is not in older versions", () => {
- expect(() => updateVersionInfoLatestJson({
- newLatestVersion: "v0.2.1",
- existingVersionInfo: oldJson,
- })).toThrow();
+ expect(() =>
+ updateVersionInfoLatestJson({
+ newLatestVersion: "v0.2.1",
+ existingVersionInfo: oldJson,
+ }),
+ ).toThrow();
});
it("should remove the new latest version from the older versions", () => {
@@ -213,7 +225,6 @@ describe("version-info", () => {
});
it("should remove rollout % on old latest version", () => {
-
const updatedJson = updateVersionInfoLatestJson({
newLatestVersion: "v0.2.4",
existingVersionInfo: oldJson,
@@ -326,7 +337,11 @@ describe("version-info", () => {
describe("getSupportedMajorVersions", () => {
const fileWith = (major_version_support: any) =>
- ({ latest: {}, older: [], major_version_support }) as unknown as VersionInfoFile;
+ ({
+ latest: {},
+ older: [],
+ major_version_support,
+ }) as unknown as VersionInfoFile;
it("returns majors whose eol is today or later, newest first", () => {
const versionInfo = fileWith([
@@ -346,7 +361,9 @@ describe("version-info", () => {
{ major: 89, released: "2026-04-01", lts: true, eol: "2026-06-05" },
]);
- expect(getSupportedMajorVersions(versionInfo, "2026-06-04")).toEqual([89]);
+ expect(getSupportedMajorVersions(versionInfo, "2026-06-04")).toEqual([
+ 89,
+ ]);
});
it("ignores the lts flag — support is computed from eol only", () => {
@@ -355,7 +372,9 @@ describe("version-info", () => {
{ major: 54, released: "2025-04-15", lts: true, eol: "2025-06-01" },
]);
- expect(getSupportedMajorVersions(versionInfo, "2026-06-04")).toEqual([60]);
+ expect(getSupportedMajorVersions(versionInfo, "2026-06-04")).toEqual([
+ 60,
+ ]);
});
it("de-duplicates repeated majors", () => {
@@ -364,7 +383,9 @@ describe("version-info", () => {
{ major: 60, released: "2026-04-01", lts: true, eol: "2027-12-01" },
]);
- expect(getSupportedMajorVersions(versionInfo, "2026-06-04")).toEqual([60]);
+ expect(getSupportedMajorVersions(versionInfo, "2026-06-04")).toEqual([
+ 60,
+ ]);
});
it("throws when major_version_support is missing or empty", () => {
diff --git a/resources/frontend_client/app/instance-loading-page/styles.css b/resources/frontend_client/app/instance-loading-page/styles.css
index e55109b1357..87b6a698fff 100644
--- a/resources/frontend_client/app/instance-loading-page/styles.css
+++ b/resources/frontend_client/app/instance-loading-page/styles.css
@@ -1,7 +1,7 @@
* {
box-sizing: border-box;
- color: #4C5773;
- font-family: Lato, 'Helvetica Neue', Helvetica, sans-serif;
+ color: #4c5773;
+ font-family: Lato, "Helvetica Neue", Helvetica, sans-serif;
margin: 0;
padding: 0;
}
@@ -19,9 +19,10 @@ body {
flex-direction: column;
}
-
.heading {
- box-shadow: 0 5px 6px rgba(80, 158, 227, 0.16), 0 12px 24px rgba(148, 154, 171, 0.08);
+ box-shadow:
+ 0 5px 6px rgba(80, 158, 227, 0.16),
+ 0 12px 24px rgba(148, 154, 171, 0.08);
border-radius: 8px;
font-size: 14px;
letter-spacing: 0;
@@ -30,15 +31,14 @@ body {
padding: 4px 20px;
text-align: center;
opacity: 1;
- transition: opacity 800ms cubic-bezier(.165,.84,.44,1);
+ transition: opacity 800ms cubic-bezier(0.165, 0.84, 0.44, 1);
}
-
.animation {
margin-top: -30px;
max-width: 100%;
opacity: 1;
- transition: opacity 800ms cubic-bezier(.165,.84,.44,1);
+ transition: opacity 800ms cubic-bezier(0.165, 0.84, 0.44, 1);
width: 600px;
}
@@ -59,7 +59,6 @@ body {
to {
transform: rotate(360deg);
}
-
}
.spinner {
@@ -72,9 +71,7 @@ body {
border-top-color: #509ee3;
border-radius: 20px;
- animation: rotation 1.3s infinite
- cubic-bezier(0.785, 0.135, 0.15, 0.86);
-
+ animation: rotation 1.3s infinite cubic-bezier(0.785, 0.135, 0.15, 0.86);
}
.spinner::after {
diff --git a/resources/frontend_client/inline_js/index_bootstrap.js b/resources/frontend_client/inline_js/index_bootstrap.js
index c011786d853..8b11477e767 100644
--- a/resources/frontend_client/inline_js/index_bootstrap.js
+++ b/resources/frontend_client/inline_js/index_bootstrap.js
@@ -1,18 +1,28 @@
-(function() {
- window.MetabaseBootstrap = JSON.parse(document.getElementById("_metabaseBootstrap").textContent);
+(function () {
+ window.MetabaseBootstrap = JSON.parse(
+ document.getElementById("_metabaseBootstrap").textContent,
+ );
// Which catalogues the script tags below carry. The app applies them before
// its first render.
- window.MetabaseLocales = JSON.parse(document.getElementById("_metabaseLocales").textContent);
- window.MetabaseUserColorScheme = JSON.parse(document.getElementById("_metabaseUserColorScheme").textContent);
+ window.MetabaseLocales = JSON.parse(
+ document.getElementById("_metabaseLocales").textContent,
+ );
+ window.MetabaseUserColorScheme = JSON.parse(
+ document.getElementById("_metabaseUserColorScheme").textContent,
+ );
// Read from the script element, not from a JSON block: the browser blanks a nonce content attribute
// after parsing, so the value never stays readable in the DOM.
- window.MetabaseNonce = document.currentScript.nonce || "";
+ window.MetabaseNonce = document.currentScript.nonce || "";
- var configuredRoot = document.head.querySelector("meta[name='base-href']").content;
+ var configuredRoot = document.head.querySelector(
+ "meta[name='base-href']",
+ ).content;
var actualRoot = "/";
// Add trailing slashes
- var backendPathname = document.head.querySelector("meta[name='uri']").content.replace(/\/*$/, "/");
+ var backendPathname = document.head
+ .querySelector("meta[name='uri']")
+ .content.replace(/\/*$/, "/");
// e.x. "/questions/"
var frontendPathname = window.location.pathname.replace(/\/*$/, "/");
// e.x. "/metabase/questions/"
@@ -23,8 +33,19 @@
}
if (actualRoot !== configuredRoot) {
- console.warn("Warning: the Metabase site URL basename \"" + configuredRoot + "\" does not match the actual basename \"" + actualRoot + "\".");
- console.warn("You probably want to update the Site URL setting to \"" + window.location.origin + actualRoot + "\"");
+ console.warn(
+ 'Warning: the Metabase site URL basename "' +
+ configuredRoot +
+ '" does not match the actual basename "' +
+ actualRoot +
+ '".',
+ );
+ console.warn(
+ 'You probably want to update the Site URL setting to "' +
+ window.location.origin +
+ actualRoot +
+ '"',
+ );
document.getElementsByTagName("base")[0].href = actualRoot;
}
diff --git a/resources/frontend_client/inline_js/init.js b/resources/frontend_client/inline_js/init.js
index dd7100e7605..918d5d8cc06 100644
--- a/resources/frontend_client/inline_js/init.js
+++ b/resources/frontend_client/inline_js/init.js
@@ -15,7 +15,7 @@ const fadeTimeInMilliseconds = 500;
let counter = 0;
function switcher() {
- setInterval(function() {
+ setInterval(function () {
counter++;
switchHeading(counter);
switchAnimation(counter);
@@ -26,7 +26,7 @@ function switchHeading(counter) {
heading.className = "transparent";
// Wait for fade out of current heading
- setTimeout(function() {
+ setTimeout(function () {
updateHeading(counter);
}, fadeTimeInMilliseconds);
}
@@ -36,7 +36,7 @@ function switchAnimation(counter) {
heading.className = "heading transparent";
// Wait for fade out of current animation
- setTimeout(function() {
+ setTimeout(function () {
fadeInNewAnimation(counter);
}, fadeTimeInMilliseconds);
}
@@ -56,7 +56,7 @@ function updateHeading(counter) {
function poll() {
const req = new XMLHttpRequest();
req.open("GET", "api/health", true);
- req.onreadystatechange = function() {
+ req.onreadystatechange = function () {
if (req.readyState === 4) {
if (req.status === 200) {
window.location.reload();