Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

utils.ts

761 lines21.7 KB

1import { isServer } from '@tanstack/router-core/isServer'
2import type { RouteIds } from './routeInfo'
3import type { AnyRouter } from './router'
4​
5export type Awaitable<T> = T | Promise<T>
6export type NoInfer<T> = [T][T extends any ? 0 : never]
7export type IsAny<TValue, TYesResult, TNoResult = TValue> = 1 extends 0 & TValue
8 ? TYesResult
9 : TNoResult
10​
11export type PickAsRequired<TValue, TKey extends keyof TValue> = Omit<
12 TValue,
13 TKey
14> &
15 Required<Pick<TValue, TKey>>
16​
17export type PickRequired<T> = {
18 [K in keyof T as undefined extends T[K] ? never : K]: T[K]
20​
21export type PickOptional<T> = {
22 [K in keyof T as undefined extends T[K] ? K : never]: T[K]
24​
25// from https://stackoverflow.com/a/76458160
26export type WithoutEmpty<T> = T extends any ? ({} extends T ? never : T) : never
27​
28export type Expand<T> = T extends object
29 ? T extends infer O
30 ? O extends Function
31 ? O
32 : { [K in keyof O]: O[K] }
33 : never
34 : T
35​
36export type DeepPartial<T> = T extends object
37 ? {
38 [P in keyof T]?: DeepPartial<T[P]>
39 }
40 : T
41​
42export type MakeDifferenceOptional<TLeft, TRight> = keyof TLeft &
43 keyof TRight extends never
44 ? TRight
45 : Omit<TRight, keyof TLeft & keyof TRight> & {
46 [K in keyof TLeft & keyof TRight]?: TRight[K]
47 }
48​
49// from https://stackoverflow.com/a/53955431
50// eslint-disable-next-line @typescript-eslint/naming-convention
51export type IsUnion<T, U extends T = T> = (
52 T extends any ? (U extends T ? false : true) : never
53) extends false
54 ? false
55 : true
56​
57export type IsNonEmptyObject<T> = T extends object
58 ? keyof T extends never
59 ? false
60 : true
61 : false
62​
63export type Assign<TLeft, TRight> = TLeft extends any
64 ? TRight extends any
65 ? IsNonEmptyObject<TLeft> extends false
66 ? TRight
67 : IsNonEmptyObject<TRight> extends false
68 ? TLeft
69 : keyof TLeft & keyof TRight extends never
70 ? TLeft & TRight
71 : Omit<TLeft, keyof TRight> & TRight
72 : never
73 : never
74​
75export type IntersectAssign<TLeft, TRight> = TLeft extends any
76 ? TRight extends any
77 ? IsNonEmptyObject<TLeft> extends false
78 ? TRight
79 : IsNonEmptyObject<TRight> extends false
80 ? TLeft
81 : TRight & TLeft
82 : never
83 : never
84​
85export type Timeout = ReturnType<typeof setTimeout>
86​
87export type Updater<TPrevious, TResult = TPrevious> =
88 | TResult
89 | ((prev?: TPrevious) => TResult)
90​
91export type NonNullableUpdater<TPrevious, TResult = TPrevious> =
92 | TResult
93 | ((prev: TPrevious) => TResult)
94​
95export type ExtractObjects<TUnion> = TUnion extends MergeAllPrimitive
96 ? never
97 : TUnion
98​
99export type PartialMergeAllObject<TUnion> =
100 ExtractObjects<TUnion> extends infer TObj
101 ? [TObj] extends [never]
102 ? never
103 : {
104 [TKey in TObj extends any ? keyof TObj : never]?: TObj extends any
105 ? TKey extends keyof TObj
106 ? TObj[TKey]
107 : never
108 : never
109 }
110 : never
111​
112export type MergeAllPrimitive =
113 | ReadonlyArray<any>
114 | number
115 | string
116 | bigint
117 | boolean
118 | symbol
119 | undefined
120 | null
121​
122export type ExtractPrimitives<TUnion> = TUnion extends MergeAllPrimitive
123 ? TUnion
124 : TUnion extends object
125 ? never
126 : TUnion
127​
128export type PartialMergeAll<TUnion> =
129 | ExtractPrimitives<TUnion>
130 | PartialMergeAllObject<TUnion>
131​
132export type Constrain<T, TConstraint, TDefault = TConstraint> =
133 | (T extends TConstraint ? T : never)
134 | TDefault
135​
136export type ConstrainLiteral<T, TConstraint, TDefault = TConstraint> =
137 | (T & TConstraint)
138 | TDefault
139​
140/**
141 * To be added to router types
142 */
143export type UnionToIntersection<T> = (
144 T extends any ? (arg: T) => any : never
145) extends (arg: infer T) => any
146 ? T
147 : never
148​
149/**
150 * Merges everything in a union into one object.
151 * This mapped type is homomorphic which means it preserves stuff! :)
152 */
153export type MergeAllObjects<
154 TUnion,
155 TIntersected = UnionToIntersection<ExtractObjects<TUnion>>,
156> = [keyof TIntersected] extends [never]
157 ? never
158 : {
159 [TKey in keyof TIntersected]: TUnion extends any
160 ? TUnion[TKey & keyof TUnion]
161 : never
162 }
163​
164export type MergeAll<TUnion> =
165 | MergeAllObjects<TUnion>
166 | ExtractPrimitives<TUnion>
167​
168export type ValidateJSON<T> = ((...args: Array<any>) => any) extends T
169 ? unknown extends T
170 ? never
171 : 'Function is not serializable'
172 : { [K in keyof T]: ValidateJSON<T[K]> }
173​
174export type LooseReturnType<T> = T extends (
175 ...args: Array<any>
176) => infer TReturn
177 ? TReturn
178 : never
179​
180export type LooseAsyncReturnType<T> = T extends (
181 ...args: Array<any>
182) => infer TReturn
183 ? TReturn extends Promise<infer TReturn>
184 ? TReturn
185 : TReturn
186 : never
187​
188/**
189 * Return the last element of an array.
190 * Intended for non-empty arrays used within router internals.
191 */
192export function last<T>(arr: ReadonlyArray<T>) {
193 return arr[arr.length - 1]
195​
196/**
197 * Apply a value-or-updater to a previous value.
198 * Accepts either a literal value or a function of the previous value.
199 */
200export function functionalUpdate<TPrevious, TResult = TPrevious>(
201 updater: Updater<TPrevious, TResult> | NonNullableUpdater<TPrevious, TResult>,
202 previous: TPrevious,
203): TResult {
204 if (typeof updater === 'function') {
205 return (updater as Function)(previous)
206 }
207​
208 return updater
210​
211export const hasOwn = Object.prototype.hasOwnProperty
212​
213export function hasKeys(obj: Record<string, unknown>) {
214 for (const key in obj) {
215 if (hasOwn.call(obj, key)) return true
216 }
217 return false
219​
220export const createNull = () => Object.create(null)
221// Search and params objects use null prototypes so keys like `__proto__` stay data.
222export const nullReplaceEqualDeep: typeof replaceEqualDeep = (prev, next) =>
223 replaceEqualDeep(prev, next, true)
224​
225/**
226 * Reuse equal children between immutable plain objects and dense arrays.
227 * Return `prev` for deeply equal values; otherwise return an object already
228 * containing the resolved children or create a copy with the shared children.
229 * Getters and own `__proto__` keys in ordinary object copies are unsupported.
230 * Do not use this with signals.
231 */
232export function replaceEqualDeep<T>(
233 prev: any,
234 next: T,
235 _nullProto?: boolean,
236 _depth?: number,
237): T
238export function replaceEqualDeep(
239 prev: any,
240 next: any,
241 _nullProto?: boolean,
242 _depth = 0,
243): any {
244 if (isServer) {
245 return next
246 }
247 if (prev === next) {
248 return prev
249 }
250​
251 if (_depth++ > 500) {
252 return next
253 }
254​
255 const array = Array.isArray(prev) && Array.isArray(next)
256​
257 if (!array && !(isPlainObject(prev) && isPlainObject(next))) {
258 return next
259 }
260​
261 const prevKeys: Array<any> = Object.keys(prev)
262 const previousCount = prevKeys.length
263 const nextKeys: Array<any> = Object.keys(next)
264 const length = nextKeys.length
265 // Hidden object keys and symbols on next make the value opaque. Arrays
266 // must have only dense enumerable indices: a hole and an extra key can
267 // cancel out in the count, so also check the last key of both arrays.
268 if (
269 array
270 ? previousCount !== prev.length ||
271 length !== next.length ||
272 (previousCount && last(prevKeys) !== `${previousCount - 1}`) ||
273 (length && last(nextKeys) !== `${length - 1}`)
274 : previousCount !== Object.getOwnPropertyNames(prev).length ||
275 length !== Object.getOwnPropertyNames(next).length ||
276 Object.getOwnPropertySymbols(next).length
277 ) {
278 return next
279 }
280​
281 let i = 0
282 let child: any
283 let previous: any
284 let key: any
285​
286 if (array) {
287 // Entries before the first difference already resolve to prev.
288 for (; i < length; i++) {
289 key = i
290 previous = prev[key]
291 child = next[key]
292 child =
293 previous === child
294 ? previous
295 : typeof previous === 'object'
296 ? replaceEqualDeep(previous, child, _nullProto, _depth)
297 : child
298 if (child !== previous) {
299 break
300 }
301 }
302 if (i === length && previousCount === length) {
303 return prev
304 }
305 } else {
306 let equal = previousCount === length
307 let unchanged = true
308 for (; i < length; i++) {
309 key = nextKeys[i]!
310 previous = prev[key]
311 const incoming = next[key]
312 child =
313 previous === incoming
314 ? previous
315 : typeof previous === 'object'
316 ? replaceEqualDeep(previous, incoming, _nullProto, _depth)
317 : incoming
318 equal &&=
319 child === previous && (prevKeys[i] === key || hasOwn.call(prev, key))
320 unchanged &&= Object.is(child, incoming)
321 // This key has been checked; its private slot can hold the result.
322 prevKeys[i] = child
323 }
324 if (equal) {
325 return Object.getOwnPropertySymbols(prev).length ? next : prev
326 }
327 if (unchanged) {
328 return next
329 }
330 }
331​
332 // Reuse the validated array key list; it is private and has the right length.
333 const copy: any = array ? nextKeys.fill(0) : _nullProto ? createNull() : {}
334 for (let j = 0; j < length; j++) {
335 key = array ? j : nextKeys[j]!
336 if (array) {
337 previous = prev[key]
338 if (j > i) {
339 child = next[key]
340 child =
341 previous === child
342 ? previous
343 : typeof previous === 'object'
344 ? replaceEqualDeep(previous, child, _nullProto, _depth)
345 : child
346 }
347 copy[key] = j < i ? previous : child
348 } else {
349 copy[key] = prevKeys[j]
350 }
351 }
352 return copy
354​
355export function isPlainObject(o: unknown): boolean {
356 if (!o || typeof o !== 'object') {
357 return false
358 }
359 // An own constructor is data, so classify the actual prototype.
360 return (Object.getPrototypeOf(o)?.constructor ?? Object) === Object
362​
363/**
364 * Check if a value is a "plain" array (no extra enumerable keys).
365 */
366export function isPlainArray(value: unknown): value is Array<unknown> {
367 return Array.isArray(value) && value.length === Object.keys(value).length
369​
370/**
371 * Perform a deep equality check optimized for router state comparisons.
372 *
373 * - `partial`: `b` may omit keys that `a` has (arrays stay length-exact).
374 * - `explicitUndefined`: keys holding `undefined` take part in the comparison
375 * instead of being ignored.
376 *
377 * Internal: the flags are positional so hot callers pass no options object.
378 */
379export function deepEqual(
380 a: any,
381 b: any,
382 partial?: boolean,
383 explicitUndefined?: boolean,
384): boolean {
385 if (a === b) {
386 return true
387 }
388​
389 if (Array.isArray(a) && Array.isArray(b)) {
390 if (a.length !== b.length) return false
391 for (let i = 0, l = a.length; i < l; i++) {
392 const av = a[i]
393 const bv = b[i]
394 if (av !== bv && !deepEqual(av, bv, partial, explicitUndefined)) {
395 return false
396 }
397 }
398 return true
399 }
400​
401 if (isPlainObject(a) && isPlainObject(b)) {
402 if (partial) {
403 for (const k in b) {
404 if (explicitUndefined || b[k] !== undefined) {
405 if (!deepEqual(a[k], b[k], partial, explicitUndefined)) return false
406 }
407 }
408 return true
409 }
410​
411 let aCount = 0
412 if (explicitUndefined) {
413 aCount = Object.keys(a).length
414 } else {
415 for (const k in a) {
416 if (a[k] !== undefined) aCount++
417 }
418 }
419​
420 for (const k in b) {
421 if (explicitUndefined || b[k] !== undefined) {
422 if (
423 aCount-- === 0 ||
424 !deepEqual(a[k], b[k], partial, explicitUndefined)
425 ) {
426 return false
427 }
428 }
429 }
430​
431 return aCount === 0
432 }
433​
434 return false
436​
437export type StringLiteral<T> = T extends string
438 ? string extends T
439 ? string
440 : T
441 : never
442​
443export type ThrowOrOptional<T, TThrow extends boolean> = TThrow extends true
444 ? T
445 : T | undefined
446​
447export type StrictOrFrom<
448 TRouter extends AnyRouter,
449 TFrom,
450 TStrict extends boolean = true,
451> = TStrict extends false
452 ? {
453 from?: never
454 strict: TStrict
455 }
456 : {
457 from: ConstrainLiteral<TFrom, RouteIds<TRouter['routeTree']>>
458 strict?: TStrict
459 }
460​
461export type ThrowConstraint<
462 TStrict extends boolean,
463 TThrow extends boolean,
464> = TStrict extends false ? (TThrow extends true ? never : TThrow) : TThrow
465​
466export type ControlledPromise<T> = Promise<T> & {
467 resolve: (value: T) => void
468 reject: (value: any) => void
469 status: 'pending' | 'resolved' | 'rejected'
470 value?: T
472​
473/**
474 * Create a promise with exposed resolve/reject and status fields.
475 * Useful for coordinating async router lifecycle operations.
476 */
477export function createControlledPromise<T>(onResolve?: (value: T) => void) {
478 let resolveLoadPromise!: (value: T) => void
479 let rejectLoadPromise!: (value: any) => void
480​
481 const controlledPromise = new Promise<T>((resolve, reject) => {
482 resolveLoadPromise = resolve
483 rejectLoadPromise = reject
484 }) as ControlledPromise<T>
485​
486 controlledPromise.status = 'pending'
487​
488 controlledPromise.resolve = (value: T) => {
489 controlledPromise.status = 'resolved'
490 controlledPromise.value = value
491 resolveLoadPromise(value)
492 onResolve?.(value)
493 }
494​
495 controlledPromise.reject = (e) => {
496 controlledPromise.status = 'rejected'
497 rejectLoadPromise(e)
498 }
499​
500 return controlledPromise
502​
503/**
504 * Heuristically detect dynamic import "module not found" errors
505 * across major browsers for lazy route component handling.
506 */
507export function isModuleNotFoundError(error: any): boolean {
508 // chrome: "Failed to fetch dynamically imported module: http://localhost:5173/src/routes/posts.index.tsx?tsr-split"
509 // firefox: "error loading dynamically imported module: http://localhost:5173/src/routes/posts.index.tsx?tsr-split"
510 // safari: "Importing a module script failed."
511 if (typeof error?.message !== 'string') return false
512 return (
513 error.message.startsWith('Failed to fetch dynamically imported module') ||
514 error.message.startsWith('error loading dynamically imported module') ||
515 error.message.startsWith('Importing a module script failed')
516 )
518​
519export function isPromise<T>(
520 value: Promise<Awaited<T>> | T,
521): value is Promise<Awaited<T>> {
522 return Boolean(
523 value &&
524 typeof value === 'object' &&
525 typeof (value as Promise<T>).then === 'function',
526 )
528​
529export function findLast<T>(
530 array: ReadonlyArray<T>,
531 predicate: (item: T) => boolean,
532): T | undefined {
533 for (let i = array.length - 1; i >= 0; i--) {
534 const item = array[i]!
535 if (predicate(item)) return item
536 }
537 return undefined
539​
540/**
541 * Re-encode characters that are unsafe in URL paths.
542 * Includes ASCII control characters (0x00-0x1F, 0x7F) and a subset of the
543 * WHATWG URL "path percent-encode set" (", <, >, `, {, }).
544 *
545 * Space (0x20) is intentionally excluded β€” decodeURI decodes %20 to space
546 * and the router stores decoded spaces in location.pathname. The existing
547 * encodePathLikeUrl already handles re-encoding spaces for outgoing URLs.
548 *
549 * These characters are decoded by decodeURI but must remain percent-encoded
550 * in paths to match how upstream layers (CDNs, edge middleware, browsers)
551 * interpret the URL, preventing infinite redirect loops and path mismatches.
552 */
553// eslint-disable-next-line no-control-regex
554const PATH_UNSAFE_RE = /[\x00-\x1f\x7f"<>`{}]/g
555​
556function sanitizePathSegment(segment: string): string {
557 return segment.replace(
558 PATH_UNSAFE_RE,
559 (ch) => '%' + ch.charCodeAt(0).toString(16).toUpperCase().padStart(2, '0'),
560 )
562​
563function decodeSegment(segment: string): string {
564 let decoded: string
565 try {
566 decoded = decodeURI(segment)
567 } catch {
568 // if the decoding fails, try to decode the various parts leaving the malformed tags in place
569 decoded = segment.replaceAll(/%[0-9A-F]{2}/gi, (match) => {
570 try {
571 return decodeURI(match)
572 } catch {
573 return match
574 }
575 })
576 }
577 return sanitizePathSegment(decoded)
579​
580/**
581 * Default list of URL protocols to allow in links, redirects, and navigation.
582 * Any absolute URL protocol not in this list is treated as dangerous by default.
583 */
584export const DEFAULT_PROTOCOL_ALLOWLIST = [
585 // Standard web navigation
586 'http:',
587 'https:',
588​
589 // Common browser-safe actions
590 'mailto:',
591 'tel:',
593​
594/**
595 * Extract the explicit URL scheme, including its colon, using WHATWG
596 * normalization rules. This does not validate the rest of the URL.
597 *
598 * Returning `undefined` means "no explicit scheme", not "safe URL";
599 * protocol-relative URLs such as "//evil.example" require a separate check.
600 */
601export function getUrlScheme(url: string): string | undefined {
602 if (url[0] === '/') {
603 return undefined
604 }
605 if (!url.includes(':')) {
606 return undefined
607 }
608 // WHATWG strips leading C0/space and TAB/LF/CR within a scheme.
609 // Match the prefix first so relative paths and URL bodies need no copying.
610 // eslint-disable-next-line no-control-regex
611 return /^[\x00-\x20]*([a-z][a-z\d+.\t\n\r-]*:)/i
612 .exec(url)?.[1]
613 ?.replace(/[\t\n\r]/g, '')
614 .toLowerCase()
616​
617// Match protocol-relative URLs such as "//evil.example", including backslash
618// and control-character variants. Stop at the second separator so validation
619// does not scan or normalize the URL body.
620// eslint-disable-next-line no-control-regex
621export const protocolRelativePrefixRegex = /^[\x00-\x20]*[\\/][\t\n\r]*[\\/]/
622​
623/**
624 * Check if a URL string uses a protocol that is not in the allowlist or is
625 * protocol-relative (e.g. "//evil.example"), which can navigate to another host.
626 * Returns true for blocked protocols like javascript:, blob:, and data:, as
627 * well as slash/backslash variants of protocol-relative URLs.
628 *
629 * Scheme parsing normalizes:
630 * - Mixed case (JavaScript: β†’ javascript:)
631 * - Whitespace/control characters (java\nscript: β†’ javascript:)
632 * - Leading whitespace
633 *
634 * For relative URLs without a protocol-relative prefix, returns false.
635 *
636 * @param url - The URL string to check
637 * @param allowlist - Set of protocols to allow
638 * @returns true if the URL uses a protocol that is not allowed or can escape
639 * the current origin through a protocol-relative URL
640 */
641export function isDangerousProtocol(
642 url: string,
643 allowlist: Set<string>,
644): boolean {
645 if (!url) return false
646​
647 // Inputs like "/\evil.example" can navigate to another host just like
648 // "//evil.example", even with leading whitespace or ignored control characters.
649 if (protocolRelativePrefixRegex.test(url)) {
650 return true
651 }
652​
653 const scheme = getUrlScheme(url)
654 return scheme ? !allowlist.has(scheme) : false
656​
657// This utility is based on https://github.com/zertosh/htmlescape
658// License: https://github.com/zertosh/htmlescape/blob/0527ca7156a524d256101bb310a9f970f63078ad/LICENSE
659const HTML_ESCAPE_LOOKUP: { [match: string]: string } = {
660 '&': '\\u0026',
661 '>': '\\u003e',
662 '<': '\\u003c',
663 '\u2028': '\\u2028',
664 '\u2029': '\\u2029',
666​
667const HTML_ESCAPE_REGEX = /[&><\u2028\u2029]/g
668​
669/**
670 * Escape HTML special characters in a string to prevent XSS attacks
671 * when embedding strings in script tags during SSR.
672 *
673 * This is essential for preventing XSS vulnerabilities when user-controlled
674 * content is embedded in inline scripts.
675 */
676export function escapeHtml(str: string): string {
677 return str.replace(HTML_ESCAPE_REGEX, (match) => HTML_ESCAPE_LOOKUP[match]!)
679​
680// Decode component data only. Leave protocol-relative URL handling to callers;
681// this decoder also receives fragments, where slashes and backslashes are data.
682export function decodePath(path: string) {
683 if (!path) {
684 return path
685 }
686 let result = path
687 // eslint-disable-next-line no-control-regex
688 if (/[%\\\x00-\x1f\x7f]/.test(path)) {
689 const re = /%25|%5C/gi
690 let cursor = 0
691 let match
692 result = ''
693 while (null !== (match = re.exec(path))) {
694 result += decodeSegment(path.slice(cursor, match.index)) + match[0]
695 cursor = re.lastIndex
696 }
697 result += decodeSegment(cursor ? path.slice(cursor) : path)
698 }
699​
700 return result
702​
703/**
704 * Encodes a path the same way `new URL()` would, but without the overhead of full URL parsing.
705 *
706 * This function encodes:
707 * - Whitespace characters (spaces β†’ %20, tabs β†’ %09, etc.)
708 * - Non-ASCII/Unicode characters (emojis, accented characters, etc.)
709 *
710 * It preserves:
711 * - Already percent-encoded sequences (won't double-encode %2F, %25, etc.)
712 * - ASCII special characters valid in URL paths (@, $, &, +, etc.)
713 * - Forward slashes as path separators
714 *
715 * Used to generate proper href values for SSR without constructing URL objects.
716 *
717 * @example
718 * encodePathLikeUrl('/path/file name.pdf') // '/path/file%20name.pdf'
719 * encodePathLikeUrl('/path/ζ—₯本θͺž') // '/path/%E6%97%A5%E6%9C%AC%E8%AA%9E'
720 * encodePathLikeUrl('/path/already%20encoded') // '/path/already%20encoded' (preserved)
721 */
722export function encodePathLikeUrl(path: string): string {
723 // Encode whitespace and non-ASCII characters that browsers encode in URLs.
724 // The test uses one character class: it matches the same code units as the
725 // replacement pattern below and is cheaper than the alternation.
726 if (!/[\s\u0080-\uFFFF]/.test(path)) {
727 return path
728 }
729 // biome-ignore lint/suspicious/noControlCharactersInRegex: intentional ASCII range check
730 // eslint-disable-next-line no-control-regex
731 return path.replace(/\s|[^\u0000-\u007F]/gu, encodeURIComponent)
733​
734/**
735 * Builds the dev-mode CSS styles URL for route-scoped CSS collection.
736 * Used by HeadContent components in all framework implementations to construct
737 * the URL for the `/@tanstack-start/styles.css` endpoint.
738 *
739 * @param basepath - The router's basepath (may or may not have leading slash)
740 * @param routeIds - Array of matched route IDs to include in the CSS collection
741 * @returns The full URL path for the dev styles CSS endpoint
742 */
743export function buildDevStylesUrl(
744 basepath: string,
745 routeIds: Array<string>,
746): string {
747 // Trim all leading and trailing slashes from basepath
748 const trimmedBasepath = basepath.replace(/^\/+|\/+$/g, '')
749 // Build normalized basepath: empty string for root, or '/path' for non-root
750 const normalizedBasepath = trimmedBasepath === '' ? '' : `/${trimmedBasepath}`
751 return `${normalizedBasepath}/@tanstack-start/styles.css?routes=${encodeURIComponent(routeIds.join(','))}`
753​
754export function arraysEqual<T>(a: Array<T>, b: Array<T>) {
755 if (a === b) return true
756 if (a.length !== b.length) return false
757 for (let i = 0; i < a.length; i++) {
758 if (a[i] !== b[i]) return false
759 }
760 return true