This commit is contained in:
2025-05-09 05:30:08 +02:00
parent 7bb10e7df4
commit 73367bad9e
5322 changed files with 1266973 additions and 313 deletions

View File

@@ -0,0 +1,8 @@
import { AnyRouter, RegisteredRouter, RouterState } from '@tanstack/router-core';
import { StructuralSharingOption, ValidateSelected } from './structuralSharing.cjs';
export type UseRouterStateOptions<TRouter extends AnyRouter, TSelected, TStructuralSharing> = {
router?: TRouter;
select?: (state: RouterState<TRouter['routeTree']>) => ValidateSelected<TRouter, TSelected, TStructuralSharing>;
} & StructuralSharingOption<TRouter, TSelected, TStructuralSharing>;
export type UseRouterStateResult<TRouter extends AnyRouter, TSelected> = unknown extends TSelected ? RouterState<TRouter['routeTree']> : TSelected;
export declare function useRouterState<TRouter extends AnyRouter = RegisteredRouter, TSelected = unknown, TStructuralSharing extends boolean = boolean>(opts?: UseRouterStateOptions<TRouter, TSelected, TStructuralSharing>): UseRouterStateResult<TRouter, TSelected>;

View File

@@ -0,0 +1 @@
module.exports={A:{A:{"1":"A B","2":"K D E F mC"},B:{"1":"0 9 C L M G N O P Q H R S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB I"},C:{"1":"0 1 2 3 4 5 6 7 8 9 J PB K D E F A B C L M G N O P QB RB SB TB UB VB WB XB YB ZB aB bB cB dB eB fB gB hB iB jB kB lB mB nB oB pB qB rB sB tB uB vB MC wB NC xB yB zB 0B 1B 2B 3B 4B 5B 6B 7B 8B 9B AC BC CC DC Q H R OC S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB I PC EC QC RC oC pC","2":"nC LC qC rC"},D:{"1":"0 1 2 3 4 5 6 7 8 9 L M G N O P QB RB SB TB UB VB WB XB YB ZB aB bB cB dB eB fB gB hB iB jB kB lB mB nB oB pB qB rB sB tB uB vB MC wB NC xB yB zB 0B 1B 2B 3B 4B 5B 6B 7B 8B 9B AC BC CC DC Q H R S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB I PC EC QC RC","2":"J PB K D E F A B C"},E:{"1":"K D E F A B C L M G uC vC wC TC FC GC xC yC zC UC VC HC 0C IC WC XC YC ZC aC 1C JC bC cC dC eC fC 2C KC gC hC iC jC 3C","2":"J sC SC","132":"PB tC"},F:{"1":"0 1 2 3 4 5 6 7 8 C G N O P QB RB SB TB UB VB WB XB YB ZB aB bB cB dB eB fB gB hB iB jB kB lB mB nB oB pB qB rB sB tB uB vB wB xB yB zB 0B 1B 2B 3B 4B 5B 6B 7B 8B 9B AC BC CC DC Q H R OC S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z 8C GC","2":"F B 4C 5C 6C 7C FC kC"},G:{"1":"E AD BD CD DD ED FD GD HD ID JD KD LD MD ND OD PD QD RD SD UC VC HC TD IC WC XC YC ZC aC UD JC bC cC dC eC fC VD KC gC hC iC jC","2":"SC 9C lC"},H:{"1":"WD"},I:{"1":"LC J I aD lC bD cD","2":"XD YD ZD"},J:{"1":"D A"},K:{"1":"C H kC GC","2":"A B FC"},L:{"1":"I"},M:{"1":"EC"},N:{"1":"A B"},O:{"1":"HC"},P:{"1":"1 2 3 4 5 6 7 8 J dD eD fD gD hD TC iD jD kD lD mD IC JC KC nD"},Q:{"1":"oD"},R:{"1":"pD"},S:{"1":"qD rD"}},B:6,C:"ECMAScript 5 Strict Mode",D:true};

View File

@@ -0,0 +1,45 @@
/**
* @fileoverview Define the cursor which iterates tokens only, with inflated range.
* @author Toru Nagashima
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const ForwardTokenCursor = require("./forward-token-cursor");
//------------------------------------------------------------------------------
// Exports
//------------------------------------------------------------------------------
/**
* The cursor which iterates tokens only, with inflated range.
* This is for the backward compatibility of padding options.
*/
module.exports = class PaddedTokenCursor extends ForwardTokenCursor {
/**
* Initializes this cursor.
* @param {Token[]} tokens The array of tokens.
* @param {Comment[]} comments The array of comments.
* @param {Object} indexMap The map from locations to indices in `tokens`.
* @param {number} startLoc The start location of the iteration range.
* @param {number} endLoc The end location of the iteration range.
* @param {number} beforeCount The number of tokens this cursor iterates before start.
* @param {number} afterCount The number of tokens this cursor iterates after end.
*/
constructor(
tokens,
comments,
indexMap,
startLoc,
endLoc,
beforeCount,
afterCount,
) {
super(tokens, comments, indexMap, startLoc, endLoc);
this.index = Math.max(0, this.index - beforeCount);
this.indexEnd = Math.min(tokens.length - 1, this.indexEnd + afterCount);
}
};

View File

@@ -0,0 +1 @@
{"version":3,"names":["_path","data","require","sep","path","endSep","substitution","starPat","starPatLast","starStarPat","starStarPatLast","escapeRegExp","string","replace","pathToPattern","pattern","dirname","parts","resolve","split","RegExp","map","part","i","last","length","indexOf","slice","join"],"sources":["../../src/config/pattern-to-regex.ts"],"sourcesContent":["import path from \"path\";\n\nconst sep = `\\\\${path.sep}`;\nconst endSep = `(?:${sep}|$)`;\n\nconst substitution = `[^${sep}]+`;\n\nconst starPat = `(?:${substitution}${sep})`;\nconst starPatLast = `(?:${substitution}${endSep})`;\n\nconst starStarPat = `${starPat}*?`;\nconst starStarPatLast = `${starPat}*?${starPatLast}?`;\n\nfunction escapeRegExp(string: string) {\n return string.replace(/[|\\\\{}()[\\]^$+*?.]/g, \"\\\\$&\");\n}\n\n/**\n * Implement basic pattern matching that will allow users to do the simple\n * tests with * and **. If users want full complex pattern matching, then can\n * always use regex matching, or function validation.\n */\nexport default function pathToPattern(\n pattern: string,\n dirname: string,\n): RegExp {\n const parts = path.resolve(dirname, pattern).split(path.sep);\n\n return new RegExp(\n [\n \"^\",\n ...parts.map((part, i) => {\n const last = i === parts.length - 1;\n\n // ** matches 0 or more path parts.\n if (part === \"**\") return last ? starStarPatLast : starStarPat;\n\n // * matches 1 path part.\n if (part === \"*\") return last ? starPatLast : starPat;\n\n // *.ext matches a wildcard with an extension.\n if (part.indexOf(\"*.\") === 0) {\n return (\n substitution + escapeRegExp(part.slice(1)) + (last ? endSep : sep)\n );\n }\n\n // Otherwise match the pattern text.\n return escapeRegExp(part) + (last ? endSep : sep);\n }),\n ].join(\"\"),\n );\n}\n"],"mappings":";;;;;;AAAA,SAAAA,MAAA;EAAA,MAAAC,IAAA,GAAAC,OAAA;EAAAF,KAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AAEA,MAAME,GAAG,GAAG,KAAKC,MAAGA,CAAC,CAACD,GAAG,EAAE;AAC3B,MAAME,MAAM,GAAG,MAAMF,GAAG,KAAK;AAE7B,MAAMG,YAAY,GAAG,KAAKH,GAAG,IAAI;AAEjC,MAAMI,OAAO,GAAG,MAAMD,YAAY,GAAGH,GAAG,GAAG;AAC3C,MAAMK,WAAW,GAAG,MAAMF,YAAY,GAAGD,MAAM,GAAG;AAElD,MAAMI,WAAW,GAAG,GAAGF,OAAO,IAAI;AAClC,MAAMG,eAAe,GAAG,GAAGH,OAAO,KAAKC,WAAW,GAAG;AAErD,SAASG,YAAYA,CAACC,MAAc,EAAE;EACpC,OAAOA,MAAM,CAACC,OAAO,CAAC,qBAAqB,EAAE,MAAM,CAAC;AACtD;AAOe,SAASC,aAAaA,CACnCC,OAAe,EACfC,OAAe,EACP;EACR,MAAMC,KAAK,GAAGb,MAAGA,CAAC,CAACc,OAAO,CAACF,OAAO,EAAED,OAAO,CAAC,CAACI,KAAK,CAACf,MAAGA,CAAC,CAACD,GAAG,CAAC;EAE5D,OAAO,IAAIiB,MAAM,CACf,CACE,GAAG,EACH,GAAGH,KAAK,CAACI,GAAG,CAAC,CAACC,IAAI,EAAEC,CAAC,KAAK;IACxB,MAAMC,IAAI,GAAGD,CAAC,KAAKN,KAAK,CAACQ,MAAM,GAAG,CAAC;IAGnC,IAAIH,IAAI,KAAK,IAAI,EAAE,OAAOE,IAAI,GAAGd,eAAe,GAAGD,WAAW;IAG9D,IAAIa,IAAI,KAAK,GAAG,EAAE,OAAOE,IAAI,GAAGhB,WAAW,GAAGD,OAAO;IAGrD,IAAIe,IAAI,CAACI,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE;MAC5B,OACEpB,YAAY,GAAGK,YAAY,CAACW,IAAI,CAACK,KAAK,CAAC,CAAC,CAAC,CAAC,IAAIH,IAAI,GAAGnB,MAAM,GAAGF,GAAG,CAAC;IAEtE;IAGA,OAAOQ,YAAY,CAACW,IAAI,CAAC,IAAIE,IAAI,GAAGnB,MAAM,GAAGF,GAAG,CAAC;EACnD,CAAC,CAAC,CACH,CAACyB,IAAI,CAAC,EAAE,CACX,CAAC;AACH;AAAC","ignoreList":[]}

View File

@@ -0,0 +1,214 @@
'use strict'
// Copyright (c) 2018 inspiredware
var path = require('path')
var pkg = require(path.resolve('package.json'))
var versionArray = process.version
.substr(1)
.replace(/-.*$/, '')
.split('.')
.map(function (item) {
return +item
})
/**
*
* A set of utilities to assist developers of tools that build
* [N-API](https://nodejs.org/api/n-api.html#n_api_n_api) native add-ons.
*
* The main repository can be found
* [here](https://github.com/inspiredware/napi-build-utils#napi-build-utils).
*
* @module napi-build-utils
*/
/**
* Implements a consistent name of `napi` for N-API runtimes.
*
* @param {string} runtime The runtime string.
* @returns {boolean}
*/
exports.isNapiRuntime = function (runtime) {
return runtime === 'napi'
}
/**
* Determines whether the specified N-API version is supported
* by both the currently running Node instance and the package.
*
* @param {string} napiVersion The N-API version to check.
* @returns {boolean}
*/
exports.isSupportedVersion = function (napiVersion) {
var version = parseInt(napiVersion, 10)
return version <= exports.getNapiVersion() && exports.packageSupportsVersion(version)
}
/**
* Determines whether the specified N-API version is supported by the package.
* The N-API version must be present in the `package.json`
* `binary.napi_versions` array.
*
* @param {number} napiVersion The N-API version to check.
* @returns {boolean}
* @private
*/
exports.packageSupportsVersion = function (napiVersion) {
if (pkg.binary && pkg.binary.napi_versions &&
pkg.binary.napi_versions instanceof Array) { // integer array
for (var i = 0; i < pkg.binary.napi_versions.length; i++) {
if (pkg.binary.napi_versions[i] === napiVersion) return true
};
};
return false
}
/**
* Issues a warning to the supplied log if the N-API version is not supported
* by the current Node instance or if the N-API version is not supported
* by the package.
*
* @param {string} napiVersion The N-API version to check.
* @param {Object} log The log object to which the warnings are to be issued.
* Must implement the `warn` method.
*/
exports.logUnsupportedVersion = function (napiVersion, log) {
if (!exports.isSupportedVersion(napiVersion)) {
if (exports.packageSupportsVersion(napiVersion)) {
log.warn('This Node instance does not support N-API version ' + napiVersion)
} else {
log.warn('This package does not support N-API version ' + napiVersion)
}
}
}
/**
* Issues warnings to the supplied log for those N-API versions not supported
* by the N-API runtime or the package.
*
* Note that this function is specific to the
* [`prebuild`](https://github.com/prebuild/prebuild#prebuild) package.
*
* `target` is the list of targets to be built and is determined in one of
* three ways from the command line arguments:
* (1) `--target` specifies a specific target to build.
* (2) `--all` specifies all N-API versions supported by the package.
* (3) Neither of these specifies to build the single "best version available."
*
* `prebuild` is an array of objects in the form `{runtime: 'napi', target: '2'}`.
* The array contains the list of N-API versions that are supported by both the
* package being built and the currently running Node instance.
*
* The objective of this function is to issue a warning for those items that appear
* in the `target` argument but not in the `prebuild` argument.
* If a specific target is supported by the package (`packageSupportsVersion`) but
* but note in `prebuild`, the assumption is that the target is not supported by
* Node.
*
* @param {(Array<string>|string)} target The N-API version(s) to check. Target is
* @param {Array<Object>} prebuild A config object created by the `prebuild` package.
* @param {Object} log The log object to which the warnings are to be issued.
* Must implement the `warn` method.
* @private
*/
exports.logMissingNapiVersions = function (target, prebuild, log) {
if (exports.getNapiBuildVersions()) {
var targets = [].concat(target)
targets.forEach(function (napiVersion) {
if (!prebuildExists(prebuild, napiVersion)) {
if (exports.packageSupportsVersion(parseInt(napiVersion, 10))) {
log.warn('This Node instance does not support N-API version ' + napiVersion)
} else {
log.warn('This package does not support N-API version ' + napiVersion)
}
}
})
} else {
log.error('Builds with runtime \'napi\' require a binary.napi_versions ' +
'property on the package.json file')
}
}
/**
* Determines whether the specified N-API version exists in the prebuild
* configuration object.
*
* Note that this function is specific to the `prebuild` and `prebuild-install`
* packages.
*
* @param {Object} prebuild A config object created by the `prebuild` package.
* @param {string} napiVersion The N-APi version to be checked.
* @return {boolean}
* @private
*/
var prebuildExists = function (prebuild, napiVersion) {
if (prebuild) {
for (var i = 0; i < prebuild.length; i++) {
if (prebuild[i].target === napiVersion) return true
}
}
return false
}
/**
* Returns the best N-API version to build given the highest N-API
* version supported by the current Node instance and the N-API versions
* supported by the package, or undefined if a suitable N-API version
* cannot be determined.
*
* The best build version is the greatest N-API version supported by
* the package that is less than or equal to the highest N-API version
* supported by the current Node instance.
*
* @returns {number|undefined}
*/
exports.getBestNapiBuildVersion = function () {
var bestNapiBuildVersion = 0
var napiBuildVersions = exports.getNapiBuildVersions(pkg) // array of integer strings
if (napiBuildVersions) {
var ourNapiVersion = exports.getNapiVersion()
napiBuildVersions.forEach(function (napiBuildVersionStr) {
var napiBuildVersion = parseInt(napiBuildVersionStr, 10)
if (napiBuildVersion > bestNapiBuildVersion &&
napiBuildVersion <= ourNapiVersion) {
bestNapiBuildVersion = napiBuildVersion
}
})
}
return bestNapiBuildVersion === 0 ? undefined : bestNapiBuildVersion
}
/**
* Returns an array of N-API versions supported by the package.
*
* @returns {Array<string>|undefined}
*/
exports.getNapiBuildVersions = function () {
var napiBuildVersions = []
// remove duplicates, convert to text
if (pkg.binary && pkg.binary.napi_versions) {
pkg.binary.napi_versions.forEach(function (napiVersion) {
var duplicated = napiBuildVersions.indexOf('' + napiVersion) !== -1
if (!duplicated) {
napiBuildVersions.push('' + napiVersion)
}
})
}
return napiBuildVersions.length ? napiBuildVersions : undefined
}
/**
* Returns the highest N-API version supported by the current node instance
* or undefined if N-API is not supported.
*
* @returns {string|undefined}
*/
exports.getNapiVersion = function () {
var version = process.versions.napi // integer string, can be undefined
if (!version) { // this code should never need to be updated
if (versionArray[0] === 9 && versionArray[1] >= 3) version = '2' // 9.3.0+
else if (versionArray[0] === 8) version = '1' // 8.0.0+
}
return version
}

View File

@@ -0,0 +1,47 @@
Node.js is licensed for use as follows:
"""
Copyright Node.js contributors. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
"""
This license applies to parts of Node.js originating from the
https://github.com/joyent/node repository:
"""
Copyright Joyent, Inc. and other Node contributors. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
"""

View File

@@ -0,0 +1,12 @@
import { ParsedHistoryState } from '@tanstack/history';
import { AnySchema } from './validators.cjs';
export interface ParsedLocation<TSearchObj extends AnySchema = {}> {
href: string;
pathname: string;
search: TSearchObj;
searchStr: string;
state: ParsedHistoryState;
hash: string;
maskedLocation?: ParsedLocation<TSearchObj>;
unmaskOnReload?: boolean;
}

View File

@@ -0,0 +1,196 @@
/**
* @fileoverview Rule to disallow certain object properties
* @author Will Klein & Eli White
*/
"use strict";
const astUtils = require("./utils/ast-utils");
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../shared/types').Rule} */
module.exports = {
meta: {
type: "suggestion",
docs: {
description: "Disallow certain properties on certain objects",
recommended: false,
url: "https://eslint.org/docs/latest/rules/no-restricted-properties",
},
schema: {
type: "array",
items: {
anyOf: [
// `object` and `property` are both optional, but at least one of them must be provided.
{
type: "object",
properties: {
object: {
type: "string",
},
property: {
type: "string",
},
message: {
type: "string",
},
},
additionalProperties: false,
required: ["object"],
},
{
type: "object",
properties: {
object: {
type: "string",
},
property: {
type: "string",
},
message: {
type: "string",
},
},
additionalProperties: false,
required: ["property"],
},
],
},
uniqueItems: true,
},
messages: {
restrictedObjectProperty:
// eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period
"'{{objectName}}.{{propertyName}}' is restricted from being used.{{message}}",
restrictedProperty:
// eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period
"'{{propertyName}}' is restricted from being used.{{message}}",
},
},
create(context) {
const restrictedCalls = context.options;
if (restrictedCalls.length === 0) {
return {};
}
const restrictedProperties = new Map();
const globallyRestrictedObjects = new Map();
const globallyRestrictedProperties = new Map();
restrictedCalls.forEach(option => {
const objectName = option.object;
const propertyName = option.property;
if (typeof objectName === "undefined") {
globallyRestrictedProperties.set(propertyName, {
message: option.message,
});
} else if (typeof propertyName === "undefined") {
globallyRestrictedObjects.set(objectName, {
message: option.message,
});
} else {
if (!restrictedProperties.has(objectName)) {
restrictedProperties.set(objectName, new Map());
}
restrictedProperties.get(objectName).set(propertyName, {
message: option.message,
});
}
});
/**
* Checks to see whether a property access is restricted, and reports it if so.
* @param {ASTNode} node The node to report
* @param {string} objectName The name of the object
* @param {string} propertyName The name of the property
* @returns {undefined}
*/
function checkPropertyAccess(node, objectName, propertyName) {
if (propertyName === null) {
return;
}
const matchedObject = restrictedProperties.get(objectName);
const matchedObjectProperty = matchedObject
? matchedObject.get(propertyName)
: globallyRestrictedObjects.get(objectName);
const globalMatchedProperty =
globallyRestrictedProperties.get(propertyName);
if (matchedObjectProperty) {
const message = matchedObjectProperty.message
? ` ${matchedObjectProperty.message}`
: "";
context.report({
node,
messageId: "restrictedObjectProperty",
data: {
objectName,
propertyName,
message,
},
});
} else if (globalMatchedProperty) {
const message = globalMatchedProperty.message
? ` ${globalMatchedProperty.message}`
: "";
context.report({
node,
messageId: "restrictedProperty",
data: {
propertyName,
message,
},
});
}
}
return {
MemberExpression(node) {
checkPropertyAccess(
node,
node.object && node.object.name,
astUtils.getStaticPropertyName(node),
);
},
ObjectPattern(node) {
let objectName = null;
if (node.parent.type === "VariableDeclarator") {
if (
node.parent.init &&
node.parent.init.type === "Identifier"
) {
objectName = node.parent.init.name;
}
} else if (
node.parent.type === "AssignmentExpression" ||
node.parent.type === "AssignmentPattern"
) {
if (node.parent.right.type === "Identifier") {
objectName = node.parent.right.name;
}
}
node.properties.forEach(property => {
checkPropertyAccess(
node,
objectName,
astUtils.getStaticPropertyName(property),
);
});
},
};
},
};

View File

@@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) Roy Riojas and Jared Wray
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,24 @@
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org>

View File

@@ -0,0 +1,12 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = clone;
var _cloneNode = require("./cloneNode.js");
function clone(node) {
return (0, _cloneNode.default)(node, false);
}
//# sourceMappingURL=clone.js.map

View File

@@ -0,0 +1,235 @@
# jiti
<!-- automd:badges color=F0DB4F bundlephobia -->
[![npm version](https://img.shields.io/npm/v/jiti?color=F0DB4F)](https://npmjs.com/package/jiti)
[![npm downloads](https://img.shields.io/npm/dm/jiti?color=F0DB4F)](https://npmjs.com/package/jiti)
[![bundle size](https://img.shields.io/bundlephobia/minzip/jiti?color=F0DB4F)](https://bundlephobia.com/package/jiti)
<!-- /automd -->
> This is the active development branch. Check out [jiti/v1](https://github.com/unjs/jiti/tree/v1) for legacy v1 docs and code.
## 🌟 Used in
[Docusaurus](https://docusaurus.io/), [ESLint](https://github.com/eslint/eslint), [FormKit](https://formkit.com/), [Histoire](https://histoire.dev/), [Knip](https://knip.dev/), [Nitro](https://nitro.unjs.io/), [Nuxt](https://nuxt.com/), [PostCSS loader](https://github.com/webpack-contrib/postcss-loader), [Rsbuild](https://rsbuild.dev/), [Size Limit](https://github.com/ai/size-limit), [Slidev](https://sli.dev/), [Tailwindcss](https://tailwindcss.com/), [Tokenami](https://github.com/tokenami/tokenami), [UnoCSS](https://unocss.dev/), [WXT](https://wxt.dev/), [Winglang](https://www.winglang.io/), [Graphql code generator](https://the-guild.dev/graphql/codegen), [Lingui](https://lingui.dev/), [Scaffdog](https://scaff.dog/), [Storybook](https://storybook.js.org), [...UnJS ecosystem](https://unjs.io/), [...60M+ npm monthly downloads](https://npm.chart.dev/jiti), [...6M+ public repositories](https://github.com/unjs/jiti/network/dependents).
## ✅ Features
- Seamless TypeScript and ESM syntax support for Node.js
- Seamless interoperability between ESM and CommonJS
- Asynchronous API to replace `import()`
- Synchronous API to replace `require()` (deprecated)
- Super slim and zero dependency
- Custom resolve aliases
- Smart syntax detection to avoid extra transforms
- Node.js native `require.cache` integration
- Filesystem transpile with hard disk caches
- ESM Loader support
- JSX support (opt-in)
> [!IMPORTANT]
> To enhance compatibility, jiti `>=2.1` enabled [`interopdefault`](#interopdefault) using a new Proxy method. If you migrated to `2.0.0` earlier, this might have caused behavior changes. In case of any issues during the upgrade, please [report](https://github.com/unjs/jiti/issues) so we can investigate to solve them. 🙏🏼
## 💡 Usage
### CLI
You can use `jiti` CLI to quickly run any script with TypeScript and native ESM support!
```bash
npx jiti ./index.ts
```
### Programmatic
Initialize a jiti instance:
```js
// ESM
import { createJiti } from "jiti";
const jiti = createJiti(import.meta.url);
// CommonJS (deprecated)
const { createJiti } = require("jiti");
const jiti = createJiti(__filename);
```
Import (async) and resolve with ESM compatibility:
```js
// jiti.import(id) is similar to import(id)
const mod = await jiti.import("./path/to/file.ts");
// jiti.esmResolve(id) is similar to import.meta.resolve(id)
const resolvedPath = jiti.esmResolve("./src");
```
If you need the default export of module, you can use `jiti.import(id, { default: true })` as shortcut to `mod?.default ?? mod`.
```js
// shortcut to mod?.default ?? mod
const modDefault = await jiti.import("./path/to/file.ts", { default: true });
```
CommonJS (sync & deprecated):
```js
// jiti() is similar to require(id)
const mod = jiti("./path/to/file.ts");
// jiti.resolve() is similar to require.resolve(id)
const resolvedPath = jiti.resolve("./src");
```
You can also pass options as the second argument:
```js
const jiti = createJiti(import.meta.url, { debug: true });
```
### Register global ESM loader
You can globally register jiti using [global hooks](https://nodejs.org/api/module.html#initialize). (Important: Requires Node.js > 20)
```js
import "jiti/register";
```
Or:
```bash
node --import jiti/register index.ts
```
## 🎈 `jiti/native`
You can alias `jiti` to `jiti/native` to directly depend on runtime's [`import.meta.resolve`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import.meta/resolve) and dynamic [`import()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import) support. This allows easing up the ecosystem transition to runtime native support by giving the same API of jiti.
## ⚙️ Options
### `debug`
- Type: Boolean
- Default: `false`
- Environment variable: `JITI_DEBUG`
Enable verbose logging. You can use `JITI_DEBUG=1 <your command>` to enable it.
### `fsCache`
- Type: Boolean | String
- Default: `true`
- Environment variable: `JITI_FS_CACHE`
Filesystem source cache (enabled by default)
By default (when is `true`), jiti uses `node_modules/.cache/jiti` (if exists) or `{TMP_DIR}/jiti`.
**Note:** It is recommended that this option be enabled for better performance.
### `moduleCache`
- Type: String
- Default: `true`
- Environment variable: `JITI_MODULE_CACHE`
Runtime module cache (enabled by default).
Disabling allows editing code and importing the same module multiple times.
When enabled, jiti integrates with Node.js native CommonJS cache-store.
### `transform`
- Type: Function
- Default: Babel (lazy loaded)
Transform function. See [src/babel](./src/babel.ts) for more details
### `sourceMaps`
- Type: Boolean
- Default `false`
- Environment variable: `JITI_SOURCE_MAPS`
Add inline source map to transformed source for better debugging.
### `interopDefault`
- Type: Boolean
- Default: `true`
- Environment variable: `JITI_INTEROP_DEFAULT`
Jiti combines module exports with the `default` export using an internal Proxy to improve compatibility with mixed CJS/ESM usage. You can check the current implementation [here](https://github.com/unjs/jiti/blob/main/src/utils.ts#L105).
### `alias`
- Type: Object
- Default: -
- Environment variable: `JITI_ALIAS`
You can also pass an object to the environment variable for inline config. Example: `JITI_ALIAS='{"~/*": "./src/*"}' jiti ...`.
Custom alias map used to resolve IDs.
### `nativeModules`
- Type: Array
- Default: ['typescript']
- Environment variable: `JITI_NATIVE_MODULES`
List of modules (within `node_modules`) to always use native `require()` for them.
### `transformModules`
- Type: Array
- Default: []
- Environment variable: `JITI_TRANSFORM_MODULES`
List of modules (within `node_modules`) to transform them regardless of syntax.
### `importMeta`
Parent module's [`import.meta`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import.meta) context to use for ESM resolution. (only used for `jiti/native` import).
### `tryNative`
- Type: Boolean
- Default: Enabled if bun is detected
- Environment variable: `JITI_TRY_NATIVE`
Try to use native require and import without jiti transformations first.
### `jsx`
- Type: Boolean | {options}
- Default: `false`
- Environment Variable: `JITI_JSX`
Enable JSX support using [`@babel/plugin-transform-react-jsx`](https://babeljs.io/docs/babel-plugin-transform-react-jsx).
See [`test/fixtures/jsx`](./test/fixtures/jsx) for framework integration examples.
## Development
- Clone this repository
- Enable [Corepack](https://github.com/nodejs/corepack) using `corepack enable`
- Install dependencies using `pnpm install`
- Run `pnpm dev`
- Run `pnpm jiti ./test/path/to/file.ts`
## License
<!-- automd:contributors license=MIT author="pi0" -->
Published under the [MIT](https://github.com/unjs/jiti/blob/main/LICENSE) license.
Made by [@pi0](https://github.com/pi0) and [community](https://github.com/unjs/jiti/graphs/contributors) 💛
<br><br>
<a href="https://github.com/unjs/jiti/graphs/contributors">
<img src="https://contrib.rocks/image?repo=unjs/jiti" />
</a>
<!-- /automd -->
<!-- automd:with-automd -->

View File

@@ -0,0 +1,217 @@
/**
* @fileoverview Flat Config Array
* @author Nicholas C. Zakas
*/
"use strict";
//-----------------------------------------------------------------------------
// Requirements
//-----------------------------------------------------------------------------
const { ConfigArray, ConfigArraySymbol } = require("@eslint/config-array");
const { flatConfigSchema } = require("./flat-config-schema");
const { defaultConfig } = require("./default-config");
const { Config } = require("./config");
//-----------------------------------------------------------------------------
// Helpers
//-----------------------------------------------------------------------------
/**
* Fields that are considered metadata and not part of the config object.
*/
const META_FIELDS = new Set(["name"]);
/**
* Wraps a config error with details about where the error occurred.
* @param {Error} error The original error.
* @param {number} originalLength The original length of the config array.
* @param {number} baseLength The length of the base config.
* @returns {TypeError} The new error with details.
*/
function wrapConfigErrorWithDetails(error, originalLength, baseLength) {
let location = "user-defined";
let configIndex = error.index;
/*
* A config array is set up in this order:
* 1. Base config
* 2. Original configs
* 3. User-defined configs
* 4. CLI-defined configs
*
* So we need to adjust the index to account for the base config.
*
* - If the index is less than the base length, it's in the base config
* (as specified by `baseConfig` argument to `FlatConfigArray` constructor).
* - If the index is greater than the base length but less than the original
* length + base length, it's in the original config. The original config
* is passed to the `FlatConfigArray` constructor as the first argument.
* - Otherwise, it's in the user-defined config, which is loaded from the
* config file and merged with any command-line options.
*/
if (error.index < baseLength) {
location = "base";
} else if (error.index < originalLength + baseLength) {
location = "original";
configIndex = error.index - baseLength;
} else {
configIndex = error.index - originalLength - baseLength;
}
return new TypeError(
`${error.message.slice(0, -1)} at ${location} index ${configIndex}.`,
{ cause: error },
);
}
const originalBaseConfig = Symbol("originalBaseConfig");
const originalLength = Symbol("originalLength");
const baseLength = Symbol("baseLength");
//-----------------------------------------------------------------------------
// Exports
//-----------------------------------------------------------------------------
/**
* Represents an array containing configuration information for ESLint.
*/
class FlatConfigArray extends ConfigArray {
/**
* Creates a new instance.
* @param {*[]} configs An array of configuration information.
* @param {{basePath: string, shouldIgnore: boolean, baseConfig: FlatConfig}} options The options
* to use for the config array instance.
*/
constructor(
configs,
{ basePath, shouldIgnore = true, baseConfig = defaultConfig } = {},
) {
super(configs, {
basePath,
schema: flatConfigSchema,
});
/**
* The original length of the array before any modifications.
* @type {number}
*/
this[originalLength] = this.length;
if (baseConfig[Symbol.iterator]) {
this.unshift(...baseConfig);
} else {
this.unshift(baseConfig);
}
/**
* The length of the array after applying the base config.
* @type {number}
*/
this[baseLength] = this.length - this[originalLength];
/**
* The base config used to build the config array.
* @type {Array<FlatConfig>}
*/
this[originalBaseConfig] = baseConfig;
Object.defineProperty(this, originalBaseConfig, { writable: false });
/**
* Determines if `ignores` fields should be honored.
* If true, then all `ignores` fields are honored.
* if false, then only `ignores` fields in the baseConfig are honored.
* @type {boolean}
*/
this.shouldIgnore = shouldIgnore;
Object.defineProperty(this, "shouldIgnore", { writable: false });
}
/**
* Normalizes the array by calling the superclass method and catching/rethrowing
* any ConfigError exceptions with additional details.
* @param {any} [context] The context to use to normalize the array.
* @returns {Promise<FlatConfigArray>} A promise that resolves when the array is normalized.
*/
normalize(context) {
return super.normalize(context).catch(error => {
if (error.name === "ConfigError") {
throw wrapConfigErrorWithDetails(
error,
this[originalLength],
this[baseLength],
);
}
throw error;
});
}
/**
* Normalizes the array by calling the superclass method and catching/rethrowing
* any ConfigError exceptions with additional details.
* @param {any} [context] The context to use to normalize the array.
* @returns {FlatConfigArray} The current instance.
* @throws {TypeError} If the config is invalid.
*/
normalizeSync(context) {
try {
return super.normalizeSync(context);
} catch (error) {
if (error.name === "ConfigError") {
throw wrapConfigErrorWithDetails(
error,
this[originalLength],
this[baseLength],
);
}
throw error;
}
}
/* eslint-disable class-methods-use-this -- Desired as instance method */
/**
* Replaces a config with another config to allow us to put strings
* in the config array that will be replaced by objects before
* normalization.
* @param {Object} config The config to preprocess.
* @returns {Object} The preprocessed config.
*/
[ConfigArraySymbol.preprocessConfig](config) {
/*
* If a config object has `ignores` and no other non-meta fields, then it's an object
* for global ignores. If `shouldIgnore` is false, that object shouldn't apply,
* so we'll remove its `ignores`.
*/
if (
!this.shouldIgnore &&
!this[originalBaseConfig].includes(config) &&
config.ignores &&
Object.keys(config).filter(key => !META_FIELDS.has(key)).length ===
1
) {
/* eslint-disable-next-line no-unused-vars -- need to strip off other keys */
const { ignores, ...otherKeys } = config;
return otherKeys;
}
return config;
}
/**
* Finalizes the config by replacing plugin references with their objects
* and validating rule option schemas.
* @param {Object} config The config to finalize.
* @returns {Object} The finalized config.
* @throws {TypeError} If the config is invalid.
*/
[ConfigArraySymbol.finalizeConfig](config) {
return new Config(config);
}
/* eslint-enable class-methods-use-this -- Desired as instance method */
}
exports.FlatConfigArray = FlatConfigArray;

View File

@@ -0,0 +1 @@
module.exports={A:{A:{"2":"K D E F mC","1028":"B","1316":"A"},B:{"1":"0 9 C L M G N O P Q H R S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB I"},C:{"1":"0 9 RB SB TB UB VB WB XB YB ZB aB bB cB dB eB fB gB hB iB jB kB lB mB nB oB pB qB rB sB tB uB vB MC wB NC xB yB zB 0B 1B 2B 3B 4B 5B 6B 7B 8B 9B AC BC CC DC Q H R OC S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB I PC EC QC RC oC pC","164":"1 2 nC LC J PB K D E F A B C L M G N O P QB qC rC","516":"3 4 5 6 7 8"},D:{"1":"0 9 SB TB UB VB WB XB YB ZB aB bB cB dB eB fB gB hB iB jB kB lB mB nB oB pB qB rB sB tB uB vB MC wB NC xB yB zB 0B 1B 2B 3B 4B 5B 6B 7B 8B 9B AC BC CC DC Q H R S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB I PC EC QC RC","33":"2 3 4 5 6 7 8 RB","164":"1 J PB K D E F A B C L M G N O P QB"},E:{"1":"F A B C L M G wC TC FC GC xC yC zC UC VC HC 0C IC WC XC YC ZC aC 1C JC bC cC dC eC fC 2C KC gC hC iC jC 3C","33":"D E uC vC","164":"J PB K sC SC tC"},F:{"1":"0 1 2 3 4 5 6 7 8 O P QB RB SB TB UB VB WB XB YB ZB aB bB cB dB eB fB gB hB iB jB kB lB mB nB oB pB qB rB sB tB uB vB wB xB yB zB 0B 1B 2B 3B 4B 5B 6B 7B 8B 9B AC BC CC DC Q H R OC S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z GC","2":"F B C 4C 5C 6C 7C FC kC 8C","33":"G N"},G:{"1":"ED FD GD HD ID JD KD LD MD ND OD PD QD RD SD UC VC HC TD IC WC XC YC ZC aC UD JC bC cC dC eC fC VD KC gC hC iC jC","33":"E CD DD","164":"SC 9C lC AD BD"},H:{"1":"WD"},I:{"1":"I bD cD","164":"LC J XD YD ZD aD lC"},J:{"1":"A","164":"D"},K:{"1":"H GC","2":"A B C FC kC"},L:{"1":"I"},M:{"1":"EC"},N:{"1":"B","292":"A"},O:{"1":"HC"},P:{"1":"1 2 3 4 5 6 7 8 J dD eD fD gD hD TC iD jD kD lD mD IC JC KC nD"},Q:{"1":"oD"},R:{"1":"pD"},S:{"1":"qD rD"}},B:4,C:"CSS Flexible Box Layout Module",D:true};

View File

@@ -0,0 +1,482 @@
'use strict';
module.exports = function generate_validate(it, $keyword, $ruleType) {
var out = '';
var $async = it.schema.$async === true,
$refKeywords = it.util.schemaHasRulesExcept(it.schema, it.RULES.all, '$ref'),
$id = it.self._getId(it.schema);
if (it.opts.strictKeywords) {
var $unknownKwd = it.util.schemaUnknownRules(it.schema, it.RULES.keywords);
if ($unknownKwd) {
var $keywordsMsg = 'unknown keyword: ' + $unknownKwd;
if (it.opts.strictKeywords === 'log') it.logger.warn($keywordsMsg);
else throw new Error($keywordsMsg);
}
}
if (it.isTop) {
out += ' var validate = ';
if ($async) {
it.async = true;
out += 'async ';
}
out += 'function(data, dataPath, parentData, parentDataProperty, rootData) { \'use strict\'; ';
if ($id && (it.opts.sourceCode || it.opts.processCode)) {
out += ' ' + ('/\*# sourceURL=' + $id + ' */') + ' ';
}
}
if (typeof it.schema == 'boolean' || !($refKeywords || it.schema.$ref)) {
var $keyword = 'false schema';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $errorKeyword;
var $data = 'data' + ($dataLvl || '');
var $valid = 'valid' + $lvl;
if (it.schema === false) {
if (it.isTop) {
$breakOnError = true;
} else {
out += ' var ' + ($valid) + ' = false; ';
}
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = ''; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ($errorKeyword || 'false schema') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
if (it.opts.messages !== false) {
out += ' , message: \'boolean schema is false\' ';
}
if (it.opts.verbose) {
out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
out += ' validate.errors = [' + (__err) + ']; return false; ';
}
} else {
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
}
} else {
if (it.isTop) {
if ($async) {
out += ' return data; ';
} else {
out += ' validate.errors = null; return true; ';
}
} else {
out += ' var ' + ($valid) + ' = true; ';
}
}
if (it.isTop) {
out += ' }; return validate; ';
}
return out;
}
if (it.isTop) {
var $top = it.isTop,
$lvl = it.level = 0,
$dataLvl = it.dataLevel = 0,
$data = 'data';
it.rootId = it.resolve.fullPath(it.self._getId(it.root.schema));
it.baseId = it.baseId || it.rootId;
delete it.isTop;
it.dataPathArr = [""];
if (it.schema.default !== undefined && it.opts.useDefaults && it.opts.strictDefaults) {
var $defaultMsg = 'default is ignored in the schema root';
if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg);
else throw new Error($defaultMsg);
}
out += ' var vErrors = null; ';
out += ' var errors = 0; ';
out += ' if (rootData === undefined) rootData = data; ';
} else {
var $lvl = it.level,
$dataLvl = it.dataLevel,
$data = 'data' + ($dataLvl || '');
if ($id) it.baseId = it.resolve.url(it.baseId, $id);
if ($async && !it.async) throw new Error('async schema in sync schema');
out += ' var errs_' + ($lvl) + ' = errors;';
}
var $valid = 'valid' + $lvl,
$breakOnError = !it.opts.allErrors,
$closingBraces1 = '',
$closingBraces2 = '';
var $errorKeyword;
var $typeSchema = it.schema.type,
$typeIsArray = Array.isArray($typeSchema);
if ($typeSchema && it.opts.nullable && it.schema.nullable === true) {
if ($typeIsArray) {
if ($typeSchema.indexOf('null') == -1) $typeSchema = $typeSchema.concat('null');
} else if ($typeSchema != 'null') {
$typeSchema = [$typeSchema, 'null'];
$typeIsArray = true;
}
}
if ($typeIsArray && $typeSchema.length == 1) {
$typeSchema = $typeSchema[0];
$typeIsArray = false;
}
if (it.schema.$ref && $refKeywords) {
if (it.opts.extendRefs == 'fail') {
throw new Error('$ref: validation keywords used in schema at path "' + it.errSchemaPath + '" (see option extendRefs)');
} else if (it.opts.extendRefs !== true) {
$refKeywords = false;
it.logger.warn('$ref: keywords ignored in schema at path "' + it.errSchemaPath + '"');
}
}
if (it.schema.$comment && it.opts.$comment) {
out += ' ' + (it.RULES.all.$comment.code(it, '$comment'));
}
if ($typeSchema) {
if (it.opts.coerceTypes) {
var $coerceToTypes = it.util.coerceToTypes(it.opts.coerceTypes, $typeSchema);
}
var $rulesGroup = it.RULES.types[$typeSchema];
if ($coerceToTypes || $typeIsArray || $rulesGroup === true || ($rulesGroup && !$shouldUseGroup($rulesGroup))) {
var $schemaPath = it.schemaPath + '.type',
$errSchemaPath = it.errSchemaPath + '/type';
var $schemaPath = it.schemaPath + '.type',
$errSchemaPath = it.errSchemaPath + '/type',
$method = $typeIsArray ? 'checkDataTypes' : 'checkDataType';
out += ' if (' + (it.util[$method]($typeSchema, $data, it.opts.strictNumbers, true)) + ') { ';
if ($coerceToTypes) {
var $dataType = 'dataType' + $lvl,
$coerced = 'coerced' + $lvl;
out += ' var ' + ($dataType) + ' = typeof ' + ($data) + '; var ' + ($coerced) + ' = undefined; ';
if (it.opts.coerceTypes == 'array') {
out += ' if (' + ($dataType) + ' == \'object\' && Array.isArray(' + ($data) + ') && ' + ($data) + '.length == 1) { ' + ($data) + ' = ' + ($data) + '[0]; ' + ($dataType) + ' = typeof ' + ($data) + '; if (' + (it.util.checkDataType(it.schema.type, $data, it.opts.strictNumbers)) + ') ' + ($coerced) + ' = ' + ($data) + '; } ';
}
out += ' if (' + ($coerced) + ' !== undefined) ; ';
var arr1 = $coerceToTypes;
if (arr1) {
var $type, $i = -1,
l1 = arr1.length - 1;
while ($i < l1) {
$type = arr1[$i += 1];
if ($type == 'string') {
out += ' else if (' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\') ' + ($coerced) + ' = \'\' + ' + ($data) + '; else if (' + ($data) + ' === null) ' + ($coerced) + ' = \'\'; ';
} else if ($type == 'number' || $type == 'integer') {
out += ' else if (' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' === null || (' + ($dataType) + ' == \'string\' && ' + ($data) + ' && ' + ($data) + ' == +' + ($data) + ' ';
if ($type == 'integer') {
out += ' && !(' + ($data) + ' % 1)';
}
out += ')) ' + ($coerced) + ' = +' + ($data) + '; ';
} else if ($type == 'boolean') {
out += ' else if (' + ($data) + ' === \'false\' || ' + ($data) + ' === 0 || ' + ($data) + ' === null) ' + ($coerced) + ' = false; else if (' + ($data) + ' === \'true\' || ' + ($data) + ' === 1) ' + ($coerced) + ' = true; ';
} else if ($type == 'null') {
out += ' else if (' + ($data) + ' === \'\' || ' + ($data) + ' === 0 || ' + ($data) + ' === false) ' + ($coerced) + ' = null; ';
} else if (it.opts.coerceTypes == 'array' && $type == 'array') {
out += ' else if (' + ($dataType) + ' == \'string\' || ' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' == null) ' + ($coerced) + ' = [' + ($data) + ']; ';
}
}
}
out += ' else { ';
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = ''; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \'';
if ($typeIsArray) {
out += '' + ($typeSchema.join(","));
} else {
out += '' + ($typeSchema);
}
out += '\' } ';
if (it.opts.messages !== false) {
out += ' , message: \'should be ';
if ($typeIsArray) {
out += '' + ($typeSchema.join(","));
} else {
out += '' + ($typeSchema);
}
out += '\' ';
}
if (it.opts.verbose) {
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
out += ' validate.errors = [' + (__err) + ']; return false; ';
}
} else {
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
}
out += ' } if (' + ($coerced) + ' !== undefined) { ';
var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData',
$parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty';
out += ' ' + ($data) + ' = ' + ($coerced) + '; ';
if (!$dataLvl) {
out += 'if (' + ($parentData) + ' !== undefined)';
}
out += ' ' + ($parentData) + '[' + ($parentDataProperty) + '] = ' + ($coerced) + '; } ';
} else {
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = ''; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \'';
if ($typeIsArray) {
out += '' + ($typeSchema.join(","));
} else {
out += '' + ($typeSchema);
}
out += '\' } ';
if (it.opts.messages !== false) {
out += ' , message: \'should be ';
if ($typeIsArray) {
out += '' + ($typeSchema.join(","));
} else {
out += '' + ($typeSchema);
}
out += '\' ';
}
if (it.opts.verbose) {
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
out += ' validate.errors = [' + (__err) + ']; return false; ';
}
} else {
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
}
}
out += ' } ';
}
}
if (it.schema.$ref && !$refKeywords) {
out += ' ' + (it.RULES.all.$ref.code(it, '$ref')) + ' ';
if ($breakOnError) {
out += ' } if (errors === ';
if ($top) {
out += '0';
} else {
out += 'errs_' + ($lvl);
}
out += ') { ';
$closingBraces2 += '}';
}
} else {
var arr2 = it.RULES;
if (arr2) {
var $rulesGroup, i2 = -1,
l2 = arr2.length - 1;
while (i2 < l2) {
$rulesGroup = arr2[i2 += 1];
if ($shouldUseGroup($rulesGroup)) {
if ($rulesGroup.type) {
out += ' if (' + (it.util.checkDataType($rulesGroup.type, $data, it.opts.strictNumbers)) + ') { ';
}
if (it.opts.useDefaults) {
if ($rulesGroup.type == 'object' && it.schema.properties) {
var $schema = it.schema.properties,
$schemaKeys = Object.keys($schema);
var arr3 = $schemaKeys;
if (arr3) {
var $propertyKey, i3 = -1,
l3 = arr3.length - 1;
while (i3 < l3) {
$propertyKey = arr3[i3 += 1];
var $sch = $schema[$propertyKey];
if ($sch.default !== undefined) {
var $passData = $data + it.util.getProperty($propertyKey);
if (it.compositeRule) {
if (it.opts.strictDefaults) {
var $defaultMsg = 'default is ignored for: ' + $passData;
if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg);
else throw new Error($defaultMsg);
}
} else {
out += ' if (' + ($passData) + ' === undefined ';
if (it.opts.useDefaults == 'empty') {
out += ' || ' + ($passData) + ' === null || ' + ($passData) + ' === \'\' ';
}
out += ' ) ' + ($passData) + ' = ';
if (it.opts.useDefaults == 'shared') {
out += ' ' + (it.useDefault($sch.default)) + ' ';
} else {
out += ' ' + (JSON.stringify($sch.default)) + ' ';
}
out += '; ';
}
}
}
}
} else if ($rulesGroup.type == 'array' && Array.isArray(it.schema.items)) {
var arr4 = it.schema.items;
if (arr4) {
var $sch, $i = -1,
l4 = arr4.length - 1;
while ($i < l4) {
$sch = arr4[$i += 1];
if ($sch.default !== undefined) {
var $passData = $data + '[' + $i + ']';
if (it.compositeRule) {
if (it.opts.strictDefaults) {
var $defaultMsg = 'default is ignored for: ' + $passData;
if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg);
else throw new Error($defaultMsg);
}
} else {
out += ' if (' + ($passData) + ' === undefined ';
if (it.opts.useDefaults == 'empty') {
out += ' || ' + ($passData) + ' === null || ' + ($passData) + ' === \'\' ';
}
out += ' ) ' + ($passData) + ' = ';
if (it.opts.useDefaults == 'shared') {
out += ' ' + (it.useDefault($sch.default)) + ' ';
} else {
out += ' ' + (JSON.stringify($sch.default)) + ' ';
}
out += '; ';
}
}
}
}
}
}
var arr5 = $rulesGroup.rules;
if (arr5) {
var $rule, i5 = -1,
l5 = arr5.length - 1;
while (i5 < l5) {
$rule = arr5[i5 += 1];
if ($shouldUseRule($rule)) {
var $code = $rule.code(it, $rule.keyword, $rulesGroup.type);
if ($code) {
out += ' ' + ($code) + ' ';
if ($breakOnError) {
$closingBraces1 += '}';
}
}
}
}
}
if ($breakOnError) {
out += ' ' + ($closingBraces1) + ' ';
$closingBraces1 = '';
}
if ($rulesGroup.type) {
out += ' } ';
if ($typeSchema && $typeSchema === $rulesGroup.type && !$coerceToTypes) {
out += ' else { ';
var $schemaPath = it.schemaPath + '.type',
$errSchemaPath = it.errSchemaPath + '/type';
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = ''; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \'';
if ($typeIsArray) {
out += '' + ($typeSchema.join(","));
} else {
out += '' + ($typeSchema);
}
out += '\' } ';
if (it.opts.messages !== false) {
out += ' , message: \'should be ';
if ($typeIsArray) {
out += '' + ($typeSchema.join(","));
} else {
out += '' + ($typeSchema);
}
out += '\' ';
}
if (it.opts.verbose) {
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
out += ' validate.errors = [' + (__err) + ']; return false; ';
}
} else {
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
}
out += ' } ';
}
}
if ($breakOnError) {
out += ' if (errors === ';
if ($top) {
out += '0';
} else {
out += 'errs_' + ($lvl);
}
out += ') { ';
$closingBraces2 += '}';
}
}
}
}
}
if ($breakOnError) {
out += ' ' + ($closingBraces2) + ' ';
}
if ($top) {
if ($async) {
out += ' if (errors === 0) return data; ';
out += ' else throw new ValidationError(vErrors); ';
} else {
out += ' validate.errors = vErrors; ';
out += ' return errors === 0; ';
}
out += ' }; return validate;';
} else {
out += ' var ' + ($valid) + ' = errors === errs_' + ($lvl) + ';';
}
function $shouldUseGroup($rulesGroup) {
var rules = $rulesGroup.rules;
for (var i = 0; i < rules.length; i++)
if ($shouldUseRule(rules[i])) return true;
}
function $shouldUseRule($rule) {
return it.schema[$rule.keyword] !== undefined || ($rule.implements && $ruleImplementsSomeKeyword($rule));
}
function $ruleImplementsSomeKeyword($rule) {
var impl = $rule.implements;
for (var i = 0; i < impl.length; i++)
if (it.schema[impl[i]] !== undefined) return true;
}
return out;
}

View File

@@ -0,0 +1 @@
module.exports={A:{A:{"2":"K D E F A B mC"},B:{"1":"0 9 C L M G N O P Q H R S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB I"},C:{"1":"0 7 8 9 RB SB TB UB VB WB XB YB ZB aB bB cB dB eB fB gB hB iB jB kB lB mB nB oB pB qB rB sB tB uB vB MC wB NC xB yB zB 0B 1B 2B 3B 4B 5B 6B 7B 8B 9B AC BC CC DC Q H R OC S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB I PC EC QC RC oC pC","2":"1 2 3 4 5 6 nC LC J PB K D E F A B C L M G N O P QB qC rC"},D:{"1":"0 9 VB WB XB YB ZB aB bB cB dB eB fB gB hB iB jB kB lB mB nB oB pB qB rB sB tB uB vB MC wB NC xB yB zB 0B 1B 2B 3B 4B 5B 6B 7B 8B 9B AC BC CC DC Q H R S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB I PC EC QC RC","2":"1 2 3 J PB K D E F A B C L M G N O P QB","130":"4 5 6 7 8 RB SB TB UB"},E:{"1":"E F A B C L M G vC wC TC FC GC xC yC zC UC VC HC 0C IC WC XC YC ZC aC 1C JC bC cC dC eC fC 2C KC gC hC iC jC 3C","2":"J PB K sC SC tC uC","130":"D"},F:{"1":"0 1 2 3 4 5 6 7 8 QB RB SB TB UB VB WB XB YB ZB aB bB cB dB eB fB gB hB iB jB kB lB mB nB oB pB qB rB sB tB uB vB wB xB yB zB 0B 1B 2B 3B 4B 5B 6B 7B 8B 9B AC BC CC DC Q H R OC S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z","2":"F B C 4C 5C 6C 7C FC kC 8C GC","130":"G N O P"},G:{"1":"E DD ED FD GD HD ID JD KD LD MD ND OD PD QD RD SD UC VC HC TD IC WC XC YC ZC aC UD JC bC cC dC eC fC VD KC gC hC iC jC","2":"SC 9C lC AD BD","130":"CD"},H:{"2":"WD"},I:{"1":"I cD","2":"LC J XD YD ZD aD lC","130":"bD"},J:{"2":"D","130":"A"},K:{"1":"H","2":"A B C FC kC GC"},L:{"1":"I"},M:{"1":"EC"},N:{"2":"A B"},O:{"1":"HC"},P:{"1":"1 2 3 4 5 6 7 8 J dD eD fD gD hD TC iD jD kD lD mD IC JC KC nD"},Q:{"1":"oD"},R:{"1":"pD"},S:{"1":"qD rD"}},B:1,C:"URL API",D:true};

View File

@@ -0,0 +1,27 @@
{
"name": "scheduler",
"version": "0.26.0",
"description": "Cooperative scheduler for the browser environment.",
"repository": {
"type": "git",
"url": "https://github.com/facebook/react.git",
"directory": "packages/scheduler"
},
"license": "MIT",
"keywords": [
"react"
],
"bugs": {
"url": "https://github.com/facebook/react/issues"
},
"homepage": "https://react.dev/",
"files": [
"LICENSE",
"README.md",
"index.js",
"index.native.js",
"unstable_mock.js",
"unstable_post_task.js",
"cjs/"
]
}

View File

@@ -0,0 +1,168 @@
'use strict';
module.exports = function generate_dependencies(it, $keyword, $ruleType) {
var out = ' ';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $data = 'data' + ($dataLvl || '');
var $errs = 'errs__' + $lvl;
var $it = it.util.copy(it);
var $closingBraces = '';
$it.level++;
var $nextValid = 'valid' + $it.level;
var $schemaDeps = {},
$propertyDeps = {},
$ownProperties = it.opts.ownProperties;
for ($property in $schema) {
if ($property == '__proto__') continue;
var $sch = $schema[$property];
var $deps = Array.isArray($sch) ? $propertyDeps : $schemaDeps;
$deps[$property] = $sch;
}
out += 'var ' + ($errs) + ' = errors;';
var $currentErrorPath = it.errorPath;
out += 'var missing' + ($lvl) + ';';
for (var $property in $propertyDeps) {
$deps = $propertyDeps[$property];
if ($deps.length) {
out += ' if ( ' + ($data) + (it.util.getProperty($property)) + ' !== undefined ';
if ($ownProperties) {
out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($property)) + '\') ';
}
if ($breakOnError) {
out += ' && ( ';
var arr1 = $deps;
if (arr1) {
var $propertyKey, $i = -1,
l1 = arr1.length - 1;
while ($i < l1) {
$propertyKey = arr1[$i += 1];
if ($i) {
out += ' || ';
}
var $prop = it.util.getProperty($propertyKey),
$useData = $data + $prop;
out += ' ( ( ' + ($useData) + ' === undefined ';
if ($ownProperties) {
out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
}
out += ') && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop)) + ') ) ';
}
}
out += ')) { ';
var $propertyPath = 'missing' + $lvl,
$missingProperty = '\' + ' + $propertyPath + ' + \'';
if (it.opts._errorDataPathProperty) {
it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath;
}
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = ''; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ('dependencies') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { property: \'' + (it.util.escapeQuotes($property)) + '\', missingProperty: \'' + ($missingProperty) + '\', depsCount: ' + ($deps.length) + ', deps: \'' + (it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", "))) + '\' } ';
if (it.opts.messages !== false) {
out += ' , message: \'should have ';
if ($deps.length == 1) {
out += 'property ' + (it.util.escapeQuotes($deps[0]));
} else {
out += 'properties ' + (it.util.escapeQuotes($deps.join(", ")));
}
out += ' when property ' + (it.util.escapeQuotes($property)) + ' is present\' ';
}
if (it.opts.verbose) {
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
out += ' validate.errors = [' + (__err) + ']; return false; ';
}
} else {
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
}
} else {
out += ' ) { ';
var arr2 = $deps;
if (arr2) {
var $propertyKey, i2 = -1,
l2 = arr2.length - 1;
while (i2 < l2) {
$propertyKey = arr2[i2 += 1];
var $prop = it.util.getProperty($propertyKey),
$missingProperty = it.util.escapeQuotes($propertyKey),
$useData = $data + $prop;
if (it.opts._errorDataPathProperty) {
it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);
}
out += ' if ( ' + ($useData) + ' === undefined ';
if ($ownProperties) {
out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
}
out += ') { var err = '; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ('dependencies') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { property: \'' + (it.util.escapeQuotes($property)) + '\', missingProperty: \'' + ($missingProperty) + '\', depsCount: ' + ($deps.length) + ', deps: \'' + (it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", "))) + '\' } ';
if (it.opts.messages !== false) {
out += ' , message: \'should have ';
if ($deps.length == 1) {
out += 'property ' + (it.util.escapeQuotes($deps[0]));
} else {
out += 'properties ' + (it.util.escapeQuotes($deps.join(", ")));
}
out += ' when property ' + (it.util.escapeQuotes($property)) + ' is present\' ';
}
if (it.opts.verbose) {
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } ';
}
}
}
out += ' } ';
if ($breakOnError) {
$closingBraces += '}';
out += ' else { ';
}
}
}
it.errorPath = $currentErrorPath;
var $currentBaseId = $it.baseId;
for (var $property in $schemaDeps) {
var $sch = $schemaDeps[$property];
if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) {
out += ' ' + ($nextValid) + ' = true; if ( ' + ($data) + (it.util.getProperty($property)) + ' !== undefined ';
if ($ownProperties) {
out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($property)) + '\') ';
}
out += ') { ';
$it.schema = $sch;
$it.schemaPath = $schemaPath + it.util.getProperty($property);
$it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($property);
out += ' ' + (it.validate($it)) + ' ';
$it.baseId = $currentBaseId;
out += ' } ';
if ($breakOnError) {
out += ' if (' + ($nextValid) + ') { ';
$closingBraces += '}';
}
}
}
if ($breakOnError) {
out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
}
return out;
}

View File

@@ -0,0 +1,29 @@
/**
* @fileoverview APIs that are not officially supported by ESLint.
* These APIs may change or be removed at any time. Use at your
* own risk.
* @author Nicholas C. Zakas
*/
"use strict";
//-----------------------------------------------------------------------------
// Requirements
//-----------------------------------------------------------------------------
const { FileEnumerator } = require("./cli-engine/file-enumerator");
const { ESLint: FlatESLint, shouldUseFlatConfig } = require("./eslint/eslint");
const { LegacyESLint } = require("./eslint/legacy-eslint");
const builtinRules = require("./rules");
//-----------------------------------------------------------------------------
// Exports
//-----------------------------------------------------------------------------
module.exports = {
builtinRules,
FlatESLint,
shouldUseFlatConfig,
FileEnumerator,
LegacyESLint,
};

View File

@@ -0,0 +1,8 @@
import { AnyRouter, Constrain, OptionalStructuralSharing, ValidateJSON } from '@tanstack/router-core';
export type DefaultStructuralSharingEnabled<TRouter extends AnyRouter> = boolean extends TRouter['options']['defaultStructuralSharing'] ? false : NonNullable<TRouter['options']['defaultStructuralSharing']>;
export interface RequiredStructuralSharing<TStructuralSharing, TConstraint> {
readonly structuralSharing: Constrain<TStructuralSharing, TConstraint>;
}
export type StructuralSharingOption<TRouter extends AnyRouter, TSelected, TStructuralSharing> = unknown extends TSelected ? OptionalStructuralSharing<TStructuralSharing, boolean> : unknown extends TRouter['routeTree'] ? OptionalStructuralSharing<TStructuralSharing, boolean> : TSelected extends ValidateJSON<TSelected> ? OptionalStructuralSharing<TStructuralSharing, boolean> : DefaultStructuralSharingEnabled<TRouter> extends true ? RequiredStructuralSharing<TStructuralSharing, false> : OptionalStructuralSharing<TStructuralSharing, false>;
export type StructuralSharingEnabled<TRouter extends AnyRouter, TStructuralSharing> = boolean extends TStructuralSharing ? DefaultStructuralSharingEnabled<TRouter> : TStructuralSharing;
export type ValidateSelected<TRouter extends AnyRouter, TSelected, TStructuralSharing> = StructuralSharingEnabled<TRouter, TStructuralSharing> extends true ? ValidateJSON<TSelected> : TSelected;

View File

@@ -0,0 +1,581 @@
import { Store } from '@tanstack/store';
import { SearchParser, SearchSerializer } from './searchParams.js';
import { AnyRedirect, ResolvedRedirect } from './redirect.js';
import { HistoryLocation, HistoryState, ParsedHistoryState, RouterHistory } from '@tanstack/history';
import { ControlledPromise, NoInfer, NonNullableUpdater, PickAsRequired, Updater } from './utils.js';
import { ParsedLocation } from './location.js';
import { DeferredPromiseState } from './defer.js';
import { AnyContext, AnyRoute, AnyRouteWithContext, MakeRemountDepsOptionsUnion, RouteMask } from './route.js';
import { FullSearchSchema, RouteById, RoutePaths, RoutesById, RoutesByPath } from './routeInfo.js';
import { AnyRouteMatch, MakeRouteMatch, MakeRouteMatchUnion, MatchRouteOptions } from './Matches.js';
import { BuildLocationFn, CommitLocationOptions, NavigateFn } from './RouterProvider.js';
import { Manifest } from './manifest.js';
import { StartSerializer } from './serializer.js';
import { AnySchema } from './validators.js';
import { NavigateOptions, ResolveRelativePath, ToOptions } from './link.js';
import { NotFoundError } from './not-found.js';
declare global {
interface Window {
__TSR_ROUTER__?: AnyRouter;
}
}
export type ControllablePromise<T = any> = Promise<T> & {
resolve: (value: T) => void;
reject: (value?: any) => void;
};
export type InjectedHtmlEntry = Promise<string>;
export interface Register {
}
export type RegisteredRouter = Register extends {
router: infer TRouter extends AnyRouter;
} ? TRouter : AnyRouter;
export type DefaultRemountDepsFn<TRouteTree extends AnyRoute> = (opts: MakeRemountDepsOptionsUnion<TRouteTree>) => any;
export interface DefaultRouterOptionsExtensions {
}
export interface RouterOptionsExtensions extends DefaultRouterOptionsExtensions {
}
export interface RouterOptions<TRouteTree extends AnyRoute, TTrailingSlashOption extends TrailingSlashOption, TDefaultStructuralSharingOption extends boolean = false, TRouterHistory extends RouterHistory = RouterHistory, TDehydrated extends Record<string, any> = Record<string, any>> extends RouterOptionsExtensions {
/**
* The history object that will be used to manage the browser history.
*
* If not provided, a new createBrowserHistory instance will be created and used.
*
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#history-property)
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/history-types)
*/
history?: TRouterHistory;
/**
* A function that will be used to stringify search params when generating links.
*
* @default defaultStringifySearch
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#stringifysearch-method)
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/custom-search-param-serialization)
*/
stringifySearch?: SearchSerializer;
/**
* A function that will be used to parse search params when parsing the current location.
*
* @default defaultParseSearch
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#parsesearch-method)
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/custom-search-param-serialization)
*/
parseSearch?: SearchParser;
/**
* If `false`, routes will not be preloaded by default in any way.
*
* If `'intent'`, routes will be preloaded by default when the user hovers over a link or a `touchstart` event is detected on a `<Link>`.
*
* If `'viewport'`, routes will be preloaded by default when they are within the viewport.
*
* @default false
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaultpreload-property)
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/preloading)
*/
defaultPreload?: false | 'intent' | 'viewport' | 'render';
/**
* The delay in milliseconds that a route must be hovered over or touched before it is preloaded.
*
* @default 50
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaultpreloaddelay-property)
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/preloading#preload-delay)
*/
defaultPreloadDelay?: number;
/**
* The default `pendingMs` a route should use if no pendingMs is provided.
*
* @default 1000
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaultpendingms-property)
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/data-loading#avoiding-pending-component-flash)
*/
defaultPendingMs?: number;
/**
* The default `pendingMinMs` a route should use if no pendingMinMs is provided.
*
* @default 500
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaultpendingminms-property)
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/data-loading#avoiding-pending-component-flash)
*/
defaultPendingMinMs?: number;
/**
* The default `staleTime` a route should use if no staleTime is provided. This is the time in milliseconds that a route will be considered fresh.
*
* @default 0
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaultstaletime-property)
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/data-loading#key-options)
*/
defaultStaleTime?: number;
/**
* The default `preloadStaleTime` a route should use if no preloadStaleTime is provided.
*
* @default 30_000 `(30 seconds)`
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaultpreloadstaletime-property)
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/preloading)
*/
defaultPreloadStaleTime?: number;
/**
* The default `defaultPreloadGcTime` a route should use if no preloadGcTime is provided.
*
* @default 1_800_000 `(30 minutes)`
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaultpreloadgctime-property)
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/preloading)
*/
defaultPreloadGcTime?: number;
/**
* If `true`, route navigations will called using `document.startViewTransition()`.
*
* If the browser does not support this api, this option will be ignored.
*
* See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Document/startViewTransition) for more information on how this function works.
*
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaultviewtransition-property)
*/
defaultViewTransition?: boolean | ViewTransitionOptions;
/**
* The default `hashScrollIntoView` a route should use if no hashScrollIntoView is provided while navigating
*
* See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView) for more information on `ScrollIntoViewOptions`.
*
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaulthashscrollintoview-property)
*/
defaultHashScrollIntoView?: boolean | ScrollIntoViewOptions;
/**
* @default 'fuzzy'
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#notfoundmode-property)
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/not-found-errors#the-notfoundmode-option)
*/
notFoundMode?: 'root' | 'fuzzy';
/**
* The default `gcTime` a route should use if no gcTime is provided.
*
* @default 1_800_000 `(30 minutes)`
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaultgctime-property)
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/data-loading#key-options)
*/
defaultGcTime?: number;
/**
* If `true`, all routes will be matched as case-sensitive.
*
* @default false
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#casesensitive-property)
*/
caseSensitive?: boolean;
/**
*
* The route tree that will be used to configure the router instance.
*
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#routetree-property)
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/routing/route-trees)
*/
routeTree?: TRouteTree;
/**
* The basepath for then entire router. This is useful for mounting a router instance at a subpath.
*
* @default '/'
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#basepath-property)
*/
basepath?: string;
/**
* The root context that will be provided to all routes in the route tree.
*
* This can be used to provide a context to all routes in the tree without having to provide it to each route individually.
*
* Optional or required if the root route was created with [`createRootRouteWithContext()`](https://tanstack.com/router/latest/docs/framework/react/api/router/createRootRouteWithContextFunction).
*
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#context-property)
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/router-context)
*/
context?: InferRouterContext<TRouteTree>;
/**
* A function that will be called when the router is dehydrated.
*
* The return value of this function will be serialized and stored in the router's dehydrated state.
*
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#dehydrate-method)
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/external-data-loading#critical-dehydrationhydration)
*/
dehydrate?: () => TDehydrated;
/**
* A function that will be called when the router is hydrated.
*
* The return value of this function will be serialized and stored in the router's dehydrated state.
*
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#hydrate-method)
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/external-data-loading#critical-dehydrationhydration)
*/
hydrate?: (dehydrated: TDehydrated) => void;
/**
* An array of route masks that will be used to mask routes in the route tree.
*
* Route masking is when you display a route at a different path than the one it is configured to match, like a modal popup that when shared will unmask to the modal's content instead of the modal's context.
*
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#routemasks-property)
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/route-masking)
*/
routeMasks?: Array<RouteMask<TRouteTree>>;
/**
* If `true`, route masks will, by default, be removed when the page is reloaded.
*
* This can be overridden on a per-mask basis by setting the `unmaskOnReload` option on the mask, or on a per-navigation basis by setting the `unmaskOnReload` option in the `Navigate` options.
*
* @default false
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#unmaskonreload-property)
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/route-masking#unmasking-on-page-reload)
*/
unmaskOnReload?: boolean;
/**
* Use `notFoundComponent` instead.
*
* @deprecated
* See https://tanstack.com/router/v1/docs/guide/not-found-errors#migrating-from-notfoundroute for more info.
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#notfoundroute-property)
*/
notFoundRoute?: AnyRoute;
/**
* Configures how trailing slashes are treated.
*
* - `'always'` will add a trailing slash if not present
* - `'never'` will remove the trailing slash if present
* - `'preserve'` will not modify the trailing slash.
*
* @default 'never'
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#trailingslash-property)
*/
trailingSlash?: TTrailingSlashOption;
/**
* While usually automatic, sometimes it can be useful to force the router into a server-side state, e.g. when using the router in a non-browser environment that has access to a global.document object.
*
* @default typeof document !== 'undefined'
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#isserver-property)
*/
isServer?: boolean;
defaultSsr?: boolean;
search?: {
/**
* Configures how unknown search params (= not returned by any `validateSearch`) are treated.
*
* @default false
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#search.strict-property)
*/
strict?: boolean;
};
/**
* Configures whether structural sharing is enabled by default for fine-grained selectors.
*
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaultstructuralsharing-property)
*/
defaultStructuralSharing?: TDefaultStructuralSharingOption;
/**
* Configures which URI characters are allowed in path params that would ordinarily be escaped by encodeURIComponent.
*
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#pathparamsallowedcharacters-property)
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/path-params#allowed-characters)
*/
pathParamsAllowedCharacters?: Array<';' | ':' | '@' | '&' | '=' | '+' | '$' | ','>;
defaultRemountDeps?: DefaultRemountDepsFn<TRouteTree>;
/**
* If `true`, scroll restoration will be enabled
*
* @default false
*/
scrollRestoration?: boolean;
/**
* A function that will be called to get the key for the scroll restoration cache.
*
* @default (location) => location.href
*/
getScrollRestorationKey?: (location: ParsedLocation) => string;
/**
* The default behavior for scroll restoration.
*
* @default 'auto'
*/
scrollRestorationBehavior?: ScrollBehavior;
/**
* An array of selectors that will be used to scroll to the top of the page in addition to `window`
*
* @default ['window']
*/
scrollToTopSelectors?: Array<string>;
}
export interface RouterState<in out TRouteTree extends AnyRoute = AnyRoute, in out TRouteMatch = MakeRouteMatchUnion> {
status: 'pending' | 'idle';
loadedAt: number;
isLoading: boolean;
isTransitioning: boolean;
matches: Array<TRouteMatch>;
pendingMatches?: Array<TRouteMatch>;
cachedMatches: Array<TRouteMatch>;
location: ParsedLocation<FullSearchSchema<TRouteTree>>;
resolvedLocation?: ParsedLocation<FullSearchSchema<TRouteTree>>;
statusCode: number;
redirect?: ResolvedRedirect;
}
export interface BuildNextOptions {
to?: string | number | null;
params?: true | Updater<unknown>;
search?: true | Updater<unknown>;
hash?: true | Updater<string>;
state?: true | NonNullableUpdater<ParsedHistoryState, HistoryState>;
mask?: {
to?: string | number | null;
params?: true | Updater<unknown>;
search?: true | Updater<unknown>;
hash?: true | Updater<string>;
state?: true | NonNullableUpdater<ParsedHistoryState, HistoryState>;
unmaskOnReload?: boolean;
};
from?: string;
_fromLocation?: ParsedLocation;
href?: string;
}
type NavigationEventInfo = {
fromLocation?: ParsedLocation;
toLocation: ParsedLocation;
pathChanged: boolean;
hrefChanged: boolean;
hashChanged: boolean;
};
export type RouterEvents = {
onBeforeNavigate: {
type: 'onBeforeNavigate';
} & NavigationEventInfo;
onBeforeLoad: {
type: 'onBeforeLoad';
} & NavigationEventInfo;
onLoad: {
type: 'onLoad';
} & NavigationEventInfo;
onResolved: {
type: 'onResolved';
} & NavigationEventInfo;
onBeforeRouteMount: {
type: 'onBeforeRouteMount';
} & NavigationEventInfo;
onInjectedHtml: {
type: 'onInjectedHtml';
promise: Promise<string>;
};
onRendered: {
type: 'onRendered';
} & NavigationEventInfo;
};
export type RouterEvent = RouterEvents[keyof RouterEvents];
export type ListenerFn<TEvent extends RouterEvent> = (event: TEvent) => void;
export type RouterListener<TRouterEvent extends RouterEvent> = {
eventType: TRouterEvent['type'];
fn: ListenerFn<TRouterEvent>;
};
export interface MatchRoutesOpts {
preload?: boolean;
throwOnError?: boolean;
_buildLocation?: boolean;
dest?: BuildNextOptions;
}
export type InferRouterContext<TRouteTree extends AnyRoute> = TRouteTree['types']['routerContext'];
export type RouterContextOptions<TRouteTree extends AnyRoute> = AnyContext extends InferRouterContext<TRouteTree> ? {
context?: InferRouterContext<TRouteTree>;
} : {
context: InferRouterContext<TRouteTree>;
};
export type RouterConstructorOptions<TRouteTree extends AnyRoute, TTrailingSlashOption extends TrailingSlashOption, TDefaultStructuralSharingOption extends boolean, TRouterHistory extends RouterHistory, TDehydrated extends Record<string, any>> = Omit<RouterOptions<TRouteTree, TTrailingSlashOption, TDefaultStructuralSharingOption, TRouterHistory, TDehydrated>, 'context'> & RouterContextOptions<TRouteTree>;
export interface RouterErrorSerializer<TSerializedError> {
serialize: (err: unknown) => TSerializedError;
deserialize: (err: TSerializedError) => unknown;
}
export interface MatchedRoutesResult {
matchedRoutes: Array<AnyRoute>;
routeParams: Record<string, string>;
}
export type PreloadRouteFn<TRouteTree extends AnyRoute, TTrailingSlashOption extends TrailingSlashOption, TDefaultStructuralSharingOption extends boolean, TRouterHistory extends RouterHistory> = <TFrom extends RoutePaths<TRouteTree> | string = string, TTo extends string | undefined = undefined, TMaskFrom extends RoutePaths<TRouteTree> | string = TFrom, TMaskTo extends string = ''>(opts: NavigateOptions<RouterCore<TRouteTree, TTrailingSlashOption, TDefaultStructuralSharingOption, TRouterHistory>, TFrom, TTo, TMaskFrom, TMaskTo>) => Promise<Array<AnyRouteMatch> | undefined>;
export type MatchRouteFn<TRouteTree extends AnyRoute, TTrailingSlashOption extends TrailingSlashOption, TDefaultStructuralSharingOption extends boolean, TRouterHistory extends RouterHistory> = <TFrom extends RoutePaths<TRouteTree> = '/', TTo extends string | undefined = undefined, TResolved = ResolveRelativePath<TFrom, NoInfer<TTo>>>(location: ToOptions<RouterCore<TRouteTree, TTrailingSlashOption, TDefaultStructuralSharingOption, TRouterHistory>, TFrom, TTo>, opts?: MatchRouteOptions) => false | RouteById<TRouteTree, TResolved>['types']['allParams'];
export type UpdateFn<TRouteTree extends AnyRoute, TTrailingSlashOption extends TrailingSlashOption, TDefaultStructuralSharingOption extends boolean, TRouterHistory extends RouterHistory, TDehydrated extends Record<string, any>> = (newOptions: RouterConstructorOptions<TRouteTree, TTrailingSlashOption, TDefaultStructuralSharingOption, TRouterHistory, TDehydrated>) => void;
export type InvalidateFn<TRouter extends AnyRouter> = (opts?: {
filter?: (d: MakeRouteMatchUnion<TRouter>) => boolean;
sync?: boolean;
}) => Promise<void>;
export type ParseLocationFn<TRouteTree extends AnyRoute> = (previousLocation?: ParsedLocation<FullSearchSchema<TRouteTree>>, locationToParse?: HistoryLocation) => ParsedLocation<FullSearchSchema<TRouteTree>>;
export type GetMatchRoutesFn = (next: ParsedLocation, dest?: BuildNextOptions) => {
matchedRoutes: Array<AnyRoute>;
routeParams: Record<string, string>;
foundRoute: AnyRoute | undefined;
};
export type EmitFn = (routerEvent: RouterEvent) => void;
export type LoadFn = (opts?: {
sync?: boolean;
}) => Promise<void>;
export type CommitLocationFn = ({ viewTransition, ignoreBlocker, ...next }: ParsedLocation & CommitLocationOptions) => Promise<void>;
export type StartTransitionFn = (fn: () => void) => void;
export type SubscribeFn = <TType extends keyof RouterEvents>(eventType: TType, fn: ListenerFn<RouterEvents[TType]>) => () => void;
export interface MatchRoutesFn {
(pathname: string, locationSearch: AnySchema, opts?: MatchRoutesOpts): Array<AnyRouteMatch>;
(next: ParsedLocation, opts?: MatchRoutesOpts): Array<AnyRouteMatch>;
(pathnameOrNext: string | ParsedLocation, locationSearchOrOpts?: AnySchema | MatchRoutesOpts, opts?: MatchRoutesOpts): Array<AnyRouteMatch>;
}
export type GetMatchFn = (matchId: string) => AnyRouteMatch | undefined;
export type UpdateMatchFn = (id: string, updater: (match: AnyRouteMatch) => AnyRouteMatch) => AnyRouteMatch;
export type LoadRouteChunkFn = (route: AnyRoute) => Promise<Array<void>>;
export type ResolveRedirect = (err: AnyRedirect) => ResolvedRedirect;
export type ClearCacheFn<TRouter extends AnyRouter> = (opts?: {
filter?: (d: MakeRouteMatchUnion<TRouter>) => boolean;
}) => void;
export interface ServerSrr {
injectedHtml: Array<InjectedHtmlEntry>;
injectHtml: (getHtml: () => string | Promise<string>) => Promise<void>;
injectScript: (getScript: () => string | Promise<string>, opts?: {
logScript?: boolean;
}) => Promise<void>;
streamValue: (key: string, value: any) => void;
streamedKeys: Set<string>;
onMatchSettled: (opts: {
router: AnyRouter;
match: AnyRouteMatch;
}) => any;
}
export type AnyRouterWithContext<TContext> = RouterCore<AnyRouteWithContext<TContext>, any, any, any, any>;
export type AnyRouter = RouterCore<any, any, any, any, any>;
export interface ViewTransitionOptions {
types: Array<string>;
}
export declare function defaultSerializeError(err: unknown): {
name: string;
message: string;
} | {
data: unknown;
};
export interface ExtractedBaseEntry {
dataType: '__beforeLoadContext' | 'loaderData';
type: string;
path: Array<string>;
id: number;
matchIndex: number;
}
export interface ExtractedStream extends ExtractedBaseEntry {
type: 'stream';
streamState: StreamState;
}
export interface ExtractedPromise extends ExtractedBaseEntry {
type: 'promise';
promiseState: DeferredPromiseState<any>;
}
export type ExtractedEntry = ExtractedStream | ExtractedPromise;
export type StreamState = {
promises: Array<ControlledPromise<string | null>>;
};
export type TrailingSlashOption = 'always' | 'never' | 'preserve';
export declare function getLocationChangeInfo(routerState: {
resolvedLocation?: ParsedLocation;
location: ParsedLocation;
}): {
fromLocation: ParsedLocation<{}> | undefined;
toLocation: ParsedLocation<{}>;
pathChanged: boolean;
hrefChanged: boolean;
hashChanged: boolean;
};
export type CreateRouterFn = <TRouteTree extends AnyRoute, TTrailingSlashOption extends TrailingSlashOption = 'never', TDefaultStructuralSharingOption extends boolean = false, TRouterHistory extends RouterHistory = RouterHistory, TDehydrated extends Record<string, any> = Record<string, any>>(options: undefined extends number ? 'strictNullChecks must be enabled in tsconfig.json' : RouterConstructorOptions<TRouteTree, TTrailingSlashOption, TDefaultStructuralSharingOption, TRouterHistory, TDehydrated>) => RouterCore<TRouteTree, TTrailingSlashOption, TDefaultStructuralSharingOption, TRouterHistory, TDehydrated>;
export declare class RouterCore<in out TRouteTree extends AnyRoute, in out TTrailingSlashOption extends TrailingSlashOption, in out TDefaultStructuralSharingOption extends boolean, in out TRouterHistory extends RouterHistory = RouterHistory, in out TDehydrated extends Record<string, any> = Record<string, any>> {
tempLocationKey: string | undefined;
resetNextScroll: boolean;
shouldViewTransition?: boolean | ViewTransitionOptions;
isViewTransitionTypesSupported?: boolean;
subscribers: Set<RouterListener<RouterEvent>>;
viewTransitionPromise?: ControlledPromise<true>;
isScrollRestoring: boolean;
isScrollRestorationSetup: boolean;
__store: Store<RouterState<TRouteTree>>;
options: PickAsRequired<RouterOptions<TRouteTree, TTrailingSlashOption, TDefaultStructuralSharingOption, TRouterHistory, TDehydrated>, 'stringifySearch' | 'parseSearch' | 'context'>;
history: TRouterHistory;
latestLocation: ParsedLocation<FullSearchSchema<TRouteTree>>;
basepath: string;
routeTree: TRouteTree;
routesById: RoutesById<TRouteTree>;
routesByPath: RoutesByPath<TRouteTree>;
flatRoutes: Array<AnyRoute>;
isServer: boolean;
pathParamsDecodeCharMap?: Map<string, string>;
/**
* @deprecated Use the `createRouter` function instead
*/
constructor(options: RouterConstructorOptions<TRouteTree, TTrailingSlashOption, TDefaultStructuralSharingOption, TRouterHistory, TDehydrated>);
startTransition: StartTransitionFn;
update: UpdateFn<TRouteTree, TTrailingSlashOption, TDefaultStructuralSharingOption, TRouterHistory, TDehydrated>;
get state(): RouterState<TRouteTree, import('./Matches.js').RouteMatch<any, any, any, any, any, any, any>>;
buildRouteTree: () => void;
subscribe: SubscribeFn;
emit: EmitFn;
parseLocation: ParseLocationFn<TRouteTree>;
resolvePathWithBase: (from: string, path: string) => string;
get looseRoutesById(): Record<string, AnyRoute>;
/**
@deprecated use the following signature instead
```ts
matchRoutes (
next: ParsedLocation,
opts?: { preload?: boolean; throwOnError?: boolean },
): Array<AnyRouteMatch>;
```
*/
matchRoutes: MatchRoutesFn;
private matchRoutesInternal;
getMatchedRoutes: GetMatchRoutesFn;
cancelMatch: (id: string) => void;
cancelMatches: () => void;
buildLocation: BuildLocationFn;
commitLocationPromise: undefined | ControlledPromise<void>;
commitLocation: CommitLocationFn;
buildAndCommitLocation: ({ replace, resetScroll, hashScrollIntoView, viewTransition, ignoreBlocker, href, ...rest }?: BuildNextOptions & CommitLocationOptions) => Promise<void>;
navigate: NavigateFn;
latestLoadPromise: undefined | Promise<void>;
load: LoadFn;
startViewTransition: (fn: () => Promise<void>) => void;
updateMatch: UpdateMatchFn;
getMatch: GetMatchFn;
loadMatches: ({ location, matches, preload: allPreload, onReady, updateMatch, sync, }: {
location: ParsedLocation;
matches: Array<AnyRouteMatch>;
preload?: boolean;
onReady?: () => Promise<void>;
updateMatch?: (id: string, updater: (match: AnyRouteMatch) => AnyRouteMatch) => void;
getMatch?: (matchId: string) => AnyRouteMatch | undefined;
sync?: boolean;
}) => Promise<Array<MakeRouteMatch>>;
invalidate: InvalidateFn<RouterCore<TRouteTree, TTrailingSlashOption, TDefaultStructuralSharingOption, TRouterHistory, TDehydrated>>;
resolveRedirect: (err: AnyRedirect) => ResolvedRedirect;
clearCache: ClearCacheFn<this>;
clearExpiredCache: () => void;
loadRouteChunk: (route: AnyRoute) => Promise<void[]>;
preloadRoute: PreloadRouteFn<TRouteTree, TTrailingSlashOption, TDefaultStructuralSharingOption, TRouterHistory>;
matchRoute: MatchRouteFn<TRouteTree, TTrailingSlashOption, TDefaultStructuralSharingOption, TRouterHistory>;
ssr?: {
manifest: Manifest | undefined;
serializer: StartSerializer;
};
serverSsr?: {
injectedHtml: Array<InjectedHtmlEntry>;
injectHtml: (getHtml: () => string | Promise<string>) => Promise<void>;
injectScript: (getScript: () => string | Promise<string>, opts?: {
logScript?: boolean;
}) => Promise<void>;
streamValue: (key: string, value: any) => void;
streamedKeys: Set<string>;
onMatchSettled: (opts: {
router: AnyRouter;
match: AnyRouteMatch;
}) => any;
};
clientSsr?: {
getStreamedValue: <T>(key: string) => T | undefined;
};
_handleNotFound: (matches: Array<AnyRouteMatch>, err: NotFoundError, { updateMatch, }?: {
updateMatch?: (id: string, updater: (match: AnyRouteMatch) => AnyRouteMatch) => void;
}) => void;
hasNotFoundMatch: () => boolean;
}
export declare class SearchParamError extends Error {
}
export declare class PathParamError extends Error {
}
export declare function lazyFn<T extends Record<string, (...args: Array<any>) => any>, TKey extends keyof T = 'default'>(fn: () => Promise<T>, key?: TKey): (...args: Parameters<T[TKey]>) => Promise<Awaited<ReturnType<T[TKey]>>>;
export declare function getInitialRouterState(location: ParsedLocation): RouterState<any>;
export declare const componentTypes: readonly ["component", "errorComponent", "pendingComponent", "notFoundComponent"];
export {};

View File

@@ -0,0 +1 @@
{"version":3,"names":["findConfigUpwards","rootDir","findPackageData","filepath","directories","pkg","isPackage","findRelativeConfig","pkgData","envName","caller","config","ignore","findRootConfig","dirname","loadConfig","name","Error","resolveShowConfigPath","ROOT_CONFIG_FILENAMES","exports","resolvePlugin","resolvePreset","loadPlugin","loadPreset"],"sources":["../../../src/config/files/index-browser.ts"],"sourcesContent":["import type { Handler } from \"gensync\";\n\nimport type {\n ConfigFile,\n IgnoreFile,\n RelativeConfig,\n FilePackageData,\n} from \"./types.ts\";\n\nimport type { CallerMetadata } from \"../validation/options.ts\";\n\nexport type { ConfigFile, IgnoreFile, RelativeConfig, FilePackageData };\n\nexport function findConfigUpwards(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n rootDir: string,\n): string | null {\n return null;\n}\n\n// eslint-disable-next-line require-yield\nexport function* findPackageData(filepath: string): Handler<FilePackageData> {\n return {\n filepath,\n directories: [],\n pkg: null,\n isPackage: false,\n };\n}\n\n// eslint-disable-next-line require-yield\nexport function* findRelativeConfig(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n pkgData: FilePackageData,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n envName: string,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n caller: CallerMetadata | undefined,\n): Handler<RelativeConfig> {\n return { config: null, ignore: null };\n}\n\n// eslint-disable-next-line require-yield\nexport function* findRootConfig(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n dirname: string,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n envName: string,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n caller: CallerMetadata | undefined,\n): Handler<ConfigFile | null> {\n return null;\n}\n\n// eslint-disable-next-line require-yield\nexport function* loadConfig(\n name: string,\n dirname: string,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n envName: string,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n caller: CallerMetadata | undefined,\n): Handler<ConfigFile> {\n throw new Error(`Cannot load ${name} relative to ${dirname} in a browser`);\n}\n\n// eslint-disable-next-line require-yield\nexport function* resolveShowConfigPath(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n dirname: string,\n): Handler<string | null> {\n return null;\n}\n\nexport const ROOT_CONFIG_FILENAMES: string[] = [];\n\ntype Resolved =\n | { loader: \"require\"; filepath: string }\n | { loader: \"import\"; filepath: string };\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function resolvePlugin(name: string, dirname: string): Resolved | null {\n return null;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function resolvePreset(name: string, dirname: string): Resolved | null {\n return null;\n}\n\nexport function loadPlugin(\n name: string,\n dirname: string,\n): Handler<{\n filepath: string;\n value: unknown;\n}> {\n throw new Error(\n `Cannot load plugin ${name} relative to ${dirname} in a browser`,\n );\n}\n\nexport function loadPreset(\n name: string,\n dirname: string,\n): Handler<{\n filepath: string;\n value: unknown;\n}> {\n throw new Error(\n `Cannot load preset ${name} relative to ${dirname} in a browser`,\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAaO,SAASA,iBAAiBA,CAE/BC,OAAe,EACA;EACf,OAAO,IAAI;AACb;AAGO,UAAUC,eAAeA,CAACC,QAAgB,EAA4B;EAC3E,OAAO;IACLA,QAAQ;IACRC,WAAW,EAAE,EAAE;IACfC,GAAG,EAAE,IAAI;IACTC,SAAS,EAAE;EACb,CAAC;AACH;AAGO,UAAUC,kBAAkBA,CAEjCC,OAAwB,EAExBC,OAAe,EAEfC,MAAkC,EACT;EACzB,OAAO;IAAEC,MAAM,EAAE,IAAI;IAAEC,MAAM,EAAE;EAAK,CAAC;AACvC;AAGO,UAAUC,cAAcA,CAE7BC,OAAe,EAEfL,OAAe,EAEfC,MAAkC,EACN;EAC5B,OAAO,IAAI;AACb;AAGO,UAAUK,UAAUA,CACzBC,IAAY,EACZF,OAAe,EAEfL,OAAe,EAEfC,MAAkC,EACb;EACrB,MAAM,IAAIO,KAAK,CAAC,eAAeD,IAAI,gBAAgBF,OAAO,eAAe,CAAC;AAC5E;AAGO,UAAUI,qBAAqBA,CAEpCJ,OAAe,EACS;EACxB,OAAO,IAAI;AACb;AAEO,MAAMK,qBAA+B,GAAAC,OAAA,CAAAD,qBAAA,GAAG,EAAE;AAO1C,SAASE,aAAaA,CAACL,IAAY,EAAEF,OAAe,EAAmB;EAC5E,OAAO,IAAI;AACb;AAGO,SAASQ,aAAaA,CAACN,IAAY,EAAEF,OAAe,EAAmB;EAC5E,OAAO,IAAI;AACb;AAEO,SAASS,UAAUA,CACxBP,IAAY,EACZF,OAAe,EAId;EACD,MAAM,IAAIG,KAAK,CACb,sBAAsBD,IAAI,gBAAgBF,OAAO,eACnD,CAAC;AACH;AAEO,SAASU,UAAUA,CACxBR,IAAY,EACZF,OAAe,EAId;EACD,MAAM,IAAIG,KAAK,CACb,sBAAsBD,IAAI,gBAAgBF,OAAO,eACnD,CAAC;AACH;AAAC","ignoreList":[]}

View File

@@ -0,0 +1,434 @@
'use strict'
let CssSyntaxError = require('./css-syntax-error')
let Stringifier = require('./stringifier')
let stringify = require('./stringify')
let { isClean, my } = require('./symbols')
function cloneNode(obj, parent) {
let cloned = new obj.constructor()
for (let i in obj) {
if (!Object.prototype.hasOwnProperty.call(obj, i)) {
/* c8 ignore next 2 */
continue
}
if (i === 'proxyCache') continue
let value = obj[i]
let type = typeof value
if (i === 'parent' && type === 'object') {
if (parent) cloned[i] = parent
} else if (i === 'source') {
cloned[i] = value
} else if (Array.isArray(value)) {
cloned[i] = value.map(j => cloneNode(j, cloned))
} else {
if (type === 'object' && value !== null) value = cloneNode(value)
cloned[i] = value
}
}
return cloned
}
function sourceOffset(inputCSS, position) {
// Not all custom syntaxes support `offset` in `source.start` and `source.end`
if (
position &&
typeof position.offset !== 'undefined'
) {
return position.offset;
}
let column = 1
let line = 1
let offset = 0
for (let i = 0; i < inputCSS.length; i++) {
if (line === position.line && column === position.column) {
offset = i
break
}
if (inputCSS[i] === '\n') {
column = 1
line += 1
} else {
column += 1
}
}
return offset
}
class Node {
get proxyOf() {
return this
}
constructor(defaults = {}) {
this.raws = {}
this[isClean] = false
this[my] = true
for (let name in defaults) {
if (name === 'nodes') {
this.nodes = []
for (let node of defaults[name]) {
if (typeof node.clone === 'function') {
this.append(node.clone())
} else {
this.append(node)
}
}
} else {
this[name] = defaults[name]
}
}
}
addToError(error) {
error.postcssNode = this
if (error.stack && this.source && /\n\s{4}at /.test(error.stack)) {
let s = this.source
error.stack = error.stack.replace(
/\n\s{4}at /,
`$&${s.input.from}:${s.start.line}:${s.start.column}$&`
)
}
return error
}
after(add) {
this.parent.insertAfter(this, add)
return this
}
assign(overrides = {}) {
for (let name in overrides) {
this[name] = overrides[name]
}
return this
}
before(add) {
this.parent.insertBefore(this, add)
return this
}
cleanRaws(keepBetween) {
delete this.raws.before
delete this.raws.after
if (!keepBetween) delete this.raws.between
}
clone(overrides = {}) {
let cloned = cloneNode(this)
for (let name in overrides) {
cloned[name] = overrides[name]
}
return cloned
}
cloneAfter(overrides = {}) {
let cloned = this.clone(overrides)
this.parent.insertAfter(this, cloned)
return cloned
}
cloneBefore(overrides = {}) {
let cloned = this.clone(overrides)
this.parent.insertBefore(this, cloned)
return cloned
}
error(message, opts = {}) {
if (this.source) {
let { end, start } = this.rangeBy(opts)
return this.source.input.error(
message,
{ column: start.column, line: start.line },
{ column: end.column, line: end.line },
opts
)
}
return new CssSyntaxError(message)
}
getProxyProcessor() {
return {
get(node, prop) {
if (prop === 'proxyOf') {
return node
} else if (prop === 'root') {
return () => node.root().toProxy()
} else {
return node[prop]
}
},
set(node, prop, value) {
if (node[prop] === value) return true
node[prop] = value
if (
prop === 'prop' ||
prop === 'value' ||
prop === 'name' ||
prop === 'params' ||
prop === 'important' ||
/* c8 ignore next */
prop === 'text'
) {
node.markDirty()
}
return true
}
}
}
/* c8 ignore next 3 */
markClean() {
this[isClean] = true
}
markDirty() {
if (this[isClean]) {
this[isClean] = false
let next = this
while ((next = next.parent)) {
next[isClean] = false
}
}
}
next() {
if (!this.parent) return undefined
let index = this.parent.index(this)
return this.parent.nodes[index + 1]
}
positionBy(opts) {
let pos = this.source.start
if (opts.index) {
pos = this.positionInside(opts.index)
} else if (opts.word) {
let inputString = ('document' in this.source.input)
? this.source.input.document
: this.source.input.css
let stringRepresentation = inputString.slice(
sourceOffset(inputString, this.source.start),
sourceOffset(inputString, this.source.end)
)
let index = stringRepresentation.indexOf(opts.word)
if (index !== -1) pos = this.positionInside(index)
}
return pos
}
positionInside(index) {
let column = this.source.start.column
let line = this.source.start.line
let inputString = ('document' in this.source.input)
? this.source.input.document
: this.source.input.css
let offset = sourceOffset(inputString, this.source.start)
let end = offset + index
for (let i = offset; i < end; i++) {
if (inputString[i] === '\n') {
column = 1
line += 1
} else {
column += 1
}
}
return { column, line }
}
prev() {
if (!this.parent) return undefined
let index = this.parent.index(this)
return this.parent.nodes[index - 1]
}
rangeBy(opts) {
let start = {
column: this.source.start.column,
line: this.source.start.line
}
let end = this.source.end
? {
column: this.source.end.column + 1,
line: this.source.end.line
}
: {
column: start.column + 1,
line: start.line
}
if (opts.word) {
let inputString = ('document' in this.source.input)
? this.source.input.document
: this.source.input.css
let stringRepresentation = inputString.slice(
sourceOffset(inputString, this.source.start),
sourceOffset(inputString, this.source.end)
)
let index = stringRepresentation.indexOf(opts.word)
if (index !== -1) {
start = this.positionInside(index)
end = this.positionInside(
index + opts.word.length,
)
}
} else {
if (opts.start) {
start = {
column: opts.start.column,
line: opts.start.line
}
} else if (opts.index) {
start = this.positionInside(opts.index)
}
if (opts.end) {
end = {
column: opts.end.column,
line: opts.end.line
}
} else if (typeof opts.endIndex === 'number') {
end = this.positionInside(opts.endIndex)
} else if (opts.index) {
end = this.positionInside(opts.index + 1)
}
}
if (
end.line < start.line ||
(end.line === start.line && end.column <= start.column)
) {
end = { column: start.column + 1, line: start.line }
}
return { end, start }
}
raw(prop, defaultType) {
let str = new Stringifier()
return str.raw(this, prop, defaultType)
}
remove() {
if (this.parent) {
this.parent.removeChild(this)
}
this.parent = undefined
return this
}
replaceWith(...nodes) {
if (this.parent) {
let bookmark = this
let foundSelf = false
for (let node of nodes) {
if (node === this) {
foundSelf = true
} else if (foundSelf) {
this.parent.insertAfter(bookmark, node)
bookmark = node
} else {
this.parent.insertBefore(bookmark, node)
}
}
if (!foundSelf) {
this.remove()
}
}
return this
}
root() {
let result = this
while (result.parent && result.parent.type !== 'document') {
result = result.parent
}
return result
}
toJSON(_, inputs) {
let fixed = {}
let emitInputs = inputs == null
inputs = inputs || new Map()
let inputsNextIndex = 0
for (let name in this) {
if (!Object.prototype.hasOwnProperty.call(this, name)) {
/* c8 ignore next 2 */
continue
}
if (name === 'parent' || name === 'proxyCache') continue
let value = this[name]
if (Array.isArray(value)) {
fixed[name] = value.map(i => {
if (typeof i === 'object' && i.toJSON) {
return i.toJSON(null, inputs)
} else {
return i
}
})
} else if (typeof value === 'object' && value.toJSON) {
fixed[name] = value.toJSON(null, inputs)
} else if (name === 'source') {
let inputId = inputs.get(value.input)
if (inputId == null) {
inputId = inputsNextIndex
inputs.set(value.input, inputsNextIndex)
inputsNextIndex++
}
fixed[name] = {
end: value.end,
inputId,
start: value.start
}
} else {
fixed[name] = value
}
}
if (emitInputs) {
fixed.inputs = [...inputs.keys()].map(input => input.toJSON())
}
return fixed
}
toProxy() {
if (!this.proxyCache) {
this.proxyCache = new Proxy(this, this.getProxyProcessor())
}
return this.proxyCache
}
toString(stringifier = stringify) {
if (stringifier.stringify) stringifier = stringifier.stringify
let result = ''
stringifier(this, i => {
result += i
})
return result
}
warn(result, text, opts) {
let data = { node: this }
for (let i in opts) data[i] = opts[i]
return result.warn(text, data)
}
}
module.exports = Node
Node.default = Node

View File

@@ -0,0 +1,57 @@
{
"name": "dequal",
"version": "2.0.3",
"repository": "lukeed/dequal",
"description": "A tiny (304B to 489B) utility for check for deep equality",
"unpkg": "dist/index.min.js",
"module": "dist/index.mjs",
"main": "dist/index.js",
"types": "index.d.ts",
"license": "MIT",
"author": {
"name": "Luke Edwards",
"email": "luke.edwards05@gmail.com",
"url": "https://lukeed.com"
},
"engines": {
"node": ">=6"
},
"scripts": {
"build": "bundt",
"pretest": "npm run build",
"postbuild": "echo \"lite\" | xargs -n1 cp -v index.d.ts",
"test": "uvu -r esm test"
},
"files": [
"*.d.ts",
"dist",
"lite"
],
"exports": {
".": {
"types": "./index.d.ts",
"import": "./dist/index.mjs",
"require": "./dist/index.js"
},
"./lite": {
"types": "./index.d.ts",
"import": "./lite/index.mjs",
"require": "./lite/index.js"
},
"./package.json": "./package.json"
},
"modes": {
"lite": "src/lite.js",
"default": "src/index.js"
},
"keywords": [
"deep",
"deep-equal",
"equality"
],
"devDependencies": {
"bundt": "1.0.2",
"esm": "3.2.25",
"uvu": "0.3.2"
}
}

View File

@@ -0,0 +1,202 @@
/**
* @fileoverview A rule to disallow or enforce spaces inside of single line blocks.
* @author Toru Nagashima
* @deprecated in ESLint v8.53.0
*/
"use strict";
const util = require("./utils/ast-utils");
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../shared/types').Rule} */
module.exports = {
meta: {
deprecated: {
message: "Formatting rules are being moved out of ESLint core.",
url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/",
deprecatedSince: "8.53.0",
availableUntil: "10.0.0",
replacedBy: [
{
message:
"ESLint Stylistic now maintains deprecated stylistic core rules.",
url: "https://eslint.style/guide/migration",
plugin: {
name: "@stylistic/eslint-plugin-js",
url: "https://eslint.style/packages/js",
},
rule: {
name: "block-spacing",
url: "https://eslint.style/rules/js/block-spacing",
},
},
],
},
type: "layout",
docs: {
description:
"Disallow or enforce spaces inside of blocks after opening block and before closing block",
recommended: false,
url: "https://eslint.org/docs/latest/rules/block-spacing",
},
fixable: "whitespace",
schema: [{ enum: ["always", "never"] }],
messages: {
missing: "Requires a space {{location}} '{{token}}'.",
extra: "Unexpected space(s) {{location}} '{{token}}'.",
},
},
create(context) {
const always = context.options[0] !== "never",
messageId = always ? "missing" : "extra",
sourceCode = context.sourceCode;
/**
* Gets the open brace token from a given node.
* @param {ASTNode} node A BlockStatement/StaticBlock/SwitchStatement node to get.
* @returns {Token} The token of the open brace.
*/
function getOpenBrace(node) {
if (node.type === "SwitchStatement") {
if (node.cases.length > 0) {
return sourceCode.getTokenBefore(node.cases[0]);
}
return sourceCode.getLastToken(node, 1);
}
if (node.type === "StaticBlock") {
return sourceCode.getFirstToken(node, { skip: 1 }); // skip the `static` token
}
// "BlockStatement"
return sourceCode.getFirstToken(node);
}
/**
* Checks whether or not:
* - given tokens are on same line.
* - there is/isn't a space between given tokens.
* @param {Token} left A token to check.
* @param {Token} right The token which is next to `left`.
* @returns {boolean}
* When the option is `"always"`, `true` if there are one or more spaces between given tokens.
* When the option is `"never"`, `true` if there are not any spaces between given tokens.
* If given tokens are not on same line, it's always `true`.
*/
function isValid(left, right) {
return (
!util.isTokenOnSameLine(left, right) ||
sourceCode.isSpaceBetweenTokens(left, right) === always
);
}
/**
* Checks and reports invalid spacing style inside braces.
* @param {ASTNode} node A BlockStatement/StaticBlock/SwitchStatement node to check.
* @returns {void}
*/
function checkSpacingInsideBraces(node) {
// Gets braces and the first/last token of content.
const openBrace = getOpenBrace(node);
const closeBrace = sourceCode.getLastToken(node);
const firstToken = sourceCode.getTokenAfter(openBrace, {
includeComments: true,
});
const lastToken = sourceCode.getTokenBefore(closeBrace, {
includeComments: true,
});
// Skip if the node is invalid or empty.
if (
openBrace.type !== "Punctuator" ||
openBrace.value !== "{" ||
closeBrace.type !== "Punctuator" ||
closeBrace.value !== "}" ||
firstToken === closeBrace
) {
return;
}
// Skip line comments for option never
if (!always && firstToken.type === "Line") {
return;
}
// Check.
if (!isValid(openBrace, firstToken)) {
let loc = openBrace.loc;
if (messageId === "extra") {
loc = {
start: openBrace.loc.end,
end: firstToken.loc.start,
};
}
context.report({
node,
loc,
messageId,
data: {
location: "after",
token: openBrace.value,
},
fix(fixer) {
if (always) {
return fixer.insertTextBefore(firstToken, " ");
}
return fixer.removeRange([
openBrace.range[1],
firstToken.range[0],
]);
},
});
}
if (!isValid(lastToken, closeBrace)) {
let loc = closeBrace.loc;
if (messageId === "extra") {
loc = {
start: lastToken.loc.end,
end: closeBrace.loc.start,
};
}
context.report({
node,
loc,
messageId,
data: {
location: "before",
token: closeBrace.value,
},
fix(fixer) {
if (always) {
return fixer.insertTextAfter(lastToken, " ");
}
return fixer.removeRange([
lastToken.range[1],
closeBrace.range[0],
]);
},
});
}
}
return {
BlockStatement: checkSpacingInsideBraces,
StaticBlock: checkSpacingInsideBraces,
SwitchStatement: checkSpacingInsideBraces,
};
},
};

View File

@@ -0,0 +1,7 @@
'use strict';
if (process.env.NODE_ENV === 'production') {
module.exports = require('./cjs/scheduler.production.js');
} else {
module.exports = require('./cjs/scheduler.development.js');
}

View File

@@ -0,0 +1,35 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = _importDeferProxy;
function _importDeferProxy(init) {
var ns = null;
var constValue = function (v) {
return function () {
return v;
};
};
var proxy = function (run) {
return function (_target, p, receiver) {
if (ns === null) ns = init();
return run(ns, p, receiver);
};
};
return new Proxy({}, {
defineProperty: constValue(false),
deleteProperty: constValue(false),
get: proxy(Reflect.get),
getOwnPropertyDescriptor: proxy(Reflect.getOwnPropertyDescriptor),
getPrototypeOf: constValue(null),
isExtensible: constValue(false),
has: proxy(Reflect.has),
ownKeys: proxy(Reflect.ownKeys),
preventExtensions: constValue(true),
set: constValue(false),
setPrototypeOf: constValue(false)
});
}
//# sourceMappingURL=importDeferProxy.js.map

View File

@@ -0,0 +1,45 @@
# loose-envify
[![Build Status](https://travis-ci.org/zertosh/loose-envify.svg?branch=master)](https://travis-ci.org/zertosh/loose-envify)
Fast (and loose) selective `process.env` replacer using [js-tokens](https://github.com/lydell/js-tokens) instead of an AST. Works just like [envify](https://github.com/hughsk/envify) but much faster.
## Gotchas
* Doesn't handle broken syntax.
* Doesn't look inside embedded expressions in template strings.
- **this won't work:**
```js
console.log(`the current env is ${process.env.NODE_ENV}`);
```
* Doesn't replace oddly-spaced or oddly-commented expressions.
- **this won't work:**
```js
console.log(process./*won't*/env./*work*/NODE_ENV);
```
## Usage/Options
loose-envify has the exact same interface as [envify](https://github.com/hughsk/envify), including the CLI.
## Benchmark
```
envify:
$ for i in {1..5}; do node bench/bench.js 'envify'; done
708ms
727ms
791ms
719ms
720ms
loose-envify:
$ for i in {1..5}; do node bench/bench.js '../'; done
51ms
52ms
52ms
52ms
52ms
```

View File

@@ -0,0 +1 @@
import{h as a}from"./chunk-P5FH2LZE.mjs";import"./chunk-HTB5LLOP.mjs";export{a as default};