@bigbinary/eslint-plugin-neeto 1.13.0 → 1.13.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +2 -0
  2. package/dist/index.js +289 -1
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -90,6 +90,7 @@ of the issues identified in JavaScript code.
90
90
  - [prefix-neeto-ui-import-alias](./docs/src/rules/prefix-neeto-ui-import-alias.md)
91
91
  - [routes-should-be-declared-and-default-exported](./docs/src/rules/routes-should-be-declared-and-default-exported.md)
92
92
  - [routes-should-match-object-path](./docs/src/rules/routes-should-match-object-path.md)
93
+ - [routes-should-use-kebab-case](./docs/src/rules/routes-should-use-kebab-case.md)
93
94
  - [use-array-methods](./docs/src/rules/use-array-methods.md)
94
95
  - [use-axios-config-for-passing-query-parameters](./docs/src/rules/use-axios-config-for-passing-query-parameters.md)
95
96
  - [use-camel-case-or-pascal-case-for-function-names](./docs/src/rules/use-camel-case-or-pascal-case-for-function-names.md)
@@ -120,6 +121,7 @@ of the issues identified in JavaScript code.
120
121
  - [ensure-peer-dependencies-are-in-sync](./docs/src/rules/ensure-peer-dependencies-are-in-sync.md)
121
122
  - [use-dayjs-from-neeto-commons-fronted](./docs/src/rules/use-dayjs-from-neeto-commons-fronted.md)
122
123
  - [standardize-help-urls](./docs/src/rules/standardize-help-urls.md)
124
+ - [use-yup-1-compatible-when](./docs/src/rules/use-yup-1-compatible-when.md)
123
125
 
124
126
  ### Warnings
125
127
 
package/dist/index.js CHANGED
@@ -130,6 +130,7 @@
130
130
  "@bigbinary/neeto/ramda-tips": "warn",
131
131
  "@bigbinary/neeto/routes-should-be-declared-and-default-exported": "error",
132
132
  "@bigbinary/neeto/routes-should-match-object-path": "error",
133
+ "@bigbinary/neeto/routes-should-use-kebab-case": "error",
133
134
  "@bigbinary/neeto/use-array-methods": "warn",
134
135
  "@bigbinary/neeto/use-axios-config-for-passing-query-parameters": "warn",
135
136
  "@bigbinary/neeto/use-camel-case-or-pascal-case-for-function-names": "error",
@@ -169,6 +170,7 @@
169
170
  "@bigbinary/neeto/jsx-prefer-guard-clause": "warn",
170
171
  "@bigbinary/neeto/ensure-usestate-has-initial-value": "error",
171
172
  "@bigbinary/neeto/use-show-thumbs-up-toastr": "error",
173
+ "@bigbinary/neeto/use-yup-1-compatible-when": "error",
172
174
  "@bigbinary/neeto/ensure-peer-dependencies-are-in-sync": "warn",
173
175
  "@bigbinary/neeto/standardize-help-urls": "error"
174
176
  };
@@ -284,7 +286,7 @@
284
286
  }
285
287
  });
286
288
 
287
- var version = "1.12.3";
289
+ var version = "1.13.1";
288
290
  var packageJson = {
289
291
  version: version};
290
292
 
@@ -463,6 +465,7 @@
463
465
  const PREFIX_NEETO_UI_IMPORT_ALIAS_MESSAGE = "Aliases for anything imported from neetoUI or neetoIcons should start with `NeetoUI`";
464
466
  const REPLACE_WITH_HANDLE_META_CLICK = "Replace with handleMetaClick function";
465
467
  const ROUTE_SHOULD_BE_A_STRING = "Route should be a plain string literal.";
468
+ const routeShouldUseKebabCase = segments => `Use kebab-case in route paths: ${segments.map(([segment, kebab]) => `\`${segment}\` should be \`${kebab}\``).join(", ")}.`;
466
469
  const ROUTE_SHOULD_MATCH_OBJECT_PATH = "Route string should match with its object path.";
467
470
  const ROUTES_HAS_ALREADY_BEEN_DECLARED = "Identifier `routes` has already been declared";
468
471
  const ROUTES_CONSTANT_SHOULD_BE_DECLARED = "A constant object named `routes` should be declared inside routes.js";
@@ -547,6 +550,9 @@
547
550
  const INVALID_SWITCH_CHILD_MESSAGE = "Switch component can only contain Route, Redirect, or PrivateRoute as direct children";
548
551
  const PREFER_RADIO_BUTTONS_FOR_FEW_OPTIONS = "Consider using Radio buttons instead of Dropdown/Select when there are fewer than 4 options.";
549
552
  const NO_EDITS_TO_GENERATED_TRANSLATION_FILES = "This translation file is auto-generated. Only edit 'en.json'; translations for all other locales are generated from it automatically. Please revert your changes in this file.";
553
+ const YUP_WHEN_BRANCH_SHOULD_BE_FUNCTION = "yup 1 needs `then` and `otherwise` to be functions of the base schema. Use `schema => schema.concat(...)`, which is what yup 0.32 did with a schema branch.";
554
+ const YUP_WHEN_BUILDER_SHOULD_DESTRUCTURE_VALUES = "yup 1 passes a .when() builder the dependency values as one array, so a builder that reads them spread gets that array and its conditions silently stop matching. Destructure them: `([a, b], schema) =>`.";
555
+ const YUP_WHEN_VALUES_IS_NOT_NEEDED = "`whenValues` was a bridge for yup 0.32, and every product is on yup 1 now. Pass the builder to `.when()` directly and destructure its values: `([a, b], schema) =>`.";
550
556
 
551
557
  const PACKAGES_TO_CHECK = ["@bigbinary/neeto-molecules", "@bigbinary/neetoui", "@bigbinary/neeto-commons-frontend"];
552
558
 
@@ -970,6 +976,9 @@
970
976
 
971
977
  const SPECIAL_KEYS = ["home", "index", "show"];
972
978
 
979
+ // Devise owns these route segments, so apps can't rename them.
980
+ const DEVISE_SEGMENTS = ["sign_in", "sign_out", "sign_up"];
981
+
973
982
  // import routes from "routes", import routes from "src/routes"
974
983
  const ROUTES_IMPORT_PATTERN = {
975
984
  type: TYPES.IMPORT_DECLARATION,
@@ -1231,6 +1240,42 @@
1231
1240
  })
1232
1241
  };
1233
1242
 
1243
+ const toKebabCase = segment => segment.replace(/([a-z\d])([A-Z])/g, "$1-$2").replace(/_/g, "-").toLowerCase();
1244
+ const isNotKebabCase = segment => /[_A-Z]/.test(segment);
1245
+
1246
+ // Params like ":ticketId" and patterns like "*" never appear in the URL.
1247
+ const isPathSegment = segment => !/^[:*(]/.test(segment) && !DEVISE_SEGMENTS.includes(segment);
1248
+ const checkRoutes = (context, node) => {
1249
+ if (node?.type === TYPES.OBJECT_EXPRESSION) {
1250
+ node.properties.forEach(property => checkRoutes(context, property.value));
1251
+ return;
1252
+ }
1253
+ if (node?.type !== TYPES.LITERAL || typeof node.value !== "string") return;
1254
+ const badSegments = node.value.split("/").map(segment => segment.split("?")[0]).filter(isPathSegment).filter(isNotKebabCase);
1255
+ if (ramda.isEmpty(badSegments)) return;
1256
+ context.report({
1257
+ node,
1258
+ message: routeShouldUseKebabCase(badSegments.map(segment => [segment, toKebabCase(segment)]))
1259
+ });
1260
+ };
1261
+ var routesShouldUseKebabCase = {
1262
+ meta: {
1263
+ type: "problem",
1264
+ docs: {
1265
+ url: "https://github.com/neetozone/eslint-plugin-neeto/blob/main/docs/src/rules/routes-should-use-kebab-case.md",
1266
+ description: "Route paths in the routes object should use kebab-case."
1267
+ }
1268
+ },
1269
+ create: context => ({
1270
+ VariableDeclaration(node) {
1271
+ if (!context.getFilename().endsWith(ROUTES_FILE_PATH)) return;
1272
+ if (neetoCist.matches(DECALARATION_PATTERN$1, node)) {
1273
+ checkRoutes(context, node.declarations[0].init);
1274
+ }
1275
+ }
1276
+ })
1277
+ };
1278
+
1234
1279
  const getCode = (context, start, length) => context.getSourceCode().text.substr(start, length);
1235
1280
  const replacer$2 = nodeReplacerWithImports(ramda.assocPath(["source", "value"], "neetocommons/utils", IMPORT_DECLARATION));
1236
1281
  var useCommonRoutes = {
@@ -11762,6 +11807,247 @@
11762
11807
  }
11763
11808
  };
11764
11809
 
11810
+ const FUNCTION_TYPES = [TYPES.ARROW_FUNCTION_EXPRESSION, TYPES.FUNCTION_EXPRESSION];
11811
+ const BRANCH_KEYS = ["then", "otherwise"];
11812
+ const SCHEMA_PARAM_NAMES = ["schema", "baseSchema", "currentSchema"];
11813
+ const SUSPENDING_KEYWORDS = ["await", "yield"];
11814
+ const WHEN_VALUES = "whenValues";
11815
+
11816
+ const isFunction = node => FUNCTION_TYPES.includes(node?.type);
11817
+ const keyName = property => property.key?.name ?? property.key?.value;
11818
+
11819
+ // `utils/yup` is where products and nanos keep their yup setup; some re-export
11820
+ // yup from it.
11821
+ const isYupSource = source => source === "yup" || source.startsWith("yup/") || source === "utils/yup";
11822
+ const isWhenCall = node => node?.type === TYPES.CALL_EXPRESSION && node.callee.type === TYPES.MEMBER_EXPRESSION && !node.callee.computed && node.callee.property.name === "when";
11823
+ const findVariable = (scope, name) => {
11824
+ for (let current = scope; current; current = current.upper) {
11825
+ const variable = current.set.get(name);
11826
+ if (variable) return variable;
11827
+ }
11828
+ return null;
11829
+ };
11830
+
11831
+ // The identifier at the start of a chain such as `yup.string().trim()`.
11832
+ const chainRoot = node => {
11833
+ let current = node;
11834
+ while (current) {
11835
+ if (current.type === TYPES.CALL_EXPRESSION) current = current.callee;else if (current.type === TYPES.MEMBER_EXPRESSION) current = current.object;else if (current.type === "AwaitExpression") current = current.argument;else return current;
11836
+ }
11837
+ return null;
11838
+ };
11839
+
11840
+ // Whether `fn` is a `.when()` builder or branch, so its parameter is a schema.
11841
+ const isWhenFunction = fn => {
11842
+ const {
11843
+ parent
11844
+ } = fn;
11845
+ if (isWhenCall(parent)) return parent.arguments.includes(fn);
11846
+ if (parent?.type === TYPES.CALL_EXPRESSION && parent.callee.type === TYPES.IDENTIFIER && parent.callee.name === WHEN_VALUES) {
11847
+ return isWhenCall(parent.parent);
11848
+ }
11849
+ return parent?.type === TYPES.PROPERTY && BRANCH_KEYS.includes(keyName(parent)) && isWhenCall(parent.parent?.parent);
11850
+ };
11851
+
11852
+ // Whether `node` evaluates to a yup schema: a chain on a yup import, a variable
11853
+ // initialised with one, or the schema parameter of a .when() builder or branch.
11854
+ const createYupSchemaCheck = sourceCode => {
11855
+ const visiting = new Set();
11856
+ const isYupSchema = node => {
11857
+ const root = chainRoot(node);
11858
+ if (root?.type !== TYPES.IDENTIFIER) return false;
11859
+ const variable = findVariable(sourceCode.getScope(root), root.name);
11860
+ const [definition] = variable?.defs ?? [];
11861
+ if (!definition || visiting.has(definition.name)) return false;
11862
+ if (definition.type === "ImportBinding") {
11863
+ return isYupSource(definition.parent.source.value);
11864
+ }
11865
+ if (definition.type === "Parameter") {
11866
+ return isFunction(definition.node) && isWhenFunction(definition.node);
11867
+ }
11868
+ if (definition.type !== "Variable" || !definition.node.init) return false;
11869
+ visiting.add(definition.name);
11870
+ const result = isYupSchema(definition.node.init);
11871
+ visiting.delete(definition.name);
11872
+ return result;
11873
+ };
11874
+ return isYupSchema;
11875
+ };
11876
+
11877
+ // A parameter name the moved expression does not already use.
11878
+ const freeParamName = (sourceCode, node) => {
11879
+ const text = sourceCode.getText(node);
11880
+ return SCHEMA_PARAM_NAMES.find(name => !new RegExp(`\\b${name}\\b`).test(text));
11881
+ };
11882
+
11883
+ // Moving `await` or `yield` into a plain arrow function would not parse.
11884
+ const suspends = (sourceCode, node) => sourceCode.getTokens(node).some(({
11885
+ type,
11886
+ value
11887
+ }) => ["Keyword", "Identifier"].includes(type) ? SUSPENDING_KEYWORDS.includes(value) : false);
11888
+ const buildFix = (sourceCode, property, value) => {
11889
+ if (suspends(sourceCode, value)) return null;
11890
+ const param = freeParamName(sourceCode, value);
11891
+ if (!param) return null;
11892
+ const branch = `${param} => ${param}.concat(${sourceCode.getText(value)})`;
11893
+
11894
+ // Replace only the value, so the key and any comments around it are kept.
11895
+ return fixer => property.shorthand ? fixer.replaceText(property, `${keyName(property)}: ${branch}`) : fixer.replaceText(value, branch);
11896
+ };
11897
+ const checkBranches = (context, isYupSchema, config) => {
11898
+ const {
11899
+ sourceCode
11900
+ } = context;
11901
+ const properties = config.properties.filter(property => property.type === TYPES.PROPERTY && !property.computed);
11902
+ if (!properties.some(property => keyName(property) === "is")) return;
11903
+ properties.filter(property => BRANCH_KEYS.includes(keyName(property))).forEach(property => {
11904
+ const {
11905
+ value
11906
+ } = property;
11907
+ // Only a value known to be a yup schema is a mistake. A function
11908
+ // reference such as `identity` or `branches.required` is already valid.
11909
+ if (isFunction(value) || !isYupSchema(value)) return;
11910
+ context.report({
11911
+ node: value,
11912
+ message: YUP_WHEN_BRANCH_SHOULD_BE_FUNCTION,
11913
+ fix: buildFix(sourceCode, property, value)
11914
+ });
11915
+ });
11916
+ };
11917
+ const isWhenValuesCall = node => node?.type === TYPES.CALL_EXPRESSION && node.callee.type === TYPES.IDENTIFIER && node.callee.name === WHEN_VALUES;
11918
+
11919
+ // How many dependency values `.when(keys, …)` passes, or null if unknown.
11920
+ const keyCount = keys => {
11921
+ if (keys?.type === "ArrayExpression") {
11922
+ return keys.elements.every(element => element?.type !== "SpreadElement") ? keys.elements.length : null;
11923
+ }
11924
+ return keys?.type === TYPES.LITERAL && typeof keys.value === "string" ? 1 : null;
11925
+ };
11926
+
11927
+ // `(a, b, schema) => …` as `([a, b], schema) => …`, the yup 1 builder form.
11928
+ const destructuredParamsText = (sourceCode, builder, count) => {
11929
+ const {
11930
+ params
11931
+ } = builder;
11932
+ if (count === null || params.length === 0) return null;
11933
+ const valueParams = params.slice(0, count);
11934
+ if (valueParams.some(param => param.type === "RestElement")) return null;
11935
+ const texts = params.map(param => sourceCode.getText(param));
11936
+ const rest = texts.slice(count);
11937
+ return [`[${texts.slice(0, count).join(", ")}]`, ...rest].join(", ");
11938
+ };
11939
+
11940
+ // The builder's source with its parameters destructured.
11941
+ const destructuredBuilderText = (sourceCode, builder, count) => {
11942
+ const paramsText = destructuredParamsText(sourceCode, builder, count);
11943
+ if (paramsText === null) return null;
11944
+ const {
11945
+ params
11946
+ } = builder;
11947
+ const text = sourceCode.getText(builder);
11948
+ const start = params[0].range[0] - builder.range[0];
11949
+ const end = params.at(-1).range[1] - builder.range[0];
11950
+ const isParenthesized = sourceCode.getTokenBefore(params[0]).value === "(" && sourceCode.getTokenBefore(params[0]).range[0] >= builder.range[0];
11951
+ const head = isParenthesized ? paramsText : `(${paramsText})`;
11952
+ return text.slice(0, start) + head + text.slice(end);
11953
+ };
11954
+
11955
+ // `[a, b]` or `[a, b] = []`: the builder already destructures yup 1's values.
11956
+ const isArrayPattern = param => param.type === "ArrayPattern" || param.type === "AssignmentPattern" && param.left.type === "ArrayPattern";
11957
+
11958
+ // Whether a builder's first parameter is used as the values array:
11959
+ // `values[0]`, `values.length`, `...values` or `const [a] = values`. Property
11960
+ // reads such as `field.value` are not counted, since a dependency value is often
11961
+ // an object, and reading it spread is exactly the mistake this rule reports.
11962
+ const readsAsValuesArray = (sourceCode, builder, param) => {
11963
+ if (param.type !== TYPES.IDENTIFIER) return false;
11964
+ const variable = sourceCode.getDeclaredVariables(builder).find(({
11965
+ name
11966
+ }) => name === param.name);
11967
+ return Boolean(variable?.references.some(({
11968
+ identifier
11969
+ }) => {
11970
+ const {
11971
+ parent
11972
+ } = identifier;
11973
+ if (parent.type === TYPES.MEMBER_EXPRESSION && parent.object === identifier) {
11974
+ return parent.computed ? parent.property.type === TYPES.LITERAL && typeof parent.property.value === "number" : parent.property.name === "length";
11975
+ }
11976
+ if (parent.type === "SpreadElement") return true;
11977
+ return parent.type === "VariableDeclarator" && parent.init === identifier && parent.id.type === "ArrayPattern";
11978
+ }));
11979
+ };
11980
+ const checkBuilder = (context, whenCall, builder) => {
11981
+ const [firstParam] = builder.params;
11982
+ if (!firstParam || isArrayPattern(firstParam)) return;
11983
+ const {
11984
+ sourceCode
11985
+ } = context;
11986
+ if (readsAsValuesArray(sourceCode, builder, firstParam)) return;
11987
+ const text = destructuredBuilderText(sourceCode, builder, keyCount(whenCall.arguments[0]));
11988
+ context.report({
11989
+ node: builder,
11990
+ message: YUP_WHEN_BUILDER_SHOULD_DESTRUCTURE_VALUES,
11991
+ fix: text === null ? null : fixer => fixer.replaceText(builder, text)
11992
+ });
11993
+ };
11994
+ const checkWhenValues = (context, whenCall, wrapper) => {
11995
+ const {
11996
+ sourceCode
11997
+ } = context;
11998
+ const [builder] = wrapper.arguments;
11999
+ let text = null;
12000
+
12001
+ // `whenValues` spreads the values, so every value parameter, even an array
12002
+ // pattern such as `[firstTag]`, moves inside the new outer array.
12003
+ if (wrapper.arguments.length === 1 && isFunction(builder)) {
12004
+ text = destructuredBuilderText(sourceCode, builder, keyCount(whenCall.arguments[0]));
12005
+ }
12006
+ context.report({
12007
+ node: wrapper,
12008
+ message: YUP_WHEN_VALUES_IS_NOT_NEEDED,
12009
+ fix: text === null ? null : fixer => fixer.replaceText(wrapper, text)
12010
+ });
12011
+ };
12012
+ var useYup1CompatibleWhen = {
12013
+ meta: {
12014
+ type: "problem",
12015
+ fixable: "code",
12016
+ docs: {
12017
+ url: "https://github.com/neetozone/eslint-plugin-neeto/blob/main/docs/src/rules/use-yup-1-compatible-when.md",
12018
+ description: "yup .when() conditions should use function branches and builders that destructure their values, as yup 1 needs."
12019
+ }
12020
+ },
12021
+ create: context => {
12022
+ let importsYup = false;
12023
+ const isYupSchema = createYupSchemaCheck(context.sourceCode);
12024
+ return {
12025
+ ImportDeclaration(node) {
12026
+ if (isYupSource(node.source.value)) importsYup = true;
12027
+ },
12028
+ CallExpression(node) {
12029
+ if (!importsYup || !isWhenCall(node)) return;
12030
+ const [, config] = node.arguments;
12031
+ if (!config) return;
12032
+
12033
+ // `whenValues` only ever wraps a yup builder, so its receiver need not
12034
+ // be traced, which matters for schemas from helpers such as
12035
+ // `buildNullableSchema()`.
12036
+ if (isWhenValuesCall(config)) {
12037
+ checkWhenValues(context, node, config);
12038
+ return;
12039
+ }
12040
+ if (!isYupSchema(node.callee.object)) return;
12041
+ if (config.type === TYPES.OBJECT_EXPRESSION) {
12042
+ checkBranches(context, isYupSchema, config);
12043
+ } else if (isFunction(config)) {
12044
+ checkBuilder(context, node, config);
12045
+ }
12046
+ }
12047
+ };
12048
+ }
12049
+ };
12050
+
11765
12051
  // pick()
11766
12052
  // eslint-disable-next-line import/exports-last
11767
12053
  const PICK_PATTERN_SHORT = {
@@ -12268,6 +12554,7 @@
12268
12554
  "ramda-tips": ramdaTips,
12269
12555
  "routes-should-be-declared-and-default-exported": routesShouldBeDeclaredAndDefaultExported,
12270
12556
  "routes-should-match-object-path": routesShouldMatchObjectPath,
12557
+ "routes-should-use-kebab-case": routesShouldUseKebabCase,
12271
12558
  "use-array-methods": useArrayMethods,
12272
12559
  "use-axios-config-for-passing-query-parameters": useAxiosConfigForPassingQueryParameters,
12273
12560
  "no-buildurl-call-with-empty-params": noBuildurlCallWithEmptyParams,
@@ -12308,6 +12595,7 @@
12308
12595
  "jsx-prefer-guard-clause": jsxPreferGuardClause,
12309
12596
  "ensure-usestate-has-initial-value": ensureUseStateHasInitialValue,
12310
12597
  "use-show-thumbs-up-toastr": useShowThumbsUpToastr,
12598
+ "use-yup-1-compatible-when": useYup1CompatibleWhen,
12311
12599
  "standardize-help-urls": standardizeHelpUrls
12312
12600
  },
12313
12601
  configs: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bigbinary/eslint-plugin-neeto",
3
- "version": "1.13.0",
3
+ "version": "1.13.2",
4
4
  "main": "dist/index.js",
5
5
  "license": "UNLICENSED",
6
6
  "scripts": {