The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Add a lint rule that keeps side-effect-free modules side-effect free (#80047)
Fraserd2c5d44b6307
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/iframe-vendors.ts b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/iframe-vendors.tsindex 30f20199f99..fc1bc12ae8a 100644--- a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/iframe-vendors.ts+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/iframe-vendors.ts@@ -3,4 +3,4 @@ import "@mantine/dates/styles.css";import "metabase-enterprise/data_apps/sandbox/iframe-baseline.css";-import "metabase/utils/csp";+import "metabase/utils/csp-setup";diff --git a/eslint.config.mjs b/eslint.config.mjsindex 0738bb545b0..2520d637527 100644--- a/eslint.config.mjs+++ b/eslint.config.mjs@@ -23,7 +23,12 @@ import i18nextPlugin from "eslint-plugin-i18next";import ttagPlugin from "eslint-plugin-ttag";import boundaries from "eslint-plugin-boundaries";+import {+ SIDE_EFFECT_FREE_PATHS,+ SIDE_EFFECT_PATHS,+} from "./frontend/build/shared/rspack/side-effect-free-modules.js";import metabasePlugin from "./frontend/lint/eslint-plugin-metabase/index.js";+import { NO_MODULE_SIDE_EFFECTS_OPTIONS } from "./frontend/lint/no-module-side-effects-options.js";import {elements as boundaryElements,enforcedRules as boundaryRules,@@ -1201,6 +1206,79 @@ const configs = ["storybook/no-renderer-packages": "off",},},++ // ============================================+ // SIDE-EFFECT-FREE MODULES+ // ============================================+ {+ // Rspack drops any file in these directories whose exports go unused, so an+ // import-time effect there is silently lost in production. Declaring a+ // directory in SIDE_EFFECT_FREE_PATHS enrols it here.+ files: SIDE_EFFECT_FREE_PATHS.map(+ (dir) => `${path.relative(__dirname, dir)}/**/*.{ts,tsx,js,jsx}`,+ ),+ ignores: [+ // A directory entry (trailing separator) covers every file under it+ ...SIDE_EFFECT_PATHS.map((entry) =>+ entry.endsWith(path.sep)+ ? `${path.relative(__dirname, entry)}/**`+ : path.relative(__dirname, entry),+ ),+ "**/*.unit.spec.*",+ "**/*.stories.*",+ "**/tests/**",+ "**/__support__/**",+ "**/*.d.ts",+ ],+ rules: {+ "metabase/no-module-side-effects": [+ "error",+ NO_MODULE_SIDE_EFFECTS_OPTIONS,+ ],+ },+ },++ // ============================================+ // BASE API OBJECT ACCESS+ // ============================================+ {+ // Endpoints are injected into the one `Api` object at import time by the+ // file that owns them, so they exist only once that file has been+ // evaluated. Reaching them by name through the base object works only while+ // something else imports the owner, and a side-effect-free api module lets+ // production shake the owner away. Consumers go through the owner's+ // exports instead.+ files: [+ "frontend/src/**/*.{ts,tsx,js,jsx}",+ "enterprise/frontend/src/**/*.{ts,tsx,js,jsx}",+ ],+ ignores: [+ // TODO(no-base-api-access): createMockState composes the whole store, so redux/store/mocks belongs in test support.+ // It moves there when the store roots are composed explicitly, and this ignore goes with it.+ "frontend/src/metabase/redux/store/mocks/api.ts",+ ],+ rules: {+ "metabase/no-base-api-access": [+ "error",+ {+ // Where an endpoint is declared is a path question: the api module, or a module's `api/` folder or `api.ts`.+ allowInjectionIn: [+ `${__dirname}/frontend/src/metabase/api/**`,+ "**/api/**",+ "**/api.ts",+ ],+ // Reaching an endpoint by name is never fine in product code, whatever the file is called.+ // Test support seeds the cache by endpoint name, after importing the whole api index so every owner has run.+ allowReachIn: [+ `${__dirname}/frontend/src/metabase/api/**`,+ `${__dirname}/frontend/test/**`,+ "**/__support__/**",+ "**/*.unit.spec.*",+ ],+ },+ ],+ },+ },];if (shouldLintCssModules) {diff --git a/frontend/build/shared/rspack/side-effect-free-modules.js b/frontend/build/shared/rspack/side-effect-free-modules.jsindex 7ef0ea9d4ba..7aae924b135 100644--- a/frontend/build/shared/rspack/side-effect-free-modules.js+++ b/frontend/build/shared/rspack/side-effect-free-modules.js@@ -17,8 +17,11 @@ const REPO_ROOT = path.resolve(__dirname, "../../../..");** Adding a directory here is a promise the bundler cannot verify. A violation* fails silently, in production only, by dropping code that was meant to run, so- * `frontend/lint/tests/side-effect-free-modules.unit.spec.js` guards the- * mechanically detectable half of the contract.+ * the `metabase/no-module-side-effects` lint rule is applied to every directory+ * listed here (see eslint.config.mjs) and reports the import-time work it can see.+ * Third-party imports are assumed self-contained: a package whose import-time work non-importers rely on+ * is listed in the registry's `packages` (frontend/lint/side-effect-files.json),+ * and a vendor with host-extending plugins gets a facade.** Only applies to production builds, where `optimization.sideEffects` is on.*/@@ -32,9 +35,27 @@ const SIDE_EFFECT_FREE_PATHS = [path.join(REPO_ROOT, "frontend/src/metabase/querying/expressions") + path.sep,];+/**+ * Paths inside a side-effect-free directory that do have an import-time effect,+ * so keep rspack's default (assume side effects) for them. An entry, and its+ * whole import graph, is kept in every bundle that reaches it, so the list+ * should stay short and every file entry should be a fix candidate.+ *+ * A directory entry (trailing separator, like SIDE_EFFECT_FREE_PATHS) covers every file under it.+ * List `<module>/api` here when a module is enrolled: those files register their endpoints on the shared Api at import,+ * so a bundle has to evaluate them even when it only reaches them by name.+ */+const SIDE_EFFECT_PATHS = [];+const SIDE_EFFECT_FREE_RULE = {include: SIDE_EFFECT_FREE_PATHS,+ // Prefix-matched like `include`, so a directory entry excludes its whole tree.+ exclude: SIDE_EFFECT_PATHS,sideEffects: false,};-module.exports = { SIDE_EFFECT_FREE_PATHS, SIDE_EFFECT_FREE_RULE };+module.exports = {+ SIDE_EFFECT_FREE_PATHS,+ SIDE_EFFECT_PATHS,+ SIDE_EFFECT_FREE_RULE,+};diff --git a/frontend/lint/eslint-plugin-metabase/index.js b/frontend/lint/eslint-plugin-metabase/index.jsindex 61c3fffc940..8d30b80baa9 100644--- a/frontend/lint/eslint-plugin-metabase/index.js+++ b/frontend/lint/eslint-plugin-metabase/index.js@@ -10,11 +10,13 @@ module.exports = {rules: {"enforce-module-public-api": require("./rules/enforce-module-public-api"),"jtag-missing-key": require("./rules/jtag-missing-key"),+ "no-base-api-access": require("./rules/no-base-api-access"),"no-color-literals": require("./rules/no-color-literals"),"no-direct-helper-import": require("./rules/no-direct-helper-import"),"no-external-references-for-sdk-package-code": require("./rules/no-external-references-for-sdk-package-code"),"no-literal-metabase-strings": require("./rules/no-literal-metabase-strings"),"no-locale-with-intl-functions": require("./rules/no-locale-with-intl-functions"),+ "no-module-side-effects": require("./rules/no-module-side-effects"),"no-oss-reinitialize-import": require("./rules/no-oss-reinitialize-import"),"no-unconditional-metabase-links-render": require("./rules/no-unconditional-metabase-links-render"),"no-unordered-test-helpers": require("./rules/no-unordered-test-helpers"),diff --git a/frontend/lint/eslint-plugin-metabase/rules/no-base-api-access.js b/frontend/lint/eslint-plugin-metabase/rules/no-base-api-access.jsnew file mode 100644index 00000000000..af2b123e0be--- /dev/null+++ b/frontend/lint/eslint-plugin-metabase/rules/no-base-api-access.js@@ -0,0 +1,201 @@+/**+ * @fileoverview Endpoints are injected into the shared `Api` at import time by the file that owns them,+ * so an endpoint exists on the base object only once the owner's file has been evaluated.+ * Reaching one there by name (`Api.endpoints.getX`, `Api.util.upsertQueryEntries`) works only while something else imports the owner,+ * and a side-effect-free build can drop that owner.+ * This reports injection outside owner files and reach-by-name outside the api module and test support.+ */++const micromatch = require("micromatch");++// The base api objects. An owner's slice (`cardApi.endpoints`) is the intended way in and is not tracked.+const DEFAULT_BASE_APIS = [+ { module: "metabase/api", name: "Api" },+ { module: "metabase/api/api", name: "Api" },+ { module: "metabase-enterprise/api", name: "EnterpriseApi" },+ { module: "metabase-enterprise/api/api", name: "EnterpriseApi" },+];++// Cross-owner by design and a no-op when nothing is registered, so they never need the endpoint to exist.+const ALLOWED_UTILS = new Set(["invalidateTags", "resetApiState"]);++const INJECTORS = new Set(["injectEndpoints", "enhanceEndpoints"]);++module.exports = {+ meta: {+ type: "problem",+ docs: {+ description:+ "Disallow reaching RTK Query endpoints through the base Api object instead of the owning module's exports",+ category: "Best Practices",+ recommended: true,+ },+ schema: [+ {+ type: "object",+ properties: {+ // Both are globs matched against the linted file's path+ allowInjectionIn: {+ type: "array",+ // Where endpoints may be injected: the api module and owner files+ items: { type: "string" },+ },+ allowReachIn: {+ type: "array",+ // Where endpoints may be reached by name: the api module and test support+ items: { type: "string" },+ },+ baseApis: {+ type: "array",+ items: {+ type: "object",+ properties: {+ module: { type: "string" },+ name: { type: "string" },+ },+ required: ["module", "name"],+ additionalProperties: false,+ },+ },+ },+ additionalProperties: false,+ },+ ],+ messages: {+ endpointAccess:+ "Reach endpoints through the owning module's exports (its hooks or api slice), not through the base {{api}} object; endpoints only exist once the owner's file has been evaluated. `{{access}}` reaches them by name.",+ injection:+ "`{{access}}` injects endpoints outside an owner file. Endpoints belong in the module's `api/` folder or `api.ts`, which exports the hooks and the api slice for consumers.",+ },+ },++ create(context) {+ const sourceCode = context.sourceCode || context.getSourceCode();+ const filename = context.filename || context.getFilename();+ const options = context.options[0] || {};+ const baseApis = options.baseApis || DEFAULT_BASE_APIS;++ // `dot: true` so a checkout under a dotted directory still matches `**`+ const isAllowedIn = (globs = []) =>+ globs.length > 0 && micromatch.isMatch(filename, globs, { dot: true });+ const injectionAllowed = isAllowedIn(options.allowInjectionIn);+ const reachAllowed = isAllowedIn(options.allowReachIn);++ if (injectionAllowed && reachAllowed) {+ return {};+ }++ function judge(property, computed) {+ if (computed || property.type !== "Identifier") {+ return null;+ }+ if (INJECTORS.has(property.name)) {+ return injectionAllowed ? null : "injection";+ }+ if (property.name === "endpoints" || property.name === "util") {+ return reachAllowed ? null : "endpointAccess";+ }+ return null;+ }++ function report(node, messageId, apiName, access) {+ context.report({ node, messageId, data: { api: apiName, access } });+ }++ function checkReference(identifier, apiName) {+ const parent = identifier.parent;+ if (+ parent.type === "MemberExpression" &&+ parent.object === identifier &&+ !parent.computed &&+ parent.property.type === "Identifier"+ ) {+ if (parent.property.name === "util") {+ if (!reachAllowed) {+ checkUtilAccess(parent, apiName);+ }+ return;+ }+ const messageId = judge(parent.property, parent.computed);+ if (messageId != null) {+ report(parent, messageId, apiName, sourceCode.getText(parent));+ }+ return;+ }+ if (+ parent.type === "VariableDeclarator" &&+ parent.init === identifier &&+ parent.id.type === "ObjectPattern"+ ) {+ for (const property of parent.id.properties) {+ if (property.type !== "Property") {+ continue;+ }+ const key = property.key;+ if (key.type !== "Identifier") {+ continue;+ }+ const messageId = judge(key, false);+ if (messageId != null) {+ report(+ property,+ messageId,+ apiName,+ `{ ${key.name} } = ${apiName}`,+ );+ }+ }+ }+ }++ // A bare `Api.util` handed on is reported too, since what it reaches cannot be seen here.+ function checkUtilAccess(utilAccess, apiName) {+ const outer = utilAccess.parent;+ if (+ outer.type === "MemberExpression" &&+ outer.object === utilAccess &&+ !outer.computed &&+ outer.property.type === "Identifier"+ ) {+ if (!ALLOWED_UTILS.has(outer.property.name)) {+ report(outer, "endpointAccess", apiName, sourceCode.getText(outer));+ }+ return;+ }+ report(+ utilAccess,+ "endpointAccess",+ apiName,+ sourceCode.getText(utilAccess),+ );+ }++ return {+ ImportDeclaration(node) {+ const matches = baseApis.filter(+ (entry) => entry.module === node.source.value,+ );+ if (matches.length === 0) {+ return;+ }+ for (const specifier of node.specifiers) {+ if (specifier.type !== "ImportSpecifier") {+ continue;+ }+ const importedName =+ specifier.imported.type === "Identifier"+ ? specifier.imported.name+ : String(specifier.imported.value);+ if (!matches.some((entry) => entry.name === importedName)) {+ continue;+ }+ for (const variable of sourceCode.getDeclaredVariables(specifier)) {+ for (const reference of variable.references) {+ checkReference(reference.identifier, importedName);+ }+ }+ }+ },+ };+ },+};diff --git a/frontend/lint/eslint-plugin-metabase/rules/no-module-side-effects.js b/frontend/lint/eslint-plugin-metabase/rules/no-module-side-effects.jsnew file mode 100644index 00000000000..092b51144a2--- /dev/null+++ b/frontend/lint/eslint-plugin-metabase/rules/no-module-side-effects.js@@ -0,0 +1,791 @@+/**+ * @fileoverview Files declared side-effect free (frontend/build/shared/rspack/side-effect-free-modules.js)+ * are dropped from production bundles once their exports go unused, so anything they do at import time is silently lost.+ * This reports module-scope code that does work at import.+ * A dropped file also takes with it everything only it imports, so it also reports an import+ * of a file that frontend/lint/side-effect-files.json classifies as having a global effect,+ * or of a third-party package the registry lists as doing global work at import.+ * The config decides which files are linted, not the rule.+ */++const fs = require("fs");+const path = require("path");++const {+ DEFAULT_REGISTRY_PATH,+ classify,+ classifyPackage,+ isFacade,+ loadRegistry,+} = require("../../side-effect-registry");++const REPO_ROOT = path.resolve(__dirname, "../../../..");++// The tsconfig `*` path roots: `metabase/x` is looked up under each in turn.+const DEFAULT_SOURCE_ROOTS = ["frontend/src", "enterprise/frontend/src"];++const SOURCE_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx"];++// Registry path -> parsed registry, so the file is read once per lint run rather than once per file.+const registries = new Map();++// Callees known to be pure, so a module-scope call to them needs no annotation.+// A name matches the imported binding or a property called on one (`memo`, `Button.extend`).+// Mantine's `extend` is the identity config helper every *.config.ts calls.+const DEFAULT_PURE_CALLEES = [+ {+ module: "react",+ names: ["createContext", "forwardRef", "memo", "lazy", "createElement"],+ },+ {+ module: "@mantine/core",+ names: [+ "rem",+ "getSize",+ "getDefaultZIndex",+ "factory",+ "polymorphicFactory",+ "createVarsResolver",+ "createPolymorphicComponent",+ "extend",+ ],+ },+ { module: "@mantine/dates", names: ["extend"] },+ { module: "@emotion/styled", names: "*" },+ { module: "classnames", names: "*" },+ { module: "clsx", names: "*" },+ { module: "ttag", names: ["t", "c", "jt", "ngettext", "msgid"] },+ { module: "color", names: "*" },+ { module: "@lezer/highlight", names: "*" },+ { module: "@codemirror/language", names: "*" },+ {+ module: "@reduxjs/toolkit",+ names: [+ "createSelector",+ "createReducer",+ "createAction",+ "createSlice",+ "createAsyncThunk",+ "createEntityAdapter",+ ],+ },+ { module: "reselect", names: ["createSelector", "createStructuredSelector"] },+ {+ module: "redux-actions",+ names: [+ "createAction",+ "createActions",+ "handleAction",+ "handleActions",+ "combineActions",+ ],+ },+ { module: "react-redux", names: ["connect"] },+ { module: "underscore", names: ["compose", "memoize", "once"] },+];++// These act on their first argument, so the verdict follows it: fine on a same-file object, a mutation otherwise.+const FIRST_ARGUMENT_MUTATORS = new Set([+ "Object.assign",+ "Object.defineProperty",+ "Object.defineProperties",+ "Object.freeze",+ "Object.seal",+]);++const CONTROL_FLOW_STATEMENTS = new Set([+ "IfStatement",+ "ForStatement",+ "ForInStatement",+ "ForOfStatement",+ "WhileStatement",+ "DoWhileStatement",+ "TryStatement",+ "SwitchStatement",+ "ThrowStatement",+ "LabeledStatement",+ "BlockStatement",+ "DebuggerStatement",+]);++// An expression under one of these is not judged.+// Function bodies run later, class bodies are not inspected,+// and a control-flow statement is reported once as a whole.+const NOT_MODULE_SCOPE = new Set([+ "FunctionDeclaration",+ "FunctionExpression",+ "ArrowFunctionExpression",+ "TSDeclareFunction",+ "MethodDefinition",+ "PropertyDefinition",+ "AccessorProperty",+ "StaticBlock",+ ...CONTROL_FLOW_STATEMENTS,+]);++const EXPRESSION_WRAPPERS = new Set([+ "TSAsExpression",+ "TSSatisfiesExpression",+ "TSNonNullExpression",+ "TSTypeAssertion",+ "TSInstantiationExpression",+ "ChainExpression",+]);++const PURE_ANNOTATION = /^\s*[#@]__PURE__\s*$/;++const CALLEE_DISPLAY_LIMIT = 60;++module.exports = {+ meta: {+ type: "problem",+ docs: {+ description:+ "Disallow import-time side effects in files declared side-effect free for rspack",+ category: "Best Practices",+ recommended: true,+ },+ schema: [+ {+ type: "object",+ properties: {+ pureCallees: {+ type: "array",+ items: {+ type: "object",+ properties: {+ module: { type: "string" },+ names: {+ anyOf: [+ { type: "array", items: { type: "string" } },+ { const: "*" },+ ],+ },+ },+ required: ["module", "names"],+ additionalProperties: false,+ },+ },+ sideEffectPaths: {+ type: "array",+ // Absolute paths allowed to have import-time effects: a file, or a+ // directory (trailing separator) covering every file under it+ items: { type: "string" },+ },+ internalModules: {+ type: "array",+ // Import alias roots that resolve inside this repo, e.g. "metabase"+ items: { type: "string" },+ },+ sideEffectRegistry: {+ // Path to the registry of effect files, default frontend/lint/side-effect-files.json+ type: "string",+ },+ sourceRoots: {+ type: "array",+ // Repo-relative directories a non-relative import is resolved under, default the tsconfig `*` roots+ items: { type: "string" },+ },+ },+ additionalProperties: false,+ },+ ],+ messages: {+ bareImport:+ "Bare import of '{{source}}' runs it for its effect at import time. Move the effect into a registration module listed in SIDE_EFFECT_PATHS, or into an entry.",+ callOnImport:+ "Module-scope call on the imported binding `{{callee}}` runs at import time. If it is pure, annotate it `/* #__PURE__ */` or add it to pureCallees; otherwise move it out of module scope.",+ callAtModuleScope:+ "Module-scope call `{{callee}}` runs at import time and its result is unused, so it exists only for its effect. Move it into a registration module listed in SIDE_EFFECT_PATHS, or annotate it `/* #__PURE__ */` if it is pure.",+ assignToImport:+ "Assigning to `{{target}}` mutates an imported object at import time. Move it into a registration module listed in SIDE_EFFECT_PATHS.",+ assignToGlobal:+ "Assigning to `{{target}}` writes global state at import time. Move it into a registration module listed in SIDE_EFFECT_PATHS, or into an entry.",+ topLevelAwait:+ "Top-level await runs at import time. Move it into a function that is called from an entry.",+ controlFlow:+ "`{{kind}}` at module scope means work runs at import time. Move it into a function, or into a registration module listed in SIDE_EFFECT_PATHS.",+ importsGlobalEffect:+ "'{{source}}' runs an effect at import that code outside it depends on. A side-effect-free file must not be the reason it loads; import it from an entry (or list it in SIDE_EFFECT_PATHS if this file is a registration module).",+ importsGlobalEffectPackage:+ "'{{source}}' does work at import that code outside it depends on (a polyfill, a plugin on a host, global CSS). A side-effect-free file must not be the reason it loads; import it from an entry, or through the vendor's facade.",+ },+ },++ create(context) {+ const sourceCode = context.sourceCode || context.getSourceCode();+ const filename = context.filename || context.getFilename();+ const options = context.options[0] || {};+ const pureCallees = [+ ...DEFAULT_PURE_CALLEES,+ ...(options.pureCallees || []),+ ];+ const sideEffectPaths = normalizeSideEffectPaths(+ options.sideEffectPaths || [],+ );+ const internalModules = new Set(options.internalModules || []);+ const registry = getRegistry(+ options.sideEffectRegistry || DEFAULT_REGISTRY_PATH,+ );+ const sourceRoots = (options.sourceRoots || DEFAULT_SOURCE_ROOTS).map(+ (root) => path.resolve(REPO_ROOT, root),+ );++ function isInternalModule(source) {+ return (+ source.startsWith(".") || internalModules.has(packageNameOf(source))+ );+ }++ // Collected over the whole file before any expression is judged, so a function declared below its call site still counts as local.+ const localNames = new Set();+ // local name -> { module, importedName }+ const importBindings = new Map();++ function classifyRoot(root) {+ if (root == null || root.type !== "Identifier") {+ return "local";+ }+ if (importBindings.has(root.name)) {+ return "import";+ }+ if (localNames.has(root.name)) {+ return "local";+ }+ return "global";+ }++ // The annotation may sit on the call or on a wrapper around it (`/* #__PURE__ */ foo()!`).+ function isPureAnnotated(node) {+ for (const current of wrapperChain(node)) {+ const comments = sourceCode.getCommentsBefore(current);+ if (+ comments.length > 0 &&+ PURE_ANNOTATION.test(comments[comments.length - 1].value)+ ) {+ return true;+ }+ }+ return false;+ }++ function isAllowlistedCallee(callee) {+ const { root, name } = getCalleeInfo(callee);+ const binding = root == null ? null : importBindings.get(root.name);+ if (binding == null) {+ return false;+ }+ return pureCallees.some(+ (entry) =>+ entry.module === binding.module &&+ (entry.names === "*" ||+ entry.names.includes(name) ||+ (name === root.name && entry.names.includes(binding.importedName))),+ );+ }++ function display(node) {+ const text = sourceCode.getText(node).replace(/\s+/g, " ");+ return text.length > CALLEE_DISPLAY_LIMIT+ ? `${text.slice(0, CALLEE_DISPLAY_LIMIT)}…`+ : text;+ }++ function reportMutationOf(target, node, targetNode) {+ const kind = classifyRoot(getRoot(target));+ if (kind === "local") {+ return;+ }+ context.report({+ node,+ messageId: kind === "import" ? "assignToImport" : "assignToGlobal",+ data: { target: display(targetNode || target) },+ });+ }++ // A call in a statement exists only for its effect, so every call not known pure is reported.+ // In an initializer the value is kept, so only calls into packages are reported.+ // Our own code (relative or in-repo alias imports) and `new` are trusted there.+ function checkCall(node, inStatement) {+ if (isPureAnnotated(node)) {+ return;+ }+ const callee =+ node.type === "TaggedTemplateExpression" ? node.tag : node.callee;+ const dottedPath = getDottedPath(callee);+ if (dottedPath != null && FIRST_ARGUMENT_MUTATORS.has(dottedPath)) {+ const [mutated] = node.arguments || [];+ if (mutated != null) {+ reportMutationOf(mutated, node, mutated);+ }+ return;+ }+ if (isAllowlistedCallee(callee)) {+ return;+ }+ const root = getRoot(callee);+ const kind = classifyRoot(root);+ if (kind === "import") {+ const trusted =+ !inStatement &&+ (node.type === "NewExpression" ||+ isInternalModule(importBindings.get(root.name).module));+ if (!trusted) {+ context.report({+ node,+ messageId: "callOnImport",+ data: { callee: display(callee) },+ });+ }+ } else if (inStatement) {+ context.report({+ node,+ messageId: "callAtModuleScope",+ data: { callee: display(callee) },+ });+ }+ }++ function checkAssignment(node) {+ if (node.left.type === "Identifier") {+ if (classifyRoot(node.left) === "global") {+ context.report({+ node,+ messageId: "assignToGlobal",+ data: { target: display(node.left) },+ });+ }+ } else if (node.left.type === "MemberExpression") {+ reportMutationOf(node.left, node);+ }+ }++ function checkUpdate(node) {+ if (+ node.argument.type === "MemberExpression" ||+ classifyRoot(node.argument) === "global"+ ) {+ reportMutationOf(node.argument, node);+ }+ }++ function checkBareImport(node) {+ const source = node.source.value;+ const target = source.startsWith(".")+ ? normalizePath(path.resolve(path.dirname(filename), source))+ : source;+ if (sideEffectPaths.allows(target)) {+ return;+ }+ context.report({ node, messageId: "bareImport", data: { source } });+ }++ // An import with bindings keeps its target alive only while this file is kept,+ // so a target whose effect others depend on must not be reached this way.+ function checkBindingImport(node) {+ const source = node.source.value;+ const target = resolveImport(source, path.dirname(filename), sourceRoots);+ if (target == null || sideEffectPaths.allows(target)) {+ return;+ }+ const relative = normalizePath(path.relative(REPO_ROOT, target));+ const classification = classify(registry, relative);+ if (+ (classification === "global" || classification === "entry") &&+ !isFacade(registry, relative)+ ) {+ context.report({+ node,+ messageId: "importsGlobalEffect",+ data: { source },+ });+ }+ }++ // A listed package is reported the same way whether the import is bare or has bindings,+ // unless this file is a registration module, where loading it is the point.+ function checkImport(node) {+ const bare = node.specifiers.length === 0;+ if (!bare && isTypeOnly(node)) {+ return;+ }+ const source = node.source.value;+ if (+ !isInternalModule(source) &&+ classifyPackage(registry, source) === "global" &&+ !sideEffectPaths.allows(normalizePath(filename))+ ) {+ context.report({+ node,+ messageId: "importsGlobalEffectPackage",+ data: { source },+ });+ } else if (bare) {+ checkBareImport(node);+ } else {+ checkBindingImport(node);+ }+ }++ function checkTopLevelStatement(node) {+ if (node.type === "ImportDeclaration") {+ checkImport(node);+ } else if (CONTROL_FLOW_STATEMENTS.has(node.type)) {+ context.report({+ node,+ messageId: "controlFlow",+ data: { kind: statementKeyword(node) },+ });+ }+ }++ function collectBindings(node) {+ switch (node.type) {+ case "ImportDeclaration":+ for (const specifier of node.specifiers) {+ importBindings.set(specifier.local.name, {+ module: node.source.value,+ importedName: importedNameOf(specifier),+ });+ }+ return;+ case "VariableDeclaration":+ for (const declarator of node.declarations) {+ for (const name of patternNames(declarator.id)) {+ localNames.add(name);+ }+ }+ return;+ case "FunctionDeclaration":+ case "ClassDeclaration":+ case "TSEnumDeclaration":+ case "TSModuleDeclaration":+ case "TSDeclareFunction":+ if (node.id && node.id.type === "Identifier") {+ localNames.add(node.id.name);+ }+ return;+ case "ExportNamedDeclaration":+ if (node.declaration != null) {+ collectBindings(node.declaration);+ }+ return;+ case "ExportDefaultDeclaration":+ collectBindings(node.declaration);+ return;+ default:+ return;+ }+ }++ // Runs `check` on the node when it is evaluated at module scope.+ // The Program visitor has already collected the bindings by then.+ function atModuleScope(check) {+ return (node) => {+ const placement = placementOf(node);+ if (placement !== "skipped") {+ check(node, placement === "statement");+ }+ };+ }++ return {+ Program(program) {+ for (const statement of program.body) {+ collectBindings(statement);+ }+ for (const statement of program.body) {+ checkTopLevelStatement(statement);+ }+ },+ CallExpression: atModuleScope(checkCall),+ NewExpression: atModuleScope(checkCall),+ TaggedTemplateExpression: atModuleScope(checkCall),+ ImportExpression: atModuleScope((node) => {+ context.report({+ node,+ messageId: "callAtModuleScope",+ data: { callee: "import()" },+ });+ }),+ AwaitExpression: atModuleScope((node) => {+ context.report({ node, messageId: "topLevelAwait" });+ }),+ AssignmentExpression: atModuleScope(checkAssignment),+ UpdateExpression: atModuleScope(checkUpdate),+ UnaryExpression: atModuleScope((node) => {+ if (node.operator === "delete") {+ reportMutationOf(node.argument, node);+ }+ }),+ };+ },+};++// Where an expression's value goes: "skipped" under a function, a class body or a control-flow statement,+// "statement" when it is discarded, "value" when it is kept.+function placementOf(node) {+ let placement = null;+ for (let current = node; current.parent != null; current = current.parent) {+ const { parent } = current;+ if (NOT_MODULE_SCOPE.has(parent.type)) {+ return "skipped";+ }+ if (placement == null && !discardsValueOf(parent, current)) {+ placement = parent.type === "ExpressionStatement" ? "statement" : "value";+ }+ }+ return placement ?? "value";+}++// Whether `parent` hands `child`'s value on unused, so an expression statement above still discards it.+function discardsValueOf(parent, child) {+ switch (parent.type) {+ case "SequenceExpression":+ return true;+ case "ConditionalExpression":+ return child !== parent.test;+ case "LogicalExpression":+ return child === parent.right;+ default:+ return EXPRESSION_WRAPPERS.has(parent.type);+ }+}++// The node and every TS wrapper or optional chain around it, innermost first.+function wrapperChain(node) {+ const chain = [node];+ let current = node;+ while (+ current.parent != null &&+ EXPRESSION_WRAPPERS.has(current.parent.type)+ ) {+ current = current.parent;+ chain.push(current);+ }+ return chain;+}++function unwrap(node) {+ let current = node;+ while (current != null && EXPRESSION_WRAPPERS.has(current.type)) {+ current = current.expression;+ }+ return current;+}++// The identifier an expression starts from: `a` for `a.b.c`, `a().b` and `(a as X)!.b?.c`.+// Null when there is none (a literal, `this`, an IIFE).+function getRoot(node) {+ let current = unwrap(node);+ while (current != null) {+ switch (current.type) {+ case "Identifier":+ return current;+ case "MemberExpression":+ current = unwrap(current.object);+ break;+ case "CallExpression":+ case "NewExpression":+ current = unwrap(current.callee);+ break;+ case "TaggedTemplateExpression":+ current = unwrap(current.tag);+ break;+ default:+ return null;+ }+ }+ return null;+}++// The root binding and the name called: `rem` for `rem(4)`, `extend` for `Button.extend({})`, `t` for `c("ctx").t\`\``.+function getCalleeInfo(callee) {+ const inner = unwrap(callee);+ if (inner == null) {+ return { root: null, name: null };+ }+ if (inner.type === "Identifier") {+ return { root: inner, name: inner.name };+ }+ if (inner.type === "MemberExpression") {+ const name =+ !inner.computed && inner.property.type === "Identifier"+ ? inner.property.name+ : null;+ return { root: getRoot(inner), name };+ }+ if (+ inner.type === "CallExpression" ||+ inner.type === "TaggedTemplateExpression"+ ) {+ return getCalleeInfo(inner.callee || inner.tag);+ }+ return { root: getRoot(inner), name: null };+}++// The dotted name of a plain member chain (`Object.assign`), null for anything else.+function getDottedPath(node) {+ const parts = [];+ let current = unwrap(node);+ while (current != null && current.type === "MemberExpression") {+ if (current.computed || current.property.type !== "Identifier") {+ return null;+ }+ parts.unshift(current.property.name);+ current = unwrap(current.object);+ }+ if (current == null || current.type !== "Identifier") {+ return null;+ }+ parts.unshift(current.name);+ return parts.join(".");+}++function importedNameOf(specifier) {+ switch (specifier.type) {+ case "ImportDefaultSpecifier":+ return "default";+ case "ImportNamespaceSpecifier":+ return "*";+ default:+ return specifier.imported.type === "Identifier"+ ? specifier.imported.name+ : String(specifier.imported.value);+ }+}++function patternNames(pattern) {+ switch (pattern.type) {+ case "Identifier":+ return [pattern.name];+ case "ObjectPattern":+ return pattern.properties.flatMap((property) =>+ property.type === "RestElement"+ ? patternNames(property.argument)+ : patternNames(property.value),+ );+ case "ArrayPattern":+ return pattern.elements.flatMap((element) =>+ element == null ? [] : patternNames(element),+ );+ case "AssignmentPattern":+ return patternNames(pattern.left);+ case "RestElement":+ return patternNames(pattern.argument);+ default:+ return [];+ }+}++function statementKeyword(node) {+ switch (node.type) {+ case "IfStatement":+ return "if";+ case "ForStatement":+ case "ForInStatement":+ case "ForOfStatement":+ return "for";+ case "WhileStatement":+ case "DoWhileStatement":+ return "while";+ case "TryStatement":+ return "try";+ case "SwitchStatement":+ return "switch";+ case "ThrowStatement":+ return "throw";+ case "DebuggerStatement":+ return "debugger";+ default:+ return "a block";+ }+}++function getRegistry(registryPath) {+ if (!registries.has(registryPath)) {+ registries.set(registryPath, loadRegistry(registryPath));+ }+ return registries.get(registryPath);+}++// A type-only import is erased, so nothing loads.+function isTypeOnly(node) {+ return (+ node.importKind === "type" ||+ node.specifiers.every((specifier) => specifier.importKind === "type")+ );+}++// The absolute file an import source names, or null when it is a package or does not resolve.+// A relative source is resolved from the importing file, any other under each source root in turn.+function resolveImport(source, fromDirectory, sourceRoots) {+ const bases = source.startsWith(".")+ ? [path.resolve(fromDirectory, source)]+ : sourceRoots.map((root) => path.join(root, source));+ for (const base of bases) {+ const file = resolveSourceFile(base);+ if (file != null) {+ return normalizePath(file);+ }+ }+ return null;+}++// `base`, `base.<ext>` or `base/index.<ext>`, whichever exists.+function resolveSourceFile(base) {+ const candidates = [+ base,+ ...SOURCE_EXTENSIONS.map((extension) => `${base}${extension}`),+ ...SOURCE_EXTENSIONS.map((extension) =>+ path.join(base, `index${extension}`),+ ),+ ];+ return (+ candidates.find((candidate) => {+ try {+ return fs.statSync(candidate).isFile();+ } catch {+ return false;+ }+ }) ?? null+ );+}++// `metabase/lib/x` maps to `metabase`, `@scope/pkg/x` to `@scope/pkg`.+function packageNameOf(source) {+ const segments = source.split("/");+ return source.startsWith("@") ? segments.slice(0, 2).join("/") : segments[0];+}++function normalizePath(file) {+ return file.replaceAll("\\", "/");+}++function stripScriptExtension(file) {+ return file.replace(/\.[jt]sx?$/, "");+}++// A directory entry ends with a separator and covers every file under it.+function normalizeSideEffectPaths(paths) {+ const files = new Set();+ const directories = [];+ for (const entry of paths) {+ const absolute = normalizePath(path.resolve(entry));+ if (normalizePath(entry).endsWith("/")) {+ directories.push(`${absolute}/`);+ } else {+ files.add(absolute);+ files.add(stripScriptExtension(absolute));+ }+ }+ return {+ allows(target) {+ return (+ files.has(target) ||+ files.has(stripScriptExtension(target)) ||+ directories.some((directory) => target.startsWith(directory))+ );+ },+ };+}diff --git a/frontend/lint/no-module-side-effects-options.js b/frontend/lint/no-module-side-effects-options.jsnew file mode 100644index 00000000000..13f9cffe1a4--- /dev/null+++ b/frontend/lint/no-module-side-effects-options.js@@ -0,0 +1,27 @@+const {+ SIDE_EFFECT_PATHS,+} = require("../build/shared/rspack/side-effect-free-modules.js");++// The options `metabase/no-module-side-effects` runs with in eslint.config.mjs.+// The registry scan (scripts/side-effect-files.js) uses the same object, so a file is in+// frontend/lint/side-effect-files.json exactly when the configured rule reports it.+const NO_MODULE_SIDE_EFFECTS_OPTIONS = {+ sideEffectPaths: SIDE_EFFECT_PATHS,+ // Alias roots that resolve inside the repo (the tsconfig `paths` roots),+ // so a module-scope call into them counts as our own code+ internalModules: [+ "metabase",+ "metabase-lib",+ "metabase-types",+ "metabase-enterprise",+ "embedding-sdk-bundle",+ "embedding-sdk-shared",+ "embedding-sdk-package",+ "embedding",+ "custom-viz",+ "cljs",+ "__support__",+ ],+};++module.exports = { NO_MODULE_SIDE_EFFECTS_OPTIONS };diff --git a/frontend/lint/scripts/side-effect-files.js b/frontend/lint/scripts/side-effect-files.jsnew file mode 100644index 00000000000..4960c22e724--- /dev/null+++ b/frontend/lint/scripts/side-effect-files.js@@ -0,0 +1,219 @@+/**+ * @fileoverview Keeps frontend/lint/side-effect-files.json in step with the source tree.+ * The registry lists every source file that `metabase/no-module-side-effects` reports under the options+ * eslint.config.mjs gives it, so this scans the tree with just that rule and compares.+ *+ * bun frontend/lint/scripts/side-effect-files.js --check exit 1 on drift, listing it+ * bun frontend/lint/scripts/side-effect-files.js --update add new files as unclassified, drop clean ones+ * bun frontend/lint/scripts/side-effect-files.js --verbose also print every finding+ */++const fs = require("fs");+const path = require("path");++const { Linter } = require("eslint");+const micromatch = require("micromatch");+const tseslint = require("typescript-eslint");++const rule = require("../eslint-plugin-metabase/rules/no-module-side-effects");+const {+ NO_MODULE_SIDE_EFFECTS_OPTIONS,+} = require("../no-module-side-effects-options");+const {+ DEFAULT_REGISTRY_PATH,+ classify,+ loadRegistry,+ validateRegistry,+} = require("../side-effect-registry");++const REPO_ROOT = path.resolve(__dirname, "../../..");++const SOURCE_ROOTS = ["frontend/src", "enterprise/frontend/src"];+const SOURCE_EXTENSIONS = new Set([".ts", ".tsx", ".js", ".jsx"]);+// The same files eslint.config.mjs leaves out of the rule.+const IGNORED_PATTERNS = [+ "**/*.unit.spec.*",+ "**/*.stories.*",+ "**/tests/**",+ "**/__support__/**",+ "**/*.d.ts",+];++const RULE_NAME = "metabase/no-module-side-effects";++function listSourceFiles() {+ const files = [];+ const walk = (dir) => {+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {+ const entryPath = path.join(dir, entry.name);+ if (entry.isDirectory()) {+ walk(entryPath);+ } else if (SOURCE_EXTENSIONS.has(path.extname(entry.name))) {+ files.push(path.relative(REPO_ROOT, entryPath).replaceAll("\\", "/"));+ }+ }+ };+ for (const root of SOURCE_ROOTS) {+ walk(path.join(REPO_ROOT, root));+ }+ return files+ .filter((file) => !micromatch.isMatch(file, IGNORED_PATTERNS))+ .sort();+}++function createLinter() {+ const linter = new Linter();+ const config = [+ {+ files: ["**/*.{ts,tsx,js,jsx}"],+ languageOptions: {+ parser: tseslint.parser,+ parserOptions: { ecmaFeatures: { jsx: true } },+ sourceType: "module",+ },+ plugins: { metabase: { rules: { "no-module-side-effects": rule } } },+ rules: { [RULE_NAME]: ["error", NO_MODULE_SIDE_EFFECTS_OPTIONS] },+ },+ ];+ return (file) => {+ const source = fs.readFileSync(path.join(REPO_ROOT, file), "utf8");+ // The registry records what a file does at import, so its imports of other effect files do not count.+ return linter+ .verify(source, config, { filename: path.join(REPO_ROOT, file) })+ .filter(+ (message) =>+ message.ruleId === RULE_NAME &&+ message.messageId !== "importsGlobalEffect",+ );+ };+}++// Repo-relative path -> messages, for every source file the rule reports.+function scanEffectFiles() {+ const lint = createLinter();+ const findings = new Map();+ for (const file of listSourceFiles()) {+ const messages = lint(file);+ if (messages.length > 0) {+ findings.set(file, messages);+ }+ }+ return findings;+}++// Listed packages that no source file imports, so the list cannot keep dead entries.+// A specifier is imported when it appears quoted, alone or with a subpath, anywhere in a source file.+function unimportedPackages(registry, files) {+ const unseen = new Map(+ Object.keys(registry.packages).map((specifier) => [+ specifier,+ new RegExp(`["'\`]${escapeRegExp(specifier)}(/[^"'\`]*)?["'\`]`),+ ]),+ );+ for (const file of files) {+ if (unseen.size === 0) {+ break;+ }+ const source = fs.readFileSync(path.join(REPO_ROOT, file), "utf8");+ for (const [specifier, pattern] of unseen) {+ if (pattern.test(source)) {+ unseen.delete(specifier);+ }+ }+ }+ return [...unseen.keys()];+}++function escapeRegExp(text) {+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");+}++// { missing: effect files the registry does not list, stale: exact entries whose file is clean }+function diffRegistry(registry, effectFiles) {+ const effectSet = new Set(effectFiles);+ const missing = effectFiles.filter(+ (file) => classify(registry, file) == null,+ );+ const stale = [+ ...Object.keys(registry.files).filter((key) => !key.includes("*")),+ ...registry.unclassified,+ ].filter((file) => !effectSet.has(file));+ return { missing, stale };+}++function updateRegistry(registryPath, { missing, stale }) {+ const raw = JSON.parse(fs.readFileSync(registryPath, "utf8"));+ const staleSet = new Set(stale);+ const files = Object.fromEntries(+ Object.entries(raw.files || {}).filter(([key]) => !staleSet.has(key)),+ );+ const unclassified = [+ ...(raw.unclassified || []).filter((file) => !staleSet.has(file)),+ ...missing,+ ].sort();+ fs.writeFileSync(+ registryPath,+ `${JSON.stringify({ ...raw, files, unclassified }, null, 2)}\n`,+ );+}++/* eslint-disable no-console */+function main(argv) {+ const started = Date.now();+ const findings = scanEffectFiles();+ const effectFiles = [...findings.keys()];+ const registry = loadRegistry(DEFAULT_REGISTRY_PATH);+ const diff = diffRegistry(registry, effectFiles);+ const problems = [+ ...validateRegistry(registry, effectFiles),+ ...unimportedPackages(registry, listSourceFiles()).map(+ (specifier) => `packages: nothing imports "${specifier}"`,+ ),+ ];+ const seconds = ((Date.now() - started) / 1000).toFixed(1);+ console.log(+ `${effectFiles.length} files with import-time effects (${seconds}s)`,+ );+ if (argv.includes("--verbose")) {+ for (const [file, messages] of findings) {+ console.log(` ${file}`);+ for (const message of messages) {+ console.log(` ${message.line}: ${message.message}`);+ }+ }+ }+ if (argv.includes("--update")) {+ updateRegistry(DEFAULT_REGISTRY_PATH, diff);+ console.log(+ `added ${diff.missing.length} as unclassified, removed ${diff.stale.length}`,+ );+ return 0;+ }+ for (const problem of problems) {+ console.log(`invalid: ${problem}`);+ }+ for (const file of diff.missing) {+ console.log(`missing: ${file}`);+ }+ for (const file of diff.stale) {+ console.log(`clean: ${file}`);+ }+ const drifted = problems.length + diff.missing.length + diff.stale.length;+ if (drifted > 0) {+ console.log(+ "\nregistry out of date. Run: bun frontend/lint/scripts/side-effect-files.js --update",+ );+ }+ return drifted > 0 ? 1 : 0;+}++module.exports = {+ listSourceFiles,+ scanEffectFiles,+ diffRegistry,+ unimportedPackages,+};++if (require.main === module) {+ process.exit(main(process.argv.slice(2)));+}diff --git a/frontend/lint/side-effect-files.json b/frontend/lint/side-effect-files.jsonnew file mode 100644index 00000000000..77d5bb5ccee--- /dev/null+++ b/frontend/lint/side-effect-files.json@@ -0,0 +1,221 @@+{+ "facades": [+ "frontend/src/metabase/router/",+ "frontend/src/metabase/ui/",+ "frontend/src/metabase/redux/",+ "frontend/src/metabase/dayjs/"+ ],+ "packages": {+ "@mantine/core/styles.css": "global",+ "@mantine/dates/styles.css": "global",+ "@xyflow/react/dist/style.css": "global",+ "fast-text-encoding": "global",+ "leaflet-draw": "global",+ "leaflet/dist/leaflet.css": "global",+ "react-grid-layout/css/styles.css": "global",+ "react-resizable/css/styles.css": "global"+ },+ "files": {+ "frontend/src/metabase/app*.ts*": "entry",+ "**/routes.tsx": "global",+ "frontend/src/metabase/auth/plugins/*.ts": "global",+ "frontend/src/embedding-sdk-bundle/components/public/**": "self",+ "frontend/src/embedding-sdk-shared/.storybook/**": "entry",+ "frontend/src/embedding-sdk-shared/jest/**": "entry",+ "enterprise/frontend/src/embedding-sdk-package/bin/*.ts": "entry",+ "enterprise/frontend/src/embedding-sdk-package/cli/**": "self",+ "frontend/src/metabase/static-viz/components/**": "global",+ "**/*.styled.tsx": "self",+ "**/*.schema.ts": "self",+ "enterprise/frontend/src/custom-viz/scripts/check-package-versions.ts": "entry",+ "enterprise/frontend/src/custom-viz/src/cli.integration.spec.ts": "self",+ "enterprise/frontend/src/custom-viz/src/cli.ts": "entry",+ "enterprise/frontend/src/custom-viz/src/templates/vite.config.ts": "self",+ "enterprise/frontend/src/custom-viz/vite.config.ts": "self",+ "enterprise/frontend/src/embedding-sdk-ee/auth/auth.ts": "global",+ "enterprise/frontend/src/embedding-sdk-ee/auth/index.ts": "global",+ "enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotQuestion.tsx": "global",+ "enterprise/frontend/src/embedding-sdk-ee/metabot/hooks/use-metabot.tsx": "global",+ "enterprise/frontend/src/embedding-sdk-ee/metabot/index.ts": "global",+ "enterprise/frontend/src/embedding-sdk-package/cli/cli.ts": "entry",+ "enterprise/frontend/src/embedding-sdk-package/cli/utils/ask-for-db-connection-info.ts": "global",+ "enterprise/frontend/src/embedding-sdk-package/data-app-dev-entry.tsx": "entry",+ "enterprise/frontend/src/embedding-sdk-package/data-app-dev/dev-plugin/virtual-modules.ts": "self",+ "enterprise/frontend/src/embedding-sdk-package/data-app.ts": "entry",+ "enterprise/frontend/src/embedding-sdk-package/index.ts": "entry",+ "enterprise/frontend/src/metabase-enterprise/advanced_permissions/components/ImpersonationModal/ImpersonationModalView.tsx": "self",+ "enterprise/frontend/src/metabase-enterprise/audit_app/components/AuditTableVisualization/AuditTableVisualization.tsx": "global",+ "enterprise/frontend/src/metabase-enterprise/auth/components/SettingsSAMLForm/SettingsSAMLForm.tsx": "self",+ "enterprise/frontend/src/metabase-enterprise/auth/constants.ts": "self",+ "enterprise/frontend/src/metabase-enterprise/auth/index.ts": "global",+ "enterprise/frontend/src/metabase-enterprise/clean_up/CleanupCollectionModal/utils.ts": "self",+ "enterprise/frontend/src/metabase-enterprise/custom_viz/components/CustomVizPage.tsx": "self",+ "enterprise/frontend/src/metabase-enterprise/data_apps/runtime/app-data-app.tsx": "entry",+ "enterprise/frontend/src/metabase-enterprise/data_apps/runtime/iframe-vendors.ts": "entry",+ "enterprise/frontend/src/metabase-enterprise/database_replication/DatabaseReplicationForm.tsx": "self",+ "enterprise/frontend/src/metabase-enterprise/embedding/index.ts": "global",+ "enterprise/frontend/src/metabase-enterprise/license/index.ts": "global",+ "enterprise/frontend/src/metabase-enterprise/moderation/constants.ts": "self",+ "enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/ConfirmCodeForm/ConfirmCodeForm.tsx": "self",+ "enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/SetupModal/SetupModal.tsx": "self",+ "enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AuthChallengeForm/AuthChallengeForm.tsx": "self",+ "enterprise/frontend/src/metabase-enterprise/overrides.ts": "entry",+ "enterprise/frontend/src/metabase-enterprise/plugins.ts": "entry",+ "enterprise/frontend/src/metabase-enterprise/redux.ts": "self",+ "enterprise/frontend/src/metabase-enterprise/remote_sync/constants.ts": "self",+ "enterprise/frontend/src/metabase-enterprise/remote_sync/middleware/remote-sync-listener-middleware.ts": "self",+ "enterprise/frontend/src/metabase-enterprise/replacement/pages/MigrateModelsPage/ReplaceWithTransformModal/ReplaceWithTransformModal.tsx": "self",+ "enterprise/frontend/src/metabase-enterprise/sdk-iframe-embedding-plugins.ts": "entry",+ "enterprise/frontend/src/metabase-enterprise/sdk-iframe-embedding-script-plugins.ts": "entry",+ "enterprise/frontend/src/metabase-enterprise/sdk-plugins.ts": "entry",+ "enterprise/frontend/src/metabase-enterprise/shared/index.ts": "global",+ "enterprise/frontend/src/metabase-enterprise/tenants/components/TenantForm/TenantForm.tsx": "self",+ "enterprise/frontend/src/metabase-enterprise/transforms-python/components/PythonEditor/utils.ts": "self",+ "enterprise/frontend/src/metabase-enterprise/user_provisioning/components/UserProvisioning.tsx": "self",+ "enterprise/frontend/src/metabase-enterprise/whitelabel/lib/whitelabel.ts": "global",+ "enterprise/frontend/src/metabase-enterprise/whitelabel/overrides.ts": "global",+ "frontend/src/embedding-sdk-bundle/components/private/PublicComponentStylesWrapper.tsx": "self",+ "frontend/src/embedding-sdk-bundle/components/private/SdkBreadcrumbs/setup.spec.tsx": "self",+ "frontend/src/embedding-sdk-bundle/embedding-sdk-bootstrap.ts": "entry",+ "frontend/src/embedding-sdk-bundle/index.ts": "entry",+ "frontend/src/embedding-sdk-bundle/lib/polyfill/use-sync-external-store.ts": "global",+ "frontend/src/embedding-sdk-bundle/lib/sdk-public-path.ts": "global",+ "frontend/src/embedding-sdk-bundle/lib/sdk-specific-imports.ts": "entry",+ "frontend/src/embedding-sdk-bundle/store/index.ts": "self",+ "frontend/src/embedding-sdk-bundle/store/listener-middleware.ts": "self",+ "frontend/src/embedding-sdk-bundle/store/use-sdk-selector.ts": "self",+ "frontend/src/embedding-sdk-bundle/test/CommonSdkCorsStoryWrapper.tsx": "entry",+ "frontend/src/embedding-sdk-bundle/test/CommonSdkStoryWrapper.tsx": "entry",+ "frontend/src/metabase/account/password/components/UserPasswordForm/UserPasswordForm.tsx": "self",+ "frontend/src/metabase/account/profile/components/UserProfileForm/UserProfileForm.tsx": "self",+ "frontend/src/metabase/actions/containers/ActionCreator/CreateActionForm/CreateActionForm.tsx": "self",+ "frontend/src/metabase/admin/ai/MetabotSlackSetup.tsx": "self",+ "frontend/src/metabase/admin/performance/utils.tsx": "self",+ "frontend/src/metabase/admin/settings/auth/constants.ts": "self",+ "frontend/src/metabase/admin/settings/components/ApiKeys/utils.ts": "self",+ "frontend/src/metabase/admin/settings/components/Email/BaseSMTPConnectionForm.tsx": "self",+ "frontend/src/metabase/admin/settings/components/SettingsLdapForm.tsx": "self",+ "frontend/src/metabase/admin/settings/slack/SlackSetupForm.tsx": "self",+ "frontend/src/metabase/api/ai-streaming/schemas.ts": "self",+ "frontend/src/metabase/api/analytics.ts": "self",+ "frontend/src/metabase/api/api.ts": "self",+ "frontend/src/metabase/auth/components/ForgotPasswordForm/ForgotPasswordForm.tsx": "self",+ "frontend/src/metabase/auth/components/LoginForm/LoginForm.tsx": "self",+ "frontend/src/metabase/auth/components/ResetPasswordForm/ResetPasswordForm.tsx": "self",+ "frontend/src/metabase/auth/plugins/index.ts": "entry",+ "frontend/src/metabase/comments/components/CommentEditor/EmojiSuggestionExtension.tsx": "self",+ "frontend/src/metabase/common/CreateDashboard/CreateDashboardForm.tsx": "self",+ "frontend/src/metabase/common/collections/components/CreateCollectionForm/CreateCollectionForm.tsx": "self",+ "frontend/src/metabase/common/collections/schemas.ts": "self",+ "frontend/src/metabase/common/components/CodeMirror/highlights.ts": "self",+ "frontend/src/metabase/common/components/ColorPicker/ColorPickerControls.tsx": "self",+ "frontend/src/metabase/common/components/CopyDashboardForm/CopyDashboardForm.tsx": "self",+ "frontend/src/metabase/common/components/DocumentCopyForm/DocumentCopyForm.tsx": "self",+ "frontend/src/metabase/common/components/Pickers/EntityPicker/components/NewCollectionDialog/NewCollectionDialog.tsx": "self",+ "frontend/src/metabase/common/components/SaveQuestionForm/schema.ts": "self",+ "frontend/src/metabase/common/components/Schedule/strings.ts": "self",+ "frontend/src/metabase/common/components/UndoListing.tsx": "self",+ "frontend/src/metabase/common/components/UserForm.tsx": "self",+ "frontend/src/metabase/common/components/dnd/CollectionDropTarget.tsx": "self",+ "frontend/src/metabase/common/components/dnd/ItemDragSource.tsx": "self",+ "frontend/src/metabase/common/components/dnd/ItemsDragLayer.tsx": "self",+ "frontend/src/metabase/common/components/dnd/PinDropTarget.tsx": "self",+ "frontend/src/metabase/common/components/dnd/PinnedItemSortDropTarget.tsx": "self",+ "frontend/src/metabase/common/components/tree/TreeNode.tsx": "self",+ "frontend/src/metabase/common/utils/chart-clipboard.ts": "self",+ "frontend/src/metabase/css/core/base.styled.ts": "self",+ "frontend/src/metabase/dashboard/actions/auto-wire-parameters/toasts.ts": "self",+ "frontend/src/metabase/dashboard/components/ActionViz/ActionViz.tsx": "self",+ "frontend/src/metabase/dashboard/components/grid/GridLayout.tsx": "self",+ "frontend/src/metabase/dashboard/selectors.ts": "self",+ "frontend/src/metabase/dashboard/visualizations/Heading/index.ts": "self",+ "frontend/src/metabase/dashboard/visualizations/Text/index.ts": "self",+ "frontend/src/metabase/databases/utils/schema.ts": "self",+ "frontend/src/metabase/dayjs/index.ts": "self",+ "frontend/src/metabase/dev.ts": "entry",+ "frontend/src/metabase/documents/components/editor-extensions/CardEmbed/CardEmbedNode.tsx": "self",+ "frontend/src/metabase/embedding-sdk/theme/default-component-theme.ts": "self",+ "frontend/src/metabase/embedding-sdk/vendors-side-effects.ts": "entry",+ "frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/SdkIframeEmbedSetupModal.tsx": "self",+ "frontend/src/metabase/embedding/embedding-iframe-sdk/analytics.ts": "self",+ "frontend/src/metabase/embedding/embedding-iframe-sdk/components/SdkIframeEmbedRoute.tsx": "global",+ "frontend/src/metabase/embedding/embedding-iframe-sdk/embed.ts": "entry",+ "frontend/src/metabase/hooks/use-page-title.ts": "self",+ "frontend/src/metabase/metabot/components/MetabotChat/MetabotFeedbackModal.tsx": "self",+ "frontend/src/metabase/metabot/components/MetabotInlineSQLPrompt/MetabotInlineSQLPromptWidget.tsx": "self",+ "frontend/src/metabase/metabot/components/editor-extensions/MetabotEmbed/MetabotEmbed.tsx": "self",+ "frontend/src/metabase/metabot/components/editor-extensions/MetabotMention/MetabotMentionExtension.tsx": "self",+ "frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchInput/errorHighlight.ts": "self",+ "frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchInput/metricTokenHighlight.ts": "self",+ "frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchInput/operatorHighlight.ts": "self",+ "frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchInput/trustedDocChangesOnly.ts": "self",+ "frontend/src/metabase/metrics/pages/NewMetricPage/CreateMetricModal/CreateMetricModal.tsx": "self",+ "frontend/src/metabase/monitor/tools/components/LogLevelsModal/LogLevelsModal.tsx": "self",+ "frontend/src/metabase/palette/components/PaletteShortcutsModal/PaletteShortcutsModal.tsx": "self",+ "frontend/src/metabase/palette/components/test/PaletteResults/setup.tsx": "self",+ "frontend/src/metabase/plugins/oss/caching.ts": "self",+ "frontend/src/metabase/querying/components/CodeMirrorEditor/language.ts": "self",+ "frontend/src/metabase/querying/components/NativeQueryEditor/SnippetForm/SnippetForm.tsx": "self",+ "frontend/src/metabase/querying/expressions/pratt/syntax.ts": "self",+ "frontend/src/metabase/querying/expressions/tokenizer/lezer.ts": "self",+ "frontend/src/metabase/questions/components/CopyCardForm/CopyCardForm.tsx": "self",+ "frontend/src/metabase/reducers-common.ts": "self",+ "frontend/src/metabase/redux/embed/embed.ts": "self",+ "frontend/src/metabase/redux/entities/index.ts": "self",+ "frontend/src/metabase/redux/hooks.ts": "self",+ "frontend/src/metabase/redux/store/mocks/api.ts": "self",+ "frontend/src/metabase/redux/utils.ts": "self",+ "frontend/src/metabase/rich_text_editing/tiptap/extensions/Blockquote/Blockquote.tsx": "self",+ "frontend/src/metabase/rich_text_editing/tiptap/extensions/BulletList/BulletList.tsx": "self",+ "frontend/src/metabase/rich_text_editing/tiptap/extensions/CodeBlock/CodeBlock.tsx": "self",+ "frontend/src/metabase/rich_text_editing/tiptap/extensions/Command/CommandExtension.ts": "self",+ "frontend/src/metabase/rich_text_editing/tiptap/extensions/CustomStarterKit/CustomStarterKit.tsx": "self",+ "frontend/src/metabase/rich_text_editing/tiptap/extensions/DisableMetabotSidebar.tsx": "self",+ "frontend/src/metabase/rich_text_editing/tiptap/extensions/FlexContainer/FlexContainer.tsx": "self",+ "frontend/src/metabase/rich_text_editing/tiptap/extensions/HandleEditorDrop/HandleEditorDrop.tsx": "self",+ "frontend/src/metabase/rich_text_editing/tiptap/extensions/Heading/Heading.tsx": "self",+ "frontend/src/metabase/rich_text_editing/tiptap/extensions/Mention/MentionExtension.ts": "self",+ "frontend/src/metabase/rich_text_editing/tiptap/extensions/OrderedList/OrderedList.tsx": "self",+ "frontend/src/metabase/rich_text_editing/tiptap/extensions/Paragraph/Paragraph.tsx": "self",+ "frontend/src/metabase/rich_text_editing/tiptap/extensions/PlainLink/PlainLink.ts": "self",+ "frontend/src/metabase/rich_text_editing/tiptap/extensions/ResizeNode/ResizeNode.tsx": "self",+ "frontend/src/metabase/rich_text_editing/tiptap/extensions/SmartLink/SmartLinkNode.tsx": "self",+ "frontend/src/metabase/rich_text_editing/tiptap/extensions/SupportingText/SupportingText.tsx": "self",+ "frontend/src/metabase/routes-public.tsx": "self",+ "frontend/src/metabase/routes.tsx": "entry",+ "frontend/src/metabase/schema.ts": "self",+ "frontend/src/metabase/setup/components/InviteUserForm/InviteUserForm.tsx": "self",+ "frontend/src/metabase/setup/components/LicenseTokenStep/constants.tsx": "self",+ "frontend/src/metabase/setup/components/UserForm/UserForm.tsx": "self",+ "frontend/src/metabase/static-viz/index.tsx": "entry",+ "frontend/src/metabase/static-viz/lib/text.ts": "self",+ "frontend/src/metabase/static-viz/polyfill.ts": "global",+ "frontend/src/metabase/timelines/common/components/EventForm/EventForm.tsx": "self",+ "frontend/src/metabase/timelines/common/components/TimelineForm/TimelineForm.tsx": "self",+ "frontend/src/metabase/transforms/components/IncrementalTransform/form.ts": "self",+ "frontend/src/metabase/transforms/components/TagMultiSelect/UpdateTagModal/UpdateTagModal.tsx": "self",+ "frontend/src/metabase/transforms/pages/NewTransformPage/CreateTransformModal/form.ts": "self",+ "frontend/src/metabase/transforms/pages/TransformSettingsPage/TransformSettingsSection/UpdateTargetModal/UpdateTargetModal.tsx": "self",+ "frontend/src/metabase/ui/components/overlays/HoverCard/index.tsx": "global",+ "frontend/src/metabase/ui/components/overlays/Popover/index.tsx": "global",+ "frontend/src/metabase/utils/csp-setup.ts": "global",+ "frontend/src/metabase/utils/date-time.ts": "self",+ "frontend/src/metabase/utils/i18n.ts": "global",+ "frontend/src/metabase/utils/react-compat.unit.ts": "self",+ "frontend/src/metabase/utils/scripts-sandbox/distortions-blocked-apis.ts": "self",+ "frontend/src/metabase/utils/scripts-sandbox/distortions-dom-mutate.ts": "self",+ "frontend/src/metabase/utils/settings.ts": "self",+ "frontend/src/metabase/value-formatting/geography.ts": "self",+ "frontend/src/metabase/visualizations/components/ClickActions/utils.ts": "self",+ "frontend/src/metabase/visualizations/components/EChartsRenderer/EChartsRenderer.tsx": "global",+ "frontend/src/metabase/visualizations/components/LeafletChoropleth.tsx": "self",+ "frontend/src/metabase/visualizations/components/LeafletMap.tsx": "self",+ "frontend/src/metabase/visualizations/lib/image-exports.ts": "self",+ "frontend/src/metabase/visualizations/lib/open-url.ts": "self",+ "frontend/src/metabase/visualizations/visualizations/Map/Map.tsx": "self",+ "frontend/src/metabase/visualizations/visualizations/ObjectDetail/ObjectDetail.ts": "self",+ "frontend/src/metabase/visualizations/visualizations/PivotTable/PivotTable.tsx": "self",+ "frontend/src/metabase/visualizer/visualizer.slice.ts": "self"+ },+ "unclassified": []+}diff --git a/frontend/lint/side-effect-registry.js b/frontend/lint/side-effect-registry.jsnew file mode 100644index 00000000000..3d579ab3af2--- /dev/null+++ b/frontend/lint/side-effect-registry.js@@ -0,0 +1,120 @@+/**+ * @fileoverview Reads frontend/lint/side-effect-files.json, the registry of source files that+ * `metabase/no-module-side-effects` reports as doing work at import time.+ *+ * Every file it reports is listed, classified once by a human:+ * "self" the effect only matters to the file's own importers (its own singleton or listener,+ * a value it exports), so dropping the file with its importers is correct+ * "global" the effect is consumed by code that does not import the file (a polyfill, a vendor patch,+ * a registry the app reads, a plugin slot write), so the file must be loaded from an entry+ * "entry" a bundle entry or a side-effects list, effectful by design+ * `unclassified` files are treated as "global" until someone classifies them.+ * `facades` are directory prefixes whose effect is their own exports (`metabase/ui`, `metabase/dayjs`),+ * so importing them with bindings is always fine.+ * `packages` are bare specifiers of third-party packages whose import-time work is consumed by code+ * that does not import them (a polyfill, a plugin on a host like `leaflet-draw` on `L`, global CSS).+ * It is hand-maintained: node_modules are not scanned, and a package it does not list is assumed+ * self-contained, its import-time work serving only its own exports.+ * A key matches its exact specifier and every subpath under it (`leaflet-draw` covers `leaflet-draw/x`).+ * A vendor whose plugins extend the host (dayjs) gets a facade, and other rules forbid importing it raw,+ * so it needs no entry here.+ * Keys are repo-relative paths; a key containing `*` is a micromatch pattern, and an exact key wins over a pattern.+ * `scripts/side-effect-files.js --check` keeps the file in step with the tree.+ */++const fs = require("fs");+const path = require("path");++const micromatch = require("micromatch");++const DEFAULT_REGISTRY_PATH = path.resolve(__dirname, "side-effect-files.json");++const CLASSIFICATIONS = ["self", "global", "entry"];++const PACKAGE_CLASSIFICATIONS = ["global"];++function loadRegistry(registryPath = DEFAULT_REGISTRY_PATH) {+ const registry = JSON.parse(fs.readFileSync(registryPath, "utf8"));+ const files = registry.files || {};+ const patterns = Object.keys(files).filter((key) => key.includes("*"));+ return {+ facades: registry.facades || [],+ files,+ packages: registry.packages || {},+ patterns,+ unclassified: new Set(registry.unclassified || []),+ };+}++// The classification of a repo-relative file, or null when the registry does not list it.+function classify(registry, file) {+ if (file in registry.files) {+ return registry.files[file];+ }+ if (registry.unclassified.has(file)) {+ return "global";+ }+ const matched = registry.patterns.filter((pattern) =>+ micromatch.isMatch(file, pattern),+ );+ return matched.length > 0 ? registry.files[matched[0]] : null;+}++function isFacade(registry, file) {+ return registry.facades.some((prefix) => file.startsWith(prefix));+}++// The classification of a package import source, or null when the registry does not list the package.+function classifyPackage(registry, source) {+ const listed = Object.keys(registry.packages).find(+ (specifier) => source === specifier || source.startsWith(`${specifier}/`),+ );+ return listed == null ? null : registry.packages[listed];+}++// Problems a hand-edited registry can have. Empty when it is well formed.+function validateRegistry(registry, effectFiles) {+ const problems = [];+ for (const [key, value] of Object.entries(registry.files)) {+ if (!CLASSIFICATIONS.includes(value)) {+ problems.push(`${key}: unknown classification "${value}"`);+ }+ if (registry.unclassified.has(key)) {+ problems.push(`${key}: both classified and unclassified`);+ }+ }+ for (const [specifier, value] of Object.entries(registry.packages)) {+ if (specifier === "" || specifier.startsWith(".")) {+ problems.push(`packages: "${specifier}" is not a bare specifier`);+ }+ if (!PACKAGE_CLASSIFICATIONS.includes(value)) {+ problems.push(`${specifier}: unknown package classification "${value}"`);+ }+ }+ for (const file of effectFiles) {+ if (file in registry.files) {+ continue;+ }+ const values = new Set(+ registry.patterns+ .filter((pattern) => micromatch.isMatch(file, pattern))+ .map((pattern) => registry.files[pattern]),+ );+ if (values.size > 1) {+ problems.push(+ `${file}: matches patterns with different classifications, add an exact entry`,+ );+ }+ }+ return problems;+}++module.exports = {+ DEFAULT_REGISTRY_PATH,+ CLASSIFICATIONS,+ loadRegistry,+ classify,+ classifyPackage,+ isFacade,+ validateRegistry,+};diff --git a/frontend/lint/tests/fixtures/side-effect-files/effects/entry.ts b/frontend/lint/tests/fixtures/side-effect-files/effects/entry.tsnew file mode 100644index 00000000000..c5b6d6020a9--- /dev/null+++ b/frontend/lint/tests/fixtures/side-effect-files/effects/entry.ts@@ -0,0 +1 @@+export const entry = "entry";diff --git a/frontend/lint/tests/fixtures/side-effect-files/effects/global.ts b/frontend/lint/tests/fixtures/side-effect-files/effects/global.tsnew file mode 100644index 00000000000..2dc603e2188--- /dev/null+++ b/frontend/lint/tests/fixtures/side-effect-files/effects/global.ts@@ -0,0 +1 @@+export const global = "global";diff --git a/frontend/lint/tests/fixtures/side-effect-files/effects/pure.ts b/frontend/lint/tests/fixtures/side-effect-files/effects/pure.tsnew file mode 100644index 00000000000..3c3e3c5a56c--- /dev/null+++ b/frontend/lint/tests/fixtures/side-effect-files/effects/pure.ts@@ -0,0 +1 @@+export const pure = "pure";diff --git a/frontend/lint/tests/fixtures/side-effect-files/effects/registration.ts b/frontend/lint/tests/fixtures/side-effect-files/effects/registration.tsnew file mode 100644index 00000000000..2916a893c86--- /dev/null+++ b/frontend/lint/tests/fixtures/side-effect-files/effects/registration.ts@@ -0,0 +1 @@+export const registration = "registration";diff --git a/frontend/lint/tests/fixtures/side-effect-files/effects/self.ts b/frontend/lint/tests/fixtures/side-effect-files/effects/self.tsnew file mode 100644index 00000000000..6a96e75b265--- /dev/null+++ b/frontend/lint/tests/fixtures/side-effect-files/effects/self.ts@@ -0,0 +1 @@+export const self = "self";diff --git a/frontend/lint/tests/fixtures/side-effect-files/effects/unclassified.ts b/frontend/lint/tests/fixtures/side-effect-files/effects/unclassified.tsnew file mode 100644index 00000000000..7ca41c7cb9b--- /dev/null+++ b/frontend/lint/tests/fixtures/side-effect-files/effects/unclassified.ts@@ -0,0 +1 @@+export const unclassified = "unclassified";diff --git a/frontend/lint/tests/fixtures/side-effect-files/facade/index.ts b/frontend/lint/tests/fixtures/side-effect-files/facade/index.tsnew file mode 100644index 00000000000..a7e831a5ed0--- /dev/null+++ b/frontend/lint/tests/fixtures/side-effect-files/facade/index.ts@@ -0,0 +1 @@+export const facade = "facade";diff --git a/frontend/lint/tests/fixtures/side-effect-files/registry.json b/frontend/lint/tests/fixtures/side-effect-files/registry.jsonnew file mode 100644index 00000000000..60844985380--- /dev/null+++ b/frontend/lint/tests/fixtures/side-effect-files/registry.json@@ -0,0 +1,16 @@+{+ "facades": ["frontend/lint/tests/fixtures/side-effect-files/facade/"],+ "packages": {+ "leaflet-draw": "global",+ "@mantine/core/styles.css": "global"+ },+ "files": {+ "frontend/lint/tests/fixtures/side-effect-files/effects/global.ts": "global",+ "frontend/lint/tests/fixtures/side-effect-files/effects/entry.ts": "entry",+ "frontend/lint/tests/fixtures/side-effect-files/effects/self.ts": "self",+ "frontend/lint/tests/fixtures/side-effect-files/effects/registration.ts": "global"+ },+ "unclassified": [+ "frontend/lint/tests/fixtures/side-effect-files/effects/unclassified.ts"+ ]+}diff --git a/frontend/lint/tests/no-base-api-access.unit.spec.js b/frontend/lint/tests/no-base-api-access.unit.spec.jsnew file mode 100644index 00000000000..66cbcc77cd8--- /dev/null+++ b/frontend/lint/tests/no-base-api-access.unit.spec.js@@ -0,0 +1,325 @@+import { RuleTester } from "eslint";+import tseslint from "typescript-eslint";++import rule from "../eslint-plugin-metabase/rules/no-base-api-access";++const ruleTester = new RuleTester({+ languageOptions: {+ parser: tseslint.parser,+ parserOptions: { ecmaFeatures: { jsx: true } },+ sourceType: "module",+ },+});++const COMPONENT_FILE = "/repo/frontend/src/metabase/foo/components/Foo.tsx";+const OWNER_FILE = "/repo/frontend/src/metabase/foo/api/bar.ts";+const OWNER_SINGLE_FILE = "/repo/frontend/src/metabase/foo/api.ts";+const SUPPORT_FILE = "/repo/frontend/test/__support__/api.ts";+const SPEC_FILE = "/repo/frontend/src/metabase/foo/Foo.unit.spec.tsx";+const API_MODULE_FILE = "/repo/frontend/src/metabase/api/card.ts";++const options = [+ {+ allowInjectionIn: [+ "/repo/frontend/src/metabase/api/**",+ "**/api/**",+ "**/api.ts",+ ],+ allowReachIn: [+ "/repo/frontend/src/metabase/api/**",+ "/repo/frontend/test/**",+ "**/__support__/**",+ "**/*.unit.spec.*",+ ],+ },+];++const VALID_CASES = [+ {+ name: "hook exported by the owner",+ filename: COMPONENT_FILE,+ options,+ code: `+ import { useGetCardQuery } from "metabase/api";+ export function Foo({ id }) {+ const { data } = useGetCardQuery(id);+ return data?.name ?? null;+ }+ `,+ },+ {+ name: "endpoint reached through the owner's api slice",+ filename: COMPONENT_FILE,+ options,+ code: `+ import { cardApi } from "metabase/api";+ export const selectCard = (state, id) =>+ cardApi.endpoints.getCard.select(id)(state);+ `,+ },+ {+ name: "tag invalidation through the base object",+ filename: COMPONENT_FILE,+ options,+ code: `+ import { Api } from "metabase/api";+ export const refresh = () => (dispatch) =>+ dispatch(Api.util.invalidateTags([{ type: "bookmark", id: "LIST" }]));+ `,+ },+ {+ name: "resetting the cache through the base object",+ filename: COMPONENT_FILE,+ options,+ code: `+ import { Api } from "metabase/api";+ export const logout = () => (dispatch) => dispatch(Api.util.resetApiState());+ `,+ },+ {+ name: "store wiring through the base object",+ filename: "/repo/frontend/src/metabase/redux/store.ts",+ options,+ code: `+ import { Api } from "metabase/api";+ export const reducers = { [Api.reducerPath]: Api.reducer };+ export const middleware = [Api.middleware];+ `,+ },+ {+ name: "injection inside an owner file under api/",+ filename: OWNER_FILE,+ options,+ code: `+ import { Api } from "metabase/api";+ export const barApi = Api.injectEndpoints({ endpoints: () => ({}) });+ `,+ },+ {+ name: "injection inside a module's api.ts",+ filename: OWNER_SINGLE_FILE,+ options,+ code: `+ import { Api } from "metabase/api/api";+ export const fooApi = Api.injectEndpoints({ endpoints: () => ({}) });+ `,+ },+ {+ name: "enterprise tag types added by the enterprise api file",+ filename: "/repo/enterprise/frontend/src/metabase-enterprise/api/api.ts",+ options,+ code: `+ import { Api } from "metabase/api";+ export const EnterpriseApi = Api.enhanceEndpoints({ addTagTypes: ["x"] });+ `,+ },+ {+ name: "cache seeding in test support",+ filename: SUPPORT_FILE,+ options,+ code: `+ import { Api } from "metabase/api";+ export const seed = (state, entries) =>+ Api.reducer(state, Api.util.upsertQueryEntries(entries));+ `,+ },+ {+ name: "endpoint access in a spec",+ filename: SPEC_FILE,+ options,+ code: `+ import { Api } from "metabase/api";+ const select = Api.endpoints.getSessionProperties.select();+ `,+ },+ {+ name: "endpoint access inside the api module",+ filename: API_MODULE_FILE,+ options,+ code: `+ import { Api } from "./api";+ import { Api as BaseApi } from "metabase/api/api";+ export const x = BaseApi.endpoints;+ `,+ },+ {+ name: "another module's Api binding",+ filename: COMPONENT_FILE,+ options,+ code: `+ import { Api } from "metabase/lib/api";+ export const load = () => Api.endpoints.get();+ `,+ },+ {+ name: "shadowed name is not the import",+ filename: COMPONENT_FILE,+ options,+ code: `+ import { Api } from "metabase/api";+ export function build(Api) {+ return Api.endpoints.getCard;+ }+ `,+ },+];++const INVALID_CASES = [+ {+ name: "endpoint selected by name in a component",+ filename: COMPONENT_FILE,+ options,+ code: `+ import { Api } from "metabase/api";+ export const selectProps = Api.endpoints.getSessionProperties.select();+ `,+ errors: [{ messageId: "endpointAccess" }],+ },+ {+ name: "endpoint initiated by name in an action",+ filename: "/repo/frontend/src/metabase/foo/actions.ts",+ options,+ code: `+ import { Api } from "metabase/api/api";+ export const load = (id) => (dispatch) =>+ dispatch(Api.endpoints.getCard.initiate(id));+ `,+ errors: [{ messageId: "endpointAccess" }],+ },+ {+ name: "cache seeding outside test support",+ filename: COMPONENT_FILE,+ options,+ code: `+ import { Api } from "metabase/api";+ export const seed = (entries) => Api.util.upsertQueryEntries(entries);+ `,+ errors: [{ messageId: "endpointAccess" }],+ },+ {+ name: "prefetch by name",+ filename: COMPONENT_FILE,+ options,+ code: `+ import { Api } from "metabase/api";+ export const warm = () => (dispatch) => dispatch(Api.util.prefetch("getCard", 1));+ `,+ errors: [{ messageId: "endpointAccess" }],+ },+ {+ name: "running queries thunk",+ filename: COMPONENT_FILE,+ options,+ code: `+ import { Api } from "metabase/api";+ export const wait = () => (dispatch) => dispatch(Api.util.getRunningQueriesThunk());+ `,+ errors: [{ messageId: "endpointAccess" }],+ },+ {+ name: "invalidated entries selected by name",+ filename: COMPONENT_FILE,+ options,+ code: `+ import { Api } from "metabase/api";+ export const stale = (state) => Api.util.selectInvalidatedBy(state, ["card"]);+ `,+ errors: [{ messageId: "endpointAccess" }],+ },+ {+ name: "util object handed on whole",+ filename: COMPONENT_FILE,+ options,+ code: `+ import { Api } from "metabase/api";+ export const util = Api.util;+ `,+ errors: [{ messageId: "endpointAccess" }],+ },+ {+ name: "endpoints destructured",+ filename: COMPONENT_FILE,+ options,+ code: `+ import { Api } from "metabase/api";+ const { endpoints } = Api;+ export const getCard = endpoints.getCard;+ `,+ errors: [{ messageId: "endpointAccess" }],+ },+ {+ name: "injection in a component",+ filename: COMPONENT_FILE,+ options,+ code: `+ import { Api } from "metabase/api";+ export const fooApi = Api.injectEndpoints({ endpoints: () => ({}) });+ `,+ errors: [{ messageId: "injection" }],+ },+ {+ name: "enhancement outside the enterprise api file",+ filename: "/repo/enterprise/frontend/src/metabase-enterprise/foo/Foo.tsx",+ options,+ code: `+ import { EnterpriseApi } from "metabase-enterprise/api";+ export const x = EnterpriseApi.enhanceEndpoints({ addTagTypes: ["y"] });+ `,+ errors: [{ messageId: "injection" }],+ },+ {+ name: "enterprise endpoint by name",+ filename: "/repo/enterprise/frontend/src/metabase-enterprise/foo/Foo.tsx",+ options,+ code: `+ import { EnterpriseApi } from "metabase-enterprise/api/api";+ export const x = EnterpriseApi.endpoints.getGsheetsStatus.select();+ `,+ errors: [{ messageId: "endpointAccess" }],+ },+ {+ name: "renamed base import",+ filename: COMPONENT_FILE,+ options,+ code: `+ import { Api as BaseApi } from "metabase/api";+ export const x = BaseApi.endpoints.getCard;+ `,+ errors: [{ messageId: "endpointAccess" }],+ },+ {+ name: "cache seeding in a product file named api.ts",+ filename: "/repo/frontend/src/metabase/redux/store/mocks/api.ts",+ options,+ code: `+ import { Api } from "metabase/api";+ export const seed = (state, entries) =>+ Api.reducer(state, Api.util.upsertQueryEntries(entries));+ `,+ errors: [{ messageId: "endpointAccess" }],+ },+ {+ name: "endpoint reached by name in an owner file",+ filename: OWNER_FILE,+ options,+ code: `+ import { Api } from "metabase/api";+ export const selectFoo = Api.endpoints.getFoo.select();+ `,+ errors: [{ messageId: "endpointAccess" }],+ },+ {+ name: "no allowlists means everywhere is checked",+ filename: OWNER_FILE,+ code: `+ import { Api } from "metabase/api";+ export const barApi = Api.injectEndpoints({ endpoints: () => ({}) });+ `,+ errors: [{ messageId: "injection" }],+ },+];++ruleTester.run("no-base-api-access", rule, {+ valid: VALID_CASES,+ invalid: INVALID_CASES,+});diff --git a/frontend/lint/tests/no-module-side-effects.unit.spec.js b/frontend/lint/tests/no-module-side-effects.unit.spec.jsnew file mode 100644index 00000000000..6257c68e32c--- /dev/null+++ b/frontend/lint/tests/no-module-side-effects.unit.spec.js@@ -0,0 +1,763 @@+import path from "path";++import { RuleTester } from "eslint";+import tseslint from "typescript-eslint";++import rule from "../eslint-plugin-metabase/rules/no-module-side-effects";++const ruleTester = new RuleTester({+ languageOptions: {+ parser: tseslint.parser,+ parserOptions: { ecmaFeatures: { jsx: true } },+ sourceType: "module",+ },+});++const FILENAME = "/repo/frontend/src/metabase/widgets/Widget/Widget.tsx";+const REGISTRATION_FILE =+ "/repo/frontend/src/metabase/widgets/Widget/register-widget.ts";++const REGISTRATION_DIR = "/repo/frontend/src/metabase/widgets/api/";++const options = [{ sideEffectPaths: [REGISTRATION_FILE, REGISTRATION_DIR] }];++// Real files, because the import check resolves each import on disk before looking it up.+// registry.json classifies effects/{global,entry,self,registration}.ts, leaves unclassified.ts+// unclassified, names facade/ a facade, and lists the packages leaflet-draw and @mantine/core/styles.css.+// pure.ts is not listed.+const FIXTURES = path.resolve(__dirname, "fixtures/side-effect-files");+const IMPORTER = path.join(FIXTURES, "importer/Widget.tsx");+const registryOptions = {+ sideEffectRegistry: path.join(FIXTURES, "registry.json"),+ sourceRoots: ["frontend/lint/tests/fixtures/side-effect-files"],+};++const VALID_CASES = [+ {+ name: "Mantine config helper",+ code: `+ import { Button } from "@mantine/core";+ export const buttonOverrides = { Button: Button.extend({ classNames: {} }) };+ `,+ },+ {+ name: "Mantine dates config helper",+ code: `+ import { DateInput } from "@mantine/dates";+ export const overrides = { DateInput: DateInput.extend({}) };+ `,+ },+ {+ name: "react element factories",+ code: `+ import { createContext, forwardRef, memo } from "react";+ export const Ctx = createContext(null);+ export const A = forwardRef(function A(props, ref) { return null; });+ export const B = memo(A);+ `,+ },+ {+ name: "react namespace import",+ code: `+ import React from "react";+ export const Ctx = React.createContext(null);+ export const Lazy = React.lazy(() => import("./Heavy"));+ `,+ },+ {+ name: "renamed pure import",+ code: `+ import { memo as remember } from "react";+ export const B = remember(function B() { return null; });+ `,+ },+ {+ name: "classnames",+ code: `+ import cx from "classnames";+ export const className = cx("a", "b");+ `,+ },+ {+ name: "ttag tagged templates",+ code: `+ import { c, t } from "ttag";+ export const LABEL = t\`Hello\`;+ export const CONTEXT_LABEL = c("a greeting").t\`Hello\`;+ `,+ },+ {+ name: "emotion styled",+ code: `+ import styled from "@emotion/styled";+ import { Icon } from "./Icon";+ export const FixedSizeIcon = styled(Icon)\`flex-shrink: 0;\`;+ `,+ },+ {+ name: "freezing a same-file object",+ code: `+ const FALLBACK = { charts: [] };+ Object.freeze(FALLBACK);+ Object.freeze(FALLBACK.charts);+ `,+ },+ {+ name: "assigning onto a same-file object",+ code: `+ import { Menu as MantineMenu } from "@mantine/core";+ function Menu(props) { return null; }+ Object.assign(Menu, MantineMenu, { Item });+ const Item = () => null;+ `,+ },+ {+ name: "displayName on a same-file component",+ code: `+ import { HoverCard as MantineHoverCard } from "@mantine/core";+ const MantineDropdown = MantineHoverCard.Dropdown;+ const HoverCardDropdown = function Dropdown() { return null; };+ HoverCardDropdown.displayName = MantineDropdown.displayName;+ `,+ },+ {+ name: "compound component members on a same-file component",+ code: `+ import { Menu as MantineMenu } from "@mantine/core";+ export function Menu(props) { return null; }+ Menu.Item = MantineMenu.Item;+ `,+ },+ {+ name: "builtin containers",+ code: `+ export const cache = new Map();+ export const seen = new Set([1, 2]);+ export const RE = new RegExp("x");+ `,+ },+ {+ name: "array spread and map on a same-file value",+ code: `+ const BASE = ["a", "b"];+ export const ALL = [...BASE, "c"].map((name) => name.toUpperCase());+ `,+ },+ {+ name: "optional chaining reads",+ code: `+ const win = typeof window !== "undefined" ? window : ({} as Window);+ const tokenFeatures = win.MetabaseBootstrap?.["token-features"] ?? {};+ export const shouldWhitelabel = !!tokenFeatures["whitelabel"];+ `,+ },+ {+ name: "annotated Object.assign onto an import",+ code: `+ import { Popover as MantinePopover } from "@mantine/core";+ export const Popover = /* #__PURE__ */ Object.assign(MantinePopover, { Dropdown });+ const Dropdown = () => null;+ `,+ },+ {+ name: "annotated call on a package (@ form)",+ code: `+ import { registerThing } from "some-registry";+ export const thing = /* @__PURE__ */ registerThing();+ `,+ },+ {+ name: "annotated call on a package through a cast",+ code: `+ import { registerThing } from "some-registry";+ export const thing = /* #__PURE__ */ registerThing() as unknown;+ `,+ },+ {+ name: "annotated statement",+ code: `+ import { registerThing } from "./registry";+ /* #__PURE__ */ registerThing();+ `,+ },+ {+ name: "css module binding import",+ code: `+ import S from "./Widget.module.css";+ export const className = S.root;+ `,+ },+ {+ name: "bare import of a listed side-effect file",+ code: `import "./register-widget";`,+ filename: FILENAME,+ options,+ },+ {+ name: "bare import of a listed side-effect file with extension",+ code: `import "./register-widget.ts";`,+ filename: FILENAME,+ options,+ },+ {+ name: "bare import of a file under a listed side-effect directory",+ code: `import "../api/nested/register-endpoints";`,+ filename: FILENAME,+ options,+ },+ {+ name: "enum",+ code: `+ export enum Size { Small = "sm", Large = "lg" }+ const enum Inline { A = 1 }+ `,+ },+ {+ name: "object literal export",+ code: `+ export const CONFIG = { a: 1, b: [1, 2], c: { d: () => 1 } };+ `,+ },+ {+ name: "class and function declarations",+ code: `+ import { Base } from "./base";+ export class Foo extends Base { static x = init(); }+ export function bar() { return dayjs.extend(utc); }+ export default function baz() {}+ `,+ },+ {+ name: "effects inside function bodies",+ code: `+ import dayjs from "dayjs";+ import utc from "dayjs/plugin/utc";+ export function setup() { dayjs.extend(utc); window.foo = 1; }+ export const setupArrow = () => { dayjs.extend(utc); };+ `,+ },+ {+ name: "type-only statements",+ code: `+ import type { X } from "./x";+ export type Y = X;+ export interface Z { y: Y }+ declare global { interface Window { foo: number } }+ `,+ },+ {+ name: "call on a relative import in an initializer",+ code: `+ import { getBaseColors } from "./constants/base-colors";+ import { DEFAULT_ACCENT_COLORS } from "./constants/accent-colors";+ export const baseColors = getBaseColors();+ export const charts = DEFAULT_ACCENT_COLORS.flatMap((c) => [c]);+ `,+ },+ {+ name: "call on an in-repo alias import in an initializer",+ code: `+ import { createThunkAction } from "metabase/lib/redux";+ import * as Lib from "metabase-lib";+ export const RUN = createThunkAction("RUN", () => () => {});+ export const stage = Lib.stageCount({});+ `,+ options: [{ internalModules: ["metabase", "metabase-lib"] }],+ },+ {+ name: "redux and underscore composition helpers",+ code: `+ import { createSelector } from "@reduxjs/toolkit";+ import { connect } from "react-redux";+ import _ from "underscore";+ export const getA = createSelector([(s) => s], (s) => s);+ export const Connected = _.compose(connect(() => ({})))(function View() {});+ `,+ },+ {+ name: "same-file call in an initializer",+ code: `+ function buildTheme() { return {}; }+ export const theme = buildTheme();+ `,+ },+ {+ name: "builtin call in an initializer",+ code: `+ export const KEYS = Object.keys({ a: 1 });+ export const NOW = Date.now();+ `,+ },+ {+ name: "constructing an imported class in an initializer",+ code: `+ import { EventEmitter } from "events";+ export const emitter = new EventEmitter();+ `,+ },+ {+ name: "call on an import through a cast, in a local declaration, allowlisted",+ code: `+ import { factory } from "@mantine/core";+ export const X = (factory(function X() {}) as unknown)!;+ `,+ },+ {+ name: "jsx element export",+ code: `+ import { Icon } from "./Icon";+ export const DEFAULT_ICON = <Icon name="x" />;+ `,+ },+ {+ name: "extra pure callee from options",+ code: `+ import dayjs from "dayjs";+ export const now = dayjs();+ `,+ options: [{ pureCallees: [{ module: "dayjs", names: "*" }] }],+ },+ {+ name: "imports a file whose effect is its own",+ code: `import { self } from "../effects/self";`,+ filename: IMPORTER,+ options: [registryOptions],+ },+ {+ name: "imports a facade",+ code: `import { facade } from "../facade";`,+ filename: IMPORTER,+ options: [registryOptions],+ },+ {+ name: "imports an unregistered file",+ code: `import { pure } from "../effects/pure";`,+ filename: IMPORTER,+ options: [registryOptions],+ },+ {+ name: "imports a global-effect file listed in sideEffectPaths",+ code: `import { registration } from "../effects/registration";`,+ filename: IMPORTER,+ options: [+ {+ ...registryOptions,+ sideEffectPaths: [path.join(FIXTURES, "effects/registration.ts")],+ },+ ],+ },+ {+ name: "type-only import of a global-effect file",+ code: `+ import type { Global } from "../effects/global";+ import { type Entry } from "../effects/entry";+ export type T = Global | Entry;+ `,+ filename: IMPORTER,+ options: [registryOptions],+ },+ {+ name: "alias import of a self-effect file",+ code: `import { self } from "effects/self";`,+ filename: IMPORTER,+ options: [registryOptions],+ },+ {+ name: "package import that resolves nowhere",+ code: `import { effects } from "effects";`,+ filename: IMPORTER,+ options: [registryOptions],+ },+ {+ name: "imports packages the registry does not list",+ code: `+ import React from "react";+ import cx from "classnames";+ import * as d3 from "d3";+ export const all = [React, cx, d3];+ `,+ filename: IMPORTER,+ options: [registryOptions],+ },+ {+ name: "type-only import of a listed package",+ code: `import type { DrawEvents } from "leaflet-draw";`,+ filename: IMPORTER,+ options: [registryOptions],+ },+ {+ name: "imports a listed package from a file in sideEffectPaths",+ code: `+ import { Draw } from "leaflet-draw";+ export { Draw };+ `,+ filename: REGISTRATION_FILE,+ options: [{ ...registryOptions, sideEffectPaths: [REGISTRATION_FILE] }],+ },+];++const INVALID_CASES = [+ {+ name: "member assignment on an import",+ code: `+ import { Popover as MantinePopover } from "@mantine/core";+ const Dropdown = () => null;+ MantinePopover.Dropdown = Dropdown;+ `,+ errors: [{ messageId: "assignToImport" }],+ },+ {+ name: "call on an import",+ code: `+ import dayjs from "dayjs";+ import utc from "dayjs/plugin/utc";+ dayjs.extend(utc);+ `,+ errors: [{ messageId: "callOnImport" }],+ },+ {+ name: "call on an import through a cast",+ code: `+ import dayjs from "dayjs";+ import utc from "dayjs/plugin/utc";+ dayjs.extend(utc) as unknown;+ `,+ errors: [{ messageId: "callOnImport" }],+ },+ {+ name: "call on an import through parentheses and a non-null assertion",+ code: `+ import dayjs from "dayjs";+ import utc from "dayjs/plugin/utc";+ (dayjs.extend(utc))!;+ `,+ errors: [{ messageId: "callOnImport" }],+ },+ {+ name: "optional call on an import",+ code: `+ import { maybeRegister } from "./registry";+ maybeRegister?.();+ `,+ errors: [{ messageId: "callOnImport" }],+ },+ {+ name: "window write",+ code: `window.foo = 1;`,+ errors: [{ messageId: "assignToGlobal" }],+ },+ {+ name: "globalThis write",+ code: `globalThis.x = 1;`,+ errors: [{ messageId: "assignToGlobal" }],+ },+ {+ name: "compound assignment on an import",+ code: `+ import { counters } from "./counters";+ counters.total += 1;+ `,+ errors: [{ messageId: "assignToImport" }],+ },+ {+ name: "increment on an import",+ code: `+ import { counters } from "./counters";+ counters.total++;+ `,+ errors: [{ messageId: "assignToImport" }],+ },+ {+ name: "delete on an import",+ code: `+ import { registry } from "./registry";+ delete registry.entry;+ `,+ errors: [{ messageId: "assignToImport" }],+ },+ {+ name: "bare css import",+ code: `import "./x.css";`,+ errors: [{ messageId: "bareImport" }],+ },+ {+ name: "bare package import",+ code: `import "some-polyfill";`,+ errors: [{ messageId: "bareImport" }],+ },+ {+ name: "bare import of an unlisted sibling",+ code: `import "./register-something-else";`,+ filename: FILENAME,+ options,+ errors: [{ messageId: "bareImport" }],+ },+ {+ name: "bare import of a sibling of a listed side-effect directory",+ code: `import "../../api-client";`,+ filename: FILENAME,+ options,+ errors: [{ messageId: "bareImport" }],+ },+ {+ name: "Object.assign onto an import without an annotation",+ code: `+ import { Popover as MantinePopover } from "@mantine/core";+ const Dropdown = () => null;+ Object.assign(MantinePopover, { Dropdown });+ `,+ errors: [{ messageId: "assignToImport" }],+ },+ {+ name: "Object.assign onto an import in an initializer",+ code: `+ import { Popover as MantinePopover } from "@mantine/core";+ const Dropdown = () => null;+ export const Popover = Object.assign(MantinePopover, { Dropdown });+ `,+ errors: [{ messageId: "assignToImport" }],+ },+ {+ name: "Object.freeze on an import",+ code: `+ import { DEFAULTS } from "./defaults";+ Object.freeze(DEFAULTS);+ `,+ errors: [{ messageId: "assignToImport" }],+ },+ {+ name: "imported registration function called as a statement",+ code: `+ import { registerX } from "./registry";+ registerX();+ `,+ errors: [{ messageId: "callOnImport" }],+ },+ {+ name: "same-file function called as a statement",+ code: `+ function registerX() {}+ registerX();+ `,+ errors: [{ messageId: "callAtModuleScope" }],+ },+ {+ name: "iife statement",+ code: `(() => { window.foo = 1; })();`,+ errors: [{ messageId: "callAtModuleScope" }],+ },+ {+ name: "guarded call",+ code: `+ import { registerX } from "./registry";+ const isDev = process.env.NODE_ENV !== "production";+ isDev && registerX();+ `,+ errors: [{ messageId: "callOnImport" }],+ },+ {+ name: "if at module scope",+ code: `+ import { registerX } from "./registry";+ if (typeof window !== "undefined") { registerX(); }+ `,+ errors: [{ messageId: "controlFlow", data: { kind: "if" } }],+ },+ {+ name: "for at module scope",+ code: `+ const items = [];+ for (const item of items) { items.push(item); }+ `,+ errors: [{ messageId: "controlFlow", data: { kind: "for" } }],+ },+ {+ name: "try at module scope",+ code: `try { JSON.parse("x"); } catch (e) {}`,+ errors: [{ messageId: "controlFlow", data: { kind: "try" } }],+ },+ {+ name: "top-level await",+ code: `+ import { load } from "./load";+ const data = await load();+ `,+ errors: [{ messageId: "topLevelAwait" }],+ },+ {+ name: "top-level await statement",+ code: `await Promise.resolve();`,+ errors: [{ messageId: "topLevelAwait" }],+ },+ {+ name: "export initialized from a package call",+ code: `+ import { registerThing } from "some-registry";+ export const thing = registerThing();+ `,+ errors: [{ messageId: "callOnImport" }],+ },+ {+ name: "package call nested in an object initializer",+ code: `+ import { registerThing } from "some-registry";+ export const things = { thing: registerThing(), list: [registerThing()] };+ `,+ errors: [{ messageId: "callOnImport" }, { messageId: "callOnImport" }],+ },+ {+ name: "package call nested in an object inside an array initializer",+ code: `+ import { registerThing } from "some-registry";+ export const things = [{ thing: registerThing() }];+ `,+ errors: [{ messageId: "callOnImport" }],+ },+ {+ name: "package call in a jsx attribute",+ code: `+ import { registerThing } from "some-registry";+ export const DEFAULT = <div onClick={registerThing()} />;+ `,+ errors: [{ messageId: "callOnImport" }],+ },+ {+ name: "delete inside a sequence",+ code: `+ import { registry } from "./registry";+ let step = 0;+ (step = 1, delete registry.entry);+ `,+ errors: [{ messageId: "assignToImport" }],+ },+ {+ name: "package call in a spread",+ code: `+ import { getDefaults } from "some-defaults";+ export const config = { ...getDefaults() };+ `,+ errors: [{ messageId: "callOnImport" }],+ },+ {+ name: "push onto an imported list",+ code: `+ import { registry } from "./registry";+ registry.list.push({});+ `,+ errors: [{ messageId: "callOnImport" }],+ },+ {+ name: "dom mutation",+ code: `+ const el = document.createElement("div");+ document.body.appendChild(el);+ `,+ errors: [{ messageId: "callAtModuleScope" }],+ },+ {+ name: "timer",+ code: `setTimeout(() => {}, 0);`,+ errors: [{ messageId: "callAtModuleScope" }],+ },+ {+ name: "dynamic import",+ code: `import("./heavy");`,+ errors: [{ messageId: "callAtModuleScope" }],+ },+ {+ name: "alias import not listed as internal",+ code: `+ import { registerThing } from "metabase/registry";+ export const thing = registerThing();+ `,+ options: [{ internalModules: ["metabase-lib"] }],+ errors: [{ messageId: "callOnImport" }],+ },+ {+ name: "relative import called as a statement",+ code: `+ import { registerThing } from "./registry";+ registerThing();+ `,+ errors: [{ messageId: "callOnImport" }],+ },+ {+ name: "unallowlisted name from an allowlisted module",+ code: `+ import { registerCustomThing } from "@mantine/core";+ export const thing = registerCustomThing();+ `,+ errors: [{ messageId: "callOnImport" }],+ },+ {+ name: "imports a global-effect file",+ code: `import { global } from "../effects/global";`,+ filename: IMPORTER,+ options: [registryOptions],+ errors: [{ messageId: "importsGlobalEffect" }],+ },+ {+ name: "imports an entry",+ code: `import entry from "../effects/entry";`,+ filename: IMPORTER,+ options: [registryOptions],+ errors: [{ messageId: "importsGlobalEffect" }],+ },+ {+ name: "imports an unclassified file",+ code: `import * as unclassified from "../effects/unclassified";`,+ filename: IMPORTER,+ options: [registryOptions],+ errors: [{ messageId: "importsGlobalEffect" }],+ },+ {+ name: "alias import of a global-effect file",+ code: `import { global } from "effects/global";`,+ filename: IMPORTER,+ options: [registryOptions],+ errors: [{ messageId: "importsGlobalEffect" }],+ },+ {+ name: "value import beside a type import of a global-effect file",+ code: `import { type Global, global } from "../effects/global";`,+ filename: IMPORTER,+ options: [registryOptions],+ errors: [{ messageId: "importsGlobalEffect" }],+ },+ {+ name: "imports a listed package with bindings",+ code: `import { Draw } from "leaflet-draw";`,+ filename: IMPORTER,+ options: [registryOptions],+ errors: [{ messageId: "importsGlobalEffectPackage" }],+ },+ {+ name: "bare import of a listed package",+ code: `import "@mantine/core/styles.css";`,+ filename: IMPORTER,+ options: [registryOptions],+ errors: [{ messageId: "importsGlobalEffectPackage" }],+ },+ {+ name: "bare import of a subpath of a listed package",+ code: `import "leaflet-draw/dist/leaflet.draw.css";`,+ filename: IMPORTER,+ options: [registryOptions],+ errors: [{ messageId: "importsGlobalEffectPackage" }],+ },+ {+ name: "extra pure callee only allows the listed name",+ code: `+ import dayjs from "dayjs";+ import utc from "dayjs/plugin/utc";+ dayjs.extend(utc);+ `,+ options: [{ pureCallees: [{ module: "dayjs", names: ["default"] }] }],+ errors: [{ messageId: "callOnImport" }],+ },+];++ruleTester.run("no-module-side-effects", rule, {+ valid: VALID_CASES,+ invalid: INVALID_CASES,+});diff --git a/frontend/lint/tests/side-effect-files.unit.spec.js b/frontend/lint/tests/side-effect-files.unit.spec.jsnew file mode 100644index 00000000000..6aa368a0ab1--- /dev/null+++ b/frontend/lint/tests/side-effect-files.unit.spec.js@@ -0,0 +1,51 @@+import fs from "fs";+import path from "path";++import {+ diffRegistry,+ listSourceFiles,+ scanEffectFiles,+ unimportedPackages,+} from "../scripts/side-effect-files";+import {+ DEFAULT_REGISTRY_PATH,+ loadRegistry,+ validateRegistry,+} from "../side-effect-registry";++const REPO_ROOT = path.resolve(__dirname, "../../..");++// A side-effect-free directory drops an unused file together with everything only it imports,+// so an import-time effect two files away is lost as silently as one in the file itself.+// The registry records every file the rule reports, classified once by hand, and the rule's+// import check consults it. This scan runs the rule over the whole tree so a new effect file+// anywhere fails CI until it is classified.+describe("side-effect-files.json", () => {+ const registry = loadRegistry(DEFAULT_REGISTRY_PATH);+ const effectFiles = [...scanEffectFiles().keys()];++ it("lists every file the rule reports and nothing else", () => {+ const { missing, stale } = diffRegistry(registry, effectFiles);+ const report = [+ ...missing.map((file) => `unregistered effect file: ${file}`),+ ...stale.map((file) => `registered but clean: ${file}`),+ ];+ // Run `bun frontend/lint/scripts/side-effect-files.js --update`, then classify the new entries.+ expect(report).toEqual([]);+ });++ it("is well formed", () => {+ expect(validateRegistry(registry, effectFiles)).toEqual([]);+ });++ it("only lists packages something imports", () => {+ expect(unimportedPackages(registry, listSourceFiles())).toEqual([]);+ });++ it("only names facades that exist", () => {+ for (const prefix of registry.facades) {+ expect(prefix.endsWith("/")).toBe(true);+ expect(fs.existsSync(path.join(REPO_ROOT, prefix))).toBe(true);+ }+ });+});diff --git a/frontend/lint/tests/side-effect-free-modules.unit.spec.js b/frontend/lint/tests/side-effect-free-modules.unit.spec.jsindex 678004442f3..2bd653612f6 100644--- a/frontend/lint/tests/side-effect-free-modules.unit.spec.js+++ b/frontend/lint/tests/side-effect-free-modules.unit.spec.js@@ -1,7 +1,10 @@import fs from "fs";import path from "path";-import { SIDE_EFFECT_FREE_PATHS } from "../../build/shared/rspack/side-effect-free-modules";+import {+ SIDE_EFFECT_FREE_PATHS,+ SIDE_EFFECT_PATHS,+} from "../../build/shared/rspack/side-effect-free-modules";// A directory in SIDE_EFFECT_FREE_PATHS promises rspack that importing any file// in it, and using none of its exports, has no observable effect. Rspack cannot@@ -9,42 +12,37 @@ import { SIDE_EFFECT_FREE_PATHS } from "../../build/shared/rspack/side-effect-fr// meant to run, while dev and jest keep working, and no size budget catches it// because dropping more is never a size failure.//-// The half of the contract that is mechanically detectable is import-time effects,-// which is what this covers. Whether a top-level call is pure still needs a human.+// The contents are checked by the `metabase/no-module-side-effects` lint rule,+// which eslint.config.mjs applies to every directory in the list. This only+// checks that the lists still point at real files, since a stale entry silently+// stops applying after a move.const SOURCE_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx"];-function sourceFilesIn(dir) {- return fs- .readdirSync(dir, { withFileTypes: true })- .flatMap((entry) => {- const entryPath = path.join(dir, entry.name);- if (entry.isDirectory()) {- return sourceFilesIn(entryPath);- }- return SOURCE_EXTENSIONS.includes(path.extname(entry.name))- ? [entryPath]- : [];- })- .filter((file) => !file.includes(".unit.spec."));-}--// `import "./x"` and `require("./x")`, which exist only for their side effects.-const BARE_IMPORT =- /^\s*(?:import\s+["'][^"']+["']|require\(["'][^"']+["']\))/m;-// Assets pulled in for their effect on the page rather than for a binding.-const ASSET_IMPORT = /^\s*import\s+[^;]*["'][^"']+\.(?:css|svg|png|jpe?g)["']/m;--describe.each(SIDE_EFFECT_FREE_PATHS)("side-effect-free %s", (dir) => {- const files = sourceFilesIn(dir);-- it("has source files to check", () => {- expect(files.length).toBeGreaterThan(0);+function hasSourceFiles(dir) {+ return fs.readdirSync(dir, { withFileTypes: true }).some((entry) => {+ const entryPath = path.join(dir, entry.name);+ return entry.isDirectory()+ ? hasSourceFiles(entryPath)+ : SOURCE_EXTENSIONS.includes(path.extname(entry.name));});+}- it.each(files)("%s has no import-time side effects", (file) => {- const source = fs.readFileSync(file, "utf8");- expect(BARE_IMPORT.test(source)).toBe(false);- expect(ASSET_IMPORT.test(source)).toBe(false);+it.each(SIDE_EFFECT_FREE_PATHS)(+ "side-effect-free directory %s has source files (a moved directory should be removed from the list)",+ (dir) => {+ expect(hasSourceFiles(dir)).toBe(true);+ },+);++// The paths that opt back out must exist, otherwise the exclusion silently+// stops applying after a move and the effect they carry becomes shakeable.+// A directory entry ends with a separator and must still hold source files.+for (const entry of SIDE_EFFECT_PATHS) {+ it(`side-effect path ${entry} exists`, () => {+ const exists = entry.endsWith(path.sep)+ ? hasSourceFiles(entry)+ : fs.statSync(entry).isFile();+ expect(exists).toBe(true);});-});+}diff --git a/frontend/src/metabase/app-embed-sdk.tsx b/frontend/src/metabase/app-embed-sdk.tsxindex b0d27e0e63c..c66ebaa5e69 100644--- a/frontend/src/metabase/app-embed-sdk.tsx+++ b/frontend/src/metabase/app-embed-sdk.tsx@@ -1,7 +1,7 @@import { createRoot } from "react-dom/client";// Setup CSP nonce for CodeMirror dynamic styles-import "metabase/utils/csp";+import "metabase/utils/csp-setup";// Import the embedding SDK vendors side-effectsimport "metabase/embedding-sdk/vendors-side-effects";diff --git a/frontend/src/metabase/app.tsx b/frontend/src/metabase/app.tsxindex 28549bac158..5b4fbb8f9a4 100644--- a/frontend/src/metabase/app.tsx+++ b/frontend/src/metabase/app.tsx@@ -18,7 +18,7 @@ import "metabase/auth/plugins";// This is conditionally aliased in the webpack config.// If EE isn't enabled, it loads an empty file.// Set CSP nonce for dynamic style injection (e.g. CodeMirror)-import "metabase/utils/csp";+import "metabase/utils/csp-setup";import { type Middleware, isAction } from "@reduxjs/toolkit";import { DragDropContextProvider } from "react-dnd";diff --git a/frontend/src/metabase/embedding-sdk/vendors-side-effects.ts b/frontend/src/metabase/embedding-sdk/vendors-side-effects.tsindex 67a002e12e3..3b6d902eb2d 100644--- a/frontend/src/metabase/embedding-sdk/vendors-side-effects.ts+++ b/frontend/src/metabase/embedding-sdk/vendors-side-effects.ts@@ -2,3 +2,7 @@ import "@mantine/core/styles.css";import "@mantine/dates/styles.css";import "metabase/css/index.module.css";++// The SDK bundle reads the CSP nonce through get-nonce, so it is set here.+// Otherwise nothing in the bundle sets it.+import "metabase/utils/csp-setup";diff --git a/frontend/src/metabase/utils/csp-setup.ts b/frontend/src/metabase/utils/csp-setup.tsnew file mode 100644index 00000000000..c04cfce1256--- /dev/null+++ b/frontend/src/metabase/utils/csp-setup.ts@@ -0,0 +1,5 @@+import { setNonce } from "get-nonce";++// Store the CSP nonce so that libraries using get-nonce can read it when injecting dynamic styles.+// Every get-nonce reader depends on this having run, so entries import this file for its effect.+setNonce(window.MetabaseNonce ?? "");diff --git a/frontend/src/metabase/utils/csp.ts b/frontend/src/metabase/utils/csp.tsindex 37cfc544ca8..3fdbb2aa281 100644--- a/frontend/src/metabase/utils/csp.ts+++ b/frontend/src/metabase/utils/csp.ts@@ -1,12 +1,6 @@-/**- * Store the CSP nonce so that libraries using `get-nonce` (e.g. CodeMirror)- * can read it when injecting dynamic styles. The nonce is generated server-side- * and placed on the window by the HTML template.- */-import { getNonce, setNonce } from "get-nonce";--setNonce(window.MetabaseNonce ?? "");+import { getNonce } from "get-nonce";+// The nonce is stored by metabase/utils/csp-setup, which every entry imports.export function getCspNonce() {return getNonce();}