Skip to content

Commit

Permalink
[metabase-lib] Dev experience and CLJC infra improvements
Browse files Browse the repository at this point in the history
Dev experience:
- CLJS now has source maps
- Devtools extension renders CLJS data in Chrome (et al) Devtools
- Use a debug build of CLJS in the tests
- Fixed line numbers and breakpoints being off-by-one in Devtools

CLJC infra:
- More robust direct approach to JS<->CLJS conversions, powered by
  Malli transformers.
- Powerful `define-getters-and-setters` macro to generate the accessors.
  • Loading branch information
bshepherdson committed Feb 27, 2023
1 parent c25066c commit 4580eab
Show file tree
Hide file tree
Showing 19 changed files with 606 additions and 143 deletions.
1 change: 1 addition & 0 deletions .clj-kondo/config.edn
Original file line number Diff line number Diff line change
Expand Up @@ -583,6 +583,7 @@
metabase.api.embed-test/with-embedding-enabled-and-temp-dashcard-referencing macros.metabase.api.embed-test/with-embedding-enabled-and-temp-dashcard-referencing
metabase.api.public-test/with-sharing-enabled-and-temp-card-referencing macros.metabase.api.public-test/with-sharing-enabled-and-temp-card-referencing
metabase.api.public-test/with-sharing-enabled-and-temp-dashcard-referencing macros.metabase.api.public-test/with-sharing-enabled-and-temp-dashcard-referencing
metabase.domain-entities.malli/define-getters-and-setters macros.metabase.domain-entities.malli/define-getters-and-setters
metabase.models.params.chain-filter-test/chain-filter macros.metabase.models.params.chain-filter-test/chain-filter
metabase.models.params.chain-filter-test/chain-filter-search macros.metabase.models.params.chain-filter-test/chain-filter
metabase.models.user-test/with-groups macros.metabase.models.user-test/with-groups
Expand Down
10 changes: 10 additions & 0 deletions .clj-kondo/macros/metabase/domain_entities/malli.clj
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
(ns macros.metabase.domain-entities.malli)

(defmacro define-getters-and-setters [schema & defs]
`(do
(comment ~schema) ;; Reference the schema
~@(for [[sym _path] (partition 2 defs)]
`(do
(defn ~sym "docs" [_x#] nil)
(defn ~(symbol (str "with-" (name sym))) "docs" [x# _new#] x#)
(defn ~(symbol (str (name sym) "-js")) "docs" [x#] x#)))))
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ dev/src/dev/nocommit/
*~
**/cypress_sample_database.json
/frontend/src/cljs
/frontend/src/cljs_release
.shadow-cljs

# lsp: ignore all but the config file
Expand Down
15 changes: 11 additions & 4 deletions deps.edn
Original file line number Diff line number Diff line change
Expand Up @@ -282,10 +282,17 @@
:cljs
{:extra-paths ["test" "shared/test"]
:extra-deps
{cljs-bean/cljs-bean {:mvn/version "1.9.0"}
com.lambdaisland/glogi {:mvn/version "1.2.164"}
io.github.metabase/hawk {:sha "45ed36008014f9ac1ea66beb56fb1c4c39f8342b"}
thheller/shadow-cljs {:mvn/version "2.20.20"}}}
{binaryage/devtools {:mvn/version "1.0.6"}
cider/cider-nrepl {:mvn/version "0.30.0"}
cider/piggieback {:mvn/version "0.5.3"}
cljs-bean/cljs-bean {:mvn/version "1.9.0"}
com.lambdaisland/glogi {:mvn/version "1.2.164"}
io.github.metabase/hawk {:sha "45ed36008014f9ac1ea66beb56fb1c4c39f8342b"}
;; Forcibly targeting a newer release than ships by default with shadow-cljs 2.20.20.
;; It fixes an issue where TypeScript can't parse the `cljs_env.js` output file.
org.clojure/google-closure-library {:mvn/version "0.0-20230227-c7c0a541"}
refactor-nrepl/refactor-nrepl {:mvn/version "3.6.0"}
thheller/shadow-cljs {:mvn/version "2.20.20"}}}

;; for local dev -- include the drivers locally with :dev:drivers
:drivers
Expand Down
1 change: 1 addition & 0 deletions frontend/src/metabase/dev.js
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
import "@pmmmwh/react-refresh-webpack-plugin/client/ReactRefreshEntry.js";
import "cljs/metabase.util.devtools";
13 changes: 13 additions & 0 deletions frontend/test/global-setup.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// A quirk of the way the tests are loaded causes a double-inclusion warning from Closure's goog.isProvided_ check.
// It's actually harmless, just an overzealous dev-mode warning, so we monkey-patch goog.isProvided_ to return false.
module.exports = function () {
const fs = require("fs");
const path = require("path");
const cljs_env = path.join(__dirname, "..", "src", "cljs", "cljs_env.js");
const contents = fs.readFileSync(cljs_env, { encoding: "utf8" });
const replaced = contents.replace(
new RegExp("goog.isProvided_ = function\\(name\\) {\\n.*?\\n\\s*};"),
"goog.isProvided_ = function(name) { return false; };",
);
fs.writeFileSync(cljs_env, replaced);
};
3 changes: 3 additions & 0 deletions jest.unit.conf.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
"<rootDir>/frontend/src",
"<rootDir>/enterprise/frontend/src"
],
"modulePathIgnorePatterns": ["<rootDir>/frontend/src/cljs_release/.*"],
"setupFiles": [
"<rootDir>/frontend/test/jest-setup.js",
"<rootDir>/frontend/test/metabase-bootstrap.js",
Expand All @@ -31,6 +32,7 @@
"@testing-library/jest-dom/extend-expect",
"<rootDir>/frontend/test/jest-setup-env.js"
],
"globalSetup": "<rootDir>/frontend/test/global-setup.js",
"globals": {
"ace": {},
"ga": {},
Expand All @@ -50,6 +52,7 @@
"/node_modules/",
"/frontend/src/metabase/visualizations/lib/errors.js",
"/frontend/src/cljs/",
"/frontend/src/cljs_release/",
"/frontend/src/metabase/internal/",
"/frontend/test/"
],
Expand Down
16 changes: 10 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,7 @@
"raf": "^3.4.0",
"react-refresh": "^0.13.0",
"shadow-cljs": "2.19.6",
"source-map-loader": "^4.0.1",
"style-loader": "3.3.1",
"typescript": "^4.7.2",
"webpack": "5.75.0",
Expand All @@ -277,29 +278,32 @@
"concurrently": "yarn && concurrently --kill-others -p name",
"dev": "yarn concurrently -n 'backend,frontend,cljs,static-viz' -c 'blue,green,yellow,magenta,red' 'clojure -M:run' 'yarn build-hot:js' 'yarn build-hot:cljs' 'yarn build-static-viz:watch'",
"dev-ee": "yarn concurrently -n 'backend,frontend,cljs,static-viz' -c 'blue,green,yellow,magenta,red' 'clojure -M:run:ee' 'MB_EDITION=ee yarn build-hot:js' 'MB_EDITION=ee yarn build-hot:cljs' 'yarn build-static-viz:watch'",
"type-check": "yarn && tsc --noEmit",
"type-check": "rm -rf frontend/src/{cljs,cljs_release} && yarn build-quick:cljs && tsc --noEmit",
"remove-webpack-cache": "rm -rf ./node_modules/.cache",
"lint": "yarn lint-eslint && yarn lint-prettier && yarn lint-docs-links && yarn lint-yaml && yarn type-check",
"lint-eslint": "yarn build-quick:cljs && eslint --ext .js,.jsx,.ts,.tsx --rulesdir frontend/lint/eslint-rules --max-warnings 0 enterprise/frontend/src frontend/src frontend/test",
"lint-prettier": "yarn && prettier -l '{enterprise/,}frontend/**/*.{js,jsx,ts,tsx,css}' || (echo '\nThese files are not formatted correctly. Did you forget to \"yarn prettier\"?' && false)",
"lint-docs-links": "yarn && ./bin/verify-doc-links",
"lint-yaml": "yamllint **/*.{yaml,yml} --ignore=node_modules/**/*.{yaml,yml}",
"test": "yarn test-unit && yarn test-timezones && yarn test-cypress",
"test-debug": "yarn build-quick:cljs && node --inspect-brk node_modules/.bin/jest --runInBand --detectOpenHandles --config jest.unit.conf.json",
"test-unit": "yarn build-quick:cljs && jest --maxWorkers=2 --config jest.unit.conf.json",
"test-unit-keep-cljs": "jest --maxWorkers=2 --config jest.unit.conf.json",
"test-unit-watch": "yarn test-unit --watch",
"test-unit-watch:cljs": "yarn concurrently -n 'cljs,tests' 'yarn build-watch:cljs' 'yarn test-unit-keep-cljs --watch'",
"test-timezones-unit": "yarn build-quick:cljs && jest --silent --maxWorkers=2 --config jest.tz.unit.conf.json",
"test-timezones": "yarn && ./frontend/test/__runner__/run_timezone_tests",
"build:js": "yarn && webpack --bail",
"build-watch:js": "yarn && webpack --watch",
"build-hot:js": "yarn && NODE_OPTIONS=--max-old-space-size=8096 WEBPACK_BUNDLE=hot webpack serve",
"build:cljs": "yarn && rm -rf frontend/src/cljs/* && shadow-cljs release app",
"build-quick:cljs": "yarn build:cljs",
"build:cljs": "yarn && rm -rf frontend/src/cljs_release/* && shadow-cljs release app",
"build-quick:cljs": "yarn && rm -rf frontend/src/cljs/* && shadow-cljs compile app",
"build-watch:cljs": "yarn && shadow-cljs watch app",
"build-hot:cljs": "yarn && shadow-cljs watch app",
"cljs-server-start": "yarn && shadow-cljs start",
"cljs-server-stop": "yarn && shadow-cljs stop",
"cljs-server-restart": "yarn && shadow-cljs restart",
"cljs-nrepl": "yarn && shadow-cljs node-repl -d cider/cider-nrepl:0.28.5 -d cider/piggieback:0.5.3 -d refactor-nrepl:3.6.0",
"cljs-nrepl": "yarn && shadow-cljs node-repl -d cider/cider-nrepl:0.30.0 -d cider/piggieback:0.5.3 -d refactor-nrepl:3.6.0",
"test-cljs": "yarn && shadow-cljs compile test && node target/node-tests.js",
"build": "yarn build:cljs && yarn build:js",
"build-watch": "yarn concurrently -n 'cljs,js' 'yarn build-watch:cljs' 'yarn build-watch:js'",
Expand Down Expand Up @@ -330,8 +334,8 @@
"test-visual": "yarn build && ./bin/build-for-test && yarn test-visual-run",
"prepare": "husky install",
"storybook": "yarn build:cljs && start-storybook -p 6006",
"build-storybook": "yarn build:cljs && build-storybook",
"chromatic": "yarn build:cljs && chromatic",
"build-storybook": "yarn build-quick:cljs && build-storybook",
"chromatic": "yarn build-quick:cljs && chromatic",
"docs-lint-links": "find docs -type f -name '*.md' -print0 | xargs -0 markdown-link-check --quiet --config .mlc_config.json"
},
"lint-staged": {
Expand Down
6 changes: 4 additions & 2 deletions shadow-cljs.edn
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@
:builds
{:app
{:target :npm-module
:output-dir "frontend/src/cljs/"
:output-dir "frontend/src/cljs_release/"
:dev {:output-dir "frontend/src/cljs/"}
:entries [metabase.domain-entities.queries.util
metabase.mbql.js
metabase.types
Expand All @@ -20,7 +21,8 @@
metabase.shared.formatting.time
metabase.shared.util.currency
metabase.shared.util.time
metabase.shared.parameters.parameters]}
metabase.shared.parameters.parameters
metabase.util.devtools]}

:test
{:target :node-test
Expand Down
153 changes: 97 additions & 56 deletions src/metabase/domain_entities/converters.cljs
Original file line number Diff line number Diff line change
@@ -1,73 +1,114 @@
(ns metabase.domain-entities.converters
(:require
[camel-snake-kebab.core :as csk]
[cljs-bean.core :as bean]
))
[malli.core :as mc]
[malli.transform :as mtx]))

(defn- ->entity
"Conversion of incoming vanilla JS objects and arrays to CLJS maps and vectors.
(defn- decode-map [schema _]
(let [drop-nil? (set (for [[map-key props val-schema] (mc/children schema)
:when (and (:optional props)
(not (#{'nil? :nil} (mc/type val-schema))))]
map-key))]
{:enter (fn [x]
(cond
(map? x) x
(object? x) (into {} (for [prop (js/Object.keys x)
:let [js-val (unchecked-get x prop)
map-key (csk/->kebab-case-keyword prop)]
;; If the value is nil, and it's both :optional and not a :maybe,
;; we just discard the value.
:when (not (and (nil? js-val)
(drop-nil? map-key)))]
[map-key js-val]))))
:leave (fn [x]
(if (map? x)
x
(throw (ex-info "decode-map leaving with a JS object not a CLJS map"
{:value x
:schema schema}))))}))

You should not need to call this directly; it's an implementation detail of [[defn]]."
[x]
(bean/->clj x
:prop->key csk/->kebab-case-keyword
:key->prop csk/->camelCaseString))
(defn- decode-map-of [keydec x]
(cond
(map? x) x
(object? x) (into {} (for [prop (js/Object.keys x)]
[(keydec prop) (unchecked-get x prop)]))))

(defn- entity->
"Conversion of cljs-bean wrapped CLJS maps and vectors back into vanilla JS objects and arrays.
(defn- encode-map [x keyenc]
(cond
(object? x) x
(map? x) (reduce-kv (fn [obj k v]
(unchecked-set obj (keyenc k) v)
obj)
#js {}
x)))

You should not need to call this directly; it's an implementation detail of [[defn]]."
[x]
(bean/->js x :key->prop csk/->camelCaseString))
(def js-transformer
"Malli transformer for converting JavaScript data to and from CLJS data.
(defn- opaque? [schema]
(-> schema :properties :bean/opaque boolean))
This is a bit more flexible than a JSON transformer. In particular, it normalizes the keys of `:map`
schema objects to `:kebab-case-keywords`, and restores them to strings with the original spelling when
converting back.
(defmulti incoming
"Note that this works on the map syntax, the Malli AST, not the raw vectors.
It's easier to process that way."
(fn [schema]
(if (opaque? schema)
:bean/opaque
(:type schema))))
**On keyword conversion**
(defmethod incoming :default [_]
identity)
Note that `\"snake_case\"` is the default spelling we expect in the JS data.
This can be overridden with the `{:js/prop \"correctSpelling\"}` property on the schema, eg.
```
[:map
[:camel-case {:js/prop \"camelCase\"} string?]
[:kebab-case {:js/prop \"kebab-case\"} number?]
[:snake-case [:enum \"foo\" \"bar\"]]]
```
(defmethod incoming :bean/opaque [_]
identity)
Observe that `:snake-case` does not need a `:js/prop` setting, since that is the default.
(defmethod incoming :vector [schema]
(let [kf (incoming (:child schema))]
#(mapv kf %)))
**On `:map-of`**
(defmethod incoming :tuple [schema]
(let [inner (map incoming (:children schema))]
(fn [value]
(mapv #(%1 %2) inner value))))
Note that `:map-of` is not `:map`. The spelling of the keys in a `:map-of` is not changed. If the key
schema is `keyword?`, they will be converted to keywords and back, but with the original spelling.
(def ^:private conversion-needed? #{:tuple :vector :map :map-of})
**On sequences**
`:tuple`, `:vector` and `:sequential` all get transformed into CLJS vectors. When converting back to JS,
they are JS arrays."
(mtx/transformer
{:name :js
:decoders {:keyword keyword
'keyword? keyword
:qualified-keyword keyword
:vector {:enter vec}
:sequential {:enter vec}
:tuple {:enter vec}
:map {:compile decode-map}
:map-of {:compile (fn [schema _]
(let [[key-schema] (mc/children schema)
keydec (mc/decoder key-schema js-transformer)]
{:enter #(decode-map-of keydec %)}))}}
:encoders {:keyword name
'keyword? name
:qualified-keyword #(str (namespace %) "/" (name %))
:vector {:leave clj->js}
:sequential {:leave clj->js}
:tuple {:leave clj->js}
:map {:compile
(fn [schema _]
(let [js-props (into {} (for [[k props] (mc/children schema)
:when (:js/prop props)]
[k (:js/prop props)]))
keyenc (fn [k] (or (get js-props k)
(csk/->snake_case_string k)))]
{:leave #(encode-map % keyenc)}))}
:map-of {:leave #(encode-map % name)}}}))

(defmethod incoming :map-of [schema]
(let [vf (incoming (:value schema))
keywordize? (-> schema :key :type (#{:keyword 'keyword?}))
recursive? (-> schema :value :type conversion-needed?)
transform (when (and (not (opaque? (:value schema)))
(not= identity vf))
vf)
opts (cond-> {:recursive (boolean recursive?)
:keywordize-keys (boolean keywordize?)}
keywordize? (assoc :prop->key csk/->kebab-case-keyword
:key->prop csk/->camelCaseString)
transform (assoc :transform transform))]
#(bean/bean % opts)))
(defn incoming
"Returns a function for converting a JS value into CLJS data structures, based on a schema."
[schema]
;; TODO This should be a mc/coercer that decodes and then validates, throwing if it doesn't match.
;; However, enabling that now breaks loads of tests that pass input data with lots of holes. The JS
;; tests (as opposed to TS) are particularly bad for this.
;; Don't forget the nested `mc/decoder` calls elsewhere in this file!
(mc/decoder schema js-transformer))

(defmethod incoming :map [_schema]
->entity)

;; TODO Does this handle cases where we didn't convert string keys to keywords? Does it need to be schema-smart too?
#_{:clj-kondo/ignore [:clojure-lsp/unused-public-var]} ;; This is used by macro-generated code.
(defn outgoing
"Converts back to pure JS form."
[x]
(entity-> x))
"Returns a function for converting a CLJS value back into a plain JS one, based on its schema."
[schema]
(mc/encoder schema js-transformer))
Loading

0 comments on commit 4580eab

Please sign in to comment.