Skip to content

Commit

Permalink
chore(lint): add certain unicorn eslint rules (#6352)
Browse files Browse the repository at this point in the history
* chore(lint): add certain unicorn eslint rules

* chore: fix lint errors
  • Loading branch information
rexxars committed Apr 26, 2024
1 parent fa9d145 commit ba83971
Show file tree
Hide file tree
Showing 53 changed files with 172 additions and 67 deletions.
5 changes: 5 additions & 0 deletions .eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ const config = {
'prettier',
'react',
'tsdoc',
'unicorn',
],
ignorePatterns: [
'**/etc/*',
Expand Down Expand Up @@ -112,6 +113,10 @@ const config = {
'no-unused-vars': 'off',
'no-useless-catch': 'warn',
'no-async-promise-executor': 'warn',
'unicorn/prefer-string-slice': 'error',
'unicorn/prefer-node-protocol': 'error',
'unicorn/prefer-keyboard-event-key': 'error',
'unicorn/custom-error-definition': 'error',
},
settings: {
'import/extensions': extensions,
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-simple-import-sort": "^12.0.0",
"eslint-plugin-tsdoc": "^0.2.17",
"eslint-plugin-unicorn": "^52.0.0",
"eslint-plugin-unused-imports": "^3.1.0",
"execa": "^2.0.0",
"glob": "^7.2.0",
Expand Down
8 changes: 4 additions & 4 deletions packages/@sanity/block-tools/src/HtmlDeserializer/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -161,18 +161,18 @@ export function trimWhitespace(blocks: TypedObject[]): TypedObject[] {
child.text = child.text.replace(/[^\S\n]+$/g, '')
}
if (
/\s/.test(child.text.substring(child.text.length - 1)) &&
/\s/.test(child.text.slice(Math.max(0, child.text.length - 1))) &&
nextChild &&
isMinimalSpan(nextChild) &&
/\s/.test(nextChild.text.substring(0, 1))
/\s/.test(nextChild.text.slice(0, 1))
) {
child.text = child.text.replace(/[^\S\n]+$/g, '')
}
if (
/\s/.test(child.text.substring(0, 1)) &&
/\s/.test(child.text.slice(0, 1)) &&
prevChild &&
isMinimalSpan(prevChild) &&
/\s/.test(prevChild.text.substring(prevChild.text.length - 1))
/\s/.test(prevChild.text.slice(Math.max(0, prevChild.text.length - 1)))
) {
child.text = child.text.replace(/^[^\S\n]+/g, '')
}
Expand Down
2 changes: 1 addition & 1 deletion packages/@sanity/block-tools/src/util/randomKey.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ function whatwgRNG(length = 16) {

const byteToHex: string[] = []
for (let i = 0; i < 256; ++i) {
byteToHex[i] = (i + 0x100).toString(16).substring(1)
byteToHex[i] = (i + 0x100).toString(16).slice(1)
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import * as fs from 'node:fs'
import * as path from 'node:path'
import assert from 'node:assert'
import fs from 'node:fs'
import path from 'node:path'

import {describe, it} from '@jest/globals'
import * as assert from 'assert'
import {JSDOM} from 'jsdom'

import * as blockTools from '../../../src'
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import assert from 'node:assert'

import {describe, it} from '@jest/globals'
import * as assert from 'assert'

import {normalizeBlock} from '../../../src/util/normalizeBlock'

Expand Down
2 changes: 1 addition & 1 deletion packages/@sanity/cli/codemods/partsTypeDirective.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const path = require('path')
const path = require('node:path')

partsTypeDirective.parser = 'tsx'
module.exports = partsTypeDirective
Expand Down
2 changes: 1 addition & 1 deletion packages/@sanity/cli/codemods/reactIconsV3.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ function replace(input, re, value) {

function pascalCaseTransform(input) {
const firstChar = input.charAt(0)
const lowerChars = input.substr(1).toLowerCase()
const lowerChars = input.slice(1).toLowerCase()
return `${firstChar.toUpperCase()}${lowerChars}`
}

Expand Down
1 change: 1 addition & 0 deletions packages/@sanity/cli/test/shared/environment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,7 @@ class ExecError extends Error {
stderr: string
constructor(message: string, code: number, stdout: string, stderr: string) {
super(message)
this.name = 'ExecError'
this.code = code
this.stdout = stdout
this.stderr = stderr
Expand Down
1 change: 1 addition & 0 deletions packages/@sanity/migrate/src/fetch-utils/fetchStream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export class HTTPError extends Error {

constructor(statusCode: number, message: string) {
super(message)
this.name = 'HTTPError'
this.statusCode = statusCode
}
}
Expand Down
4 changes: 2 additions & 2 deletions packages/@sanity/migrate/src/it-utils/split.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@ export async function* split(
buf += chunk
if (buf.includes(delimiter)) {
const lastIndex = buf.lastIndexOf(delimiter)
const parts = buf.substring(0, lastIndex).split(delimiter)
const parts = buf.slice(0, Math.max(0, lastIndex)).split(delimiter)

for (const part of parts) {
yield part
}
buf = buf.substring(lastIndex + delimiter.length)
buf = buf.slice(Math.max(0, lastIndex + delimiter.length))
}
}
yield buf
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ export default class CollaborationEnvironment extends NodeEnvironment {
}

// This will identify this test throughout the web environment
const testId = (Math.random() + 1).toString(36).substring(7)
const testId = (Math.random() + 1).toString(36).slice(7)

// Hook up page console and npm debug in the PTE
if (DEBUG) {
Expand All @@ -101,11 +101,11 @@ export default class CollaborationEnvironment extends NodeEnvironment {
}, DEBUG)
this._pageA.on('console', (message) =>
// eslint-disable-next-line no-console
console.log(`A:${message.type().substring(0, 3).toUpperCase()} ${message.text()}`),
console.log(`A:${message.type().slice(0, 3).toUpperCase()} ${message.text()}`),
)
this._pageB.on('console', (message) =>
// eslint-disable-next-line no-console
console.log(`B:${message.type().substring(0, 3).toUpperCase()} ${message.text()}`),
console.log(`B:${message.type().slice(0, 3).toUpperCase()} ${message.text()}`),
)
}
this._pageA.on('pageerror', (err) => {
Expand All @@ -120,7 +120,7 @@ export default class CollaborationEnvironment extends NodeEnvironment {
this.global.setDocumentValue = async (
value: PortableTextBlock[] | undefined,
): Promise<void> => {
const revId = (Math.random() + 1).toString(36).substring(7)
const revId = (Math.random() + 1).toString(36).slice(7)
ipc.of.socketServer.emit('payload', JSON.stringify({type: 'value', value, testId, revId}))
await this._pageA?.waitForSelector(`code[data-rev-id="${revId}"]`, {
timeout: REVISION_TIMEOUT_MS,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export function App() {
const {editorId, testId} = useMemo(() => {
const params = new URLSearchParams(document.location.search)
return {
editorId: params.get('editorId') || (Math.random() + 1).toString(36).substring(7),
editorId: params.get('editorId') || (Math.random() + 1).toString(36).slice(7),
testId: params.get('testId') || 'noTestIdGiven',
}
}, [])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ export const Editor = ({
const [selectionValue, setSelectionValue] = useState<EditorSelection | null>(selection)
const selectionString = useMemo(() => JSON.stringify(selectionValue), [selectionValue])
const editor = useRef<PortableTextEditor>(null)
const keyGenFn = useMemo(() => createKeyGenerator(editorId.substring(0, 1)), [editorId])
const keyGenFn = useMemo(() => createKeyGenerator(editorId.slice(0, 1)), [editorId])
const [isOffline, setIsOffline] = useState(!window.navigator.onLine)
const [readOnly, setReadOnly] = useState(false)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ app.ws('/', (s, req) => {
}
if (mutatedValue !== null) {
// Assign revId and store value
const revId = (Math.random() + 1).toString(36).substring(7)
const revId = (Math.random() + 1).toString(36).slice(7)
valueMap[testId] = mutatedValue
revisionMap[testId] = revId
// Broadcast to all
Expand Down
2 changes: 1 addition & 1 deletion packages/@sanity/schema/example/test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import assert from 'assert'
import assert from 'node:assert'

import {Schema} from '../src/legacy/Schema'
import schemaDef from './schema-def'
Expand Down
2 changes: 1 addition & 1 deletion packages/@sanity/util/src/content/randomKey.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const getByteHexTable = (() => {

table = []
for (let i = 0; i < 256; ++i) {
table[i] = (i + 0x100).toString(16).substring(1)
table[i] = (i + 0x100).toString(16).slice(1)
}
return table
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export class SchemaError extends Error {

constructor(problemGroups: SchemaValidationProblemGroup[]) {
super('Schema errors encountered')
this.name = 'SchemaError'
this.problemGroups = problemGroups
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -724,6 +724,7 @@ class HelpfulError extends Error {

constructor(message: string, helpUrl?: string) {
super(message)
this.name = 'HelpfulError'
this.helpUrl = helpUrl
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ function formatPath(pathSegments: SchemaValidationProblemPath) {
return `${mode === 'array' ? `[${name}]` : `.${name}`}${format(next)}`
}

return format(pathSegments.slice(1)).substring(1) // removes the top-level type and leading `.`
return format(pathSegments.slice(1)).slice(1) // removes the top-level type and leading `.`
}

export function getAggregatedSeverity(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export const levelValues = {error: 0, warning: 1, info: 2} as const
*/
export const count = (amount: number, subject: string): string =>
`${amount.toLocaleString('en-US')} ${
amount === 1 ? subject.substring(0, subject.length - 1) : subject
amount === 1 ? subject.slice(0, Math.max(0, subject.length - 1)) : subject
}`

const percentageFormatter = new Intl.NumberFormat('en-US', {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export const createAliasHandler: CliCommandAction = async (args, context) => {
let aliasOutputName = aliasName

if (aliasName.startsWith(ALIAS_PREFIX)) {
aliasName = aliasName.substring(1)
aliasName = aliasName.slice(1)
} else {
aliasOutputName = `${ALIAS_PREFIX}${aliasName}`
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export const deleteAliasHandler: CliCommandAction<DeleteAliasFlags> = async (arg
if (dsError) {
throw dsError
}
aliasName = aliasName.startsWith(ALIAS_PREFIX) ? aliasName.substring(1) : aliasName
aliasName = aliasName.startsWith(ALIAS_PREFIX) ? aliasName.slice(1) : aliasName

const [fetchedAliases] = await Promise.all([aliasClient.listAliases(client)])
const linkedAlias = fetchedAliases.find((elem) => elem.name === aliasName)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export const linkAliasHandler: CliCommandAction = async (args, context) => {
let aliasOutputName = aliasName

if (aliasName.startsWith(ALIAS_PREFIX)) {
aliasName = aliasName.substring(1)
aliasName = aliasName.slice(1)
} else {
aliasOutputName = `${ALIAS_PREFIX}${aliasName}`
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export const unlinkAliasHandler: CliCommandAction<UnlinkFlags> = async (args, co
let aliasOutputName = aliasName

if (aliasName.startsWith(ALIAS_PREFIX)) {
aliasName = aliasName.substring(1)
aliasName = aliasName.slice(1)
} else {
aliasOutputName = `${ALIAS_PREFIX}${aliasName}`
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ describe('validateDocuments', () => {
.filter((key) => key.startsWith('$'))
.reduce<Record<string, string | string[]>>((acc, key) => {
const values = searchParams.getAll(key)
acc[key.substring(1)] = values.length === 1 ? values[0] : values
acc[key.slice(1)] = values.length === 1 ? values[0] : values
return acc
}, {})

Expand Down
5 changes: 5 additions & 0 deletions packages/sanity/src/_internal/cli/util/getUrlHeaders.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@ import {promise} from 'get-it/middleware'
const request = getIt([promise()])

export class HttpError extends Error {
constructor(message: string) {
super(message)
this.name = 'HttpError'
}

statusCode?: number
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,10 +97,11 @@ export function CommentInputProvider(props: CommentInputProviderProps) {
const isDeleteText = event.inputType === 'deleteContentBackward'
const isInsertingAtChar = isInsertText && event.data === '@'

const lastIndexOfAt = focusSpan?.text.substring(0, cursorOffset).lastIndexOf('@') || 0
const lastIndexOfAt =
focusSpan?.text.slice(0, Math.max(0, cursorOffset)).lastIndexOf('@') || 0

const isWhitespaceCharBeforeCursorPosition =
focusSpan?.text.substring(cursorOffset - 1, cursorOffset) === ' '
focusSpan?.text.slice(cursorOffset - 1, cursorOffset) === ' '

const filterStartsWithSpaceChar = isInsertText && event.data === ' ' && !mentionsSearchTerm

Expand All @@ -126,14 +127,14 @@ export function CommentInputProvider(props: CommentInputProviderProps) {
// Update the search term
if (isPortableTextSpan(focusChild)) {
// Term starts with the @ char in the value until the cursor offset
let term = focusChild.text.substring(lastIndexOfAt + 1, cursorOffset)
let term = focusChild.text.slice(lastIndexOfAt + 1, cursorOffset)
// Add the char to the mentions search term
if (isInsertText) {
term += event.data
}
// Exclude the char from the mentions search term
if (isDeleteText) {
term = term.substring(0, term.length - 1)
term = term.slice(0, Math.max(0, term.length - 1))
}
// Set the updated mentions search term
setMentionsSearchTerm(term)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,11 +90,11 @@ export function buildRangeDecorationSelectionsFromComments(
.replaceAll(COMMENT_INDICATORS[0], '')
.indexOf(COMMENT_INDICATORS[1])
const textWithoutCommentTags = diffedText.replaceAll(COMMENT_INDICATORS_REGEX, '')
const oldCommentedText = selectionMember.text.substring(
const oldCommentedText = selectionMember.text.slice(
selectionMember.text.indexOf(COMMENT_INDICATORS[0]) + 1,
selectionMember.text.indexOf(COMMENT_INDICATORS[1]),
)
const newCommentedText = textWithoutCommentTags.substring(startIndex, endIndex)
const newCommentedText = textWithoutCommentTags.slice(startIndex, endIndex)
const {levenshtein} = diffText(newCommentedText, oldCommentedText)
const threshold = Math.round(newCommentedText.length + oldCommentedText.length / 2)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ export function buildTextSelectionFromFragment(
if (child._key === fragmentStartSpan?._key) {
originalTextBeforeSelection +=
(isPortableTextSpan(child) &&
child.text.substring(0, normalizedSelection.anchor.offset)) ||
child.text.slice(0, Math.max(0, normalizedSelection.anchor.offset))) ||
''
break
}
Expand All @@ -68,7 +68,7 @@ export function buildTextSelectionFromFragment(
if (child._key === fragmentEndSpan?._key) {
originalTextAfterSelection =
((isPortableTextSpan(child) &&
child.text.substring(normalizedSelection.focus.offset, child.text.length)) ||
child.text.slice(normalizedSelection.focus.offset, child.text.length)) ||
'') + originalTextAfterSelection
break
}
Expand Down
1 change: 1 addition & 0 deletions packages/sanity/src/core/config/ConfigPropertyError.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export class ConfigPropertyError extends Error {
`An error occurred while resolving \`${propertyName}\` from ${path.join(' > ')}${message}`,
)

this.name = 'ConfigPropertyError'
this.propertyName = propertyName
this.cause = cause
this.path = path
Expand Down
1 change: 1 addition & 0 deletions packages/sanity/src/core/config/ConfigResolutionError.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ export class ConfigResolutionError extends Error {
.join('\n')}\n\n`,
)

// eslint-disable-next-line unicorn/custom-error-definition
this.name = name
this.causes = causes
this.type = type
Expand Down
1 change: 1 addition & 0 deletions packages/sanity/src/core/config/SchemaError.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,6 @@ import {type Schema} from '@sanity/types'
export class SchemaError extends Error {
constructor(public schema: Schema) {
super('SchemaError')
this.name = 'SchemaError'
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -345,11 +345,11 @@ function renderDecorators({
.filter((text) => !!text)
.join('')
const ptDiffMatchString = ptDiffChildren
const controlString = ptDiffMatchString.substring(
const controlString = ptDiffMatchString.slice(
0,
ptDiffMatchString.indexOf(seg.text) + seg.text.length,
Math.max(0, ptDiffMatchString.indexOf(seg.text) + seg.text.length),
)
const toTest = controlString.substring(0, controlString.indexOf(seg.text))
const toTest = controlString.slice(0, Math.max(0, controlString.indexOf(seg.text)))
const marks: string[] = []
const matches = [...toTest.matchAll(markRegex)]
matches.forEach((match) => {
Expand Down
Loading

0 comments on commit ba83971

Please sign in to comment.