deploy test

This commit is contained in:
Kilton937342 2023-02-23 17:11:57 +01:00
parent 410d759edf
commit cae88256ee
10059 changed files with 3239879 additions and 1392 deletions

View File

@ -1,19 +1,18 @@
from sqlmodel import JSON, Column, select
from sqlalchemy.inspection import inspect
from enum import Enum from enum import Enum
import os from typing import List
from pydantic import BaseModel
from pydantic import validator, root_validator
from generateur.generateur_main import generate_from_path
from services.exoValidation import get_support_from_path
from services.io import add_fast_api_root, get_filename_from_path
from services.schema import as_form
from typing import Any, List, Optional
from sqlmodel import SQLModel, Field, Relationship, Session
from database.auth.models import User, UserRead
from typing import TYPE_CHECKING, Optional from typing import TYPE_CHECKING, Optional
from pydantic import BaseModel
from pydantic import validator
from sqlalchemy.inspection import inspect
from sqlmodel import JSON, Column
from sqlmodel import SQLModel, Field, Relationship
from database.auth.models import User
from services.io import get_filename_from_path
from services.schema import as_form
from .FileField import FileField from .FileField import FileField
from database.db import get_session
if TYPE_CHECKING: if TYPE_CHECKING:
from database.auth.models import User from database.auth.models import User
@ -33,8 +32,8 @@ class GeneratorOutput(BaseModel):
class Example(BaseModel): class Example(BaseModel):
type: ExampleEnum = ExampleEnum.undisponible type: ExampleEnum = ExampleEnum.undisponible
data: List[GeneratorOutput] | None = None data: List[GeneratorOutput] | None = None
class ExercicesTagLink(SQLModel, table=True): class ExercicesTagLink(SQLModel, table=True):
exercice_id: Optional[int] = Field( exercice_id: Optional[int] = Field(
default=None, foreign_key='exercice.id', primary_key=True) default=None, foreign_key='exercice.id', primary_key=True)
@ -46,14 +45,15 @@ class ExerciceBase(SQLModel):
name: str = Field(max_length=50, index=True) name: str = Field(max_length=50, index=True)
consigne: Optional[str] = Field(max_length=200, default=None) consigne: Optional[str] = Field(max_length=200, default=None)
private: Optional[bool] = Field(default=False) private: Optional[bool] = Field(default=False)
class Supports(SQLModel): class Supports(SQLModel):
csv: bool csv: bool
pdf: bool pdf: bool
web: bool web: bool
class Exercice(ExerciceBase,Supports, table=True):
class Exercice(ExerciceBase, Supports, table=True):
id: Optional[int] = Field(default=None, primary_key=True) id: Optional[int] = Field(default=None, primary_key=True)
id_code: str = Field(unique=True, index=True) id_code: str = Field(unique=True, index=True)
@ -71,27 +71,38 @@ class Exercice(ExerciceBase,Supports, table=True):
tags: List['Tag'] = Relationship( tags: List['Tag'] = Relationship(
back_populates='exercices', link_model=ExercicesTagLink) back_populates='exercices', link_model=ExercicesTagLink)
examples: Optional[Example] = Field( examples: Optional[Example] = Field(
sa_column=Column(JSON), default={}) sa_column=Column(JSON), default={})
def dict_relationship(self, *, exclude: List[str], include: List[str]): def dict_relationship(self, *, exclude: List[str], include: List[str]):
relationships = inspect(self.__class__).relationships.items() relationships = inspect(self.__class__).relationships.items()
relationsData = {rname: getattr(self, rname) for rname, rp in relationships if rname not in exclude and (rname in include if len(include) != 0 else True)} relationsData = {rname: getattr(self, rname) for rname, rp in relationships if
rname not in exclude and (rname in include if len(include) != 0 else True)}
return {**self.dict(), **relationsData} return {**self.dict(), **relationsData}
class Config: class Config:
validate_assignment = True validate_assignment = True
extra='allow' extra = 'allow'
# translate the folowing object to python enum
class ColorEnum(Enum): class ColorEnum(Enum):
green='#00ff00' bleu = "rgb(51,123,255)"
red="#ff0000" vert = "rgb(0,204,0)"
blue="#0000ff" rouge = "rgb(255,0,0)"
string="string" marron = "rgb(153,76,0)"
violet = "rgb(204,0,204)"
jaune = "rgb(255,255,0)"
orange = "rgb(255,128,0)"
noir = "rgb(10,10,10)"
rose = "rgb(255,102,255)"
blanc = "rgb(240,240,240)"
blanche = "rgb(240,240,240)"
class TagBase(SQLModel): class TagBase(SQLModel):
label: str = Field(max_length=20) label: str = Field(max_length=20)
color: ColorEnum color: ColorEnum
@ -125,28 +136,21 @@ class ExerciceEdit(ExerciceCreate):
pass pass
class Author(SQLModel): class Author(SQLModel):
username: str username: str
class ExerciceOrigin(SQLModel): class ExerciceOrigin(SQLModel):
#id: int # id: int
id_code: str id_code: str
name: str name: str
author: str author: str
def get_source_path_from_name_and_id(name: str, id_code: str): def get_source_path_from_name_and_id(name: str, id_code: str):
return f'/uploads/{id_code}/{name}' return f'/uploads/{id_code}/{name}'
class ExerciceReadBase(ExerciceBase): class ExerciceReadBase(ExerciceBase):
id_code: str id_code: str
author: Author author: Author
@ -154,30 +158,27 @@ class ExerciceReadBase(ExerciceBase):
tags: List[TagRead] = None tags: List[TagRead] = None
exo_source: str exo_source: str
examples: Example = None examples: Example = None
is_author: bool = None is_author: bool = None
@validator('exo_source') @validator('exo_source')
def get_exo_source_name(cls, value, values): def get_exo_source_name(cls, value, values):
if value is not None: if value is not None:
return get_filename_from_path(value) return get_filename_from_path(value)
return value return value
class ExerciceRead(ExerciceBase, Supports): class ExerciceRead(ExerciceBase, Supports):
id_code: str id_code: str
id: int id: int
author_id:int author_id: int
exo_source: str exo_source: str
author: User author: User
original: Optional[Exercice] original: Optional[Exercice]
tags: List[Tag] tags: List[Tag]
examples: Example examples: Example
class ExerciceReadFull(ExerciceReadBase): class ExerciceReadFull(ExerciceReadBase):
supports: Supports supports: Supports

View File

@ -291,7 +291,7 @@ def serialize_parcours_short(parcours: Parcours, member: Member, db: Session):
challenger = getChallenger(parcours, member, db) challenger = getChallenger(parcours, member, db)
return ParcoursReadShort(name=parcours.name, id_code=parcours.id_code, best_note=challenger.best, return ParcoursReadShort(name=parcours.name, id_code=parcours.id_code, best_note=challenger.best,
validated=challenger.validated) validated=challenger.validated, avg=challenger.avg)
def serialize_challenge(challenge: Challenge): def serialize_challenge(challenge: Challenge):
@ -344,7 +344,7 @@ def getAvgTops(p: Parcours, db: Session):
def getRank(c: Challenger, p: Parcours, db: Session): def getRank(c: Challenger, p: Parcours, db: Session):
noteRank = db.exec(select([func.count(Challenge.id)]).where(Challenge.parcours_id == p.id_code).order_by( noteRank = db.exec(select([func.count(Challenge.id)]).where(Challenge.parcours_id == p.id_code).order_by(
col(Challenge.mistakes), col(Challenge.time)).where(Challenge.mistakes <= c.best, col(Challenge.mistakes), col(Challenge.time)).where(Challenge.mistakes < c.best,
Challenge.time < c.best_time)).one() Challenge.time < c.best_time)).one()
return noteRank + 1 return noteRank + 1
@ -525,7 +525,7 @@ def change_challengers_validation(p: Parcours, validation: int, db: Session):
def change_challenges_validation(p: Parcours, validation: int, db: Session): def change_challenges_validation(p: Parcours, validation: int, db: Session):
print('cHANGE')
challenges = db.exec(select(Challenge).where( challenges = db.exec(select(Challenge).where(
Challenge.parcours_id == p.id_code)).all() Challenge.parcours_id == p.id_code)).all()
print('CHALLS', challenges) print('CHALLS', challenges)

View File

@ -1,11 +1,10 @@
from uuid import UUID, uuid4
from pydantic import root_validator, BaseModel
import pydantic.json
from typing import List, Optional, TYPE_CHECKING from typing import List, Optional, TYPE_CHECKING
from sqlmodel import SQLModel, Field, Relationship, JSON, Column, ForeignKeyConstraint from uuid import UUID, uuid4
from database.exercices.models import Example
from database.auth.models import UserRead
from pydantic import BaseModel
from sqlmodel import SQLModel, Field, Relationship, JSON, Column, ForeignKeyConstraint
from database.exercices.models import Example
if TYPE_CHECKING: if TYPE_CHECKING:
from database.auth.models import User from database.auth.models import User
@ -132,6 +131,7 @@ class ParcoursReadShort(SQLModel):
best_note: str | None = None best_note: str | None = None
validated: bool = False validated: bool = False
id_code: str id_code: str
avg: float | None = None
class ParcoursReadUpdate(SQLModel): class ParcoursReadUpdate(SQLModel):
id_code: str id_code: str

Binary file not shown.

View File

@ -5,8 +5,8 @@ def exos(nb, username, password):
'password': password, 'password_confirm': password}) 'password': password, 'password_confirm': password})
token = rr.json()['access_token'] token = rr.json()['access_token']
for i in range(nb): for i in range(nb):
r = requests.post('http://localhost:8002/exercices', data={"name": "FakingTest" + str(i), "consigne": "consigne", "private": False}, files={ r = requests.post('http://localhost:8002/exercices', data={"name": "Test" + str(i), "consigne": "consigne", "private": False}, files={
'file': ('test.py', open('./tests/testing_exo_source/exo_source.py', 'rb'))}, headers={"Authorization": "Bearer " + token}) 'file': ('test.py', open('./tests/testing_exo_source/exo_source.py', 'rb'))}, headers={"Authorization": "Bearer " + token})
print('DONE') print('DONE')
exos(100, "lilianTest", "Pomme937342") exos(100, "lilianTest2", "Pomme937342")

View File

@ -1,6 +1,7 @@
from typing import Any, TYPE_CHECKING, Callable from typing import Any, TYPE_CHECKING, Callable
from fastapi.websockets import WebSocket from fastapi.websockets import WebSocket
from sqlalchemy.orm.exc import StaleDataError
from sqlmodel import Session from sqlmodel import Session
from database.auth.crud import get_user_from_token from database.auth.crud import get_user_from_token
@ -22,6 +23,7 @@ class RoomConsumer(Consumer):
self.manager = manager self.manager = manager
self.db = db self.db = db
self.member = None self.member = None
self.banned = False
# WS Utilities # WS Utilities
async def send(self, payload: Any | Callable): async def send(self, payload: Any | Callable):
@ -55,20 +57,26 @@ class RoomConsumer(Consumer):
if isinstance(self.member, Member): if isinstance(self.member, Member):
connect_member(self.member, self.db) connect_member(self.member, self.db)
await self.manager.broadcast(lambda m: {"type": "connect", "data": { await self.manager.broadcast(lambda m: {"type": "connect", "data": {
"member": serialize_member(self.member, admin=m.is_admin, m2=m)}}, self.room.id_code, exclude=[self]) "member": serialize_member(self.member, admin=m.is_admin, m2=m)}}, self.room.id_code, exclude=[self], conditions=[lambda m: m.member.waiting is not True])
# await self.broadcast(type="connect", payload={"member": serialize_member(self.member)}, exclude=True) # await self.broadcast(type="connect", payload={"member": serialize_member(self.member)}, exclude=True)
async def disconnect_self(self): async def disconnect_self(self):
print(self.manager.active_connections[self.room.id_code])
self.manager.remove(self.room.id_code, self)
print(self.manager.active_connections[self.room.id_code])
if isinstance(self.member, Member): if isinstance(self.member, Member):
''' self.db.expire(self.member) print('MEMBER', self.member)
self.db.refresh(self.member) ''' try:
disconnect_member(self.member, self.db) disconnect_member(self.member, self.db)
except StaleDataError:
return
if self.member.waiting is False: if self.member.waiting is False:
await self.manager.broadcast(lambda m: {"type": "disconnect", "data": { await self.manager.broadcast(lambda m: {"type": "disconnect", "data": {
"member": serialize_member(self.member, admin=m.is_admin, m2=m)}}, self.room.id_code, "member": serialize_member(self.member, admin=m.is_admin, m2=m)}}, self.room.id_code,
exclude=[self]) exclude=[self], conditions=[lambda m: m.member.waiting is not True])
# await self.broadcast(type="disconnect", payload={"member": serialize_member(self.member)}) # await self.broadcast(type="disconnect", payload={"member": serialize_member(self.member)})
else: else:
await self.send_to_admin(type="disconnect_waiter", payload={"waiter": serialize_member(self.member)}) await self.send_to_admin(type="disconnect_waiter", payload={"waiter": serialize_member(self.member)})
async def loginMember(self, member: Member): async def loginMember(self, member: Member):
@ -166,7 +174,8 @@ class RoomConsumer(Consumer):
self.add_to_group() self.add_to_group()
if self.room.public is False: if self.room.public is False:
await self.direct_send(type="waiting", payload={"waiter": serialize_member(self.member)}) await self.direct_send(type="waiting", payload={"waiter": serialize_member(self.member), "room": {
"name": self.room.name, "id_code": self.room.id_code}})
await self.send_to_admin(type="waiter", payload={"waiter": serialize_member(self.member)}) await self.send_to_admin(type="waiter", payload={"waiter": serialize_member(self.member)})
else: else:
await self.manager.broadcast( await self.manager.broadcast(
@ -286,10 +295,11 @@ class RoomConsumer(Consumer):
return {"waiter_id": waiter_id} return {"waiter_id": waiter_id}
@Consumer.sending("banned", conditions=[isMember]) @Consumer.sending("banned", conditions=[isMember])
def banned(self): async def banned(self):
self.member = None self.member = None
self.manager.remove(self.room.id, self) self.manager.remove(self.room.id_code, self)
self.ws.close() self.banned = True
#await self.ws.close()
return {} return {}
@Consumer.sending('ping', conditions=[isMember]) @Consumer.sending('ping', conditions=[isMember])
@ -298,5 +308,10 @@ class RoomConsumer(Consumer):
async def disconnect(self): async def disconnect(self):
print('DISCONNECTED', self.member) print('DISCONNECTED', self.member)
self.manager.remove(self.room.id, self) print(self.manager.active_connections[self.room.id_code])
self.manager.remove(self.room.id_code, self)
for p in self.room.parcours:
self.manager.remove(p.id_code, self)
await self.disconnect_self() await self.disconnect_self()

View File

@ -1,5 +1,7 @@
from typing import TYPE_CHECKING, Dict, List, Callable, Any from typing import TYPE_CHECKING, Dict, List, Callable, Any
from starlette.websockets import WebSocketState from starlette.websockets import WebSocketState
if TYPE_CHECKING: if TYPE_CHECKING:
from routes.room.consumer import RoomConsumer from routes.room.consumer import RoomConsumer
@ -16,38 +18,44 @@ class RoomManager:
self.active_connections[group].append(member) self.active_connections[group].append(member)
async def _send(self, connection: "RoomConsumer", message, group: str): async def _send(self, connection: "RoomConsumer", message, group: str):
print("STATE", connection.ws.client_state.__str__()) print('SENDING', connection.ws.application_state, connection.ws.client_state)
if connection.ws.application_state == WebSocketState.DISCONNECTED or connection.ws.client_state == WebSocketState.DISCONNECTED: if connection.ws.application_state == WebSocketState.DISCONNECTED or connection.ws.client_state == WebSocketState.DISCONNECTED:
self.remove(group, connection) self.remove(group, connection)
elif connection.ws.application_state == WebSocketState.CONNECTED: elif connection.ws.application_state == WebSocketState.CONNECTED and connection.ws.client_state == WebSocketState.CONNECTED:
await connection.send(message) try:
await connection.send(message)
except:
pass
def remove(self, group: str, member: "RoomConsumer"): def remove(self, group: str, member: "RoomConsumer"):
if group in self.active_connections: if group in self.active_connections:
if member in self.active_connections[group]: if member in self.active_connections[group]:
print("remoied")
self.active_connections[group].remove(member) self.active_connections[group].remove(member)
return True
async def broadcast(self, message: Any | Callable, group: str, conditions: list[Callable] = [], exclude: list["RoomConsumer"] = [], ): async def broadcast(self, message: Any | Callable, group: str, conditions: list[Callable] = [], exclude: list["RoomConsumer"] = [], ):
print('BROADCaST', message, self.active_connections) print('BROADCaST', self.active_connections)
if group in self.active_connections: if group in self.active_connections:
for connection in list(set(self.active_connections[group])): for connection in list(set(self.active_connections[group])):
print(connection, connection.ws.state, connection.ws.client_state, connection.ws.application_state) print(connection, connection.ws.state, connection.ws.client_state, connection.ws.application_state)
if connection not in exclude and all(f(connection) for f in conditions ): if connection not in exclude and all(f(connection) for f in conditions):
await self._send(connection, message, group) await self._send(connection, message, group)
async def send_to(self, group, id_code, msg): async def send_to(self, group, id_code, msg):
print('SENDING TO')
if group in self.active_connections: if group in self.active_connections:
members = [c for c in self.active_connections[group] members = [c for c in self.active_connections[group]
if c.member.id_code == id_code] if c.member.id_code == id_code]
print('MEM', members)
for m in members: for m in members:
await self._send(m, msg, group) await self._send(m, msg, group)
async def send_to_admin(self, group, msg): async def send_to_admin(self, group, msg):
if group in self.active_connections: if group in self.active_connections:
print('MEMBERS', self.active_connections[group], [(c.ws.state, c.ws.client_state, c.ws.application_state) for c in self.active_connections[group]])
members = [c for c in self.active_connections[group] members = [c for c in self.active_connections[group]
if c.member is not None and c.member.is_admin == True] if c.member is not None and c.member.is_admin is True]
for m in members: for m in members:
await self._send(m, msg, group) await self._send(m, msg, group)

View File

@ -56,18 +56,21 @@ def get_manager():
@router.post('/room', response_model=RoomConnectionInfos) @router.post('/room', response_model=RoomConnectionInfos)
def create_room(room: RoomCreate, username: Optional[str] = Query(default=None, max_length=20), user: User | None = Depends(get_current_user_optional), db: Session = Depends(get_session)): def create_room(room: RoomCreate, username: Optional[str] = Query(default=None, max_length=20),
user: User | None = Depends(get_current_user_optional), db: Session = Depends(get_session)):
room_obj = create_room_db(room=room, user=user, username=username, db=db) room_obj = create_room_db(room=room, user=user, username=username, db=db)
return {'room': room_obj['room'].id_code, "member": getattr(room_obj['member'].anonymous, "reconnect_code", None)} return {'room': room_obj['room'].id_code, "member": getattr(room_obj['member'].anonymous, "reconnect_code", None)}
@router.get('/room/{room_id}', response_model=RoomInfo) @router.get('/room/{room_id}', response_model=RoomInfo)
def get_room_route(room: Room = Depends(get_room), member: Member = Depends(get_member_dep), db: Session = Depends(get_session)): def get_room_route(room: Room = Depends(get_room), member: Member = Depends(get_member_dep),
db: Session = Depends(get_session)):
return serialize_room(room, member, db) return serialize_room(room, member, db)
@router.post('/room/{room_id}/parcours', response_model=ParcoursRead) @router.post('/room/{room_id}/parcours', response_model=ParcoursRead)
async def create_parcours(*, parcours: ParcoursCreate, room_id: str, member: Member = Depends(check_admin), m: RoomManager = Depends(get_manager), db: Session = Depends(get_session)): async def create_parcours(*, parcours: ParcoursCreate, room_id: str, member: Member = Depends(check_admin),
m: RoomManager = Depends(get_manager), db: Session = Depends(get_session)):
parcours_obj = create_parcours_db(parcours, member.room_id, db) parcours_obj = create_parcours_db(parcours, member.room_id, db)
if type(parcours_obj) == str: if type(parcours_obj) == str:
raise HTTPException( raise HTTPException(
@ -80,7 +83,8 @@ async def create_parcours(*, parcours: ParcoursCreate, room_id: str, member: Mem
@router.get('/room/{room_id}/parcours/{parcours_id}', response_model=ParcoursRead) @router.get('/room/{room_id}/parcours/{parcours_id}', response_model=ParcoursRead)
async def get_parcours_route(*, parcours: Parcours = Depends(get_parcours), member: Member = Depends(get_member_dep), db: Session = Depends(get_session)): async def get_parcours_route(*, parcours: Parcours = Depends(get_parcours), member: Member = Depends(get_member_dep),
db: Session = Depends(get_session)):
return serialize_parcours(parcours, member, db) return serialize_parcours(parcours, member, db)
@ -105,7 +109,8 @@ async def update_parcours(*, room_id: str, parcours: ParcoursCreate, member: Mem
@router.delete('/room/{room_id}/parcours/{parcours_id}', dependencies=[Depends(check_admin)]) @router.delete('/room/{room_id}/parcours/{parcours_id}', dependencies=[Depends(check_admin)])
async def delete_parcours(parcours: Parcours = Depends(get_parcours), m: RoomManager = Depends(get_manager), db: Session = Depends(get_session)): async def delete_parcours(parcours: Parcours = Depends(get_parcours), m: RoomManager = Depends(get_manager),
db: Session = Depends(get_session)):
delete_parcours_db(parcours, db) delete_parcours_db(parcours, db)
await m.broadcast({"type": "del_parcours", "data": {"parcours_id": parcours.id_code}}, parcours.room.id_code) await m.broadcast({"type": "del_parcours", "data": {"parcours_id": parcours.id_code}}, parcours.room.id_code)
return "ok" return "ok"
@ -152,16 +157,21 @@ async def send_challenge(*, challenge: List[CorrectionData], correction: TmpCorr
detail={"challenge_error": "Object does not correspond to correction"}) detail={"challenge_error": "Object does not correspond to correction"})
chall, challenger = create_challenge(**data, challenger=member, chall, challenger = create_challenge(**data, challenger=member,
parcours=parcours, time=time, db=db) parcours=parcours, time=time, db=db)
print('CHALLENGE', chall)
await m.broadcast({"type": "challenge", "data": ChallengeInfo( await m.broadcast({"type": "challenge", "data": ChallengeInfo(
challenger={"name": member.user.username if member.user_id != None else member.anonymous.username, challenger={"name": member.user.username if member.user_id != None else member.anonymous.username,
"id_code": member.id_code}, "id_code": member.id_code},
challenges=[Challenges(**{**chall.dict(), "canCorrige": chall.data != [], })]).dict()}, parcours.id_code, challenges=[Challenges(**{**chall.dict(), "canCorrige": chall.data != [], })]).dict()}, parcours.id_code,
conditions=[lambda c: c.member.is_admin or c.member.id_code == member.id_code]) conditions=[lambda c: c.member.is_admin or c.member.id_code == member.id_code])
#TODO : Envoyer que à ceux d'après
# TODO : Envoyer que à ceux d'après
await m.broadcast(lambda m: {"type": "newRanks", "data": {"rank": getMemberRank(m, correction.parcours, db), await m.broadcast(lambda m: {"type": "newRanks", "data": {"rank": getMemberRank(m, correction.parcours, db),
"avgRank": getMemberAvgRank(m, correction.parcours, db)}}, "avgRank": getMemberAvgRank(m, correction.parcours, db)}},
parcours.id_code) parcours.id_code)
print('WOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOoo')
await m.send_to(parcours.room.id_code, member.id_code, {"type": "parcours_stats", "data": {
"parcours": ParcoursReadShort(name=parcours.name, best_note=challenger.best, validated=challenger.validated,
id_code=parcours.id_code, avg=challenger.avg).dict()}})
print('CHALLENGE', chall) print('CHALLENGE', chall)
rank, avgRank = getRank( rank, avgRank = getRank(
challenger, parcours, db), getAvgRank(challenger, parcours, db) challenger, parcours, db), getAvgRank(challenger, parcours, db)
@ -229,7 +239,7 @@ async def corrige(*, correction: List[CorrigedData] = Body(), challenge: Challen
rank, avgRank = getRank( rank, avgRank = getRank(
challenger, parcours, db), getAvgRank(challenger, parcours, db) challenger, parcours, db), getAvgRank(challenger, parcours, db)
print('Rank', rank, avgRank)
if rank <= 3 or avgRank <= 3: if rank <= 3 or avgRank <= 3:
await m.broadcast({"type": "newTops", "data": { await m.broadcast({"type": "newTops", "data": {
"tops": getTops(parcours, db), "tops": getTops(parcours, db),
@ -237,15 +247,17 @@ async def corrige(*, correction: List[CorrigedData] = Body(), challenge: Challen
}}, parcours.id_code) }}, parcours.id_code)
await m.broadcast({"type": "challenge_change", await m.broadcast({"type": "challenge_change",
"data": {"challenge": Challenges(**challenge.dict()).dict(), "member": member.id_code}}, "data": {"challenge": Challenges(**challenge.dict()).dict(), "member": member.id_code,
"validated": challenger.validated}},
parcours.id_code, conditions=[lambda m: m.member.is_admin or m.member.id_code == member.id_code]) parcours.id_code, conditions=[lambda m: m.member.is_admin or m.member.id_code == member.id_code])
return {**ChallengeRead(**challenge.dict()).dict(), "challenger": {"name": obj.username}} return {**ChallengeRead(**challenge.dict()).dict(), "challenger": {"name": obj.username}}
return {**ChallengeRead.from_orm(challenge).dict(), "challenger": {"name": obj.username, }} # return {**ChallengeRead.from_orm(challenge).dict(), "challenger": {"name": obj.username, }}
@router.websocket('/ws/room/{room_id}') @router.websocket('/ws/room/{room_id}')
async def room_ws(ws: WebSocket, room: Room | None = Depends(check_room), db: Session = Depends(get_session), m: RoomManager = Depends(get_manager)): async def room_ws(ws: WebSocket, room: Room | None = Depends(check_room), db: Session = Depends(get_session),
m: RoomManager = Depends(get_manager)):
if room is None: if room is None:
raise HTTPException( raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail='Room not found') status_code=status.HTTP_404_NOT_FOUND, detail='Room not found')

311
fold/.svelte-kit/ambient.d.ts vendored Normal file
View File

@ -0,0 +1,311 @@
// this file is generated — do not edit it
/// <reference types="@sveltejs/kit" />
/**
* Environment variables [loaded by Vite](https://vitejs.dev/guide/env-and-mode.html#env-files) from `.env` files and `process.env`. Like [`$env/dynamic/private`](https://kit.svelte.dev/docs/modules#$env-dynamic-private), this module cannot be imported into client-side code. This module only includes variables that _do not_ begin with [`config.kit.env.publicPrefix`](https://kit.svelte.dev/docs/configuration#env).
*
* _Unlike_ [`$env/dynamic/private`](https://kit.svelte.dev/docs/modules#$env-dynamic-private), the values exported from this module are statically injected into your bundle at build time, enabling optimisations like dead code elimination.
*
* ```ts
* import { API_KEY } from '$env/static/private';
* ```
*
* Note that all environment variables referenced in your code should be declared (for example in an `.env` file), even if they don't have a value until the app is deployed:
*
* ```
* MY_FEATURE_FLAG=""
* ```
*
* You can override `.env` values from the command line like so:
*
* ```bash
* MY_FEATURE_FLAG="enabled" npm run dev
* ```
*/
declare module '$env/static/private' {
export const KDE_FULL_SESSION: string;
export const npm_package_devDependencies_vitest: string;
export const USER: string;
export const npm_config_user_agent: string;
export const XDG_SEAT: string;
export const SSH_AGENT_PID: string;
export const XDG_SESSION_TYPE: string;
export const GIT_ASKPASS: string;
export const npm_package_devDependencies_vite: string;
export const npm_node_execpath: string;
export const XCURSOR_SIZE: string;
export const SHLVL: string;
export const HOME: string;
export const CHROME_DESKTOP: string;
export const KDE_APPLICATIONS_AS_SCOPE: string;
export const OLDPWD: string;
export const npm_package_devDependencies__typescript_eslint_parser: string;
export const TERM_PROGRAM_VERSION: string;
export const D_DISABLE_RT_SCREEN_SCALE: string;
export const DESKTOP_SESSION: string;
export const npm_package_devDependencies_eslint_config_prettier: string;
export const npm_package_devDependencies_svelte_preprocess: string;
export const GTK_RC_FILES: string;
export const GTK_MODULES: string;
export const XDG_SEAT_PATH: string;
export const KDE_SESSION_VERSION: string;
export const VSCODE_GIT_ASKPASS_MAIN: string;
export const npm_package_devDependencies_svelte_check: string;
export const VSCODE_GIT_ASKPASS_NODE: string;
export const MANAGERPID: string;
export const npm_package_scripts_check: string;
export const SYSTEMD_EXEC_PID: string;
export const CHROME_EXECUTABLE: string;
export const DBUS_SESSION_BUS_ADDRESS: string;
export const npm_config_engine_strict: string;
export const COLORTERM: string;
export const npm_package_devDependencies_typescript: string;
export const IM_CONFIG_PHASE: string;
export const npm_package_scripts_dev: string;
export const npm_package_devDependencies__playwright_test: string;
export const npm_package_devDependencies_prettier: string;
export const GTK_IM_MODULE: string;
export const LOGNAME: string;
export const npm_package_type: string;
export const QT_AUTO_SCREEN_SCALE_FACTOR: string;
export const JOURNAL_STREAM: string;
export const _: string;
export const npm_package_private: string;
export const npm_package_scripts_check_watch: string;
export const npm_package_devDependencies_node_sass: string;
export const XDG_SESSION_CLASS: string;
export const npm_package_scripts_lint: string;
export const npm_package_devDependencies__typescript_eslint_eslint_plugin: string;
export const npm_config_registry: string;
export const TERM: string;
export const XDG_SESSION_ID: string;
export const npm_package_devDependencies_eslint_plugin_svelte3: string;
export const GTK2_RC_FILES: string;
export const npm_config_node_gyp: string;
export const PATH: string;
export const SESSION_MANAGER: string;
export const INVOCATION_ID: string;
export const GTK3_MODULES: string;
export const npm_package_name: string;
export const NODE: string;
export const XDG_SESSION_PATH: string;
export const XDG_RUNTIME_DIR: string;
export const XCURSOR_THEME: string;
export const GDK_BACKEND: string;
export const DISPLAY: string;
export const npm_package_scripts_test_unit: string;
export const LANG: string;
export const XDG_CURRENT_DESKTOP: string;
export const npm_package_devDependencies_eslint: string;
export const XMODIFIERS: string;
export const XDG_SESSION_DESKTOP: string;
export const XAUTHORITY: string;
export const LS_COLORS: string;
export const VSCODE_GIT_IPC_HANDLE: string;
export const TERM_PROGRAM: string;
export const npm_lifecycle_script: string;
export const SSH_AUTH_SOCK: string;
export const XDG_GREETER_DATA_DIR: string;
export const ORIGINAL_XDG_CURRENT_DESKTOP: string;
export const npm_package_scripts_test: string;
export const npm_package_devDependencies__sveltejs_kit: string;
export const SHELL: string;
export const NODE_PATH: string;
export const npm_package_version: string;
export const npm_lifecycle_event: string;
export const QT_ACCESSIBILITY: string;
export const GDMSESSION: string;
export const npm_package_scripts_build: string;
export const npm_package_devDependencies_svelte: string;
export const npm_package_devDependencies_tslib: string;
export const force_s3tc_enable: string;
export const GPG_AGENT_INFO: string;
export const npm_package_dependencies_sass: string;
export const VSCODE_GIT_ASKPASS_EXTRA_ARGS: string;
export const QT_IM_MODULE: string;
export const XDG_VTNR: string;
export const npm_package_scripts_format: string;
export const PWD: string;
export const npm_execpath: string;
export const XDG_CONFIG_DIRS: string;
export const CLUTTER_IM_MODULE: string;
export const ANDROID_HOME: string;
export const XDG_DATA_DIRS: string;
export const npm_package_devDependencies__sveltejs_adapter_auto: string;
export const PNPM_SCRIPT_SRC_DIR: string;
export const KDE_SESSION_UID: string;
export const npm_package_scripts_preview: string;
export const npm_package_devDependencies_prettier_plugin_svelte: string;
export const PNPM_HOME: string;
export const VTE_VERSION: string;
export const INIT_CWD: string;
export const NODE_ENV: string;
}
/**
* Similar to [`$env/static/private`](https://kit.svelte.dev/docs/modules#$env-static-private), except that it only includes environment variables that begin with [`config.kit.env.publicPrefix`](https://kit.svelte.dev/docs/configuration#env) (which defaults to `PUBLIC_`), and can therefore safely be exposed to client-side code.
*
* Values are replaced statically at build time.
*
* ```ts
* import { PUBLIC_BASE_URL } from '$env/static/public';
* ```
*/
declare module '$env/static/public' {
}
/**
* This module provides access to runtime environment variables, as defined by the platform you're running on. For example if you're using [`adapter-node`](https://github.com/sveltejs/kit/tree/master/packages/adapter-node) (or running [`vite preview`](https://kit.svelte.dev/docs/cli)), this is equivalent to `process.env`. This module only includes variables that _do not_ begin with [`config.kit.env.publicPrefix`](https://kit.svelte.dev/docs/configuration#env).
*
* This module cannot be imported into client-side code.
*
* ```ts
* import { env } from '$env/dynamic/private';
* console.log(env.DEPLOYMENT_SPECIFIC_VARIABLE);
* ```
*
* > In `dev`, `$env/dynamic` always includes environment variables from `.env`. In `prod`, this behavior will depend on your adapter.
*/
declare module '$env/dynamic/private' {
export const env: {
KDE_FULL_SESSION: string;
npm_package_devDependencies_vitest: string;
USER: string;
npm_config_user_agent: string;
XDG_SEAT: string;
SSH_AGENT_PID: string;
XDG_SESSION_TYPE: string;
GIT_ASKPASS: string;
npm_package_devDependencies_vite: string;
npm_node_execpath: string;
XCURSOR_SIZE: string;
SHLVL: string;
HOME: string;
CHROME_DESKTOP: string;
KDE_APPLICATIONS_AS_SCOPE: string;
OLDPWD: string;
npm_package_devDependencies__typescript_eslint_parser: string;
TERM_PROGRAM_VERSION: string;
D_DISABLE_RT_SCREEN_SCALE: string;
DESKTOP_SESSION: string;
npm_package_devDependencies_eslint_config_prettier: string;
npm_package_devDependencies_svelte_preprocess: string;
GTK_RC_FILES: string;
GTK_MODULES: string;
XDG_SEAT_PATH: string;
KDE_SESSION_VERSION: string;
VSCODE_GIT_ASKPASS_MAIN: string;
npm_package_devDependencies_svelte_check: string;
VSCODE_GIT_ASKPASS_NODE: string;
MANAGERPID: string;
npm_package_scripts_check: string;
SYSTEMD_EXEC_PID: string;
CHROME_EXECUTABLE: string;
DBUS_SESSION_BUS_ADDRESS: string;
npm_config_engine_strict: string;
COLORTERM: string;
npm_package_devDependencies_typescript: string;
IM_CONFIG_PHASE: string;
npm_package_scripts_dev: string;
npm_package_devDependencies__playwright_test: string;
npm_package_devDependencies_prettier: string;
GTK_IM_MODULE: string;
LOGNAME: string;
npm_package_type: string;
QT_AUTO_SCREEN_SCALE_FACTOR: string;
JOURNAL_STREAM: string;
_: string;
npm_package_private: string;
npm_package_scripts_check_watch: string;
npm_package_devDependencies_node_sass: string;
XDG_SESSION_CLASS: string;
npm_package_scripts_lint: string;
npm_package_devDependencies__typescript_eslint_eslint_plugin: string;
npm_config_registry: string;
TERM: string;
XDG_SESSION_ID: string;
npm_package_devDependencies_eslint_plugin_svelte3: string;
GTK2_RC_FILES: string;
npm_config_node_gyp: string;
PATH: string;
SESSION_MANAGER: string;
INVOCATION_ID: string;
GTK3_MODULES: string;
npm_package_name: string;
NODE: string;
XDG_SESSION_PATH: string;
XDG_RUNTIME_DIR: string;
XCURSOR_THEME: string;
GDK_BACKEND: string;
DISPLAY: string;
npm_package_scripts_test_unit: string;
LANG: string;
XDG_CURRENT_DESKTOP: string;
npm_package_devDependencies_eslint: string;
XMODIFIERS: string;
XDG_SESSION_DESKTOP: string;
XAUTHORITY: string;
LS_COLORS: string;
VSCODE_GIT_IPC_HANDLE: string;
TERM_PROGRAM: string;
npm_lifecycle_script: string;
SSH_AUTH_SOCK: string;
XDG_GREETER_DATA_DIR: string;
ORIGINAL_XDG_CURRENT_DESKTOP: string;
npm_package_scripts_test: string;
npm_package_devDependencies__sveltejs_kit: string;
SHELL: string;
NODE_PATH: string;
npm_package_version: string;
npm_lifecycle_event: string;
QT_ACCESSIBILITY: string;
GDMSESSION: string;
npm_package_scripts_build: string;
npm_package_devDependencies_svelte: string;
npm_package_devDependencies_tslib: string;
force_s3tc_enable: string;
GPG_AGENT_INFO: string;
npm_package_dependencies_sass: string;
VSCODE_GIT_ASKPASS_EXTRA_ARGS: string;
QT_IM_MODULE: string;
XDG_VTNR: string;
npm_package_scripts_format: string;
PWD: string;
npm_execpath: string;
XDG_CONFIG_DIRS: string;
CLUTTER_IM_MODULE: string;
ANDROID_HOME: string;
XDG_DATA_DIRS: string;
npm_package_devDependencies__sveltejs_adapter_auto: string;
PNPM_SCRIPT_SRC_DIR: string;
KDE_SESSION_UID: string;
npm_package_scripts_preview: string;
npm_package_devDependencies_prettier_plugin_svelte: string;
PNPM_HOME: string;
VTE_VERSION: string;
INIT_CWD: string;
NODE_ENV: string;
[key: `PUBLIC_${string}`]: undefined;
[key: string]: string | undefined;
}
}
/**
* Similar to [`$env/dynamic/private`](https://kit.svelte.dev/docs/modules#$env-dynamic-private), but only includes variables that begin with [`config.kit.env.publicPrefix`](https://kit.svelte.dev/docs/configuration#env) (which defaults to `PUBLIC_`), and can therefore safely be exposed to client-side code.
*
* Note that public dynamic environment variables must all be sent from the server to the client, causing larger network requests when possible, use `$env/static/public` instead.
*
* ```ts
* import { env } from '$env/dynamic/public';
* console.log(env.PUBLIC_DEPLOYMENT_SPECIFIC_VARIABLE);
* ```
*/
declare module '$env/dynamic/public' {
export const env: {
[key: `PUBLIC_${string}`]: string | undefined;
}
}

View File

@ -0,0 +1,17 @@
export { matchers } from './client-matchers.js';
export const nodes = [() => import('./nodes/0'),
() => import('./nodes/1'),
() => import('./nodes/2'),
() => import('./nodes/3')];
export const server_loads = [];
export const dictionary = {
"/": [2],
"/exercices/[[slug]]": [3]
};
export const hooks = {
handleError: (({ error }) => { console.error(error) }),
};

View File

@ -0,0 +1 @@
export const matchers = {};

View File

@ -0,0 +1 @@
export { default as component } from "../../../src/routes/+layout.svelte";

View File

@ -0,0 +1 @@
export { default as component } from "../../../node_modules/.pnpm/@sveltejs+kit@1.0.1_svelte@3.55.0+vite@4.0.3/node_modules/@sveltejs/kit/src/runtime/components/error.svelte";

View File

@ -0,0 +1 @@
export { default as component } from "../../../src/routes/+page.svelte";

View File

@ -0,0 +1,3 @@
import * as universal from "../../../src/routes/exercices/[[slug]]/+page.js";
export { universal };
export { default as component } from "../../../src/routes/exercices/[[slug]]/+page.svelte";

View File

@ -0,0 +1,53 @@
<!-- This file is generated by @sveltejs/kit — do not edit it! -->
<script>
import { setContext, afterUpdate, onMount } from 'svelte';
import { browser } from '$app/environment';
// stores
export let stores;
export let page;
export let components;
export let form;
export let data_0 = null;
export let data_1 = null;
if (!browser) {
setContext('__svelte__', stores);
}
$: stores.page.set(page);
afterUpdate(stores.page.notify);
let mounted = false;
let navigated = false;
let title = null;
onMount(() => {
const unsubscribe = stores.page.subscribe(() => {
if (mounted) {
navigated = true;
title = document.title || 'untitled page';
}
});
mounted = true;
return unsubscribe;
});
</script>
{#if components[1]}
<svelte:component this={components[0]} data={data_0}>
<svelte:component this={components[1]} data={data_1} {form} />
</svelte:component>
{:else}
<svelte:component this={components[0]} data={data_0} {form} />
{/if}
{#if mounted}
<div id="svelte-announcer" aria-live="assertive" aria-atomic="true" style="position: absolute; left: 0; top: 0; clip: rect(0 0 0 0); clip-path: inset(50%); overflow: hidden; white-space: nowrap; width: 1px; height: 1px">
{#if navigated}
{title}
{/if}
</div>
{/if}

View File

@ -0,0 +1,39 @@
{
"compilerOptions": {
"baseUrl": "..",
"paths": {},
"rootDirs": [
"..",
"./types"
],
"importsNotUsedAsValues": "error",
"isolatedModules": true,
"preserveValueImports": true,
"lib": [
"esnext",
"DOM",
"DOM.Iterable"
],
"moduleResolution": "node",
"module": "esnext",
"target": "esnext"
},
"include": [
"ambient.d.ts",
"./types/**/$types.d.ts",
"../vite.config.ts",
"../src/**/*.js",
"../src/**/*.ts",
"../src/**/*.svelte",
"../src/**/*.js",
"../src/**/*.ts",
"../src/**/*.svelte",
"../tests/**/*.js",
"../tests/**/*.ts",
"../tests/**/*.svelte"
],
"exclude": [
"../node_modules/**",
"./[!ambient.d.ts]**"
]
}

View File

@ -0,0 +1,6 @@
{
"/": [],
"/exercices/[[slug]]": [
"src/routes/exercices/[[slug]]/+page.js"
]
}

View File

@ -0,0 +1,19 @@
import type * as Kit from '@sveltejs/kit';
type Expand<T> = T extends infer O ? { [K in keyof O]: O[K] } : never;
type RouteParams = { }
type RouteId = '/';
type MaybeWithVoid<T> = {} extends T ? T | void : T;
export type RequiredKeys<T> = { [K in keyof T]-?: {} extends { [P in K]: T[K] } ? never : K; }[keyof T];
type OutputDataShape<T> = MaybeWithVoid<Omit<App.PageData, RequiredKeys<T>> & Partial<Pick<App.PageData, keyof T & keyof App.PageData>> & Record<string, any>>
type EnsureDefined<T> = T extends null | undefined ? {} : T;
type OptionalUnion<U extends Record<string, any>, A extends keyof U = U extends U ? keyof U : never> = U extends unknown ? { [P in Exclude<A, keyof U>]?: never } & U : never;
type PageParentData = EnsureDefined<LayoutData>;
type LayoutRouteId = RouteId | "/" | "/exercices/[[slug]]" | null
type LayoutParams = RouteParams & { slug?: string }
type LayoutParentData = EnsureDefined<{}>;
export type PageServerData = null;
export type PageData = Expand<PageParentData>;
export type LayoutServerData = null;
export type LayoutData = Expand<LayoutParentData>;

View File

@ -0,0 +1,14 @@
import type * as Kit from '@sveltejs/kit';
type Expand<T> = T extends infer O ? { [K in keyof O]: O[K] } : never;
type RouteParams = { }
type RouteId = '/exercices';
type MaybeWithVoid<T> = {} extends T ? T | void : T;
export type RequiredKeys<T> = { [K in keyof T]-?: {} extends { [P in K]: T[K] } ? never : K; }[keyof T];
type OutputDataShape<T> = MaybeWithVoid<Omit<App.PageData, RequiredKeys<T>> & Partial<Pick<App.PageData, keyof T & keyof App.PageData>> & Record<string, any>>
type EnsureDefined<T> = T extends null | undefined ? {} : T;
type OptionalUnion<U extends Record<string, any>, A extends keyof U = U extends U ? keyof U : never> = U extends unknown ? { [P in Exclude<A, keyof U>]?: never } & U : never;
type PageParentData = EnsureDefined<import('../$types.js').LayoutData>;
export type PageServerData = null;
export type PageData = Expand<PageParentData>;

View File

@ -0,0 +1,16 @@
import type * as Kit from '@sveltejs/kit';
type Expand<T> = T extends infer O ? { [K in keyof O]: O[K] } : never;
type RouteParams = { slug?: string }
type RouteId = '/exercices/[[slug]]';
type MaybeWithVoid<T> = {} extends T ? T | void : T;
export type RequiredKeys<T> = { [K in keyof T]-?: {} extends { [P in K]: T[K] } ? never : K; }[keyof T];
type OutputDataShape<T> = MaybeWithVoid<Omit<App.PageData, RequiredKeys<T>> & Partial<Pick<App.PageData, keyof T & keyof App.PageData>> & Record<string, any>>
type EnsureDefined<T> = T extends null | undefined ? {} : T;
type OptionalUnion<U extends Record<string, any>, A extends keyof U = U extends U ? keyof U : never> = U extends unknown ? { [P in Exclude<A, keyof U>]?: never } & U : never;
type PageParentData = EnsureDefined<import('../../$types.js').LayoutData>;
export type PageServerData = null;
export type PageLoad<OutputData extends OutputDataShape<PageParentData> = OutputDataShape<PageParentData>> = Kit.Load<RouteParams, PageServerData, PageParentData, OutputData, RouteId>;
export type PageLoadEvent = Parameters<PageLoad>[0];
export type PageData = Expand<Omit<PageParentData, keyof Kit.AwaitedProperties<Awaited<ReturnType<typeof import('./proxy+page.js').load>>>> & OptionalUnion<EnsureDefined<Kit.AwaitedProperties<Awaited<ReturnType<typeof import('./proxy+page.js').load>>>>>>;

View File

@ -0,0 +1,11 @@
// @ts-nocheck
/** @param {Parameters<import('./$types').PageLoad>[0]} event */
export function load({params, url}) {
return {
post: {
title: `Title for ${params.slug} goes here`,
content: `Content for ${params.slug} goes here ${url.searchParams}`
}
};
}

17
fold/node_modules/.bin/eslint generated vendored Executable file
View File

@ -0,0 +1,17 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -z "$NODE_PATH" ]; then
export NODE_PATH="/home/lilian/Dev/project/fastapi_gen/frontend/node_modules/.pnpm/node_modules"
else
export NODE_PATH="$NODE_PATH:/home/lilian/Dev/project/fastapi_gen/frontend/node_modules/.pnpm/node_modules"
fi
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../eslint/bin/eslint.js" "$@"
else
exec node "$basedir/../eslint/bin/eslint.js" "$@"
fi

17
fold/node_modules/.bin/eslint-config-prettier generated vendored Executable file
View File

@ -0,0 +1,17 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -z "$NODE_PATH" ]; then
export NODE_PATH="/home/lilian/Dev/project/fastapi_gen/frontend/node_modules/.pnpm/node_modules"
else
export NODE_PATH="$NODE_PATH:/home/lilian/Dev/project/fastapi_gen/frontend/node_modules/.pnpm/node_modules"
fi
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../eslint-config-prettier/bin/cli.js" "$@"
else
exec node "$basedir/../eslint-config-prettier/bin/cli.js" "$@"
fi

17
fold/node_modules/.bin/node-sass generated vendored Executable file
View File

@ -0,0 +1,17 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -z "$NODE_PATH" ]; then
export NODE_PATH="/home/lilian/Dev/project/fastapi_gen/frontend/node_modules/.pnpm/node_modules"
else
export NODE_PATH="$NODE_PATH:/home/lilian/Dev/project/fastapi_gen/frontend/node_modules/.pnpm/node_modules"
fi
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../node-sass/bin/node-sass" "$@"
else
exec node "$basedir/../node-sass/bin/node-sass" "$@"
fi

17
fold/node_modules/.bin/playwright generated vendored Executable file
View File

@ -0,0 +1,17 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -z "$NODE_PATH" ]; then
export NODE_PATH="/home/lilian/Dev/project/fastapi_gen/frontend/node_modules/.pnpm/node_modules"
else
export NODE_PATH="$NODE_PATH:/home/lilian/Dev/project/fastapi_gen/frontend/node_modules/.pnpm/node_modules"
fi
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../@playwright/test/cli.js" "$@"
else
exec node "$basedir/../@playwright/test/cli.js" "$@"
fi

17
fold/node_modules/.bin/prettier generated vendored Executable file
View File

@ -0,0 +1,17 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -z "$NODE_PATH" ]; then
export NODE_PATH="/home/lilian/Dev/project/fastapi_gen/frontend/node_modules/.pnpm/node_modules"
else
export NODE_PATH="$NODE_PATH:/home/lilian/Dev/project/fastapi_gen/frontend/node_modules/.pnpm/node_modules"
fi
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../prettier/bin-prettier.js" "$@"
else
exec node "$basedir/../prettier/bin-prettier.js" "$@"
fi

17
fold/node_modules/.bin/sass generated vendored Executable file
View File

@ -0,0 +1,17 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -z "$NODE_PATH" ]; then
export NODE_PATH="/home/lilian/Dev/project/fastapi_gen/frontend/node_modules/.pnpm/node_modules"
else
export NODE_PATH="$NODE_PATH:/home/lilian/Dev/project/fastapi_gen/frontend/node_modules/.pnpm/node_modules"
fi
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../sass/sass.js" "$@"
else
exec node "$basedir/../sass/sass.js" "$@"
fi

17
fold/node_modules/.bin/svelte-check generated vendored Executable file
View File

@ -0,0 +1,17 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -z "$NODE_PATH" ]; then
export NODE_PATH="/home/lilian/Dev/project/fastapi_gen/frontend/node_modules/.pnpm/node_modules"
else
export NODE_PATH="$NODE_PATH:/home/lilian/Dev/project/fastapi_gen/frontend/node_modules/.pnpm/node_modules"
fi
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../svelte-check/bin/svelte-check" "$@"
else
exec node "$basedir/../svelte-check/bin/svelte-check" "$@"
fi

17
fold/node_modules/.bin/svelte-kit generated vendored Executable file
View File

@ -0,0 +1,17 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -z "$NODE_PATH" ]; then
export NODE_PATH="/home/lilian/Dev/project/fastapi_gen/frontend/node_modules/.pnpm/node_modules"
else
export NODE_PATH="$NODE_PATH:/home/lilian/Dev/project/fastapi_gen/frontend/node_modules/.pnpm/node_modules"
fi
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../@sveltejs/kit/svelte-kit.js" "$@"
else
exec node "$basedir/../@sveltejs/kit/svelte-kit.js" "$@"
fi

17
fold/node_modules/.bin/tsc generated vendored Executable file
View File

@ -0,0 +1,17 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -z "$NODE_PATH" ]; then
export NODE_PATH="/home/lilian/Dev/project/fastapi_gen/frontend/node_modules/.pnpm/node_modules"
else
export NODE_PATH="$NODE_PATH:/home/lilian/Dev/project/fastapi_gen/frontend/node_modules/.pnpm/node_modules"
fi
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../typescript/bin/tsc" "$@"
else
exec node "$basedir/../typescript/bin/tsc" "$@"
fi

17
fold/node_modules/.bin/tsserver generated vendored Executable file
View File

@ -0,0 +1,17 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -z "$NODE_PATH" ]; then
export NODE_PATH="/home/lilian/Dev/project/fastapi_gen/frontend/node_modules/.pnpm/node_modules"
else
export NODE_PATH="$NODE_PATH:/home/lilian/Dev/project/fastapi_gen/frontend/node_modules/.pnpm/node_modules"
fi
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../typescript/bin/tsserver" "$@"
else
exec node "$basedir/../typescript/bin/tsserver" "$@"
fi

17
fold/node_modules/.bin/vite generated vendored Executable file
View File

@ -0,0 +1,17 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -z "$NODE_PATH" ]; then
export NODE_PATH="/home/lilian/Dev/project/fastapi_gen/frontend/node_modules/.pnpm/node_modules"
else
export NODE_PATH="$NODE_PATH:/home/lilian/Dev/project/fastapi_gen/frontend/node_modules/.pnpm/node_modules"
fi
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../vite/bin/vite.js" "$@"
else
exec node "$basedir/../vite/bin/vite.js" "$@"
fi

17
fold/node_modules/.bin/vitest generated vendored Executable file
View File

@ -0,0 +1,17 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -z "$NODE_PATH" ]; then
export NODE_PATH="/home/lilian/Dev/project/fastapi_gen/frontend/node_modules/.pnpm/node_modules"
else
export NODE_PATH="$NODE_PATH:/home/lilian/Dev/project/fastapi_gen/frontend/node_modules/.pnpm/node_modules"
fi
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../vitest/vitest.mjs" "$@"
else
exec node "$basedir/../vitest/vitest.mjs" "$@"
fi

735
fold/node_modules/.modules.yaml generated vendored Normal file
View File

@ -0,0 +1,735 @@
hoistPattern:
- '*'
hoistedDependencies:
/@babel/code-frame/7.18.6:
'@babel/code-frame': private
/@babel/helper-validator-identifier/7.19.1:
'@babel/helper-validator-identifier': private
/@babel/highlight/7.18.6:
'@babel/highlight': private
/@esbuild/android-arm/0.16.11:
'@esbuild/android-arm': private
/@esbuild/android-arm64/0.16.11:
'@esbuild/android-arm64': private
/@esbuild/android-x64/0.16.11:
'@esbuild/android-x64': private
/@esbuild/darwin-arm64/0.16.11:
'@esbuild/darwin-arm64': private
/@esbuild/darwin-x64/0.16.11:
'@esbuild/darwin-x64': private
/@esbuild/freebsd-arm64/0.16.11:
'@esbuild/freebsd-arm64': private
/@esbuild/freebsd-x64/0.16.11:
'@esbuild/freebsd-x64': private
/@esbuild/linux-arm/0.16.11:
'@esbuild/linux-arm': private
/@esbuild/linux-arm64/0.16.11:
'@esbuild/linux-arm64': private
/@esbuild/linux-ia32/0.16.11:
'@esbuild/linux-ia32': private
/@esbuild/linux-loong64/0.16.11:
'@esbuild/linux-loong64': private
/@esbuild/linux-mips64el/0.16.11:
'@esbuild/linux-mips64el': private
/@esbuild/linux-ppc64/0.16.11:
'@esbuild/linux-ppc64': private
/@esbuild/linux-riscv64/0.16.11:
'@esbuild/linux-riscv64': private
/@esbuild/linux-s390x/0.16.11:
'@esbuild/linux-s390x': private
/@esbuild/linux-x64/0.16.11:
'@esbuild/linux-x64': private
/@esbuild/netbsd-x64/0.16.11:
'@esbuild/netbsd-x64': private
/@esbuild/openbsd-x64/0.16.11:
'@esbuild/openbsd-x64': private
/@esbuild/sunos-x64/0.16.11:
'@esbuild/sunos-x64': private
/@esbuild/win32-arm64/0.16.11:
'@esbuild/win32-arm64': private
/@esbuild/win32-ia32/0.16.11:
'@esbuild/win32-ia32': private
/@esbuild/win32-x64/0.16.11:
'@esbuild/win32-x64': private
/@eslint/eslintrc/1.4.0:
'@eslint/eslintrc': public
/@gar/promisify/1.1.3:
'@gar/promisify': private
/@humanwhocodes/config-array/0.11.8:
'@humanwhocodes/config-array': private
/@humanwhocodes/module-importer/1.0.1:
'@humanwhocodes/module-importer': private
/@humanwhocodes/object-schema/1.2.1:
'@humanwhocodes/object-schema': private
/@jridgewell/resolve-uri/3.1.0:
'@jridgewell/resolve-uri': private
/@jridgewell/sourcemap-codec/1.4.14:
'@jridgewell/sourcemap-codec': private
/@jridgewell/trace-mapping/0.3.17:
'@jridgewell/trace-mapping': private
/@nodelib/fs.scandir/2.1.5:
'@nodelib/fs.scandir': private
/@nodelib/fs.stat/2.0.5:
'@nodelib/fs.stat': private
/@nodelib/fs.walk/1.2.8:
'@nodelib/fs.walk': private
/@npmcli/fs/2.1.2:
'@npmcli/fs': private
/@npmcli/move-file/2.0.1:
'@npmcli/move-file': private
/@polka/url/1.0.0-next.21:
'@polka/url': private
/@sveltejs/vite-plugin-svelte/2.0.2_svelte@3.55.0+vite@4.0.3:
'@sveltejs/vite-plugin-svelte': private
/@tootallnate/once/2.0.0:
'@tootallnate/once': private
/@types/chai-subset/1.3.3:
'@types/chai-subset': private
/@types/chai/4.3.4:
'@types/chai': private
/@types/cookie/0.5.1:
'@types/cookie': private
/@types/json-schema/7.0.11:
'@types/json-schema': private
/@types/minimist/1.2.2:
'@types/minimist': private
/@types/node/18.11.18:
'@types/node': private
/@types/normalize-package-data/2.4.1:
'@types/normalize-package-data': private
/@types/pug/2.0.6:
'@types/pug': private
/@types/sass/1.43.1:
'@types/sass': private
/@types/semver/7.3.13:
'@types/semver': private
/@typescript-eslint/scope-manager/5.47.1:
'@typescript-eslint/scope-manager': public
/@typescript-eslint/type-utils/5.47.1_lzzuuodtsqwxnvqeq4g4likcqa:
'@typescript-eslint/type-utils': public
/@typescript-eslint/types/5.47.1:
'@typescript-eslint/types': public
/@typescript-eslint/typescript-estree/5.47.1_typescript@4.9.4:
'@typescript-eslint/typescript-estree': public
/@typescript-eslint/utils/5.47.1_lzzuuodtsqwxnvqeq4g4likcqa:
'@typescript-eslint/utils': public
/@typescript-eslint/visitor-keys/5.47.1:
'@typescript-eslint/visitor-keys': public
/abbrev/1.1.1:
abbrev: private
/acorn-jsx/5.3.2_acorn@8.8.1:
acorn-jsx: private
/acorn-walk/8.2.0:
acorn-walk: private
/acorn/8.8.1:
acorn: private
/agent-base/6.0.2:
agent-base: private
/agentkeepalive/4.2.1:
agentkeepalive: private
/aggregate-error/3.1.0:
aggregate-error: private
/ajv/6.12.6:
ajv: private
/ansi-regex/5.0.1:
ansi-regex: private
/ansi-styles/4.3.0:
ansi-styles: private
/anymatch/3.1.3:
anymatch: private
/aproba/2.0.0:
aproba: private
/are-we-there-yet/3.0.1:
are-we-there-yet: private
/argparse/2.0.1:
argparse: private
/array-union/2.1.0:
array-union: private
/arrify/1.0.1:
arrify: private
/assertion-error/1.1.0:
assertion-error: private
/async-foreach/0.1.3:
async-foreach: private
/balanced-match/1.0.2:
balanced-match: private
/binary-extensions/2.2.0:
binary-extensions: private
/brace-expansion/1.1.11:
brace-expansion: private
/braces/3.0.2:
braces: private
/buffer-crc32/0.2.13:
buffer-crc32: private
/busboy/1.6.0:
busboy: private
/cacache/16.1.3:
cacache: private
/callsites/3.1.0:
callsites: private
/camelcase-keys/6.2.2:
camelcase-keys: private
/camelcase/5.3.1:
camelcase: private
/chai/4.3.7:
chai: private
/chalk/4.1.2:
chalk: private
/check-error/1.0.2:
check-error: private
/chokidar/3.5.3:
chokidar: private
/chownr/2.0.0:
chownr: private
/clean-stack/2.2.0:
clean-stack: private
/cliui/8.0.1:
cliui: private
/color-convert/2.0.1:
color-convert: private
/color-name/1.1.4:
color-name: private
/color-support/1.1.3:
color-support: private
/concat-map/0.0.1:
concat-map: private
/console-control-strings/1.1.0:
console-control-strings: private
/cookie/0.5.0:
cookie: private
/core-util-is/1.0.3:
core-util-is: private
/cross-spawn/7.0.3:
cross-spawn: private
/debug/4.3.4:
debug: private
/decamelize-keys/1.1.1:
decamelize-keys: private
/decamelize/1.2.0:
decamelize: private
/deep-eql/4.1.3:
deep-eql: private
/deep-is/0.1.4:
deep-is: private
/deepmerge/4.2.2:
deepmerge: private
/delegates/1.0.0:
delegates: private
/depd/1.1.2:
depd: private
/detect-indent/6.1.0:
detect-indent: private
/devalue/4.2.0:
devalue: private
/dir-glob/3.0.1:
dir-glob: private
/doctrine/3.0.0:
doctrine: private
/emoji-regex/8.0.0:
emoji-regex: private
/encoding/0.1.13:
encoding: private
/env-paths/2.2.1:
env-paths: private
/err-code/2.0.3:
err-code: private
/error-ex/1.3.2:
error-ex: private
/es6-promise/3.3.1:
es6-promise: private
/esbuild/0.16.11:
esbuild: private
/escalade/3.1.1:
escalade: private
/escape-string-regexp/4.0.0:
escape-string-regexp: private
/eslint-scope/7.1.1:
eslint-scope: public
/eslint-utils/3.0.0_eslint@8.30.0:
eslint-utils: public
/eslint-visitor-keys/3.3.0:
eslint-visitor-keys: public
/esm-env/1.0.0:
esm-env: private
/espree/9.4.1:
espree: private
/esquery/1.4.0:
esquery: private
/esrecurse/4.3.0:
esrecurse: private
/estraverse/5.3.0:
estraverse: private
/esutils/2.0.3:
esutils: private
/fast-deep-equal/3.1.3:
fast-deep-equal: private
/fast-glob/3.2.12:
fast-glob: private
/fast-json-stable-stringify/2.1.0:
fast-json-stable-stringify: private
/fast-levenshtein/2.0.6:
fast-levenshtein: private
/fastq/1.14.0:
fastq: private
/file-entry-cache/6.0.1:
file-entry-cache: private
/fill-range/7.0.1:
fill-range: private
/find-up/5.0.0:
find-up: private
/flat-cache/3.0.4:
flat-cache: private
/flatted/3.2.7:
flatted: private
/fs-minipass/2.1.0:
fs-minipass: private
/fs.realpath/1.0.0:
fs.realpath: private
/fsevents/2.3.2:
fsevents: private
/function-bind/1.1.1:
function-bind: private
/gauge/4.0.4:
gauge: private
/gaze/1.1.3:
gaze: private
/get-caller-file/2.0.5:
get-caller-file: private
/get-func-name/2.0.0:
get-func-name: private
/get-stdin/4.0.1:
get-stdin: private
/glob-parent/6.0.2:
glob-parent: private
/glob/7.2.3:
glob: private
/globals/13.19.0:
globals: private
/globalyzer/0.1.0:
globalyzer: private
/globby/11.1.0:
globby: private
/globrex/0.1.2:
globrex: private
/globule/1.3.4:
globule: private
/graceful-fs/4.2.10:
graceful-fs: private
/grapheme-splitter/1.0.4:
grapheme-splitter: private
/hard-rejection/2.1.0:
hard-rejection: private
/has-flag/4.0.0:
has-flag: private
/has-unicode/2.0.1:
has-unicode: private
/has/1.0.3:
has: private
/hosted-git-info/4.1.0:
hosted-git-info: private
/http-cache-semantics/4.1.0:
http-cache-semantics: private
/http-proxy-agent/5.0.0:
http-proxy-agent: private
/https-proxy-agent/5.0.1:
https-proxy-agent: private
/humanize-ms/1.2.1:
humanize-ms: private
/iconv-lite/0.6.3:
iconv-lite: private
/ignore/5.2.4:
ignore: private
/immutable/4.2.1:
immutable: private
/import-fresh/3.3.0:
import-fresh: private
/import-meta-resolve/2.2.0:
import-meta-resolve: private
/imurmurhash/0.1.4:
imurmurhash: private
/indent-string/4.0.0:
indent-string: private
/infer-owner/1.0.4:
infer-owner: private
/inflight/1.0.6:
inflight: private
/inherits/2.0.4:
inherits: private
/ip/2.0.0:
ip: private
/is-arrayish/0.2.1:
is-arrayish: private
/is-binary-path/2.1.0:
is-binary-path: private
/is-core-module/2.11.0:
is-core-module: private
/is-extglob/2.1.1:
is-extglob: private
/is-fullwidth-code-point/3.0.0:
is-fullwidth-code-point: private
/is-glob/4.0.3:
is-glob: private
/is-lambda/1.0.1:
is-lambda: private
/is-number/7.0.0:
is-number: private
/is-path-inside/3.0.3:
is-path-inside: private
/is-plain-obj/1.1.0:
is-plain-obj: private
/isarray/1.0.0:
isarray: private
/isexe/2.0.0:
isexe: private
/js-base64/2.6.4:
js-base64: private
/js-sdsl/4.2.0:
js-sdsl: private
/js-tokens/4.0.0:
js-tokens: private
/js-yaml/4.1.0:
js-yaml: private
/json-parse-even-better-errors/2.3.1:
json-parse-even-better-errors: private
/json-schema-traverse/0.4.1:
json-schema-traverse: private
/json-stable-stringify-without-jsonify/1.0.1:
json-stable-stringify-without-jsonify: private
/kind-of/6.0.3:
kind-of: private
/kleur/4.1.5:
kleur: private
/levn/0.4.1:
levn: private
/lines-and-columns/1.2.4:
lines-and-columns: private
/local-pkg/0.4.2:
local-pkg: private
/locate-path/6.0.0:
locate-path: private
/lodash.merge/4.6.2:
lodash.merge: private
/lodash/4.17.21:
lodash: private
/loupe/2.3.6:
loupe: private
/lru-cache/7.14.1:
lru-cache: private
/magic-string/0.27.0:
magic-string: private
/make-fetch-happen/10.2.1:
make-fetch-happen: private
/map-obj/4.3.0:
map-obj: private
/meow/9.0.0:
meow: private
/merge2/1.4.1:
merge2: private
/micromatch/4.0.5:
micromatch: private
/mime/3.0.0:
mime: private
/min-indent/1.0.1:
min-indent: private
/minimatch/3.1.2:
minimatch: private
/minimist-options/4.1.0:
minimist-options: private
/minimist/1.2.7:
minimist: private
/minipass-collect/1.0.2:
minipass-collect: private
/minipass-fetch/2.1.2:
minipass-fetch: private
/minipass-flush/1.0.5:
minipass-flush: private
/minipass-pipeline/1.2.4:
minipass-pipeline: private
/minipass-sized/1.0.3:
minipass-sized: private
/minipass/3.3.6:
minipass: private
/minizlib/2.1.2:
minizlib: private
/mkdirp/1.0.4:
mkdirp: private
/mri/1.2.0:
mri: private
/mrmime/1.0.1:
mrmime: private
/ms/2.1.2:
ms: private
/nan/2.17.0:
nan: private
/nanoid/3.3.4:
nanoid: private
/natural-compare-lite/1.4.0:
natural-compare-lite: private
/natural-compare/1.4.0:
natural-compare: private
/negotiator/0.6.3:
negotiator: private
/node-gyp/8.4.1:
node-gyp: private
/nopt/5.0.0:
nopt: private
/normalize-package-data/3.0.3:
normalize-package-data: private
/normalize-path/3.0.0:
normalize-path: private
/npmlog/6.0.2:
npmlog: private
/once/1.4.0:
once: private
/optionator/0.9.1:
optionator: private
/p-limit/3.1.0:
p-limit: private
/p-locate/5.0.0:
p-locate: private
/p-map/4.0.0:
p-map: private
/p-try/2.2.0:
p-try: private
/parent-module/1.0.1:
parent-module: private
/parse-json/5.2.0:
parse-json: private
/path-exists/4.0.0:
path-exists: private
/path-is-absolute/1.0.1:
path-is-absolute: private
/path-key/3.1.1:
path-key: private
/path-parse/1.0.7:
path-parse: private
/path-type/4.0.0:
path-type: private
/pathval/1.1.1:
pathval: private
/picocolors/1.0.0:
picocolors: private
/picomatch/2.3.1:
picomatch: private
/playwright-core/1.29.1:
playwright-core: private
/postcss/8.4.20:
postcss: private
/prelude-ls/1.2.1:
prelude-ls: private
/process-nextick-args/2.0.1:
process-nextick-args: private
/promise-inflight/1.0.1:
promise-inflight: private
/promise-retry/2.0.1:
promise-retry: private
/punycode/2.1.1:
punycode: private
/queue-microtask/1.2.3:
queue-microtask: private
/quick-lru/4.0.1:
quick-lru: private
/read-pkg-up/7.0.1:
read-pkg-up: private
/read-pkg/5.2.0:
read-pkg: private
/readable-stream/2.3.7:
readable-stream: private
/readdirp/3.6.0:
readdirp: private
/redent/3.0.0:
redent: private
/regexpp/3.2.0:
regexpp: private
/require-directory/2.1.1:
require-directory: private
/resolve-from/4.0.0:
resolve-from: private
/resolve/1.22.1:
resolve: private
/retry/0.12.0:
retry: private
/reusify/1.0.4:
reusify: private
/rimraf/3.0.2:
rimraf: private
/rollup/3.8.1:
rollup: private
/run-parallel/1.2.0:
run-parallel: private
/sade/1.8.1:
sade: private
/safe-buffer/5.1.2:
safe-buffer: private
/safer-buffer/2.1.2:
safer-buffer: private
/sander/0.5.1:
sander: private
/sass-graph/4.0.1:
sass-graph: private
/scss-tokenizer/0.4.3:
scss-tokenizer: private
/semver/7.3.8:
semver: private
/set-blocking/2.0.0:
set-blocking: private
/set-cookie-parser/2.5.1:
set-cookie-parser: private
/shebang-command/2.0.0:
shebang-command: private
/shebang-regex/3.0.0:
shebang-regex: private
/signal-exit/3.0.7:
signal-exit: private
/sirv/2.0.2:
sirv: private
/slash/3.0.0:
slash: private
/smart-buffer/4.2.0:
smart-buffer: private
/socks-proxy-agent/7.0.0:
socks-proxy-agent: private
/socks/2.7.1:
socks: private
/sorcery/0.10.0:
sorcery: private
/source-map-js/1.0.2:
source-map-js: private
/source-map/0.6.1:
source-map: private
/sourcemap-codec/1.4.8:
sourcemap-codec: private
/spdx-correct/3.1.1:
spdx-correct: private
/spdx-exceptions/2.3.0:
spdx-exceptions: private
/spdx-expression-parse/3.0.1:
spdx-expression-parse: private
/spdx-license-ids/3.0.12:
spdx-license-ids: private
/ssri/9.0.1:
ssri: private
/stdout-stream/1.4.1:
stdout-stream: private
/streamsearch/1.1.0:
streamsearch: private
/string-width/4.2.3:
string-width: private
/string_decoder/1.1.1:
string_decoder: private
/strip-ansi/6.0.1:
strip-ansi: private
/strip-indent/3.0.0:
strip-indent: private
/strip-json-comments/3.1.1:
strip-json-comments: private
/strip-literal/1.0.0:
strip-literal: private
/supports-color/7.2.0:
supports-color: private
/supports-preserve-symlinks-flag/1.0.0:
supports-preserve-symlinks-flag: private
/svelte-hmr/0.15.1_svelte@3.55.0:
svelte-hmr: private
/tar/6.1.13:
tar: private
/text-table/0.2.0:
text-table: private
/tiny-glob/0.2.9:
tiny-glob: private
/tinybench/2.3.1:
tinybench: private
/tinypool/0.3.0:
tinypool: private
/tinyspy/1.0.2:
tinyspy: private
/to-regex-range/5.0.1:
to-regex-range: private
/totalist/3.0.0:
totalist: private
/trim-newlines/3.0.1:
trim-newlines: private
/true-case-path/2.2.1:
true-case-path: private
/tsutils/3.21.0_typescript@4.9.4:
tsutils: private
/type-check/0.4.0:
type-check: private
/type-detect/4.0.8:
type-detect: private
/type-fest/0.20.2:
type-fest: private
/undici/5.14.0:
undici: private
/unique-filename/2.0.1:
unique-filename: private
/unique-slug/3.0.0:
unique-slug: private
/uri-js/4.4.1:
uri-js: private
/util-deprecate/1.0.2:
util-deprecate: private
/validate-npm-package-license/3.0.4:
validate-npm-package-license: private
/vitefu/0.2.4_vite@4.0.3:
vitefu: private
/which/2.0.2:
which: private
/wide-align/1.1.5:
wide-align: private
/word-wrap/1.2.3:
word-wrap: private
/wrap-ansi/7.0.0:
wrap-ansi: private
/wrappy/1.0.2:
wrappy: private
/y18n/5.0.8:
y18n: private
/yallist/4.0.0:
yallist: private
/yargs-parser/20.2.9:
yargs-parser: private
/yargs/17.6.2:
yargs: private
/yocto-queue/0.1.0:
yocto-queue: private
included:
dependencies: true
devDependencies: true
optionalDependencies: true
injectedDeps: {}
layoutVersion: 5
nodeLinker: isolated
packageManager: pnpm@7.13.5
pendingBuilds: []
prunedAt: Tue, 27 Dec 2022 17:31:03 GMT
publicHoistPattern:
- '*eslint*'
- '*prettier*'
registries:
default: https://registry.npmjs.org/
skipped:
- /@esbuild/android-arm/0.16.11
- /@esbuild/android-arm64/0.16.11
- /@esbuild/android-x64/0.16.11
- /@esbuild/darwin-arm64/0.16.11
- /@esbuild/darwin-x64/0.16.11
- /@esbuild/freebsd-arm64/0.16.11
- /@esbuild/freebsd-x64/0.16.11
- /@esbuild/linux-arm/0.16.11
- /@esbuild/linux-arm64/0.16.11
- /@esbuild/linux-ia32/0.16.11
- /@esbuild/linux-loong64/0.16.11
- /@esbuild/linux-mips64el/0.16.11
- /@esbuild/linux-ppc64/0.16.11
- /@esbuild/linux-riscv64/0.16.11
- /@esbuild/linux-s390x/0.16.11
- /@esbuild/netbsd-x64/0.16.11
- /@esbuild/openbsd-x64/0.16.11
- /@esbuild/sunos-x64/0.16.11
- /@esbuild/win32-arm64/0.16.11
- /@esbuild/win32-ia32/0.16.11
- /@esbuild/win32-x64/0.16.11
- /fsevents/2.3.2
storeDir: /home/lilian/.local/share/pnpm/store/v3
virtualStoreDir: .pnpm

View File

@ -0,0 +1,22 @@
MIT License
Copyright (c) 2014-present Sebastian McKenzie and other contributors
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,19 @@
# @babel/code-frame
> Generate errors that contain a code frame that point to source locations.
See our website [@babel/code-frame](https://babeljs.io/docs/en/babel-code-frame) for more information.
## Install
Using npm:
```sh
npm install --save-dev @babel/code-frame
```
or using yarn:
```sh
yarn add @babel/code-frame --dev
```

View File

@ -0,0 +1,163 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.codeFrameColumns = codeFrameColumns;
exports.default = _default;
var _highlight = require("@babel/highlight");
let deprecationWarningShown = false;
function getDefs(chalk) {
return {
gutter: chalk.grey,
marker: chalk.red.bold,
message: chalk.red.bold
};
}
const NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
function getMarkerLines(loc, source, opts) {
const startLoc = Object.assign({
column: 0,
line: -1
}, loc.start);
const endLoc = Object.assign({}, startLoc, loc.end);
const {
linesAbove = 2,
linesBelow = 3
} = opts || {};
const startLine = startLoc.line;
const startColumn = startLoc.column;
const endLine = endLoc.line;
const endColumn = endLoc.column;
let start = Math.max(startLine - (linesAbove + 1), 0);
let end = Math.min(source.length, endLine + linesBelow);
if (startLine === -1) {
start = 0;
}
if (endLine === -1) {
end = source.length;
}
const lineDiff = endLine - startLine;
const markerLines = {};
if (lineDiff) {
for (let i = 0; i <= lineDiff; i++) {
const lineNumber = i + startLine;
if (!startColumn) {
markerLines[lineNumber] = true;
} else if (i === 0) {
const sourceLength = source[lineNumber - 1].length;
markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1];
} else if (i === lineDiff) {
markerLines[lineNumber] = [0, endColumn];
} else {
const sourceLength = source[lineNumber - i].length;
markerLines[lineNumber] = [0, sourceLength];
}
}
} else {
if (startColumn === endColumn) {
if (startColumn) {
markerLines[startLine] = [startColumn, 0];
} else {
markerLines[startLine] = true;
}
} else {
markerLines[startLine] = [startColumn, endColumn - startColumn];
}
}
return {
start,
end,
markerLines
};
}
function codeFrameColumns(rawLines, loc, opts = {}) {
const highlighted = (opts.highlightCode || opts.forceColor) && (0, _highlight.shouldHighlight)(opts);
const chalk = (0, _highlight.getChalk)(opts);
const defs = getDefs(chalk);
const maybeHighlight = (chalkFn, string) => {
return highlighted ? chalkFn(string) : string;
};
const lines = rawLines.split(NEWLINE);
const {
start,
end,
markerLines
} = getMarkerLines(loc, lines, opts);
const hasColumns = loc.start && typeof loc.start.column === "number";
const numberMaxWidth = String(end).length;
const highlightedLines = highlighted ? (0, _highlight.default)(rawLines, opts) : rawLines;
let frame = highlightedLines.split(NEWLINE, end).slice(start, end).map((line, index) => {
const number = start + 1 + index;
const paddedNumber = ` ${number}`.slice(-numberMaxWidth);
const gutter = ` ${paddedNumber} |`;
const hasMarker = markerLines[number];
const lastMarkerLine = !markerLines[number + 1];
if (hasMarker) {
let markerLine = "";
if (Array.isArray(hasMarker)) {
const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " ");
const numberOfMarkers = hasMarker[1] || 1;
markerLine = ["\n ", maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")), " ", markerSpacing, maybeHighlight(defs.marker, "^").repeat(numberOfMarkers)].join("");
if (lastMarkerLine && opts.message) {
markerLine += " " + maybeHighlight(defs.message, opts.message);
}
}
return [maybeHighlight(defs.marker, ">"), maybeHighlight(defs.gutter, gutter), line.length > 0 ? ` ${line}` : "", markerLine].join("");
} else {
return ` ${maybeHighlight(defs.gutter, gutter)}${line.length > 0 ? ` ${line}` : ""}`;
}
}).join("\n");
if (opts.message && !hasColumns) {
frame = `${" ".repeat(numberMaxWidth + 1)}${opts.message}\n${frame}`;
}
if (highlighted) {
return chalk.reset(frame);
} else {
return frame;
}
}
function _default(rawLines, lineNumber, colNumber, opts = {}) {
if (!deprecationWarningShown) {
deprecationWarningShown = true;
const message = "Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`.";
if (process.emitWarning) {
process.emitWarning(message, "DeprecationWarning");
} else {
const deprecationError = new Error(message);
deprecationError.name = "DeprecationWarning";
console.warn(new Error(message));
}
}
colNumber = Math.max(colNumber, 0);
const location = {
start: {
column: colNumber,
line: lineNumber
}
};
return codeFrameColumns(rawLines, location, opts);
}

View File

@ -0,0 +1,30 @@
{
"name": "@babel/code-frame",
"version": "7.18.6",
"description": "Generate errors that contain a code frame that point to source locations.",
"author": "The Babel Team (https://babel.dev/team)",
"homepage": "https://babel.dev/docs/en/next/babel-code-frame",
"bugs": "https://github.com/babel/babel/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen",
"license": "MIT",
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "https://github.com/babel/babel.git",
"directory": "packages/babel-code-frame"
},
"main": "./lib/index.js",
"dependencies": {
"@babel/highlight": "^7.18.6"
},
"devDependencies": {
"@types/chalk": "^2.0.0",
"chalk": "^2.0.0",
"strip-ansi": "^4.0.0"
},
"engines": {
"node": ">=6.9.0"
},
"type": "commonjs"
}

View File

@ -0,0 +1 @@
../../../@babel+highlight@7.18.6/node_modules/@babel/highlight

View File

@ -0,0 +1,22 @@
MIT License
Copyright (c) 2014-present Sebastian McKenzie and other contributors
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,19 @@
# @babel/helper-validator-identifier
> Validate identifier/keywords name
See our website [@babel/helper-validator-identifier](https://babeljs.io/docs/en/babel-helper-validator-identifier) for more information.
## Install
Using npm:
```sh
npm install --save @babel/helper-validator-identifier
```
or using yarn:
```sh
yarn add @babel/helper-validator-identifier
```

View File

@ -0,0 +1,86 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.isIdentifierChar = isIdentifierChar;
exports.isIdentifierName = isIdentifierName;
exports.isIdentifierStart = isIdentifierStart;
let nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7ca\ua7d0\ua7d1\ua7d3\ua7d5-\ua7d9\ua7f2-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc";
let nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0898-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0cf3\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ece\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f";
const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
const astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 68, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 349, 41, 7, 1, 79, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 20, 1, 64, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 4026, 582, 8634, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 43, 8, 8936, 3, 2, 6, 2, 1, 2, 290, 16, 0, 30, 2, 3, 0, 15, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 7, 5, 262, 61, 147, 44, 11, 6, 17, 0, 322, 29, 19, 43, 485, 27, 757, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4153, 7, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938, 6, 4191];
const astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 370, 1, 81, 2, 71, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 3, 0, 158, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 406, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 10, 1, 2, 0, 49, 6, 4, 4, 14, 9, 5351, 0, 7, 14, 13835, 9, 87, 9, 39, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4706, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 101, 0, 161, 6, 10, 9, 357, 0, 62, 13, 499, 13, 983, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];
function isInAstralSet(code, set) {
let pos = 0x10000;
for (let i = 0, length = set.length; i < length; i += 2) {
pos += set[i];
if (pos > code) return false;
pos += set[i + 1];
if (pos >= code) return true;
}
return false;
}
function isIdentifierStart(code) {
if (code < 65) return code === 36;
if (code <= 90) return true;
if (code < 97) return code === 95;
if (code <= 122) return true;
if (code <= 0xffff) {
return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code));
}
return isInAstralSet(code, astralIdentifierStartCodes);
}
function isIdentifierChar(code) {
if (code < 48) return code === 36;
if (code < 58) return true;
if (code < 65) return false;
if (code <= 90) return true;
if (code < 97) return code === 95;
if (code <= 122) return true;
if (code <= 0xffff) {
return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));
}
return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
}
function isIdentifierName(name) {
let isFirst = true;
for (let i = 0; i < name.length; i++) {
let cp = name.charCodeAt(i);
if ((cp & 0xfc00) === 0xd800 && i + 1 < name.length) {
const trail = name.charCodeAt(++i);
if ((trail & 0xfc00) === 0xdc00) {
cp = 0x10000 + ((cp & 0x3ff) << 10) + (trail & 0x3ff);
}
}
if (isFirst) {
isFirst = false;
if (!isIdentifierStart(cp)) {
return false;
}
} else if (!isIdentifierChar(cp)) {
return false;
}
}
return !isFirst;
}
//# sourceMappingURL=identifier.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,59 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "isIdentifierChar", {
enumerable: true,
get: function () {
return _identifier.isIdentifierChar;
}
});
Object.defineProperty(exports, "isIdentifierName", {
enumerable: true,
get: function () {
return _identifier.isIdentifierName;
}
});
Object.defineProperty(exports, "isIdentifierStart", {
enumerable: true,
get: function () {
return _identifier.isIdentifierStart;
}
});
Object.defineProperty(exports, "isKeyword", {
enumerable: true,
get: function () {
return _keyword.isKeyword;
}
});
Object.defineProperty(exports, "isReservedWord", {
enumerable: true,
get: function () {
return _keyword.isReservedWord;
}
});
Object.defineProperty(exports, "isStrictBindOnlyReservedWord", {
enumerable: true,
get: function () {
return _keyword.isStrictBindOnlyReservedWord;
}
});
Object.defineProperty(exports, "isStrictBindReservedWord", {
enumerable: true,
get: function () {
return _keyword.isStrictBindReservedWord;
}
});
Object.defineProperty(exports, "isStrictReservedWord", {
enumerable: true,
get: function () {
return _keyword.isStrictReservedWord;
}
});
var _identifier = require("./identifier");
var _keyword = require("./keyword");
//# sourceMappingURL=index.js.map

View File

@ -0,0 +1 @@
{"version":3,"names":[],"sources":["../src/index.ts"],"sourcesContent":["export {\n isIdentifierName,\n isIdentifierChar,\n isIdentifierStart,\n} from \"./identifier\";\nexport {\n isReservedWord,\n isStrictBindOnlyReservedWord,\n isStrictBindReservedWord,\n isStrictReservedWord,\n isKeyword,\n} from \"./keyword\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;AAKA"}

View File

@ -0,0 +1,40 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.isKeyword = isKeyword;
exports.isReservedWord = isReservedWord;
exports.isStrictBindOnlyReservedWord = isStrictBindOnlyReservedWord;
exports.isStrictBindReservedWord = isStrictBindReservedWord;
exports.isStrictReservedWord = isStrictReservedWord;
const reservedWords = {
keyword: ["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete"],
strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"],
strictBind: ["eval", "arguments"]
};
const keywords = new Set(reservedWords.keyword);
const reservedWordsStrictSet = new Set(reservedWords.strict);
const reservedWordsStrictBindSet = new Set(reservedWords.strictBind);
function isReservedWord(word, inModule) {
return inModule && word === "await" || word === "enum";
}
function isStrictReservedWord(word, inModule) {
return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word);
}
function isStrictBindOnlyReservedWord(word) {
return reservedWordsStrictBindSet.has(word);
}
function isStrictBindReservedWord(word, inModule) {
return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word);
}
function isKeyword(word) {
return keywords.has(word);
}
//# sourceMappingURL=keyword.js.map

View File

@ -0,0 +1 @@
{"version":3,"names":["reservedWords","keyword","strict","strictBind","keywords","Set","reservedWordsStrictSet","reservedWordsStrictBindSet","isReservedWord","word","inModule","isStrictReservedWord","has","isStrictBindOnlyReservedWord","isStrictBindReservedWord","isKeyword"],"sources":["../src/keyword.ts"],"sourcesContent":["const reservedWords = {\n keyword: [\n \"break\",\n \"case\",\n \"catch\",\n \"continue\",\n \"debugger\",\n \"default\",\n \"do\",\n \"else\",\n \"finally\",\n \"for\",\n \"function\",\n \"if\",\n \"return\",\n \"switch\",\n \"throw\",\n \"try\",\n \"var\",\n \"const\",\n \"while\",\n \"with\",\n \"new\",\n \"this\",\n \"super\",\n \"class\",\n \"extends\",\n \"export\",\n \"import\",\n \"null\",\n \"true\",\n \"false\",\n \"in\",\n \"instanceof\",\n \"typeof\",\n \"void\",\n \"delete\",\n ],\n strict: [\n \"implements\",\n \"interface\",\n \"let\",\n \"package\",\n \"private\",\n \"protected\",\n \"public\",\n \"static\",\n \"yield\",\n ],\n strictBind: [\"eval\", \"arguments\"],\n};\nconst keywords = new Set(reservedWords.keyword);\nconst reservedWordsStrictSet = new Set(reservedWords.strict);\nconst reservedWordsStrictBindSet = new Set(reservedWords.strictBind);\n\n/**\n * Checks if word is a reserved word in non-strict mode\n */\nexport function isReservedWord(word: string, inModule: boolean): boolean {\n return (inModule && word === \"await\") || word === \"enum\";\n}\n\n/**\n * Checks if word is a reserved word in non-binding strict mode\n *\n * Includes non-strict reserved words\n */\nexport function isStrictReservedWord(word: string, inModule: boolean): boolean {\n return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word);\n}\n\n/**\n * Checks if word is a reserved word in binding strict mode, but it is allowed as\n * a normal identifier.\n */\nexport function isStrictBindOnlyReservedWord(word: string): boolean {\n return reservedWordsStrictBindSet.has(word);\n}\n\n/**\n * Checks if word is a reserved word in binding strict mode\n *\n * Includes non-strict reserved words and non-binding strict reserved words\n */\nexport function isStrictBindReservedWord(\n word: string,\n inModule: boolean,\n): boolean {\n return (\n isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word)\n );\n}\n\nexport function isKeyword(word: string): boolean {\n return keywords.has(word);\n}\n"],"mappings":";;;;;;;;;;AAAA,MAAMA,aAAa,GAAG;EACpBC,OAAO,EAAE,CACP,OADO,EAEP,MAFO,EAGP,OAHO,EAIP,UAJO,EAKP,UALO,EAMP,SANO,EAOP,IAPO,EAQP,MARO,EASP,SATO,EAUP,KAVO,EAWP,UAXO,EAYP,IAZO,EAaP,QAbO,EAcP,QAdO,EAeP,OAfO,EAgBP,KAhBO,EAiBP,KAjBO,EAkBP,OAlBO,EAmBP,OAnBO,EAoBP,MApBO,EAqBP,KArBO,EAsBP,MAtBO,EAuBP,OAvBO,EAwBP,OAxBO,EAyBP,SAzBO,EA0BP,QA1BO,EA2BP,QA3BO,EA4BP,MA5BO,EA6BP,MA7BO,EA8BP,OA9BO,EA+BP,IA/BO,EAgCP,YAhCO,EAiCP,QAjCO,EAkCP,MAlCO,EAmCP,QAnCO,CADW;EAsCpBC,MAAM,EAAE,CACN,YADM,EAEN,WAFM,EAGN,KAHM,EAIN,SAJM,EAKN,SALM,EAMN,WANM,EAON,QAPM,EAQN,QARM,EASN,OATM,CAtCY;EAiDpBC,UAAU,EAAE,CAAC,MAAD,EAAS,WAAT;AAjDQ,CAAtB;AAmDA,MAAMC,QAAQ,GAAG,IAAIC,GAAJ,CAAQL,aAAa,CAACC,OAAtB,CAAjB;AACA,MAAMK,sBAAsB,GAAG,IAAID,GAAJ,CAAQL,aAAa,CAACE,MAAtB,CAA/B;AACA,MAAMK,0BAA0B,GAAG,IAAIF,GAAJ,CAAQL,aAAa,CAACG,UAAtB,CAAnC;;AAKO,SAASK,cAAT,CAAwBC,IAAxB,EAAsCC,QAAtC,EAAkE;EACvE,OAAQA,QAAQ,IAAID,IAAI,KAAK,OAAtB,IAAkCA,IAAI,KAAK,MAAlD;AACD;;AAOM,SAASE,oBAAT,CAA8BF,IAA9B,EAA4CC,QAA5C,EAAwE;EAC7E,OAAOF,cAAc,CAACC,IAAD,EAAOC,QAAP,CAAd,IAAkCJ,sBAAsB,CAACM,GAAvB,CAA2BH,IAA3B,CAAzC;AACD;;AAMM,SAASI,4BAAT,CAAsCJ,IAAtC,EAA6D;EAClE,OAAOF,0BAA0B,CAACK,GAA3B,CAA+BH,IAA/B,CAAP;AACD;;AAOM,SAASK,wBAAT,CACLL,IADK,EAELC,QAFK,EAGI;EACT,OACEC,oBAAoB,CAACF,IAAD,EAAOC,QAAP,CAApB,IAAwCG,4BAA4B,CAACJ,IAAD,CADtE;AAGD;;AAEM,SAASM,SAAT,CAAmBN,IAAnB,EAA0C;EAC/C,OAAOL,QAAQ,CAACQ,GAAT,CAAaH,IAAb,CAAP;AACD"}

View File

@ -0,0 +1,28 @@
{
"name": "@babel/helper-validator-identifier",
"version": "7.19.1",
"description": "Validate identifier/keywords name",
"repository": {
"type": "git",
"url": "https://github.com/babel/babel.git",
"directory": "packages/babel-helper-validator-identifier"
},
"license": "MIT",
"publishConfig": {
"access": "public"
},
"main": "./lib/index.js",
"exports": {
".": "./lib/index.js",
"./package.json": "./package.json"
},
"devDependencies": {
"@unicode/unicode-15.0.0": "^1.3.1",
"charcodes": "^0.2.0"
},
"engines": {
"node": ">=6.9.0"
},
"author": "The Babel Team (https://babel.dev/team)",
"type": "commonjs"
}

View File

@ -0,0 +1,75 @@
"use strict";
// Always use the latest available version of Unicode!
// https://tc39.github.io/ecma262/#sec-conformance
const version = "15.0.0";
const start = require("@unicode/unicode-" +
version +
"/Binary_Property/ID_Start/code-points.js").filter(function (ch) {
return ch > 0x7f;
});
let last = -1;
const cont = [0x200c, 0x200d].concat(
require("@unicode/unicode-" +
version +
"/Binary_Property/ID_Continue/code-points.js").filter(function (ch) {
return ch > 0x7f && search(start, ch, last + 1) == -1;
})
);
function search(arr, ch, starting) {
for (let i = starting; arr[i] <= ch && i < arr.length; last = i++) {
if (arr[i] === ch) return i;
}
return -1;
}
function pad(str, width) {
while (str.length < width) str = "0" + str;
return str;
}
function esc(code) {
const hex = code.toString(16);
if (hex.length <= 2) return "\\x" + pad(hex, 2);
else return "\\u" + pad(hex, 4);
}
function generate(chars) {
const astral = [];
let re = "";
for (let i = 0, at = 0x10000; i < chars.length; i++) {
const from = chars[i];
let to = from;
while (i < chars.length - 1 && chars[i + 1] == to + 1) {
i++;
to++;
}
if (to <= 0xffff) {
if (from == to) re += esc(from);
else if (from + 1 == to) re += esc(from) + esc(to);
else re += esc(from) + "-" + esc(to);
} else {
astral.push(from - at, to - from);
at = to;
}
}
return { nonASCII: re, astral: astral };
}
const startData = generate(start);
const contData = generate(cont);
console.log("/* prettier-ignore */");
console.log('let nonASCIIidentifierStartChars = "' + startData.nonASCII + '";');
console.log("/* prettier-ignore */");
console.log('let nonASCIIidentifierChars = "' + contData.nonASCII + '";');
console.log("/* prettier-ignore */");
console.log(
"const astralIdentifierStartCodes = " + JSON.stringify(startData.astral) + ";"
);
console.log("/* prettier-ignore */");
console.log(
"const astralIdentifierCodes = " + JSON.stringify(contData.astral) + ";"
);

View File

@ -0,0 +1 @@
../../../@babel+helper-validator-identifier@7.19.1/node_modules/@babel/helper-validator-identifier

View File

@ -0,0 +1,22 @@
MIT License
Copyright (c) 2014-present Sebastian McKenzie and other contributors
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,19 @@
# @babel/highlight
> Syntax highlight JavaScript strings for output in terminals.
See our website [@babel/highlight](https://babeljs.io/docs/en/babel-highlight) for more information.
## Install
Using npm:
```sh
npm install --save-dev @babel/highlight
```
or using yarn:
```sh
yarn add @babel/highlight --dev
```

View File

@ -0,0 +1,116 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = highlight;
exports.getChalk = getChalk;
exports.shouldHighlight = shouldHighlight;
var _jsTokens = require("js-tokens");
var _helperValidatorIdentifier = require("@babel/helper-validator-identifier");
var _chalk = require("chalk");
const sometimesKeywords = new Set(["as", "async", "from", "get", "of", "set"]);
function getDefs(chalk) {
return {
keyword: chalk.cyan,
capitalized: chalk.yellow,
jsxIdentifier: chalk.yellow,
punctuator: chalk.yellow,
number: chalk.magenta,
string: chalk.green,
regex: chalk.magenta,
comment: chalk.grey,
invalid: chalk.white.bgRed.bold
};
}
const NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
const BRACKET = /^[()[\]{}]$/;
let tokenize;
{
const JSX_TAG = /^[a-z][\w-]*$/i;
const getTokenType = function (token, offset, text) {
if (token.type === "name") {
if ((0, _helperValidatorIdentifier.isKeyword)(token.value) || (0, _helperValidatorIdentifier.isStrictReservedWord)(token.value, true) || sometimesKeywords.has(token.value)) {
return "keyword";
}
if (JSX_TAG.test(token.value) && (text[offset - 1] === "<" || text.slice(offset - 2, offset) == "</")) {
return "jsxIdentifier";
}
if (token.value[0] !== token.value[0].toLowerCase()) {
return "capitalized";
}
}
if (token.type === "punctuator" && BRACKET.test(token.value)) {
return "bracket";
}
if (token.type === "invalid" && (token.value === "@" || token.value === "#")) {
return "punctuator";
}
return token.type;
};
tokenize = function* (text) {
let match;
while (match = _jsTokens.default.exec(text)) {
const token = _jsTokens.matchToToken(match);
yield {
type: getTokenType(token, match.index, text),
value: token.value
};
}
};
}
function highlightTokens(defs, text) {
let highlighted = "";
for (const {
type,
value
} of tokenize(text)) {
const colorize = defs[type];
if (colorize) {
highlighted += value.split(NEWLINE).map(str => colorize(str)).join("\n");
} else {
highlighted += value;
}
}
return highlighted;
}
function shouldHighlight(options) {
return !!_chalk.supportsColor || options.forceColor;
}
function getChalk(options) {
return options.forceColor ? new _chalk.constructor({
enabled: true,
level: 1
}) : _chalk;
}
function highlight(code, options = {}) {
if (code !== "" && shouldHighlight(options)) {
const chalk = getChalk(options);
const defs = getDefs(chalk);
return highlightTokens(defs, code);
} else {
return code;
}
}

View File

@ -0,0 +1,30 @@
{
"name": "@babel/highlight",
"version": "7.18.6",
"description": "Syntax highlight JavaScript strings for output in terminals.",
"author": "The Babel Team (https://babel.dev/team)",
"homepage": "https://babel.dev/docs/en/next/babel-highlight",
"license": "MIT",
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "https://github.com/babel/babel.git",
"directory": "packages/babel-highlight"
},
"main": "./lib/index.js",
"dependencies": {
"@babel/helper-validator-identifier": "^7.18.6",
"chalk": "^2.0.0",
"js-tokens": "^4.0.0"
},
"devDependencies": {
"@types/chalk": "^2.0.0",
"strip-ansi": "^4.0.0"
},
"engines": {
"node": ">=6.9.0"
},
"type": "commonjs"
}

View File

@ -0,0 +1 @@
../../chalk@2.4.2/node_modules/chalk

View File

@ -0,0 +1 @@
../../js-tokens@4.0.0/node_modules/js-tokens

View File

@ -0,0 +1,3 @@
# esbuild
This is the Linux 64-bit binary for esbuild, a JavaScript bundler and minifier. See https://github.com/evanw/esbuild for details.

View File

@ -0,0 +1,17 @@
{
"name": "@esbuild/linux-x64",
"version": "0.16.11",
"description": "The Linux 64-bit binary for esbuild, a JavaScript bundler.",
"repository": "https://github.com/evanw/esbuild",
"license": "MIT",
"preferUnplugged": true,
"engines": {
"node": ">=12"
},
"os": [
"linux"
],
"cpu": [
"x64"
]
}

View File

@ -0,0 +1,19 @@
Copyright OpenJS Foundation and other contributors, <www.openjsf.org>
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,68 @@
# ESLintRC Library
This repository contains the legacy ESLintRC configuration file format for ESLint. This package is not intended for use outside of the ESLint ecosystem. It is ESLint-specific and not intended for use in other programs.
**Note:** This package is frozen except for critical bug fixes as ESLint moves to a new config system.
## Installation
You can install the package as follows:
```
npm install @eslint/eslintrc --save-dev
# or
yarn add @eslint/eslintrc -D
```
## Usage
The primary class in this package is `FlatCompat`, which is a utility to translate ESLintRC-style configs into flat configs. Here's how you use it inside of your `eslint.config.js` file:
```js
import { FlatCompat } from "@eslint/eslintrc";
import path from "path";
import { fileURLToPath } from "url";
// mimic CommonJS variables -- not needed if using CommonJS
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const compat = new FlatCompat({
baseDirectory: __dirname, // optional; default: process.cwd()
resolvePluginsRelativeTo: __dirname // optional
});
export default [
// mimic ESLintRC-style extends
compat.extends("standard", "example"),
// mimic environments
compat.env({
es2020: true,
node: true
}),
// mimic plugins
compat.plugins("airbnb", "react"),
// translate an entire config
compat.config({
plugins: ["airbnb", "react"],
extends: "standard",
env: {
es2020: true,
node: true
},
rules: {
semi: "error"
}
})
];
```
## License
MIT License

View File

@ -0,0 +1,79 @@
/**
* @fileoverview Defines a schema for configs.
* @author Sylvan Mably
*/
const baseConfigProperties = {
$schema: { type: "string" },
env: { type: "object" },
extends: { $ref: "#/definitions/stringOrStrings" },
globals: { type: "object" },
overrides: {
type: "array",
items: { $ref: "#/definitions/overrideConfig" },
additionalItems: false
},
parser: { type: ["string", "null"] },
parserOptions: { type: "object" },
plugins: { type: "array" },
processor: { type: "string" },
rules: { type: "object" },
settings: { type: "object" },
noInlineConfig: { type: "boolean" },
reportUnusedDisableDirectives: { type: "boolean" },
ecmaFeatures: { type: "object" } // deprecated; logs a warning when used
};
const configSchema = {
definitions: {
stringOrStrings: {
oneOf: [
{ type: "string" },
{
type: "array",
items: { type: "string" },
additionalItems: false
}
]
},
stringOrStringsRequired: {
oneOf: [
{ type: "string" },
{
type: "array",
items: { type: "string" },
additionalItems: false,
minItems: 1
}
]
},
// Config at top-level.
objectConfig: {
type: "object",
properties: {
root: { type: "boolean" },
ignorePatterns: { $ref: "#/definitions/stringOrStrings" },
...baseConfigProperties
},
additionalProperties: false
},
// Config in `overrides`.
overrideConfig: {
type: "object",
properties: {
excludedFiles: { $ref: "#/definitions/stringOrStrings" },
files: { $ref: "#/definitions/stringOrStringsRequired" },
...baseConfigProperties
},
required: ["files"],
additionalProperties: false
}
},
$ref: "#/definitions/objectConfig"
};
export default configSchema;

View File

@ -0,0 +1,203 @@
/**
* @fileoverview Defines environment settings and globals.
* @author Elan Shanker
*/
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
import globals from "globals";
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
/**
* Get the object that has difference.
* @param {Record<string,boolean>} current The newer object.
* @param {Record<string,boolean>} prev The older object.
* @returns {Record<string,boolean>} The difference object.
*/
function getDiff(current, prev) {
const retv = {};
for (const [key, value] of Object.entries(current)) {
if (!Object.hasOwnProperty.call(prev, key)) {
retv[key] = value;
}
}
return retv;
}
const newGlobals2015 = getDiff(globals.es2015, globals.es5); // 19 variables such as Promise, Map, ...
const newGlobals2017 = {
Atomics: false,
SharedArrayBuffer: false
};
const newGlobals2020 = {
BigInt: false,
BigInt64Array: false,
BigUint64Array: false,
globalThis: false
};
const newGlobals2021 = {
AggregateError: false,
FinalizationRegistry: false,
WeakRef: false
};
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
/** @type {Map<string, import("../lib/shared/types").Environment>} */
export default new Map(Object.entries({
// Language
builtin: {
globals: globals.es5
},
es6: {
globals: newGlobals2015,
parserOptions: {
ecmaVersion: 6
}
},
es2015: {
globals: newGlobals2015,
parserOptions: {
ecmaVersion: 6
}
},
es2016: {
globals: newGlobals2015,
parserOptions: {
ecmaVersion: 7
}
},
es2017: {
globals: { ...newGlobals2015, ...newGlobals2017 },
parserOptions: {
ecmaVersion: 8
}
},
es2018: {
globals: { ...newGlobals2015, ...newGlobals2017 },
parserOptions: {
ecmaVersion: 9
}
},
es2019: {
globals: { ...newGlobals2015, ...newGlobals2017 },
parserOptions: {
ecmaVersion: 10
}
},
es2020: {
globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020 },
parserOptions: {
ecmaVersion: 11
}
},
es2021: {
globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 },
parserOptions: {
ecmaVersion: 12
}
},
es2022: {
globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 },
parserOptions: {
ecmaVersion: 13
}
},
// Platforms
browser: {
globals: globals.browser
},
node: {
globals: globals.node,
parserOptions: {
ecmaFeatures: {
globalReturn: true
}
}
},
"shared-node-browser": {
globals: globals["shared-node-browser"]
},
worker: {
globals: globals.worker
},
serviceworker: {
globals: globals.serviceworker
},
// Frameworks
commonjs: {
globals: globals.commonjs,
parserOptions: {
ecmaFeatures: {
globalReturn: true
}
}
},
amd: {
globals: globals.amd
},
mocha: {
globals: globals.mocha
},
jasmine: {
globals: globals.jasmine
},
jest: {
globals: globals.jest
},
phantomjs: {
globals: globals.phantomjs
},
jquery: {
globals: globals.jquery
},
qunit: {
globals: globals.qunit
},
prototypejs: {
globals: globals.prototypejs
},
shelljs: {
globals: globals.shelljs
},
meteor: {
globals: globals.meteor
},
mongo: {
globals: globals.mongo
},
protractor: {
globals: globals.protractor
},
applescript: {
globals: globals.applescript
},
nashorn: {
globals: globals.nashorn
},
atomtest: {
globals: globals.atomtest
},
embertest: {
globals: globals.embertest
},
webextensions: {
globals: globals.webextensions
},
greasemonkey: {
globals: globals.greasemonkey
}
}));

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,532 @@
/**
* @fileoverview `CascadingConfigArrayFactory` class.
*
* `CascadingConfigArrayFactory` class has a responsibility:
*
* 1. Handles cascading of config files.
*
* It provides two methods:
*
* - `getConfigArrayForFile(filePath)`
* Get the corresponded configuration of a given file. This method doesn't
* throw even if the given file didn't exist.
* - `clearCache()`
* Clear the internal cache. You have to call this method when
* `additionalPluginPool` was updated if `baseConfig` or `cliConfig` depends
* on the additional plugins. (`CLIEngine#addPlugin()` method calls this.)
*
* @author Toru Nagashima <https://github.com/mysticatea>
*/
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
import debugOrig from "debug";
import os from "os";
import path from "path";
import { ConfigArrayFactory } from "./config-array-factory.js";
import {
ConfigArray,
ConfigDependency,
IgnorePattern
} from "./config-array/index.js";
import ConfigValidator from "./shared/config-validator.js";
import { emitDeprecationWarning } from "./shared/deprecation-warnings.js";
const debug = debugOrig("eslintrc:cascading-config-array-factory");
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
// Define types for VSCode IntelliSense.
/** @typedef {import("./shared/types").ConfigData} ConfigData */
/** @typedef {import("./shared/types").Parser} Parser */
/** @typedef {import("./shared/types").Plugin} Plugin */
/** @typedef {import("./shared/types").Rule} Rule */
/** @typedef {ReturnType<ConfigArrayFactory["create"]>} ConfigArray */
/**
* @typedef {Object} CascadingConfigArrayFactoryOptions
* @property {Map<string,Plugin>} [additionalPluginPool] The map for additional plugins.
* @property {ConfigData} [baseConfig] The config by `baseConfig` option.
* @property {ConfigData} [cliConfig] The config by CLI options (`--env`, `--global`, `--ignore-pattern`, `--parser`, `--parser-options`, `--plugin`, and `--rule`). CLI options overwrite the setting in config files.
* @property {string} [cwd] The base directory to start lookup.
* @property {string} [ignorePath] The path to the alternative file of `.eslintignore`.
* @property {string[]} [rulePaths] The value of `--rulesdir` option.
* @property {string} [specificConfigPath] The value of `--config` option.
* @property {boolean} [useEslintrc] if `false` then it doesn't load config files.
* @property {Function} loadRules The function to use to load rules.
* @property {Map<string,Rule>} builtInRules The rules that are built in to ESLint.
* @property {Object} [resolver=ModuleResolver] The module resolver object.
* @property {string} eslintAllPath The path to the definitions for eslint:all.
* @property {Function} getEslintAllConfig Returns the config data for eslint:all.
* @property {string} eslintRecommendedPath The path to the definitions for eslint:recommended.
* @property {Function} getEslintRecommendedConfig Returns the config data for eslint:recommended.
*/
/**
* @typedef {Object} CascadingConfigArrayFactoryInternalSlots
* @property {ConfigArray} baseConfigArray The config array of `baseConfig` option.
* @property {ConfigData} baseConfigData The config data of `baseConfig` option. This is used to reset `baseConfigArray`.
* @property {ConfigArray} cliConfigArray The config array of CLI options.
* @property {ConfigData} cliConfigData The config data of CLI options. This is used to reset `cliConfigArray`.
* @property {ConfigArrayFactory} configArrayFactory The factory for config arrays.
* @property {Map<string, ConfigArray>} configCache The cache from directory paths to config arrays.
* @property {string} cwd The base directory to start lookup.
* @property {WeakMap<ConfigArray, ConfigArray>} finalizeCache The cache from config arrays to finalized config arrays.
* @property {string} [ignorePath] The path to the alternative file of `.eslintignore`.
* @property {string[]|null} rulePaths The value of `--rulesdir` option. This is used to reset `baseConfigArray`.
* @property {string|null} specificConfigPath The value of `--config` option. This is used to reset `cliConfigArray`.
* @property {boolean} useEslintrc if `false` then it doesn't load config files.
* @property {Function} loadRules The function to use to load rules.
* @property {Map<string,Rule>} builtInRules The rules that are built in to ESLint.
* @property {Object} [resolver=ModuleResolver] The module resolver object.
* @property {string} eslintAllPath The path to the definitions for eslint:all.
* @property {Function} getEslintAllConfig Returns the config data for eslint:all.
* @property {string} eslintRecommendedPath The path to the definitions for eslint:recommended.
* @property {Function} getEslintRecommendedConfig Returns the config data for eslint:recommended.
*/
/** @type {WeakMap<CascadingConfigArrayFactory, CascadingConfigArrayFactoryInternalSlots>} */
const internalSlotsMap = new WeakMap();
/**
* Create the config array from `baseConfig` and `rulePaths`.
* @param {CascadingConfigArrayFactoryInternalSlots} slots The slots.
* @returns {ConfigArray} The config array of the base configs.
*/
function createBaseConfigArray({
configArrayFactory,
baseConfigData,
rulePaths,
cwd,
loadRules
}) {
const baseConfigArray = configArrayFactory.create(
baseConfigData,
{ name: "BaseConfig" }
);
/*
* Create the config array element for the default ignore patterns.
* This element has `ignorePattern` property that ignores the default
* patterns in the current working directory.
*/
baseConfigArray.unshift(configArrayFactory.create(
{ ignorePatterns: IgnorePattern.DefaultPatterns },
{ name: "DefaultIgnorePattern" }
)[0]);
/*
* Load rules `--rulesdir` option as a pseudo plugin.
* Use a pseudo plugin to define rules of `--rulesdir`, so we can validate
* the rule's options with only information in the config array.
*/
if (rulePaths && rulePaths.length > 0) {
baseConfigArray.push({
type: "config",
name: "--rulesdir",
filePath: "",
plugins: {
"": new ConfigDependency({
definition: {
rules: rulePaths.reduce(
(map, rulesPath) => Object.assign(
map,
loadRules(rulesPath, cwd)
),
{}
)
},
filePath: "",
id: "",
importerName: "--rulesdir",
importerPath: ""
})
}
});
}
return baseConfigArray;
}
/**
* Create the config array from CLI options.
* @param {CascadingConfigArrayFactoryInternalSlots} slots The slots.
* @returns {ConfigArray} The config array of the base configs.
*/
function createCLIConfigArray({
cliConfigData,
configArrayFactory,
cwd,
ignorePath,
specificConfigPath
}) {
const cliConfigArray = configArrayFactory.create(
cliConfigData,
{ name: "CLIOptions" }
);
cliConfigArray.unshift(
...(ignorePath
? configArrayFactory.loadESLintIgnore(ignorePath)
: configArrayFactory.loadDefaultESLintIgnore())
);
if (specificConfigPath) {
cliConfigArray.unshift(
...configArrayFactory.loadFile(
specificConfigPath,
{ name: "--config", basePath: cwd }
)
);
}
return cliConfigArray;
}
/**
* The error type when there are files matched by a glob, but all of them have been ignored.
*/
class ConfigurationNotFoundError extends Error {
// eslint-disable-next-line jsdoc/require-description
/**
* @param {string} directoryPath The directory path.
*/
constructor(directoryPath) {
super(`No ESLint configuration found in ${directoryPath}.`);
this.messageTemplate = "no-config-found";
this.messageData = { directoryPath };
}
}
/**
* This class provides the functionality that enumerates every file which is
* matched by given glob patterns and that configuration.
*/
class CascadingConfigArrayFactory {
/**
* Initialize this enumerator.
* @param {CascadingConfigArrayFactoryOptions} options The options.
*/
constructor({
additionalPluginPool = new Map(),
baseConfig: baseConfigData = null,
cliConfig: cliConfigData = null,
cwd = process.cwd(),
ignorePath,
resolvePluginsRelativeTo,
rulePaths = [],
specificConfigPath = null,
useEslintrc = true,
builtInRules = new Map(),
loadRules,
resolver,
eslintRecommendedPath,
getEslintRecommendedConfig,
eslintAllPath,
getEslintAllConfig
} = {}) {
const configArrayFactory = new ConfigArrayFactory({
additionalPluginPool,
cwd,
resolvePluginsRelativeTo,
builtInRules,
resolver,
eslintRecommendedPath,
getEslintRecommendedConfig,
eslintAllPath,
getEslintAllConfig
});
internalSlotsMap.set(this, {
baseConfigArray: createBaseConfigArray({
baseConfigData,
configArrayFactory,
cwd,
rulePaths,
loadRules
}),
baseConfigData,
cliConfigArray: createCLIConfigArray({
cliConfigData,
configArrayFactory,
cwd,
ignorePath,
specificConfigPath
}),
cliConfigData,
configArrayFactory,
configCache: new Map(),
cwd,
finalizeCache: new WeakMap(),
ignorePath,
rulePaths,
specificConfigPath,
useEslintrc,
builtInRules,
loadRules
});
}
/**
* The path to the current working directory.
* This is used by tests.
* @type {string}
*/
get cwd() {
const { cwd } = internalSlotsMap.get(this);
return cwd;
}
/**
* Get the config array of a given file.
* If `filePath` was not given, it returns the config which contains only
* `baseConfigData` and `cliConfigData`.
* @param {string} [filePath] The file path to a file.
* @param {Object} [options] The options.
* @param {boolean} [options.ignoreNotFoundError] If `true` then it doesn't throw `ConfigurationNotFoundError`.
* @returns {ConfigArray} The config array of the file.
*/
getConfigArrayForFile(filePath, { ignoreNotFoundError = false } = {}) {
const {
baseConfigArray,
cliConfigArray,
cwd
} = internalSlotsMap.get(this);
if (!filePath) {
return new ConfigArray(...baseConfigArray, ...cliConfigArray);
}
const directoryPath = path.dirname(path.resolve(cwd, filePath));
debug(`Load config files for ${directoryPath}.`);
return this._finalizeConfigArray(
this._loadConfigInAncestors(directoryPath),
directoryPath,
ignoreNotFoundError
);
}
/**
* Set the config data to override all configs.
* Require to call `clearCache()` method after this method is called.
* @param {ConfigData} configData The config data to override all configs.
* @returns {void}
*/
setOverrideConfig(configData) {
const slots = internalSlotsMap.get(this);
slots.cliConfigData = configData;
}
/**
* Clear config cache.
* @returns {void}
*/
clearCache() {
const slots = internalSlotsMap.get(this);
slots.baseConfigArray = createBaseConfigArray(slots);
slots.cliConfigArray = createCLIConfigArray(slots);
slots.configCache.clear();
}
/**
* Load and normalize config files from the ancestor directories.
* @param {string} directoryPath The path to a leaf directory.
* @param {boolean} configsExistInSubdirs `true` if configurations exist in subdirectories.
* @returns {ConfigArray} The loaded config.
* @private
*/
_loadConfigInAncestors(directoryPath, configsExistInSubdirs = false) {
const {
baseConfigArray,
configArrayFactory,
configCache,
cwd,
useEslintrc
} = internalSlotsMap.get(this);
if (!useEslintrc) {
return baseConfigArray;
}
let configArray = configCache.get(directoryPath);
// Hit cache.
if (configArray) {
debug(`Cache hit: ${directoryPath}.`);
return configArray;
}
debug(`No cache found: ${directoryPath}.`);
const homePath = os.homedir();
// Consider this is root.
if (directoryPath === homePath && cwd !== homePath) {
debug("Stop traversing because of considered root.");
if (configsExistInSubdirs) {
const filePath = ConfigArrayFactory.getPathToConfigFileInDirectory(directoryPath);
if (filePath) {
emitDeprecationWarning(
filePath,
"ESLINT_PERSONAL_CONFIG_SUPPRESS"
);
}
}
return this._cacheConfig(directoryPath, baseConfigArray);
}
// Load the config on this directory.
try {
configArray = configArrayFactory.loadInDirectory(directoryPath);
} catch (error) {
/* istanbul ignore next */
if (error.code === "EACCES") {
debug("Stop traversing because of 'EACCES' error.");
return this._cacheConfig(directoryPath, baseConfigArray);
}
throw error;
}
if (configArray.length > 0 && configArray.isRoot()) {
debug("Stop traversing because of 'root:true'.");
configArray.unshift(...baseConfigArray);
return this._cacheConfig(directoryPath, configArray);
}
// Load from the ancestors and merge it.
const parentPath = path.dirname(directoryPath);
const parentConfigArray = parentPath && parentPath !== directoryPath
? this._loadConfigInAncestors(
parentPath,
configsExistInSubdirs || configArray.length > 0
)
: baseConfigArray;
if (configArray.length > 0) {
configArray.unshift(...parentConfigArray);
} else {
configArray = parentConfigArray;
}
// Cache and return.
return this._cacheConfig(directoryPath, configArray);
}
/**
* Freeze and cache a given config.
* @param {string} directoryPath The path to a directory as a cache key.
* @param {ConfigArray} configArray The config array as a cache value.
* @returns {ConfigArray} The `configArray` (frozen).
*/
_cacheConfig(directoryPath, configArray) {
const { configCache } = internalSlotsMap.get(this);
Object.freeze(configArray);
configCache.set(directoryPath, configArray);
return configArray;
}
/**
* Finalize a given config array.
* Concatenate `--config` and other CLI options.
* @param {ConfigArray} configArray The parent config array.
* @param {string} directoryPath The path to the leaf directory to find config files.
* @param {boolean} ignoreNotFoundError If `true` then it doesn't throw `ConfigurationNotFoundError`.
* @returns {ConfigArray} The loaded config.
* @private
*/
_finalizeConfigArray(configArray, directoryPath, ignoreNotFoundError) {
const {
cliConfigArray,
configArrayFactory,
finalizeCache,
useEslintrc,
builtInRules
} = internalSlotsMap.get(this);
let finalConfigArray = finalizeCache.get(configArray);
if (!finalConfigArray) {
finalConfigArray = configArray;
// Load the personal config if there are no regular config files.
if (
useEslintrc &&
configArray.every(c => !c.filePath) &&
cliConfigArray.every(c => !c.filePath) // `--config` option can be a file.
) {
const homePath = os.homedir();
debug("Loading the config file of the home directory:", homePath);
const personalConfigArray = configArrayFactory.loadInDirectory(
homePath,
{ name: "PersonalConfig" }
);
if (
personalConfigArray.length > 0 &&
!directoryPath.startsWith(homePath)
) {
const lastElement =
personalConfigArray[personalConfigArray.length - 1];
emitDeprecationWarning(
lastElement.filePath,
"ESLINT_PERSONAL_CONFIG_LOAD"
);
}
finalConfigArray = finalConfigArray.concat(personalConfigArray);
}
// Apply CLI options.
if (cliConfigArray.length > 0) {
finalConfigArray = finalConfigArray.concat(cliConfigArray);
}
// Validate rule settings and environments.
const validator = new ConfigValidator({
builtInRules
});
validator.validateConfigArray(finalConfigArray);
// Cache it.
Object.freeze(finalConfigArray);
finalizeCache.set(configArray, finalConfigArray);
debug(
"Configuration was determined: %o on %s",
finalConfigArray,
directoryPath
);
}
// At least one element (the default ignore patterns) exists.
if (!ignoreNotFoundError && useEslintrc && finalConfigArray.length <= 1) {
throw new ConfigurationNotFoundError(directoryPath);
}
return finalConfigArray;
}
}
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
export { CascadingConfigArrayFactory };

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,523 @@
/**
* @fileoverview `ConfigArray` class.
*
* `ConfigArray` class expresses the full of a configuration. It has the entry
* config file, base config files that were extended, loaded parsers, and loaded
* plugins.
*
* `ConfigArray` class provides three properties and two methods.
*
* - `pluginEnvironments`
* - `pluginProcessors`
* - `pluginRules`
* The `Map` objects that contain the members of all plugins that this
* config array contains. Those map objects don't have mutation methods.
* Those keys are the member ID such as `pluginId/memberName`.
* - `isRoot()`
* If `true` then this configuration has `root:true` property.
* - `extractConfig(filePath)`
* Extract the final configuration for a given file. This means merging
* every config array element which that `criteria` property matched. The
* `filePath` argument must be an absolute path.
*
* `ConfigArrayFactory` provides the loading logic of config files.
*
* @author Toru Nagashima <https://github.com/mysticatea>
*/
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
import { ExtractedConfig } from "./extracted-config.js";
import { IgnorePattern } from "./ignore-pattern.js";
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
// Define types for VSCode IntelliSense.
/** @typedef {import("../../shared/types").Environment} Environment */
/** @typedef {import("../../shared/types").GlobalConf} GlobalConf */
/** @typedef {import("../../shared/types").RuleConf} RuleConf */
/** @typedef {import("../../shared/types").Rule} Rule */
/** @typedef {import("../../shared/types").Plugin} Plugin */
/** @typedef {import("../../shared/types").Processor} Processor */
/** @typedef {import("./config-dependency").DependentParser} DependentParser */
/** @typedef {import("./config-dependency").DependentPlugin} DependentPlugin */
/** @typedef {import("./override-tester")["OverrideTester"]} OverrideTester */
/**
* @typedef {Object} ConfigArrayElement
* @property {string} name The name of this config element.
* @property {string} filePath The path to the source file of this config element.
* @property {InstanceType<OverrideTester>|null} criteria The tester for the `files` and `excludedFiles` of this config element.
* @property {Record<string, boolean>|undefined} env The environment settings.
* @property {Record<string, GlobalConf>|undefined} globals The global variable settings.
* @property {IgnorePattern|undefined} ignorePattern The ignore patterns.
* @property {boolean|undefined} noInlineConfig The flag that disables directive comments.
* @property {DependentParser|undefined} parser The parser loader.
* @property {Object|undefined} parserOptions The parser options.
* @property {Record<string, DependentPlugin>|undefined} plugins The plugin loaders.
* @property {string|undefined} processor The processor name to refer plugin's processor.
* @property {boolean|undefined} reportUnusedDisableDirectives The flag to report unused `eslint-disable` comments.
* @property {boolean|undefined} root The flag to express root.
* @property {Record<string, RuleConf>|undefined} rules The rule settings
* @property {Object|undefined} settings The shared settings.
* @property {"config" | "ignore" | "implicit-processor"} type The element type.
*/
/**
* @typedef {Object} ConfigArrayInternalSlots
* @property {Map<string, ExtractedConfig>} cache The cache to extract configs.
* @property {ReadonlyMap<string, Environment>|null} envMap The map from environment ID to environment definition.
* @property {ReadonlyMap<string, Processor>|null} processorMap The map from processor ID to environment definition.
* @property {ReadonlyMap<string, Rule>|null} ruleMap The map from rule ID to rule definition.
*/
/** @type {WeakMap<ConfigArray, ConfigArrayInternalSlots>} */
const internalSlotsMap = new class extends WeakMap {
get(key) {
let value = super.get(key);
if (!value) {
value = {
cache: new Map(),
envMap: null,
processorMap: null,
ruleMap: null
};
super.set(key, value);
}
return value;
}
}();
/**
* Get the indices which are matched to a given file.
* @param {ConfigArrayElement[]} elements The elements.
* @param {string} filePath The path to a target file.
* @returns {number[]} The indices.
*/
function getMatchedIndices(elements, filePath) {
const indices = [];
for (let i = elements.length - 1; i >= 0; --i) {
const element = elements[i];
if (!element.criteria || (filePath && element.criteria.test(filePath))) {
indices.push(i);
}
}
return indices;
}
/**
* Check if a value is a non-null object.
* @param {any} x The value to check.
* @returns {boolean} `true` if the value is a non-null object.
*/
function isNonNullObject(x) {
return typeof x === "object" && x !== null;
}
/**
* Merge two objects.
*
* Assign every property values of `y` to `x` if `x` doesn't have the property.
* If `x`'s property value is an object, it does recursive.
* @param {Object} target The destination to merge
* @param {Object|undefined} source The source to merge.
* @returns {void}
*/
function mergeWithoutOverwrite(target, source) {
if (!isNonNullObject(source)) {
return;
}
for (const key of Object.keys(source)) {
if (key === "__proto__") {
continue;
}
if (isNonNullObject(target[key])) {
mergeWithoutOverwrite(target[key], source[key]);
} else if (target[key] === void 0) {
if (isNonNullObject(source[key])) {
target[key] = Array.isArray(source[key]) ? [] : {};
mergeWithoutOverwrite(target[key], source[key]);
} else if (source[key] !== void 0) {
target[key] = source[key];
}
}
}
}
/**
* The error for plugin conflicts.
*/
class PluginConflictError extends Error {
/**
* Initialize this error object.
* @param {string} pluginId The plugin ID.
* @param {{filePath:string, importerName:string}[]} plugins The resolved plugins.
*/
constructor(pluginId, plugins) {
super(`Plugin "${pluginId}" was conflicted between ${plugins.map(p => `"${p.importerName}"`).join(" and ")}.`);
this.messageTemplate = "plugin-conflict";
this.messageData = { pluginId, plugins };
}
}
/**
* Merge plugins.
* `target`'s definition is prior to `source`'s.
* @param {Record<string, DependentPlugin>} target The destination to merge
* @param {Record<string, DependentPlugin>|undefined} source The source to merge.
* @returns {void}
*/
function mergePlugins(target, source) {
if (!isNonNullObject(source)) {
return;
}
for (const key of Object.keys(source)) {
if (key === "__proto__") {
continue;
}
const targetValue = target[key];
const sourceValue = source[key];
// Adopt the plugin which was found at first.
if (targetValue === void 0) {
if (sourceValue.error) {
throw sourceValue.error;
}
target[key] = sourceValue;
} else if (sourceValue.filePath !== targetValue.filePath) {
throw new PluginConflictError(key, [
{
filePath: targetValue.filePath,
importerName: targetValue.importerName
},
{
filePath: sourceValue.filePath,
importerName: sourceValue.importerName
}
]);
}
}
}
/**
* Merge rule configs.
* `target`'s definition is prior to `source`'s.
* @param {Record<string, Array>} target The destination to merge
* @param {Record<string, RuleConf>|undefined} source The source to merge.
* @returns {void}
*/
function mergeRuleConfigs(target, source) {
if (!isNonNullObject(source)) {
return;
}
for (const key of Object.keys(source)) {
if (key === "__proto__") {
continue;
}
const targetDef = target[key];
const sourceDef = source[key];
// Adopt the rule config which was found at first.
if (targetDef === void 0) {
if (Array.isArray(sourceDef)) {
target[key] = [...sourceDef];
} else {
target[key] = [sourceDef];
}
/*
* If the first found rule config is severity only and the current rule
* config has options, merge the severity and the options.
*/
} else if (
targetDef.length === 1 &&
Array.isArray(sourceDef) &&
sourceDef.length >= 2
) {
targetDef.push(...sourceDef.slice(1));
}
}
}
/**
* Create the extracted config.
* @param {ConfigArray} instance The config elements.
* @param {number[]} indices The indices to use.
* @returns {ExtractedConfig} The extracted config.
*/
function createConfig(instance, indices) {
const config = new ExtractedConfig();
const ignorePatterns = [];
// Merge elements.
for (const index of indices) {
const element = instance[index];
// Adopt the parser which was found at first.
if (!config.parser && element.parser) {
if (element.parser.error) {
throw element.parser.error;
}
config.parser = element.parser;
}
// Adopt the processor which was found at first.
if (!config.processor && element.processor) {
config.processor = element.processor;
}
// Adopt the noInlineConfig which was found at first.
if (config.noInlineConfig === void 0 && element.noInlineConfig !== void 0) {
config.noInlineConfig = element.noInlineConfig;
config.configNameOfNoInlineConfig = element.name;
}
// Adopt the reportUnusedDisableDirectives which was found at first.
if (config.reportUnusedDisableDirectives === void 0 && element.reportUnusedDisableDirectives !== void 0) {
config.reportUnusedDisableDirectives = element.reportUnusedDisableDirectives;
}
// Collect ignorePatterns
if (element.ignorePattern) {
ignorePatterns.push(element.ignorePattern);
}
// Merge others.
mergeWithoutOverwrite(config.env, element.env);
mergeWithoutOverwrite(config.globals, element.globals);
mergeWithoutOverwrite(config.parserOptions, element.parserOptions);
mergeWithoutOverwrite(config.settings, element.settings);
mergePlugins(config.plugins, element.plugins);
mergeRuleConfigs(config.rules, element.rules);
}
// Create the predicate function for ignore patterns.
if (ignorePatterns.length > 0) {
config.ignores = IgnorePattern.createIgnore(ignorePatterns.reverse());
}
return config;
}
/**
* Collect definitions.
* @template T, U
* @param {string} pluginId The plugin ID for prefix.
* @param {Record<string,T>} defs The definitions to collect.
* @param {Map<string, U>} map The map to output.
* @param {function(T): U} [normalize] The normalize function for each value.
* @returns {void}
*/
function collect(pluginId, defs, map, normalize) {
if (defs) {
const prefix = pluginId && `${pluginId}/`;
for (const [key, value] of Object.entries(defs)) {
map.set(
`${prefix}${key}`,
normalize ? normalize(value) : value
);
}
}
}
/**
* Normalize a rule definition.
* @param {Function|Rule} rule The rule definition to normalize.
* @returns {Rule} The normalized rule definition.
*/
function normalizePluginRule(rule) {
return typeof rule === "function" ? { create: rule } : rule;
}
/**
* Delete the mutation methods from a given map.
* @param {Map<any, any>} map The map object to delete.
* @returns {void}
*/
function deleteMutationMethods(map) {
Object.defineProperties(map, {
clear: { configurable: true, value: void 0 },
delete: { configurable: true, value: void 0 },
set: { configurable: true, value: void 0 }
});
}
/**
* Create `envMap`, `processorMap`, `ruleMap` with the plugins in the config array.
* @param {ConfigArrayElement[]} elements The config elements.
* @param {ConfigArrayInternalSlots} slots The internal slots.
* @returns {void}
*/
function initPluginMemberMaps(elements, slots) {
const processed = new Set();
slots.envMap = new Map();
slots.processorMap = new Map();
slots.ruleMap = new Map();
for (const element of elements) {
if (!element.plugins) {
continue;
}
for (const [pluginId, value] of Object.entries(element.plugins)) {
const plugin = value.definition;
if (!plugin || processed.has(pluginId)) {
continue;
}
processed.add(pluginId);
collect(pluginId, plugin.environments, slots.envMap);
collect(pluginId, plugin.processors, slots.processorMap);
collect(pluginId, plugin.rules, slots.ruleMap, normalizePluginRule);
}
}
deleteMutationMethods(slots.envMap);
deleteMutationMethods(slots.processorMap);
deleteMutationMethods(slots.ruleMap);
}
/**
* Create `envMap`, `processorMap`, `ruleMap` with the plugins in the config array.
* @param {ConfigArray} instance The config elements.
* @returns {ConfigArrayInternalSlots} The extracted config.
*/
function ensurePluginMemberMaps(instance) {
const slots = internalSlotsMap.get(instance);
if (!slots.ruleMap) {
initPluginMemberMaps(instance, slots);
}
return slots;
}
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
/**
* The Config Array.
*
* `ConfigArray` instance contains all settings, parsers, and plugins.
* You need to call `ConfigArray#extractConfig(filePath)` method in order to
* extract, merge and get only the config data which is related to an arbitrary
* file.
* @extends {Array<ConfigArrayElement>}
*/
class ConfigArray extends Array {
/**
* Get the plugin environments.
* The returned map cannot be mutated.
* @type {ReadonlyMap<string, Environment>} The plugin environments.
*/
get pluginEnvironments() {
return ensurePluginMemberMaps(this).envMap;
}
/**
* Get the plugin processors.
* The returned map cannot be mutated.
* @type {ReadonlyMap<string, Processor>} The plugin processors.
*/
get pluginProcessors() {
return ensurePluginMemberMaps(this).processorMap;
}
/**
* Get the plugin rules.
* The returned map cannot be mutated.
* @returns {ReadonlyMap<string, Rule>} The plugin rules.
*/
get pluginRules() {
return ensurePluginMemberMaps(this).ruleMap;
}
/**
* Check if this config has `root` flag.
* @returns {boolean} `true` if this config array is root.
*/
isRoot() {
for (let i = this.length - 1; i >= 0; --i) {
const root = this[i].root;
if (typeof root === "boolean") {
return root;
}
}
return false;
}
/**
* Extract the config data which is related to a given file.
* @param {string} filePath The absolute path to the target file.
* @returns {ExtractedConfig} The extracted config data.
*/
extractConfig(filePath) {
const { cache } = internalSlotsMap.get(this);
const indices = getMatchedIndices(this, filePath);
const cacheKey = indices.join(",");
if (!cache.has(cacheKey)) {
cache.set(cacheKey, createConfig(this, indices));
}
return cache.get(cacheKey);
}
/**
* Check if a given path is an additional lint target.
* @param {string} filePath The absolute path to the target file.
* @returns {boolean} `true` if the file is an additional lint target.
*/
isAdditionalTargetPath(filePath) {
for (const { criteria, type } of this) {
if (
type === "config" &&
criteria &&
!criteria.endsWithWildcard &&
criteria.test(filePath)
) {
return true;
}
}
return false;
}
}
/**
* Get the used extracted configs.
* CLIEngine will use this method to collect used deprecated rules.
* @param {ConfigArray} instance The config array object to get.
* @returns {ExtractedConfig[]} The used extracted configs.
* @private
*/
function getUsedExtractedConfigs(instance) {
const { cache } = internalSlotsMap.get(instance);
return Array.from(cache.values());
}
export {
ConfigArray,
getUsedExtractedConfigs
};

View File

@ -0,0 +1,115 @@
/**
* @fileoverview `ConfigDependency` class.
*
* `ConfigDependency` class expresses a loaded parser or plugin.
*
* If the parser or plugin was loaded successfully, it has `definition` property
* and `filePath` property. Otherwise, it has `error` property.
*
* When `JSON.stringify()` converted a `ConfigDependency` object to a JSON, it
* omits `definition` property.
*
* `ConfigArrayFactory` creates `ConfigDependency` objects when it loads parsers
* or plugins.
*
* @author Toru Nagashima <https://github.com/mysticatea>
*/
import util from "util";
/**
* The class is to store parsers or plugins.
* This class hides the loaded object from `JSON.stringify()` and `console.log`.
* @template T
*/
class ConfigDependency {
/**
* Initialize this instance.
* @param {Object} data The dependency data.
* @param {T} [data.definition] The dependency if the loading succeeded.
* @param {Error} [data.error] The error object if the loading failed.
* @param {string} [data.filePath] The actual path to the dependency if the loading succeeded.
* @param {string} data.id The ID of this dependency.
* @param {string} data.importerName The name of the config file which loads this dependency.
* @param {string} data.importerPath The path to the config file which loads this dependency.
*/
constructor({
definition = null,
error = null,
filePath = null,
id,
importerName,
importerPath
}) {
/**
* The loaded dependency if the loading succeeded.
* @type {T|null}
*/
this.definition = definition;
/**
* The error object if the loading failed.
* @type {Error|null}
*/
this.error = error;
/**
* The loaded dependency if the loading succeeded.
* @type {string|null}
*/
this.filePath = filePath;
/**
* The ID of this dependency.
* @type {string}
*/
this.id = id;
/**
* The name of the config file which loads this dependency.
* @type {string}
*/
this.importerName = importerName;
/**
* The path to the config file which loads this dependency.
* @type {string}
*/
this.importerPath = importerPath;
}
// eslint-disable-next-line jsdoc/require-description
/**
* @returns {Object} a JSON compatible object.
*/
toJSON() {
const obj = this[util.inspect.custom]();
// Display `error.message` (`Error#message` is unenumerable).
if (obj.error instanceof Error) {
obj.error = { ...obj.error, message: obj.error.message };
}
return obj;
}
// eslint-disable-next-line jsdoc/require-description
/**
* @returns {Object} an object to display by `console.log()`.
*/
[util.inspect.custom]() {
const {
definition: _ignore, // eslint-disable-line no-unused-vars
...obj
} = this;
return obj;
}
}
/** @typedef {ConfigDependency<import("../../shared/types").Parser>} DependentParser */
/** @typedef {ConfigDependency<import("../../shared/types").Plugin>} DependentPlugin */
export { ConfigDependency };

View File

@ -0,0 +1,145 @@
/**
* @fileoverview `ExtractedConfig` class.
*
* `ExtractedConfig` class expresses a final configuration for a specific file.
*
* It provides one method.
*
* - `toCompatibleObjectAsConfigFileContent()`
* Convert this configuration to the compatible object as the content of
* config files. It converts the loaded parser and plugins to strings.
* `CLIEngine#getConfigForFile(filePath)` method uses this method.
*
* `ConfigArray#extractConfig(filePath)` creates a `ExtractedConfig` instance.
*
* @author Toru Nagashima <https://github.com/mysticatea>
*/
import { IgnorePattern } from "./ignore-pattern.js";
// For VSCode intellisense
/** @typedef {import("../../shared/types").ConfigData} ConfigData */
/** @typedef {import("../../shared/types").GlobalConf} GlobalConf */
/** @typedef {import("../../shared/types").SeverityConf} SeverityConf */
/** @typedef {import("./config-dependency").DependentParser} DependentParser */
/** @typedef {import("./config-dependency").DependentPlugin} DependentPlugin */
/**
* Check if `xs` starts with `ys`.
* @template T
* @param {T[]} xs The array to check.
* @param {T[]} ys The array that may be the first part of `xs`.
* @returns {boolean} `true` if `xs` starts with `ys`.
*/
function startsWith(xs, ys) {
return xs.length >= ys.length && ys.every((y, i) => y === xs[i]);
}
/**
* The class for extracted config data.
*/
class ExtractedConfig {
constructor() {
/**
* The config name what `noInlineConfig` setting came from.
* @type {string}
*/
this.configNameOfNoInlineConfig = "";
/**
* Environments.
* @type {Record<string, boolean>}
*/
this.env = {};
/**
* Global variables.
* @type {Record<string, GlobalConf>}
*/
this.globals = {};
/**
* The glob patterns that ignore to lint.
* @type {(((filePath:string, dot?:boolean) => boolean) & { basePath:string; patterns:string[] }) | undefined}
*/
this.ignores = void 0;
/**
* The flag that disables directive comments.
* @type {boolean|undefined}
*/
this.noInlineConfig = void 0;
/**
* Parser definition.
* @type {DependentParser|null}
*/
this.parser = null;
/**
* Options for the parser.
* @type {Object}
*/
this.parserOptions = {};
/**
* Plugin definitions.
* @type {Record<string, DependentPlugin>}
*/
this.plugins = {};
/**
* Processor ID.
* @type {string|null}
*/
this.processor = null;
/**
* The flag that reports unused `eslint-disable` directive comments.
* @type {boolean|undefined}
*/
this.reportUnusedDisableDirectives = void 0;
/**
* Rule settings.
* @type {Record<string, [SeverityConf, ...any[]]>}
*/
this.rules = {};
/**
* Shared settings.
* @type {Object}
*/
this.settings = {};
}
/**
* Convert this config to the compatible object as a config file content.
* @returns {ConfigData} The converted object.
*/
toCompatibleObjectAsConfigFileContent() {
const {
/* eslint-disable no-unused-vars */
configNameOfNoInlineConfig: _ignore1,
processor: _ignore2,
/* eslint-enable no-unused-vars */
ignores,
...config
} = this;
config.parser = config.parser && config.parser.filePath;
config.plugins = Object.keys(config.plugins).filter(Boolean).reverse();
config.ignorePatterns = ignores ? ignores.patterns : [];
// Strip the default patterns from `ignorePatterns`.
if (startsWith(config.ignorePatterns, IgnorePattern.DefaultPatterns)) {
config.ignorePatterns =
config.ignorePatterns.slice(IgnorePattern.DefaultPatterns.length);
}
return config;
}
}
export { ExtractedConfig };

View File

@ -0,0 +1,238 @@
/**
* @fileoverview `IgnorePattern` class.
*
* `IgnorePattern` class has the set of glob patterns and the base path.
*
* It provides two static methods.
*
* - `IgnorePattern.createDefaultIgnore(cwd)`
* Create the default predicate function.
* - `IgnorePattern.createIgnore(ignorePatterns)`
* Create the predicate function from multiple `IgnorePattern` objects.
*
* It provides two properties and a method.
*
* - `patterns`
* The glob patterns that ignore to lint.
* - `basePath`
* The base path of the glob patterns. If absolute paths existed in the
* glob patterns, those are handled as relative paths to the base path.
* - `getPatternsRelativeTo(basePath)`
* Get `patterns` as modified for a given base path. It modifies the
* absolute paths in the patterns as prepending the difference of two base
* paths.
*
* `ConfigArrayFactory` creates `IgnorePattern` objects when it processes
* `ignorePatterns` properties.
*
* @author Toru Nagashima <https://github.com/mysticatea>
*/
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
import assert from "assert";
import path from "path";
import ignore from "ignore";
import debugOrig from "debug";
const debug = debugOrig("eslintrc:ignore-pattern");
/** @typedef {ReturnType<import("ignore").default>} Ignore */
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
/**
* Get the path to the common ancestor directory of given paths.
* @param {string[]} sourcePaths The paths to calculate the common ancestor.
* @returns {string} The path to the common ancestor directory.
*/
function getCommonAncestorPath(sourcePaths) {
let result = sourcePaths[0];
for (let i = 1; i < sourcePaths.length; ++i) {
const a = result;
const b = sourcePaths[i];
// Set the shorter one (it's the common ancestor if one includes the other).
result = a.length < b.length ? a : b;
// Set the common ancestor.
for (let j = 0, lastSepPos = 0; j < a.length && j < b.length; ++j) {
if (a[j] !== b[j]) {
result = a.slice(0, lastSepPos);
break;
}
if (a[j] === path.sep) {
lastSepPos = j;
}
}
}
let resolvedResult = result || path.sep;
// if Windows common ancestor is root of drive must have trailing slash to be absolute.
if (resolvedResult && resolvedResult.endsWith(":") && process.platform === "win32") {
resolvedResult += path.sep;
}
return resolvedResult;
}
/**
* Make relative path.
* @param {string} from The source path to get relative path.
* @param {string} to The destination path to get relative path.
* @returns {string} The relative path.
*/
function relative(from, to) {
const relPath = path.relative(from, to);
if (path.sep === "/") {
return relPath;
}
return relPath.split(path.sep).join("/");
}
/**
* Get the trailing slash if existed.
* @param {string} filePath The path to check.
* @returns {string} The trailing slash if existed.
*/
function dirSuffix(filePath) {
const isDir = (
filePath.endsWith(path.sep) ||
(process.platform === "win32" && filePath.endsWith("/"))
);
return isDir ? "/" : "";
}
const DefaultPatterns = Object.freeze(["/**/node_modules/*"]);
const DotPatterns = Object.freeze([".*", "!.eslintrc.*", "!../"]);
//------------------------------------------------------------------------------
// Public
//------------------------------------------------------------------------------
class IgnorePattern {
/**
* The default patterns.
* @type {string[]}
*/
static get DefaultPatterns() {
return DefaultPatterns;
}
/**
* Create the default predicate function.
* @param {string} cwd The current working directory.
* @returns {((filePath:string, dot:boolean) => boolean) & {basePath:string; patterns:string[]}}
* The preficate function.
* The first argument is an absolute path that is checked.
* The second argument is the flag to not ignore dotfiles.
* If the predicate function returned `true`, it means the path should be ignored.
*/
static createDefaultIgnore(cwd) {
return this.createIgnore([new IgnorePattern(DefaultPatterns, cwd)]);
}
/**
* Create the predicate function from multiple `IgnorePattern` objects.
* @param {IgnorePattern[]} ignorePatterns The list of ignore patterns.
* @returns {((filePath:string, dot?:boolean) => boolean) & {basePath:string; patterns:string[]}}
* The preficate function.
* The first argument is an absolute path that is checked.
* The second argument is the flag to not ignore dotfiles.
* If the predicate function returned `true`, it means the path should be ignored.
*/
static createIgnore(ignorePatterns) {
debug("Create with: %o", ignorePatterns);
const basePath = getCommonAncestorPath(ignorePatterns.map(p => p.basePath));
const patterns = [].concat(
...ignorePatterns.map(p => p.getPatternsRelativeTo(basePath))
);
const ig = ignore({ allowRelativePaths: true }).add([...DotPatterns, ...patterns]);
const dotIg = ignore({ allowRelativePaths: true }).add(patterns);
debug(" processed: %o", { basePath, patterns });
return Object.assign(
(filePath, dot = false) => {
assert(path.isAbsolute(filePath), "'filePath' should be an absolute path.");
const relPathRaw = relative(basePath, filePath);
const relPath = relPathRaw && (relPathRaw + dirSuffix(filePath));
const adoptedIg = dot ? dotIg : ig;
const result = relPath !== "" && adoptedIg.ignores(relPath);
debug("Check", { filePath, dot, relativePath: relPath, result });
return result;
},
{ basePath, patterns }
);
}
/**
* Initialize a new `IgnorePattern` instance.
* @param {string[]} patterns The glob patterns that ignore to lint.
* @param {string} basePath The base path of `patterns`.
*/
constructor(patterns, basePath) {
assert(path.isAbsolute(basePath), "'basePath' should be an absolute path.");
/**
* The glob patterns that ignore to lint.
* @type {string[]}
*/
this.patterns = patterns;
/**
* The base path of `patterns`.
* @type {string}
*/
this.basePath = basePath;
/**
* If `true` then patterns which don't start with `/` will match the paths to the outside of `basePath`. Defaults to `false`.
*
* It's set `true` for `.eslintignore`, `package.json`, and `--ignore-path` for backward compatibility.
* It's `false` as-is for `ignorePatterns` property in config files.
* @type {boolean}
*/
this.loose = false;
}
/**
* Get `patterns` as modified for a given base path. It modifies the
* absolute paths in the patterns as prepending the difference of two base
* paths.
* @param {string} newBasePath The base path.
* @returns {string[]} Modifired patterns.
*/
getPatternsRelativeTo(newBasePath) {
assert(path.isAbsolute(newBasePath), "'newBasePath' should be an absolute path.");
const { basePath, loose, patterns } = this;
if (newBasePath === basePath) {
return patterns;
}
const prefix = `/${relative(newBasePath, basePath)}`;
return patterns.map(pattern => {
const negative = pattern.startsWith("!");
const head = negative ? "!" : "";
const body = negative ? pattern.slice(1) : pattern;
if (body.startsWith("/") || body.startsWith("../")) {
return `${head}${prefix}${body}`;
}
return loose ? pattern : `${head}${prefix}/**/${body}`;
});
}
}
export { IgnorePattern };

View File

@ -0,0 +1,19 @@
/**
* @fileoverview `ConfigArray` class.
* @author Toru Nagashima <https://github.com/mysticatea>
*/
import { ConfigArray, getUsedExtractedConfigs } from "./config-array.js";
import { ConfigDependency } from "./config-dependency.js";
import { ExtractedConfig } from "./extracted-config.js";
import { IgnorePattern } from "./ignore-pattern.js";
import { OverrideTester } from "./override-tester.js";
export {
ConfigArray,
ConfigDependency,
ExtractedConfig,
IgnorePattern,
OverrideTester,
getUsedExtractedConfigs
};

View File

@ -0,0 +1,225 @@
/**
* @fileoverview `OverrideTester` class.
*
* `OverrideTester` class handles `files` property and `excludedFiles` property
* of `overrides` config.
*
* It provides one method.
*
* - `test(filePath)`
* Test if a file path matches the pair of `files` property and
* `excludedFiles` property. The `filePath` argument must be an absolute
* path.
*
* `ConfigArrayFactory` creates `OverrideTester` objects when it processes
* `overrides` properties.
*
* @author Toru Nagashima <https://github.com/mysticatea>
*/
import assert from "assert";
import path from "path";
import util from "util";
import minimatch from "minimatch";
const { Minimatch } = minimatch;
const minimatchOpts = { dot: true, matchBase: true };
/**
* @typedef {Object} Pattern
* @property {InstanceType<Minimatch>[] | null} includes The positive matchers.
* @property {InstanceType<Minimatch>[] | null} excludes The negative matchers.
*/
/**
* Normalize a given pattern to an array.
* @param {string|string[]|undefined} patterns A glob pattern or an array of glob patterns.
* @returns {string[]|null} Normalized patterns.
* @private
*/
function normalizePatterns(patterns) {
if (Array.isArray(patterns)) {
return patterns.filter(Boolean);
}
if (typeof patterns === "string" && patterns) {
return [patterns];
}
return [];
}
/**
* Create the matchers of given patterns.
* @param {string[]} patterns The patterns.
* @returns {InstanceType<Minimatch>[] | null} The matchers.
*/
function toMatcher(patterns) {
if (patterns.length === 0) {
return null;
}
return patterns.map(pattern => {
if (/^\.[/\\]/u.test(pattern)) {
return new Minimatch(
pattern.slice(2),
// `./*.js` should not match with `subdir/foo.js`
{ ...minimatchOpts, matchBase: false }
);
}
return new Minimatch(pattern, minimatchOpts);
});
}
/**
* Convert a given matcher to string.
* @param {Pattern} matchers The matchers.
* @returns {string} The string expression of the matcher.
*/
function patternToJson({ includes, excludes }) {
return {
includes: includes && includes.map(m => m.pattern),
excludes: excludes && excludes.map(m => m.pattern)
};
}
/**
* The class to test given paths are matched by the patterns.
*/
class OverrideTester {
/**
* Create a tester with given criteria.
* If there are no criteria, returns `null`.
* @param {string|string[]} files The glob patterns for included files.
* @param {string|string[]} excludedFiles The glob patterns for excluded files.
* @param {string} basePath The path to the base directory to test paths.
* @returns {OverrideTester|null} The created instance or `null`.
*/
static create(files, excludedFiles, basePath) {
const includePatterns = normalizePatterns(files);
const excludePatterns = normalizePatterns(excludedFiles);
let endsWithWildcard = false;
if (includePatterns.length === 0) {
return null;
}
// Rejects absolute paths or relative paths to parents.
for (const pattern of includePatterns) {
if (path.isAbsolute(pattern) || pattern.includes("..")) {
throw new Error(`Invalid override pattern (expected relative path not containing '..'): ${pattern}`);
}
if (pattern.endsWith("*")) {
endsWithWildcard = true;
}
}
for (const pattern of excludePatterns) {
if (path.isAbsolute(pattern) || pattern.includes("..")) {
throw new Error(`Invalid override pattern (expected relative path not containing '..'): ${pattern}`);
}
}
const includes = toMatcher(includePatterns);
const excludes = toMatcher(excludePatterns);
return new OverrideTester(
[{ includes, excludes }],
basePath,
endsWithWildcard
);
}
/**
* Combine two testers by logical and.
* If either of the testers was `null`, returns the other tester.
* The `basePath` property of the two must be the same value.
* @param {OverrideTester|null} a A tester.
* @param {OverrideTester|null} b Another tester.
* @returns {OverrideTester|null} Combined tester.
*/
static and(a, b) {
if (!b) {
return a && new OverrideTester(
a.patterns,
a.basePath,
a.endsWithWildcard
);
}
if (!a) {
return new OverrideTester(
b.patterns,
b.basePath,
b.endsWithWildcard
);
}
assert.strictEqual(a.basePath, b.basePath);
return new OverrideTester(
a.patterns.concat(b.patterns),
a.basePath,
a.endsWithWildcard || b.endsWithWildcard
);
}
/**
* Initialize this instance.
* @param {Pattern[]} patterns The matchers.
* @param {string} basePath The base path.
* @param {boolean} endsWithWildcard If `true` then a pattern ends with `*`.
*/
constructor(patterns, basePath, endsWithWildcard = false) {
/** @type {Pattern[]} */
this.patterns = patterns;
/** @type {string} */
this.basePath = basePath;
/** @type {boolean} */
this.endsWithWildcard = endsWithWildcard;
}
/**
* Test if a given path is matched or not.
* @param {string} filePath The absolute path to the target file.
* @returns {boolean} `true` if the path was matched.
*/
test(filePath) {
if (typeof filePath !== "string" || !path.isAbsolute(filePath)) {
throw new Error(`'filePath' should be an absolute path, but got ${filePath}.`);
}
const relativePath = path.relative(this.basePath, filePath);
return this.patterns.every(({ includes, excludes }) => (
(!includes || includes.some(m => m.match(relativePath))) &&
(!excludes || !excludes.some(m => m.match(relativePath)))
));
}
// eslint-disable-next-line jsdoc/require-description
/**
* @returns {Object} a JSON compatible object.
*/
toJSON() {
if (this.patterns.length === 1) {
return {
...patternToJson(this.patterns[0]),
basePath: this.basePath
};
}
return {
AND: this.patterns.map(patternToJson),
basePath: this.basePath
};
}
// eslint-disable-next-line jsdoc/require-description
/**
* @returns {Object} an object to display by `console.log()`.
*/
[util.inspect.custom]() {
return this.toJSON();
}
}
export { OverrideTester };

View File

@ -0,0 +1,307 @@
/**
* @fileoverview Compatibility class for flat config.
* @author Nicholas C. Zakas
*/
//-----------------------------------------------------------------------------
// Requirements
//-----------------------------------------------------------------------------
import createDebug from "debug";
import path from "path";
import environments from "../conf/environments.js";
import { ConfigArrayFactory } from "./config-array-factory.js";
//-----------------------------------------------------------------------------
// Helpers
//-----------------------------------------------------------------------------
/** @typedef {import("../../shared/types").Environment} Environment */
/** @typedef {import("../../shared/types").Processor} Processor */
const debug = createDebug("eslintrc:flat-compat");
const cafactory = Symbol("cafactory");
/**
* Translates an ESLintRC-style config object into a flag-config-style config
* object.
* @param {Object} eslintrcConfig An ESLintRC-style config object.
* @param {Object} options Options to help translate the config.
* @param {string} options.resolveConfigRelativeTo To the directory to resolve
* configs from.
* @param {string} options.resolvePluginsRelativeTo The directory to resolve
* plugins from.
* @param {ReadOnlyMap<string,Environment>} options.pluginEnvironments A map of plugin environment
* names to objects.
* @param {ReadOnlyMap<string,Processor>} options.pluginProcessors A map of plugin processor
* names to objects.
* @returns {Object} A flag-config-style config object.
*/
function translateESLintRC(eslintrcConfig, {
resolveConfigRelativeTo,
resolvePluginsRelativeTo,
pluginEnvironments,
pluginProcessors
}) {
const flatConfig = {};
const configs = [];
const languageOptions = {};
const linterOptions = {};
const keysToCopy = ["settings", "rules", "processor"];
const languageOptionsKeysToCopy = ["globals", "parser", "parserOptions"];
const linterOptionsKeysToCopy = ["noInlineConfig", "reportUnusedDisableDirectives"];
// check for special settings for eslint:all and eslint:recommended:
if (eslintrcConfig.settings) {
if (eslintrcConfig.settings["eslint:all"] === true) {
return ["eslint:all"];
}
if (eslintrcConfig.settings["eslint:recommended"] === true) {
return ["eslint:recommended"];
}
}
// copy over simple translations
for (const key of keysToCopy) {
if (key in eslintrcConfig && typeof eslintrcConfig[key] !== "undefined") {
flatConfig[key] = eslintrcConfig[key];
}
}
// copy over languageOptions
for (const key of languageOptionsKeysToCopy) {
if (key in eslintrcConfig && typeof eslintrcConfig[key] !== "undefined") {
// create the languageOptions key in the flat config
flatConfig.languageOptions = languageOptions;
if (key === "parser") {
debug(`Resolving parser '${languageOptions[key]}' relative to ${resolveConfigRelativeTo}`);
if (eslintrcConfig[key].error) {
throw eslintrcConfig[key].error;
}
languageOptions[key] = eslintrcConfig[key].definition;
continue;
}
// clone any object values that are in the eslintrc config
if (eslintrcConfig[key] && typeof eslintrcConfig[key] === "object") {
languageOptions[key] = {
...eslintrcConfig[key]
};
} else {
languageOptions[key] = eslintrcConfig[key];
}
}
}
// copy over linterOptions
for (const key of linterOptionsKeysToCopy) {
if (key in eslintrcConfig && typeof eslintrcConfig[key] !== "undefined") {
flatConfig.linterOptions = linterOptions;
linterOptions[key] = eslintrcConfig[key];
}
}
// move ecmaVersion a level up
if (languageOptions.parserOptions) {
if ("ecmaVersion" in languageOptions.parserOptions) {
languageOptions.ecmaVersion = languageOptions.parserOptions.ecmaVersion;
delete languageOptions.parserOptions.ecmaVersion;
}
if ("sourceType" in languageOptions.parserOptions) {
languageOptions.sourceType = languageOptions.parserOptions.sourceType;
delete languageOptions.parserOptions.sourceType;
}
// check to see if we even need parserOptions anymore and remove it if not
if (Object.keys(languageOptions.parserOptions).length === 0) {
delete languageOptions.parserOptions;
}
}
// overrides
if (eslintrcConfig.criteria) {
flatConfig.files = [absoluteFilePath => eslintrcConfig.criteria.test(absoluteFilePath)];
}
// translate plugins
if (eslintrcConfig.plugins && typeof eslintrcConfig.plugins === "object") {
debug(`Translating plugins: ${eslintrcConfig.plugins}`);
flatConfig.plugins = {};
for (const pluginName of Object.keys(eslintrcConfig.plugins)) {
debug(`Translating plugin: ${pluginName}`);
debug(`Resolving plugin '${pluginName} relative to ${resolvePluginsRelativeTo}`);
const { definition: plugin, error } = eslintrcConfig.plugins[pluginName];
if (error) {
throw error;
}
flatConfig.plugins[pluginName] = plugin;
// create a config for any processors
if (plugin.processors) {
for (const processorName of Object.keys(plugin.processors)) {
if (processorName.startsWith(".")) {
debug(`Assigning processor: ${pluginName}/${processorName}`);
configs.unshift({
files: [`**/*${processorName}`],
processor: pluginProcessors.get(`${pluginName}/${processorName}`)
});
}
}
}
}
}
// translate env - must come after plugins
if (eslintrcConfig.env && typeof eslintrcConfig.env === "object") {
for (const envName of Object.keys(eslintrcConfig.env)) {
// only add environments that are true
if (eslintrcConfig.env[envName]) {
debug(`Translating environment: ${envName}`);
if (environments.has(envName)) {
// built-in environments should be defined first
configs.unshift(...translateESLintRC(environments.get(envName), {
resolveConfigRelativeTo,
resolvePluginsRelativeTo
}));
} else if (pluginEnvironments.has(envName)) {
// if the environment comes from a plugin, it should come after the plugin config
configs.push(...translateESLintRC(pluginEnvironments.get(envName), {
resolveConfigRelativeTo,
resolvePluginsRelativeTo
}));
}
}
}
}
// only add if there are actually keys in the config
if (Object.keys(flatConfig).length > 0) {
configs.push(flatConfig);
}
return configs;
}
//-----------------------------------------------------------------------------
// Exports
//-----------------------------------------------------------------------------
/**
* A compatibility class for working with configs.
*/
class FlatCompat {
constructor({
baseDirectory = process.cwd(),
resolvePluginsRelativeTo = baseDirectory
} = {}) {
this.baseDirectory = baseDirectory;
this.resolvePluginsRelativeTo = resolvePluginsRelativeTo;
this[cafactory] = new ConfigArrayFactory({
cwd: baseDirectory,
resolvePluginsRelativeTo,
getEslintAllConfig: () => ({ settings: { "eslint:all": true } }),
getEslintRecommendedConfig: () => ({ settings: { "eslint:recommended": true } })
});
}
/**
* Translates an ESLintRC-style config into a flag-config-style config.
* @param {Object} eslintrcConfig The ESLintRC-style config object.
* @returns {Object} A flag-config-style config object.
*/
config(eslintrcConfig) {
const eslintrcArray = this[cafactory].create(eslintrcConfig, {
basePath: this.baseDirectory
});
const flatArray = [];
let hasIgnorePatterns = false;
eslintrcArray.forEach(configData => {
if (configData.type === "config") {
hasIgnorePatterns = hasIgnorePatterns || configData.ignorePattern;
flatArray.push(...translateESLintRC(configData, {
resolveConfigRelativeTo: path.join(this.baseDirectory, "__placeholder.js"),
resolvePluginsRelativeTo: path.join(this.resolvePluginsRelativeTo, "__placeholder.js"),
pluginEnvironments: eslintrcArray.pluginEnvironments,
pluginProcessors: eslintrcArray.pluginProcessors
}));
}
});
// combine ignorePatterns to emulate ESLintRC behavior better
if (hasIgnorePatterns) {
flatArray.unshift({
ignores: [filePath => {
// Compute the final config for this file.
// This filters config array elements by `files`/`excludedFiles` then merges the elements.
const finalConfig = eslintrcArray.extractConfig(filePath);
// Test the `ignorePattern` properties of the final config.
return Boolean(finalConfig.ignores) && finalConfig.ignores(filePath);
}]
});
}
return flatArray;
}
/**
* Translates the `env` section of an ESLintRC-style config.
* @param {Object} envConfig The `env` section of an ESLintRC config.
* @returns {Object} A flag-config object representing the environments.
*/
env(envConfig) {
return this.config({
env: envConfig
});
}
/**
* Translates the `extends` section of an ESLintRC-style config.
* @param {...string} configsToExtend The names of the configs to load.
* @returns {Object} A flag-config object representing the config.
*/
extends(...configsToExtend) {
return this.config({
extends: configsToExtend
});
}
/**
* Translates the `plugins` section of an ESLintRC-style config.
* @param {...string} plugins The names of the plugins to load.
* @returns {Object} A flag-config object representing the plugins.
*/
plugins(...plugins) {
return this.config({
plugins
});
}
}
export { FlatCompat };

View File

@ -0,0 +1,29 @@
/**
* @fileoverview Package exports for @eslint/eslintrc
* @author Nicholas C. Zakas
*/
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
import * as ConfigOps from "./shared/config-ops.js";
import ConfigValidator from "./shared/config-validator.js";
import * as naming from "./shared/naming.js";
import environments from "../conf/environments.js";
//-----------------------------------------------------------------------------
// Exports
//-----------------------------------------------------------------------------
const Legacy = {
environments,
// shared
ConfigOps,
ConfigValidator,
naming
};
export {
Legacy
};

View File

@ -0,0 +1,56 @@
/**
* @fileoverview Package exports for @eslint/eslintrc
* @author Nicholas C. Zakas
*/
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
import {
ConfigArrayFactory,
createContext as createConfigArrayFactoryContext
} from "./config-array-factory.js";
import { CascadingConfigArrayFactory } from "./cascading-config-array-factory.js";
import * as ModuleResolver from "./shared/relative-module-resolver.js";
import { ConfigArray, getUsedExtractedConfigs } from "./config-array/index.js";
import { ConfigDependency } from "./config-array/config-dependency.js";
import { ExtractedConfig } from "./config-array/extracted-config.js";
import { IgnorePattern } from "./config-array/ignore-pattern.js";
import { OverrideTester } from "./config-array/override-tester.js";
import * as ConfigOps from "./shared/config-ops.js";
import ConfigValidator from "./shared/config-validator.js";
import * as naming from "./shared/naming.js";
import { FlatCompat } from "./flat-compat.js";
import environments from "../conf/environments.js";
//-----------------------------------------------------------------------------
// Exports
//-----------------------------------------------------------------------------
const Legacy = {
ConfigArray,
createConfigArrayFactoryContext,
CascadingConfigArrayFactory,
ConfigArrayFactory,
ConfigDependency,
ExtractedConfig,
IgnorePattern,
OverrideTester,
getUsedExtractedConfigs,
environments,
// shared
ConfigOps,
ConfigValidator,
ModuleResolver,
naming
};
export {
Legacy,
FlatCompat
};

View File

@ -0,0 +1,191 @@
/**
* @fileoverview The instance of Ajv validator.
* @author Evgeny Poberezkin
*/
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
import Ajv from "ajv";
//-----------------------------------------------------------------------------
// Helpers
//-----------------------------------------------------------------------------
/*
* Copied from ajv/lib/refs/json-schema-draft-04.json
* The MIT License (MIT)
* Copyright (c) 2015-2017 Evgeny Poberezkin
*/
const metaSchema = {
id: "http://json-schema.org/draft-04/schema#",
$schema: "http://json-schema.org/draft-04/schema#",
description: "Core schema meta-schema",
definitions: {
schemaArray: {
type: "array",
minItems: 1,
items: { $ref: "#" }
},
positiveInteger: {
type: "integer",
minimum: 0
},
positiveIntegerDefault0: {
allOf: [{ $ref: "#/definitions/positiveInteger" }, { default: 0 }]
},
simpleTypes: {
enum: ["array", "boolean", "integer", "null", "number", "object", "string"]
},
stringArray: {
type: "array",
items: { type: "string" },
minItems: 1,
uniqueItems: true
}
},
type: "object",
properties: {
id: {
type: "string"
},
$schema: {
type: "string"
},
title: {
type: "string"
},
description: {
type: "string"
},
default: { },
multipleOf: {
type: "number",
minimum: 0,
exclusiveMinimum: true
},
maximum: {
type: "number"
},
exclusiveMaximum: {
type: "boolean",
default: false
},
minimum: {
type: "number"
},
exclusiveMinimum: {
type: "boolean",
default: false
},
maxLength: { $ref: "#/definitions/positiveInteger" },
minLength: { $ref: "#/definitions/positiveIntegerDefault0" },
pattern: {
type: "string",
format: "regex"
},
additionalItems: {
anyOf: [
{ type: "boolean" },
{ $ref: "#" }
],
default: { }
},
items: {
anyOf: [
{ $ref: "#" },
{ $ref: "#/definitions/schemaArray" }
],
default: { }
},
maxItems: { $ref: "#/definitions/positiveInteger" },
minItems: { $ref: "#/definitions/positiveIntegerDefault0" },
uniqueItems: {
type: "boolean",
default: false
},
maxProperties: { $ref: "#/definitions/positiveInteger" },
minProperties: { $ref: "#/definitions/positiveIntegerDefault0" },
required: { $ref: "#/definitions/stringArray" },
additionalProperties: {
anyOf: [
{ type: "boolean" },
{ $ref: "#" }
],
default: { }
},
definitions: {
type: "object",
additionalProperties: { $ref: "#" },
default: { }
},
properties: {
type: "object",
additionalProperties: { $ref: "#" },
default: { }
},
patternProperties: {
type: "object",
additionalProperties: { $ref: "#" },
default: { }
},
dependencies: {
type: "object",
additionalProperties: {
anyOf: [
{ $ref: "#" },
{ $ref: "#/definitions/stringArray" }
]
}
},
enum: {
type: "array",
minItems: 1,
uniqueItems: true
},
type: {
anyOf: [
{ $ref: "#/definitions/simpleTypes" },
{
type: "array",
items: { $ref: "#/definitions/simpleTypes" },
minItems: 1,
uniqueItems: true
}
]
},
format: { type: "string" },
allOf: { $ref: "#/definitions/schemaArray" },
anyOf: { $ref: "#/definitions/schemaArray" },
oneOf: { $ref: "#/definitions/schemaArray" },
not: { $ref: "#" }
},
dependencies: {
exclusiveMaximum: ["maximum"],
exclusiveMinimum: ["minimum"]
},
default: { }
};
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
export default (additionalOptions = {}) => {
const ajv = new Ajv({
meta: false,
useDefaults: true,
validateSchema: false,
missingRefs: "ignore",
verbose: true,
schemaId: "auto",
...additionalOptions
});
ajv.addMetaSchema(metaSchema);
// eslint-disable-next-line no-underscore-dangle
ajv._opts.defaultMeta = metaSchema.id;
return ajv;
};

View File

@ -0,0 +1,135 @@
/**
* @fileoverview Config file operations. This file must be usable in the browser,
* so no Node-specific code can be here.
* @author Nicholas C. Zakas
*/
//------------------------------------------------------------------------------
// Private
//------------------------------------------------------------------------------
const RULE_SEVERITY_STRINGS = ["off", "warn", "error"],
RULE_SEVERITY = RULE_SEVERITY_STRINGS.reduce((map, value, index) => {
map[value] = index;
return map;
}, {}),
VALID_SEVERITIES = [0, 1, 2, "off", "warn", "error"];
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
/**
* Normalizes the severity value of a rule's configuration to a number
* @param {(number|string|[number, ...*]|[string, ...*])} ruleConfig A rule's configuration value, generally
* received from the user. A valid config value is either 0, 1, 2, the string "off" (treated the same as 0),
* the string "warn" (treated the same as 1), the string "error" (treated the same as 2), or an array
* whose first element is one of the above values. Strings are matched case-insensitively.
* @returns {(0|1|2)} The numeric severity value if the config value was valid, otherwise 0.
*/
function getRuleSeverity(ruleConfig) {
const severityValue = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig;
if (severityValue === 0 || severityValue === 1 || severityValue === 2) {
return severityValue;
}
if (typeof severityValue === "string") {
return RULE_SEVERITY[severityValue.toLowerCase()] || 0;
}
return 0;
}
/**
* Converts old-style severity settings (0, 1, 2) into new-style
* severity settings (off, warn, error) for all rules. Assumption is that severity
* values have already been validated as correct.
* @param {Object} config The config object to normalize.
* @returns {void}
*/
function normalizeToStrings(config) {
if (config.rules) {
Object.keys(config.rules).forEach(ruleId => {
const ruleConfig = config.rules[ruleId];
if (typeof ruleConfig === "number") {
config.rules[ruleId] = RULE_SEVERITY_STRINGS[ruleConfig] || RULE_SEVERITY_STRINGS[0];
} else if (Array.isArray(ruleConfig) && typeof ruleConfig[0] === "number") {
ruleConfig[0] = RULE_SEVERITY_STRINGS[ruleConfig[0]] || RULE_SEVERITY_STRINGS[0];
}
});
}
}
/**
* Determines if the severity for the given rule configuration represents an error.
* @param {int|string|Array} ruleConfig The configuration for an individual rule.
* @returns {boolean} True if the rule represents an error, false if not.
*/
function isErrorSeverity(ruleConfig) {
return getRuleSeverity(ruleConfig) === 2;
}
/**
* Checks whether a given config has valid severity or not.
* @param {number|string|Array} ruleConfig The configuration for an individual rule.
* @returns {boolean} `true` if the configuration has valid severity.
*/
function isValidSeverity(ruleConfig) {
let severity = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig;
if (typeof severity === "string") {
severity = severity.toLowerCase();
}
return VALID_SEVERITIES.indexOf(severity) !== -1;
}
/**
* Checks whether every rule of a given config has valid severity or not.
* @param {Object} config The configuration for rules.
* @returns {boolean} `true` if the configuration has valid severity.
*/
function isEverySeverityValid(config) {
return Object.keys(config).every(ruleId => isValidSeverity(config[ruleId]));
}
/**
* Normalizes a value for a global in a config
* @param {(boolean|string|null)} configuredValue The value given for a global in configuration or in
* a global directive comment
* @returns {("readable"|"writeable"|"off")} The value normalized as a string
* @throws Error if global value is invalid
*/
function normalizeConfigGlobal(configuredValue) {
switch (configuredValue) {
case "off":
return "off";
case true:
case "true":
case "writeable":
case "writable":
return "writable";
case null:
case false:
case "false":
case "readable":
case "readonly":
return "readonly";
default:
throw new Error(`'${configuredValue}' is not a valid configuration for a global (use 'readonly', 'writable', or 'off')`);
}
}
export {
getRuleSeverity,
normalizeToStrings,
isErrorSeverity,
isValidSeverity,
isEverySeverityValid,
normalizeConfigGlobal
};

View File

@ -0,0 +1,325 @@
/**
* @fileoverview Validates configs.
* @author Brandon Mills
*/
/* eslint class-methods-use-this: "off" */
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
import util from "util";
import * as ConfigOps from "./config-ops.js";
import { emitDeprecationWarning } from "./deprecation-warnings.js";
import ajvOrig from "./ajv.js";
import configSchema from "../../conf/config-schema.js";
import BuiltInEnvironments from "../../conf/environments.js";
const ajv = ajvOrig();
const ruleValidators = new WeakMap();
const noop = Function.prototype;
//------------------------------------------------------------------------------
// Private
//------------------------------------------------------------------------------
let validateSchema;
const severityMap = {
error: 2,
warn: 1,
off: 0
};
const validated = new WeakSet();
//-----------------------------------------------------------------------------
// Exports
//-----------------------------------------------------------------------------
export default class ConfigValidator {
constructor({ builtInRules = new Map() } = {}) {
this.builtInRules = builtInRules;
}
/**
* Gets a complete options schema for a rule.
* @param {{create: Function, schema: (Array|null)}} rule A new-style rule object
* @returns {Object} JSON Schema for the rule's options.
*/
getRuleOptionsSchema(rule) {
if (!rule) {
return null;
}
const schema = rule.schema || rule.meta && rule.meta.schema;
// Given a tuple of schemas, insert warning level at the beginning
if (Array.isArray(schema)) {
if (schema.length) {
return {
type: "array",
items: schema,
minItems: 0,
maxItems: schema.length
};
}
return {
type: "array",
minItems: 0,
maxItems: 0
};
}
// Given a full schema, leave it alone
return schema || null;
}
/**
* Validates a rule's severity and returns the severity value. Throws an error if the severity is invalid.
* @param {options} options The given options for the rule.
* @returns {number|string} The rule's severity value
*/
validateRuleSeverity(options) {
const severity = Array.isArray(options) ? options[0] : options;
const normSeverity = typeof severity === "string" ? severityMap[severity.toLowerCase()] : severity;
if (normSeverity === 0 || normSeverity === 1 || normSeverity === 2) {
return normSeverity;
}
throw new Error(`\tSeverity should be one of the following: 0 = off, 1 = warn, 2 = error (you passed '${util.inspect(severity).replace(/'/gu, "\"").replace(/\n/gu, "")}').\n`);
}
/**
* Validates the non-severity options passed to a rule, based on its schema.
* @param {{create: Function}} rule The rule to validate
* @param {Array} localOptions The options for the rule, excluding severity
* @returns {void}
*/
validateRuleSchema(rule, localOptions) {
if (!ruleValidators.has(rule)) {
const schema = this.getRuleOptionsSchema(rule);
if (schema) {
ruleValidators.set(rule, ajv.compile(schema));
}
}
const validateRule = ruleValidators.get(rule);
if (validateRule) {
validateRule(localOptions);
if (validateRule.errors) {
throw new Error(validateRule.errors.map(
error => `\tValue ${JSON.stringify(error.data)} ${error.message}.\n`
).join(""));
}
}
}
/**
* Validates a rule's options against its schema.
* @param {{create: Function}|null} rule The rule that the config is being validated for
* @param {string} ruleId The rule's unique name.
* @param {Array|number} options The given options for the rule.
* @param {string|null} source The name of the configuration source to report in any errors. If null or undefined,
* no source is prepended to the message.
* @returns {void}
*/
validateRuleOptions(rule, ruleId, options, source = null) {
try {
const severity = this.validateRuleSeverity(options);
if (severity !== 0) {
this.validateRuleSchema(rule, Array.isArray(options) ? options.slice(1) : []);
}
} catch (err) {
const enhancedMessage = `Configuration for rule "${ruleId}" is invalid:\n${err.message}`;
if (typeof source === "string") {
throw new Error(`${source}:\n\t${enhancedMessage}`);
} else {
throw new Error(enhancedMessage);
}
}
}
/**
* Validates an environment object
* @param {Object} environment The environment config object to validate.
* @param {string} source The name of the configuration source to report in any errors.
* @param {function(envId:string): Object} [getAdditionalEnv] A map from strings to loaded environments.
* @returns {void}
*/
validateEnvironment(
environment,
source,
getAdditionalEnv = noop
) {
// not having an environment is ok
if (!environment) {
return;
}
Object.keys(environment).forEach(id => {
const env = getAdditionalEnv(id) || BuiltInEnvironments.get(id) || null;
if (!env) {
const message = `${source}:\n\tEnvironment key "${id}" is unknown\n`;
throw new Error(message);
}
});
}
/**
* Validates a rules config object
* @param {Object} rulesConfig The rules config object to validate.
* @param {string} source The name of the configuration source to report in any errors.
* @param {function(ruleId:string): Object} getAdditionalRule A map from strings to loaded rules
* @returns {void}
*/
validateRules(
rulesConfig,
source,
getAdditionalRule = noop
) {
if (!rulesConfig) {
return;
}
Object.keys(rulesConfig).forEach(id => {
const rule = getAdditionalRule(id) || this.builtInRules.get(id) || null;
this.validateRuleOptions(rule, id, rulesConfig[id], source);
});
}
/**
* Validates a `globals` section of a config file
* @param {Object} globalsConfig The `globals` section
* @param {string|null} source The name of the configuration source to report in the event of an error.
* @returns {void}
*/
validateGlobals(globalsConfig, source = null) {
if (!globalsConfig) {
return;
}
Object.entries(globalsConfig)
.forEach(([configuredGlobal, configuredValue]) => {
try {
ConfigOps.normalizeConfigGlobal(configuredValue);
} catch (err) {
throw new Error(`ESLint configuration of global '${configuredGlobal}' in ${source} is invalid:\n${err.message}`);
}
});
}
/**
* Validate `processor` configuration.
* @param {string|undefined} processorName The processor name.
* @param {string} source The name of config file.
* @param {function(id:string): Processor} getProcessor The getter of defined processors.
* @returns {void}
*/
validateProcessor(processorName, source, getProcessor) {
if (processorName && !getProcessor(processorName)) {
throw new Error(`ESLint configuration of processor in '${source}' is invalid: '${processorName}' was not found.`);
}
}
/**
* Formats an array of schema validation errors.
* @param {Array} errors An array of error messages to format.
* @returns {string} Formatted error message
*/
formatErrors(errors) {
return errors.map(error => {
if (error.keyword === "additionalProperties") {
const formattedPropertyPath = error.dataPath.length ? `${error.dataPath.slice(1)}.${error.params.additionalProperty}` : error.params.additionalProperty;
return `Unexpected top-level property "${formattedPropertyPath}"`;
}
if (error.keyword === "type") {
const formattedField = error.dataPath.slice(1);
const formattedExpectedType = Array.isArray(error.schema) ? error.schema.join("/") : error.schema;
const formattedValue = JSON.stringify(error.data);
return `Property "${formattedField}" is the wrong type (expected ${formattedExpectedType} but got \`${formattedValue}\`)`;
}
const field = error.dataPath[0] === "." ? error.dataPath.slice(1) : error.dataPath;
return `"${field}" ${error.message}. Value: ${JSON.stringify(error.data)}`;
}).map(message => `\t- ${message}.\n`).join("");
}
/**
* Validates the top level properties of the config object.
* @param {Object} config The config object to validate.
* @param {string} source The name of the configuration source to report in any errors.
* @returns {void}
*/
validateConfigSchema(config, source = null) {
validateSchema = validateSchema || ajv.compile(configSchema);
if (!validateSchema(config)) {
throw new Error(`ESLint configuration in ${source} is invalid:\n${this.formatErrors(validateSchema.errors)}`);
}
if (Object.hasOwnProperty.call(config, "ecmaFeatures")) {
emitDeprecationWarning(source, "ESLINT_LEGACY_ECMAFEATURES");
}
}
/**
* Validates an entire config object.
* @param {Object} config The config object to validate.
* @param {string} source The name of the configuration source to report in any errors.
* @param {function(ruleId:string): Object} [getAdditionalRule] A map from strings to loaded rules.
* @param {function(envId:string): Object} [getAdditionalEnv] A map from strings to loaded envs.
* @returns {void}
*/
validate(config, source, getAdditionalRule, getAdditionalEnv) {
this.validateConfigSchema(config, source);
this.validateRules(config.rules, source, getAdditionalRule);
this.validateEnvironment(config.env, source, getAdditionalEnv);
this.validateGlobals(config.globals, source);
for (const override of config.overrides || []) {
this.validateRules(override.rules, source, getAdditionalRule);
this.validateEnvironment(override.env, source, getAdditionalEnv);
this.validateGlobals(config.globals, source);
}
}
/**
* Validate config array object.
* @param {ConfigArray} configArray The config array to validate.
* @returns {void}
*/
validateConfigArray(configArray) {
const getPluginEnv = Map.prototype.get.bind(configArray.pluginEnvironments);
const getPluginProcessor = Map.prototype.get.bind(configArray.pluginProcessors);
const getPluginRule = Map.prototype.get.bind(configArray.pluginRules);
// Validate.
for (const element of configArray) {
if (validated.has(element)) {
continue;
}
validated.add(element);
this.validateEnvironment(element.env, element.name, getPluginEnv);
this.validateGlobals(element.globals, element.name);
this.validateProcessor(element.processor, element.name, getPluginProcessor);
this.validateRules(element.rules, element.name, getPluginRule);
}
}
}

View File

@ -0,0 +1,63 @@
/**
* @fileoverview Provide the function that emits deprecation warnings.
* @author Toru Nagashima <http://github.com/mysticatea>
*/
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
import path from "path";
//------------------------------------------------------------------------------
// Private
//------------------------------------------------------------------------------
// Defitions for deprecation warnings.
const deprecationWarningMessages = {
ESLINT_LEGACY_ECMAFEATURES:
"The 'ecmaFeatures' config file property is deprecated and has no effect.",
ESLINT_PERSONAL_CONFIG_LOAD:
"'~/.eslintrc.*' config files have been deprecated. " +
"Please use a config file per project or the '--config' option.",
ESLINT_PERSONAL_CONFIG_SUPPRESS:
"'~/.eslintrc.*' config files have been deprecated. " +
"Please remove it or add 'root:true' to the config files in your " +
"projects in order to avoid loading '~/.eslintrc.*' accidentally."
};
const sourceFileErrorCache = new Set();
/**
* Emits a deprecation warning containing a given filepath. A new deprecation warning is emitted
* for each unique file path, but repeated invocations with the same file path have no effect.
* No warnings are emitted if the `--no-deprecation` or `--no-warnings` Node runtime flags are active.
* @param {string} source The name of the configuration source to report the warning for.
* @param {string} errorCode The warning message to show.
* @returns {void}
*/
function emitDeprecationWarning(source, errorCode) {
const cacheKey = JSON.stringify({ source, errorCode });
if (sourceFileErrorCache.has(cacheKey)) {
return;
}
sourceFileErrorCache.add(cacheKey);
const rel = path.relative(process.cwd(), source);
const message = deprecationWarningMessages[errorCode];
process.emitWarning(
`${message} (found in "${rel}")`,
"DeprecationWarning",
errorCode
);
}
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
export {
emitDeprecationWarning
};

View File

@ -0,0 +1,96 @@
/**
* @fileoverview Common helpers for naming of plugins, formatters and configs
*/
const NAMESPACE_REGEX = /^@.*\//iu;
/**
* Brings package name to correct format based on prefix
* @param {string} name The name of the package.
* @param {string} prefix Can be either "eslint-plugin", "eslint-config" or "eslint-formatter"
* @returns {string} Normalized name of the package
* @private
*/
function normalizePackageName(name, prefix) {
let normalizedName = name;
/**
* On Windows, name can come in with Windows slashes instead of Unix slashes.
* Normalize to Unix first to avoid errors later on.
* https://github.com/eslint/eslint/issues/5644
*/
if (normalizedName.includes("\\")) {
normalizedName = normalizedName.replace(/\\/gu, "/");
}
if (normalizedName.charAt(0) === "@") {
/**
* it's a scoped package
* package name is the prefix, or just a username
*/
const scopedPackageShortcutRegex = new RegExp(`^(@[^/]+)(?:/(?:${prefix})?)?$`, "u"),
scopedPackageNameRegex = new RegExp(`^${prefix}(-|$)`, "u");
if (scopedPackageShortcutRegex.test(normalizedName)) {
normalizedName = normalizedName.replace(scopedPackageShortcutRegex, `$1/${prefix}`);
} else if (!scopedPackageNameRegex.test(normalizedName.split("/")[1])) {
/**
* for scoped packages, insert the prefix after the first / unless
* the path is already @scope/eslint or @scope/eslint-xxx-yyy
*/
normalizedName = normalizedName.replace(/^@([^/]+)\/(.*)$/u, `@$1/${prefix}-$2`);
}
} else if (!normalizedName.startsWith(`${prefix}-`)) {
normalizedName = `${prefix}-${normalizedName}`;
}
return normalizedName;
}
/**
* Removes the prefix from a fullname.
* @param {string} fullname The term which may have the prefix.
* @param {string} prefix The prefix to remove.
* @returns {string} The term without prefix.
*/
function getShorthandName(fullname, prefix) {
if (fullname[0] === "@") {
let matchResult = new RegExp(`^(@[^/]+)/${prefix}$`, "u").exec(fullname);
if (matchResult) {
return matchResult[1];
}
matchResult = new RegExp(`^(@[^/]+)/${prefix}-(.+)$`, "u").exec(fullname);
if (matchResult) {
return `${matchResult[1]}/${matchResult[2]}`;
}
} else if (fullname.startsWith(`${prefix}-`)) {
return fullname.slice(prefix.length + 1);
}
return fullname;
}
/**
* Gets the scope (namespace) of a term.
* @param {string} term The term which may have the namespace.
* @returns {string} The namespace of the term if it has one.
*/
function getNamespaceFromTerm(term) {
const match = term.match(NAMESPACE_REGEX);
return match ? match[0] : "";
}
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
export {
normalizePackageName,
getShorthandName,
getNamespaceFromTerm
};

View File

@ -0,0 +1,42 @@
/**
* Utility for resolving a module relative to another module
* @author Teddy Katz
*/
import Module from "module";
/*
* `Module.createRequire` is added in v12.2.0. It supports URL as well.
* We only support the case where the argument is a filepath, not a URL.
*/
const createRequire = Module.createRequire;
/**
* Resolves a Node module relative to another module
* @param {string} moduleName The name of a Node module, or a path to a Node module.
* @param {string} relativeToPath An absolute path indicating the module that `moduleName` should be resolved relative to. This must be
* a file rather than a directory, but the file need not actually exist.
* @returns {string} The absolute path that would result from calling `require.resolve(moduleName)` in a file located at `relativeToPath`
*/
function resolve(moduleName, relativeToPath) {
try {
return createRequire(relativeToPath).resolve(moduleName);
} catch (error) {
// This `if` block is for older Node.js than 12.0.0. We can remove this block in the future.
if (
typeof error === "object" &&
error !== null &&
error.code === "MODULE_NOT_FOUND" &&
!error.requireStack &&
error.message.includes(moduleName)
) {
error.message += `\nRequire stack:\n- ${relativeToPath}`;
}
throw error;
}
}
export {
resolve
};

View File

@ -0,0 +1,149 @@
/**
* @fileoverview Define common types for input completion.
* @author Toru Nagashima <https://github.com/mysticatea>
*/
/** @type {any} */
export default {};
/** @typedef {boolean | "off" | "readable" | "readonly" | "writable" | "writeable"} GlobalConf */
/** @typedef {0 | 1 | 2 | "off" | "warn" | "error"} SeverityConf */
/** @typedef {SeverityConf | [SeverityConf, ...any[]]} RuleConf */
/**
* @typedef {Object} EcmaFeatures
* @property {boolean} [globalReturn] Enabling `return` statements at the top-level.
* @property {boolean} [jsx] Enabling JSX syntax.
* @property {boolean} [impliedStrict] Enabling strict mode always.
*/
/**
* @typedef {Object} ParserOptions
* @property {EcmaFeatures} [ecmaFeatures] The optional features.
* @property {3|5|6|7|8|9|10|11|12|2015|2016|2017|2018|2019|2020|2021} [ecmaVersion] The ECMAScript version (or revision number).
* @property {"script"|"module"} [sourceType] The source code type.
*/
/**
* @typedef {Object} ConfigData
* @property {Record<string, boolean>} [env] The environment settings.
* @property {string | string[]} [extends] The path to other config files or the package name of shareable configs.
* @property {Record<string, GlobalConf>} [globals] The global variable settings.
* @property {string | string[]} [ignorePatterns] The glob patterns that ignore to lint.
* @property {boolean} [noInlineConfig] The flag that disables directive comments.
* @property {OverrideConfigData[]} [overrides] The override settings per kind of files.
* @property {string} [parser] The path to a parser or the package name of a parser.
* @property {ParserOptions} [parserOptions] The parser options.
* @property {string[]} [plugins] The plugin specifiers.
* @property {string} [processor] The processor specifier.
* @property {boolean} [reportUnusedDisableDirectives] The flag to report unused `eslint-disable` comments.
* @property {boolean} [root] The root flag.
* @property {Record<string, RuleConf>} [rules] The rule settings.
* @property {Object} [settings] The shared settings.
*/
/**
* @typedef {Object} OverrideConfigData
* @property {Record<string, boolean>} [env] The environment settings.
* @property {string | string[]} [excludedFiles] The glob pattarns for excluded files.
* @property {string | string[]} [extends] The path to other config files or the package name of shareable configs.
* @property {string | string[]} files The glob patterns for target files.
* @property {Record<string, GlobalConf>} [globals] The global variable settings.
* @property {boolean} [noInlineConfig] The flag that disables directive comments.
* @property {OverrideConfigData[]} [overrides] The override settings per kind of files.
* @property {string} [parser] The path to a parser or the package name of a parser.
* @property {ParserOptions} [parserOptions] The parser options.
* @property {string[]} [plugins] The plugin specifiers.
* @property {string} [processor] The processor specifier.
* @property {boolean} [reportUnusedDisableDirectives] The flag to report unused `eslint-disable` comments.
* @property {Record<string, RuleConf>} [rules] The rule settings.
* @property {Object} [settings] The shared settings.
*/
/**
* @typedef {Object} ParseResult
* @property {Object} ast The AST.
* @property {ScopeManager} [scopeManager] The scope manager of the AST.
* @property {Record<string, any>} [services] The services that the parser provides.
* @property {Record<string, string[]>} [visitorKeys] The visitor keys of the AST.
*/
/**
* @typedef {Object} Parser
* @property {(text:string, options:ParserOptions) => Object} parse The definition of global variables.
* @property {(text:string, options:ParserOptions) => ParseResult} [parseForESLint] The parser options that will be enabled under this environment.
*/
/**
* @typedef {Object} Environment
* @property {Record<string, GlobalConf>} [globals] The definition of global variables.
* @property {ParserOptions} [parserOptions] The parser options that will be enabled under this environment.
*/
/**
* @typedef {Object} LintMessage
* @property {number} column The 1-based column number.
* @property {number} [endColumn] The 1-based column number of the end location.
* @property {number} [endLine] The 1-based line number of the end location.
* @property {boolean} fatal If `true` then this is a fatal error.
* @property {{range:[number,number], text:string}} [fix] Information for autofix.
* @property {number} line The 1-based line number.
* @property {string} message The error message.
* @property {string|null} ruleId The ID of the rule which makes this message.
* @property {0|1|2} severity The severity of this message.
* @property {Array<{desc?: string, messageId?: string, fix: {range: [number, number], text: string}}>} [suggestions] Information for suggestions.
*/
/**
* @typedef {Object} SuggestionResult
* @property {string} desc A short description.
* @property {string} [messageId] Id referencing a message for the description.
* @property {{ text: string, range: number[] }} fix fix result info
*/
/**
* @typedef {Object} Processor
* @property {(text:string, filename:string) => Array<string | { text:string, filename:string }>} [preprocess] The function to extract code blocks.
* @property {(messagesList:LintMessage[][], filename:string) => LintMessage[]} [postprocess] The function to merge messages.
* @property {boolean} [supportsAutofix] If `true` then it means the processor supports autofix.
*/
/**
* @typedef {Object} RuleMetaDocs
* @property {string} category The category of the rule.
* @property {string} description The description of the rule.
* @property {boolean} recommended If `true` then the rule is included in `eslint:recommended` preset.
* @property {string} url The URL of the rule documentation.
*/
/**
* @typedef {Object} RuleMeta
* @property {boolean} [deprecated] If `true` then the rule has been deprecated.
* @property {RuleMetaDocs} docs The document information of the rule.
* @property {"code"|"whitespace"} [fixable] The autofix type.
* @property {Record<string,string>} [messages] The messages the rule reports.
* @property {string[]} [replacedBy] The IDs of the alternative rules.
* @property {Array|Object} schema The option schema of the rule.
* @property {"problem"|"suggestion"|"layout"} type The rule type.
*/
/**
* @typedef {Object} Rule
* @property {Function} create The factory of the rule.
* @property {RuleMeta} meta The meta data of the rule.
*/
/**
* @typedef {Object} Plugin
* @property {Record<string, ConfigData>} [configs] The definition of plugin configs.
* @property {Record<string, Environment>} [environments] The definition of plugin environments.
* @property {Record<string, Processor>} [processors] The definition of plugin processors.
* @property {Record<string, Function | Rule>} [rules] The definition of plugin rules.
*/
/**
* Information of deprecated rules.
* @typedef {Object} DeprecatedRuleInfo
* @property {string} ruleId The rule ID.
* @property {string[]} replacedBy The rule IDs that replace this deprecated rule.
*/

View File

@ -0,0 +1,17 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -z "$NODE_PATH" ]; then
export NODE_PATH="/home/lilian/Dev/project/fastapi_gen/frontend/node_modules/.pnpm/node_modules"
else
export NODE_PATH="$NODE_PATH:/home/lilian/Dev/project/fastapi_gen/frontend/node_modules/.pnpm/node_modules"
fi
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../../../../../../js-yaml@4.1.0/node_modules/js-yaml/bin/js-yaml.js" "$@"
else
exec node "$basedir/../../../../../../js-yaml@4.1.0/node_modules/js-yaml/bin/js-yaml.js" "$@"
fi

View File

@ -0,0 +1,82 @@
{
"name": "@eslint/eslintrc",
"version": "1.4.0",
"description": "The legacy ESLintRC config file format for ESLint",
"type": "module",
"main": "./dist/eslintrc.cjs",
"exports": {
".": {
"import": "./lib/index.js",
"require": "./dist/eslintrc.cjs"
},
"./package.json": "./package.json",
"./universal": {
"import": "./lib/index-universal.js",
"require": "./dist/eslintrc-universal.cjs"
}
},
"files": [
"lib",
"conf",
"LICENSE",
"dist",
"universal.js"
],
"publishConfig": {
"access": "public"
},
"scripts": {
"prepare": "npm run build",
"build": "rollup -c",
"lint": "eslint . --report-unused-disable-directives",
"fix": "npm run lint -- --fix",
"test": "mocha -R progress -c 'tests/lib/*.cjs' && c8 mocha -R progress -c 'tests/lib/**/*.js'",
"generate-release": "eslint-generate-release",
"generate-alpharelease": "eslint-generate-prerelease alpha",
"generate-betarelease": "eslint-generate-prerelease beta",
"generate-rcrelease": "eslint-generate-prerelease rc",
"publish-release": "eslint-publish-release"
},
"repository": "eslint/eslintrc",
"funding": "https://opencollective.com/eslint",
"keywords": [
"ESLint",
"ESLintRC",
"Configuration"
],
"author": "Nicholas C. Zakas",
"license": "MIT",
"bugs": {
"url": "https://github.com/eslint/eslintrc/issues"
},
"homepage": "https://github.com/eslint/eslintrc#readme",
"devDependencies": {
"c8": "^7.7.3",
"chai": "^4.3.4",
"eslint": "^7.31.0",
"eslint-config-eslint": "^7.0.0",
"eslint-plugin-jsdoc": "^35.4.1",
"eslint-plugin-node": "^11.1.0",
"eslint-release": "^3.2.0",
"fs-teardown": "^0.1.3",
"mocha": "^9.0.3",
"rollup": "^2.70.1",
"shelljs": "^0.8.4",
"sinon": "^11.1.2",
"temp-dir": "^2.0.0"
},
"dependencies": {
"ajv": "^6.12.4",
"debug": "^4.3.2",
"espree": "^9.4.0",
"globals": "^13.19.0",
"ignore": "^5.2.0",
"import-fresh": "^3.2.1",
"js-yaml": "^4.1.0",
"minimatch": "^3.1.2",
"strip-json-comments": "^3.1.1"
},
"engines": {
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
}
}

View File

@ -0,0 +1,9 @@
// Jest (and probably some other runtimes with custom implementations of
// `require`) doesn't support `exports` in `package.json`, so this file is here
// to help them load this module. Note that it is also `.js` and not `.cjs` for
// the same reason - `cjs` files requires to be loaded with an extension, but
// since Jest doesn't respect `module` outside of ESM mode it still works in
// this case (and the `require` in _this_ file does specify the extension).
// eslint-disable-next-line no-undef
module.exports = require("./dist/eslintrc-universal.cjs");

View File

@ -0,0 +1 @@
../../ajv@6.12.6/node_modules/ajv

View File

@ -0,0 +1 @@
../../debug@4.3.4/node_modules/debug

View File

@ -0,0 +1 @@
../../espree@9.4.1/node_modules/espree

View File

@ -0,0 +1 @@
../../globals@13.19.0/node_modules/globals

View File

@ -0,0 +1 @@
../../ignore@5.2.4/node_modules/ignore

View File

@ -0,0 +1 @@
../../import-fresh@3.3.0/node_modules/import-fresh

View File

@ -0,0 +1 @@
../../js-yaml@4.1.0/node_modules/js-yaml

View File

@ -0,0 +1 @@
../../minimatch@3.1.2/node_modules/minimatch

View File

@ -0,0 +1 @@
../../strip-json-comments@3.1.1/node_modules/strip-json-comments

View File

@ -0,0 +1,10 @@
The MIT License (MIT)
Copyright © 2020-2022 Michael Garvin
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,65 @@
# @gar/promisify
### Promisify an entire object or class instance
This module leverages es6 Proxy and Reflect to promisify every function in an
object or class instance.
It assumes the callback that the function is expecting is the last
parameter, and that it is an error-first callback with only one value,
i.e. `(err, value) => ...`. This mirrors node's `util.promisify` method.
In order that you can use it as a one-stop-shop for all your promisify
needs, you can also pass it a function. That function will be
promisified as normal using node's built-in `util.promisify` method.
[node's custom promisified
functions](https://nodejs.org/api/util.html#util_custom_promisified_functions)
will also be mirrored, further allowing this to be a drop-in replacement
for the built-in `util.promisify`.
### Examples
Promisify an entire object
```javascript
const promisify = require('@gar/promisify')
class Foo {
constructor (attr) {
this.attr = attr
}
double (input, cb) {
cb(null, input * 2)
}
const foo = new Foo('baz')
const promisified = promisify(foo)
console.log(promisified.attr)
console.log(await promisified.double(1024))
```
Promisify a function
```javascript
const promisify = require('@gar/promisify')
function foo (a, cb) {
if (a !== 'bad') {
return cb(null, 'ok')
}
return cb('not ok')
}
const promisified = promisify(foo)
// This will resolve to 'ok'
promisified('good')
// this will reject
promisified('bad')
```

Some files were not shown because too many files have changed in this diff Show More