diff --git a/client/coverage_report.txt b/client/coverage_report.txt new file mode 100644 index 00000000..10783a38 --- /dev/null +++ b/client/coverage_report.txt @@ -0,0 +1,749 @@ +8:35:56 AM [vite] warning: `optimizeDeps.esbuildOptions` option was specified by "vite:react-swc" plugin. This option is deprecated, please use `optimizeDeps.rolldownOptions` instead. +`esbuild` option is set to false, but `oxc` option was not set to false. `esbuild: false` does not have effect any more. If you want to disable the default transformation, which is now handled by Oxc, please set `oxc: false` instead. + + RUN  v4.1.2 /home/idealz/Drips-Projects/tokenbound_impl/client + Coverage enabled with v8 + +Browserslist: caniuse-lite is outdated. Please run: + npx update-browserslist-db@latest + Why you should do it regularly: https://github.com/browserslist/update-db#readme +stdout | src/__tests__/CoverageBooster.test.jsx > Coverage Booster Tests > triggers EventDetails interactive functions as organizer +{ + theme: 291n, + event_type: 1110n, + status: 1n, + start_date: 123456n, + end_date: 234567n, + ticket_price: 10000000000000000000n, + total_tickets: 100n, + tickets_sold: 20n, + is_canceled: false, + organizer: 291n, + event_ticket_addr: 1929n +} +1 +TokenboundClient { + transferERC20: [Function: Mock] { + _isMockFunction: true, + getMockImplementation: [Function (anonymous)], + mock: { + calls: [], + contexts: [], + instances: [], + invocationCallOrder: [], + settledResults: [], + results: [], + lastCall: [Getter] + }, + mockImplementation: [Function: mockImplementation], + mockImplementationOnce: [Function: mockImplementationOnce], + withImplementation: [Function: withImplementation], + mockReturnThis: [Function: mockReturnThis], + mockReturnValue: [Function: mockReturnValue], + mockReturnValueOnce: [Function: mockReturnValueOnce], + mockThrow: [Function: mockThrow], + mockThrowOnce: [Function: mockThrowOnce], + mockResolvedValue: [Function: mockResolvedValue], + mockResolvedValueOnce: [Function: mockResolvedValueOnce], + mockRejectedValue: [Function: mockRejectedValue], + mockRejectedValueOnce: [Function: mockRejectedValueOnce], + mockClear: [Function: mockClear], + mockReset: [Function: mockReset], + mockRestore: [Function: mockRestore], + mockName: [Function: mockName], + getMockName: [Function: getMockName], + [Symbol(nodejs.dispose)]: [Function (anonymous)] + }, + checkAccountDeployment: [Function: Mock] { + _isMockFunction: true, + getMockImplementation: [Function (anonymous)], + mock: { + calls: [], + contexts: [], + instances: [], + invocationCallOrder: [], + settledResults: [], + results: [], + lastCall: [Getter] + }, + mockImplementation: [Function: mockImplementation], + mockImplementationOnce: [Function: mockImplementationOnce], + withImplementation: [Function: withImplementation], + mockReturnThis: [Function: mockReturnThis], + mockReturnValue: [Function: mockReturnValue], + mockReturnValueOnce: [Function: mockReturnValueOnce], + mockThrow: [Function: mockThrow], + mockThrowOnce: [Function: mockThrowOnce], + mockResolvedValue: [Function: mockResolvedValue], + mockResolvedValueOnce: [Function: mockResolvedValueOnce], + mockRejectedValue: [Function: mockRejectedValue], + mockRejectedValueOnce: [Function: mockRejectedValueOnce], + mockClear: [Function: mockClear], + mockReset: [Function: mockReset], + mockRestore: [Function: mockRestore], + mockName: [Function: mockName], + getMockName: [Function: getMockName], + [Symbol(nodejs.dispose)]: [Function (anonymous)] + }, + createAccount: [Function: Mock] { + _isMockFunction: true, + getMockImplementation: [Function (anonymous)], + mock: { + calls: [], + contexts: [], + instances: [], + invocationCallOrder: [], + settledResults: [], + results: [], + lastCall: [Getter] + }, + mockImplementation: [Function: mockImplementation], + mockImplementationOnce: [Function: mockImplementationOnce], + withImplementation: [Function: withImplementation], + mockReturnThis: [Function: mockReturnThis], + mockReturnValue: [Function: mockReturnValue], + mockReturnValueOnce: [Function: mockReturnValueOnce], + mockThrow: [Function: mockThrow], + mockThrowOnce: [Function: mockThrowOnce], + mockResolvedValue: [Function: mockResolvedValue], + mockResolvedValueOnce: [Function: mockResolvedValueOnce], + mockRejectedValue: [Function: mockRejectedValue], + mockRejectedValueOnce: [Function: mockRejectedValueOnce], + mockClear: [Function: mockClear], + mockReset: [Function: mockReset], + mockRestore: [Function: mockRestore], + mockName: [Function: mockName], + getMockName: [Function: getMockName], + [Symbol(nodejs.dispose)]: [Function (anonymous)] + }, + getAccount: [Function: Mock] { + _isMockFunction: true, + getMockImplementation: [Function (anonymous)], + mock: { + calls: [], + contexts: [], + instances: [], + invocationCallOrder: [], + settledResults: [], + results: [], + lastCall: [Getter] + }, + mockImplementation: [Function: mockImplementation], + mockImplementationOnce: [Function: mockImplementationOnce], + withImplementation: [Function: withImplementation], + mockReturnThis: [Function: mockReturnThis], + mockReturnValue: [Function: mockReturnValue], + mockReturnValueOnce: [Function: mockReturnValueOnce], + mockThrow: [Function: mockThrow], + mockThrowOnce: [Function: mockThrowOnce], + mockResolvedValue: [Function: mockResolvedValue], + mockResolvedValueOnce: [Function: mockResolvedValueOnce], + mockRejectedValue: [Function: mockRejectedValue], + mockRejectedValueOnce: [Function: mockRejectedValueOnce], + mockClear: [Function: mockClear], + mockReset: [Function: mockReset], + mockRestore: [Function: mockRestore], + mockName: [Function: mockName], + getMockName: [Function: getMockName], + [Symbol(nodejs.dispose)]: [Function (anonymous)] + } +} + +100n + +stdout | src/__tests__/CoverageBooster.test.jsx > Coverage Booster Tests > triggers EventDetails interactive functions as organizer +true + +stdout | src/__tests__/CoverageBooster.test.jsx > Coverage Booster Tests > renders EventDetails as regular user and triggers purchase +{ + theme: 291n, + event_type: 1110n, + status: 1n, + start_date: 123456n, + end_date: 234567n, + ticket_price: 10000000000000000000n, + total_tickets: 100n, + tickets_sold: 20n, + is_canceled: false, + organizer: 291n, + event_ticket_addr: 1929n +} +1 +TokenboundClient { + transferERC20: [Function: Mock] { + _isMockFunction: true, + getMockImplementation: [Function (anonymous)], + mock: { + calls: [], + contexts: [], + instances: [], + invocationCallOrder: [], + settledResults: [], + results: [], + lastCall: [Getter] + }, + mockImplementation: [Function: mockImplementation], + mockImplementationOnce: [Function: mockImplementationOnce], + withImplementation: [Function: withImplementation], + mockReturnThis: [Function: mockReturnThis], + mockReturnValue: [Function: mockReturnValue], + mockReturnValueOnce: [Function: mockReturnValueOnce], + mockThrow: [Function: mockThrow], + mockThrowOnce: [Function: mockThrowOnce], + mockResolvedValue: [Function: mockResolvedValue], + mockResolvedValueOnce: [Function: mockResolvedValueOnce], + mockRejectedValue: [Function: mockRejectedValue], + mockRejectedValueOnce: [Function: mockRejectedValueOnce], + mockClear: [Function: mockClear], + mockReset: [Function: mockReset], + mockRestore: [Function: mockRestore], + mockName: [Function: mockName], + getMockName: [Function: getMockName], + [Symbol(nodejs.dispose)]: [Function (anonymous)] + }, + checkAccountDeployment: [Function: Mock] { + _isMockFunction: true, + getMockImplementation: [Function (anonymous)], + mock: { + calls: [], + contexts: [], + instances: [], + invocationCallOrder: [], + settledResults: [], + results: [], + lastCall: [Getter] + }, + mockImplementation: [Function: mockImplementation], + mockImplementationOnce: [Function: mockImplementationOnce], + withImplementation: [Function: withImplementation], + mockReturnThis: [Function: mockReturnThis], + mockReturnValue: [Function: mockReturnValue], + mockReturnValueOnce: [Function: mockReturnValueOnce], + mockThrow: [Function: mockThrow], + mockThrowOnce: [Function: mockThrowOnce], + mockResolvedValue: [Function: mockResolvedValue], + mockResolvedValueOnce: [Function: mockResolvedValueOnce], + mockRejectedValue: [Function: mockRejectedValue], + mockRejectedValueOnce: [Function: mockRejectedValueOnce], + mockClear: [Function: mockClear], + mockReset: [Function: mockReset], + mockRestore: [Function: mockRestore], + mockName: [Function: mockName], + getMockName: [Function: getMockName], + [Symbol(nodejs.dispose)]: [Function (anonymous)] + }, + createAccount: [Function: Mock] { + _isMockFunction: true, + getMockImplementation: [Function (anonymous)], + mock: { + calls: [], + contexts: [], + instances: [], + invocationCallOrder: [], + settledResults: [], + results: [], + lastCall: [Getter] + }, + mockImplementation: [Function: mockImplementation], + mockImplementationOnce: [Function: mockImplementationOnce], + withImplementation: [Function: withImplementation], + mockReturnThis: [Function: mockReturnThis], + mockReturnValue: [Function: mockReturnValue], + mockReturnValueOnce: [Function: mockReturnValueOnce], + mockThrow: [Function: mockThrow], + mockThrowOnce: [Function: mockThrowOnce], + mockResolvedValue: [Function: mockResolvedValue], + mockResolvedValueOnce: [Function: mockResolvedValueOnce], + mockRejectedValue: [Function: mockRejectedValue], + mockRejectedValueOnce: [Function: mockRejectedValueOnce], + mockClear: [Function: mockClear], + mockReset: [Function: mockReset], + mockRestore: [Function: mockRestore], + mockName: [Function: mockName], + getMockName: [Function: getMockName], + [Symbol(nodejs.dispose)]: [Function (anonymous)] + }, + getAccount: [Function: Mock] { + _isMockFunction: true, + getMockImplementation: [Function (anonymous)], + mock: { + calls: [], + contexts: [], + instances: [], + invocationCallOrder: [], + settledResults: [], + results: [], + lastCall: [Getter] + }, + mockImplementation: [Function: mockImplementation], + mockImplementationOnce: [Function: mockImplementationOnce], + withImplementation: [Function: withImplementation], + mockReturnThis: [Function: mockReturnThis], + mockReturnValue: [Function: mockReturnValue], + mockReturnValueOnce: [Function: mockReturnValueOnce], + mockThrow: [Function: mockThrow], + mockThrowOnce: [Function: mockThrowOnce], + mockResolvedValue: [Function: mockResolvedValue], + mockResolvedValueOnce: [Function: mockResolvedValueOnce], + mockRejectedValue: [Function: mockRejectedValue], + mockRejectedValueOnce: [Function: mockRejectedValueOnce], + mockClear: [Function: mockClear], + mockReset: [Function: mockReset], + mockRestore: [Function: mockRestore], + mockName: [Function: mockName], + getMockName: [Function: getMockName], + [Symbol(nodejs.dispose)]: [Function (anonymous)] + } +} + +100n + +stdout | src/__tests__/CoverageBooster.test.jsx > Coverage Booster Tests > renders EventDetails as regular user and triggers purchase +true + + ✓ src/__tests__/DashboardExpanded.test.jsx (4 tests) 2021ms + ✓ renders TransferDialog and handles input changes  1363ms + ✓ renders Shared Dialog correctly  331ms +Error: [vitest] No "alchemyProvider" export is defined on the "@starknet-react/core" mock. Did you forget to return it from "vi.mock"? +If you need to partially mock a module, you can use "importOriginal" helper inside: + + at VitestMocker.createError (file:///home/idealz/Drips-Projects/tokenbound_impl/client/node_modules/vitest/dist/chunks/startVitestModuleRunner.bRl2_oI_.js:62:17) + at Object.alchemyProvider [as get] (file:///home/idealz/Drips-Projects/tokenbound_impl/client/node_modules/vitest/dist/chunks/startVitestModuleRunner.bRl2_oI_.js:324:16) + at StarknetProvider (/home/idealz/Drips-Projects/tokenbound_impl/client/src/context/starknet-provider.jsx:29:20) + at renderWithHooks (/home/idealz/Drips-Projects/tokenbound_impl/client/node_modules/react-dom/cjs/react-dom.development.js:15486:18) + at mountIndeterminateComponent (/home/idealz/Drips-Projects/tokenbound_impl/client/node_modules/react-dom/cjs/react-dom.development.js:20103:13) + at beginWork (/home/idealz/Drips-Projects/tokenbound_impl/client/node_modules/react-dom/cjs/react-dom.development.js:21626:16) + at HTMLUnknownElement.callCallback (/home/idealz/Drips-Projects/tokenbound_impl/client/node_modules/react-dom/cjs/react-dom.development.js:4164:14) + at HTMLUnknownElement.callTheUserObjectsOperation (/home/idealz/Drips-Projects/tokenbound_impl/client/node_modules/jsdom/lib/generated/idl/EventListener.js:26:30) + at innerInvokeEventListeners (/home/idealz/Drips-Projects/tokenbound_impl/client/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:360:16) + at invokeEventListeners (/home/idealz/Drips-Projects/tokenbound_impl/client/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:296:3) +Error: [vitest] No "alchemyProvider" export is defined on the "@starknet-react/core" mock. Did you forget to return it from "vi.mock"? +If you need to partially mock a module, you can use "importOriginal" helper inside: + + at VitestMocker.createError (file:///home/idealz/Drips-Projects/tokenbound_impl/client/node_modules/vitest/dist/chunks/startVitestModuleRunner.bRl2_oI_.js:62:17) + at Object.alchemyProvider [as get] (file:///home/idealz/Drips-Projects/tokenbound_impl/client/node_modules/vitest/dist/chunks/startVitestModuleRunner.bRl2_oI_.js:324:16) + at StarknetProvider (/home/idealz/Drips-Projects/tokenbound_impl/client/src/context/starknet-provider.jsx:29:20) + at renderWithHooks (/home/idealz/Drips-Projects/tokenbound_impl/client/node_modules/react-dom/cjs/react-dom.development.js:15486:18) + at mountIndeterminateComponent (/home/idealz/Drips-Projects/tokenbound_impl/client/node_modules/react-dom/cjs/react-dom.development.js:20103:13) + at beginWork (/home/idealz/Drips-Projects/tokenbound_impl/client/node_modules/react-dom/cjs/react-dom.development.js:21626:16) + at HTMLUnknownElement.callCallback (/home/idealz/Drips-Projects/tokenbound_impl/client/node_modules/react-dom/cjs/react-dom.development.js:4164:14) + at HTMLUnknownElement.callTheUserObjectsOperation (/home/idealz/Drips-Projects/tokenbound_impl/client/node_modules/jsdom/lib/generated/idl/EventListener.js:26:30) + at innerInvokeEventListeners (/home/idealz/Drips-Projects/tokenbound_impl/client/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:360:16) + at invokeEventListeners (/home/idealz/Drips-Projects/tokenbound_impl/client/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:296:3) +stderr | src/__tests__/AppDisconnected.test.jsx > App Disconnected State > renders landing page when disconnected +The above error occurred in the component: + + at StarknetProvider (/home/idealz/Drips-Projects/tokenbound_impl/client/src/context/starknet-provider.jsx:11:29) + at App + at Router (/home/idealz/Drips-Projects/tokenbound_impl/client/node_modules/react-router/dist/umd/react-router.development.js:1163:17) + at BrowserRouter (/home/idealz/Drips-Projects/tokenbound_impl/client/node_modules/react-router-dom/dist/umd/react-router-dom.development.js:694:7) + +Consider adding an error boundary to your tree to customize error handling behavior. +Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries. + + ❯ src/__tests__/CoverageBooster.test.jsx (4 tests | 2 failed) 2295ms + × triggers EventDetails interactive functions as organizer 814ms + × renders EventDetails as regular user and triggers purchase 223ms + ✓ triggers Sidebar with long and short addresses 176ms + ✓ triggers TransferDialog success path  1070ms + ❯ src/__tests__/AppDisconnected.test.jsx (1 test | 1 failed) 202ms + × renders landing page when disconnected 187ms + ✓ src/__tests__/Footer.test.jsx (4 tests) 1566ms + ✓ renders logo and newsletter section  1287ms + ✓ src/__tests__/HowItWorksSection.test.jsx (2 tests) 2138ms + ✓ renders section title correctly  1785ms + ✓ displays titles when rendered  341ms + ✓ src/__tests__/CreateEvent.test.jsx (3 tests) 2001ms + ✓ renders the creation form correctly  332ms + ✓ submits form correctly  1382ms + ✓ src/__tests__/Shared.test.jsx (3 tests) 1057ms + ✓ renders correctly  793ms + ✓ src/__tests__/PartnersSection.test.jsx (3 tests) 1011ms + ✓ renders navigation buttons  793ms + ✓ src/__tests__/SharedExpanded.test.jsx (5 tests) 1364ms + ✓ renders closed state correctly with plus icon  971ms +stderr | src/__tests__/DashboardSubComponents.test.jsx > Dashboard Individual Components Tests > renders TicketCard correctly +Warning: Received `false` for a non-boolean attribute `prefetch`. + +If you want to write it to the DOM, pass a string instead: prefetch="false" or prefetch={value.toString()}. + +If you used to conditionally omit it with prefetch={condition && value}, pass prefetch={condition ? value : undefined} instead. + at a + at LinkWithRef (/home/idealz/Drips-Projects/tokenbound_impl/client/node_modules/react-router-dom/dist/umd/react-router-dom.development.js:810:9) + at div + at TicketCard (/home/idealz/Drips-Projects/tokenbound_impl/client/src/Components/dashboard/ticket-card.jsx:11:23) + at Router (/home/idealz/Drips-Projects/tokenbound_impl/client/node_modules/react-router/dist/umd/react-router.development.js:1163:17) + at BrowserRouter (/home/idealz/Drips-Projects/tokenbound_impl/client/node_modules/react-router-dom/dist/umd/react-router-dom.development.js:694:7) + + ✓ src/__tests__/Header.test.jsx (3 tests) 807ms + ✓ renders correctly with logo and links  741ms + ✓ src/__tests__/DashboardSubComponents.test.jsx (5 tests) 328ms +stdout | src/__tests__/DashboardPages.test.jsx > Dashboard Pages Rendering Tests > renders Dashboard page correctly +{} + +stdout | src/__tests__/DashboardPages.test.jsx > Dashboard Pages Rendering Tests > renders Events page correctly +{} +1 + +stdout | src/__tests__/DashboardPages.test.jsx > Dashboard Pages Rendering Tests > renders EventDetails page correctly +{ + theme: 291n, + event_type: 1110n, + status: 1n, + start_date: 123456n, + end_date: 234567n, + ticket_price: 10000000000000000000n, + total_tickets: 100n, + tickets_sold: 20n, + is_canceled: false, + organizer: 291n, + event_ticket_addr: 1929n +} +1 +C { + account: {}, + jsonRPC: 'https://starknet-sepolia.g.alchemy.com/starknet/version/rpc/v0_7/RCp5m7oq9i9myxsvC8ctUmNq2Wq2Pa_v', + registryAddress: '0x4101d3fa033024654083dd982273a300cb019b8cb96dd829267a4daf59f7b7e', + implementationAddress: '0x45d67b8590561c9b54e14dd309c9f38c4e2c554dd59414021f9d079811621bd', + isInitialized: false +} + +100n + + ✓ src/__tests__/DashboardPages.test.jsx (7 tests) 996ms + ✓ renders EventDetails page correctly  677ms + ✓ src/__tests__/AboutSection.test.jsx (3 tests) 440ms + ✓ renders with images and correctly titled card  382ms + ✓ src/__tests__/WalletContext.test.jsx (1 test) 200ms + ✓ src/__tests__/FeaturesSection.test.jsx (3 tests) 180ms +stdout | src/__tests__/Soroban.test.js > Soroban Library Mock > provides a functional sorobanContract mock for creating events +Creating event on Soroban with params: { + theme: 'Test Event', + type: 'meetup', + startTime: 123456, + endTime: 234567, + ticketPrice: 10, + total_ticket: 100 +} + +stdout | src/__tests__/Soroban.test.js > Soroban Library Mock > provides a functional sorobanContract mock for canceling events +Canceling event on Soroban: event_id_123 + + ✓ src/__tests__/Soroban.test.js (3 tests) 16ms + ✓ src/__tests__/AppLogic.test.jsx (1 test) 70ms + +⎯⎯⎯⎯⎯⎯⎯ Failed Tests 3 ⎯⎯⎯⎯⎯⎯⎯ + + FAIL  src/__tests__/AppDisconnected.test.jsx > App Disconnected State > renders landing page when disconnected +Error: [vitest] No "alchemyProvider" export is defined on the "@starknet-react/core" mock. Did you forget to return it from "vi.mock"? +If you need to partially mock a module, you can use "importOriginal" helper inside: + +vi.mock(import("@starknet-react/core"), async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + // your mocked methods + } +}) + + ❯ StarknetProvider src/context/starknet-provider.jsx:29:20 +  27| +  28| // const provider = jsonRpcProvider({ rpc: 'https://starknet-sepolia… +  29| const provider = alchemyProvider({ apiKey: 'RCp5m7oq9i9myxsvC8ctUmNq… +  | ^ +  30| +  31| return ( + ❯ renderWithHooks node_modules/react-dom/cjs/react-dom.development.js:15486:18 + ❯ mountIndeterminateComponent node_modules/react-dom/cjs/react-dom.development.js:20103:13 + ❯ beginWork node_modules/react-dom/cjs/react-dom.development.js:21626:16 + ❯ beginWork$1 node_modules/react-dom/cjs/react-dom.development.js:27465:14 + ❯ performUnitOfWork node_modules/react-dom/cjs/react-dom.development.js:26599:12 + ❯ workLoopSync node_modules/react-dom/cjs/react-dom.development.js:26505:5 + ❯ renderRootSync node_modules/react-dom/cjs/react-dom.development.js:26473:7 + +⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/3]⎯ + + FAIL  src/__tests__/CoverageBooster.test.jsx > Coverage Booster Tests > triggers EventDetails interactive functions as organizer +TestingLibraryElementError: Unable to find an element with the text: /Cancel Event/i. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible. + +Ignored nodes: comments, script, style + + 
 +  +  +  +  +  +  +  +  + 
 +  + isActive ? \"bg-primary\" : \"\"" + href="/dashboard" + > +  + 
 +  +  +  + 
 +  + Dashboard +  +  +  + isActive ? \"bg-primary\" : \"\"" + href="/events" + > +  + 
 +  +  +  + 
 +  + Events +  +  +  + isActive ? \"bg-primary\" : \"\"" + href="/tickets" + > +  + 
 +  +  +  + 
 +  + ... + ❯ Object.getElementError node_modules/@testing-library/dom/dist/config.js:37:19 + ❯ node_modules/@testing-library/dom/dist/query-helpers.js:76:38 + ❯ node_modules/@testing-library/dom/dist/query-helpers.js:52:17 + ❯ getByText node_modules/@testing-library/dom/dist/query-helpers.js:95:19 + ❯ src/__tests__/CoverageBooster.test.jsx:93:34 +  91| </KitContext.Provider> +  92| ); +  93| const cancelBtn = screen.getByText(/Cancel Event/i); +  | ^ +  94| fireEvent.click(cancelBtn); +  95| expect(mockContext.eventContract.cancel_event).toHaveBeenCalle… + +⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[2/3]⎯ + + FAIL  src/__tests__/CoverageBooster.test.jsx > Coverage Booster Tests > renders EventDetails as regular user and triggers purchase +TestingLibraryElementError: Unable to find an element with the text: /Get ticket/i. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible. + +Ignored nodes: comments, script, style + + 
 +  +  +  +  +  +  +  +  + 
 +  + isActive ? \"bg-primary\" : \"\"" + href="/dashboard" + > +  + 
 +  +  +  + 
 +  + Dashboard +  +  +  + isActive ? \"bg-primary\" : \"\"" + href="/events" + > +  + 
 +  +  +  + 
 +  + Events +  +  +  + isActive ? \"bg-primary\" : \"\"" + href="/tickets" + > +  + 
 +  +  +  + 
 +  + ... + ❯ Object.getElementError node_modules/@testing-library/dom/dist/config.js:37:19 + ❯ node_modules/@testing-library/dom/dist/query-helpers.js:76:38 + ❯ node_modules/@testing-library/dom/dist/query-helpers.js:52:17 + ❯ getByText node_modules/@testing-library/dom/dist/query-helpers.js:95:19 + ❯ src/__tests__/CoverageBooster.test.jsx:111:23 + 109| </KitContext.Provider> + 110| ); + 111| expect(screen.getByText(/Get ticket/i)).toBeInTheDocument(); +  | ^ + 112| fireEvent.click(screen.getByText(/Give app approval/i)); + 113| fireEvent.click(screen.getByText(/Get ticket/i)); + +⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[3/3]⎯ + + + Test Files  2 failed | 15 passed (17) + Tests  3 failed | 52 passed (55) + Start at  08:35:57 + Duration  97.21s (transform 14.02s, setup 20.46s, import 29.98s, tests 16.69s, environment 189.65s) + diff --git a/client/package-lock.json b/client/package-lock.json index e0074f98..dff9b7df 100644 --- a/client/package-lock.json +++ b/client/package-lock.json @@ -40,11 +40,12 @@ "web-vitals": "^4.0.0" }, "devDependencies": { - "@axe-core/cli": "^4.11.1", + "@testing-library/jest-dom": "^6.9.1", + "@testing-library/react": "^16.3.2", + "@testing-library/user-event": "^14.6.1", "@types/react": "^18.3.3", "@types/react-dom": "^18.3.0", "@vitejs/plugin-react-swc": "^3.5.0", - "@vitest/browser-playwright": "^4.1.2", "@vitest/coverage-v8": "^4.1.2", "autoprefixer": "^10.4.19", "eslint": "^8.57.0", @@ -53,8 +54,7 @@ "eslint-plugin-react": "^7.34.3", "eslint-plugin-react-hooks": "^4.6.2", "eslint-plugin-react-refresh": "^0.4.7", - "eslint-plugin-storybook": "^10.3.3", - "playwright": "^1.58.2", + "jsdom": "^29.0.1", "postcss": "^8.4.39", "prettier": "^3.8.1", "tailwindcss": "^3.4.6", @@ -98,64 +98,88 @@ "node": ">=6.0.0" } }, - "node_modules/@axe-core/cli": { - "version": "4.11.1", - "resolved": "https://registry.npmjs.org/@axe-core/cli/-/cli-4.11.1.tgz", - "integrity": "sha512-xC7doMReoy7QnQ18azdpIZHoYL1HcG5c5wvEcCpm5kWny520RGTRrBcnAZENaQ9nTQAkE7fXZFK4Z1cfBDTBFg==", + "node_modules/@asamuzakjp/css-color": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-5.1.1.tgz", + "integrity": "sha512-iGWN8E45Ws0XWx3D44Q1t6vX2LqhCKcwfmwBYCDsFrYFS6m4q/Ks61L2veETaLv+ckDC6+dTETJoaAAb7VjLiw==", "dev": true, - "license": "MPL-2.0", + "license": "MIT", "dependencies": { - "@axe-core/webdriverjs": "^4.11.1", - "axe-core": "~4.11.1", - "chromedriver": "latest", - "colors": "^1.4.0", - "commander": "^9.4.1", - "dotenv": "^17.2.2", - "selenium-webdriver": "~4.39.0" - }, - "bin": { - "axe": "dist/src/bin/cli.js" + "@csstools/css-calc": "^3.1.1", + "@csstools/css-color-parser": "^4.0.2", + "@csstools/css-parser-algorithms": "^4.0.0", + "@csstools/css-tokenizer": "^4.0.0", + "lru-cache": "^11.2.7" }, "engines": { - "node": ">=8" + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" } }, - "node_modules/@axe-core/cli/node_modules/commander": { - "version": "9.5.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-9.5.0.tgz", - "integrity": "sha512-KRs7WVDKg86PWiuAqhDrAQnTXZKraVcCc6vFdL14qrZ/DcWwuRo7VoiYXalXO7S5GKpqYiVEwCbgFDfxNHKJBQ==", + "node_modules/@asamuzakjp/css-color/node_modules/lru-cache": { + "version": "11.2.7", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.2.7.tgz", + "integrity": "sha512-aY/R+aEsRelme17KGQa/1ZSIpLpNYYrhcrepKTZgE+W3WM16YMCaPwOHLHsmopZHELU0Ojin1lPVxKR0MihncA==", "dev": true, - "license": "MIT", + "license": "BlueOak-1.0.0", "engines": { - "node": "^12.20.0 || >=14" + "node": "20 || >=22" } }, - "node_modules/@axe-core/cli/node_modules/dotenv": { - "version": "17.3.1", - "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.3.1.tgz", - "integrity": "sha512-IO8C/dzEb6O3F9/twg6ZLXz164a2fhTnEWb95H23Dm4OuN+92NmEAlTrupP9VW6Jm3sO26tQlqyvyi4CsnY9GA==", + "node_modules/@asamuzakjp/dom-selector": { + "version": "7.0.4", + "resolved": "https://registry.npmjs.org/@asamuzakjp/dom-selector/-/dom-selector-7.0.4.tgz", + "integrity": "sha512-jXR6x4AcT3eIrS2fSNAwJpwirOkGcd+E7F7CP3zjdTqz9B/2huHOL8YJZBgekKwLML+u7qB/6P1LXQuMScsx0w==", "dev": true, - "license": "BSD-2-Clause", - "engines": { - "node": ">=12" + "license": "MIT", + "dependencies": { + "@asamuzakjp/nwsapi": "^2.3.9", + "bidi-js": "^1.0.3", + "css-tree": "^3.2.1", + "is-potential-custom-element-name": "^1.0.1", + "lru-cache": "^11.2.7" }, - "funding": { - "url": "https://dotenvx.com" + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" } }, - "node_modules/@axe-core/webdriverjs": { - "version": "4.11.1", - "resolved": "https://registry.npmjs.org/@axe-core/webdriverjs/-/webdriverjs-4.11.1.tgz", - "integrity": "sha512-UVq7uBsqaQlHj7PQPg+WhE0nV6ccYtE0cnGglStS5RE3RAB+gQcb30R1k3usI+Q/xyROSJHhusOus4BzqrlZ1w==", + "node_modules/@asamuzakjp/dom-selector/node_modules/css-tree": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-3.2.1.tgz", + "integrity": "sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==", "dev": true, - "license": "MPL-2.0", + "license": "MIT", "dependencies": { - "axe-core": "~4.11.1" + "mdn-data": "2.27.1", + "source-map-js": "^1.2.1" }, - "peerDependencies": { - "selenium-webdriver": ">3.0.0-beta || >=2.53.1 || >4.0.0-alpha" + "engines": { + "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0" + } + }, + "node_modules/@asamuzakjp/dom-selector/node_modules/lru-cache": { + "version": "11.2.7", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.2.7.tgz", + "integrity": "sha512-aY/R+aEsRelme17KGQa/1ZSIpLpNYYrhcrepKTZgE+W3WM16YMCaPwOHLHsmopZHELU0Ojin1lPVxKR0MihncA==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" } }, + "node_modules/@asamuzakjp/dom-selector/node_modules/mdn-data": { + "version": "2.27.1", + "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.27.1.tgz", + "integrity": "sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==", + "dev": true, + "license": "CC0-1.0" + }, + "node_modules/@asamuzakjp/nwsapi": { + "version": "2.3.9", + "resolved": "https://registry.npmjs.org/@asamuzakjp/nwsapi/-/nwsapi-2.3.9.tgz", + "integrity": "sha512-n8GuYSrI9bF7FFZ/SjhwevlHc8xaVlb/7HmHelnc/PZXBD2ZR49NnN9sMMuDdEGPeeRQ5d0hqlSlEpgCX3Wl0Q==", + "dev": true, + "license": "MIT" + }, "node_modules/@babel/code-frame": { "version": "7.29.0", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.0.tgz", @@ -600,13 +624,13 @@ } }, "node_modules/@babel/helpers": { - "version": "7.29.2", - "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.2.tgz", - "integrity": "sha512-HoGuUs4sCZNezVEKdVcwqmZN8GoHirLUcLaYVNBK2J0DadGtdcqgr3BCbvH8+XUo4NGjNl3VOtSjEKNzqfFgKw==", + "version": "7.24.8", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.24.8.tgz", + "integrity": "sha512-gV2265Nkcz7weJJfvDoAEVzC1e2OTDpkGbEsebse8koXUJUXPsCMi7sRo/+SPMuMZ9MtUPnGwITTnQnU5YjyaQ==", "license": "MIT", "dependencies": { - "@babel/template": "^7.28.6", - "@babel/types": "^7.29.0" + "@babel/template": "^7.24.7", + "@babel/types": "^7.24.8" }, "engines": { "node": ">=6.9.0" @@ -2251,71 +2275,153 @@ "integrity": "sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==", "license": "MIT" }, - "node_modules/@blazediff/core": { - "version": "1.9.1", - "resolved": "https://registry.npmjs.org/@blazediff/core/-/core-1.9.1.tgz", - "integrity": "sha512-ehg3jIkYKulZh+8om/O25vkvSsXXwC+skXmyA87FFx6A/45eqOkZsBltMw/TVteb0mloiGT8oGRTcjRAz66zaA==", + "node_modules/@bramus/specificity": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/@bramus/specificity/-/specificity-2.4.2.tgz", + "integrity": "sha512-ctxtJ/eA+t+6q2++vj5j7FYX3nRu311q1wfYH3xjlLOsczhlhxAg2FWNUXhpGvAw3BWo1xBcvOV6/YLc2r5FJw==", "dev": true, - "license": "MIT" + "license": "MIT", + "dependencies": { + "css-tree": "^3.0.0" + }, + "bin": { + "specificity": "bin/cli.js" + } }, - "node_modules/@chromatic-com/storybook": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/@chromatic-com/storybook/-/storybook-5.1.1.tgz", - "integrity": "sha512-BPoAXHM71XgeCK2u0jKr9i8apeQMm/Z9IWGyndA2FMijfQG9m8ox45DdWh/pxFkK5ClhGgirv5QwMhFIeHmThg==", + "node_modules/@bramus/specificity/node_modules/css-tree": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-3.2.1.tgz", + "integrity": "sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==", "dev": true, "license": "MIT", "dependencies": { - "@neoconfetti/react": "^1.0.0", - "chromatic": "^13.3.4", - "filesize": "^10.0.12", - "jsonfile": "^6.1.0", - "strip-ansi": "^7.1.0" + "mdn-data": "2.27.1", + "source-map-js": "^1.2.1" }, "engines": { - "node": ">=20.0.0", - "yarn": ">=1.22.18" + "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0" + } + }, + "node_modules/@bramus/specificity/node_modules/mdn-data": { + "version": "2.27.1", + "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.27.1.tgz", + "integrity": "sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==", + "dev": true, + "license": "CC0-1.0" + }, + "node_modules/@csstools/color-helpers": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-6.0.2.tgz", + "integrity": "sha512-LMGQLS9EuADloEFkcTBR3BwV/CGHV7zyDxVRtVDTwdI2Ca4it0CCVTT9wCkxSgokjE5Ho41hEPgb8OEUwoXr6Q==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT-0", + "engines": { + "node": ">=20.19.0" + } + }, + "node_modules/@csstools/css-calc": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-3.1.1.tgz", + "integrity": "sha512-HJ26Z/vmsZQqs/o3a6bgKslXGFAungXGbinULZO3eMsOyNJHeBBZfup5FiZInOghgoM4Hwnmw+OgbJCNg1wwUQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=20.19.0" }, "peerDependencies": { - "storybook": "^0.0.0-0 || ^10.1.0 || ^10.1.0-0 || ^10.2.0-0 || ^10.3.0-0 || ^10.4.0-0" + "@csstools/css-parser-algorithms": "^4.0.0", + "@csstools/css-tokenizer": "^4.0.0" } }, - "node_modules/@chromatic-com/storybook/node_modules/ansi-regex": { - "version": "6.2.2", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz", - "integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==", + "node_modules/@csstools/css-color-parser": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-4.0.2.tgz", + "integrity": "sha512-0GEfbBLmTFf0dJlpsNU7zwxRIH0/BGEMuXLTCvFYxuL1tNhqzTbtnFICyJLTNK4a+RechKP75e7w42ClXSnJQw==", "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], "license": "MIT", + "dependencies": { + "@csstools/color-helpers": "^6.0.2", + "@csstools/css-calc": "^3.1.1" + }, "engines": { - "node": ">=12" + "node": ">=20.19.0" }, - "funding": { - "url": "https://github.com/chalk/ansi-regex?sponsor=1" + "peerDependencies": { + "@csstools/css-parser-algorithms": "^4.0.0", + "@csstools/css-tokenizer": "^4.0.0" } }, - "node_modules/@chromatic-com/storybook/node_modules/filesize": { - "version": "10.1.6", - "resolved": "https://registry.npmjs.org/filesize/-/filesize-10.1.6.tgz", - "integrity": "sha512-sJslQKU2uM33qH5nqewAwVB2QgR6w1aMNsYUp3aN5rMRyXEwJGmZvaWzeJFNTOXWlHQyBFCWrdj3fV/fsTOX8w==", + "node_modules/@csstools/css-parser-algorithms": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-4.0.0.tgz", + "integrity": "sha512-+B87qS7fIG3L5h3qwJ/IFbjoVoOe/bpOdh9hAjXbvx0o8ImEmUsGXN0inFOnk2ChCFgqkkGFQ+TpM5rbhkKe4w==", "dev": true, - "license": "BSD-3-Clause", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", "engines": { - "node": ">= 10.4.0" + "node": ">=20.19.0" + }, + "peerDependencies": { + "@csstools/css-tokenizer": "^4.0.0" } }, - "node_modules/@chromatic-com/storybook/node_modules/strip-ansi": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.2.0.tgz", - "integrity": "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==", + "node_modules/@csstools/css-tokenizer": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-4.0.0.tgz", + "integrity": "sha512-QxULHAm7cNu72w97JUNCBFODFaXpbDg+dP8b/oWFAZ2MTRppA3U00Y2L1HqaS4J6yBqxwa/Y3nMBaxVKbB/NsA==", "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], "license": "MIT", - "dependencies": { - "ansi-regex": "^6.2.2" - }, "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/strip-ansi?sponsor=1" + "node": ">=20.19.0" } }, "node_modules/@csstools/normalize.css": { @@ -2957,6 +3063,24 @@ "node": ">=12" } }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.4.tgz", + "integrity": "sha512-xHT8X4sb0GS8qTqiwzHqpY00C95DPAq7nAwX35Ie/s+LO9830hrMd3oX0ZMKLvy7vsonee73x0lmcdOVXFzd6Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "peer": true, + "engines": { + "node": ">=18" + } + }, "node_modules/@esbuild/netbsd-x64": { "version": "0.21.5", "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.21.5.tgz", @@ -2974,6 +3098,24 @@ "node": ">=12" } }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.4.tgz", + "integrity": "sha512-2MyL3IAaTX+1/qP0O1SwskwcwCoOI4kV2IBX1xYnDDqthmq5ArrW94qSIKCAuRraMgPOmG0RDTA74mzYNQA9ow==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "peer": true, + "engines": { + "node": ">=18" + } + }, "node_modules/@esbuild/openbsd-x64": { "version": "0.21.5", "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.21.5.tgz", @@ -2991,6 +3133,24 @@ "node": ">=12" } }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.4.tgz", + "integrity": "sha512-JkTZrl6VbyO8lDQO3yv26nNr2RM2yZzNrNHEsj9bm6dOwwu9OYN28CjzZkH57bh4w0I2F7IodpQvUAEd1mbWXg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "peer": true, + "engines": { + "node": ">=18" + } + }, "node_modules/@esbuild/sunos-x64": { "version": "0.21.5", "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.21.5.tgz", @@ -3554,6 +3714,15 @@ "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" } }, + "node_modules/@jest/diff-sequences": { + "version": "30.3.0", + "resolved": "https://registry.npmjs.org/@jest/diff-sequences/-/diff-sequences-30.3.0.tgz", + "integrity": "sha512-cG51MVnLq1ecVUaQ3fr6YuuAOitHK1S4WUJHnsPFE/quQr33ADUx1FfrTCpMCRxvy0Yr9BThKpDjSlcTi91tMA==", + "license": "MIT", + "engines": { + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" + } + }, "node_modules/@jest/environment": { "version": "27.5.1", "resolved": "https://registry.npmjs.org/@jest/environment/-/environment-27.5.1.tgz", @@ -3595,15 +3764,15 @@ } }, "node_modules/@jest/expect-utils": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/expect-utils/-/expect-utils-29.7.0.tgz", - "integrity": "sha512-GlsNBWiFQFCVi9QVSx7f5AgMeLxe9YCCs5PuP2O2LdjDAA8Jh9eX7lA1Jq/xdXw3Wb3hyvlFNfZIfcRetSzYcA==", + "version": "30.3.0", + "resolved": "https://registry.npmjs.org/@jest/expect-utils/-/expect-utils-30.3.0.tgz", + "integrity": "sha512-j0+W5iQQ8hBh7tHZkTQv3q2Fh/M7Je72cIsYqC4OaktgtO7v1So9UTjp6uPBHIaB6beoF/RRsCgMJKvti0wADA==", "license": "MIT", "dependencies": { - "jest-get-type": "^29.6.3" + "@jest/get-type": "30.1.0" }, "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/@jest/fake-timers": { @@ -3685,6 +3854,15 @@ "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" } }, + "node_modules/@jest/get-type": { + "version": "30.1.0", + "resolved": "https://registry.npmjs.org/@jest/get-type/-/get-type-30.1.0.tgz", + "integrity": "sha512-eMbZE2hUnx1WV0pmURZY9XoXPkUYjpc55mb0CrhtdWLtzMQPFvu/rZkTLZFTsdaVQa+Tr4eWAteqcUzoawq/uA==", + "license": "MIT", + "engines": { + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" + } + }, "node_modules/@jest/globals": { "version": "27.5.1", "resolved": "https://registry.npmjs.org/@jest/globals/-/globals-27.5.1.tgz", @@ -3807,6 +3985,28 @@ "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" } }, + "node_modules/@jest/pattern": { + "version": "30.0.1", + "resolved": "https://registry.npmjs.org/@jest/pattern/-/pattern-30.0.1.tgz", + "integrity": "sha512-gWp7NfQW27LaBQz3TITS8L7ZCQ0TLvtmI//4OwlQRx4rnWxcPNIYjxZpDcN4+UlGxgm3jS5QPz8IPTCkb59wZA==", + "license": "MIT", + "dependencies": { + "@types/node": "*", + "jest-regex-util": "30.0.1" + }, + "engines": { + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" + } + }, + "node_modules/@jest/pattern/node_modules/jest-regex-util": { + "version": "30.0.1", + "resolved": "https://registry.npmjs.org/jest-regex-util/-/jest-regex-util-30.0.1.tgz", + "integrity": "sha512-jHEQgBXAgc+Gh4g0p3bCevgRCVRkB4VB70zhoAE48gxeSr1hfUOsM/C2WoJgVL7Eyg//hudYENbm3Ne+/dRVVA==", + "license": "MIT", + "engines": { + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" + } + }, "node_modules/@jest/reporters": { "version": "27.5.1", "resolved": "https://registry.npmjs.org/@jest/reporters/-/reporters-27.5.1.tgz", @@ -3903,15 +4103,15 @@ } }, "node_modules/@jest/schemas": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-29.6.3.tgz", - "integrity": "sha512-mo5j5X+jIZmJQveBKeS/clAueipV7KgiX1vMgCxam1RNYiqE1w62n0/tJJnHtjW8ZHcQco5gY85jA3mi0L+nSA==", + "version": "30.0.5", + "resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-30.0.5.tgz", + "integrity": "sha512-DmdYgtezMkh3cpU8/1uyXakv3tJRcmcXxBOcO0tbaozPwpmh4YMsnWrQm9ZmZMfa5ocbxzbFk6O4bDPEc/iAnA==", "license": "MIT", "dependencies": { - "@sinclair/typebox": "^0.27.8" + "@sinclair/typebox": "^0.34.0" }, "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/@jest/source-map": { @@ -4076,20 +4276,21 @@ } }, "node_modules/@jest/types": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/@jest/types/-/types-29.6.3.tgz", - "integrity": "sha512-u3UPsIilWKOM3F9CXtrG8LEJmNxwoCQC/XVj4IKYXvvpx7QIi/Kg1LI5uDmDpKlac62NUtX7eLjRh+jVZcLOzw==", + "version": "30.3.0", + "resolved": "https://registry.npmjs.org/@jest/types/-/types-30.3.0.tgz", + "integrity": "sha512-JHm87k7bA33hpBngtU8h6UBub/fqqA9uXfw+21j5Hmk7ooPHlboRNxHq0JcMtC+n8VJGP1mcfnD3Mk+XKe1oSw==", "license": "MIT", "dependencies": { - "@jest/schemas": "^29.6.3", - "@types/istanbul-lib-coverage": "^2.0.0", - "@types/istanbul-reports": "^3.0.0", + "@jest/pattern": "30.0.1", + "@jest/schemas": "30.0.5", + "@types/istanbul-lib-coverage": "^2.0.6", + "@types/istanbul-reports": "^3.0.4", "@types/node": "*", - "@types/yargs": "^17.0.8", - "chalk": "^4.0.0" + "@types/yargs": "^17.0.33", + "chalk": "^4.1.2" }, "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/@joshwooding/vite-plugin-react-docgen-typescript": { @@ -4307,13 +4508,6 @@ "@emnapi/runtime": "^1.7.1" } }, - "node_modules/@neoconfetti/react": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/@neoconfetti/react/-/react-1.0.0.tgz", - "integrity": "sha512-klcSooChXXOzIm+SE5IISIAn3bYzYfPjbX7D7HoqZL84oAfgREeSg5vSIaSFH+DaGzzvImTyWe1OyrJ67vik4A==", - "dev": true, - "license": "MIT" - }, "node_modules/@nicolo-ribaudo/eslint-scope-5-internals": { "version": "5.1.1-v1", "resolved": "https://registry.npmjs.org/@nicolo-ribaudo/eslint-scope-5-internals/-/eslint-scope-5-internals-5.1.1-v1.tgz", @@ -4412,12 +4606,6 @@ "url": "https://github.com/sponsors/Boshen" } }, - "node_modules/@pinojs/redact": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/@pinojs/redact/-/redact-0.4.0.tgz", - "integrity": "sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg==", - "license": "MIT" - }, "node_modules/@pkgjs/parseargs": { "version": "0.11.0", "resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz", @@ -5047,7 +5235,7 @@ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.0.0-rc.12.tgz", "integrity": "sha512-nWwpvUSPkoFmZo0kQazZYOrT7J5DGOJ/+QHHzjvNlooDZED8oH82Yg67HvehPPLAg5fUff7TfWFHQS8IV1n3og==", "cpu": [ - "s390x" + "x64" ], "dev": true, "license": "MIT", @@ -5081,7 +5269,7 @@ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.0.0-rc.12.tgz", "integrity": "sha512-Jpw/0iwoKWx3LJ2rc1yjFrj+T7iHZn2JDg1Yny1ma0luviFS4mhAIcd1LFNxK3EYu3DHWCps0ydXQ5i/rrJ2ig==", "cpu": [ - "x64" + "arm64" ], "dev": true, "license": "MIT", @@ -5168,30 +5356,270 @@ "dev": true, "license": "MIT" }, - "node_modules/@rollup/pluginutils": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-5.3.0.tgz", - "integrity": "sha512-5EdhGZtnu3V88ces7s53hhfK5KSASnJZv8Lulpc04cWO3REESroJXg73DFsOmgbU2BhwV0E20bu2IDZb3VKW4Q==", + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.18.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.18.1.tgz", + "integrity": "sha512-lncuC4aHicncmbORnx+dUaAgzee9cm/PbIqgWz1PpXuwc+sa1Ct83tnqUDy/GFKleLiN7ZIeytM6KJ4cAn1SxA==", + "cpu": [ + "arm" + ], "dev": true, "license": "MIT", - "dependencies": { - "@types/estree": "^1.0.0", - "estree-walker": "^2.0.2", - "picomatch": "^4.0.2" - }, - "engines": { - "node": ">=14.0.0" - }, - "peerDependencies": { - "rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0" - }, - "peerDependenciesMeta": { - "rollup": { - "optional": true - } - } + "optional": true, + "os": [ + "android" + ] }, - "node_modules/@rollup/pluginutils/node_modules/estree-walker": { + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.18.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.18.1.tgz", + "integrity": "sha512-F/tkdw0WSs4ojqz5Ovrw5r9odqzFjb5LIgHdHZG65dFI1lWTWRVy32KDJLKRISHgJvqUeUhdIvy43fX41znyDg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.18.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.18.1.tgz", + "integrity": "sha512-vk+ma8iC1ebje/ahpxpnrfVQJibTMyHdWpOGZ3JpQ7Mgn/3QNHmPq7YwjZbIE7km73dH5M1e6MRRsnEBW7v5CQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.18.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.18.1.tgz", + "integrity": "sha512-IgpzXKauRe1Tafcej9STjSSuG0Ghu/xGYH+qG6JwsAUxXrnkvNHcq/NL6nz1+jzvWAnQkuAJ4uIwGB48K9OCGA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.18.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.18.1.tgz", + "integrity": "sha512-P9bSiAUnSSM7EmyRK+e5wgpqai86QOSv8BwvkGjLwYuOpaeomiZWifEos517CwbG+aZl1T4clSE1YqqH2JRs+g==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.18.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.18.1.tgz", + "integrity": "sha512-5RnjpACoxtS+aWOI1dURKno11d7krfpGDEn19jI8BuWmSBbUC4ytIADfROM1FZrFhQPSoP+KEa3NlEScznBTyQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.18.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.18.1.tgz", + "integrity": "sha512-8mwmGD668m8WaGbthrEYZ9CBmPug2QPGWxhJxh/vCgBjro5o96gL04WLlg5BA233OCWLqERy4YUzX3bJGXaJgQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.18.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.18.1.tgz", + "integrity": "sha512-dJX9u4r4bqInMGOAQoGYdwDP8lQiisWb9et+T84l2WXk41yEej8v2iGKodmdKimT8cTAYt0jFb+UEBxnPkbXEQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-powerpc64le-gnu": { + "version": "4.18.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-powerpc64le-gnu/-/rollup-linux-powerpc64le-gnu-4.18.1.tgz", + "integrity": "sha512-V72cXdTl4EI0x6FNmho4D502sy7ed+LuVW6Ym8aI6DRQ9hQZdp5sj0a2usYOlqvFBNKQnLQGwmYnujo2HvjCxQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.18.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.18.1.tgz", + "integrity": "sha512-f+pJih7sxoKmbjghrM2RkWo2WHUW8UbfxIQiWo5yeCaCM0TveMEuAzKJte4QskBp1TIinpnRcxkquY+4WuY/tg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.18.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.18.1.tgz", + "integrity": "sha512-qb1hMMT3Fr/Qz1OKovCuUM11MUNLUuHeBC2DPPAWUYYUAOFWaxInaTwTQmc7Fl5La7DShTEpmYwgdt2hG+4TEg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.18.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.18.1.tgz", + "integrity": "sha512-7O5u/p6oKUFYjRbZkL2FLbwsyoJAjyeXHCU3O4ndvzg2OFO2GinFPSJFGbiwFDaCFc+k7gs9CF243PwdPQFh5g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.18.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.18.1.tgz", + "integrity": "sha512-pDLkYITdYrH/9Cv/Vlj8HppDuLMDUBmgsM0+N+xLtFd18aXgM9Nyqupb/Uw+HeidhfYg2lD6CXvz6CjoVOaKjQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.18.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.18.1.tgz", + "integrity": "sha512-W2ZNI323O/8pJdBGil1oCauuCzmVd9lDmWBBqxYZcOqWD6aWqJtVBQ1dFrF4dYpZPks6F+xCZHfzG5hYlSHZ6g==", + "cpu": [ + "wasm32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@napi-rs/wasm-runtime": "^1.1.1" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@rolldown/binding-win32-arm64-msvc": { + "version": "1.0.0-rc.12", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.0.0-rc.12.tgz", + "integrity": "sha512-5eOND4duWkwx1AzCxadcOrNeighiLwMInEADT0YM7xeEOOFcovWZCq8dadXgcRHSf3Ulh1kFo/qvzoFiCLOL1Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-x64-msvc": { + "version": "1.0.0-rc.12", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.0.0-rc.12.tgz", + "integrity": "sha512-PyqoipaswDLAZtot351MLhrlrh6lcZPo2LSYE+VDxbVk24LVKAGOuE4hb8xZQmrPAuEtTZW8E6D2zc5EUZX4Lw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.0.0-rc.12", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-rc.12.tgz", + "integrity": "sha512-HHMwmarRKvoFsJorqYlFeFRzXZqCt2ETQlEDOb9aqssrnVBB1/+xgTGtuTrIk5vzLNX1MjMtTf7W9z3tsSbrxw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@rollup/pluginutils": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-5.3.0.tgz", + "integrity": "sha512-5EdhGZtnu3V88ces7s53hhfK5KSASnJZv8Lulpc04cWO3REESroJXg73DFsOmgbU2BhwV0E20bu2IDZb3VKW4Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0", + "estree-walker": "^2.0.2", + "picomatch": "^4.0.2" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0" + }, + "peerDependenciesMeta": { + "rollup": { + "optional": true + } + } + }, + "node_modules/@rollup/pluginutils/node_modules/estree-walker": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==", @@ -5626,9 +6054,9 @@ } }, "node_modules/@sinclair/typebox": { - "version": "0.27.8", - "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.27.8.tgz", - "integrity": "sha512-+Fj43pSMwJs4KRrH/938Uf+uAELIgVBmQzg/q1YG10djyfA3TnrU8N8XzqCh/okZdszqBQTZf96idMfE5lnwTA==", + "version": "0.34.49", + "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.34.49.tgz", + "integrity": "sha512-brySQQs7Jtn0joV8Xh9ZV/hZb9Ozb0pmazDIASBkYKCjXrXU3mpcFahmK/z4YDhGkQvP9mWJbVyahdtU5wQA+A==", "license": "MIT" }, "node_modules/@sinonjs/commons": { @@ -6475,6 +6903,7 @@ "version": "10.3.2", "resolved": "https://registry.npmjs.org/@testing-library/dom/-/dom-10.3.2.tgz", "integrity": "sha512-0bxIdP9mmPiOJ6wHLj8bdJRq+51oddObeCGdEf6PNEhYd93ZYAN+lPRnEOVFtheVwDM7+p+tza3LAQgp0PTudg==", + "dev": true, "license": "MIT", "peer": true, "dependencies": { @@ -6492,96 +6921,68 @@ } }, "node_modules/@testing-library/jest-dom": { - "version": "5.17.0", - "resolved": "https://registry.npmjs.org/@testing-library/jest-dom/-/jest-dom-5.17.0.tgz", - "integrity": "sha512-ynmNeT7asXyH3aSVv4vvX4Rb+0qjOhdNHnO/3vuZNqPmhDpV/+rCSGwQ7bLcmU2cJ4dvoheIO85LQj0IbJHEtg==", - "license": "MIT", - "dependencies": { - "@adobe/css-tools": "^4.0.1", - "@babel/runtime": "^7.9.2", - "@types/testing-library__jest-dom": "^5.9.1", + "version": "6.9.1", + "resolved": "https://registry.npmjs.org/@testing-library/jest-dom/-/jest-dom-6.9.1.tgz", + "integrity": "sha512-zIcONa+hVtVSSep9UT3jZ5rizo2BsxgyDYU7WFD5eICBE7no3881HGeb/QkGfsJs6JTkY1aQhT7rIPC7e+0nnA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@adobe/css-tools": "^4.4.0", "aria-query": "^5.0.0", - "chalk": "^3.0.0", "css.escape": "^1.5.1", - "dom-accessibility-api": "^0.5.6", - "lodash": "^4.17.15", + "dom-accessibility-api": "^0.6.3", + "picocolors": "^1.1.1", "redent": "^3.0.0" }, "engines": { - "node": ">=8", + "node": ">=14", "npm": ">=6", "yarn": ">=1" } }, - "node_modules/@testing-library/jest-dom/node_modules/chalk": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-3.0.0.tgz", - "integrity": "sha512-4D3B6Wf41KOYRFdszmDqMCGq5VV/uMAB273JILmO+3jAlh8X4qDtdtgCR3fxtbLEMzSx22QdhnDcJvu2u1fVwg==", - "license": "MIT", - "dependencies": { - "ansi-styles": "^4.1.0", - "supports-color": "^7.1.0" - }, - "engines": { - "node": ">=8" - } + "node_modules/@testing-library/jest-dom/node_modules/dom-accessibility-api": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.6.3.tgz", + "integrity": "sha512-7ZgogeTnjuHbo+ct10G9Ffp0mif17idi0IyWNVA/wcwcm7NPOD/WEHVP3n7n3MhXqxoIYm8d6MuZohYWIZ4T3w==", + "dev": true, + "license": "MIT" }, "node_modules/@testing-library/react": { - "version": "13.4.0", - "resolved": "https://registry.npmjs.org/@testing-library/react/-/react-13.4.0.tgz", - "integrity": "sha512-sXOGON+WNTh3MLE9rve97ftaZukN3oNf2KjDy7YTx6hcTO2uuLHuCGynMDhFwGw/jYf4OJ2Qk0i4i79qMNNkyw==", + "version": "16.3.2", + "resolved": "https://registry.npmjs.org/@testing-library/react/-/react-16.3.2.tgz", + "integrity": "sha512-XU5/SytQM+ykqMnAnvB2umaJNIOsLF3PVv//1Ew4CTcpz0/BRyy/af40qqrt7SjKpDdT1saBMc42CUok5gaw+g==", + "dev": true, "license": "MIT", "dependencies": { - "@babel/runtime": "^7.12.5", - "@testing-library/dom": "^8.5.0", - "@types/react-dom": "^18.0.0" + "@babel/runtime": "^7.12.5" }, "engines": { - "node": ">=12" + "node": ">=18" }, "peerDependencies": { - "react": "^18.0.0", - "react-dom": "^18.0.0" - } - }, - "node_modules/@testing-library/react/node_modules/@testing-library/dom": { - "version": "8.20.1", - "resolved": "https://registry.npmjs.org/@testing-library/dom/-/dom-8.20.1.tgz", - "integrity": "sha512-/DiOQ5xBxgdYRC8LNk7U+RWat0S3qRLeIw3ZIkMQ9kkVlRmwD/Eg8k8CqIpD6GW7u20JIUOfMKbxtiLutpjQ4g==", - "license": "MIT", - "dependencies": { - "@babel/code-frame": "^7.10.4", - "@babel/runtime": "^7.12.5", - "@types/aria-query": "^5.0.1", - "aria-query": "5.1.3", - "chalk": "^4.1.0", - "dom-accessibility-api": "^0.5.9", - "lz-string": "^1.5.0", - "pretty-format": "^27.0.2" + "@testing-library/dom": "^10.0.0", + "@types/react": "^18.0.0 || ^19.0.0", + "@types/react-dom": "^18.0.0 || ^19.0.0", + "react": "^18.0.0 || ^19.0.0", + "react-dom": "^18.0.0 || ^19.0.0" }, - "engines": { - "node": ">=12" - } - }, - "node_modules/@testing-library/react/node_modules/aria-query": { - "version": "5.1.3", - "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.1.3.tgz", - "integrity": "sha512-R5iJ5lkuHybztUfuOAznmboyjWq8O6sqNqtK7CLOqdydi54VNbORp49mb14KbWgG1QD3JFO9hJdZ+y4KutfdOQ==", - "license": "Apache-2.0", - "dependencies": { - "deep-equal": "^2.0.5" + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } } }, "node_modules/@testing-library/user-event": { - "version": "13.5.0", - "resolved": "https://registry.npmjs.org/@testing-library/user-event/-/user-event-13.5.0.tgz", - "integrity": "sha512-5Kwtbo3Y/NowpkbRuSepbyMFkZmHgD+vPzYB/RJ4oxt5Gj/avFFBYjhw27cqSVPVw/3a67NK1PbiIr9k4Gwmdg==", + "version": "14.6.1", + "resolved": "https://registry.npmjs.org/@testing-library/user-event/-/user-event-14.6.1.tgz", + "integrity": "sha512-vq7fv0rnt+QTXgPxr5Hjc210p6YKq2kmdziLgnsZGgLJ9e6VAShx1pACLuRjd/AS/sr7phAR58OIIpf0LlmQNw==", + "dev": true, "license": "MIT", - "dependencies": { - "@babel/runtime": "^7.12.5" - }, "engines": { - "node": ">=10", + "node": ">=12", "npm": ">=6" }, "peerDependencies": { @@ -6735,13 +7136,6 @@ "dev": true, "license": "MIT" }, - "node_modules/@types/doctrine": { - "version": "0.0.9", - "resolved": "https://registry.npmjs.org/@types/doctrine/-/doctrine-0.0.9.tgz", - "integrity": "sha512-eOIHzCUSH7SMfonMG1LsC2f8vxBFtho6NGBznK41R84YzPuvSBzrhEps33IsQiOW9+VL6NQ9DbjQJznk/S4uRA==", - "dev": true, - "license": "MIT" - }, "node_modules/@types/eslint": { "version": "8.56.10", "resolved": "https://registry.npmjs.org/@types/eslint/-/eslint-8.56.10.tgz", @@ -6847,13 +7241,13 @@ } }, "node_modules/@types/jest": { - "version": "29.5.12", - "resolved": "https://registry.npmjs.org/@types/jest/-/jest-29.5.12.tgz", - "integrity": "sha512-eDC8bTvT/QhYdxJAulQikueigY5AsdBRH2yDKW3yveW7svY3+DzN84/2NUgkw10RTiJbWqZrTtoGVdYlvFJdLw==", + "version": "30.0.0", + "resolved": "https://registry.npmjs.org/@types/jest/-/jest-30.0.0.tgz", + "integrity": "sha512-XTYugzhuwqWjws0CVz8QpM36+T+Dz5mTEBKhNs/esGLnCIlGdRy+Dq78NRjd7ls7r8BC8ZRMOrKlkO1hU0JOwA==", "license": "MIT", "dependencies": { - "expect": "^29.0.0", - "pretty-format": "^29.0.0" + "expect": "^30.0.0", + "pretty-format": "^30.0.0" } }, "node_modules/@types/jest/node_modules/ansi-styles": { @@ -6869,17 +7263,17 @@ } }, "node_modules/@types/jest/node_modules/pretty-format": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.7.0.tgz", - "integrity": "sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ==", + "version": "30.3.0", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-30.3.0.tgz", + "integrity": "sha512-oG4T3wCbfeuvljnyAzhBvpN45E8iOTXCU/TD3zXW80HA3dQ4ahdqMkWGiPWZvjpQwlbyHrPTWUAqUzGzv4l1JQ==", "license": "MIT", "dependencies": { - "@jest/schemas": "^29.6.3", - "ansi-styles": "^5.0.0", - "react-is": "^18.0.0" + "@jest/schemas": "30.0.5", + "ansi-styles": "^5.2.0", + "react-is": "^18.3.1" }, "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/@types/jest/node_modules/react-is": { @@ -7077,9 +7471,9 @@ } }, "node_modules/@types/yargs": { - "version": "17.0.32", - "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.32.tgz", - "integrity": "sha512-xQ67Yc/laOG5uMfX/093MRlGGCIBzZMarVa+gfNKJxWAIgykYpVGkBdbqEzGDDfCrVUj6Hiff4mTZ5BA6TmAog==", + "version": "17.0.35", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.35.tgz", + "integrity": "sha512-qUHkeCyQFxMXg79wQfTtfndEC+N9ZZg76HJftDJp+qH2tV7Gj4OJi7l+PiWwJ+pWtW8GwSmqsDj/oymhrTWXjg==", "license": "MIT", "dependencies": { "@types/yargs-parser": "*" @@ -7799,6 +8193,143 @@ "url": "https://opencollective.com/vitest" } }, + "node_modules/@vitest/coverage-v8": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/@vitest/coverage-v8/-/coverage-v8-4.1.2.tgz", + "integrity": "sha512-sPK//PHO+kAkScb8XITeB1bf7fsk85Km7+rt4eeuRR3VS1/crD47cmV5wicisJmjNdfeokTZwjMk4Mj2d58Mgg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@bcoe/v8-coverage": "^1.0.2", + "@vitest/utils": "4.1.2", + "ast-v8-to-istanbul": "^1.0.0", + "istanbul-lib-coverage": "^3.2.2", + "istanbul-lib-report": "^3.0.1", + "istanbul-reports": "^3.2.0", + "magicast": "^0.5.2", + "obug": "^2.1.1", + "std-env": "^4.0.0-rc.1", + "tinyrainbow": "^3.1.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@vitest/browser": "4.1.2", + "vitest": "4.1.2" + }, + "peerDependenciesMeta": { + "@vitest/browser": { + "optional": true + } + } + }, + "node_modules/@vitest/coverage-v8/node_modules/@bcoe/v8-coverage": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-1.0.2.tgz", + "integrity": "sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@vitest/expect": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.2.tgz", + "integrity": "sha512-gbu+7B0YgUJ2nkdsRJrFFW6X7NTP44WlhiclHniUhxADQJH5Szt9mZ9hWnJPJ8YwOK5zUOSSlSvyzRf0u1DSBQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@standard-schema/spec": "^1.1.0", + "@types/chai": "^5.2.2", + "@vitest/spy": "4.1.2", + "@vitest/utils": "4.1.2", + "chai": "^6.2.2", + "tinyrainbow": "^3.1.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/pretty-format": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.2.tgz", + "integrity": "sha512-dwQga8aejqeuB+TvXCMzSQemvV9hNEtDDpgUKDzOmNQayl2OG241PSWeJwKRH3CiC+sESrmoFd49rfnq7T4RnA==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyrainbow": "^3.1.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/runner": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.2.tgz", + "integrity": "sha512-Gr+FQan34CdiYAwpGJmQG8PgkyFVmARK8/xSijia3eTFgVfpcpztWLuP6FttGNfPLJhaZVP/euvujeNYar36OQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/utils": "4.1.2", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/snapshot": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.2.tgz", + "integrity": "sha512-g7yfUmxYS4mNxk31qbOYsSt2F4m1E02LFqO53Xpzg3zKMhLAPZAjjfyl9e6z7HrW6LvUdTwAQR3HHfLjpko16A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "4.1.2", + "@vitest/utils": "4.1.2", + "magic-string": "^0.30.21", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/snapshot/node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/@vitest/spy": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.2.tgz", + "integrity": "sha512-DU4fBnbVCJGNBwVA6xSToNXrkZNSiw59H8tcuUspVMsBDBST4nfvsPsEHDHGtWRRnqBERBQu7TrTKskmjqTXKA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/utils": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.2.tgz", + "integrity": "sha512-xw2/TiX82lQHA06cgbqRKFb5lCAy3axQ4H4SoUFhUsg+wztiet+co86IAMDtF6Vm1hc7J6j09oh/rgDn+JdKIQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "4.1.2", + "convert-source-map": "^2.0.0", + "tinyrainbow": "^3.1.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, "node_modules/@webassemblyjs/ast": { "version": "1.12.1", "resolved": "https://registry.npmjs.org/@webassemblyjs/ast/-/ast-1.12.1.tgz", @@ -8332,6 +8863,7 @@ "version": "5.3.0", "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.0.tgz", "integrity": "sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A==", + "dev": true, "license": "Apache-2.0", "dependencies": { "dequal": "^2.0.3" @@ -8541,17 +9073,14 @@ "integrity": "sha512-BSHWgDSAiKs50o2Re8ppvp3seVHXSRM44cdSsT9FfNEUUZLOGWVCsiWaRPWM1Znn+mqZ1OfVZ3z3DWEzSp7hRA==", "license": "MIT" }, - "node_modules/ast-types": { - "version": "0.13.4", - "resolved": "https://registry.npmjs.org/ast-types/-/ast-types-0.13.4.tgz", - "integrity": "sha512-x1FCFnFifvYDDzTaLII71vG5uvDwgtmDTEVWAxrgeiR8VjMONcCXJx7E+USjDtHlwFmt9MysbqgF9b9Vjr6w+w==", + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", "dev": true, "license": "MIT", - "dependencies": { - "tslib": "^2.0.1" - }, "engines": { - "node": ">=4" + "node": ">=12" } }, "node_modules/ast-types-flow": { @@ -8560,21 +9089,43 @@ "integrity": "sha512-OH/2E5Fg20h2aPrbe+QL8JZQFko0YZaF+j4mnQ7BGhfavO7OpSLa8a0y9sBwomHdSbkhTS8TQNayBfnW5DwbvQ==", "license": "MIT" }, - "node_modules/ast-types/node_modules/tslib": { - "version": "2.8.1", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", - "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "node_modules/ast-v8-to-istanbul": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/ast-v8-to-istanbul/-/ast-v8-to-istanbul-1.0.0.tgz", + "integrity": "sha512-1fSfIwuDICFA4LKkCzRPO7F0hzFf0B7+Xqrl27ynQaa+Rh0e1Es0v6kWHPott3lU10AyAr7oKHa65OppjLn3Rg==", "dev": true, - "license": "0BSD" - }, - "node_modules/async": { - "version": "3.2.5", - "resolved": "https://registry.npmjs.org/async/-/async-3.2.5.tgz", - "integrity": "sha512-baNZyqaaLhyLVKm/DlvdW051MSgO6b8eVfIezl9E5PqWxFgzLm/wQntEW4zOytVburDEr0JlALEpdOFwvErLsg==", - "license": "MIT" + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.31", + "estree-walker": "^3.0.3", + "js-tokens": "^10.0.0" + } }, - "node_modules/asynckit": { - "version": "0.4.0", + "node_modules/ast-v8-to-istanbul/node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/ast-v8-to-istanbul/node_modules/js-tokens": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-10.0.0.tgz", + "integrity": "sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/async": { + "version": "3.2.5", + "resolved": "https://registry.npmjs.org/async/-/async-3.2.5.tgz", + "integrity": "sha512-baNZyqaaLhyLVKm/DlvdW051MSgO6b8eVfIezl9E5PqWxFgzLm/wQntEW4zOytVburDEr0JlALEpdOFwvErLsg==", + "license": "MIT" + }, + "node_modules/asynckit": { + "version": "0.4.0", "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", "license": "MIT" @@ -9018,6 +9569,16 @@ "node": ">= 8.0.0" } }, + "node_modules/bidi-js": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/bidi-js/-/bidi-js-1.0.3.tgz", + "integrity": "sha512-RKshQI1R3YQ+n9YJz2QQ147P66ELpa1FQEg20Dk8oW9t2KgLbpDLLp9aGZ7y8WHSshDknG0bknqGw5/tyCs5tw==", + "dev": true, + "license": "MIT", + "dependencies": { + "require-from-string": "^2.0.2" + } + }, "node_modules/big.js": { "version": "5.2.2", "resolved": "https://registry.npmjs.org/big.js/-/big.js-5.2.2.tgz", @@ -9400,18 +9961,11 @@ } }, "node_modules/chai": { - "version": "5.3.3", - "resolved": "https://registry.npmjs.org/chai/-/chai-5.3.3.tgz", - "integrity": "sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==", + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz", + "integrity": "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==", "dev": true, "license": "MIT", - "dependencies": { - "assertion-error": "^2.0.1", - "check-error": "^2.1.1", - "deep-eql": "^5.0.1", - "loupe": "^3.1.0", - "pathval": "^2.0.0" - }, "engines": { "node": ">=18" } @@ -10419,52 +10973,88 @@ } }, "node_modules/data-urls": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-2.0.0.tgz", - "integrity": "sha512-X5eWTSXO/BJmpdIKCRuKUgSCgAN0OwliVK3yPKbwIWU1Tdw5BRajxlzMidvh+gwko9AfQ9zIj52pzF91Q3YAvQ==", + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-7.0.0.tgz", + "integrity": "sha512-23XHcCF+coGYevirZceTVD7NdJOqVn+49IHyxgszm+JIiHLoB2TkmPtsYkNWT1pvRSGkc35L6NHs0yHkN2SumA==", + "dev": true, "license": "MIT", "dependencies": { - "abab": "^2.0.3", - "whatwg-mimetype": "^2.3.0", - "whatwg-url": "^8.0.0" + "whatwg-mimetype": "^5.0.0", + "whatwg-url": "^16.0.0" }, "engines": { - "node": ">=10" + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + } + }, + "node_modules/data-urls/node_modules/@exodus/bytes": { + "version": "1.15.0", + "resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.15.0.tgz", + "integrity": "sha512-UY0nlA+feH81UGSHv92sLEPLCeZFjXOuHhrIo0HQydScuQc8s0A7kL/UdgwgDq8g8ilksmuoF35YVTNphV2aBQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + }, + "peerDependencies": { + "@noble/hashes": "^1.8.0 || ^2.0.0" + }, + "peerDependenciesMeta": { + "@noble/hashes": { + "optional": true + } + } + }, + "node_modules/data-urls/node_modules/@noble/hashes": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.0.1.tgz", + "integrity": "sha512-XlOlEbQcE9fmuXxrVTXCTlG2nlRXa9Rj3rr5Ue/+tX+nmkgbX720YHh0VR3hBF9xDvwnb8D2shVGOwNx+ulArw==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" } }, "node_modules/data-urls/node_modules/tr46": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/tr46/-/tr46-2.1.0.tgz", - "integrity": "sha512-15Ih7phfcdP5YxqiB+iDtLoaTz4Nd35+IiAv0kQ5FNKHzXgdWqPoTIqEDDJmXceQt4JZk6lVPT8lnDlPpGDppw==", + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-6.0.0.tgz", + "integrity": "sha512-bLVMLPtstlZ4iMQHpFHTR7GAGj2jxi8Dg0s2h2MafAE4uSWF98FC/3MomU51iQAMf8/qDUbKWf5GxuvvVcXEhw==", + "dev": true, "license": "MIT", "dependencies": { - "punycode": "^2.1.1" + "punycode": "^2.3.1" }, "engines": { - "node": ">=8" + "node": ">=20" } }, "node_modules/data-urls/node_modules/webidl-conversions": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-6.1.0.tgz", - "integrity": "sha512-qBIvFLGiBpLjfwmYAaHPXsn+ho5xZnGvyGvsarywGNc8VyQJUMHJ8OBKGGrPER0okBeMDaan4mNBlgBROxuI8w==", + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-8.0.1.tgz", + "integrity": "sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==", + "dev": true, "license": "BSD-2-Clause", "engines": { - "node": ">=10.4" + "node": ">=20" } }, "node_modules/data-urls/node_modules/whatwg-url": { - "version": "8.7.0", - "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-8.7.0.tgz", - "integrity": "sha512-gAojqb/m9Q8a5IV96E3fHJM70AzCkgt4uXYX2O7EmuyOnLrViCQlsEBmF9UQIu3/aeAIp2U17rtbpZWNntQqdg==", + "version": "16.0.1", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-16.0.1.tgz", + "integrity": "sha512-1to4zXBxmXHV3IiSSEInrreIlu02vUOvrhxJJH5vcxYTBDAx51cqZiKdyTxlecdKNSjj8EcxGBxNf6Vg+945gw==", + "dev": true, "license": "MIT", "dependencies": { - "lodash": "^4.7.0", - "tr46": "^2.1.0", - "webidl-conversions": "^6.1.0" + "@exodus/bytes": "^1.11.0", + "tr46": "^6.0.0", + "webidl-conversions": "^8.0.1" }, "engines": { - "node": ">=10" + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" } }, "node_modules/data-view-buffer": { @@ -10551,9 +11141,9 @@ } }, "node_modules/decimal.js": { - "version": "10.4.3", - "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.4.3.tgz", - "integrity": "sha512-VBBaLc1MgL5XpzgIP7ny5Z6Nx3UrRkIViUkPUdtl9aya5amy3De1gsUUSB1g3+3sExYNjCAsAznmukyxCb1GRA==", + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz", + "integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==", "license": "MIT" }, "node_modules/dedent": { @@ -10848,6 +11438,7 @@ "version": "2.0.3", "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==", + "dev": true, "license": "MIT", "engines": { "node": ">=6" @@ -10932,15 +11523,6 @@ "integrity": "sha512-gxtyfqMg7GKyhQmb056K7M3xszy/myH8w+B4RT+QXBQsvAOdc3XymqDDPHx1BgPgsdAA5SIifona89YtRATDzw==", "license": "Apache-2.0" }, - "node_modules/diff-sequences": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-29.6.3.tgz", - "integrity": "sha512-EjePK1srD3P08o2j4f0ExnylqRs5B9tJjcp9t1krH2qRi8CCdsYfwe9JgSLurFBWwq4uOlipzfk5fHNvwFKr8Q==", - "license": "MIT", - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, "node_modules/dir-glob": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/dir-glob/-/dir-glob-3.0.1.tgz", @@ -12416,19 +12998,44 @@ } }, "node_modules/expect": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/expect/-/expect-29.7.0.tgz", - "integrity": "sha512-2Zks0hf1VLFYI1kbh0I5jP3KHHyCHpkfyHBzsSXRFgl/Bg9mWYfMW8oD+PdMPlEwy5HNsR9JutYy6pMeOh61nw==", + "version": "30.3.0", + "resolved": "https://registry.npmjs.org/expect/-/expect-30.3.0.tgz", + "integrity": "sha512-1zQrciTiQfRdo7qJM1uG4navm8DayFa2TgCSRlzUyNkhcJ6XUZF3hjnpkyr3VhAqPH7i/9GkG7Tv5abz6fqz0Q==", + "license": "MIT", + "dependencies": { + "@jest/expect-utils": "30.3.0", + "@jest/get-type": "30.1.0", + "jest-matcher-utils": "30.3.0", + "jest-message-util": "30.3.0", + "jest-mock": "30.3.0", + "jest-util": "30.3.0" + }, + "engines": { + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" + } + }, + "node_modules/expect-type": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.3.0.tgz", + "integrity": "sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/expect/node_modules/jest-mock": { + "version": "30.3.0", + "resolved": "https://registry.npmjs.org/jest-mock/-/jest-mock-30.3.0.tgz", + "integrity": "sha512-OTzICK8CpE+t4ndhKrwlIdbM6Pn8j00lvmSmq5ejiO+KxukbLjgOflKWMn3KE34EZdQm5RqTuKj+5RIEniYhog==", "license": "MIT", "dependencies": { - "@jest/expect-utils": "^29.7.0", - "jest-get-type": "^29.6.3", - "jest-matcher-utils": "^29.7.0", - "jest-message-util": "^29.7.0", - "jest-util": "^29.7.0" + "@jest/types": "30.3.0", + "@types/node": "*", + "jest-util": "30.3.0" }, "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/expect-type": { @@ -12965,14 +13572,16 @@ } }, "node_modules/form-data": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-3.0.1.tgz", - "integrity": "sha512-RHkBKtLWUVwd7SqRIvCZMEvAMoGUp0XU+seQiZejj0COz3RI3hWP4sCv3gZWWLjJTd7rGwcsF5eKZGii0r/hbg==", + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-3.0.4.tgz", + "integrity": "sha512-f0cRzm6dkyVYV3nPoooP8XlccPQukegwhAnpoLcXy+X+A8KfpGOoXwDr9FLZd3wzgLaBGQBE3lY93Zm/i1JvIQ==", "license": "MIT", "dependencies": { "asynckit": "^0.4.0", "combined-stream": "^1.0.8", - "mime-types": "^2.1.12" + "es-set-tostringtag": "^2.1.0", + "hasown": "^2.0.2", + "mime-types": "^2.1.35" }, "engines": { "node": ">= 6" @@ -13579,15 +14188,49 @@ } }, "node_modules/html-encoding-sniffer": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-2.0.1.tgz", - "integrity": "sha512-D5JbOMBIR/TVZkubHT+OyT2705QvogUW4IBn6nHd756OwieSF9aDYFj4dv6HHEVGYbHaLETa3WggZYWWMyy3ZQ==", + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-6.0.0.tgz", + "integrity": "sha512-CV9TW3Y3f8/wT0BRFc1/KAVQ3TUHiXmaAb6VW9vtiMFf7SLoMd1PdAc4W3KFOFETBJUb90KatHqlsZMWV+R9Gg==", + "dev": true, "license": "MIT", "dependencies": { - "whatwg-encoding": "^1.0.5" + "@exodus/bytes": "^1.6.0" }, "engines": { - "node": ">=10" + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + } + }, + "node_modules/html-encoding-sniffer/node_modules/@exodus/bytes": { + "version": "1.15.0", + "resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.15.0.tgz", + "integrity": "sha512-UY0nlA+feH81UGSHv92sLEPLCeZFjXOuHhrIo0HQydScuQc8s0A7kL/UdgwgDq8g8ilksmuoF35YVTNphV2aBQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + }, + "peerDependencies": { + "@noble/hashes": "^1.8.0 || ^2.0.0" + }, + "peerDependenciesMeta": { + "@noble/hashes": { + "optional": true + } + } + }, + "node_modules/html-encoding-sniffer/node_modules/@noble/hashes": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.0.1.tgz", + "integrity": "sha512-XlOlEbQcE9fmuXxrVTXCTlG2nlRXa9Rj3rr5Ue/+tX+nmkgbX720YHh0VR3hBF9xDvwnb8D2shVGOwNx+ulArw==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" } }, "node_modules/html-entities": { @@ -15223,18 +15866,18 @@ } }, "node_modules/jest-diff": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-diff/-/jest-diff-29.7.0.tgz", - "integrity": "sha512-LMIgiIrhigmPrs03JHpxUh2yISK3vLFPkAodPeo0+BuF7wA2FoQbkEg1u8gBYBThncu7e1oEDUfIXVuTqLRUjw==", + "version": "30.3.0", + "resolved": "https://registry.npmjs.org/jest-diff/-/jest-diff-30.3.0.tgz", + "integrity": "sha512-n3q4PDQjS4LrKxfWB3Z5KNk1XjXtZTBwQp71OP0Jo03Z6V60x++K5L8k6ZrW8MY8pOFylZvHM0zsjS1RqlHJZQ==", "license": "MIT", "dependencies": { - "chalk": "^4.0.0", - "diff-sequences": "^29.6.3", - "jest-get-type": "^29.6.3", - "pretty-format": "^29.7.0" + "@jest/diff-sequences": "30.3.0", + "@jest/get-type": "30.1.0", + "chalk": "^4.1.2", + "pretty-format": "30.3.0" }, "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/jest-diff/node_modules/ansi-styles": { @@ -15250,17 +15893,17 @@ } }, "node_modules/jest-diff/node_modules/pretty-format": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.7.0.tgz", - "integrity": "sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ==", + "version": "30.3.0", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-30.3.0.tgz", + "integrity": "sha512-oG4T3wCbfeuvljnyAzhBvpN45E8iOTXCU/TD3zXW80HA3dQ4ahdqMkWGiPWZvjpQwlbyHrPTWUAqUzGzv4l1JQ==", "license": "MIT", "dependencies": { - "@jest/schemas": "^29.6.3", - "ansi-styles": "^5.0.0", - "react-is": "^18.0.0" + "@jest/schemas": "30.0.5", + "ansi-styles": "^5.2.0", + "react-is": "^18.3.1" }, "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/jest-diff/node_modules/react-is": { @@ -15391,66 +16034,33 @@ "@types/yargs-parser": "*" } }, - "node_modules/jest-environment-jsdom/node_modules/jest-util": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-util/-/jest-util-27.5.1.tgz", - "integrity": "sha512-Kv2o/8jNvX1MQ0KGtw480E/w4fBCDOnH6+6DmeKi6LZUIlKA5kwY0YNdlzaWTiVgxqAqik11QyxDOKk543aKXw==", - "license": "MIT", - "dependencies": { - "@jest/types": "^27.5.1", - "@types/node": "*", - "chalk": "^4.0.0", - "ci-info": "^3.2.0", - "graceful-fs": "^4.2.9", - "picomatch": "^2.2.3" - }, - "engines": { - "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" - } - }, - "node_modules/jest-environment-node": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-environment-node/-/jest-environment-node-27.5.1.tgz", - "integrity": "sha512-Jt4ZUnxdOsTGwSRAfKEnE6BcwsSPNOijjwifq5sDFSA2kesnXTvNqKHYgM0hDq3549Uf/KzdXNYn4wMZJPlFLw==", + "node_modules/jest-environment-jsdom/node_modules/data-urls": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-2.0.0.tgz", + "integrity": "sha512-X5eWTSXO/BJmpdIKCRuKUgSCgAN0OwliVK3yPKbwIWU1Tdw5BRajxlzMidvh+gwko9AfQ9zIj52pzF91Q3YAvQ==", "license": "MIT", "dependencies": { - "@jest/environment": "^27.5.1", - "@jest/fake-timers": "^27.5.1", - "@jest/types": "^27.5.1", - "@types/node": "*", - "jest-mock": "^27.5.1", - "jest-util": "^27.5.1" + "abab": "^2.0.3", + "whatwg-mimetype": "^2.3.0", + "whatwg-url": "^8.0.0" }, "engines": { - "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + "node": ">=10" } }, - "node_modules/jest-environment-node/node_modules/@jest/types": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/@jest/types/-/types-27.5.1.tgz", - "integrity": "sha512-Cx46iJ9QpwQTjIdq5VJu2QTMMs3QlEjI0x1QbBP5W1+nMzyc2XmimiRR/CbX9TO0cPTeUlxWMOu8mslYsJ8DEw==", + "node_modules/jest-environment-jsdom/node_modules/html-encoding-sniffer": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-2.0.1.tgz", + "integrity": "sha512-D5JbOMBIR/TVZkubHT+OyT2705QvogUW4IBn6nHd756OwieSF9aDYFj4dv6HHEVGYbHaLETa3WggZYWWMyy3ZQ==", "license": "MIT", "dependencies": { - "@types/istanbul-lib-coverage": "^2.0.0", - "@types/istanbul-reports": "^3.0.0", - "@types/node": "*", - "@types/yargs": "^16.0.0", - "chalk": "^4.0.0" + "whatwg-encoding": "^1.0.5" }, "engines": { - "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" - } - }, - "node_modules/jest-environment-node/node_modules/@types/yargs": { - "version": "16.0.9", - "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-16.0.9.tgz", - "integrity": "sha512-tHhzvkFXZQeTECenFoRljLBYPZJ7jAVxqqtEI0qTLOmuultnFp4I9yKE17vTuhf7BkhCu7I4XuemPgikDVuYqA==", - "license": "MIT", - "dependencies": { - "@types/yargs-parser": "*" + "node": ">=10" } }, - "node_modules/jest-environment-node/node_modules/jest-util": { + "node_modules/jest-environment-jsdom/node_modules/jest-util": { "version": "27.5.1", "resolved": "https://registry.npmjs.org/jest-util/-/jest-util-27.5.1.tgz", "integrity": "sha512-Kv2o/8jNvX1MQ0KGtw480E/w4fBCDOnH6+6DmeKi6LZUIlKA5kwY0YNdlzaWTiVgxqAqik11QyxDOKk543aKXw==", @@ -15467,18 +16077,215 @@ "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" } }, - "node_modules/jest-get-type": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/jest-get-type/-/jest-get-type-29.6.3.tgz", - "integrity": "sha512-zrteXnqYxfQh7l5FHyL38jL39di8H8rHoecLH3JNxH3BwOrBsNeabdap5e0I23lD4HHI8W5VFBZqG4Eaq5LNcw==", + "node_modules/jest-environment-jsdom/node_modules/jsdom": { + "version": "16.7.0", + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-16.7.0.tgz", + "integrity": "sha512-u9Smc2G1USStM+s/x1ru5Sxrl6mPYCbByG1U/hUmqaVsm4tbNyS7CicOSRyuGQYZhTu0h84qkZZQ/I+dzizSVw==", "license": "MIT", + "dependencies": { + "abab": "^2.0.5", + "acorn": "^8.2.4", + "acorn-globals": "^6.0.0", + "cssom": "^0.4.4", + "cssstyle": "^2.3.0", + "data-urls": "^2.0.0", + "decimal.js": "^10.2.1", + "domexception": "^2.0.1", + "escodegen": "^2.0.0", + "form-data": "^3.0.0", + "html-encoding-sniffer": "^2.0.1", + "http-proxy-agent": "^4.0.1", + "https-proxy-agent": "^5.0.0", + "is-potential-custom-element-name": "^1.0.1", + "nwsapi": "^2.2.0", + "parse5": "6.0.1", + "saxes": "^5.0.1", + "symbol-tree": "^3.2.4", + "tough-cookie": "^4.0.0", + "w3c-hr-time": "^1.0.2", + "w3c-xmlserializer": "^2.0.0", + "webidl-conversions": "^6.1.0", + "whatwg-encoding": "^1.0.5", + "whatwg-mimetype": "^2.3.0", + "whatwg-url": "^8.5.0", + "ws": "^7.4.6", + "xml-name-validator": "^3.0.0" + }, "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + "node": ">=10" + }, + "peerDependencies": { + "canvas": "^2.5.0" + }, + "peerDependenciesMeta": { + "canvas": { + "optional": true + } } }, - "node_modules/jest-haste-map": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-haste-map/-/jest-haste-map-27.5.1.tgz", + "node_modules/jest-environment-jsdom/node_modules/parse5": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-6.0.1.tgz", + "integrity": "sha512-Ofn/CTFzRGTTxwpNEs9PP93gXShHcTq255nzRYSKe8AkVpZY7e1fpmTfOyoIvjP5HG7Z2ZM7VS9PPhQGW2pOpw==", + "license": "MIT" + }, + "node_modules/jest-environment-jsdom/node_modules/saxes": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/saxes/-/saxes-5.0.1.tgz", + "integrity": "sha512-5LBh1Tls8c9xgGjw3QrMwETmTMVk0oFgvrFSvWx62llR2hcEInrKNZ2GZCCuuy2lvWrdl5jhbpeqc5hRYKFOcw==", + "license": "ISC", + "dependencies": { + "xmlchars": "^2.2.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/jest-environment-jsdom/node_modules/tough-cookie": { + "version": "4.1.4", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-4.1.4.tgz", + "integrity": "sha512-Loo5UUvLD9ScZ6jh8beX1T6sO1w2/MpCRpEP7V280GKMVUQ0Jzar2U3UJPsrdbziLEMMhu3Ujnq//rhiFuIeag==", + "license": "BSD-3-Clause", + "dependencies": { + "psl": "^1.1.33", + "punycode": "^2.1.1", + "universalify": "^0.2.0", + "url-parse": "^1.5.3" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/jest-environment-jsdom/node_modules/tr46": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-2.1.0.tgz", + "integrity": "sha512-15Ih7phfcdP5YxqiB+iDtLoaTz4Nd35+IiAv0kQ5FNKHzXgdWqPoTIqEDDJmXceQt4JZk6lVPT8lnDlPpGDppw==", + "license": "MIT", + "dependencies": { + "punycode": "^2.1.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/jest-environment-jsdom/node_modules/universalify": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.2.0.tgz", + "integrity": "sha512-CJ1QgKmNg3CwvAv/kOFmtnEN05f0D/cn9QntgNOQlQF9dgvVTHj3t+8JPdjqawCHk7V/KA+fbUqzZ9XWhcqPUg==", + "license": "MIT", + "engines": { + "node": ">= 4.0.0" + } + }, + "node_modules/jest-environment-jsdom/node_modules/w3c-xmlserializer": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-2.0.0.tgz", + "integrity": "sha512-4tzD0mF8iSiMiNs30BiLO3EpfGLZUT2MSX/G+o7ZywDzliWQ3OPtTZ0PTC3B3ca1UAf4cJMHB+2Bf56EriJuRA==", + "license": "MIT", + "dependencies": { + "xml-name-validator": "^3.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/jest-environment-jsdom/node_modules/webidl-conversions": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-6.1.0.tgz", + "integrity": "sha512-qBIvFLGiBpLjfwmYAaHPXsn+ho5xZnGvyGvsarywGNc8VyQJUMHJ8OBKGGrPER0okBeMDaan4mNBlgBROxuI8w==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=10.4" + } + }, + "node_modules/jest-environment-jsdom/node_modules/whatwg-mimetype": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-2.3.0.tgz", + "integrity": "sha512-M4yMwr6mAnQz76TbJm914+gPpB/nCwvZbJU28cUD6dR004SAxDLOOSUaB1JDRqLtaOV/vi0IC5lEAGFgrjGv/g==", + "license": "MIT" + }, + "node_modules/jest-environment-jsdom/node_modules/whatwg-url": { + "version": "8.7.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-8.7.0.tgz", + "integrity": "sha512-gAojqb/m9Q8a5IV96E3fHJM70AzCkgt4uXYX2O7EmuyOnLrViCQlsEBmF9UQIu3/aeAIp2U17rtbpZWNntQqdg==", + "license": "MIT", + "dependencies": { + "lodash": "^4.7.0", + "tr46": "^2.1.0", + "webidl-conversions": "^6.1.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/jest-environment-jsdom/node_modules/xml-name-validator": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-3.0.0.tgz", + "integrity": "sha512-A5CUptxDsvxKJEU3yO6DuWBSJz/qizqzJKOMIfUJHETbBw/sFaDxgd6fxm1ewUaM0jZ444Fc5vC5ROYurg/4Pw==", + "license": "Apache-2.0" + }, + "node_modules/jest-environment-node": { + "version": "27.5.1", + "resolved": "https://registry.npmjs.org/jest-environment-node/-/jest-environment-node-27.5.1.tgz", + "integrity": "sha512-Jt4ZUnxdOsTGwSRAfKEnE6BcwsSPNOijjwifq5sDFSA2kesnXTvNqKHYgM0hDq3549Uf/KzdXNYn4wMZJPlFLw==", + "license": "MIT", + "dependencies": { + "@jest/environment": "^27.5.1", + "@jest/fake-timers": "^27.5.1", + "@jest/types": "^27.5.1", + "@types/node": "*", + "jest-mock": "^27.5.1", + "jest-util": "^27.5.1" + }, + "engines": { + "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + } + }, + "node_modules/jest-environment-node/node_modules/@jest/types": { + "version": "27.5.1", + "resolved": "https://registry.npmjs.org/@jest/types/-/types-27.5.1.tgz", + "integrity": "sha512-Cx46iJ9QpwQTjIdq5VJu2QTMMs3QlEjI0x1QbBP5W1+nMzyc2XmimiRR/CbX9TO0cPTeUlxWMOu8mslYsJ8DEw==", + "license": "MIT", + "dependencies": { + "@types/istanbul-lib-coverage": "^2.0.0", + "@types/istanbul-reports": "^3.0.0", + "@types/node": "*", + "@types/yargs": "^16.0.0", + "chalk": "^4.0.0" + }, + "engines": { + "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + } + }, + "node_modules/jest-environment-node/node_modules/@types/yargs": { + "version": "16.0.9", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-16.0.9.tgz", + "integrity": "sha512-tHhzvkFXZQeTECenFoRljLBYPZJ7jAVxqqtEI0qTLOmuultnFp4I9yKE17vTuhf7BkhCu7I4XuemPgikDVuYqA==", + "license": "MIT", + "dependencies": { + "@types/yargs-parser": "*" + } + }, + "node_modules/jest-environment-node/node_modules/jest-util": { + "version": "27.5.1", + "resolved": "https://registry.npmjs.org/jest-util/-/jest-util-27.5.1.tgz", + "integrity": "sha512-Kv2o/8jNvX1MQ0KGtw480E/w4fBCDOnH6+6DmeKi6LZUIlKA5kwY0YNdlzaWTiVgxqAqik11QyxDOKk543aKXw==", + "license": "MIT", + "dependencies": { + "@jest/types": "^27.5.1", + "@types/node": "*", + "chalk": "^4.0.0", + "ci-info": "^3.2.0", + "graceful-fs": "^4.2.9", + "picomatch": "^2.2.3" + }, + "engines": { + "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + } + }, + "node_modules/jest-haste-map": { + "version": "27.5.1", + "resolved": "https://registry.npmjs.org/jest-haste-map/-/jest-haste-map-27.5.1.tgz", "integrity": "sha512-7GgkZ4Fw4NFbMSDSpZwXeBiIbx+t/46nJ2QitkOjvwPYyZmqttu2TDSimMHP1EkPOi4xUZAN1doE5Vd25H4Jng==", "license": "MIT", "dependencies": { @@ -15720,18 +16527,18 @@ } }, "node_modules/jest-matcher-utils": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-matcher-utils/-/jest-matcher-utils-29.7.0.tgz", - "integrity": "sha512-sBkD+Xi9DtcChsI3L3u0+N0opgPYnCRPtGcQYrgXmR+hmt/fYfWAL0xRXYU8eWOdfuLgBe0YCW3AFtnRLagq/g==", + "version": "30.3.0", + "resolved": "https://registry.npmjs.org/jest-matcher-utils/-/jest-matcher-utils-30.3.0.tgz", + "integrity": "sha512-HEtc9uFQgaUHkC7nLSlQL3Tph4Pjxt/yiPvkIrrDCt9jhoLIgxaubo1G+CFOnmHYMxHwwdaSN7mkIFs6ZK8OhA==", "license": "MIT", "dependencies": { - "chalk": "^4.0.0", - "jest-diff": "^29.7.0", - "jest-get-type": "^29.6.3", - "pretty-format": "^29.7.0" + "@jest/get-type": "30.1.0", + "chalk": "^4.1.2", + "jest-diff": "30.3.0", + "pretty-format": "30.3.0" }, "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/jest-matcher-utils/node_modules/ansi-styles": { @@ -15747,17 +16554,17 @@ } }, "node_modules/jest-matcher-utils/node_modules/pretty-format": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.7.0.tgz", - "integrity": "sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ==", + "version": "30.3.0", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-30.3.0.tgz", + "integrity": "sha512-oG4T3wCbfeuvljnyAzhBvpN45E8iOTXCU/TD3zXW80HA3dQ4ahdqMkWGiPWZvjpQwlbyHrPTWUAqUzGzv4l1JQ==", "license": "MIT", "dependencies": { - "@jest/schemas": "^29.6.3", - "ansi-styles": "^5.0.0", - "react-is": "^18.0.0" + "@jest/schemas": "30.0.5", + "ansi-styles": "^5.2.0", + "react-is": "^18.3.1" }, "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/jest-matcher-utils/node_modules/react-is": { @@ -15767,23 +16574,23 @@ "license": "MIT" }, "node_modules/jest-message-util": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-message-util/-/jest-message-util-29.7.0.tgz", - "integrity": "sha512-GBEV4GRADeP+qtB2+6u61stea8mGcOT4mCtrYISZwfu9/ISHFJ/5zOMXYbpBE9RsS5+Gb63DW4FgmnKJ79Kf6w==", + "version": "30.3.0", + "resolved": "https://registry.npmjs.org/jest-message-util/-/jest-message-util-30.3.0.tgz", + "integrity": "sha512-Z/j4Bo+4ySJ+JPJN3b2Qbl9hDq3VrXmnjjGEWD/x0BCXeOXPTV1iZYYzl2X8c1MaCOL+ewMyNBcm88sboE6YWw==", "license": "MIT", "dependencies": { - "@babel/code-frame": "^7.12.13", - "@jest/types": "^29.6.3", - "@types/stack-utils": "^2.0.0", - "chalk": "^4.0.0", - "graceful-fs": "^4.2.9", - "micromatch": "^4.0.4", - "pretty-format": "^29.7.0", + "@babel/code-frame": "^7.27.1", + "@jest/types": "30.3.0", + "@types/stack-utils": "^2.0.3", + "chalk": "^4.1.2", + "graceful-fs": "^4.2.11", + "picomatch": "^4.0.3", + "pretty-format": "30.3.0", "slash": "^3.0.0", - "stack-utils": "^2.0.3" + "stack-utils": "^2.0.6" }, "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/jest-message-util/node_modules/ansi-styles": { @@ -15798,18 +16605,30 @@ "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, + "node_modules/jest-message-util/node_modules/picomatch": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz", + "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, "node_modules/jest-message-util/node_modules/pretty-format": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.7.0.tgz", - "integrity": "sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ==", + "version": "30.3.0", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-30.3.0.tgz", + "integrity": "sha512-oG4T3wCbfeuvljnyAzhBvpN45E8iOTXCU/TD3zXW80HA3dQ4ahdqMkWGiPWZvjpQwlbyHrPTWUAqUzGzv4l1JQ==", "license": "MIT", "dependencies": { - "@jest/schemas": "^29.6.3", - "ansi-styles": "^5.0.0", - "react-is": "^18.0.0" + "@jest/schemas": "30.0.5", + "ansi-styles": "^5.2.0", + "react-is": "^18.3.1" }, "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/jest-message-util/node_modules/react-is": { @@ -16481,20 +17300,47 @@ } }, "node_modules/jest-util": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-util/-/jest-util-29.7.0.tgz", - "integrity": "sha512-z6EbKajIpqGKU56y5KBUgy1dt1ihhQJgWzUlZHArA/+X2ad7Cb5iF+AK1EWVL/Bo7Rz9uurpqw6SiBCefUbCGA==", + "version": "30.3.0", + "resolved": "https://registry.npmjs.org/jest-util/-/jest-util-30.3.0.tgz", + "integrity": "sha512-/jZDa00a3Sz7rdyu55NLrQCIrbyIkbBxareejQI315f/i8HjYN+ZWsDLLpoQSiUIEIyZF/R8fDg3BmB8AtHttg==", "license": "MIT", "dependencies": { - "@jest/types": "^29.6.3", + "@jest/types": "30.3.0", "@types/node": "*", - "chalk": "^4.0.0", - "ci-info": "^3.2.0", - "graceful-fs": "^4.2.9", - "picomatch": "^2.2.3" + "chalk": "^4.1.2", + "ci-info": "^4.2.0", + "graceful-fs": "^4.2.11", + "picomatch": "^4.0.3" }, "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" + } + }, + "node_modules/jest-util/node_modules/ci-info": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-4.4.0.tgz", + "integrity": "sha512-77PSwercCZU2Fc4sX94eF8k8Pxte6JAwL4/ICZLFjJLqegs7kCuAsqqj/70NQF6TvDpgFjkubQB2FW2ZZddvQg==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/sibiraj-s" + } + ], + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/jest-util/node_modules/picomatch": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz", + "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" } }, "node_modules/jest-validate": { @@ -16986,44 +17832,39 @@ } }, "node_modules/jsdom": { - "version": "16.7.0", - "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-16.7.0.tgz", - "integrity": "sha512-u9Smc2G1USStM+s/x1ru5Sxrl6mPYCbByG1U/hUmqaVsm4tbNyS7CicOSRyuGQYZhTu0h84qkZZQ/I+dzizSVw==", + "version": "29.0.1", + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-29.0.1.tgz", + "integrity": "sha512-z6JOK5gRO7aMybVq/y/MlIpKh8JIi68FBKMUtKkK2KH/wMSRlCxQ682d08LB9fYXplyY/UXG8P4XXTScmdjApg==", + "dev": true, "license": "MIT", "dependencies": { - "abab": "^2.0.5", - "acorn": "^8.2.4", - "acorn-globals": "^6.0.0", - "cssom": "^0.4.4", - "cssstyle": "^2.3.0", - "data-urls": "^2.0.0", - "decimal.js": "^10.2.1", - "domexception": "^2.0.1", - "escodegen": "^2.0.0", - "form-data": "^3.0.0", - "html-encoding-sniffer": "^2.0.1", - "http-proxy-agent": "^4.0.1", - "https-proxy-agent": "^5.0.0", + "@asamuzakjp/css-color": "^5.0.1", + "@asamuzakjp/dom-selector": "^7.0.3", + "@bramus/specificity": "^2.4.2", + "@csstools/css-syntax-patches-for-csstree": "^1.1.1", + "@exodus/bytes": "^1.15.0", + "css-tree": "^3.2.1", + "data-urls": "^7.0.0", + "decimal.js": "^10.6.0", + "html-encoding-sniffer": "^6.0.0", "is-potential-custom-element-name": "^1.0.1", - "nwsapi": "^2.2.0", - "parse5": "6.0.1", - "saxes": "^5.0.1", + "lru-cache": "^11.2.7", + "parse5": "^8.0.0", + "saxes": "^6.0.0", "symbol-tree": "^3.2.4", - "tough-cookie": "^4.0.0", - "w3c-hr-time": "^1.0.2", - "w3c-xmlserializer": "^2.0.0", - "webidl-conversions": "^6.1.0", - "whatwg-encoding": "^1.0.5", - "whatwg-mimetype": "^2.3.0", - "whatwg-url": "^8.5.0", - "ws": "^7.4.6", - "xml-name-validator": "^3.0.0" + "tough-cookie": "^6.0.1", + "undici": "^7.24.5", + "w3c-xmlserializer": "^5.0.0", + "webidl-conversions": "^8.0.1", + "whatwg-mimetype": "^5.0.0", + "whatwg-url": "^16.0.1", + "xml-name-validator": "^5.0.0" }, "engines": { - "node": ">=10" + "node": "^20.19.0 || ^22.13.0 || >=24.0.0" }, "peerDependencies": { - "canvas": "^2.5.0" + "canvas": "^3.0.0" }, "peerDependenciesMeta": { "canvas": { @@ -17031,45 +17872,137 @@ } } }, - "node_modules/jsdom/node_modules/tr46": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/tr46/-/tr46-2.1.0.tgz", - "integrity": "sha512-15Ih7phfcdP5YxqiB+iDtLoaTz4Nd35+IiAv0kQ5FNKHzXgdWqPoTIqEDDJmXceQt4JZk6lVPT8lnDlPpGDppw==", - "license": "MIT", - "dependencies": { - "punycode": "^2.1.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/jsdom/node_modules/webidl-conversions": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-6.1.0.tgz", - "integrity": "sha512-qBIvFLGiBpLjfwmYAaHPXsn+ho5xZnGvyGvsarywGNc8VyQJUMHJ8OBKGGrPER0okBeMDaan4mNBlgBROxuI8w==", + "node_modules/jsdom/node_modules/@csstools/css-syntax-patches-for-csstree": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@csstools/css-syntax-patches-for-csstree/-/css-syntax-patches-for-csstree-1.1.2.tgz", + "integrity": "sha512-5GkLzz4prTIpoyeUiIu3iV6CSG3Plo7xRVOFPKI7FVEJ3mZ0A8SwK0XU3Gl7xAkiQ+mDyam+NNp875/C5y+jSA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT-0", + "peerDependencies": { + "css-tree": "^3.2.1" + }, + "peerDependenciesMeta": { + "css-tree": { + "optional": true + } + } + }, + "node_modules/jsdom/node_modules/@exodus/bytes": { + "version": "1.15.0", + "resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.15.0.tgz", + "integrity": "sha512-UY0nlA+feH81UGSHv92sLEPLCeZFjXOuHhrIo0HQydScuQc8s0A7kL/UdgwgDq8g8ilksmuoF35YVTNphV2aBQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + }, + "peerDependencies": { + "@noble/hashes": "^1.8.0 || ^2.0.0" + }, + "peerDependenciesMeta": { + "@noble/hashes": { + "optional": true + } + } + }, + "node_modules/jsdom/node_modules/@noble/hashes": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.0.1.tgz", + "integrity": "sha512-XlOlEbQcE9fmuXxrVTXCTlG2nlRXa9Rj3rr5Ue/+tX+nmkgbX720YHh0VR3hBF9xDvwnb8D2shVGOwNx+ulArw==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/jsdom/node_modules/css-tree": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-3.2.1.tgz", + "integrity": "sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==", + "dev": true, + "license": "MIT", + "dependencies": { + "mdn-data": "2.27.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0" + } + }, + "node_modules/jsdom/node_modules/lru-cache": { + "version": "11.2.7", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.2.7.tgz", + "integrity": "sha512-aY/R+aEsRelme17KGQa/1ZSIpLpNYYrhcrepKTZgE+W3WM16YMCaPwOHLHsmopZHELU0Ojin1lPVxKR0MihncA==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/jsdom/node_modules/mdn-data": { + "version": "2.27.1", + "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.27.1.tgz", + "integrity": "sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==", + "dev": true, + "license": "CC0-1.0" + }, + "node_modules/jsdom/node_modules/tr46": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-6.0.0.tgz", + "integrity": "sha512-bLVMLPtstlZ4iMQHpFHTR7GAGj2jxi8Dg0s2h2MafAE4uSWF98FC/3MomU51iQAMf8/qDUbKWf5GxuvvVcXEhw==", + "dev": true, + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/jsdom/node_modules/webidl-conversions": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-8.0.1.tgz", + "integrity": "sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==", + "dev": true, "license": "BSD-2-Clause", "engines": { - "node": ">=10.4" + "node": ">=20" } }, "node_modules/jsdom/node_modules/whatwg-url": { - "version": "8.7.0", - "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-8.7.0.tgz", - "integrity": "sha512-gAojqb/m9Q8a5IV96E3fHJM70AzCkgt4uXYX2O7EmuyOnLrViCQlsEBmF9UQIu3/aeAIp2U17rtbpZWNntQqdg==", + "version": "16.0.1", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-16.0.1.tgz", + "integrity": "sha512-1to4zXBxmXHV3IiSSEInrreIlu02vUOvrhxJJH5vcxYTBDAx51cqZiKdyTxlecdKNSjj8EcxGBxNf6Vg+945gw==", + "dev": true, "license": "MIT", "dependencies": { - "lodash": "^4.7.0", - "tr46": "^2.1.0", - "webidl-conversions": "^6.1.0" + "@exodus/bytes": "^1.11.0", + "tr46": "^6.0.0", + "webidl-conversions": "^8.0.1" }, "engines": { - "node": ">=10" + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" } }, "node_modules/jsesc": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", - "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==", + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz", + "integrity": "sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==", "license": "MIT", "bin": { "jsesc": "bin/jsesc" @@ -17605,70 +18538,331 @@ "immediate": "~3.0.5" } }, - "node_modules/lilconfig": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-2.1.0.tgz", - "integrity": "sha512-utWOt/GHzuUxnLKxB6dk81RoOeoNeHgbrXiuGk4yyF5qlRz+iIVWu56E2fqGHFrXz0QNUhLB/8nKqvRH66JKGQ==", - "license": "MIT", + "node_modules/lightningcss": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz", + "integrity": "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==", + "dev": true, + "license": "MPL-2.0", + "dependencies": { + "detect-libc": "^2.0.3" + }, "engines": { - "node": ">=10" + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.32.0", + "lightningcss-darwin-arm64": "1.32.0", + "lightningcss-darwin-x64": "1.32.0", + "lightningcss-freebsd-x64": "1.32.0", + "lightningcss-linux-arm-gnueabihf": "1.32.0", + "lightningcss-linux-arm64-gnu": "1.32.0", + "lightningcss-linux-arm64-musl": "1.32.0", + "lightningcss-linux-x64-gnu": "1.32.0", + "lightningcss-linux-x64-musl": "1.32.0", + "lightningcss-win32-arm64-msvc": "1.32.0", + "lightningcss-win32-x64-msvc": "1.32.0" } }, - "node_modules/lines-and-columns": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", - "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", - "license": "MIT" - }, - "node_modules/loader-runner": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/loader-runner/-/loader-runner-4.3.0.tgz", - "integrity": "sha512-3R/1M+yS3j5ou80Me59j7F9IMs4PXs3VqRrm0TU3AbKPxlmpoY1TNscJV/oGJXo8qCatFGTfDbY6W6ipGOYXfg==", - "license": "MIT", + "node_modules/lightningcss-android-arm64": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.32.0.tgz", + "integrity": "sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], "engines": { - "node": ">=6.11.5" + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" } }, - "node_modules/loader-utils": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-2.0.4.tgz", - "integrity": "sha512-xXqpXoINfFhgua9xiqD8fPFHgkoq1mmmpE92WlDbm9rNRd/EbRb+Gqf908T2DMfuHjjJlksiK2RbHVOdD/MqSw==", - "license": "MIT", - "dependencies": { - "big.js": "^5.2.2", - "emojis-list": "^3.0.0", - "json5": "^2.1.2" - }, + "node_modules/lightningcss-darwin-arm64": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.32.0.tgz", + "integrity": "sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], "engines": { - "node": ">=8.9.0" + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" } }, - "node_modules/locate-path": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", - "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", - "license": "MIT", - "dependencies": { - "p-locate": "^5.0.0" - }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.32.0.tgz", + "integrity": "sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], "engines": { - "node": ">=10" + "node": ">= 12.0.0" }, "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "type": "opencollective", + "url": "https://opencollective.com/parcel" } }, - "node_modules/lodash": { - "version": "4.17.21", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", - "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", - "license": "MIT" + "node_modules/lightningcss-freebsd-x64": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.32.0.tgz", + "integrity": "sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } }, - "node_modules/lodash.debounce": { - "version": "4.0.8", - "resolved": "https://registry.npmjs.org/lodash.debounce/-/lodash.debounce-4.0.8.tgz", - "integrity": "sha512-FT1yDzDYEoYWhnSGnpE/4Kj1fLZkDFyqRb7fNt6FdYOSxlUWAtp42Eh6Wb0rGIv/m9Bgo7x4GhQbm5Ys4SG5ow==", - "license": "MIT" + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.32.0.tgz", + "integrity": "sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.32.0.tgz", + "integrity": "sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.32.0.tgz", + "integrity": "sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.32.0.tgz", + "integrity": "sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.32.0.tgz", + "integrity": "sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.32.0.tgz", + "integrity": "sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.32.0.tgz", + "integrity": "sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lilconfig": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-2.1.0.tgz", + "integrity": "sha512-utWOt/GHzuUxnLKxB6dk81RoOeoNeHgbrXiuGk4yyF5qlRz+iIVWu56E2fqGHFrXz0QNUhLB/8nKqvRH66JKGQ==", + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/lines-and-columns": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", + "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", + "license": "MIT" + }, + "node_modules/loader-runner": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/loader-runner/-/loader-runner-4.3.0.tgz", + "integrity": "sha512-3R/1M+yS3j5ou80Me59j7F9IMs4PXs3VqRrm0TU3AbKPxlmpoY1TNscJV/oGJXo8qCatFGTfDbY6W6ipGOYXfg==", + "license": "MIT", + "engines": { + "node": ">=6.11.5" + } + }, + "node_modules/loader-utils": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-2.0.4.tgz", + "integrity": "sha512-xXqpXoINfFhgua9xiqD8fPFHgkoq1mmmpE92WlDbm9rNRd/EbRb+Gqf908T2DMfuHjjJlksiK2RbHVOdD/MqSw==", + "license": "MIT", + "dependencies": { + "big.js": "^5.2.2", + "emojis-list": "^3.0.0", + "json5": "^2.1.2" + }, + "engines": { + "node": ">=8.9.0" + } + }, + "node_modules/locate-path": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", + "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", + "license": "MIT", + "dependencies": { + "p-locate": "^5.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/lodash": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", + "license": "MIT" + }, + "node_modules/lodash.debounce": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/lodash.debounce/-/lodash.debounce-4.0.8.tgz", + "integrity": "sha512-FT1yDzDYEoYWhnSGnpE/4Kj1fLZkDFyqRb7fNt6FdYOSxlUWAtp42Eh6Wb0rGIv/m9Bgo7x4GhQbm5Ys4SG5ow==", + "license": "MIT" }, "node_modules/lodash.memoize": { "version": "4.1.2", @@ -18182,9 +19376,9 @@ } }, "node_modules/nwsapi": { - "version": "2.2.12", - "resolved": "https://registry.npmjs.org/nwsapi/-/nwsapi-2.2.12.tgz", - "integrity": "sha512-qXDmcVlZV4XRtKFzddidpfVP4oMSGhga+xdMc25mv8kaLUHtgzCDhUxkrN8exkGdTlLNaXj7CV3GtON7zuGZ+w==", + "version": "2.2.23", + "resolved": "https://registry.npmjs.org/nwsapi/-/nwsapi-2.2.23.tgz", + "integrity": "sha512-7wfH4sLbt4M0gCDzGE6vzQBo0bfTKjU7Sfpqy/7gs1qBfYz2vEJH6vXcBKpO3+6Yu1telwd0t9HpyOoLEQQbIQ==", "license": "MIT" }, "node_modules/object-assign": { @@ -18361,15 +19555,6 @@ ], "license": "MIT" }, - "node_modules/on-exit-leak-free": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-2.1.2.tgz", - "integrity": "sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA==", - "license": "MIT", - "engines": { - "node": ">=14.0.0" - } - }, "node_modules/on-finished": { "version": "2.4.1", "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", @@ -18643,10 +19828,30 @@ } }, "node_modules/parse5": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-8.0.0.tgz", + "integrity": "sha512-9m4m5GSgXjL4AjumKzq1Fgfp3Z8rsvjRNbnkVwfu2ImRqE5D0LnY2QfDen18FSY9C573YU5XxSapdHZTZ2WolA==", + "dev": true, + "license": "MIT", + "dependencies": { + "entities": "^6.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "node_modules/parse5/node_modules/entities": { "version": "6.0.1", - "resolved": "https://registry.npmjs.org/parse5/-/parse5-6.0.1.tgz", - "integrity": "sha512-Ofn/CTFzRGTTxwpNEs9PP93gXShHcTq255nzRYSKe8AkVpZY7e1fpmTfOyoIvjP5HG7Z2ZM7VS9PPhQGW2pOpw==", - "license": "MIT" + "resolved": "https://registry.npmjs.org/entities/-/entities-6.0.1.tgz", + "integrity": "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } }, "node_modules/parseurl": { "version": "1.3.3", @@ -18737,10 +19942,10 @@ "node": ">=8" } }, - "node_modules/pend": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz", - "integrity": "sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==", + "node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", "dev": true, "license": "MIT" }, @@ -20624,10 +21829,16 @@ } }, "node_modules/psl": { - "version": "1.9.0", - "resolved": "https://registry.npmjs.org/psl/-/psl-1.9.0.tgz", - "integrity": "sha512-E/ZsdU4HLs/68gYzgGTkMicWTLPdAftJLfJFlLUAAKZGkStNU72sZjT66SnMDVOfOWY/YAoiD7Jxa9iHvngcag==", - "license": "MIT" + "version": "1.15.0", + "resolved": "https://registry.npmjs.org/psl/-/psl-1.15.0.tgz", + "integrity": "sha512-JZd3gMVBAVQkSs6HdNZo9Sdo0LNcQeMNP3CozBJb3JYC/QUYZTnKxP+f8oWRX4rHP5EurWxqAHTSwUCjlNKa1w==", + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "funding": { + "url": "https://github.com/sponsors/lupomontero" + } }, "node_modules/pump": { "version": "3.0.4", @@ -21940,15 +23151,16 @@ "license": "ISC" }, "node_modules/saxes": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/saxes/-/saxes-5.0.1.tgz", - "integrity": "sha512-5LBh1Tls8c9xgGjw3QrMwETmTMVk0oFgvrFSvWx62llR2hcEInrKNZ2GZCCuuy2lvWrdl5jhbpeqc5hRYKFOcw==", + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz", + "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==", + "dev": true, "license": "ISC", "dependencies": { "xmlchars": "^2.2.0" }, "engines": { - "node": ">=10" + "node": ">=v12.22.7" } }, "node_modules/scheduler": { @@ -22673,24 +23885,131 @@ "web-vitals": "^2.1.4" } }, - "node_modules/starknet-tokenbound-sdk/node_modules/web-vitals": { - "version": "2.1.4", - "resolved": "https://registry.npmjs.org/web-vitals/-/web-vitals-2.1.4.tgz", - "integrity": "sha512-sVWcwhU5mX6crfI5Vd2dC4qchyTqxV8URinzt25XqVh+bHEPGH4C3NPrNionCP7Obx59wrYEbNlw4Z8sjALzZg==", - "license": "Apache-2.0" - }, - "node_modules/static-eval": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/static-eval/-/static-eval-2.0.2.tgz", - "integrity": "sha512-N/D219Hcr2bPjLxPiV+TQE++Tsmrady7TqAJugLy7Xk1EumfDWS/f5dtBbkRCGE7wKKXuYockQoj8Rm2/pVKyg==", + "node_modules/starknet-tokenbound-sdk/node_modules/@testing-library/dom": { + "version": "8.20.1", + "resolved": "https://registry.npmjs.org/@testing-library/dom/-/dom-8.20.1.tgz", + "integrity": "sha512-/DiOQ5xBxgdYRC8LNk7U+RWat0S3qRLeIw3ZIkMQ9kkVlRmwD/Eg8k8CqIpD6GW7u20JIUOfMKbxtiLutpjQ4g==", "license": "MIT", "dependencies": { - "escodegen": "^1.8.1" + "@babel/code-frame": "^7.10.4", + "@babel/runtime": "^7.12.5", + "@types/aria-query": "^5.0.1", + "aria-query": "5.1.3", + "chalk": "^4.1.0", + "dom-accessibility-api": "^0.5.9", + "lz-string": "^1.5.0", + "pretty-format": "^27.0.2" + }, + "engines": { + "node": ">=12" } }, - "node_modules/static-eval/node_modules/escodegen": { - "version": "1.14.3", - "resolved": "https://registry.npmjs.org/escodegen/-/escodegen-1.14.3.tgz", + "node_modules/starknet-tokenbound-sdk/node_modules/@testing-library/dom/node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/starknet-tokenbound-sdk/node_modules/@testing-library/jest-dom": { + "version": "5.17.0", + "resolved": "https://registry.npmjs.org/@testing-library/jest-dom/-/jest-dom-5.17.0.tgz", + "integrity": "sha512-ynmNeT7asXyH3aSVv4vvX4Rb+0qjOhdNHnO/3vuZNqPmhDpV/+rCSGwQ7bLcmU2cJ4dvoheIO85LQj0IbJHEtg==", + "license": "MIT", + "dependencies": { + "@adobe/css-tools": "^4.0.1", + "@babel/runtime": "^7.9.2", + "@types/testing-library__jest-dom": "^5.9.1", + "aria-query": "^5.0.0", + "chalk": "^3.0.0", + "css.escape": "^1.5.1", + "dom-accessibility-api": "^0.5.6", + "lodash": "^4.17.15", + "redent": "^3.0.0" + }, + "engines": { + "node": ">=8", + "npm": ">=6", + "yarn": ">=1" + } + }, + "node_modules/starknet-tokenbound-sdk/node_modules/@testing-library/react": { + "version": "13.4.0", + "resolved": "https://registry.npmjs.org/@testing-library/react/-/react-13.4.0.tgz", + "integrity": "sha512-sXOGON+WNTh3MLE9rve97ftaZukN3oNf2KjDy7YTx6hcTO2uuLHuCGynMDhFwGw/jYf4OJ2Qk0i4i79qMNNkyw==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.12.5", + "@testing-library/dom": "^8.5.0", + "@types/react-dom": "^18.0.0" + }, + "engines": { + "node": ">=12" + }, + "peerDependencies": { + "react": "^18.0.0", + "react-dom": "^18.0.0" + } + }, + "node_modules/starknet-tokenbound-sdk/node_modules/@testing-library/user-event": { + "version": "13.5.0", + "resolved": "https://registry.npmjs.org/@testing-library/user-event/-/user-event-13.5.0.tgz", + "integrity": "sha512-5Kwtbo3Y/NowpkbRuSepbyMFkZmHgD+vPzYB/RJ4oxt5Gj/avFFBYjhw27cqSVPVw/3a67NK1PbiIr9k4Gwmdg==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.12.5" + }, + "engines": { + "node": ">=10", + "npm": ">=6" + }, + "peerDependencies": { + "@testing-library/dom": ">=7.21.4" + } + }, + "node_modules/starknet-tokenbound-sdk/node_modules/aria-query": { + "version": "5.1.3", + "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.1.3.tgz", + "integrity": "sha512-R5iJ5lkuHybztUfuOAznmboyjWq8O6sqNqtK7CLOqdydi54VNbORp49mb14KbWgG1QD3JFO9hJdZ+y4KutfdOQ==", + "license": "Apache-2.0", + "dependencies": { + "deep-equal": "^2.0.5" + } + }, + "node_modules/starknet-tokenbound-sdk/node_modules/chalk": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-3.0.0.tgz", + "integrity": "sha512-4D3B6Wf41KOYRFdszmDqMCGq5VV/uMAB273JILmO+3jAlh8X4qDtdtgCR3fxtbLEMzSx22QdhnDcJvu2u1fVwg==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/static-eval": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/static-eval/-/static-eval-2.0.2.tgz", + "integrity": "sha512-N/D219Hcr2bPjLxPiV+TQE++Tsmrady7TqAJugLy7Xk1EumfDWS/f5dtBbkRCGE7wKKXuYockQoj8Rm2/pVKyg==", + "license": "MIT", + "dependencies": { + "escodegen": "^1.8.1" + } + }, + "node_modules/static-eval/node_modules/escodegen": { + "version": "1.14.3", + "resolved": "https://registry.npmjs.org/escodegen/-/escodegen-1.14.3.tgz", "integrity": "sha512-qFcX0XJkdg+PB3xjZZG/wKSuT1PnQWx57+TVSjIMmILd2yC/6ByYElPwJnslDsuWuSAp4AwJGumarAAmJch5Kw==", "license": "BSD-2-Clause", "dependencies": { @@ -23939,6 +25258,113 @@ "node": ">=14.14" } }, + "node_modules/throat": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/throat/-/throat-6.0.2.tgz", + "integrity": "sha512-WKexMoJj3vEuK0yFEapj8y64V0A6xcuPuK9Gt1d0R+dzCSJc0lHqQytAbSB4cDAK0dWh4T0E2ETkoLE2WZ41OQ==", + "license": "MIT" + }, + "node_modules/thunky": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/thunky/-/thunky-1.1.0.tgz", + "integrity": "sha512-eHY7nBftgThBqOyHGVN+l8gF0BucP09fMo0oO/Lb0w1OF80dJv+lDVpXG60WMQvkcxAkNybKsrEIE3ZtKGmPrA==", + "license": "MIT" + }, + "node_modules/tinybench": { + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", + "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinyexec": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.0.4.tgz", + "integrity": "sha512-u9r3uZC0bdpGOXtlxUIdwf9pkmvhqJdrVCH9fapQtgy/OeTTMZ1nqH7agtvEfmGui6e1XxjcdrlxvxJvc3sMqw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.15", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz", + "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.3" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tinyglobby/node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/tinyglobby/node_modules/picomatch": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz", + "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/tinyrainbow": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.1.0.tgz", + "integrity": "sha512-Bf+ILmBgretUrdJxzXM0SgXLZ3XfiaUuOj/IKQHuTXip+05Xn+uyEYdVg0kYDipTBcLrCVyUzAPz7QmArb0mmw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tldts": { + "version": "7.0.27", + "resolved": "https://registry.npmjs.org/tldts/-/tldts-7.0.27.tgz", + "integrity": "sha512-I4FZcVFcqCRuT0ph6dCDpPuO4Xgzvh+spkcTr1gK7peIvxWauoloVO0vuy1FQnijT63ss6AsHB6+OIM4aXHbPg==", + "dev": true, + "license": "MIT", + "dependencies": { + "tldts-core": "^7.0.27" + }, + "bin": { + "tldts": "bin/cli.js" + } + }, + "node_modules/tldts-core": { + "version": "7.0.27", + "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-7.0.27.tgz", + "integrity": "sha512-YQ7uPjgWUibIK6DW5lrKujGwUKhLevU4hcGbP5O6TcIUb+oTjJYJVWPS4nZsIHrEEEG6myk/oqAJUEQmpZrHsg==", + "dev": true, + "license": "MIT" + }, "node_modules/tmpl": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/tmpl/-/tmpl-1.0.5.tgz", @@ -23977,27 +25403,16 @@ } }, "node_modules/tough-cookie": { - "version": "4.1.4", - "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-4.1.4.tgz", - "integrity": "sha512-Loo5UUvLD9ScZ6jh8beX1T6sO1w2/MpCRpEP7V280GKMVUQ0Jzar2U3UJPsrdbziLEMMhu3Ujnq//rhiFuIeag==", + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-6.0.1.tgz", + "integrity": "sha512-LktZQb3IeoUWB9lqR5EWTHgW/VTITCXg4D21M+lvybRVdylLrRMnqaIONLVb5mav8vM19m44HIcGq4qASeu2Qw==", + "dev": true, "license": "BSD-3-Clause", "dependencies": { - "psl": "^1.1.33", - "punycode": "^2.1.1", - "universalify": "^0.2.0", - "url-parse": "^1.5.3" + "tldts": "^7.0.5" }, "engines": { - "node": ">=6" - } - }, - "node_modules/tough-cookie/node_modules/universalify": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.2.0.tgz", - "integrity": "sha512-CJ1QgKmNg3CwvAv/kOFmtnEN05f0D/cn9QntgNOQlQF9dgvVTHj3t+8JPdjqawCHk7V/KA+fbUqzZ9XWhcqPUg==", - "license": "MIT", - "engines": { - "node": ">= 4.0.0" + "node": ">=16" } }, "node_modules/tr46": { @@ -24256,6 +25671,16 @@ "integrity": "sha512-hEQt0+ZLDVUMhebKxL4x1BTtDY7bavVofhZ9KZ4aI26X9SRaE+Y3m83XUL1UP2jn8ynjndwCCpEHdUG+9pP1Tw==", "license": "MIT" }, + "node_modules/undici": { + "version": "7.24.6", + "resolved": "https://registry.npmjs.org/undici/-/undici-7.24.6.tgz", + "integrity": "sha512-Xi4agocCbRzt0yYMZGMA6ApD7gvtUFaxm4ZmeacWI4cZxaF6C+8I8QfofC20NAePiB/IcvZmzkJ7XPa471AEtA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20.18.1" + } + }, "node_modules/undici-types": { "version": "7.18.2", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.18.2.tgz", @@ -24486,16 +25911,6 @@ "integrity": "sha512-xNvxJEOUiWPGhUuUdQgAJPKOOJfGnIyKySOc09XkKsgdUV/3E2zvwZYdejjmRgPCgcym1juLH3226yA7sEFJKQ==", "license": "0BSD" }, - "node_modules/use-sync-external-store": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.6.0.tgz", - "integrity": "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w==", - "dev": true, - "license": "MIT", - "peerDependencies": { - "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" - } - }, "node_modules/util-deprecate": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", @@ -24561,169 +25976,565 @@ "integrity": "sha512-ASFBup0Mz1uyiIjANan1jzLQami9z1PoYSZCiiYW2FczPbenXc45FZdBZLzOT+r6+iciuEModtmCti+hjaAk0A==", "license": "MIT" }, - "node_modules/vary": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", - "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/vite": { + "version": "5.3.4", + "resolved": "https://registry.npmjs.org/vite/-/vite-5.3.4.tgz", + "integrity": "sha512-Cw+7zL3ZG9/NZBB8C+8QbQZmR54GwqIz+WMI4b3JgdYJvX+ny9AjJXqkGQlDXSXRP9rP0B4tbciRMOVEKulVOA==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.21.3", + "postcss": "^8.4.39", + "rollup": "^4.13.0" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^18.0.0 || >=20.0.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^18.0.0 || >=20.0.0", + "less": "*", + "lightningcss": "^1.21.0", + "sass": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.4.0" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + } + } + }, + "node_modules/vitest": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.2.tgz", + "integrity": "sha512-xjR1dMTVHlFLh98JE3i/f/WePqJsah4A0FK9cc8Ehp9Udk0AZk6ccpIZhh1qJ/yxVWRZ+Q54ocnD8TXmkhspGg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/expect": "4.1.2", + "@vitest/mocker": "4.1.2", + "@vitest/pretty-format": "4.1.2", + "@vitest/runner": "4.1.2", + "@vitest/snapshot": "4.1.2", + "@vitest/spy": "4.1.2", + "@vitest/utils": "4.1.2", + "es-module-lexer": "^2.0.0", + "expect-type": "^1.3.0", + "magic-string": "^0.30.21", + "obug": "^2.1.1", + "pathe": "^2.0.3", + "picomatch": "^4.0.3", + "std-env": "^4.0.0-rc.1", + "tinybench": "^2.9.0", + "tinyexec": "^1.0.2", + "tinyglobby": "^0.2.15", + "tinyrainbow": "^3.1.0", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0", + "why-is-node-running": "^2.3.0" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^20.0.0 || ^22.0.0 || >=24.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@opentelemetry/api": "^1.9.0", + "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0", + "@vitest/browser-playwright": "4.1.2", + "@vitest/browser-preview": "4.1.2", + "@vitest/browser-webdriverio": "4.1.2", + "@vitest/ui": "4.1.2", + "happy-dom": "*", + "jsdom": "*", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@opentelemetry/api": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser-playwright": { + "optional": true + }, + "@vitest/browser-preview": { + "optional": true + }, + "@vitest/browser-webdriverio": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + }, + "vite": { + "optional": false + } + } + }, + "node_modules/vitest/node_modules/@esbuild/aix-ppc64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.4.tgz", + "integrity": "sha512-cQPwL2mp2nSmHHJlCyoXgHGhbEPMrEEU5xhkcy3Hs/O7nGZqEpZ2sUtLaL9MORLtDfRvVl2/3PAuEkYZH0Ty8Q==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "peer": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/vitest/node_modules/@esbuild/android-arm": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.4.tgz", + "integrity": "sha512-X9bUgvxiC8CHAGKYufLIHGXPJWnr0OCdR0anD2e21vdvgCI8lIfqFbnoeOz7lBjdrAGUhqLZLcQo6MLhTO2DKQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "peer": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/vitest/node_modules/@esbuild/android-arm64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.4.tgz", + "integrity": "sha512-gdLscB7v75wRfu7QSm/zg6Rx29VLdy9eTr2t44sfTW7CxwAtQghZ4ZnqHk3/ogz7xao0QAgrkradbBzcqFPasw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "peer": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/vitest/node_modules/@esbuild/android-x64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.4.tgz", + "integrity": "sha512-PzPFnBNVF292sfpfhiyiXCGSn9HZg5BcAz+ivBuSsl6Rk4ga1oEXAamhOXRFyMcjwr2DVtm40G65N3GLeH1Lvw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "peer": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/vitest/node_modules/@esbuild/darwin-arm64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.4.tgz", + "integrity": "sha512-b7xaGIwdJlht8ZFCvMkpDN6uiSmnxxK56N2GDTMYPr2/gzvfdQN8rTfBsvVKmIVY/X7EM+/hJKEIbbHs9oA4tQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "peer": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/vitest/node_modules/@esbuild/darwin-x64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.4.tgz", + "integrity": "sha512-sR+OiKLwd15nmCdqpXMnuJ9W2kpy0KigzqScqHI3Hqwr7IXxBp3Yva+yJwoqh7rE8V77tdoheRYataNKL4QrPw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "peer": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/vitest/node_modules/@esbuild/freebsd-arm64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.4.tgz", + "integrity": "sha512-jnfpKe+p79tCnm4GVav68A7tUFeKQwQyLgESwEAUzyxk/TJr4QdGog9sqWNcUbr/bZt/O/HXouspuQDd9JxFSw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "peer": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/vitest/node_modules/@esbuild/freebsd-x64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.4.tgz", + "integrity": "sha512-2kb4ceA/CpfUrIcTUl1wrP/9ad9Atrp5J94Lq69w7UwOMolPIGrfLSvAKJp0RTvkPPyn6CIWrNy13kyLikZRZQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "peer": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/vitest/node_modules/@esbuild/linux-arm": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.4.tgz", + "integrity": "sha512-aBYgcIxX/wd5n2ys0yESGeYMGF+pv6g0DhZr3G1ZG4jMfruU9Tl1i2Z+Wnj9/KjGz1lTLCcorqE2viePZqj4Eg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/vitest/node_modules/@esbuild/linux-arm64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.4.tgz", + "integrity": "sha512-7nQOttdzVGth1iz57kxg9uCz57dxQLHWxopL6mYuYthohPKEK0vU0C3O21CcBK6KDlkYVcnDXY099HcCDXd9dA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/vitest/node_modules/@esbuild/linux-ia32": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.4.tgz", + "integrity": "sha512-oPtixtAIzgvzYcKBQM/qZ3R+9TEUd1aNJQu0HhGyqtx6oS7qTpvjheIWBbes4+qu1bNlo2V4cbkISr8q6gRBFA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/vitest/node_modules/@esbuild/linux-loong64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.4.tgz", + "integrity": "sha512-8mL/vh8qeCoRcFH2nM8wm5uJP+ZcVYGGayMavi8GmRJjuI3g1v6Z7Ni0JJKAJW+m0EtUuARb6Lmp4hMjzCBWzA==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/vitest/node_modules/@esbuild/linux-mips64el": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.4.tgz", + "integrity": "sha512-1RdrWFFiiLIW7LQq9Q2NES+HiD4NyT8Itj9AUeCl0IVCA459WnPhREKgwrpaIfTOe+/2rdntisegiPWn/r/aAw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/vitest/node_modules/@esbuild/linux-ppc64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.4.tgz", + "integrity": "sha512-tLCwNG47l3sd9lpfyx9LAGEGItCUeRCWeAx6x2Jmbav65nAwoPXfewtAdtbtit/pJFLUWOhpv0FpS6GQAmPrHA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/vitest/node_modules/@esbuild/linux-riscv64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.4.tgz", + "integrity": "sha512-BnASypppbUWyqjd1KIpU4AUBiIhVr6YlHx/cnPgqEkNoVOhHg+YiSVxM1RLfiy4t9cAulbRGTNCKOcqHrEQLIw==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/vitest/node_modules/@esbuild/linux-s390x": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.4.tgz", + "integrity": "sha512-+eUqgb/Z7vxVLezG8bVB9SfBie89gMueS+I0xYh2tJdw3vqA/0ImZJ2ROeWwVJN59ihBeZ7Tu92dF/5dy5FttA==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/vitest/node_modules/@esbuild/linux-x64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.4.tgz", + "integrity": "sha512-S5qOXrKV8BQEzJPVxAwnryi2+Iq5pB40gTEIT69BQONqR7JH1EPIcQ/Uiv9mCnn05jff9umq/5nqzxlqTOg9NA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/vitest/node_modules/@esbuild/netbsd-x64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.4.tgz", + "integrity": "sha512-RugOvOdXfdyi5Tyv40kgQnI0byv66BFgAqjdgtAKqHoZTbTF2QqfQrFwa7cHEORJf6X2ht+l9ABLMP0dnKYsgg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "peer": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/vitest/node_modules/@esbuild/openbsd-x64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.4.tgz", + "integrity": "sha512-u8fg/jQ5aQDfsnIV6+KwLOf1CmJnfu1ShpwqdwC0uA7ZPwFws55Ngc12vBdeUdnuWoQYx/SOQLGDcdlfXhYmXQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "peer": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/vitest/node_modules/@esbuild/sunos-x64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.4.tgz", + "integrity": "sha512-/gOzgaewZJfeJTlsWhvUEmUG4tWEY2Spp5M20INYRg2ZKl9QPO3QEEgPeRtLjEWSW8FilRNacPOg8R1uaYkA6g==", + "cpu": [ + "x64" + ], + "dev": true, "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "peer": true, "engines": { - "node": ">= 0.8" + "node": ">=18" } }, - "node_modules/vite": { - "version": "5.3.4", - "resolved": "https://registry.npmjs.org/vite/-/vite-5.3.4.tgz", - "integrity": "sha512-Cw+7zL3ZG9/NZBB8C+8QbQZmR54GwqIz+WMI4b3JgdYJvX+ny9AjJXqkGQlDXSXRP9rP0B4tbciRMOVEKulVOA==", + "node_modules/vitest/node_modules/@esbuild/win32-arm64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.4.tgz", + "integrity": "sha512-Z9SExBg2y32smoDQdf1HRwHRt6vAHLXcxD2uGgO/v2jK7Y718Ix4ndsbNMU/+1Qiem9OiOdaqitioZwxivhXYg==", + "cpu": [ + "arm64" + ], "dev": true, "license": "MIT", - "dependencies": { - "esbuild": "^0.21.3", - "postcss": "^8.4.39", - "rollup": "^4.13.0" - }, - "bin": { - "vite": "bin/vite.js" - }, + "optional": true, + "os": [ + "win32" + ], + "peer": true, "engines": { - "node": "^18.0.0 || >=20.0.0" - }, - "funding": { - "url": "https://github.com/vitejs/vite?sponsor=1" - }, - "optionalDependencies": { - "fsevents": "~2.3.3" - }, - "peerDependencies": { - "@types/node": "^18.0.0 || >=20.0.0", - "less": "*", - "lightningcss": "^1.21.0", - "sass": "*", - "stylus": "*", - "sugarss": "*", - "terser": "^5.4.0" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - }, - "less": { - "optional": true - }, - "lightningcss": { - "optional": true - }, - "sass": { - "optional": true - }, - "stylus": { - "optional": true - }, - "sugarss": { - "optional": true - }, - "terser": { - "optional": true - } + "node": ">=18" } }, - "node_modules/vitest": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.2.tgz", - "integrity": "sha512-xjR1dMTVHlFLh98JE3i/f/WePqJsah4A0FK9cc8Ehp9Udk0AZk6ccpIZhh1qJ/yxVWRZ+Q54ocnD8TXmkhspGg==", + "node_modules/vitest/node_modules/@esbuild/win32-ia32": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.4.tgz", + "integrity": "sha512-DAyGLS0Jz5G5iixEbMHi5KdiApqHBWMGzTtMiJ72ZOLhbu/bzxgAe8Ue8CTS3n3HbIUHQz/L51yMdGMeoxXNJw==", + "cpu": [ + "ia32" + ], "dev": true, "license": "MIT", - "dependencies": { - "@vitest/expect": "4.1.2", - "@vitest/mocker": "4.1.2", - "@vitest/pretty-format": "4.1.2", - "@vitest/runner": "4.1.2", - "@vitest/snapshot": "4.1.2", - "@vitest/spy": "4.1.2", - "@vitest/utils": "4.1.2", - "es-module-lexer": "^2.0.0", - "expect-type": "^1.3.0", - "magic-string": "^0.30.21", - "obug": "^2.1.1", - "pathe": "^2.0.3", - "picomatch": "^4.0.3", - "std-env": "^4.0.0-rc.1", - "tinybench": "^2.9.0", - "tinyexec": "^1.0.2", - "tinyglobby": "^0.2.15", - "tinyrainbow": "^3.1.0", - "vite": "^6.0.0 || ^7.0.0 || ^8.0.0", - "why-is-node-running": "^2.3.0" - }, - "bin": { - "vitest": "vitest.mjs" - }, + "optional": true, + "os": [ + "win32" + ], + "peer": true, "engines": { - "node": "^20.0.0 || ^22.0.0 || >=24.0.0" - }, - "funding": { - "url": "https://opencollective.com/vitest" - }, - "peerDependencies": { - "@edge-runtime/vm": "*", - "@opentelemetry/api": "^1.9.0", - "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0", - "@vitest/browser-playwright": "4.1.2", - "@vitest/browser-preview": "4.1.2", - "@vitest/browser-webdriverio": "4.1.2", - "@vitest/ui": "4.1.2", - "happy-dom": "*", - "jsdom": "*", - "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" - }, - "peerDependenciesMeta": { - "@edge-runtime/vm": { - "optional": true - }, - "@opentelemetry/api": { - "optional": true - }, - "@types/node": { - "optional": true - }, - "@vitest/browser-playwright": { - "optional": true - }, - "@vitest/browser-preview": { - "optional": true - }, - "@vitest/browser-webdriverio": { - "optional": true - }, - "@vitest/ui": { - "optional": true - }, - "happy-dom": { - "optional": true - }, - "jsdom": { - "optional": true - }, - "vite": { - "optional": false - } + "node": ">=18" } }, - "node_modules/vitest/node_modules/@vitest/expect": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.2.tgz", - "integrity": "sha512-gbu+7B0YgUJ2nkdsRJrFFW6X7NTP44WlhiclHniUhxADQJH5Szt9mZ9hWnJPJ8YwOK5zUOSSlSvyzRf0u1DSBQ==", + "node_modules/vitest/node_modules/@esbuild/win32-x64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.4.tgz", + "integrity": "sha512-+knoa0BDoeXgkNvvV1vvbZX4+hizelrkwmGJBdT17t8FNPwG2lKemmuMZlmaNQ3ws3DKKCxpb4zRZEIp3UxFCg==", + "cpu": [ + "x64" + ], "dev": true, "license": "MIT", - "dependencies": { - "@standard-schema/spec": "^1.1.0", - "@types/chai": "^5.2.2", - "@vitest/spy": "4.1.2", - "@vitest/utils": "4.1.2", - "chai": "^6.2.2", - "tinyrainbow": "^3.1.0" - }, - "funding": { - "url": "https://opencollective.com/vitest" + "optional": true, + "os": [ + "win32" + ], + "peer": true, + "engines": { + "node": ">=18" } }, "node_modules/vitest/node_modules/@vitest/mocker": { @@ -24753,33 +26564,57 @@ } } }, - "node_modules/vitest/node_modules/@vitest/spy": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.2.tgz", - "integrity": "sha512-DU4fBnbVCJGNBwVA6xSToNXrkZNSiw59H8tcuUspVMsBDBST4nfvsPsEHDHGtWRRnqBERBQu7TrTKskmjqTXKA==", + "node_modules/vitest/node_modules/es-module-lexer": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.0.0.tgz", + "integrity": "sha512-5POEcUuZybH7IdmGsD8wlf0AI55wMecM9rVBTI/qEAy2c1kTOm3DjFYjrBdI2K3BaJjJYfYFeRtM0t9ssnRuxw==", "dev": true, - "license": "MIT", - "funding": { - "url": "https://opencollective.com/vitest" - } + "license": "MIT" }, - "node_modules/vitest/node_modules/chai": { - "version": "6.2.2", - "resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz", - "integrity": "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==", + "node_modules/vitest/node_modules/esbuild": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.4.tgz", + "integrity": "sha512-Rq4vbHnYkK5fws5NF7MYTU68FPRE1ajX7heQ/8QXXWqNgqqJ/GkmmyxIzUnf2Sr/bakf8l54716CcMGHYhMrrQ==", "dev": true, + "hasInstallScript": true, "license": "MIT", + "optional": true, + "peer": true, + "bin": { + "esbuild": "bin/esbuild" + }, "engines": { "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.27.4", + "@esbuild/android-arm": "0.27.4", + "@esbuild/android-arm64": "0.27.4", + "@esbuild/android-x64": "0.27.4", + "@esbuild/darwin-arm64": "0.27.4", + "@esbuild/darwin-x64": "0.27.4", + "@esbuild/freebsd-arm64": "0.27.4", + "@esbuild/freebsd-x64": "0.27.4", + "@esbuild/linux-arm": "0.27.4", + "@esbuild/linux-arm64": "0.27.4", + "@esbuild/linux-ia32": "0.27.4", + "@esbuild/linux-loong64": "0.27.4", + "@esbuild/linux-mips64el": "0.27.4", + "@esbuild/linux-ppc64": "0.27.4", + "@esbuild/linux-riscv64": "0.27.4", + "@esbuild/linux-s390x": "0.27.4", + "@esbuild/linux-x64": "0.27.4", + "@esbuild/netbsd-arm64": "0.27.4", + "@esbuild/netbsd-x64": "0.27.4", + "@esbuild/openbsd-arm64": "0.27.4", + "@esbuild/openbsd-x64": "0.27.4", + "@esbuild/openharmony-arm64": "0.27.4", + "@esbuild/sunos-x64": "0.27.4", + "@esbuild/win32-arm64": "0.27.4", + "@esbuild/win32-ia32": "0.27.4", + "@esbuild/win32-x64": "0.27.4" } }, - "node_modules/vitest/node_modules/es-module-lexer": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.0.0.tgz", - "integrity": "sha512-5POEcUuZybH7IdmGsD8wlf0AI55wMecM9rVBTI/qEAy2c1kTOm3DjFYjrBdI2K3BaJjJYfYFeRtM0t9ssnRuxw==", - "dev": true, - "license": "MIT" - }, "node_modules/vitest/node_modules/estree-walker": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", @@ -24891,6 +26726,24 @@ } } }, + "node_modules/vitest/node_modules/yaml": { + "version": "2.8.3", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.8.3.tgz", + "integrity": "sha512-AvbaCLOO2Otw/lW5bmh9d/WEdcDFdQp2Z2ZUH3pX9U2ihyUY0nvLv7J6TrWowklRGPYbB/IuIMfYgxaCPg5Bpg==", + "dev": true, + "license": "ISC", + "optional": true, + "peer": true, + "bin": { + "yaml": "bin.mjs" + }, + "engines": { + "node": ">= 14.6" + }, + "funding": { + "url": "https://github.com/sponsors/eemeli" + } + }, "node_modules/w3c-hr-time": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/w3c-hr-time/-/w3c-hr-time-1.0.2.tgz", @@ -24902,15 +26755,16 @@ } }, "node_modules/w3c-xmlserializer": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-2.0.0.tgz", - "integrity": "sha512-4tzD0mF8iSiMiNs30BiLO3EpfGLZUT2MSX/G+o7ZywDzliWQ3OPtTZ0PTC3B3ca1UAf4cJMHB+2Bf56EriJuRA==", + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz", + "integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==", + "dev": true, "license": "MIT", "dependencies": { - "xml-name-validator": "^3.0.0" + "xml-name-validator": "^5.0.0" }, "engines": { - "node": ">=10" + "node": ">=18" } }, "node_modules/walker": { @@ -25226,6 +27080,7 @@ "version": "1.0.5", "resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-1.0.5.tgz", "integrity": "sha512-b5lim54JOPN9HtzvK9HFXvBma/rnfFeqsic0hSpjtDbVxR3dJKLc+KB4V6GgiGOvl7CY/KNh8rxSo9DKQrnUEw==", + "deprecated": "Use @exodus/bytes instead for a more spec-conformant and faster implementation", "license": "MIT", "dependencies": { "iconv-lite": "0.4.24" @@ -25250,10 +27105,14 @@ "license": "MIT" }, "node_modules/whatwg-mimetype": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-2.3.0.tgz", - "integrity": "sha512-M4yMwr6mAnQz76TbJm914+gPpB/nCwvZbJU28cUD6dR004SAxDLOOSUaB1JDRqLtaOV/vi0IC5lEAGFgrjGv/g==", - "license": "MIT" + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-5.0.0.tgz", + "integrity": "sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20" + } }, "node_modules/whatwg-url": { "version": "5.0.0", @@ -25954,10 +27813,14 @@ } }, "node_modules/xml-name-validator": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-3.0.0.tgz", - "integrity": "sha512-A5CUptxDsvxKJEU3yO6DuWBSJz/qizqzJKOMIfUJHETbBw/sFaDxgd6fxm1ewUaM0jZ444Fc5vC5ROYurg/4Pw==", - "license": "Apache-2.0" + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz", + "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18" + } }, "node_modules/xmlchars": { "version": "2.2.0", diff --git a/client/package.json b/client/package.json index 6dca333d..2005c6a1 100644 --- a/client/package.json +++ b/client/package.json @@ -49,10 +49,13 @@ "web-vitals": "^4.0.0" }, "devDependencies": { - "@axe-core/cli": "^4.11.1", + "@testing-library/jest-dom": "^6.9.1", + "@testing-library/react": "^16.3.2", + "@testing-library/user-event": "^14.6.1", "@types/react": "^18.3.3", "@types/react-dom": "^18.3.0", "@vitejs/plugin-react-swc": "^3.5.0", + "@vitest/coverage-v8": "^4.1.2", "autoprefixer": "^10.4.19", "eslint": "^8.57.0", "eslint-config-prettier": "^10.1.8", @@ -60,21 +63,11 @@ "eslint-plugin-react": "^7.34.3", "eslint-plugin-react-hooks": "^4.6.2", "eslint-plugin-react-refresh": "^0.4.7", + "jsdom": "^29.0.1", "postcss": "^8.4.39", "prettier": "^3.8.1", "tailwindcss": "^3.4.6", "vite": "^5.3.4", - "storybook": "^10.3.3", - "@storybook/react-vite": "^10.3.3", - "@chromatic-com/storybook": "^5.1.1", - "@storybook/addon-vitest": "^10.3.3", - "@storybook/addon-a11y": "^10.3.3", - "@storybook/addon-docs": "^10.3.3", - "@storybook/addon-onboarding": "^10.3.3", - "eslint-plugin-storybook": "^10.3.3", - "vitest": "^4.1.2", - "playwright": "^1.58.2", - "@vitest/browser-playwright": "^4.1.2", - "@vitest/coverage-v8": "^4.1.2" + "vitest": "^4.1.2" } } diff --git a/client/src/Components/dashboard/reschedule-dialog.jsx b/client/src/Components/dashboard/reschedule-dialog.jsx index 8c85d592..080f4adf 100644 --- a/client/src/Components/dashboard/reschedule-dialog.jsx +++ b/client/src/Components/dashboard/reschedule-dialog.jsx @@ -56,16 +56,16 @@ export function RescheduleDialog({ id }) { Reschedule Event - change the start and end date of your event + change the start and end date of your event
-
-
 + + ❯ Object.getElementError node_modules/@testing-library/dom/dist/config.js:37:19 + ❯ getElementError node_modules/@testing-library/dom/dist/query-helpers.js:20:35 + ❯ getMultipleElementsFoundError node_modules/@testing-library/dom/dist/query-helpers.js:23:10 + ❯ node_modules/@testing-library/dom/dist/query-helpers.js:55:13 + ❯ getByText node_modules/@testing-library/dom/dist/query-helpers.js:95:19 + ❯ src/__tests__/FeaturesSection.test.jsx:28:23 +  26| it('renders all feature cards defined in data', () => { +  27| render(<FeaturesSection />); +  28| expect(screen.getByText(/Event Management/i)).toBeInTheDocumen… +  | ^ +  29| expect(screen.getByText(/Real Time Analytics/i)).toBeInTheDocu… +  30| expect(screen.getByText(/POAP Integration/i)).toBeInTheDocumen… + +⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[2/2]⎯ + + + Test Files  2 failed | 7 passed (9) + Tests  2 failed | 22 passed (24) + Start at  07:44:44 + Duration  21.40s (transform 1.08s, setup 7.08s, import 3.51s, tests 10.27s, environment 30.10s) + diff --git a/client/vite.config.js b/client/vite.config.js index 57456f9a..81c2a3ee 100644 --- a/client/vite.config.js +++ b/client/vite.config.js @@ -1,37 +1,23 @@ -/// -import { defineConfig } from 'vite'; -import react from '@vitejs/plugin-react-swc'; +// vite.config.js +import { defineConfig } from 'vite' +import react from '@vitejs/plugin-react-swc' -// https://vitejs.dev/config/ -import path from 'node:path'; -import { fileURLToPath } from 'node:url'; -import { storybookTest } from '@storybook/addon-vitest/vitest-plugin'; -import { playwright } from '@vitest/browser-playwright'; -const dirname = typeof __dirname !== 'undefined' ? __dirname : path.dirname(fileURLToPath(import.meta.url)); - -// More info at: https://storybook.js.org/docs/next/writing-tests/integrations/vitest-addon export default defineConfig({ plugins: [react()], test: { - projects: [{ - extends: true, - plugins: [ - // The plugin will run tests for the stories defined in your Storybook config - // See options at: https://storybook.js.org/docs/next/writing-tests/integrations/vitest-addon#storybooktest - storybookTest({ - configDir: path.join(dirname, '.storybook') - })], - test: { - name: 'storybook', - browser: { - enabled: true, - headless: true, - provider: playwright({}), - instances: [{ - browser: 'chromium' - }] - } - } - }] - } -}); \ No newline at end of file + globals: true, + environment: 'jsdom', + setupFiles: './src/test/setup.js', + testTimeout: 60000, + coverage: { + provider: 'v8', + reporter: ['text', 'json', 'html'], + thresholds: { + lines: 80, + functions: 80, + branches: 80, + statements: 80, + }, + }, + }, +}) diff --git a/node_modules/.bin/lz-string b/node_modules/.bin/lz-string new file mode 120000 index 00000000..14bd70d2 --- /dev/null +++ b/node_modules/.bin/lz-string @@ -0,0 +1 @@ +../lz-string/bin/bin.js \ No newline at end of file diff --git a/node_modules/.bin/nanoid b/node_modules/.bin/nanoid new file mode 120000 index 00000000..e2be547b --- /dev/null +++ b/node_modules/.bin/nanoid @@ -0,0 +1 @@ +../nanoid/bin/nanoid.cjs \ No newline at end of file diff --git a/node_modules/.bin/parser b/node_modules/.bin/parser new file mode 120000 index 00000000..ce7bf97e --- /dev/null +++ b/node_modules/.bin/parser @@ -0,0 +1 @@ +../@babel/parser/bin/babel-parser.js \ No newline at end of file diff --git a/node_modules/.bin/rolldown b/node_modules/.bin/rolldown new file mode 120000 index 00000000..7725012c --- /dev/null +++ b/node_modules/.bin/rolldown @@ -0,0 +1 @@ +../rolldown/bin/cli.mjs \ No newline at end of file diff --git a/node_modules/.bin/semver b/node_modules/.bin/semver new file mode 120000 index 00000000..5aaadf42 --- /dev/null +++ b/node_modules/.bin/semver @@ -0,0 +1 @@ +../semver/bin/semver.js \ No newline at end of file diff --git a/node_modules/.bin/specificity b/node_modules/.bin/specificity new file mode 120000 index 00000000..ee9d3afb --- /dev/null +++ b/node_modules/.bin/specificity @@ -0,0 +1 @@ +../@bramus/specificity/bin/cli.js \ No newline at end of file diff --git a/node_modules/.bin/tldts b/node_modules/.bin/tldts new file mode 120000 index 00000000..85001241 --- /dev/null +++ b/node_modules/.bin/tldts @@ -0,0 +1 @@ +../tldts/bin/cli.js \ No newline at end of file diff --git a/node_modules/.bin/vite b/node_modules/.bin/vite new file mode 120000 index 00000000..6d1e3bea --- /dev/null +++ b/node_modules/.bin/vite @@ -0,0 +1 @@ +../vite/bin/vite.js \ No newline at end of file diff --git a/node_modules/.bin/vitest b/node_modules/.bin/vitest new file mode 120000 index 00000000..22734979 --- /dev/null +++ b/node_modules/.bin/vitest @@ -0,0 +1 @@ +../vitest/vitest.mjs \ No newline at end of file diff --git a/node_modules/.bin/why-is-node-running b/node_modules/.bin/why-is-node-running new file mode 120000 index 00000000..f08a594c --- /dev/null +++ b/node_modules/.bin/why-is-node-running @@ -0,0 +1 @@ +../why-is-node-running/cli.js \ No newline at end of file diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json new file mode 100644 index 00000000..9c8a2853 --- /dev/null +++ b/node_modules/.package-lock.json @@ -0,0 +1,1771 @@ +{ + "name": "tokenbound_impl", + "lockfileVersion": 3, + "requires": true, + "packages": { + "node_modules/@adobe/css-tools": { + "version": "4.4.4", + "resolved": "https://registry.npmjs.org/@adobe/css-tools/-/css-tools-4.4.4.tgz", + "integrity": "sha512-Elp+iwUx5rN5+Y8xLt5/GRoG20WGoDCQ/1Fb+1LiGtvwbDavuSk0jhD/eZdckHAuzcDzccnkv+rEjyWfRx18gg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@asamuzakjp/css-color": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-5.1.1.tgz", + "integrity": "sha512-iGWN8E45Ws0XWx3D44Q1t6vX2LqhCKcwfmwBYCDsFrYFS6m4q/Ks61L2veETaLv+ckDC6+dTETJoaAAb7VjLiw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@csstools/css-calc": "^3.1.1", + "@csstools/css-color-parser": "^4.0.2", + "@csstools/css-parser-algorithms": "^4.0.0", + "@csstools/css-tokenizer": "^4.0.0", + "lru-cache": "^11.2.7" + }, + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + } + }, + "node_modules/@asamuzakjp/dom-selector": { + "version": "7.0.4", + "resolved": "https://registry.npmjs.org/@asamuzakjp/dom-selector/-/dom-selector-7.0.4.tgz", + "integrity": "sha512-jXR6x4AcT3eIrS2fSNAwJpwirOkGcd+E7F7CP3zjdTqz9B/2huHOL8YJZBgekKwLML+u7qB/6P1LXQuMScsx0w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@asamuzakjp/nwsapi": "^2.3.9", + "bidi-js": "^1.0.3", + "css-tree": "^3.2.1", + "is-potential-custom-element-name": "^1.0.1", + "lru-cache": "^11.2.7" + }, + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + } + }, + "node_modules/@asamuzakjp/nwsapi": { + "version": "2.3.9", + "resolved": "https://registry.npmjs.org/@asamuzakjp/nwsapi/-/nwsapi-2.3.9.tgz", + "integrity": "sha512-n8GuYSrI9bF7FFZ/SjhwevlHc8xaVlb/7HmHelnc/PZXBD2ZR49NnN9sMMuDdEGPeeRQ5d0hqlSlEpgCX3Wl0Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/@babel/code-frame": { + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.0.tgz", + "integrity": "sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@babel/helper-validator-identifier": "^7.28.5", + "js-tokens": "^4.0.0", + "picocolors": "^1.1.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz", + "integrity": "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz", + "integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.29.2", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.2.tgz", + "integrity": "sha512-4GgRzy/+fsBa72/RZVJmGKPmZu9Byn8o4MoLpmNe1m8ZfYnz5emHLQz3U4gLud6Zwl0RZIcgiLD7Uq7ySFuDLA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.29.0" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/runtime": { + "version": "7.29.2", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.2.tgz", + "integrity": "sha512-JiDShH45zKHWyGe4ZNVRrCjBz8Nh9TMmZG1kh4QTK8hCBTWBi8Da+i7s1fJw7/lYpM4ccepSNfqzZ/QvABBi5g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/types": { + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.0.tgz", + "integrity": "sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.27.1", + "@babel/helper-validator-identifier": "^7.28.5" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@bcoe/v8-coverage": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-1.0.2.tgz", + "integrity": "sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@bramus/specificity": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/@bramus/specificity/-/specificity-2.4.2.tgz", + "integrity": "sha512-ctxtJ/eA+t+6q2++vj5j7FYX3nRu311q1wfYH3xjlLOsczhlhxAg2FWNUXhpGvAw3BWo1xBcvOV6/YLc2r5FJw==", + "dev": true, + "license": "MIT", + "dependencies": { + "css-tree": "^3.0.0" + }, + "bin": { + "specificity": "bin/cli.js" + } + }, + "node_modules/@csstools/color-helpers": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-6.0.2.tgz", + "integrity": "sha512-LMGQLS9EuADloEFkcTBR3BwV/CGHV7zyDxVRtVDTwdI2Ca4it0CCVTT9wCkxSgokjE5Ho41hEPgb8OEUwoXr6Q==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT-0", + "engines": { + "node": ">=20.19.0" + } + }, + "node_modules/@csstools/css-calc": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-3.1.1.tgz", + "integrity": "sha512-HJ26Z/vmsZQqs/o3a6bgKslXGFAungXGbinULZO3eMsOyNJHeBBZfup5FiZInOghgoM4Hwnmw+OgbJCNg1wwUQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=20.19.0" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^4.0.0", + "@csstools/css-tokenizer": "^4.0.0" + } + }, + "node_modules/@csstools/css-color-parser": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-4.0.2.tgz", + "integrity": "sha512-0GEfbBLmTFf0dJlpsNU7zwxRIH0/BGEMuXLTCvFYxuL1tNhqzTbtnFICyJLTNK4a+RechKP75e7w42ClXSnJQw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "dependencies": { + "@csstools/color-helpers": "^6.0.2", + "@csstools/css-calc": "^3.1.1" + }, + "engines": { + "node": ">=20.19.0" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^4.0.0", + "@csstools/css-tokenizer": "^4.0.0" + } + }, + "node_modules/@csstools/css-parser-algorithms": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-4.0.0.tgz", + "integrity": "sha512-+B87qS7fIG3L5h3qwJ/IFbjoVoOe/bpOdh9hAjXbvx0o8ImEmUsGXN0inFOnk2ChCFgqkkGFQ+TpM5rbhkKe4w==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=20.19.0" + }, + "peerDependencies": { + "@csstools/css-tokenizer": "^4.0.0" + } + }, + "node_modules/@csstools/css-syntax-patches-for-csstree": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@csstools/css-syntax-patches-for-csstree/-/css-syntax-patches-for-csstree-1.1.2.tgz", + "integrity": "sha512-5GkLzz4prTIpoyeUiIu3iV6CSG3Plo7xRVOFPKI7FVEJ3mZ0A8SwK0XU3Gl7xAkiQ+mDyam+NNp875/C5y+jSA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT-0", + "peerDependencies": { + "css-tree": "^3.2.1" + }, + "peerDependenciesMeta": { + "css-tree": { + "optional": true + } + } + }, + "node_modules/@csstools/css-tokenizer": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-4.0.0.tgz", + "integrity": "sha512-QxULHAm7cNu72w97JUNCBFODFaXpbDg+dP8b/oWFAZ2MTRppA3U00Y2L1HqaS4J6yBqxwa/Y3nMBaxVKbB/NsA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=20.19.0" + } + }, + "node_modules/@exodus/bytes": { + "version": "1.15.0", + "resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.15.0.tgz", + "integrity": "sha512-UY0nlA+feH81UGSHv92sLEPLCeZFjXOuHhrIo0HQydScuQc8s0A7kL/UdgwgDq8g8ilksmuoF35YVTNphV2aBQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + }, + "peerDependencies": { + "@noble/hashes": "^1.8.0 || ^2.0.0" + }, + "peerDependenciesMeta": { + "@noble/hashes": { + "optional": true + } + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", + "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@oxc-project/types": { + "version": "0.122.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.122.0.tgz", + "integrity": "sha512-oLAl5kBpV4w69UtFZ9xqcmTi+GENWOcPF7FCrczTiBbmC0ibXxCwyvZGbO39rCVEuLGAZM84DH0pUIyyv/YJzA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/Boshen" + } + }, + "node_modules/@rolldown/binding-linux-x64-gnu": { + "version": "1.0.0-rc.12", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.0.0-rc.12.tgz", + "integrity": "sha512-RNrafz5bcwRy+O9e6P8Z/OCAJW/A+qtBczIqVYwTs14pf4iV1/+eKEjdOUta93q2TsT/FI0XYDP3TCky38LMAg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.0.0-rc.12", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-rc.12.tgz", + "integrity": "sha512-HHMwmarRKvoFsJorqYlFeFRzXZqCt2ETQlEDOb9aqssrnVBB1/+xgTGtuTrIk5vzLNX1MjMtTf7W9z3tsSbrxw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@standard-schema/spec": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", + "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@testing-library/dom": { + "version": "10.4.1", + "resolved": "https://registry.npmjs.org/@testing-library/dom/-/dom-10.4.1.tgz", + "integrity": "sha512-o4PXJQidqJl82ckFaXUeoAW+XysPLauYI43Abki5hABd853iMhitooc6znOnczgbTYmEP6U6/y1ZyKAIsvMKGg==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@babel/code-frame": "^7.10.4", + "@babel/runtime": "^7.12.5", + "@types/aria-query": "^5.0.1", + "aria-query": "5.3.0", + "dom-accessibility-api": "^0.5.9", + "lz-string": "^1.5.0", + "picocolors": "1.1.1", + "pretty-format": "^27.0.2" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@testing-library/jest-dom": { + "version": "6.9.1", + "resolved": "https://registry.npmjs.org/@testing-library/jest-dom/-/jest-dom-6.9.1.tgz", + "integrity": "sha512-zIcONa+hVtVSSep9UT3jZ5rizo2BsxgyDYU7WFD5eICBE7no3881HGeb/QkGfsJs6JTkY1aQhT7rIPC7e+0nnA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@adobe/css-tools": "^4.4.0", + "aria-query": "^5.0.0", + "css.escape": "^1.5.1", + "dom-accessibility-api": "^0.6.3", + "picocolors": "^1.1.1", + "redent": "^3.0.0" + }, + "engines": { + "node": ">=14", + "npm": ">=6", + "yarn": ">=1" + } + }, + "node_modules/@testing-library/jest-dom/node_modules/dom-accessibility-api": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.6.3.tgz", + "integrity": "sha512-7ZgogeTnjuHbo+ct10G9Ffp0mif17idi0IyWNVA/wcwcm7NPOD/WEHVP3n7n3MhXqxoIYm8d6MuZohYWIZ4T3w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@testing-library/react": { + "version": "16.3.2", + "resolved": "https://registry.npmjs.org/@testing-library/react/-/react-16.3.2.tgz", + "integrity": "sha512-XU5/SytQM+ykqMnAnvB2umaJNIOsLF3PVv//1Ew4CTcpz0/BRyy/af40qqrt7SjKpDdT1saBMc42CUok5gaw+g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.12.5" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@testing-library/dom": "^10.0.0", + "@types/react": "^18.0.0 || ^19.0.0", + "@types/react-dom": "^18.0.0 || ^19.0.0", + "react": "^18.0.0 || ^19.0.0", + "react-dom": "^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@types/aria-query": { + "version": "5.0.4", + "resolved": "https://registry.npmjs.org/@types/aria-query/-/aria-query-5.0.4.tgz", + "integrity": "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==", + "dev": true, + "license": "MIT", + "peer": true + }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", + "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@vitest/coverage-v8": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/@vitest/coverage-v8/-/coverage-v8-4.1.2.tgz", + "integrity": "sha512-sPK//PHO+kAkScb8XITeB1bf7fsk85Km7+rt4eeuRR3VS1/crD47cmV5wicisJmjNdfeokTZwjMk4Mj2d58Mgg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@bcoe/v8-coverage": "^1.0.2", + "@vitest/utils": "4.1.2", + "ast-v8-to-istanbul": "^1.0.0", + "istanbul-lib-coverage": "^3.2.2", + "istanbul-lib-report": "^3.0.1", + "istanbul-reports": "^3.2.0", + "magicast": "^0.5.2", + "obug": "^2.1.1", + "std-env": "^4.0.0-rc.1", + "tinyrainbow": "^3.1.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@vitest/browser": "4.1.2", + "vitest": "4.1.2" + }, + "peerDependenciesMeta": { + "@vitest/browser": { + "optional": true + } + } + }, + "node_modules/@vitest/expect": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.2.tgz", + "integrity": "sha512-gbu+7B0YgUJ2nkdsRJrFFW6X7NTP44WlhiclHniUhxADQJH5Szt9mZ9hWnJPJ8YwOK5zUOSSlSvyzRf0u1DSBQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@standard-schema/spec": "^1.1.0", + "@types/chai": "^5.2.2", + "@vitest/spy": "4.1.2", + "@vitest/utils": "4.1.2", + "chai": "^6.2.2", + "tinyrainbow": "^3.1.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/mocker": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.2.tgz", + "integrity": "sha512-Ize4iQtEALHDttPRCmN+FKqOl2vxTiNUhzobQFFt/BM1lRUTG7zRCLOykG/6Vo4E4hnUdfVLo5/eqKPukcWW7Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/spy": "4.1.2", + "estree-walker": "^3.0.3", + "magic-string": "^0.30.21" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/pretty-format": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.2.tgz", + "integrity": "sha512-dwQga8aejqeuB+TvXCMzSQemvV9hNEtDDpgUKDzOmNQayl2OG241PSWeJwKRH3CiC+sESrmoFd49rfnq7T4RnA==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyrainbow": "^3.1.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/runner": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.2.tgz", + "integrity": "sha512-Gr+FQan34CdiYAwpGJmQG8PgkyFVmARK8/xSijia3eTFgVfpcpztWLuP6FttGNfPLJhaZVP/euvujeNYar36OQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/utils": "4.1.2", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/snapshot": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.2.tgz", + "integrity": "sha512-g7yfUmxYS4mNxk31qbOYsSt2F4m1E02LFqO53Xpzg3zKMhLAPZAjjfyl9e6z7HrW6LvUdTwAQR3HHfLjpko16A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "4.1.2", + "@vitest/utils": "4.1.2", + "magic-string": "^0.30.21", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/spy": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.2.tgz", + "integrity": "sha512-DU4fBnbVCJGNBwVA6xSToNXrkZNSiw59H8tcuUspVMsBDBST4nfvsPsEHDHGtWRRnqBERBQu7TrTKskmjqTXKA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/utils": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.2.tgz", + "integrity": "sha512-xw2/TiX82lQHA06cgbqRKFb5lCAy3axQ4H4SoUFhUsg+wztiet+co86IAMDtF6Vm1hc7J6j09oh/rgDn+JdKIQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "4.1.2", + "convert-source-map": "^2.0.0", + "tinyrainbow": "^3.1.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", + "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/aria-query": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.0.tgz", + "integrity": "sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "dequal": "^2.0.3" + } + }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/ast-v8-to-istanbul": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/ast-v8-to-istanbul/-/ast-v8-to-istanbul-1.0.0.tgz", + "integrity": "sha512-1fSfIwuDICFA4LKkCzRPO7F0hzFf0B7+Xqrl27ynQaa+Rh0e1Es0v6kWHPott3lU10AyAr7oKHa65OppjLn3Rg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.31", + "estree-walker": "^3.0.3", + "js-tokens": "^10.0.0" + } + }, + "node_modules/ast-v8-to-istanbul/node_modules/js-tokens": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-10.0.0.tgz", + "integrity": "sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/bidi-js": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/bidi-js/-/bidi-js-1.0.3.tgz", + "integrity": "sha512-RKshQI1R3YQ+n9YJz2QQ147P66ELpa1FQEg20Dk8oW9t2KgLbpDLLp9aGZ7y8WHSshDknG0bknqGw5/tyCs5tw==", + "dev": true, + "license": "MIT", + "dependencies": { + "require-from-string": "^2.0.2" + } + }, + "node_modules/chai": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz", + "integrity": "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "dev": true, + "license": "MIT" + }, + "node_modules/css-tree": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-3.2.1.tgz", + "integrity": "sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==", + "dev": true, + "license": "MIT", + "dependencies": { + "mdn-data": "2.27.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0" + } + }, + "node_modules/css.escape": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/css.escape/-/css.escape-1.5.1.tgz", + "integrity": "sha512-YUifsXXuknHlUsmlgyY0PKzgPOr7/FjCePfHNt0jxm83wHZi44VDMQ7/fGNkjY3/jV1MC+1CmZbaHzugyeRtpg==", + "dev": true, + "license": "MIT" + }, + "node_modules/data-urls": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-7.0.0.tgz", + "integrity": "sha512-23XHcCF+coGYevirZceTVD7NdJOqVn+49IHyxgszm+JIiHLoB2TkmPtsYkNWT1pvRSGkc35L6NHs0yHkN2SumA==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-mimetype": "^5.0.0", + "whatwg-url": "^16.0.0" + }, + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + } + }, + "node_modules/decimal.js": { + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz", + "integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==", + "dev": true, + "license": "MIT" + }, + "node_modules/dequal": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", + "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/dom-accessibility-api": { + "version": "0.5.16", + "resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz", + "integrity": "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==", + "dev": true, + "license": "MIT", + "peer": true + }, + "node_modules/entities": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/entities/-/entities-6.0.1.tgz", + "integrity": "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/es-module-lexer": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.0.0.tgz", + "integrity": "sha512-5POEcUuZybH7IdmGsD8wlf0AI55wMecM9rVBTI/qEAy2c1kTOm3DjFYjrBdI2K3BaJjJYfYFeRtM0t9ssnRuxw==", + "dev": true, + "license": "MIT" + }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/expect-type": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.3.0.tgz", + "integrity": "sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/html-encoding-sniffer": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-6.0.0.tgz", + "integrity": "sha512-CV9TW3Y3f8/wT0BRFc1/KAVQ3TUHiXmaAb6VW9vtiMFf7SLoMd1PdAc4W3KFOFETBJUb90KatHqlsZMWV+R9Gg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@exodus/bytes": "^1.6.0" + }, + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + } + }, + "node_modules/html-escaper": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz", + "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==", + "dev": true, + "license": "MIT" + }, + "node_modules/indent-string": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-4.0.0.tgz", + "integrity": "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-potential-custom-element-name": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz", + "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/istanbul-lib-coverage": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.2.tgz", + "integrity": "sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=8" + } + }, + "node_modules/istanbul-lib-report": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz", + "integrity": "sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "istanbul-lib-coverage": "^3.0.0", + "make-dir": "^4.0.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/istanbul-reports": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.2.0.tgz", + "integrity": "sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "html-escaper": "^2.0.0", + "istanbul-lib-report": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "dev": true, + "license": "MIT", + "peer": true + }, + "node_modules/jsdom": { + "version": "29.0.1", + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-29.0.1.tgz", + "integrity": "sha512-z6JOK5gRO7aMybVq/y/MlIpKh8JIi68FBKMUtKkK2KH/wMSRlCxQ682d08LB9fYXplyY/UXG8P4XXTScmdjApg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@asamuzakjp/css-color": "^5.0.1", + "@asamuzakjp/dom-selector": "^7.0.3", + "@bramus/specificity": "^2.4.2", + "@csstools/css-syntax-patches-for-csstree": "^1.1.1", + "@exodus/bytes": "^1.15.0", + "css-tree": "^3.2.1", + "data-urls": "^7.0.0", + "decimal.js": "^10.6.0", + "html-encoding-sniffer": "^6.0.0", + "is-potential-custom-element-name": "^1.0.1", + "lru-cache": "^11.2.7", + "parse5": "^8.0.0", + "saxes": "^6.0.0", + "symbol-tree": "^3.2.4", + "tough-cookie": "^6.0.1", + "undici": "^7.24.5", + "w3c-xmlserializer": "^5.0.0", + "webidl-conversions": "^8.0.1", + "whatwg-mimetype": "^5.0.0", + "whatwg-url": "^16.0.1", + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24.0.0" + }, + "peerDependencies": { + "canvas": "^3.0.0" + }, + "peerDependenciesMeta": { + "canvas": { + "optional": true + } + } + }, + "node_modules/lightningcss": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz", + "integrity": "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==", + "dev": true, + "license": "MPL-2.0", + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.32.0", + "lightningcss-darwin-arm64": "1.32.0", + "lightningcss-darwin-x64": "1.32.0", + "lightningcss-freebsd-x64": "1.32.0", + "lightningcss-linux-arm-gnueabihf": "1.32.0", + "lightningcss-linux-arm64-gnu": "1.32.0", + "lightningcss-linux-arm64-musl": "1.32.0", + "lightningcss-linux-x64-gnu": "1.32.0", + "lightningcss-linux-x64-musl": "1.32.0", + "lightningcss-win32-arm64-msvc": "1.32.0", + "lightningcss-win32-x64-msvc": "1.32.0" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.32.0.tgz", + "integrity": "sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lru-cache": { + "version": "11.2.7", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.2.7.tgz", + "integrity": "sha512-aY/R+aEsRelme17KGQa/1ZSIpLpNYYrhcrepKTZgE+W3WM16YMCaPwOHLHsmopZHELU0Ojin1lPVxKR0MihncA==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/lz-string": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/lz-string/-/lz-string-1.5.0.tgz", + "integrity": "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==", + "dev": true, + "license": "MIT", + "peer": true, + "bin": { + "lz-string": "bin/bin.js" + } + }, + "node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/magicast": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/magicast/-/magicast-0.5.2.tgz", + "integrity": "sha512-E3ZJh4J3S9KfwdjZhe2afj6R9lGIN5Pher1pF39UGrXRqq/VDaGVIGN13BjHd2u8B61hArAGOnso7nBOouW3TQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.0", + "@babel/types": "^7.29.0", + "source-map-js": "^1.2.1" + } + }, + "node_modules/make-dir": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz", + "integrity": "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==", + "dev": true, + "license": "MIT", + "dependencies": { + "semver": "^7.5.3" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/mdn-data": { + "version": "2.27.1", + "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.27.1.tgz", + "integrity": "sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==", + "dev": true, + "license": "CC0-1.0" + }, + "node_modules/min-indent": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/min-indent/-/min-indent-1.0.1.tgz", + "integrity": "sha512-I9jwMn07Sy/IwOj3zVkVik2JTvgpaykDZEigL6Rx6N9LbMywwUSMtxET+7lVoDLLd3O3IXwJwvuuns8UB/HeAg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/nanoid": { + "version": "3.3.11", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz", + "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/obug": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/obug/-/obug-2.1.1.tgz", + "integrity": "sha512-uTqF9MuPraAQ+IsnPf366RG4cP9RtUi7MLO1N3KEc+wb0a6yKpeL0lmk2IB1jY5KHPAlTc6T/JRdC/YqxHNwkQ==", + "dev": true, + "funding": [ + "https://github.com/sponsors/sxzz", + "https://opencollective.com/debug" + ], + "license": "MIT" + }, + "node_modules/parse5": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-8.0.0.tgz", + "integrity": "sha512-9m4m5GSgXjL4AjumKzq1Fgfp3Z8rsvjRNbnkVwfu2ImRqE5D0LnY2QfDen18FSY9C573YU5XxSapdHZTZ2WolA==", + "dev": true, + "license": "MIT", + "dependencies": { + "entities": "^6.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "dev": true, + "license": "MIT" + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz", + "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.8", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.8.tgz", + "integrity": "sha512-OW/rX8O/jXnm82Ey1k44pObPtdblfiuWnrd8X7GJ7emImCOstunGbXUpp7HdBrFQX6rJzn3sPT397Wp5aCwCHg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.11", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/pretty-format": { + "version": "27.5.1", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-27.5.1.tgz", + "integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "ansi-regex": "^5.0.1", + "ansi-styles": "^5.0.0", + "react-is": "^17.0.1" + }, + "engines": { + "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + } + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/react": { + "version": "19.2.4", + "resolved": "https://registry.npmjs.org/react/-/react-19.2.4.tgz", + "integrity": "sha512-9nfp2hYpCwOjAN+8TZFGhtWEwgvWHXqESH8qT89AT/lWklpLON22Lc8pEtnpsZz7VmawabSU0gCjnj8aC0euHQ==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-dom": { + "version": "19.2.4", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.4.tgz", + "integrity": "sha512-AXJdLo8kgMbimY95O2aKQqsz2iWi9jMgKJhRBAxECE4IFxfcazB2LmzloIoibJI3C12IlY20+KFaLv+71bUJeQ==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "scheduler": "^0.27.0" + }, + "peerDependencies": { + "react": "^19.2.4" + } + }, + "node_modules/react-is": { + "version": "17.0.2", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz", + "integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==", + "dev": true, + "license": "MIT", + "peer": true + }, + "node_modules/redent": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/redent/-/redent-3.0.0.tgz", + "integrity": "sha512-6tDA8g98We0zd0GvVeMT9arEOnTw9qM03L9cJXaCjrip1OO764RDBLBfrB4cwzNGDj5OA5ioymC9GkizgWJDUg==", + "dev": true, + "license": "MIT", + "dependencies": { + "indent-string": "^4.0.0", + "strip-indent": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/rolldown": { + "version": "1.0.0-rc.12", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.0.0-rc.12.tgz", + "integrity": "sha512-yP4USLIMYrwpPHEFB5JGH1uxhcslv6/hL0OyvTuY+3qlOSJvZ7ntYnoWpehBxufkgN0cvXxppuTu5hHa/zPh+A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@oxc-project/types": "=0.122.0", + "@rolldown/pluginutils": "1.0.0-rc.12" + }, + "bin": { + "rolldown": "bin/cli.mjs" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "optionalDependencies": { + "@rolldown/binding-android-arm64": "1.0.0-rc.12", + "@rolldown/binding-darwin-arm64": "1.0.0-rc.12", + "@rolldown/binding-darwin-x64": "1.0.0-rc.12", + "@rolldown/binding-freebsd-x64": "1.0.0-rc.12", + "@rolldown/binding-linux-arm-gnueabihf": "1.0.0-rc.12", + "@rolldown/binding-linux-arm64-gnu": "1.0.0-rc.12", + "@rolldown/binding-linux-arm64-musl": "1.0.0-rc.12", + "@rolldown/binding-linux-ppc64-gnu": "1.0.0-rc.12", + "@rolldown/binding-linux-s390x-gnu": "1.0.0-rc.12", + "@rolldown/binding-linux-x64-gnu": "1.0.0-rc.12", + "@rolldown/binding-linux-x64-musl": "1.0.0-rc.12", + "@rolldown/binding-openharmony-arm64": "1.0.0-rc.12", + "@rolldown/binding-wasm32-wasi": "1.0.0-rc.12", + "@rolldown/binding-win32-arm64-msvc": "1.0.0-rc.12", + "@rolldown/binding-win32-x64-msvc": "1.0.0-rc.12" + } + }, + "node_modules/saxes": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz", + "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==", + "dev": true, + "license": "ISC", + "dependencies": { + "xmlchars": "^2.2.0" + }, + "engines": { + "node": ">=v12.22.7" + } + }, + "node_modules/scheduler": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz", + "integrity": "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==", + "dev": true, + "license": "MIT", + "peer": true + }, + "node_modules/semver": { + "version": "7.7.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz", + "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/siginfo": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", + "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==", + "dev": true, + "license": "ISC" + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/stackback": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", + "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==", + "dev": true, + "license": "MIT" + }, + "node_modules/std-env": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.0.0.tgz", + "integrity": "sha512-zUMPtQ/HBY3/50VbpkupYHbRroTRZJPRLvreamgErJVys0ceuzMkD44J/QjqhHjOzK42GQ3QZIeFG1OYfOtKqQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/strip-indent": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-3.0.0.tgz", + "integrity": "sha512-laJTa3Jb+VQpaC6DseHhF7dXVqHTfJPCRDaEbid/drOhgitgYku/letMUqOXFoWV0zIIUbjpdH2t+tYj4bQMRQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "min-indent": "^1.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/symbol-tree": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz", + "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinybench": { + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", + "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinyexec": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.0.4.tgz", + "integrity": "sha512-u9r3uZC0bdpGOXtlxUIdwf9pkmvhqJdrVCH9fapQtgy/OeTTMZ1nqH7agtvEfmGui6e1XxjcdrlxvxJvc3sMqw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.15", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz", + "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.3" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tinyrainbow": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.1.0.tgz", + "integrity": "sha512-Bf+ILmBgretUrdJxzXM0SgXLZ3XfiaUuOj/IKQHuTXip+05Xn+uyEYdVg0kYDipTBcLrCVyUzAPz7QmArb0mmw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tldts": { + "version": "7.0.27", + "resolved": "https://registry.npmjs.org/tldts/-/tldts-7.0.27.tgz", + "integrity": "sha512-I4FZcVFcqCRuT0ph6dCDpPuO4Xgzvh+spkcTr1gK7peIvxWauoloVO0vuy1FQnijT63ss6AsHB6+OIM4aXHbPg==", + "dev": true, + "license": "MIT", + "dependencies": { + "tldts-core": "^7.0.27" + }, + "bin": { + "tldts": "bin/cli.js" + } + }, + "node_modules/tldts-core": { + "version": "7.0.27", + "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-7.0.27.tgz", + "integrity": "sha512-YQ7uPjgWUibIK6DW5lrKujGwUKhLevU4hcGbP5O6TcIUb+oTjJYJVWPS4nZsIHrEEEG6myk/oqAJUEQmpZrHsg==", + "dev": true, + "license": "MIT" + }, + "node_modules/tough-cookie": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-6.0.1.tgz", + "integrity": "sha512-LktZQb3IeoUWB9lqR5EWTHgW/VTITCXg4D21M+lvybRVdylLrRMnqaIONLVb5mav8vM19m44HIcGq4qASeu2Qw==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "tldts": "^7.0.5" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/tr46": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-6.0.0.tgz", + "integrity": "sha512-bLVMLPtstlZ4iMQHpFHTR7GAGj2jxi8Dg0s2h2MafAE4uSWF98FC/3MomU51iQAMf8/qDUbKWf5GxuvvVcXEhw==", + "dev": true, + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/undici": { + "version": "7.24.6", + "resolved": "https://registry.npmjs.org/undici/-/undici-7.24.6.tgz", + "integrity": "sha512-Xi4agocCbRzt0yYMZGMA6ApD7gvtUFaxm4ZmeacWI4cZxaF6C+8I8QfofC20NAePiB/IcvZmzkJ7XPa471AEtA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20.18.1" + } + }, + "node_modules/vite": { + "version": "8.0.3", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.0.3.tgz", + "integrity": "sha512-B9ifbFudT1TFhfltfaIPgjo9Z3mDynBTJSUYxTjOQruf/zHH+ezCQKcoqO+h7a9Pw9Nm/OtlXAiGT1axBgwqrQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "lightningcss": "^1.32.0", + "picomatch": "^4.0.4", + "postcss": "^8.5.8", + "rolldown": "1.0.0-rc.12", + "tinyglobby": "^0.2.15" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "@vitejs/devtools": "^0.1.0", + "esbuild": "^0.27.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "@vitejs/devtools": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vitest": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.2.tgz", + "integrity": "sha512-xjR1dMTVHlFLh98JE3i/f/WePqJsah4A0FK9cc8Ehp9Udk0AZk6ccpIZhh1qJ/yxVWRZ+Q54ocnD8TXmkhspGg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/expect": "4.1.2", + "@vitest/mocker": "4.1.2", + "@vitest/pretty-format": "4.1.2", + "@vitest/runner": "4.1.2", + "@vitest/snapshot": "4.1.2", + "@vitest/spy": "4.1.2", + "@vitest/utils": "4.1.2", + "es-module-lexer": "^2.0.0", + "expect-type": "^1.3.0", + "magic-string": "^0.30.21", + "obug": "^2.1.1", + "pathe": "^2.0.3", + "picomatch": "^4.0.3", + "std-env": "^4.0.0-rc.1", + "tinybench": "^2.9.0", + "tinyexec": "^1.0.2", + "tinyglobby": "^0.2.15", + "tinyrainbow": "^3.1.0", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0", + "why-is-node-running": "^2.3.0" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^20.0.0 || ^22.0.0 || >=24.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@opentelemetry/api": "^1.9.0", + "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0", + "@vitest/browser-playwright": "4.1.2", + "@vitest/browser-preview": "4.1.2", + "@vitest/browser-webdriverio": "4.1.2", + "@vitest/ui": "4.1.2", + "happy-dom": "*", + "jsdom": "*", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@opentelemetry/api": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser-playwright": { + "optional": true + }, + "@vitest/browser-preview": { + "optional": true + }, + "@vitest/browser-webdriverio": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + }, + "vite": { + "optional": false + } + } + }, + "node_modules/w3c-xmlserializer": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz", + "integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==", + "dev": true, + "license": "MIT", + "dependencies": { + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/webidl-conversions": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-8.0.1.tgz", + "integrity": "sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=20" + } + }, + "node_modules/whatwg-mimetype": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-5.0.0.tgz", + "integrity": "sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20" + } + }, + "node_modules/whatwg-url": { + "version": "16.0.1", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-16.0.1.tgz", + "integrity": "sha512-1to4zXBxmXHV3IiSSEInrreIlu02vUOvrhxJJH5vcxYTBDAx51cqZiKdyTxlecdKNSjj8EcxGBxNf6Vg+945gw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@exodus/bytes": "^1.11.0", + "tr46": "^6.0.0", + "webidl-conversions": "^8.0.1" + }, + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + } + }, + "node_modules/why-is-node-running": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", + "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==", + "dev": true, + "license": "MIT", + "dependencies": { + "siginfo": "^2.0.0", + "stackback": "0.0.2" + }, + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/xml-name-validator": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz", + "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/xmlchars": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz", + "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", + "dev": true, + "license": "MIT" + } + } +} diff --git a/node_modules/@adobe/css-tools/LICENSE b/node_modules/@adobe/css-tools/LICENSE new file mode 100644 index 00000000..e63de06c --- /dev/null +++ b/node_modules/@adobe/css-tools/LICENSE @@ -0,0 +1,10 @@ +(The MIT License) + +Copyright (c) 2012 TJ Holowaychuk +Copyright (c) 2022 Jean-Philippe Zolesio + +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. diff --git a/node_modules/@adobe/css-tools/README.md b/node_modules/@adobe/css-tools/README.md new file mode 100644 index 00000000..13053ccd --- /dev/null +++ b/node_modules/@adobe/css-tools/README.md @@ -0,0 +1,146 @@ +# @adobe/css-tools + +> A modern CSS parser and stringifier with TypeScript support + +[![npm version](https://badge.fury.io/js/%40adobe%2Fcss-tools.svg)](https://badge.fury.io/js/%40adobe%2Fcss-tools) +[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) + +Parse CSS into an Abstract Syntax Tree (AST) and convert it back to CSS with configurable formatting. Built with TypeScript for type safety and modern JavaScript features. + +## Install + +```bash +npm install @adobe/css-tools +``` + +## Usage + +```js +import { parse, stringify } from '@adobe/css-tools' + +// Parse CSS to AST +const ast = parse('body { font-size: 12px; }') + +// Stringify AST back to CSS +const css = stringify(ast) +// => "body { font-size: 12px; }" + +// Pretty print with custom indentation +const formatted = stringify(ast, { indent: ' ' }) +// => "body {\n font-size: 12px;\n}" + +// Minify output +const minified = stringify(ast, { compress: true }) +// => "body{font-size:12px}" +``` + +## API + +### `parse(code, options?)` + +Parses CSS code and returns an Abstract Syntax Tree (AST). + +**Parameters:** +- `code` (string) - The CSS code to parse +- `options` (object, optional) - Parsing options + - `silent` (boolean) - Silently fail on parse errors instead of throwing + - `source` (string) - File path for better error reporting + +**Returns:** `CssStylesheetAST` - The parsed CSS as an AST + +### `stringify(ast, options?)` + +Converts a CSS AST back to CSS string with configurable formatting. + +**Parameters:** +- `ast` (CssStylesheetAST) - The CSS AST to stringify +- `options` (object, optional) - Stringification options + - `indent` (string) - Indentation string (default: `' '`) + - `compress` (boolean) - Whether to compress/minify the output (default: `false`) + +**Returns:** `string` - The formatted CSS string + +## Features + +- **Complete CSS Support**: All standard CSS features including selectors, properties, values, at-rules, and comments +- **TypeScript Support**: Full type definitions for all AST nodes and functions +- **Error Handling**: Configurable error handling with detailed position information +- **Formatting Options**: Pretty print, minify, or custom formatting +- **Performance Optimized**: Efficient parsing and stringification for large CSS files +- **Source Maps**: Track original source positions for debugging and tooling + +### Supported CSS Features + +- **Selectors**: Element, class, ID, attribute, pseudo-class, pseudo-element selectors +- **Properties**: All standard CSS properties and custom properties +- **Values**: Colors, lengths, percentages, functions, calc(), etc. +- **At-rules**: @media, @keyframes, @import, @charset, @namespace, @font-face, @page, @document, @supports, @container, @layer, @starting-style, @host, @custom-media +- **Comments**: Both /* */ and // comments +- **Whitespace**: Preserves formatting information +- **Vendor prefixes**: Supports vendor-prefixed at-rules and properties +- **Nested rules**: Media queries, supports, containers, etc. +- **Complex selectors**: Combinators, pseudo-selectors, attribute selectors + +## Examples + +### Error Handling + +```js +import { parse } from '@adobe/css-tools' + +const malformedCss = ` + body { color: red; } + { color: blue; } /* Missing selector */ + .valid { background: green; } +` + +// Parse with silent error handling +const result = parse(malformedCss, { silent: true }) + +// Check for parsing errors +if (result.stylesheet.parsingErrors) { + console.log('Parsing errors:', result.stylesheet.parsingErrors.length) + result.stylesheet.parsingErrors.forEach(error => { + console.log(`Error at line ${error.line}: ${error.message}`) + }) +} + +// Valid rules are still parsed +console.log('Valid rules:', result.stylesheet.rules.length) +``` + +### Source Tracking + +```js +import { parse } from '@adobe/css-tools' + +const css = 'body { color: red; }' +const ast = parse(css, { source: 'styles.css' }) + +// Position information is available +const rule = ast.stylesheet.rules[0] +console.log(rule.position?.source) // "styles.css" +console.log(rule.position?.start) // { line: 1, column: 1 } +console.log(rule.position?.end) // { line: 1, column: 20 } +``` + +For more examples, see the [Examples documentation](docs/EXAMPLES.md). + +## Performance + +The library is optimized for performance and can handle large CSS files efficiently. For benchmarking information, see the `benchmark/` directory in the source code. + +## Documentation + +- [API Reference](docs/API.md) - Complete API documentation +- [AST Structure](docs/AST.md) - Detailed AST node types and structure +- [Examples](docs/EXAMPLES.md) - Comprehensive usage examples +- [Changelog](docs/CHANGELOG.md) - Version history and changes + +## Background + +This is a fork of the npm `css` package, maintained by Adobe with modern improvements including TypeScript support, enhanced performance, and security updates. It provides a robust foundation for CSS tooling, preprocessing, and analysis. + +## License + +[MIT](LICENSE) diff --git a/node_modules/@adobe/css-tools/dist/cjs/adobe-css-tools.cjs b/node_modules/@adobe/css-tools/dist/cjs/adobe-css-tools.cjs new file mode 100644 index 00000000..085994d9 --- /dev/null +++ b/node_modules/@adobe/css-tools/dist/cjs/adobe-css-tools.cjs @@ -0,0 +1,2 @@ +"use strict";Object.defineProperty(exports,"__esModule",{value:!0});class t extends Error{reason;filename;line;column;source;constructor(t,s,e,i,n){super(`${t}:${e}:${i}: ${s}`),this.reason=s,this.filename=t,this.line=e,this.column=i,this.source=n}}class s{start;end;source;constructor(t,s,e){this.start=t,this.end=s,this.source=e}}var e;exports.CssTypes=void 0,(e=exports.CssTypes||(exports.CssTypes={})).stylesheet="stylesheet",e.rule="rule",e.declaration="declaration",e.comment="comment",e.container="container",e.charset="charset",e.document="document",e.customMedia="custom-media",e.fontFace="font-face",e.host="host",e.import="import",e.keyframes="keyframes",e.keyframe="keyframe",e.layer="layer",e.media="media",e.namespace="namespace",e.page="page",e.startingStyle="starting-style",e.supports="supports";const i=(t,s,e)=>{let i=e,n=1e4;do{const e=s.map(s=>t.indexOf(s,i));e.push(t.indexOf("\\",i));const r=e.filter(t=>-1!==t);if(0===r.length)return-1;const o=Math.min(...r);if("\\"!==t[o])return o;i=o+2,n--}while(n>0);throw new Error("Too many escaping")},n=(t,s,e)=>{let r=e,o=1e4;do{const e=s.map(s=>t.indexOf(s,r));e.push(t.indexOf("(",r)),e.push(t.indexOf('"',r)),e.push(t.indexOf("'",r)),e.push(t.indexOf("\\",r));const c=e.filter(t=>-1!==t);if(0===c.length)return-1;const a=Math.min(...c);switch(t[a]){case"\\":r=a+2;break;case"(":{const s=n(t,[")"],a+1);if(-1===s)return-1;r=s+1}break;case'"':{const s=i(t,['"'],a+1);if(-1===s)return-1;r=s+1}break;case"'":{const s=i(t,["'"],a+1);if(-1===s)return-1;r=s+1}break;default:return a}o--}while(o>0);throw new Error("Too many escaping")},r=/\/\*[^]*?(?:\*\/|$)/g;function o(t){return t?t.trim():""}function c(t,s){const e=t&&"string"==typeof t.type,i=e?t:s;for(const s in t){const e=t[s];Array.isArray(e)?e.forEach(t=>{c(t,i)}):e&&"object"==typeof e&&c(e,i)}return e&&Object.defineProperty(t,"parent",{configurable:!0,writable:!0,enumerable:!1,value:s||null}),t}class a{level=0;indentation=" ";compress=!1;constructor(t){"string"==typeof t?.indent&&(this.indentation=t?.indent),t?.compress&&(this.compress=!0)}emit(t,s){return t}indent(t){return this.level=this.level||1,t?(this.level+=t,""):Array(this.level).join(this.indentation)}visit(t){switch(t.type){case exports.CssTypes.stylesheet:return this.stylesheet(t);case exports.CssTypes.rule:return this.rule(t);case exports.CssTypes.declaration:return this.declaration(t);case exports.CssTypes.comment:return this.comment(t);case exports.CssTypes.container:return this.container(t);case exports.CssTypes.charset:return this.charset(t);case exports.CssTypes.document:return this.document(t);case exports.CssTypes.customMedia:return this.customMedia(t);case exports.CssTypes.fontFace:return this.fontFace(t);case exports.CssTypes.host:return this.host(t);case exports.CssTypes.import:return this.import(t);case exports.CssTypes.keyframes:return this.keyframes(t);case exports.CssTypes.keyframe:return this.keyframe(t);case exports.CssTypes.layer:return this.layer(t);case exports.CssTypes.media:return this.media(t);case exports.CssTypes.namespace:return this.namespace(t);case exports.CssTypes.page:return this.page(t);case exports.CssTypes.startingStyle:return this.startingStyle(t);case exports.CssTypes.supports:return this.supports(t)}}mapVisit(t,s){let e="";s=s||"";for(let i=0,n=t.length;ie+t).join(",\n"),t.position)+this.emit(" {\n")+this.emit(this.indent(1))+this.mapVisit(s,"\n")+this.emit(this.indent(-1))+this.emit(`\n${this.indent()}}`)}declaration(t){return this.compress?this.emit(`${t.property}:${t.value}`,t.position)+this.emit(";"):"grid-template-areas"===t.property?this.emit(this.indent())+this.emit(t.property+": "+t.value.split("\n").join("\n".padEnd(22)+this.indent()),t.position)+this.emit(";"):this.emit(this.indent())+this.emit(`${t.property}: ${t.value}`,t.position)+this.emit(";")}}const p=(e,i)=>{i=i||{};let a=1,p=1;function m(){const t={line:a,column:p};return e=>(e.position=new s(t,{line:a,column:p},i?.source||""),x(),e)}const h=[];function u(s){const n=new t(i?.source||"",s,a,p,e);if(!i?.silent)throw n;h.push(n)}function l(){const t=/^{\s*/.exec(e);return!!t&&(y(t),!0)}function f(){const t=/^}/.exec(e);return!!t&&(y(t),!0)}function d(){let t;const s=[];for(x(),g(s);e.length&&"}"!==e.charAt(0)&&(t=O()||E(),t);)s.push(t),g(s);return s}function y(t){const s=t[0];return function(t){const s=t.match(/\n/g);s&&(a+=s.length);const e=t.lastIndexOf("\n");p=~e?t.length-e:p+t.length}(s),e=e.slice(s.length),t}function x(){const t=/^\s*/.exec(e);t&&y(t)}function g(t){t=t||[];let s=$();for(;s;)t.push(s),s=$();return t}function $(){const t=m();if("/"!==e.charAt(0)||"*"!==e.charAt(1))return;const s=/^\/\*[^]*?\*\//.exec(e);return s?(y(s),t({type:exports.CssTypes.comment,comment:s[0].slice(2,-2)})):u("End of comment missing")}function T(){const t=/^([^{]+)/.exec(e);if(!t)return;y(t);return((t,s)=>{const e=[];let i=0;for(;io(t))}function C(){const t=m(),s=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/.exec(e);if(!s)return;y(s);const i=o(s[0]),c=/^:\s*/.exec(e);if(!c)return u("property missing ':'");y(c);let a="";const p=n(e,[";","}"]);if(-1!==p){a=e.substring(0,p);y([a]),a=o(a).replace(r,"")}const h=t({type:exports.CssTypes.declaration,property:i.replace(r,""),value:a}),l=/^[;\s]*/.exec(e);return l&&y(l),h}function V(){const t=[];if(!l())return u("missing '{'");g(t);let s=C();for(;s;)t.push(s),g(t),s=C();return f()?t:u("missing '}'")}function k(){const t=[],s=m();let i=/^((\d+\.\d+|\.\d+|\d+)%?|[a-z]+)\s*/.exec(e);for(;i;){const s=y(i);t.push(s[1]);const n=/^,\s*/.exec(e);n&&y(n),i=/^((\d+\.\d+|\.\d+|\d+)%?|[a-z]+)\s*/.exec(e)}if(t.length)return s({type:exports.CssTypes.keyframe,values:t,declarations:V()||[]})}const v=j("import"),w=j("charset"),b=j("namespace");function j(t){const s=new RegExp("^@"+t+"\\s*((?::?[^;'\"]|\"(?:\\\\\"|[^\"])*?\"|'(?:\\\\'|[^'])*?')+)(?:;|$)");return()=>{const i=m(),n=s.exec(e);if(!n)return;const r=y(n),o={type:t};return o[t]=r[1].trim(),i(o)}}function O(){if("@"===e[0])return function(){const t=m(),s=/^@([-\w]+)?keyframes\s*/.exec(e);if(!s)return;const i=y(s)[1],n=/^([-\w]+)\s*/.exec(e);if(!n)return u("@keyframes missing name");const r=y(n)[1];if(!l())return u("@keyframes missing '{'");let o=g(),c=k();for(;c;)o.push(c),o=o.concat(g()),c=k();return f()?t({type:exports.CssTypes.keyframes,name:r,vendor:i,keyframes:o}):u("@keyframes missing '}'")}()||function(){const t=m(),s=/^@media *([^{]+)/.exec(e);if(!s)return;const i=o(y(s)[1]);if(!l())return u("@media missing '{'");const n=g().concat(d());return f()?t({type:exports.CssTypes.media,media:i,rules:n}):u("@media missing '}'")}()||function(){const t=m(),s=/^@custom-media\s+(--\S+)\s+([^{;\s][^{;]*);/.exec(e);if(!s)return;const i=y(s);return t({type:exports.CssTypes.customMedia,name:o(i[1]),media:o(i[2])})}()||function(){const t=m(),s=/^@supports *([^{]+)/.exec(e);if(!s)return;const i=o(y(s)[1]);if(!l())return u("@supports missing '{'");const n=g().concat(d());return f()?t({type:exports.CssTypes.supports,supports:i,rules:n}):u("@supports missing '}'")}()||v()||w()||b()||function(){const t=m(),s=/^@([-\w]+)?document *([^{]+)/.exec(e);if(!s)return;const i=y(s),n=o(i[1]),r=o(i[2]);if(!l())return u("@document missing '{'");const c=g().concat(d());return f()?t({type:exports.CssTypes.document,document:r,vendor:n,rules:c}):u("@document missing '}'")}()||function(){const t=m(),s=/^@page */.exec(e);if(!s)return;y(s);const i=T()||[];if(!l())return u("@page missing '{'");let n=g(),r=C();for(;r;)n.push(r),n=n.concat(g()),r=C();return f()?t({type:exports.CssTypes.page,selectors:i,declarations:n}):u("@page missing '}'")}()||function(){const t=m(),s=/^@host\s*/.exec(e);if(!s)return;if(y(s),!l())return u("@host missing '{'");const i=g().concat(d());return f()?t({type:exports.CssTypes.host,rules:i}):u("@host missing '}'")}()||function(){const t=m(),s=/^@font-face\s*/.exec(e);if(!s)return;if(y(s),!l())return u("@font-face missing '{'");let i=g(),n=C();for(;n;)i.push(n),i=i.concat(g()),n=C();return f()?t({type:exports.CssTypes.fontFace,declarations:i}):u("@font-face missing '}'")}()||function(){const t=m(),s=/^@container *([^{]+)/.exec(e);if(!s)return;const i=o(y(s)[1]);if(!l())return u("@container missing '{'");const n=g().concat(d());return f()?t({type:exports.CssTypes.container,container:i,rules:n}):u("@container missing '}'")}()||function(){const t=m(),s=/^@starting-style\s*/.exec(e);if(!s)return;if(y(s),!l())return u("@starting-style missing '{'");const i=g().concat(d());return f()?t({type:exports.CssTypes.startingStyle,rules:i}):u("@starting-style missing '}'")}()||function(){const t=m(),s=/^@layer *([^{;@]+)/.exec(e);if(!s)return;const i=o(y(s)[1]);if(!l()){const s=/^[;\s]*/.exec(e);return s&&y(s),t({type:exports.CssTypes.layer,layer:i})}const n=g().concat(d());return f()?t({type:exports.CssTypes.layer,layer:i,rules:n}):u("@layer missing '}'")}()}function E(){const t=m(),s=T();return s?(g(),t({type:exports.CssTypes.rule,selectors:s,declarations:V()||[]})):u("selector missing")}return c(function(){const t=d();return{type:exports.CssTypes.stylesheet,stylesheet:{source:i?.source,rules:t,parsingErrors:h}}}())},m=(t,s)=>new a(s||{}).compile(t);var h={parse:p,stringify:m};exports.default=h,exports.parse=p,exports.stringify=m; +//# sourceMappingURL=adobe-css-tools.cjs.map diff --git a/node_modules/@adobe/css-tools/dist/cjs/adobe-css-tools.cjs.map b/node_modules/@adobe/css-tools/dist/cjs/adobe-css-tools.cjs.map new file mode 100644 index 00000000..2a984d9c --- /dev/null +++ b/node_modules/@adobe/css-tools/dist/cjs/adobe-css-tools.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"adobe-css-tools.cjs","sources":["../../../src/CssParseError.ts","../../../src/CssPosition.ts","../../../src/type.ts","../../../src/utils/stringSearch.ts","../../../src/parse/index.ts","../../../src/stringify/compiler.ts","../../../src/index.ts","../../../src/stringify/index.ts"],"sourcesContent":[null,null,null,null,null,null,null,null],"names":["CssParseError","Error","reason","filename","line","column","source","constructor","msg","lineno","css","super","this","Position","start","end","CssTypes","indexOfArrayNonEscaped","string","search","position","currentPosition","maxLoop","all","map","v","indexOf","push","foundAll","filter","length","found","Math","min","indexOfArrayWithBracketAndQuoteSupport","currentSearchPosition","firstMatchPos","endPosition","endQuotePosition","commentRegex","trim","str","addParent","obj","parent","isNode","type","childParent","k","value","Array","isArray","forEach","Object","defineProperty","configurable","writable","enumerable","Compiler","level","indentation","compress","options","indent","emit","_position","join","visit","node","stylesheet","rule","declaration","comment","container","charset","document","customMedia","fontFace","host","import","keyframes","keyframe","layer","media","namespace","page","startingStyle","supports","mapVisit","nodes","delim","buf","i","compile","rules","doc","vendor","name","decls","declarations","values","sel","selectors","s","property","split","padEnd","parse","whitespace","errorsList","error","err","silent","open","openMatch","exec","processMatch","close","closeMatch","comments","charAt","atRule","m","lines","match","lastIndexOf","updatePosition","slice","c","pos","selector","result","index","substring","splitWithBracketAndQuoteSupport","replace","propMatch","propValue","separatorMatch","endValuePosition","ret","endMatch","decl","vals","res","spacesMatch","atImport","_compileAtRule","atCharset","atNamespace","re","RegExp","m1","m2","frames","frame","concat","atKeyframes","style","atMedia","atCustomMedia","atSupports","atDocument","atPage","atHost","atFontFace","atContainer","atStartingStyle","atLayer","rulesList","parsingErrors","stringify"],"mappings":"oEAAc,MAAOA,UAAsBC,MAChCC,OACAC,SACAC,KACAC,OACAC,OAET,WAAAC,CACEJ,EACAK,EACAC,EACAJ,EACAK,GAEAC,MAAM,GAAGR,KAAYM,KAAUJ,MAAWG,KAC1CI,KAAKV,OAASM,EACdI,KAAKT,SAAWA,EAChBS,KAAKR,KAAOK,EACZG,KAAKP,OAASA,EACdO,KAAKN,OAASI,CAChB,ECjBY,MAAOG,EACnBC,MACAC,IACAT,OAEA,WAAAC,CACEO,EACAC,EACAT,GAEAM,KAAKE,MAAQA,EACbF,KAAKG,IAAMA,EACXH,KAAKN,OAASA,CAChB,ECbF,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,QAAQzB,GDE1B,IAAAgE,EAAe,CAAEzB,QAAOgE"} \ No newline at end of file diff --git a/node_modules/@adobe/css-tools/dist/cjs/adobe-css-tools.d.cts b/node_modules/@adobe/css-tools/dist/cjs/adobe-css-tools.d.cts new file mode 100644 index 00000000..878ccaf3 --- /dev/null +++ b/node_modules/@adobe/css-tools/dist/cjs/adobe-css-tools.d.cts @@ -0,0 +1,176 @@ +declare class CssParseError extends Error { + readonly reason: string; + readonly filename?: string; + readonly line: number; + readonly column: number; + readonly source: string; + constructor(filename: string, msg: string, lineno: number, column: number, css: string); +} + +/** + * Store position information for a node + */ +declare class Position { + start: { + line: number; + column: number; + }; + end: { + line: number; + column: number; + }; + source?: string; + constructor(start: { + line: number; + column: number; + }, end: { + line: number; + column: number; + }, source: string); +} + +declare enum CssTypes { + stylesheet = "stylesheet", + rule = "rule", + declaration = "declaration", + comment = "comment", + container = "container", + charset = "charset", + document = "document", + customMedia = "custom-media", + fontFace = "font-face", + host = "host", + import = "import", + keyframes = "keyframes", + keyframe = "keyframe", + layer = "layer", + media = "media", + namespace = "namespace", + page = "page", + startingStyle = "starting-style", + supports = "supports" +} +type CssCommonAST = { + type: CssTypes; +}; +type CssCommonPositionAST = CssCommonAST & { + position?: Position; + parent?: unknown; +}; +type CssStylesheetAST = CssCommonAST & { + type: CssTypes.stylesheet; + stylesheet: { + source?: string; + rules: Array; + parsingErrors?: Array; + }; +}; +type CssRuleAST = CssCommonPositionAST & { + type: CssTypes.rule; + selectors: Array; + declarations: Array; +}; +type CssDeclarationAST = CssCommonPositionAST & { + type: CssTypes.declaration; + property: string; + value: string; +}; +type CssCommentAST = CssCommonPositionAST & { + type: CssTypes.comment; + comment: string; +}; +type CssContainerAST = CssCommonPositionAST & { + type: CssTypes.container; + container: string; + rules: Array; +}; +type CssCharsetAST = CssCommonPositionAST & { + type: CssTypes.charset; + charset: string; +}; +type CssCustomMediaAST = CssCommonPositionAST & { + type: CssTypes.customMedia; + name: string; + media: string; +}; +type CssDocumentAST = CssCommonPositionAST & { + type: CssTypes.document; + document: string; + vendor?: string; + rules: Array; +}; +type CssFontFaceAST = CssCommonPositionAST & { + type: CssTypes.fontFace; + declarations: Array; +}; +type CssHostAST = CssCommonPositionAST & { + type: CssTypes.host; + rules: Array; +}; +type CssImportAST = CssCommonPositionAST & { + type: CssTypes.import; + import: string; +}; +type CssKeyframesAST = CssCommonPositionAST & { + type: CssTypes.keyframes; + name: string; + vendor?: string; + keyframes: Array; +}; +type CssKeyframeAST = CssCommonPositionAST & { + type: CssTypes.keyframe; + values: Array; + declarations: Array; +}; +type CssLayerAST = CssCommonPositionAST & { + type: CssTypes.layer; + layer: string; + rules?: Array; +}; +type CssMediaAST = CssCommonPositionAST & { + type: CssTypes.media; + media: string; + rules: Array; +}; +type CssNamespaceAST = CssCommonPositionAST & { + type: CssTypes.namespace; + namespace: string; +}; +type CssPageAST = CssCommonPositionAST & { + type: CssTypes.page; + selectors: Array; + declarations: Array; +}; +type CssSupportsAST = CssCommonPositionAST & { + type: CssTypes.supports; + supports: string; + rules: Array; +}; +type CssStartingStyleAST = CssCommonPositionAST & { + type: CssTypes.startingStyle; + rules: Array; +}; +type CssAtRuleAST = CssRuleAST | CssCommentAST | CssContainerAST | CssCharsetAST | CssCustomMediaAST | CssDocumentAST | CssFontFaceAST | CssHostAST | CssImportAST | CssKeyframesAST | CssLayerAST | CssMediaAST | CssNamespaceAST | CssPageAST | CssSupportsAST | CssStartingStyleAST; +type CssAllNodesAST = CssAtRuleAST | CssStylesheetAST | CssDeclarationAST | CssKeyframeAST; + +type CompilerOptions = { + indent?: string; + compress?: boolean; +}; + +declare const parse: (css: string, options?: { + source?: string; + silent?: boolean; +}) => CssStylesheetAST; +declare const stringify: (node: CssStylesheetAST, options?: CompilerOptions) => string; + +declare const _default: { + parse: (css: string, options?: { + source?: string; + silent?: boolean; + }) => CssStylesheetAST; + stringify: (node: CssStylesheetAST, options?: CompilerOptions) => string; +}; + +export { CssTypes, _default as default, parse, stringify }; +export type { CssAllNodesAST, CssAtRuleAST, CssCharsetAST, CssCommentAST, CssCommonAST, CssCommonPositionAST, CssContainerAST, CssCustomMediaAST, CssDeclarationAST, CssDocumentAST, CssFontFaceAST, CssHostAST, CssImportAST, CssKeyframeAST, CssKeyframesAST, CssLayerAST, CssMediaAST, CssNamespaceAST, CssPageAST, CssRuleAST, CssStartingStyleAST, CssStylesheetAST, CssSupportsAST }; diff --git a/node_modules/@adobe/css-tools/dist/esm/adobe-css-tools.d.mts b/node_modules/@adobe/css-tools/dist/esm/adobe-css-tools.d.mts new file mode 100644 index 00000000..878ccaf3 --- /dev/null +++ b/node_modules/@adobe/css-tools/dist/esm/adobe-css-tools.d.mts @@ -0,0 +1,176 @@ +declare class CssParseError extends Error { + readonly reason: string; + readonly filename?: string; + readonly line: number; + readonly column: number; + readonly source: string; + constructor(filename: string, msg: string, lineno: number, column: number, css: string); +} + +/** + * Store position information for a node + */ +declare class Position { + start: { + line: number; + column: number; + }; + end: { + line: number; + column: number; + }; + source?: string; + constructor(start: { + line: number; + column: number; + }, end: { + line: number; + column: number; + }, source: string); +} + +declare enum CssTypes { + stylesheet = "stylesheet", + rule = "rule", + declaration = "declaration", + comment = "comment", + container = "container", + charset = "charset", + document = "document", + customMedia = "custom-media", + fontFace = "font-face", + host = "host", + import = "import", + keyframes = "keyframes", + keyframe = "keyframe", + layer = "layer", + media = "media", + namespace = "namespace", + page = "page", + startingStyle = "starting-style", + supports = "supports" +} +type CssCommonAST = { + type: CssTypes; +}; +type CssCommonPositionAST = CssCommonAST & { + position?: Position; + parent?: unknown; +}; +type CssStylesheetAST = CssCommonAST & { + type: CssTypes.stylesheet; + stylesheet: { + source?: string; + rules: Array; + parsingErrors?: Array; + }; +}; +type CssRuleAST = CssCommonPositionAST & { + type: CssTypes.rule; + selectors: Array; + declarations: Array; +}; +type CssDeclarationAST = CssCommonPositionAST & { + type: CssTypes.declaration; + property: string; + value: string; +}; +type CssCommentAST = CssCommonPositionAST & { + type: CssTypes.comment; + comment: string; +}; +type CssContainerAST = CssCommonPositionAST & { + type: CssTypes.container; + container: string; + rules: Array; +}; +type CssCharsetAST = CssCommonPositionAST & { + type: CssTypes.charset; + charset: string; +}; +type CssCustomMediaAST = CssCommonPositionAST & { + type: CssTypes.customMedia; + name: string; + media: string; +}; +type CssDocumentAST = CssCommonPositionAST & { + type: CssTypes.document; + document: string; + vendor?: string; + rules: Array; +}; +type CssFontFaceAST = CssCommonPositionAST & { + type: CssTypes.fontFace; + declarations: Array; +}; +type CssHostAST = CssCommonPositionAST & { + type: CssTypes.host; + rules: Array; +}; +type CssImportAST = CssCommonPositionAST & { + type: CssTypes.import; + import: string; +}; +type CssKeyframesAST = CssCommonPositionAST & { + type: CssTypes.keyframes; + name: string; + vendor?: string; + keyframes: Array; +}; +type CssKeyframeAST = CssCommonPositionAST & { + type: CssTypes.keyframe; + values: Array; + declarations: Array; +}; +type CssLayerAST = CssCommonPositionAST & { + type: CssTypes.layer; + layer: string; + rules?: Array; +}; +type CssMediaAST = CssCommonPositionAST & { + type: CssTypes.media; + media: string; + rules: Array; +}; +type CssNamespaceAST = CssCommonPositionAST & { + type: CssTypes.namespace; + namespace: string; +}; +type CssPageAST = CssCommonPositionAST & { + type: CssTypes.page; + selectors: Array; + declarations: Array; +}; +type CssSupportsAST = CssCommonPositionAST & { + type: CssTypes.supports; + supports: string; + rules: Array; +}; +type CssStartingStyleAST = CssCommonPositionAST & { + type: CssTypes.startingStyle; + rules: Array; +}; +type CssAtRuleAST = CssRuleAST | CssCommentAST | CssContainerAST | CssCharsetAST | CssCustomMediaAST | CssDocumentAST | CssFontFaceAST | CssHostAST | CssImportAST | CssKeyframesAST | CssLayerAST | CssMediaAST | CssNamespaceAST | CssPageAST | CssSupportsAST | CssStartingStyleAST; +type CssAllNodesAST = CssAtRuleAST | CssStylesheetAST | CssDeclarationAST | CssKeyframeAST; + +type CompilerOptions = { + indent?: string; + compress?: boolean; +}; + +declare const parse: (css: string, options?: { + source?: string; + silent?: boolean; +}) => CssStylesheetAST; +declare const stringify: (node: CssStylesheetAST, options?: CompilerOptions) => string; + +declare const _default: { + parse: (css: string, options?: { + source?: string; + silent?: boolean; + }) => CssStylesheetAST; + stringify: (node: CssStylesheetAST, options?: CompilerOptions) => string; +}; + +export { CssTypes, _default as default, parse, stringify }; +export type { CssAllNodesAST, CssAtRuleAST, CssCharsetAST, CssCommentAST, CssCommonAST, CssCommonPositionAST, CssContainerAST, CssCustomMediaAST, CssDeclarationAST, CssDocumentAST, CssFontFaceAST, CssHostAST, CssImportAST, CssKeyframeAST, CssKeyframesAST, CssLayerAST, CssMediaAST, CssNamespaceAST, CssPageAST, CssRuleAST, CssStartingStyleAST, CssStylesheetAST, CssSupportsAST }; diff --git a/node_modules/@adobe/css-tools/dist/esm/adobe-css-tools.mjs b/node_modules/@adobe/css-tools/dist/esm/adobe-css-tools.mjs new file mode 100644 index 00000000..4a2195fb --- /dev/null +++ b/node_modules/@adobe/css-tools/dist/esm/adobe-css-tools.mjs @@ -0,0 +1,2 @@ +class t extends Error{reason;filename;line;column;source;constructor(t,e,i,s,n){super(`${t}:${i}:${s}: ${e}`),this.reason=e,this.filename=t,this.line=i,this.column=s,this.source=n}}class e{start;end;source;constructor(t,e,i){this.start=t,this.end=e,this.source=i}}var i;!function(t){t.stylesheet="stylesheet",t.rule="rule",t.declaration="declaration",t.comment="comment",t.container="container",t.charset="charset",t.document="document",t.customMedia="custom-media",t.fontFace="font-face",t.host="host",t.import="import",t.keyframes="keyframes",t.keyframe="keyframe",t.layer="layer",t.media="media",t.namespace="namespace",t.page="page",t.startingStyle="starting-style",t.supports="supports"}(i||(i={}));const s=(t,e,i)=>{let s=i,n=1e4;do{const i=e.map(e=>t.indexOf(e,s));i.push(t.indexOf("\\",s));const r=i.filter(t=>-1!==t);if(0===r.length)return-1;const o=Math.min(...r);if("\\"!==t[o])return o;s=o+2,n--}while(n>0);throw new Error("Too many escaping")},n=(t,e,i)=>{let r=i,o=1e4;do{const i=e.map(e=>t.indexOf(e,r));i.push(t.indexOf("(",r)),i.push(t.indexOf('"',r)),i.push(t.indexOf("'",r)),i.push(t.indexOf("\\",r));const c=i.filter(t=>-1!==t);if(0===c.length)return-1;const a=Math.min(...c);switch(t[a]){case"\\":r=a+2;break;case"(":{const e=n(t,[")"],a+1);if(-1===e)return-1;r=e+1}break;case'"':{const e=s(t,['"'],a+1);if(-1===e)return-1;r=e+1}break;case"'":{const e=s(t,["'"],a+1);if(-1===e)return-1;r=e+1}break;default:return a}o--}while(o>0);throw new Error("Too many escaping")},r=/\/\*[^]*?(?:\*\/|$)/g;function o(t){return t?t.trim():""}function c(t,e){const i=t&&"string"==typeof t.type,s=i?t:e;for(const e in t){const i=t[e];Array.isArray(i)?i.forEach(t=>{c(t,s)}):i&&"object"==typeof i&&c(i,s)}return i&&Object.defineProperty(t,"parent",{configurable:!0,writable:!0,enumerable:!1,value:e||null}),t}class a{level=0;indentation=" ";compress=!1;constructor(t){"string"==typeof t?.indent&&(this.indentation=t?.indent),t?.compress&&(this.compress=!0)}emit(t,e){return t}indent(t){return this.level=this.level||1,t?(this.level+=t,""):Array(this.level).join(this.indentation)}visit(t){switch(t.type){case i.stylesheet:return this.stylesheet(t);case i.rule:return this.rule(t);case i.declaration:return this.declaration(t);case i.comment:return this.comment(t);case i.container:return this.container(t);case i.charset:return this.charset(t);case i.document:return this.document(t);case i.customMedia:return this.customMedia(t);case i.fontFace:return this.fontFace(t);case i.host:return this.host(t);case i.import:return this.import(t);case i.keyframes:return this.keyframes(t);case i.keyframe:return this.keyframe(t);case i.layer:return this.layer(t);case i.media:return this.media(t);case i.namespace:return this.namespace(t);case i.page:return this.page(t);case i.startingStyle:return this.startingStyle(t);case i.supports:return this.supports(t)}}mapVisit(t,e){let i="";e=e||"";for(let s=0,n=t.length;si+t).join(",\n"),t.position)+this.emit(" {\n")+this.emit(this.indent(1))+this.mapVisit(e,"\n")+this.emit(this.indent(-1))+this.emit(`\n${this.indent()}}`)}declaration(t){return this.compress?this.emit(`${t.property}:${t.value}`,t.position)+this.emit(";"):"grid-template-areas"===t.property?this.emit(this.indent())+this.emit(t.property+": "+t.value.split("\n").join("\n".padEnd(22)+this.indent()),t.position)+this.emit(";"):this.emit(this.indent())+this.emit(`${t.property}: ${t.value}`,t.position)+this.emit(";")}}const m=(s,a)=>{a=a||{};let m=1,h=1;function u(){const t={line:m,column:h};return i=>(i.position=new e(t,{line:m,column:h},a?.source||""),$(),i)}const p=[];function l(e){const i=new t(a?.source||"",e,m,h,s);if(!a?.silent)throw i;p.push(i)}function f(){const t=/^{\s*/.exec(s);return!!t&&(g(t),!0)}function d(){const t=/^}/.exec(s);return!!t&&(g(t),!0)}function y(){let t;const e=[];for($(),x(e);s.length&&"}"!==s.charAt(0)&&(t=A()||S(),t);)e.push(t),x(e);return e}function g(t){const e=t[0];return function(t){const e=t.match(/\n/g);e&&(m+=e.length);const i=t.lastIndexOf("\n");h=~i?t.length-i:h+t.length}(e),s=s.slice(e.length),t}function $(){const t=/^\s*/.exec(s);t&&g(t)}function x(t){t=t||[];let e=V();for(;e;)t.push(e),e=V();return t}function V(){const t=u();if("/"!==s.charAt(0)||"*"!==s.charAt(1))return;const e=/^\/\*[^]*?\*\//.exec(s);return e?(g(e),t({type:i.comment,comment:e[0].slice(2,-2)})):l("End of comment missing")}function k(){const t=/^([^{]+)/.exec(s);if(!t)return;g(t);return((t,e)=>{const i=[];let s=0;for(;so(t))}function v(){const t=u(),e=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/.exec(s);if(!e)return;g(e);const c=o(e[0]),a=/^:\s*/.exec(s);if(!a)return l("property missing ':'");g(a);let m="";const h=n(s,[";","}"]);if(-1!==h){m=s.substring(0,h);g([m]),m=o(m).replace(r,"")}const p=t({type:i.declaration,property:c.replace(r,""),value:m}),f=/^[;\s]*/.exec(s);return f&&g(f),p}function w(){const t=[];if(!f())return l("missing '{'");x(t);let e=v();for(;e;)t.push(e),x(t),e=v();return d()?t:l("missing '}'")}function b(){const t=[],e=u();let n=/^((\d+\.\d+|\.\d+|\d+)%?|[a-z]+)\s*/.exec(s);for(;n;){const e=g(n);t.push(e[1]);const i=/^,\s*/.exec(s);i&&g(i),n=/^((\d+\.\d+|\.\d+|\d+)%?|[a-z]+)\s*/.exec(s)}if(t.length)return e({type:i.keyframe,values:t,declarations:w()||[]})}const j=M("import"),O=M("charset"),E=M("namespace");function M(t){const e=new RegExp("^@"+t+"\\s*((?::?[^;'\"]|\"(?:\\\\\"|[^\"])*?\"|'(?:\\\\'|[^'])*?')+)(?:;|$)");return()=>{const i=u(),n=e.exec(s);if(!n)return;const r=g(n),o={type:t};return o[t]=r[1].trim(),i(o)}}function A(){if("@"===s[0])return function(){const t=u(),e=/^@([-\w]+)?keyframes\s*/.exec(s);if(!e)return;const n=g(e)[1],r=/^([-\w]+)\s*/.exec(s);if(!r)return l("@keyframes missing name");const o=g(r)[1];if(!f())return l("@keyframes missing '{'");let c=x(),a=b();for(;a;)c.push(a),c=c.concat(x()),a=b();return d()?t({type:i.keyframes,name:o,vendor:n,keyframes:c}):l("@keyframes missing '}'")}()||function(){const t=u(),e=/^@media *([^{]+)/.exec(s);if(!e)return;const n=o(g(e)[1]);if(!f())return l("@media missing '{'");const r=x().concat(y());return d()?t({type:i.media,media:n,rules:r}):l("@media missing '}'")}()||function(){const t=u(),e=/^@custom-media\s+(--\S+)\s+([^{;\s][^{;]*);/.exec(s);if(!e)return;const n=g(e);return t({type:i.customMedia,name:o(n[1]),media:o(n[2])})}()||function(){const t=u(),e=/^@supports *([^{]+)/.exec(s);if(!e)return;const n=o(g(e)[1]);if(!f())return l("@supports missing '{'");const r=x().concat(y());return d()?t({type:i.supports,supports:n,rules:r}):l("@supports missing '}'")}()||j()||O()||E()||function(){const t=u(),e=/^@([-\w]+)?document *([^{]+)/.exec(s);if(!e)return;const n=g(e),r=o(n[1]),c=o(n[2]);if(!f())return l("@document missing '{'");const a=x().concat(y());return d()?t({type:i.document,document:c,vendor:r,rules:a}):l("@document missing '}'")}()||function(){const t=u(),e=/^@page */.exec(s);if(!e)return;g(e);const n=k()||[];if(!f())return l("@page missing '{'");let r=x(),o=v();for(;o;)r.push(o),r=r.concat(x()),o=v();return d()?t({type:i.page,selectors:n,declarations:r}):l("@page missing '}'")}()||function(){const t=u(),e=/^@host\s*/.exec(s);if(!e)return;if(g(e),!f())return l("@host missing '{'");const n=x().concat(y());return d()?t({type:i.host,rules:n}):l("@host missing '}'")}()||function(){const t=u(),e=/^@font-face\s*/.exec(s);if(!e)return;if(g(e),!f())return l("@font-face missing '{'");let n=x(),r=v();for(;r;)n.push(r),n=n.concat(x()),r=v();return d()?t({type:i.fontFace,declarations:n}):l("@font-face missing '}'")}()||function(){const t=u(),e=/^@container *([^{]+)/.exec(s);if(!e)return;const n=o(g(e)[1]);if(!f())return l("@container missing '{'");const r=x().concat(y());return d()?t({type:i.container,container:n,rules:r}):l("@container missing '}'")}()||function(){const t=u(),e=/^@starting-style\s*/.exec(s);if(!e)return;if(g(e),!f())return l("@starting-style missing '{'");const n=x().concat(y());return d()?t({type:i.startingStyle,rules:n}):l("@starting-style missing '}'")}()||function(){const t=u(),e=/^@layer *([^{;@]+)/.exec(s);if(!e)return;const n=o(g(e)[1]);if(!f()){const e=/^[;\s]*/.exec(s);return e&&g(e),t({type:i.layer,layer:n})}const r=x().concat(y());return d()?t({type:i.layer,layer:n,rules:r}):l("@layer missing '}'")}()}function S(){const t=u(),e=k();return e?(x(),t({type:i.rule,selectors:e,declarations:w()||[]})):l("selector missing")}return c(function(){const t=y();return{type:i.stylesheet,stylesheet:{source:a?.source,rules:t,parsingErrors:p}}}())},h=(t,e)=>new a(e||{}).compile(t);var u={parse:m,stringify:h};export{i as CssTypes,u as default,m as parse,h as stringify}; +//# sourceMappingURL=adobe-css-tools.mjs.map diff --git a/node_modules/@adobe/css-tools/dist/esm/adobe-css-tools.mjs.map b/node_modules/@adobe/css-tools/dist/esm/adobe-css-tools.mjs.map new file mode 100644 index 00000000..6ae214ee --- /dev/null +++ b/node_modules/@adobe/css-tools/dist/esm/adobe-css-tools.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"adobe-css-tools.mjs","sources":["../../../src/CssParseError.ts","../../../src/CssPosition.ts","../../../src/type.ts","../../../src/utils/stringSearch.ts","../../../src/parse/index.ts","../../../src/stringify/compiler.ts","../../../src/index.ts","../../../src/stringify/index.ts"],"sourcesContent":[null,null,null,null,null,null,null,null],"names":["CssParseError","Error","reason","filename","line","column","source","constructor","msg","lineno","css","super","this","Position","start","end","CssTypes","indexOfArrayNonEscaped","string","search","position","currentPosition","maxLoop","all","map","v","indexOf","push","foundAll","filter","length","found","Math","min","indexOfArrayWithBracketAndQuoteSupport","currentSearchPosition","firstMatchPos","endPosition","endQuotePosition","commentRegex","trim","str","addParent","obj","parent","isNode","type","childParent","k","value","Array","isArray","forEach","Object","defineProperty","configurable","writable","enumerable","Compiler","level","indentation","compress","options","indent","emit","_position","join","visit","node","stylesheet","rule","declaration","comment","container","charset","document","customMedia","fontFace","host","import","keyframes","keyframe","layer","media","namespace","page","startingStyle","supports","mapVisit","nodes","delim","buf","i","compile","rules","doc","vendor","name","decls","declarations","values","sel","selectors","s","property","split","padEnd","parse","whitespace","errorsList","error","err","silent","open","openMatch","exec","processMatch","close","closeMatch","comments","charAt","atRule","m","lines","match","lastIndexOf","updatePosition","slice","c","pos","selector","result","index","substring","splitWithBracketAndQuoteSupport","replace","propMatch","propValue","separatorMatch","endValuePosition","ret","endMatch","decl","vals","res","spacesMatch","atImport","_compileAtRule","atCharset","atNamespace","re","RegExp","m1","m2","frames","frame","concat","atKeyframes","style","atMedia","atCustomMedia","atSupports","atDocument","atPage","atHost","atFontFace","atContainer","atStartingStyle","atLayer","rulesList","parsingErrors","stringify"],"mappings":"AAAc,MAAOA,UAAsBC,MAChCC,OACAC,SACAC,KACAC,OACAC,OAET,WAAAC,CACEJ,EACAK,EACAC,EACAJ,EACAK,GAEAC,MAAM,GAAGR,KAAYM,KAAUJ,MAAW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,EAAe,CAAEzB,QAAOgE"} \ No newline at end of file diff --git a/node_modules/@adobe/css-tools/dist/umd/adobe-css-tools.d.ts b/node_modules/@adobe/css-tools/dist/umd/adobe-css-tools.d.ts new file mode 100644 index 00000000..878ccaf3 --- /dev/null +++ b/node_modules/@adobe/css-tools/dist/umd/adobe-css-tools.d.ts @@ -0,0 +1,176 @@ +declare class CssParseError extends Error { + readonly reason: string; + readonly filename?: string; + readonly line: number; + readonly column: number; + readonly source: string; + constructor(filename: string, msg: string, lineno: number, column: number, css: string); +} + +/** + * Store position information for a node + */ +declare class Position { + start: { + line: number; + column: number; + }; + end: { + line: number; + column: number; + }; + source?: string; + constructor(start: { + line: number; + column: number; + }, end: { + line: number; + column: number; + }, source: string); +} + +declare enum CssTypes { + stylesheet = "stylesheet", + rule = "rule", + declaration = "declaration", + comment = "comment", + container = "container", + charset = "charset", + document = "document", + customMedia = "custom-media", + fontFace = "font-face", + host = "host", + import = "import", + keyframes = "keyframes", + keyframe = "keyframe", + layer = "layer", + media = "media", + namespace = "namespace", + page = "page", + startingStyle = "starting-style", + supports = "supports" +} +type CssCommonAST = { + type: CssTypes; +}; +type CssCommonPositionAST = CssCommonAST & { + position?: Position; + parent?: unknown; +}; +type CssStylesheetAST = CssCommonAST & { + type: CssTypes.stylesheet; + stylesheet: { + source?: string; + rules: Array; + parsingErrors?: Array; + }; +}; +type CssRuleAST = CssCommonPositionAST & { + type: CssTypes.rule; + selectors: Array; + declarations: Array; +}; +type CssDeclarationAST = CssCommonPositionAST & { + type: CssTypes.declaration; + property: string; + value: string; +}; +type CssCommentAST = CssCommonPositionAST & { + type: CssTypes.comment; + comment: string; +}; +type CssContainerAST = CssCommonPositionAST & { + type: CssTypes.container; + container: string; + rules: Array; +}; +type CssCharsetAST = CssCommonPositionAST & { + type: CssTypes.charset; + charset: string; +}; +type CssCustomMediaAST = CssCommonPositionAST & { + type: CssTypes.customMedia; + name: string; + media: string; +}; +type CssDocumentAST = CssCommonPositionAST & { + type: CssTypes.document; + document: string; + vendor?: string; + rules: Array; +}; +type CssFontFaceAST = CssCommonPositionAST & { + type: CssTypes.fontFace; + declarations: Array; +}; +type CssHostAST = CssCommonPositionAST & { + type: CssTypes.host; + rules: Array; +}; +type CssImportAST = CssCommonPositionAST & { + type: CssTypes.import; + import: string; +}; +type CssKeyframesAST = CssCommonPositionAST & { + type: CssTypes.keyframes; + name: string; + vendor?: string; + keyframes: Array; +}; +type CssKeyframeAST = CssCommonPositionAST & { + type: CssTypes.keyframe; + values: Array; + declarations: Array; +}; +type CssLayerAST = CssCommonPositionAST & { + type: CssTypes.layer; + layer: string; + rules?: Array; +}; +type CssMediaAST = CssCommonPositionAST & { + type: CssTypes.media; + media: string; + rules: Array; +}; +type CssNamespaceAST = CssCommonPositionAST & { + type: CssTypes.namespace; + namespace: string; +}; +type CssPageAST = CssCommonPositionAST & { + type: CssTypes.page; + selectors: Array; + declarations: Array; +}; +type CssSupportsAST = CssCommonPositionAST & { + type: CssTypes.supports; + supports: string; + rules: Array; +}; +type CssStartingStyleAST = CssCommonPositionAST & { + type: CssTypes.startingStyle; + rules: Array; +}; +type CssAtRuleAST = CssRuleAST | CssCommentAST | CssContainerAST | CssCharsetAST | CssCustomMediaAST | CssDocumentAST | CssFontFaceAST | CssHostAST | CssImportAST | CssKeyframesAST | CssLayerAST | CssMediaAST | CssNamespaceAST | CssPageAST | CssSupportsAST | CssStartingStyleAST; +type CssAllNodesAST = CssAtRuleAST | CssStylesheetAST | CssDeclarationAST | CssKeyframeAST; + +type CompilerOptions = { + indent?: string; + compress?: boolean; +}; + +declare const parse: (css: string, options?: { + source?: string; + silent?: boolean; +}) => CssStylesheetAST; +declare const stringify: (node: CssStylesheetAST, options?: CompilerOptions) => string; + +declare const _default: { + parse: (css: string, options?: { + source?: string; + silent?: boolean; + }) => CssStylesheetAST; + stringify: (node: CssStylesheetAST, options?: CompilerOptions) => string; +}; + +export { CssTypes, _default as default, parse, stringify }; +export type { CssAllNodesAST, CssAtRuleAST, CssCharsetAST, CssCommentAST, CssCommonAST, CssCommonPositionAST, CssContainerAST, CssCustomMediaAST, CssDeclarationAST, CssDocumentAST, CssFontFaceAST, CssHostAST, CssImportAST, CssKeyframeAST, CssKeyframesAST, CssLayerAST, CssMediaAST, CssNamespaceAST, CssPageAST, CssRuleAST, CssStartingStyleAST, CssStylesheetAST, CssSupportsAST }; diff --git a/node_modules/@adobe/css-tools/dist/umd/adobe-css-tools.js b/node_modules/@adobe/css-tools/dist/umd/adobe-css-tools.js new file mode 100644 index 00000000..d5fc3f62 --- /dev/null +++ b/node_modules/@adobe/css-tools/dist/umd/adobe-css-tools.js @@ -0,0 +1,2 @@ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).cssTools={})}(this,function(t){"use strict";class e extends Error{reason;filename;line;column;source;constructor(t,e,s,i,n){super(`${t}:${s}:${i}: ${e}`),this.reason=e,this.filename=t,this.line=s,this.column=i,this.source=n}}class s{start;end;source;constructor(t,e,s){this.start=t,this.end=e,this.source=s}}var i;t.CssTypes=void 0,(i=t.CssTypes||(t.CssTypes={})).stylesheet="stylesheet",i.rule="rule",i.declaration="declaration",i.comment="comment",i.container="container",i.charset="charset",i.document="document",i.customMedia="custom-media",i.fontFace="font-face",i.host="host",i.import="import",i.keyframes="keyframes",i.keyframe="keyframe",i.layer="layer",i.media="media",i.namespace="namespace",i.page="page",i.startingStyle="starting-style",i.supports="supports";const n=(t,e,s)=>{let i=s,n=1e4;do{const s=e.map(e=>t.indexOf(e,i));s.push(t.indexOf("\\",i));const r=s.filter(t=>-1!==t);if(0===r.length)return-1;const o=Math.min(...r);if("\\"!==t[o])return o;i=o+2,n--}while(n>0);throw new Error("Too many escaping")},r=(t,e,s)=>{let i=s,o=1e4;do{const s=e.map(e=>t.indexOf(e,i));s.push(t.indexOf("(",i)),s.push(t.indexOf('"',i)),s.push(t.indexOf("'",i)),s.push(t.indexOf("\\",i));const c=s.filter(t=>-1!==t);if(0===c.length)return-1;const a=Math.min(...c);switch(t[a]){case"\\":i=a+2;break;case"(":{const e=r(t,[")"],a+1);if(-1===e)return-1;i=e+1}break;case'"':{const e=n(t,['"'],a+1);if(-1===e)return-1;i=e+1}break;case"'":{const e=n(t,["'"],a+1);if(-1===e)return-1;i=e+1}break;default:return a}o--}while(o>0);throw new Error("Too many escaping")},o=/\/\*[^]*?(?:\*\/|$)/g;function c(t){return t?t.trim():""}function a(t,e){const s=t&&"string"==typeof t.type,i=s?t:e;for(const e in t){const s=t[e];Array.isArray(s)?s.forEach(t=>{a(t,i)}):s&&"object"==typeof s&&a(s,i)}return s&&Object.defineProperty(t,"parent",{configurable:!0,writable:!0,enumerable:!1,value:e||null}),t}class h{level=0;indentation=" ";compress=!1;constructor(t){"string"==typeof t?.indent&&(this.indentation=t?.indent),t?.compress&&(this.compress=!0)}emit(t,e){return t}indent(t){return this.level=this.level||1,t?(this.level+=t,""):Array(this.level).join(this.indentation)}visit(e){switch(e.type){case t.CssTypes.stylesheet:return this.stylesheet(e);case t.CssTypes.rule:return this.rule(e);case t.CssTypes.declaration:return this.declaration(e);case t.CssTypes.comment:return this.comment(e);case t.CssTypes.container:return this.container(e);case t.CssTypes.charset:return this.charset(e);case t.CssTypes.document:return this.document(e);case t.CssTypes.customMedia:return this.customMedia(e);case t.CssTypes.fontFace:return this.fontFace(e);case t.CssTypes.host:return this.host(e);case t.CssTypes.import:return this.import(e);case t.CssTypes.keyframes:return this.keyframes(e);case t.CssTypes.keyframe:return this.keyframe(e);case t.CssTypes.layer:return this.layer(e);case t.CssTypes.media:return this.media(e);case t.CssTypes.namespace:return this.namespace(e);case t.CssTypes.page:return this.page(e);case t.CssTypes.startingStyle:return this.startingStyle(e);case t.CssTypes.supports:return this.supports(e)}}mapVisit(t,e){let s="";e=e||"";for(let i=0,n=t.length;is+t).join(",\n"),t.position)+this.emit(" {\n")+this.emit(this.indent(1))+this.mapVisit(e,"\n")+this.emit(this.indent(-1))+this.emit(`\n${this.indent()}}`)}declaration(t){return this.compress?this.emit(`${t.property}:${t.value}`,t.position)+this.emit(";"):"grid-template-areas"===t.property?this.emit(this.indent())+this.emit(t.property+": "+t.value.split("\n").join("\n".padEnd(22)+this.indent()),t.position)+this.emit(";"):this.emit(this.indent())+this.emit(`${t.property}: ${t.value}`,t.position)+this.emit(";")}}const m=(i,n)=>{n=n||{};let h=1,m=1;function u(){const t={line:h,column:m};return e=>(e.position=new s(t,{line:h,column:m},n?.source||""),$(),e)}const p=[];function l(t){const s=new e(n?.source||"",t,h,m,i);if(!n?.silent)throw s;p.push(s)}function f(){const t=/^{\s*/.exec(i);return!!t&&(g(t),!0)}function d(){const t=/^}/.exec(i);return!!t&&(g(t),!0)}function y(){let t;const e=[];for($(),T(e);i.length&&"}"!==i.charAt(0)&&(t=E()||M(),t);)e.push(t),T(e);return e}function g(t){const e=t[0];return function(t){const e=t.match(/\n/g);e&&(h+=e.length);const s=t.lastIndexOf("\n");m=~s?t.length-s:m+t.length}(e),i=i.slice(e.length),t}function $(){const t=/^\s*/.exec(i);t&&g(t)}function T(t){t=t||[];let e=C();for(;e;)t.push(e),e=C();return t}function C(){const e=u();if("/"!==i.charAt(0)||"*"!==i.charAt(1))return;const s=/^\/\*[^]*?\*\//.exec(i);return s?(g(s),e({type:t.CssTypes.comment,comment:s[0].slice(2,-2)})):l("End of comment missing")}function x(){const t=/^([^{]+)/.exec(i);if(!t)return;g(t);return((t,e)=>{const s=[];let i=0;for(;ic(t))}function V(){const e=u(),s=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/.exec(i);if(!s)return;g(s);const n=c(s[0]),a=/^:\s*/.exec(i);if(!a)return l("property missing ':'");g(a);let h="";const m=r(i,[";","}"]);if(-1!==m){h=i.substring(0,m);g([h]),h=c(h).replace(o,"")}const p=e({type:t.CssTypes.declaration,property:n.replace(o,""),value:h}),f=/^[;\s]*/.exec(i);return f&&g(f),p}function k(){const t=[];if(!f())return l("missing '{'");T(t);let e=V();for(;e;)t.push(e),T(t),e=V();return d()?t:l("missing '}'")}function v(){const e=[],s=u();let n=/^((\d+\.\d+|\.\d+|\d+)%?|[a-z]+)\s*/.exec(i);for(;n;){const t=g(n);e.push(t[1]);const s=/^,\s*/.exec(i);s&&g(s),n=/^((\d+\.\d+|\.\d+|\d+)%?|[a-z]+)\s*/.exec(i)}if(e.length)return s({type:t.CssTypes.keyframe,values:e,declarations:k()||[]})}const w=O("import"),b=O("charset"),j=O("namespace");function O(t){const e=new RegExp("^@"+t+"\\s*((?::?[^;'\"]|\"(?:\\\\\"|[^\"])*?\"|'(?:\\\\'|[^'])*?')+)(?:;|$)");return()=>{const s=u(),n=e.exec(i);if(!n)return;const r=g(n),o={type:t};return o[t]=r[1].trim(),s(o)}}function E(){if("@"===i[0])return function(){const e=u(),s=/^@([-\w]+)?keyframes\s*/.exec(i);if(!s)return;const n=g(s)[1],r=/^([-\w]+)\s*/.exec(i);if(!r)return l("@keyframes missing name");const o=g(r)[1];if(!f())return l("@keyframes missing '{'");let c=T(),a=v();for(;a;)c.push(a),c=c.concat(T()),a=v();return d()?e({type:t.CssTypes.keyframes,name:o,vendor:n,keyframes:c}):l("@keyframes missing '}'")}()||function(){const e=u(),s=/^@media *([^{]+)/.exec(i);if(!s)return;const n=c(g(s)[1]);if(!f())return l("@media missing '{'");const r=T().concat(y());return d()?e({type:t.CssTypes.media,media:n,rules:r}):l("@media missing '}'")}()||function(){const e=u(),s=/^@custom-media\s+(--\S+)\s+([^{;\s][^{;]*);/.exec(i);if(!s)return;const n=g(s);return e({type:t.CssTypes.customMedia,name:c(n[1]),media:c(n[2])})}()||function(){const e=u(),s=/^@supports *([^{]+)/.exec(i);if(!s)return;const n=c(g(s)[1]);if(!f())return l("@supports missing '{'");const r=T().concat(y());return d()?e({type:t.CssTypes.supports,supports:n,rules:r}):l("@supports missing '}'")}()||w()||b()||j()||function(){const e=u(),s=/^@([-\w]+)?document *([^{]+)/.exec(i);if(!s)return;const n=g(s),r=c(n[1]),o=c(n[2]);if(!f())return l("@document missing '{'");const a=T().concat(y());return d()?e({type:t.CssTypes.document,document:o,vendor:r,rules:a}):l("@document missing '}'")}()||function(){const e=u(),s=/^@page */.exec(i);if(!s)return;g(s);const n=x()||[];if(!f())return l("@page missing '{'");let r=T(),o=V();for(;o;)r.push(o),r=r.concat(T()),o=V();return d()?e({type:t.CssTypes.page,selectors:n,declarations:r}):l("@page missing '}'")}()||function(){const e=u(),s=/^@host\s*/.exec(i);if(!s)return;if(g(s),!f())return l("@host missing '{'");const n=T().concat(y());return d()?e({type:t.CssTypes.host,rules:n}):l("@host missing '}'")}()||function(){const e=u(),s=/^@font-face\s*/.exec(i);if(!s)return;if(g(s),!f())return l("@font-face missing '{'");let n=T(),r=V();for(;r;)n.push(r),n=n.concat(T()),r=V();return d()?e({type:t.CssTypes.fontFace,declarations:n}):l("@font-face missing '}'")}()||function(){const e=u(),s=/^@container *([^{]+)/.exec(i);if(!s)return;const n=c(g(s)[1]);if(!f())return l("@container missing '{'");const r=T().concat(y());return d()?e({type:t.CssTypes.container,container:n,rules:r}):l("@container missing '}'")}()||function(){const e=u(),s=/^@starting-style\s*/.exec(i);if(!s)return;if(g(s),!f())return l("@starting-style missing '{'");const n=T().concat(y());return d()?e({type:t.CssTypes.startingStyle,rules:n}):l("@starting-style missing '}'")}()||function(){const e=u(),s=/^@layer *([^{;@]+)/.exec(i);if(!s)return;const n=c(g(s)[1]);if(!f()){const s=/^[;\s]*/.exec(i);return s&&g(s),e({type:t.CssTypes.layer,layer:n})}const r=T().concat(y());return d()?e({type:t.CssTypes.layer,layer:n,rules:r}):l("@layer missing '}'")}()}function M(){const e=u(),s=x();return s?(T(),e({type:t.CssTypes.rule,selectors:s,declarations:k()||[]})):l("selector missing")}return a(function(){const e=y();return{type:t.CssTypes.stylesheet,stylesheet:{source:n?.source,rules:e,parsingErrors:p}}}())},u=(t,e)=>new h(e||{}).compile(t);var p={parse:m,stringify:u};t.default=p,t.parse=m,t.stringify=u,Object.defineProperty(t,"__esModule",{value:!0})}); +//# sourceMappingURL=adobe-css-tools.js.map diff --git a/node_modules/@adobe/css-tools/dist/umd/adobe-css-tools.js.map b/node_modules/@adobe/css-tools/dist/umd/adobe-css-tools.js.map new file mode 100644 index 00000000..af7b79d4 --- /dev/null +++ b/node_modules/@adobe/css-tools/dist/umd/adobe-css-tools.js.map @@ -0,0 +1 @@ +{"version":3,"file":"adobe-css-tools.js","sources":["../../../src/CssParseError.ts","../../../src/CssPosition.ts","../../../src/type.ts","../../../src/utils/stringSearch.ts","../../../src/parse/index.ts","../../../src/stringify/compiler.ts","../../../src/index.ts","../../../src/stringify/index.ts"],"sourcesContent":[null,null,null,null,null,null,null,null],"names":["CssParseError","Error","reason","filename","line","column","source","constructor","msg","lineno","css","super","this","Position","start","end","CssTypes","indexOfArrayNonEscaped","string","search","position","currentPosition","maxLoop","all","map","v","indexOf","push","foundAll","filter","length","found","Math","min","indexOfArrayWithBracketAndQuoteSupport","currentSearchPosition","firstMatchPos","endPosition","endQuotePosition","commentRegex","trim","str","addParent","obj","parent","isNode","type","childParent","k","value","Array","isArray","forEach","Object","defineProperty","configurable","writable","enumerable","Compiler","level","indentation","compress","options","indent","emit","_position","join","visit","node","stylesheet","rule","declaration","comment","container","charset","document","customMedia","fontFace","host","import","keyframes","keyframe","layer","media","namespace","page","startingStyle","supports","mapVisit","nodes","delim","buf","i","compile","rules","doc","vendor","name","decls","declarations","values","sel","selectors","s","property","split","padEnd","parse","whitespace","errorsList","error","err","silent","open","openMatch","exec","processMatch","close","closeMatch","comments","charAt","atRule","m","lines","match","lastIndexOf","updatePosition","slice","c","pos","selector","result","index","substring","splitWithBracketAndQuoteSupport","replace","propMatch","propValue","separatorMatch","endValuePosition","ret","endMatch","decl","vals","res","spacesMatch","atImport","_compileAtRule","atCharset","atNamespace","re","RegExp","m1","m2","frames","frame","concat","atKeyframes","style","atMedia","atCustomMedia","atSupports","atDocument","atPage","atHost","atFontFace","atContainer","atStartingStyle","atLayer","rulesList","parsingErrors","stringify"],"mappings":"+OAAc,MAAOA,UAAsBC,MAChCC,OACAC,SACAC,KACAC,OACAC,OAET,WAAAC,CACEJ,EACAK,EACAC,EACAJ,EACAK,GAEAC,MAAM,GAAGR,KAAYM,KAAUJ,MAAWG,KAC1CI,KAAKV,OAASM,EACdI,KAAKT,SAAWA,EAChBS,KAAKR,KAAOK,EACZG,KAAKP,OAASA,EACdO,KAAKN,OAASI,CAChB,ECjBY,MAAOG,EACnBC,MACAC,IACAT,OAEA,WAAAC,CACEO,EACAC,EACAT,GAEAM,KAAKE,MAAQA,EACbF,KAAKG,IAAMA,EACXH,KAAKN,OAASA,CAChB,ECbF,IAAYU,EAAAA,EAAAA,cAAAA,GAAAA,EAAAA,EAAAA,WAAAA,WAAQ,CAAA,IAClB,WAAA,aACAA,EAAA,KAAA,OACAA,EAAA,YAAA,cACAA,EAAA,QAAA,UACAA,EAAA,UAAA,YACAA,EAAA,QAAA,UACAA,EAAA,SAAA,WACAA,EAAA,YAAA,eACAA,EAAA,SAAA,YACAA,EAAA,KAAA,OACAA,EAAA,OAAA,SACAA,EAAA,UAAA,YACAA,EAAA,SAAA,WACAA,EAAA,MAAA,QACAA,EAAA,MAAA,QACAA,EAAA,UAAA,YACAA,EAAA,KAAA,OACAA,EAAA,cAAA,iBACAA,EAAA,SAAA,WCtBK,MAkBMC,EAAyB,CACpCC,EACAC,EACAC,KAEA,IAAIC,EAAkBD,EAClBE,EAxBkB,IAyBtB,EAAG,CACD,MAAMC,EAAMJ,EAAOK,IAAKC,GAAMP,EAAOQ,QAAQD,EAAGJ,IAChDE,EAAII,KAAKT,EAAOQ,QAAQ,KAAML,IAC9B,MAAMO,EAAWL,EAAIM,OAAQJ,QAAMA,GACnC,GAAwB,IAApBG,EAASE,OACX,OAAO,EAGT,MAAMC,EAAQC,KAAKC,OAAOL,GAC1B,GAAsB,OAAlBV,EAAOa,GAIT,OAAOA,EAHPV,EAAkBU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jB,CAkPI0D,EAEJ,CAKA,SAASlG,IACP,MAAM2D,EAAM7G,IACNiF,EAAM6B,IAEZ,OAAK7B,GAGLkB,IAEOU,EAAgB,CACrBnF,KAAM9B,EAAAA,SAASsD,KACfgC,UAAWD,EACXF,aAAcA,KAAkB,MAPzBW,EAAM,mBASjB,CAEA,OAAOpE,EAzpBP,WACE,MAAM+H,EAAY3E,IAWlB,MATiC,CAC/BhD,KAAM9B,EAAAA,SAASqD,WACfA,WAAY,CACV/D,OAAQwD,GAASxD,OACjBwF,MAAO2E,EACPC,cAAe7D,GAKrB,CA4oBiBxC,KE7vBNsG,ECAE,CAACvG,EAAwBN,IACrB,IAAIJ,EAASI,GAAW,CAAA,GACzB+B,QAAQzB,GDE1B,IAAAgE,EAAe,CAAEzB,QAAOgE"} \ No newline at end of file diff --git a/node_modules/@adobe/css-tools/docs/API.md b/node_modules/@adobe/css-tools/docs/API.md new file mode 100644 index 00000000..35f178c7 --- /dev/null +++ b/node_modules/@adobe/css-tools/docs/API.md @@ -0,0 +1,314 @@ +# API Reference + +## Overview + +`@adobe/css-tools` provides a modern CSS parser and stringifier with comprehensive TypeScript support. It can parse CSS into an Abstract Syntax Tree (AST) and convert the AST back to CSS with various formatting options. + +## Installation + +```bash +npm install @adobe/css-tools +``` + +## Core Functions + +### `parse(code, options?)` + +Parses CSS code and returns an Abstract Syntax Tree (AST). + +#### Parameters + +- `code` (string) - The CSS code to parse +- `options` (object, optional) - Parsing options + - `silent` (boolean) - Silently fail on parse errors instead of throwing. When `true`, errors are collected in `ast.stylesheet.parsingErrors` + - `source` (string) - File path for better error reporting + +#### Returns + +- `CssStylesheetAST` - The parsed CSS as an AST + +#### Example + +```javascript +import { parse } from '@adobe/css-tools'; + +const css = ` + .example { + color: red; + font-size: 16px; + } +`; + +const ast = parse(css); +console.log(ast.stylesheet.rules); +``` + +### `stringify(ast, options?)` + +Converts a CSS AST back to CSS string with configurable formatting. + +#### Parameters + +- `ast` (CssStylesheetAST) - The CSS AST to stringify +- `options` (CompilerOptions, optional) - Stringification options + - `indent` (string) - Indentation string (default: `' '`) + - `compress` (boolean) - Whether to compress/minify the output (default: `false`) + +#### Returns + +- `string` - The formatted CSS string + +#### Example + +```javascript +import { parse, stringify } from '@adobe/css-tools'; + +const css = '.example { color: red; }'; +const ast = parse(css); + +// Pretty print +const formatted = stringify(ast, { indent: ' ' }); +console.log(formatted); +// Output: +// .example { +// color: red; +// } + +// Compressed +const minified = stringify(ast, { compress: true }); +console.log(minified); +// Output: .example{color:red} +``` + +## Type Definitions + +### Core Types + +#### `CssStylesheetAST` +The root AST node representing a complete CSS stylesheet. + +```typescript +type CssStylesheetAST = { + type: CssTypes.stylesheet; + stylesheet: { + source?: string; + rules: CssRuleAST[]; + parsingErrors?: CssParseError[]; + }; +}; +``` + +#### `CssRuleAST` +Represents a CSS rule (selector + declarations). + +```typescript +type CssRuleAST = { + type: CssTypes.rule; + selectors: string[]; + declarations: CssDeclarationAST[]; + position?: CssPosition; + parent?: CssStylesheetAST; +}; +``` + +#### `CssDeclarationAST` +Represents a CSS property declaration. + +```typescript +type CssDeclarationAST = { + type: CssTypes.declaration; + property: string; + value: string; + position?: CssPosition; + parent?: CssRuleAST; +}; +``` + +#### `CssMediaAST` +Represents a CSS @media rule. + +```typescript +type CssMediaAST = { + type: CssTypes.media; + media: string; + rules: CssRuleAST[]; + position?: CssPosition; + parent?: CssStylesheetAST; +}; +``` + +#### `CssKeyframesAST` +Represents a CSS @keyframes rule. + +```typescript +type CssKeyframesAST = { + type: CssTypes.keyframes; + name: string; + keyframes: CssKeyframeAST[]; + position?: CssPosition; + parent?: CssStylesheetAST; +}; +``` + +#### `CssPosition` +Represents source position information. + +```typescript +type CssPosition = { + source?: string; + start: { + line: number; + column: number; + }; + end: { + line: number; + column: number; + }; +}; +``` + +#### `CssParseError` +Represents a parsing error. + +```typescript +type CssParseError = { + message: string; + reason: string; + filename?: string; + line: number; + column: number; + source?: string; +}; +``` + +### Compiler Options + +#### `CompilerOptions` +Options for the stringifier. + +```typescript +type CompilerOptions = { + indent?: string; // Default: ' ' + compress?: boolean; // Default: false +}; +``` + +## Error Handling + +### Silent Parsing + +When parsing malformed CSS, you can use the `silent` option to collect errors instead of throwing: + +```javascript +import { parse } from '@adobe/css-tools'; + +const malformedCss = ` + body { color: red; } + { color: blue; } /* Missing selector */ + .valid { background: green; } +`; + +const result = parse(malformedCss, { silent: true }); + +if (result.stylesheet.parsingErrors) { + result.stylesheet.parsingErrors.forEach(error => { + console.log(`Error at line ${error.line}: ${error.message}`); + }); +} + +// Valid rules are still parsed +console.log('Valid rules:', result.stylesheet.rules.length); +``` + +### Source Tracking + +Enable source tracking for better error reporting: + +```javascript +import { parse } from '@adobe/css-tools'; + +const css = 'body { color: red; }'; +const ast = parse(css, { source: 'styles.css' }); + +const rule = ast.stylesheet.rules[0]; +console.log(rule.position?.source); // "styles.css" +console.log(rule.position?.start); // { line: 1, column: 1 } +console.log(rule.position?.end); // { line: 1, column: 20 } +``` + +## Advanced Usage + +### Working with At-Rules + +```javascript +import { parse, stringify } from '@adobe/css-tools'; + +const css = ` + @media (max-width: 768px) { + .container { + padding: 10px; + } + } + + @keyframes fadeIn { + from { opacity: 0; } + to { opacity: 1; } + } +`; + +const ast = parse(css); + +// Access media rules +const mediaRule = ast.stylesheet.rules.find(rule => rule.type === 'media'); +console.log(mediaRule.media); // "(max-width: 768px)" + +// Access keyframes +const keyframesRule = ast.stylesheet.rules.find(rule => rule.type === 'keyframes'); +console.log(keyframesRule.name); // "fadeIn" +``` + +### Custom Formatting + +```javascript +import { parse, stringify } from '@adobe/css-tools'; + +const css = '.example{color:red;font-size:16px}'; +const ast = parse(css); + +// Custom indentation +const formatted = stringify(ast, { indent: ' ' }); +console.log(formatted); +// Output: +// .example { +// color: red; +// font-size: 16px; +// } + +// Compressed with no spaces +const compressed = stringify(ast, { compress: true }); +console.log(compressed); +// Output: .example{color:red;font-size:16px} +``` + +## TypeScript Integration + +The library provides comprehensive TypeScript support with full type definitions for all AST nodes and functions: + +```typescript +import { parse, stringify, type CssStylesheetAST } from '@adobe/css-tools'; + +const css: string = '.example { color: red; }'; +const ast: CssStylesheetAST = parse(css); +const output: string = stringify(ast); +``` + +## Performance Considerations + +- The parser is optimized for large CSS files +- AST nodes are lightweight and memory-efficient +- Stringification is fast and supports streaming for large outputs +- Consider using `compress: true` for production builds to reduce file size + +## Browser Support + +The library works in all modern browsers and Node.js environments. For older environments, you may need to use a bundler with appropriate polyfills. diff --git a/node_modules/@adobe/css-tools/docs/AST.md b/node_modules/@adobe/css-tools/docs/AST.md new file mode 100644 index 00000000..eaac3dd1 --- /dev/null +++ b/node_modules/@adobe/css-tools/docs/AST.md @@ -0,0 +1,366 @@ +# Abstract Syntax Tree (AST) + +## Overview + +The AST represents CSS as a tree structure where each node has a specific type and properties. All nodes share common properties and have type-specific properties. + +## Common Properties + +All AST nodes have these properties: + +### `type` + +The node type as a string. See [Node Types](#node-types) for all possible values. + +### `position` (optional) + +Position information for the node in the source code: + +```typescript +{ + start: { line: number; column: number }; + end: { line: number; column: number }; + source?: string; +} +``` + +### `parent` (optional) + +Reference to the parent node in the AST. + +## Node Types + +### `stylesheet` + +The root node representing an entire CSS document. + +**Properties:** +- `stylesheet.source` (optional): Source file path +- `stylesheet.rules`: Array of top-level rules +- `stylesheet.parsingErrors` (optional): Array of parse errors when `silent` option is used + +**Example:** +```json +{ + "type": "stylesheet", + "stylesheet": { + "rules": [ + // ... other nodes + ] + } +} +``` + +### `rule` + +A CSS rule with selectors and declarations. + +**Properties:** +- `selectors`: Array of CSS selectors as strings +- `declarations`: Array of declarations and comments + +**Example:** +```json +{ + "type": "rule", + "selectors": ["body", "html"], + "declarations": [ + { + "type": "declaration", + "property": "color", + "value": "red" + } + ] +} +``` + +### `declaration` + +A CSS property declaration. + +**Properties:** +- `property`: The CSS property name +- `value`: The CSS property value as a string + +**Example:** +```json +{ + "type": "declaration", + "property": "background-color", + "value": "#ffffff" +} +``` + +### `comment` + +A CSS comment. + +**Properties:** +- `comment`: The comment text (without `/*` and `*/`) + +**Example:** +```json +{ + "type": "comment", + "comment": " This is a comment " +} +``` + +### `media` + +A `@media` rule. + +**Properties:** +- `media`: The media query string +- `rules`: Array of rules within the media block + +**Example:** +```json +{ + "type": "media", + "media": "screen and (max-width: 768px)", + "rules": [ + // ... nested rules + ] +} +``` + +### `keyframes` + +A `@keyframes` rule. + +**Properties:** +- `name`: The keyframes name +- `vendor` (optional): Vendor prefix (e.g., "-webkit-") +- `keyframes`: Array of keyframe rules and comments + +**Example:** +```json +{ + "type": "keyframes", + "name": "fade", + "keyframes": [ + { + "type": "keyframe", + "values": ["from"], + "declarations": [ + { + "type": "declaration", + "property": "opacity", + "value": "0" + } + ] + } + ] +} +``` + +### `keyframe` + +A keyframe within a `@keyframes` rule. + +**Properties:** +- `values`: Array of keyframe selectors (e.g., `["from"]`, `["to"]`, `["50%"]`) +- `declarations`: Array of declarations and comments + +### `import` + +An `@import` rule. + +**Properties:** +- `import`: The import string (URL or media query) + +**Example:** +```json +{ + "type": "import", + "import": "url('styles.css')" +} +``` + +### `charset` + +A `@charset` rule. + +**Properties:** +- `charset`: The character encoding + +**Example:** +```json +{ + "type": "charset", + "charset": "utf-8" +} +``` + +### `namespace` + +A `@namespace` rule. + +**Properties:** +- `namespace`: The namespace declaration + +**Example:** +```json +{ + "type": "namespace", + "namespace": "url(http://www.w3.org/1999/xhtml)" +} +``` + +### `supports` + +A `@supports` rule. + +**Properties:** +- `supports`: The supports condition +- `rules`: Array of rules within the supports block + +**Example:** +```json +{ + "type": "supports", + "supports": "(display: grid)", + "rules": [ + // ... nested rules + ] +} +``` + +### `document` + +A `@document` rule. + +**Properties:** +- `document`: The document condition +- `vendor` (optional): Vendor prefix +- `rules`: Array of rules within the document block + +### `page` + +A `@page` rule. + +**Properties:** +- `selectors`: Array of page selectors +- `declarations`: Array of declarations and comments + +### `font-face` + +A `@font-face` rule. + +**Properties:** +- `declarations`: Array of font declarations and comments + +### `host` + +A `:host` rule. + +**Properties:** +- `rules`: Array of rules within the host block + +### `container` + +A `@container` rule. + +**Properties:** +- `container`: The container query +- `rules`: Array of rules within the container block + +### `layer` + +A `@layer` rule. + +**Properties:** +- `layer`: The layer name +- `rules` (optional): Array of rules within the layer block + +### `custom-media` + +A `@custom-media` rule. + +**Properties:** +- `name`: The custom media query name +- `media`: The media query definition + +### `starting-style` + +A `@starting-style` rule. + +**Properties:** +- `rules`: Array of rules within the starting-style block + +## Type Hierarchy + +The AST nodes are organized in the following hierarchy: + +- `CssStylesheetAST` - Root node +- `CssAtRuleAST` - Union of all at-rule and rule nodes +- `CssAllNodesAST` - Union of all possible node types + +## Working with the AST + +### Traversing Nodes + +```typescript +import { parse, CssStylesheetAST } from '@adobe/css-tools'; + +const ast: CssStylesheetAST = parse('body { color: red; }'); + +// Access top-level rules +ast.stylesheet.rules.forEach(rule => { + if (rule.type === 'rule') { + console.log('Selectors:', rule.selectors); + rule.declarations.forEach(decl => { + if (decl.type === 'declaration') { + console.log(`${decl.property}: ${decl.value}`); + } + }); + } +}); +``` + +### Modifying Nodes + +```typescript +// Add a new declaration +const newDecl = { + type: 'declaration' as const, + property: 'font-size', + value: '16px' +}; + +// Find a rule and add the declaration +ast.stylesheet.rules.forEach(rule => { + if (rule.type === 'rule' && rule.selectors.includes('body')) { + rule.declarations.push(newDecl); + } +}); +``` + +### Error Handling + +When parsing with the `silent` option, errors are collected in the AST: + +```typescript +const ast = parse('invalid css {', { silent: true }); + +if (ast.stylesheet.parsingErrors) { + ast.stylesheet.parsingErrors.forEach(error => { + console.error('Parse error:', error.message); + }); +} +``` + +## Position Information + +Position information is available on most nodes and includes: + +- `start.line` and `start.column`: Beginning of the node +- `end.line` and `end.column`: End of the node +- `source`: Source file path (if provided during parsing) + +This is useful for: +- Error reporting +- Source mapping +- Code analysis tools +- IDE integration diff --git a/node_modules/@adobe/css-tools/docs/CHANGELOG.md b/node_modules/@adobe/css-tools/docs/CHANGELOG.md new file mode 100644 index 00000000..b2082034 --- /dev/null +++ b/node_modules/@adobe/css-tools/docs/CHANGELOG.md @@ -0,0 +1,191 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [4.4.4] - 2025-07-22 + +### Changed +- Switch from yarn to npm for package management +- Switch from eslint to biome for code formatting and linting +- Reformat codebase to comply with biome recommendations +- Switch from webpack to rollup for bundling + +### Fixed +- Fix module exports to ensure proper compatibility with bundlers +- Add validation check to prevent future export issues + +## [4.4.3] - 2025-05-15 + +### Security +- Fix polynomial regular expression vulnerability on uncontrolled data +- Refactor code to enable GitHub security static analysis + +### Performance +- Improve parsing performance with minor optimizations +- Replace regex patterns with string search (indexOf-based) for better performance + +### Added +- Add new utility functions with comprehensive unit tests +- Add improved formatting for CSS Grid template areas (#283 by @jogibear9988) + +### Fixed +- Fix TypeScript error with ConstructorParameters in Parcel bundler (#444) + +## [4.4.2] - 2025-02-12 + +### Fixed +- Fix regular expression for parsing quoted values in parentheses + +## [4.4.0] - 2024-06-05 + +### Added +- Add support for CSS `@starting-style` at-rule (#319) + +## [4.3.3] - 2024-01-24 + +### Changed +- Update package export configuration (#271) + +## [4.3.2] - 2023-11-28 + +### Security +- Fix ReDoS vulnerability with crafted CSS strings - CVE-2023-48631 + +### Fixed +- Fix parsing issues with `:is()` and nested `:nth-child()` selectors (#211) + +## [4.3.1] - 2023-03-14 + +### Security +- Fix ReDoS vulnerability with crafted CSS strings - CVE-2023-26364 + +## [4.3.0] - 2023-03-07 + +### Changed +- Update build toolchain and dependencies +- Update package exports configuration and file structure + +## [4.2.0] - 2023-02-21 + +### Added +- Add support for CSS `@container` at-rule +- Add support for CSS `@layer` at-rule + +## [4.1.0] - 2023-01-25 + +### Added +- Add support for ES Modules (ESM) + +## [4.0.2] - 2023-01-12 + +### Fixed +- Fix `@import` parsing when URL contains semicolons (#71) +- Fix regression in selector parsing for attribute selectors (#77) + +## [4.0.1] - 2022-08-03 + +### Fixed +- Fix `globalThis` configuration for webpack to enable UMD module usage in Node.js environments + +## [4.0.0] - 2022-06-09 + +### Changed +- Fork from original css library to Adobe's `@adobe/css-tools` package +- Convert codebase from JavaScript to TypeScript +- Improve parsing performance by approximately 25% +- Update all dependencies to latest versions +- Remove source map support + +--- + +## Legacy Versions (Pre-Adobe Fork) + +## [3.0.0] - 2020-07-01 + +### Changed +- Bump major version due to major dependency updates and Node.js version requirement changes + +## [2.2.1] - 2015-06-17 + +### Fixed +- Fix parsing of escaped quotes in quoted strings + +## [2.2.0] - 2015-02-18 + +### Added +- Add `parsingErrors` property to list errors when parsing with `silent: true` +- Accept EOL characters and all whitespace characters in at-rules such as `@media` + +## [2.1.0] - 2014-08-05 + +### Added +- Add `inputSourcemaps` option to disable input source map processing +- Add `sourcemap: 'generator'` option to return the `SourceMapGenerator` object +- Use `inherits` package for inheritance (fixes browser compatibility issues) + +### Changed +- Change error message format and add `.reason` property to error objects + +## [2.0.0] - 2014-06-18 + +### Added +- Add non-enumerable parent reference to each AST node +- Add support for `@custom-media`, `@host`, and `@font-face` at-rules +- Allow commas inside selector functions +- Allow empty property values +- Add `node.position.content` property +- Integrate css-parse and css-stringify libraries +- Apply original source maps from source files + +### Changed +- Change default `options.position` value to `true` +- Remove comments from properties and values + +### Removed +- Drop Component(1) support + +### Fixed +- Fix assertion errors when selectors are missing + +## [1.6.1] - 2014-01-02 + +### Fixed +- Fix component.json configuration + +## [1.6.0] - 2013-12-21 + +### Changed +- Update dependencies + +## [1.5.0] - 2013-12-03 + +### Changed +- Update dependencies + +## [1.1.0] - 2013-04-04 + +### Changed +- Update dependencies + +## [1.0.7] - 2012-11-21 + +### Fixed +- Fix component.json configuration + +## [1.0.4] - 2012-11-15 + +### Changed +- Update css-stringify dependency + +## [1.0.3] - 2012-09-01 + +### Added +- Add Component support + +## [0.0.1] - 2010-01-03 + +### Added +- Initial release diff --git a/node_modules/@adobe/css-tools/docs/EXAMPLES.md b/node_modules/@adobe/css-tools/docs/EXAMPLES.md new file mode 100644 index 00000000..81565c67 --- /dev/null +++ b/node_modules/@adobe/css-tools/docs/EXAMPLES.md @@ -0,0 +1,450 @@ +# Usage Examples + +## Basic Usage + +### Parsing CSS + +```javascript +import { parse } from '@adobe/css-tools'; + +// Basic CSS parsing +const css = ` + body { + font-size: 12px; + color: #333; + } + + .container { + max-width: 1200px; + margin: 0 auto; + } +`; + +const ast = parse(css); +console.log(ast); +``` + +### Stringifying AST + +```javascript +import { parse, stringify } from '@adobe/css-tools'; + +const css = 'body { font-size: 12px; color: #333; }'; +const ast = parse(css); + +// Convert back to CSS +const output = stringify(ast); +console.log(output); // "body { font-size: 12px; color: #333; }" +``` + +## Advanced Parsing Options + +### Source Tracking + +```javascript +import { parse } from '@adobe/css-tools'; + +const css = 'body { color: red; }'; +const ast = parse(css, { source: 'styles.css' }); + +// Position information is available +const rule = ast.stylesheet.rules[0]; +console.log(rule.position?.source); // "styles.css" +console.log(rule.position?.start); // { line: 1, column: 1 } +console.log(rule.position?.end); // { line: 1, column: 20 } +``` + +### Silent Error Handling + +```javascript +import { parse } from '@adobe/css-tools'; + +const malformedCss = ` + body { color: red; } + { color: blue; } /* Missing selector */ + .valid { background: green; } +`; + +// Parse with silent error handling +const result = parse(malformedCss, { silent: true }); + +// Check for parsing errors +if (result.stylesheet.parsingErrors) { + console.log('Parsing errors:', result.stylesheet.parsingErrors.length); + result.stylesheet.parsingErrors.forEach(error => { + console.log(`Error at line ${error.line}: ${error.message}`); + }); +} + +// Valid rules are still parsed +console.log('Valid rules:', result.stylesheet.rules.length); +``` + +## AST Structure Examples + +### Basic Rule + +```javascript +import { parse } from '@adobe/css-tools'; + +const css = ` + .header { + background: #f0f0f0; + padding: 20px; + border-bottom: 1px solid #ccc; + } +`; + +const ast = parse(css); +const rule = ast.stylesheet.rules[0]; + +console.log(rule.type); // "rule" +console.log(rule.selectors); // [".header"] +console.log(rule.declarations.length); // 3 + +rule.declarations.forEach(decl => { + console.log(`${decl.property}: ${decl.value}`); +}); +// Output: +// background: #f0f0f0 +// padding: 20px +// border-bottom: 1px solid #ccc +``` + +### Media Queries + +```javascript +import { parse } from '@adobe/css-tools'; + +const css = ` + @media screen and (max-width: 768px) { + .container { + padding: 10px; + } + + .sidebar { + display: none; + } + } +`; + +const ast = parse(css); +const mediaRule = ast.stylesheet.rules[0]; + +console.log(mediaRule.type); // "media" +console.log(mediaRule.media); // "screen and (max-width: 768px)" +console.log(mediaRule.rules.length); // 2 +``` + +### Keyframes + +```javascript +import { parse } from '@adobe/css-tools'; + +const css = ` + @keyframes fadeIn { + from { + opacity: 0; + } + to { + opacity: 1; + } + } +`; + +const ast = parse(css); +const keyframesRule = ast.stylesheet.rules[0]; + +console.log(keyframesRule.type); // "keyframes" +console.log(keyframesRule.name); // "fadeIn" +console.log(keyframesRule.keyframes.length); // 2 + +keyframesRule.keyframes.forEach(keyframe => { + console.log(`Keyframe: ${keyframe.values.join(', ')}`); + keyframe.declarations.forEach(decl => { + console.log(` ${decl.property}: ${decl.value}`); + }); +}); +``` + +### Comments + +```javascript +import { parse } from '@adobe/css-tools'; + +const css = ` + /* Header styles */ + .header { + background: red; /* Fallback color */ + } + + /* Footer styles */ + .footer { + background: blue; + } +`; + +const ast = parse(css); + +ast.stylesheet.rules.forEach(rule => { + if (rule.type === 'comment') { + console.log(`Comment: ${rule.comment}`); + } else if (rule.type === 'rule') { + console.log(`Rule: ${rule.selectors.join(', ')}`); + + rule.declarations.forEach(decl => { + if (decl.type === 'comment') { + console.log(` Comment: ${decl.comment}`); + } else { + console.log(` ${decl.property}: ${decl.value}`); + } + }); + } +}); +``` + +## Stringifying Options + +### Compressed Output + +```javascript +import { parse, stringify } from '@adobe/css-tools'; + +const css = ` + body { + font-size: 12px; + color: #333; + margin: 0; + padding: 0; + } +`; + +const ast = parse(css); + +// Compressed output +const compressed = stringify(ast, { compress: true }); +console.log(compressed); +// Output: "body{font-size:12px;color:#333;margin:0;padding:0}" +``` + +### Custom Indentation + +```javascript +import { parse, stringify } from '@adobe/css-tools'; + +const css = 'body { font-size: 12px; color: #333; }'; +const ast = parse(css); + +// Custom indentation +const formatted = stringify(ast, { indent: ' ' }); +console.log(formatted); +// Output: +// body { +// font-size: 12px; +// color: #333; +// } +``` + +## Working with Complex CSS + +### Nested Rules and At-Rules + +```javascript +import { parse, stringify } from '@adobe/css-tools'; + +const complexCss = ` + @import url('https://fonts.googleapis.com/css2?family=Roboto'); + + @charset "UTF-8"; + + @media print { + body { + font-size: 12pt; + } + } + + @supports (display: grid) { + .grid { + display: grid; + } + } + + @keyframes slideIn { + 0% { transform: translateX(-100%); } + 100% { transform: translateX(0); } + } + + @font-face { + font-family: 'CustomFont'; + src: url('custom-font.woff2') format('woff2'); + } +`; + +const ast = parse(complexCss); + +ast.stylesheet.rules.forEach(rule => { + switch (rule.type) { + case 'import': + console.log(`Import: ${rule.import}`); + break; + case 'charset': + console.log(`Charset: ${rule.charset}`); + break; + case 'media': + console.log(`Media query: ${rule.media}`); + break; + case 'supports': + console.log(`Supports: ${rule.supports}`); + break; + case 'keyframes': + console.log(`Keyframes: ${rule.name}`); + break; + case 'font-face': + console.log('Font-face rule'); + break; + } +}); +``` + +### Manipulating the AST + +```javascript +import { parse, stringify } from '@adobe/css-tools'; + +const css = ` + .button { + background: blue; + color: white; + padding: 10px; + } +`; + +const ast = parse(css); +const rule = ast.stylesheet.rules[0]; + +// Add a new declaration +rule.declarations.push({ + type: 'declaration', + property: 'border-radius', + value: '5px' +}); + +// Modify existing declaration +const backgroundDecl = rule.declarations.find(d => d.property === 'background'); +if (backgroundDecl) { + backgroundDecl.value = 'red'; +} + +// Add a new selector +rule.selectors.push('.btn'); + +const modifiedCss = stringify(ast); +console.log(modifiedCss); +``` + +## Error Handling + +### Catching Parse Errors + +```javascript +import { parse, CssParseError } from '@adobe/css-tools'; + +try { + const ast = parse('body { color: red; } { invalid }'); +} catch (error) { + if (error instanceof CssParseError) { + console.log(`Parse error at line ${error.line}, column ${error.column}:`); + console.log(error.message); + console.log(`Source: ${error.filename}`); + } +} +``` + +### Working with Silent Errors + +```javascript +import { parse } from '@adobe/css-tools'; + +const problematicCss = ` + body { color: red; } + { color: blue; } /* Missing selector */ + .valid { background: green; } + .another { border: 1px solid; } /* Missing closing brace */ +`; + +const result = parse(problematicCss, { + silent: true, + source: 'problematic.css' +}); + +// Process valid rules +const validRules = result.stylesheet.rules.filter(rule => rule.type === 'rule'); +console.log(`Found ${validRules.length} valid rules`); + +// Log errors for debugging +if (result.stylesheet.parsingErrors) { + result.stylesheet.parsingErrors.forEach(error => { + console.log(`Error: ${error.message} at line ${error.line}`); + }); +} +``` + +### CSS Minification + +```javascript +import { parse, stringify } from '@adobe/css-tools'; + +function minifyCSS(css) { + const ast = parse(css); + return stringify(ast, { compress: true }); +} + +const css = ` + body { + font-size: 12px; + color: #333; + margin: 0; + padding: 0; + } + + .container { + max-width: 1200px; + margin: 0 auto; + } +`; + +const minified = minifyCSS(css); +console.log(minified); +// Output: "body{font-size:12px;color:#333;margin:0;padding:0}.container{max-width:1200px;margin:0 auto}" +``` + +### CSS Validation + +```javascript +import { parse } from '@adobe/css-tools'; + +function validateCSS(css, filename = 'unknown') { + try { + const ast = parse(css, { source: filename }); + return { + valid: true, + rules: ast.stylesheet.rules.length, + errors: [] + }; + } catch (error) { + return { + valid: false, + rules: 0, + errors: [{ + message: error.message, + line: error.line, + column: error.column, + source: error.filename + }] + }; + } +} + +const result = validateCSS('body { color: red; } { invalid }', 'test.css'); +console.log(result); +``` diff --git a/node_modules/@adobe/css-tools/package.json b/node_modules/@adobe/css-tools/package.json new file mode 100644 index 00000000..1a053556 --- /dev/null +++ b/node_modules/@adobe/css-tools/package.json @@ -0,0 +1,82 @@ +{ + "name": "@adobe/css-tools", + "version": "4.4.4", + "description": "A modern CSS parser and stringifier with TypeScript support", + "source": "src/index.ts", + "main": "./dist/cjs/adobe-css-tools.cjs", + "module": "./dist/esm/adobe-css-tools.mjs", + "browser": "./dist/umd/adobe-css-tools.js", + "sideEffects": false, + "exports": { + ".": { + "import": "./dist/esm/adobe-css-tools.mjs", + "require": "./dist/cjs/adobe-css-tools.cjs" + }, + "./package.json": "./package.json" + }, + "types": "./dist/esm/adobe-css-tools.d.mts", + "type": "module", + "files": [ + "dist/cjs", + "dist/esm", + "dist/umd", + "README.md", + "docs/" + ], + "devDependencies": { + "@arethetypeswrong/cli": "^0.18.2", + "@biomejs/biome": "^2.1.2", + "@rollup/plugin-commonjs": "^28.0.6", + "@rollup/plugin-node-resolve": "^16.0.1", + "@rollup/plugin-terser": "^0.4.4", + "@rollup/plugin-typescript": "^12.1.4", + "@types/benchmark": "^2.1.1", + "@types/bytes": "^3.1.5", + "@types/jest": "^29.5.14", + "@types/node": "^24.0.3", + "benchmark": "^2.1.4", + "bytes": "^3.1.0", + "jest": "^29.7.0", + "rollup": "^4.45.1", + "rollup-plugin-dts": "^6.2.1", + "ts-jest": "^29.1.1", + "tslib": "^2.8.1", + "typescript": "^5.7.3" + }, + "scripts": { + "benchmark": "npm run build && node benchmark/index.mjs", + "test": "jest", + "clean": "rm -rf ./dist", + "build": "rollup -c", + "fix": "biome check --write", + "check-package-bundle": "attw --pack .", + "lint": "biome check", + "prebuild": "npm run clean", + "prepack": "rollup -c", + "posttest": "npm run lint", + "postbuild": "tar -czf dist/archive.tgz LICENSE README.md dist/cjs dist/esm dist/umd docs package.json && npx attw --format ascii dist/archive.tgz && rm dist/archive.tgz" + }, + "author": "TJ Holowaychuk ", + "contributors": [ + "Jean-Philippe Zolesio " + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/adobe/css-tools.git" + }, + "keywords": [ + "css", + "parser", + "stringifier", + "stylesheet", + "ast", + "typescript", + "css-parser", + "css-ast", + "css-tools", + "minify", + "format", + "preprocessor" + ] +} diff --git a/node_modules/@asamuzakjp/css-color/LICENSE b/node_modules/@asamuzakjp/css-color/LICENSE new file mode 100644 index 00000000..0004c527 --- /dev/null +++ b/node_modules/@asamuzakjp/css-color/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 asamuzaK (Kazz) + +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. diff --git a/node_modules/@asamuzakjp/css-color/README.md b/node_modules/@asamuzakjp/css-color/README.md new file mode 100644 index 00000000..715b6c35 --- /dev/null +++ b/node_modules/@asamuzakjp/css-color/README.md @@ -0,0 +1,316 @@ +# CSS color + +[![build](https://github.com/asamuzaK/cssColor/actions/workflows/node.js.yml/badge.svg)](https://github.com/asamuzaK/cssColor/actions/workflows/node.js.yml) +[![CodeQL](https://github.com/asamuzaK/cssColor/actions/workflows/github-code-scanning/codeql/badge.svg)](https://github.com/asamuzaK/cssColor/actions/workflows/github-code-scanning/codeql) +[![npm (scoped)](https://img.shields.io/npm/v/@asamuzakjp/css-color)](https://www.npmjs.com/package/@asamuzakjp/css-color) + +Resolve and convert CSS colors. + +## Install + +```console +npm i @asamuzakjp/css-color +``` + +## Usage + +```javascript +import { convert, resolve, utils } from '@asamuzakjp/css-color'; + +const resolvedValue = resolve( + 'color-mix(in oklab, lch(67.5345 42.5 258.2), color(srgb 0 0.5 0))' +); +// 'oklab(0.620754 -0.0931934 -0.00374881)' + +const convertedValue = convert.colorToHex('lab(46.2775% -47.5621 48.5837)'); +// '#008000' + +const result = utils.isColor('green'); +// true +``` + + + +### resolve(color, opt) + +resolves CSS color + +#### Parameters + +- `color` **[string][133]** color value + - system colors are not supported +- `opt` **[object][135]?** options (optional, default `{}`) + - `opt.currentColor` **[string][133]?** + - color to use for `currentcolor` keyword + - if omitted, it will be treated as a missing color, + i.e. `rgb(none none none / none)` + - `opt.customProperty` **[object][135]?** + - custom properties + - pair of `--` prefixed property name as a key and it's value, + e.g. + ```javascript + const opt = { + customProperty: { + '--some-color': '#008000', + '--some-length': '16px' + } + }; + ``` + - and/or `callback` function to get the value of the custom property, + e.g. + ```javascript + const node = document.getElementById('foo'); + const opt = { + customProperty: { + callback: node.style.getPropertyValue + } + }; + ``` + - `opt.dimension` **[object][135]?** + - dimension, e.g. for converting relative length to pixels + - pair of unit as a key and number in pixels as it's value, + e.g. suppose `1em === 12px`, `1rem === 16px` and `100vw === 1024px`, then + ```javascript + const opt = { + dimension: { + em: 12, + rem: 16, + vw: 10.24 + } + }; + ``` + - and/or `callback` function to get the value as a number in pixels, + e.g. + ```javascript + const opt = { + dimension: { + callback: unit => { + switch (unit) { + case 'em': + return 12; + case 'rem': + return 16; + case 'vw': + return 10.24; + default: + return; + } + } + } + }; + ``` + - `opt.format` **[string][133]?** + - output format, one of below + - `computedValue` (default), [computed value][139] of the color + - `specifiedValue`, [specified value][140] of the color + - `hex`, hex color notation, i.e. `#rrggbb` + - `hexAlpha`, hex color notation with alpha channel, i.e. `#rrggbbaa` + +Returns **[string][133]?** one of `rgba?()`, `#rrggbb(aa)?`, `color-name`, `color(color-space r g b / alpha)`, `color(color-space x y z / alpha)`, `(ok)?lab(l a b / alpha)`, `(ok)?lch(l c h / alpha)`, `'(empty-string)'`, `null` + +- in `computedValue`, values are numbers, however `rgb()` values are integers +- in `specifiedValue`, returns `empty string` for unknown and/or invalid color +- in `hex`, returns `null` for `transparent`, and also returns `null` if any of `r`, `g`, `b`, `alpha` is not a number +- in `hexAlpha`, returns `#00000000` for `transparent`, however returns `null` if any of `r`, `g`, `b`, `alpha` is not a number + +### convert + +Contains various color conversion functions. + +### convert.numberToHex(value) + +convert number to hex string + +#### Parameters + +- `value` **[number][134]** color value + +Returns **[string][133]** hex string: 00..ff + +### convert.colorToHex(value, opt) + +convert color to hex + +#### Parameters + +- `value` **[string][133]** color value +- `opt` **[object][135]?** options (optional, default `{}`) + - `opt.alpha` **[boolean][136]?** return in #rrggbbaa notation + - `opt.customProperty` **[object][135]?** + - custom properties, see `resolve()` function above + - `opt.dimension` **[object][135]?** + - dimension, see `resolve()` function above + +Returns **[string][133]** #rrggbb(aa)? + +### convert.colorToHsl(value, opt) + +convert color to hsl + +#### Parameters + +- `value` **[string][133]** color value +- `opt` **[object][135]?** options (optional, default `{}`) + - `opt.customProperty` **[object][135]?** + - custom properties, see `resolve()` function above + - `opt.dimension` **[object][135]?** + - dimension, see `resolve()` function above + +Returns **[Array][137]<[number][134]>** \[h, s, l, alpha] + +### convert.colorToHwb(value, opt) + +convert color to hwb + +#### Parameters + +- `value` **[string][133]** color value +- `opt` **[object][135]?** options (optional, default `{}`) + - `opt.customProperty` **[object][135]?** + - custom properties, see `resolve()` function above + - `opt.dimension` **[object][135]?** + - dimension, see `resolve()` function above + +Returns **[Array][137]<[number][134]>** \[h, w, b, alpha] + +### convert.colorToLab(value, opt) + +convert color to lab + +#### Parameters + +- `value` **[string][133]** color value +- `opt` **[object][135]?** options (optional, default `{}`) + - `opt.customProperty` **[object][135]?** + - custom properties, see `resolve()` function above + - `opt.dimension` **[object][135]?** + - dimension, see `resolve()` function above + +Returns **[Array][137]<[number][134]>** \[l, a, b, alpha] + +### convert.colorToLch(value, opt) + +convert color to lch + +#### Parameters + +- `value` **[string][133]** color value +- `opt` **[object][135]?** options (optional, default `{}`) + - `opt.customProperty` **[object][135]?** + - custom properties, see `resolve()` function above + - `opt.dimension` **[object][135]?** + - dimension, see `resolve()` function above + +Returns **[Array][137]<[number][134]>** \[l, c, h, alpha] + +### convert.colorToOklab(value, opt) + +convert color to oklab + +#### Parameters + +- `value` **[string][133]** color value +- `opt` **[object][135]?** options (optional, default `{}`) + - `opt.customProperty` **[object][135]?** + - custom properties, see `resolve()` function above + - `opt.dimension` **[object][135]?** + - dimension, see `resolve()` function above + +Returns **[Array][137]<[number][134]>** \[l, a, b, alpha] + +### convert.colorToOklch(value, opt) + +convert color to oklch + +#### Parameters + +- `value` **[string][133]** color value +- `opt` **[object][135]?** options (optional, default `{}`) + - `opt.customProperty` **[object][135]?** + - custom properties, see `resolve()` function above + - `opt.dimension` **[object][135]?** + - dimension, see `resolve()` function above + +Returns **[Array][137]<[number][134]>** \[l, c, h, alpha] + +### convert.colorToRgb(value, opt) + +convert color to rgb + +#### Parameters + +- `value` **[string][133]** color value +- `opt` **[object][135]?** options (optional, default `{}`) + - `opt.customProperty` **[object][135]?** + - custom properties, see `resolve()` function above + - `opt.dimension` **[object][135]?** + - dimension, see `resolve()` function above + +Returns **[Array][137]<[number][134]>** \[r, g, b, alpha] + +### convert.colorToXyz(value, opt) + +convert color to xyz + +#### Parameters + +- `value` **[string][133]** color value +- `opt` **[object][135]?** options (optional, default `{}`) + - `opt.customProperty` **[object][135]?** + - custom properties, see `resolve()` function above + - `opt.dimension` **[object][135]?** + - dimension, see `resolve()` function above + - `opt.d50` **[boolean][136]?** xyz in d50 white point + +Returns **[Array][137]<[number][134]>** \[x, y, z, alpha] + +### convert.colorToXyzD50(value, opt) + +convert color to xyz-d50 + +#### Parameters + +- `value` **[string][133]** color value +- `opt` **[object][135]?** options (optional, default `{}`) + - `opt.customProperty` **[object][135]?** + - custom properties, see `resolve()` function above + - `opt.dimension` **[object][135]?** + - dimension, see `resolve()` function above + +Returns **[Array][137]<[number][134]>** \[x, y, z, alpha] + +### utils + +Contains utility functions. + +### utils.isColor(color) + +is valid color type + +#### Parameters + +- `color` **[string][133]** color value + - system colors are not supported + +Returns **[boolean][136]** + +## Acknowledgments + +The following resources have been of great help in the development of the CSS color. + +- [csstools/postcss-plugins](https://github.com/csstools/postcss-plugins) +- [lru-cache](https://github.com/isaacs/node-lru-cache) + +--- + +Copyright (c) 2024 [asamuzaK (Kazz)](https://github.com/asamuzaK/) + +[133]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String +[134]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number +[135]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object +[136]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean +[137]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array +[138]: https://w3c.github.io/csswg-drafts/css-color-4/#color-conversion-code +[139]: https://developer.mozilla.org/en-US/docs/Web/CSS/computed_value +[140]: https://developer.mozilla.org/en-US/docs/Web/CSS/specified_value +[141]: https://www.npmjs.com/package/@csstools/css-calc diff --git a/node_modules/@asamuzakjp/css-color/dist/esm/index.d.ts b/node_modules/@asamuzakjp/css-color/dist/esm/index.d.ts new file mode 100644 index 00000000..34cd0df4 --- /dev/null +++ b/node_modules/@asamuzakjp/css-color/dist/esm/index.d.ts @@ -0,0 +1,20 @@ +/*! + * CSS color - Resolve, parse, convert CSS color. + * @license MIT + * @copyright asamuzaK (Kazz) + * @see {@link https://github.com/asamuzaK/cssColor/blob/main/LICENSE} + */ +export { convert } from './js/convert.js'; +export { resolve } from './js/resolve.js'; +export declare const utils: { + cssCalc: (value: string, opt?: import('./js/typedef.js').Options) => string; + cssVar: (value: string, opt?: import('./js/typedef.js').Options) => string; + extractDashedIdent: (value: string) => string[]; + isAbsoluteFontSize: (value: unknown) => boolean; + isAbsoluteSizeOrLength: (value: number | string, unit: string | undefined) => boolean; + isColor: (value: unknown, opt?: import('./js/typedef.js').Options) => boolean; + isGradient: (value: string, opt?: import('./js/typedef.js').Options) => boolean; + resolveGradient: (value: string, opt?: import('./js/typedef.js').Options) => string; + resolveLengthInPixels: (value: number | string, unit: string | undefined, opt?: import('./js/typedef.js').Options) => number; + splitValue: (value: string, opt?: import('./js/typedef.js').Options) => string[]; +}; diff --git a/node_modules/@asamuzakjp/css-color/dist/esm/index.js b/node_modules/@asamuzakjp/css-color/dist/esm/index.js new file mode 100644 index 00000000..d6721063 --- /dev/null +++ b/node_modules/@asamuzakjp/css-color/dist/esm/index.js @@ -0,0 +1,29 @@ +import { cssVar } from "./js/css-var.js"; +import { resolve } from "./js/resolve.js"; +import { extractDashedIdent, isAbsoluteFontSize, isAbsoluteSizeOrLength, isColor, resolveLengthInPixels, splitValue } from "./js/util.js"; +import { cssCalc } from "./js/css-calc.js"; +import { isGradient, resolveGradient } from "./js/css-gradient.js"; +import { convert } from "./js/convert.js"; +//#region src/index.ts +/*! +* CSS color - Resolve, parse, convert CSS color. +* @license MIT +* @copyright asamuzaK (Kazz) +* @see {@link https://github.com/asamuzaK/cssColor/blob/main/LICENSE} +*/ +var utils = { + cssCalc, + cssVar, + extractDashedIdent, + isAbsoluteFontSize, + isAbsoluteSizeOrLength, + isColor, + isGradient, + resolveGradient, + resolveLengthInPixels, + splitValue +}; +//#endregion +export { convert, resolve, utils }; + +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@asamuzakjp/css-color/dist/esm/index.js.map b/node_modules/@asamuzakjp/css-color/dist/esm/index.js.map new file mode 100644 index 00000000..bc1aa81f --- /dev/null +++ b/node_modules/@asamuzakjp/css-color/dist/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","names":[],"sources":["../../src/index.ts"],"sourcesContent":["/*!\n * CSS color - Resolve, parse, convert CSS color.\n * @license MIT\n * @copyright asamuzaK (Kazz)\n * @see {@link https://github.com/asamuzaK/cssColor/blob/main/LICENSE}\n */\n\nimport { cssCalc } from './js/css-calc';\nimport { isGradient, resolveGradient } from './js/css-gradient';\nimport { cssVar } from './js/css-var';\nimport {\n extractDashedIdent,\n isAbsoluteFontSize,\n isAbsoluteSizeOrLength,\n isColor,\n resolveLengthInPixels,\n splitValue\n} from './js/util';\n\nexport { convert } from './js/convert';\nexport { resolve } from './js/resolve';\n/* utils */\nexport const utils = {\n cssCalc,\n cssVar,\n extractDashedIdent,\n isAbsoluteFontSize,\n isAbsoluteSizeOrLength,\n isColor,\n isGradient,\n resolveGradient,\n resolveLengthInPixels,\n splitValue\n};\n"],"mappings":";;;;;;;;;;;;;AAsBA,IAAa,QAAQ;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD"} \ No newline at end of file diff --git a/node_modules/@asamuzakjp/css-color/dist/esm/js/cache.d.ts b/node_modules/@asamuzakjp/css-color/dist/esm/js/cache.d.ts new file mode 100644 index 00000000..74b26f66 --- /dev/null +++ b/node_modules/@asamuzakjp/css-color/dist/esm/js/cache.d.ts @@ -0,0 +1,44 @@ +import { LRUCache } from 'lru-cache'; +import { Options } from './typedef.js'; +/** + * CacheItem + */ +export declare class CacheItem { + #private; + /** + * constructor + */ + constructor(item: unknown, isNull?: boolean); + get item(): unknown; + get isNull(): boolean; +} +/** + * NullObject + */ +export declare class NullObject extends CacheItem { + /** + * constructor + */ + constructor(); +} +export declare const lruCache: LRUCache<{}, {}, unknown>; +/** + * set cache + * @param key - cache key + * @param value - value to cache + * @returns void + */ +export declare const setCache: (key: string, value: unknown) => void; +/** + * get cache + * @param key - cache key + * @returns cached item or false otherwise + */ +export declare const getCache: (key: string) => CacheItem | boolean; +/** + * create cache key + * @param keyData - key data + * @param [opt] - options + * @returns cache key + */ +export declare const createCacheKey: (keyData: Record, opt?: Options) => string; diff --git a/node_modules/@asamuzakjp/css-color/dist/esm/js/cache.js b/node_modules/@asamuzakjp/css-color/dist/esm/js/cache.js new file mode 100644 index 00000000..d1c5f675 --- /dev/null +++ b/node_modules/@asamuzakjp/css-color/dist/esm/js/cache.js @@ -0,0 +1,83 @@ +import { valueToJsonString } from "./util.js"; +import { LRUCache } from "lru-cache"; +//#region src/js/cache.ts +/** +* cache +*/ +var MAX_CACHE = 4096; +/** +* CacheItem +*/ +var CacheItem = class { + #isNull; + #item; + /** + * constructor + */ + constructor(item, isNull = false) { + this.#item = item; + this.#isNull = !!isNull; + } + get item() { + return this.#item; + } + get isNull() { + return this.#isNull; + } +}; +/** +* NullObject +*/ +var NullObject = class extends CacheItem { + /** + * constructor + */ + constructor() { + super(Symbol("null"), true); + } +}; +var lruCache = new LRUCache({ max: MAX_CACHE }); +/** +* set cache +* @param key - cache key +* @param value - value to cache +* @returns void +*/ +var setCache = (key, value) => { + if (key) if (value === null) lruCache.set(key, new NullObject()); + else if (value instanceof CacheItem) lruCache.set(key, value); + else lruCache.set(key, new CacheItem(value)); +}; +/** +* get cache +* @param key - cache key +* @returns cached item or false otherwise +*/ +var getCache = (key) => { + if (key && lruCache.has(key)) { + const item = lruCache.get(key); + if (item instanceof CacheItem) return item; + lruCache.delete(key); + return false; + } + return false; +}; +/** +* create cache key +* @param keyData - key data +* @param [opt] - options +* @returns cache key +*/ +var createCacheKey = (keyData, opt = {}) => { + const { customProperty = {}, dimension = {} } = opt; + let cacheKey = ""; + if (keyData && Object.keys(keyData).length && typeof customProperty.callback !== "function" && typeof dimension.callback !== "function") { + keyData.opt = valueToJsonString(opt); + cacheKey = valueToJsonString(keyData); + } + return cacheKey; +}; +//#endregion +export { CacheItem, NullObject, createCacheKey, getCache, setCache }; + +//# sourceMappingURL=cache.js.map \ No newline at end of file diff --git a/node_modules/@asamuzakjp/css-color/dist/esm/js/cache.js.map b/node_modules/@asamuzakjp/css-color/dist/esm/js/cache.js.map new file mode 100644 index 00000000..6ae9de3b --- /dev/null +++ b/node_modules/@asamuzakjp/css-color/dist/esm/js/cache.js.map @@ -0,0 +1 @@ +{"version":3,"file":"cache.js","names":["#item","#isNull"],"sources":["../../../src/js/cache.ts"],"sourcesContent":["/**\n * cache\n */\n\nimport { LRUCache } from 'lru-cache';\nimport { Options } from './typedef';\nimport { valueToJsonString } from './util';\n\n/* numeric constants */\nconst MAX_CACHE = 4096;\n\n/**\n * CacheItem\n */\nexport class CacheItem {\n /* private */\n #isNull: boolean;\n #item: unknown;\n\n /**\n * constructor\n */\n constructor(item: unknown, isNull: boolean = false) {\n this.#item = item;\n this.#isNull = !!isNull;\n }\n\n get item() {\n return this.#item;\n }\n\n get isNull() {\n return this.#isNull;\n }\n}\n\n/**\n * NullObject\n */\nexport class NullObject extends CacheItem {\n /**\n * constructor\n */\n constructor() {\n super(Symbol('null'), true);\n }\n}\n\n/*\n * lru cache\n */\nexport const lruCache = new LRUCache({\n max: MAX_CACHE\n});\n\n/**\n * set cache\n * @param key - cache key\n * @param value - value to cache\n * @returns void\n */\nexport const setCache = (key: string, value: unknown): void => {\n if (key) {\n if (value === null) {\n lruCache.set(key, new NullObject());\n } else if (value instanceof CacheItem) {\n lruCache.set(key, value);\n } else {\n lruCache.set(key, new CacheItem(value));\n }\n }\n};\n\n/**\n * get cache\n * @param key - cache key\n * @returns cached item or false otherwise\n */\nexport const getCache = (key: string): CacheItem | boolean => {\n if (key && lruCache.has(key)) {\n const item = lruCache.get(key);\n if (item instanceof CacheItem) {\n return item;\n }\n // delete unexpected cached item\n lruCache.delete(key);\n return false;\n }\n return false;\n};\n\n/**\n * create cache key\n * @param keyData - key data\n * @param [opt] - options\n * @returns cache key\n */\nexport const createCacheKey = (\n keyData: Record,\n opt: Options = {}\n): string => {\n const { customProperty = {}, dimension = {} } = opt;\n let cacheKey = '';\n if (\n keyData &&\n Object.keys(keyData).length &&\n typeof customProperty.callback !== 'function' &&\n typeof dimension.callback !== 'function'\n ) {\n keyData.opt = valueToJsonString(opt);\n cacheKey = valueToJsonString(keyData);\n }\n return cacheKey;\n};\n"],"mappings":";;;;;;AASA,IAAM,YAAY;;;;AAKlB,IAAa,YAAb,MAAuB;CAErB;CACA;;;;CAKA,YAAY,MAAe,SAAkB,OAAO;AAClD,QAAA,OAAa;AACb,QAAA,SAAe,CAAC,CAAC;;CAGnB,IAAI,OAAO;AACT,SAAO,MAAA;;CAGT,IAAI,SAAS;AACX,SAAO,MAAA;;;;;;AAOX,IAAa,aAAb,cAAgC,UAAU;;;;CAIxC,cAAc;AACZ,QAAM,OAAO,OAAO,EAAE,KAAK;;;AAO/B,IAAa,WAAW,IAAI,SAAS,EACnC,KAAK,WACN,CAAC;;;;;;;AAQF,IAAa,YAAY,KAAa,UAAyB;AAC7D,KAAI,IACF,KAAI,UAAU,KACZ,UAAS,IAAI,KAAK,IAAI,YAAY,CAAC;UAC1B,iBAAiB,UAC1B,UAAS,IAAI,KAAK,MAAM;KAExB,UAAS,IAAI,KAAK,IAAI,UAAU,MAAM,CAAC;;;;;;;AAU7C,IAAa,YAAY,QAAqC;AAC5D,KAAI,OAAO,SAAS,IAAI,IAAI,EAAE;EAC5B,MAAM,OAAO,SAAS,IAAI,IAAI;AAC9B,MAAI,gBAAgB,UAClB,QAAO;AAGT,WAAS,OAAO,IAAI;AACpB,SAAO;;AAET,QAAO;;;;;;;;AAST,IAAa,kBACX,SACA,MAAe,EAAE,KACN;CACX,MAAM,EAAE,iBAAiB,EAAE,EAAE,YAAY,EAAE,KAAK;CAChD,IAAI,WAAW;AACf,KACE,WACA,OAAO,KAAK,QAAQ,CAAC,UACrB,OAAO,eAAe,aAAa,cACnC,OAAO,UAAU,aAAa,YAC9B;AACA,UAAQ,MAAM,kBAAkB,IAAI;AACpC,aAAW,kBAAkB,QAAQ;;AAEvC,QAAO"} \ No newline at end of file diff --git a/node_modules/@asamuzakjp/css-color/dist/esm/js/color.d.ts b/node_modules/@asamuzakjp/css-color/dist/esm/js/color.d.ts new file mode 100644 index 00000000..9a1a0e22 --- /dev/null +++ b/node_modules/@asamuzakjp/css-color/dist/esm/js/color.d.ts @@ -0,0 +1,537 @@ +import { NullObject } from './cache.js'; +import { ColorChannels, Options, SpecifiedColorChannels } from './typedef.js'; +/** + * @type TriColorChannels - color channels without alpha + */ +type TriColorChannels = [x: number, y: number, z: number]; +/** + * @type ColorMatrix - color matrix + */ +type ColorMatrix = [ + r1: TriColorChannels, + r2: TriColorChannels, + r3: TriColorChannels +]; +/** + * named colors + */ +export declare const NAMED_COLORS: { + readonly aliceblue: [240, 248, 255]; + readonly antiquewhite: [250, 235, 215]; + readonly aqua: [0, 255, 255]; + readonly aquamarine: [127, 255, 212]; + readonly azure: [240, 255, 255]; + readonly beige: [245, 245, 220]; + readonly bisque: [255, 228, 196]; + readonly black: [0, 0, 0]; + readonly blanchedalmond: [255, 235, 205]; + readonly blue: [0, 0, 255]; + readonly blueviolet: [138, 43, 226]; + readonly brown: [165, 42, 42]; + readonly burlywood: [222, 184, 135]; + readonly cadetblue: [95, 158, 160]; + readonly chartreuse: [127, 255, 0]; + readonly chocolate: [210, 105, 30]; + readonly coral: [255, 127, 80]; + readonly cornflowerblue: [100, 149, 237]; + readonly cornsilk: [255, 248, 220]; + readonly crimson: [220, 20, 60]; + readonly cyan: [0, 255, 255]; + readonly darkblue: [0, 0, 139]; + readonly darkcyan: [0, 139, 139]; + readonly darkgoldenrod: [184, 134, 11]; + readonly darkgray: [169, 169, 169]; + readonly darkgreen: [0, 100, 0]; + readonly darkgrey: [169, 169, 169]; + readonly darkkhaki: [189, 183, 107]; + readonly darkmagenta: [139, 0, 139]; + readonly darkolivegreen: [85, 107, 47]; + readonly darkorange: [255, 140, 0]; + readonly darkorchid: [153, 50, 204]; + readonly darkred: [139, 0, 0]; + readonly darksalmon: [233, 150, 122]; + readonly darkseagreen: [143, 188, 143]; + readonly darkslateblue: [72, 61, 139]; + readonly darkslategray: [47, 79, 79]; + readonly darkslategrey: [47, 79, 79]; + readonly darkturquoise: [0, 206, 209]; + readonly darkviolet: [148, 0, 211]; + readonly deeppink: [255, 20, 147]; + readonly deepskyblue: [0, 191, 255]; + readonly dimgray: [105, 105, 105]; + readonly dimgrey: [105, 105, 105]; + readonly dodgerblue: [30, 144, 255]; + readonly firebrick: [178, 34, 34]; + readonly floralwhite: [255, 250, 240]; + readonly forestgreen: [34, 139, 34]; + readonly fuchsia: [255, 0, 255]; + readonly gainsboro: [220, 220, 220]; + readonly ghostwhite: [248, 248, 255]; + readonly gold: [255, 215, 0]; + readonly goldenrod: [218, 165, 32]; + readonly gray: [128, 128, 128]; + readonly green: [0, 128, 0]; + readonly greenyellow: [173, 255, 47]; + readonly grey: [128, 128, 128]; + readonly honeydew: [240, 255, 240]; + readonly hotpink: [255, 105, 180]; + readonly indianred: [205, 92, 92]; + readonly indigo: [75, 0, 130]; + readonly ivory: [255, 255, 240]; + readonly khaki: [240, 230, 140]; + readonly lavender: [230, 230, 250]; + readonly lavenderblush: [255, 240, 245]; + readonly lawngreen: [124, 252, 0]; + readonly lemonchiffon: [255, 250, 205]; + readonly lightblue: [173, 216, 230]; + readonly lightcoral: [240, 128, 128]; + readonly lightcyan: [224, 255, 255]; + readonly lightgoldenrodyellow: [250, 250, 210]; + readonly lightgray: [211, 211, 211]; + readonly lightgreen: [144, 238, 144]; + readonly lightgrey: [211, 211, 211]; + readonly lightpink: [255, 182, 193]; + readonly lightsalmon: [255, 160, 122]; + readonly lightseagreen: [32, 178, 170]; + readonly lightskyblue: [135, 206, 250]; + readonly lightslategray: [119, 136, 153]; + readonly lightslategrey: [119, 136, 153]; + readonly lightsteelblue: [176, 196, 222]; + readonly lightyellow: [255, 255, 224]; + readonly lime: [0, 255, 0]; + readonly limegreen: [50, 205, 50]; + readonly linen: [250, 240, 230]; + readonly magenta: [255, 0, 255]; + readonly maroon: [128, 0, 0]; + readonly mediumaquamarine: [102, 205, 170]; + readonly mediumblue: [0, 0, 205]; + readonly mediumorchid: [186, 85, 211]; + readonly mediumpurple: [147, 112, 219]; + readonly mediumseagreen: [60, 179, 113]; + readonly mediumslateblue: [123, 104, 238]; + readonly mediumspringgreen: [0, 250, 154]; + readonly mediumturquoise: [72, 209, 204]; + readonly mediumvioletred: [199, 21, 133]; + readonly midnightblue: [25, 25, 112]; + readonly mintcream: [245, 255, 250]; + readonly mistyrose: [255, 228, 225]; + readonly moccasin: [255, 228, 181]; + readonly navajowhite: [255, 222, 173]; + readonly navy: [0, 0, 128]; + readonly oldlace: [253, 245, 230]; + readonly olive: [128, 128, 0]; + readonly olivedrab: [107, 142, 35]; + readonly orange: [255, 165, 0]; + readonly orangered: [255, 69, 0]; + readonly orchid: [218, 112, 214]; + readonly palegoldenrod: [238, 232, 170]; + readonly palegreen: [152, 251, 152]; + readonly paleturquoise: [175, 238, 238]; + readonly palevioletred: [219, 112, 147]; + readonly papayawhip: [255, 239, 213]; + readonly peachpuff: [255, 218, 185]; + readonly peru: [205, 133, 63]; + readonly pink: [255, 192, 203]; + readonly plum: [221, 160, 221]; + readonly powderblue: [176, 224, 230]; + readonly purple: [128, 0, 128]; + readonly rebeccapurple: [102, 51, 153]; + readonly red: [255, 0, 0]; + readonly rosybrown: [188, 143, 143]; + readonly royalblue: [65, 105, 225]; + readonly saddlebrown: [139, 69, 19]; + readonly salmon: [250, 128, 114]; + readonly sandybrown: [244, 164, 96]; + readonly seagreen: [46, 139, 87]; + readonly seashell: [255, 245, 238]; + readonly sienna: [160, 82, 45]; + readonly silver: [192, 192, 192]; + readonly skyblue: [135, 206, 235]; + readonly slateblue: [106, 90, 205]; + readonly slategray: [112, 128, 144]; + readonly slategrey: [112, 128, 144]; + readonly snow: [255, 250, 250]; + readonly springgreen: [0, 255, 127]; + readonly steelblue: [70, 130, 180]; + readonly tan: [210, 180, 140]; + readonly teal: [0, 128, 128]; + readonly thistle: [216, 191, 216]; + readonly tomato: [255, 99, 71]; + readonly turquoise: [64, 224, 208]; + readonly violet: [238, 130, 238]; + readonly wheat: [245, 222, 179]; + readonly white: [255, 255, 255]; + readonly whitesmoke: [245, 245, 245]; + readonly yellow: [255, 255, 0]; + readonly yellowgreen: [154, 205, 50]; +}; +/** + * cache invalid color value + * @param key - cache key + * @param nullable - is nullable + * @returns cached value + */ +export declare const cacheInvalidColorValue: (cacheKey: string, format: string, nullable?: boolean) => SpecifiedColorChannels | string | NullObject; +/** + * resolve invalid color value + * @param format - output format + * @param nullable - is nullable + * @returns resolved value + */ +export declare const resolveInvalidColorValue: (format: string, nullable?: boolean) => SpecifiedColorChannels | string | NullObject; +/** + * validate color components + * @param arr - color components + * @param [opt] - options + * @param [opt.alpha] - alpha channel + * @param [opt.minLength] - min length + * @param [opt.maxLength] - max length + * @param [opt.minRange] - min range + * @param [opt.maxRange] - max range + * @param [opt.validateRange] - validate range + * @returns result - validated color components + */ +export declare const validateColorComponents: (arr: ColorChannels | TriColorChannels, opt?: { + alpha?: boolean; + minLength?: number; + maxLength?: number; + minRange?: number; + maxRange?: number; + validateRange?: boolean; +}) => ColorChannels | TriColorChannels; +/** + * transform matrix + * @param mtx - 3 * 3 matrix + * @param vct - vector + * @param [skip] - skip validate + * @returns TriColorChannels - [p1, p2, p3] + */ +export declare const transformMatrix: (mtx: ColorMatrix, vct: TriColorChannels, skip?: boolean) => TriColorChannels; +/** + * normalize color components + * @param colorA - color components [v1, v2, v3, v4] + * @param colorB - color components [v1, v2, v3, v4] + * @param [skip] - skip validate + * @returns result - [colorA, colorB] + */ +export declare const normalizeColorComponents: (colorA: [number | string, number | string, number | string, number | string], colorB: [number | string, number | string, number | string, number | string], skip?: boolean) => [ColorChannels, ColorChannels]; +/** + * number to hex string + * @param value - numeric value + * @returns hex string + */ +export declare const numberToHexString: (value: number) => string; +/** + * angle to deg + * @param angle + * @returns deg: 0..360 + */ +export declare const angleToDeg: (angle: string) => number; +/** + * parse alpha + * @param [alpha] - alpha value + * @returns alpha: 0..1 + */ +export declare const parseAlpha: (alpha?: string) => number; +/** + * parse hex alpha + * @param value - alpha value in hex string + * @returns alpha: 0..1 + */ +export declare const parseHexAlpha: (value: string) => number; +/** + * transform rgb to linear rgb + * @param rgb - [r, g, b] r|g|b: 0..255 + * @param [skip] - skip validate + * @returns TriColorChannels - [r, g, b] r|g|b: 0..1 + */ +export declare const transformRgbToLinearRgb: (rgb: TriColorChannels, skip?: boolean) => TriColorChannels; +/** + * transform rgb to xyz + * @param rgb - [r, g, b] r|g|b: 0..255 + * @param [skip] - skip validate + * @returns TriColorChannels - [x, y, z] + */ +export declare const transformRgbToXyz: (rgb: TriColorChannels, skip?: boolean) => TriColorChannels; +/** + * transform rgb to xyz-d50 + * @param rgb - [r, g, b] r|g|b: 0..255 alpha: 0..1 + * @returns TriColorChannels - [x, y, z] + */ +export declare const transformRgbToXyzD50: (rgb: TriColorChannels) => TriColorChannels; +/** + * transform linear rgb to rgb + * @param rgb - [r, g, b] r|g|b: 0..1 + * @param [round] - round result + * @returns TriColorChannels - [r, g, b] r|g|b: 0..255 + */ +export declare const transformLinearRgbToRgb: (rgb: TriColorChannels, round?: boolean) => TriColorChannels; +/** + * transform xyz to rgb + * @param xyz - [x, y, z] + * @param [skip] - skip validate + * @returns TriColorChannels - [r, g, b] r|g|b: 0..255 + */ +export declare const transformXyzToRgb: (xyz: TriColorChannels, skip?: boolean) => TriColorChannels; +/** + * transform xyz to xyz-d50 + * @param xyz - [x, y, z] + * @returns TriColorChannels - [x, y, z] + */ +export declare const transformXyzToXyzD50: (xyz: TriColorChannels) => TriColorChannels; +/** + * transform xyz to hsl + * @param xyz - [x, y, z] + * @param [skip] - skip validate + * @returns TriColorChannels - [h, s, l] + */ +export declare const transformXyzToHsl: (xyz: TriColorChannels, skip?: boolean) => TriColorChannels; +/** + * transform xyz to hwb + * @param xyz - [x, y, z] + * @param [skip] - skip validate + * @returns TriColorChannels - [h, w, b] + */ +export declare const transformXyzToHwb: (xyz: TriColorChannels, skip?: boolean) => TriColorChannels; +/** + * transform xyz to oklab + * @param xyz - [x, y, z] + * @param [skip] - skip validate + * @returns TriColorChannels - [l, a, b] + */ +export declare const transformXyzToOklab: (xyz: TriColorChannels, skip?: boolean) => TriColorChannels; +/** + * transform xyz to oklch + * @param xyz - [x, y, z] + * @param [skip] - skip validate + * @returns TriColorChannels - [l, c, h] + */ +export declare const transformXyzToOklch: (xyz: TriColorChannels, skip?: boolean) => TriColorChannels; +/** + * transform xyz D50 to rgb + * @param xyz - [x, y, z] + * @param [skip] - skip validate + * @returns TriColorChannels - [r, g, b] r|g|b: 0..255 + */ +export declare const transformXyzD50ToRgb: (xyz: TriColorChannels, skip?: boolean) => TriColorChannels; +/** + * transform xyz-d50 to lab + * @param xyz - [x, y, z] + * @param [skip] - skip validate + * @returns TriColorChannels - [l, a, b] + */ +export declare const transformXyzD50ToLab: (xyz: TriColorChannels, skip?: boolean) => TriColorChannels; +/** + * transform xyz-d50 to lch + * @param xyz - [x, y, z] + * @param [skip] - skip validate + * @returns TriColorChannels - [l, c, h] + */ +export declare const transformXyzD50ToLch: (xyz: TriColorChannels, skip?: boolean) => TriColorChannels; +/** + * convert rgb to hex color + * @param rgb - [r, g, b, alpha] r|g|b: 0..255 alpha: 0..1 + * @returns hex color + */ +export declare const convertRgbToHex: (rgb: ColorChannels) => string; +/** + * convert linear rgb to hex color + * @param rgb - [r, g, b, alpha] r|g|b|alpha: 0..1 + * @param [skip] - skip validate + * @returns hex color + */ +export declare const convertLinearRgbToHex: (rgb: ColorChannels, skip?: boolean) => string; +/** + * convert xyz to hex color + * @param xyz - [x, y, z, alpha] + * @returns hex color + */ +export declare const convertXyzToHex: (xyz: ColorChannels) => string; +/** + * convert xyz D50 to hex color + * @param xyz - [x, y, z, alpha] + * @returns hex color + */ +export declare const convertXyzD50ToHex: (xyz: ColorChannels) => string; +/** + * convert hex color to rgb + * @param value - hex color value + * @returns ColorChannels - [r, g, b, alpha] r|g|b: 0..255 alpha: 0..1 + */ +export declare const convertHexToRgb: (value: string) => ColorChannels; +/** + * convert hex color to linear rgb + * @param value - hex color value + * @returns ColorChannels - [r, g, b, alpha] r|g|b|alpha: 0..1 + */ +export declare const convertHexToLinearRgb: (value: string) => ColorChannels; +/** + * convert hex color to xyz + * @param value - hex color value + * @returns ColorChannels - [x, y, z, alpha] + */ +export declare const convertHexToXyz: (value: string) => ColorChannels; +/** + * parse rgb() + * @param value - rgb color value + * @param [opt] - options + * @returns parsed color - ['rgb', r, g, b, alpha], '(empty)', NullObject + */ +export declare const parseRgb: (value: string, opt?: Options) => SpecifiedColorChannels | string | NullObject; +/** + * parse hsl() + * @param value - hsl color value + * @param [opt] - options + * @returns parsed color - ['rgb', r, g, b, alpha], '(empty)', NullObject + */ +export declare const parseHsl: (value: string, opt?: Options) => SpecifiedColorChannels | string | NullObject; +/** + * parse hwb() + * @param value - hwb color value + * @param [opt] - options + * @returns parsed color - ['rgb', r, g, b, alpha], '(empty)', NullObject + */ +export declare const parseHwb: (value: string, opt?: Options) => SpecifiedColorChannels | string | NullObject; +/** + * parse lab() + * @param value - lab color value + * @param [opt] - options + * @returns parsed color + * - [xyz-d50, x, y, z, alpha], ['lab', l, a, b, alpha], '(empty)', NullObject + */ +export declare const parseLab: (value: string, opt?: Options) => SpecifiedColorChannels | string | NullObject; +/** + * parse lch() + * @param value - lch color value + * @param [opt] - options + * @returns parsed color + * - ['xyz-d50', x, y, z, alpha], ['lch', l, c, h, alpha] + * - '(empty)', NullObject + */ +export declare const parseLch: (value: string, opt?: Options) => SpecifiedColorChannels | string | NullObject; +/** + * parse oklab() + * @param value - oklab color value + * @param [opt] - options + * @returns parsed color + * - ['xyz-d65', x, y, z, alpha], ['oklab', l, a, b, alpha] + * - '(empty)', NullObject + */ +export declare const parseOklab: (value: string, opt?: Options) => SpecifiedColorChannels | string | NullObject; +/** + * parse oklch() + * @param value - oklch color value + * @param [opt] - options + * @returns parsed color + * - ['xyz-d65', x, y, z, alpha], ['oklch', l, c, h, alpha] + * - '(empty)', NullObject + */ +export declare const parseOklch: (value: string, opt?: Options) => SpecifiedColorChannels | string | NullObject; +/** + * parse color() + * @param value - color function value + * @param [opt] - options + * @returns parsed color + * - ['xyz-(d50|d65)', x, y, z, alpha], [cs, r, g, b, alpha] + * - '(empty)', NullObject + */ +export declare const parseColorFunc: (value: string, opt?: Options) => SpecifiedColorChannels | string | NullObject; +/** + * parse color value + * @param value - CSS color value + * @param [opt] - options + * @returns parsed color + * - ['xyz-(d50|d65)', x, y, z, alpha], ['rgb', r, g, b, alpha] + * - value, '(empty)', NullObject + */ +export declare const parseColorValue: (value: string, opt?: Options) => SpecifiedColorChannels | string | NullObject; +/** + * resolve color value + * @param value - CSS color value + * @param [opt] - options + * @returns resolved color + * - [cs, v1, v2, v3, alpha], value, '(empty)', NullObject + */ +export declare const resolveColorValue: (value: string, opt?: Options) => SpecifiedColorChannels | string | NullObject; +/** + * resolve color() + * @param value - color function value + * @param [opt] - options + * @returns resolved color - [cs, v1, v2, v3, alpha], '(empty)', NullObject + */ +export declare const resolveColorFunc: (value: string, opt?: Options) => SpecifiedColorChannels | string | NullObject; +/** + * convert color value to linear rgb + * @param value - CSS color value + * @param [opt] - options + * @returns ColorChannels | NullObject - [r, g, b, alpha] r|g|b|alpha: 0..1 + */ +export declare const convertColorToLinearRgb: (value: string, opt?: { + colorSpace?: string; + format?: string; +}) => ColorChannels | NullObject; +/** + * convert color value to rgb + * @param value - CSS color value + * @param [opt] - options + * @returns ColorChannels | NullObject + * - [r, g, b, alpha] r|g|b: 0..255 alpha: 0..1 + */ +export declare const convertColorToRgb: (value: string, opt?: Options) => ColorChannels | NullObject; +/** + * convert color value to xyz + * @param value - CSS color value + * @param [opt] - options + * @returns ColorChannels | NullObject - [x, y, z, alpha] + */ +export declare const convertColorToXyz: (value: string, opt?: Options) => ColorChannels | NullObject; +/** + * convert color value to hsl + * @param value - CSS color value + * @param [opt] - options + * @returns ColorChannels | NullObject - [h, s, l, alpha], hue may be powerless + */ +export declare const convertColorToHsl: (value: string, opt?: Options) => ColorChannels | [number | string, number, number, number] | NullObject; +/** + * convert color value to hwb + * @param value - CSS color value + * @param [opt] - options + * @returns ColorChannels | NullObject - [h, w, b, alpha], hue may be powerless + */ +export declare const convertColorToHwb: (value: string, opt?: Options) => ColorChannels | [number | string, number, number, number] | NullObject; +/** + * convert color value to lab + * @param value - CSS color value + * @param [opt] - options + * @returns ColorChannels | NullObject - [l, a, b, alpha] + */ +export declare const convertColorToLab: (value: string, opt?: Options) => ColorChannels | NullObject; +/** + * convert color value to lch + * @param value - CSS color value + * @param [opt] - options + * @returns ColorChannels | NullObject - [l, c, h, alpha], hue may be powerless + */ +export declare const convertColorToLch: (value: string, opt?: Options) => ColorChannels | [number, number, number | string, number] | NullObject; +/** + * convert color value to oklab + * @param value - CSS color value + * @param [opt] - options + * @returns ColorChannels | NullObject - [l, a, b, alpha] + */ +export declare const convertColorToOklab: (value: string, opt?: Options) => ColorChannels | NullObject; +/** + * convert color value to oklch + * @param value - CSS color value + * @param [opt] - options + * @returns ColorChannels | NullObject - [l, c, h, alpha], hue may be powerless + */ +export declare const convertColorToOklch: (value: string, opt?: Options) => ColorChannels | [number, number, number | string, number] | NullObject; +/** + * resolve color-mix() + * @param value - color-mix color value + * @param [opt] - options + * @returns resolved color - [cs, v1, v2, v3, alpha], '(empty)' + */ +export declare const resolveColorMix: (value: string, opt?: Options) => SpecifiedColorChannels | string | NullObject; +export {}; diff --git a/node_modules/@asamuzakjp/css-color/dist/esm/js/color.js b/node_modules/@asamuzakjp/css-color/dist/esm/js/color.js new file mode 100644 index 00000000..bc3646b3 --- /dev/null +++ b/node_modules/@asamuzakjp/css-color/dist/esm/js/color.js @@ -0,0 +1,3536 @@ +import { isString } from "./common.js"; +import { ANGLE, CS_HUE_CAPT, CS_MIX, CS_RGB, CS_XYZ, FN_MIX, NONE, NUM, PCT, SYN_COLOR_TYPE, SYN_FN_COLOR, SYN_HSL, SYN_HSL_LV3, SYN_LCH, SYN_MIX, SYN_MIX_CAPT, SYN_MIX_PART, SYN_MOD, SYN_RGB_LV3, VAL_COMP, VAL_MIX, VAL_SPEC } from "./constant.js"; +import { resolveColor } from "./resolve.js"; +import { interpolateHue, roundToPrecision, splitValue } from "./util.js"; +import { CacheItem, NullObject, createCacheKey, getCache, setCache } from "./cache.js"; +//#region src/js/color.ts +/** +* color +* +* Ref: CSS Color Module Level 4 +* Sample code for Color Conversions +* https://w3c.github.io/csswg-drafts/css-color-4/#color-conversion-code +*/ +var NAMESPACE = "color"; +var PPTH = .001; +var HALF = .5; +var DUO = 2; +var TRIA = 3; +var QUAD = 4; +var OCT = 8; +var DEC = 10; +var DOZ = 12; +var HEX = 16; +var SEXA = 60; +var DEG_HALF = 180; +var DEG = 360; +var MAX_PCT = 100; +var MAX_RGB = 255; +var POW_SQR = 2; +var POW_CUBE = 3; +var POW_LINEAR = 2.4; +var LINEAR_COEF = 12.92; +var LINEAR_OFFSET = .055; +var LAB_L = 116; +var LAB_A = 500; +var LAB_B = 200; +var LAB_EPSILON = 216 / 24389; +var LAB_KAPPA = 24389 / 27; +var D50 = [ + .3457 / .3585, + 1, + .2958 / .3585 +]; +var MATRIX_D50_TO_D65 = [ + [ + .955473421488075, + -.02309845494876471, + .06325924320057072 + ], + [ + -.0283697093338637, + 1.0099953980813041, + .021041441191917323 + ], + [ + .012314014864481998, + -.020507649298898964, + 1.330365926242124 + ] +]; +var MATRIX_D65_TO_D50 = [ + [ + 1.0479297925449969, + .022946870601609652, + -.05019226628920524 + ], + [ + .02962780877005599, + .9904344267538799, + -.017073799063418826 + ], + [ + -.009243040646204504, + .015055191490298152, + .7518742814281371 + ] +]; +var MATRIX_L_RGB_TO_XYZ = [ + [ + 506752 / 1228815, + 87881 / 245763, + 12673 / 70218 + ], + [ + 87098 / 409605, + 175762 / 245763, + 12673 / 175545 + ], + [ + 7918 / 409605, + 87881 / 737289, + 1001167 / 1053270 + ] +]; +var MATRIX_XYZ_TO_L_RGB = [ + [ + 12831 / 3959, + -329 / 214, + -1974 / 3959 + ], + [ + -851781 / 878810, + 1648619 / 878810, + 36519 / 878810 + ], + [ + 705 / 12673, + -2585 / 12673, + 705 / 667 + ] +]; +var MATRIX_XYZ_TO_LMS = [ + [ + .819022437996703, + .3619062600528904, + -.1288737815209879 + ], + [ + .0329836539323885, + .9292868615863434, + .0361446663506424 + ], + [ + .0481771893596242, + .2642395317527308, + .6335478284694309 + ] +]; +var MATRIX_LMS_TO_XYZ = [ + [ + 1.2268798758459243, + -.5578149944602171, + .2813910456659647 + ], + [ + -.0405757452148008, + 1.112286803280317, + -.0717110580655164 + ], + [ + -.0763729366746601, + -.4214933324022432, + 1.5869240198367816 + ] +]; +var MATRIX_OKLAB_TO_LMS = [ + [ + 1, + .3963377773761749, + .2158037573099136 + ], + [ + 1, + -.1055613458156586, + -.0638541728258133 + ], + [ + 1, + -.0894841775298119, + -1.2914855480194092 + ] +]; +var MATRIX_LMS_TO_OKLAB = [ + [ + .210454268309314, + .7936177747023054, + -.0040720430116193 + ], + [ + 1.9779985324311684, + -2.42859224204858, + .450593709617411 + ], + [ + .0259040424655478, + .7827717124575296, + -.8086757549230774 + ] +]; +var MATRIX_P3_TO_XYZ = [ + [ + 608311 / 1250200, + 189793 / 714400, + 198249 / 1000160 + ], + [ + 35783 / 156275, + 247089 / 357200, + 198249 / 2500400 + ], + [ + 0 / 1, + 32229 / 714400, + 5220557 / 5000800 + ] +]; +var MATRIX_REC2020_TO_XYZ = [ + [ + 63426534 / 99577255, + 20160776 / 139408157, + 47086771 / 278816314 + ], + [ + 26158966 / 99577255, + 472592308 / 697040785, + 8267143 / 139408157 + ], + [ + 0 / 1, + 19567812 / 697040785, + 295819943 / 278816314 + ] +]; +var MATRIX_A98_TO_XYZ = [ + [ + 573536 / 994567, + 263643 / 1420810, + 187206 / 994567 + ], + [ + 591459 / 1989134, + 6239551 / 9945670, + 374412 / 4972835 + ], + [ + 53769 / 1989134, + 351524 / 4972835, + 4929758 / 4972835 + ] +]; +var MATRIX_PROPHOTO_TO_XYZ_D50 = [ + [ + .7977666449006423, + .13518129740053308, + .0313477341283922 + ], + [ + .2880748288194013, + .711835234241873, + 8993693872564e-17 + ], + [ + 0, + 0, + .8251046025104602 + ] +]; +var REG_COLOR = new RegExp(`^(?:${SYN_COLOR_TYPE})$`); +var REG_CS_HUE = new RegExp(`^${CS_HUE_CAPT}$`); +var REG_CS_XYZ = /^xyz(?:-d(?:50|65))?$/; +var REG_CURRENT = /^currentColor$/i; +var REG_FN_COLOR = new RegExp(`^color\\(\\s*(${SYN_FN_COLOR})\\s*\\)$`); +var REG_HSL = new RegExp(`^hsla?\\(\\s*(${SYN_HSL}|${SYN_HSL_LV3})\\s*\\)$`); +var REG_HWB = new RegExp(`^hwb\\(\\s*(${SYN_HSL})\\s*\\)$`); +var REG_LAB = new RegExp(`^lab\\(\\s*(${SYN_MOD})\\s*\\)$`); +var REG_LCH = new RegExp(`^lch\\(\\s*(${SYN_LCH})\\s*\\)$`); +var REG_MIX = new RegExp(`^${SYN_MIX}$`); +var REG_MIX_CAPT = new RegExp(`^${SYN_MIX_CAPT}$`); +var REG_MIX_NEST = new RegExp(`${SYN_MIX}`, "g"); +var REG_OKLAB = new RegExp(`^oklab\\(\\s*(${SYN_MOD})\\s*\\)$`); +var REG_OKLCH = new RegExp(`^oklch\\(\\s*(${SYN_LCH})\\s*\\)$`); +var REG_SPEC = /^(?:specifi|comput)edValue$/; +/** +* named colors +*/ +var NAMED_COLORS = { + aliceblue: [ + 240, + 248, + 255 + ], + antiquewhite: [ + 250, + 235, + 215 + ], + aqua: [ + 0, + 255, + 255 + ], + aquamarine: [ + 127, + 255, + 212 + ], + azure: [ + 240, + 255, + 255 + ], + beige: [ + 245, + 245, + 220 + ], + bisque: [ + 255, + 228, + 196 + ], + black: [ + 0, + 0, + 0 + ], + blanchedalmond: [ + 255, + 235, + 205 + ], + blue: [ + 0, + 0, + 255 + ], + blueviolet: [ + 138, + 43, + 226 + ], + brown: [ + 165, + 42, + 42 + ], + burlywood: [ + 222, + 184, + 135 + ], + cadetblue: [ + 95, + 158, + 160 + ], + chartreuse: [ + 127, + 255, + 0 + ], + chocolate: [ + 210, + 105, + 30 + ], + coral: [ + 255, + 127, + 80 + ], + cornflowerblue: [ + 100, + 149, + 237 + ], + cornsilk: [ + 255, + 248, + 220 + ], + crimson: [ + 220, + 20, + 60 + ], + cyan: [ + 0, + 255, + 255 + ], + darkblue: [ + 0, + 0, + 139 + ], + darkcyan: [ + 0, + 139, + 139 + ], + darkgoldenrod: [ + 184, + 134, + 11 + ], + darkgray: [ + 169, + 169, + 169 + ], + darkgreen: [ + 0, + 100, + 0 + ], + darkgrey: [ + 169, + 169, + 169 + ], + darkkhaki: [ + 189, + 183, + 107 + ], + darkmagenta: [ + 139, + 0, + 139 + ], + darkolivegreen: [ + 85, + 107, + 47 + ], + darkorange: [ + 255, + 140, + 0 + ], + darkorchid: [ + 153, + 50, + 204 + ], + darkred: [ + 139, + 0, + 0 + ], + darksalmon: [ + 233, + 150, + 122 + ], + darkseagreen: [ + 143, + 188, + 143 + ], + darkslateblue: [ + 72, + 61, + 139 + ], + darkslategray: [ + 47, + 79, + 79 + ], + darkslategrey: [ + 47, + 79, + 79 + ], + darkturquoise: [ + 0, + 206, + 209 + ], + darkviolet: [ + 148, + 0, + 211 + ], + deeppink: [ + 255, + 20, + 147 + ], + deepskyblue: [ + 0, + 191, + 255 + ], + dimgray: [ + 105, + 105, + 105 + ], + dimgrey: [ + 105, + 105, + 105 + ], + dodgerblue: [ + 30, + 144, + 255 + ], + firebrick: [ + 178, + 34, + 34 + ], + floralwhite: [ + 255, + 250, + 240 + ], + forestgreen: [ + 34, + 139, + 34 + ], + fuchsia: [ + 255, + 0, + 255 + ], + gainsboro: [ + 220, + 220, + 220 + ], + ghostwhite: [ + 248, + 248, + 255 + ], + gold: [ + 255, + 215, + 0 + ], + goldenrod: [ + 218, + 165, + 32 + ], + gray: [ + 128, + 128, + 128 + ], + green: [ + 0, + 128, + 0 + ], + greenyellow: [ + 173, + 255, + 47 + ], + grey: [ + 128, + 128, + 128 + ], + honeydew: [ + 240, + 255, + 240 + ], + hotpink: [ + 255, + 105, + 180 + ], + indianred: [ + 205, + 92, + 92 + ], + indigo: [ + 75, + 0, + 130 + ], + ivory: [ + 255, + 255, + 240 + ], + khaki: [ + 240, + 230, + 140 + ], + lavender: [ + 230, + 230, + 250 + ], + lavenderblush: [ + 255, + 240, + 245 + ], + lawngreen: [ + 124, + 252, + 0 + ], + lemonchiffon: [ + 255, + 250, + 205 + ], + lightblue: [ + 173, + 216, + 230 + ], + lightcoral: [ + 240, + 128, + 128 + ], + lightcyan: [ + 224, + 255, + 255 + ], + lightgoldenrodyellow: [ + 250, + 250, + 210 + ], + lightgray: [ + 211, + 211, + 211 + ], + lightgreen: [ + 144, + 238, + 144 + ], + lightgrey: [ + 211, + 211, + 211 + ], + lightpink: [ + 255, + 182, + 193 + ], + lightsalmon: [ + 255, + 160, + 122 + ], + lightseagreen: [ + 32, + 178, + 170 + ], + lightskyblue: [ + 135, + 206, + 250 + ], + lightslategray: [ + 119, + 136, + 153 + ], + lightslategrey: [ + 119, + 136, + 153 + ], + lightsteelblue: [ + 176, + 196, + 222 + ], + lightyellow: [ + 255, + 255, + 224 + ], + lime: [ + 0, + 255, + 0 + ], + limegreen: [ + 50, + 205, + 50 + ], + linen: [ + 250, + 240, + 230 + ], + magenta: [ + 255, + 0, + 255 + ], + maroon: [ + 128, + 0, + 0 + ], + mediumaquamarine: [ + 102, + 205, + 170 + ], + mediumblue: [ + 0, + 0, + 205 + ], + mediumorchid: [ + 186, + 85, + 211 + ], + mediumpurple: [ + 147, + 112, + 219 + ], + mediumseagreen: [ + 60, + 179, + 113 + ], + mediumslateblue: [ + 123, + 104, + 238 + ], + mediumspringgreen: [ + 0, + 250, + 154 + ], + mediumturquoise: [ + 72, + 209, + 204 + ], + mediumvioletred: [ + 199, + 21, + 133 + ], + midnightblue: [ + 25, + 25, + 112 + ], + mintcream: [ + 245, + 255, + 250 + ], + mistyrose: [ + 255, + 228, + 225 + ], + moccasin: [ + 255, + 228, + 181 + ], + navajowhite: [ + 255, + 222, + 173 + ], + navy: [ + 0, + 0, + 128 + ], + oldlace: [ + 253, + 245, + 230 + ], + olive: [ + 128, + 128, + 0 + ], + olivedrab: [ + 107, + 142, + 35 + ], + orange: [ + 255, + 165, + 0 + ], + orangered: [ + 255, + 69, + 0 + ], + orchid: [ + 218, + 112, + 214 + ], + palegoldenrod: [ + 238, + 232, + 170 + ], + palegreen: [ + 152, + 251, + 152 + ], + paleturquoise: [ + 175, + 238, + 238 + ], + palevioletred: [ + 219, + 112, + 147 + ], + papayawhip: [ + 255, + 239, + 213 + ], + peachpuff: [ + 255, + 218, + 185 + ], + peru: [ + 205, + 133, + 63 + ], + pink: [ + 255, + 192, + 203 + ], + plum: [ + 221, + 160, + 221 + ], + powderblue: [ + 176, + 224, + 230 + ], + purple: [ + 128, + 0, + 128 + ], + rebeccapurple: [ + 102, + 51, + 153 + ], + red: [ + 255, + 0, + 0 + ], + rosybrown: [ + 188, + 143, + 143 + ], + royalblue: [ + 65, + 105, + 225 + ], + saddlebrown: [ + 139, + 69, + 19 + ], + salmon: [ + 250, + 128, + 114 + ], + sandybrown: [ + 244, + 164, + 96 + ], + seagreen: [ + 46, + 139, + 87 + ], + seashell: [ + 255, + 245, + 238 + ], + sienna: [ + 160, + 82, + 45 + ], + silver: [ + 192, + 192, + 192 + ], + skyblue: [ + 135, + 206, + 235 + ], + slateblue: [ + 106, + 90, + 205 + ], + slategray: [ + 112, + 128, + 144 + ], + slategrey: [ + 112, + 128, + 144 + ], + snow: [ + 255, + 250, + 250 + ], + springgreen: [ + 0, + 255, + 127 + ], + steelblue: [ + 70, + 130, + 180 + ], + tan: [ + 210, + 180, + 140 + ], + teal: [ + 0, + 128, + 128 + ], + thistle: [ + 216, + 191, + 216 + ], + tomato: [ + 255, + 99, + 71 + ], + turquoise: [ + 64, + 224, + 208 + ], + violet: [ + 238, + 130, + 238 + ], + wheat: [ + 245, + 222, + 179 + ], + white: [ + 255, + 255, + 255 + ], + whitesmoke: [ + 245, + 245, + 245 + ], + yellow: [ + 255, + 255, + 0 + ], + yellowgreen: [ + 154, + 205, + 50 + ] +}; +/** +* cache invalid color value +* @param key - cache key +* @param nullable - is nullable +* @returns cached value +*/ +var cacheInvalidColorValue = (cacheKey, format, nullable = false) => { + if (format === "specifiedValue") { + const res = ""; + setCache(cacheKey, res); + return res; + } + if (nullable) { + setCache(cacheKey, null); + return new NullObject(); + } + const res = [ + "rgb", + 0, + 0, + 0, + 0 + ]; + setCache(cacheKey, res); + return res; +}; +/** +* resolve invalid color value +* @param format - output format +* @param nullable - is nullable +* @returns resolved value +*/ +var resolveInvalidColorValue = (format, nullable = false) => { + switch (format) { + case "hsl": + case "hwb": + case VAL_MIX: return new NullObject(); + case VAL_SPEC: return ""; + default: + if (nullable) return new NullObject(); + return [ + "rgb", + 0, + 0, + 0, + 0 + ]; + } +}; +/** +* validate color components +* @param arr - color components +* @param [opt] - options +* @param [opt.alpha] - alpha channel +* @param [opt.minLength] - min length +* @param [opt.maxLength] - max length +* @param [opt.minRange] - min range +* @param [opt.maxRange] - max range +* @param [opt.validateRange] - validate range +* @returns result - validated color components +*/ +var validateColorComponents = (arr, opt = {}) => { + if (!Array.isArray(arr)) throw new TypeError(`${arr} is not an array.`); + const { alpha = false, minLength = TRIA, maxLength = QUAD, minRange = 0, maxRange = 1, validateRange = true } = opt; + if (!Number.isFinite(minLength)) throw new TypeError(`${minLength} is not a number.`); + if (!Number.isFinite(maxLength)) throw new TypeError(`${maxLength} is not a number.`); + if (!Number.isFinite(minRange)) throw new TypeError(`${minRange} is not a number.`); + if (!Number.isFinite(maxRange)) throw new TypeError(`${maxRange} is not a number.`); + const l = arr.length; + if (l < minLength || l > maxLength) throw new Error(`Unexpected array length ${l}.`); + let i = 0; + while (i < l) { + const v = arr[i]; + if (!Number.isFinite(v)) throw new TypeError(`${v} is not a number.`); + else if (i < TRIA && validateRange && (v < minRange || v > maxRange)) throw new RangeError(`${v} is not between ${minRange} and ${maxRange}.`); + else if (i === TRIA && (v < 0 || v > 1)) throw new RangeError(`${v} is not between 0 and 1.`); + i++; + } + if (alpha && l === TRIA) arr.push(1); + return arr; +}; +/** +* transform matrix +* @param mtx - 3 * 3 matrix +* @param vct - vector +* @param [skip] - skip validate +* @returns TriColorChannels - [p1, p2, p3] +*/ +var transformMatrix = (mtx, vct, skip = false) => { + if (!Array.isArray(mtx)) throw new TypeError(`${mtx} is not an array.`); + else if (mtx.length !== TRIA) throw new Error(`Unexpected array length ${mtx.length}.`); + else if (!skip) for (let i of mtx) i = validateColorComponents(i, { + maxLength: TRIA, + validateRange: false + }); + const [[r1c1, r1c2, r1c3], [r2c1, r2c2, r2c3], [r3c1, r3c2, r3c3]] = mtx; + let v1, v2, v3; + if (skip) [v1, v2, v3] = vct; + else [v1, v2, v3] = validateColorComponents(vct, { + maxLength: TRIA, + validateRange: false + }); + return [ + r1c1 * v1 + r1c2 * v2 + r1c3 * v3, + r2c1 * v1 + r2c2 * v2 + r2c3 * v3, + r3c1 * v1 + r3c2 * v2 + r3c3 * v3 + ]; +}; +/** +* normalize color components +* @param colorA - color components [v1, v2, v3, v4] +* @param colorB - color components [v1, v2, v3, v4] +* @param [skip] - skip validate +* @returns result - [colorA, colorB] +*/ +var normalizeColorComponents = (colorA, colorB, skip = false) => { + if (!Array.isArray(colorA)) throw new TypeError(`${colorA} is not an array.`); + else if (colorA.length !== QUAD) throw new Error(`Unexpected array length ${colorA.length}.`); + if (!Array.isArray(colorB)) throw new TypeError(`${colorB} is not an array.`); + else if (colorB.length !== QUAD) throw new Error(`Unexpected array length ${colorB.length}.`); + let i = 0; + while (i < QUAD) { + if (colorA[i] === "none" && colorB[i] === "none") { + colorA[i] = 0; + colorB[i] = 0; + } else if (colorA[i] === "none") colorA[i] = colorB[i]; + else if (colorB[i] === "none") colorB[i] = colorA[i]; + i++; + } + if (skip) return [colorA, colorB]; + return [validateColorComponents(colorA, { + minLength: QUAD, + validateRange: false + }), validateColorComponents(colorB, { + minLength: QUAD, + validateRange: false + })]; +}; +/** +* number to hex string +* @param value - numeric value +* @returns hex string +*/ +var numberToHexString = (value) => { + if (!Number.isFinite(value)) throw new TypeError(`${value} is not a number.`); + else { + value = Math.round(value); + if (value < 0 || value > MAX_RGB) throw new RangeError(`${value} is not between 0 and ${MAX_RGB}.`); + } + let hex = value.toString(HEX); + if (hex.length === 1) hex = `0${hex}`; + return hex; +}; +/** +* angle to deg +* @param angle +* @returns deg: 0..360 +*/ +var angleToDeg = (angle) => { + if (isString(angle)) angle = angle.trim(); + else throw new TypeError(`${angle} is not a string.`); + const GRAD = DEG / 400; + const RAD = DEG / (Math.PI * DUO); + const reg = new RegExp(`^(${NUM})(${ANGLE})?$`); + if (!reg.test(angle)) throw new SyntaxError(`Invalid property value: ${angle}`); + const [, value, unit] = angle.match(reg); + let deg; + switch (unit) { + case "grad": + deg = parseFloat(value) * GRAD; + break; + case "rad": + deg = parseFloat(value) * RAD; + break; + case "turn": + deg = parseFloat(value) * DEG; + break; + default: deg = parseFloat(value); + } + deg %= DEG; + if (deg < 0) deg += DEG; + else if (Object.is(deg, -0)) deg = 0; + return deg; +}; +/** +* parse alpha +* @param [alpha] - alpha value +* @returns alpha: 0..1 +*/ +var parseAlpha = (alpha = "") => { + if (isString(alpha)) { + alpha = alpha.trim(); + if (!alpha) alpha = "1"; + else if (alpha === "none") alpha = "0"; + else { + let a; + if (alpha.endsWith("%")) a = parseFloat(alpha) / MAX_PCT; + else a = parseFloat(alpha); + if (!Number.isFinite(a)) throw new TypeError(`${a} is not a finite number.`); + if (a < PPTH) alpha = "0"; + else if (a > 1) alpha = "1"; + else alpha = a.toFixed(TRIA); + } + } else alpha = "1"; + return parseFloat(alpha); +}; +/** +* parse hex alpha +* @param value - alpha value in hex string +* @returns alpha: 0..1 +*/ +var parseHexAlpha = (value) => { + if (isString(value)) { + if (value === "") throw new SyntaxError("Invalid property value: (empty string)"); + value = value.trim(); + } else throw new TypeError(`${value} is not a string.`); + let alpha = parseInt(value, HEX); + if (alpha <= 0) return 0; + if (alpha >= MAX_RGB) return 1; + const alphaMap = /* @__PURE__ */ new Map(); + for (let i = 1; i < MAX_PCT; i++) alphaMap.set(Math.round(i * MAX_RGB / MAX_PCT), i); + if (alphaMap.has(alpha)) alpha = alphaMap.get(alpha) / MAX_PCT; + else alpha = Math.round(alpha / MAX_RGB / PPTH) * PPTH; + return parseFloat(alpha.toFixed(TRIA)); +}; +/** +* transform rgb to linear rgb +* @param rgb - [r, g, b] r|g|b: 0..255 +* @param [skip] - skip validate +* @returns TriColorChannels - [r, g, b] r|g|b: 0..1 +*/ +var transformRgbToLinearRgb = (rgb, skip = false) => { + let rr, gg, bb; + if (skip) [rr, gg, bb] = rgb; + else [rr, gg, bb] = validateColorComponents(rgb, { + maxLength: TRIA, + maxRange: MAX_RGB + }); + let r = rr / MAX_RGB; + let g = gg / MAX_RGB; + let b = bb / MAX_RGB; + const COND_POW = .04045; + if (r > COND_POW) r = Math.pow((r + LINEAR_OFFSET) / (1 + LINEAR_OFFSET), POW_LINEAR); + else r /= LINEAR_COEF; + if (g > COND_POW) g = Math.pow((g + LINEAR_OFFSET) / (1 + LINEAR_OFFSET), POW_LINEAR); + else g /= LINEAR_COEF; + if (b > COND_POW) b = Math.pow((b + LINEAR_OFFSET) / (1 + LINEAR_OFFSET), POW_LINEAR); + else b /= LINEAR_COEF; + return [ + r, + g, + b + ]; +}; +/** +* transform rgb to xyz +* @param rgb - [r, g, b] r|g|b: 0..255 +* @param [skip] - skip validate +* @returns TriColorChannels - [x, y, z] +*/ +var transformRgbToXyz = (rgb, skip = false) => { + if (!skip) rgb = validateColorComponents(rgb, { + maxLength: TRIA, + maxRange: MAX_RGB + }); + rgb = transformRgbToLinearRgb(rgb, true); + return transformMatrix(MATRIX_L_RGB_TO_XYZ, rgb, true); +}; +/** +* transform linear rgb to rgb +* @param rgb - [r, g, b] r|g|b: 0..1 +* @param [round] - round result +* @returns TriColorChannels - [r, g, b] r|g|b: 0..255 +*/ +var transformLinearRgbToRgb = (rgb, round = false) => { + let [r, g, b] = validateColorComponents(rgb, { maxLength: TRIA }); + const COND_POW = 809 / 258400; + if (r > COND_POW) r = Math.pow(r, 1 / POW_LINEAR) * (1 + LINEAR_OFFSET) - LINEAR_OFFSET; + else r *= LINEAR_COEF; + r *= MAX_RGB; + if (g > COND_POW) g = Math.pow(g, 1 / POW_LINEAR) * (1 + LINEAR_OFFSET) - LINEAR_OFFSET; + else g *= LINEAR_COEF; + g *= MAX_RGB; + if (b > COND_POW) b = Math.pow(b, 1 / POW_LINEAR) * (1 + LINEAR_OFFSET) - LINEAR_OFFSET; + else b *= LINEAR_COEF; + b *= MAX_RGB; + return [ + round ? Math.round(r) : r, + round ? Math.round(g) : g, + round ? Math.round(b) : b + ]; +}; +/** +* transform xyz to rgb +* @param xyz - [x, y, z] +* @param [skip] - skip validate +* @returns TriColorChannels - [r, g, b] r|g|b: 0..255 +*/ +var transformXyzToRgb = (xyz, skip = false) => { + if (!skip) xyz = validateColorComponents(xyz, { + maxLength: TRIA, + validateRange: false + }); + let [r, g, b] = transformMatrix(MATRIX_XYZ_TO_L_RGB, xyz, true); + [r, g, b] = transformLinearRgbToRgb([ + Math.min(Math.max(r, 0), 1), + Math.min(Math.max(g, 0), 1), + Math.min(Math.max(b, 0), 1) + ], true); + return [ + r, + g, + b + ]; +}; +/** +* transform xyz to hsl +* @param xyz - [x, y, z] +* @param [skip] - skip validate +* @returns TriColorChannels - [h, s, l] +*/ +var transformXyzToHsl = (xyz, skip = false) => { + const [rr, gg, bb] = transformXyzToRgb(xyz, skip); + const r = rr / MAX_RGB; + const g = gg / MAX_RGB; + const b = bb / MAX_RGB; + const max = Math.max(r, g, b); + const min = Math.min(r, g, b); + const d = max - min; + const l = (max + min) * HALF * MAX_PCT; + let h, s; + if (Math.round(l) === 0 || Math.round(l) === MAX_PCT) { + h = 0; + s = 0; + } else { + s = d / (1 - Math.abs(max + min - 1)) * MAX_PCT; + if (s === 0) h = 0; + else { + switch (max) { + case r: + h = (g - b) / d; + break; + case g: + h = (b - r) / d + DUO; + break; + case b: + default: + h = (r - g) / d + QUAD; + break; + } + h = h * SEXA % DEG; + if (h < 0) h += DEG; + } + } + return [ + h, + s, + l + ]; +}; +/** +* transform xyz to hwb +* @param xyz - [x, y, z] +* @param [skip] - skip validate +* @returns TriColorChannels - [h, w, b] +*/ +var transformXyzToHwb = (xyz, skip = false) => { + const [r, g, b] = transformXyzToRgb(xyz, skip); + const wh = Math.min(r, g, b) / MAX_RGB; + const bk = 1 - Math.max(r, g, b) / MAX_RGB; + let h; + if (wh + bk === 1) h = 0; + else [h] = transformXyzToHsl(xyz); + return [ + h, + wh * MAX_PCT, + bk * MAX_PCT + ]; +}; +/** +* transform xyz to oklab +* @param xyz - [x, y, z] +* @param [skip] - skip validate +* @returns TriColorChannels - [l, a, b] +*/ +var transformXyzToOklab = (xyz, skip = false) => { + if (!skip) xyz = validateColorComponents(xyz, { + maxLength: TRIA, + validateRange: false + }); + let [l, a, b] = transformMatrix(MATRIX_LMS_TO_OKLAB, transformMatrix(MATRIX_XYZ_TO_LMS, xyz, true).map((c) => Math.cbrt(c)), true); + l = Math.min(Math.max(l, 0), 1); + const lPct = Math.round(parseFloat(l.toFixed(QUAD)) * MAX_PCT); + if (lPct === 0 || lPct === MAX_PCT) { + a = 0; + b = 0; + } + return [ + l, + a, + b + ]; +}; +/** +* transform xyz to oklch +* @param xyz - [x, y, z] +* @param [skip] - skip validate +* @returns TriColorChannels - [l, c, h] +*/ +var transformXyzToOklch = (xyz, skip = false) => { + const [l, a, b] = transformXyzToOklab(xyz, skip); + let c, h; + const lPct = Math.round(parseFloat(l.toFixed(QUAD)) * MAX_PCT); + if (lPct === 0 || lPct === MAX_PCT) { + c = 0; + h = 0; + } else { + c = Math.max(Math.sqrt(Math.pow(a, POW_SQR) + Math.pow(b, POW_SQR)), 0); + if (parseFloat(c.toFixed(QUAD)) === 0) h = 0; + else { + h = Math.atan2(b, a) * DEG_HALF / Math.PI; + if (h < 0) h += DEG; + } + } + return [ + l, + c, + h + ]; +}; +/** +* transform xyz D50 to rgb +* @param xyz - [x, y, z] +* @param [skip] - skip validate +* @returns TriColorChannels - [r, g, b] r|g|b: 0..255 +*/ +var transformXyzD50ToRgb = (xyz, skip = false) => { + if (!skip) xyz = validateColorComponents(xyz, { + maxLength: TRIA, + validateRange: false + }); + return transformXyzToRgb(transformMatrix(MATRIX_D50_TO_D65, xyz, true), true); +}; +/** +* transform xyz-d50 to lab +* @param xyz - [x, y, z] +* @param [skip] - skip validate +* @returns TriColorChannels - [l, a, b] +*/ +var transformXyzD50ToLab = (xyz, skip = false) => { + if (!skip) xyz = validateColorComponents(xyz, { + maxLength: TRIA, + validateRange: false + }); + const [f0, f1, f2] = xyz.map((val, i) => val / D50[i]).map((val) => val > LAB_EPSILON ? Math.cbrt(val) : (val * LAB_KAPPA + HEX) / LAB_L); + const l = Math.min(Math.max(LAB_L * f1 - HEX, 0), MAX_PCT); + let a, b; + if (l === 0 || l === MAX_PCT) { + a = 0; + b = 0; + } else { + a = (f0 - f1) * LAB_A; + b = (f1 - f2) * LAB_B; + } + return [ + l, + a, + b + ]; +}; +/** +* transform xyz-d50 to lch +* @param xyz - [x, y, z] +* @param [skip] - skip validate +* @returns TriColorChannels - [l, c, h] +*/ +var transformXyzD50ToLch = (xyz, skip = false) => { + const [l, a, b] = transformXyzD50ToLab(xyz, skip); + let c, h; + if (l === 0 || l === MAX_PCT) { + c = 0; + h = 0; + } else { + c = Math.max(Math.sqrt(Math.pow(a, POW_SQR) + Math.pow(b, POW_SQR)), 0); + h = Math.atan2(b, a) * DEG_HALF / Math.PI; + if (h < 0) h += DEG; + } + return [ + l, + c, + h + ]; +}; +/** +* convert rgb to hex color +* @param rgb - [r, g, b, alpha] r|g|b: 0..255 alpha: 0..1 +* @returns hex color +*/ +var convertRgbToHex = (rgb) => { + const [r, g, b, alpha] = validateColorComponents(rgb, { + alpha: true, + maxRange: MAX_RGB + }); + const rr = numberToHexString(r); + const gg = numberToHexString(g); + const bb = numberToHexString(b); + const aa = numberToHexString(alpha * MAX_RGB); + let hex; + if (aa === "ff") hex = `#${rr}${gg}${bb}`; + else hex = `#${rr}${gg}${bb}${aa}`; + return hex; +}; +/** +* convert hex color to rgb +* @param value - hex color value +* @returns ColorChannels - [r, g, b, alpha] r|g|b: 0..255 alpha: 0..1 +*/ +var convertHexToRgb = (value) => { + if (isString(value)) value = value.toLowerCase().trim(); + else throw new TypeError(`${value} is not a string.`); + if (!(/^#[\da-f]{6}$/.test(value) || /^#[\da-f]{3}$/.test(value) || /^#[\da-f]{8}$/.test(value) || /^#[\da-f]{4}$/.test(value))) throw new SyntaxError(`Invalid property value: ${value}`); + const arr = []; + if (/^#[\da-f]{3}$/.test(value)) { + const [, r, g, b] = value.match(/^#([\da-f])([\da-f])([\da-f])$/); + arr.push(parseInt(`${r}${r}`, HEX), parseInt(`${g}${g}`, HEX), parseInt(`${b}${b}`, HEX), 1); + } else if (/^#[\da-f]{4}$/.test(value)) { + const [, r, g, b, alpha] = value.match(/^#([\da-f])([\da-f])([\da-f])([\da-f])$/); + arr.push(parseInt(`${r}${r}`, HEX), parseInt(`${g}${g}`, HEX), parseInt(`${b}${b}`, HEX), parseHexAlpha(`${alpha}${alpha}`)); + } else if (/^#[\da-f]{8}$/.test(value)) { + const [, r, g, b, alpha] = value.match(/^#([\da-f]{2})([\da-f]{2})([\da-f]{2})([\da-f]{2})$/); + arr.push(parseInt(r, HEX), parseInt(g, HEX), parseInt(b, HEX), parseHexAlpha(alpha)); + } else { + const [, r, g, b] = value.match(/^#([\da-f]{2})([\da-f]{2})([\da-f]{2})$/); + arr.push(parseInt(r, HEX), parseInt(g, HEX), parseInt(b, HEX), 1); + } + return arr; +}; +/** +* convert hex color to linear rgb +* @param value - hex color value +* @returns ColorChannels - [r, g, b, alpha] r|g|b|alpha: 0..1 +*/ +var convertHexToLinearRgb = (value) => { + const [rr, gg, bb, alpha] = convertHexToRgb(value); + const [r, g, b] = transformRgbToLinearRgb([ + rr, + gg, + bb + ], true); + return [ + r, + g, + b, + alpha + ]; +}; +/** +* convert hex color to xyz +* @param value - hex color value +* @returns ColorChannels - [x, y, z, alpha] +*/ +var convertHexToXyz = (value) => { + const [r, g, b, alpha] = convertHexToLinearRgb(value); + const [x, y, z] = transformMatrix(MATRIX_L_RGB_TO_XYZ, [ + r, + g, + b + ], true); + return [ + x, + y, + z, + alpha + ]; +}; +/** +* parse rgb() +* @param value - rgb color value +* @param [opt] - options +* @returns parsed color - ['rgb', r, g, b, alpha], '(empty)', NullObject +*/ +var parseRgb = (value, opt = {}) => { + if (isString(value)) value = value.toLowerCase().trim(); + else throw new TypeError(`${value} is not a string.`); + const { format = "", nullable = false } = opt; + const reg = new RegExp(`^rgba?\\(\\s*(${SYN_MOD}|${SYN_RGB_LV3})\\s*\\)$`); + if (!reg.test(value)) { + const res = resolveInvalidColorValue(format, nullable); + if (res instanceof NullObject) return res; + if (isString(res)) return res; + return res; + } + const [, val] = value.match(reg); + const [v1, v2, v3, v4 = ""] = val.replace(/[,/]/g, " ").split(/\s+/); + let r, g, b; + if (v1 === "none") r = 0; + else { + if (v1.endsWith("%")) r = parseFloat(v1) * MAX_RGB / MAX_PCT; + else r = parseFloat(v1); + r = Math.min(Math.max(roundToPrecision(r, OCT), 0), MAX_RGB); + } + if (v2 === "none") g = 0; + else { + if (v2.endsWith("%")) g = parseFloat(v2) * MAX_RGB / MAX_PCT; + else g = parseFloat(v2); + g = Math.min(Math.max(roundToPrecision(g, OCT), 0), MAX_RGB); + } + if (v3 === "none") b = 0; + else { + if (v3.endsWith("%")) b = parseFloat(v3) * MAX_RGB / MAX_PCT; + else b = parseFloat(v3); + b = Math.min(Math.max(roundToPrecision(b, OCT), 0), MAX_RGB); + } + const alpha = parseAlpha(v4); + return [ + "rgb", + r, + g, + b, + format === "mixValue" && v4 === "none" ? NONE : alpha + ]; +}; +/** +* parse hsl() +* @param value - hsl color value +* @param [opt] - options +* @returns parsed color - ['rgb', r, g, b, alpha], '(empty)', NullObject +*/ +var parseHsl = (value, opt = {}) => { + if (isString(value)) value = value.trim(); + else throw new TypeError(`${value} is not a string.`); + const { format = "", nullable = false } = opt; + if (!REG_HSL.test(value)) { + const res = resolveInvalidColorValue(format, nullable); + if (res instanceof NullObject) return res; + if (isString(res)) return res; + return res; + } + const [, val] = value.match(REG_HSL); + const [v1, v2, v3, v4 = ""] = val.replace(/[,/]/g, " ").split(/\s+/); + let h, s, l; + if (v1 === "none") h = 0; + else h = angleToDeg(v1); + if (v2 === "none") s = 0; + else s = Math.min(Math.max(parseFloat(v2), 0), MAX_PCT); + if (v3 === "none") l = 0; + else l = Math.min(Math.max(parseFloat(v3), 0), MAX_PCT); + const alpha = parseAlpha(v4); + if (format === "hsl") return [ + format, + v1 === "none" ? v1 : h, + v2 === "none" ? v2 : s, + v3 === "none" ? v3 : l, + v4 === "none" ? v4 : alpha + ]; + h = h / DEG * DOZ; + l /= MAX_PCT; + const sa = s / MAX_PCT * Math.min(l, 1 - l); + const rk = h % DOZ; + const gk = (8 + h) % DOZ; + const bk = (4 + h) % DOZ; + const r = l - sa * Math.max(-1, Math.min(rk - TRIA, TRIA ** POW_SQR - rk, 1)); + const g = l - sa * Math.max(-1, Math.min(gk - TRIA, TRIA ** POW_SQR - gk, 1)); + const b = l - sa * Math.max(-1, Math.min(bk - TRIA, TRIA ** POW_SQR - bk, 1)); + return [ + "rgb", + Math.min(Math.max(roundToPrecision(r * MAX_RGB, OCT), 0), MAX_RGB), + Math.min(Math.max(roundToPrecision(g * MAX_RGB, OCT), 0), MAX_RGB), + Math.min(Math.max(roundToPrecision(b * MAX_RGB, OCT), 0), MAX_RGB), + alpha + ]; +}; +/** +* parse hwb() +* @param value - hwb color value +* @param [opt] - options +* @returns parsed color - ['rgb', r, g, b, alpha], '(empty)', NullObject +*/ +var parseHwb = (value, opt = {}) => { + if (isString(value)) value = value.trim(); + else throw new TypeError(`${value} is not a string.`); + const { format = "", nullable = false } = opt; + if (!REG_HWB.test(value)) { + const res = resolveInvalidColorValue(format, nullable); + if (res instanceof NullObject) return res; + if (isString(res)) return res; + return res; + } + const [, val] = value.match(REG_HWB); + const [v1, v2, v3, v4 = ""] = val.replace("/", " ").split(/\s+/); + let h, wh, bk; + if (v1 === "none") h = 0; + else h = angleToDeg(v1); + if (v2 === "none") wh = 0; + else wh = Math.min(Math.max(parseFloat(v2), 0), MAX_PCT) / MAX_PCT; + if (v3 === "none") bk = 0; + else bk = Math.min(Math.max(parseFloat(v3), 0), MAX_PCT) / MAX_PCT; + const alpha = parseAlpha(v4); + if (format === "hwb") return [ + format, + v1 === "none" ? v1 : h, + v2 === "none" ? v2 : wh * MAX_PCT, + v3 === "none" ? v3 : bk * MAX_PCT, + v4 === "none" ? v4 : alpha + ]; + if (wh + bk >= 1) { + const v = roundToPrecision(wh / (wh + bk) * MAX_RGB, OCT); + return [ + "rgb", + v, + v, + v, + alpha + ]; + } + const factor = (1 - wh - bk) / MAX_RGB; + let [, r, g, b] = parseHsl(`hsl(${h} 100 50)`); + r = roundToPrecision((r * factor + wh) * MAX_RGB, OCT); + g = roundToPrecision((g * factor + wh) * MAX_RGB, OCT); + b = roundToPrecision((b * factor + wh) * MAX_RGB, OCT); + return [ + "rgb", + Math.min(Math.max(r, 0), MAX_RGB), + Math.min(Math.max(g, 0), MAX_RGB), + Math.min(Math.max(b, 0), MAX_RGB), + alpha + ]; +}; +/** +* parse lab() +* @param value - lab color value +* @param [opt] - options +* @returns parsed color +* - [xyz-d50, x, y, z, alpha], ['lab', l, a, b, alpha], '(empty)', NullObject +*/ +var parseLab = (value, opt = {}) => { + if (isString(value)) value = value.trim(); + else throw new TypeError(`${value} is not a string.`); + const { format = "", nullable = false } = opt; + if (!REG_LAB.test(value)) { + const res = resolveInvalidColorValue(format, nullable); + if (res instanceof NullObject) return res; + if (isString(res)) return res; + return res; + } + const COEF_PCT = 1.25; + const COND_POW = 8; + const [, val] = value.match(REG_LAB); + const [v1, v2, v3, v4 = ""] = val.replace("/", " ").split(/\s+/); + let l, a, b; + if (v1 === "none") l = 0; + else { + if (v1.endsWith("%")) { + l = parseFloat(v1); + if (l > MAX_PCT) l = MAX_PCT; + } else l = parseFloat(v1); + if (l < 0) l = 0; + } + if (v2 === "none") a = 0; + else a = v2.endsWith("%") ? parseFloat(v2) * COEF_PCT : parseFloat(v2); + if (v3 === "none") b = 0; + else b = v3.endsWith("%") ? parseFloat(v3) * COEF_PCT : parseFloat(v3); + const alpha = parseAlpha(v4); + if (REG_SPEC.test(format)) return [ + "lab", + v1 === "none" ? v1 : roundToPrecision(l, HEX), + v2 === "none" ? v2 : roundToPrecision(a, HEX), + v3 === "none" ? v3 : roundToPrecision(b, HEX), + v4 === "none" ? v4 : alpha + ]; + const fl = (l + HEX) / LAB_L; + const fa = a / LAB_A + fl; + const fb = fl - b / LAB_B; + const powFl = Math.pow(fl, POW_CUBE); + const powFa = Math.pow(fa, POW_CUBE); + const powFb = Math.pow(fb, POW_CUBE); + const [x, y, z] = [ + powFa > LAB_EPSILON ? powFa : (fa * LAB_L - HEX) / LAB_KAPPA, + l > COND_POW ? powFl : l / LAB_KAPPA, + powFb > LAB_EPSILON ? powFb : (fb * LAB_L - HEX) / LAB_KAPPA + ].map((val, i) => val * D50[i]); + return [ + "xyz-d50", + roundToPrecision(x, HEX), + roundToPrecision(y, HEX), + roundToPrecision(z, HEX), + alpha + ]; +}; +/** +* parse lch() +* @param value - lch color value +* @param [opt] - options +* @returns parsed color +* - ['xyz-d50', x, y, z, alpha], ['lch', l, c, h, alpha] +* - '(empty)', NullObject +*/ +var parseLch = (value, opt = {}) => { + if (isString(value)) value = value.trim(); + else throw new TypeError(`${value} is not a string.`); + const { format = "", nullable = false } = opt; + if (!REG_LCH.test(value)) { + const res = resolveInvalidColorValue(format, nullable); + if (res instanceof NullObject) return res; + if (isString(res)) return res; + return res; + } + const COEF_PCT = 1.5; + const [, val] = value.match(REG_LCH); + const [v1, v2, v3, v4 = ""] = val.replace("/", " ").split(/\s+/); + let l, c, h; + if (v1 === "none") l = 0; + else { + l = parseFloat(v1); + if (l < 0) l = 0; + } + if (v2 === "none") c = 0; + else c = v2.endsWith("%") ? parseFloat(v2) * COEF_PCT : parseFloat(v2); + if (v3 === "none") h = 0; + else h = angleToDeg(v3); + const alpha = parseAlpha(v4); + if (REG_SPEC.test(format)) return [ + "lch", + v1 === "none" ? v1 : roundToPrecision(l, HEX), + v2 === "none" ? v2 : roundToPrecision(c, HEX), + v3 === "none" ? v3 : roundToPrecision(h, HEX), + v4 === "none" ? v4 : alpha + ]; + const a = c * Math.cos(h * Math.PI / DEG_HALF); + const b = c * Math.sin(h * Math.PI / DEG_HALF); + const [, x, y, z] = parseLab(`lab(${l} ${a} ${b})`); + return [ + "xyz-d50", + roundToPrecision(x, HEX), + roundToPrecision(y, HEX), + roundToPrecision(z, HEX), + alpha + ]; +}; +/** +* parse oklab() +* @param value - oklab color value +* @param [opt] - options +* @returns parsed color +* - ['xyz-d65', x, y, z, alpha], ['oklab', l, a, b, alpha] +* - '(empty)', NullObject +*/ +var parseOklab = (value, opt = {}) => { + if (isString(value)) value = value.trim(); + else throw new TypeError(`${value} is not a string.`); + const { format = "", nullable = false } = opt; + if (!REG_OKLAB.test(value)) { + const res = resolveInvalidColorValue(format, nullable); + if (res instanceof NullObject) return res; + if (isString(res)) return res; + return res; + } + const COEF_PCT = .4; + const [, val] = value.match(REG_OKLAB); + const [v1, v2, v3, v4 = ""] = val.replace("/", " ").split(/\s+/); + let l, a, b; + if (v1 === "none") l = 0; + else { + l = v1.endsWith("%") ? parseFloat(v1) / MAX_PCT : parseFloat(v1); + if (l < 0) l = 0; + } + if (v2 === "none") a = 0; + else if (v2.endsWith("%")) a = parseFloat(v2) * COEF_PCT / MAX_PCT; + else a = parseFloat(v2); + if (v3 === "none") b = 0; + else if (v3.endsWith("%")) b = parseFloat(v3) * COEF_PCT / MAX_PCT; + else b = parseFloat(v3); + const alpha = parseAlpha(v4); + if (REG_SPEC.test(format)) return [ + "oklab", + v1 === "none" ? v1 : roundToPrecision(l, HEX), + v2 === "none" ? v2 : roundToPrecision(a, HEX), + v3 === "none" ? v3 : roundToPrecision(b, HEX), + v4 === "none" ? v4 : alpha + ]; + const [x, y, z] = transformMatrix(MATRIX_LMS_TO_XYZ, transformMatrix(MATRIX_OKLAB_TO_LMS, [ + l, + a, + b + ]).map((c) => Math.pow(c, POW_CUBE)), true); + return [ + "xyz-d65", + roundToPrecision(x, HEX), + roundToPrecision(y, HEX), + roundToPrecision(z, HEX), + alpha + ]; +}; +/** +* parse oklch() +* @param value - oklch color value +* @param [opt] - options +* @returns parsed color +* - ['xyz-d65', x, y, z, alpha], ['oklch', l, c, h, alpha] +* - '(empty)', NullObject +*/ +var parseOklch = (value, opt = {}) => { + if (isString(value)) value = value.trim(); + else throw new TypeError(`${value} is not a string.`); + const { format = "", nullable = false } = opt; + if (!REG_OKLCH.test(value)) { + const res = resolveInvalidColorValue(format, nullable); + if (res instanceof NullObject) return res; + if (isString(res)) return res; + return res; + } + const COEF_PCT = .4; + const [, val] = value.match(REG_OKLCH); + const [v1, v2, v3, v4 = ""] = val.replace("/", " ").split(/\s+/); + let l, c, h; + if (v1 === "none") l = 0; + else { + l = v1.endsWith("%") ? parseFloat(v1) / MAX_PCT : parseFloat(v1); + if (l < 0) l = 0; + } + if (v2 === "none") c = 0; + else { + if (v2.endsWith("%")) c = parseFloat(v2) * COEF_PCT / MAX_PCT; + else c = parseFloat(v2); + if (c < 0) c = 0; + } + if (v3 === "none") h = 0; + else h = angleToDeg(v3); + const alpha = parseAlpha(v4); + if (REG_SPEC.test(format)) return [ + "oklch", + v1 === "none" ? v1 : roundToPrecision(l, HEX), + v2 === "none" ? v2 : roundToPrecision(c, HEX), + v3 === "none" ? v3 : roundToPrecision(h, HEX), + v4 === "none" ? v4 : alpha + ]; + const a = c * Math.cos(h * Math.PI / DEG_HALF); + const b = c * Math.sin(h * Math.PI / DEG_HALF); + const [x, y, z] = transformMatrix(MATRIX_LMS_TO_XYZ, transformMatrix(MATRIX_OKLAB_TO_LMS, [ + l, + a, + b + ]).map((cc) => Math.pow(cc, POW_CUBE)), true); + return [ + "xyz-d65", + roundToPrecision(x, HEX), + roundToPrecision(y, HEX), + roundToPrecision(z, HEX), + alpha + ]; +}; +/** +* parse color() +* @param value - color function value +* @param [opt] - options +* @returns parsed color +* - ['xyz-(d50|d65)', x, y, z, alpha], [cs, r, g, b, alpha] +* - '(empty)', NullObject +*/ +var parseColorFunc = (value, opt = {}) => { + if (isString(value)) value = value.trim(); + else throw new TypeError(`${value} is not a string.`); + const { colorSpace = "", d50 = false, format = "", nullable = false } = opt; + if (!REG_FN_COLOR.test(value)) { + const res = resolveInvalidColorValue(format, nullable); + if (res instanceof NullObject) return res; + if (isString(res)) return res; + return res; + } + const [, val] = value.match(REG_FN_COLOR); + let [cs, v1, v2, v3, v4 = ""] = val.replace("/", " ").split(/\s+/); + let r, g, b; + if (cs === "xyz") cs = "xyz-d65"; + if (v1 === "none") r = 0; + else r = v1.endsWith("%") ? parseFloat(v1) / MAX_PCT : parseFloat(v1); + if (v2 === "none") g = 0; + else g = v2.endsWith("%") ? parseFloat(v2) / MAX_PCT : parseFloat(v2); + if (v3 === "none") b = 0; + else b = v3.endsWith("%") ? parseFloat(v3) / MAX_PCT : parseFloat(v3); + const alpha = parseAlpha(v4); + if (REG_SPEC.test(format) || format === "mixValue" && cs === colorSpace) return [ + cs, + v1 === "none" ? v1 : roundToPrecision(r, DEC), + v2 === "none" ? v2 : roundToPrecision(g, DEC), + v3 === "none" ? v3 : roundToPrecision(b, DEC), + v4 === "none" ? v4 : alpha + ]; + let x = 0; + let y = 0; + let z = 0; + if (cs === "srgb-linear") { + [x, y, z] = transformMatrix(MATRIX_L_RGB_TO_XYZ, [ + r, + g, + b + ]); + if (d50) [x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [ + x, + y, + z + ], true); + } else if (cs === "display-p3") { + const linearRgb = transformRgbToLinearRgb([ + r * MAX_RGB, + g * MAX_RGB, + b * MAX_RGB + ]); + [x, y, z] = transformMatrix(MATRIX_P3_TO_XYZ, linearRgb); + if (d50) [x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [ + x, + y, + z + ], true); + } else if (cs === "rec2020") { + const ALPHA = 1.09929682680944; + const BETA = .018053968510807; + const REC_COEF = .45; + const rgb = [ + r, + g, + b + ].map((c) => { + let cl; + if (c < BETA * REC_COEF * DEC) cl = c / (REC_COEF * DEC); + else cl = Math.pow((c + ALPHA - 1) / ALPHA, 1 / REC_COEF); + return cl; + }); + [x, y, z] = transformMatrix(MATRIX_REC2020_TO_XYZ, rgb); + if (d50) [x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [ + x, + y, + z + ], true); + } else if (cs === "a98-rgb") { + const POW_A98 = 563 / 256; + const rgb = [ + r, + g, + b + ].map((c) => { + return Math.pow(c, POW_A98); + }); + [x, y, z] = transformMatrix(MATRIX_A98_TO_XYZ, rgb); + if (d50) [x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [ + x, + y, + z + ], true); + } else if (cs === "prophoto-rgb") { + const POW_PROPHOTO = 1.8; + const rgb = [ + r, + g, + b + ].map((c) => { + let cl; + if (c > 1 / (HEX * DUO)) cl = Math.pow(c, POW_PROPHOTO); + else cl = c / HEX; + return cl; + }); + [x, y, z] = transformMatrix(MATRIX_PROPHOTO_TO_XYZ_D50, rgb); + if (!d50) [x, y, z] = transformMatrix(MATRIX_D50_TO_D65, [ + x, + y, + z + ], true); + } else if (/^xyz(?:-d(?:50|65))?$/.test(cs)) { + [x, y, z] = [ + r, + g, + b + ]; + if (cs === "xyz-d50") { + if (!d50) [x, y, z] = transformMatrix(MATRIX_D50_TO_D65, [ + x, + y, + z + ]); + } else if (d50) [x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [ + x, + y, + z + ], true); + } else { + [x, y, z] = transformRgbToXyz([ + r * MAX_RGB, + g * MAX_RGB, + b * MAX_RGB + ]); + if (d50) [x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [ + x, + y, + z + ], true); + } + return [ + d50 ? "xyz-d50" : "xyz-d65", + roundToPrecision(x, HEX), + roundToPrecision(y, HEX), + roundToPrecision(z, HEX), + format === "mixValue" && v4 === "none" ? v4 : alpha + ]; +}; +/** +* parse color value +* @param value - CSS color value +* @param [opt] - options +* @returns parsed color +* - ['xyz-(d50|d65)', x, y, z, alpha], ['rgb', r, g, b, alpha] +* - value, '(empty)', NullObject +*/ +var parseColorValue = (value, opt = {}) => { + if (isString(value)) value = value.toLowerCase().trim(); + else throw new TypeError(`${value} is not a string.`); + const { d50 = false, format = "", nullable = false } = opt; + if (!REG_COLOR.test(value)) { + const res = resolveInvalidColorValue(format, nullable); + if (res instanceof NullObject) return res; + if (isString(res)) return res; + return res; + } + let x = 0; + let y = 0; + let z = 0; + let alpha = 0; + if (REG_CURRENT.test(value)) { + if (format === "computedValue") return [ + "rgb", + 0, + 0, + 0, + 0 + ]; + if (format === "specifiedValue") return value; + } else if (/^[a-z]+$/.test(value)) if (Object.hasOwn(NAMED_COLORS, value)) { + if (format === "specifiedValue") return value; + const [r, g, b] = NAMED_COLORS[value]; + alpha = 1; + if (format === "computedValue") return [ + "rgb", + r, + g, + b, + alpha + ]; + [x, y, z] = transformRgbToXyz([ + r, + g, + b + ], true); + if (d50) [x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [ + x, + y, + z + ], true); + } else switch (format) { + case VAL_COMP: + if (nullable && value !== "transparent") return new NullObject(); + return [ + "rgb", + 0, + 0, + 0, + 0 + ]; + case VAL_SPEC: + if (value === "transparent") return value; + return ""; + case VAL_MIX: + if (value === "transparent") return [ + "rgb", + 0, + 0, + 0, + 0 + ]; + return new NullObject(); + default: + } + else if (value[0] === "#") { + if (REG_SPEC.test(format)) return ["rgb", ...convertHexToRgb(value)]; + [x, y, z, alpha] = convertHexToXyz(value); + if (d50) [x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [ + x, + y, + z + ], true); + } else if (value.startsWith("lab")) { + if (REG_SPEC.test(format)) return parseLab(value, opt); + [, x, y, z, alpha] = parseLab(value); + if (!d50) [x, y, z] = transformMatrix(MATRIX_D50_TO_D65, [ + x, + y, + z + ], true); + } else if (value.startsWith("lch")) { + if (REG_SPEC.test(format)) return parseLch(value, opt); + [, x, y, z, alpha] = parseLch(value); + if (!d50) [x, y, z] = transformMatrix(MATRIX_D50_TO_D65, [ + x, + y, + z + ], true); + } else if (value.startsWith("oklab")) { + if (REG_SPEC.test(format)) return parseOklab(value, opt); + [, x, y, z, alpha] = parseOklab(value); + if (d50) [x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [ + x, + y, + z + ], true); + } else if (value.startsWith("oklch")) { + if (REG_SPEC.test(format)) return parseOklch(value, opt); + [, x, y, z, alpha] = parseOklch(value); + if (d50) [x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [ + x, + y, + z + ], true); + } else { + let r, g, b; + if (value.startsWith("hsl")) [, r, g, b, alpha] = parseHsl(value); + else if (value.startsWith("hwb")) [, r, g, b, alpha] = parseHwb(value); + else [, r, g, b, alpha] = parseRgb(value, opt); + if (REG_SPEC.test(format)) return [ + "rgb", + Math.round(r), + Math.round(g), + Math.round(b), + alpha + ]; + [x, y, z] = transformRgbToXyz([ + r, + g, + b + ]); + if (d50) [x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [ + x, + y, + z + ], true); + } + return [ + d50 ? "xyz-d50" : "xyz-d65", + roundToPrecision(x, HEX), + roundToPrecision(y, HEX), + roundToPrecision(z, HEX), + alpha + ]; +}; +/** +* resolve color value +* @param value - CSS color value +* @param [opt] - options +* @returns resolved color +* - [cs, v1, v2, v3, alpha], value, '(empty)', NullObject +*/ +var resolveColorValue = (value, opt = {}) => { + if (isString(value)) value = value.toLowerCase().trim(); + else throw new TypeError(`${value} is not a string.`); + const { colorSpace = "", format = "", nullable = false } = opt; + const cacheKey = createCacheKey({ + namespace: NAMESPACE, + name: "resolveColorValue", + value + }, opt); + const cachedResult = getCache(cacheKey); + if (cachedResult instanceof CacheItem) { + if (cachedResult.isNull) return cachedResult; + const cachedItem = cachedResult.item; + if (isString(cachedItem)) return cachedItem; + return cachedItem; + } + if (!REG_COLOR.test(value)) { + const res = resolveInvalidColorValue(format, nullable); + if (res instanceof NullObject) { + setCache(cacheKey, null); + return res; + } + setCache(cacheKey, res); + if (isString(res)) return res; + return res; + } + let cs = ""; + let r = 0; + let g = 0; + let b = 0; + let alpha = 0; + if (REG_CURRENT.test(value)) { + if (format === "specifiedValue") { + setCache(cacheKey, value); + return value; + } + } else if (/^[a-z]+$/.test(value)) if (Object.hasOwn(NAMED_COLORS, value)) { + if (format === "specifiedValue") { + setCache(cacheKey, value); + return value; + } + [r, g, b] = NAMED_COLORS[value]; + alpha = 1; + } else switch (format) { + case VAL_SPEC: { + if (value === "transparent") { + setCache(cacheKey, value); + return value; + } + const res = ""; + setCache(cacheKey, res); + return res; + } + case VAL_MIX: + if (value === "transparent") { + const res = [ + "rgb", + 0, + 0, + 0, + 0 + ]; + setCache(cacheKey, res); + return res; + } + setCache(cacheKey, null); + return new NullObject(); + case VAL_COMP: + default: { + if (nullable && value !== "transparent") { + setCache(cacheKey, null); + return new NullObject(); + } + const res = [ + "rgb", + 0, + 0, + 0, + 0 + ]; + setCache(cacheKey, res); + return res; + } + } + else if (value[0] === "#") [r, g, b, alpha] = convertHexToRgb(value); + else if (value.startsWith("hsl")) [, r, g, b, alpha] = parseHsl(value, opt); + else if (value.startsWith("hwb")) [, r, g, b, alpha] = parseHwb(value, opt); + else if (/^l(?:ab|ch)/.test(value)) { + let x, y, z; + if (value.startsWith("lab")) [cs, x, y, z, alpha] = parseLab(value, opt); + else [cs, x, y, z, alpha] = parseLch(value, opt); + if (REG_SPEC.test(format)) { + const res = [ + cs, + x, + y, + z, + alpha + ]; + setCache(cacheKey, res); + return res; + } + [r, g, b] = transformXyzD50ToRgb([ + x, + y, + z + ]); + } else if (/^okl(?:ab|ch)/.test(value)) { + let x, y, z; + if (value.startsWith("oklab")) [cs, x, y, z, alpha] = parseOklab(value, opt); + else [cs, x, y, z, alpha] = parseOklch(value, opt); + if (REG_SPEC.test(format)) { + const res = [ + cs, + x, + y, + z, + alpha + ]; + setCache(cacheKey, res); + return res; + } + [r, g, b] = transformXyzToRgb([ + x, + y, + z + ]); + } else [, r, g, b, alpha] = parseRgb(value, opt); + if (format === "mixValue" && colorSpace === "srgb") { + const res = [ + "srgb", + r / MAX_RGB, + g / MAX_RGB, + b / MAX_RGB, + alpha + ]; + setCache(cacheKey, res); + return res; + } + const res = [ + "rgb", + Math.round(r), + Math.round(g), + Math.round(b), + alpha + ]; + setCache(cacheKey, res); + return res; +}; +/** +* resolve color() +* @param value - color function value +* @param [opt] - options +* @returns resolved color - [cs, v1, v2, v3, alpha], '(empty)', NullObject +*/ +var resolveColorFunc = (value, opt = {}) => { + if (isString(value)) value = value.toLowerCase().trim(); + else throw new TypeError(`${value} is not a string.`); + const { colorSpace = "", format = "", nullable = false } = opt; + const cacheKey = createCacheKey({ + namespace: NAMESPACE, + name: "resolveColorFunc", + value + }, opt); + const cachedResult = getCache(cacheKey); + if (cachedResult instanceof CacheItem) { + if (cachedResult.isNull) return cachedResult; + const cachedItem = cachedResult.item; + if (isString(cachedItem)) return cachedItem; + return cachedItem; + } + if (!REG_FN_COLOR.test(value)) { + const res = resolveInvalidColorValue(format, nullable); + if (res instanceof NullObject) { + setCache(cacheKey, null); + return res; + } + setCache(cacheKey, res); + if (isString(res)) return res; + return res; + } + const [cs, v1, v2, v3, v4] = parseColorFunc(value, opt); + if (REG_SPEC.test(format) || format === "mixValue" && cs === colorSpace) { + const res = [ + cs, + v1, + v2, + v3, + v4 + ]; + setCache(cacheKey, res); + return res; + } + const x = parseFloat(`${v1}`); + const y = parseFloat(`${v2}`); + const z = parseFloat(`${v3}`); + const alpha = parseAlpha(`${v4}`); + const [r, g, b] = transformXyzToRgb([ + x, + y, + z + ], true); + const res = [ + "rgb", + r, + g, + b, + alpha + ]; + setCache(cacheKey, res); + return res; +}; +/** +* convert color value to linear rgb +* @param value - CSS color value +* @param [opt] - options +* @returns ColorChannels | NullObject - [r, g, b, alpha] r|g|b|alpha: 0..1 +*/ +var convertColorToLinearRgb = (value, opt = {}) => { + if (isString(value)) value = value.trim(); + else throw new TypeError(`${value} is not a string.`); + const { colorSpace = "", format = "" } = opt; + let cs = ""; + let r, g, b, alpha, x, y, z; + if (format === "mixValue") { + let xyz; + if (value.startsWith("color(")) xyz = parseColorFunc(value, opt); + else xyz = parseColorValue(value, opt); + if (xyz instanceof NullObject) return xyz; + [cs, x, y, z, alpha] = xyz; + if (cs === colorSpace) return [ + x, + y, + z, + alpha + ]; + [r, g, b] = transformMatrix(MATRIX_XYZ_TO_L_RGB, [ + x, + y, + z + ], true); + } else if (value.startsWith("color(")) { + const [, val] = value.match(REG_FN_COLOR); + const [cs] = val.replace("/", " ").split(/\s+/); + if (cs === "srgb-linear") [, r, g, b, alpha] = resolveColorFunc(value, { format: VAL_COMP }); + else { + [, x, y, z, alpha] = parseColorFunc(value); + [r, g, b] = transformMatrix(MATRIX_XYZ_TO_L_RGB, [ + x, + y, + z + ], true); + } + } else { + [, x, y, z, alpha] = parseColorValue(value); + [r, g, b] = transformMatrix(MATRIX_XYZ_TO_L_RGB, [ + x, + y, + z + ], true); + } + return [ + Math.min(Math.max(r, 0), 1), + Math.min(Math.max(g, 0), 1), + Math.min(Math.max(b, 0), 1), + alpha + ]; +}; +/** +* convert color value to rgb +* @param value - CSS color value +* @param [opt] - options +* @returns ColorChannels | NullObject +* - [r, g, b, alpha] r|g|b: 0..255 alpha: 0..1 +*/ +var convertColorToRgb = (value, opt = {}) => { + if (isString(value)) value = value.trim(); + else throw new TypeError(`${value} is not a string.`); + const { format = "" } = opt; + let r, g, b, alpha; + if (format === "mixValue") { + let rgb; + if (value.startsWith("color(")) rgb = resolveColorFunc(value, opt); + else rgb = resolveColorValue(value, opt); + if (rgb instanceof NullObject) return rgb; + [, r, g, b, alpha] = rgb; + } else if (value.startsWith("color(")) { + const [, val] = value.match(REG_FN_COLOR); + const [cs] = val.replace("/", " ").split(/\s+/); + if (cs === "srgb") { + [, r, g, b, alpha] = resolveColorFunc(value, { format: VAL_COMP }); + r *= MAX_RGB; + g *= MAX_RGB; + b *= MAX_RGB; + } else [, r, g, b, alpha] = resolveColorFunc(value); + } else if (/^(?:ok)?l(?:ab|ch)/.test(value)) { + [r, g, b, alpha] = convertColorToLinearRgb(value); + [r, g, b] = transformLinearRgbToRgb([ + r, + g, + b + ]); + } else [, r, g, b, alpha] = resolveColorValue(value, { format: VAL_COMP }); + return [ + r, + g, + b, + alpha + ]; +}; +/** +* convert color value to xyz +* @param value - CSS color value +* @param [opt] - options +* @returns ColorChannels | NullObject - [x, y, z, alpha] +*/ +var convertColorToXyz = (value, opt = {}) => { + if (isString(value)) value = value.trim(); + else throw new TypeError(`${value} is not a string.`); + const { d50 = false, format = "" } = opt; + let x, y, z, alpha; + if (format === "mixValue") { + let xyz; + if (value.startsWith("color(")) xyz = parseColorFunc(value, opt); + else xyz = parseColorValue(value, opt); + if (xyz instanceof NullObject) return xyz; + [, x, y, z, alpha] = xyz; + } else if (value.startsWith("color(")) { + const [, val] = value.match(REG_FN_COLOR); + const [cs] = val.replace("/", " ").split(/\s+/); + if (d50) if (cs === "xyz-d50") [, x, y, z, alpha] = resolveColorFunc(value, { format: VAL_COMP }); + else [, x, y, z, alpha] = parseColorFunc(value, opt); + else if (/^xyz(?:-d65)?$/.test(cs)) [, x, y, z, alpha] = resolveColorFunc(value, { format: VAL_COMP }); + else [, x, y, z, alpha] = parseColorFunc(value); + } else [, x, y, z, alpha] = parseColorValue(value, opt); + return [ + x, + y, + z, + alpha + ]; +}; +/** +* convert color value to hsl +* @param value - CSS color value +* @param [opt] - options +* @returns ColorChannels | NullObject - [h, s, l, alpha], hue may be powerless +*/ +var convertColorToHsl = (value, opt = {}) => { + if (isString(value)) value = value.trim(); + else throw new TypeError(`${value} is not a string.`); + const { format = "" } = opt; + let h, s, l, alpha; + if (REG_HSL.test(value)) { + [, h, s, l, alpha] = parseHsl(value, { format: "hsl" }); + if (format === "hsl") return [ + Math.round(h), + Math.round(s), + Math.round(l), + alpha + ]; + return [ + h, + s, + l, + alpha + ]; + } + let x, y, z; + if (format === "mixValue") { + let xyz; + if (value.startsWith("color(")) xyz = parseColorFunc(value, opt); + else xyz = parseColorValue(value, opt); + if (xyz instanceof NullObject) return xyz; + [, x, y, z, alpha] = xyz; + } else if (value.startsWith("color(")) [, x, y, z, alpha] = parseColorFunc(value); + else [, x, y, z, alpha] = parseColorValue(value); + [h, s, l] = transformXyzToHsl([ + x, + y, + z + ], true); + if (format === "hsl") return [ + Math.round(h), + Math.round(s), + Math.round(l), + alpha + ]; + return [ + format === "mixValue" && s === 0 ? NONE : h, + s, + l, + alpha + ]; +}; +/** +* convert color value to hwb +* @param value - CSS color value +* @param [opt] - options +* @returns ColorChannels | NullObject - [h, w, b, alpha], hue may be powerless +*/ +var convertColorToHwb = (value, opt = {}) => { + if (isString(value)) value = value.trim(); + else throw new TypeError(`${value} is not a string.`); + const { format = "" } = opt; + let h, w, b, alpha; + if (REG_HWB.test(value)) { + [, h, w, b, alpha] = parseHwb(value, { format: "hwb" }); + if (format === "hwb") return [ + Math.round(h), + Math.round(w), + Math.round(b), + alpha + ]; + return [ + h, + w, + b, + alpha + ]; + } + let x, y, z; + if (format === "mixValue") { + let xyz; + if (value.startsWith("color(")) xyz = parseColorFunc(value, opt); + else xyz = parseColorValue(value, opt); + if (xyz instanceof NullObject) return xyz; + [, x, y, z, alpha] = xyz; + } else if (value.startsWith("color(")) [, x, y, z, alpha] = parseColorFunc(value); + else [, x, y, z, alpha] = parseColorValue(value); + [h, w, b] = transformXyzToHwb([ + x, + y, + z + ], true); + if (format === "hwb") return [ + Math.round(h), + Math.round(w), + Math.round(b), + alpha + ]; + return [ + format === "mixValue" && w + b >= 100 ? NONE : h, + w, + b, + alpha + ]; +}; +/** +* convert color value to lab +* @param value - CSS color value +* @param [opt] - options +* @returns ColorChannels | NullObject - [l, a, b, alpha] +*/ +var convertColorToLab = (value, opt = {}) => { + if (isString(value)) value = value.trim(); + else throw new TypeError(`${value} is not a string.`); + const { format = "" } = opt; + let l, a, b, alpha; + if (REG_LAB.test(value)) { + [, l, a, b, alpha] = parseLab(value, { format: VAL_COMP }); + return [ + l, + a, + b, + alpha + ]; + } + let x, y, z; + if (format === "mixValue") { + let xyz; + opt.d50 = true; + if (value.startsWith("color(")) xyz = parseColorFunc(value, opt); + else xyz = parseColorValue(value, opt); + if (xyz instanceof NullObject) return xyz; + [, x, y, z, alpha] = xyz; + } else if (value.startsWith("color(")) [, x, y, z, alpha] = parseColorFunc(value, { d50: true }); + else [, x, y, z, alpha] = parseColorValue(value, { d50: true }); + [l, a, b] = transformXyzD50ToLab([ + x, + y, + z + ], true); + return [ + l, + a, + b, + alpha + ]; +}; +/** +* convert color value to lch +* @param value - CSS color value +* @param [opt] - options +* @returns ColorChannels | NullObject - [l, c, h, alpha], hue may be powerless +*/ +var convertColorToLch = (value, opt = {}) => { + if (isString(value)) value = value.trim(); + else throw new TypeError(`${value} is not a string.`); + const { format = "" } = opt; + let l, c, h, alpha; + if (REG_LCH.test(value)) { + [, l, c, h, alpha] = parseLch(value, { format: VAL_COMP }); + return [ + l, + c, + h, + alpha + ]; + } + let x, y, z; + if (format === "mixValue") { + let xyz; + opt.d50 = true; + if (value.startsWith("color(")) xyz = parseColorFunc(value, opt); + else xyz = parseColorValue(value, opt); + if (xyz instanceof NullObject) return xyz; + [, x, y, z, alpha] = xyz; + } else if (value.startsWith("color(")) [, x, y, z, alpha] = parseColorFunc(value, { d50: true }); + else [, x, y, z, alpha] = parseColorValue(value, { d50: true }); + [l, c, h] = transformXyzD50ToLch([ + x, + y, + z + ], true); + return [ + l, + c, + format === "mixValue" && c === 0 ? NONE : h, + alpha + ]; +}; +/** +* convert color value to oklab +* @param value - CSS color value +* @param [opt] - options +* @returns ColorChannels | NullObject - [l, a, b, alpha] +*/ +var convertColorToOklab = (value, opt = {}) => { + if (isString(value)) value = value.trim(); + else throw new TypeError(`${value} is not a string.`); + const { format = "" } = opt; + let l, a, b, alpha; + if (REG_OKLAB.test(value)) { + [, l, a, b, alpha] = parseOklab(value, { format: VAL_COMP }); + return [ + l, + a, + b, + alpha + ]; + } + let x, y, z; + if (format === "mixValue") { + let xyz; + if (value.startsWith("color(")) xyz = parseColorFunc(value, opt); + else xyz = parseColorValue(value, opt); + if (xyz instanceof NullObject) return xyz; + [, x, y, z, alpha] = xyz; + } else if (value.startsWith("color(")) [, x, y, z, alpha] = parseColorFunc(value); + else [, x, y, z, alpha] = parseColorValue(value); + [l, a, b] = transformXyzToOklab([ + x, + y, + z + ], true); + return [ + l, + a, + b, + alpha + ]; +}; +/** +* convert color value to oklch +* @param value - CSS color value +* @param [opt] - options +* @returns ColorChannels | NullObject - [l, c, h, alpha], hue may be powerless +*/ +var convertColorToOklch = (value, opt = {}) => { + if (isString(value)) value = value.trim(); + else throw new TypeError(`${value} is not a string.`); + const { format = "" } = opt; + let l, c, h, alpha; + if (REG_OKLCH.test(value)) { + [, l, c, h, alpha] = parseOklch(value, { format: VAL_COMP }); + return [ + l, + c, + h, + alpha + ]; + } + let x, y, z; + if (format === "mixValue") { + let xyz; + if (value.startsWith("color(")) xyz = parseColorFunc(value, opt); + else xyz = parseColorValue(value, opt); + if (xyz instanceof NullObject) return xyz; + [, x, y, z, alpha] = xyz; + } else if (value.startsWith("color(")) [, x, y, z, alpha] = parseColorFunc(value); + else [, x, y, z, alpha] = parseColorValue(value); + [l, c, h] = transformXyzToOklch([ + x, + y, + z + ], true); + return [ + l, + c, + format === "mixValue" && c === 0 ? NONE : h, + alpha + ]; +}; +/** +* resolve color-mix() +* @param value - color-mix color value +* @param [opt] - options +* @returns resolved color - [cs, v1, v2, v3, alpha], '(empty)' +*/ +var resolveColorMix = (value, opt = {}) => { + if (isString(value)) value = value.toLowerCase().trim(); + else throw new TypeError(`${value} is not a string.`); + const { format = "", nullable = false } = opt; + const cacheKey = createCacheKey({ + namespace: NAMESPACE, + name: "resolveColorMix", + value + }, opt); + const cachedResult = getCache(cacheKey); + if (cachedResult instanceof CacheItem) { + if (cachedResult.isNull) return cachedResult; + const cachedItem = cachedResult.item; + if (isString(cachedItem)) return cachedItem; + return cachedItem; + } + const nestedItems = []; + let colorSpace = ""; + let hueArc = ""; + let colorA = ""; + let pctA = ""; + let colorB = ""; + let pctB = ""; + let parsed = false; + if (!REG_MIX.test(value)) if (value.startsWith("color-mix(") && REG_MIX_NEST.test(value)) { + const regColorSpace = new RegExp(`^(?:${CS_RGB}|${CS_XYZ})$`); + const items = value.match(REG_MIX_NEST); + for (const item of items) if (item) { + let val = resolveColorMix(item, { format: format === "specifiedValue" ? format : VAL_COMP }); + if (Array.isArray(val)) { + const [cs, v1, v2, v3, v4] = val; + if (v1 === 0 && v2 === 0 && v3 === 0 && v4 === 0) { + value = ""; + break; + } + if (regColorSpace.test(cs)) if (v4 === 1) val = `color(${cs} ${v1} ${v2} ${v3})`; + else val = `color(${cs} ${v1} ${v2} ${v3} / ${v4})`; + else if (v4 === 1) val = `${cs}(${v1} ${v2} ${v3})`; + else val = `${cs}(${v1} ${v2} ${v3} / ${v4})`; + } else if (!REG_MIX.test(val)) { + value = ""; + break; + } + nestedItems.push(val); + value = value.replace(item, val); + } + if (!value) return cacheInvalidColorValue(cacheKey, format, nullable); + } else if (value.startsWith("color-mix(") && value.endsWith(")") && value.includes("light-dark(")) { + const regColorSpace = new RegExp(`in\\s+(${CS_MIX})`); + const [csPart = "", partA = "", partB = ""] = splitValue(value.replace(FN_MIX, "").replace(/\)$/, ""), { delimiter: "," }); + const [colorPartA = "", pctPartA = ""] = splitValue(partA); + const [colorPartB = "", pctPartB = ""] = splitValue(partB); + const specifiedColorA = resolveColor(colorPartA, { format: VAL_SPEC }); + const specifiedColorB = resolveColor(colorPartB, { format: VAL_SPEC }); + if (regColorSpace.test(csPart) && specifiedColorA && specifiedColorB) if (format === "specifiedValue") { + const [, cs] = csPart.match(regColorSpace); + if (REG_CS_HUE.test(cs)) [, colorSpace, hueArc] = cs.match(REG_CS_HUE); + else colorSpace = cs; + colorA = specifiedColorA; + if (pctPartA) pctA = pctPartA; + colorB = specifiedColorB; + if (pctPartB) pctB = pctPartB; + value = value.replace(colorPartA, specifiedColorA).replace(colorPartB, specifiedColorB); + parsed = true; + } else { + const resolvedColorA = resolveColor(colorPartA, opt); + const resolvedColorB = resolveColor(colorPartB, opt); + if (isString(resolvedColorA) && isString(resolvedColorB)) value = value.replace(colorPartA, resolvedColorA).replace(colorPartB, resolvedColorB); + } + else return cacheInvalidColorValue(cacheKey, format, nullable); + } else return cacheInvalidColorValue(cacheKey, format, nullable); + if (nestedItems.length && format === "specifiedValue") { + const regColorSpace = new RegExp(`^color-mix\\(\\s*in\\s+(${CS_MIX})\\s*,`); + const [, cs] = value.match(regColorSpace); + if (REG_CS_HUE.test(cs)) [, colorSpace, hueArc] = cs.match(REG_CS_HUE); + else colorSpace = cs; + if (nestedItems.length === 2) { + let [itemA, itemB] = nestedItems; + itemA = itemA.replace(/(?=[()])/g, "\\"); + itemB = itemB.replace(/(?=[()])/g, "\\"); + const regA = new RegExp(`(${itemA})(?:\\s+(${PCT}))?`); + const regB = new RegExp(`(${itemB})(?:\\s+(${PCT}))?`); + [, colorA, pctA] = value.match(regA); + [, colorB, pctB] = value.match(regB); + } else { + let [item] = nestedItems; + item = item.replace(/(?=[()])/g, "\\"); + const itemPart = `${item}(?:\\s+${PCT})?`; + const itemPartCapt = `(${item})(?:\\s+(${PCT}))?`; + const regItemPart = new RegExp(`^${itemPartCapt}$`); + const regLastItem = new RegExp(`${itemPartCapt}\\s*\\)$`); + const regColorPart = new RegExp(`^(${SYN_COLOR_TYPE})(?:\\s+(${PCT}))?$`); + if (regLastItem.test(value)) { + const reg = new RegExp(`(${SYN_MIX_PART})\\s*,\\s*(${itemPart})\\s*\\)$`); + const [, colorPartA, colorPartB] = value.match(reg); + [, colorA, pctA] = colorPartA.match(regColorPart); + [, colorB, pctB] = colorPartB.match(regItemPart); + } else { + const reg = new RegExp(`(${itemPart})\\s*,\\s*(${SYN_MIX_PART})\\s*\\)$`); + const [, colorPartA, colorPartB] = value.match(reg); + [, colorA, pctA] = colorPartA.match(regItemPart); + [, colorB, pctB] = colorPartB.match(regColorPart); + } + } + } else if (!parsed) { + const [, cs, colorPartA, colorPartB] = value.match(REG_MIX_CAPT); + const reg = new RegExp(`^(${SYN_COLOR_TYPE})(?:\\s+(${PCT}))?$`); + [, colorA, pctA] = colorPartA.match(reg); + [, colorB, pctB] = colorPartB.match(reg); + if (REG_CS_HUE.test(cs)) [, colorSpace, hueArc] = cs.match(REG_CS_HUE); + else colorSpace = cs; + } + let pA, pB, m; + if (pctA && pctB) { + const p1 = parseFloat(pctA) / MAX_PCT; + const p2 = parseFloat(pctB) / MAX_PCT; + if (p1 < 0 || p1 > 1 || p2 < 0 || p2 > 1 || p1 === 0 && p2 === 0) return cacheInvalidColorValue(cacheKey, format, nullable); + const factor = p1 + p2; + pA = p1 / factor; + pB = p2 / factor; + m = factor < 1 ? factor : 1; + } else { + if (pctA) { + pA = parseFloat(pctA) / MAX_PCT; + if (pA < 0 || pA > 1) return cacheInvalidColorValue(cacheKey, format, nullable); + pB = 1 - pA; + } else if (pctB) { + pB = parseFloat(pctB) / MAX_PCT; + if (pB < 0 || pB > 1) return cacheInvalidColorValue(cacheKey, format, nullable); + pA = 1 - pB; + } else { + pA = HALF; + pB = HALF; + } + m = 1; + } + if (colorSpace === "xyz") colorSpace = "xyz-d65"; + if (format === "specifiedValue") { + let valueA = ""; + let valueB = ""; + if (colorA.startsWith("color-mix(") || colorA.startsWith("light-dark(")) valueA = colorA; + else if (colorA.startsWith("color(")) { + const [cs, v1, v2, v3, v4] = parseColorFunc(colorA, opt); + if (v4 === 1) valueA = `color(${cs} ${v1} ${v2} ${v3})`; + else valueA = `color(${cs} ${v1} ${v2} ${v3} / ${v4})`; + } else { + const val = parseColorValue(colorA, opt); + if (Array.isArray(val)) { + const [cs, v1, v2, v3, v4] = val; + if (v4 === 1) if (cs === "rgb") valueA = `${cs}(${v1}, ${v2}, ${v3})`; + else valueA = `${cs}(${v1} ${v2} ${v3})`; + else if (cs === "rgb") valueA = `${cs}a(${v1}, ${v2}, ${v3}, ${v4})`; + else valueA = `${cs}(${v1} ${v2} ${v3} / ${v4})`; + } else { + if (!isString(val) || !val) { + setCache(cacheKey, ""); + return ""; + } + valueA = val; + } + } + if (colorB.startsWith("color-mix(") || colorB.startsWith("light-dark(")) valueB = colorB; + else if (colorB.startsWith("color(")) { + const [cs, v1, v2, v3, v4] = parseColorFunc(colorB, opt); + if (v4 === 1) valueB = `color(${cs} ${v1} ${v2} ${v3})`; + else valueB = `color(${cs} ${v1} ${v2} ${v3} / ${v4})`; + } else { + const val = parseColorValue(colorB, opt); + if (Array.isArray(val)) { + const [cs, v1, v2, v3, v4] = val; + if (v4 === 1) if (cs === "rgb") valueB = `${cs}(${v1}, ${v2}, ${v3})`; + else valueB = `${cs}(${v1} ${v2} ${v3})`; + else if (cs === "rgb") valueB = `${cs}a(${v1}, ${v2}, ${v3}, ${v4})`; + else valueB = `${cs}(${v1} ${v2} ${v3} / ${v4})`; + } else { + if (!isString(val) || !val) { + setCache(cacheKey, ""); + return ""; + } + valueB = val; + } + } + if (pctA && pctB) { + valueA += ` ${parseFloat(pctA)}%`; + valueB += ` ${parseFloat(pctB)}%`; + } else if (pctA) { + const pA = parseFloat(pctA); + if (pA !== MAX_PCT * HALF) valueA += ` ${pA}%`; + } else if (pctB) { + const pA = MAX_PCT - parseFloat(pctB); + if (pA !== MAX_PCT * HALF) valueA += ` ${pA}%`; + } + if (hueArc) { + const res = `color-mix(in ${colorSpace} ${hueArc} hue, ${valueA}, ${valueB})`; + setCache(cacheKey, res); + return res; + } else { + const res = `color-mix(in ${colorSpace}, ${valueA}, ${valueB})`; + setCache(cacheKey, res); + return res; + } + } + let r = 0; + let g = 0; + let b = 0; + let alpha = 0; + if (/^srgb(?:-linear)?$/.test(colorSpace)) { + let rgbA, rgbB; + if (colorSpace === "srgb") { + if (REG_CURRENT.test(colorA)) rgbA = [ + NONE, + NONE, + NONE, + NONE + ]; + else rgbA = convertColorToRgb(colorA, { + colorSpace, + format: VAL_MIX + }); + if (REG_CURRENT.test(colorB)) rgbB = [ + NONE, + NONE, + NONE, + NONE + ]; + else rgbB = convertColorToRgb(colorB, { + colorSpace, + format: VAL_MIX + }); + } else { + if (REG_CURRENT.test(colorA)) rgbA = [ + NONE, + NONE, + NONE, + NONE + ]; + else rgbA = convertColorToLinearRgb(colorA, { + colorSpace, + format: VAL_MIX + }); + if (REG_CURRENT.test(colorB)) rgbB = [ + NONE, + NONE, + NONE, + NONE + ]; + else rgbB = convertColorToLinearRgb(colorB, { + colorSpace, + format: VAL_MIX + }); + } + if (rgbA instanceof NullObject || rgbB instanceof NullObject) return cacheInvalidColorValue(cacheKey, format, nullable); + const [rrA, ggA, bbA, aaA] = rgbA; + const [rrB, ggB, bbB, aaB] = rgbB; + const rNone = rrA === "none" && rrB === "none"; + const gNone = ggA === "none" && ggB === "none"; + const bNone = bbA === "none" && bbB === "none"; + const alphaNone = aaA === "none" && aaB === "none"; + const [[rA, gA, bA, alphaA], [rB, gB, bB, alphaB]] = normalizeColorComponents([ + rrA, + ggA, + bbA, + aaA + ], [ + rrB, + ggB, + bbB, + aaB + ], true); + const factorA = alphaA * pA; + const factorB = alphaB * pB; + alpha = factorA + factorB; + if (alpha === 0) { + r = rA * pA + rB * pB; + g = gA * pA + gB * pB; + b = bA * pA + bB * pB; + } else { + r = (rA * factorA + rB * factorB) / alpha; + g = (gA * factorA + gB * factorB) / alpha; + b = (bA * factorA + bB * factorB) / alpha; + alpha = parseFloat(alpha.toFixed(3)); + } + if (format === "computedValue") { + const res = [ + colorSpace, + rNone ? NONE : roundToPrecision(r, HEX), + gNone ? NONE : roundToPrecision(g, HEX), + bNone ? NONE : roundToPrecision(b, HEX), + alphaNone ? NONE : alpha * m + ]; + setCache(cacheKey, res); + return res; + } + r *= MAX_RGB; + g *= MAX_RGB; + b *= MAX_RGB; + } else if (REG_CS_XYZ.test(colorSpace)) { + let xyzA, xyzB; + if (REG_CURRENT.test(colorA)) xyzA = [ + NONE, + NONE, + NONE, + NONE + ]; + else xyzA = convertColorToXyz(colorA, { + colorSpace, + d50: colorSpace === "xyz-d50", + format: VAL_MIX + }); + if (REG_CURRENT.test(colorB)) xyzB = [ + NONE, + NONE, + NONE, + NONE + ]; + else xyzB = convertColorToXyz(colorB, { + colorSpace, + d50: colorSpace === "xyz-d50", + format: VAL_MIX + }); + if (xyzA instanceof NullObject || xyzB instanceof NullObject) return cacheInvalidColorValue(cacheKey, format, nullable); + const [xxA, yyA, zzA, aaA] = xyzA; + const [xxB, yyB, zzB, aaB] = xyzB; + const xNone = xxA === "none" && xxB === "none"; + const yNone = yyA === "none" && yyB === "none"; + const zNone = zzA === "none" && zzB === "none"; + const alphaNone = aaA === "none" && aaB === "none"; + const [[xA, yA, zA, alphaA], [xB, yB, zB, alphaB]] = normalizeColorComponents([ + xxA, + yyA, + zzA, + aaA + ], [ + xxB, + yyB, + zzB, + aaB + ], true); + const factorA = alphaA * pA; + const factorB = alphaB * pB; + alpha = factorA + factorB; + let x, y, z; + if (alpha === 0) { + x = xA * pA + xB * pB; + y = yA * pA + yB * pB; + z = zA * pA + zB * pB; + } else { + x = (xA * factorA + xB * factorB) / alpha; + y = (yA * factorA + yB * factorB) / alpha; + z = (zA * factorA + zB * factorB) / alpha; + alpha = parseFloat(alpha.toFixed(3)); + } + if (format === "computedValue") { + const res = [ + colorSpace, + xNone ? NONE : roundToPrecision(x, HEX), + yNone ? NONE : roundToPrecision(y, HEX), + zNone ? NONE : roundToPrecision(z, HEX), + alphaNone ? NONE : alpha * m + ]; + setCache(cacheKey, res); + return res; + } + if (colorSpace === "xyz-d50") [r, g, b] = transformXyzD50ToRgb([ + x, + y, + z + ], true); + else [r, g, b] = transformXyzToRgb([ + x, + y, + z + ], true); + } else if (/^h(?:sl|wb)$/.test(colorSpace)) { + let hslA, hslB; + if (colorSpace === "hsl") { + if (REG_CURRENT.test(colorA)) hslA = [ + NONE, + NONE, + NONE, + NONE + ]; + else hslA = convertColorToHsl(colorA, { + colorSpace, + format: VAL_MIX + }); + if (REG_CURRENT.test(colorB)) hslB = [ + NONE, + NONE, + NONE, + NONE + ]; + else hslB = convertColorToHsl(colorB, { + colorSpace, + format: VAL_MIX + }); + } else { + if (REG_CURRENT.test(colorA)) hslA = [ + NONE, + NONE, + NONE, + NONE + ]; + else hslA = convertColorToHwb(colorA, { + colorSpace, + format: VAL_MIX + }); + if (REG_CURRENT.test(colorB)) hslB = [ + NONE, + NONE, + NONE, + NONE + ]; + else hslB = convertColorToHwb(colorB, { + colorSpace, + format: VAL_MIX + }); + } + if (hslA instanceof NullObject || hslB instanceof NullObject) return cacheInvalidColorValue(cacheKey, format, nullable); + const [hhA, ssA, llA, aaA] = hslA; + const [hhB, ssB, llB, aaB] = hslB; + const alphaNone = aaA === "none" && aaB === "none"; + let [[hA, sA, lA, alphaA], [hB, sB, lB, alphaB]] = normalizeColorComponents([ + hhA, + ssA, + llA, + aaA + ], [ + hhB, + ssB, + llB, + aaB + ], true); + if (hueArc) [hA, hB] = interpolateHue(hA, hB, hueArc); + const factorA = alphaA * pA; + const factorB = alphaB * pB; + alpha = factorA + factorB; + const h = (hA * pA + hB * pB) % DEG; + let s, l; + if (alpha === 0) { + s = sA * pA + sB * pB; + l = lA * pA + lB * pB; + } else { + s = (sA * factorA + sB * factorB) / alpha; + l = (lA * factorA + lB * factorB) / alpha; + alpha = parseFloat(alpha.toFixed(3)); + } + [r, g, b] = convertColorToRgb(`${colorSpace}(${h} ${s} ${l})`); + if (format === "computedValue") { + const res = [ + "srgb", + roundToPrecision(r / MAX_RGB, HEX), + roundToPrecision(g / MAX_RGB, HEX), + roundToPrecision(b / MAX_RGB, HEX), + alphaNone ? NONE : alpha * m + ]; + setCache(cacheKey, res); + return res; + } + } else if (/^(?:ok)?lch$/.test(colorSpace)) { + let lchA, lchB; + if (colorSpace === "lch") { + if (REG_CURRENT.test(colorA)) lchA = [ + NONE, + NONE, + NONE, + NONE + ]; + else lchA = convertColorToLch(colorA, { + colorSpace, + format: VAL_MIX + }); + if (REG_CURRENT.test(colorB)) lchB = [ + NONE, + NONE, + NONE, + NONE + ]; + else lchB = convertColorToLch(colorB, { + colorSpace, + format: VAL_MIX + }); + } else { + if (REG_CURRENT.test(colorA)) lchA = [ + NONE, + NONE, + NONE, + NONE + ]; + else lchA = convertColorToOklch(colorA, { + colorSpace, + format: VAL_MIX + }); + if (REG_CURRENT.test(colorB)) lchB = [ + NONE, + NONE, + NONE, + NONE + ]; + else lchB = convertColorToOklch(colorB, { + colorSpace, + format: VAL_MIX + }); + } + if (lchA instanceof NullObject || lchB instanceof NullObject) return cacheInvalidColorValue(cacheKey, format, nullable); + const [llA, ccA, hhA, aaA] = lchA; + const [llB, ccB, hhB, aaB] = lchB; + const lNone = llA === "none" && llB === "none"; + const cNone = ccA === "none" && ccB === "none"; + const hNone = hhA === "none" && hhB === "none"; + const alphaNone = aaA === "none" && aaB === "none"; + let [[lA, cA, hA, alphaA], [lB, cB, hB, alphaB]] = normalizeColorComponents([ + llA, + ccA, + hhA, + aaA + ], [ + llB, + ccB, + hhB, + aaB + ], true); + if (hueArc) [hA, hB] = interpolateHue(hA, hB, hueArc); + const factorA = alphaA * pA; + const factorB = alphaB * pB; + alpha = factorA + factorB; + const h = (hA * pA + hB * pB) % DEG; + let l, c; + if (alpha === 0) { + l = lA * pA + lB * pB; + c = cA * pA + cB * pB; + } else { + l = (lA * factorA + lB * factorB) / alpha; + c = (cA * factorA + cB * factorB) / alpha; + alpha = parseFloat(alpha.toFixed(3)); + } + if (format === "computedValue") { + const res = [ + colorSpace, + lNone ? NONE : roundToPrecision(l, HEX), + cNone ? NONE : roundToPrecision(c, HEX), + hNone ? NONE : roundToPrecision(h, HEX), + alphaNone ? NONE : alpha * m + ]; + setCache(cacheKey, res); + return res; + } + [, r, g, b] = resolveColorValue(`${colorSpace}(${l} ${c} ${h})`); + } else { + let labA, labB; + if (colorSpace === "lab") { + if (REG_CURRENT.test(colorA)) labA = [ + NONE, + NONE, + NONE, + NONE + ]; + else labA = convertColorToLab(colorA, { + colorSpace, + format: VAL_MIX + }); + if (REG_CURRENT.test(colorB)) labB = [ + NONE, + NONE, + NONE, + NONE + ]; + else labB = convertColorToLab(colorB, { + colorSpace, + format: VAL_MIX + }); + } else { + if (REG_CURRENT.test(colorA)) labA = [ + NONE, + NONE, + NONE, + NONE + ]; + else labA = convertColorToOklab(colorA, { + colorSpace, + format: VAL_MIX + }); + if (REG_CURRENT.test(colorB)) labB = [ + NONE, + NONE, + NONE, + NONE + ]; + else labB = convertColorToOklab(colorB, { + colorSpace, + format: VAL_MIX + }); + } + if (labA instanceof NullObject || labB instanceof NullObject) return cacheInvalidColorValue(cacheKey, format, nullable); + const [llA, aaA, bbA, alA] = labA; + const [llB, aaB, bbB, alB] = labB; + const lNone = llA === "none" && llB === "none"; + const aNone = aaA === "none" && aaB === "none"; + const bNone = bbA === "none" && bbB === "none"; + const alphaNone = alA === "none" && alB === "none"; + const [[lA, aA, bA, alphaA], [lB, aB, bB, alphaB]] = normalizeColorComponents([ + llA, + aaA, + bbA, + alA + ], [ + llB, + aaB, + bbB, + alB + ], true); + const factorA = alphaA * pA; + const factorB = alphaB * pB; + alpha = factorA + factorB; + let l, aO, bO; + if (alpha === 0) { + l = lA * pA + lB * pB; + aO = aA * pA + aB * pB; + bO = bA * pA + bB * pB; + } else { + l = (lA * factorA + lB * factorB) / alpha; + aO = (aA * factorA + aB * factorB) / alpha; + bO = (bA * factorA + bB * factorB) / alpha; + alpha = parseFloat(alpha.toFixed(3)); + } + if (format === "computedValue") { + const res = [ + colorSpace, + lNone ? NONE : roundToPrecision(l, HEX), + aNone ? NONE : roundToPrecision(aO, HEX), + bNone ? NONE : roundToPrecision(bO, HEX), + alphaNone ? NONE : alpha * m + ]; + setCache(cacheKey, res); + return res; + } + [, r, g, b] = resolveColorValue(`${colorSpace}(${l} ${aO} ${bO})`); + } + const res = [ + "rgb", + Math.round(r), + Math.round(g), + Math.round(b), + parseFloat((alpha * m).toFixed(3)) + ]; + setCache(cacheKey, res); + return res; +}; +//#endregion +export { NAMED_COLORS, convertColorToHsl, convertColorToHwb, convertColorToLab, convertColorToLch, convertColorToOklab, convertColorToOklch, convertColorToRgb, convertRgbToHex, numberToHexString, parseColorFunc, parseColorValue, resolveColorFunc, resolveColorMix, resolveColorValue }; + +//# sourceMappingURL=color.js.map \ No newline at end of file diff --git a/node_modules/@asamuzakjp/css-color/dist/esm/js/color.js.map b/node_modules/@asamuzakjp/css-color/dist/esm/js/color.js.map new file mode 100644 index 00000000..951dbd49 --- /dev/null +++ b/node_modules/@asamuzakjp/css-color/dist/esm/js/color.js.map @@ -0,0 +1 @@ +{"version":3,"file":"color.js","names":[],"sources":["../../../src/js/color.ts"],"sourcesContent":["/**\n * color\n *\n * Ref: CSS Color Module Level 4\n * Sample code for Color Conversions\n * https://w3c.github.io/csswg-drafts/css-color-4/#color-conversion-code\n */\n\nimport {\n CacheItem,\n NullObject,\n createCacheKey,\n getCache,\n setCache\n} from './cache';\nimport { isString } from './common';\nimport { resolveColor } from './resolve';\nimport { interpolateHue, roundToPrecision, splitValue } from './util';\nimport {\n ColorChannels,\n ComputedColorChannels,\n Options,\n MatchedRegExp,\n SpecifiedColorChannels,\n StringColorChannels,\n StringColorSpacedChannels\n} from './typedef';\n\n/* constants */\nimport {\n ANGLE,\n CS_HUE_CAPT,\n CS_MIX,\n CS_RGB,\n CS_XYZ,\n FN_COLOR,\n FN_LIGHT_DARK,\n FN_MIX,\n NONE,\n NUM,\n PCT,\n SYN_COLOR_TYPE,\n SYN_FN_COLOR,\n SYN_HSL,\n SYN_HSL_LV3,\n SYN_LCH,\n SYN_MIX,\n SYN_MIX_CAPT,\n SYN_MIX_PART,\n SYN_MOD,\n SYN_RGB_LV3,\n VAL_COMP,\n VAL_MIX,\n VAL_SPEC\n} from './constant';\nconst NAMESPACE = 'color';\n\n/* numeric constants */\nconst PPTH = 0.001;\nconst HALF = 0.5;\nconst DUO = 2;\nconst TRIA = 3;\nconst QUAD = 4;\nconst OCT = 8;\nconst DEC = 10;\nconst DOZ = 12;\nconst HEX = 16;\nconst SEXA = 60;\nconst DEG_HALF = 180;\nconst DEG = 360;\nconst MAX_PCT = 100;\nconst MAX_RGB = 255;\nconst POW_SQR = 2;\nconst POW_CUBE = 3;\nconst POW_LINEAR = 2.4;\nconst LINEAR_COEF = 12.92;\nconst LINEAR_OFFSET = 0.055;\nconst LAB_L = 116;\nconst LAB_A = 500;\nconst LAB_B = 200;\nconst LAB_EPSILON = 216 / 24389;\nconst LAB_KAPPA = 24389 / 27;\n\n/* type definitions */\n/**\n * @type NumStrColorChannels - string or numeric color channels\n */\ntype NumStrColorChannels = [\n x: number | string,\n y: number | string,\n z: number | string,\n alpha: number | string\n];\n\n/**\n * @type TriColorChannels - color channels without alpha\n */\ntype TriColorChannels = [x: number, y: number, z: number];\n\n/**\n * @type ColorMatrix - color matrix\n */\ntype ColorMatrix = [\n r1: TriColorChannels,\n r2: TriColorChannels,\n r3: TriColorChannels\n];\n\n/* white point */\nconst D50: TriColorChannels = [\n 0.3457 / 0.3585,\n 1.0,\n (1.0 - 0.3457 - 0.3585) / 0.3585\n];\nconst MATRIX_D50_TO_D65: ColorMatrix = [\n [0.955473421488075, -0.02309845494876471, 0.06325924320057072],\n [-0.0283697093338637, 1.0099953980813041, 0.021041441191917323],\n [0.012314014864481998, -0.020507649298898964, 1.330365926242124]\n];\nconst MATRIX_D65_TO_D50: ColorMatrix = [\n [1.0479297925449969, 0.022946870601609652, -0.05019226628920524],\n [0.02962780877005599, 0.9904344267538799, -0.017073799063418826],\n [-0.009243040646204504, 0.015055191490298152, 0.7518742814281371]\n];\n\n/* color space */\nconst MATRIX_L_RGB_TO_XYZ: ColorMatrix = [\n [506752 / 1228815, 87881 / 245763, 12673 / 70218],\n [87098 / 409605, 175762 / 245763, 12673 / 175545],\n [7918 / 409605, 87881 / 737289, 1001167 / 1053270]\n];\nconst MATRIX_XYZ_TO_L_RGB: ColorMatrix = [\n [12831 / 3959, -329 / 214, -1974 / 3959],\n [-851781 / 878810, 1648619 / 878810, 36519 / 878810],\n [705 / 12673, -2585 / 12673, 705 / 667]\n];\nconst MATRIX_XYZ_TO_LMS: ColorMatrix = [\n [0.819022437996703, 0.3619062600528904, -0.1288737815209879],\n [0.0329836539323885, 0.9292868615863434, 0.0361446663506424],\n [0.0481771893596242, 0.2642395317527308, 0.6335478284694309]\n];\nconst MATRIX_LMS_TO_XYZ: ColorMatrix = [\n [1.2268798758459243, -0.5578149944602171, 0.2813910456659647],\n [-0.0405757452148008, 1.112286803280317, -0.0717110580655164],\n [-0.0763729366746601, -0.4214933324022432, 1.5869240198367816]\n];\nconst MATRIX_OKLAB_TO_LMS: ColorMatrix = [\n [1.0, 0.3963377773761749, 0.2158037573099136],\n [1.0, -0.1055613458156586, -0.0638541728258133],\n [1.0, -0.0894841775298119, -1.2914855480194092]\n];\nconst MATRIX_LMS_TO_OKLAB: ColorMatrix = [\n [0.210454268309314, 0.7936177747023054, -0.0040720430116193],\n [1.9779985324311684, -2.4285922420485799, 0.450593709617411],\n [0.0259040424655478, 0.7827717124575296, -0.8086757549230774]\n];\nconst MATRIX_P3_TO_XYZ: ColorMatrix = [\n [608311 / 1250200, 189793 / 714400, 198249 / 1000160],\n [35783 / 156275, 247089 / 357200, 198249 / 2500400],\n [0 / 1, 32229 / 714400, 5220557 / 5000800]\n];\nconst MATRIX_REC2020_TO_XYZ: ColorMatrix = [\n [63426534 / 99577255, 20160776 / 139408157, 47086771 / 278816314],\n [26158966 / 99577255, 472592308 / 697040785, 8267143 / 139408157],\n [0 / 1, 19567812 / 697040785, 295819943 / 278816314]\n];\nconst MATRIX_A98_TO_XYZ: ColorMatrix = [\n [573536 / 994567, 263643 / 1420810, 187206 / 994567],\n [591459 / 1989134, 6239551 / 9945670, 374412 / 4972835],\n [53769 / 1989134, 351524 / 4972835, 4929758 / 4972835]\n];\nconst MATRIX_PROPHOTO_TO_XYZ_D50: ColorMatrix = [\n [0.7977666449006423, 0.13518129740053308, 0.0313477341283922],\n [0.2880748288194013, 0.711835234241873, 0.00008993693872564],\n [0.0, 0.0, 0.8251046025104602]\n];\n\n/* regexp */\nconst REG_COLOR = new RegExp(`^(?:${SYN_COLOR_TYPE})$`);\nconst REG_CS_HUE = new RegExp(`^${CS_HUE_CAPT}$`);\nconst REG_CS_XYZ = /^xyz(?:-d(?:50|65))?$/;\nconst REG_CURRENT = /^currentColor$/i;\nconst REG_FN_COLOR = new RegExp(`^color\\\\(\\\\s*(${SYN_FN_COLOR})\\\\s*\\\\)$`);\nconst REG_HSL = new RegExp(`^hsla?\\\\(\\\\s*(${SYN_HSL}|${SYN_HSL_LV3})\\\\s*\\\\)$`);\nconst REG_HWB = new RegExp(`^hwb\\\\(\\\\s*(${SYN_HSL})\\\\s*\\\\)$`);\nconst REG_LAB = new RegExp(`^lab\\\\(\\\\s*(${SYN_MOD})\\\\s*\\\\)$`);\nconst REG_LCH = new RegExp(`^lch\\\\(\\\\s*(${SYN_LCH})\\\\s*\\\\)$`);\nconst REG_MIX = new RegExp(`^${SYN_MIX}$`);\nconst REG_MIX_CAPT = new RegExp(`^${SYN_MIX_CAPT}$`);\nconst REG_MIX_NEST = new RegExp(`${SYN_MIX}`, 'g');\nconst REG_OKLAB = new RegExp(`^oklab\\\\(\\\\s*(${SYN_MOD})\\\\s*\\\\)$`);\nconst REG_OKLCH = new RegExp(`^oklch\\\\(\\\\s*(${SYN_LCH})\\\\s*\\\\)$`);\nconst REG_SPEC = /^(?:specifi|comput)edValue$/;\n\n/**\n * named colors\n */\nexport const NAMED_COLORS = {\n aliceblue: [0xf0, 0xf8, 0xff],\n antiquewhite: [0xfa, 0xeb, 0xd7],\n aqua: [0x00, 0xff, 0xff],\n aquamarine: [0x7f, 0xff, 0xd4],\n azure: [0xf0, 0xff, 0xff],\n beige: [0xf5, 0xf5, 0xdc],\n bisque: [0xff, 0xe4, 0xc4],\n black: [0x00, 0x00, 0x00],\n blanchedalmond: [0xff, 0xeb, 0xcd],\n blue: [0x00, 0x00, 0xff],\n blueviolet: [0x8a, 0x2b, 0xe2],\n brown: [0xa5, 0x2a, 0x2a],\n burlywood: [0xde, 0xb8, 0x87],\n cadetblue: [0x5f, 0x9e, 0xa0],\n chartreuse: [0x7f, 0xff, 0x00],\n chocolate: [0xd2, 0x69, 0x1e],\n coral: [0xff, 0x7f, 0x50],\n cornflowerblue: [0x64, 0x95, 0xed],\n cornsilk: [0xff, 0xf8, 0xdc],\n crimson: [0xdc, 0x14, 0x3c],\n cyan: [0x00, 0xff, 0xff],\n darkblue: [0x00, 0x00, 0x8b],\n darkcyan: [0x00, 0x8b, 0x8b],\n darkgoldenrod: [0xb8, 0x86, 0x0b],\n darkgray: [0xa9, 0xa9, 0xa9],\n darkgreen: [0x00, 0x64, 0x00],\n darkgrey: [0xa9, 0xa9, 0xa9],\n darkkhaki: [0xbd, 0xb7, 0x6b],\n darkmagenta: [0x8b, 0x00, 0x8b],\n darkolivegreen: [0x55, 0x6b, 0x2f],\n darkorange: [0xff, 0x8c, 0x00],\n darkorchid: [0x99, 0x32, 0xcc],\n darkred: [0x8b, 0x00, 0x00],\n darksalmon: [0xe9, 0x96, 0x7a],\n darkseagreen: [0x8f, 0xbc, 0x8f],\n darkslateblue: [0x48, 0x3d, 0x8b],\n darkslategray: [0x2f, 0x4f, 0x4f],\n darkslategrey: [0x2f, 0x4f, 0x4f],\n darkturquoise: [0x00, 0xce, 0xd1],\n darkviolet: [0x94, 0x00, 0xd3],\n deeppink: [0xff, 0x14, 0x93],\n deepskyblue: [0x00, 0xbf, 0xff],\n dimgray: [0x69, 0x69, 0x69],\n dimgrey: [0x69, 0x69, 0x69],\n dodgerblue: [0x1e, 0x90, 0xff],\n firebrick: [0xb2, 0x22, 0x22],\n floralwhite: [0xff, 0xfa, 0xf0],\n forestgreen: [0x22, 0x8b, 0x22],\n fuchsia: [0xff, 0x00, 0xff],\n gainsboro: [0xdc, 0xdc, 0xdc],\n ghostwhite: [0xf8, 0xf8, 0xff],\n gold: [0xff, 0xd7, 0x00],\n goldenrod: [0xda, 0xa5, 0x20],\n gray: [0x80, 0x80, 0x80],\n green: [0x00, 0x80, 0x00],\n greenyellow: [0xad, 0xff, 0x2f],\n grey: [0x80, 0x80, 0x80],\n honeydew: [0xf0, 0xff, 0xf0],\n hotpink: [0xff, 0x69, 0xb4],\n indianred: [0xcd, 0x5c, 0x5c],\n indigo: [0x4b, 0x00, 0x82],\n ivory: [0xff, 0xff, 0xf0],\n khaki: [0xf0, 0xe6, 0x8c],\n lavender: [0xe6, 0xe6, 0xfa],\n lavenderblush: [0xff, 0xf0, 0xf5],\n lawngreen: [0x7c, 0xfc, 0x00],\n lemonchiffon: [0xff, 0xfa, 0xcd],\n lightblue: [0xad, 0xd8, 0xe6],\n lightcoral: [0xf0, 0x80, 0x80],\n lightcyan: [0xe0, 0xff, 0xff],\n lightgoldenrodyellow: [0xfa, 0xfa, 0xd2],\n lightgray: [0xd3, 0xd3, 0xd3],\n lightgreen: [0x90, 0xee, 0x90],\n lightgrey: [0xd3, 0xd3, 0xd3],\n lightpink: [0xff, 0xb6, 0xc1],\n lightsalmon: [0xff, 0xa0, 0x7a],\n lightseagreen: [0x20, 0xb2, 0xaa],\n lightskyblue: [0x87, 0xce, 0xfa],\n lightslategray: [0x77, 0x88, 0x99],\n lightslategrey: [0x77, 0x88, 0x99],\n lightsteelblue: [0xb0, 0xc4, 0xde],\n lightyellow: [0xff, 0xff, 0xe0],\n lime: [0x00, 0xff, 0x00],\n limegreen: [0x32, 0xcd, 0x32],\n linen: [0xfa, 0xf0, 0xe6],\n magenta: [0xff, 0x00, 0xff],\n maroon: [0x80, 0x00, 0x00],\n mediumaquamarine: [0x66, 0xcd, 0xaa],\n mediumblue: [0x00, 0x00, 0xcd],\n mediumorchid: [0xba, 0x55, 0xd3],\n mediumpurple: [0x93, 0x70, 0xdb],\n mediumseagreen: [0x3c, 0xb3, 0x71],\n mediumslateblue: [0x7b, 0x68, 0xee],\n mediumspringgreen: [0x00, 0xfa, 0x9a],\n mediumturquoise: [0x48, 0xd1, 0xcc],\n mediumvioletred: [0xc7, 0x15, 0x85],\n midnightblue: [0x19, 0x19, 0x70],\n mintcream: [0xf5, 0xff, 0xfa],\n mistyrose: [0xff, 0xe4, 0xe1],\n moccasin: [0xff, 0xe4, 0xb5],\n navajowhite: [0xff, 0xde, 0xad],\n navy: [0x00, 0x00, 0x80],\n oldlace: [0xfd, 0xf5, 0xe6],\n olive: [0x80, 0x80, 0x00],\n olivedrab: [0x6b, 0x8e, 0x23],\n orange: [0xff, 0xa5, 0x00],\n orangered: [0xff, 0x45, 0x00],\n orchid: [0xda, 0x70, 0xd6],\n palegoldenrod: [0xee, 0xe8, 0xaa],\n palegreen: [0x98, 0xfb, 0x98],\n paleturquoise: [0xaf, 0xee, 0xee],\n palevioletred: [0xdb, 0x70, 0x93],\n papayawhip: [0xff, 0xef, 0xd5],\n peachpuff: [0xff, 0xda, 0xb9],\n peru: [0xcd, 0x85, 0x3f],\n pink: [0xff, 0xc0, 0xcb],\n plum: [0xdd, 0xa0, 0xdd],\n powderblue: [0xb0, 0xe0, 0xe6],\n purple: [0x80, 0x00, 0x80],\n rebeccapurple: [0x66, 0x33, 0x99],\n red: [0xff, 0x00, 0x00],\n rosybrown: [0xbc, 0x8f, 0x8f],\n royalblue: [0x41, 0x69, 0xe1],\n saddlebrown: [0x8b, 0x45, 0x13],\n salmon: [0xfa, 0x80, 0x72],\n sandybrown: [0xf4, 0xa4, 0x60],\n seagreen: [0x2e, 0x8b, 0x57],\n seashell: [0xff, 0xf5, 0xee],\n sienna: [0xa0, 0x52, 0x2d],\n silver: [0xc0, 0xc0, 0xc0],\n skyblue: [0x87, 0xce, 0xeb],\n slateblue: [0x6a, 0x5a, 0xcd],\n slategray: [0x70, 0x80, 0x90],\n slategrey: [0x70, 0x80, 0x90],\n snow: [0xff, 0xfa, 0xfa],\n springgreen: [0x00, 0xff, 0x7f],\n steelblue: [0x46, 0x82, 0xb4],\n tan: [0xd2, 0xb4, 0x8c],\n teal: [0x00, 0x80, 0x80],\n thistle: [0xd8, 0xbf, 0xd8],\n tomato: [0xff, 0x63, 0x47],\n turquoise: [0x40, 0xe0, 0xd0],\n violet: [0xee, 0x82, 0xee],\n wheat: [0xf5, 0xde, 0xb3],\n white: [0xff, 0xff, 0xff],\n whitesmoke: [0xf5, 0xf5, 0xf5],\n yellow: [0xff, 0xff, 0x00],\n yellowgreen: [0x9a, 0xcd, 0x32]\n} as const satisfies {\n [key: string]: TriColorChannels;\n};\n\n/**\n * cache invalid color value\n * @param key - cache key\n * @param nullable - is nullable\n * @returns cached value\n */\nexport const cacheInvalidColorValue = (\n cacheKey: string,\n format: string,\n nullable: boolean = false\n): SpecifiedColorChannels | string | NullObject => {\n if (format === VAL_SPEC) {\n const res = '';\n setCache(cacheKey, res);\n return res;\n }\n if (nullable) {\n setCache(cacheKey, null);\n return new NullObject();\n }\n const res: SpecifiedColorChannels = ['rgb', 0, 0, 0, 0];\n setCache(cacheKey, res);\n return res;\n};\n\n/**\n * resolve invalid color value\n * @param format - output format\n * @param nullable - is nullable\n * @returns resolved value\n */\nexport const resolveInvalidColorValue = (\n format: string,\n nullable: boolean = false\n): SpecifiedColorChannels | string | NullObject => {\n switch (format) {\n case 'hsl':\n case 'hwb':\n case VAL_MIX: {\n return new NullObject();\n }\n case VAL_SPEC: {\n return '';\n }\n default: {\n if (nullable) {\n return new NullObject();\n }\n return ['rgb', 0, 0, 0, 0] as SpecifiedColorChannels;\n }\n }\n};\n\n/**\n * validate color components\n * @param arr - color components\n * @param [opt] - options\n * @param [opt.alpha] - alpha channel\n * @param [opt.minLength] - min length\n * @param [opt.maxLength] - max length\n * @param [opt.minRange] - min range\n * @param [opt.maxRange] - max range\n * @param [opt.validateRange] - validate range\n * @returns result - validated color components\n */\nexport const validateColorComponents = (\n arr: ColorChannels | TriColorChannels,\n opt: {\n alpha?: boolean;\n minLength?: number;\n maxLength?: number;\n minRange?: number;\n maxRange?: number;\n validateRange?: boolean;\n } = {}\n): ColorChannels | TriColorChannels => {\n if (!Array.isArray(arr)) {\n throw new TypeError(`${arr} is not an array.`);\n }\n const {\n alpha = false,\n minLength = TRIA,\n maxLength = QUAD,\n minRange = 0,\n maxRange = 1,\n validateRange = true\n } = opt;\n if (!Number.isFinite(minLength)) {\n throw new TypeError(`${minLength} is not a number.`);\n }\n if (!Number.isFinite(maxLength)) {\n throw new TypeError(`${maxLength} is not a number.`);\n }\n if (!Number.isFinite(minRange)) {\n throw new TypeError(`${minRange} is not a number.`);\n }\n if (!Number.isFinite(maxRange)) {\n throw new TypeError(`${maxRange} is not a number.`);\n }\n const l = arr.length;\n if (l < minLength || l > maxLength) {\n throw new Error(`Unexpected array length ${l}.`);\n }\n let i = 0;\n while (i < l) {\n const v = arr[i] as number;\n if (!Number.isFinite(v)) {\n throw new TypeError(`${v} is not a number.`);\n } else if (i < TRIA && validateRange && (v < minRange || v > maxRange)) {\n throw new RangeError(`${v} is not between ${minRange} and ${maxRange}.`);\n } else if (i === TRIA && (v < 0 || v > 1)) {\n throw new RangeError(`${v} is not between 0 and 1.`);\n }\n i++;\n }\n if (alpha && l === TRIA) {\n arr.push(1);\n }\n return arr;\n};\n\n/**\n * transform matrix\n * @param mtx - 3 * 3 matrix\n * @param vct - vector\n * @param [skip] - skip validate\n * @returns TriColorChannels - [p1, p2, p3]\n */\nexport const transformMatrix = (\n mtx: ColorMatrix,\n vct: TriColorChannels,\n skip: boolean = false\n): TriColorChannels => {\n if (!Array.isArray(mtx)) {\n throw new TypeError(`${mtx} is not an array.`);\n } else if (mtx.length !== TRIA) {\n throw new Error(`Unexpected array length ${mtx.length}.`);\n } else if (!skip) {\n for (let i of mtx) {\n i = validateColorComponents(i as TriColorChannels, {\n maxLength: TRIA,\n validateRange: false\n }) as TriColorChannels;\n }\n }\n const [[r1c1, r1c2, r1c3], [r2c1, r2c2, r2c3], [r3c1, r3c2, r3c3]] = mtx;\n let v1, v2, v3;\n if (skip) {\n [v1, v2, v3] = vct;\n } else {\n [v1, v2, v3] = validateColorComponents(vct, {\n maxLength: TRIA,\n validateRange: false\n });\n }\n const p1 = r1c1 * v1 + r1c2 * v2 + r1c3 * v3;\n const p2 = r2c1 * v1 + r2c2 * v2 + r2c3 * v3;\n const p3 = r3c1 * v1 + r3c2 * v2 + r3c3 * v3;\n return [p1, p2, p3];\n};\n\n/**\n * normalize color components\n * @param colorA - color components [v1, v2, v3, v4]\n * @param colorB - color components [v1, v2, v3, v4]\n * @param [skip] - skip validate\n * @returns result - [colorA, colorB]\n */\nexport const normalizeColorComponents = (\n colorA: [number | string, number | string, number | string, number | string],\n colorB: [number | string, number | string, number | string, number | string],\n skip: boolean = false\n): [ColorChannels, ColorChannels] => {\n if (!Array.isArray(colorA)) {\n throw new TypeError(`${colorA} is not an array.`);\n } else if (colorA.length !== QUAD) {\n throw new Error(`Unexpected array length ${colorA.length}.`);\n }\n if (!Array.isArray(colorB)) {\n throw new TypeError(`${colorB} is not an array.`);\n } else if (colorB.length !== QUAD) {\n throw new Error(`Unexpected array length ${colorB.length}.`);\n }\n let i = 0;\n while (i < QUAD) {\n if (colorA[i] === NONE && colorB[i] === NONE) {\n colorA[i] = 0;\n colorB[i] = 0;\n } else if (colorA[i] === NONE) {\n colorA[i] = colorB[i] as number;\n } else if (colorB[i] === NONE) {\n colorB[i] = colorA[i] as number;\n }\n i++;\n }\n if (skip) {\n return [colorA as ColorChannels, colorB as ColorChannels];\n }\n const validatedColorA = validateColorComponents(colorA as ColorChannels, {\n minLength: QUAD,\n validateRange: false\n });\n const validatedColorB = validateColorComponents(colorB as ColorChannels, {\n minLength: QUAD,\n validateRange: false\n });\n return [validatedColorA as ColorChannels, validatedColorB as ColorChannels];\n};\n\n/**\n * number to hex string\n * @param value - numeric value\n * @returns hex string\n */\nexport const numberToHexString = (value: number): string => {\n if (!Number.isFinite(value)) {\n throw new TypeError(`${value} is not a number.`);\n } else {\n value = Math.round(value);\n if (value < 0 || value > MAX_RGB) {\n throw new RangeError(`${value} is not between 0 and ${MAX_RGB}.`);\n }\n }\n let hex = value.toString(HEX);\n if (hex.length === 1) {\n hex = `0${hex}`;\n }\n return hex;\n};\n\n/**\n * angle to deg\n * @param angle\n * @returns deg: 0..360\n */\nexport const angleToDeg = (angle: string): number => {\n if (isString(angle)) {\n angle = angle.trim();\n } else {\n throw new TypeError(`${angle} is not a string.`);\n }\n const GRAD = DEG / 400;\n const RAD = DEG / (Math.PI * DUO);\n const reg = new RegExp(`^(${NUM})(${ANGLE})?$`);\n if (!reg.test(angle)) {\n throw new SyntaxError(`Invalid property value: ${angle}`);\n }\n const [, value, unit] = angle.match(reg) as MatchedRegExp;\n let deg;\n switch (unit) {\n case 'grad':\n deg = parseFloat(value) * GRAD;\n break;\n case 'rad':\n deg = parseFloat(value) * RAD;\n break;\n case 'turn':\n deg = parseFloat(value) * DEG;\n break;\n default:\n deg = parseFloat(value);\n }\n deg %= DEG;\n if (deg < 0) {\n deg += DEG;\n } else if (Object.is(deg, -0)) {\n deg = 0;\n }\n return deg;\n};\n\n/**\n * parse alpha\n * @param [alpha] - alpha value\n * @returns alpha: 0..1\n */\nexport const parseAlpha = (alpha: string = ''): number => {\n if (isString(alpha)) {\n alpha = alpha.trim();\n if (!alpha) {\n alpha = '1';\n } else if (alpha === NONE) {\n alpha = '0';\n } else {\n let a;\n if (alpha.endsWith('%')) {\n a = parseFloat(alpha) / MAX_PCT;\n } else {\n a = parseFloat(alpha);\n }\n if (!Number.isFinite(a)) {\n throw new TypeError(`${a} is not a finite number.`);\n }\n if (a < PPTH) {\n alpha = '0';\n } else if (a > 1) {\n alpha = '1';\n } else {\n alpha = a.toFixed(TRIA);\n }\n }\n } else {\n alpha = '1';\n }\n return parseFloat(alpha);\n};\n\n/**\n * parse hex alpha\n * @param value - alpha value in hex string\n * @returns alpha: 0..1\n */\nexport const parseHexAlpha = (value: string): number => {\n if (isString(value)) {\n if (value === '') {\n throw new SyntaxError('Invalid property value: (empty string)');\n }\n value = value.trim();\n } else {\n throw new TypeError(`${value} is not a string.`);\n }\n let alpha = parseInt(value, HEX);\n if (alpha <= 0) {\n return 0;\n }\n if (alpha >= MAX_RGB) {\n return 1;\n }\n const alphaMap = new Map();\n for (let i = 1; i < MAX_PCT; i++) {\n alphaMap.set(Math.round((i * MAX_RGB) / MAX_PCT), i);\n }\n if (alphaMap.has(alpha)) {\n alpha = alphaMap.get(alpha) / MAX_PCT;\n } else {\n alpha = Math.round(alpha / MAX_RGB / PPTH) * PPTH;\n }\n return parseFloat(alpha.toFixed(TRIA));\n};\n\n/**\n * transform rgb to linear rgb\n * @param rgb - [r, g, b] r|g|b: 0..255\n * @param [skip] - skip validate\n * @returns TriColorChannels - [r, g, b] r|g|b: 0..1\n */\nexport const transformRgbToLinearRgb = (\n rgb: TriColorChannels,\n skip: boolean = false\n): TriColorChannels => {\n let rr, gg, bb;\n if (skip) {\n [rr, gg, bb] = rgb;\n } else {\n [rr, gg, bb] = validateColorComponents(rgb, {\n maxLength: TRIA,\n maxRange: MAX_RGB\n });\n }\n let r = rr / MAX_RGB;\n let g = gg / MAX_RGB;\n let b = bb / MAX_RGB;\n const COND_POW = 0.04045;\n if (r > COND_POW) {\n r = Math.pow((r + LINEAR_OFFSET) / (1 + LINEAR_OFFSET), POW_LINEAR);\n } else {\n r /= LINEAR_COEF;\n }\n if (g > COND_POW) {\n g = Math.pow((g + LINEAR_OFFSET) / (1 + LINEAR_OFFSET), POW_LINEAR);\n } else {\n g /= LINEAR_COEF;\n }\n if (b > COND_POW) {\n b = Math.pow((b + LINEAR_OFFSET) / (1 + LINEAR_OFFSET), POW_LINEAR);\n } else {\n b /= LINEAR_COEF;\n }\n return [r, g, b];\n};\n\n/**\n * transform rgb to xyz\n * @param rgb - [r, g, b] r|g|b: 0..255\n * @param [skip] - skip validate\n * @returns TriColorChannels - [x, y, z]\n */\nexport const transformRgbToXyz = (\n rgb: TriColorChannels,\n skip: boolean = false\n): TriColorChannels => {\n if (!skip) {\n rgb = validateColorComponents(rgb, {\n maxLength: TRIA,\n maxRange: MAX_RGB\n }) as TriColorChannels;\n }\n rgb = transformRgbToLinearRgb(rgb, true);\n const xyz = transformMatrix(MATRIX_L_RGB_TO_XYZ, rgb, true);\n return xyz;\n};\n\n/**\n * transform rgb to xyz-d50\n * @param rgb - [r, g, b] r|g|b: 0..255 alpha: 0..1\n * @returns TriColorChannels - [x, y, z]\n */\nexport const transformRgbToXyzD50 = (\n rgb: TriColorChannels\n): TriColorChannels => {\n let xyz = transformRgbToXyz(rgb);\n xyz = transformMatrix(MATRIX_D65_TO_D50, xyz, true);\n return xyz;\n};\n\n/**\n * transform linear rgb to rgb\n * @param rgb - [r, g, b] r|g|b: 0..1\n * @param [round] - round result\n * @returns TriColorChannels - [r, g, b] r|g|b: 0..255\n */\nexport const transformLinearRgbToRgb = (\n rgb: TriColorChannels,\n round: boolean = false\n): TriColorChannels => {\n let [r, g, b] = validateColorComponents(rgb, {\n maxLength: TRIA\n });\n const COND_POW = 809 / 258400;\n if (r > COND_POW) {\n r = Math.pow(r, 1 / POW_LINEAR) * (1 + LINEAR_OFFSET) - LINEAR_OFFSET;\n } else {\n r *= LINEAR_COEF;\n }\n r *= MAX_RGB;\n if (g > COND_POW) {\n g = Math.pow(g, 1 / POW_LINEAR) * (1 + LINEAR_OFFSET) - LINEAR_OFFSET;\n } else {\n g *= LINEAR_COEF;\n }\n g *= MAX_RGB;\n if (b > COND_POW) {\n b = Math.pow(b, 1 / POW_LINEAR) * (1 + LINEAR_OFFSET) - LINEAR_OFFSET;\n } else {\n b *= LINEAR_COEF;\n }\n b *= MAX_RGB;\n return [\n round ? Math.round(r) : r,\n round ? Math.round(g) : g,\n round ? Math.round(b) : b\n ];\n};\n\n/**\n * transform xyz to rgb\n * @param xyz - [x, y, z]\n * @param [skip] - skip validate\n * @returns TriColorChannels - [r, g, b] r|g|b: 0..255\n */\nexport const transformXyzToRgb = (\n xyz: TriColorChannels,\n skip: boolean = false\n): TriColorChannels => {\n if (!skip) {\n xyz = validateColorComponents(xyz, {\n maxLength: TRIA,\n validateRange: false\n }) as TriColorChannels;\n }\n let [r, g, b] = transformMatrix(MATRIX_XYZ_TO_L_RGB, xyz, true);\n [r, g, b] = transformLinearRgbToRgb(\n [\n Math.min(Math.max(r, 0), 1),\n Math.min(Math.max(g, 0), 1),\n Math.min(Math.max(b, 0), 1)\n ],\n true\n );\n return [r, g, b];\n};\n\n/**\n * transform xyz to xyz-d50\n * @param xyz - [x, y, z]\n * @returns TriColorChannels - [x, y, z]\n */\nexport const transformXyzToXyzD50 = (\n xyz: TriColorChannels\n): TriColorChannels => {\n xyz = validateColorComponents(xyz, {\n maxLength: TRIA,\n validateRange: false\n }) as TriColorChannels;\n xyz = transformMatrix(MATRIX_D65_TO_D50, xyz, true);\n return xyz;\n};\n\n/**\n * transform xyz to hsl\n * @param xyz - [x, y, z]\n * @param [skip] - skip validate\n * @returns TriColorChannels - [h, s, l]\n */\nexport const transformXyzToHsl = (\n xyz: TriColorChannels,\n skip: boolean = false\n): TriColorChannels => {\n const [rr, gg, bb] = transformXyzToRgb(xyz, skip);\n const r = rr / MAX_RGB;\n const g = gg / MAX_RGB;\n const b = bb / MAX_RGB;\n const max = Math.max(r, g, b);\n const min = Math.min(r, g, b);\n const d = max - min;\n const l = (max + min) * HALF * MAX_PCT;\n let h, s;\n if (Math.round(l) === 0 || Math.round(l) === MAX_PCT) {\n h = 0;\n s = 0;\n } else {\n s = (d / (1 - Math.abs(max + min - 1))) * MAX_PCT;\n if (s === 0) {\n h = 0;\n } else {\n switch (max) {\n case r:\n h = (g - b) / d;\n break;\n case g:\n h = (b - r) / d + DUO;\n break;\n case b:\n default:\n h = (r - g) / d + QUAD;\n break;\n }\n h = (h * SEXA) % DEG;\n if (h < 0) {\n h += DEG;\n }\n }\n }\n return [h, s, l];\n};\n\n/**\n * transform xyz to hwb\n * @param xyz - [x, y, z]\n * @param [skip] - skip validate\n * @returns TriColorChannels - [h, w, b]\n */\nexport const transformXyzToHwb = (\n xyz: TriColorChannels,\n skip: boolean = false\n): TriColorChannels => {\n const [r, g, b] = transformXyzToRgb(xyz, skip);\n const wh = Math.min(r, g, b) / MAX_RGB;\n const bk = 1 - Math.max(r, g, b) / MAX_RGB;\n let h;\n if (wh + bk === 1) {\n h = 0;\n } else {\n [h] = transformXyzToHsl(xyz);\n }\n return [h, wh * MAX_PCT, bk * MAX_PCT];\n};\n\n/**\n * transform xyz to oklab\n * @param xyz - [x, y, z]\n * @param [skip] - skip validate\n * @returns TriColorChannels - [l, a, b]\n */\nexport const transformXyzToOklab = (\n xyz: TriColorChannels,\n skip: boolean = false\n): TriColorChannels => {\n if (!skip) {\n xyz = validateColorComponents(xyz, {\n maxLength: TRIA,\n validateRange: false\n }) as TriColorChannels;\n }\n const lms = transformMatrix(MATRIX_XYZ_TO_LMS, xyz, true);\n const xyzLms = lms.map(c => Math.cbrt(c)) as TriColorChannels;\n let [l, a, b] = transformMatrix(MATRIX_LMS_TO_OKLAB, xyzLms, true);\n l = Math.min(Math.max(l, 0), 1);\n const lPct = Math.round(parseFloat(l.toFixed(QUAD)) * MAX_PCT);\n if (lPct === 0 || lPct === MAX_PCT) {\n a = 0;\n b = 0;\n }\n return [l, a, b];\n};\n\n/**\n * transform xyz to oklch\n * @param xyz - [x, y, z]\n * @param [skip] - skip validate\n * @returns TriColorChannels - [l, c, h]\n */\nexport const transformXyzToOklch = (\n xyz: TriColorChannels,\n skip: boolean = false\n): TriColorChannels => {\n const [l, a, b] = transformXyzToOklab(xyz, skip);\n let c, h;\n const lPct = Math.round(parseFloat(l.toFixed(QUAD)) * MAX_PCT);\n if (lPct === 0 || lPct === MAX_PCT) {\n c = 0;\n h = 0;\n } else {\n c = Math.max(Math.sqrt(Math.pow(a, POW_SQR) + Math.pow(b, POW_SQR)), 0);\n if (parseFloat(c.toFixed(QUAD)) === 0) {\n h = 0;\n } else {\n h = (Math.atan2(b, a) * DEG_HALF) / Math.PI;\n if (h < 0) {\n h += DEG;\n }\n }\n }\n return [l, c, h];\n};\n\n/**\n * transform xyz D50 to rgb\n * @param xyz - [x, y, z]\n * @param [skip] - skip validate\n * @returns TriColorChannels - [r, g, b] r|g|b: 0..255\n */\nexport const transformXyzD50ToRgb = (\n xyz: TriColorChannels,\n skip: boolean = false\n): TriColorChannels => {\n if (!skip) {\n xyz = validateColorComponents(xyz, {\n maxLength: TRIA,\n validateRange: false\n }) as TriColorChannels;\n }\n const xyzD65 = transformMatrix(MATRIX_D50_TO_D65, xyz, true);\n const rgb = transformXyzToRgb(xyzD65, true);\n return rgb;\n};\n\n/**\n * transform xyz-d50 to lab\n * @param xyz - [x, y, z]\n * @param [skip] - skip validate\n * @returns TriColorChannels - [l, a, b]\n */\nexport const transformXyzD50ToLab = (\n xyz: TriColorChannels,\n skip: boolean = false\n): TriColorChannels => {\n if (!skip) {\n xyz = validateColorComponents(xyz, {\n maxLength: TRIA,\n validateRange: false\n }) as TriColorChannels;\n }\n const xyzD50 = xyz.map((val, i) => val / (D50[i] as number));\n const [f0, f1, f2] = xyzD50.map(val =>\n val > LAB_EPSILON ? Math.cbrt(val) : (val * LAB_KAPPA + HEX) / LAB_L\n ) as TriColorChannels;\n const l = Math.min(Math.max(LAB_L * f1 - HEX, 0), MAX_PCT);\n let a, b;\n if (l === 0 || l === MAX_PCT) {\n a = 0;\n b = 0;\n } else {\n a = (f0 - f1) * LAB_A;\n b = (f1 - f2) * LAB_B;\n }\n return [l, a, b];\n};\n\n/**\n * transform xyz-d50 to lch\n * @param xyz - [x, y, z]\n * @param [skip] - skip validate\n * @returns TriColorChannels - [l, c, h]\n */\nexport const transformXyzD50ToLch = (\n xyz: TriColorChannels,\n skip: boolean = false\n): TriColorChannels => {\n const [l, a, b] = transformXyzD50ToLab(xyz, skip);\n let c, h;\n if (l === 0 || l === MAX_PCT) {\n c = 0;\n h = 0;\n } else {\n c = Math.max(Math.sqrt(Math.pow(a, POW_SQR) + Math.pow(b, POW_SQR)), 0);\n h = (Math.atan2(b, a) * DEG_HALF) / Math.PI;\n if (h < 0) {\n h += DEG;\n }\n }\n return [l, c, h];\n};\n\n/**\n * convert rgb to hex color\n * @param rgb - [r, g, b, alpha] r|g|b: 0..255 alpha: 0..1\n * @returns hex color\n */\nexport const convertRgbToHex = (rgb: ColorChannels): string => {\n const [r, g, b, alpha] = validateColorComponents(rgb, {\n alpha: true,\n maxRange: MAX_RGB\n }) as ColorChannels;\n const rr = numberToHexString(r);\n const gg = numberToHexString(g);\n const bb = numberToHexString(b);\n const aa = numberToHexString(alpha * MAX_RGB);\n let hex;\n if (aa === 'ff') {\n hex = `#${rr}${gg}${bb}`;\n } else {\n hex = `#${rr}${gg}${bb}${aa}`;\n }\n return hex;\n};\n\n/**\n * convert linear rgb to hex color\n * @param rgb - [r, g, b, alpha] r|g|b|alpha: 0..1\n * @param [skip] - skip validate\n * @returns hex color\n */\nexport const convertLinearRgbToHex = (\n rgb: ColorChannels,\n skip: boolean = false\n): string => {\n let r, g, b, alpha;\n if (skip) {\n [r, g, b, alpha] = rgb;\n } else {\n [r, g, b, alpha] = validateColorComponents(rgb, {\n minLength: QUAD\n }) as ColorChannels;\n }\n [r, g, b] = transformLinearRgbToRgb([r, g, b], true);\n const rr = numberToHexString(r);\n const gg = numberToHexString(g);\n const bb = numberToHexString(b);\n const aa = numberToHexString(alpha * MAX_RGB);\n let hex;\n if (aa === 'ff') {\n hex = `#${rr}${gg}${bb}`;\n } else {\n hex = `#${rr}${gg}${bb}${aa}`;\n }\n return hex;\n};\n\n/**\n * convert xyz to hex color\n * @param xyz - [x, y, z, alpha]\n * @returns hex color\n */\nexport const convertXyzToHex = (xyz: ColorChannels): string => {\n const [x, y, z, alpha] = validateColorComponents(xyz, {\n minLength: QUAD,\n validateRange: false\n }) as ColorChannels;\n const [r, g, b] = transformMatrix(MATRIX_XYZ_TO_L_RGB, [x, y, z], true);\n const hex = convertLinearRgbToHex(\n [\n Math.min(Math.max(r, 0), 1),\n Math.min(Math.max(g, 0), 1),\n Math.min(Math.max(b, 0), 1),\n alpha\n ],\n true\n );\n return hex;\n};\n\n/**\n * convert xyz D50 to hex color\n * @param xyz - [x, y, z, alpha]\n * @returns hex color\n */\nexport const convertXyzD50ToHex = (xyz: ColorChannels): string => {\n const [x, y, z, alpha] = validateColorComponents(xyz, {\n minLength: QUAD,\n validateRange: false\n }) as ColorChannels;\n const xyzD65 = transformMatrix(MATRIX_D50_TO_D65, [x, y, z], true);\n const [r, g, b] = transformMatrix(MATRIX_XYZ_TO_L_RGB, xyzD65, true);\n const hex = convertLinearRgbToHex([\n Math.min(Math.max(r, 0), 1),\n Math.min(Math.max(g, 0), 1),\n Math.min(Math.max(b, 0), 1),\n alpha\n ]);\n return hex;\n};\n\n/**\n * convert hex color to rgb\n * @param value - hex color value\n * @returns ColorChannels - [r, g, b, alpha] r|g|b: 0..255 alpha: 0..1\n */\nexport const convertHexToRgb = (value: string): ColorChannels => {\n if (isString(value)) {\n value = value.toLowerCase().trim();\n } else {\n throw new TypeError(`${value} is not a string.`);\n }\n if (\n !(\n /^#[\\da-f]{6}$/.test(value) ||\n /^#[\\da-f]{3}$/.test(value) ||\n /^#[\\da-f]{8}$/.test(value) ||\n /^#[\\da-f]{4}$/.test(value)\n )\n ) {\n throw new SyntaxError(`Invalid property value: ${value}`);\n }\n const arr: number[] = [];\n if (/^#[\\da-f]{3}$/.test(value)) {\n const [, r, g, b] = value.match(\n /^#([\\da-f])([\\da-f])([\\da-f])$/\n ) as MatchedRegExp;\n arr.push(\n parseInt(`${r}${r}`, HEX),\n parseInt(`${g}${g}`, HEX),\n parseInt(`${b}${b}`, HEX),\n 1\n );\n } else if (/^#[\\da-f]{4}$/.test(value)) {\n const [, r, g, b, alpha] = value.match(\n /^#([\\da-f])([\\da-f])([\\da-f])([\\da-f])$/\n ) as MatchedRegExp;\n arr.push(\n parseInt(`${r}${r}`, HEX),\n parseInt(`${g}${g}`, HEX),\n parseInt(`${b}${b}`, HEX),\n parseHexAlpha(`${alpha}${alpha}`)\n );\n } else if (/^#[\\da-f]{8}$/.test(value)) {\n const [, r, g, b, alpha] = value.match(\n /^#([\\da-f]{2})([\\da-f]{2})([\\da-f]{2})([\\da-f]{2})$/\n ) as MatchedRegExp;\n arr.push(\n parseInt(r, HEX),\n parseInt(g, HEX),\n parseInt(b, HEX),\n parseHexAlpha(alpha)\n );\n } else {\n const [, r, g, b] = value.match(\n /^#([\\da-f]{2})([\\da-f]{2})([\\da-f]{2})$/\n ) as MatchedRegExp;\n arr.push(parseInt(r, HEX), parseInt(g, HEX), parseInt(b, HEX), 1);\n }\n return arr as ColorChannels;\n};\n\n/**\n * convert hex color to linear rgb\n * @param value - hex color value\n * @returns ColorChannels - [r, g, b, alpha] r|g|b|alpha: 0..1\n */\nexport const convertHexToLinearRgb = (value: string): ColorChannels => {\n const [rr, gg, bb, alpha] = convertHexToRgb(value);\n const [r, g, b] = transformRgbToLinearRgb([rr, gg, bb], true);\n return [r, g, b, alpha];\n};\n\n/**\n * convert hex color to xyz\n * @param value - hex color value\n * @returns ColorChannels - [x, y, z, alpha]\n */\nexport const convertHexToXyz = (value: string): ColorChannels => {\n const [r, g, b, alpha] = convertHexToLinearRgb(value);\n const [x, y, z] = transformMatrix(MATRIX_L_RGB_TO_XYZ, [r, g, b], true);\n return [x, y, z, alpha];\n};\n\n/**\n * parse rgb()\n * @param value - rgb color value\n * @param [opt] - options\n * @returns parsed color - ['rgb', r, g, b, alpha], '(empty)', NullObject\n */\nexport const parseRgb = (\n value: string,\n opt: Options = {}\n): SpecifiedColorChannels | string | NullObject => {\n if (isString(value)) {\n value = value.toLowerCase().trim();\n } else {\n throw new TypeError(`${value} is not a string.`);\n }\n const { format = '', nullable = false } = opt;\n const reg = new RegExp(`^rgba?\\\\(\\\\s*(${SYN_MOD}|${SYN_RGB_LV3})\\\\s*\\\\)$`);\n if (!reg.test(value)) {\n const res = resolveInvalidColorValue(format, nullable);\n if (res instanceof NullObject) {\n return res;\n }\n if (isString(res)) {\n return res as string;\n }\n return res as SpecifiedColorChannels;\n }\n const [, val] = value.match(reg) as MatchedRegExp;\n const [v1, v2, v3, v4 = ''] = val\n .replace(/[,/]/g, ' ')\n .split(/\\s+/) as StringColorChannels;\n let r, g, b;\n if (v1 === NONE) {\n r = 0;\n } else {\n if (v1.endsWith('%')) {\n r = (parseFloat(v1) * MAX_RGB) / MAX_PCT;\n } else {\n r = parseFloat(v1);\n }\n r = Math.min(Math.max(roundToPrecision(r, OCT), 0), MAX_RGB);\n }\n if (v2 === NONE) {\n g = 0;\n } else {\n if (v2.endsWith('%')) {\n g = (parseFloat(v2) * MAX_RGB) / MAX_PCT;\n } else {\n g = parseFloat(v2);\n }\n g = Math.min(Math.max(roundToPrecision(g, OCT), 0), MAX_RGB);\n }\n if (v3 === NONE) {\n b = 0;\n } else {\n if (v3.endsWith('%')) {\n b = (parseFloat(v3) * MAX_RGB) / MAX_PCT;\n } else {\n b = parseFloat(v3);\n }\n b = Math.min(Math.max(roundToPrecision(b, OCT), 0), MAX_RGB);\n }\n const alpha = parseAlpha(v4);\n return ['rgb', r, g, b, format === VAL_MIX && v4 === NONE ? NONE : alpha];\n};\n\n/**\n * parse hsl()\n * @param value - hsl color value\n * @param [opt] - options\n * @returns parsed color - ['rgb', r, g, b, alpha], '(empty)', NullObject\n */\nexport const parseHsl = (\n value: string,\n opt: Options = {}\n): SpecifiedColorChannels | string | NullObject => {\n if (isString(value)) {\n value = value.trim();\n } else {\n throw new TypeError(`${value} is not a string.`);\n }\n const { format = '', nullable = false } = opt;\n if (!REG_HSL.test(value)) {\n const res = resolveInvalidColorValue(format, nullable);\n if (res instanceof NullObject) {\n return res;\n }\n if (isString(res)) {\n return res as string;\n }\n return res as SpecifiedColorChannels;\n }\n const [, val] = value.match(REG_HSL) as MatchedRegExp;\n const [v1, v2, v3, v4 = ''] = val\n .replace(/[,/]/g, ' ')\n .split(/\\s+/) as StringColorChannels;\n let h, s, l;\n if (v1 === NONE) {\n h = 0;\n } else {\n h = angleToDeg(v1);\n }\n if (v2 === NONE) {\n s = 0;\n } else {\n s = Math.min(Math.max(parseFloat(v2), 0), MAX_PCT);\n }\n if (v3 === NONE) {\n l = 0;\n } else {\n l = Math.min(Math.max(parseFloat(v3), 0), MAX_PCT);\n }\n const alpha = parseAlpha(v4);\n if (format === 'hsl') {\n return [\n format,\n v1 === NONE ? v1 : h,\n v2 === NONE ? v2 : s,\n v3 === NONE ? v3 : l,\n v4 === NONE ? v4 : alpha\n ];\n }\n h = (h / DEG) * DOZ;\n l /= MAX_PCT;\n const sa = (s / MAX_PCT) * Math.min(l, 1 - l);\n const rk = h % DOZ;\n const gk = (8 + h) % DOZ;\n const bk = (4 + h) % DOZ;\n const r = l - sa * Math.max(-1, Math.min(rk - TRIA, TRIA ** POW_SQR - rk, 1));\n const g = l - sa * Math.max(-1, Math.min(gk - TRIA, TRIA ** POW_SQR - gk, 1));\n const b = l - sa * Math.max(-1, Math.min(bk - TRIA, TRIA ** POW_SQR - bk, 1));\n return [\n 'rgb',\n Math.min(Math.max(roundToPrecision(r * MAX_RGB, OCT), 0), MAX_RGB),\n Math.min(Math.max(roundToPrecision(g * MAX_RGB, OCT), 0), MAX_RGB),\n Math.min(Math.max(roundToPrecision(b * MAX_RGB, OCT), 0), MAX_RGB),\n alpha\n ];\n};\n\n/**\n * parse hwb()\n * @param value - hwb color value\n * @param [opt] - options\n * @returns parsed color - ['rgb', r, g, b, alpha], '(empty)', NullObject\n */\nexport const parseHwb = (\n value: string,\n opt: Options = {}\n): SpecifiedColorChannels | string | NullObject => {\n if (isString(value)) {\n value = value.trim();\n } else {\n throw new TypeError(`${value} is not a string.`);\n }\n const { format = '', nullable = false } = opt;\n if (!REG_HWB.test(value)) {\n const res = resolveInvalidColorValue(format, nullable);\n if (res instanceof NullObject) {\n return res;\n }\n if (isString(res)) {\n return res as string;\n }\n return res as SpecifiedColorChannels;\n }\n const [, val] = value.match(REG_HWB) as MatchedRegExp;\n const [v1, v2, v3, v4 = ''] = val\n .replace('/', ' ')\n .split(/\\s+/) as StringColorChannels;\n let h, wh, bk;\n if (v1 === NONE) {\n h = 0;\n } else {\n h = angleToDeg(v1);\n }\n if (v2 === NONE) {\n wh = 0;\n } else {\n wh = Math.min(Math.max(parseFloat(v2), 0), MAX_PCT) / MAX_PCT;\n }\n if (v3 === NONE) {\n bk = 0;\n } else {\n bk = Math.min(Math.max(parseFloat(v3), 0), MAX_PCT) / MAX_PCT;\n }\n const alpha = parseAlpha(v4);\n if (format === 'hwb') {\n return [\n format,\n v1 === NONE ? v1 : h,\n v2 === NONE ? v2 : wh * MAX_PCT,\n v3 === NONE ? v3 : bk * MAX_PCT,\n v4 === NONE ? v4 : alpha\n ];\n }\n if (wh + bk >= 1) {\n const v = roundToPrecision((wh / (wh + bk)) * MAX_RGB, OCT);\n return ['rgb', v, v, v, alpha];\n }\n const factor = (1 - wh - bk) / MAX_RGB;\n let [, r, g, b] = parseHsl(`hsl(${h} 100 50)`) as ComputedColorChannels;\n r = roundToPrecision((r * factor + wh) * MAX_RGB, OCT);\n g = roundToPrecision((g * factor + wh) * MAX_RGB, OCT);\n b = roundToPrecision((b * factor + wh) * MAX_RGB, OCT);\n return [\n 'rgb',\n Math.min(Math.max(r, 0), MAX_RGB),\n Math.min(Math.max(g, 0), MAX_RGB),\n Math.min(Math.max(b, 0), MAX_RGB),\n alpha\n ];\n};\n\n/**\n * parse lab()\n * @param value - lab color value\n * @param [opt] - options\n * @returns parsed color\n * - [xyz-d50, x, y, z, alpha], ['lab', l, a, b, alpha], '(empty)', NullObject\n */\nexport const parseLab = (\n value: string,\n opt: Options = {}\n): SpecifiedColorChannels | string | NullObject => {\n if (isString(value)) {\n value = value.trim();\n } else {\n throw new TypeError(`${value} is not a string.`);\n }\n const { format = '', nullable = false } = opt;\n if (!REG_LAB.test(value)) {\n const res = resolveInvalidColorValue(format, nullable);\n if (res instanceof NullObject) {\n return res;\n }\n if (isString(res)) {\n return res as string;\n }\n return res as SpecifiedColorChannels;\n }\n const COEF_PCT = 1.25;\n const COND_POW = 8;\n const [, val] = value.match(REG_LAB) as MatchedRegExp;\n const [v1, v2, v3, v4 = ''] = val\n .replace('/', ' ')\n .split(/\\s+/) as StringColorChannels;\n let l, a, b;\n if (v1 === NONE) {\n l = 0;\n } else {\n if (v1.endsWith('%')) {\n l = parseFloat(v1);\n if (l > MAX_PCT) {\n l = MAX_PCT;\n }\n } else {\n l = parseFloat(v1);\n }\n if (l < 0) {\n l = 0;\n }\n }\n if (v2 === NONE) {\n a = 0;\n } else {\n a = v2.endsWith('%') ? parseFloat(v2) * COEF_PCT : parseFloat(v2);\n }\n if (v3 === NONE) {\n b = 0;\n } else {\n b = v3.endsWith('%') ? parseFloat(v3) * COEF_PCT : parseFloat(v3);\n }\n const alpha = parseAlpha(v4);\n if (REG_SPEC.test(format)) {\n return [\n 'lab',\n v1 === NONE ? v1 : roundToPrecision(l, HEX),\n v2 === NONE ? v2 : roundToPrecision(a, HEX),\n v3 === NONE ? v3 : roundToPrecision(b, HEX),\n v4 === NONE ? v4 : alpha\n ];\n }\n const fl = (l + HEX) / LAB_L;\n const fa = a / LAB_A + fl;\n const fb = fl - b / LAB_B;\n const powFl = Math.pow(fl, POW_CUBE);\n const powFa = Math.pow(fa, POW_CUBE);\n const powFb = Math.pow(fb, POW_CUBE);\n const xyz = [\n powFa > LAB_EPSILON ? powFa : (fa * LAB_L - HEX) / LAB_KAPPA,\n l > COND_POW ? powFl : l / LAB_KAPPA,\n powFb > LAB_EPSILON ? powFb : (fb * LAB_L - HEX) / LAB_KAPPA\n ];\n const [x, y, z] = xyz.map(\n (val, i) => val * (D50[i] as number)\n ) as TriColorChannels;\n return [\n 'xyz-d50',\n roundToPrecision(x, HEX),\n roundToPrecision(y, HEX),\n roundToPrecision(z, HEX),\n alpha\n ];\n};\n\n/**\n * parse lch()\n * @param value - lch color value\n * @param [opt] - options\n * @returns parsed color\n * - ['xyz-d50', x, y, z, alpha], ['lch', l, c, h, alpha]\n * - '(empty)', NullObject\n */\nexport const parseLch = (\n value: string,\n opt: Options = {}\n): SpecifiedColorChannels | string | NullObject => {\n if (isString(value)) {\n value = value.trim();\n } else {\n throw new TypeError(`${value} is not a string.`);\n }\n const { format = '', nullable = false } = opt;\n if (!REG_LCH.test(value)) {\n const res = resolveInvalidColorValue(format, nullable);\n if (res instanceof NullObject) {\n return res;\n }\n if (isString(res)) {\n return res as string;\n }\n return res as SpecifiedColorChannels;\n }\n const COEF_PCT = 1.5;\n const [, val] = value.match(REG_LCH) as MatchedRegExp;\n const [v1, v2, v3, v4 = ''] = val\n .replace('/', ' ')\n .split(/\\s+/) as StringColorChannels;\n let l, c, h;\n if (v1 === NONE) {\n l = 0;\n } else {\n l = parseFloat(v1);\n if (l < 0) {\n l = 0;\n }\n }\n if (v2 === NONE) {\n c = 0;\n } else {\n c = v2.endsWith('%') ? parseFloat(v2) * COEF_PCT : parseFloat(v2);\n }\n if (v3 === NONE) {\n h = 0;\n } else {\n h = angleToDeg(v3);\n }\n const alpha = parseAlpha(v4);\n if (REG_SPEC.test(format)) {\n return [\n 'lch',\n v1 === NONE ? v1 : roundToPrecision(l, HEX),\n v2 === NONE ? v2 : roundToPrecision(c, HEX),\n v3 === NONE ? v3 : roundToPrecision(h, HEX),\n v4 === NONE ? v4 : alpha\n ];\n }\n const a = c * Math.cos((h * Math.PI) / DEG_HALF);\n const b = c * Math.sin((h * Math.PI) / DEG_HALF);\n const [, x, y, z] = parseLab(`lab(${l} ${a} ${b})`) as ComputedColorChannels;\n return [\n 'xyz-d50',\n roundToPrecision(x, HEX),\n roundToPrecision(y, HEX),\n roundToPrecision(z, HEX),\n alpha as number\n ];\n};\n\n/**\n * parse oklab()\n * @param value - oklab color value\n * @param [opt] - options\n * @returns parsed color\n * - ['xyz-d65', x, y, z, alpha], ['oklab', l, a, b, alpha]\n * - '(empty)', NullObject\n */\nexport const parseOklab = (\n value: string,\n opt: Options = {}\n): SpecifiedColorChannels | string | NullObject => {\n if (isString(value)) {\n value = value.trim();\n } else {\n throw new TypeError(`${value} is not a string.`);\n }\n const { format = '', nullable = false } = opt;\n if (!REG_OKLAB.test(value)) {\n const res = resolveInvalidColorValue(format, nullable);\n if (res instanceof NullObject) {\n return res;\n }\n if (isString(res)) {\n return res as string;\n }\n return res as SpecifiedColorChannels;\n }\n const COEF_PCT = 0.4;\n const [, val] = value.match(REG_OKLAB) as MatchedRegExp;\n const [v1, v2, v3, v4 = ''] = val\n .replace('/', ' ')\n .split(/\\s+/) as StringColorChannels;\n let l, a, b;\n if (v1 === NONE) {\n l = 0;\n } else {\n l = v1.endsWith('%') ? parseFloat(v1) / MAX_PCT : parseFloat(v1);\n if (l < 0) {\n l = 0;\n }\n }\n if (v2 === NONE) {\n a = 0;\n } else if (v2.endsWith('%')) {\n a = (parseFloat(v2) * COEF_PCT) / MAX_PCT;\n } else {\n a = parseFloat(v2);\n }\n if (v3 === NONE) {\n b = 0;\n } else if (v3.endsWith('%')) {\n b = (parseFloat(v3) * COEF_PCT) / MAX_PCT;\n } else {\n b = parseFloat(v3);\n }\n const alpha = parseAlpha(v4);\n if (REG_SPEC.test(format)) {\n return [\n 'oklab',\n v1 === NONE ? v1 : roundToPrecision(l, HEX),\n v2 === NONE ? v2 : roundToPrecision(a, HEX),\n v3 === NONE ? v3 : roundToPrecision(b, HEX),\n v4 === NONE ? v4 : alpha\n ];\n }\n const lms = transformMatrix(MATRIX_OKLAB_TO_LMS, [l, a, b]);\n const xyzLms = lms.map(c => Math.pow(c, POW_CUBE)) as TriColorChannels;\n const [x, y, z] = transformMatrix(MATRIX_LMS_TO_XYZ, xyzLms, true);\n return [\n 'xyz-d65',\n roundToPrecision(x, HEX),\n roundToPrecision(y, HEX),\n roundToPrecision(z, HEX),\n alpha as number\n ];\n};\n\n/**\n * parse oklch()\n * @param value - oklch color value\n * @param [opt] - options\n * @returns parsed color\n * - ['xyz-d65', x, y, z, alpha], ['oklch', l, c, h, alpha]\n * - '(empty)', NullObject\n */\nexport const parseOklch = (\n value: string,\n opt: Options = {}\n): SpecifiedColorChannels | string | NullObject => {\n if (isString(value)) {\n value = value.trim();\n } else {\n throw new TypeError(`${value} is not a string.`);\n }\n const { format = '', nullable = false } = opt;\n if (!REG_OKLCH.test(value)) {\n const res = resolveInvalidColorValue(format, nullable);\n if (res instanceof NullObject) {\n return res;\n }\n if (isString(res)) {\n return res as string;\n }\n return res as SpecifiedColorChannels;\n }\n const COEF_PCT = 0.4;\n const [, val] = value.match(REG_OKLCH) as MatchedRegExp;\n const [v1, v2, v3, v4 = ''] = val\n .replace('/', ' ')\n .split(/\\s+/) as StringColorChannels;\n let l, c, h;\n if (v1 === NONE) {\n l = 0;\n } else {\n l = v1.endsWith('%') ? parseFloat(v1) / MAX_PCT : parseFloat(v1);\n if (l < 0) {\n l = 0;\n }\n }\n if (v2 === NONE) {\n c = 0;\n } else {\n if (v2.endsWith('%')) {\n c = (parseFloat(v2) * COEF_PCT) / MAX_PCT;\n } else {\n c = parseFloat(v2);\n }\n if (c < 0) {\n c = 0;\n }\n }\n if (v3 === NONE) {\n h = 0;\n } else {\n h = angleToDeg(v3);\n }\n const alpha = parseAlpha(v4);\n if (REG_SPEC.test(format)) {\n return [\n 'oklch',\n v1 === NONE ? v1 : roundToPrecision(l, HEX),\n v2 === NONE ? v2 : roundToPrecision(c, HEX),\n v3 === NONE ? v3 : roundToPrecision(h, HEX),\n v4 === NONE ? v4 : alpha\n ];\n }\n const a = c * Math.cos((h * Math.PI) / DEG_HALF);\n const b = c * Math.sin((h * Math.PI) / DEG_HALF);\n const lms = transformMatrix(MATRIX_OKLAB_TO_LMS, [l, a, b]);\n const xyzLms = lms.map(cc => Math.pow(cc, POW_CUBE)) as TriColorChannels;\n const [x, y, z] = transformMatrix(MATRIX_LMS_TO_XYZ, xyzLms, true);\n return [\n 'xyz-d65',\n roundToPrecision(x, HEX),\n roundToPrecision(y, HEX),\n roundToPrecision(z, HEX),\n alpha\n ];\n};\n\n/**\n * parse color()\n * @param value - color function value\n * @param [opt] - options\n * @returns parsed color\n * - ['xyz-(d50|d65)', x, y, z, alpha], [cs, r, g, b, alpha]\n * - '(empty)', NullObject\n */\nexport const parseColorFunc = (\n value: string,\n opt: Options = {}\n): SpecifiedColorChannels | string | NullObject => {\n if (isString(value)) {\n value = value.trim();\n } else {\n throw new TypeError(`${value} is not a string.`);\n }\n const { colorSpace = '', d50 = false, format = '', nullable = false } = opt;\n if (!REG_FN_COLOR.test(value)) {\n const res = resolveInvalidColorValue(format, nullable);\n if (res instanceof NullObject) {\n return res;\n }\n if (isString(res)) {\n return res as string;\n }\n return res as SpecifiedColorChannels;\n }\n const [, val] = value.match(REG_FN_COLOR) as MatchedRegExp;\n let [cs, v1, v2, v3, v4 = ''] = val\n .replace('/', ' ')\n .split(/\\s+/) as StringColorSpacedChannels;\n let r, g, b;\n if (cs === 'xyz') {\n cs = 'xyz-d65';\n }\n if (v1 === NONE) {\n r = 0;\n } else {\n r = v1.endsWith('%') ? parseFloat(v1) / MAX_PCT : parseFloat(v1);\n }\n if (v2 === NONE) {\n g = 0;\n } else {\n g = v2.endsWith('%') ? parseFloat(v2) / MAX_PCT : parseFloat(v2);\n }\n if (v3 === NONE) {\n b = 0;\n } else {\n b = v3.endsWith('%') ? parseFloat(v3) / MAX_PCT : parseFloat(v3);\n }\n const alpha = parseAlpha(v4);\n if (REG_SPEC.test(format) || (format === VAL_MIX && cs === colorSpace)) {\n return [\n cs,\n v1 === NONE ? v1 : roundToPrecision(r, DEC),\n v2 === NONE ? v2 : roundToPrecision(g, DEC),\n v3 === NONE ? v3 : roundToPrecision(b, DEC),\n v4 === NONE ? v4 : alpha\n ];\n }\n let x = 0;\n let y = 0;\n let z = 0;\n // srgb-linear\n if (cs === 'srgb-linear') {\n [x, y, z] = transformMatrix(MATRIX_L_RGB_TO_XYZ, [r, g, b]);\n if (d50) {\n [x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [x, y, z], true);\n }\n // display-p3\n } else if (cs === 'display-p3') {\n const linearRgb = transformRgbToLinearRgb([\n r * MAX_RGB,\n g * MAX_RGB,\n b * MAX_RGB\n ]);\n [x, y, z] = transformMatrix(MATRIX_P3_TO_XYZ, linearRgb);\n if (d50) {\n [x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [x, y, z], true);\n }\n // rec2020\n } else if (cs === 'rec2020') {\n const ALPHA = 1.09929682680944;\n const BETA = 0.018053968510807;\n const REC_COEF = 0.45;\n const rgb = [r, g, b].map(c => {\n let cl;\n if (c < BETA * REC_COEF * DEC) {\n cl = c / (REC_COEF * DEC);\n } else {\n cl = Math.pow((c + ALPHA - 1) / ALPHA, 1 / REC_COEF);\n }\n return cl;\n }) as TriColorChannels;\n [x, y, z] = transformMatrix(MATRIX_REC2020_TO_XYZ, rgb);\n if (d50) {\n [x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [x, y, z], true);\n }\n // a98-rgb\n } else if (cs === 'a98-rgb') {\n const POW_A98 = 563 / 256;\n const rgb = [r, g, b].map(c => {\n const cl = Math.pow(c, POW_A98);\n return cl;\n }) as TriColorChannels;\n [x, y, z] = transformMatrix(MATRIX_A98_TO_XYZ, rgb);\n if (d50) {\n [x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [x, y, z], true);\n }\n // prophoto-rgb\n } else if (cs === 'prophoto-rgb') {\n const POW_PROPHOTO = 1.8;\n const rgb = [r, g, b].map(c => {\n let cl;\n if (c > 1 / (HEX * DUO)) {\n cl = Math.pow(c, POW_PROPHOTO);\n } else {\n cl = c / HEX;\n }\n return cl;\n }) as TriColorChannels;\n [x, y, z] = transformMatrix(MATRIX_PROPHOTO_TO_XYZ_D50, rgb);\n if (!d50) {\n [x, y, z] = transformMatrix(MATRIX_D50_TO_D65, [x, y, z], true);\n }\n // xyz, xyz-d50, xyz-d65\n } else if (/^xyz(?:-d(?:50|65))?$/.test(cs)) {\n [x, y, z] = [r, g, b];\n if (cs === 'xyz-d50') {\n if (!d50) {\n [x, y, z] = transformMatrix(MATRIX_D50_TO_D65, [x, y, z]);\n }\n } else if (d50) {\n [x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [x, y, z], true);\n }\n // srgb\n } else {\n [x, y, z] = transformRgbToXyz([r * MAX_RGB, g * MAX_RGB, b * MAX_RGB]);\n if (d50) {\n [x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [x, y, z], true);\n }\n }\n return [\n d50 ? 'xyz-d50' : 'xyz-d65',\n roundToPrecision(x, HEX),\n roundToPrecision(y, HEX),\n roundToPrecision(z, HEX),\n format === VAL_MIX && v4 === NONE ? v4 : alpha\n ];\n};\n\n/**\n * parse color value\n * @param value - CSS color value\n * @param [opt] - options\n * @returns parsed color\n * - ['xyz-(d50|d65)', x, y, z, alpha], ['rgb', r, g, b, alpha]\n * - value, '(empty)', NullObject\n */\nexport const parseColorValue = (\n value: string,\n opt: Options = {}\n): SpecifiedColorChannels | string | NullObject => {\n if (isString(value)) {\n value = value.toLowerCase().trim();\n } else {\n throw new TypeError(`${value} is not a string.`);\n }\n const { d50 = false, format = '', nullable = false } = opt;\n if (!REG_COLOR.test(value)) {\n const res = resolveInvalidColorValue(format, nullable);\n if (res instanceof NullObject) {\n return res;\n }\n if (isString(res)) {\n return res as string;\n }\n return res as SpecifiedColorChannels;\n }\n let x = 0;\n let y = 0;\n let z = 0;\n let alpha = 0;\n // complement currentcolor as a missing color\n if (REG_CURRENT.test(value)) {\n if (format === VAL_COMP) {\n return ['rgb', 0, 0, 0, 0];\n }\n if (format === VAL_SPEC) {\n return value;\n }\n // named-color\n } else if (/^[a-z]+$/.test(value)) {\n if (Object.hasOwn(NAMED_COLORS, value)) {\n if (format === VAL_SPEC) {\n return value;\n }\n const [r, g, b] = NAMED_COLORS[\n value as keyof typeof NAMED_COLORS\n ] as TriColorChannels;\n alpha = 1;\n if (format === VAL_COMP) {\n return ['rgb', r, g, b, alpha];\n }\n [x, y, z] = transformRgbToXyz([r, g, b], true);\n if (d50) {\n [x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [x, y, z], true);\n }\n } else {\n switch (format) {\n case VAL_COMP: {\n if (nullable && value !== 'transparent') {\n return new NullObject();\n }\n return ['rgb', 0, 0, 0, 0];\n }\n case VAL_SPEC: {\n if (value === 'transparent') {\n return value;\n }\n return '';\n }\n case VAL_MIX: {\n if (value === 'transparent') {\n return ['rgb', 0, 0, 0, 0];\n }\n return new NullObject();\n }\n default:\n }\n }\n // hex-color\n } else if (value[0] === '#') {\n if (REG_SPEC.test(format)) {\n const rgb = convertHexToRgb(value);\n return ['rgb', ...rgb];\n }\n [x, y, z, alpha] = convertHexToXyz(value);\n if (d50) {\n [x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [x, y, z], true);\n }\n // lab()\n } else if (value.startsWith('lab')) {\n if (REG_SPEC.test(format)) {\n return parseLab(value, opt);\n }\n [, x, y, z, alpha] = parseLab(value) as ComputedColorChannels;\n if (!d50) {\n [x, y, z] = transformMatrix(MATRIX_D50_TO_D65, [x, y, z], true);\n }\n // lch()\n } else if (value.startsWith('lch')) {\n if (REG_SPEC.test(format)) {\n return parseLch(value, opt);\n }\n [, x, y, z, alpha] = parseLch(value) as ComputedColorChannels;\n if (!d50) {\n [x, y, z] = transformMatrix(MATRIX_D50_TO_D65, [x, y, z], true);\n }\n // oklab()\n } else if (value.startsWith('oklab')) {\n if (REG_SPEC.test(format)) {\n return parseOklab(value, opt);\n }\n [, x, y, z, alpha] = parseOklab(value) as ComputedColorChannels;\n if (d50) {\n [x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [x, y, z], true);\n }\n // oklch()\n } else if (value.startsWith('oklch')) {\n if (REG_SPEC.test(format)) {\n return parseOklch(value, opt);\n }\n [, x, y, z, alpha] = parseOklch(value) as ComputedColorChannels;\n if (d50) {\n [x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [x, y, z], true);\n }\n } else {\n let r, g, b;\n // hsl()\n if (value.startsWith('hsl')) {\n [, r, g, b, alpha] = parseHsl(value) as ComputedColorChannels;\n // hwb()\n } else if (value.startsWith('hwb')) {\n [, r, g, b, alpha] = parseHwb(value) as ComputedColorChannels;\n // rgb()\n } else {\n [, r, g, b, alpha] = parseRgb(value, opt) as ComputedColorChannels;\n }\n if (REG_SPEC.test(format)) {\n return ['rgb', Math.round(r), Math.round(g), Math.round(b), alpha];\n }\n [x, y, z] = transformRgbToXyz([r, g, b]);\n if (d50) {\n [x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [x, y, z], true);\n }\n }\n return [\n d50 ? 'xyz-d50' : 'xyz-d65',\n roundToPrecision(x, HEX),\n roundToPrecision(y, HEX),\n roundToPrecision(z, HEX),\n alpha\n ];\n};\n\n/**\n * resolve color value\n * @param value - CSS color value\n * @param [opt] - options\n * @returns resolved color\n * - [cs, v1, v2, v3, alpha], value, '(empty)', NullObject\n */\nexport const resolveColorValue = (\n value: string,\n opt: Options = {}\n): SpecifiedColorChannels | string | NullObject => {\n if (isString(value)) {\n value = value.toLowerCase().trim();\n } else {\n throw new TypeError(`${value} is not a string.`);\n }\n const { colorSpace = '', format = '', nullable = false } = opt;\n const cacheKey: string = createCacheKey(\n {\n namespace: NAMESPACE,\n name: 'resolveColorValue',\n value\n },\n opt\n );\n const cachedResult = getCache(cacheKey);\n if (cachedResult instanceof CacheItem) {\n if (cachedResult.isNull) {\n return cachedResult as NullObject;\n }\n const cachedItem = cachedResult.item;\n if (isString(cachedItem)) {\n return cachedItem as string;\n }\n return cachedItem as SpecifiedColorChannels;\n }\n if (!REG_COLOR.test(value)) {\n const res = resolveInvalidColorValue(format, nullable);\n if (res instanceof NullObject) {\n setCache(cacheKey, null);\n return res;\n }\n setCache(cacheKey, res);\n if (isString(res)) {\n return res as string;\n }\n return res as SpecifiedColorChannels;\n }\n let cs = '';\n let r = 0;\n let g = 0;\n let b = 0;\n let alpha = 0;\n // complement currentcolor as a missing color\n if (REG_CURRENT.test(value)) {\n if (format === VAL_SPEC) {\n setCache(cacheKey, value);\n return value;\n }\n // named-color\n } else if (/^[a-z]+$/.test(value)) {\n if (Object.hasOwn(NAMED_COLORS, value)) {\n if (format === VAL_SPEC) {\n setCache(cacheKey, value);\n return value;\n }\n [r, g, b] = NAMED_COLORS[\n value as keyof typeof NAMED_COLORS\n ] as TriColorChannels;\n alpha = 1;\n } else {\n switch (format) {\n case VAL_SPEC: {\n if (value === 'transparent') {\n setCache(cacheKey, value);\n return value;\n }\n const res = '';\n setCache(cacheKey, res);\n return res;\n }\n case VAL_MIX: {\n if (value === 'transparent') {\n const res: SpecifiedColorChannels = ['rgb', 0, 0, 0, 0];\n setCache(cacheKey, res);\n return res;\n }\n setCache(cacheKey, null);\n return new NullObject();\n }\n case VAL_COMP:\n default: {\n if (nullable && value !== 'transparent') {\n setCache(cacheKey, null);\n return new NullObject();\n }\n const res: SpecifiedColorChannels = ['rgb', 0, 0, 0, 0];\n setCache(cacheKey, res);\n return res;\n }\n }\n }\n // hex-color\n } else if (value[0] === '#') {\n [r, g, b, alpha] = convertHexToRgb(value);\n // hsl()\n } else if (value.startsWith('hsl')) {\n [, r, g, b, alpha] = parseHsl(value, opt) as ComputedColorChannels;\n // hwb()\n } else if (value.startsWith('hwb')) {\n [, r, g, b, alpha] = parseHwb(value, opt) as ComputedColorChannels;\n // lab(), lch()\n } else if (/^l(?:ab|ch)/.test(value)) {\n let x, y, z;\n if (value.startsWith('lab')) {\n [cs, x, y, z, alpha] = parseLab(value, opt) as ComputedColorChannels;\n } else {\n [cs, x, y, z, alpha] = parseLch(value, opt) as ComputedColorChannels;\n }\n if (REG_SPEC.test(format)) {\n const res: SpecifiedColorChannels = [cs, x, y, z, alpha];\n setCache(cacheKey, res);\n return res;\n }\n [r, g, b] = transformXyzD50ToRgb([x, y, z]);\n // oklab(), oklch()\n } else if (/^okl(?:ab|ch)/.test(value)) {\n let x, y, z;\n if (value.startsWith('oklab')) {\n [cs, x, y, z, alpha] = parseOklab(value, opt) as ComputedColorChannels;\n } else {\n [cs, x, y, z, alpha] = parseOklch(value, opt) as ComputedColorChannels;\n }\n if (REG_SPEC.test(format)) {\n const res: SpecifiedColorChannels = [cs, x, y, z, alpha];\n setCache(cacheKey, res);\n return res;\n }\n [r, g, b] = transformXyzToRgb([x, y, z]);\n // rgb()\n } else {\n [, r, g, b, alpha] = parseRgb(value, opt) as ComputedColorChannels;\n }\n if (format === VAL_MIX && colorSpace === 'srgb') {\n const res: SpecifiedColorChannels = [\n 'srgb',\n r / MAX_RGB,\n g / MAX_RGB,\n b / MAX_RGB,\n alpha\n ];\n setCache(cacheKey, res);\n return res;\n }\n const res: SpecifiedColorChannels = [\n 'rgb',\n Math.round(r),\n Math.round(g),\n Math.round(b),\n alpha\n ];\n setCache(cacheKey, res);\n return res;\n};\n\n/**\n * resolve color()\n * @param value - color function value\n * @param [opt] - options\n * @returns resolved color - [cs, v1, v2, v3, alpha], '(empty)', NullObject\n */\nexport const resolveColorFunc = (\n value: string,\n opt: Options = {}\n): SpecifiedColorChannels | string | NullObject => {\n if (isString(value)) {\n value = value.toLowerCase().trim();\n } else {\n throw new TypeError(`${value} is not a string.`);\n }\n const { colorSpace = '', format = '', nullable = false } = opt;\n const cacheKey: string = createCacheKey(\n {\n namespace: NAMESPACE,\n name: 'resolveColorFunc',\n value\n },\n opt\n );\n const cachedResult = getCache(cacheKey);\n if (cachedResult instanceof CacheItem) {\n if (cachedResult.isNull) {\n return cachedResult as NullObject;\n }\n const cachedItem = cachedResult.item;\n if (isString(cachedItem)) {\n return cachedItem as string;\n }\n return cachedItem as SpecifiedColorChannels;\n }\n if (!REG_FN_COLOR.test(value)) {\n const res = resolveInvalidColorValue(format, nullable);\n if (res instanceof NullObject) {\n setCache(cacheKey, null);\n return res;\n }\n setCache(cacheKey, res);\n if (isString(res)) {\n return res as string;\n }\n return res as SpecifiedColorChannels;\n }\n const [cs, v1, v2, v3, v4] = parseColorFunc(\n value,\n opt\n ) as SpecifiedColorChannels;\n if (REG_SPEC.test(format) || (format === VAL_MIX && cs === colorSpace)) {\n const res: SpecifiedColorChannels = [cs, v1, v2, v3, v4];\n setCache(cacheKey, res);\n return res;\n }\n const x = parseFloat(`${v1}`);\n const y = parseFloat(`${v2}`);\n const z = parseFloat(`${v3}`);\n const alpha = parseAlpha(`${v4}`);\n const [r, g, b] = transformXyzToRgb([x, y, z], true);\n const res: SpecifiedColorChannels = ['rgb', r, g, b, alpha];\n setCache(cacheKey, res);\n return res;\n};\n\n/**\n * convert color value to linear rgb\n * @param value - CSS color value\n * @param [opt] - options\n * @returns ColorChannels | NullObject - [r, g, b, alpha] r|g|b|alpha: 0..1\n */\nexport const convertColorToLinearRgb = (\n value: string,\n opt: {\n colorSpace?: string;\n format?: string;\n } = {}\n): ColorChannels | NullObject => {\n if (isString(value)) {\n value = value.trim();\n } else {\n throw new TypeError(`${value} is not a string.`);\n }\n const { colorSpace = '', format = '' } = opt;\n let cs = '';\n let r, g, b, alpha, x, y, z;\n if (format === VAL_MIX) {\n let xyz;\n if (value.startsWith(FN_COLOR)) {\n xyz = parseColorFunc(value, opt);\n } else {\n xyz = parseColorValue(value, opt);\n }\n if (xyz instanceof NullObject) {\n return xyz;\n }\n [cs, x, y, z, alpha] = xyz as ComputedColorChannels;\n if (cs === colorSpace) {\n return [x, y, z, alpha];\n }\n [r, g, b] = transformMatrix(MATRIX_XYZ_TO_L_RGB, [x, y, z], true);\n } else if (value.startsWith(FN_COLOR)) {\n const [, val] = value.match(REG_FN_COLOR) as MatchedRegExp;\n const [cs] = val\n .replace('/', ' ')\n .split(/\\s+/) as StringColorSpacedChannels;\n if (cs === 'srgb-linear') {\n [, r, g, b, alpha] = resolveColorFunc(value, {\n format: VAL_COMP\n }) as ComputedColorChannels;\n } else {\n [, x, y, z, alpha] = parseColorFunc(value) as ComputedColorChannels;\n [r, g, b] = transformMatrix(MATRIX_XYZ_TO_L_RGB, [x, y, z], true);\n }\n } else {\n [, x, y, z, alpha] = parseColorValue(value) as ComputedColorChannels;\n [r, g, b] = transformMatrix(MATRIX_XYZ_TO_L_RGB, [x, y, z], true);\n }\n return [\n Math.min(Math.max(r, 0), 1),\n Math.min(Math.max(g, 0), 1),\n Math.min(Math.max(b, 0), 1),\n alpha\n ];\n};\n\n/**\n * convert color value to rgb\n * @param value - CSS color value\n * @param [opt] - options\n * @returns ColorChannels | NullObject\n * - [r, g, b, alpha] r|g|b: 0..255 alpha: 0..1\n */\nexport const convertColorToRgb = (\n value: string,\n opt: Options = {}\n): ColorChannels | NullObject => {\n if (isString(value)) {\n value = value.trim();\n } else {\n throw new TypeError(`${value} is not a string.`);\n }\n const { format = '' } = opt;\n let r, g, b, alpha;\n if (format === VAL_MIX) {\n let rgb;\n if (value.startsWith(FN_COLOR)) {\n rgb = resolveColorFunc(value, opt);\n } else {\n rgb = resolveColorValue(value, opt);\n }\n if (rgb instanceof NullObject) {\n return rgb;\n }\n [, r, g, b, alpha] = rgb as ComputedColorChannels;\n } else if (value.startsWith(FN_COLOR)) {\n const [, val] = value.match(REG_FN_COLOR) as MatchedRegExp;\n const [cs] = val\n .replace('/', ' ')\n .split(/\\s+/) as StringColorSpacedChannels;\n if (cs === 'srgb') {\n [, r, g, b, alpha] = resolveColorFunc(value, {\n format: VAL_COMP\n }) as ComputedColorChannels;\n r *= MAX_RGB;\n g *= MAX_RGB;\n b *= MAX_RGB;\n } else {\n [, r, g, b, alpha] = resolveColorFunc(value) as ComputedColorChannels;\n }\n } else if (/^(?:ok)?l(?:ab|ch)/.test(value)) {\n [r, g, b, alpha] = convertColorToLinearRgb(value) as ColorChannels;\n [r, g, b] = transformLinearRgbToRgb([r, g, b]);\n } else {\n [, r, g, b, alpha] = resolveColorValue(value, {\n format: VAL_COMP\n }) as ComputedColorChannels;\n }\n return [r, g, b, alpha];\n};\n\n/**\n * convert color value to xyz\n * @param value - CSS color value\n * @param [opt] - options\n * @returns ColorChannels | NullObject - [x, y, z, alpha]\n */\nexport const convertColorToXyz = (\n value: string,\n opt: Options = {}\n): ColorChannels | NullObject => {\n if (isString(value)) {\n value = value.trim();\n } else {\n throw new TypeError(`${value} is not a string.`);\n }\n const { d50 = false, format = '' } = opt;\n let x, y, z, alpha;\n if (format === VAL_MIX) {\n let xyz;\n if (value.startsWith(FN_COLOR)) {\n xyz = parseColorFunc(value, opt);\n } else {\n xyz = parseColorValue(value, opt);\n }\n if (xyz instanceof NullObject) {\n return xyz;\n }\n [, x, y, z, alpha] = xyz as ComputedColorChannels;\n } else if (value.startsWith(FN_COLOR)) {\n const [, val] = value.match(REG_FN_COLOR) as MatchedRegExp;\n const [cs] = val\n .replace('/', ' ')\n .split(/\\s+/) as StringColorSpacedChannels;\n if (d50) {\n if (cs === 'xyz-d50') {\n [, x, y, z, alpha] = resolveColorFunc(value, {\n format: VAL_COMP\n }) as ComputedColorChannels;\n } else {\n [, x, y, z, alpha] = parseColorFunc(\n value,\n opt\n ) as ComputedColorChannels;\n }\n } else if (/^xyz(?:-d65)?$/.test(cs)) {\n [, x, y, z, alpha] = resolveColorFunc(value, {\n format: VAL_COMP\n }) as ComputedColorChannels;\n } else {\n [, x, y, z, alpha] = parseColorFunc(value) as ComputedColorChannels;\n }\n } else {\n [, x, y, z, alpha] = parseColorValue(value, opt) as ComputedColorChannels;\n }\n return [x, y, z, alpha];\n};\n\n/**\n * convert color value to hsl\n * @param value - CSS color value\n * @param [opt] - options\n * @returns ColorChannels | NullObject - [h, s, l, alpha], hue may be powerless\n */\nexport const convertColorToHsl = (\n value: string,\n opt: Options = {}\n): ColorChannels | [number | string, number, number, number] | NullObject => {\n if (isString(value)) {\n value = value.trim();\n } else {\n throw new TypeError(`${value} is not a string.`);\n }\n const { format = '' } = opt;\n let h, s, l, alpha;\n if (REG_HSL.test(value)) {\n [, h, s, l, alpha] = parseHsl(value, {\n format: 'hsl'\n }) as ComputedColorChannels;\n if (format === 'hsl') {\n return [Math.round(h), Math.round(s), Math.round(l), alpha];\n }\n return [h, s, l, alpha];\n }\n let x, y, z;\n if (format === VAL_MIX) {\n let xyz;\n if (value.startsWith(FN_COLOR)) {\n xyz = parseColorFunc(value, opt);\n } else {\n xyz = parseColorValue(value, opt);\n }\n if (xyz instanceof NullObject) {\n return xyz;\n }\n [, x, y, z, alpha] = xyz as ComputedColorChannels;\n } else if (value.startsWith(FN_COLOR)) {\n [, x, y, z, alpha] = parseColorFunc(value) as ComputedColorChannels;\n } else {\n [, x, y, z, alpha] = parseColorValue(value) as ComputedColorChannels;\n }\n [h, s, l] = transformXyzToHsl([x, y, z], true) as TriColorChannels;\n if (format === 'hsl') {\n return [Math.round(h), Math.round(s), Math.round(l), alpha];\n }\n return [format === VAL_MIX && s === 0 ? NONE : h, s, l, alpha];\n};\n\n/**\n * convert color value to hwb\n * @param value - CSS color value\n * @param [opt] - options\n * @returns ColorChannels | NullObject - [h, w, b, alpha], hue may be powerless\n */\nexport const convertColorToHwb = (\n value: string,\n opt: Options = {}\n): ColorChannels | [number | string, number, number, number] | NullObject => {\n if (isString(value)) {\n value = value.trim();\n } else {\n throw new TypeError(`${value} is not a string.`);\n }\n const { format = '' } = opt;\n let h, w, b, alpha;\n if (REG_HWB.test(value)) {\n [, h, w, b, alpha] = parseHwb(value, {\n format: 'hwb'\n }) as ComputedColorChannels;\n if (format === 'hwb') {\n return [Math.round(h), Math.round(w), Math.round(b), alpha];\n }\n return [h, w, b, alpha];\n }\n let x, y, z;\n if (format === VAL_MIX) {\n let xyz;\n if (value.startsWith(FN_COLOR)) {\n xyz = parseColorFunc(value, opt);\n } else {\n xyz = parseColorValue(value, opt);\n }\n if (xyz instanceof NullObject) {\n return xyz;\n }\n [, x, y, z, alpha] = xyz as ComputedColorChannels;\n } else if (value.startsWith(FN_COLOR)) {\n [, x, y, z, alpha] = parseColorFunc(value) as ComputedColorChannels;\n } else {\n [, x, y, z, alpha] = parseColorValue(value) as ComputedColorChannels;\n }\n [h, w, b] = transformXyzToHwb([x, y, z], true) as TriColorChannels;\n if (format === 'hwb') {\n return [Math.round(h), Math.round(w), Math.round(b), alpha];\n }\n return [format === VAL_MIX && w + b >= 100 ? NONE : h, w, b, alpha];\n};\n\n/**\n * convert color value to lab\n * @param value - CSS color value\n * @param [opt] - options\n * @returns ColorChannels | NullObject - [l, a, b, alpha]\n */\nexport const convertColorToLab = (\n value: string,\n opt: Options = {}\n): ColorChannels | NullObject => {\n if (isString(value)) {\n value = value.trim();\n } else {\n throw new TypeError(`${value} is not a string.`);\n }\n const { format = '' } = opt;\n let l, a, b, alpha;\n if (REG_LAB.test(value)) {\n [, l, a, b, alpha] = parseLab(value, {\n format: VAL_COMP\n }) as ComputedColorChannels;\n return [l, a, b, alpha];\n }\n let x, y, z;\n if (format === VAL_MIX) {\n let xyz;\n opt.d50 = true;\n if (value.startsWith(FN_COLOR)) {\n xyz = parseColorFunc(value, opt);\n } else {\n xyz = parseColorValue(value, opt);\n }\n if (xyz instanceof NullObject) {\n return xyz;\n }\n [, x, y, z, alpha] = xyz as ComputedColorChannels;\n } else if (value.startsWith(FN_COLOR)) {\n [, x, y, z, alpha] = parseColorFunc(value, {\n d50: true\n }) as ComputedColorChannels;\n } else {\n [, x, y, z, alpha] = parseColorValue(value, {\n d50: true\n }) as ComputedColorChannels;\n }\n [l, a, b] = transformXyzD50ToLab([x, y, z], true);\n return [l, a, b, alpha];\n};\n\n/**\n * convert color value to lch\n * @param value - CSS color value\n * @param [opt] - options\n * @returns ColorChannels | NullObject - [l, c, h, alpha], hue may be powerless\n */\nexport const convertColorToLch = (\n value: string,\n opt: Options = {}\n): ColorChannels | [number, number, number | string, number] | NullObject => {\n if (isString(value)) {\n value = value.trim();\n } else {\n throw new TypeError(`${value} is not a string.`);\n }\n const { format = '' } = opt;\n let l, c, h, alpha;\n if (REG_LCH.test(value)) {\n [, l, c, h, alpha] = parseLch(value, {\n format: VAL_COMP\n }) as ComputedColorChannels;\n return [l, c, h, alpha];\n }\n let x, y, z;\n if (format === VAL_MIX) {\n let xyz;\n opt.d50 = true;\n if (value.startsWith(FN_COLOR)) {\n xyz = parseColorFunc(value, opt);\n } else {\n xyz = parseColorValue(value, opt);\n }\n if (xyz instanceof NullObject) {\n return xyz;\n }\n [, x, y, z, alpha] = xyz as ComputedColorChannels;\n } else if (value.startsWith(FN_COLOR)) {\n [, x, y, z, alpha] = parseColorFunc(value, {\n d50: true\n }) as ComputedColorChannels;\n } else {\n [, x, y, z, alpha] = parseColorValue(value, {\n d50: true\n }) as ComputedColorChannels;\n }\n [l, c, h] = transformXyzD50ToLch([x, y, z], true);\n return [l, c, format === VAL_MIX && c === 0 ? NONE : h, alpha];\n};\n\n/**\n * convert color value to oklab\n * @param value - CSS color value\n * @param [opt] - options\n * @returns ColorChannels | NullObject - [l, a, b, alpha]\n */\nexport const convertColorToOklab = (\n value: string,\n opt: Options = {}\n): ColorChannels | NullObject => {\n if (isString(value)) {\n value = value.trim();\n } else {\n throw new TypeError(`${value} is not a string.`);\n }\n const { format = '' } = opt;\n let l, a, b, alpha;\n if (REG_OKLAB.test(value)) {\n [, l, a, b, alpha] = parseOklab(value, {\n format: VAL_COMP\n }) as ComputedColorChannels;\n return [l, a, b, alpha];\n }\n let x, y, z;\n if (format === VAL_MIX) {\n let xyz;\n if (value.startsWith(FN_COLOR)) {\n xyz = parseColorFunc(value, opt);\n } else {\n xyz = parseColorValue(value, opt);\n }\n if (xyz instanceof NullObject) {\n return xyz;\n }\n [, x, y, z, alpha] = xyz as ComputedColorChannels;\n } else if (value.startsWith(FN_COLOR)) {\n [, x, y, z, alpha] = parseColorFunc(value) as ComputedColorChannels;\n } else {\n [, x, y, z, alpha] = parseColorValue(value) as ComputedColorChannels;\n }\n [l, a, b] = transformXyzToOklab([x, y, z], true);\n return [l, a, b, alpha];\n};\n\n/**\n * convert color value to oklch\n * @param value - CSS color value\n * @param [opt] - options\n * @returns ColorChannels | NullObject - [l, c, h, alpha], hue may be powerless\n */\nexport const convertColorToOklch = (\n value: string,\n opt: Options = {}\n): ColorChannels | [number, number, number | string, number] | NullObject => {\n if (isString(value)) {\n value = value.trim();\n } else {\n throw new TypeError(`${value} is not a string.`);\n }\n const { format = '' } = opt;\n let l, c, h, alpha;\n if (REG_OKLCH.test(value)) {\n [, l, c, h, alpha] = parseOklch(value, {\n format: VAL_COMP\n }) as ComputedColorChannels;\n return [l, c, h, alpha];\n }\n let x, y, z;\n if (format === VAL_MIX) {\n let xyz;\n if (value.startsWith(FN_COLOR)) {\n xyz = parseColorFunc(value, opt);\n } else {\n xyz = parseColorValue(value, opt);\n }\n if (xyz instanceof NullObject) {\n return xyz;\n }\n [, x, y, z, alpha] = xyz as ComputedColorChannels;\n } else if (value.startsWith(FN_COLOR)) {\n [, x, y, z, alpha] = parseColorFunc(value) as ComputedColorChannels;\n } else {\n [, x, y, z, alpha] = parseColorValue(value) as ComputedColorChannels;\n }\n [l, c, h] = transformXyzToOklch([x, y, z], true) as TriColorChannels;\n return [l, c, format === VAL_MIX && c === 0 ? NONE : h, alpha];\n};\n\n/**\n * resolve color-mix()\n * @param value - color-mix color value\n * @param [opt] - options\n * @returns resolved color - [cs, v1, v2, v3, alpha], '(empty)'\n */\nexport const resolveColorMix = (\n value: string,\n opt: Options = {}\n): SpecifiedColorChannels | string | NullObject => {\n if (isString(value)) {\n value = value.toLowerCase().trim();\n } else {\n throw new TypeError(`${value} is not a string.`);\n }\n const { format = '', nullable = false } = opt;\n const cacheKey: string = createCacheKey(\n {\n namespace: NAMESPACE,\n name: 'resolveColorMix',\n value\n },\n opt\n );\n const cachedResult = getCache(cacheKey);\n if (cachedResult instanceof CacheItem) {\n if (cachedResult.isNull) {\n return cachedResult as NullObject;\n }\n const cachedItem = cachedResult.item;\n if (isString(cachedItem)) {\n return cachedItem as string;\n }\n return cachedItem as SpecifiedColorChannels;\n }\n const nestedItems = [];\n let colorSpace = '';\n let hueArc = '';\n let colorA = '';\n let pctA = '';\n let colorB = '';\n let pctB = '';\n let parsed = false;\n if (!REG_MIX.test(value)) {\n // nested color-mix()\n if (value.startsWith(FN_MIX) && REG_MIX_NEST.test(value)) {\n const regColorSpace = new RegExp(`^(?:${CS_RGB}|${CS_XYZ})$`);\n const items = value.match(REG_MIX_NEST) as RegExpMatchArray;\n for (const item of items) {\n if (item) {\n let val = resolveColorMix(item, {\n format: format === VAL_SPEC ? format : VAL_COMP\n }) as ComputedColorChannels | string;\n // computed value\n if (Array.isArray(val)) {\n const [cs, v1, v2, v3, v4] = val as ComputedColorChannels;\n if (v1 === 0 && v2 === 0 && v3 === 0 && v4 === 0) {\n value = '';\n break;\n }\n if (regColorSpace.test(cs)) {\n if (v4 === 1) {\n val = `color(${cs} ${v1} ${v2} ${v3})`;\n } else {\n val = `color(${cs} ${v1} ${v2} ${v3} / ${v4})`;\n }\n } else if (v4 === 1) {\n val = `${cs}(${v1} ${v2} ${v3})`;\n } else {\n val = `${cs}(${v1} ${v2} ${v3} / ${v4})`;\n }\n } else if (!REG_MIX.test(val)) {\n value = '';\n break;\n }\n nestedItems.push(val);\n value = value.replace(item, val);\n }\n }\n if (!value) {\n const res = cacheInvalidColorValue(cacheKey, format, nullable);\n return res;\n }\n // contains light-dark()\n } else if (\n value.startsWith(FN_MIX) &&\n value.endsWith(')') &&\n value.includes(FN_LIGHT_DARK)\n ) {\n const regColorSpace = new RegExp(`in\\\\s+(${CS_MIX})`);\n const colorParts = value.replace(FN_MIX, '').replace(/\\)$/, '');\n const [csPart = '', partA = '', partB = ''] = splitValue(colorParts, {\n delimiter: ','\n });\n const [colorPartA = '', pctPartA = ''] = splitValue(partA);\n const [colorPartB = '', pctPartB = ''] = splitValue(partB);\n const specifiedColorA = resolveColor(colorPartA, {\n format: VAL_SPEC\n }) as string;\n const specifiedColorB = resolveColor(colorPartB, {\n format: VAL_SPEC\n }) as string;\n if (regColorSpace.test(csPart) && specifiedColorA && specifiedColorB) {\n if (format === VAL_SPEC) {\n const [, cs] = csPart.match(regColorSpace) as MatchedRegExp;\n if (REG_CS_HUE.test(cs)) {\n [, colorSpace, hueArc] = cs.match(REG_CS_HUE) as MatchedRegExp;\n } else {\n colorSpace = cs;\n }\n colorA = specifiedColorA;\n if (pctPartA) {\n pctA = pctPartA;\n }\n colorB = specifiedColorB;\n if (pctPartB) {\n pctB = pctPartB;\n }\n value = value\n .replace(colorPartA, specifiedColorA)\n .replace(colorPartB, specifiedColorB);\n parsed = true;\n } else {\n const resolvedColorA = resolveColor(colorPartA, opt);\n const resolvedColorB = resolveColor(colorPartB, opt);\n if (isString(resolvedColorA) && isString(resolvedColorB)) {\n value = value\n .replace(colorPartA, resolvedColorA)\n .replace(colorPartB, resolvedColorB);\n }\n }\n } else {\n const res = cacheInvalidColorValue(cacheKey, format, nullable);\n return res;\n }\n } else {\n const res = cacheInvalidColorValue(cacheKey, format, nullable);\n return res;\n }\n }\n if (nestedItems.length && format === VAL_SPEC) {\n const regColorSpace = new RegExp(`^color-mix\\\\(\\\\s*in\\\\s+(${CS_MIX})\\\\s*,`);\n const [, cs] = value.match(regColorSpace) as MatchedRegExp;\n if (REG_CS_HUE.test(cs)) {\n [, colorSpace, hueArc] = cs.match(REG_CS_HUE) as MatchedRegExp;\n } else {\n colorSpace = cs;\n }\n if (nestedItems.length === 2) {\n let [itemA, itemB] = nestedItems as [string, string];\n itemA = itemA.replace(/(?=[()])/g, '\\\\');\n itemB = itemB.replace(/(?=[()])/g, '\\\\');\n const regA = new RegExp(`(${itemA})(?:\\\\s+(${PCT}))?`);\n const regB = new RegExp(`(${itemB})(?:\\\\s+(${PCT}))?`);\n [, colorA, pctA] = value.match(regA) as MatchedRegExp;\n [, colorB, pctB] = value.match(regB) as MatchedRegExp;\n } else {\n let [item] = nestedItems as [string];\n item = item.replace(/(?=[()])/g, '\\\\');\n const itemPart = `${item}(?:\\\\s+${PCT})?`;\n const itemPartCapt = `(${item})(?:\\\\s+(${PCT}))?`;\n const regItemPart = new RegExp(`^${itemPartCapt}$`);\n const regLastItem = new RegExp(`${itemPartCapt}\\\\s*\\\\)$`);\n const regColorPart = new RegExp(`^(${SYN_COLOR_TYPE})(?:\\\\s+(${PCT}))?$`);\n // item is at the end\n if (regLastItem.test(value)) {\n const reg = new RegExp(\n `(${SYN_MIX_PART})\\\\s*,\\\\s*(${itemPart})\\\\s*\\\\)$`\n );\n const [, colorPartA, colorPartB] = value.match(reg) as MatchedRegExp;\n [, colorA, pctA] = colorPartA.match(regColorPart) as MatchedRegExp;\n [, colorB, pctB] = colorPartB.match(regItemPart) as MatchedRegExp;\n } else {\n const reg = new RegExp(\n `(${itemPart})\\\\s*,\\\\s*(${SYN_MIX_PART})\\\\s*\\\\)$`\n );\n const [, colorPartA, colorPartB] = value.match(reg) as MatchedRegExp;\n [, colorA, pctA] = colorPartA.match(regItemPart) as MatchedRegExp;\n [, colorB, pctB] = colorPartB.match(regColorPart) as MatchedRegExp;\n }\n }\n } else if (!parsed) {\n const [, cs, colorPartA, colorPartB] = value.match(\n REG_MIX_CAPT\n ) as MatchedRegExp;\n const reg = new RegExp(`^(${SYN_COLOR_TYPE})(?:\\\\s+(${PCT}))?$`);\n [, colorA, pctA] = colorPartA.match(reg) as MatchedRegExp;\n [, colorB, pctB] = colorPartB.match(reg) as MatchedRegExp;\n if (REG_CS_HUE.test(cs)) {\n [, colorSpace, hueArc] = cs.match(REG_CS_HUE) as MatchedRegExp;\n } else {\n colorSpace = cs;\n }\n }\n // normalize percentages and set multipler\n let pA, pB, m;\n if (pctA && pctB) {\n const p1 = parseFloat(pctA) / MAX_PCT;\n const p2 = parseFloat(pctB) / MAX_PCT;\n if (p1 < 0 || p1 > 1 || p2 < 0 || p2 > 1 || (p1 === 0 && p2 === 0)) {\n const res = cacheInvalidColorValue(cacheKey, format, nullable);\n return res;\n }\n const factor = p1 + p2;\n pA = p1 / factor;\n pB = p2 / factor;\n m = factor < 1 ? factor : 1;\n } else {\n if (pctA) {\n pA = parseFloat(pctA) / MAX_PCT;\n if (pA < 0 || pA > 1) {\n const res = cacheInvalidColorValue(cacheKey, format, nullable);\n return res;\n }\n pB = 1 - pA;\n } else if (pctB) {\n pB = parseFloat(pctB) / MAX_PCT;\n if (pB < 0 || pB > 1) {\n const res = cacheInvalidColorValue(cacheKey, format, nullable);\n return res;\n }\n pA = 1 - pB;\n } else {\n pA = HALF;\n pB = HALF;\n }\n m = 1;\n }\n if (colorSpace === 'xyz') {\n colorSpace = 'xyz-d65';\n }\n // specified value\n if (format === VAL_SPEC) {\n let valueA = '';\n let valueB = '';\n if (colorA.startsWith(FN_MIX) || colorA.startsWith(FN_LIGHT_DARK)) {\n valueA = colorA;\n } else if (colorA.startsWith(FN_COLOR)) {\n const [cs, v1, v2, v3, v4] = parseColorFunc(\n colorA,\n opt\n ) as SpecifiedColorChannels;\n if (v4 === 1) {\n valueA = `color(${cs} ${v1} ${v2} ${v3})`;\n } else {\n valueA = `color(${cs} ${v1} ${v2} ${v3} / ${v4})`;\n }\n } else {\n const val = parseColorValue(colorA, opt);\n if (Array.isArray(val)) {\n const [cs, v1, v2, v3, v4] = val;\n if (v4 === 1) {\n if (cs === 'rgb') {\n valueA = `${cs}(${v1}, ${v2}, ${v3})`;\n } else {\n valueA = `${cs}(${v1} ${v2} ${v3})`;\n }\n } else if (cs === 'rgb') {\n valueA = `${cs}a(${v1}, ${v2}, ${v3}, ${v4})`;\n } else {\n valueA = `${cs}(${v1} ${v2} ${v3} / ${v4})`;\n }\n } else {\n if (!isString(val) || !val) {\n setCache(cacheKey, '');\n return '';\n }\n valueA = val;\n }\n }\n if (colorB.startsWith(FN_MIX) || colorB.startsWith(FN_LIGHT_DARK)) {\n valueB = colorB;\n } else if (colorB.startsWith(FN_COLOR)) {\n const [cs, v1, v2, v3, v4] = parseColorFunc(\n colorB,\n opt\n ) as SpecifiedColorChannels;\n if (v4 === 1) {\n valueB = `color(${cs} ${v1} ${v2} ${v3})`;\n } else {\n valueB = `color(${cs} ${v1} ${v2} ${v3} / ${v4})`;\n }\n } else {\n const val = parseColorValue(colorB, opt);\n if (Array.isArray(val)) {\n const [cs, v1, v2, v3, v4] = val;\n if (v4 === 1) {\n if (cs === 'rgb') {\n valueB = `${cs}(${v1}, ${v2}, ${v3})`;\n } else {\n valueB = `${cs}(${v1} ${v2} ${v3})`;\n }\n } else if (cs === 'rgb') {\n valueB = `${cs}a(${v1}, ${v2}, ${v3}, ${v4})`;\n } else {\n valueB = `${cs}(${v1} ${v2} ${v3} / ${v4})`;\n }\n } else {\n if (!isString(val) || !val) {\n setCache(cacheKey, '');\n return '';\n }\n valueB = val;\n }\n }\n if (pctA && pctB) {\n valueA += ` ${parseFloat(pctA)}%`;\n valueB += ` ${parseFloat(pctB)}%`;\n } else if (pctA) {\n const pA = parseFloat(pctA);\n if (pA !== MAX_PCT * HALF) {\n valueA += ` ${pA}%`;\n }\n } else if (pctB) {\n const pA = MAX_PCT - parseFloat(pctB);\n if (pA !== MAX_PCT * HALF) {\n valueA += ` ${pA}%`;\n }\n }\n if (hueArc) {\n const res = `color-mix(in ${colorSpace} ${hueArc} hue, ${valueA}, ${valueB})`;\n setCache(cacheKey, res);\n return res;\n } else {\n const res = `color-mix(in ${colorSpace}, ${valueA}, ${valueB})`;\n setCache(cacheKey, res);\n return res;\n }\n }\n let r = 0;\n let g = 0;\n let b = 0;\n let alpha = 0;\n // in srgb, srgb-linear\n if (/^srgb(?:-linear)?$/.test(colorSpace)) {\n let rgbA, rgbB;\n if (colorSpace === 'srgb') {\n if (REG_CURRENT.test(colorA)) {\n rgbA = [NONE, NONE, NONE, NONE];\n } else {\n rgbA = convertColorToRgb(colorA, {\n colorSpace,\n format: VAL_MIX\n });\n }\n if (REG_CURRENT.test(colorB)) {\n rgbB = [NONE, NONE, NONE, NONE];\n } else {\n rgbB = convertColorToRgb(colorB, {\n colorSpace,\n format: VAL_MIX\n });\n }\n } else {\n if (REG_CURRENT.test(colorA)) {\n rgbA = [NONE, NONE, NONE, NONE];\n } else {\n rgbA = convertColorToLinearRgb(colorA, {\n colorSpace,\n format: VAL_MIX\n });\n }\n if (REG_CURRENT.test(colorB)) {\n rgbB = [NONE, NONE, NONE, NONE];\n } else {\n rgbB = convertColorToLinearRgb(colorB, {\n colorSpace,\n format: VAL_MIX\n });\n }\n }\n if (rgbA instanceof NullObject || rgbB instanceof NullObject) {\n const res = cacheInvalidColorValue(cacheKey, format, nullable);\n return res;\n }\n const [rrA, ggA, bbA, aaA] = rgbA as NumStrColorChannels;\n const [rrB, ggB, bbB, aaB] = rgbB as NumStrColorChannels;\n const rNone = rrA === NONE && rrB === NONE;\n const gNone = ggA === NONE && ggB === NONE;\n const bNone = bbA === NONE && bbB === NONE;\n const alphaNone = aaA === NONE && aaB === NONE;\n const [[rA, gA, bA, alphaA], [rB, gB, bB, alphaB]] =\n normalizeColorComponents(\n [rrA, ggA, bbA, aaA],\n [rrB, ggB, bbB, aaB],\n true\n );\n const factorA = alphaA * pA;\n const factorB = alphaB * pB;\n alpha = factorA + factorB;\n if (alpha === 0) {\n r = rA * pA + rB * pB;\n g = gA * pA + gB * pB;\n b = bA * pA + bB * pB;\n } else {\n r = (rA * factorA + rB * factorB) / alpha;\n g = (gA * factorA + gB * factorB) / alpha;\n b = (bA * factorA + bB * factorB) / alpha;\n alpha = parseFloat(alpha.toFixed(3));\n }\n if (format === VAL_COMP) {\n const res: SpecifiedColorChannels = [\n colorSpace,\n rNone ? NONE : roundToPrecision(r, HEX),\n gNone ? NONE : roundToPrecision(g, HEX),\n bNone ? NONE : roundToPrecision(b, HEX),\n alphaNone ? NONE : alpha * m\n ];\n setCache(cacheKey, res);\n return res;\n }\n r *= MAX_RGB;\n g *= MAX_RGB;\n b *= MAX_RGB;\n // in xyz, xyz-d65, xyz-d50\n } else if (REG_CS_XYZ.test(colorSpace)) {\n let xyzA, xyzB;\n if (REG_CURRENT.test(colorA)) {\n xyzA = [NONE, NONE, NONE, NONE];\n } else {\n xyzA = convertColorToXyz(colorA, {\n colorSpace,\n d50: colorSpace === 'xyz-d50',\n format: VAL_MIX\n });\n }\n if (REG_CURRENT.test(colorB)) {\n xyzB = [NONE, NONE, NONE, NONE];\n } else {\n xyzB = convertColorToXyz(colorB, {\n colorSpace,\n d50: colorSpace === 'xyz-d50',\n format: VAL_MIX\n });\n }\n if (xyzA instanceof NullObject || xyzB instanceof NullObject) {\n const res = cacheInvalidColorValue(cacheKey, format, nullable);\n return res;\n }\n const [xxA, yyA, zzA, aaA] = xyzA;\n const [xxB, yyB, zzB, aaB] = xyzB;\n const xNone = xxA === NONE && xxB === NONE;\n const yNone = yyA === NONE && yyB === NONE;\n const zNone = zzA === NONE && zzB === NONE;\n const alphaNone = aaA === NONE && aaB === NONE;\n const [[xA, yA, zA, alphaA], [xB, yB, zB, alphaB]] =\n normalizeColorComponents(\n [xxA, yyA, zzA, aaA],\n [xxB, yyB, zzB, aaB],\n true\n );\n const factorA = alphaA * pA;\n const factorB = alphaB * pB;\n alpha = factorA + factorB;\n let x, y, z;\n if (alpha === 0) {\n x = xA * pA + xB * pB;\n y = yA * pA + yB * pB;\n z = zA * pA + zB * pB;\n } else {\n x = (xA * factorA + xB * factorB) / alpha;\n y = (yA * factorA + yB * factorB) / alpha;\n z = (zA * factorA + zB * factorB) / alpha;\n alpha = parseFloat(alpha.toFixed(3));\n }\n if (format === VAL_COMP) {\n const res: SpecifiedColorChannels = [\n colorSpace,\n xNone ? NONE : roundToPrecision(x, HEX),\n yNone ? NONE : roundToPrecision(y, HEX),\n zNone ? NONE : roundToPrecision(z, HEX),\n alphaNone ? NONE : alpha * m\n ];\n setCache(cacheKey, res);\n return res;\n }\n if (colorSpace === 'xyz-d50') {\n [r, g, b] = transformXyzD50ToRgb([x, y, z], true);\n } else {\n [r, g, b] = transformXyzToRgb([x, y, z], true);\n }\n // in hsl, hwb\n } else if (/^h(?:sl|wb)$/.test(colorSpace)) {\n let hslA, hslB;\n if (colorSpace === 'hsl') {\n if (REG_CURRENT.test(colorA)) {\n hslA = [NONE, NONE, NONE, NONE];\n } else {\n hslA = convertColorToHsl(colorA, {\n colorSpace,\n format: VAL_MIX\n });\n }\n if (REG_CURRENT.test(colorB)) {\n hslB = [NONE, NONE, NONE, NONE];\n } else {\n hslB = convertColorToHsl(colorB, {\n colorSpace,\n format: VAL_MIX\n });\n }\n } else {\n if (REG_CURRENT.test(colorA)) {\n hslA = [NONE, NONE, NONE, NONE];\n } else {\n hslA = convertColorToHwb(colorA, {\n colorSpace,\n format: VAL_MIX\n });\n }\n if (REG_CURRENT.test(colorB)) {\n hslB = [NONE, NONE, NONE, NONE];\n } else {\n hslB = convertColorToHwb(colorB, {\n colorSpace,\n format: VAL_MIX\n });\n }\n }\n if (hslA instanceof NullObject || hslB instanceof NullObject) {\n const res = cacheInvalidColorValue(cacheKey, format, nullable);\n return res;\n }\n const [hhA, ssA, llA, aaA] = hslA;\n const [hhB, ssB, llB, aaB] = hslB;\n const alphaNone = aaA === NONE && aaB === NONE;\n let [[hA, sA, lA, alphaA], [hB, sB, lB, alphaB]] = normalizeColorComponents(\n [hhA, ssA, llA, aaA],\n [hhB, ssB, llB, aaB],\n true\n );\n if (hueArc) {\n [hA, hB] = interpolateHue(hA, hB, hueArc);\n }\n const factorA = alphaA * pA;\n const factorB = alphaB * pB;\n alpha = factorA + factorB;\n const h = (hA * pA + hB * pB) % DEG;\n let s, l;\n if (alpha === 0) {\n s = sA * pA + sB * pB;\n l = lA * pA + lB * pB;\n } else {\n s = (sA * factorA + sB * factorB) / alpha;\n l = (lA * factorA + lB * factorB) / alpha;\n alpha = parseFloat(alpha.toFixed(3));\n }\n [r, g, b] = convertColorToRgb(\n `${colorSpace}(${h} ${s} ${l})`\n ) as ColorChannels;\n if (format === VAL_COMP) {\n const res: SpecifiedColorChannels = [\n 'srgb',\n roundToPrecision(r / MAX_RGB, HEX),\n roundToPrecision(g / MAX_RGB, HEX),\n roundToPrecision(b / MAX_RGB, HEX),\n alphaNone ? NONE : alpha * m\n ];\n setCache(cacheKey, res);\n return res;\n }\n // in lch, oklch\n } else if (/^(?:ok)?lch$/.test(colorSpace)) {\n let lchA, lchB;\n if (colorSpace === 'lch') {\n if (REG_CURRENT.test(colorA)) {\n lchA = [NONE, NONE, NONE, NONE];\n } else {\n lchA = convertColorToLch(colorA, {\n colorSpace,\n format: VAL_MIX\n });\n }\n if (REG_CURRENT.test(colorB)) {\n lchB = [NONE, NONE, NONE, NONE];\n } else {\n lchB = convertColorToLch(colorB, {\n colorSpace,\n format: VAL_MIX\n });\n }\n } else {\n if (REG_CURRENT.test(colorA)) {\n lchA = [NONE, NONE, NONE, NONE];\n } else {\n lchA = convertColorToOklch(colorA, {\n colorSpace,\n format: VAL_MIX\n });\n }\n if (REG_CURRENT.test(colorB)) {\n lchB = [NONE, NONE, NONE, NONE];\n } else {\n lchB = convertColorToOklch(colorB, {\n colorSpace,\n format: VAL_MIX\n });\n }\n }\n if (lchA instanceof NullObject || lchB instanceof NullObject) {\n const res = cacheInvalidColorValue(cacheKey, format, nullable);\n return res;\n }\n const [llA, ccA, hhA, aaA] = lchA;\n const [llB, ccB, hhB, aaB] = lchB;\n const lNone = llA === NONE && llB === NONE;\n const cNone = ccA === NONE && ccB === NONE;\n const hNone = hhA === NONE && hhB === NONE;\n const alphaNone = aaA === NONE && aaB === NONE;\n let [[lA, cA, hA, alphaA], [lB, cB, hB, alphaB]] = normalizeColorComponents(\n [llA, ccA, hhA, aaA],\n [llB, ccB, hhB, aaB],\n true\n );\n if (hueArc) {\n [hA, hB] = interpolateHue(hA, hB, hueArc);\n }\n const factorA = alphaA * pA;\n const factorB = alphaB * pB;\n alpha = factorA + factorB;\n const h = (hA * pA + hB * pB) % DEG;\n let l, c;\n if (alpha === 0) {\n l = lA * pA + lB * pB;\n c = cA * pA + cB * pB;\n } else {\n l = (lA * factorA + lB * factorB) / alpha;\n c = (cA * factorA + cB * factorB) / alpha;\n alpha = parseFloat(alpha.toFixed(3));\n }\n if (format === VAL_COMP) {\n const res: SpecifiedColorChannels = [\n colorSpace,\n lNone ? NONE : roundToPrecision(l, HEX),\n cNone ? NONE : roundToPrecision(c, HEX),\n hNone ? NONE : roundToPrecision(h, HEX),\n alphaNone ? NONE : alpha * m\n ];\n setCache(cacheKey, res);\n return res;\n }\n [, r, g, b] = resolveColorValue(\n `${colorSpace}(${l} ${c} ${h})`\n ) as ComputedColorChannels;\n // in lab, oklab\n } else {\n let labA, labB;\n if (colorSpace === 'lab') {\n if (REG_CURRENT.test(colorA)) {\n labA = [NONE, NONE, NONE, NONE];\n } else {\n labA = convertColorToLab(colorA, {\n colorSpace,\n format: VAL_MIX\n });\n }\n if (REG_CURRENT.test(colorB)) {\n labB = [NONE, NONE, NONE, NONE];\n } else {\n labB = convertColorToLab(colorB, {\n colorSpace,\n format: VAL_MIX\n });\n }\n } else {\n if (REG_CURRENT.test(colorA)) {\n labA = [NONE, NONE, NONE, NONE];\n } else {\n labA = convertColorToOklab(colorA, {\n colorSpace,\n format: VAL_MIX\n });\n }\n if (REG_CURRENT.test(colorB)) {\n labB = [NONE, NONE, NONE, NONE];\n } else {\n labB = convertColorToOklab(colorB, {\n colorSpace,\n format: VAL_MIX\n });\n }\n }\n if (labA instanceof NullObject || labB instanceof NullObject) {\n const res = cacheInvalidColorValue(cacheKey, format, nullable);\n return res;\n }\n const [llA, aaA, bbA, alA] = labA;\n const [llB, aaB, bbB, alB] = labB;\n const lNone = llA === NONE && llB === NONE;\n const aNone = aaA === NONE && aaB === NONE;\n const bNone = bbA === NONE && bbB === NONE;\n const alphaNone = alA === NONE && alB === NONE;\n const [[lA, aA, bA, alphaA], [lB, aB, bB, alphaB]] =\n normalizeColorComponents(\n [llA, aaA, bbA, alA],\n [llB, aaB, bbB, alB],\n true\n );\n const factorA = alphaA * pA;\n const factorB = alphaB * pB;\n alpha = factorA + factorB;\n let l, aO, bO;\n if (alpha === 0) {\n l = lA * pA + lB * pB;\n aO = aA * pA + aB * pB;\n bO = bA * pA + bB * pB;\n } else {\n l = (lA * factorA + lB * factorB) / alpha;\n aO = (aA * factorA + aB * factorB) / alpha;\n bO = (bA * factorA + bB * factorB) / alpha;\n alpha = parseFloat(alpha.toFixed(3));\n }\n if (format === VAL_COMP) {\n const res: SpecifiedColorChannels = [\n colorSpace,\n lNone ? NONE : roundToPrecision(l, HEX),\n aNone ? NONE : roundToPrecision(aO, HEX),\n bNone ? NONE : roundToPrecision(bO, HEX),\n alphaNone ? NONE : alpha * m\n ];\n setCache(cacheKey, res);\n return res;\n }\n [, r, g, b] = resolveColorValue(\n `${colorSpace}(${l} ${aO} ${bO})`\n ) as ComputedColorChannels;\n }\n const res: SpecifiedColorChannels = [\n 'rgb',\n Math.round(r),\n Math.round(g),\n Math.round(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AClC;EACA,KAAK,MAAM,EAAE;EACb,KAAK,MAAM,EAAE;EACb,KAAK,MAAM,EAAE;EACb,YAAY,QAAQ,GAAG,QAAQ,EAAE,CAAC;EACnC;AACD,UAAS,UAAU,IAAI;AACvB,QAAO"} \ No newline at end of file diff --git a/node_modules/@asamuzakjp/css-color/dist/esm/js/common.d.ts b/node_modules/@asamuzakjp/css-color/dist/esm/js/common.d.ts new file mode 100644 index 00000000..6039ef34 --- /dev/null +++ b/node_modules/@asamuzakjp/css-color/dist/esm/js/common.d.ts @@ -0,0 +1,21 @@ +/** + * common + */ +/** + * get type + * @param o - object to check + * @returns type of object + */ +export declare const getType: (o: unknown) => string; +/** + * is string + * @param o - object to check + * @returns result + */ +export declare const isString: (o: unknown) => o is string; +/** + * is string or number + * @param o - object to check + * @returns result + */ +export declare const isStringOrNumber: (o: unknown) => boolean; diff --git a/node_modules/@asamuzakjp/css-color/dist/esm/js/common.js b/node_modules/@asamuzakjp/css-color/dist/esm/js/common.js new file mode 100644 index 00000000..dec91c64 --- /dev/null +++ b/node_modules/@asamuzakjp/css-color/dist/esm/js/common.js @@ -0,0 +1,17 @@ +//#region src/js/common.ts +/** +* is string +* @param o - object to check +* @returns result +*/ +var isString = (o) => typeof o === "string" || o instanceof String; +/** +* is string or number +* @param o - object to check +* @returns result +*/ +var isStringOrNumber = (o) => isString(o) || typeof o === "number"; +//#endregion +export { isString, isStringOrNumber }; + +//# sourceMappingURL=common.js.map \ No newline at end of file diff --git a/node_modules/@asamuzakjp/css-color/dist/esm/js/common.js.map b/node_modules/@asamuzakjp/css-color/dist/esm/js/common.js.map new file mode 100644 index 00000000..0a8abaac --- /dev/null +++ b/node_modules/@asamuzakjp/css-color/dist/esm/js/common.js.map @@ -0,0 +1 @@ +{"version":3,"file":"common.js","names":[],"sources":["../../../src/js/common.ts"],"sourcesContent":["/**\n * common\n */\n\n/* numeric constants */\nconst TYPE_FROM = 8;\nconst TYPE_TO = -1;\n\n/**\n * get type\n * @param o - object to check\n * @returns type of object\n */\nexport const getType = (o: unknown): string =>\n Object.prototype.toString.call(o).slice(TYPE_FROM, TYPE_TO);\n\n/**\n * is string\n * @param o - object to check\n * @returns result\n */\nexport const isString = (o: unknown): o is string =>\n typeof o === 'string' || o instanceof String;\n\n/**\n * is string or number\n * @param o - object to check\n * @returns result\n */\nexport const isStringOrNumber = (o: unknown): boolean =>\n isString(o) || typeof o === 'number';\n"],"mappings":";;;;;;AAqBA,IAAa,YAAY,MACvB,OAAO,MAAM,YAAY,aAAa;;;;;;AAOxC,IAAa,oBAAoB,MAC/B,SAAS,EAAE,IAAI,OAAO,MAAM"} \ No newline at end of file diff --git a/node_modules/@asamuzakjp/css-color/dist/esm/js/constant.d.ts b/node_modules/@asamuzakjp/css-color/dist/esm/js/constant.d.ts new file mode 100644 index 00000000..287e617c --- /dev/null +++ b/node_modules/@asamuzakjp/css-color/dist/esm/js/constant.d.ts @@ -0,0 +1,43 @@ +/** + * constant + */ +export declare const ANGLE = "deg|g?rad|turn"; +export declare const LENGTH = "[cm]m|[dls]?v(?:[bhiw]|max|min)|in|p[ctx]|q|r?(?:[cl]h|cap|e[mx]|ic)"; +export declare const NUM = "[+-]?(?:(?:0|[1-9]\\d*)(?:\\.\\d*)?|\\.\\d+)(?:e-?(?:0|[1-9]\\d*))?"; +export declare const NUM_POSITIVE = "\\+?(?:(?:0|[1-9]\\d*)(?:\\.\\d*)?|\\.\\d+)(?:e-?(?:0|[1-9]\\d*))?"; +export declare const NONE = "none"; +export declare const PCT = "[+-]?(?:(?:0|[1-9]\\d*)(?:\\.\\d*)?|\\.\\d+)(?:e-?(?:0|[1-9]\\d*))?%"; +export declare const SYN_FN_CALC = "^(?:calc|clamp|max|min|exp|hypot|log|pow|sqrt|abs|sign|mod|rem|round|a?(?:cos|sin|tan)|atan2)\\(|(?<=[*\\/\\s\\(])(?:calc|clamp|max|min|exp|hypot|log|pow|sqrt|abs|sign|mod|rem|round|a?(?:cos|sin|tan)|atan2)\\("; +export declare const SYN_FN_MATH_START = "^(?:clamp|max|min|exp|hypot|log|pow|sqrt|abs|sign|mod|rem|round|a?(?:cos|sin|tan)|atan2)\\($"; +export declare const SYN_FN_VAR = "^var\\(|(?<=[*\\/\\s\\(])var\\("; +export declare const SYN_FN_VAR_START = "^(?:var|calc|clamp|max|min|exp|hypot|log|pow|sqrt|abs|sign|mod|rem|round|a?(?:cos|sin|tan)|atan2)\\("; +export declare const CS_HUE = "(?:(?:ok)?lch|hsl|hwb)(?:\\s(?:(?:de|in)creasing|longer|shorter)\\shue)?"; +export declare const CS_HUE_CAPT = "((?:ok)?lch|hsl|hwb)(?:\\s((?:de|in)creasing|longer|shorter)\\shue)?"; +export declare const CS_LAB = "(?:ok)?lab"; +export declare const CS_LCH = "(?:ok)?lch"; +export declare const CS_SRGB = "srgb(?:-linear)?"; +export declare const CS_RGB = "(?:a98|prophoto)-rgb|display-p3|rec2020|srgb(?:-linear)?"; +export declare const CS_XYZ = "xyz(?:-d(?:50|65))?"; +export declare const CS_RECT = "(?:ok)?lab|(?:a98|prophoto)-rgb|display-p3|rec2020|srgb(?:-linear)?|xyz(?:-d(?:50|65))?"; +export declare const CS_MIX = "(?:(?:ok)?lch|hsl|hwb)(?:\\s(?:(?:de|in)creasing|longer|shorter)\\shue)?|(?:ok)?lab|(?:a98|prophoto)-rgb|display-p3|rec2020|srgb(?:-linear)?|xyz(?:-d(?:50|65))?"; +export declare const FN_COLOR = "color("; +export declare const FN_LIGHT_DARK = "light-dark("; +export declare const FN_MIX = "color-mix("; +export declare const FN_REL = "(?:(?:ok)?l(?:ab|ch)|color|hsla?|hwb|rgba?)\\(\\s*from\\s+"; +export declare const FN_REL_CAPT = "((?:ok)?l(?:ab|ch)|color|hsla?|hwb|rgba?)\\(\\s*from\\s+"; +export declare const FN_VAR = "var("; +export declare const SYN_FN_COLOR = "(?:(?:a98|prophoto)-rgb|display-p3|rec2020|srgb(?:-linear)?|xyz(?:-d(?:50|65))?)(?:\\s+(?:[+-]?(?:(?:0|[1-9]\\d*)(?:\\.\\d*)?|\\.\\d+)(?:e-?(?:0|[1-9]\\d*))?|[+-]?(?:(?:0|[1-9]\\d*)(?:\\.\\d*)?|\\.\\d+)(?:e-?(?:0|[1-9]\\d*))?%|none)){3}(?:\\s*\\/\\s*(?:[+-]?(?:(?:0|[1-9]\\d*)(?:\\.\\d*)?|\\.\\d+)(?:e-?(?:0|[1-9]\\d*))?|[+-]?(?:(?:0|[1-9]\\d*)(?:\\.\\d*)?|\\.\\d+)(?:e-?(?:0|[1-9]\\d*))?%|none))?"; +export declare const SYN_FN_LIGHT_DARK = "^light-dark\\("; +export declare const SYN_FN_REL = "^(?:(?:ok)?l(?:ab|ch)|color|hsla?|hwb|rgba?)\\(\\s*from\\s+|(?<=[\\s])(?:(?:ok)?l(?:ab|ch)|color|hsla?|hwb|rgba?)\\(\\s*from\\s+"; +export declare const SYN_HSL = "(?:[+-]?(?:(?:0|[1-9]\\d*)(?:\\.\\d*)?|\\.\\d+)(?:e-?(?:0|[1-9]\\d*))?(?:deg|g?rad|turn)?|none)(?:\\s+(?:[+-]?(?:(?:0|[1-9]\\d*)(?:\\.\\d*)?|\\.\\d+)(?:e-?(?:0|[1-9]\\d*))?|[+-]?(?:(?:0|[1-9]\\d*)(?:\\.\\d*)?|\\.\\d+)(?:e-?(?:0|[1-9]\\d*))?%|none)){2}(?:\\s*\\/\\s*(?:[+-]?(?:(?:0|[1-9]\\d*)(?:\\.\\d*)?|\\.\\d+)(?:e-?(?:0|[1-9]\\d*))?|[+-]?(?:(?:0|[1-9]\\d*)(?:\\.\\d*)?|\\.\\d+)(?:e-?(?:0|[1-9]\\d*))?%|none))?"; +export declare const SYN_HSL_LV3 = "[+-]?(?:(?:0|[1-9]\\d*)(?:\\.\\d*)?|\\.\\d+)(?:e-?(?:0|[1-9]\\d*))?(?:deg|g?rad|turn)?(?:\\s*,\\s*[+-]?(?:(?:0|[1-9]\\d*)(?:\\.\\d*)?|\\.\\d+)(?:e-?(?:0|[1-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)(?:\\.\\d*)?|\\.\\d+)(?:e-?(?:0|[1-9]\\d*))?|[+-]?(?:(?:0|[1-9]\\d*)(?:\\.\\d*)?|\\.\\d+)(?:e-?(?:0|[1-9]\\d*))?%|none))?\\s*\\)|color\\(\\s*(?:(?:a98|prophoto)-rgb|display-p3|rec2020|srgb(?:-linear)?|xyz(?:-d(?:50|65))?)(?:\\s+(?:[+-]?(?:(?:0|[1-9]\\d*)(?:\\.\\d*)?|\\.\\d+)(?:e-?(?:0|[1-9]\\d*))?|[+-]?(?:(?:0|[1-9]\\d*)(?:\\.\\d*)?|\\.\\d+)(?:e-?(?:0|[1-9]\\d*))?%|none)){3}(?:\\s*\\/\\s*(?:[+-]?(?:(?:0|[1-9]\\d*)(?:\\.\\d*)?|\\.\\d+)(?:e-?(?:0|[1-9]\\d*))?|[+-]?(?:(?:0|[1-9]\\d*)(?:\\.\\d*)?|\\.\\d+)(?:e-?(?:0|[1-9]\\d*))?%|none))?\\s*\\))(?:\\s+[+-]?(?:(?:0|[1-9]\\d*)(?:\\.\\d*)?|\\.\\d+)(?:e-?(?:0|[1-9]\\d*))?%)?"; +export declare const SYN_MIX = "color-mix\\(\\s*in\\s+(?:(?:(?:ok)?lch|hsl|hwb)(?:\\s(?:(?:de|in)creasing|longer|shorter)\\shue)?|(?:ok)?lab|(?:a98|prophoto)-rgb|display-p3|rec2020|srgb(?:-linear)?|xyz(?:-d(?:50|65))?)\\s*,\\s*(?:[a-z]+|#[\\da-f]{3}|#[\\da-f]{4}|#[\\da-f]{6}|#[\\da-f]{8}|hsla?\\(\\s*[+-]?(?:(?:0|[1-9]\\d*)(?:\\.\\d*)?|\\.\\d+)(?:e-?(?:0|[1-9]\\d*))?(?:deg|g?rad|turn)?(?:\\s*,\\s*[+-]?(?:(?:0|[1-9]\\d*)(?:\\.\\d*)?|\\.\\d+)(?:e-?(?:0|[1-9]\\d*))?%){2}(?:\\s*,\\s*(?:[+-]?(?:(?:0|[1-9]\\d*)(?:\\.\\d*)?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d*))?%|none))?\\s*\\)|(?:ok)?lch\\(\\s*(?:(?:[+-]?(?:(?:0|[1-9]\\d*)(?:\\.\\d*)?|\\.\\d+)(?:e-?(?:0|[1-9]\\d*))?|[+-]?(?:(?:0|[1-9]\\d*)(?:\\.\\d*)?|\\.\\d+)(?:e-?(?:0|[1-9]\\d*))?%|none)\\s+){2}(?:[+-]?(?:(?:0|[1-9]\\d*)(?:\\.\\d*)?|\\.\\d+)(?:e-?(?:0|[1-9]\\d*))?(?:deg|g?rad|turn)?|none)(?:\\s*\\/\\s*(?:[+-]?(?:(?:0|[1-9]\\d*)(?:\\.\\d*)?|\\.\\d+)(?:e-?(?:0|[1-9]\\d*))?|[+-]?(?:(?:0|[1-9]\\d*)(?:\\.\\d*)?|\\.\\d+)(?:e-?(?:0|[1-9]\\d*))?%|none))?\\s*\\)|color\\(\\s*(?:(?:a98|prophoto)-rgb|display-p3|rec2020|srgb(?:-linear)?|xyz(?:-d(?:50|65))?)(?:\\s+(?:[+-]?(?:(?:0|[1-9]\\d*)(?:\\.\\d*)?|\\.\\d+)(?:e-?(?:0|[1-9]\\d*))?|[+-]?(?:(?:0|[1-9]\\d*)(?:\\.\\d*)?|\\.\\d+)(?:e-?(?:0|[1-9]\\d*))?%|none)){3}(?:\\s*\\/\\s*(?:[+-]?(?:(?:0|[1-9]\\d*)(?:\\.\\d*)?|\\.\\d+)(?:e-?(?:0|[1-9]\\d*))?|[+-]?(?:(?:0|[1-9]\\d*)(?:\\.\\d*)?|\\.\\d+)(?:e-?(?:0|[1-9]\\d*))?%|none))?\\s*\\))(?:\\s+[+-]?(?:(?:0|[1-9]\\d*)(?:\\.\\d*)?|\\.\\d+)(?:e-?(?:0|[1-9]\\d*))?%)?\\s*\\)"; +export declare const SYN_MIX_CAPT = "color-mix\\(\\s*in\\s+((?:(?:ok)?lch|hsl|hwb)(?:\\s(?:(?:de|in)creasing|longer|shorter)\\shue)?|(?:ok)?lab|(?:a98|prophoto)-rgb|display-p3|rec2020|srg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\\d+)(?:e-?(?:0|[1-9]\\d*))?|[+-]?(?:(?:0|[1-9]\\d*)(?:\\.\\d*)?|\\.\\d+)(?:e-?(?:0|[1-9]\\d*))?%|none))?\\s*\\))(?:\\s+[+-]?(?:(?:0|[1-9]\\d*)(?:\\.\\d*)?|\\.\\d+)(?:e-?(?:0|[1-9]\\d*))?%)?)\\s*\\)"; +export declare const VAL_COMP = "computedValue"; +export declare const VAL_MIX = "mixValue"; +export declare const VAL_SPEC = "specifiedValue"; diff --git a/node_modules/@asamuzakjp/css-color/dist/esm/js/constant.js b/node_modules/@asamuzakjp/css-color/dist/esm/js/constant.js new file mode 100644 index 00000000..6fed58c0 --- /dev/null +++ b/node_modules/@asamuzakjp/css-color/dist/esm/js/constant.js @@ -0,0 +1,60 @@ +//#region src/js/constant.ts +/** +* constant +*/ +var _DIGIT = "(?:0|[1-9]\\d*)"; +var _MATH = `clamp|max|min|exp|hypot|log|pow|sqrt|abs|sign|mod|rem|round|a?(?:cos|sin|tan)|atan2`; +var _CALC = `calc|${_MATH}`; +var _VAR = `var|${_CALC}`; +var ANGLE = "deg|g?rad|turn"; +var LENGTH = "[cm]m|[dls]?v(?:[bhiw]|max|min)|in|p[ctx]|q|r?(?:[cl]h|cap|e[mx]|ic)"; +var NUM = `[+-]?(?:${_DIGIT}(?:\\.\\d*)?|\\.\\d+)(?:e-?${_DIGIT})?`; +var NUM_POSITIVE = `\\+?(?:${_DIGIT}(?:\\.\\d*)?|\\.\\d+)(?:e-?${_DIGIT})?`; +var NONE = "none"; +var PCT = `${NUM}%`; +var SYN_FN_CALC = `^(?:${_CALC})\\(|(?<=[*\\/\\s\\(])(?:${_CALC})\\(`; +var SYN_FN_MATH_START = `^(?:${_MATH})\\($`; +var SYN_FN_VAR = "^var\\(|(?<=[*\\/\\s\\(])var\\("; +var SYN_FN_VAR_START = `^(?:${_VAR})\\(`; +var _ALPHA = `(?:\\s*\\/\\s*(?:${NUM}|${PCT}|${NONE}))?`; +var _ALPHA_LV3 = `(?:\\s*,\\s*(?:${NUM}|${PCT}))?`; +var _COLOR_FUNC = "(?:ok)?l(?:ab|ch)|color|hsla?|hwb|rgba?"; +var _COLOR_KEY = "[a-z]+|#[\\da-f]{3}|#[\\da-f]{4}|#[\\da-f]{6}|#[\\da-f]{8}"; +var _CS_HUE = "(?:ok)?lch|hsl|hwb"; +var _CS_HUE_ARC = "(?:de|in)creasing|longer|shorter"; +var _NUM_ANGLE = `${NUM}(?:${ANGLE})?`; +var _NUM_ANGLE_NONE = `(?:${NUM}(?:${ANGLE})?|${NONE})`; +var _NUM_PCT_NONE = `(?:${NUM}|${PCT}|${NONE})`; +var CS_HUE = `(?:${_CS_HUE})(?:\\s(?:${_CS_HUE_ARC})\\shue)?`; +var CS_HUE_CAPT = `(${_CS_HUE})(?:\\s(${_CS_HUE_ARC})\\shue)?`; +var CS_LAB = "(?:ok)?lab"; +var CS_LCH = "(?:ok)?lch"; +var CS_RGB = `(?:a98|prophoto)-rgb|display-p3|rec2020|srgb(?:-linear)?`; +var CS_XYZ = "xyz(?:-d(?:50|65))?"; +var CS_RECT = `${CS_LAB}|${CS_RGB}|${CS_XYZ}`; +var CS_MIX = `${CS_HUE}|${CS_RECT}`; +var FN_COLOR = "color("; +var FN_LIGHT_DARK = "light-dark("; +var FN_MIX = "color-mix("; +var FN_REL = `(?:${_COLOR_FUNC})\\(\\s*from\\s+`; +var FN_REL_CAPT = `(${_COLOR_FUNC})\\(\\s*from\\s+`; +var FN_VAR = "var("; +var SYN_FN_COLOR = `(?:${CS_RGB}|${CS_XYZ})(?:\\s+${_NUM_PCT_NONE}){3}${_ALPHA}`; +var SYN_FN_LIGHT_DARK = "^light-dark\\("; +var SYN_FN_REL = `^${FN_REL}|(?<=[\\s])${FN_REL}`; +var SYN_HSL = `${_NUM_ANGLE_NONE}(?:\\s+${_NUM_PCT_NONE}){2}${_ALPHA}`; +var SYN_HSL_LV3 = `${_NUM_ANGLE}(?:\\s*,\\s*${PCT}){2}${_ALPHA_LV3}`; +var SYN_LCH = `(?:${_NUM_PCT_NONE}\\s+){2}${_NUM_ANGLE_NONE}${_ALPHA}`; +var SYN_MOD = `${_NUM_PCT_NONE}(?:\\s+${_NUM_PCT_NONE}){2}${_ALPHA}`; +var SYN_RGB_LV3 = `(?:${NUM}(?:\\s*,\\s*${NUM}){2}|${PCT}(?:\\s*,\\s*${PCT}){2})${_ALPHA_LV3}`; +var SYN_COLOR_TYPE = `${_COLOR_KEY}|hsla?\\(\\s*${SYN_HSL_LV3}\\s*\\)|rgba?\\(\\s*${SYN_RGB_LV3}\\s*\\)|(?:hsla?|hwb)\\(\\s*${SYN_HSL}\\s*\\)|(?:(?:ok)?lab|rgba?)\\(\\s*${SYN_MOD}\\s*\\)|(?:ok)?lch\\(\\s*${SYN_LCH}\\s*\\)|color\\(\\s*${SYN_FN_COLOR}\\s*\\)`; +var SYN_MIX_PART = `(?:${SYN_COLOR_TYPE})(?:\\s+${PCT})?`; +var SYN_MIX = `color-mix\\(\\s*in\\s+(?:${CS_MIX})\\s*,\\s*${SYN_MIX_PART}\\s*,\\s*${SYN_MIX_PART}\\s*\\)`; +var SYN_MIX_CAPT = `color-mix\\(\\s*in\\s+(${CS_MIX})\\s*,\\s*(${SYN_MIX_PART})\\s*,\\s*(${SYN_MIX_PART})\\s*\\)`; +var VAL_COMP = "computedValue"; +var VAL_MIX = "mixValue"; +var VAL_SPEC = "specifiedValue"; +//#endregion +export { ANGLE, CS_HUE, CS_HUE_CAPT, CS_LAB, CS_LCH, CS_MIX, CS_RECT, CS_RGB, CS_XYZ, FN_COLOR, FN_LIGHT_DARK, FN_MIX, FN_REL, FN_REL_CAPT, FN_VAR, LENGTH, NONE, NUM, NUM_POSITIVE, PCT, SYN_COLOR_TYPE, SYN_FN_CALC, SYN_FN_COLOR, SYN_FN_LIGHT_DARK, SYN_FN_MATH_START, SYN_FN_REL, SYN_FN_VAR, SYN_FN_VAR_START, SYN_HSL, SYN_HSL_LV3, SYN_LCH, SYN_MIX, SYN_MIX_CAPT, SYN_MIX_PART, SYN_MOD, SYN_RGB_LV3, VAL_COMP, VAL_MIX, VAL_SPEC }; + +//# sourceMappingURL=constant.js.map \ No newline at end of file diff --git a/node_modules/@asamuzakjp/css-color/dist/esm/js/constant.js.map b/node_modules/@asamuzakjp/css-color/dist/esm/js/constant.js.map new file mode 100644 index 00000000..c540ed0c --- /dev/null +++ b/node_modules/@asamuzakjp/css-color/dist/esm/js/constant.js.map @@ -0,0 +1 @@ +{"version":3,"file":"constant.js","names":[],"sources":["../../../src/js/constant.ts"],"sourcesContent":["/**\n * constant\n */\n\n/* values and units */\nconst _DIGIT = '(?:0|[1-9]\\\\d*)';\nconst _COMPARE = 'clamp|max|min';\nconst _EXPO = 'exp|hypot|log|pow|sqrt';\nconst _SIGN = 'abs|sign';\nconst _STEP = 'mod|rem|round';\nconst _TRIG = 'a?(?:cos|sin|tan)|atan2';\nconst _MATH = `${_COMPARE}|${_EXPO}|${_SIGN}|${_STEP}|${_TRIG}`;\nconst _CALC = `calc|${_MATH}`;\nconst _VAR = `var|${_CALC}`;\nexport const ANGLE = 'deg|g?rad|turn';\nexport const LENGTH =\n '[cm]m|[dls]?v(?:[bhiw]|max|min)|in|p[ctx]|q|r?(?:[cl]h|cap|e[mx]|ic)';\nexport const NUM = `[+-]?(?:${_DIGIT}(?:\\\\.\\\\d*)?|\\\\.\\\\d+)(?:e-?${_DIGIT})?`;\nexport const NUM_POSITIVE = `\\\\+?(?:${_DIGIT}(?:\\\\.\\\\d*)?|\\\\.\\\\d+)(?:e-?${_DIGIT})?`;\nexport const NONE = 'none';\nexport const PCT = `${NUM}%`;\nexport const SYN_FN_CALC = `^(?:${_CALC})\\\\(|(?<=[*\\\\/\\\\s\\\\(])(?:${_CALC})\\\\(`;\nexport const SYN_FN_MATH_START = `^(?:${_MATH})\\\\($`;\nexport const SYN_FN_VAR = '^var\\\\(|(?<=[*\\\\/\\\\s\\\\(])var\\\\(';\nexport const SYN_FN_VAR_START = `^(?:${_VAR})\\\\(`;\n\n/* colors */\nconst _ALPHA = `(?:\\\\s*\\\\/\\\\s*(?:${NUM}|${PCT}|${NONE}))?`;\nconst _ALPHA_LV3 = `(?:\\\\s*,\\\\s*(?:${NUM}|${PCT}))?`;\nconst _COLOR_FUNC = '(?:ok)?l(?:ab|ch)|color|hsla?|hwb|rgba?';\nconst _COLOR_KEY = '[a-z]+|#[\\\\da-f]{3}|#[\\\\da-f]{4}|#[\\\\da-f]{6}|#[\\\\da-f]{8}';\nconst _CS_HUE = '(?:ok)?lch|hsl|hwb';\nconst _CS_HUE_ARC = '(?:de|in)creasing|longer|shorter';\nconst _NUM_ANGLE = `${NUM}(?:${ANGLE})?`;\nconst _NUM_ANGLE_NONE = `(?:${NUM}(?:${ANGLE})?|${NONE})`;\nconst _NUM_PCT_NONE = `(?:${NUM}|${PCT}|${NONE})`;\nexport const CS_HUE = `(?:${_CS_HUE})(?:\\\\s(?:${_CS_HUE_ARC})\\\\shue)?`;\nexport const CS_HUE_CAPT = `(${_CS_HUE})(?:\\\\s(${_CS_HUE_ARC})\\\\shue)?`;\nexport const CS_LAB = '(?:ok)?lab';\nexport const CS_LCH = '(?:ok)?lch';\nexport const CS_SRGB = 'srgb(?:-linear)?';\nexport const CS_RGB = `(?:a98|prophoto)-rgb|display-p3|rec2020|${CS_SRGB}`;\nexport const CS_XYZ = 'xyz(?:-d(?:50|65))?';\nexport const CS_RECT = `${CS_LAB}|${CS_RGB}|${CS_XYZ}`;\nexport const CS_MIX = `${CS_HUE}|${CS_RECT}`;\nexport const FN_COLOR = 'color(';\nexport const FN_LIGHT_DARK = 'light-dark(';\nexport const FN_MIX = 'color-mix(';\nexport const FN_REL = `(?:${_COLOR_FUNC})\\\\(\\\\s*from\\\\s+`;\nexport const FN_REL_CAPT = `(${_COLOR_FUNC})\\\\(\\\\s*from\\\\s+`;\nexport const FN_VAR = 'var(';\nexport const SYN_FN_COLOR = `(?:${CS_RGB}|${CS_XYZ})(?:\\\\s+${_NUM_PCT_NONE}){3}${_ALPHA}`;\nexport const SYN_FN_LIGHT_DARK = '^light-dark\\\\(';\nexport const SYN_FN_REL = `^${FN_REL}|(?<=[\\\\s])${FN_REL}`;\nexport const SYN_HSL = `${_NUM_ANGLE_NONE}(?:\\\\s+${_NUM_PCT_NONE}){2}${_ALPHA}`;\nexport const SYN_HSL_LV3 = `${_NUM_ANGLE}(?:\\\\s*,\\\\s*${PCT}){2}${_ALPHA_LV3}`;\nexport const SYN_LCH = `(?:${_NUM_PCT_NONE}\\\\s+){2}${_NUM_ANGLE_NONE}${_ALPHA}`;\nexport const SYN_MOD = `${_NUM_PCT_NONE}(?:\\\\s+${_NUM_PCT_NONE}){2}${_ALPHA}`;\nexport const SYN_RGB_LV3 = `(?:${NUM}(?:\\\\s*,\\\\s*${NUM}){2}|${PCT}(?:\\\\s*,\\\\s*${PCT}){2})${_ALPHA_LV3}`;\nexport const SYN_COLOR_TYPE = `${_COLOR_KEY}|hsla?\\\\(\\\\s*${SYN_HSL_LV3}\\\\s*\\\\)|rgba?\\\\(\\\\s*${SYN_RGB_LV3}\\\\s*\\\\)|(?:hsla?|hwb)\\\\(\\\\s*${SYN_HSL}\\\\s*\\\\)|(?:(?:ok)?lab|rgba?)\\\\(\\\\s*${SYN_MOD}\\\\s*\\\\)|(?:ok)?lch\\\\(\\\\s*${SYN_LCH}\\\\s*\\\\)|color\\\\(\\\\s*${SYN_FN_COLOR}\\\\s*\\\\)`;\nexport const SYN_MIX_PART = `(?:${SYN_COLOR_TYPE})(?:\\\\s+${PCT})?`;\nexport const SYN_MIX = `color-mix\\\\(\\\\s*in\\\\s+(?:${CS_MIX})\\\\s*,\\\\s*${SYN_MIX_PART}\\\\s*,\\\\s*${SYN_MIX_PART}\\\\s*\\\\)`;\nexport const SYN_MIX_CAPT = `color-mix\\\\(\\\\s*in\\\\s+(${CS_MIX})\\\\s*,\\\\s*(${SYN_MIX_PART})\\\\s*,\\\\s*(${SYN_MIX_PART})\\\\s*\\\\)`;\n\n/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GAAG,OAAO,UAAU,cAAc,MAAM;AACjF,IAAa,oBAAoB;AACjC,IAAa,aAAa,IAAI,OAAO,aAAa;AAClD,IAAa,UAAU,GAAG,gBAAgB,SAAS,cAAc,MAAM;AACvE,IAAa,cAAc,GAAG,WAAW,cAAc,IAAI,MAAM;AACjE,IAAa,UAAU,MAAM,cAAc,UAAU,kBAAkB;AACvE,IAAa,UAAU,GAAG,cAAc,SAAS,cAAc,MAAM;AACrE,IAAa,cAAc,MAAM,IAAI,cAAc,IAAI,OAAO,IAAI,cAAc,IAAI,OAAO;AAC3F,IAAa,iBAAiB,GAAG,WAAW,eAAe,YAAY,sBAAsB,YAAY,8BAA8B,QAAQ,qCAAqC,QAAQ,2BAA2B,QAAQ,sBAAsB,aAAa;AAClQ,IAAa,eAAe,MAAM,eAAe,UAAU,IAAI;AAC/D,IAAa,UAAU,4BAA4B,OAAO,YAAY,aAAa,WAAW,aAAa;AAC3G,IAAa,eAAe,0BAA0B,OAAO,aAAa,aAAa,aAAa,aAAa;AAGjH,IAAa,WAAW;AACxB,IAAa,UAAU;AACvB,IAAa,WAAW"} \ No newline at end of file diff --git a/node_modules/@asamuzakjp/css-color/dist/esm/js/convert.d.ts b/node_modules/@asamuzakjp/css-color/dist/esm/js/convert.d.ts new file mode 100644 index 00000000..fe97f7fc --- /dev/null +++ b/node_modules/@asamuzakjp/css-color/dist/esm/js/convert.d.ts @@ -0,0 +1,99 @@ +import { NullObject } from './cache.js'; +import { ColorChannels, Options } from './typedef.js'; +/** + * pre process + * @param value - CSS color value + * @param [opt] - options + * @returns value + */ +export declare const preProcess: (value: string, opt?: Options) => string | NullObject; +/** + * convert number to hex string + * @param value - numeric value + * @returns hex string: 00..ff + */ +export declare const numberToHex: (value: number) => string; +/** + * convert color to hex + * @param value - CSS color value + * @param [opt] - options + * @param [opt.alpha] - enable alpha channel + * @returns #rrggbb | #rrggbbaa | null + */ +export declare const colorToHex: (value: string, opt?: Options) => string | null; +/** + * convert color to hsl + * @param value - CSS color value + * @param [opt] - options + * @returns ColorChannels - [h, s, l, alpha] + */ +export declare const colorToHsl: (value: string, opt?: Options) => ColorChannels; +/** + * convert color to hwb + * @param value - CSS color value + * @param [opt] - options + * @returns ColorChannels - [h, w, b, alpha] + */ +export declare const colorToHwb: (value: string, opt?: Options) => ColorChannels; +/** + * convert color to lab + * @param value - CSS color value + * @param [opt] - options + * @returns ColorChannels - [l, a, b, alpha] + */ +export declare const colorToLab: (value: string, opt?: Options) => ColorChannels; +/** + * convert color to lch + * @param value - CSS color value + * @param [opt] - options + * @returns ColorChannels - [l, c, h, alpha] + */ +export declare const colorToLch: (value: string, opt?: Options) => ColorChannels; +/** + * convert color to oklab + * @param value - CSS color value + * @param [opt] - options + * @returns ColorChannels - [l, a, b, alpha] + */ +export declare const colorToOklab: (value: string, opt?: Options) => ColorChannels; +/** + * convert color to oklch + * @param value - CSS color value + * @param [opt] - options + * @returns ColorChannels - [l, c, h, alpha] + */ +export declare const colorToOklch: (value: string, opt?: Options) => ColorChannels; +/** + * convert color to rgb + * @param value - CSS color value + * @param [opt] - options + * @returns ColorChannels - [r, g, b, alpha] + */ +export declare const colorToRgb: (value: string, opt?: Options) => ColorChannels; +/** + * convert color to xyz + * @param value - CSS color value + * @param [opt] - options + * @returns ColorChannels - [x, y, z, alpha] + */ +export declare const colorToXyz: (value: string, opt?: Options) => ColorChannels; +/** + * convert color to xyz-d50 + * @param value - CSS color value + * @param [opt] - options + * @returns ColorChannels - [x, y, z, alpha] + */ +export declare const colorToXyzD50: (value: string, opt?: Options) => ColorChannels; +export declare const convert: { + colorToHex: (value: string, opt?: Options) => string | null; + colorToHsl: (value: string, opt?: Options) => ColorChannels; + colorToHwb: (value: string, opt?: Options) => ColorChannels; + colorToLab: (value: string, opt?: Options) => ColorChannels; + colorToLch: (value: string, opt?: Options) => ColorChannels; + colorToOklab: (value: string, opt?: Options) => ColorChannels; + colorToOklch: (value: string, opt?: Options) => ColorChannels; + colorToRgb: (value: string, opt?: Options) => ColorChannels; + colorToXyz: (value: string, opt?: Options) => ColorChannels; + colorToXyzD50: (value: string, opt?: Options) => ColorChannels; + numberToHex: (value: number) => string; +}; diff --git a/node_modules/@asamuzakjp/css-color/dist/esm/js/convert.js b/node_modules/@asamuzakjp/css-color/dist/esm/js/convert.js new file mode 100644 index 00000000..63bb6de1 --- /dev/null +++ b/node_modules/@asamuzakjp/css-color/dist/esm/js/convert.js @@ -0,0 +1,367 @@ +import { isString } from "./common.js"; +import { SYN_FN_CALC, SYN_FN_REL, SYN_FN_VAR, VAL_COMP } from "./constant.js"; +import { convertColorToHsl, convertColorToHwb, convertColorToLab, convertColorToLch, convertColorToOklab, convertColorToOklch, convertColorToRgb, numberToHexString, parseColorFunc, parseColorValue } from "./color.js"; +import { resolveVar } from "./css-var.js"; +import { resolveRelativeColor } from "./relative-color.js"; +import { resolveColor } from "./resolve.js"; +import { CacheItem, NullObject, createCacheKey, getCache, setCache } from "./cache.js"; +import { cssCalc } from "./css-calc.js"; +//#region src/js/convert.ts +/** +* convert +*/ +var NAMESPACE = "convert"; +var REG_FN_CALC = new RegExp(SYN_FN_CALC); +var REG_FN_REL = new RegExp(SYN_FN_REL); +var REG_FN_VAR = new RegExp(SYN_FN_VAR); +/** +* pre process +* @param value - CSS color value +* @param [opt] - options +* @returns value +*/ +var preProcess = (value, opt = {}) => { + if (isString(value)) { + value = value.trim(); + if (!value) return new NullObject(); + } else return new NullObject(); + const cacheKey = createCacheKey({ + namespace: NAMESPACE, + name: "preProcess", + value + }, opt); + const cachedResult = getCache(cacheKey); + if (cachedResult instanceof CacheItem) { + if (cachedResult.isNull) return cachedResult; + return cachedResult.item; + } + if (REG_FN_VAR.test(value)) { + const resolvedValue = resolveVar(value, opt); + if (isString(resolvedValue)) value = resolvedValue; + else { + setCache(cacheKey, null); + return new NullObject(); + } + } + if (REG_FN_REL.test(value)) { + const resolvedValue = resolveRelativeColor(value, opt); + if (isString(resolvedValue)) value = resolvedValue; + else { + setCache(cacheKey, null); + return new NullObject(); + } + } else if (REG_FN_CALC.test(value)) value = cssCalc(value, opt); + if (value.startsWith("color-mix")) { + const clonedOpt = structuredClone(opt); + clonedOpt.format = VAL_COMP; + clonedOpt.nullable = true; + const resolvedValue = resolveColor(value, clonedOpt); + setCache(cacheKey, resolvedValue); + return resolvedValue; + } + setCache(cacheKey, value); + return value; +}; +/** +* convert number to hex string +* @param value - numeric value +* @returns hex string: 00..ff +*/ +var numberToHex = (value) => { + return numberToHexString(value); +}; +/** +* convert color to hex +* @param value - CSS color value +* @param [opt] - options +* @param [opt.alpha] - enable alpha channel +* @returns #rrggbb | #rrggbbaa | null +*/ +var colorToHex = (value, opt = {}) => { + if (isString(value)) { + const resolvedValue = preProcess(value, opt); + if (resolvedValue instanceof NullObject) return null; + value = resolvedValue.toLowerCase(); + } else throw new TypeError(`${value} is not a string.`); + const { alpha = false } = opt; + const cacheKey = createCacheKey({ + namespace: NAMESPACE, + name: "colorToHex", + value + }, opt); + const cachedResult = getCache(cacheKey); + if (cachedResult instanceof CacheItem) { + if (cachedResult.isNull) return null; + return cachedResult.item; + } + let hex; + opt.nullable = true; + if (alpha) { + opt.format = "hexAlpha"; + hex = resolveColor(value, opt); + } else { + opt.format = "hex"; + hex = resolveColor(value, opt); + } + if (isString(hex)) { + setCache(cacheKey, hex); + return hex; + } + setCache(cacheKey, null); + return null; +}; +/** +* convert color to hsl +* @param value - CSS color value +* @param [opt] - options +* @returns ColorChannels - [h, s, l, alpha] +*/ +var colorToHsl = (value, opt = {}) => { + if (isString(value)) { + const resolvedValue = preProcess(value, opt); + if (resolvedValue instanceof NullObject) return [ + 0, + 0, + 0, + 0 + ]; + value = resolvedValue.toLowerCase(); + } else throw new TypeError(`${value} is not a string.`); + const cacheKey = createCacheKey({ + namespace: NAMESPACE, + name: "colorToHsl", + value + }, opt); + const cachedResult = getCache(cacheKey); + if (cachedResult instanceof CacheItem) return cachedResult.item; + opt.format = "hsl"; + const hsl = convertColorToHsl(value, opt); + setCache(cacheKey, hsl); + return hsl; +}; +/** +* convert color to hwb +* @param value - CSS color value +* @param [opt] - options +* @returns ColorChannels - [h, w, b, alpha] +*/ +var colorToHwb = (value, opt = {}) => { + if (isString(value)) { + const resolvedValue = preProcess(value, opt); + if (resolvedValue instanceof NullObject) return [ + 0, + 0, + 0, + 0 + ]; + value = resolvedValue.toLowerCase(); + } else throw new TypeError(`${value} is not a string.`); + const cacheKey = createCacheKey({ + namespace: NAMESPACE, + name: "colorToHwb", + value + }, opt); + const cachedResult = getCache(cacheKey); + if (cachedResult instanceof CacheItem) return cachedResult.item; + opt.format = "hwb"; + const hwb = convertColorToHwb(value, opt); + setCache(cacheKey, hwb); + return hwb; +}; +/** +* convert color to lab +* @param value - CSS color value +* @param [opt] - options +* @returns ColorChannels - [l, a, b, alpha] +*/ +var colorToLab = (value, opt = {}) => { + if (isString(value)) { + const resolvedValue = preProcess(value, opt); + if (resolvedValue instanceof NullObject) return [ + 0, + 0, + 0, + 0 + ]; + value = resolvedValue.toLowerCase(); + } else throw new TypeError(`${value} is not a string.`); + const cacheKey = createCacheKey({ + namespace: NAMESPACE, + name: "colorToLab", + value + }, opt); + const cachedResult = getCache(cacheKey); + if (cachedResult instanceof CacheItem) return cachedResult.item; + const lab = convertColorToLab(value, opt); + setCache(cacheKey, lab); + return lab; +}; +/** +* convert color to lch +* @param value - CSS color value +* @param [opt] - options +* @returns ColorChannels - [l, c, h, alpha] +*/ +var colorToLch = (value, opt = {}) => { + if (isString(value)) { + const resolvedValue = preProcess(value, opt); + if (resolvedValue instanceof NullObject) return [ + 0, + 0, + 0, + 0 + ]; + value = resolvedValue.toLowerCase(); + } else throw new TypeError(`${value} is not a string.`); + const cacheKey = createCacheKey({ + namespace: NAMESPACE, + name: "colorToLch", + value + }, opt); + const cachedResult = getCache(cacheKey); + if (cachedResult instanceof CacheItem) return cachedResult.item; + const lch = convertColorToLch(value, opt); + setCache(cacheKey, lch); + return lch; +}; +/** +* convert color to oklab +* @param value - CSS color value +* @param [opt] - options +* @returns ColorChannels - [l, a, b, alpha] +*/ +var colorToOklab = (value, opt = {}) => { + if (isString(value)) { + const resolvedValue = preProcess(value, opt); + if (resolvedValue instanceof NullObject) return [ + 0, + 0, + 0, + 0 + ]; + value = resolvedValue.toLowerCase(); + } else throw new TypeError(`${value} is not a string.`); + const cacheKey = createCacheKey({ + namespace: NAMESPACE, + name: "colorToOklab", + value + }, opt); + const cachedResult = getCache(cacheKey); + if (cachedResult instanceof CacheItem) return cachedResult.item; + const lab = convertColorToOklab(value, opt); + setCache(cacheKey, lab); + return lab; +}; +/** +* convert color to oklch +* @param value - CSS color value +* @param [opt] - options +* @returns ColorChannels - [l, c, h, alpha] +*/ +var colorToOklch = (value, opt = {}) => { + if (isString(value)) { + const resolvedValue = preProcess(value, opt); + if (resolvedValue instanceof NullObject) return [ + 0, + 0, + 0, + 0 + ]; + value = resolvedValue.toLowerCase(); + } else throw new TypeError(`${value} is not a string.`); + const cacheKey = createCacheKey({ + namespace: NAMESPACE, + name: "colorToOklch", + value + }, opt); + const cachedResult = getCache(cacheKey); + if (cachedResult instanceof CacheItem) return cachedResult.item; + const lch = convertColorToOklch(value, opt); + setCache(cacheKey, lch); + return lch; +}; +/** +* convert color to rgb +* @param value - CSS color value +* @param [opt] - options +* @returns ColorChannels - [r, g, b, alpha] +*/ +var colorToRgb = (value, opt = {}) => { + if (isString(value)) { + const resolvedValue = preProcess(value, opt); + if (resolvedValue instanceof NullObject) return [ + 0, + 0, + 0, + 0 + ]; + value = resolvedValue.toLowerCase(); + } else throw new TypeError(`${value} is not a string.`); + const cacheKey = createCacheKey({ + namespace: NAMESPACE, + name: "colorToRgb", + value + }, opt); + const cachedResult = getCache(cacheKey); + if (cachedResult instanceof CacheItem) return cachedResult.item; + const rgb = convertColorToRgb(value, opt); + setCache(cacheKey, rgb); + return rgb; +}; +/** +* convert color to xyz +* @param value - CSS color value +* @param [opt] - options +* @returns ColorChannels - [x, y, z, alpha] +*/ +var colorToXyz = (value, opt = {}) => { + if (isString(value)) { + const resolvedValue = preProcess(value, opt); + if (resolvedValue instanceof NullObject) return [ + 0, + 0, + 0, + 0 + ]; + value = resolvedValue.toLowerCase(); + } else throw new TypeError(`${value} is not a string.`); + const cacheKey = createCacheKey({ + namespace: NAMESPACE, + name: "colorToXyz", + value + }, opt); + const cachedResult = getCache(cacheKey); + if (cachedResult instanceof CacheItem) return cachedResult.item; + let xyz; + if (value.startsWith("color(")) [, ...xyz] = parseColorFunc(value, opt); + else [, ...xyz] = parseColorValue(value, opt); + setCache(cacheKey, xyz); + return xyz; +}; +/** +* convert color to xyz-d50 +* @param value - CSS color value +* @param [opt] - options +* @returns ColorChannels - [x, y, z, alpha] +*/ +var colorToXyzD50 = (value, opt = {}) => { + opt.d50 = true; + return colorToXyz(value, opt); +}; +var convert = { + colorToHex, + colorToHsl, + colorToHwb, + colorToLab, + colorToLch, + colorToOklab, + colorToOklch, + colorToRgb, + colorToXyz, + colorToXyzD50, + numberToHex +}; +//#endregion +export { convert }; + +//# sourceMappingURL=convert.js.map \ No newline at end of file diff --git a/node_modules/@asamuzakjp/css-color/dist/esm/js/convert.js.map b/node_modules/@asamuzakjp/css-color/dist/esm/js/convert.js.map new file mode 100644 index 00000000..ed77147f --- /dev/null +++ b/node_modules/@asamuzakjp/css-color/dist/esm/js/convert.js.map @@ -0,0 +1 @@ +{"version":3,"file":"convert.js","names":[],"sources":["../../../src/js/convert.ts"],"sourcesContent":["/**\n * convert\n */\n\nimport {\n CacheItem,\n NullObject,\n createCacheKey,\n getCache,\n setCache\n} from './cache';\nimport {\n convertColorToHsl,\n convertColorToHwb,\n convertColorToLab,\n convertColorToLch,\n convertColorToOklab,\n convertColorToOklch,\n convertColorToRgb,\n numberToHexString,\n parseColorFunc,\n parseColorValue\n} from './color';\nimport { isString } from './common';\nimport { cssCalc } from './css-calc';\nimport { resolveVar } from './css-var';\nimport { resolveRelativeColor } from './relative-color';\nimport { resolveColor } from './resolve';\nimport { ColorChannels, ComputedColorChannels, Options } from './typedef';\n\n/* constants */\nimport { SYN_FN_CALC, SYN_FN_REL, SYN_FN_VAR, VAL_COMP } from './constant';\nconst NAMESPACE = 'convert';\n\n/* regexp */\nconst REG_FN_CALC = new RegExp(SYN_FN_CALC);\nconst REG_FN_REL = new RegExp(SYN_FN_REL);\nconst REG_FN_VAR = new RegExp(SYN_FN_VAR);\n\n/**\n * pre process\n * @param value - CSS color value\n * @param [opt] - options\n * @returns value\n */\nexport const preProcess = (\n value: string,\n opt: Options = {}\n): string | NullObject => {\n if (isString(value)) {\n value = value.trim();\n if (!value) {\n return new NullObject();\n }\n } else {\n return new NullObject();\n }\n const cacheKey: string = createCacheKey(\n {\n namespace: NAMESPACE,\n name: 'preProcess',\n value\n },\n opt\n );\n const cachedResult = getCache(cacheKey);\n if (cachedResult instanceof CacheItem) {\n if (cachedResult.isNull) {\n return cachedResult as NullObject;\n }\n return cachedResult.item as string;\n }\n if (REG_FN_VAR.test(value)) {\n const resolvedValue = resolveVar(value, opt);\n if (isString(resolvedValue)) {\n value = resolvedValue;\n } else {\n setCache(cacheKey, null);\n return new NullObject();\n }\n }\n if (REG_FN_REL.test(value)) {\n const resolvedValue = resolveRelativeColor(value, opt);\n if (isString(resolvedValue)) {\n value = resolvedValue;\n } else {\n setCache(cacheKey, null);\n return new NullObject();\n }\n } else if (REG_FN_CALC.test(value)) {\n value = cssCalc(value, opt);\n }\n if (value.startsWith('color-mix')) {\n const clonedOpt = structuredClone(opt);\n clonedOpt.format = VAL_COMP;\n clonedOpt.nullable = true;\n const resolvedValue = resolveColor(value, clonedOpt);\n setCache(cacheKey, resolvedValue);\n return resolvedValue;\n }\n setCache(cacheKey, value);\n return value;\n};\n\n/**\n * convert number to hex string\n * @param value - numeric value\n * @returns hex string: 00..ff\n */\nexport const numberToHex = (value: number): string => {\n const hex = numberToHexString(value);\n return hex;\n};\n\n/**\n * convert color to hex\n * @param value - CSS color value\n * @param [opt] - options\n * @param [opt.alpha] - enable alpha channel\n * @returns #rrggbb | #rrggbbaa | null\n */\nexport const colorToHex = (value: string, opt: Options = {}): string | null => {\n if (isString(value)) {\n const resolvedValue = preProcess(value, opt);\n if (resolvedValue instanceof NullObject) {\n return null;\n }\n value = resolvedValue.toLowerCase();\n } else {\n throw new TypeError(`${value} is not a string.`);\n }\n const { alpha = false } = opt;\n const cacheKey: string = createCacheKey(\n {\n namespace: NAMESPACE,\n name: 'colorToHex',\n value\n },\n opt\n );\n const cachedResult = getCache(cacheKey);\n if (cachedResult instanceof CacheItem) {\n if (cachedResult.isNull) {\n return null;\n }\n return cachedResult.item as string;\n }\n let hex;\n opt.nullable = true;\n if (alpha) {\n opt.format = 'hexAlpha';\n hex = resolveColor(value, opt);\n } else {\n opt.format = 'hex';\n hex = resolveColor(value, opt);\n }\n if (isString(hex)) {\n setCache(cacheKey, hex);\n return hex;\n }\n setCache(cacheKey, null);\n return null;\n};\n\n/**\n * convert color to hsl\n * @param value - CSS color value\n * @param [opt] - options\n * @returns ColorChannels - [h, s, l, alpha]\n */\nexport const colorToHsl = (value: string, opt: Options = {}): ColorChannels => {\n if (isString(value)) {\n const resolvedValue = preProcess(value, opt);\n if (resolvedValue instanceof NullObject) {\n return [0, 0, 0, 0];\n }\n value = resolvedValue.toLowerCase();\n } else {\n throw new TypeError(`${value} is not a string.`);\n }\n const cacheKey: string = createCacheKey(\n {\n namespace: NAMESPACE,\n name: 'colorToHsl',\n value\n },\n opt\n );\n const cachedResult = getCache(cacheKey);\n if (cachedResult instanceof CacheItem) {\n return cachedResult.item as ColorChannels;\n }\n opt.format = 'hsl';\n const hsl = convertColorToHsl(value, opt) as ColorChannels;\n setCache(cacheKey, hsl);\n return hsl;\n};\n\n/**\n * convert color to hwb\n * @param value - CSS color value\n * @param [opt] - options\n * @returns ColorChannels - [h, w, b, alpha]\n */\nexport const colorToHwb = (value: string, opt: Options = {}): ColorChannels => {\n if (isString(value)) {\n const resolvedValue = preProcess(value, opt);\n if (resolvedValue instanceof NullObject) {\n return [0, 0, 0, 0];\n }\n value = resolvedValue.toLowerCase();\n } else {\n throw new TypeError(`${value} is not a string.`);\n }\n const cacheKey: string = createCacheKey(\n {\n namespace: NAMESPACE,\n name: 'colorToHwb',\n value\n },\n opt\n );\n const cachedResult = getCache(cacheKey);\n if (cachedResult instanceof CacheItem) {\n return cachedResult.item as ColorChannels;\n }\n opt.format = 'hwb';\n const hwb = convertColorToHwb(value, opt) as ColorChannels;\n setCache(cacheKey, hwb);\n return hwb;\n};\n\n/**\n * convert color to lab\n * @param value - CSS color value\n * @param [opt] - options\n * @returns ColorChannels - [l, a, b, alpha]\n */\nexport const colorToLab = (value: string, opt: Options = {}): ColorChannels => {\n if (isString(value)) {\n const resolvedValue = preProcess(value, opt);\n if (resolvedValue instanceof NullObject) {\n return [0, 0, 0, 0];\n }\n value = resolvedValue.toLowerCase();\n } else {\n throw new TypeError(`${value} is not a string.`);\n }\n const cacheKey: string = createCacheKey(\n {\n namespace: NAMESPACE,\n name: 'colorToLab',\n value\n },\n opt\n );\n const cachedResult = getCache(cacheKey);\n if (cachedResult instanceof CacheItem) {\n return cachedResult.item as ColorChannels;\n }\n const lab = convertColorToLab(value, opt) as ColorChannels;\n setCache(cacheKey, lab);\n return lab;\n};\n\n/**\n * convert color to lch\n * @param value - CSS color value\n * @param [opt] - options\n * @returns ColorChannels - [l, c, h, alpha]\n */\nexport const colorToLch = (value: string, opt: Options = {}): ColorChannels => {\n if (isString(value)) {\n const resolvedValue = preProcess(value, opt);\n if (resolvedValue instanceof NullObject) {\n return [0, 0, 0, 0];\n }\n value = resolvedValue.toLowerCase();\n } else {\n throw new TypeError(`${value} is not a string.`);\n }\n const cacheKey: string = createCacheKey(\n {\n namespace: NAMESPACE,\n name: 'colorToLch',\n value\n },\n opt\n );\n const cachedResult = getCache(cacheKey);\n if (cachedResult instanceof CacheItem) {\n return cachedResult.item as ColorChannels;\n }\n const lch = convertColorToLch(value, opt) as ColorChannels;\n setCache(cacheKey, lch);\n return lch;\n};\n\n/**\n * convert color to oklab\n * @param value - CSS color value\n * @param [opt] - options\n * @returns ColorChannels - [l, a, b, alpha]\n */\nexport const colorToOklab = (\n value: string,\n opt: Options = {}\n): ColorChannels => {\n if (isString(value)) {\n const resolvedValue = preProcess(value, opt);\n if (resolvedValue instanceof NullObject) {\n return [0, 0, 0, 0];\n }\n value = resolvedValue.toLowerCase();\n } else {\n throw new TypeError(`${value} is not a string.`);\n }\n const cacheKey: string = createCacheKey(\n {\n namespace: NAMESPACE,\n name: 'colorToOklab',\n value\n },\n opt\n );\n const cachedResult = getCache(cacheKey);\n if (cachedResult instanceof CacheItem) {\n return cachedResult.item as ColorChannels;\n }\n const lab = convertColorToOklab(value, opt) as ColorChannels;\n setCache(cacheKey, lab);\n return lab;\n};\n\n/**\n * convert color to oklch\n * @param value - CSS color value\n * @param [opt] - options\n * @returns ColorChannels - [l, c, h, alpha]\n */\nexport const colorToOklch = (\n value: string,\n opt: Options = {}\n): ColorChannels => {\n if (isString(value)) {\n const resolvedValue = preProcess(value, opt);\n if (resolvedValue instanceof NullObject) {\n return [0, 0, 0, 0];\n }\n value = resolvedValue.toLowerCase();\n } else {\n throw new TypeError(`${value} is not a string.`);\n }\n const cacheKey: string = createCacheKey(\n {\n namespace: NAMESPACE,\n name: 'colorToOklch',\n value\n },\n opt\n );\n const cachedResult = getCache(cacheKey);\n if (cachedResult instanceof CacheItem) {\n return cachedResult.item as ColorChannels;\n }\n const lch = convertColorToOklch(value, opt) as ColorChannels;\n setCache(cacheKey, lch);\n return lch;\n};\n\n/**\n * convert color to rgb\n * @param value - CSS color value\n * @param [opt] - options\n * @returns ColorChannels - [r, g, b, alpha]\n */\nexport const colorToRgb = (value: string, opt: Options = {}): ColorChannels => {\n if (isString(value)) {\n const resolvedValue = preProcess(value, opt);\n if (resolvedValue instanceof NullObject) {\n return [0, 0, 0, 0];\n }\n value = resolvedValue.toLowerCase();\n } else {\n throw new TypeError(`${value} is not a string.`);\n }\n const cacheKey: string = createCacheKey(\n {\n namespace: NAMESPACE,\n name: 'colorToRgb',\n value\n },\n opt\n );\n const cachedResult = getCache(cacheKey);\n if (cachedResult instanceof CacheItem) {\n return cachedResult.item as ColorChannels;\n }\n const rgb = convertColorToRgb(value, opt) as ColorChannels;\n setCache(cacheKey, rgb);\n return rgb;\n};\n\n/**\n * convert color to xyz\n * @param value - CSS color value\n * @param [opt] - options\n * @returns ColorChannels - [x, y, z, alpha]\n */\nexport const colorToXyz = (value: string, opt: Options = {}): ColorChannels => {\n if (isString(value)) {\n const resolvedValue = preProcess(value, opt);\n if (resolvedValue instanceof NullObject) {\n return [0, 0, 0, 0];\n }\n value = resolvedValue.toLowerCase();\n } else {\n throw new TypeError(`${value} is not a string.`);\n }\n const cacheKey: string = createCacheKey(\n {\n namespace: NAMESPACE,\n name: 'colorToXyz',\n value\n },\n opt\n );\n const cachedResult = getCache(cacheKey);\n if (cachedResult instanceof CacheItem) {\n return cachedResult.item as ColorChannels;\n }\n let xyz;\n if (value.startsWith('color(')) {\n [, ...xyz] = parseColorFunc(value, opt) as ComputedColorChannels;\n } else {\n [, ...xyz] = parseColorValue(value, opt) as ComputedColorChannels;\n }\n setCache(cacheKey, xyz);\n return xyz as ColorChannels;\n};\n\n/**\n * convert color to xyz-d50\n * @param value - CSS color value\n * @param [opt] - options\n * @returns ColorChannels - [x, y, z, alpha]\n */\nexport const colorToXyzD50 = (\n value: string,\n opt: Options = {}\n): ColorChannels => {\n opt.d50 = true;\n return colorToXyz(value, opt);\n};\n\n/* convert */\nexport const convert = {\n colorToHex,\n colorToHsl,\n colorToHwb,\n colorToLab,\n colorToLch,\n colorToOklab,\n colorToOklch,\n colorToRgb,\n colorToXyz,\n colorToXyzD50,\n numberToHex\n};\n"],"mappings":";;;;;;;;;;;;AAgCA,IAAM,YAAY;AAGlB,IAAM,cAAc,IAAI,OAAO,YAAY;AAC3C,IAAM,aAAa,IAAI,OAAO,WAAW;AACzC,IAAM,aAAa,IAAI,OAAO,WAAW;;;;;;;AAQzC,IAAa,cACX,OACA,MAAe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AU,IAAI;AACvB,QAAO;;;;;;;;AAST,IAAa,cAAc,OAAe,MAAe,EAAE,KAAoB;AAC7E,KAAI,SAAS,MAAM,EAAE;EACnB,MAAM,gBAAgB,WAAW,OAAO,IAAI;AAC5C,MAAI,yBAAyB,WAC3B,QAAO;GAAC;GAAG;GAAG;GAAG;GAAE;AAErB,UAAQ,cAAc,aAAa;OAEnC,OAAM,IAAI,UAAU,GAAG,MAAM,mBAAmB;CAElD,MAAM,WAAmB,eACvB;EACE,WAAW;EACX,MAAM;EACN;EACD,EACD,IACD;CACD,MAAM,eAAe,SAAS,SAAS;AACvC,KAAI,wBAAwB,UAC1B,QAAO,aAAa;CAEtB,IAAI;AACJ,KAAI,MAAM,WAAW,SAAS,CAC5B,OAAM,OAAO,eAAe,OAAO,IAAI;KAEvC,OAAM,OAAO,gBAAgB,OAAO,IAAI;AAE1C,UAAS,UAAU,IAAI;AACvB,QAAO;;;;;;;;AAST,IAAa,iBACX,OACA,MAAe,EAAE,KACC;AAClB,KAAI,MAAM;AACV,QAAO,WAAW,OAAO,IAAI;;AAI/B,IAAa,UAAU;CACrB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD"} \ No newline at end of file diff --git a/node_modules/@asamuzakjp/css-color/dist/esm/js/css-calc.d.ts b/node_modules/@asamuzakjp/css-color/dist/esm/js/css-calc.d.ts new file mode 100644 index 00000000..265e284c --- /dev/null +++ b/node_modules/@asamuzakjp/css-color/dist/esm/js/css-calc.d.ts @@ -0,0 +1,89 @@ +import { CSSToken } from '@csstools/css-tokenizer'; +import { NullObject } from './cache.js'; +import { Options } from './typedef.js'; +/** + * Calclator + */ +export declare class Calculator { + #private; + /** + * constructor + */ + constructor(); + get hasNum(): boolean; + set hasNum(value: boolean); + get numSum(): number[]; + get numMul(): number[]; + get hasPct(): boolean; + set hasPct(value: boolean); + get pctSum(): number[]; + get pctMul(): number[]; + get hasDim(): boolean; + set hasDim(value: boolean); + get dimSum(): string[]; + get dimSub(): string[]; + get dimMul(): string[]; + get dimDiv(): string[]; + get hasEtc(): boolean; + set hasEtc(value: boolean); + get etcSum(): string[]; + get etcSub(): string[]; + get etcMul(): string[]; + get etcDiv(): string[]; + /** + * clear values + * @returns void + */ + clear(): void; + /** + * sort values + * @param values - values + * @returns sorted values + */ + sort(values?: string[]): string[]; + /** + * multiply values + * @returns resolved value + */ + multiply(): string; + /** + * sum values + * @returns resolved value + */ + sum(): string; +} +/** + * sort calc values + * @param values - values to sort + * @param [finalize] - finalize values + * @returns sorted values + */ +export declare const sortCalcValues: (values?: (number | string)[], finalize?: boolean) => string; +/** + * serialize calc + * @param value - CSS value + * @param [opt] - options + * @returns serialized value + */ +export declare const serializeCalc: (value: string, opt?: Options) => string; +/** + * resolve dimension + * @param token - CSS token + * @param [opt] - options + * @returns resolved value + */ +export declare const resolveDimension: (token: CSSToken, opt?: Options) => string | NullObject; +/** + * parse tokens + * @param tokens - CSS tokens + * @param [opt] - options + * @returns parsed tokens + */ +export declare const parseTokens: (tokens: CSSToken[], opt?: Options) => string[]; +/** + * CSS calc() + * @param value - CSS value including calc() + * @param [opt] - options + * @returns resolved value + */ +export declare const cssCalc: (value: string, opt?: Options) => string; diff --git a/node_modules/@asamuzakjp/css-color/dist/esm/js/css-calc.js b/node_modules/@asamuzakjp/css-color/dist/esm/js/css-calc.js new file mode 100644 index 00000000..7bec1d45 --- /dev/null +++ b/node_modules/@asamuzakjp/css-color/dist/esm/js/css-calc.js @@ -0,0 +1,593 @@ +import { isString, isStringOrNumber } from "./common.js"; +import { ANGLE, LENGTH, NUM, SYN_FN_CALC, SYN_FN_MATH_START, SYN_FN_VAR, SYN_FN_VAR_START } from "./constant.js"; +import { resolveVar } from "./css-var.js"; +import { resolveLengthInPixels, roundToPrecision } from "./util.js"; +import { CacheItem, NullObject, createCacheKey, getCache, setCache } from "./cache.js"; +import { calc } from "@csstools/css-calc"; +import { TokenType, tokenize } from "@csstools/css-tokenizer"; +//#region src/js/css-calc.ts +/** +* css-calc +*/ +var { CloseParen: PAREN_CLOSE, Comment: COMMENT, Dimension: DIM, EOF, Function: FUNC, OpenParen: PAREN_OPEN, Whitespace: W_SPACE } = TokenType; +var NAMESPACE = "css-calc"; +var TRIA = 3; +var HEX = 16; +var MAX_PCT = 100; +var REG_FN_CALC = new RegExp(SYN_FN_CALC); +var REG_FN_CALC_NUM = new RegExp(`^calc\\((${NUM})\\)$`); +var REG_FN_MATH_START = new RegExp(SYN_FN_MATH_START); +var REG_FN_VAR = new RegExp(SYN_FN_VAR); +var REG_FN_VAR_START = new RegExp(SYN_FN_VAR_START); +var REG_OPERATOR = /\s[*+/-]\s/; +var REG_TYPE_DIM = new RegExp(`^(${NUM})(${ANGLE}|${LENGTH})$`); +var REG_TYPE_DIM_PCT = new RegExp(`^(${NUM})(${ANGLE}|${LENGTH}|%)$`); +var REG_TYPE_PCT = new RegExp(`^(${NUM})%$`); +/** +* Calclator +*/ +var Calculator = class { + #hasNum; + #numSum; + #numMul; + #hasPct; + #pctSum; + #pctMul; + #hasDim; + #dimSum; + #dimSub; + #dimMul; + #dimDiv; + #hasEtc; + #etcSum; + #etcSub; + #etcMul; + #etcDiv; + #calcOpts; + /** + * constructor + */ + constructor() { + this.#hasNum = false; + this.#numSum = []; + this.#numMul = []; + this.#hasPct = false; + this.#pctSum = []; + this.#pctMul = []; + this.#hasDim = false; + this.#dimSum = []; + this.#dimSub = []; + this.#dimMul = []; + this.#dimDiv = []; + this.#hasEtc = false; + this.#etcSum = []; + this.#etcSub = []; + this.#etcMul = []; + this.#etcDiv = []; + this.#calcOpts = { toCanonicalUnits: true }; + } + get hasNum() { + return this.#hasNum; + } + set hasNum(value) { + this.#hasNum = !!value; + } + get numSum() { + return this.#numSum; + } + get numMul() { + return this.#numMul; + } + get hasPct() { + return this.#hasPct; + } + set hasPct(value) { + this.#hasPct = !!value; + } + get pctSum() { + return this.#pctSum; + } + get pctMul() { + return this.#pctMul; + } + get hasDim() { + return this.#hasDim; + } + set hasDim(value) { + this.#hasDim = !!value; + } + get dimSum() { + return this.#dimSum; + } + get dimSub() { + return this.#dimSub; + } + get dimMul() { + return this.#dimMul; + } + get dimDiv() { + return this.#dimDiv; + } + get hasEtc() { + return this.#hasEtc; + } + set hasEtc(value) { + this.#hasEtc = !!value; + } + get etcSum() { + return this.#etcSum; + } + get etcSub() { + return this.#etcSub; + } + get etcMul() { + return this.#etcMul; + } + get etcDiv() { + return this.#etcDiv; + } + /** + * clear values + * @returns void + */ + clear() { + this.#hasNum = false; + this.#numSum = []; + this.#numMul = []; + this.#hasPct = false; + this.#pctSum = []; + this.#pctMul = []; + this.#hasDim = false; + this.#dimSum = []; + this.#dimSub = []; + this.#dimMul = []; + this.#dimDiv = []; + this.#hasEtc = false; + this.#etcSum = []; + this.#etcSub = []; + this.#etcMul = []; + this.#etcDiv = []; + } + /** + * sort values + * @param values - values + * @returns sorted values + */ + sort(values = []) { + const arr = [...values]; + if (arr.length > 1) arr.sort((a, b) => { + let res; + if (REG_TYPE_DIM_PCT.test(a) && REG_TYPE_DIM_PCT.test(b)) { + const [, valA, unitA] = a.match(REG_TYPE_DIM_PCT); + const [, valB, unitB] = b.match(REG_TYPE_DIM_PCT); + if (unitA === unitB) if (Number(valA) === Number(valB)) res = 0; + else if (Number(valA) > Number(valB)) res = 1; + else res = -1; + else if (unitA > unitB) res = 1; + else res = -1; + } else if (a === b) res = 0; + else if (a > b) res = 1; + else res = -1; + return res; + }); + return arr; + } + /** + * multiply values + * @returns resolved value + */ + multiply() { + const value = []; + let num; + if (this.#hasNum) { + num = 1; + for (const i of this.#numMul) { + num *= i; + if (num === 0 || !Number.isFinite(num) || Number.isNaN(num)) break; + } + if (!this.#hasPct && !this.#hasDim && !this.hasEtc) { + if (Number.isFinite(num)) num = roundToPrecision(num, HEX); + value.push(num); + } + } + if (this.#hasPct) { + if (typeof num !== "number") num = 1; + for (const i of this.#pctMul) { + num *= i; + if (num === 0 || !Number.isFinite(num) || Number.isNaN(num)) break; + } + if (Number.isFinite(num)) num = `${roundToPrecision(num, HEX)}%`; + if (!this.#hasDim && !this.hasEtc) value.push(num); + } + if (this.#hasDim) { + let dim = ""; + let mul = ""; + let div = ""; + if (this.#dimMul.length) if (this.#dimMul.length === 1) [mul] = this.#dimMul; + else mul = `${this.sort(this.#dimMul).join(" * ")}`; + if (this.#dimDiv.length) if (this.#dimDiv.length === 1) [div] = this.#dimDiv; + else div = `${this.sort(this.#dimDiv).join(" * ")}`; + if (Number.isFinite(num)) { + if (mul) if (div) if (div.includes("*")) dim = calc(`calc(${num} * ${mul} / (${div}))`, this.#calcOpts); + else dim = calc(`calc(${num} * ${mul} / ${div})`, this.#calcOpts); + else dim = calc(`calc(${num} * ${mul})`, this.#calcOpts); + else if (div.includes("*")) dim = calc(`calc(${num} / (${div}))`, this.#calcOpts); + else dim = calc(`calc(${num} / ${div})`, this.#calcOpts); + value.push(dim.replace(/^calc/, "")); + } else { + if (!value.length && num !== void 0) value.push(num); + if (mul) { + if (div) if (div.includes("*")) dim = calc(`calc(${mul} / (${div}))`, this.#calcOpts); + else dim = calc(`calc(${mul} / ${div})`, this.#calcOpts); + else dim = calc(`calc(${mul})`, this.#calcOpts); + if (value.length) value.push("*", dim.replace(/^calc/, "")); + else value.push(dim.replace(/^calc/, "")); + } else { + dim = calc(`calc(${div})`, this.#calcOpts); + if (value.length) value.push("/", dim.replace(/^calc/, "")); + else value.push("1", "/", dim.replace(/^calc/, "")); + } + } + } + if (this.#hasEtc) { + if (this.#etcMul.length) { + if (!value.length && num !== void 0) value.push(num); + const mul = this.sort(this.#etcMul).join(" * "); + if (value.length) value.push(`* ${mul}`); + else value.push(`${mul}`); + } + if (this.#etcDiv.length) { + const div = this.sort(this.#etcDiv).join(" * "); + if (div.includes("*")) if (value.length) value.push(`/ (${div})`); + else value.push(`1 / (${div})`); + else if (value.length) value.push(`/ ${div}`); + else value.push(`1 / ${div}`); + } + } + if (value.length) return value.join(" "); + return ""; + } + /** + * sum values + * @returns resolved value + */ + sum() { + const value = []; + if (this.#hasNum) { + let num = 0; + for (const i of this.#numSum) { + num += i; + if (!Number.isFinite(num) || Number.isNaN(num)) break; + } + value.push(num); + } + if (this.#hasPct) { + let num = 0; + for (const i of this.#pctSum) { + num += i; + if (!Number.isFinite(num)) break; + } + if (Number.isFinite(num)) num = `${num}%`; + if (value.length) value.push(`+ ${num}`); + else value.push(num); + } + if (this.#hasDim) { + let dim, sum, sub; + if (this.#dimSum.length) sum = this.sort(this.#dimSum).join(" + "); + if (this.#dimSub.length) sub = this.sort(this.#dimSub).join(" + "); + if (sum) if (sub) if (sub.includes("-")) dim = calc(`calc(${sum} - (${sub}))`, this.#calcOpts); + else dim = calc(`calc(${sum} - ${sub})`, this.#calcOpts); + else dim = calc(`calc(${sum})`, this.#calcOpts); + else dim = calc(`calc(-1 * (${sub}))`, this.#calcOpts); + if (value.length) value.push("+", dim.replace(/^calc/, "")); + else value.push(dim.replace(/^calc/, "")); + } + if (this.#hasEtc) { + if (this.#etcSum.length) { + const sum = this.sort(this.#etcSum).map((item) => { + let res; + if (REG_OPERATOR.test(item) && !item.startsWith("(") && !item.endsWith(")")) res = `(${item})`; + else res = item; + return res; + }).join(" + "); + if (value.length) if (this.#etcSum.length > 1) value.push(`+ (${sum})`); + else value.push(`+ ${sum}`); + else value.push(`${sum}`); + } + if (this.#etcSub.length) { + const sub = this.sort(this.#etcSub).map((item) => { + let res; + if (REG_OPERATOR.test(item) && !item.startsWith("(") && !item.endsWith(")")) res = `(${item})`; + else res = item; + return res; + }).join(" + "); + if (value.length) if (this.#etcSub.length > 1) value.push(`- (${sub})`); + else value.push(`- ${sub}`); + else if (this.#etcSub.length > 1) value.push(`-1 * (${sub})`); + else value.push(`-1 * ${sub}`); + } + } + if (value.length) return value.join(" "); + return ""; + } +}; +/** +* sort calc values +* @param values - values to sort +* @param [finalize] - finalize values +* @returns sorted values +*/ +var sortCalcValues = (values = [], finalize = false) => { + if (values.length < TRIA) throw new Error(`Unexpected array length ${values.length}.`); + const start = values.shift(); + if (!isString(start) || !start.endsWith("(")) throw new Error(`Unexpected token ${start}.`); + const end = values.pop(); + if (end !== ")") throw new Error(`Unexpected token ${end}.`); + if (values.length === 1) { + const [value] = values; + if (!isStringOrNumber(value)) throw new Error(`Unexpected token ${value}.`); + return `${start}${value}${end}`; + } + const sortedValues = []; + const cal = new Calculator(); + let operator = ""; + const l = values.length; + for (let i = 0; i < l; i++) { + const value = values[i]; + if (!isStringOrNumber(value)) throw new Error(`Unexpected token ${value}.`); + if (value === "*" || value === "/") operator = value; + else if (value === "+" || value === "-") { + const sortedValue = cal.multiply(); + if (sortedValue) sortedValues.push(sortedValue, value); + cal.clear(); + operator = ""; + } else { + const numValue = Number(value); + const strValue = `${value}`; + switch (operator) { + case "/": + if (Number.isFinite(numValue)) { + cal.hasNum = true; + cal.numMul.push(1 / numValue); + } else if (REG_TYPE_PCT.test(strValue)) { + const [, val] = strValue.match(REG_TYPE_PCT); + cal.hasPct = true; + cal.pctMul.push(MAX_PCT * MAX_PCT / Number(val)); + } else if (REG_TYPE_DIM.test(strValue)) { + cal.hasDim = true; + cal.dimDiv.push(strValue); + } else { + cal.hasEtc = true; + cal.etcDiv.push(strValue); + } + break; + default: if (Number.isFinite(numValue)) { + cal.hasNum = true; + cal.numMul.push(numValue); + } else if (REG_TYPE_PCT.test(strValue)) { + const [, val] = strValue.match(REG_TYPE_PCT); + cal.hasPct = true; + cal.pctMul.push(Number(val)); + } else if (REG_TYPE_DIM.test(strValue)) { + cal.hasDim = true; + cal.dimMul.push(strValue); + } else { + cal.hasEtc = true; + cal.etcMul.push(strValue); + } + } + } + if (i === l - 1) { + const sortedValue = cal.multiply(); + if (sortedValue) sortedValues.push(sortedValue); + cal.clear(); + operator = ""; + } + } + let resolvedValue = ""; + if (finalize && (sortedValues.includes("+") || sortedValues.includes("-"))) { + const finalizedValues = []; + cal.clear(); + operator = ""; + const l = sortedValues.length; + for (let i = 0; i < l; i++) { + const value = sortedValues[i]; + if (isStringOrNumber(value)) if (value === "+" || value === "-") operator = value; + else { + const numValue = Number(value); + const strValue = `${value}`; + switch (operator) { + case "-": + if (Number.isFinite(numValue)) { + cal.hasNum = true; + cal.numSum.push(-1 * numValue); + } else if (REG_TYPE_PCT.test(strValue)) { + const [, val] = strValue.match(REG_TYPE_PCT); + cal.hasPct = true; + cal.pctSum.push(-1 * Number(val)); + } else if (REG_TYPE_DIM.test(strValue)) { + cal.hasDim = true; + cal.dimSub.push(strValue); + } else { + cal.hasEtc = true; + cal.etcSub.push(strValue); + } + break; + default: if (Number.isFinite(numValue)) { + cal.hasNum = true; + cal.numSum.push(numValue); + } else if (REG_TYPE_PCT.test(strValue)) { + const [, val] = strValue.match(REG_TYPE_PCT); + cal.hasPct = true; + cal.pctSum.push(Number(val)); + } else if (REG_TYPE_DIM.test(strValue)) { + cal.hasDim = true; + cal.dimSum.push(strValue); + } else { + cal.hasEtc = true; + cal.etcSum.push(strValue); + } + } + } + if (i === l - 1) { + const sortedValue = cal.sum(); + if (sortedValue) finalizedValues.push(sortedValue); + cal.clear(); + operator = ""; + } + } + resolvedValue = finalizedValues.join(" ").replace(/\+\s-/g, "- "); + } else resolvedValue = sortedValues.join(" ").replace(/\+\s-/g, "- "); + if (resolvedValue.startsWith("(") && resolvedValue.endsWith(")") && resolvedValue.lastIndexOf("(") === 0 && resolvedValue.indexOf(")") === resolvedValue.length - 1) resolvedValue = resolvedValue.replace(/^\(/, "").replace(/\)$/, ""); + return `${start}${resolvedValue}${end}`; +}; +/** +* serialize calc +* @param value - CSS value +* @param [opt] - options +* @returns serialized value +*/ +var serializeCalc = (value, opt = {}) => { + const { format = "" } = opt; + if (isString(value)) { + if (!REG_FN_VAR_START.test(value) || format !== "specifiedValue") return value; + value = value.toLowerCase().trim(); + } else throw new TypeError(`${value} is not a string.`); + const cacheKey = createCacheKey({ + namespace: NAMESPACE, + name: "serializeCalc", + value + }, opt); + const cachedResult = getCache(cacheKey); + if (cachedResult instanceof CacheItem) return cachedResult.item; + const items = tokenize({ css: value }).map((token) => { + const [type, value] = token; + let res = ""; + if (type !== W_SPACE && type !== COMMENT) res = value; + return res; + }).filter((v) => v); + let startIndex = items.findLastIndex((item) => /\($/.test(item)); + while (startIndex) { + const endIndex = items.findIndex((item, index) => { + return item === ")" && index > startIndex; + }); + let serializedValue = sortCalcValues(items.slice(startIndex, endIndex + 1)); + if (REG_FN_VAR_START.test(serializedValue)) serializedValue = calc(serializedValue, { toCanonicalUnits: true }); + items.splice(startIndex, endIndex - startIndex + 1, serializedValue); + startIndex = items.findLastIndex((item) => /\($/.test(item)); + } + const serializedCalc = sortCalcValues(items, true); + setCache(cacheKey, serializedCalc); + return serializedCalc; +}; +/** +* resolve dimension +* @param token - CSS token +* @param [opt] - options +* @returns resolved value +*/ +var resolveDimension = (token, opt = {}) => { + if (!Array.isArray(token)) throw new TypeError(`${token} is not an array.`); + const [, , , , detail = {}] = token; + const { unit, value } = detail; + if (unit === "px") return `${value}${unit}`; + const pixelValue = resolveLengthInPixels(Number(value), unit, opt); + if (Number.isFinite(pixelValue)) return `${roundToPrecision(pixelValue, HEX)}px`; + return new NullObject(); +}; +/** +* parse tokens +* @param tokens - CSS tokens +* @param [opt] - options +* @returns parsed tokens +*/ +var parseTokens = (tokens, opt = {}) => { + if (!Array.isArray(tokens)) throw new TypeError(`${tokens} is not an array.`); + const { format = "" } = opt; + const mathFunc = /* @__PURE__ */ new Set(); + let nest = 0; + const res = []; + while (tokens.length) { + const token = tokens.shift(); + if (!Array.isArray(token)) throw new TypeError(`${token} is not an array.`); + const [type = "", value = ""] = token; + switch (type) { + case DIM: + if (format === "specifiedValue" && !mathFunc.has(nest)) res.push(value); + else { + const resolvedValue = resolveDimension(token, opt); + if (isString(resolvedValue)) res.push(resolvedValue); + else res.push(value); + } + break; + case FUNC: + case PAREN_OPEN: + res.push(value); + nest++; + if (REG_FN_MATH_START.test(value)) mathFunc.add(nest); + break; + case PAREN_CLOSE: + if (res.length) if (res[res.length - 1] === " ") res.splice(-1, 1, value); + else res.push(value); + else res.push(value); + if (mathFunc.has(nest)) mathFunc.delete(nest); + nest--; + break; + case W_SPACE: + if (res.length) { + const lastValue = res[res.length - 1]; + if (isString(lastValue) && !lastValue.endsWith("(") && lastValue !== " ") res.push(value); + } + break; + default: if (type !== COMMENT && type !== EOF) res.push(value); + } + } + return res; +}; +/** +* CSS calc() +* @param value - CSS value including calc() +* @param [opt] - options +* @returns resolved value +*/ +var cssCalc = (value, opt = {}) => { + const { format = "" } = opt; + if (isString(value)) { + if (REG_FN_VAR.test(value)) if (format === "specifiedValue") return value; + else { + const resolvedValue = resolveVar(value, opt); + if (isString(resolvedValue)) return resolvedValue; + else return ""; + } + else if (!REG_FN_CALC.test(value)) return value; + value = value.toLowerCase().trim(); + } else throw new TypeError(`${value} is not a string.`); + const cacheKey = createCacheKey({ + namespace: NAMESPACE, + name: "cssCalc", + value + }, opt); + const cachedResult = getCache(cacheKey); + if (cachedResult instanceof CacheItem) return cachedResult.item; + let resolvedValue = calc(parseTokens(tokenize({ css: value }), opt).join(""), { toCanonicalUnits: true }); + if (REG_FN_VAR_START.test(value)) { + if (REG_TYPE_DIM_PCT.test(resolvedValue)) { + const [, val, unit] = resolvedValue.match(REG_TYPE_DIM_PCT); + resolvedValue = `${roundToPrecision(Number(val), HEX)}${unit}`; + } + if (resolvedValue && !REG_FN_VAR_START.test(resolvedValue) && format === "specifiedValue") resolvedValue = `calc(${resolvedValue})`; + } + if (format === "specifiedValue") { + if (/\s[-+*/]\s/.test(resolvedValue) && !resolvedValue.includes("NaN")) resolvedValue = serializeCalc(resolvedValue, opt); + else if (REG_FN_CALC_NUM.test(resolvedValue)) { + const [, val] = resolvedValue.match(REG_FN_CALC_NUM); + resolvedValue = `calc(${roundToPrecision(Number(val), HEX)})`; + } + } + setCache(cacheKey, resolvedValue); + return resolvedValue; +}; +//#endregion +export { cssCalc, resolveDimension, serializeCalc }; + +//# sourceMappingURL=css-calc.js.map \ No newline at end of file diff --git a/node_modules/@asamuzakjp/css-color/dist/esm/js/css-calc.js.map b/node_modules/@asamuzakjp/css-color/dist/esm/js/css-calc.js.map new file mode 100644 index 00000000..2d85d71f --- /dev/null +++ b/node_modules/@asamuzakjp/css-color/dist/esm/js/css-calc.js.map @@ -0,0 +1 @@ +{"version":3,"file":"css-calc.js","names":["#hasNum","#numSum","#numMul","#hasPct","#pctSum","#pctMul","#hasDim","#dimSum","#dimSub","#dimMul","#dimDiv","#hasEtc","#etcSum","#etcSub","#etcMul","#etcDiv","#calcOpts"],"sources":["../../../src/js/css-calc.ts"],"sourcesContent":["/**\n * css-calc\n */\n\nimport { calc, conversionOptions as CalcOptions } from '@csstools/css-calc';\nimport { CSSToken, TokenType, tokenize } from '@csstools/css-tokenizer';\nimport {\n CacheItem,\n NullObject,\n createCacheKey,\n getCache,\n setCache\n} from './cache';\nimport { isString, isStringOrNumber } from './common';\nimport { resolveVar } from './css-var';\nimport { resolveLengthInPixels, roundToPrecision } from './util';\nimport { MatchedRegExp, Options } from './typedef';\n\n/* constants */\nimport {\n ANGLE,\n LENGTH,\n NUM,\n SYN_FN_CALC,\n SYN_FN_MATH_START,\n SYN_FN_VAR,\n SYN_FN_VAR_START,\n VAL_SPEC\n} from './constant';\nconst {\n CloseParen: PAREN_CLOSE,\n Comment: COMMENT,\n Dimension: DIM,\n EOF,\n Function: FUNC,\n OpenParen: PAREN_OPEN,\n Whitespace: W_SPACE\n} = TokenType;\nconst NAMESPACE = 'css-calc';\n\n/* numeric constants */\nconst TRIA = 3;\nconst HEX = 16;\nconst MAX_PCT = 100;\n\n/* regexp */\nconst REG_FN_CALC = new RegExp(SYN_FN_CALC);\nconst REG_FN_CALC_NUM = new RegExp(`^calc\\\\((${NUM})\\\\)$`);\nconst REG_FN_MATH_START = new RegExp(SYN_FN_MATH_START);\nconst REG_FN_VAR = new RegExp(SYN_FN_VAR);\nconst REG_FN_VAR_START = new RegExp(SYN_FN_VAR_START);\nconst REG_OPERATOR = /\\s[*+/-]\\s/;\nconst REG_TYPE_DIM = new RegExp(`^(${NUM})(${ANGLE}|${LENGTH})$`);\nconst REG_TYPE_DIM_PCT = new RegExp(`^(${NUM})(${ANGLE}|${LENGTH}|%)$`);\nconst REG_TYPE_PCT = new RegExp(`^(${NUM})%$`);\n\n/**\n * Calclator\n */\nexport class Calculator {\n /* private */\n // number\n #hasNum: boolean;\n #numSum: number[];\n #numMul: number[];\n // percentage\n #hasPct: boolean;\n #pctSum: number[];\n #pctMul: number[];\n // dimension\n #hasDim: boolean;\n #dimSum: string[];\n #dimSub: string[];\n #dimMul: string[];\n #dimDiv: string[];\n // et cetra\n #hasEtc: boolean;\n #etcSum: string[];\n #etcSub: string[];\n #etcMul: string[];\n #etcDiv: string[];\n // calc options\n #calcOpts: CalcOptions;\n\n /**\n * constructor\n */\n constructor() {\n // number\n this.#hasNum = false;\n this.#numSum = [];\n this.#numMul = [];\n // percentage\n this.#hasPct = false;\n this.#pctSum = [];\n this.#pctMul = [];\n // dimension\n this.#hasDim = false;\n this.#dimSum = [];\n this.#dimSub = [];\n this.#dimMul = [];\n this.#dimDiv = [];\n // et cetra\n this.#hasEtc = false;\n this.#etcSum = [];\n this.#etcSub = [];\n this.#etcMul = [];\n this.#etcDiv = [];\n // calc options\n this.#calcOpts = {\n toCanonicalUnits: true\n };\n }\n\n get hasNum() {\n return this.#hasNum;\n }\n\n set hasNum(value: boolean) {\n this.#hasNum = !!value;\n }\n\n get numSum() {\n return this.#numSum;\n }\n\n get numMul() {\n return this.#numMul;\n }\n\n get hasPct() {\n return this.#hasPct;\n }\n\n set hasPct(value: boolean) {\n this.#hasPct = !!value;\n }\n\n get pctSum() {\n return this.#pctSum;\n }\n\n get pctMul() {\n return this.#pctMul;\n }\n\n get hasDim() {\n return this.#hasDim;\n }\n\n set hasDim(value: boolean) {\n this.#hasDim = !!value;\n }\n\n get dimSum() {\n return this.#dimSum;\n }\n\n get dimSub() {\n return this.#dimSub;\n }\n\n get dimMul() {\n return this.#dimMul;\n }\n\n get dimDiv() {\n return this.#dimDiv;\n }\n\n get hasEtc() {\n return this.#hasEtc;\n }\n\n set hasEtc(value: boolean) {\n this.#hasEtc = !!value;\n }\n\n get etcSum() {\n return this.#etcSum;\n }\n\n get etcSub() {\n return this.#etcSub;\n }\n\n get etcMul() {\n return this.#etcMul;\n }\n\n get etcDiv() {\n return this.#etcDiv;\n }\n\n /**\n * clear values\n * @returns void\n */\n clear() {\n // number\n this.#hasNum = false;\n this.#numSum = [];\n this.#numMul = [];\n // percentage\n this.#hasPct = false;\n this.#pctSum = [];\n this.#pctMul = [];\n // dimension\n this.#hasDim = false;\n this.#dimSum = [];\n this.#dimSub = [];\n this.#dimMul = [];\n this.#dimDiv = [];\n // et cetra\n this.#hasEtc = false;\n this.#etcSum = [];\n this.#etcSub = [];\n this.#etcMul = [];\n this.#etcDiv = [];\n }\n\n /**\n * sort values\n * @param values - values\n * @returns sorted values\n */\n sort(values: string[] = []): string[] {\n const arr = [...values];\n if (arr.length > 1) {\n arr.sort((a, b) => {\n let res;\n if (REG_TYPE_DIM_PCT.test(a) && REG_TYPE_DIM_PCT.test(b)) {\n const [, valA, unitA] = a.match(REG_TYPE_DIM_PCT) as MatchedRegExp;\n const [, valB, unitB] = b.match(REG_TYPE_DIM_PCT) as MatchedRegExp;\n if (unitA === unitB) {\n if (Number(valA) === Number(valB)) {\n res = 0;\n } else if (Number(valA) > Number(valB)) {\n res = 1;\n } else {\n res = -1;\n }\n } else if (unitA > unitB) {\n res = 1;\n } else {\n res = -1;\n }\n } else {\n if (a === b) {\n res = 0;\n } else if (a > b) {\n res = 1;\n } else {\n res = -1;\n }\n }\n return res;\n });\n }\n return arr;\n }\n\n /**\n * multiply values\n * @returns resolved value\n */\n multiply(): string {\n const value = [];\n let num;\n if (this.#hasNum) {\n num = 1;\n for (const i of this.#numMul) {\n num *= i;\n if (num === 0 || !Number.isFinite(num) || Number.isNaN(num)) {\n break;\n }\n }\n if (!this.#hasPct && !this.#hasDim && !this.hasEtc) {\n if (Number.isFinite(num)) {\n num = roundToPrecision(num, HEX);\n }\n value.push(num);\n }\n }\n if (this.#hasPct) {\n if (typeof num !== 'number') {\n num = 1;\n }\n for (const i of this.#pctMul) {\n num *= i;\n if (num === 0 || !Number.isFinite(num) || Number.isNaN(num)) {\n break;\n }\n }\n if (Number.isFinite(num)) {\n num = `${roundToPrecision(num, HEX)}%`;\n }\n if (!this.#hasDim && !this.hasEtc) {\n value.push(num);\n }\n }\n if (this.#hasDim) {\n let dim = '';\n let mul = '';\n let div = '';\n if (this.#dimMul.length) {\n if (this.#dimMul.length === 1) {\n [mul] = this.#dimMul as [string];\n } else {\n mul = `${this.sort(this.#dimMul).join(' * ')}`;\n }\n }\n if (this.#dimDiv.length) {\n if (this.#dimDiv.length === 1) {\n [div] = this.#dimDiv as [string];\n } else {\n div = `${this.sort(this.#dimDiv).join(' * ')}`;\n }\n }\n if (Number.isFinite(num)) {\n if (mul) {\n if (div) {\n if (div.includes('*')) {\n dim = calc(`calc(${num} * ${mul} / (${div}))`, this.#calcOpts);\n } else {\n dim = calc(`calc(${num} * ${mul} / ${div})`, this.#calcOpts);\n }\n } else {\n dim = calc(`calc(${num} * ${mul})`, this.#calcOpts);\n }\n } else if (div.includes('*')) {\n dim = calc(`calc(${num} / (${div}))`, this.#calcOpts);\n } else {\n dim = calc(`calc(${num} / ${div})`, this.#calcOpts);\n }\n value.push(dim.replace(/^calc/, ''));\n } else {\n if (!value.length && num !== undefined) {\n value.push(num);\n }\n if (mul) {\n if (div) {\n if (div.includes('*')) {\n dim = calc(`calc(${mul} / (${div}))`, this.#calcOpts);\n } else {\n dim = calc(`calc(${mul} / ${div})`, this.#calcOpts);\n }\n } else {\n dim = calc(`calc(${mul})`, this.#calcOpts);\n }\n if (value.length) {\n value.push('*', dim.replace(/^calc/, ''));\n } else {\n value.push(dim.replace(/^calc/, ''));\n }\n } else {\n dim = calc(`calc(${div})`, this.#calcOpts);\n if (value.length) {\n value.push('/', dim.replace(/^calc/, ''));\n } else {\n value.push('1', '/', dim.replace(/^calc/, ''));\n }\n }\n }\n }\n if (this.#hasEtc) {\n if (this.#etcMul.length) {\n if (!value.length && num !== undefined) {\n value.push(num);\n }\n const mul = this.sort(this.#etcMul).join(' * ');\n if (value.length) {\n value.push(`* ${mul}`);\n } else {\n value.push(`${mul}`);\n }\n }\n if (this.#etcDiv.length) {\n const div = this.sort(this.#etcDiv).join(' * ');\n if (div.includes('*')) {\n if (value.length) {\n value.push(`/ (${div})`);\n } else {\n value.push(`1 / (${div})`);\n }\n } else if (value.length) {\n value.push(`/ ${div}`);\n } else {\n value.push(`1 / ${div}`);\n }\n }\n }\n if (value.length) {\n return value.join(' ');\n }\n return '';\n }\n\n /**\n * sum values\n * @returns resolved value\n */\n sum(): string {\n const value = [];\n if (this.#hasNum) {\n let num = 0;\n for (const i of this.#numSum) {\n num += i;\n if (!Number.isFinite(num) || Number.isNaN(num)) {\n break;\n }\n }\n value.push(num);\n }\n if (this.#hasPct) {\n let num: number | string = 0;\n for (const i of this.#pctSum) {\n num += i;\n if (!Number.isFinite(num)) {\n break;\n }\n }\n if (Number.isFinite(num)) {\n num = `${num}%`;\n }\n if (value.length) {\n value.push(`+ ${num}`);\n } else {\n value.push(num);\n }\n }\n if (this.#hasDim) {\n let dim, sum, sub;\n if (this.#dimSum.length) {\n sum = this.sort(this.#dimSum).join(' + ');\n }\n if (this.#dimSub.length) {\n sub = this.sort(this.#dimSub).join(' + ');\n }\n if (sum) {\n if (sub) {\n if (sub.includes('-')) {\n dim = calc(`calc(${sum} - (${sub}))`, this.#calcOpts);\n } else {\n dim = calc(`calc(${sum} - ${sub})`, this.#calcOpts);\n }\n } else {\n dim = calc(`calc(${sum})`, this.#calcOpts);\n }\n } else {\n dim = calc(`calc(-1 * (${sub}))`, this.#calcOpts);\n }\n if (value.length) {\n value.push('+', dim.replace(/^calc/, ''));\n } else {\n value.push(dim.replace(/^calc/, ''));\n }\n }\n if (this.#hasEtc) {\n if (this.#etcSum.length) {\n const sum = this.sort(this.#etcSum)\n .map(item => {\n let res;\n if (\n REG_OPERATOR.test(item) &&\n !item.startsWith('(') &&\n !item.endsWith(')')\n ) {\n res = `(${item})`;\n } else {\n res = item;\n }\n return res;\n })\n .join(' + ');\n if (value.length) {\n if (this.#etcSum.length > 1) {\n value.push(`+ (${sum})`);\n } else {\n value.push(`+ ${sum}`);\n }\n } else {\n value.push(`${sum}`);\n }\n }\n if (this.#etcSub.length) {\n const sub = this.sort(this.#etcSub)\n .map(item => {\n let res;\n if (\n REG_OPERATOR.test(item) &&\n !item.startsWith('(') &&\n !item.endsWith(')')\n ) {\n res = `(${item})`;\n } else {\n res = item;\n }\n return res;\n })\n .join(' + ');\n if (value.length) {\n if (this.#etcSub.length > 1) {\n value.push(`- (${sub})`);\n } else {\n value.push(`- ${sub}`);\n }\n } else if (this.#etcSub.length > 1) {\n value.push(`-1 * (${sub})`);\n } else {\n value.push(`-1 * ${sub}`);\n }\n }\n }\n if (value.length) {\n return value.join(' ');\n }\n return '';\n }\n}\n\n/**\n * sort calc values\n * @param values - values to sort\n * @param [finalize] - finalize values\n * @returns sorted values\n */\nexport const sortCalcValues = (\n values: (number | string)[] = [],\n finalize: boolean = false\n): string => {\n if (values.length < TRIA) {\n throw new Error(`Unexpected array length ${values.length}.`);\n }\n const start = values.shift();\n if (!isString(start) || !start.endsWith('(')) {\n throw new Error(`Unexpected token ${start}.`);\n }\n const end = values.pop();\n if (end !== ')') {\n throw new Error(`Unexpected token ${end}.`);\n }\n if (values.length === 1) {\n const [value] = values;\n if (!isStringOrNumber(value)) {\n throw new Error(`Unexpected token ${value}.`);\n }\n return `${start}${value}${end}`;\n }\n const sortedValues = [];\n const cal = new Calculator();\n let operator: string = '';\n const l = values.length;\n for (let i = 0; i < l; i++) {\n const value = values[i];\n if (!isStringOrNumber(value)) {\n throw new Error(`Unexpected token ${value}.`);\n }\n if (value === '*' || value === '/') {\n operator = value;\n } else if (value === '+' || value === '-') {\n const sortedValue = cal.multiply();\n if (sortedValue) {\n sortedValues.push(sortedValue, value);\n }\n cal.clear();\n operator = '';\n } else {\n const numValue = Number(value);\n const strValue = `${value}`;\n switch (operator) {\n case '/': {\n if (Number.isFinite(numValue)) {\n cal.hasNum = true;\n cal.numMul.push(1 / numValue);\n } else if (REG_TYPE_PCT.test(strValue)) {\n const [, val] = strValue.match(REG_TYPE_PCT) as MatchedRegExp;\n cal.hasPct = true;\n cal.pctMul.push((MAX_PCT * MAX_PCT) / Number(val));\n } else if (REG_TYPE_DIM.test(strValue)) {\n cal.hasDim = true;\n cal.dimDiv.push(strValue);\n } else {\n cal.hasEtc = true;\n cal.etcDiv.push(strValue);\n }\n break;\n }\n case '*':\n default: {\n if (Number.isFinite(numValue)) {\n cal.hasNum = true;\n cal.numMul.push(numValue);\n } else if (REG_TYPE_PCT.test(strValue)) {\n const [, val] = strValue.match(REG_TYPE_PCT) as MatchedRegExp;\n cal.hasPct = true;\n cal.pctMul.push(Number(val));\n } else if (REG_TYPE_DIM.test(strValue)) {\n cal.hasDim = true;\n cal.dimMul.push(strValue);\n } else {\n cal.hasEtc = true;\n cal.etcMul.push(strValue);\n }\n }\n }\n }\n if (i === l - 1) {\n const sortedValue = cal.multiply();\n if (sortedValue) {\n sortedValues.push(sortedValue);\n }\n cal.clear();\n operator = '';\n }\n }\n let resolvedValue = '';\n if (finalize && (sortedValues.includes('+') || sortedValues.includes('-'))) {\n const finalizedValues = [];\n cal.clear();\n operator = '';\n const l = sortedValues.length;\n for (let i = 0; i < l; i++) {\n const value = sortedValues[i];\n if (isStringOrNumber(value)) {\n if (value === '+' || value === '-') {\n operator = value;\n } else {\n const numValue = Number(value);\n const strValue = `${value}`;\n switch (operator) {\n case '-': {\n if (Number.isFinite(numValue)) {\n cal.hasNum = true;\n cal.numSum.push(-1 * numValue);\n } else if (REG_TYPE_PCT.test(strValue)) {\n const [, val] = strValue.match(REG_TYPE_PCT) as MatchedRegExp;\n cal.hasPct = true;\n cal.pctSum.push(-1 * Number(val));\n } else if (REG_TYPE_DIM.test(strValue)) {\n cal.hasDim = true;\n cal.dimSub.push(strValue);\n } else {\n cal.hasEtc = true;\n cal.etcSub.push(strValue);\n }\n break;\n }\n case '+':\n default: {\n if (Number.isFinite(numValue)) {\n cal.hasNum = true;\n cal.numSum.push(numValue);\n } else if (REG_TYPE_PCT.test(strValue)) {\n const [, val] = strValue.match(REG_TYPE_PCT) as MatchedRegExp;\n cal.hasPct = true;\n cal.pctSum.push(Number(val));\n } else if (REG_TYPE_DIM.test(strValue)) {\n cal.hasDim = true;\n cal.dimSum.push(strValue);\n } else {\n cal.hasEtc = true;\n cal.etcSum.push(strValue);\n }\n }\n }\n }\n }\n if (i === l - 1) {\n const sortedValue = cal.sum();\n if (sortedValue) {\n finalizedValues.push(sortedValue);\n }\n cal.clear();\n operator = '';\n }\n }\n resolvedValue = finalizedValues.join(' ').replace(/\\+\\s-/g, '- ');\n } else {\n resolvedValue = sortedValues.join(' ').replace(/\\+\\s-/g, '- ');\n }\n if (\n resolvedValue.startsWith('(') &&\n resolvedValue.endsWith(')') &&\n resolvedValue.lastIndexOf('(') === 0 &&\n resolvedValue.indexOf(')') === resolvedValue.length - 1\n ) {\n resolvedValue = resolvedValue.replace(/^\\(/, '').replace(/\\)$/, '');\n }\n return `${start}${resolvedValue}${end}`;\n};\n\n/**\n * serialize calc\n * @param value - CSS value\n * @param [opt] - options\n * @returns serialized value\n */\nexport const serializeCalc = (value: string, opt: Options = {}): string => {\n const { format = '' } = opt;\n if (isString(value)) {\n if (!REG_FN_VAR_START.test(value) || format !== VAL_SPEC) {\n return value;\n }\n value = value.toLowerCase().trim();\n } else {\n throw new TypeError(`${value} is not a string.`);\n }\n const cacheKey: string = createCacheKey(\n {\n namespace: NAMESPACE,\n name: 'serializeCalc',\n value\n },\n opt\n );\n const cachedResult = getCache(cacheKey);\n if (cachedResult instanceof CacheItem) {\n return cachedResult.item as string;\n }\n const items: string[] = tokenize({ css: value })\n .map((token: CSSToken): string => {\n const [type, value] = token as [TokenType, string];\n let res = '';\n if (type !== W_SPACE && type !== COMMENT) {\n res = value;\n }\n return res;\n })\n .filter(v => v);\n let startIndex = items.findLastIndex((item: string) => /\\($/.test(item));\n while (startIndex) {\n const endIndex = items.findIndex((item: unknown, index: number) => {\n return item === ')' && index > startIndex;\n });\n const slicedValues: string[] = items.slice(startIndex, endIndex + 1);\n let serializedValue: string = sortCalcValues(slicedValues);\n if (REG_FN_VAR_START.test(serializedValue)) {\n serializedValue = calc(serializedValue, {\n toCanonicalUnits: true\n });\n }\n items.splice(startIndex, endIndex - startIndex + 1, serializedValue);\n startIndex = items.findLastIndex((item: string) => /\\($/.test(item));\n }\n const serializedCalc = sortCalcValues(items, true);\n setCache(cacheKey, serializedCalc);\n return serializedCalc;\n};\n\n/**\n * resolve dimension\n * @param token - CSS token\n * @param [opt] - options\n * @returns resolved value\n */\nexport const resolveDimension = (\n token: CSSToken,\n opt: Options = {}\n): string | NullObject => {\n if (!Array.isArray(token)) {\n throw new TypeError(`${token} is not an array.`);\n }\n const [, , , , detail = {}] = token;\n const { unit, value } = detail as {\n unit: string;\n value: number;\n };\n if (unit === 'px') {\n return `${value}${unit}`;\n }\n const pixelValue = resolveLengthInPixels(Number(value), unit, opt);\n if (Number.isFinite(pixelValue)) {\n return `${roundToPrecision(pixelValue, HEX)}px`;\n }\n return new NullObject();\n};\n\n/**\n * parse tokens\n * @param tokens - CSS tokens\n * @param [opt] - options\n * @returns parsed tokens\n */\nexport const parseTokens = (\n tokens: CSSToken[],\n opt: Options = {}\n): string[] => {\n if (!Array.isArray(tokens)) {\n throw new TypeError(`${tokens} is not an array.`);\n }\n const { format = '' } = opt;\n const mathFunc = new Set();\n let nest = 0;\n const res: string[] = [];\n while (tokens.length) {\n const token = tokens.shift();\n if (!Array.isArray(token)) {\n throw new TypeError(`${token} is not an array.`);\n }\n const [type = '', value = ''] = token as [TokenType, string];\n switch (type) {\n case DIM: {\n if (format === VAL_SPEC && !mathFunc.has(nest)) {\n res.push(value);\n } else {\n const resolvedValue = resolveDimension(token, opt);\n if (isString(resolvedValue)) {\n res.push(resolvedValue);\n } else {\n res.push(value);\n }\n }\n break;\n }\n case FUNC:\n case PAREN_OPEN: {\n res.push(value);\n nest++;\n if (REG_FN_MATH_START.test(value)) {\n mathFunc.add(nest);\n }\n break;\n }\n case PAREN_CLOSE: {\n if (res.length) {\n const lastValue = res[res.length - 1];\n if (lastValue === ' ') {\n res.splice(-1, 1, value);\n } else {\n res.push(value);\n }\n } else {\n res.push(value);\n }\n if (mathFunc.has(nest)) {\n mathFunc.delete(nest);\n }\n nest--;\n break;\n }\n case W_SPACE: {\n if (res.length) {\n const lastValue = res[res.length - 1];\n if (\n isString(lastValue) &&\n !lastValue.endsWith('(') &&\n lastValue !== ' '\n ) {\n res.push(value);\n }\n }\n break;\n }\n default: {\n if (type !== COMMENT && type !== EOF) {\n res.push(value);\n }\n }\n }\n }\n return res;\n};\n\n/**\n * CSS calc()\n * @param value - CSS value including calc()\n * @param [opt] - options\n * @returns resolved value\n */\nexport const cssCalc = (value: string, opt: Options = {}): string => {\n const { format = '' } = opt;\n if (isString(value)) {\n if (REG_FN_VAR.test(value)) {\n if (format === VAL_SPEC) {\n return value;\n } else {\n const resolvedValue = resolveVar(value, opt);\n if (isString(resolvedValue)) {\n return resolvedValue;\n } else {\n return '';\n }\n }\n } else if (!REG_FN_CALC.test(value)) {\n return value;\n }\n value = value.toLowerCase().trim();\n } else {\n throw new TypeError(`${value} is not a string.`);\n }\n const cacheKey: string = createCacheKey(\n {\n namespace: NAMESPACE,\n name: 'cssCalc',\n value\n },\n opt\n );\n const cachedResult = getCache(cacheKey);\n if (cachedResult instanceof CacheItem) {\n return cachedResult.item as string;\n }\n const tokens = tokenize({ css: value });\n const values = parseTokens(tokens, opt);\n let resolvedValue: string = calc(values.join(''), {\n toCanonicalUnits: true\n });\n if (REG_FN_VAR_START.test(value)) {\n if (REG_TYPE_DIM_PCT.test(resolvedValue)) {\n const [, val, unit] = resolvedValue.match(\n REG_TYPE_DIM_PCT\n ) as MatchedRegExp;\n resolvedValue = `${roundToPrecision(Number(val), HEX)}${unit}`;\n }\n // wrap with `calc()`\n if (\n resolvedValue &&\n !REG_FN_VAR_START.test(resolvedValue) &&\n format === VAL_SPEC\n ) {\n resolvedValue = `calc(${resolvedValue})`;\n }\n }\n if (format === VAL_SPEC) {\n if (/\\s[-+*/]\\s/.test(resolvedValue) && !resolvedValue.includes('NaN')) {\n resolvedValue = serializeCalc(resolvedValue, opt);\n } else if (REG_FN_CALC_NUM.test(resolvedValue)) {\n const [, val] = resolvedValue.match(REG_FN_CALC_NUM) as MatchedRegExp;\n resolvedValue = `calc(${roundToPrecision(Number(val), HEX)})`;\n }\n }\n setCache(cacheKey, resolvedValue);\n return resolvedValue;\n};\n"],"mappings":";;;;;;;;;;;AA6BA,IAAM,EACJ,YAAY,aACZ,SAAS,SACT,WAAW,KACX,KACA,UAAU,MACV,WAAW,YACX,YAAY,YACV;AACJ,IAAM,YAAY;AAGlB,IAAM,OAAO;AACb,IAAM,MAAM;AACZ,IAAM,UAAU;AAGhB,IAAM,cAAc,IAAI,OAAO,YAAY;AAC3C,IAAM,kBAAkB,IAAI,OAAO,YAAY,IAAI,OAAO;AAC1D,IAAM,oBAAoB,IAAI,OAAO,kBAAkB;AACvD,IAAM,aAAa,IAAI,OAAO,WAAW;AACzC,IAAM,mBAAmB,IAAI,OAAO,iBAAiB;AACrD,IAAM,eAAe;AACrB,IAAM,eAAe,IAAI,OAAO,KAAK,IAAI,IAAI,MAAM,GAAG,OAAO,IAAI;AACjE,IAAM,mBAAmB,IAAI,OAAO,KAAK,IAAI,IAAI,MAAM,GAAG,OAAO,MAAM;AACvE,IAAM,eAAe,IAAI,OAAO,KAAK,IAAI,KAAK;;;;AAK9C,IAAa,aAAb,MAAwB;CAGtB;CACA;CACA;CAEA;CACA;CACA;CAEA;CACA;CACA;CACA;CACA;CAEA;CACA;CACA;CACA;CACA;CAEA;;;;CAKA,cAAc;AAEZ,QAAA,SAAe;AACf,QAAA,SAAe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C,OAAM,IAAI,UAAU,GAAG,MAAM,mBAAmB;CAElD,MAAM,WAAmB,eACvB;EACE,WAAW;EACX,MAAM;EACN;EACD,EACD,IACD;CACD,MAAM,eAAe,SAAS,SAAS;AACvC,KAAI,wBAAwB,UAC1B,QAAO,aAAa;CAItB,IAAI,gBAAwB,KADb,YADA,SAAS,EAAE,KAAK,OAAO,CAAC,EACJ,IAAI,CACC,KAAK,GAAG,EAAE,EAChD,kBAAkB,MACnB,CAAC;AACF,KAAI,iBAAiB,KAAK,MAAM,EAAE;AAChC,MAAI,iBAAiB,KAAK,cAAc,EAAE;GACxC,MAAM,GAAG,KAAK,QAAQ,cAAc,MAClC,iBACD;AACD,mBAAgB,GAAG,iBAAiB,OAAO,IAAI,EAAE,IAAI,GAAG;;AAG1D,MACE,iBACA,CAAC,iBAAiB,KAAK,cAAc,IACrC,WAAA,iBAEA,iBAAgB,QAAQ,cAAc;;AAG1C,KAAI,WAAA;MACE,aAAa,KAAK,cAAc,IAAI,CAAC,cAAc,SAAS,MAAM,CACpE,iBAAgB,cAAc,eAAe,IAAI;WACxC,gBAAgB,KAAK,cAAc,EAAE;GAC9C,MAAM,GAAG,OAAO,cAAc,MAAM,gBAAgB;AACpD,mBAAgB,QAAQ,iBAAiB,OAAO,IAAI,EAAE,IAAI,CAAC;;;AAG/D,UAAS,UAAU,cAAc;AACjC,QAAO"} \ No newline at end of file diff --git a/node_modules/@asamuzakjp/css-color/dist/esm/js/css-gradient.d.ts b/node_modules/@asamuzakjp/css-color/dist/esm/js/css-gradient.d.ts new file mode 100644 index 00000000..cf0b891a --- /dev/null +++ b/node_modules/@asamuzakjp/css-color/dist/esm/js/css-gradient.d.ts @@ -0,0 +1,79 @@ +import { Options } from './typedef.js'; +/** + * @type ColorStopList - list of color stops + */ +type ColorStopList = [string, string, ...string[]]; +/** + * @typedef ValidateGradientLine - validate gradient line + * @property line - gradient line + * @property valid - result + */ +interface ValidateGradientLine { + line: string; + valid: boolean; +} +/** + * @typedef ValidateColorStops - validate color stops + * @property colorStops - list of color stops + * @property valid - result + */ +interface ValidateColorStops { + colorStops: string[]; + valid: boolean; +} +/** + * @typedef Gradient - parsed CSS gradient + * @property value - input value + * @property type - gradient type + * @property [gradientLine] - gradient line + * @property colorStopList - list of color stops + */ +interface Gradient { + value: string; + type: string; + gradientLine?: string; + colorStopList: ColorStopList; +} +/** + * get gradient type + * @param value - gradient value + * @returns gradient type + */ +export declare const getGradientType: (value: string) => string; +/** + * validate gradient line + * @param value - gradient line value + * @param type - gradient type + * @returns result + */ +export declare const validateGradientLine: (value: string, type: string) => ValidateGradientLine; +/** + * validate color stop list + * @param list + * @param type + * @param [opt] + * @returns result + */ +export declare const validateColorStopList: (list: string[], type: string, opt?: Options) => ValidateColorStops; +/** + * parse CSS gradient + * @param value - gradient value + * @param [opt] - options + * @returns parsed result + */ +export declare const parseGradient: (value: string, opt?: Options) => Gradient | null; +/** + * resolve CSS gradient + * @param value - CSS value + * @param [opt] - options + * @returns result + */ +export declare const resolveGradient: (value: string, opt?: Options) => string; +/** + * is CSS gradient + * @param value - CSS value + * @param [opt] - options + * @returns result + */ +export declare const isGradient: (value: string, opt?: Options) => boolean; +export {}; diff --git a/node_modules/@asamuzakjp/css-color/dist/esm/js/css-gradient.js b/node_modules/@asamuzakjp/css-color/dist/esm/js/css-gradient.js new file mode 100644 index 00000000..9d5ed564 --- /dev/null +++ b/node_modules/@asamuzakjp/css-color/dist/esm/js/css-gradient.js @@ -0,0 +1,257 @@ +import { isString } from "./common.js"; +import { ANGLE, CS_HUE, CS_RECT, LENGTH, NUM, NUM_POSITIVE, PCT, VAL_COMP } from "./constant.js"; +import { resolveColor } from "./resolve.js"; +import { isColor, splitValue } from "./util.js"; +import { CacheItem, createCacheKey, getCache, setCache } from "./cache.js"; +//#region src/js/css-gradient.ts +/** +* css-gradient +*/ +var NAMESPACE = "css-gradient"; +var DIM_ANGLE = `${NUM}(?:${ANGLE})`; +var DIM_ANGLE_PCT = `${DIM_ANGLE}|${PCT}`; +var DIM_LEN_PCT = `${`${NUM}(?:${LENGTH})|0`}|${PCT}`; +var DIM_LEN_PCT_POSI = `${NUM_POSITIVE}(?:${LENGTH}|%)|0`; +var DIM_LEN_POSI = `${NUM_POSITIVE}(?:${LENGTH})|0`; +var CTR = "center"; +var L_R = "left|right"; +var T_B = "top|bottom"; +var S_E = "start|end"; +var AXIS_X = `${L_R}|x-(?:${S_E})`; +var AXIS_Y = `${T_B}|y-(?:${S_E})`; +var BLOCK = `block-(?:${S_E})`; +var INLINE = `inline-(?:${S_E})`; +var POS_1 = `${CTR}|${AXIS_X}|${AXIS_Y}|${BLOCK}|${INLINE}|${DIM_LEN_PCT}`; +var POS_2 = [ + `(?:${CTR}|${AXIS_X})\\s+(?:${CTR}|${AXIS_Y})`, + `(?:${CTR}|${AXIS_Y})\\s+(?:${CTR}|${AXIS_X})`, + `(?:${CTR}|${AXIS_X}|${DIM_LEN_PCT})\\s+(?:${CTR}|${AXIS_Y}|${DIM_LEN_PCT})`, + `(?:${CTR}|${BLOCK})\\s+(?:${CTR}|${INLINE})`, + `(?:${CTR}|${INLINE})\\s+(?:${CTR}|${BLOCK})`, + `(?:${CTR}|${S_E})\\s+(?:${CTR}|${S_E})` +].join("|"); +var POS_4 = [ + `(?:${AXIS_X})\\s+(?:${DIM_LEN_PCT})\\s+(?:${AXIS_Y})\\s+(?:${DIM_LEN_PCT})`, + `(?:${AXIS_Y})\\s+(?:${DIM_LEN_PCT})\\s+(?:${AXIS_X})\\s+(?:${DIM_LEN_PCT})`, + `(?:${BLOCK})\\s+(?:${DIM_LEN_PCT})\\s+(?:${INLINE})\\s+(?:${DIM_LEN_PCT})`, + `(?:${INLINE})\\s+(?:${DIM_LEN_PCT})\\s+(?:${BLOCK})\\s+(?:${DIM_LEN_PCT})`, + `(?:${S_E})\\s+(?:${DIM_LEN_PCT})\\s+(?:${S_E})\\s+(?:${DIM_LEN_PCT})` +].join("|"); +var RAD_EXTENT = "(?:clos|farth)est-(?:corner|side)"; +var RAD_SIZE = [ + `${RAD_EXTENT}(?:\\s+${RAD_EXTENT})?`, + `${DIM_LEN_POSI}`, + `(?:${DIM_LEN_PCT_POSI})\\s+(?:${DIM_LEN_PCT_POSI})` +].join("|"); +var RAD_SHAPE = "circle|ellipse"; +var FROM_ANGLE = `from\\s+${DIM_ANGLE}`; +var AT_POSITION = `at\\s+(?:${POS_1}|${POS_2}|${POS_4})`; +var TO_SIDE_CORNER = `to\\s+(?:(?:${L_R})(?:\\s(?:${T_B}))?|(?:${T_B})(?:\\s(?:${L_R}))?)`; +var IN_COLOR_SPACE = `in\\s+(?:${CS_RECT}|${CS_HUE})`; +var REG_GRAD = /^(?:repeating-)?(?:conic|linear|radial)-gradient\(/; +var REG_GRAD_CAPT = /^((?:repeating-)?(?:conic|linear|radial)-gradient)\(/; +/** +* get gradient type +* @param value - gradient value +* @returns gradient type +*/ +var getGradientType = (value) => { + if (isString(value)) { + value = value.trim(); + if (REG_GRAD.test(value)) { + const [, type] = value.match(REG_GRAD_CAPT); + return type; + } + } + return ""; +}; +/** +* validate gradient line +* @param value - gradient line value +* @param type - gradient type +* @returns result +*/ +var validateGradientLine = (value, type) => { + if (isString(value) && isString(type)) { + value = value.trim(); + type = type.trim(); + let lineSyntax = ""; + const defaultValues = []; + if (/^(?:repeating-)?linear-gradient$/.test(type)) { + lineSyntax = [`(?:${DIM_ANGLE}|${TO_SIDE_CORNER})(?:\\s+${IN_COLOR_SPACE})?`, `${IN_COLOR_SPACE}(?:\\s+(?:${DIM_ANGLE}|${TO_SIDE_CORNER}))?`].join("|"); + defaultValues.push(/to\s+bottom/); + } else if (/^(?:repeating-)?radial-gradient$/.test(type)) { + lineSyntax = [ + `(?:${RAD_SHAPE})(?:\\s+(?:${RAD_SIZE}))?(?:\\s+${AT_POSITION})?(?:\\s+${IN_COLOR_SPACE})?`, + `(?:${RAD_SIZE})(?:\\s+(?:${RAD_SHAPE}))?(?:\\s+${AT_POSITION})?(?:\\s+${IN_COLOR_SPACE})?`, + `${AT_POSITION}(?:\\s+${IN_COLOR_SPACE})?`, + `${IN_COLOR_SPACE}(?:\\s+${RAD_SHAPE})(?:\\s+(?:${RAD_SIZE}))?(?:\\s+${AT_POSITION})?`, + `${IN_COLOR_SPACE}(?:\\s+${RAD_SIZE})(?:\\s+(?:${RAD_SHAPE}))?(?:\\s+${AT_POSITION})?`, + `${IN_COLOR_SPACE}(?:\\s+${AT_POSITION})?` + ].join("|"); + defaultValues.push(/ellipse/, /farthest-corner/, /at\s+center/); + } else if (/^(?:repeating-)?conic-gradient$/.test(type)) { + lineSyntax = [ + `${FROM_ANGLE}(?:\\s+${AT_POSITION})?(?:\\s+${IN_COLOR_SPACE})?`, + `${AT_POSITION}(?:\\s+${IN_COLOR_SPACE})?`, + `${IN_COLOR_SPACE}(?:\\s+${FROM_ANGLE})?(?:\\s+${AT_POSITION})?` + ].join("|"); + defaultValues.push(/at\s+center/); + } + if (lineSyntax) { + const valid = new RegExp(`^(?:${lineSyntax})$`).test(value); + if (valid) { + let line = value; + for (const defaultValue of defaultValues) line = line.replace(defaultValue, ""); + line = line.replace(/\s{2,}/g, " ").trim(); + return { + line, + valid + }; + } + return { + valid, + line: value + }; + } + } + return { + line: value, + valid: false + }; +}; +/** +* validate color stop list +* @param list +* @param type +* @param [opt] +* @returns result +*/ +var validateColorStopList = (list, type, opt = {}) => { + if (Array.isArray(list) && list.length > 1) { + const dimension = /^(?:repeating-)?conic-gradient$/.test(type) ? DIM_ANGLE_PCT : DIM_LEN_PCT; + const regColorHint = new RegExp(`^(?:${dimension})$`); + const regDimension = new RegExp(`(?:\\s+(?:${dimension})){1,2}$`); + const valueTypes = []; + const valueList = []; + for (const item of list) if (isString(item)) if (regColorHint.test(item)) { + valueTypes.push("hint"); + valueList.push(item); + } else { + const itemColor = item.replace(regDimension, ""); + if (isColor(itemColor, { format: "specifiedValue" })) { + const resolvedColor = resolveColor(itemColor, opt); + valueTypes.push("color"); + valueList.push(item.replace(itemColor, resolvedColor)); + } else return { + colorStops: list, + valid: false + }; + } + return { + valid: /^color(?:,(?:hint,)?color)+$/.test(valueTypes.join(",")), + colorStops: valueList + }; + } + return { + colorStops: list, + valid: false + }; +}; +/** +* parse CSS gradient +* @param value - gradient value +* @param [opt] - options +* @returns parsed result +*/ +var parseGradient = (value, opt = {}) => { + if (isString(value)) { + value = value.trim(); + const cacheKey = createCacheKey({ + namespace: NAMESPACE, + name: "parseGradient", + value + }, opt); + const cachedResult = getCache(cacheKey); + if (cachedResult instanceof CacheItem) { + if (cachedResult.isNull) return null; + return cachedResult.item; + } + const type = getGradientType(value); + const gradValue = value.replace(REG_GRAD, "").replace(/\)$/, ""); + if (type && gradValue) { + const [lineOrColorStop = "", ...itemList] = splitValue(gradValue, { delimiter: "," }); + const dimension = /^(?:repeating-)?conic-gradient$/.test(type) ? DIM_ANGLE_PCT : DIM_LEN_PCT; + const regDimension = new RegExp(`(?:\\s+(?:${dimension})){1,2}$`); + let colorStop = ""; + if (regDimension.test(lineOrColorStop)) { + const itemColor = lineOrColorStop.replace(regDimension, ""); + if (isColor(itemColor, { format: "specifiedValue" })) { + const resolvedColor = resolveColor(itemColor, opt); + colorStop = lineOrColorStop.replace(itemColor, resolvedColor); + } + } else if (isColor(lineOrColorStop, { format: "specifiedValue" })) colorStop = resolveColor(lineOrColorStop, opt); + if (colorStop) { + itemList.unshift(colorStop); + const { colorStops, valid } = validateColorStopList(itemList, type, opt); + if (valid) { + const res = { + value, + type, + colorStopList: colorStops + }; + setCache(cacheKey, res); + return res; + } + } else if (itemList.length > 1) { + const { line: gradientLine, valid: validLine } = validateGradientLine(lineOrColorStop, type); + const { colorStops, valid: validColorStops } = validateColorStopList(itemList, type, opt); + if (validLine && validColorStops) { + const res = { + value, + type, + gradientLine, + colorStopList: colorStops + }; + setCache(cacheKey, res); + return res; + } + } + } + setCache(cacheKey, null); + return null; + } + return null; +}; +/** +* resolve CSS gradient +* @param value - CSS value +* @param [opt] - options +* @returns result +*/ +var resolveGradient = (value, opt = {}) => { + const { format = VAL_COMP } = opt; + const gradient = parseGradient(value, opt); + if (gradient) { + const { type = "", gradientLine = "", colorStopList = [] } = gradient; + if (type && Array.isArray(colorStopList) && colorStopList.length > 1) { + if (gradientLine) return `${type}(${gradientLine}, ${colorStopList.join(", ")})`; + return `${type}(${colorStopList.join(", ")})`; + } + } + if (format === "specifiedValue") return ""; + return "none"; +}; +/** +* is CSS gradient +* @param value - CSS value +* @param [opt] - options +* @returns result +*/ +var isGradient = (value, opt = {}) => { + return parseGradient(value, opt) !== null; +}; +//#endregion +export { isGradient, resolveGradient }; + +//# sourceMappingURL=css-gradient.js.map \ No newline at end of file diff --git a/node_modules/@asamuzakjp/css-color/dist/esm/js/css-gradient.js.map b/node_modules/@asamuzakjp/css-color/dist/esm/js/css-gradient.js.map new file mode 100644 index 00000000..deba4e6b --- /dev/null +++ b/node_modules/@asamuzakjp/css-color/dist/esm/js/css-gradient.js.map @@ -0,0 +1 @@ +{"version":3,"file":"css-gradient.js","names":[],"sources":["../../../src/js/css-gradient.ts"],"sourcesContent":["/**\n * css-gradient\n */\n\nimport { CacheItem, createCacheKey, getCache, setCache } from './cache';\nimport { resolveColor } from './resolve';\nimport { isString } from './common';\nimport { MatchedRegExp, Options } from './typedef';\nimport { isColor, splitValue } from './util';\n\n/* constants */\nimport {\n ANGLE,\n CS_HUE,\n CS_RECT,\n LENGTH,\n NUM,\n NUM_POSITIVE,\n PCT,\n VAL_COMP,\n VAL_SPEC\n} from './constant';\nconst NAMESPACE = 'css-gradient';\nconst DIM_ANGLE = `${NUM}(?:${ANGLE})`;\nconst DIM_ANGLE_PCT = `${DIM_ANGLE}|${PCT}`;\nconst DIM_LEN = `${NUM}(?:${LENGTH})|0`;\nconst DIM_LEN_PCT = `${DIM_LEN}|${PCT}`;\nconst DIM_LEN_PCT_POSI = `${NUM_POSITIVE}(?:${LENGTH}|%)|0`;\nconst DIM_LEN_POSI = `${NUM_POSITIVE}(?:${LENGTH})|0`;\nconst CTR = 'center';\nconst L_R = 'left|right';\nconst T_B = 'top|bottom';\nconst S_E = 'start|end';\nconst AXIS_X = `${L_R}|x-(?:${S_E})`;\nconst AXIS_Y = `${T_B}|y-(?:${S_E})`;\nconst BLOCK = `block-(?:${S_E})`;\nconst INLINE = `inline-(?:${S_E})`;\nconst POS_1 = `${CTR}|${AXIS_X}|${AXIS_Y}|${BLOCK}|${INLINE}|${DIM_LEN_PCT}`;\nconst POS_2 = [\n `(?:${CTR}|${AXIS_X})\\\\s+(?:${CTR}|${AXIS_Y})`,\n `(?:${CTR}|${AXIS_Y})\\\\s+(?:${CTR}|${AXIS_X})`,\n `(?:${CTR}|${AXIS_X}|${DIM_LEN_PCT})\\\\s+(?:${CTR}|${AXIS_Y}|${DIM_LEN_PCT})`,\n `(?:${CTR}|${BLOCK})\\\\s+(?:${CTR}|${INLINE})`,\n `(?:${CTR}|${INLINE})\\\\s+(?:${CTR}|${BLOCK})`,\n `(?:${CTR}|${S_E})\\\\s+(?:${CTR}|${S_E})`\n].join('|');\nconst POS_4 = [\n `(?:${AXIS_X})\\\\s+(?:${DIM_LEN_PCT})\\\\s+(?:${AXIS_Y})\\\\s+(?:${DIM_LEN_PCT})`,\n `(?:${AXIS_Y})\\\\s+(?:${DIM_LEN_PCT})\\\\s+(?:${AXIS_X})\\\\s+(?:${DIM_LEN_PCT})`,\n `(?:${BLOCK})\\\\s+(?:${DIM_LEN_PCT})\\\\s+(?:${INLINE})\\\\s+(?:${DIM_LEN_PCT})`,\n `(?:${INLINE})\\\\s+(?:${DIM_LEN_PCT})\\\\s+(?:${BLOCK})\\\\s+(?:${DIM_LEN_PCT})`,\n `(?:${S_E})\\\\s+(?:${DIM_LEN_PCT})\\\\s+(?:${S_E})\\\\s+(?:${DIM_LEN_PCT})`\n].join('|');\nconst RAD_EXTENT = '(?:clos|farth)est-(?:corner|side)';\nconst RAD_SIZE = [\n `${RAD_EXTENT}(?:\\\\s+${RAD_EXTENT})?`,\n `${DIM_LEN_POSI}`,\n `(?:${DIM_LEN_PCT_POSI})\\\\s+(?:${DIM_LEN_PCT_POSI})`\n].join('|');\nconst RAD_SHAPE = 'circle|ellipse';\nconst FROM_ANGLE = `from\\\\s+${DIM_ANGLE}`;\nconst AT_POSITION = `at\\\\s+(?:${POS_1}|${POS_2}|${POS_4})`;\nconst TO_SIDE_CORNER = `to\\\\s+(?:(?:${L_R})(?:\\\\s(?:${T_B}))?|(?:${T_B})(?:\\\\s(?:${L_R}))?)`;\nconst IN_COLOR_SPACE = `in\\\\s+(?:${CS_RECT}|${CS_HUE})`;\n\n/* type definitions */\n/**\n * @type ColorStopList - list of color stops\n */\ntype ColorStopList = [string, string, ...string[]];\n\n/**\n * @typedef ValidateGradientLine - validate gradient line\n * @property line - gradient line\n * @property valid - result\n */\ninterface ValidateGradientLine {\n line: string;\n valid: boolean;\n}\n\n/**\n * @typedef ValidateColorStops - validate color stops\n * @property colorStops - list of color stops\n * @property valid - result\n */\ninterface ValidateColorStops {\n colorStops: string[];\n valid: boolean;\n}\n\n/**\n * @typedef Gradient - parsed CSS gradient\n * @property value - input value\n * @property type - gradient type\n * @property [gradientLine] - gradient line\n * @property colorStopList - list of color stops\n */\ninterface Gradient {\n value: string;\n type: string;\n gradientLine?: string;\n colorStopList: ColorStopList;\n}\n\n/* regexp */\nconst REG_GRAD = /^(?:repeating-)?(?:conic|linear|radial)-gradient\\(/;\nconst REG_GRAD_CAPT = /^((?:repeating-)?(?:conic|linear|radial)-gradient)\\(/;\n\n/**\n * get gradient type\n * @param value - gradient value\n * @returns gradient type\n */\nexport const getGradientType = (value: string): string => {\n if (isString(value)) {\n value = value.trim();\n if (REG_GRAD.test(value)) {\n const [, type] = value.match(REG_GRAD_CAPT) as MatchedRegExp;\n return type;\n }\n }\n return '';\n};\n\n/**\n * validate gradient line\n * @param value - gradient line value\n * @param type - gradient type\n * @returns result\n */\nexport const validateGradientLine = (\n value: string,\n type: string\n): ValidateGradientLine => {\n if (isString(value) && isString(type)) {\n value = value.trim();\n type = type.trim();\n let lineSyntax = '';\n const defaultValues = [];\n if (/^(?:repeating-)?linear-gradient$/.test(type)) {\n /*\n * = [\n * [ | to ] ||\n * \n * ]\n */\n lineSyntax = [\n `(?:${DIM_ANGLE}|${TO_SIDE_CORNER})(?:\\\\s+${IN_COLOR_SPACE})?`,\n `${IN_COLOR_SPACE}(?:\\\\s+(?:${DIM_ANGLE}|${TO_SIDE_CORNER}))?`\n ].join('|');\n defaultValues.push(/to\\s+bottom/);\n } else if (/^(?:repeating-)?radial-gradient$/.test(type)) {\n /*\n * = [\n * [ [ || ]? [ at ]? ] ||\n * ]?\n */\n lineSyntax = [\n `(?:${RAD_SHAPE})(?:\\\\s+(?:${RAD_SIZE}))?(?:\\\\s+${AT_POSITION})?(?:\\\\s+${IN_COLOR_SPACE})?`,\n `(?:${RAD_SIZE})(?:\\\\s+(?:${RAD_SHAPE}))?(?:\\\\s+${AT_POSITION})?(?:\\\\s+${IN_COLOR_SPACE})?`,\n `${AT_POSITION}(?:\\\\s+${IN_COLOR_SPACE})?`,\n `${IN_COLOR_SPACE}(?:\\\\s+${RAD_SHAPE})(?:\\\\s+(?:${RAD_SIZE}))?(?:\\\\s+${AT_POSITION})?`,\n `${IN_COLOR_SPACE}(?:\\\\s+${RAD_SIZE})(?:\\\\s+(?:${RAD_SHAPE}))?(?:\\\\s+${AT_POSITION})?`,\n `${IN_COLOR_SPACE}(?:\\\\s+${AT_POSITION})?`\n ].join('|');\n defaultValues.push(/ellipse/, /farthest-corner/, /at\\s+center/);\n } else if (/^(?:repeating-)?conic-gradient$/.test(type)) {\n /*\n * = [\n * [ [ from ]? [ at ]? ] ||\n * \n * ]\n */\n lineSyntax = [\n `${FROM_ANGLE}(?:\\\\s+${AT_POSITION})?(?:\\\\s+${IN_COLOR_SPACE})?`,\n `${AT_POSITION}(?:\\\\s+${IN_COLOR_SPACE})?`,\n `${IN_COLOR_SPACE}(?:\\\\s+${FROM_ANGLE})?(?:\\\\s+${AT_POSITION})?`\n ].join('|');\n defaultValues.push(/at\\s+center/);\n }\n if (lineSyntax) {\n const reg = new RegExp(`^(?:${lineSyntax})$`);\n const valid = reg.test(value);\n if (valid) {\n let line = value;\n for (const defaultValue of defaultValues) {\n line = line.replace(defaultValue, '');\n }\n line = line.replace(/\\s{2,}/g, ' ').trim();\n return {\n line,\n valid\n };\n }\n return {\n valid,\n line: value\n };\n }\n }\n return {\n line: value,\n valid: false\n };\n};\n\n/**\n * validate color stop list\n * @param list\n * @param type\n * @param [opt]\n * @returns result\n */\nexport const validateColorStopList = (\n list: string[],\n type: string,\n opt: Options = {}\n): ValidateColorStops => {\n if (Array.isArray(list) && list.length > 1) {\n const dimension = /^(?:repeating-)?conic-gradient$/.test(type)\n ? DIM_ANGLE_PCT\n : DIM_LEN_PCT;\n const regColorHint = new RegExp(`^(?:${dimension})$`);\n const regDimension = new RegExp(`(?:\\\\s+(?:${dimension})){1,2}$`);\n const valueTypes = [];\n const valueList = [];\n for (const item of list) {\n if (isString(item)) {\n if (regColorHint.test(item)) {\n valueTypes.push('hint');\n valueList.push(item);\n } else {\n const itemColor = item.replace(regDimension, '');\n if (isColor(itemColor, { format: VAL_SPEC })) {\n const resolvedColor = resolveColor(itemColor, opt) as string;\n valueTypes.push('color');\n valueList.push(item.replace(itemColor, resolvedColor));\n } else {\n return {\n colorStops: list,\n valid: false\n };\n }\n }\n }\n }\n const valid = /^color(?:,(?:hint,)?color)+$/.test(valueTypes.join(','));\n return {\n valid,\n colorStops: valueList\n };\n }\n return {\n colorStops: list,\n valid: false\n };\n};\n\n/**\n * parse CSS gradient\n * @param value - gradient value\n * @param [opt] - options\n * @returns parsed result\n */\nexport const parseGradient = (\n value: string,\n opt: Options = {}\n): Gradient | null => {\n if (isString(value)) {\n value = value.trim();\n const cacheKey: string = createCacheKey(\n {\n namespace: NAMESPACE,\n name: 'parseGradient',\n value\n },\n opt\n );\n const cachedResult = getCache(cacheKey);\n if (cachedResult instanceof CacheItem) {\n if (cachedResult.isNull) {\n return null;\n }\n return cachedResult.item as Gradient;\n }\n const type = getGradientType(value);\n const gradValue = value.replace(REG_GRAD, '').replace(/\\)$/, '');\n if (type && gradValue) {\n const [lineOrColorStop = '', ...itemList] = splitValue(gradValue, {\n delimiter: ','\n });\n const dimension = /^(?:repeating-)?conic-gradient$/.test(type)\n ? DIM_ANGLE_PCT\n : DIM_LEN_PCT;\n const regDimension = new RegExp(`(?:\\\\s+(?:${dimension})){1,2}$`);\n let colorStop = '';\n if (regDimension.test(lineOrColorStop)) {\n const itemColor = lineOrColorStop.replace(regDimension, '');\n if (isColor(itemColor, { format: VAL_SPEC })) {\n const resolvedColor = resolveColor(itemColor, opt) as string;\n colorStop = lineOrColorStop.replace(itemColor, resolvedColor);\n }\n } else if (isColor(lineOrColorStop, { format: VAL_SPEC })) {\n colorStop = resolveColor(lineOrColorStop, opt) as string;\n }\n if (colorStop) {\n itemList.unshift(colorStop);\n const { colorStops, valid } = validateColorStopList(\n itemList,\n type,\n opt\n );\n if (valid) {\n const res: Gradient = {\n value,\n type,\n colorStopList: colorStops as ColorStopList\n };\n setCache(cacheKey, res);\n return res;\n }\n } else if (itemList.length > 1) {\n const { line: gradientLine, valid: validLine } = validateGradientLine(\n lineOrColorStop,\n type\n );\n const { colorStops, valid: validColorStops } = validateColorStopList(\n itemList,\n type,\n opt\n );\n if (validLine && validColorStops) {\n const res: Gradient = {\n value,\n type,\n gradientLine,\n colorStopList: colorStops as ColorStopList\n };\n setCache(cacheKey, res);\n return res;\n }\n }\n }\n setCache(cacheKey, null);\n return null;\n }\n return null;\n};\n\n/**\n * resolve CSS gradient\n * @param value - CSS value\n * @param [opt] - options\n * @returns result\n */\nexport const resolveGradient = (value: string, opt: Options = {}): string => {\n const { format = VAL_COMP } = opt;\n const gradient = parseGradient(value, opt);\n if (gradient) {\n const { type = '', gradientLine = '', colorStopList = [] } = gradient;\n if (type && Array.isArray(colorStopList) && colorStopList.length > 1) {\n if (gradientLine) {\n return `${type}(${gradientLine}, ${colorStopList.join(', ')})`;\n }\n return `${type}(${colorStopList.join(', ')})`;\n }\n }\n if (format === VAL_SPEC) {\n return '';\n }\n return 'none';\n};\n\n/**\n * is CSS gradient\n * @param value - CSS value\n * @param [opt] - options\n * @returns result\n */\nexport const isGradient = (value: string, opt: Options = {}): boolean => {\n const gradient = parseGradient(value, opt);\n return gradient !== null;\n};\n"],"mappings":";;;;;;;;;AAsBA,IAAM,YAAY;AAClB,IAAM,YAAY,GAAG,IAAI,KAAK,MAAM;AACpC,IAAM,gBAAgB,GAAG,UAAU,GAAG;AAEtC,IAAM,cAAc,GADJ,GAAG,IAAI,KAAK,OAAO,KACJ,GAAG;AAClC,IAAM,mBAAmB,GAAG,aAAa,KAAK,OAAO;AACrD,IAAM,eAAe,GAAG,aAAa,KAAK,OAAO;AACjD,IAAM,MAAM;AACZ,IAAM,MAAM;AACZ,IAAM,MAAM;AACZ,IAAM,MAAM;AACZ,IAAM,SAAS,GAAG,IAAI,QAAQ,IAAI;AAClC,IAAM,SAAS,GAAG,IAAI,QAAQ,IAAI;AAClC,IAAM,QAAQ,YAAY,IAAI;AAC9B,IAAM,SAAS,aAAa,IAAI;AAChC,IAAM,QAAQ,GAAG,IAAI,GAAG,OAAO,GAAG,OAAO,GAAG,MAAM,GAAG,OAAO,GAAG;AAC/D,IAAM,QAAQ;CACZ,MAAM,IAAI,GAAG,OAAO,UAAU,IAAI,GAAG,OAAO;CAC5C,MAAM,IAAI,GAAG,OAAO,UAAU,IAAI,GAAG,OAAO;CAC5C,MAAM,IAAI,GAAG,OAAO,GAAG,YAAY,UAAU,IAAI,GAAG,OAAO,GAAG,YAAY;CAC1E,MAAM,IAAI,GAAG,MAAM,UAAU,IAAI,GAAG,OAAO;CAC3C,MAAM,IAAI,GAAG,OAAO,UAAU,IAAI,GAAG,MAAM;CAC3C,MAAM,IAAI,GAAG,IAAI,UAAU,IAAI,GAAG,IAAI;CACvC,CAAC,KAAK,IAAI;AACX,IAAM,QAAQ;CACZ,MAAM,OAAO,UAAU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diff --git a/node_modules/@asamuzakjp/css-color/dist/esm/js/css-var.d.ts b/node_modules/@asamuzakjp/css-color/dist/esm/js/css-var.d.ts new file mode 100644 index 00000000..90723536 --- /dev/null +++ b/node_modules/@asamuzakjp/css-color/dist/esm/js/css-var.d.ts @@ -0,0 +1,31 @@ +import { CSSToken } from '@csstools/css-tokenizer'; +import { NullObject } from './cache.js'; +import { Options } from './typedef.js'; +/** + * resolve custom property + * @param tokens - CSS tokens + * @param [opt] - options + * @returns result - [tokens, resolvedValue] + */ +export declare function resolveCustomProperty(tokens: CSSToken[], opt?: Options): [CSSToken[], string]; +/** + * parse tokens + * @param tokens - CSS tokens + * @param [opt] - options + * @returns parsed tokens + */ +export declare function parseTokens(tokens: CSSToken[], opt?: Options): string[] | NullObject; +/** + * resolve CSS var() + * @param value - CSS value including var() + * @param [opt] - options + * @returns resolved value + */ +export declare function resolveVar(value: string, opt?: Options): string | NullObject; +/** + * CSS var() + * @param value - CSS value including var() + * @param [opt] - options + * @returns resolved value + */ +export declare const cssVar: (value: string, opt?: Options) => string; diff --git a/node_modules/@asamuzakjp/css-color/dist/esm/js/css-var.js b/node_modules/@asamuzakjp/css-color/dist/esm/js/css-var.js new file mode 100644 index 00000000..bf8c97bf --- /dev/null +++ b/node_modules/@asamuzakjp/css-color/dist/esm/js/css-var.js @@ -0,0 +1,147 @@ +import { isString } from "./common.js"; +import { SYN_FN_CALC, SYN_FN_VAR } from "./constant.js"; +import { isColor } from "./util.js"; +import { CacheItem, NullObject, createCacheKey, getCache, setCache } from "./cache.js"; +import { cssCalc } from "./css-calc.js"; +import { TokenType, tokenize } from "@csstools/css-tokenizer"; +//#region src/js/css-var.ts +/** +* css-var +*/ +var { CloseParen: PAREN_CLOSE, Comment: COMMENT, EOF, Ident: IDENT, Whitespace: W_SPACE } = TokenType; +var NAMESPACE = "css-var"; +var REG_FN_CALC = new RegExp(SYN_FN_CALC); +var REG_FN_VAR = new RegExp(SYN_FN_VAR); +/** +* resolve custom property +* @param tokens - CSS tokens +* @param [opt] - options +* @returns result - [tokens, resolvedValue] +*/ +function resolveCustomProperty(tokens, opt = {}) { + if (!Array.isArray(tokens)) throw new TypeError(`${tokens} is not an array.`); + const { customProperty = {} } = opt; + const items = []; + while (tokens.length) { + const token = tokens.shift(); + if (!Array.isArray(token)) throw new TypeError(`${token} is not an array.`); + const [type, value] = token; + if (type === PAREN_CLOSE) break; + if (value === "var(") { + const [restTokens, item] = resolveCustomProperty(tokens, opt); + tokens = restTokens; + if (item) items.push(item); + } else if (type === IDENT) { + if (value.startsWith("--")) { + let item; + if (Object.hasOwn(customProperty, value)) item = customProperty[value]; + else if (typeof customProperty.callback === "function") item = customProperty.callback(value); + if (item) items.push(item); + } else if (value) items.push(value); + } + } + let resolveAsColor = false; + if (items.length > 1) { + const lastValue = items[items.length - 1]; + resolveAsColor = isColor(lastValue); + } + let resolvedValue = ""; + for (let item of items) { + item = item.trim(); + if (REG_FN_VAR.test(item)) { + const resolvedItem = resolveVar(item, opt); + if (isString(resolvedItem)) if (resolveAsColor) { + if (isColor(resolvedItem)) resolvedValue = resolvedItem; + } else resolvedValue = resolvedItem; + } else if (REG_FN_CALC.test(item)) { + item = cssCalc(item, opt); + if (resolveAsColor) { + if (isColor(item)) resolvedValue = item; + } else resolvedValue = item; + } else if (item && !/^(?:inherit|initial|revert(?:-layer)?|unset)$/.test(item)) if (resolveAsColor) { + if (isColor(item)) resolvedValue = item; + } else resolvedValue = item; + if (resolvedValue) break; + } + return [tokens, resolvedValue]; +} +/** +* parse tokens +* @param tokens - CSS tokens +* @param [opt] - options +* @returns parsed tokens +*/ +function parseTokens(tokens, opt = {}) { + const res = []; + while (tokens.length) { + const [type = "", value = ""] = tokens.shift(); + if (value === "var(") { + const [restTokens, resolvedValue] = resolveCustomProperty(tokens, opt); + if (!resolvedValue) return new NullObject(); + tokens = restTokens; + res.push(resolvedValue); + } else switch (type) { + case PAREN_CLOSE: + if (res.length) if (res[res.length - 1] === " ") res.splice(-1, 1, value); + else res.push(value); + else res.push(value); + break; + case W_SPACE: + if (res.length) { + const lastValue = res[res.length - 1]; + if (isString(lastValue) && !lastValue.endsWith("(") && lastValue !== " ") res.push(value); + } + break; + default: if (type !== COMMENT && type !== EOF) res.push(value); + } + } + return res; +} +/** +* resolve CSS var() +* @param value - CSS value including var() +* @param [opt] - options +* @returns resolved value +*/ +function resolveVar(value, opt = {}) { + const { format = "" } = opt; + if (isString(value)) { + if (!REG_FN_VAR.test(value) || format === "specifiedValue") return value; + value = value.trim(); + } else throw new TypeError(`${value} is not a string.`); + const cacheKey = createCacheKey({ + namespace: NAMESPACE, + name: "resolveVar", + value + }, opt); + const cachedResult = getCache(cacheKey); + if (cachedResult instanceof CacheItem) { + if (cachedResult.isNull) return cachedResult; + return cachedResult.item; + } + const values = parseTokens(tokenize({ css: value }), opt); + if (Array.isArray(values)) { + let color = values.join(""); + if (REG_FN_CALC.test(color)) color = cssCalc(color, opt); + setCache(cacheKey, color); + return color; + } else { + setCache(cacheKey, null); + return new NullObject(); + } +} +/** +* CSS var() +* @param value - CSS value including var() +* @param [opt] - options +* @returns resolved value +*/ +var cssVar = (value, opt = {}) => { + const resolvedValue = resolveVar(value, opt); + if (isString(resolvedValue)) return resolvedValue; + return ""; +}; +//#endregion +export { cssVar, resolveVar }; + +//# sourceMappingURL=css-var.js.map \ No newline at end of file diff --git a/node_modules/@asamuzakjp/css-color/dist/esm/js/css-var.js.map b/node_modules/@asamuzakjp/css-color/dist/esm/js/css-var.js.map new file mode 100644 index 00000000..6f4eb5ca --- /dev/null +++ b/node_modules/@asamuzakjp/css-color/dist/esm/js/css-var.js.map @@ -0,0 +1 @@ +{"version":3,"file":"css-var.js","names":[],"sources":["../../../src/js/css-var.ts"],"sourcesContent":["/**\n * css-var\n */\n\nimport { CSSToken, TokenType, tokenize } from '@csstools/css-tokenizer';\nimport {\n CacheItem,\n NullObject,\n createCacheKey,\n getCache,\n setCache\n} from './cache';\nimport { isString } from './common';\nimport { cssCalc } from './css-calc';\nimport { isColor } from './util';\nimport { Options } from './typedef';\n\n/* constants */\nimport { FN_VAR, SYN_FN_CALC, SYN_FN_VAR, VAL_SPEC } from './constant';\nconst {\n CloseParen: PAREN_CLOSE,\n Comment: COMMENT,\n EOF,\n Ident: IDENT,\n Whitespace: W_SPACE\n} = TokenType;\nconst NAMESPACE = 'css-var';\n\n/* regexp */\nconst REG_FN_CALC = new RegExp(SYN_FN_CALC);\nconst REG_FN_VAR = new RegExp(SYN_FN_VAR);\n\n/**\n * resolve custom property\n * @param tokens - CSS tokens\n * @param [opt] - options\n * @returns result - [tokens, resolvedValue]\n */\nexport function resolveCustomProperty(\n tokens: CSSToken[],\n opt: Options = {}\n): [CSSToken[], string] {\n if (!Array.isArray(tokens)) {\n throw new TypeError(`${tokens} is not an array.`);\n }\n const { customProperty = {} } = opt;\n const items: string[] = [];\n while (tokens.length) {\n const token = tokens.shift();\n if (!Array.isArray(token)) {\n throw new TypeError(`${token} is not an array.`);\n }\n const [type, value] = token as [TokenType, string];\n // end of var()\n if (type === PAREN_CLOSE) {\n break;\n }\n // nested var()\n if (value === FN_VAR) {\n const [restTokens, item] = resolveCustomProperty(tokens, opt);\n tokens = restTokens;\n if (item) {\n items.push(item);\n }\n } else if (type === IDENT) {\n if (value.startsWith('--')) {\n let item;\n if (Object.hasOwn(customProperty, value)) {\n item = customProperty[value] as string;\n } else if (typeof customProperty.callback === 'function') {\n item = customProperty.callback(value);\n }\n if (item) {\n items.push(item);\n }\n } else if (value) {\n items.push(value);\n }\n }\n }\n let resolveAsColor = false;\n if (items.length > 1) {\n const lastValue = items[items.length - 1];\n resolveAsColor = isColor(lastValue);\n }\n let resolvedValue = '';\n for (let item of items) {\n item = item.trim();\n if (REG_FN_VAR.test(item)) {\n // recurse resolveVar()\n const resolvedItem = resolveVar(item, opt);\n if (isString(resolvedItem)) {\n if (resolveAsColor) {\n if (isColor(resolvedItem)) {\n resolvedValue = resolvedItem;\n }\n } else {\n resolvedValue = resolvedItem;\n }\n }\n } else if (REG_FN_CALC.test(item)) {\n item = cssCalc(item, opt);\n if (resolveAsColor) {\n if (isColor(item)) {\n resolvedValue = item;\n }\n } else {\n resolvedValue = item;\n }\n } else if (\n item &&\n !/^(?:inherit|initial|revert(?:-layer)?|unset)$/.test(item)\n ) {\n if (resolveAsColor) {\n if (isColor(item)) {\n resolvedValue = item;\n }\n } else {\n resolvedValue = item;\n }\n }\n if (resolvedValue) {\n break;\n }\n }\n return [tokens, resolvedValue];\n}\n\n/**\n * parse tokens\n * @param tokens - CSS tokens\n * @param [opt] - options\n * @returns parsed tokens\n */\nexport function parseTokens(\n tokens: CSSToken[],\n opt: Options = {}\n): string[] | NullObject {\n const res: string[] = [];\n while (tokens.length) {\n const token = tokens.shift();\n const [type = '', value = ''] = token as [TokenType, string];\n if (value === FN_VAR) {\n const [restTokens, resolvedValue] = resolveCustomProperty(tokens, opt);\n if (!resolvedValue) {\n return new NullObject();\n }\n tokens = restTokens;\n res.push(resolvedValue);\n } else {\n switch (type) {\n case PAREN_CLOSE: {\n if (res.length) {\n const lastValue = res[res.length - 1];\n if (lastValue === ' ') {\n res.splice(-1, 1, value);\n } else {\n res.push(value);\n }\n } else {\n res.push(value);\n }\n break;\n }\n case W_SPACE: {\n if (res.length) {\n const lastValue = res[res.length - 1];\n if (\n isString(lastValue) &&\n !lastValue.endsWith('(') &&\n lastValue !== ' '\n ) {\n res.push(value);\n }\n }\n break;\n }\n default: {\n if (type !== COMMENT && type !== EOF) {\n res.push(value);\n }\n }\n }\n }\n }\n return res;\n}\n\n/**\n * resolve CSS var()\n * @param value - CSS value including var()\n * @param [opt] - options\n * @returns resolved value\n */\nexport function resolveVar(\n value: string,\n opt: Options = {}\n): string | NullObject {\n const { format = '' } = opt;\n if (isString(value)) {\n if (!REG_FN_VAR.test(value) || format === VAL_SPEC) {\n return value;\n }\n value = value.trim();\n } else {\n throw new TypeError(`${value} is not a string.`);\n }\n const cacheKey: string = createCacheKey(\n {\n namespace: NAMESPACE,\n name: 'resolveVar',\n value\n },\n opt\n );\n const cachedResult = getCache(cacheKey);\n if (cachedResult instanceof CacheItem) {\n if (cachedResult.isNull) {\n return cachedResult as NullObject;\n }\n return cachedResult.item as string;\n }\n const tokens = tokenize({ css: value });\n const values = parseTokens(tokens, opt);\n if (Array.isArray(values)) {\n let color = values.join('');\n if (REG_FN_CALC.test(color)) {\n color = cssCalc(color, opt);\n }\n setCache(cacheKey, color);\n return color;\n } else {\n setCache(cacheKey, null);\n return new NullObject();\n }\n}\n\n/**\n * CSS var()\n * @param value - CSS value including var()\n * @param [opt] - options\n * @returns resolved value\n */\nexport const cssVar = (value: string, opt: Options = {}): string => {\n const resolvedValue = resolveVar(value, opt);\n if (isString(resolvedValue)) {\n return resolvedValue;\n }\n return '';\n};\n"],"mappings":";;;;;;;;;;AAmBA,IAAM,EACJ,YAAY,aACZ,SAAS,SACT,KACA,OAAO,OACP,YAAY,YACV;AACJ,IAAM,YAAY;AAGlB,IAAM,cAAc,IAAI,OAAO,YAAY;AAC3C,IAAM,aAAa,IAAI,OAAO,WAAW;;;;;;;AAQzC,SAAgB,sBACd,QACA,MAAe,EAAE,EACK;AACtB,KAAI,CAAC,MAAM,QAAQ,OAAO,CACxB,OAAM,IAAI,UAAU,GAAG,OAAO,mBAAmB;CAEnD,MAAM,EAAE,iBAAiB,EAAE,KAAK;CAChC,MAAM,QAAkB,EAAE;AAC1B,QAAO,OAAO,QAAQ;EACpB,MAAM,QAAQ,OAAO,OAAO;AAC5B,MAAI,CAAC,MAAM,QAAQ,MAAM,CACvB,OAAM,IAAI,UAAU,GAAG,MAAM,mBAAmB;EAElD,MAAM,CAAC,MAAM,SAAS;AAEtB,MAAI,SAAS,YACX;AAGF,MAAI,UAAA,QAAkB;GACpB,MAAM,CAAC,YAAY,QAAQ,sBAAsB,QAAQ,IAAI;AAC7D,YAAS;AACT,OAAI,KACF,OAAM,KAAK,KAAK;aAET,SAAS;OACd,MAAM,WAAW,KAAK,EAAE;IAC1B,IAAI;AACJ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,KAAI,KAAK,MAAM;QAGjB,KAAI,KAAK,MAAM;AAEjB;GAEF,KAAK;AACH,QAAI,IAAI,QAAQ;KACd,MAAM,YAAY,IAAI,IAAI,SAAS;AACnC,SACE,SAAS,UAAU,IACnB,CAAC,UAAU,SAAS,IAAI,IACxB,cAAc,IAEd,KAAI,KAAK,MAAM;;AAGnB;GAEF,QACE,KAAI,SAAS,WAAW,SAAS,IAC/B,KAAI,KAAK,MAAM;;;AAMzB,QAAO;;;;;;;;AAST,SAAgB,WACd,OACA,MAAe,EAAE,EACI;CACrB,MAAM,EAAE,SAAS,OAAO;AACxB,KAAI,SAAS,MAAM,EAAE;AACnB,MAAI,CAAC,WAAW,KAAK,MAAM,IAAI,WAAA,iBAC7B,QAAO;AAET,UAAQ,MAAM,MAAM;OAEpB,OAAM,IAAI,UAAU,GAAG,MAAM,mBAAmB;CAElD,MAAM,WAAmB,eACvB;EACE,WAAW;EACX,MAAM;EACN;EACD,EACD,IACD;CACD,MAAM,eAAe,SAAS,SAAS;AACvC,KAAI,wBAAwB,WAAW;AACrC,MAAI,aAAa,OACf,QAAO;AAET,SAAO,aAAa;;CAGtB,MAAM,SAAS,YADA,SAAS,EAAE,KAAK,OAAO,CAAC,EACJ,IAAI;AACvC,KAAI,MAAM,QAAQ,OAAO,EAAE;EACzB,IAAI,QAAQ,OAAO,KAAK,GAAG;AAC3B,MAAI,YAAY,KAAK,MAAM,CACzB,SAAQ,QAAQ,OAAO,IAAI;AAE7B,WAAS,UAAU,MAAM;AACzB,SAAO;QACF;AACL,WAAS,UAAU,KAAK;AACxB,SAAO,IAAI,YAAY;;;;;;;;;AAU3B,IAAa,UAAU,OAAe,MAAe,EAAE,KAAa;CAClE,MAAM,gBAAgB,WAAW,OAAO,IAAI;AAC5C,KAAI,SAAS,cAAc,CACzB,QAAO;AAET,QAAO"} \ No newline at end of file diff --git a/node_modules/@asamuzakjp/css-color/dist/esm/js/relative-color.d.ts b/node_modules/@asamuzakjp/css-color/dist/esm/js/relative-color.d.ts new file mode 100644 index 00000000..ed0abfcb --- /dev/null +++ b/node_modules/@asamuzakjp/css-color/dist/esm/js/relative-color.d.ts @@ -0,0 +1,29 @@ +import { CSSToken } from '@csstools/css-tokenizer'; +import { NullObject } from './cache.js'; +import { ColorChannels, Options, StringColorChannels } from './typedef.js'; +/** + * @type NumberOrStringColorChannels - color channel + */ +type NumberOrStringColorChannels = ColorChannels & StringColorChannels; +/** + * resolve relative color channels + * @param tokens - CSS tokens + * @param [opt] - options + * @returns resolved color channels + */ +export declare function resolveColorChannels(tokens: CSSToken[], opt?: Options): NumberOrStringColorChannels | NullObject; +/** + * extract origin color + * @param value - CSS color value + * @param [opt] - options + * @returns origin color value + */ +export declare function extractOriginColor(value: string, opt?: Options): string | NullObject; +/** + * resolve relative color + * @param value - CSS relative color value + * @param [opt] - options + * @returns resolved value + */ +export declare function resolveRelativeColor(value: string, opt?: Options): string | NullObject; +export {}; diff --git a/node_modules/@asamuzakjp/css-color/dist/esm/js/relative-color.js b/node_modules/@asamuzakjp/css-color/dist/esm/js/relative-color.js new file mode 100644 index 00000000..aed5b1fd --- /dev/null +++ b/node_modules/@asamuzakjp/css-color/dist/esm/js/relative-color.js @@ -0,0 +1,410 @@ +import { isString, isStringOrNumber } from "./common.js"; +import { CS_LAB, CS_LCH, FN_REL, FN_REL_CAPT, FN_VAR, NONE, SYN_COLOR_TYPE, SYN_FN_MATH_START, SYN_FN_VAR, SYN_MIX, VAL_SPEC } from "./constant.js"; +import { NAMED_COLORS, convertColorToRgb } from "./color.js"; +import { resolveColor } from "./resolve.js"; +import { roundToPrecision, splitValue } from "./util.js"; +import { CacheItem, NullObject, createCacheKey, getCache, setCache } from "./cache.js"; +import { resolveDimension, serializeCalc } from "./css-calc.js"; +import { TokenType, tokenize } from "@csstools/css-tokenizer"; +import { SyntaxFlag, color } from "@csstools/css-color-parser"; +import { parseComponentValue } from "@csstools/css-parser-algorithms"; +//#region src/js/relative-color.ts +/** +* relative-color +*/ +var { CloseParen: PAREN_CLOSE, Comment: COMMENT, Delim: DELIM, Dimension: DIM, EOF, Function: FUNC, Ident: IDENT, Number: NUM, OpenParen: PAREN_OPEN, Percentage: PCT, Whitespace: W_SPACE } = TokenType; +var { HasNoneKeywords: KEY_NONE } = SyntaxFlag; +var NAMESPACE = "relative-color"; +var OCT = 8; +var DEC = 10; +var HEX = 16; +var MAX_PCT = 100; +var MAX_RGB = 255; +var REG_COLOR_CAPT = new RegExp(`^${FN_REL}(${SYN_COLOR_TYPE}|${SYN_MIX})\\s+`); +var REG_CS_HSL = /(?:hsla?|hwb)$/; +var REG_CS_CIE = new RegExp(`^(?:${CS_LAB}|${CS_LCH})$`); +var REG_FN_CALC_SUM = /^(?:abs|sig?n|cos|tan)\(/; +var REG_FN_MATH_START = new RegExp(SYN_FN_MATH_START); +var REG_FN_REL = new RegExp(FN_REL); +var REG_FN_REL_CAPT = new RegExp(`^${FN_REL_CAPT}`); +var REG_FN_REL_START = new RegExp(`^${FN_REL}`); +var REG_FN_VAR = new RegExp(SYN_FN_VAR); +/** +* resolve relative color channels +* @param tokens - CSS tokens +* @param [opt] - options +* @returns resolved color channels +*/ +function resolveColorChannels(tokens, opt = {}) { + if (!Array.isArray(tokens)) throw new TypeError(`${tokens} is not an array.`); + const { colorSpace = "", format = "" } = opt; + const colorChannel = new Map([ + ["color", [ + "r", + "g", + "b", + "alpha" + ]], + ["hsl", [ + "h", + "s", + "l", + "alpha" + ]], + ["hsla", [ + "h", + "s", + "l", + "alpha" + ]], + ["hwb", [ + "h", + "w", + "b", + "alpha" + ]], + ["lab", [ + "l", + "a", + "b", + "alpha" + ]], + ["lch", [ + "l", + "c", + "h", + "alpha" + ]], + ["oklab", [ + "l", + "a", + "b", + "alpha" + ]], + ["oklch", [ + "l", + "c", + "h", + "alpha" + ]], + ["rgb", [ + "r", + "g", + "b", + "alpha" + ]], + ["rgba", [ + "r", + "g", + "b", + "alpha" + ]] + ]).get(colorSpace); + if (!colorChannel) return new NullObject(); + const mathFunc = /* @__PURE__ */ new Set(); + const channels = [ + [], + [], + [], + [] + ]; + let i = 0; + let nest = 0; + let func = ""; + let precededPct = false; + while (tokens.length) { + const token = tokens.shift(); + if (!Array.isArray(token)) throw new TypeError(`${token} is not an array.`); + const [type, value, , , detail] = token; + const channel = channels[i]; + if (Array.isArray(channel)) switch (type) { + case DELIM: + if (func) { + if ((value === "+" || value === "-") && precededPct && !REG_FN_CALC_SUM.test(func)) return new NullObject(); + precededPct = false; + channel.push(value); + } + break; + case DIM: { + if (!func || !REG_FN_CALC_SUM.test(func)) return new NullObject(); + const resolvedValue = resolveDimension(token, opt); + if (isString(resolvedValue)) channel.push(resolvedValue); + else channel.push(value); + break; + } + case FUNC: + channel.push(value); + func = value; + nest++; + if (REG_FN_MATH_START.test(value)) mathFunc.add(nest); + break; + case IDENT: + if (!colorChannel.includes(value)) return new NullObject(); + channel.push(value); + if (!func) i++; + break; + case NUM: + channel.push(Number(detail?.value)); + if (!func) i++; + break; + case PAREN_OPEN: + channel.push(value); + nest++; + break; + case PAREN_CLOSE: + if (func) { + if (channel[channel.length - 1] === " ") channel.splice(-1, 1, value); + else channel.push(value); + if (mathFunc.has(nest)) mathFunc.delete(nest); + nest--; + if (nest === 0) { + func = ""; + i++; + } + } + break; + case PCT: + if (!func) return new NullObject(); + else if (!REG_FN_CALC_SUM.test(func)) { + const lastValue = channel.toReversed().find((v) => v !== " "); + if (lastValue === "+" || lastValue === "-") return new NullObject(); + else if (lastValue === "*" || lastValue === "/") precededPct = false; + else precededPct = true; + } + channel.push(Number(detail?.value) / MAX_PCT); + if (!func) i++; + break; + case W_SPACE: + if (channel.length && func) { + const lastValue = channel[channel.length - 1]; + if (typeof lastValue === "number") channel.push(value); + else if (isString(lastValue) && !lastValue.endsWith("(") && lastValue !== " ") channel.push(value); + } + break; + default: if (type !== COMMENT && type !== EOF && func) channel.push(value); + } + } + const channelValues = []; + for (const channel of channels) if (channel.length === 1) { + const [resolvedValue] = channel; + if (isStringOrNumber(resolvedValue)) channelValues.push(resolvedValue); + } else if (channel.length) { + const resolvedValue = serializeCalc(channel.join(""), { format }); + channelValues.push(resolvedValue); + } + return channelValues; +} +/** +* extract origin color +* @param value - CSS color value +* @param [opt] - options +* @returns origin color value +*/ +function extractOriginColor(value, opt = {}) { + const { colorScheme = "normal", currentColor = "", format = "" } = opt; + if (isString(value)) { + value = value.toLowerCase().trim(); + if (!value) return new NullObject(); + if (!REG_FN_REL_START.test(value)) return value; + } else return new NullObject(); + const cacheKey = createCacheKey({ + namespace: NAMESPACE, + name: "extractOriginColor", + value + }, opt); + const cachedResult = getCache(cacheKey); + if (cachedResult instanceof CacheItem) { + if (cachedResult.isNull) return cachedResult; + return cachedResult.item; + } + if (/currentcolor/.test(value)) if (currentColor) value = value.replace(/currentcolor/g, currentColor); + else { + setCache(cacheKey, null); + return new NullObject(); + } + let colorSpace = ""; + if (REG_FN_REL_CAPT.test(value)) [, colorSpace] = value.match(REG_FN_REL_CAPT); + opt.colorSpace = colorSpace; + if (value.includes("light-dark(")) { + const [, originColor = ""] = splitValue(value.replace(new RegExp(`^${colorSpace}\\(`), "").replace(/\)$/, "")); + const specifiedOriginColor = resolveColor(originColor, { + colorScheme, + format: VAL_SPEC + }); + if (specifiedOriginColor === "") { + setCache(cacheKey, null); + return new NullObject(); + } + if (format === "specifiedValue") value = value.replace(originColor, specifiedOriginColor); + else { + const resolvedOriginColor = resolveColor(specifiedOriginColor, opt); + if (isString(resolvedOriginColor)) value = value.replace(originColor, resolvedOriginColor); + } + } + if (REG_COLOR_CAPT.test(value)) { + const [, originColor] = value.match(REG_COLOR_CAPT); + const [, restValue] = value.split(originColor); + if (/^[a-z]+$/.test(originColor)) { + if (!/^transparent$/.test(originColor) && !Object.hasOwn(NAMED_COLORS, originColor)) { + setCache(cacheKey, null); + return new NullObject(); + } + } else if (format === "specifiedValue") { + const resolvedOriginColor = resolveColor(originColor, opt); + if (isString(resolvedOriginColor)) value = value.replace(originColor, resolvedOriginColor); + } + if (format === "specifiedValue") { + const channelValues = resolveColorChannels(tokenize({ css: restValue }), opt); + if (channelValues instanceof NullObject) { + setCache(cacheKey, null); + return channelValues; + } + const [v1, v2, v3, v4] = channelValues; + let channelValue = ""; + if (isStringOrNumber(v4)) channelValue = ` ${v1} ${v2} ${v3} / ${v4})`; + else channelValue = ` ${channelValues.join(" ")})`; + if (restValue !== channelValue) value = value.replace(restValue, channelValue); + } + } else { + const [, restValue] = value.split(REG_FN_REL_START); + const tokens = tokenize({ css: restValue }); + const originColor = []; + let nest = 0; + while (tokens.length) { + const [type, tokenValue] = tokens.shift(); + switch (type) { + case FUNC: + case PAREN_OPEN: + originColor.push(tokenValue); + nest++; + break; + case PAREN_CLOSE: { + const lastValue = originColor[originColor.length - 1]; + if (lastValue === " ") originColor.splice(-1, 1, tokenValue); + else if (isString(lastValue)) originColor.push(tokenValue); + nest--; + break; + } + case W_SPACE: { + const lastValue = originColor[originColor.length - 1]; + if (isString(lastValue) && !lastValue.endsWith("(") && lastValue !== " ") originColor.push(tokenValue); + break; + } + default: if (type !== COMMENT && type !== EOF) originColor.push(tokenValue); + } + if (nest === 0) break; + } + const resolvedOriginColor = resolveRelativeColor(originColor.join("").trim(), opt); + if (resolvedOriginColor instanceof NullObject) { + setCache(cacheKey, null); + return resolvedOriginColor; + } + const channelValues = resolveColorChannels(tokens, opt); + if (channelValues instanceof NullObject) { + setCache(cacheKey, null); + return channelValues; + } + const [v1, v2, v3, v4] = channelValues; + let channelValue = ""; + if (isStringOrNumber(v4)) channelValue = ` ${v1} ${v2} ${v3} / ${v4})`; + else channelValue = ` ${channelValues.join(" ")})`; + value = value.replace(restValue, `${resolvedOriginColor}${channelValue}`); + } + setCache(cacheKey, value); + return value; +} +/** +* resolve relative color +* @param value - CSS relative color value +* @param [opt] - options +* @returns resolved value +*/ +function resolveRelativeColor(value, opt = {}) { + const { format = "" } = opt; + if (isString(value)) { + if (REG_FN_VAR.test(value)) if (format === "specifiedValue") return value; + else throw new SyntaxError(`Unexpected token ${FN_VAR} found.`); + else if (!REG_FN_REL.test(value)) return value; + value = value.toLowerCase().trim(); + } else throw new TypeError(`${value} is not a string.`); + const cacheKey = createCacheKey({ + namespace: NAMESPACE, + name: "resolveRelativeColor", + value + }, opt); + const cachedResult = getCache(cacheKey); + if (cachedResult instanceof CacheItem) { + if (cachedResult.isNull) return cachedResult; + return cachedResult.item; + } + const originColor = extractOriginColor(value, opt); + if (originColor instanceof NullObject) { + setCache(cacheKey, null); + return originColor; + } + value = originColor; + if (format === "specifiedValue") { + if (value.startsWith("rgba(")) value = value.replace(/^rgba\(/, "rgb("); + else if (value.startsWith("hsla(")) value = value.replace(/^hsla\(/, "hsl("); + return value; + } + const parsedComponents = color(parseComponentValue(tokenize({ css: value }))); + if (!parsedComponents) { + setCache(cacheKey, null); + return new NullObject(); + } + const { alpha: alphaComponent, channels: channelsComponent, colorNotation, syntaxFlags } = parsedComponents; + let alpha; + if (Number.isNaN(Number(alphaComponent))) if (syntaxFlags instanceof Set && syntaxFlags.has(KEY_NONE)) alpha = NONE; + else alpha = 0; + else alpha = roundToPrecision(Number(alphaComponent), OCT); + let v1; + let v2; + let v3; + [v1, v2, v3] = channelsComponent; + let resolvedValue; + if (REG_CS_CIE.test(colorNotation)) { + const hasNone = syntaxFlags instanceof Set && syntaxFlags.has(KEY_NONE); + if (Number.isNaN(v1)) if (hasNone) v1 = NONE; + else v1 = 0; + else v1 = roundToPrecision(v1, HEX); + if (Number.isNaN(v2)) if (hasNone) v2 = NONE; + else v2 = 0; + else v2 = roundToPrecision(v2, HEX); + if (Number.isNaN(v3)) if (hasNone) v3 = NONE; + else v3 = 0; + else v3 = roundToPrecision(v3, HEX); + if (alpha === 1) resolvedValue = `${colorNotation}(${v1} ${v2} ${v3})`; + else resolvedValue = `${colorNotation}(${v1} ${v2} ${v3} / ${alpha})`; + } else if (REG_CS_HSL.test(colorNotation)) { + if (Number.isNaN(v1)) v1 = 0; + if (Number.isNaN(v2)) v2 = 0; + if (Number.isNaN(v3)) v3 = 0; + let [r, g, b] = convertColorToRgb(`${colorNotation}(${v1} ${v2} ${v3} / ${alpha})`); + r = roundToPrecision(r / MAX_RGB, DEC); + g = roundToPrecision(g / MAX_RGB, DEC); + b = roundToPrecision(b / MAX_RGB, DEC); + if (alpha === 1) resolvedValue = `color(srgb ${r} ${g} ${b})`; + else resolvedValue = `color(srgb ${r} ${g} ${b} / ${alpha})`; + } else { + const cs = colorNotation === "rgb" ? "srgb" : colorNotation; + const hasNone = syntaxFlags instanceof Set && syntaxFlags.has(KEY_NONE); + if (Number.isNaN(v1)) if (hasNone) v1 = NONE; + else v1 = 0; + else v1 = roundToPrecision(v1, DEC); + if (Number.isNaN(v2)) if (hasNone) v2 = NONE; + else v2 = 0; + else v2 = roundToPrecision(v2, DEC); + if (Number.isNaN(v3)) if (hasNone) v3 = NONE; + else v3 = 0; + else v3 = roundToPrecision(v3, DEC); + if (alpha === 1) resolvedValue = `color(${cs} ${v1} ${v2} ${v3})`; + else resolvedValue = `color(${cs} ${v1} ${v2} ${v3} / ${alpha})`; + } + setCache(cacheKey, resolvedValue); + return resolvedValue; +} +//#endregion +export { resolveRelativeColor }; + +//# sourceMappingURL=relative-color.js.map \ No newline at end of file diff --git a/node_modules/@asamuzakjp/css-color/dist/esm/js/relative-color.js.map b/node_modules/@asamuzakjp/css-color/dist/esm/js/relative-color.js.map new file mode 100644 index 00000000..2cd28320 --- /dev/null +++ b/node_modules/@asamuzakjp/css-color/dist/esm/js/relative-color.js.map @@ -0,0 +1 @@ +{"version":3,"file":"relative-color.js","names":[],"sources":["../../../src/js/relative-color.ts"],"sourcesContent":["/**\n * relative-color\n */\n\nimport { SyntaxFlag, color as colorParser } from '@csstools/css-color-parser';\nimport {\n ComponentValue,\n parseComponentValue\n} from '@csstools/css-parser-algorithms';\nimport { CSSToken, TokenType, tokenize } from '@csstools/css-tokenizer';\nimport {\n CacheItem,\n NullObject,\n createCacheKey,\n getCache,\n setCache\n} from './cache';\nimport { NAMED_COLORS, convertColorToRgb } from './color';\nimport { isString, isStringOrNumber } from './common';\nimport { resolveDimension, serializeCalc } from './css-calc';\nimport { resolveColor } from './resolve';\nimport { roundToPrecision, splitValue } from './util';\nimport {\n ColorChannels,\n MatchedRegExp,\n Options,\n StringColorChannels\n} from './typedef';\n\n/* constants */\nimport {\n CS_LAB,\n CS_LCH,\n FN_LIGHT_DARK,\n FN_REL,\n FN_REL_CAPT,\n FN_VAR,\n NONE,\n SYN_COLOR_TYPE,\n SYN_FN_MATH_START,\n SYN_FN_VAR,\n SYN_MIX,\n VAL_SPEC\n} from './constant';\nconst {\n CloseParen: PAREN_CLOSE,\n Comment: COMMENT,\n Delim: DELIM,\n Dimension: DIM,\n EOF,\n Function: FUNC,\n Ident: IDENT,\n Number: NUM,\n OpenParen: PAREN_OPEN,\n Percentage: PCT,\n Whitespace: W_SPACE\n} = TokenType;\nconst { HasNoneKeywords: KEY_NONE } = SyntaxFlag;\nconst NAMESPACE = 'relative-color';\n\n/* numeric constants */\nconst OCT = 8;\nconst DEC = 10;\nconst HEX = 16;\nconst MAX_PCT = 100;\nconst MAX_RGB = 255;\n\n/* type definitions */\n/**\n * @type NumberOrStringColorChannels - color channel\n */\ntype NumberOrStringColorChannels = ColorChannels & StringColorChannels;\n\n/* regexp */\nconst REG_COLOR_CAPT = new RegExp(\n `^${FN_REL}(${SYN_COLOR_TYPE}|${SYN_MIX})\\\\s+`\n);\nconst REG_CS_HSL = /(?:hsla?|hwb)$/;\nconst REG_CS_CIE = new RegExp(`^(?:${CS_LAB}|${CS_LCH})$`);\nconst REG_FN_CALC_SUM = /^(?:abs|sig?n|cos|tan)\\(/;\nconst REG_FN_MATH_START = new RegExp(SYN_FN_MATH_START);\nconst REG_FN_REL = new RegExp(FN_REL);\nconst REG_FN_REL_CAPT = new RegExp(`^${FN_REL_CAPT}`);\nconst REG_FN_REL_START = new RegExp(`^${FN_REL}`);\nconst REG_FN_VAR = new RegExp(SYN_FN_VAR);\n\n/**\n * resolve relative color channels\n * @param tokens - CSS tokens\n * @param [opt] - options\n * @returns resolved color channels\n */\nexport function resolveColorChannels(\n tokens: CSSToken[],\n opt: Options = {}\n): NumberOrStringColorChannels | NullObject {\n if (!Array.isArray(tokens)) {\n throw new TypeError(`${tokens} is not an array.`);\n }\n const { colorSpace = '', format = '' } = opt;\n const colorChannels = new Map([\n ['color', ['r', 'g', 'b', 'alpha']],\n ['hsl', ['h', 's', 'l', 'alpha']],\n ['hsla', ['h', 's', 'l', 'alpha']],\n ['hwb', ['h', 'w', 'b', 'alpha']],\n ['lab', ['l', 'a', 'b', 'alpha']],\n ['lch', ['l', 'c', 'h', 'alpha']],\n ['oklab', ['l', 'a', 'b', 'alpha']],\n ['oklch', ['l', 'c', 'h', 'alpha']],\n ['rgb', ['r', 'g', 'b', 'alpha']],\n ['rgba', ['r', 'g', 'b', 'alpha']]\n ]);\n const colorChannel = colorChannels.get(colorSpace);\n // invalid color channel\n if (!colorChannel) {\n return new NullObject();\n }\n const mathFunc = new Set();\n const channels: [\n (number | string)[],\n (number | string)[],\n (number | string)[],\n (number | string)[]\n ] = [[], [], [], []];\n let i = 0;\n let nest = 0;\n let func = '';\n let precededPct = false;\n while (tokens.length) {\n const token = tokens.shift();\n if (!Array.isArray(token)) {\n throw new TypeError(`${token} is not an array.`);\n }\n const [type, value, , , detail] = token as [\n TokenType,\n string,\n number,\n number,\n { value: string | number } | undefined\n ];\n const channel = channels[i];\n if (Array.isArray(channel)) {\n switch (type) {\n case DELIM: {\n if (func) {\n if (\n (value === '+' || value === '-') &&\n precededPct &&\n !REG_FN_CALC_SUM.test(func)\n ) {\n return new NullObject();\n }\n precededPct = false;\n channel.push(value);\n }\n break;\n }\n case DIM: {\n if (!func || !REG_FN_CALC_SUM.test(func)) {\n return new NullObject();\n }\n const resolvedValue = resolveDimension(token, opt);\n if (isString(resolvedValue)) {\n channel.push(resolvedValue);\n } else {\n channel.push(value);\n }\n break;\n }\n case FUNC: {\n channel.push(value);\n func = value;\n nest++;\n if (REG_FN_MATH_START.test(value)) {\n mathFunc.add(nest);\n }\n break;\n }\n case IDENT: {\n // invalid channel key\n if (!colorChannel.includes(value)) {\n return new NullObject();\n }\n channel.push(value);\n if (!func) {\n i++;\n }\n break;\n }\n case NUM: {\n channel.push(Number(detail?.value));\n if (!func) {\n i++;\n }\n break;\n }\n case PAREN_OPEN: {\n channel.push(value);\n nest++;\n break;\n }\n case PAREN_CLOSE: {\n if (func) {\n const lastValue = channel[channel.length - 1];\n if (lastValue === ' ') {\n channel.splice(-1, 1, value);\n } else {\n channel.push(value);\n }\n if (mathFunc.has(nest)) {\n mathFunc.delete(nest);\n }\n nest--;\n if (nest === 0) {\n func = '';\n i++;\n }\n }\n break;\n }\n case PCT: {\n if (!func) {\n return new NullObject();\n } else if (!REG_FN_CALC_SUM.test(func)) {\n const lastValue = channel.toReversed().find(v => v !== ' ');\n if (lastValue === '+' || lastValue === '-') {\n return new NullObject();\n } else if (lastValue === '*' || lastValue === '/') {\n precededPct = false;\n } else {\n precededPct = true;\n }\n }\n channel.push(Number(detail?.value) / MAX_PCT);\n if (!func) {\n i++;\n }\n break;\n }\n case W_SPACE: {\n if (channel.length && func) {\n const lastValue = channel[channel.length - 1];\n if (typeof lastValue === 'number') {\n channel.push(value);\n } else if (\n isString(lastValue) &&\n !lastValue.endsWith('(') &&\n lastValue !== ' '\n ) {\n channel.push(value);\n }\n }\n break;\n }\n default: {\n if (type !== COMMENT && type !== EOF && func) {\n channel.push(value);\n }\n }\n }\n }\n }\n const channelValues = [];\n for (const channel of channels) {\n if (channel.length === 1) {\n const [resolvedValue] = channel;\n if (isStringOrNumber(resolvedValue)) {\n channelValues.push(resolvedValue);\n }\n } else if (channel.length) {\n const resolvedValue = serializeCalc(channel.join(''), {\n format\n });\n channelValues.push(resolvedValue);\n }\n }\n return channelValues as NumberOrStringColorChannels;\n}\n\n/**\n * extract origin color\n * @param value - CSS color value\n * @param [opt] - options\n * @returns origin color value\n */\nexport function extractOriginColor(\n value: string,\n opt: Options = {}\n): string | NullObject {\n const { colorScheme = 'normal', currentColor = '', format = '' } = opt;\n if (isString(value)) {\n value = value.toLowerCase().trim();\n if (!value) {\n return new NullObject();\n }\n if (!REG_FN_REL_START.test(value)) {\n return value;\n }\n } else {\n return new NullObject();\n }\n const cacheKey: string = createCacheKey(\n {\n namespace: NAMESPACE,\n name: 'extractOriginColor',\n value\n },\n opt\n );\n const cachedResult = getCache(cacheKey);\n if (cachedResult instanceof CacheItem) {\n if (cachedResult.isNull) {\n return cachedResult as NullObject;\n }\n return cachedResult.item as string;\n }\n if (/currentcolor/.test(value)) {\n if (currentColor) {\n value = value.replace(/currentcolor/g, currentColor);\n } else {\n setCache(cacheKey, null);\n return new NullObject();\n }\n }\n let colorSpace = '';\n if (REG_FN_REL_CAPT.test(value)) {\n [, colorSpace] = value.match(REG_FN_REL_CAPT) as MatchedRegExp;\n }\n opt.colorSpace = colorSpace;\n if (value.includes(FN_LIGHT_DARK)) {\n const colorParts = value\n .replace(new RegExp(`^${colorSpace}\\\\(`), '')\n .replace(/\\)$/, '');\n const [, originColor = ''] = splitValue(colorParts);\n const specifiedOriginColor = resolveColor(originColor, {\n colorScheme,\n format: VAL_SPEC\n }) as string;\n if (specifiedOriginColor === '') {\n setCache(cacheKey, null);\n return new NullObject();\n }\n if (format === VAL_SPEC) {\n value = value.replace(originColor, specifiedOriginColor);\n } else {\n const resolvedOriginColor = resolveColor(specifiedOriginColor, opt);\n if (isString(resolvedOriginColor)) {\n value = value.replace(originColor, resolvedOriginColor);\n }\n }\n }\n if (REG_COLOR_CAPT.test(value)) {\n const [, originColor] = value.match(REG_COLOR_CAPT) as MatchedRegExp;\n const [, restValue] = value.split(originColor) as MatchedRegExp;\n if (/^[a-z]+$/.test(originColor)) {\n if (\n !/^transparent$/.test(originColor) &&\n !Object.hasOwn(NAMED_COLORS, originColor)\n ) {\n setCache(cacheKey, null);\n return new NullObject();\n }\n } else if (format === VAL_SPEC) {\n const resolvedOriginColor = resolveColor(originColor, opt);\n if (isString(resolvedOriginColor)) {\n value = value.replace(originColor, resolvedOriginColor);\n }\n }\n if (format === VAL_SPEC) {\n const tokens = tokenize({ css: restValue });\n const channelValues = resolveColorChannels(tokens, opt);\n if (channelValues instanceof NullObject) {\n setCache(cacheKey, null);\n return channelValues;\n }\n const [v1, v2, v3, v4] = channelValues;\n let channelValue = '';\n if (isStringOrNumber(v4)) {\n channelValue = ` ${v1} ${v2} ${v3} / ${v4})`;\n } else {\n channelValue = ` ${channelValues.join(' ')})`;\n }\n if (restValue !== channelValue) {\n value = value.replace(restValue, channelValue);\n }\n }\n // nested relative color\n } else {\n const [, restValue] = value.split(REG_FN_REL_START) as MatchedRegExp;\n const tokens = tokenize({ css: restValue });\n const originColor: string[] = [];\n let nest = 0;\n while (tokens.length) {\n const [type, tokenValue] = tokens.shift() as [TokenType, string];\n switch (type) {\n case FUNC:\n case PAREN_OPEN: {\n originColor.push(tokenValue);\n nest++;\n break;\n }\n case PAREN_CLOSE: {\n const lastValue = originColor[originColor.length - 1];\n if (lastValue === ' ') {\n originColor.splice(-1, 1, tokenValue);\n } else if (isString(lastValue)) {\n originColor.push(tokenValue);\n }\n nest--;\n break;\n }\n case W_SPACE: {\n const lastValue = originColor[originColor.length - 1];\n if (\n isString(lastValue) &&\n !lastValue.endsWith('(') &&\n lastValue !== ' '\n ) {\n originColor.push(tokenValue);\n }\n break;\n }\n default: {\n if (type !== COMMENT && type !== EOF) {\n originColor.push(tokenValue);\n }\n }\n }\n if (nest === 0) {\n break;\n }\n }\n const resolvedOriginColor = resolveRelativeColor(\n originColor.join('').trim(),\n opt\n );\n if (resolvedOriginColor instanceof NullObject) {\n setCache(cacheKey, null);\n return resolvedOriginColor;\n }\n const channelValues = resolveColorChannels(tokens, opt);\n if (channelValues instanceof NullObject) {\n setCache(cacheKey, null);\n return channelValues;\n }\n const [v1, v2, v3, v4] = channelValues;\n let channelValue = '';\n if (isStringOrNumber(v4)) {\n channelValue = ` ${v1} ${v2} ${v3} / ${v4})`;\n } else {\n channelValue = ` ${channelValues.join(' ')})`;\n }\n value = value.replace(restValue, `${resolvedOriginColor}${channelValue}`);\n }\n setCache(cacheKey, value);\n return value;\n}\n\n/**\n * resolve relative color\n * @param value - CSS relative color value\n * @param [opt] - options\n * @returns resolved value\n */\nexport function resolveRelativeColor(\n value: string,\n opt: Options = {}\n): string | NullObject {\n const { format = '' } = opt;\n if (isString(value)) {\n if (REG_FN_VAR.test(value)) {\n if (format === VAL_SPEC) {\n return value;\n // var() must be resolved before resolveRelativeColor()\n } else {\n throw new SyntaxError(`Unexpected token ${FN_VAR} found.`);\n }\n } else if (!REG_FN_REL.test(value)) {\n return value;\n }\n value = value.toLowerCase().trim();\n } else {\n throw new TypeError(`${value} is not a string.`);\n }\n const cacheKey: string = createCacheKey(\n {\n namespace: NAMESPACE,\n name: 'resolveRelativeColor',\n value\n },\n opt\n );\n const cachedResult = getCache(cacheKey);\n if (cachedResult instanceof CacheItem) {\n if (cachedResult.isNull) {\n return cachedResult as NullObject;\n }\n return cachedResult.item as string;\n }\n const originColor = extractOriginColor(value, opt);\n if (originColor instanceof NullObject) {\n setCache(cacheKey, null);\n return originColor;\n }\n value = originColor;\n if (format === VAL_SPEC) {\n if (value.startsWith('rgba(')) {\n value = value.replace(/^rgba\\(/, 'rgb(');\n } else if (value.startsWith('hsla(')) {\n value = value.replace(/^hsla\\(/, 'hsl(');\n }\n return value;\n }\n const tokens = tokenize({ css: value });\n const components = parseComponentValue(tokens) as ComponentValue;\n const parsedComponents = colorParser(components);\n if (!parsedComponents) {\n setCache(cacheKey, null);\n return new NullObject();\n }\n const {\n alpha: alphaComponent,\n channels: channelsComponent,\n colorNotation,\n syntaxFlags\n } = parsedComponents;\n let alpha: number | string;\n if (Number.isNaN(Number(alphaComponent))) {\n if (syntaxFlags instanceof Set && syntaxFlags.has(KEY_NONE)) {\n alpha = NONE;\n } else {\n alpha = 0;\n }\n } else {\n alpha = roundToPrecision(Number(alphaComponent), OCT);\n }\n let v1: number | string;\n let v2: number | string;\n let v3: number | string;\n [v1, v2, v3] = channelsComponent;\n let resolvedValue;\n if (REG_CS_CIE.test(colorNotation)) {\n const hasNone = syntaxFlags instanceof Set && syntaxFlags.has(KEY_NONE);\n if (Number.isNaN(v1)) {\n if (hasNone) {\n v1 = NONE;\n } else {\n v1 = 0;\n }\n } else {\n v1 = roundToPrecision(v1, HEX);\n }\n if (Number.isNaN(v2)) {\n if (hasNone) {\n v2 = NONE;\n } else {\n v2 = 0;\n }\n } else {\n v2 = roundToPrecision(v2, HEX);\n }\n if (Number.isNaN(v3)) {\n if (hasNone) {\n v3 = NONE;\n } else {\n v3 = 0;\n }\n } else {\n v3 = roundToPrecision(v3, HEX);\n }\n if (alpha === 1) {\n resolvedValue = `${colorNotation}(${v1} ${v2} ${v3})`;\n } else {\n resolvedValue = `${colorNotation}(${v1} ${v2} ${v3} / ${alpha})`;\n }\n } else if (REG_CS_HSL.test(colorNotation)) {\n if (Number.isNaN(v1)) {\n v1 = 0;\n }\n if (Number.isNaN(v2)) {\n v2 = 0;\n }\n if (Number.isNaN(v3)) {\n v3 = 0;\n }\n let [r, g, b] = convertColorToRgb(\n `${colorNotation}(${v1} ${v2} ${v3} / ${alpha})`\n ) as ColorChannels;\n r = roundToPrecision(r / MAX_RGB, DEC);\n g = roundToPrecision(g / MAX_RGB, DEC);\n b = roundToPrecision(b / MAX_RGB, DEC);\n if (alpha === 1) {\n resolvedValue = `color(srgb ${r} ${g} ${b})`;\n } else {\n resolvedValue = `color(srgb ${r} ${g} ${b} / ${alpha})`;\n }\n } else {\n const cs = colorNotation === 'rgb' ? 'srgb' : colorNotation;\n const hasNone = syntaxFlags instanceof Set && syntaxFlags.has(KEY_NONE);\n if (Number.isNaN(v1)) {\n if (hasNone) {\n v1 = NONE;\n } else {\n v1 = 0;\n }\n } else {\n v1 = roundToPrecision(v1, DEC);\n }\n if (Number.isNaN(v2)) {\n if (hasNone) {\n v2 = NONE;\n } else {\n v2 = 0;\n }\n } else {\n v2 = roundToPrecision(v2, DEC);\n }\n if (Number.isNaN(v3)) {\n if (hasNone) {\n v3 = NONE;\n } else {\n v3 = 0;\n }\n } else {\n v3 = roundToPrecision(v3, DEC);\n }\n if (alpha === 1) {\n resolvedValue = `color(${cs} ${v1} ${v2} ${v3})`;\n } else {\n resolvedValue = `color(${cs} ${v1} ${v2} ${v3} / ${alpha})`;\n }\n }\n setCache(cacheKey, resolvedValue);\n return resolvedValue;\n}\n"],"mappings":";;;;;;;;;;;;;;AA4CA,IAAM,EACJ,YAAY,aACZ,SAAS,SACT,OAAO,OACP,WAAW,KACX,KACA,UAAU,MACV,OAAO,OACP,QAAQ,KACR,WAAW,YACX,YAAY,KACZ,YAAY,YACV;AACJ,IAAM,EAAE,iBAAiB,aAAa;AACtC,IAAM,YAAY;AAGlB,IAAM,MAAM;AACZ,IAAM,MAAM;AACZ,IAAM,MAAM;AACZ,IAAM,UAAU;AAChB,IAAM,UAAU;AAShB,IAAM,iBAAiB,IAAI,OACzB,IAAI,OAAO,GAAG,eAAe,GAAG,QAAQ,OACzC;AACD,IAAM,aAAa;AACnB,IAAM,aAAa,IAAI,OAAO,OAAO,OAAO,GAAG,OAAO,IAAI;AAC1D,IAAM,kBAAkB;AACxB,IAAM,oBAAoB,IAAI,OAAO,kBAAkB;AACvD,IAAM,aAAa,IAAI,OAAO,OAAO;AACrC,IAAM,kBAAkB,IAAI,OAAO,IAAI,cAAc;AACrD,IAAM,mBAAmB,IAAI,OAAO,IAAI,SAAS;AACjD,IAAM,aAAa,IAAI,OAAO,WAAW;;;;;;;AAQzC,SAAgB,qBACd,QACA,MAAe,EAAE,EACyB;AAC1C,KAAI,CAAC,MAAM,QAAQ,OAAO,CACxB,OAAM,IAAI,UAAU,GAAG,OAAO,mBAAmB;CAEnD,MAAM,EAAE,aAAa,IAAI,SAAS,OAAO;CAazC,MAAM,eAZgB,IAAI,IAAI;EAC5B,CAAC,SAAS;GAAC;GAAK;GAAK;GAAK;GAAQ,CAAC;EACnC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IAAI;AAEhC,MAAI,OAAO,MAAM,GAAG,CAClB,KAAI,QACF,MAAK;MAEL,MAAK;MAGP,MAAK,iBAAiB,IAAI,IAAI;AAEhC,MAAI,OAAO,MAAM,GAAG,CAClB,KAAI,QACF,MAAK;MAEL,MAAK;MAGP,MAAK,iBAAiB,IAAI,IAAI;AAEhC,MAAI,UAAU,EACZ,iBAAgB,SAAS,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG;MAE9C,iBAAgB,SAAS,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,KAAK,MAAM;;AAG7D,UAAS,UAAU,cAAc;AACjC,QAAO"} \ No newline at end of file diff --git a/node_modules/@asamuzakjp/css-color/dist/esm/js/resolve.d.ts b/node_modules/@asamuzakjp/css-color/dist/esm/js/resolve.d.ts new file mode 100644 index 00000000..a9880783 --- /dev/null +++ b/node_modules/@asamuzakjp/css-color/dist/esm/js/resolve.d.ts @@ -0,0 +1,52 @@ +import { NullObject } from './cache.js'; +import { Options } from './typedef.js'; +/** + * resolve color + * @param value - CSS color value + * @param [opt] - options + * @returns resolved color + */ +export declare const resolveColor: (value: string, opt?: Options) => string | NullObject; +/** + * resolve CSS color + * @param value + * - CSS color value + * - system colors are not supported + * @param [opt] - options + * @param [opt.currentColor] + * - color to use for `currentcolor` keyword + * - if omitted, it will be treated as a missing color + * i.e. `rgb(none none none / none)` + * @param [opt.customProperty] + * - custom properties + * - pair of `--` prefixed property name and value, + * e.g. `customProperty: { '--some-color': '#0000ff' }` + * - and/or `callback` function to get the value of the custom property, + * e.g. `customProperty: { callback: someDeclaration.getPropertyValue }` + * @param [opt.dimension] + * - dimension, convert relative length to pixels + * - pair of unit and it's value as a number in pixels, + * e.g. `dimension: { em: 12, rem: 16, vw: 10.26 }` + * - and/or `callback` function to get the value as a number in pixels, + * e.g. `dimension: { callback: convertUnitToPixel }` + * @param [opt.format] + * - output format, one of below + * - `computedValue` (default), [computed value][139] of the color + * - `specifiedValue`, [specified value][140] of the color + * - `hex`, hex color notation, i.e. `rrggbb` + * - `hexAlpha`, hex color notation with alpha channel, i.e. `#rrggbbaa` + * @returns + * - one of rgba?(), #rrggbb(aa)?, color-name, '(empty-string)', + * color(color-space r g b / alpha), color(color-space x y z / alpha), + * lab(l a b / alpha), lch(l c h / alpha), oklab(l a b / alpha), + * oklch(l c h / alpha), null + * - in `computedValue`, values are numbers, however `rgb()` values are + * integers + * - in `specifiedValue`, returns `empty string` for unknown and/or invalid + * color + * - in `hex`, returns `null` for `transparent`, and also returns `null` if + * any of `r`, `g`, `b`, `alpha` is not a number + * - in `hexAlpha`, returns `#00000000` for `transparent`, + * however returns `null` if any of `r`, `g`, `b`, `alpha` is not a number + */ +export declare const resolve: (value: string, opt?: Options) => string | null; diff --git a/node_modules/@asamuzakjp/css-color/dist/esm/js/resolve.js b/node_modules/@asamuzakjp/css-color/dist/esm/js/resolve.js new file mode 100644 index 00000000..ebb291f6 --- /dev/null +++ b/node_modules/@asamuzakjp/css-color/dist/esm/js/resolve.js @@ -0,0 +1,316 @@ +import { isString } from "./common.js"; +import { SYN_FN_CALC, SYN_FN_LIGHT_DARK, SYN_FN_REL, SYN_FN_VAR, VAL_COMP, VAL_SPEC } from "./constant.js"; +import { convertRgbToHex, resolveColorFunc, resolveColorMix, resolveColorValue } from "./color.js"; +import { resolveVar } from "./css-var.js"; +import { resolveRelativeColor } from "./relative-color.js"; +import { splitValue } from "./util.js"; +import { CacheItem, NullObject, createCacheKey, getCache, setCache } from "./cache.js"; +import { cssCalc } from "./css-calc.js"; +//#region src/js/resolve.ts +/** +* resolve +*/ +var NAMESPACE = "resolve"; +var RGB_TRANSPARENT = "rgba(0, 0, 0, 0)"; +var REG_FN_CALC = new RegExp(SYN_FN_CALC); +var REG_FN_LIGHT_DARK = new RegExp(SYN_FN_LIGHT_DARK); +var REG_FN_REL = new RegExp(SYN_FN_REL); +var REG_FN_VAR = new RegExp(SYN_FN_VAR); +/** +* resolve color +* @param value - CSS color value +* @param [opt] - options +* @returns resolved color +*/ +var resolveColor = (value, opt = {}) => { + if (isString(value)) value = value.trim(); + else throw new TypeError(`${value} is not a string.`); + const { colorScheme = "normal", currentColor = "", format = VAL_COMP, nullable = false } = opt; + const cacheKey = createCacheKey({ + namespace: NAMESPACE, + name: "resolve", + value + }, opt); + const cachedResult = getCache(cacheKey); + if (cachedResult instanceof CacheItem) { + if (cachedResult.isNull) return cachedResult; + return cachedResult.item; + } + if (REG_FN_VAR.test(value)) { + if (format === "specifiedValue") { + setCache(cacheKey, value); + return value; + } + const resolvedValue = resolveVar(value, opt); + if (resolvedValue instanceof NullObject) switch (format) { + case "hex": + case "hexAlpha": + setCache(cacheKey, resolvedValue); + return resolvedValue; + default: { + if (nullable) { + setCache(cacheKey, resolvedValue); + return resolvedValue; + } + const res = RGB_TRANSPARENT; + setCache(cacheKey, res); + return res; + } + } + else value = resolvedValue; + } + if (opt.format !== format) opt.format = format; + value = value.toLowerCase(); + if (REG_FN_LIGHT_DARK.test(value) && value.endsWith(")")) { + const [light = "", dark = ""] = splitValue(value.replace(REG_FN_LIGHT_DARK, "").replace(/\)$/, ""), { delimiter: "," }); + if (light && dark) { + if (format === "specifiedValue") { + const lightColor = resolveColor(light, opt); + const darkColor = resolveColor(dark, opt); + let res; + if (lightColor && darkColor) res = `light-dark(${lightColor}, ${darkColor})`; + else res = ""; + setCache(cacheKey, res); + return res; + } + let resolvedValue; + if (colorScheme === "dark") resolvedValue = resolveColor(dark, opt); + else resolvedValue = resolveColor(light, opt); + let res; + if (resolvedValue instanceof NullObject) if (nullable) res = resolvedValue; + else res = RGB_TRANSPARENT; + else res = resolvedValue; + setCache(cacheKey, res); + return res; + } + switch (format) { + case VAL_SPEC: + setCache(cacheKey, ""); + return ""; + case "hex": + case "hexAlpha": + setCache(cacheKey, null); + return new NullObject(); + case VAL_COMP: + default: { + const res = RGB_TRANSPARENT; + setCache(cacheKey, res); + return res; + } + } + } + if (REG_FN_REL.test(value)) { + const resolvedValue = resolveRelativeColor(value, opt); + if (format === "computedValue") { + let res; + if (resolvedValue instanceof NullObject) if (nullable) res = resolvedValue; + else res = RGB_TRANSPARENT; + else res = resolvedValue; + setCache(cacheKey, res); + return res; + } + if (format === "specifiedValue") { + let res = ""; + if (resolvedValue instanceof NullObject) res = ""; + else res = resolvedValue; + setCache(cacheKey, res); + return res; + } + if (resolvedValue instanceof NullObject) value = ""; + else value = resolvedValue; + } + if (REG_FN_CALC.test(value)) value = cssCalc(value, opt); + let cs = ""; + let r = NaN; + let g = NaN; + let b = NaN; + let alpha = NaN; + if (value === "transparent") switch (format) { + case VAL_SPEC: + setCache(cacheKey, value); + return value; + case "hex": + setCache(cacheKey, null); + return new NullObject(); + case "hexAlpha": { + const res = "#00000000"; + setCache(cacheKey, res); + return res; + } + case VAL_COMP: + default: { + const res = RGB_TRANSPARENT; + setCache(cacheKey, res); + return res; + } + } + else if (value === "currentcolor") { + if (format === "specifiedValue") { + setCache(cacheKey, value); + return value; + } + if (currentColor) { + let resolvedValue; + if (currentColor.startsWith("color-mix(")) resolvedValue = resolveColorMix(currentColor, opt); + else if (currentColor.startsWith("color(")) resolvedValue = resolveColorFunc(currentColor, opt); + else resolvedValue = resolveColorValue(currentColor, opt); + if (resolvedValue instanceof NullObject) { + setCache(cacheKey, resolvedValue); + return resolvedValue; + } + [cs, r, g, b, alpha] = resolvedValue; + } else if (format === "computedValue") { + const res = RGB_TRANSPARENT; + setCache(cacheKey, res); + return res; + } + } else if (format === "specifiedValue") if (value.startsWith("color-mix(")) { + const res = resolveColorMix(value, opt); + setCache(cacheKey, res); + return res; + } else if (value.startsWith("color(")) { + const [scs, rr, gg, bb, aa] = resolveColorFunc(value, opt); + let res = ""; + if (aa === 1) res = `color(${scs} ${rr} ${gg} ${bb})`; + else res = `color(${scs} ${rr} ${gg} ${bb} / ${aa})`; + setCache(cacheKey, res); + return res; + } else { + const rgb = resolveColorValue(value, opt); + if (isString(rgb)) { + setCache(cacheKey, rgb); + return rgb; + } + const [scs, rr, gg, bb, aa] = rgb; + let res = ""; + if (scs === "rgb") if (aa === 1) res = `${scs}(${rr}, ${gg}, ${bb})`; + else res = `${scs}a(${rr}, ${gg}, ${bb}, ${aa})`; + else if (aa === 1) res = `${scs}(${rr} ${gg} ${bb})`; + else res = `${scs}(${rr} ${gg} ${bb} / ${aa})`; + setCache(cacheKey, res); + return res; + } + else if (value.startsWith("color-mix(")) { + if (/currentcolor/.test(value)) { + if (currentColor) value = value.replace(/currentcolor/g, currentColor); + } + if (/transparent/.test(value)) value = value.replace(/transparent/g, RGB_TRANSPARENT); + const resolvedValue = resolveColorMix(value, opt); + if (resolvedValue instanceof NullObject) { + setCache(cacheKey, resolvedValue); + return resolvedValue; + } + [cs, r, g, b, alpha] = resolvedValue; + } else if (value.startsWith("color(")) { + const resolvedValue = resolveColorFunc(value, opt); + if (resolvedValue instanceof NullObject) { + setCache(cacheKey, resolvedValue); + return resolvedValue; + } + [cs, r, g, b, alpha] = resolvedValue; + } else if (value) { + const resolvedValue = resolveColorValue(value, opt); + if (resolvedValue instanceof NullObject) { + setCache(cacheKey, resolvedValue); + return resolvedValue; + } + [cs, r, g, b, alpha] = resolvedValue; + } + let res = ""; + switch (format) { + case "hex": + if (Number.isNaN(r) || Number.isNaN(g) || Number.isNaN(b) || Number.isNaN(alpha) || alpha === 0) { + setCache(cacheKey, null); + return new NullObject(); + } + res = convertRgbToHex([ + r, + g, + b, + 1 + ]); + break; + case "hexAlpha": + if (Number.isNaN(r) || Number.isNaN(g) || Number.isNaN(b) || Number.isNaN(alpha)) { + setCache(cacheKey, null); + return new NullObject(); + } + res = convertRgbToHex([ + r, + g, + b, + alpha + ]); + break; + case VAL_COMP: + default: switch (cs) { + case "rgb": + if (alpha === 1) res = `${cs}(${r}, ${g}, ${b})`; + else res = `${cs}a(${r}, ${g}, ${b}, ${alpha})`; + break; + case "lab": + case "lch": + case "oklab": + case "oklch": + if (alpha === 1) res = `${cs}(${r} ${g} ${b})`; + else res = `${cs}(${r} ${g} ${b} / ${alpha})`; + break; + default: if (alpha === 1) res = `color(${cs} ${r} ${g} ${b})`; + else res = `color(${cs} ${r} ${g} ${b} / ${alpha})`; + } + } + setCache(cacheKey, res); + return res; +}; +/** +* resolve CSS color +* @param value +* - CSS color value +* - system colors are not supported +* @param [opt] - options +* @param [opt.currentColor] +* - color to use for `currentcolor` keyword +* - if omitted, it will be treated as a missing color +* i.e. `rgb(none none none / none)` +* @param [opt.customProperty] +* - custom properties +* - pair of `--` prefixed property name and value, +* e.g. `customProperty: { '--some-color': '#0000ff' }` +* - and/or `callback` function to get the value of the custom property, +* e.g. `customProperty: { callback: someDeclaration.getPropertyValue }` +* @param [opt.dimension] +* - dimension, convert relative length to pixels +* - pair of unit and it's value as a number in pixels, +* e.g. `dimension: { em: 12, rem: 16, vw: 10.26 }` +* - and/or `callback` function to get the value as a number in pixels, +* e.g. `dimension: { callback: convertUnitToPixel }` +* @param [opt.format] +* - output format, one of below +* - `computedValue` (default), [computed value][139] of the color +* - `specifiedValue`, [specified value][140] of the color +* - `hex`, hex color notation, i.e. `rrggbb` +* - `hexAlpha`, hex color notation with alpha channel, i.e. `#rrggbbaa` +* @returns +* - one of rgba?(), #rrggbb(aa)?, color-name, '(empty-string)', +* color(color-space r g b / alpha), color(color-space x y z / alpha), +* lab(l a b / alpha), lch(l c h / alpha), oklab(l a b / alpha), +* oklch(l c h / alpha), null +* - in `computedValue`, values are numbers, however `rgb()` values are +* integers +* - in `specifiedValue`, returns `empty string` for unknown and/or invalid +* color +* - in `hex`, returns `null` for `transparent`, and also returns `null` if +* any of `r`, `g`, `b`, `alpha` is not a number +* - in `hexAlpha`, returns `#00000000` for `transparent`, +* however returns `null` if any of `r`, `g`, `b`, `alpha` is not a number +*/ +var resolve = (value, opt = {}) => { + opt.nullable = false; + const resolvedValue = resolveColor(value, opt); + if (resolvedValue instanceof NullObject) return null; + return resolvedValue; +}; +//#endregion +export { resolve, resolveColor }; + +//# sourceMappingURL=resolve.js.map \ No newline at end of file diff --git a/node_modules/@asamuzakjp/css-color/dist/esm/js/resolve.js.map b/node_modules/@asamuzakjp/css-color/dist/esm/js/resolve.js.map new file mode 100644 index 00000000..b2a85e1a --- /dev/null +++ b/node_modules/@asamuzakjp/css-color/dist/esm/js/resolve.js.map @@ -0,0 +1 @@ +{"version":3,"file":"resolve.js","names":[],"sources":["../../../src/js/resolve.ts"],"sourcesContent":["/**\n * resolve\n */\n\nimport {\n CacheItem,\n NullObject,\n createCacheKey,\n getCache,\n setCache\n} from './cache';\nimport {\n convertRgbToHex,\n resolveColorFunc,\n resolveColorMix,\n resolveColorValue\n} from './color';\nimport { isString } from './common';\nimport { cssCalc } from './css-calc';\nimport { resolveVar } from './css-var';\nimport { resolveRelativeColor } from './relative-color';\nimport { splitValue } from './util';\nimport {\n ComputedColorChannels,\n Options,\n SpecifiedColorChannels\n} from './typedef';\n\n/* constants */\nimport {\n FN_COLOR,\n FN_MIX,\n SYN_FN_CALC,\n SYN_FN_LIGHT_DARK,\n SYN_FN_REL,\n SYN_FN_VAR,\n VAL_COMP,\n VAL_SPEC\n} from './constant';\nconst NAMESPACE = 'resolve';\nconst RGB_TRANSPARENT = 'rgba(0, 0, 0, 0)';\n\n/* regexp */\nconst REG_FN_CALC = new RegExp(SYN_FN_CALC);\nconst REG_FN_LIGHT_DARK = new RegExp(SYN_FN_LIGHT_DARK);\nconst REG_FN_REL = new RegExp(SYN_FN_REL);\nconst REG_FN_VAR = new RegExp(SYN_FN_VAR);\n\n/**\n * resolve color\n * @param value - CSS color value\n * @param [opt] - options\n * @returns resolved color\n */\nexport const resolveColor = (\n value: string,\n opt: Options = {}\n): string | NullObject => {\n if (isString(value)) {\n value = value.trim();\n } else {\n throw new TypeError(`${value} is not a string.`);\n }\n const {\n colorScheme = 'normal',\n currentColor = '',\n format = VAL_COMP,\n nullable = false\n } = opt;\n const cacheKey: string = createCacheKey(\n {\n namespace: NAMESPACE,\n name: 'resolve',\n value\n },\n opt\n );\n const cachedResult = getCache(cacheKey);\n if (cachedResult instanceof CacheItem) {\n if (cachedResult.isNull) {\n return cachedResult as NullObject;\n }\n return cachedResult.item as string;\n }\n if (REG_FN_VAR.test(value)) {\n if (format === VAL_SPEC) {\n setCache(cacheKey, value);\n return value;\n }\n const resolvedValue = resolveVar(value, opt);\n if (resolvedValue instanceof NullObject) {\n switch (format) {\n case 'hex':\n case 'hexAlpha': {\n setCache(cacheKey, resolvedValue);\n return resolvedValue;\n }\n default: {\n if (nullable) {\n setCache(cacheKey, resolvedValue);\n return resolvedValue;\n }\n const res = RGB_TRANSPARENT;\n setCache(cacheKey, res);\n return res;\n }\n }\n } else {\n value = resolvedValue;\n }\n }\n if (opt.format !== format) {\n opt.format = format;\n }\n value = value.toLowerCase();\n if (REG_FN_LIGHT_DARK.test(value) && value.endsWith(')')) {\n const colorParts = value.replace(REG_FN_LIGHT_DARK, '').replace(/\\)$/, '');\n const [light = '', dark = ''] = splitValue(colorParts, {\n delimiter: ','\n });\n if (light && dark) {\n if (format === VAL_SPEC) {\n const lightColor = resolveColor(light, opt);\n const darkColor = resolveColor(dark, opt);\n let res;\n if (lightColor && darkColor) {\n res = `light-dark(${lightColor}, ${darkColor})`;\n } else {\n res = '';\n }\n setCache(cacheKey, res);\n return res;\n }\n let resolvedValue;\n if (colorScheme === 'dark') {\n resolvedValue = resolveColor(dark, opt);\n } else {\n resolvedValue = resolveColor(light, opt);\n }\n let res;\n if (resolvedValue instanceof NullObject) {\n if (nullable) {\n res = resolvedValue;\n } else {\n res = RGB_TRANSPARENT;\n }\n } else {\n res = resolvedValue;\n }\n setCache(cacheKey, res);\n return res;\n }\n // invalid value\n switch (format) {\n case VAL_SPEC: {\n setCache(cacheKey, '');\n return '';\n }\n case 'hex':\n case 'hexAlpha': {\n setCache(cacheKey, null);\n return new NullObject();\n }\n case VAL_COMP:\n default: {\n const res = RGB_TRANSPARENT;\n setCache(cacheKey, res);\n return res;\n }\n }\n }\n if (REG_FN_REL.test(value)) {\n const resolvedValue = resolveRelativeColor(value, opt);\n if (format === VAL_COMP) {\n let res;\n if (resolvedValue instanceof NullObject) {\n if (nullable) {\n res = resolvedValue;\n } else {\n res = RGB_TRANSPARENT;\n }\n } else {\n res = resolvedValue;\n }\n setCache(cacheKey, res);\n return res;\n }\n if (format === VAL_SPEC) {\n let res = '';\n if (resolvedValue instanceof NullObject) {\n res = '';\n } else {\n res = resolvedValue;\n }\n setCache(cacheKey, res);\n return res;\n }\n if (resolvedValue instanceof NullObject) {\n value = '';\n } else {\n value = resolvedValue;\n }\n }\n if (REG_FN_CALC.test(value)) {\n value = cssCalc(value, opt);\n }\n let cs = '';\n let r = NaN;\n let g = NaN;\n let b = NaN;\n let alpha = NaN;\n if (value === 'transparent') {\n switch (format) {\n case VAL_SPEC: {\n setCache(cacheKey, value);\n return value;\n }\n case 'hex': {\n setCache(cacheKey, null);\n return new NullObject();\n }\n case 'hexAlpha': {\n const res = '#00000000';\n setCache(cacheKey, res);\n return res;\n }\n case VAL_COMP:\n default: {\n const res = RGB_TRANSPARENT;\n setCache(cacheKey, res);\n return res;\n }\n }\n } else if (value === 'currentcolor') {\n if (format === VAL_SPEC) {\n setCache(cacheKey, value);\n return value;\n }\n if (currentColor) {\n let resolvedValue;\n if (currentColor.startsWith(FN_MIX)) {\n resolvedValue = resolveColorMix(currentColor, opt);\n } else if (currentColor.startsWith(FN_COLOR)) {\n resolvedValue = resolveColorFunc(currentColor, opt);\n } else {\n resolvedValue = resolveColorValue(currentColor, opt);\n }\n if (resolvedValue instanceof NullObject) {\n setCache(cacheKey, resolvedValue);\n return resolvedValue;\n }\n [cs, r, g, b, alpha] = resolvedValue as ComputedColorChannels;\n } else if (format === VAL_COMP) {\n const res = RGB_TRANSPARENT;\n setCache(cacheKey, res);\n return res;\n }\n } else if (format === VAL_SPEC) {\n if (value.startsWith(FN_MIX)) {\n const res = resolveColorMix(value, opt) as string;\n setCache(cacheKey, res);\n return res;\n } else if (value.startsWith(FN_COLOR)) {\n const [scs, rr, gg, bb, aa] = resolveColorFunc(\n value,\n opt\n ) as SpecifiedColorChannels;\n let res = '';\n if (aa === 1) {\n res = `color(${scs} ${rr} ${gg} ${bb})`;\n } else {\n res = `color(${scs} ${rr} ${gg} ${bb} / ${aa})`;\n }\n setCache(cacheKey, res);\n return res;\n } else {\n const rgb = resolveColorValue(value, opt);\n if (isString(rgb)) {\n setCache(cacheKey, rgb);\n return rgb;\n }\n const [scs, rr, gg, bb, aa] = rgb as SpecifiedColorChannels;\n let res = '';\n if (scs === 'rgb') {\n if (aa === 1) {\n res = `${scs}(${rr}, ${gg}, ${bb})`;\n } else {\n res = `${scs}a(${rr}, ${gg}, ${bb}, ${aa})`;\n }\n } else if (aa === 1) {\n res = `${scs}(${rr} ${gg} ${bb})`;\n } else {\n res = `${scs}(${rr} ${gg} ${bb} / ${aa})`;\n }\n setCache(cacheKey, res);\n return res;\n }\n } else if (value.startsWith(FN_MIX)) {\n if (/currentcolor/.test(value)) {\n if (currentColor) {\n value = value.replace(/currentcolor/g, currentColor);\n }\n }\n if (/transparent/.test(value)) {\n value = value.replace(/transparent/g, RGB_TRANSPARENT);\n }\n const resolvedValue = resolveColorMix(value, opt);\n if (resolvedValue instanceof NullObject) {\n setCache(cacheKey, resolvedValue);\n return resolvedValue;\n }\n [cs, r, g, b, alpha] = resolvedValue as ComputedColorChannels;\n } else if (value.startsWith(FN_COLOR)) {\n const resolvedValue = resolveColorFunc(value, opt);\n if (resolvedValue instanceof NullObject) {\n setCache(cacheKey, resolvedValue);\n return resolvedValue;\n }\n [cs, r, g, b, alpha] = resolvedValue as ComputedColorChannels;\n } else if (value) {\n const resolvedValue = resolveColorValue(value, opt);\n if (resolvedValue instanceof NullObject) {\n setCache(cacheKey, resolvedValue);\n return resolvedValue;\n }\n [cs, r, g, b, alpha] = resolvedValue as ComputedColorChannels;\n }\n let res = '';\n switch (format) {\n case 'hex': {\n if (\n Number.isNaN(r) ||\n Number.isNaN(g) ||\n Number.isNaN(b) ||\n Number.isNaN(alpha) ||\n alpha === 0\n ) {\n setCache(cacheKey, null);\n return new NullObject();\n }\n res = convertRgbToHex([r, g, b, 1]);\n break;\n }\n case 'hexAlpha': {\n if (\n Number.isNaN(r) ||\n Number.isNaN(g) ||\n Number.isNaN(b) ||\n Number.isNaN(alpha)\n ) {\n setCache(cacheKey, null);\n return new NullObject();\n }\n res = convertRgbToHex([r, g, b, alpha]);\n break;\n }\n case VAL_COMP:\n default: {\n switch (cs) {\n case 'rgb': {\n if (alpha === 1) {\n res = `${cs}(${r}, ${g}, ${b})`;\n } else {\n res = `${cs}a(${r}, ${g}, ${b}, ${alpha})`;\n }\n break;\n }\n case 'lab':\n case 'lch':\n case 'oklab':\n case 'oklch': {\n if (alpha === 1) {\n res = `${cs}(${r} ${g} ${b})`;\n } else {\n res = `${cs}(${r} ${g} ${b} / ${alpha})`;\n }\n break;\n }\n // color()\n default: {\n if (alpha === 1) {\n res = `color(${cs} ${r} ${g} ${b})`;\n } else {\n res = `color(${cs} ${r} ${g} ${b} / ${alpha})`;\n }\n }\n }\n }\n }\n setCache(cacheKey, res);\n return res;\n};\n\n/**\n * resolve CSS color\n * @param value\n * - CSS color value\n * - system colors are not supported\n * @param [opt] - options\n * @param [opt.currentColor]\n * - color to use for `currentcolor` keyword\n * - if omitted, it will be treated as a missing color\n * i.e. `rgb(none none none / none)`\n * @param [opt.customProperty]\n * - custom properties\n * - pair of `--` prefixed property name and value,\n * e.g. `customProperty: { '--some-color': '#0000ff' }`\n * - and/or `callback` function to get the value of the custom property,\n * e.g. `customProperty: { callback: someDeclaration.getPropertyValue }`\n * @param [opt.dimension]\n * - dimension, convert relative length to pixels\n * - pair of unit and it's value as a number in pixels,\n * e.g. `dimension: { em: 12, rem: 16, vw: 10.26 }`\n * - and/or `callback` function to get the value as a number in pixels,\n * e.g. `dimension: { callback: convertUnitToPixel }`\n * @param [opt.format]\n * - output format, one of below\n * - `computedValue` (default), [computed value][139] of the color\n * - `specifiedValue`, [specified value][140] of the color\n * - `hex`, hex color notation, i.e. `rrggbb`\n * - `hexAlpha`, hex color notation with alpha channel, i.e. `#rrggbbaa`\n * @returns\n * - one of rgba?(), #rrggbb(aa)?, color-name, '(empty-string)',\n * color(color-space r g b / alpha), color(color-space x y z / alpha),\n * lab(l a b / alpha), lch(l c h / alpha), oklab(l a b / alpha),\n * oklch(l c h / alpha), null\n * - in `computedValue`, values are numbers, however `rgb()` values are\n * integers\n * - in `specifiedValue`, returns `empty string` for unknown and/or invalid\n * color\n * - in `hex`, returns `null` for `transparent`, and also returns `null` if\n * any of `r`, `g`, `b`, `alpha` is not a number\n * - in `hexAlpha`, returns `#00000000` for `transparent`,\n * however returns `null` if any of `r`, `g`, `b`, `alpha` is not a number\n */\nexport const resolve = (value: string, opt: Options = {}): string | null => {\n opt.nullable = false;\n const resolvedValue = resolveColor(value, opt);\n if (resolvedValue instanceof NullObject) {\n return null;\n }\n return resolvedValue as string;\n};\n"],"mappings":";;;;;;;;;;;;AAuCA,IAAM,YAAY;AAClB,IAAM,kBAAkB;AAGxB,IAAM,cAAc,IAAI,OAAO,YAAY;AAC3C,IAAM,oBAAoB,IAAI,OAAO,kBAAkB;AACvD,IAAM,aAAa,IAAI,OAAO,WAAW;AACzC,IAAM,aAAa,IAAI,OAAO,WAAW;;;;;;;AAQzC,IAAa,gBACX,OACA,MAAe,EAAE,KACO;AACxB,KAAI,SAAS,MAAM,CACjB,SAAQ,MAAM,MAAM;KAEpB,OAAM,IAAI,UAAU,GAAG,MAAM,mBAAmB;CAElD,MAAM,EACJ,cAAc,UACd,eAAe,IACf,SAAS,UACT,WAAW,UACT;CACJ,MAAM,WAAmB,eACvB;EACE,WAAW;EACX,MAAM;EACN;EACD,EACD,IACD;CACD,MAAM,eAAe,SAAS,SAAS;AACvC,KAAI,wBAAwB,WAAW;AACrC,MAAI,aAAa,OACf,QAAO;AAET,SAAO,aAAa;;AAEtB,KAAI,WAAW,KAAK,MAAM,EAAE;AAC1B,MAAI,WAAA,kBAAqB;AACvB,YAAS,UAAU,MAAM;AACz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E,GAAG,EAAE;QAE3B,OAAM,GAAG,GAAG,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,KAAK,MAAM;AAExC;GAGF,QACE,KAAI,UAAU,EACZ,OAAM,SAAS,GAAG,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE;OAEjC,OAAM,SAAS,GAAG,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,KAAK,MAAM;;;AAMtD,UAAS,UAAU,IAAI;AACvB,QAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CT,IAAa,WAAW,OAAe,MAAe,EAAE,KAAoB;AAC1E,KAAI,WAAW;CACf,MAAM,gBAAgB,aAAa,OAAO,IAAI;AAC9C,KAAI,yBAAyB,WAC3B,QAAO;AAET,QAAO"} \ No newline at end of file diff --git a/node_modules/@asamuzakjp/css-color/dist/esm/js/typedef.d.ts b/node_modules/@asamuzakjp/css-color/dist/esm/js/typedef.d.ts new file mode 100644 index 00000000..51303772 --- /dev/null +++ b/node_modules/@asamuzakjp/css-color/dist/esm/js/typedef.d.ts @@ -0,0 +1,80 @@ +/** + * typedef + */ +/** + * @typedef Options - options + * @property [alpha] - enable alpha + * @property [colorSpace] - color space + * @property [currentColor] - color for currentcolor + * @property [customProperty] - custom properties + * @property [d50] - white point in d50 + * @property [dimension] - dimension + * @property [format] - output format + * @property [key] - key + */ +export interface Options { + alpha?: boolean; + colorScheme?: string; + colorSpace?: string; + currentColor?: string; + customProperty?: Record string)>; + d50?: boolean; + delimiter?: string | string[]; + dimension?: Record number)>; + format?: string; + nullable?: boolean; + preserveComment?: boolean; +} +/** + * @type ColorChannels - color channels + */ +export type ColorChannels = [x: number, y: number, z: number, alpha: number]; +/** + * @type StringColorChannels - color channels + */ +export type StringColorChannels = [ + x: string, + y: string, + z: string, + alpha: string | undefined +]; +/** + * @type StringColorSpacedChannels - specified value + */ +export type StringColorSpacedChannels = [ + cs: string, + x: string, + y: string, + z: string, + alpha: string | undefined +]; +/** + * @type ComputedColorChannels - computed value + */ +export type ComputedColorChannels = [ + cs: string, + x: number, + y: number, + z: number, + alpha: number +]; +/** + * @type SpecifiedColorChannels - specified value + */ +export type SpecifiedColorChannels = [ + cs: string, + x: number | string, + y: number | string, + z: number | string, + alpha: number | string +]; +/** + * @type MatchedRegExp - matched regexp array + */ +export type MatchedRegExp = [ + match: string, + gr1: string, + gr2: string, + gr3: string, + gr4: string +]; diff --git a/node_modules/@asamuzakjp/css-color/dist/esm/js/util.d.ts b/node_modules/@asamuzakjp/css-color/dist/esm/js/util.d.ts new file mode 100644 index 00000000..bc5d487f --- /dev/null +++ b/node_modules/@asamuzakjp/css-color/dist/esm/js/util.d.ts @@ -0,0 +1,66 @@ +import { Options } from './typedef.js'; +/** + * split value + * NOTE: comments are stripped, it can be preserved if, in the options param, + * `delimiter` is either ',' or '/' and with `preserveComment` set to `true` + * @param value - CSS value + * @param [opt] - options + * @returns array of values + */ +export declare const splitValue: (value: string, opt?: Options) => string[]; +/** + * extract dashed-ident tokens + * @param value - CSS value + * @returns array of dashed-ident tokens + */ +export declare const extractDashedIdent: (value: string) => string[]; +/** + * is color + * @param value - CSS value + * @param [opt] - options + * @returns result + */ +export declare const isColor: (value: unknown, opt?: Options) => boolean; +/** + * value to JSON string + * @param value - CSS value + * @param [func] - stringify function + * @returns stringified value in JSON notation + */ +export declare const valueToJsonString: (value: unknown, func?: boolean) => string; +/** + * round to specified precision + * @param value - numeric value + * @param bit - minimum bits + * @returns rounded value + */ +export declare const roundToPrecision: (value: number, bit?: number) => number; +/** + * interpolate hue + * @param hueA - hue value + * @param hueB - hue value + * @param arc - shorter | longer | increasing | decreasing + * @returns result - [hueA, hueB] + */ +export declare const interpolateHue: (hueA: number, hueB: number, arc?: string) => [number, number]; +/** + * resolve length in pixels + * @param value - value + * @param unit - unit + * @param [opt] - options + * @returns pixelated value + */ +export declare const resolveLengthInPixels: (value: number | string, unit: string | undefined, opt?: Options) => number; +/** + * is absolute size or length + * @param value - value + * @param unit - unit + * @returns result + */ +export declare const isAbsoluteSizeOrLength: (value: number | string, unit: string | undefined) => boolean; +/** + * is absolute font size + * @param value - value + * @returns result + */ +export declare const isAbsoluteFontSize: (value: unknown) => boolean; diff --git a/node_modules/@asamuzakjp/css-color/dist/esm/js/util.js b/node_modules/@asamuzakjp/css-color/dist/esm/js/util.js new file mode 100644 index 00000000..add7596c --- /dev/null +++ b/node_modules/@asamuzakjp/css-color/dist/esm/js/util.js @@ -0,0 +1,303 @@ +import { isString } from "./common.js"; +import { SYN_COLOR_TYPE, SYN_MIX, VAL_SPEC } from "./constant.js"; +import { NAMED_COLORS } from "./color.js"; +import { resolveColor } from "./resolve.js"; +import { CacheItem, createCacheKey, getCache, setCache } from "./cache.js"; +import { TokenType, tokenize } from "@csstools/css-tokenizer"; +//#region src/js/util.ts +/** +* util +*/ +var { CloseParen: PAREN_CLOSE, Comma: COMMA, Comment: COMMENT, Delim: DELIM, EOF, Function: FUNC, Ident: IDENT, OpenParen: PAREN_OPEN, Whitespace: W_SPACE } = TokenType; +var NAMESPACE = "util"; +var DEC = 10; +var HEX = 16; +var DEG = 360; +var DEG_HALF = 180; +var REG_COLOR = new RegExp(`^(?:${SYN_COLOR_TYPE})$`); +var REG_FN_COLOR = /^(?:(?:ok)?l(?:ab|ch)|color(?:-mix)?|hsla?|hwb|rgba?|var)\(/; +var REG_MIX = new RegExp(SYN_MIX); +/** +* split value +* NOTE: comments are stripped, it can be preserved if, in the options param, +* `delimiter` is either ',' or '/' and with `preserveComment` set to `true` +* @param value - CSS value +* @param [opt] - options +* @returns array of values +*/ +var splitValue = (value, opt = {}) => { + if (isString(value)) value = value.trim(); + else throw new TypeError(`${value} is not a string.`); + const { delimiter = " ", preserveComment = false } = opt; + const cacheKey = createCacheKey({ + namespace: NAMESPACE, + name: "splitValue", + value + }, { + delimiter, + preserveComment + }); + const cachedResult = getCache(cacheKey); + if (cachedResult instanceof CacheItem) return cachedResult.item; + let regDelimiter; + if (delimiter === ",") regDelimiter = /^,$/; + else if (delimiter === "/") regDelimiter = /^\/$/; + else regDelimiter = /^\s+$/; + const tokens = tokenize({ css: value }); + let nest = 0; + let str = ""; + const res = []; + while (tokens.length) { + const [type, value] = tokens.shift(); + switch (type) { + case COMMA: + if (regDelimiter.test(value)) if (nest === 0) { + res.push(str.trim()); + str = ""; + } else str += value; + else str += value; + break; + case DELIM: + if (regDelimiter.test(value)) if (nest === 0) { + res.push(str.trim()); + str = ""; + } else str += value; + else str += value; + break; + case COMMENT: + if (preserveComment && (delimiter === "," || delimiter === "/")) str += value; + break; + case FUNC: + case PAREN_OPEN: + str += value; + nest++; + break; + case PAREN_CLOSE: + str += value; + nest--; + break; + case W_SPACE: + if (regDelimiter.test(value)) if (nest === 0) { + if (str) { + res.push(str.trim()); + str = ""; + } + } else str += " "; + else if (!str.endsWith(" ")) str += " "; + break; + default: if (type === EOF) { + res.push(str.trim()); + str = ""; + } else str += value; + } + } + setCache(cacheKey, res); + return res; +}; +/** +* extract dashed-ident tokens +* @param value - CSS value +* @returns array of dashed-ident tokens +*/ +var extractDashedIdent = (value) => { + if (isString(value)) value = value.trim(); + else throw new TypeError(`${value} is not a string.`); + const cacheKey = createCacheKey({ + namespace: NAMESPACE, + name: "extractDashedIdent", + value + }); + const cachedResult = getCache(cacheKey); + if (cachedResult instanceof CacheItem) return cachedResult.item; + const tokens = tokenize({ css: value }); + const items = /* @__PURE__ */ new Set(); + while (tokens.length) { + const [type, value] = tokens.shift(); + if (type === IDENT && value.startsWith("--")) items.add(value); + } + const res = [...items]; + setCache(cacheKey, res); + return res; +}; +/** +* is color +* @param value - CSS value +* @param [opt] - options +* @returns result +*/ +var isColor = (value, opt = {}) => { + if (isString(value)) { + value = value.toLowerCase().trim(); + if (value && isString(value)) { + if (/^[a-z]+$/.test(value)) { + if (/^(?:currentcolor|transparent)$/.test(value) || Object.hasOwn(NAMED_COLORS, value)) return true; + } else if (REG_COLOR.test(value) || REG_MIX.test(value)) return true; + else if (REG_FN_COLOR.test(value)) { + opt.nullable = true; + if (!opt.format) opt.format = VAL_SPEC; + if (resolveColor(value, opt)) return true; + } + } + } + return false; +}; +/** +* value to JSON string +* @param value - CSS value +* @param [func] - stringify function +* @returns stringified value in JSON notation +*/ +var valueToJsonString = (value, func = false) => { + if (typeof value === "undefined") return ""; + return JSON.stringify(value, (_key, val) => { + let replacedValue; + if (typeof val === "undefined") replacedValue = null; + else if (typeof val === "function") if (func) replacedValue = val.toString().replace(/\s/g, "").substring(0, HEX); + else replacedValue = val.name; + else if (val instanceof Map || val instanceof Set) replacedValue = [...val]; + else if (typeof val === "bigint") replacedValue = val.toString(); + else replacedValue = val; + return replacedValue; + }); +}; +/** +* round to specified precision +* @param value - numeric value +* @param bit - minimum bits +* @returns rounded value +*/ +var roundToPrecision = (value, bit = 0) => { + if (!Number.isFinite(value)) throw new TypeError(`${value} is not a finite number.`); + if (!Number.isFinite(bit)) throw new TypeError(`${bit} is not a finite number.`); + else if (bit < 0 || bit > HEX) throw new RangeError(`${bit} is not between 0 and ${HEX}.`); + if (bit === 0) return Math.round(value); + let val; + if (bit === HEX) val = value.toPrecision(6); + else if (bit < DEC) val = value.toPrecision(4); + else val = value.toPrecision(5); + return parseFloat(val); +}; +/** +* interpolate hue +* @param hueA - hue value +* @param hueB - hue value +* @param arc - shorter | longer | increasing | decreasing +* @returns result - [hueA, hueB] +*/ +var interpolateHue = (hueA, hueB, arc = "shorter") => { + if (!Number.isFinite(hueA)) throw new TypeError(`${hueA} is not a finite number.`); + if (!Number.isFinite(hueB)) throw new TypeError(`${hueB} is not a finite number.`); + switch (arc) { + case "decreasing": + if (hueB > hueA) hueA += DEG; + break; + case "increasing": + if (hueB < hueA) hueB += DEG; + break; + case "longer": + if (hueB > hueA && hueB < hueA + DEG_HALF) hueA += DEG; + else if (hueB > hueA + DEG_HALF * -1 && hueB <= hueA) hueB += DEG; + break; + default: if (hueB > hueA + DEG_HALF) hueA += DEG; + else if (hueB < hueA + DEG_HALF * -1) hueB += DEG; + } + return [hueA, hueB]; +}; +var absoluteFontSize = new Map([ + ["xx-small", 9 / 16], + ["x-small", 5 / 8], + ["small", 13 / 16], + ["medium", 1], + ["large", 9 / 8], + ["x-large", 3 / 2], + ["xx-large", 2], + ["xxx-large", 3] +]); +var relativeFontSize = new Map([["smaller", 1 / 1.2], ["larger", 1.2]]); +var absoluteLength = new Map([ + ["cm", 96 / 2.54], + ["mm", 96 / 2.54 / 10], + ["q", 96 / 2.54 / 40], + ["in", 96], + ["pc", 96 / 6], + ["pt", 96 / 72], + ["px", 1] +]); +var relativeLength = new Map([ + ["rcap", 1], + ["rch", .5], + ["rem", 1], + ["rex", .5], + ["ric", 1], + ["rlh", 1.2] +]); +/** +* resolve length in pixels +* @param value - value +* @param unit - unit +* @param [opt] - options +* @returns pixelated value +*/ +var resolveLengthInPixels = (value, unit, opt = {}) => { + const { dimension = {} } = opt; + const { callback, em, rem, vh, vw } = dimension; + if (isString(value)) { + value = value.toLowerCase().trim(); + if (absoluteFontSize.has(value)) return Number(absoluteFontSize.get(value)) * rem; + else if (relativeFontSize.has(value)) return Number(relativeFontSize.get(value)) * em; + return NaN; + } else if (Number.isFinite(value) && unit) if (Object.hasOwn(dimension, unit)) return value * Number(dimension[unit]); + else if (typeof callback === "function") return value * callback(unit); + else if (absoluteLength.has(unit)) return value * Number(absoluteLength.get(unit)); + else if (relativeLength.has(unit)) return value * Number(relativeLength.get(unit)) * rem; + else if (relativeLength.has(`r${unit}`)) return value * Number(relativeLength.get(`r${unit}`)) * em; + else switch (unit) { + case "vb": + case "vi": return value * vw; + case "vmax": + if (vh > vw) return value * vh; + return value * vw; + case "vmin": + if (vh < vw) return value * vh; + return value * vw; + default: return NaN; + } + return NaN; +}; +/** +* is absolute size or length +* @param value - value +* @param unit - unit +* @returns result +*/ +var isAbsoluteSizeOrLength = (value, unit) => { + if (isString(value)) { + value = value.toLowerCase().trim(); + return absoluteFontSize.has(value); + } else if (isString(unit)) { + unit = unit.toLowerCase().trim(); + return absoluteLength.has(unit); + } + return value === 0; +}; +/** +* is absolute font size +* @param value - value +* @returns result +*/ +var isAbsoluteFontSize = (value) => { + if (isString(value)) { + const size = value.toLowerCase().trim(); + if (/^[a-z-]+$/.test(size)) return absoluteFontSize.has(size); + else { + const [, val, unit] = /^(\d+(?:\.\d+)?|\.\d+)([a-z-]+)?$/.exec(size); + if (unit) return absoluteLength.has(unit); + else if (val) return parseFloat(val) === 0; + } + } + return false; +}; +//#endregion +export { extractDashedIdent, interpolateHue, isAbsoluteFontSize, isAbsoluteSizeOrLength, isColor, resolveLengthInPixels, roundToPrecision, splitValue, valueToJsonString }; + +//# sourceMappingURL=util.js.map \ No newline at end of file diff --git a/node_modules/@asamuzakjp/css-color/dist/esm/js/util.js.map b/node_modules/@asamuzakjp/css-color/dist/esm/js/util.js.map new file mode 100644 index 00000000..6a8be8e2 --- /dev/null +++ b/node_modules/@asamuzakjp/css-color/dist/esm/js/util.js.map @@ -0,0 +1 @@ +{"version":3,"file":"util.js","names":[],"sources":["../../../src/js/util.ts"],"sourcesContent":["/**\n * util\n */\n\nimport { TokenType, tokenize } from '@csstools/css-tokenizer';\nimport { CacheItem, createCacheKey, getCache, setCache } from './cache';\nimport { isString } from './common';\nimport { resolveColor } from './resolve';\nimport { Options } from './typedef';\n\n/* constants */\nimport { NAMED_COLORS } from './color';\nimport { SYN_COLOR_TYPE, SYN_MIX, VAL_SPEC } from './constant';\nconst {\n CloseParen: PAREN_CLOSE,\n Comma: COMMA,\n Comment: COMMENT,\n Delim: DELIM,\n EOF,\n Function: FUNC,\n Ident: IDENT,\n OpenParen: PAREN_OPEN,\n Whitespace: W_SPACE\n} = TokenType;\nconst NAMESPACE = 'util';\n\n/* numeric constants */\nconst DEC = 10;\nconst HEX = 16;\nconst DEG = 360;\nconst DEG_HALF = 180;\n\n/* regexp */\nconst REG_COLOR = new RegExp(`^(?:${SYN_COLOR_TYPE})$`);\nconst REG_FN_COLOR =\n /^(?:(?:ok)?l(?:ab|ch)|color(?:-mix)?|hsla?|hwb|rgba?|var)\\(/;\nconst REG_MIX = new RegExp(SYN_MIX);\n\n/**\n * split value\n * NOTE: comments are stripped, it can be preserved if, in the options param,\n * `delimiter` is either ',' or '/' and with `preserveComment` set to `true`\n * @param value - CSS value\n * @param [opt] - options\n * @returns array of values\n */\nexport const splitValue = (value: string, opt: Options = {}): string[] => {\n if (isString(value)) {\n value = value.trim();\n } else {\n throw new TypeError(`${value} is not a string.`);\n }\n const { delimiter = ' ', preserveComment = false } = opt;\n const cacheKey: string = createCacheKey(\n {\n namespace: NAMESPACE,\n name: 'splitValue',\n value\n },\n {\n delimiter,\n preserveComment\n }\n );\n const cachedResult = getCache(cacheKey);\n if (cachedResult instanceof CacheItem) {\n return cachedResult.item as string[];\n }\n let regDelimiter;\n if (delimiter === ',') {\n regDelimiter = /^,$/;\n } else if (delimiter === '/') {\n regDelimiter = /^\\/$/;\n } else {\n regDelimiter = /^\\s+$/;\n }\n const tokens = tokenize({ css: value });\n let nest = 0;\n let str = '';\n const res: string[] = [];\n while (tokens.length) {\n const [type, value] = tokens.shift() as [TokenType, string];\n switch (type) {\n case COMMA: {\n if (regDelimiter.test(value)) {\n if (nest === 0) {\n res.push(str.trim());\n str = '';\n } else {\n str += value;\n }\n } else {\n str += value;\n }\n break;\n }\n case DELIM: {\n if (regDelimiter.test(value)) {\n if (nest === 0) {\n res.push(str.trim());\n str = '';\n } else {\n str += value;\n }\n } else {\n str += value;\n }\n break;\n }\n case COMMENT: {\n if (preserveComment && (delimiter === ',' || delimiter === '/')) {\n str += value;\n }\n break;\n }\n case FUNC:\n case PAREN_OPEN: {\n str += value;\n nest++;\n break;\n }\n case PAREN_CLOSE: {\n str += value;\n nest--;\n break;\n }\n case W_SPACE: {\n if (regDelimiter.test(value)) {\n if (nest === 0) {\n if (str) {\n res.push(str.trim());\n str = '';\n }\n } else {\n str += ' ';\n }\n } else if (!str.endsWith(' ')) {\n str += ' ';\n }\n break;\n }\n default: {\n if (type === EOF) {\n res.push(str.trim());\n str = '';\n } else {\n str += value;\n }\n }\n }\n }\n setCache(cacheKey, res);\n return res;\n};\n\n/**\n * extract dashed-ident tokens\n * @param value - CSS value\n * @returns array of dashed-ident tokens\n */\nexport const extractDashedIdent = (value: string): string[] => {\n if (isString(value)) {\n value = value.trim();\n } else {\n throw new TypeError(`${value} is not a string.`);\n }\n const cacheKey: string = createCacheKey({\n namespace: NAMESPACE,\n name: 'extractDashedIdent',\n value\n });\n const cachedResult = getCache(cacheKey);\n if (cachedResult instanceof CacheItem) {\n return cachedResult.item as string[];\n }\n const tokens = tokenize({ css: value });\n const items = new Set();\n while (tokens.length) {\n const [type, value] = tokens.shift() as [TokenType, string];\n if (type === IDENT && value.startsWith('--')) {\n items.add(value);\n }\n }\n const res = [...items] as string[];\n setCache(cacheKey, res);\n return res;\n};\n\n/**\n * is color\n * @param value - CSS value\n * @param [opt] - options\n * @returns result\n */\nexport const isColor = (value: unknown, opt: Options = {}): boolean => {\n if (isString(value)) {\n value = value.toLowerCase().trim();\n if (value && isString(value)) {\n if (/^[a-z]+$/.test(value)) {\n if (\n /^(?:currentcolor|transparent)$/.test(value) ||\n Object.hasOwn(NAMED_COLORS, value)\n ) {\n return true;\n }\n } else if (REG_COLOR.test(value) || REG_MIX.test(value)) {\n return true;\n } else if (REG_FN_COLOR.test(value)) {\n opt.nullable = true;\n if (!opt.format) {\n opt.format = VAL_SPEC;\n }\n const resolvedValue = resolveColor(value, opt);\n if (resolvedValue) {\n return true;\n }\n }\n }\n }\n return false;\n};\n\n/**\n * value to JSON string\n * @param value - CSS value\n * @param [func] - stringify function\n * @returns stringified value in JSON notation\n */\nexport const valueToJsonString = (\n value: unknown,\n func: boolean = false\n): string => {\n if (typeof value === 'undefined') {\n return '';\n }\n const res = JSON.stringify(value, (_key, val) => {\n let replacedValue;\n if (typeof val === 'undefined') {\n replacedValue = null;\n } else if (typeof val === 'function') {\n if (func) {\n replacedValue = val.toString().replace(/\\s/g, '').substring(0, HEX);\n } else {\n replacedValue = val.name;\n }\n } else if (val instanceof Map || val instanceof Set) {\n replacedValue = [...val];\n } else if (typeof val === 'bigint') {\n replacedValue = val.toString();\n } else {\n replacedValue = val;\n }\n return replacedValue;\n });\n return res;\n};\n\n/**\n * round to specified precision\n * @param value - numeric value\n * @param bit - minimum bits\n * @returns rounded value\n */\nexport const roundToPrecision = (value: number, bit: number = 0): number => {\n if (!Number.isFinite(value)) {\n throw new TypeError(`${value} is not a finite number.`);\n }\n if (!Number.isFinite(bit)) {\n throw new TypeError(`${bit} is not a finite number.`);\n } else if (bit < 0 || bit > HEX) {\n throw new RangeError(`${bit} is not between 0 and ${HEX}.`);\n }\n if (bit === 0) {\n return Math.round(value);\n }\n let val;\n if (bit === HEX) {\n val = value.toPrecision(6);\n } else if (bit < DEC) {\n val = value.toPrecision(4);\n } else {\n val = value.toPrecision(5);\n }\n return parseFloat(val);\n};\n\n/**\n * interpolate hue\n * @param hueA - hue value\n * @param hueB - hue value\n * @param arc - shorter | longer | increasing | decreasing\n * @returns result - [hueA, hueB]\n */\nexport const interpolateHue = (\n hueA: number,\n hueB: number,\n arc: string = 'shorter'\n): [number, number] => {\n if (!Number.isFinite(hueA)) {\n throw new TypeError(`${hueA} is not a finite number.`);\n }\n if (!Number.isFinite(hueB)) {\n throw new TypeError(`${hueB} is not a finite number.`);\n }\n switch (arc) {\n case 'decreasing': {\n if (hueB > hueA) {\n hueA += DEG;\n }\n break;\n }\n case 'increasing': {\n if (hueB < hueA) {\n hueB += DEG;\n }\n break;\n }\n case 'longer': {\n if (hueB > hueA && hueB < hueA + DEG_HALF) {\n hueA += DEG;\n } else if (hueB > hueA + DEG_HALF * -1 && hueB <= hueA) {\n hueB += DEG;\n }\n break;\n }\n case 'shorter':\n default: {\n if (hueB > hueA + DEG_HALF) {\n hueA += DEG;\n } else if (hueB < hueA + DEG_HALF * -1) {\n hueB += DEG;\n }\n }\n }\n return [hueA, hueB];\n};\n\n/* absolute font size to pixel ratio */\nconst absoluteFontSize = new Map([\n ['xx-small', 9 / 16],\n ['x-small', 5 / 8],\n ['small', 13 / 16],\n ['medium', 1],\n ['large', 9 / 8],\n ['x-large', 3 / 2],\n ['xx-large', 2],\n ['xxx-large', 3]\n]);\n\n/* relative font size to pixel ratio */\nconst relativeFontSize = new Map([\n ['smaller', 1 / 1.2],\n ['larger', 1.2]\n]);\n\n/* absolute length to pixel ratio */\nconst absoluteLength = new Map([\n ['cm', 96 / 2.54],\n ['mm', 96 / 2.54 / 10],\n ['q', 96 / 2.54 / 40],\n ['in', 96],\n ['pc', 96 / 6],\n ['pt', 96 / 72],\n ['px', 1]\n]);\n\n/* relative length to pixel ratio */\nconst relativeLength = new Map([\n ['rcap', 1],\n ['rch', 0.5],\n ['rem', 1],\n ['rex', 0.5],\n ['ric', 1],\n ['rlh', 1.2]\n]);\n\n/**\n * resolve length in pixels\n * @param value - value\n * @param unit - unit\n * @param [opt] - options\n * @returns pixelated value\n */\nexport const resolveLengthInPixels = (\n value: number | string,\n unit: string | undefined,\n opt: Options = {}\n): number => {\n const { dimension = {} } = opt;\n const { callback, em, rem, vh, vw } = dimension as {\n callback: (K: string) => number;\n em: number;\n rem: number;\n vh: number;\n vw: number;\n };\n if (isString(value)) {\n value = value.toLowerCase().trim();\n if (absoluteFontSize.has(value)) {\n return Number(absoluteFontSize.get(value)) * rem;\n } else if (relativeFontSize.has(value)) {\n return Number(relativeFontSize.get(value)) * em;\n }\n return Number.NaN;\n } else if (Number.isFinite(value) && unit) {\n if (Object.hasOwn(dimension, unit)) {\n return value * Number(dimension[unit]);\n } else if (typeof callback === 'function') {\n return value * callback(unit);\n } else if (absoluteLength.has(unit)) {\n return value * Number(absoluteLength.get(unit));\n } else if (relativeLength.has(unit)) {\n return value * Number(relativeLength.get(unit)) * rem;\n } else if (relativeLength.has(`r${unit}`)) {\n return value * Number(relativeLength.get(`r${unit}`)) * em;\n } else {\n switch (unit) {\n case 'vb':\n case 'vi': {\n return value * vw;\n }\n case 'vmax': {\n if (vh > vw) {\n return value * vh;\n }\n return value * vw;\n }\n case 'vmin': {\n if (vh < vw) {\n return value * vh;\n }\n return value * vw;\n }\n default: {\n // unsupported or invalid unit\n return Number.NaN;\n }\n }\n }\n }\n // unsupported or invalid value\n return Number.NaN;\n};\n\n/**\n * is absolute size or length\n * @param value - value\n * @param unit - unit\n * @returns result\n */\nexport const isAbsoluteSizeOrLength = (\n value: number | string,\n unit: string | undefined\n): boolean => {\n if (isString(value)) {\n value = value.toLowerCase().trim();\n return absoluteFontSize.has(value);\n } else if (isString(unit)) {\n unit = unit.toLowerCase().trim();\n return absoluteLength.has(unit);\n }\n return value === 0;\n};\n\n/**\n * is absolute font size\n * @param value - value\n * @returns result\n */\nexport const isAbsoluteFontSize = (value: unknown): boolean => {\n if (isString(value)) {\n const size = value.toLowerCase().trim() as string;\n if (/^[a-z-]+$/.test(size)) {\n return absoluteFontSize.has(size);\n } else {\n const [, val, unit] = /^(\\d+(?:\\.\\d+)?|\\.\\d+)([a-z-]+)?$/.exec(\n size\n ) as RegExpExecArray;\n if (unit) {\n return absoluteLength.has(unit);\n } else if (val) {\n const num = parseFloat(val);\n return num === 0;\n }\n }\n }\n return false;\n};\n"],"mappings":";;;;;;;;;;AAaA,IAAM,EACJ,YAAY,aACZ,OAAO,OACP,SAAS,SACT,OAAO,OACP,KACA,UAAU,MACV,OAAO,OACP,WAAW,YACX,YAAY,YACV;AACJ,IAAM,YAAY;AAGlB,IAAM,MAAM;AACZ,IAAM,MAAM;AACZ,IAAM,MAAM;AACZ,IAAM,WAAW;AAGjB,IAAM,YAAY,IAAI,OAAO,OAAO,eAAe,IAAI;AACvD,IAAM,eACJ;AACF,IAAM,UAAU,IAAI,OAAO,QAAQ;;;;;;;;;AAUnC,IAAa,cAAc,OAAe,MAAe,EAAE,KAAe;AACxE,KAAI,SAAS,MAAM,CACjB,SAAQ,MAAM,MAAM;KAEpB,OAAM,IAAI,UAAU,GAAG,MAAM,mBAAmB;CAElD,MAAM,EAAE,YAAY,KAAK,kBAAkB,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AAO,UAAU,MAAM;UAC7B,OAAO,aAAa,WAC7B,QAAO,QAAQ,SAAS,KAAK;UACpB,eAAe,IAAI,KAAK,CACjC,QAAO,QAAQ,OAAO,eAAe,IAAI,KAAK,CAAC;UACtC,eAAe,IAAI,KAAK,CACjC,QAAO,QAAQ,OAAO,eAAe,IAAI,KAAK,CAAC,GAAG;UACzC,eAAe,IAAI,IAAI,OAAO,CACvC,QAAO,QAAQ,OAAO,eAAe,IAAI,IAAI,OAAO,CAAC,GAAG;KAExD,SAAQ,MAAR;EACE,KAAK;EACL,KAAK,KACH,QAAO,QAAQ;EAEjB,KAAK;AACH,OAAI,KAAK,GACP,QAAO,QAAQ;AAEjB,UAAO,QAAQ;EAEjB,KAAK;AACH,OAAI,KAAK,GACP,QAAO,QAAQ;AAEjB,UAAO,QAAQ;EAEjB,QAEE,QAAO;;AAMf,QAAO;;;;;;;;AAST,IAAa,0BACX,OACA,SACY;AACZ,KAAI,SAAS,MAAM,EAAE;AACnB,UAAQ,MAAM,aAAa,CAAC,MAAM;AAClC,SAAO,iBAAiB,IAAI,MAAM;YACzB,SAAS,KAAK,EAAE;AACzB,SAAO,KAAK,aAAa,CAAC,MAAM;AAChC,SAAO,eAAe,IAAI,KAAK;;AAEjC,QAAO,UAAU;;;;;;;AAQnB,IAAa,sBAAsB,UAA4B;AAC7D,KAAI,SAAS,MAAM,EAAE;EACnB,MAAM,OAAO,MAAM,aAAa,CAAC,MAAM;AACvC,MAAI,YAAY,KAAK,KAAK,CACxB,QAAO,iBAAiB,IAAI,KAAK;OAC5B;GACL,MAAM,GAAG,KAAK,QAAQ,oCAAoC,KACxD,KACD;AACD,OAAI,KACF,QAAO,eAAe,IAAI,KAAK;YACtB,IAET,QADY,WAAW,IAAI,KACZ;;;AAIrB,QAAO"} \ No newline at end of file diff --git a/node_modules/@asamuzakjp/css-color/package.json b/node_modules/@asamuzakjp/css-color/package.json new file mode 100644 index 00000000..b4bd091e --- /dev/null +++ b/node_modules/@asamuzakjp/css-color/package.json @@ -0,0 +1,83 @@ +{ + "name": "@asamuzakjp/css-color", + "description": "CSS color - Resolve and convert CSS colors.", + "author": "asamuzaK", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/asamuzaK/cssColor.git" + }, + "homepage": "https://github.com/asamuzaK/cssColor#readme", + "bugs": { + "url": "https://github.com/asamuzaK/cssColor/issues" + }, + "files": [ + "dist", + "src" + ], + "type": "module", + "exports": { + ".": { + "types": "./dist/esm/index.d.ts", + "default": "./dist/esm/index.js" + }, + "./package.json": "./package.json" + }, + "dependencies": { + "@csstools/css-calc": "^3.1.1", + "@csstools/css-color-parser": "^4.0.2", + "@csstools/css-parser-algorithms": "^4.0.0", + "@csstools/css-tokenizer": "^4.0.0", + "lru-cache": "^11.2.7" + }, + "devDependencies": { + "@tanstack/vite-config": "^0.5.2", + "@vitest/coverage-istanbul": "^4.1.2", + "esbuild": "^0.27.4", + "eslint": "^9.39.4", + "eslint-plugin-regexp": "^3.1.0", + "globals": "^17.4.0", + "knip": "^6.1.0", + "neostandard": "^0.13.0", + "prettier": "^3.8.1", + "publint": "^0.3.18", + "rimraf": "^6.1.3", + "typescript": "^5.9.3", + "vite": "^8.0.3", + "vitest": "^4.1.2" + }, + "packageManager": "pnpm@10.33.0", + "pnpm": { + "onlyBuiltDependencies": [ + "esbuild", + "oxc-resolver", + "unrs-resolver" + ], + "overrides": { + "ajv": "^8.18.0", + "@eslint/eslintrc>ajv": "^6.14.0", + "eslint>ajv": "^6.14.0", + "brace-expansion": "^5.0.4", + "minimatch": "^3.1.5", + "@typescript-eslint/typescript-estree>minimatch": "^9.0.9", + "@vue/language-core>minimatch": "^9.0.9", + "eslint-plugin-import-x>minimatch": "^10.2.4", + "glob>minimatch": "^10.2.4" + } + }, + "scripts": { + "build": "pnpm run clean && pnpm run test && pnpm run knip && vite build && pnpm run publint", + "clean": "rimraf ./coverage ./dist", + "knip": "knip", + "prettier": "prettier . --ignore-unknown --write", + "publint": "publint --strict", + "test": "pnpm run prettier && pnpm run --stream \"/^test:.*/\"", + "test:eslint": "eslint ./src ./test --fix", + "test:types": "tsc", + "test:unit": "vitest" + }, + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + }, + "version": "5.1.1" +} diff --git a/node_modules/@asamuzakjp/css-color/src/index.ts b/node_modules/@asamuzakjp/css-color/src/index.ts new file mode 100644 index 00000000..ff2ab2d7 --- /dev/null +++ b/node_modules/@asamuzakjp/css-color/src/index.ts @@ -0,0 +1,34 @@ +/*! + * CSS color - Resolve, parse, convert CSS color. + * @license MIT + * @copyright asamuzaK (Kazz) + * @see {@link https://github.com/asamuzaK/cssColor/blob/main/LICENSE} + */ + +import { cssCalc } from './js/css-calc'; +import { isGradient, resolveGradient } from './js/css-gradient'; +import { cssVar } from './js/css-var'; +import { + extractDashedIdent, + isAbsoluteFontSize, + isAbsoluteSizeOrLength, + isColor, + resolveLengthInPixels, + splitValue +} from './js/util'; + +export { convert } from './js/convert'; +export { resolve } from './js/resolve'; +/* utils */ +export const utils = { + cssCalc, + cssVar, + extractDashedIdent, + isAbsoluteFontSize, + isAbsoluteSizeOrLength, + isColor, + isGradient, + resolveGradient, + resolveLengthInPixels, + splitValue +}; diff --git a/node_modules/@asamuzakjp/css-color/src/js/cache.ts b/node_modules/@asamuzakjp/css-color/src/js/cache.ts new file mode 100644 index 00000000..86421139 --- /dev/null +++ b/node_modules/@asamuzakjp/css-color/src/js/cache.ts @@ -0,0 +1,114 @@ +/** + * cache + */ + +import { LRUCache } from 'lru-cache'; +import { Options } from './typedef'; +import { valueToJsonString } from './util'; + +/* numeric constants */ +const MAX_CACHE = 4096; + +/** + * CacheItem + */ +export class CacheItem { + /* private */ + #isNull: boolean; + #item: unknown; + + /** + * constructor + */ + constructor(item: unknown, isNull: boolean = false) { + this.#item = item; + this.#isNull = !!isNull; + } + + get item() { + return this.#item; + } + + get isNull() { + return this.#isNull; + } +} + +/** + * NullObject + */ +export class NullObject extends CacheItem { + /** + * constructor + */ + constructor() { + super(Symbol('null'), true); + } +} + +/* + * lru cache + */ +export const lruCache = new LRUCache({ + max: MAX_CACHE +}); + +/** + * set cache + * @param key - cache key + * @param value - value to cache + * @returns void + */ +export const setCache = (key: string, value: unknown): void => { + if (key) { + if (value === null) { + lruCache.set(key, new NullObject()); + } else if (value instanceof CacheItem) { + lruCache.set(key, value); + } else { + lruCache.set(key, new CacheItem(value)); + } + } +}; + +/** + * get cache + * @param key - cache key + * @returns cached item or false otherwise + */ +export const getCache = (key: string): CacheItem | boolean => { + if (key && lruCache.has(key)) { + const item = lruCache.get(key); + if (item instanceof CacheItem) { + return item; + } + // delete unexpected cached item + lruCache.delete(key); + return false; + } + return false; +}; + +/** + * create cache key + * @param keyData - key data + * @param [opt] - options + * @returns cache key + */ +export const createCacheKey = ( + keyData: Record, + opt: Options = {} +): string => { + const { customProperty = {}, dimension = {} } = opt; + let cacheKey = ''; + if ( + keyData && + Object.keys(keyData).length && + typeof customProperty.callback !== 'function' && + typeof dimension.callback !== 'function' + ) { + keyData.opt = valueToJsonString(opt); + cacheKey = valueToJsonString(keyData); + } + return cacheKey; +}; diff --git a/node_modules/@asamuzakjp/css-color/src/js/color.ts b/node_modules/@asamuzakjp/css-color/src/js/color.ts new file mode 100644 index 00000000..2fe737dd --- /dev/null +++ b/node_modules/@asamuzakjp/css-color/src/js/color.ts @@ -0,0 +1,3511 @@ +/** + * color + * + * Ref: CSS Color Module Level 4 + * Sample code for Color Conversions + * https://w3c.github.io/csswg-drafts/css-color-4/#color-conversion-code + */ + +import { + CacheItem, + NullObject, + createCacheKey, + getCache, + setCache +} from './cache'; +import { isString } from './common'; +import { resolveColor } from './resolve'; +import { interpolateHue, roundToPrecision, splitValue } from './util'; +import { + ColorChannels, + ComputedColorChannels, + Options, + MatchedRegExp, + SpecifiedColorChannels, + StringColorChannels, + StringColorSpacedChannels +} from './typedef'; + +/* constants */ +import { + ANGLE, + CS_HUE_CAPT, + CS_MIX, + CS_RGB, + CS_XYZ, + FN_COLOR, + FN_LIGHT_DARK, + FN_MIX, + NONE, + NUM, + PCT, + SYN_COLOR_TYPE, + SYN_FN_COLOR, + SYN_HSL, + SYN_HSL_LV3, + SYN_LCH, + SYN_MIX, + SYN_MIX_CAPT, + SYN_MIX_PART, + SYN_MOD, + SYN_RGB_LV3, + VAL_COMP, + VAL_MIX, + VAL_SPEC +} from './constant'; +const NAMESPACE = 'color'; + +/* numeric constants */ +const PPTH = 0.001; +const HALF = 0.5; +const DUO = 2; +const TRIA = 3; +const QUAD = 4; +const OCT = 8; +const DEC = 10; +const DOZ = 12; +const HEX = 16; +const SEXA = 60; +const DEG_HALF = 180; +const DEG = 360; +const MAX_PCT = 100; +const MAX_RGB = 255; +const POW_SQR = 2; +const POW_CUBE = 3; +const POW_LINEAR = 2.4; +const LINEAR_COEF = 12.92; +const LINEAR_OFFSET = 0.055; +const LAB_L = 116; +const LAB_A = 500; +const LAB_B = 200; +const LAB_EPSILON = 216 / 24389; +const LAB_KAPPA = 24389 / 27; + +/* type definitions */ +/** + * @type NumStrColorChannels - string or numeric color channels + */ +type NumStrColorChannels = [ + x: number | string, + y: number | string, + z: number | string, + alpha: number | string +]; + +/** + * @type TriColorChannels - color channels without alpha + */ +type TriColorChannels = [x: number, y: number, z: number]; + +/** + * @type ColorMatrix - color matrix + */ +type ColorMatrix = [ + r1: TriColorChannels, + r2: TriColorChannels, + r3: TriColorChannels +]; + +/* white point */ +const D50: TriColorChannels = [ + 0.3457 / 0.3585, + 1.0, + (1.0 - 0.3457 - 0.3585) / 0.3585 +]; +const MATRIX_D50_TO_D65: ColorMatrix = [ + [0.955473421488075, -0.02309845494876471, 0.06325924320057072], + [-0.0283697093338637, 1.0099953980813041, 0.021041441191917323], + [0.012314014864481998, -0.020507649298898964, 1.330365926242124] +]; +const MATRIX_D65_TO_D50: ColorMatrix = [ + [1.0479297925449969, 0.022946870601609652, -0.05019226628920524], + [0.02962780877005599, 0.9904344267538799, -0.017073799063418826], + [-0.009243040646204504, 0.015055191490298152, 0.7518742814281371] +]; + +/* color space */ +const MATRIX_L_RGB_TO_XYZ: ColorMatrix = [ + [506752 / 1228815, 87881 / 245763, 12673 / 70218], + [87098 / 409605, 175762 / 245763, 12673 / 175545], + [7918 / 409605, 87881 / 737289, 1001167 / 1053270] +]; +const MATRIX_XYZ_TO_L_RGB: ColorMatrix = [ + [12831 / 3959, -329 / 214, -1974 / 3959], + [-851781 / 878810, 1648619 / 878810, 36519 / 878810], + [705 / 12673, -2585 / 12673, 705 / 667] +]; +const MATRIX_XYZ_TO_LMS: ColorMatrix = [ + [0.819022437996703, 0.3619062600528904, -0.1288737815209879], + [0.0329836539323885, 0.9292868615863434, 0.0361446663506424], + [0.0481771893596242, 0.2642395317527308, 0.6335478284694309] +]; +const MATRIX_LMS_TO_XYZ: ColorMatrix = [ + [1.2268798758459243, -0.5578149944602171, 0.2813910456659647], + [-0.0405757452148008, 1.112286803280317, -0.0717110580655164], + [-0.0763729366746601, -0.4214933324022432, 1.5869240198367816] +]; +const MATRIX_OKLAB_TO_LMS: ColorMatrix = [ + [1.0, 0.3963377773761749, 0.2158037573099136], + [1.0, -0.1055613458156586, -0.0638541728258133], + [1.0, -0.0894841775298119, -1.2914855480194092] +]; +const MATRIX_LMS_TO_OKLAB: ColorMatrix = [ + [0.210454268309314, 0.7936177747023054, -0.0040720430116193], + [1.9779985324311684, -2.4285922420485799, 0.450593709617411], + [0.0259040424655478, 0.7827717124575296, -0.8086757549230774] +]; +const MATRIX_P3_TO_XYZ: ColorMatrix = [ + [608311 / 1250200, 189793 / 714400, 198249 / 1000160], + [35783 / 156275, 247089 / 357200, 198249 / 2500400], + [0 / 1, 32229 / 714400, 5220557 / 5000800] +]; +const MATRIX_REC2020_TO_XYZ: ColorMatrix = [ + [63426534 / 99577255, 20160776 / 139408157, 47086771 / 278816314], + [26158966 / 99577255, 472592308 / 697040785, 8267143 / 139408157], + [0 / 1, 19567812 / 697040785, 295819943 / 278816314] +]; +const MATRIX_A98_TO_XYZ: ColorMatrix = [ + [573536 / 994567, 263643 / 1420810, 187206 / 994567], + [591459 / 1989134, 6239551 / 9945670, 374412 / 4972835], + [53769 / 1989134, 351524 / 4972835, 4929758 / 4972835] +]; +const MATRIX_PROPHOTO_TO_XYZ_D50: ColorMatrix = [ + [0.7977666449006423, 0.13518129740053308, 0.0313477341283922], + [0.2880748288194013, 0.711835234241873, 0.00008993693872564], + [0.0, 0.0, 0.8251046025104602] +]; + +/* regexp */ +const REG_COLOR = new RegExp(`^(?:${SYN_COLOR_TYPE})$`); +const REG_CS_HUE = new RegExp(`^${CS_HUE_CAPT}$`); +const REG_CS_XYZ = /^xyz(?:-d(?:50|65))?$/; +const REG_CURRENT = /^currentColor$/i; +const REG_FN_COLOR = new RegExp(`^color\\(\\s*(${SYN_FN_COLOR})\\s*\\)$`); +const REG_HSL = new RegExp(`^hsla?\\(\\s*(${SYN_HSL}|${SYN_HSL_LV3})\\s*\\)$`); +const REG_HWB = new RegExp(`^hwb\\(\\s*(${SYN_HSL})\\s*\\)$`); +const REG_LAB = new RegExp(`^lab\\(\\s*(${SYN_MOD})\\s*\\)$`); +const REG_LCH = new RegExp(`^lch\\(\\s*(${SYN_LCH})\\s*\\)$`); +const REG_MIX = new RegExp(`^${SYN_MIX}$`); +const REG_MIX_CAPT = new RegExp(`^${SYN_MIX_CAPT}$`); +const REG_MIX_NEST = new RegExp(`${SYN_MIX}`, 'g'); +const REG_OKLAB = new RegExp(`^oklab\\(\\s*(${SYN_MOD})\\s*\\)$`); +const REG_OKLCH = new RegExp(`^oklch\\(\\s*(${SYN_LCH})\\s*\\)$`); +const REG_SPEC = /^(?:specifi|comput)edValue$/; + +/** + * named colors + */ +export const NAMED_COLORS = { + aliceblue: [0xf0, 0xf8, 0xff], + antiquewhite: [0xfa, 0xeb, 0xd7], + aqua: [0x00, 0xff, 0xff], + aquamarine: [0x7f, 0xff, 0xd4], + azure: [0xf0, 0xff, 0xff], + beige: [0xf5, 0xf5, 0xdc], + bisque: [0xff, 0xe4, 0xc4], + black: [0x00, 0x00, 0x00], + blanchedalmond: [0xff, 0xeb, 0xcd], + blue: [0x00, 0x00, 0xff], + blueviolet: [0x8a, 0x2b, 0xe2], + brown: [0xa5, 0x2a, 0x2a], + burlywood: [0xde, 0xb8, 0x87], + cadetblue: [0x5f, 0x9e, 0xa0], + chartreuse: [0x7f, 0xff, 0x00], + chocolate: [0xd2, 0x69, 0x1e], + coral: [0xff, 0x7f, 0x50], + cornflowerblue: [0x64, 0x95, 0xed], + cornsilk: [0xff, 0xf8, 0xdc], + crimson: [0xdc, 0x14, 0x3c], + cyan: [0x00, 0xff, 0xff], + darkblue: [0x00, 0x00, 0x8b], + darkcyan: [0x00, 0x8b, 0x8b], + darkgoldenrod: [0xb8, 0x86, 0x0b], + darkgray: [0xa9, 0xa9, 0xa9], + darkgreen: [0x00, 0x64, 0x00], + darkgrey: [0xa9, 0xa9, 0xa9], + darkkhaki: [0xbd, 0xb7, 0x6b], + darkmagenta: [0x8b, 0x00, 0x8b], + darkolivegreen: [0x55, 0x6b, 0x2f], + darkorange: [0xff, 0x8c, 0x00], + darkorchid: [0x99, 0x32, 0xcc], + darkred: [0x8b, 0x00, 0x00], + darksalmon: [0xe9, 0x96, 0x7a], + darkseagreen: [0x8f, 0xbc, 0x8f], + darkslateblue: [0x48, 0x3d, 0x8b], + darkslategray: [0x2f, 0x4f, 0x4f], + darkslategrey: [0x2f, 0x4f, 0x4f], + darkturquoise: [0x00, 0xce, 0xd1], + darkviolet: [0x94, 0x00, 0xd3], + deeppink: [0xff, 0x14, 0x93], + deepskyblue: [0x00, 0xbf, 0xff], + dimgray: [0x69, 0x69, 0x69], + dimgrey: [0x69, 0x69, 0x69], + dodgerblue: [0x1e, 0x90, 0xff], + firebrick: [0xb2, 0x22, 0x22], + floralwhite: [0xff, 0xfa, 0xf0], + forestgreen: [0x22, 0x8b, 0x22], + fuchsia: [0xff, 0x00, 0xff], + gainsboro: [0xdc, 0xdc, 0xdc], + ghostwhite: [0xf8, 0xf8, 0xff], + gold: [0xff, 0xd7, 0x00], + goldenrod: [0xda, 0xa5, 0x20], + gray: [0x80, 0x80, 0x80], + green: [0x00, 0x80, 0x00], + greenyellow: [0xad, 0xff, 0x2f], + grey: [0x80, 0x80, 0x80], + honeydew: [0xf0, 0xff, 0xf0], + hotpink: [0xff, 0x69, 0xb4], + indianred: [0xcd, 0x5c, 0x5c], + indigo: [0x4b, 0x00, 0x82], + ivory: [0xff, 0xff, 0xf0], + khaki: [0xf0, 0xe6, 0x8c], + lavender: [0xe6, 0xe6, 0xfa], + lavenderblush: [0xff, 0xf0, 0xf5], + lawngreen: [0x7c, 0xfc, 0x00], + lemonchiffon: [0xff, 0xfa, 0xcd], + lightblue: [0xad, 0xd8, 0xe6], + lightcoral: [0xf0, 0x80, 0x80], + lightcyan: [0xe0, 0xff, 0xff], + lightgoldenrodyellow: [0xfa, 0xfa, 0xd2], + lightgray: [0xd3, 0xd3, 0xd3], + lightgreen: [0x90, 0xee, 0x90], + lightgrey: [0xd3, 0xd3, 0xd3], + lightpink: [0xff, 0xb6, 0xc1], + lightsalmon: [0xff, 0xa0, 0x7a], + lightseagreen: [0x20, 0xb2, 0xaa], + lightskyblue: [0x87, 0xce, 0xfa], + lightslategray: [0x77, 0x88, 0x99], + lightslategrey: [0x77, 0x88, 0x99], + lightsteelblue: [0xb0, 0xc4, 0xde], + lightyellow: [0xff, 0xff, 0xe0], + lime: [0x00, 0xff, 0x00], + limegreen: [0x32, 0xcd, 0x32], + linen: [0xfa, 0xf0, 0xe6], + magenta: [0xff, 0x00, 0xff], + maroon: [0x80, 0x00, 0x00], + mediumaquamarine: [0x66, 0xcd, 0xaa], + mediumblue: [0x00, 0x00, 0xcd], + mediumorchid: [0xba, 0x55, 0xd3], + mediumpurple: [0x93, 0x70, 0xdb], + mediumseagreen: [0x3c, 0xb3, 0x71], + mediumslateblue: [0x7b, 0x68, 0xee], + mediumspringgreen: [0x00, 0xfa, 0x9a], + mediumturquoise: [0x48, 0xd1, 0xcc], + mediumvioletred: [0xc7, 0x15, 0x85], + midnightblue: [0x19, 0x19, 0x70], + mintcream: [0xf5, 0xff, 0xfa], + mistyrose: [0xff, 0xe4, 0xe1], + moccasin: [0xff, 0xe4, 0xb5], + navajowhite: [0xff, 0xde, 0xad], + navy: [0x00, 0x00, 0x80], + oldlace: [0xfd, 0xf5, 0xe6], + olive: [0x80, 0x80, 0x00], + olivedrab: [0x6b, 0x8e, 0x23], + orange: [0xff, 0xa5, 0x00], + orangered: [0xff, 0x45, 0x00], + orchid: [0xda, 0x70, 0xd6], + palegoldenrod: [0xee, 0xe8, 0xaa], + palegreen: [0x98, 0xfb, 0x98], + paleturquoise: [0xaf, 0xee, 0xee], + palevioletred: [0xdb, 0x70, 0x93], + papayawhip: [0xff, 0xef, 0xd5], + peachpuff: [0xff, 0xda, 0xb9], + peru: [0xcd, 0x85, 0x3f], + pink: [0xff, 0xc0, 0xcb], + plum: [0xdd, 0xa0, 0xdd], + powderblue: [0xb0, 0xe0, 0xe6], + purple: [0x80, 0x00, 0x80], + rebeccapurple: [0x66, 0x33, 0x99], + red: [0xff, 0x00, 0x00], + rosybrown: [0xbc, 0x8f, 0x8f], + royalblue: [0x41, 0x69, 0xe1], + saddlebrown: [0x8b, 0x45, 0x13], + salmon: [0xfa, 0x80, 0x72], + sandybrown: [0xf4, 0xa4, 0x60], + seagreen: [0x2e, 0x8b, 0x57], + seashell: [0xff, 0xf5, 0xee], + sienna: [0xa0, 0x52, 0x2d], + silver: [0xc0, 0xc0, 0xc0], + skyblue: [0x87, 0xce, 0xeb], + slateblue: [0x6a, 0x5a, 0xcd], + slategray: [0x70, 0x80, 0x90], + slategrey: [0x70, 0x80, 0x90], + snow: [0xff, 0xfa, 0xfa], + springgreen: [0x00, 0xff, 0x7f], + steelblue: [0x46, 0x82, 0xb4], + tan: [0xd2, 0xb4, 0x8c], + teal: [0x00, 0x80, 0x80], + thistle: [0xd8, 0xbf, 0xd8], + tomato: [0xff, 0x63, 0x47], + turquoise: [0x40, 0xe0, 0xd0], + violet: [0xee, 0x82, 0xee], + wheat: [0xf5, 0xde, 0xb3], + white: [0xff, 0xff, 0xff], + whitesmoke: [0xf5, 0xf5, 0xf5], + yellow: [0xff, 0xff, 0x00], + yellowgreen: [0x9a, 0xcd, 0x32] +} as const satisfies { + [key: string]: TriColorChannels; +}; + +/** + * cache invalid color value + * @param key - cache key + * @param nullable - is nullable + * @returns cached value + */ +export const cacheInvalidColorValue = ( + cacheKey: string, + format: string, + nullable: boolean = false +): SpecifiedColorChannels | string | NullObject => { + if (format === VAL_SPEC) { + const res = ''; + setCache(cacheKey, res); + return res; + } + if (nullable) { + setCache(cacheKey, null); + return new NullObject(); + } + const res: SpecifiedColorChannels = ['rgb', 0, 0, 0, 0]; + setCache(cacheKey, res); + return res; +}; + +/** + * resolve invalid color value + * @param format - output format + * @param nullable - is nullable + * @returns resolved value + */ +export const resolveInvalidColorValue = ( + format: string, + nullable: boolean = false +): SpecifiedColorChannels | string | NullObject => { + switch (format) { + case 'hsl': + case 'hwb': + case VAL_MIX: { + return new NullObject(); + } + case VAL_SPEC: { + return ''; + } + default: { + if (nullable) { + return new NullObject(); + } + return ['rgb', 0, 0, 0, 0] as SpecifiedColorChannels; + } + } +}; + +/** + * validate color components + * @param arr - color components + * @param [opt] - options + * @param [opt.alpha] - alpha channel + * @param [opt.minLength] - min length + * @param [opt.maxLength] - max length + * @param [opt.minRange] - min range + * @param [opt.maxRange] - max range + * @param [opt.validateRange] - validate range + * @returns result - validated color components + */ +export const validateColorComponents = ( + arr: ColorChannels | TriColorChannels, + opt: { + alpha?: boolean; + minLength?: number; + maxLength?: number; + minRange?: number; + maxRange?: number; + validateRange?: boolean; + } = {} +): ColorChannels | TriColorChannels => { + if (!Array.isArray(arr)) { + throw new TypeError(`${arr} is not an array.`); + } + const { + alpha = false, + minLength = TRIA, + maxLength = QUAD, + minRange = 0, + maxRange = 1, + validateRange = true + } = opt; + if (!Number.isFinite(minLength)) { + throw new TypeError(`${minLength} is not a number.`); + } + if (!Number.isFinite(maxLength)) { + throw new TypeError(`${maxLength} is not a number.`); + } + if (!Number.isFinite(minRange)) { + throw new TypeError(`${minRange} is not a number.`); + } + if (!Number.isFinite(maxRange)) { + throw new TypeError(`${maxRange} is not a number.`); + } + const l = arr.length; + if (l < minLength || l > maxLength) { + throw new Error(`Unexpected array length ${l}.`); + } + let i = 0; + while (i < l) { + const v = arr[i] as number; + if (!Number.isFinite(v)) { + throw new TypeError(`${v} is not a number.`); + } else if (i < TRIA && validateRange && (v < minRange || v > maxRange)) { + throw new RangeError(`${v} is not between ${minRange} and ${maxRange}.`); + } else if (i === TRIA && (v < 0 || v > 1)) { + throw new RangeError(`${v} is not between 0 and 1.`); + } + i++; + } + if (alpha && l === TRIA) { + arr.push(1); + } + return arr; +}; + +/** + * transform matrix + * @param mtx - 3 * 3 matrix + * @param vct - vector + * @param [skip] - skip validate + * @returns TriColorChannels - [p1, p2, p3] + */ +export const transformMatrix = ( + mtx: ColorMatrix, + vct: TriColorChannels, + skip: boolean = false +): TriColorChannels => { + if (!Array.isArray(mtx)) { + throw new TypeError(`${mtx} is not an array.`); + } else if (mtx.length !== TRIA) { + throw new Error(`Unexpected array length ${mtx.length}.`); + } else if (!skip) { + for (let i of mtx) { + i = validateColorComponents(i as TriColorChannels, { + maxLength: TRIA, + validateRange: false + }) as TriColorChannels; + } + } + const [[r1c1, r1c2, r1c3], [r2c1, r2c2, r2c3], [r3c1, r3c2, r3c3]] = mtx; + let v1, v2, v3; + if (skip) { + [v1, v2, v3] = vct; + } else { + [v1, v2, v3] = validateColorComponents(vct, { + maxLength: TRIA, + validateRange: false + }); + } + const p1 = r1c1 * v1 + r1c2 * v2 + r1c3 * v3; + const p2 = r2c1 * v1 + r2c2 * v2 + r2c3 * v3; + const p3 = r3c1 * v1 + r3c2 * v2 + r3c3 * v3; + return [p1, p2, p3]; +}; + +/** + * normalize color components + * @param colorA - color components [v1, v2, v3, v4] + * @param colorB - color components [v1, v2, v3, v4] + * @param [skip] - skip validate + * @returns result - [colorA, colorB] + */ +export const normalizeColorComponents = ( + colorA: [number | string, number | string, number | string, number | string], + colorB: [number | string, number | string, number | string, number | string], + skip: boolean = false +): [ColorChannels, ColorChannels] => { + if (!Array.isArray(colorA)) { + throw new TypeError(`${colorA} is not an array.`); + } else if (colorA.length !== QUAD) { + throw new Error(`Unexpected array length ${colorA.length}.`); + } + if (!Array.isArray(colorB)) { + throw new TypeError(`${colorB} is not an array.`); + } else if (colorB.length !== QUAD) { + throw new Error(`Unexpected array length ${colorB.length}.`); + } + let i = 0; + while (i < QUAD) { + if (colorA[i] === NONE && colorB[i] === NONE) { + colorA[i] = 0; + colorB[i] = 0; + } else if (colorA[i] === NONE) { + colorA[i] = colorB[i] as number; + } else if (colorB[i] === NONE) { + colorB[i] = colorA[i] as number; + } + i++; + } + if (skip) { + return [colorA as ColorChannels, colorB as ColorChannels]; + } + const validatedColorA = validateColorComponents(colorA as ColorChannels, { + minLength: QUAD, + validateRange: false + }); + const validatedColorB = validateColorComponents(colorB as ColorChannels, { + minLength: QUAD, + validateRange: false + }); + return [validatedColorA as ColorChannels, validatedColorB as ColorChannels]; +}; + +/** + * number to hex string + * @param value - numeric value + * @returns hex string + */ +export const numberToHexString = (value: number): string => { + if (!Number.isFinite(value)) { + throw new TypeError(`${value} is not a number.`); + } else { + value = Math.round(value); + if (value < 0 || value > MAX_RGB) { + throw new RangeError(`${value} is not between 0 and ${MAX_RGB}.`); + } + } + let hex = value.toString(HEX); + if (hex.length === 1) { + hex = `0${hex}`; + } + return hex; +}; + +/** + * angle to deg + * @param angle + * @returns deg: 0..360 + */ +export const angleToDeg = (angle: string): number => { + if (isString(angle)) { + angle = angle.trim(); + } else { + throw new TypeError(`${angle} is not a string.`); + } + const GRAD = DEG / 400; + const RAD = DEG / (Math.PI * DUO); + const reg = new RegExp(`^(${NUM})(${ANGLE})?$`); + if (!reg.test(angle)) { + throw new SyntaxError(`Invalid property value: ${angle}`); + } + const [, value, unit] = angle.match(reg) as MatchedRegExp; + let deg; + switch (unit) { + case 'grad': + deg = parseFloat(value) * GRAD; + break; + case 'rad': + deg = parseFloat(value) * RAD; + break; + case 'turn': + deg = parseFloat(value) * DEG; + break; + default: + deg = parseFloat(value); + } + deg %= DEG; + if (deg < 0) { + deg += DEG; + } else if (Object.is(deg, -0)) { + deg = 0; + } + return deg; +}; + +/** + * parse alpha + * @param [alpha] - alpha value + * @returns alpha: 0..1 + */ +export const parseAlpha = (alpha: string = ''): number => { + if (isString(alpha)) { + alpha = alpha.trim(); + if (!alpha) { + alpha = '1'; + } else if (alpha === NONE) { + alpha = '0'; + } else { + let a; + if (alpha.endsWith('%')) { + a = parseFloat(alpha) / MAX_PCT; + } else { + a = parseFloat(alpha); + } + if (!Number.isFinite(a)) { + throw new TypeError(`${a} is not a finite number.`); + } + if (a < PPTH) { + alpha = '0'; + } else if (a > 1) { + alpha = '1'; + } else { + alpha = a.toFixed(TRIA); + } + } + } else { + alpha = '1'; + } + return parseFloat(alpha); +}; + +/** + * parse hex alpha + * @param value - alpha value in hex string + * @returns alpha: 0..1 + */ +export const parseHexAlpha = (value: string): number => { + if (isString(value)) { + if (value === '') { + throw new SyntaxError('Invalid property value: (empty string)'); + } + value = value.trim(); + } else { + throw new TypeError(`${value} is not a string.`); + } + let alpha = parseInt(value, HEX); + if (alpha <= 0) { + return 0; + } + if (alpha >= MAX_RGB) { + return 1; + } + const alphaMap = new Map(); + for (let i = 1; i < MAX_PCT; i++) { + alphaMap.set(Math.round((i * MAX_RGB) / MAX_PCT), i); + } + if (alphaMap.has(alpha)) { + alpha = alphaMap.get(alpha) / MAX_PCT; + } else { + alpha = Math.round(alpha / MAX_RGB / PPTH) * PPTH; + } + return parseFloat(alpha.toFixed(TRIA)); +}; + +/** + * transform rgb to linear rgb + * @param rgb - [r, g, b] r|g|b: 0..255 + * @param [skip] - skip validate + * @returns TriColorChannels - [r, g, b] r|g|b: 0..1 + */ +export const transformRgbToLinearRgb = ( + rgb: TriColorChannels, + skip: boolean = false +): TriColorChannels => { + let rr, gg, bb; + if (skip) { + [rr, gg, bb] = rgb; + } else { + [rr, gg, bb] = validateColorComponents(rgb, { + maxLength: TRIA, + maxRange: MAX_RGB + }); + } + let r = rr / MAX_RGB; + let g = gg / MAX_RGB; + let b = bb / MAX_RGB; + const COND_POW = 0.04045; + if (r > COND_POW) { + r = Math.pow((r + LINEAR_OFFSET) / (1 + LINEAR_OFFSET), POW_LINEAR); + } else { + r /= LINEAR_COEF; + } + if (g > COND_POW) { + g = Math.pow((g + LINEAR_OFFSET) / (1 + LINEAR_OFFSET), POW_LINEAR); + } else { + g /= LINEAR_COEF; + } + if (b > COND_POW) { + b = Math.pow((b + LINEAR_OFFSET) / (1 + LINEAR_OFFSET), POW_LINEAR); + } else { + b /= LINEAR_COEF; + } + return [r, g, b]; +}; + +/** + * transform rgb to xyz + * @param rgb - [r, g, b] r|g|b: 0..255 + * @param [skip] - skip validate + * @returns TriColorChannels - [x, y, z] + */ +export const transformRgbToXyz = ( + rgb: TriColorChannels, + skip: boolean = false +): TriColorChannels => { + if (!skip) { + rgb = validateColorComponents(rgb, { + maxLength: TRIA, + maxRange: MAX_RGB + }) as TriColorChannels; + } + rgb = transformRgbToLinearRgb(rgb, true); + const xyz = transformMatrix(MATRIX_L_RGB_TO_XYZ, rgb, true); + return xyz; +}; + +/** + * transform rgb to xyz-d50 + * @param rgb - [r, g, b] r|g|b: 0..255 alpha: 0..1 + * @returns TriColorChannels - [x, y, z] + */ +export const transformRgbToXyzD50 = ( + rgb: TriColorChannels +): TriColorChannels => { + let xyz = transformRgbToXyz(rgb); + xyz = transformMatrix(MATRIX_D65_TO_D50, xyz, true); + return xyz; +}; + +/** + * transform linear rgb to rgb + * @param rgb - [r, g, b] r|g|b: 0..1 + * @param [round] - round result + * @returns TriColorChannels - [r, g, b] r|g|b: 0..255 + */ +export const transformLinearRgbToRgb = ( + rgb: TriColorChannels, + round: boolean = false +): TriColorChannels => { + let [r, g, b] = validateColorComponents(rgb, { + maxLength: TRIA + }); + const COND_POW = 809 / 258400; + if (r > COND_POW) { + r = Math.pow(r, 1 / POW_LINEAR) * (1 + LINEAR_OFFSET) - LINEAR_OFFSET; + } else { + r *= LINEAR_COEF; + } + r *= MAX_RGB; + if (g > COND_POW) { + g = Math.pow(g, 1 / POW_LINEAR) * (1 + LINEAR_OFFSET) - LINEAR_OFFSET; + } else { + g *= LINEAR_COEF; + } + g *= MAX_RGB; + if (b > COND_POW) { + b = Math.pow(b, 1 / POW_LINEAR) * (1 + LINEAR_OFFSET) - LINEAR_OFFSET; + } else { + b *= LINEAR_COEF; + } + b *= MAX_RGB; + return [ + round ? Math.round(r) : r, + round ? Math.round(g) : g, + round ? Math.round(b) : b + ]; +}; + +/** + * transform xyz to rgb + * @param xyz - [x, y, z] + * @param [skip] - skip validate + * @returns TriColorChannels - [r, g, b] r|g|b: 0..255 + */ +export const transformXyzToRgb = ( + xyz: TriColorChannels, + skip: boolean = false +): TriColorChannels => { + if (!skip) { + xyz = validateColorComponents(xyz, { + maxLength: TRIA, + validateRange: false + }) as TriColorChannels; + } + let [r, g, b] = transformMatrix(MATRIX_XYZ_TO_L_RGB, xyz, true); + [r, g, b] = transformLinearRgbToRgb( + [ + Math.min(Math.max(r, 0), 1), + Math.min(Math.max(g, 0), 1), + Math.min(Math.max(b, 0), 1) + ], + true + ); + return [r, g, b]; +}; + +/** + * transform xyz to xyz-d50 + * @param xyz - [x, y, z] + * @returns TriColorChannels - [x, y, z] + */ +export const transformXyzToXyzD50 = ( + xyz: TriColorChannels +): TriColorChannels => { + xyz = validateColorComponents(xyz, { + maxLength: TRIA, + validateRange: false + }) as TriColorChannels; + xyz = transformMatrix(MATRIX_D65_TO_D50, xyz, true); + return xyz; +}; + +/** + * transform xyz to hsl + * @param xyz - [x, y, z] + * @param [skip] - skip validate + * @returns TriColorChannels - [h, s, l] + */ +export const transformXyzToHsl = ( + xyz: TriColorChannels, + skip: boolean = false +): TriColorChannels => { + const [rr, gg, bb] = transformXyzToRgb(xyz, skip); + const r = rr / MAX_RGB; + const g = gg / MAX_RGB; + const b = bb / MAX_RGB; + const max = Math.max(r, g, b); + const min = Math.min(r, g, b); + const d = max - min; + const l = (max + min) * HALF * MAX_PCT; + let h, s; + if (Math.round(l) === 0 || Math.round(l) === MAX_PCT) { + h = 0; + s = 0; + } else { + s = (d / (1 - Math.abs(max + min - 1))) * MAX_PCT; + if (s === 0) { + h = 0; + } else { + switch (max) { + case r: + h = (g - b) / d; + break; + case g: + h = (b - r) / d + DUO; + break; + case b: + default: + h = (r - g) / d + QUAD; + break; + } + h = (h * SEXA) % DEG; + if (h < 0) { + h += DEG; + } + } + } + return [h, s, l]; +}; + +/** + * transform xyz to hwb + * @param xyz - [x, y, z] + * @param [skip] - skip validate + * @returns TriColorChannels - [h, w, b] + */ +export const transformXyzToHwb = ( + xyz: TriColorChannels, + skip: boolean = false +): TriColorChannels => { + const [r, g, b] = transformXyzToRgb(xyz, skip); + const wh = Math.min(r, g, b) / MAX_RGB; + const bk = 1 - Math.max(r, g, b) / MAX_RGB; + let h; + if (wh + bk === 1) { + h = 0; + } else { + [h] = transformXyzToHsl(xyz); + } + return [h, wh * MAX_PCT, bk * MAX_PCT]; +}; + +/** + * transform xyz to oklab + * @param xyz - [x, y, z] + * @param [skip] - skip validate + * @returns TriColorChannels - [l, a, b] + */ +export const transformXyzToOklab = ( + xyz: TriColorChannels, + skip: boolean = false +): TriColorChannels => { + if (!skip) { + xyz = validateColorComponents(xyz, { + maxLength: TRIA, + validateRange: false + }) as TriColorChannels; + } + const lms = transformMatrix(MATRIX_XYZ_TO_LMS, xyz, true); + const xyzLms = lms.map(c => Math.cbrt(c)) as TriColorChannels; + let [l, a, b] = transformMatrix(MATRIX_LMS_TO_OKLAB, xyzLms, true); + l = Math.min(Math.max(l, 0), 1); + const lPct = Math.round(parseFloat(l.toFixed(QUAD)) * MAX_PCT); + if (lPct === 0 || lPct === MAX_PCT) { + a = 0; + b = 0; + } + return [l, a, b]; +}; + +/** + * transform xyz to oklch + * @param xyz - [x, y, z] + * @param [skip] - skip validate + * @returns TriColorChannels - [l, c, h] + */ +export const transformXyzToOklch = ( + xyz: TriColorChannels, + skip: boolean = false +): TriColorChannels => { + const [l, a, b] = transformXyzToOklab(xyz, skip); + let c, h; + const lPct = Math.round(parseFloat(l.toFixed(QUAD)) * MAX_PCT); + if (lPct === 0 || lPct === MAX_PCT) { + c = 0; + h = 0; + } else { + c = Math.max(Math.sqrt(Math.pow(a, POW_SQR) + Math.pow(b, POW_SQR)), 0); + if (parseFloat(c.toFixed(QUAD)) === 0) { + h = 0; + } else { + h = (Math.atan2(b, a) * DEG_HALF) / Math.PI; + if (h < 0) { + h += DEG; + } + } + } + return [l, c, h]; +}; + +/** + * transform xyz D50 to rgb + * @param xyz - [x, y, z] + * @param [skip] - skip validate + * @returns TriColorChannels - [r, g, b] r|g|b: 0..255 + */ +export const transformXyzD50ToRgb = ( + xyz: TriColorChannels, + skip: boolean = false +): TriColorChannels => { + if (!skip) { + xyz = validateColorComponents(xyz, { + maxLength: TRIA, + validateRange: false + }) as TriColorChannels; + } + const xyzD65 = transformMatrix(MATRIX_D50_TO_D65, xyz, true); + const rgb = transformXyzToRgb(xyzD65, true); + return rgb; +}; + +/** + * transform xyz-d50 to lab + * @param xyz - [x, y, z] + * @param [skip] - skip validate + * @returns TriColorChannels - [l, a, b] + */ +export const transformXyzD50ToLab = ( + xyz: TriColorChannels, + skip: boolean = false +): TriColorChannels => { + if (!skip) { + xyz = validateColorComponents(xyz, { + maxLength: TRIA, + validateRange: false + }) as TriColorChannels; + } + const xyzD50 = xyz.map((val, i) => val / (D50[i] as number)); + const [f0, f1, f2] = xyzD50.map(val => + val > LAB_EPSILON ? Math.cbrt(val) : (val * LAB_KAPPA + HEX) / LAB_L + ) as TriColorChannels; + const l = Math.min(Math.max(LAB_L * f1 - HEX, 0), MAX_PCT); + let a, b; + if (l === 0 || l === MAX_PCT) { + a = 0; + b = 0; + } else { + a = (f0 - f1) * LAB_A; + b = (f1 - f2) * LAB_B; + } + return [l, a, b]; +}; + +/** + * transform xyz-d50 to lch + * @param xyz - [x, y, z] + * @param [skip] - skip validate + * @returns TriColorChannels - [l, c, h] + */ +export const transformXyzD50ToLch = ( + xyz: TriColorChannels, + skip: boolean = false +): TriColorChannels => { + const [l, a, b] = transformXyzD50ToLab(xyz, skip); + let c, h; + if (l === 0 || l === MAX_PCT) { + c = 0; + h = 0; + } else { + c = Math.max(Math.sqrt(Math.pow(a, POW_SQR) + Math.pow(b, POW_SQR)), 0); + h = (Math.atan2(b, a) * DEG_HALF) / Math.PI; + if (h < 0) { + h += DEG; + } + } + return [l, c, h]; +}; + +/** + * convert rgb to hex color + * @param rgb - [r, g, b, alpha] r|g|b: 0..255 alpha: 0..1 + * @returns hex color + */ +export const convertRgbToHex = (rgb: ColorChannels): string => { + const [r, g, b, alpha] = validateColorComponents(rgb, { + alpha: true, + maxRange: MAX_RGB + }) as ColorChannels; + const rr = numberToHexString(r); + const gg = numberToHexString(g); + const bb = numberToHexString(b); + const aa = numberToHexString(alpha * MAX_RGB); + let hex; + if (aa === 'ff') { + hex = `#${rr}${gg}${bb}`; + } else { + hex = `#${rr}${gg}${bb}${aa}`; + } + return hex; +}; + +/** + * convert linear rgb to hex color + * @param rgb - [r, g, b, alpha] r|g|b|alpha: 0..1 + * @param [skip] - skip validate + * @returns hex color + */ +export const convertLinearRgbToHex = ( + rgb: ColorChannels, + skip: boolean = false +): string => { + let r, g, b, alpha; + if (skip) { + [r, g, b, alpha] = rgb; + } else { + [r, g, b, alpha] = validateColorComponents(rgb, { + minLength: QUAD + }) as ColorChannels; + } + [r, g, b] = transformLinearRgbToRgb([r, g, b], true); + const rr = numberToHexString(r); + const gg = numberToHexString(g); + const bb = numberToHexString(b); + const aa = numberToHexString(alpha * MAX_RGB); + let hex; + if (aa === 'ff') { + hex = `#${rr}${gg}${bb}`; + } else { + hex = `#${rr}${gg}${bb}${aa}`; + } + return hex; +}; + +/** + * convert xyz to hex color + * @param xyz - [x, y, z, alpha] + * @returns hex color + */ +export const convertXyzToHex = (xyz: ColorChannels): string => { + const [x, y, z, alpha] = validateColorComponents(xyz, { + minLength: QUAD, + validateRange: false + }) as ColorChannels; + const [r, g, b] = transformMatrix(MATRIX_XYZ_TO_L_RGB, [x, y, z], true); + const hex = convertLinearRgbToHex( + [ + Math.min(Math.max(r, 0), 1), + Math.min(Math.max(g, 0), 1), + Math.min(Math.max(b, 0), 1), + alpha + ], + true + ); + return hex; +}; + +/** + * convert xyz D50 to hex color + * @param xyz - [x, y, z, alpha] + * @returns hex color + */ +export const convertXyzD50ToHex = (xyz: ColorChannels): string => { + const [x, y, z, alpha] = validateColorComponents(xyz, { + minLength: QUAD, + validateRange: false + }) as ColorChannels; + const xyzD65 = transformMatrix(MATRIX_D50_TO_D65, [x, y, z], true); + const [r, g, b] = transformMatrix(MATRIX_XYZ_TO_L_RGB, xyzD65, true); + const hex = convertLinearRgbToHex([ + Math.min(Math.max(r, 0), 1), + Math.min(Math.max(g, 0), 1), + Math.min(Math.max(b, 0), 1), + alpha + ]); + return hex; +}; + +/** + * convert hex color to rgb + * @param value - hex color value + * @returns ColorChannels - [r, g, b, alpha] r|g|b: 0..255 alpha: 0..1 + */ +export const convertHexToRgb = (value: string): ColorChannels => { + if (isString(value)) { + value = value.toLowerCase().trim(); + } else { + throw new TypeError(`${value} is not a string.`); + } + if ( + !( + /^#[\da-f]{6}$/.test(value) || + /^#[\da-f]{3}$/.test(value) || + /^#[\da-f]{8}$/.test(value) || + /^#[\da-f]{4}$/.test(value) + ) + ) { + throw new SyntaxError(`Invalid property value: ${value}`); + } + const arr: number[] = []; + if (/^#[\da-f]{3}$/.test(value)) { + const [, r, g, b] = value.match( + /^#([\da-f])([\da-f])([\da-f])$/ + ) as MatchedRegExp; + arr.push( + parseInt(`${r}${r}`, HEX), + parseInt(`${g}${g}`, HEX), + parseInt(`${b}${b}`, HEX), + 1 + ); + } else if (/^#[\da-f]{4}$/.test(value)) { + const [, r, g, b, alpha] = value.match( + /^#([\da-f])([\da-f])([\da-f])([\da-f])$/ + ) as MatchedRegExp; + arr.push( + parseInt(`${r}${r}`, HEX), + parseInt(`${g}${g}`, HEX), + parseInt(`${b}${b}`, HEX), + parseHexAlpha(`${alpha}${alpha}`) + ); + } else if (/^#[\da-f]{8}$/.test(value)) { + const [, r, g, b, alpha] = value.match( + /^#([\da-f]{2})([\da-f]{2})([\da-f]{2})([\da-f]{2})$/ + ) as MatchedRegExp; + arr.push( + parseInt(r, HEX), + parseInt(g, HEX), + parseInt(b, HEX), + parseHexAlpha(alpha) + ); + } else { + const [, r, g, b] = value.match( + /^#([\da-f]{2})([\da-f]{2})([\da-f]{2})$/ + ) as MatchedRegExp; + arr.push(parseInt(r, HEX), parseInt(g, HEX), parseInt(b, HEX), 1); + } + return arr as ColorChannels; +}; + +/** + * convert hex color to linear rgb + * @param value - hex color value + * @returns ColorChannels - [r, g, b, alpha] r|g|b|alpha: 0..1 + */ +export const convertHexToLinearRgb = (value: string): ColorChannels => { + const [rr, gg, bb, alpha] = convertHexToRgb(value); + const [r, g, b] = transformRgbToLinearRgb([rr, gg, bb], true); + return [r, g, b, alpha]; +}; + +/** + * convert hex color to xyz + * @param value - hex color value + * @returns ColorChannels - [x, y, z, alpha] + */ +export const convertHexToXyz = (value: string): ColorChannels => { + const [r, g, b, alpha] = convertHexToLinearRgb(value); + const [x, y, z] = transformMatrix(MATRIX_L_RGB_TO_XYZ, [r, g, b], true); + return [x, y, z, alpha]; +}; + +/** + * parse rgb() + * @param value - rgb color value + * @param [opt] - options + * @returns parsed color - ['rgb', r, g, b, alpha], '(empty)', NullObject + */ +export const parseRgb = ( + value: string, + opt: Options = {} +): SpecifiedColorChannels | string | NullObject => { + if (isString(value)) { + value = value.toLowerCase().trim(); + } else { + throw new TypeError(`${value} is not a string.`); + } + const { format = '', nullable = false } = opt; + const reg = new RegExp(`^rgba?\\(\\s*(${SYN_MOD}|${SYN_RGB_LV3})\\s*\\)$`); + if (!reg.test(value)) { + const res = resolveInvalidColorValue(format, nullable); + if (res instanceof NullObject) { + return res; + } + if (isString(res)) { + return res as string; + } + return res as SpecifiedColorChannels; + } + const [, val] = value.match(reg) as MatchedRegExp; + const [v1, v2, v3, v4 = ''] = val + .replace(/[,/]/g, ' ') + .split(/\s+/) as StringColorChannels; + let r, g, b; + if (v1 === NONE) { + r = 0; + } else { + if (v1.endsWith('%')) { + r = (parseFloat(v1) * MAX_RGB) / MAX_PCT; + } else { + r = parseFloat(v1); + } + r = Math.min(Math.max(roundToPrecision(r, OCT), 0), MAX_RGB); + } + if (v2 === NONE) { + g = 0; + } else { + if (v2.endsWith('%')) { + g = (parseFloat(v2) * MAX_RGB) / MAX_PCT; + } else { + g = parseFloat(v2); + } + g = Math.min(Math.max(roundToPrecision(g, OCT), 0), MAX_RGB); + } + if (v3 === NONE) { + b = 0; + } else { + if (v3.endsWith('%')) { + b = (parseFloat(v3) * MAX_RGB) / MAX_PCT; + } else { + b = parseFloat(v3); + } + b = Math.min(Math.max(roundToPrecision(b, OCT), 0), MAX_RGB); + } + const alpha = parseAlpha(v4); + return ['rgb', r, g, b, format === VAL_MIX && v4 === NONE ? NONE : alpha]; +}; + +/** + * parse hsl() + * @param value - hsl color value + * @param [opt] - options + * @returns parsed color - ['rgb', r, g, b, alpha], '(empty)', NullObject + */ +export const parseHsl = ( + value: string, + opt: Options = {} +): SpecifiedColorChannels | string | NullObject => { + if (isString(value)) { + value = value.trim(); + } else { + throw new TypeError(`${value} is not a string.`); + } + const { format = '', nullable = false } = opt; + if (!REG_HSL.test(value)) { + const res = resolveInvalidColorValue(format, nullable); + if (res instanceof NullObject) { + return res; + } + if (isString(res)) { + return res as string; + } + return res as SpecifiedColorChannels; + } + const [, val] = value.match(REG_HSL) as MatchedRegExp; + const [v1, v2, v3, v4 = ''] = val + .replace(/[,/]/g, ' ') + .split(/\s+/) as StringColorChannels; + let h, s, l; + if (v1 === NONE) { + h = 0; + } else { + h = angleToDeg(v1); + } + if (v2 === NONE) { + s = 0; + } else { + s = Math.min(Math.max(parseFloat(v2), 0), MAX_PCT); + } + if (v3 === NONE) { + l = 0; + } else { + l = Math.min(Math.max(parseFloat(v3), 0), MAX_PCT); + } + const alpha = parseAlpha(v4); + if (format === 'hsl') { + return [ + format, + v1 === NONE ? v1 : h, + v2 === NONE ? v2 : s, + v3 === NONE ? v3 : l, + v4 === NONE ? v4 : alpha + ]; + } + h = (h / DEG) * DOZ; + l /= MAX_PCT; + const sa = (s / MAX_PCT) * Math.min(l, 1 - l); + const rk = h % DOZ; + const gk = (8 + h) % DOZ; + const bk = (4 + h) % DOZ; + const r = l - sa * Math.max(-1, Math.min(rk - TRIA, TRIA ** POW_SQR - rk, 1)); + const g = l - sa * Math.max(-1, Math.min(gk - TRIA, TRIA ** POW_SQR - gk, 1)); + const b = l - sa * Math.max(-1, Math.min(bk - TRIA, TRIA ** POW_SQR - bk, 1)); + return [ + 'rgb', + Math.min(Math.max(roundToPrecision(r * MAX_RGB, OCT), 0), MAX_RGB), + Math.min(Math.max(roundToPrecision(g * MAX_RGB, OCT), 0), MAX_RGB), + Math.min(Math.max(roundToPrecision(b * MAX_RGB, OCT), 0), MAX_RGB), + alpha + ]; +}; + +/** + * parse hwb() + * @param value - hwb color value + * @param [opt] - options + * @returns parsed color - ['rgb', r, g, b, alpha], '(empty)', NullObject + */ +export const parseHwb = ( + value: string, + opt: Options = {} +): SpecifiedColorChannels | string | NullObject => { + if (isString(value)) { + value = value.trim(); + } else { + throw new TypeError(`${value} is not a string.`); + } + const { format = '', nullable = false } = opt; + if (!REG_HWB.test(value)) { + const res = resolveInvalidColorValue(format, nullable); + if (res instanceof NullObject) { + return res; + } + if (isString(res)) { + return res as string; + } + return res as SpecifiedColorChannels; + } + const [, val] = value.match(REG_HWB) as MatchedRegExp; + const [v1, v2, v3, v4 = ''] = val + .replace('/', ' ') + .split(/\s+/) as StringColorChannels; + let h, wh, bk; + if (v1 === NONE) { + h = 0; + } else { + h = angleToDeg(v1); + } + if (v2 === NONE) { + wh = 0; + } else { + wh = Math.min(Math.max(parseFloat(v2), 0), MAX_PCT) / MAX_PCT; + } + if (v3 === NONE) { + bk = 0; + } else { + bk = Math.min(Math.max(parseFloat(v3), 0), MAX_PCT) / MAX_PCT; + } + const alpha = parseAlpha(v4); + if (format === 'hwb') { + return [ + format, + v1 === NONE ? v1 : h, + v2 === NONE ? v2 : wh * MAX_PCT, + v3 === NONE ? v3 : bk * MAX_PCT, + v4 === NONE ? v4 : alpha + ]; + } + if (wh + bk >= 1) { + const v = roundToPrecision((wh / (wh + bk)) * MAX_RGB, OCT); + return ['rgb', v, v, v, alpha]; + } + const factor = (1 - wh - bk) / MAX_RGB; + let [, r, g, b] = parseHsl(`hsl(${h} 100 50)`) as ComputedColorChannels; + r = roundToPrecision((r * factor + wh) * MAX_RGB, OCT); + g = roundToPrecision((g * factor + wh) * MAX_RGB, OCT); + b = roundToPrecision((b * factor + wh) * MAX_RGB, OCT); + return [ + 'rgb', + Math.min(Math.max(r, 0), MAX_RGB), + Math.min(Math.max(g, 0), MAX_RGB), + Math.min(Math.max(b, 0), MAX_RGB), + alpha + ]; +}; + +/** + * parse lab() + * @param value - lab color value + * @param [opt] - options + * @returns parsed color + * - [xyz-d50, x, y, z, alpha], ['lab', l, a, b, alpha], '(empty)', NullObject + */ +export const parseLab = ( + value: string, + opt: Options = {} +): SpecifiedColorChannels | string | NullObject => { + if (isString(value)) { + value = value.trim(); + } else { + throw new TypeError(`${value} is not a string.`); + } + const { format = '', nullable = false } = opt; + if (!REG_LAB.test(value)) { + const res = resolveInvalidColorValue(format, nullable); + if (res instanceof NullObject) { + return res; + } + if (isString(res)) { + return res as string; + } + return res as SpecifiedColorChannels; + } + const COEF_PCT = 1.25; + const COND_POW = 8; + const [, val] = value.match(REG_LAB) as MatchedRegExp; + const [v1, v2, v3, v4 = ''] = val + .replace('/', ' ') + .split(/\s+/) as StringColorChannels; + let l, a, b; + if (v1 === NONE) { + l = 0; + } else { + if (v1.endsWith('%')) { + l = parseFloat(v1); + if (l > MAX_PCT) { + l = MAX_PCT; + } + } else { + l = parseFloat(v1); + } + if (l < 0) { + l = 0; + } + } + if (v2 === NONE) { + a = 0; + } else { + a = v2.endsWith('%') ? parseFloat(v2) * COEF_PCT : parseFloat(v2); + } + if (v3 === NONE) { + b = 0; + } else { + b = v3.endsWith('%') ? parseFloat(v3) * COEF_PCT : parseFloat(v3); + } + const alpha = parseAlpha(v4); + if (REG_SPEC.test(format)) { + return [ + 'lab', + v1 === NONE ? v1 : roundToPrecision(l, HEX), + v2 === NONE ? v2 : roundToPrecision(a, HEX), + v3 === NONE ? v3 : roundToPrecision(b, HEX), + v4 === NONE ? v4 : alpha + ]; + } + const fl = (l + HEX) / LAB_L; + const fa = a / LAB_A + fl; + const fb = fl - b / LAB_B; + const powFl = Math.pow(fl, POW_CUBE); + const powFa = Math.pow(fa, POW_CUBE); + const powFb = Math.pow(fb, POW_CUBE); + const xyz = [ + powFa > LAB_EPSILON ? powFa : (fa * LAB_L - HEX) / LAB_KAPPA, + l > COND_POW ? powFl : l / LAB_KAPPA, + powFb > LAB_EPSILON ? powFb : (fb * LAB_L - HEX) / LAB_KAPPA + ]; + const [x, y, z] = xyz.map( + (val, i) => val * (D50[i] as number) + ) as TriColorChannels; + return [ + 'xyz-d50', + roundToPrecision(x, HEX), + roundToPrecision(y, HEX), + roundToPrecision(z, HEX), + alpha + ]; +}; + +/** + * parse lch() + * @param value - lch color value + * @param [opt] - options + * @returns parsed color + * - ['xyz-d50', x, y, z, alpha], ['lch', l, c, h, alpha] + * - '(empty)', NullObject + */ +export const parseLch = ( + value: string, + opt: Options = {} +): SpecifiedColorChannels | string | NullObject => { + if (isString(value)) { + value = value.trim(); + } else { + throw new TypeError(`${value} is not a string.`); + } + const { format = '', nullable = false } = opt; + if (!REG_LCH.test(value)) { + const res = resolveInvalidColorValue(format, nullable); + if (res instanceof NullObject) { + return res; + } + if (isString(res)) { + return res as string; + } + return res as SpecifiedColorChannels; + } + const COEF_PCT = 1.5; + const [, val] = value.match(REG_LCH) as MatchedRegExp; + const [v1, v2, v3, v4 = ''] = val + .replace('/', ' ') + .split(/\s+/) as StringColorChannels; + let l, c, h; + if (v1 === NONE) { + l = 0; + } else { + l = parseFloat(v1); + if (l < 0) { + l = 0; + } + } + if (v2 === NONE) { + c = 0; + } else { + c = v2.endsWith('%') ? parseFloat(v2) * COEF_PCT : parseFloat(v2); + } + if (v3 === NONE) { + h = 0; + } else { + h = angleToDeg(v3); + } + const alpha = parseAlpha(v4); + if (REG_SPEC.test(format)) { + return [ + 'lch', + v1 === NONE ? v1 : roundToPrecision(l, HEX), + v2 === NONE ? v2 : roundToPrecision(c, HEX), + v3 === NONE ? v3 : roundToPrecision(h, HEX), + v4 === NONE ? v4 : alpha + ]; + } + const a = c * Math.cos((h * Math.PI) / DEG_HALF); + const b = c * Math.sin((h * Math.PI) / DEG_HALF); + const [, x, y, z] = parseLab(`lab(${l} ${a} ${b})`) as ComputedColorChannels; + return [ + 'xyz-d50', + roundToPrecision(x, HEX), + roundToPrecision(y, HEX), + roundToPrecision(z, HEX), + alpha as number + ]; +}; + +/** + * parse oklab() + * @param value - oklab color value + * @param [opt] - options + * @returns parsed color + * - ['xyz-d65', x, y, z, alpha], ['oklab', l, a, b, alpha] + * - '(empty)', NullObject + */ +export const parseOklab = ( + value: string, + opt: Options = {} +): SpecifiedColorChannels | string | NullObject => { + if (isString(value)) { + value = value.trim(); + } else { + throw new TypeError(`${value} is not a string.`); + } + const { format = '', nullable = false } = opt; + if (!REG_OKLAB.test(value)) { + const res = resolveInvalidColorValue(format, nullable); + if (res instanceof NullObject) { + return res; + } + if (isString(res)) { + return res as string; + } + return res as SpecifiedColorChannels; + } + const COEF_PCT = 0.4; + const [, val] = value.match(REG_OKLAB) as MatchedRegExp; + const [v1, v2, v3, v4 = ''] = val + .replace('/', ' ') + .split(/\s+/) as StringColorChannels; + let l, a, b; + if (v1 === NONE) { + l = 0; + } else { + l = v1.endsWith('%') ? parseFloat(v1) / MAX_PCT : parseFloat(v1); + if (l < 0) { + l = 0; + } + } + if (v2 === NONE) { + a = 0; + } else if (v2.endsWith('%')) { + a = (parseFloat(v2) * COEF_PCT) / MAX_PCT; + } else { + a = parseFloat(v2); + } + if (v3 === NONE) { + b = 0; + } else if (v3.endsWith('%')) { + b = (parseFloat(v3) * COEF_PCT) / MAX_PCT; + } else { + b = parseFloat(v3); + } + const alpha = parseAlpha(v4); + if (REG_SPEC.test(format)) { + return [ + 'oklab', + v1 === NONE ? v1 : roundToPrecision(l, HEX), + v2 === NONE ? v2 : roundToPrecision(a, HEX), + v3 === NONE ? v3 : roundToPrecision(b, HEX), + v4 === NONE ? v4 : alpha + ]; + } + const lms = transformMatrix(MATRIX_OKLAB_TO_LMS, [l, a, b]); + const xyzLms = lms.map(c => Math.pow(c, POW_CUBE)) as TriColorChannels; + const [x, y, z] = transformMatrix(MATRIX_LMS_TO_XYZ, xyzLms, true); + return [ + 'xyz-d65', + roundToPrecision(x, HEX), + roundToPrecision(y, HEX), + roundToPrecision(z, HEX), + alpha as number + ]; +}; + +/** + * parse oklch() + * @param value - oklch color value + * @param [opt] - options + * @returns parsed color + * - ['xyz-d65', x, y, z, alpha], ['oklch', l, c, h, alpha] + * - '(empty)', NullObject + */ +export const parseOklch = ( + value: string, + opt: Options = {} +): SpecifiedColorChannels | string | NullObject => { + if (isString(value)) { + value = value.trim(); + } else { + throw new TypeError(`${value} is not a string.`); + } + const { format = '', nullable = false } = opt; + if (!REG_OKLCH.test(value)) { + const res = resolveInvalidColorValue(format, nullable); + if (res instanceof NullObject) { + return res; + } + if (isString(res)) { + return res as string; + } + return res as SpecifiedColorChannels; + } + const COEF_PCT = 0.4; + const [, val] = value.match(REG_OKLCH) as MatchedRegExp; + const [v1, v2, v3, v4 = ''] = val + .replace('/', ' ') + .split(/\s+/) as StringColorChannels; + let l, c, h; + if (v1 === NONE) { + l = 0; + } else { + l = v1.endsWith('%') ? parseFloat(v1) / MAX_PCT : parseFloat(v1); + if (l < 0) { + l = 0; + } + } + if (v2 === NONE) { + c = 0; + } else { + if (v2.endsWith('%')) { + c = (parseFloat(v2) * COEF_PCT) / MAX_PCT; + } else { + c = parseFloat(v2); + } + if (c < 0) { + c = 0; + } + } + if (v3 === NONE) { + h = 0; + } else { + h = angleToDeg(v3); + } + const alpha = parseAlpha(v4); + if (REG_SPEC.test(format)) { + return [ + 'oklch', + v1 === NONE ? v1 : roundToPrecision(l, HEX), + v2 === NONE ? v2 : roundToPrecision(c, HEX), + v3 === NONE ? v3 : roundToPrecision(h, HEX), + v4 === NONE ? v4 : alpha + ]; + } + const a = c * Math.cos((h * Math.PI) / DEG_HALF); + const b = c * Math.sin((h * Math.PI) / DEG_HALF); + const lms = transformMatrix(MATRIX_OKLAB_TO_LMS, [l, a, b]); + const xyzLms = lms.map(cc => Math.pow(cc, POW_CUBE)) as TriColorChannels; + const [x, y, z] = transformMatrix(MATRIX_LMS_TO_XYZ, xyzLms, true); + return [ + 'xyz-d65', + roundToPrecision(x, HEX), + roundToPrecision(y, HEX), + roundToPrecision(z, HEX), + alpha + ]; +}; + +/** + * parse color() + * @param value - color function value + * @param [opt] - options + * @returns parsed color + * - ['xyz-(d50|d65)', x, y, z, alpha], [cs, r, g, b, alpha] + * - '(empty)', NullObject + */ +export const parseColorFunc = ( + value: string, + opt: Options = {} +): SpecifiedColorChannels | string | NullObject => { + if (isString(value)) { + value = value.trim(); + } else { + throw new TypeError(`${value} is not a string.`); + } + const { colorSpace = '', d50 = false, format = '', nullable = false } = opt; + if (!REG_FN_COLOR.test(value)) { + const res = resolveInvalidColorValue(format, nullable); + if (res instanceof NullObject) { + return res; + } + if (isString(res)) { + return res as string; + } + return res as SpecifiedColorChannels; + } + const [, val] = value.match(REG_FN_COLOR) as MatchedRegExp; + let [cs, v1, v2, v3, v4 = ''] = val + .replace('/', ' ') + .split(/\s+/) as StringColorSpacedChannels; + let r, g, b; + if (cs === 'xyz') { + cs = 'xyz-d65'; + } + if (v1 === NONE) { + r = 0; + } else { + r = v1.endsWith('%') ? parseFloat(v1) / MAX_PCT : parseFloat(v1); + } + if (v2 === NONE) { + g = 0; + } else { + g = v2.endsWith('%') ? parseFloat(v2) / MAX_PCT : parseFloat(v2); + } + if (v3 === NONE) { + b = 0; + } else { + b = v3.endsWith('%') ? parseFloat(v3) / MAX_PCT : parseFloat(v3); + } + const alpha = parseAlpha(v4); + if (REG_SPEC.test(format) || (format === VAL_MIX && cs === colorSpace)) { + return [ + cs, + v1 === NONE ? v1 : roundToPrecision(r, DEC), + v2 === NONE ? v2 : roundToPrecision(g, DEC), + v3 === NONE ? v3 : roundToPrecision(b, DEC), + v4 === NONE ? v4 : alpha + ]; + } + let x = 0; + let y = 0; + let z = 0; + // srgb-linear + if (cs === 'srgb-linear') { + [x, y, z] = transformMatrix(MATRIX_L_RGB_TO_XYZ, [r, g, b]); + if (d50) { + [x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [x, y, z], true); + } + // display-p3 + } else if (cs === 'display-p3') { + const linearRgb = transformRgbToLinearRgb([ + r * MAX_RGB, + g * MAX_RGB, + b * MAX_RGB + ]); + [x, y, z] = transformMatrix(MATRIX_P3_TO_XYZ, linearRgb); + if (d50) { + [x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [x, y, z], true); + } + // rec2020 + } else if (cs === 'rec2020') { + const ALPHA = 1.09929682680944; + const BETA = 0.018053968510807; + const REC_COEF = 0.45; + const rgb = [r, g, b].map(c => { + let cl; + if (c < BETA * REC_COEF * DEC) { + cl = c / (REC_COEF * DEC); + } else { + cl = Math.pow((c + ALPHA - 1) / ALPHA, 1 / REC_COEF); + } + return cl; + }) as TriColorChannels; + [x, y, z] = transformMatrix(MATRIX_REC2020_TO_XYZ, rgb); + if (d50) { + [x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [x, y, z], true); + } + // a98-rgb + } else if (cs === 'a98-rgb') { + const POW_A98 = 563 / 256; + const rgb = [r, g, b].map(c => { + const cl = Math.pow(c, POW_A98); + return cl; + }) as TriColorChannels; + [x, y, z] = transformMatrix(MATRIX_A98_TO_XYZ, rgb); + if (d50) { + [x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [x, y, z], true); + } + // prophoto-rgb + } else if (cs === 'prophoto-rgb') { + const POW_PROPHOTO = 1.8; + const rgb = [r, g, b].map(c => { + let cl; + if (c > 1 / (HEX * DUO)) { + cl = Math.pow(c, POW_PROPHOTO); + } else { + cl = c / HEX; + } + return cl; + }) as TriColorChannels; + [x, y, z] = transformMatrix(MATRIX_PROPHOTO_TO_XYZ_D50, rgb); + if (!d50) { + [x, y, z] = transformMatrix(MATRIX_D50_TO_D65, [x, y, z], true); + } + // xyz, xyz-d50, xyz-d65 + } else if (/^xyz(?:-d(?:50|65))?$/.test(cs)) { + [x, y, z] = [r, g, b]; + if (cs === 'xyz-d50') { + if (!d50) { + [x, y, z] = transformMatrix(MATRIX_D50_TO_D65, [x, y, z]); + } + } else if (d50) { + [x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [x, y, z], true); + } + // srgb + } else { + [x, y, z] = transformRgbToXyz([r * MAX_RGB, g * MAX_RGB, b * MAX_RGB]); + if (d50) { + [x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [x, y, z], true); + } + } + return [ + d50 ? 'xyz-d50' : 'xyz-d65', + roundToPrecision(x, HEX), + roundToPrecision(y, HEX), + roundToPrecision(z, HEX), + format === VAL_MIX && v4 === NONE ? v4 : alpha + ]; +}; + +/** + * parse color value + * @param value - CSS color value + * @param [opt] - options + * @returns parsed color + * - ['xyz-(d50|d65)', x, y, z, alpha], ['rgb', r, g, b, alpha] + * - value, '(empty)', NullObject + */ +export const parseColorValue = ( + value: string, + opt: Options = {} +): SpecifiedColorChannels | string | NullObject => { + if (isString(value)) { + value = value.toLowerCase().trim(); + } else { + throw new TypeError(`${value} is not a string.`); + } + const { d50 = false, format = '', nullable = false } = opt; + if (!REG_COLOR.test(value)) { + const res = resolveInvalidColorValue(format, nullable); + if (res instanceof NullObject) { + return res; + } + if (isString(res)) { + return res as string; + } + return res as SpecifiedColorChannels; + } + let x = 0; + let y = 0; + let z = 0; + let alpha = 0; + // complement currentcolor as a missing color + if (REG_CURRENT.test(value)) { + if (format === VAL_COMP) { + return ['rgb', 0, 0, 0, 0]; + } + if (format === VAL_SPEC) { + return value; + } + // named-color + } else if (/^[a-z]+$/.test(value)) { + if (Object.hasOwn(NAMED_COLORS, value)) { + if (format === VAL_SPEC) { + return value; + } + const [r, g, b] = NAMED_COLORS[ + value as keyof typeof NAMED_COLORS + ] as TriColorChannels; + alpha = 1; + if (format === VAL_COMP) { + return ['rgb', r, g, b, alpha]; + } + [x, y, z] = transformRgbToXyz([r, g, b], true); + if (d50) { + [x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [x, y, z], true); + } + } else { + switch (format) { + case VAL_COMP: { + if (nullable && value !== 'transparent') { + return new NullObject(); + } + return ['rgb', 0, 0, 0, 0]; + } + case VAL_SPEC: { + if (value === 'transparent') { + return value; + } + return ''; + } + case VAL_MIX: { + if (value === 'transparent') { + return ['rgb', 0, 0, 0, 0]; + } + return new NullObject(); + } + default: + } + } + // hex-color + } else if (value[0] === '#') { + if (REG_SPEC.test(format)) { + const rgb = convertHexToRgb(value); + return ['rgb', ...rgb]; + } + [x, y, z, alpha] = convertHexToXyz(value); + if (d50) { + [x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [x, y, z], true); + } + // lab() + } else if (value.startsWith('lab')) { + if (REG_SPEC.test(format)) { + return parseLab(value, opt); + } + [, x, y, z, alpha] = parseLab(value) as ComputedColorChannels; + if (!d50) { + [x, y, z] = transformMatrix(MATRIX_D50_TO_D65, [x, y, z], true); + } + // lch() + } else if (value.startsWith('lch')) { + if (REG_SPEC.test(format)) { + return parseLch(value, opt); + } + [, x, y, z, alpha] = parseLch(value) as ComputedColorChannels; + if (!d50) { + [x, y, z] = transformMatrix(MATRIX_D50_TO_D65, [x, y, z], true); + } + // oklab() + } else if (value.startsWith('oklab')) { + if (REG_SPEC.test(format)) { + return parseOklab(value, opt); + } + [, x, y, z, alpha] = parseOklab(value) as ComputedColorChannels; + if (d50) { + [x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [x, y, z], true); + } + // oklch() + } else if (value.startsWith('oklch')) { + if (REG_SPEC.test(format)) { + return parseOklch(value, opt); + } + [, x, y, z, alpha] = parseOklch(value) as ComputedColorChannels; + if (d50) { + [x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [x, y, z], true); + } + } else { + let r, g, b; + // hsl() + if (value.startsWith('hsl')) { + [, r, g, b, alpha] = parseHsl(value) as ComputedColorChannels; + // hwb() + } else if (value.startsWith('hwb')) { + [, r, g, b, alpha] = parseHwb(value) as ComputedColorChannels; + // rgb() + } else { + [, r, g, b, alpha] = parseRgb(value, opt) as ComputedColorChannels; + } + if (REG_SPEC.test(format)) { + return ['rgb', Math.round(r), Math.round(g), Math.round(b), alpha]; + } + [x, y, z] = transformRgbToXyz([r, g, b]); + if (d50) { + [x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [x, y, z], true); + } + } + return [ + d50 ? 'xyz-d50' : 'xyz-d65', + roundToPrecision(x, HEX), + roundToPrecision(y, HEX), + roundToPrecision(z, HEX), + alpha + ]; +}; + +/** + * resolve color value + * @param value - CSS color value + * @param [opt] - options + * @returns resolved color + * - [cs, v1, v2, v3, alpha], value, '(empty)', NullObject + */ +export const resolveColorValue = ( + value: string, + opt: Options = {} +): SpecifiedColorChannels | string | NullObject => { + if (isString(value)) { + value = value.toLowerCase().trim(); + } else { + throw new TypeError(`${value} is not a string.`); + } + const { colorSpace = '', format = '', nullable = false } = opt; + const cacheKey: string = createCacheKey( + { + namespace: NAMESPACE, + name: 'resolveColorValue', + value + }, + opt + ); + const cachedResult = getCache(cacheKey); + if (cachedResult instanceof CacheItem) { + if (cachedResult.isNull) { + return cachedResult as NullObject; + } + const cachedItem = cachedResult.item; + if (isString(cachedItem)) { + return cachedItem as string; + } + return cachedItem as SpecifiedColorChannels; + } + if (!REG_COLOR.test(value)) { + const res = resolveInvalidColorValue(format, nullable); + if (res instanceof NullObject) { + setCache(cacheKey, null); + return res; + } + setCache(cacheKey, res); + if (isString(res)) { + return res as string; + } + return res as SpecifiedColorChannels; + } + let cs = ''; + let r = 0; + let g = 0; + let b = 0; + let alpha = 0; + // complement currentcolor as a missing color + if (REG_CURRENT.test(value)) { + if (format === VAL_SPEC) { + setCache(cacheKey, value); + return value; + } + // named-color + } else if (/^[a-z]+$/.test(value)) { + if (Object.hasOwn(NAMED_COLORS, value)) { + if (format === VAL_SPEC) { + setCache(cacheKey, value); + return value; + } + [r, g, b] = NAMED_COLORS[ + value as keyof typeof NAMED_COLORS + ] as TriColorChannels; + alpha = 1; + } else { + switch (format) { + case VAL_SPEC: { + if (value === 'transparent') { + setCache(cacheKey, value); + return value; + } + const res = ''; + setCache(cacheKey, res); + return res; + } + case VAL_MIX: { + if (value === 'transparent') { + const res: SpecifiedColorChannels = ['rgb', 0, 0, 0, 0]; + setCache(cacheKey, res); + return res; + } + setCache(cacheKey, null); + return new NullObject(); + } + case VAL_COMP: + default: { + if (nullable && value !== 'transparent') { + setCache(cacheKey, null); + return new NullObject(); + } + const res: SpecifiedColorChannels = ['rgb', 0, 0, 0, 0]; + setCache(cacheKey, res); + return res; + } + } + } + // hex-color + } else if (value[0] === '#') { + [r, g, b, alpha] = convertHexToRgb(value); + // hsl() + } else if (value.startsWith('hsl')) { + [, r, g, b, alpha] = parseHsl(value, opt) as ComputedColorChannels; + // hwb() + } else if (value.startsWith('hwb')) { + [, r, g, b, alpha] = parseHwb(value, opt) as ComputedColorChannels; + // lab(), lch() + } else if (/^l(?:ab|ch)/.test(value)) { + let x, y, z; + if (value.startsWith('lab')) { + [cs, x, y, z, alpha] = parseLab(value, opt) as ComputedColorChannels; + } else { + [cs, x, y, z, alpha] = parseLch(value, opt) as ComputedColorChannels; + } + if (REG_SPEC.test(format)) { + const res: SpecifiedColorChannels = [cs, x, y, z, alpha]; + setCache(cacheKey, res); + return res; + } + [r, g, b] = transformXyzD50ToRgb([x, y, z]); + // oklab(), oklch() + } else if (/^okl(?:ab|ch)/.test(value)) { + let x, y, z; + if (value.startsWith('oklab')) { + [cs, x, y, z, alpha] = parseOklab(value, opt) as ComputedColorChannels; + } else { + [cs, x, y, z, alpha] = parseOklch(value, opt) as ComputedColorChannels; + } + if (REG_SPEC.test(format)) { + const res: SpecifiedColorChannels = [cs, x, y, z, alpha]; + setCache(cacheKey, res); + return res; + } + [r, g, b] = transformXyzToRgb([x, y, z]); + // rgb() + } else { + [, r, g, b, alpha] = parseRgb(value, opt) as ComputedColorChannels; + } + if (format === VAL_MIX && colorSpace === 'srgb') { + const res: SpecifiedColorChannels = [ + 'srgb', + r / MAX_RGB, + g / MAX_RGB, + b / MAX_RGB, + alpha + ]; + setCache(cacheKey, res); + return res; + } + const res: SpecifiedColorChannels = [ + 'rgb', + Math.round(r), + Math.round(g), + Math.round(b), + alpha + ]; + setCache(cacheKey, res); + return res; +}; + +/** + * resolve color() + * @param value - color function value + * @param [opt] - options + * @returns resolved color - [cs, v1, v2, v3, alpha], '(empty)', NullObject + */ +export const resolveColorFunc = ( + value: string, + opt: Options = {} +): SpecifiedColorChannels | string | NullObject => { + if (isString(value)) { + value = value.toLowerCase().trim(); + } else { + throw new TypeError(`${value} is not a string.`); + } + const { colorSpace = '', format = '', nullable = false } = opt; + const cacheKey: string = createCacheKey( + { + namespace: NAMESPACE, + name: 'resolveColorFunc', + value + }, + opt + ); + const cachedResult = getCache(cacheKey); + if (cachedResult instanceof CacheItem) { + if (cachedResult.isNull) { + return cachedResult as NullObject; + } + const cachedItem = cachedResult.item; + if (isString(cachedItem)) { + return cachedItem as string; + } + return cachedItem as SpecifiedColorChannels; + } + if (!REG_FN_COLOR.test(value)) { + const res = resolveInvalidColorValue(format, nullable); + if (res instanceof NullObject) { + setCache(cacheKey, null); + return res; + } + setCache(cacheKey, res); + if (isString(res)) { + return res as string; + } + return res as SpecifiedColorChannels; + } + const [cs, v1, v2, v3, v4] = parseColorFunc( + value, + opt + ) as SpecifiedColorChannels; + if (REG_SPEC.test(format) || (format === VAL_MIX && cs === colorSpace)) { + const res: SpecifiedColorChannels = [cs, v1, v2, v3, v4]; + setCache(cacheKey, res); + return res; + } + const x = parseFloat(`${v1}`); + const y = parseFloat(`${v2}`); + const z = parseFloat(`${v3}`); + const alpha = parseAlpha(`${v4}`); + const [r, g, b] = transformXyzToRgb([x, y, z], true); + const res: SpecifiedColorChannels = ['rgb', r, g, b, alpha]; + setCache(cacheKey, res); + return res; +}; + +/** + * convert color value to linear rgb + * @param value - CSS color value + * @param [opt] - options + * @returns ColorChannels | NullObject - [r, g, b, alpha] r|g|b|alpha: 0..1 + */ +export const convertColorToLinearRgb = ( + value: string, + opt: { + colorSpace?: string; + format?: string; + } = {} +): ColorChannels | NullObject => { + if (isString(value)) { + value = value.trim(); + } else { + throw new TypeError(`${value} is not a string.`); + } + const { colorSpace = '', format = '' } = opt; + let cs = ''; + let r, g, b, alpha, x, y, z; + if (format === VAL_MIX) { + let xyz; + if (value.startsWith(FN_COLOR)) { + xyz = parseColorFunc(value, opt); + } else { + xyz = parseColorValue(value, opt); + } + if (xyz instanceof NullObject) { + return xyz; + } + [cs, x, y, z, alpha] = xyz as ComputedColorChannels; + if (cs === colorSpace) { + return [x, y, z, alpha]; + } + [r, g, b] = transformMatrix(MATRIX_XYZ_TO_L_RGB, [x, y, z], true); + } else if (value.startsWith(FN_COLOR)) { + const [, val] = value.match(REG_FN_COLOR) as MatchedRegExp; + const [cs] = val + .replace('/', ' ') + .split(/\s+/) as StringColorSpacedChannels; + if (cs === 'srgb-linear') { + [, r, g, b, alpha] = resolveColorFunc(value, { + format: VAL_COMP + }) as ComputedColorChannels; + } else { + [, x, y, z, alpha] = parseColorFunc(value) as ComputedColorChannels; + [r, g, b] = transformMatrix(MATRIX_XYZ_TO_L_RGB, [x, y, z], true); + } + } else { + [, x, y, z, alpha] = parseColorValue(value) as ComputedColorChannels; + [r, g, b] = transformMatrix(MATRIX_XYZ_TO_L_RGB, [x, y, z], true); + } + return [ + Math.min(Math.max(r, 0), 1), + Math.min(Math.max(g, 0), 1), + Math.min(Math.max(b, 0), 1), + alpha + ]; +}; + +/** + * convert color value to rgb + * @param value - CSS color value + * @param [opt] - options + * @returns ColorChannels | NullObject + * - [r, g, b, alpha] r|g|b: 0..255 alpha: 0..1 + */ +export const convertColorToRgb = ( + value: string, + opt: Options = {} +): ColorChannels | NullObject => { + if (isString(value)) { + value = value.trim(); + } else { + throw new TypeError(`${value} is not a string.`); + } + const { format = '' } = opt; + let r, g, b, alpha; + if (format === VAL_MIX) { + let rgb; + if (value.startsWith(FN_COLOR)) { + rgb = resolveColorFunc(value, opt); + } else { + rgb = resolveColorValue(value, opt); + } + if (rgb instanceof NullObject) { + return rgb; + } + [, r, g, b, alpha] = rgb as ComputedColorChannels; + } else if (value.startsWith(FN_COLOR)) { + const [, val] = value.match(REG_FN_COLOR) as MatchedRegExp; + const [cs] = val + .replace('/', ' ') + .split(/\s+/) as StringColorSpacedChannels; + if (cs === 'srgb') { + [, r, g, b, alpha] = resolveColorFunc(value, { + format: VAL_COMP + }) as ComputedColorChannels; + r *= MAX_RGB; + g *= MAX_RGB; + b *= MAX_RGB; + } else { + [, r, g, b, alpha] = resolveColorFunc(value) as ComputedColorChannels; + } + } else if (/^(?:ok)?l(?:ab|ch)/.test(value)) { + [r, g, b, alpha] = convertColorToLinearRgb(value) as ColorChannels; + [r, g, b] = transformLinearRgbToRgb([r, g, b]); + } else { + [, r, g, b, alpha] = resolveColorValue(value, { + format: VAL_COMP + }) as ComputedColorChannels; + } + return [r, g, b, alpha]; +}; + +/** + * convert color value to xyz + * @param value - CSS color value + * @param [opt] - options + * @returns ColorChannels | NullObject - [x, y, z, alpha] + */ +export const convertColorToXyz = ( + value: string, + opt: Options = {} +): ColorChannels | NullObject => { + if (isString(value)) { + value = value.trim(); + } else { + throw new TypeError(`${value} is not a string.`); + } + const { d50 = false, format = '' } = opt; + let x, y, z, alpha; + if (format === VAL_MIX) { + let xyz; + if (value.startsWith(FN_COLOR)) { + xyz = parseColorFunc(value, opt); + } else { + xyz = parseColorValue(value, opt); + } + if (xyz instanceof NullObject) { + return xyz; + } + [, x, y, z, alpha] = xyz as ComputedColorChannels; + } else if (value.startsWith(FN_COLOR)) { + const [, val] = value.match(REG_FN_COLOR) as MatchedRegExp; + const [cs] = val + .replace('/', ' ') + .split(/\s+/) as StringColorSpacedChannels; + if (d50) { + if (cs === 'xyz-d50') { + [, x, y, z, alpha] = resolveColorFunc(value, { + format: VAL_COMP + }) as ComputedColorChannels; + } else { + [, x, y, z, alpha] = parseColorFunc( + value, + opt + ) as ComputedColorChannels; + } + } else if (/^xyz(?:-d65)?$/.test(cs)) { + [, x, y, z, alpha] = resolveColorFunc(value, { + format: VAL_COMP + }) as ComputedColorChannels; + } else { + [, x, y, z, alpha] = parseColorFunc(value) as ComputedColorChannels; + } + } else { + [, x, y, z, alpha] = parseColorValue(value, opt) as ComputedColorChannels; + } + return [x, y, z, alpha]; +}; + +/** + * convert color value to hsl + * @param value - CSS color value + * @param [opt] - options + * @returns ColorChannels | NullObject - [h, s, l, alpha], hue may be powerless + */ +export const convertColorToHsl = ( + value: string, + opt: Options = {} +): ColorChannels | [number | string, number, number, number] | NullObject => { + if (isString(value)) { + value = value.trim(); + } else { + throw new TypeError(`${value} is not a string.`); + } + const { format = '' } = opt; + let h, s, l, alpha; + if (REG_HSL.test(value)) { + [, h, s, l, alpha] = parseHsl(value, { + format: 'hsl' + }) as ComputedColorChannels; + if (format === 'hsl') { + return [Math.round(h), Math.round(s), Math.round(l), alpha]; + } + return [h, s, l, alpha]; + } + let x, y, z; + if (format === VAL_MIX) { + let xyz; + if (value.startsWith(FN_COLOR)) { + xyz = parseColorFunc(value, opt); + } else { + xyz = parseColorValue(value, opt); + } + if (xyz instanceof NullObject) { + return xyz; + } + [, x, y, z, alpha] = xyz as ComputedColorChannels; + } else if (value.startsWith(FN_COLOR)) { + [, x, y, z, alpha] = parseColorFunc(value) as ComputedColorChannels; + } else { + [, x, y, z, alpha] = parseColorValue(value) as ComputedColorChannels; + } + [h, s, l] = transformXyzToHsl([x, y, z], true) as TriColorChannels; + if (format === 'hsl') { + return [Math.round(h), Math.round(s), Math.round(l), alpha]; + } + return [format === VAL_MIX && s === 0 ? NONE : h, s, l, alpha]; +}; + +/** + * convert color value to hwb + * @param value - CSS color value + * @param [opt] - options + * @returns ColorChannels | NullObject - [h, w, b, alpha], hue may be powerless + */ +export const convertColorToHwb = ( + value: string, + opt: Options = {} +): ColorChannels | [number | string, number, number, number] | NullObject => { + if (isString(value)) { + value = value.trim(); + } else { + throw new TypeError(`${value} is not a string.`); + } + const { format = '' } = opt; + let h, w, b, alpha; + if (REG_HWB.test(value)) { + [, h, w, b, alpha] = parseHwb(value, { + format: 'hwb' + }) as ComputedColorChannels; + if (format === 'hwb') { + return [Math.round(h), Math.round(w), Math.round(b), alpha]; + } + return [h, w, b, alpha]; + } + let x, y, z; + if (format === VAL_MIX) { + let xyz; + if (value.startsWith(FN_COLOR)) { + xyz = parseColorFunc(value, opt); + } else { + xyz = parseColorValue(value, opt); + } + if (xyz instanceof NullObject) { + return xyz; + } + [, x, y, z, alpha] = xyz as ComputedColorChannels; + } else if (value.startsWith(FN_COLOR)) { + [, x, y, z, alpha] = parseColorFunc(value) as ComputedColorChannels; + } else { + [, x, y, z, alpha] = parseColorValue(value) as ComputedColorChannels; + } + [h, w, b] = transformXyzToHwb([x, y, z], true) as TriColorChannels; + if (format === 'hwb') { + return [Math.round(h), Math.round(w), Math.round(b), alpha]; + } + return [format === VAL_MIX && w + b >= 100 ? NONE : h, w, b, alpha]; +}; + +/** + * convert color value to lab + * @param value - CSS color value + * @param [opt] - options + * @returns ColorChannels | NullObject - [l, a, b, alpha] + */ +export const convertColorToLab = ( + value: string, + opt: Options = {} +): ColorChannels | NullObject => { + if (isString(value)) { + value = value.trim(); + } else { + throw new TypeError(`${value} is not a string.`); + } + const { format = '' } = opt; + let l, a, b, alpha; + if (REG_LAB.test(value)) { + [, l, a, b, alpha] = parseLab(value, { + format: VAL_COMP + }) as ComputedColorChannels; + return [l, a, b, alpha]; + } + let x, y, z; + if (format === VAL_MIX) { + let xyz; + opt.d50 = true; + if (value.startsWith(FN_COLOR)) { + xyz = parseColorFunc(value, opt); + } else { + xyz = parseColorValue(value, opt); + } + if (xyz instanceof NullObject) { + return xyz; + } + [, x, y, z, alpha] = xyz as ComputedColorChannels; + } else if (value.startsWith(FN_COLOR)) { + [, x, y, z, alpha] = parseColorFunc(value, { + d50: true + }) as ComputedColorChannels; + } else { + [, x, y, z, alpha] = parseColorValue(value, { + d50: true + }) as ComputedColorChannels; + } + [l, a, b] = transformXyzD50ToLab([x, y, z], true); + return [l, a, b, alpha]; +}; + +/** + * convert color value to lch + * @param value - CSS color value + * @param [opt] - options + * @returns ColorChannels | NullObject - [l, c, h, alpha], hue may be powerless + */ +export const convertColorToLch = ( + value: string, + opt: Options = {} +): ColorChannels | [number, number, number | string, number] | NullObject => { + if (isString(value)) { + value = value.trim(); + } else { + throw new TypeError(`${value} is not a string.`); + } + const { format = '' } = opt; + let l, c, h, alpha; + if (REG_LCH.test(value)) { + [, l, c, h, alpha] = parseLch(value, { + format: VAL_COMP + }) as ComputedColorChannels; + return [l, c, h, alpha]; + } + let x, y, z; + if (format === VAL_MIX) { + let xyz; + opt.d50 = true; + if (value.startsWith(FN_COLOR)) { + xyz = parseColorFunc(value, opt); + } else { + xyz = parseColorValue(value, opt); + } + if (xyz instanceof NullObject) { + return xyz; + } + [, x, y, z, alpha] = xyz as ComputedColorChannels; + } else if (value.startsWith(FN_COLOR)) { + [, x, y, z, alpha] = parseColorFunc(value, { + d50: true + }) as ComputedColorChannels; + } else { + [, x, y, z, alpha] = parseColorValue(value, { + d50: true + }) as ComputedColorChannels; + } + [l, c, h] = transformXyzD50ToLch([x, y, z], true); + return [l, c, format === VAL_MIX && c === 0 ? NONE : h, alpha]; +}; + +/** + * convert color value to oklab + * @param value - CSS color value + * @param [opt] - options + * @returns ColorChannels | NullObject - [l, a, b, alpha] + */ +export const convertColorToOklab = ( + value: string, + opt: Options = {} +): ColorChannels | NullObject => { + if (isString(value)) { + value = value.trim(); + } else { + throw new TypeError(`${value} is not a string.`); + } + const { format = '' } = opt; + let l, a, b, alpha; + if (REG_OKLAB.test(value)) { + [, l, a, b, alpha] = parseOklab(value, { + format: VAL_COMP + }) as ComputedColorChannels; + return [l, a, b, alpha]; + } + let x, y, z; + if (format === VAL_MIX) { + let xyz; + if (value.startsWith(FN_COLOR)) { + xyz = parseColorFunc(value, opt); + } else { + xyz = parseColorValue(value, opt); + } + if (xyz instanceof NullObject) { + return xyz; + } + [, x, y, z, alpha] = xyz as ComputedColorChannels; + } else if (value.startsWith(FN_COLOR)) { + [, x, y, z, alpha] = parseColorFunc(value) as ComputedColorChannels; + } else { + [, x, y, z, alpha] = parseColorValue(value) as ComputedColorChannels; + } + [l, a, b] = transformXyzToOklab([x, y, z], true); + return [l, a, b, alpha]; +}; + +/** + * convert color value to oklch + * @param value - CSS color value + * @param [opt] - options + * @returns ColorChannels | NullObject - [l, c, h, alpha], hue may be powerless + */ +export const convertColorToOklch = ( + value: string, + opt: Options = {} +): ColorChannels | [number, number, number | string, number] | NullObject => { + if (isString(value)) { + value = value.trim(); + } else { + throw new TypeError(`${value} is not a string.`); + } + const { format = '' } = opt; + let l, c, h, alpha; + if (REG_OKLCH.test(value)) { + [, l, c, h, alpha] = parseOklch(value, { + format: VAL_COMP + }) as ComputedColorChannels; + return [l, c, h, alpha]; + } + let x, y, z; + if (format === VAL_MIX) { + let xyz; + if (value.startsWith(FN_COLOR)) { + xyz = parseColorFunc(value, opt); + } else { + xyz = parseColorValue(value, opt); + } + if (xyz instanceof NullObject) { + return xyz; + } + [, x, y, z, alpha] = xyz as ComputedColorChannels; + } else if (value.startsWith(FN_COLOR)) { + [, x, y, z, alpha] = parseColorFunc(value) as ComputedColorChannels; + } else { + [, x, y, z, alpha] = parseColorValue(value) as ComputedColorChannels; + } + [l, c, h] = transformXyzToOklch([x, y, z], true) as TriColorChannels; + return [l, c, format === VAL_MIX && c === 0 ? NONE : h, alpha]; +}; + +/** + * resolve color-mix() + * @param value - color-mix color value + * @param [opt] - options + * @returns resolved color - [cs, v1, v2, v3, alpha], '(empty)' + */ +export const resolveColorMix = ( + value: string, + opt: Options = {} +): SpecifiedColorChannels | string | NullObject => { + if (isString(value)) { + value = value.toLowerCase().trim(); + } else { + throw new TypeError(`${value} is not a string.`); + } + const { format = '', nullable = false } = opt; + const cacheKey: string = createCacheKey( + { + namespace: NAMESPACE, + name: 'resolveColorMix', + value + }, + opt + ); + const cachedResult = getCache(cacheKey); + if (cachedResult instanceof CacheItem) { + if (cachedResult.isNull) { + return cachedResult as NullObject; + } + const cachedItem = cachedResult.item; + if (isString(cachedItem)) { + return cachedItem as string; + } + return cachedItem as SpecifiedColorChannels; + } + const nestedItems = []; + let colorSpace = ''; + let hueArc = ''; + let colorA = ''; + let pctA = ''; + let colorB = ''; + let pctB = ''; + let parsed = false; + if (!REG_MIX.test(value)) { + // nested color-mix() + if (value.startsWith(FN_MIX) && REG_MIX_NEST.test(value)) { + const regColorSpace = new RegExp(`^(?:${CS_RGB}|${CS_XYZ})$`); + const items = value.match(REG_MIX_NEST) as RegExpMatchArray; + for (const item of items) { + if (item) { + let val = resolveColorMix(item, { + format: format === VAL_SPEC ? format : VAL_COMP + }) as ComputedColorChannels | string; + // computed value + if (Array.isArray(val)) { + const [cs, v1, v2, v3, v4] = val as ComputedColorChannels; + if (v1 === 0 && v2 === 0 && v3 === 0 && v4 === 0) { + value = ''; + break; + } + if (regColorSpace.test(cs)) { + if (v4 === 1) { + val = `color(${cs} ${v1} ${v2} ${v3})`; + } else { + val = `color(${cs} ${v1} ${v2} ${v3} / ${v4})`; + } + } else if (v4 === 1) { + val = `${cs}(${v1} ${v2} ${v3})`; + } else { + val = `${cs}(${v1} ${v2} ${v3} / ${v4})`; + } + } else if (!REG_MIX.test(val)) { + value = ''; + break; + } + nestedItems.push(val); + value = value.replace(item, val); + } + } + if (!value) { + const res = cacheInvalidColorValue(cacheKey, format, nullable); + return res; + } + // contains light-dark() + } else if ( + value.startsWith(FN_MIX) && + value.endsWith(')') && + value.includes(FN_LIGHT_DARK) + ) { + const regColorSpace = new RegExp(`in\\s+(${CS_MIX})`); + const colorParts = value.replace(FN_MIX, '').replace(/\)$/, ''); + const [csPart = '', partA = '', partB = ''] = splitValue(colorParts, { + delimiter: ',' + }); + const [colorPartA = '', pctPartA = ''] = splitValue(partA); + const [colorPartB = '', pctPartB = ''] = splitValue(partB); + const specifiedColorA = resolveColor(colorPartA, { + format: VAL_SPEC + }) as string; + const specifiedColorB = resolveColor(colorPartB, { + format: VAL_SPEC + }) as string; + if (regColorSpace.test(csPart) && specifiedColorA && specifiedColorB) { + if (format === VAL_SPEC) { + const [, cs] = csPart.match(regColorSpace) as MatchedRegExp; + if (REG_CS_HUE.test(cs)) { + [, colorSpace, hueArc] = cs.match(REG_CS_HUE) as MatchedRegExp; + } else { + colorSpace = cs; + } + colorA = specifiedColorA; + if (pctPartA) { + pctA = pctPartA; + } + colorB = specifiedColorB; + if (pctPartB) { + pctB = pctPartB; + } + value = value + .replace(colorPartA, specifiedColorA) + .replace(colorPartB, specifiedColorB); + parsed = true; + } else { + const resolvedColorA = resolveColor(colorPartA, opt); + const resolvedColorB = resolveColor(colorPartB, opt); + if (isString(resolvedColorA) && isString(resolvedColorB)) { + value = value + .replace(colorPartA, resolvedColorA) + .replace(colorPartB, resolvedColorB); + } + } + } else { + const res = cacheInvalidColorValue(cacheKey, format, nullable); + return res; + } + } else { + const res = cacheInvalidColorValue(cacheKey, format, nullable); + return res; + } + } + if (nestedItems.length && format === VAL_SPEC) { + const regColorSpace = new RegExp(`^color-mix\\(\\s*in\\s+(${CS_MIX})\\s*,`); + const [, cs] = value.match(regColorSpace) as MatchedRegExp; + if (REG_CS_HUE.test(cs)) { + [, colorSpace, hueArc] = cs.match(REG_CS_HUE) as MatchedRegExp; + } else { + colorSpace = cs; + } + if (nestedItems.length === 2) { + let [itemA, itemB] = nestedItems as [string, string]; + itemA = itemA.replace(/(?=[()])/g, '\\'); + itemB = itemB.replace(/(?=[()])/g, '\\'); + const regA = new RegExp(`(${itemA})(?:\\s+(${PCT}))?`); + const regB = new RegExp(`(${itemB})(?:\\s+(${PCT}))?`); + [, colorA, pctA] = value.match(regA) as MatchedRegExp; + [, colorB, pctB] = value.match(regB) as MatchedRegExp; + } else { + let [item] = nestedItems as [string]; + item = item.replace(/(?=[()])/g, '\\'); + const itemPart = `${item}(?:\\s+${PCT})?`; + const itemPartCapt = `(${item})(?:\\s+(${PCT}))?`; + const regItemPart = new RegExp(`^${itemPartCapt}$`); + const regLastItem = new RegExp(`${itemPartCapt}\\s*\\)$`); + const regColorPart = new RegExp(`^(${SYN_COLOR_TYPE})(?:\\s+(${PCT}))?$`); + // item is at the end + if (regLastItem.test(value)) { + const reg = new RegExp( + `(${SYN_MIX_PART})\\s*,\\s*(${itemPart})\\s*\\)$` + ); + const [, colorPartA, colorPartB] = value.match(reg) as MatchedRegExp; + [, colorA, pctA] = colorPartA.match(regColorPart) as MatchedRegExp; + [, colorB, pctB] = colorPartB.match(regItemPart) as MatchedRegExp; + } else { + const reg = new RegExp( + `(${itemPart})\\s*,\\s*(${SYN_MIX_PART})\\s*\\)$` + ); + const [, colorPartA, colorPartB] = value.match(reg) as MatchedRegExp; + [, colorA, pctA] = colorPartA.match(regItemPart) as MatchedRegExp; + [, colorB, pctB] = colorPartB.match(regColorPart) as MatchedRegExp; + } + } + } else if (!parsed) { + const [, cs, colorPartA, colorPartB] = value.match( + REG_MIX_CAPT + ) as MatchedRegExp; + const reg = new RegExp(`^(${SYN_COLOR_TYPE})(?:\\s+(${PCT}))?$`); + [, colorA, pctA] = colorPartA.match(reg) as MatchedRegExp; + [, colorB, pctB] = colorPartB.match(reg) as MatchedRegExp; + if (REG_CS_HUE.test(cs)) { + [, colorSpace, hueArc] = cs.match(REG_CS_HUE) as MatchedRegExp; + } else { + colorSpace = cs; + } + } + // normalize percentages and set multipler + let pA, pB, m; + if (pctA && pctB) { + const p1 = parseFloat(pctA) / MAX_PCT; + const p2 = parseFloat(pctB) / MAX_PCT; + if (p1 < 0 || p1 > 1 || p2 < 0 || p2 > 1 || (p1 === 0 && p2 === 0)) { + const res = cacheInvalidColorValue(cacheKey, format, nullable); + return res; + } + const factor = p1 + p2; + pA = p1 / factor; + pB = p2 / factor; + m = factor < 1 ? factor : 1; + } else { + if (pctA) { + pA = parseFloat(pctA) / MAX_PCT; + if (pA < 0 || pA > 1) { + const res = cacheInvalidColorValue(cacheKey, format, nullable); + return res; + } + pB = 1 - pA; + } else if (pctB) { + pB = parseFloat(pctB) / MAX_PCT; + if (pB < 0 || pB > 1) { + const res = cacheInvalidColorValue(cacheKey, format, nullable); + return res; + } + pA = 1 - pB; + } else { + pA = HALF; + pB = HALF; + } + m = 1; + } + if (colorSpace === 'xyz') { + colorSpace = 'xyz-d65'; + } + // specified value + if (format === VAL_SPEC) { + let valueA = ''; + let valueB = ''; + if (colorA.startsWith(FN_MIX) || colorA.startsWith(FN_LIGHT_DARK)) { + valueA = colorA; + } else if (colorA.startsWith(FN_COLOR)) { + const [cs, v1, v2, v3, v4] = parseColorFunc( + colorA, + opt + ) as SpecifiedColorChannels; + if (v4 === 1) { + valueA = `color(${cs} ${v1} ${v2} ${v3})`; + } else { + valueA = `color(${cs} ${v1} ${v2} ${v3} / ${v4})`; + } + } else { + const val = parseColorValue(colorA, opt); + if (Array.isArray(val)) { + const [cs, v1, v2, v3, v4] = val; + if (v4 === 1) { + if (cs === 'rgb') { + valueA = `${cs}(${v1}, ${v2}, ${v3})`; + } else { + valueA = `${cs}(${v1} ${v2} ${v3})`; + } + } else if (cs === 'rgb') { + valueA = `${cs}a(${v1}, ${v2}, ${v3}, ${v4})`; + } else { + valueA = `${cs}(${v1} ${v2} ${v3} / ${v4})`; + } + } else { + if (!isString(val) || !val) { + setCache(cacheKey, ''); + return ''; + } + valueA = val; + } + } + if (colorB.startsWith(FN_MIX) || colorB.startsWith(FN_LIGHT_DARK)) { + valueB = colorB; + } else if (colorB.startsWith(FN_COLOR)) { + const [cs, v1, v2, v3, v4] = parseColorFunc( + colorB, + opt + ) as SpecifiedColorChannels; + if (v4 === 1) { + valueB = `color(${cs} ${v1} ${v2} ${v3})`; + } else { + valueB = `color(${cs} ${v1} ${v2} ${v3} / ${v4})`; + } + } else { + const val = parseColorValue(colorB, opt); + if (Array.isArray(val)) { + const [cs, v1, v2, v3, v4] = val; + if (v4 === 1) { + if (cs === 'rgb') { + valueB = `${cs}(${v1}, ${v2}, ${v3})`; + } else { + valueB = `${cs}(${v1} ${v2} ${v3})`; + } + } else if (cs === 'rgb') { + valueB = `${cs}a(${v1}, ${v2}, ${v3}, ${v4})`; + } else { + valueB = `${cs}(${v1} ${v2} ${v3} / ${v4})`; + } + } else { + if (!isString(val) || !val) { + setCache(cacheKey, ''); + return ''; + } + valueB = val; + } + } + if (pctA && pctB) { + valueA += ` ${parseFloat(pctA)}%`; + valueB += ` ${parseFloat(pctB)}%`; + } else if (pctA) { + const pA = parseFloat(pctA); + if (pA !== MAX_PCT * HALF) { + valueA += ` ${pA}%`; + } + } else if (pctB) { + const pA = MAX_PCT - parseFloat(pctB); + if (pA !== MAX_PCT * HALF) { + valueA += ` ${pA}%`; + } + } + if (hueArc) { + const res = `color-mix(in ${colorSpace} ${hueArc} hue, ${valueA}, ${valueB})`; + setCache(cacheKey, res); + return res; + } else { + const res = `color-mix(in ${colorSpace}, ${valueA}, ${valueB})`; + setCache(cacheKey, res); + return res; + } + } + let r = 0; + let g = 0; + let b = 0; + let alpha = 0; + // in srgb, srgb-linear + if (/^srgb(?:-linear)?$/.test(colorSpace)) { + let rgbA, rgbB; + if (colorSpace === 'srgb') { + if (REG_CURRENT.test(colorA)) { + rgbA = [NONE, NONE, NONE, NONE]; + } else { + rgbA = convertColorToRgb(colorA, { + colorSpace, + format: VAL_MIX + }); + } + if (REG_CURRENT.test(colorB)) { + rgbB = [NONE, NONE, NONE, NONE]; + } else { + rgbB = convertColorToRgb(colorB, { + colorSpace, + format: VAL_MIX + }); + } + } else { + if (REG_CURRENT.test(colorA)) { + rgbA = [NONE, NONE, NONE, NONE]; + } else { + rgbA = convertColorToLinearRgb(colorA, { + colorSpace, + format: VAL_MIX + }); + } + if (REG_CURRENT.test(colorB)) { + rgbB = [NONE, NONE, NONE, NONE]; + } else { + rgbB = convertColorToLinearRgb(colorB, { + colorSpace, + format: VAL_MIX + }); + } + } + if (rgbA instanceof NullObject || rgbB instanceof NullObject) { + const res = cacheInvalidColorValue(cacheKey, format, nullable); + return res; + } + const [rrA, ggA, bbA, aaA] = rgbA as NumStrColorChannels; + const [rrB, ggB, bbB, aaB] = rgbB as NumStrColorChannels; + const rNone = rrA === NONE && rrB === NONE; + const gNone = ggA === NONE && ggB === NONE; + const bNone = bbA === NONE && bbB === NONE; + const alphaNone = aaA === NONE && aaB === NONE; + const [[rA, gA, bA, alphaA], [rB, gB, bB, alphaB]] = + normalizeColorComponents( + [rrA, ggA, bbA, aaA], + [rrB, ggB, bbB, aaB], + true + ); + const factorA = alphaA * pA; + const factorB = alphaB * pB; + alpha = factorA + factorB; + if (alpha === 0) { + r = rA * pA + rB * pB; + g = gA * pA + gB * pB; + b = bA * pA + bB * pB; + } else { + r = (rA * factorA + rB * factorB) / alpha; + g = (gA * factorA + gB * factorB) / alpha; + b = (bA * factorA + bB * factorB) / alpha; + alpha = parseFloat(alpha.toFixed(3)); + } + if (format === VAL_COMP) { + const res: SpecifiedColorChannels = [ + colorSpace, + rNone ? NONE : roundToPrecision(r, HEX), + gNone ? NONE : roundToPrecision(g, HEX), + bNone ? NONE : roundToPrecision(b, HEX), + alphaNone ? NONE : alpha * m + ]; + setCache(cacheKey, res); + return res; + } + r *= MAX_RGB; + g *= MAX_RGB; + b *= MAX_RGB; + // in xyz, xyz-d65, xyz-d50 + } else if (REG_CS_XYZ.test(colorSpace)) { + let xyzA, xyzB; + if (REG_CURRENT.test(colorA)) { + xyzA = [NONE, NONE, NONE, NONE]; + } else { + xyzA = convertColorToXyz(colorA, { + colorSpace, + d50: colorSpace === 'xyz-d50', + format: VAL_MIX + }); + } + if (REG_CURRENT.test(colorB)) { + xyzB = [NONE, NONE, NONE, NONE]; + } else { + xyzB = convertColorToXyz(colorB, { + colorSpace, + d50: colorSpace === 'xyz-d50', + format: VAL_MIX + }); + } + if (xyzA instanceof NullObject || xyzB instanceof NullObject) { + const res = cacheInvalidColorValue(cacheKey, format, nullable); + return res; + } + const [xxA, yyA, zzA, aaA] = xyzA; + const [xxB, yyB, zzB, aaB] = xyzB; + const xNone = xxA === NONE && xxB === NONE; + const yNone = yyA === NONE && yyB === NONE; + const zNone = zzA === NONE && zzB === NONE; + const alphaNone = aaA === NONE && aaB === NONE; + const [[xA, yA, zA, alphaA], [xB, yB, zB, alphaB]] = + normalizeColorComponents( + [xxA, yyA, zzA, aaA], + [xxB, yyB, zzB, aaB], + true + ); + const factorA = alphaA * pA; + const factorB = alphaB * pB; + alpha = factorA + factorB; + let x, y, z; + if (alpha === 0) { + x = xA * pA + xB * pB; + y = yA * pA + yB * pB; + z = zA * pA + zB * pB; + } else { + x = (xA * factorA + xB * factorB) / alpha; + y = (yA * factorA + yB * factorB) / alpha; + z = (zA * factorA + zB * factorB) / alpha; + alpha = parseFloat(alpha.toFixed(3)); + } + if (format === VAL_COMP) { + const res: SpecifiedColorChannels = [ + colorSpace, + xNone ? NONE : roundToPrecision(x, HEX), + yNone ? NONE : roundToPrecision(y, HEX), + zNone ? NONE : roundToPrecision(z, HEX), + alphaNone ? NONE : alpha * m + ]; + setCache(cacheKey, res); + return res; + } + if (colorSpace === 'xyz-d50') { + [r, g, b] = transformXyzD50ToRgb([x, y, z], true); + } else { + [r, g, b] = transformXyzToRgb([x, y, z], true); + } + // in hsl, hwb + } else if (/^h(?:sl|wb)$/.test(colorSpace)) { + let hslA, hslB; + if (colorSpace === 'hsl') { + if (REG_CURRENT.test(colorA)) { + hslA = [NONE, NONE, NONE, NONE]; + } else { + hslA = convertColorToHsl(colorA, { + colorSpace, + format: VAL_MIX + }); + } + if (REG_CURRENT.test(colorB)) { + hslB = [NONE, NONE, NONE, NONE]; + } else { + hslB = convertColorToHsl(colorB, { + colorSpace, + format: VAL_MIX + }); + } + } else { + if (REG_CURRENT.test(colorA)) { + hslA = [NONE, NONE, NONE, NONE]; + } else { + hslA = convertColorToHwb(colorA, { + colorSpace, + format: VAL_MIX + }); + } + if (REG_CURRENT.test(colorB)) { + hslB = [NONE, NONE, NONE, NONE]; + } else { + hslB = convertColorToHwb(colorB, { + colorSpace, + format: VAL_MIX + }); + } + } + if (hslA instanceof NullObject || hslB instanceof NullObject) { + const res = cacheInvalidColorValue(cacheKey, format, nullable); + return res; + } + const [hhA, ssA, llA, aaA] = hslA; + const [hhB, ssB, llB, aaB] = hslB; + const alphaNone = aaA === NONE && aaB === NONE; + let [[hA, sA, lA, alphaA], [hB, sB, lB, alphaB]] = normalizeColorComponents( + [hhA, ssA, llA, aaA], + [hhB, ssB, llB, aaB], + true + ); + if (hueArc) { + [hA, hB] = interpolateHue(hA, hB, hueArc); + } + const factorA = alphaA * pA; + const factorB = alphaB * pB; + alpha = factorA + factorB; + const h = (hA * pA + hB * pB) % DEG; + let s, l; + if (alpha === 0) { + s = sA * pA + sB * pB; + l = lA * pA + lB * pB; + } else { + s = (sA * factorA + sB * factorB) / alpha; + l = (lA * factorA + lB * factorB) / alpha; + alpha = parseFloat(alpha.toFixed(3)); + } + [r, g, b] = convertColorToRgb( + `${colorSpace}(${h} ${s} ${l})` + ) as ColorChannels; + if (format === VAL_COMP) { + const res: SpecifiedColorChannels = [ + 'srgb', + roundToPrecision(r / MAX_RGB, HEX), + roundToPrecision(g / MAX_RGB, HEX), + roundToPrecision(b / MAX_RGB, HEX), + alphaNone ? NONE : alpha * m + ]; + setCache(cacheKey, res); + return res; + } + // in lch, oklch + } else if (/^(?:ok)?lch$/.test(colorSpace)) { + let lchA, lchB; + if (colorSpace === 'lch') { + if (REG_CURRENT.test(colorA)) { + lchA = [NONE, NONE, NONE, NONE]; + } else { + lchA = convertColorToLch(colorA, { + colorSpace, + format: VAL_MIX + }); + } + if (REG_CURRENT.test(colorB)) { + lchB = [NONE, NONE, NONE, NONE]; + } else { + lchB = convertColorToLch(colorB, { + colorSpace, + format: VAL_MIX + }); + } + } else { + if (REG_CURRENT.test(colorA)) { + lchA = [NONE, NONE, NONE, NONE]; + } else { + lchA = convertColorToOklch(colorA, { + colorSpace, + format: VAL_MIX + }); + } + if (REG_CURRENT.test(colorB)) { + lchB = [NONE, NONE, NONE, NONE]; + } else { + lchB = convertColorToOklch(colorB, { + colorSpace, + format: VAL_MIX + }); + } + } + if (lchA instanceof NullObject || lchB instanceof NullObject) { + const res = cacheInvalidColorValue(cacheKey, format, nullable); + return res; + } + const [llA, ccA, hhA, aaA] = lchA; + const [llB, ccB, hhB, aaB] = lchB; + const lNone = llA === NONE && llB === NONE; + const cNone = ccA === NONE && ccB === NONE; + const hNone = hhA === NONE && hhB === NONE; + const alphaNone = aaA === NONE && aaB === NONE; + let [[lA, cA, hA, alphaA], [lB, cB, hB, alphaB]] = normalizeColorComponents( + [llA, ccA, hhA, aaA], + [llB, ccB, hhB, aaB], + true + ); + if (hueArc) { + [hA, hB] = interpolateHue(hA, hB, hueArc); + } + const factorA = alphaA * pA; + const factorB = alphaB * pB; + alpha = factorA + factorB; + const h = (hA * pA + hB * pB) % DEG; + let l, c; + if (alpha === 0) { + l = lA * pA + lB * pB; + c = cA * pA + cB * pB; + } else { + l = (lA * factorA + lB * factorB) / alpha; + c = (cA * factorA + cB * factorB) / alpha; + alpha = parseFloat(alpha.toFixed(3)); + } + if (format === VAL_COMP) { + const res: SpecifiedColorChannels = [ + colorSpace, + lNone ? NONE : roundToPrecision(l, HEX), + cNone ? NONE : roundToPrecision(c, HEX), + hNone ? NONE : roundToPrecision(h, HEX), + alphaNone ? NONE : alpha * m + ]; + setCache(cacheKey, res); + return res; + } + [, r, g, b] = resolveColorValue( + `${colorSpace}(${l} ${c} ${h})` + ) as ComputedColorChannels; + // in lab, oklab + } else { + let labA, labB; + if (colorSpace === 'lab') { + if (REG_CURRENT.test(colorA)) { + labA = [NONE, NONE, NONE, NONE]; + } else { + labA = convertColorToLab(colorA, { + colorSpace, + format: VAL_MIX + }); + } + if (REG_CURRENT.test(colorB)) { + labB = [NONE, NONE, NONE, NONE]; + } else { + labB = convertColorToLab(colorB, { + colorSpace, + format: VAL_MIX + }); + } + } else { + if (REG_CURRENT.test(colorA)) { + labA = [NONE, NONE, NONE, NONE]; + } else { + labA = convertColorToOklab(colorA, { + colorSpace, + format: VAL_MIX + }); + } + if (REG_CURRENT.test(colorB)) { + labB = [NONE, NONE, NONE, NONE]; + } else { + labB = convertColorToOklab(colorB, { + colorSpace, + format: VAL_MIX + }); + } + } + if (labA instanceof NullObject || labB instanceof NullObject) { + const res = cacheInvalidColorValue(cacheKey, format, nullable); + return res; + } + const [llA, aaA, bbA, alA] = labA; + const [llB, aaB, bbB, alB] = labB; + const lNone = llA === NONE && llB === NONE; + const aNone = aaA === NONE && aaB === NONE; + const bNone = bbA === NONE && bbB === NONE; + const alphaNone = alA === NONE && alB === NONE; + const [[lA, aA, bA, alphaA], [lB, aB, bB, alphaB]] = + normalizeColorComponents( + [llA, aaA, bbA, alA], + [llB, aaB, bbB, alB], + true + ); + const factorA = alphaA * pA; + const factorB = alphaB * pB; + alpha = factorA + factorB; + let l, aO, bO; + if (alpha === 0) { + l = lA * pA + lB * pB; + aO = aA * pA + aB * pB; + bO = bA * pA + bB * pB; + } else { + l = (lA * factorA + lB * factorB) / alpha; + aO = (aA * factorA + aB * factorB) / alpha; + bO = (bA * factorA + bB * factorB) / alpha; + alpha = parseFloat(alpha.toFixed(3)); + } + if (format === VAL_COMP) { + const res: SpecifiedColorChannels = [ + colorSpace, + lNone ? NONE : roundToPrecision(l, HEX), + aNone ? NONE : roundToPrecision(aO, HEX), + bNone ? NONE : roundToPrecision(bO, HEX), + alphaNone ? NONE : alpha * m + ]; + setCache(cacheKey, res); + return res; + } + [, r, g, b] = resolveColorValue( + `${colorSpace}(${l} ${aO} ${bO})` + ) as ComputedColorChannels; + } + const res: SpecifiedColorChannels = [ + 'rgb', + Math.round(r), + Math.round(g), + Math.round(b), + parseFloat((alpha * m).toFixed(3)) + ]; + setCache(cacheKey, res); + return res; +}; diff --git a/node_modules/@asamuzakjp/css-color/src/js/common.ts b/node_modules/@asamuzakjp/css-color/src/js/common.ts new file mode 100644 index 00000000..32bf8bdc --- /dev/null +++ b/node_modules/@asamuzakjp/css-color/src/js/common.ts @@ -0,0 +1,31 @@ +/** + * common + */ + +/* numeric constants */ +const TYPE_FROM = 8; +const TYPE_TO = -1; + +/** + * get type + * @param o - object to check + * @returns type of object + */ +export const getType = (o: unknown): string => + Object.prototype.toString.call(o).slice(TYPE_FROM, TYPE_TO); + +/** + * is string + * @param o - object to check + * @returns result + */ +export const isString = (o: unknown): o is string => + typeof o === 'string' || o instanceof String; + +/** + * is string or number + * @param o - object to check + * @returns result + */ +export const isStringOrNumber = (o: unknown): boolean => + isString(o) || typeof o === 'number'; diff --git a/node_modules/@asamuzakjp/css-color/src/js/constant.ts b/node_modules/@asamuzakjp/css-color/src/js/constant.ts new file mode 100644 index 00000000..b3311814 --- /dev/null +++ b/node_modules/@asamuzakjp/css-color/src/js/constant.ts @@ -0,0 +1,68 @@ +/** + * constant + */ + +/* values and units */ +const _DIGIT = '(?:0|[1-9]\\d*)'; +const _COMPARE = 'clamp|max|min'; +const _EXPO = 'exp|hypot|log|pow|sqrt'; +const _SIGN = 'abs|sign'; +const _STEP = 'mod|rem|round'; +const _TRIG = 'a?(?:cos|sin|tan)|atan2'; +const _MATH = `${_COMPARE}|${_EXPO}|${_SIGN}|${_STEP}|${_TRIG}`; +const _CALC = `calc|${_MATH}`; +const _VAR = `var|${_CALC}`; +export const ANGLE = 'deg|g?rad|turn'; +export const LENGTH = + '[cm]m|[dls]?v(?:[bhiw]|max|min)|in|p[ctx]|q|r?(?:[cl]h|cap|e[mx]|ic)'; +export const NUM = `[+-]?(?:${_DIGIT}(?:\\.\\d*)?|\\.\\d+)(?:e-?${_DIGIT})?`; +export const NUM_POSITIVE = `\\+?(?:${_DIGIT}(?:\\.\\d*)?|\\.\\d+)(?:e-?${_DIGIT})?`; +export const NONE = 'none'; +export const PCT = `${NUM}%`; +export const SYN_FN_CALC = `^(?:${_CALC})\\(|(?<=[*\\/\\s\\(])(?:${_CALC})\\(`; +export const SYN_FN_MATH_START = `^(?:${_MATH})\\($`; +export const SYN_FN_VAR = '^var\\(|(?<=[*\\/\\s\\(])var\\('; +export const SYN_FN_VAR_START = `^(?:${_VAR})\\(`; + +/* colors */ +const _ALPHA = `(?:\\s*\\/\\s*(?:${NUM}|${PCT}|${NONE}))?`; +const _ALPHA_LV3 = `(?:\\s*,\\s*(?:${NUM}|${PCT}))?`; +const _COLOR_FUNC = '(?:ok)?l(?:ab|ch)|color|hsla?|hwb|rgba?'; +const _COLOR_KEY = '[a-z]+|#[\\da-f]{3}|#[\\da-f]{4}|#[\\da-f]{6}|#[\\da-f]{8}'; +const _CS_HUE = '(?:ok)?lch|hsl|hwb'; +const _CS_HUE_ARC = '(?:de|in)creasing|longer|shorter'; +const _NUM_ANGLE = `${NUM}(?:${ANGLE})?`; +const _NUM_ANGLE_NONE = `(?:${NUM}(?:${ANGLE})?|${NONE})`; +const _NUM_PCT_NONE = `(?:${NUM}|${PCT}|${NONE})`; +export const CS_HUE = `(?:${_CS_HUE})(?:\\s(?:${_CS_HUE_ARC})\\shue)?`; +export const CS_HUE_CAPT = `(${_CS_HUE})(?:\\s(${_CS_HUE_ARC})\\shue)?`; +export const CS_LAB = '(?:ok)?lab'; +export const CS_LCH = '(?:ok)?lch'; +export const CS_SRGB = 'srgb(?:-linear)?'; +export const CS_RGB = `(?:a98|prophoto)-rgb|display-p3|rec2020|${CS_SRGB}`; +export const CS_XYZ = 'xyz(?:-d(?:50|65))?'; +export const CS_RECT = `${CS_LAB}|${CS_RGB}|${CS_XYZ}`; +export const CS_MIX = `${CS_HUE}|${CS_RECT}`; +export const FN_COLOR = 'color('; +export const FN_LIGHT_DARK = 'light-dark('; +export const FN_MIX = 'color-mix('; +export const FN_REL = `(?:${_COLOR_FUNC})\\(\\s*from\\s+`; +export const FN_REL_CAPT = `(${_COLOR_FUNC})\\(\\s*from\\s+`; +export const FN_VAR = 'var('; +export const SYN_FN_COLOR = `(?:${CS_RGB}|${CS_XYZ})(?:\\s+${_NUM_PCT_NONE}){3}${_ALPHA}`; +export const SYN_FN_LIGHT_DARK = '^light-dark\\('; +export const SYN_FN_REL = `^${FN_REL}|(?<=[\\s])${FN_REL}`; +export const SYN_HSL = `${_NUM_ANGLE_NONE}(?:\\s+${_NUM_PCT_NONE}){2}${_ALPHA}`; +export const SYN_HSL_LV3 = `${_NUM_ANGLE}(?:\\s*,\\s*${PCT}){2}${_ALPHA_LV3}`; +export const SYN_LCH = `(?:${_NUM_PCT_NONE}\\s+){2}${_NUM_ANGLE_NONE}${_ALPHA}`; +export const SYN_MOD = `${_NUM_PCT_NONE}(?:\\s+${_NUM_PCT_NONE}){2}${_ALPHA}`; +export const SYN_RGB_LV3 = `(?:${NUM}(?:\\s*,\\s*${NUM}){2}|${PCT}(?:\\s*,\\s*${PCT}){2})${_ALPHA_LV3}`; +export const SYN_COLOR_TYPE = `${_COLOR_KEY}|hsla?\\(\\s*${SYN_HSL_LV3}\\s*\\)|rgba?\\(\\s*${SYN_RGB_LV3}\\s*\\)|(?:hsla?|hwb)\\(\\s*${SYN_HSL}\\s*\\)|(?:(?:ok)?lab|rgba?)\\(\\s*${SYN_MOD}\\s*\\)|(?:ok)?lch\\(\\s*${SYN_LCH}\\s*\\)|color\\(\\s*${SYN_FN_COLOR}\\s*\\)`; +export const SYN_MIX_PART = `(?:${SYN_COLOR_TYPE})(?:\\s+${PCT})?`; +export const SYN_MIX = `color-mix\\(\\s*in\\s+(?:${CS_MIX})\\s*,\\s*${SYN_MIX_PART}\\s*,\\s*${SYN_MIX_PART}\\s*\\)`; +export const SYN_MIX_CAPT = `color-mix\\(\\s*in\\s+(${CS_MIX})\\s*,\\s*(${SYN_MIX_PART})\\s*,\\s*(${SYN_MIX_PART})\\s*\\)`; + +/* formats */ +export const VAL_COMP = 'computedValue'; +export const VAL_MIX = 'mixValue'; +export const VAL_SPEC = 'specifiedValue'; diff --git a/node_modules/@asamuzakjp/css-color/src/js/convert.ts b/node_modules/@asamuzakjp/css-color/src/js/convert.ts new file mode 100644 index 00000000..bcde6db2 --- /dev/null +++ b/node_modules/@asamuzakjp/css-color/src/js/convert.ts @@ -0,0 +1,469 @@ +/** + * convert + */ + +import { + CacheItem, + NullObject, + createCacheKey, + getCache, + setCache +} from './cache'; +import { + convertColorToHsl, + convertColorToHwb, + convertColorToLab, + convertColorToLch, + convertColorToOklab, + convertColorToOklch, + convertColorToRgb, + numberToHexString, + parseColorFunc, + parseColorValue +} from './color'; +import { isString } from './common'; +import { cssCalc } from './css-calc'; +import { resolveVar } from './css-var'; +import { resolveRelativeColor } from './relative-color'; +import { resolveColor } from './resolve'; +import { ColorChannels, ComputedColorChannels, Options } from './typedef'; + +/* constants */ +import { SYN_FN_CALC, SYN_FN_REL, SYN_FN_VAR, VAL_COMP } from './constant'; +const NAMESPACE = 'convert'; + +/* regexp */ +const REG_FN_CALC = new RegExp(SYN_FN_CALC); +const REG_FN_REL = new RegExp(SYN_FN_REL); +const REG_FN_VAR = new RegExp(SYN_FN_VAR); + +/** + * pre process + * @param value - CSS color value + * @param [opt] - options + * @returns value + */ +export const preProcess = ( + value: string, + opt: Options = {} +): string | NullObject => { + if (isString(value)) { + value = value.trim(); + if (!value) { + return new NullObject(); + } + } else { + return new NullObject(); + } + const cacheKey: string = createCacheKey( + { + namespace: NAMESPACE, + name: 'preProcess', + value + }, + opt + ); + const cachedResult = getCache(cacheKey); + if (cachedResult instanceof CacheItem) { + if (cachedResult.isNull) { + return cachedResult as NullObject; + } + return cachedResult.item as string; + } + if (REG_FN_VAR.test(value)) { + const resolvedValue = resolveVar(value, opt); + if (isString(resolvedValue)) { + value = resolvedValue; + } else { + setCache(cacheKey, null); + return new NullObject(); + } + } + if (REG_FN_REL.test(value)) { + const resolvedValue = resolveRelativeColor(value, opt); + if (isString(resolvedValue)) { + value = resolvedValue; + } else { + setCache(cacheKey, null); + return new NullObject(); + } + } else if (REG_FN_CALC.test(value)) { + value = cssCalc(value, opt); + } + if (value.startsWith('color-mix')) { + const clonedOpt = structuredClone(opt); + clonedOpt.format = VAL_COMP; + clonedOpt.nullable = true; + const resolvedValue = resolveColor(value, clonedOpt); + setCache(cacheKey, resolvedValue); + return resolvedValue; + } + setCache(cacheKey, value); + return value; +}; + +/** + * convert number to hex string + * @param value - numeric value + * @returns hex string: 00..ff + */ +export const numberToHex = (value: number): string => { + const hex = numberToHexString(value); + return hex; +}; + +/** + * convert color to hex + * @param value - CSS color value + * @param [opt] - options + * @param [opt.alpha] - enable alpha channel + * @returns #rrggbb | #rrggbbaa | null + */ +export const colorToHex = (value: string, opt: Options = {}): string | null => { + if (isString(value)) { + const resolvedValue = preProcess(value, opt); + if (resolvedValue instanceof NullObject) { + return null; + } + value = resolvedValue.toLowerCase(); + } else { + throw new TypeError(`${value} is not a string.`); + } + const { alpha = false } = opt; + const cacheKey: string = createCacheKey( + { + namespace: NAMESPACE, + name: 'colorToHex', + value + }, + opt + ); + const cachedResult = getCache(cacheKey); + if (cachedResult instanceof CacheItem) { + if (cachedResult.isNull) { + return null; + } + return cachedResult.item as string; + } + let hex; + opt.nullable = true; + if (alpha) { + opt.format = 'hexAlpha'; + hex = resolveColor(value, opt); + } else { + opt.format = 'hex'; + hex = resolveColor(value, opt); + } + if (isString(hex)) { + setCache(cacheKey, hex); + return hex; + } + setCache(cacheKey, null); + return null; +}; + +/** + * convert color to hsl + * @param value - CSS color value + * @param [opt] - options + * @returns ColorChannels - [h, s, l, alpha] + */ +export const colorToHsl = (value: string, opt: Options = {}): ColorChannels => { + if (isString(value)) { + const resolvedValue = preProcess(value, opt); + if (resolvedValue instanceof NullObject) { + return [0, 0, 0, 0]; + } + value = resolvedValue.toLowerCase(); + } else { + throw new TypeError(`${value} is not a string.`); + } + const cacheKey: string = createCacheKey( + { + namespace: NAMESPACE, + name: 'colorToHsl', + value + }, + opt + ); + const cachedResult = getCache(cacheKey); + if (cachedResult instanceof CacheItem) { + return cachedResult.item as ColorChannels; + } + opt.format = 'hsl'; + const hsl = convertColorToHsl(value, opt) as ColorChannels; + setCache(cacheKey, hsl); + return hsl; +}; + +/** + * convert color to hwb + * @param value - CSS color value + * @param [opt] - options + * @returns ColorChannels - [h, w, b, alpha] + */ +export const colorToHwb = (value: string, opt: Options = {}): ColorChannels => { + if (isString(value)) { + const resolvedValue = preProcess(value, opt); + if (resolvedValue instanceof NullObject) { + return [0, 0, 0, 0]; + } + value = resolvedValue.toLowerCase(); + } else { + throw new TypeError(`${value} is not a string.`); + } + const cacheKey: string = createCacheKey( + { + namespace: NAMESPACE, + name: 'colorToHwb', + value + }, + opt + ); + const cachedResult = getCache(cacheKey); + if (cachedResult instanceof CacheItem) { + return cachedResult.item as ColorChannels; + } + opt.format = 'hwb'; + const hwb = convertColorToHwb(value, opt) as ColorChannels; + setCache(cacheKey, hwb); + return hwb; +}; + +/** + * convert color to lab + * @param value - CSS color value + * @param [opt] - options + * @returns ColorChannels - [l, a, b, alpha] + */ +export const colorToLab = (value: string, opt: Options = {}): ColorChannels => { + if (isString(value)) { + const resolvedValue = preProcess(value, opt); + if (resolvedValue instanceof NullObject) { + return [0, 0, 0, 0]; + } + value = resolvedValue.toLowerCase(); + } else { + throw new TypeError(`${value} is not a string.`); + } + const cacheKey: string = createCacheKey( + { + namespace: NAMESPACE, + name: 'colorToLab', + value + }, + opt + ); + const cachedResult = getCache(cacheKey); + if (cachedResult instanceof CacheItem) { + return cachedResult.item as ColorChannels; + } + const lab = convertColorToLab(value, opt) as ColorChannels; + setCache(cacheKey, lab); + return lab; +}; + +/** + * convert color to lch + * @param value - CSS color value + * @param [opt] - options + * @returns ColorChannels - [l, c, h, alpha] + */ +export const colorToLch = (value: string, opt: Options = {}): ColorChannels => { + if (isString(value)) { + const resolvedValue = preProcess(value, opt); + if (resolvedValue instanceof NullObject) { + return [0, 0, 0, 0]; + } + value = resolvedValue.toLowerCase(); + } else { + throw new TypeError(`${value} is not a string.`); + } + const cacheKey: string = createCacheKey( + { + namespace: NAMESPACE, + name: 'colorToLch', + value + }, + opt + ); + const cachedResult = getCache(cacheKey); + if (cachedResult instanceof CacheItem) { + return cachedResult.item as ColorChannels; + } + const lch = convertColorToLch(value, opt) as ColorChannels; + setCache(cacheKey, lch); + return lch; +}; + +/** + * convert color to oklab + * @param value - CSS color value + * @param [opt] - options + * @returns ColorChannels - [l, a, b, alpha] + */ +export const colorToOklab = ( + value: string, + opt: Options = {} +): ColorChannels => { + if (isString(value)) { + const resolvedValue = preProcess(value, opt); + if (resolvedValue instanceof NullObject) { + return [0, 0, 0, 0]; + } + value = resolvedValue.toLowerCase(); + } else { + throw new TypeError(`${value} is not a string.`); + } + const cacheKey: string = createCacheKey( + { + namespace: NAMESPACE, + name: 'colorToOklab', + value + }, + opt + ); + const cachedResult = getCache(cacheKey); + if (cachedResult instanceof CacheItem) { + return cachedResult.item as ColorChannels; + } + const lab = convertColorToOklab(value, opt) as ColorChannels; + setCache(cacheKey, lab); + return lab; +}; + +/** + * convert color to oklch + * @param value - CSS color value + * @param [opt] - options + * @returns ColorChannels - [l, c, h, alpha] + */ +export const colorToOklch = ( + value: string, + opt: Options = {} +): ColorChannels => { + if (isString(value)) { + const resolvedValue = preProcess(value, opt); + if (resolvedValue instanceof NullObject) { + return [0, 0, 0, 0]; + } + value = resolvedValue.toLowerCase(); + } else { + throw new TypeError(`${value} is not a string.`); + } + const cacheKey: string = createCacheKey( + { + namespace: NAMESPACE, + name: 'colorToOklch', + value + }, + opt + ); + const cachedResult = getCache(cacheKey); + if (cachedResult instanceof CacheItem) { + return cachedResult.item as ColorChannels; + } + const lch = convertColorToOklch(value, opt) as ColorChannels; + setCache(cacheKey, lch); + return lch; +}; + +/** + * convert color to rgb + * @param value - CSS color value + * @param [opt] - options + * @returns ColorChannels - [r, g, b, alpha] + */ +export const colorToRgb = (value: string, opt: Options = {}): ColorChannels => { + if (isString(value)) { + const resolvedValue = preProcess(value, opt); + if (resolvedValue instanceof NullObject) { + return [0, 0, 0, 0]; + } + value = resolvedValue.toLowerCase(); + } else { + throw new TypeError(`${value} is not a string.`); + } + const cacheKey: string = createCacheKey( + { + namespace: NAMESPACE, + name: 'colorToRgb', + value + }, + opt + ); + const cachedResult = getCache(cacheKey); + if (cachedResult instanceof CacheItem) { + return cachedResult.item as ColorChannels; + } + const rgb = convertColorToRgb(value, opt) as ColorChannels; + setCache(cacheKey, rgb); + return rgb; +}; + +/** + * convert color to xyz + * @param value - CSS color value + * @param [opt] - options + * @returns ColorChannels - [x, y, z, alpha] + */ +export const colorToXyz = (value: string, opt: Options = {}): ColorChannels => { + if (isString(value)) { + const resolvedValue = preProcess(value, opt); + if (resolvedValue instanceof NullObject) { + return [0, 0, 0, 0]; + } + value = resolvedValue.toLowerCase(); + } else { + throw new TypeError(`${value} is not a string.`); + } + const cacheKey: string = createCacheKey( + { + namespace: NAMESPACE, + name: 'colorToXyz', + value + }, + opt + ); + const cachedResult = getCache(cacheKey); + if (cachedResult instanceof CacheItem) { + return cachedResult.item as ColorChannels; + } + let xyz; + if (value.startsWith('color(')) { + [, ...xyz] = parseColorFunc(value, opt) as ComputedColorChannels; + } else { + [, ...xyz] = parseColorValue(value, opt) as ComputedColorChannels; + } + setCache(cacheKey, xyz); + return xyz as ColorChannels; +}; + +/** + * convert color to xyz-d50 + * @param value - CSS color value + * @param [opt] - options + * @returns ColorChannels - [x, y, z, alpha] + */ +export const colorToXyzD50 = ( + value: string, + opt: Options = {} +): ColorChannels => { + opt.d50 = true; + return colorToXyz(value, opt); +}; + +/* convert */ +export const convert = { + colorToHex, + colorToHsl, + colorToHwb, + colorToLab, + colorToLch, + colorToOklab, + colorToOklch, + colorToRgb, + colorToXyz, + colorToXyzD50, + numberToHex +}; diff --git a/node_modules/@asamuzakjp/css-color/src/js/css-calc.ts b/node_modules/@asamuzakjp/css-color/src/js/css-calc.ts new file mode 100644 index 00000000..fca84c28 --- /dev/null +++ b/node_modules/@asamuzakjp/css-color/src/js/css-calc.ts @@ -0,0 +1,935 @@ +/** + * css-calc + */ + +import { calc, conversionOptions as CalcOptions } from '@csstools/css-calc'; +import { CSSToken, TokenType, tokenize } from '@csstools/css-tokenizer'; +import { + CacheItem, + NullObject, + createCacheKey, + getCache, + setCache +} from './cache'; +import { isString, isStringOrNumber } from './common'; +import { resolveVar } from './css-var'; +import { resolveLengthInPixels, roundToPrecision } from './util'; +import { MatchedRegExp, Options } from './typedef'; + +/* constants */ +import { + ANGLE, + LENGTH, + NUM, + SYN_FN_CALC, + SYN_FN_MATH_START, + SYN_FN_VAR, + SYN_FN_VAR_START, + VAL_SPEC +} from './constant'; +const { + CloseParen: PAREN_CLOSE, + Comment: COMMENT, + Dimension: DIM, + EOF, + Function: FUNC, + OpenParen: PAREN_OPEN, + Whitespace: W_SPACE +} = TokenType; +const NAMESPACE = 'css-calc'; + +/* numeric constants */ +const TRIA = 3; +const HEX = 16; +const MAX_PCT = 100; + +/* regexp */ +const REG_FN_CALC = new RegExp(SYN_FN_CALC); +const REG_FN_CALC_NUM = new RegExp(`^calc\\((${NUM})\\)$`); +const REG_FN_MATH_START = new RegExp(SYN_FN_MATH_START); +const REG_FN_VAR = new RegExp(SYN_FN_VAR); +const REG_FN_VAR_START = new RegExp(SYN_FN_VAR_START); +const REG_OPERATOR = /\s[*+/-]\s/; +const REG_TYPE_DIM = new RegExp(`^(${NUM})(${ANGLE}|${LENGTH})$`); +const REG_TYPE_DIM_PCT = new RegExp(`^(${NUM})(${ANGLE}|${LENGTH}|%)$`); +const REG_TYPE_PCT = new RegExp(`^(${NUM})%$`); + +/** + * Calclator + */ +export class Calculator { + /* private */ + // number + #hasNum: boolean; + #numSum: number[]; + #numMul: number[]; + // percentage + #hasPct: boolean; + #pctSum: number[]; + #pctMul: number[]; + // dimension + #hasDim: boolean; + #dimSum: string[]; + #dimSub: string[]; + #dimMul: string[]; + #dimDiv: string[]; + // et cetra + #hasEtc: boolean; + #etcSum: string[]; + #etcSub: string[]; + #etcMul: string[]; + #etcDiv: string[]; + // calc options + #calcOpts: CalcOptions; + + /** + * constructor + */ + constructor() { + // number + this.#hasNum = false; + this.#numSum = []; + this.#numMul = []; + // percentage + this.#hasPct = false; + this.#pctSum = []; + this.#pctMul = []; + // dimension + this.#hasDim = false; + this.#dimSum = []; + this.#dimSub = []; + this.#dimMul = []; + this.#dimDiv = []; + // et cetra + this.#hasEtc = false; + this.#etcSum = []; + this.#etcSub = []; + this.#etcMul = []; + this.#etcDiv = []; + // calc options + this.#calcOpts = { + toCanonicalUnits: true + }; + } + + get hasNum() { + return this.#hasNum; + } + + set hasNum(value: boolean) { + this.#hasNum = !!value; + } + + get numSum() { + return this.#numSum; + } + + get numMul() { + return this.#numMul; + } + + get hasPct() { + return this.#hasPct; + } + + set hasPct(value: boolean) { + this.#hasPct = !!value; + } + + get pctSum() { + return this.#pctSum; + } + + get pctMul() { + return this.#pctMul; + } + + get hasDim() { + return this.#hasDim; + } + + set hasDim(value: boolean) { + this.#hasDim = !!value; + } + + get dimSum() { + return this.#dimSum; + } + + get dimSub() { + return this.#dimSub; + } + + get dimMul() { + return this.#dimMul; + } + + get dimDiv() { + return this.#dimDiv; + } + + get hasEtc() { + return this.#hasEtc; + } + + set hasEtc(value: boolean) { + this.#hasEtc = !!value; + } + + get etcSum() { + return this.#etcSum; + } + + get etcSub() { + return this.#etcSub; + } + + get etcMul() { + return this.#etcMul; + } + + get etcDiv() { + return this.#etcDiv; + } + + /** + * clear values + * @returns void + */ + clear() { + // number + this.#hasNum = false; + this.#numSum = []; + this.#numMul = []; + // percentage + this.#hasPct = false; + this.#pctSum = []; + this.#pctMul = []; + // dimension + this.#hasDim = false; + this.#dimSum = []; + this.#dimSub = []; + this.#dimMul = []; + this.#dimDiv = []; + // et cetra + this.#hasEtc = false; + this.#etcSum = []; + this.#etcSub = []; + this.#etcMul = []; + this.#etcDiv = []; + } + + /** + * sort values + * @param values - values + * @returns sorted values + */ + sort(values: string[] = []): string[] { + const arr = [...values]; + if (arr.length > 1) { + arr.sort((a, b) => { + let res; + if (REG_TYPE_DIM_PCT.test(a) && REG_TYPE_DIM_PCT.test(b)) { + const [, valA, unitA] = a.match(REG_TYPE_DIM_PCT) as MatchedRegExp; + const [, valB, unitB] = b.match(REG_TYPE_DIM_PCT) as MatchedRegExp; + if (unitA === unitB) { + if (Number(valA) === Number(valB)) { + res = 0; + } else if (Number(valA) > Number(valB)) { + res = 1; + } else { + res = -1; + } + } else if (unitA > unitB) { + res = 1; + } else { + res = -1; + } + } else { + if (a === b) { + res = 0; + } else if (a > b) { + res = 1; + } else { + res = -1; + } + } + return res; + }); + } + return arr; + } + + /** + * multiply values + * @returns resolved value + */ + multiply(): string { + const value = []; + let num; + if (this.#hasNum) { + num = 1; + for (const i of this.#numMul) { + num *= i; + if (num === 0 || !Number.isFinite(num) || Number.isNaN(num)) { + break; + } + } + if (!this.#hasPct && !this.#hasDim && !this.hasEtc) { + if (Number.isFinite(num)) { + num = roundToPrecision(num, HEX); + } + value.push(num); + } + } + if (this.#hasPct) { + if (typeof num !== 'number') { + num = 1; + } + for (const i of this.#pctMul) { + num *= i; + if (num === 0 || !Number.isFinite(num) || Number.isNaN(num)) { + break; + } + } + if (Number.isFinite(num)) { + num = `${roundToPrecision(num, HEX)}%`; + } + if (!this.#hasDim && !this.hasEtc) { + value.push(num); + } + } + if (this.#hasDim) { + let dim = ''; + let mul = ''; + let div = ''; + if (this.#dimMul.length) { + if (this.#dimMul.length === 1) { + [mul] = this.#dimMul as [string]; + } else { + mul = `${this.sort(this.#dimMul).join(' * ')}`; + } + } + if (this.#dimDiv.length) { + if (this.#dimDiv.length === 1) { + [div] = this.#dimDiv as [string]; + } else { + div = `${this.sort(this.#dimDiv).join(' * ')}`; + } + } + if (Number.isFinite(num)) { + if (mul) { + if (div) { + if (div.includes('*')) { + dim = calc(`calc(${num} * ${mul} / (${div}))`, this.#calcOpts); + } else { + dim = calc(`calc(${num} * ${mul} / ${div})`, this.#calcOpts); + } + } else { + dim = calc(`calc(${num} * ${mul})`, this.#calcOpts); + } + } else if (div.includes('*')) { + dim = calc(`calc(${num} / (${div}))`, this.#calcOpts); + } else { + dim = calc(`calc(${num} / ${div})`, this.#calcOpts); + } + value.push(dim.replace(/^calc/, '')); + } else { + if (!value.length && num !== undefined) { + value.push(num); + } + if (mul) { + if (div) { + if (div.includes('*')) { + dim = calc(`calc(${mul} / (${div}))`, this.#calcOpts); + } else { + dim = calc(`calc(${mul} / ${div})`, this.#calcOpts); + } + } else { + dim = calc(`calc(${mul})`, this.#calcOpts); + } + if (value.length) { + value.push('*', dim.replace(/^calc/, '')); + } else { + value.push(dim.replace(/^calc/, '')); + } + } else { + dim = calc(`calc(${div})`, this.#calcOpts); + if (value.length) { + value.push('/', dim.replace(/^calc/, '')); + } else { + value.push('1', '/', dim.replace(/^calc/, '')); + } + } + } + } + if (this.#hasEtc) { + if (this.#etcMul.length) { + if (!value.length && num !== undefined) { + value.push(num); + } + const mul = this.sort(this.#etcMul).join(' * '); + if (value.length) { + value.push(`* ${mul}`); + } else { + value.push(`${mul}`); + } + } + if (this.#etcDiv.length) { + const div = this.sort(this.#etcDiv).join(' * '); + if (div.includes('*')) { + if (value.length) { + value.push(`/ (${div})`); + } else { + value.push(`1 / (${div})`); + } + } else if (value.length) { + value.push(`/ ${div}`); + } else { + value.push(`1 / ${div}`); + } + } + } + if (value.length) { + return value.join(' '); + } + return ''; + } + + /** + * sum values + * @returns resolved value + */ + sum(): string { + const value = []; + if (this.#hasNum) { + let num = 0; + for (const i of this.#numSum) { + num += i; + if (!Number.isFinite(num) || Number.isNaN(num)) { + break; + } + } + value.push(num); + } + if (this.#hasPct) { + let num: number | string = 0; + for (const i of this.#pctSum) { + num += i; + if (!Number.isFinite(num)) { + break; + } + } + if (Number.isFinite(num)) { + num = `${num}%`; + } + if (value.length) { + value.push(`+ ${num}`); + } else { + value.push(num); + } + } + if (this.#hasDim) { + let dim, sum, sub; + if (this.#dimSum.length) { + sum = this.sort(this.#dimSum).join(' + '); + } + if (this.#dimSub.length) { + sub = this.sort(this.#dimSub).join(' + '); + } + if (sum) { + if (sub) { + if (sub.includes('-')) { + dim = calc(`calc(${sum} - (${sub}))`, this.#calcOpts); + } else { + dim = calc(`calc(${sum} - ${sub})`, this.#calcOpts); + } + } else { + dim = calc(`calc(${sum})`, this.#calcOpts); + } + } else { + dim = calc(`calc(-1 * (${sub}))`, this.#calcOpts); + } + if (value.length) { + value.push('+', dim.replace(/^calc/, '')); + } else { + value.push(dim.replace(/^calc/, '')); + } + } + if (this.#hasEtc) { + if (this.#etcSum.length) { + const sum = this.sort(this.#etcSum) + .map(item => { + let res; + if ( + REG_OPERATOR.test(item) && + !item.startsWith('(') && + !item.endsWith(')') + ) { + res = `(${item})`; + } else { + res = item; + } + return res; + }) + .join(' + '); + if (value.length) { + if (this.#etcSum.length > 1) { + value.push(`+ (${sum})`); + } else { + value.push(`+ ${sum}`); + } + } else { + value.push(`${sum}`); + } + } + if (this.#etcSub.length) { + const sub = this.sort(this.#etcSub) + .map(item => { + let res; + if ( + REG_OPERATOR.test(item) && + !item.startsWith('(') && + !item.endsWith(')') + ) { + res = `(${item})`; + } else { + res = item; + } + return res; + }) + .join(' + '); + if (value.length) { + if (this.#etcSub.length > 1) { + value.push(`- (${sub})`); + } else { + value.push(`- ${sub}`); + } + } else if (this.#etcSub.length > 1) { + value.push(`-1 * (${sub})`); + } else { + value.push(`-1 * ${sub}`); + } + } + } + if (value.length) { + return value.join(' '); + } + return ''; + } +} + +/** + * sort calc values + * @param values - values to sort + * @param [finalize] - finalize values + * @returns sorted values + */ +export const sortCalcValues = ( + values: (number | string)[] = [], + finalize: boolean = false +): string => { + if (values.length < TRIA) { + throw new Error(`Unexpected array length ${values.length}.`); + } + const start = values.shift(); + if (!isString(start) || !start.endsWith('(')) { + throw new Error(`Unexpected token ${start}.`); + } + const end = values.pop(); + if (end !== ')') { + throw new Error(`Unexpected token ${end}.`); + } + if (values.length === 1) { + const [value] = values; + if (!isStringOrNumber(value)) { + throw new Error(`Unexpected token ${value}.`); + } + return `${start}${value}${end}`; + } + const sortedValues = []; + const cal = new Calculator(); + let operator: string = ''; + const l = values.length; + for (let i = 0; i < l; i++) { + const value = values[i]; + if (!isStringOrNumber(value)) { + throw new Error(`Unexpected token ${value}.`); + } + if (value === '*' || value === '/') { + operator = value; + } else if (value === '+' || value === '-') { + const sortedValue = cal.multiply(); + if (sortedValue) { + sortedValues.push(sortedValue, value); + } + cal.clear(); + operator = ''; + } else { + const numValue = Number(value); + const strValue = `${value}`; + switch (operator) { + case '/': { + if (Number.isFinite(numValue)) { + cal.hasNum = true; + cal.numMul.push(1 / numValue); + } else if (REG_TYPE_PCT.test(strValue)) { + const [, val] = strValue.match(REG_TYPE_PCT) as MatchedRegExp; + cal.hasPct = true; + cal.pctMul.push((MAX_PCT * MAX_PCT) / Number(val)); + } else if (REG_TYPE_DIM.test(strValue)) { + cal.hasDim = true; + cal.dimDiv.push(strValue); + } else { + cal.hasEtc = true; + cal.etcDiv.push(strValue); + } + break; + } + case '*': + default: { + if (Number.isFinite(numValue)) { + cal.hasNum = true; + cal.numMul.push(numValue); + } else if (REG_TYPE_PCT.test(strValue)) { + const [, val] = strValue.match(REG_TYPE_PCT) as MatchedRegExp; + cal.hasPct = true; + cal.pctMul.push(Number(val)); + } else if (REG_TYPE_DIM.test(strValue)) { + cal.hasDim = true; + cal.dimMul.push(strValue); + } else { + cal.hasEtc = true; + cal.etcMul.push(strValue); + } + } + } + } + if (i === l - 1) { + const sortedValue = cal.multiply(); + if (sortedValue) { + sortedValues.push(sortedValue); + } + cal.clear(); + operator = ''; + } + } + let resolvedValue = ''; + if (finalize && (sortedValues.includes('+') || sortedValues.includes('-'))) { + const finalizedValues = []; + cal.clear(); + operator = ''; + const l = sortedValues.length; + for (let i = 0; i < l; i++) { + const value = sortedValues[i]; + if (isStringOrNumber(value)) { + if (value === '+' || value === '-') { + operator = value; + } else { + const numValue = Number(value); + const strValue = `${value}`; + switch (operator) { + case '-': { + if (Number.isFinite(numValue)) { + cal.hasNum = true; + cal.numSum.push(-1 * numValue); + } else if (REG_TYPE_PCT.test(strValue)) { + const [, val] = strValue.match(REG_TYPE_PCT) as MatchedRegExp; + cal.hasPct = true; + cal.pctSum.push(-1 * Number(val)); + } else if (REG_TYPE_DIM.test(strValue)) { + cal.hasDim = true; + cal.dimSub.push(strValue); + } else { + cal.hasEtc = true; + cal.etcSub.push(strValue); + } + break; + } + case '+': + default: { + if (Number.isFinite(numValue)) { + cal.hasNum = true; + cal.numSum.push(numValue); + } else if (REG_TYPE_PCT.test(strValue)) { + const [, val] = strValue.match(REG_TYPE_PCT) as MatchedRegExp; + cal.hasPct = true; + cal.pctSum.push(Number(val)); + } else if (REG_TYPE_DIM.test(strValue)) { + cal.hasDim = true; + cal.dimSum.push(strValue); + } else { + cal.hasEtc = true; + cal.etcSum.push(strValue); + } + } + } + } + } + if (i === l - 1) { + const sortedValue = cal.sum(); + if (sortedValue) { + finalizedValues.push(sortedValue); + } + cal.clear(); + operator = ''; + } + } + resolvedValue = finalizedValues.join(' ').replace(/\+\s-/g, '- '); + } else { + resolvedValue = sortedValues.join(' ').replace(/\+\s-/g, '- '); + } + if ( + resolvedValue.startsWith('(') && + resolvedValue.endsWith(')') && + resolvedValue.lastIndexOf('(') === 0 && + resolvedValue.indexOf(')') === resolvedValue.length - 1 + ) { + resolvedValue = resolvedValue.replace(/^\(/, '').replace(/\)$/, ''); + } + return `${start}${resolvedValue}${end}`; +}; + +/** + * serialize calc + * @param value - CSS value + * @param [opt] - options + * @returns serialized value + */ +export const serializeCalc = (value: string, opt: Options = {}): string => { + const { format = '' } = opt; + if (isString(value)) { + if (!REG_FN_VAR_START.test(value) || format !== VAL_SPEC) { + return value; + } + value = value.toLowerCase().trim(); + } else { + throw new TypeError(`${value} is not a string.`); + } + const cacheKey: string = createCacheKey( + { + namespace: NAMESPACE, + name: 'serializeCalc', + value + }, + opt + ); + const cachedResult = getCache(cacheKey); + if (cachedResult instanceof CacheItem) { + return cachedResult.item as string; + } + const items: string[] = tokenize({ css: value }) + .map((token: CSSToken): string => { + const [type, value] = token as [TokenType, string]; + let res = ''; + if (type !== W_SPACE && type !== COMMENT) { + res = value; + } + return res; + }) + .filter(v => v); + let startIndex = items.findLastIndex((item: string) => /\($/.test(item)); + while (startIndex) { + const endIndex = items.findIndex((item: unknown, index: number) => { + return item === ')' && index > startIndex; + }); + const slicedValues: string[] = items.slice(startIndex, endIndex + 1); + let serializedValue: string = sortCalcValues(slicedValues); + if (REG_FN_VAR_START.test(serializedValue)) { + serializedValue = calc(serializedValue, { + toCanonicalUnits: true + }); + } + items.splice(startIndex, endIndex - startIndex + 1, serializedValue); + startIndex = items.findLastIndex((item: string) => /\($/.test(item)); + } + const serializedCalc = sortCalcValues(items, true); + setCache(cacheKey, serializedCalc); + return serializedCalc; +}; + +/** + * resolve dimension + * @param token - CSS token + * @param [opt] - options + * @returns resolved value + */ +export const resolveDimension = ( + token: CSSToken, + opt: Options = {} +): string | NullObject => { + if (!Array.isArray(token)) { + throw new TypeError(`${token} is not an array.`); + } + const [, , , , detail = {}] = token; + const { unit, value } = detail as { + unit: string; + value: number; + }; + if (unit === 'px') { + return `${value}${unit}`; + } + const pixelValue = resolveLengthInPixels(Number(value), unit, opt); + if (Number.isFinite(pixelValue)) { + return `${roundToPrecision(pixelValue, HEX)}px`; + } + return new NullObject(); +}; + +/** + * parse tokens + * @param tokens - CSS tokens + * @param [opt] - options + * @returns parsed tokens + */ +export const parseTokens = ( + tokens: CSSToken[], + opt: Options = {} +): string[] => { + if (!Array.isArray(tokens)) { + throw new TypeError(`${tokens} is not an array.`); + } + const { format = '' } = opt; + const mathFunc = new Set(); + let nest = 0; + const res: string[] = []; + while (tokens.length) { + const token = tokens.shift(); + if (!Array.isArray(token)) { + throw new TypeError(`${token} is not an array.`); + } + const [type = '', value = ''] = token as [TokenType, string]; + switch (type) { + case DIM: { + if (format === VAL_SPEC && !mathFunc.has(nest)) { + res.push(value); + } else { + const resolvedValue = resolveDimension(token, opt); + if (isString(resolvedValue)) { + res.push(resolvedValue); + } else { + res.push(value); + } + } + break; + } + case FUNC: + case PAREN_OPEN: { + res.push(value); + nest++; + if (REG_FN_MATH_START.test(value)) { + mathFunc.add(nest); + } + break; + } + case PAREN_CLOSE: { + if (res.length) { + const lastValue = res[res.length - 1]; + if (lastValue === ' ') { + res.splice(-1, 1, value); + } else { + res.push(value); + } + } else { + res.push(value); + } + if (mathFunc.has(nest)) { + mathFunc.delete(nest); + } + nest--; + break; + } + case W_SPACE: { + if (res.length) { + const lastValue = res[res.length - 1]; + if ( + isString(lastValue) && + !lastValue.endsWith('(') && + lastValue !== ' ' + ) { + res.push(value); + } + } + break; + } + default: { + if (type !== COMMENT && type !== EOF) { + res.push(value); + } + } + } + } + return res; +}; + +/** + * CSS calc() + * @param value - CSS value including calc() + * @param [opt] - options + * @returns resolved value + */ +export const cssCalc = (value: string, opt: Options = {}): string => { + const { format = '' } = opt; + if (isString(value)) { + if (REG_FN_VAR.test(value)) { + if (format === VAL_SPEC) { + return value; + } else { + const resolvedValue = resolveVar(value, opt); + if (isString(resolvedValue)) { + return resolvedValue; + } else { + return ''; + } + } + } else if (!REG_FN_CALC.test(value)) { + return value; + } + value = value.toLowerCase().trim(); + } else { + throw new TypeError(`${value} is not a string.`); + } + const cacheKey: string = createCacheKey( + { + namespace: NAMESPACE, + name: 'cssCalc', + value + }, + opt + ); + const cachedResult = getCache(cacheKey); + if (cachedResult instanceof CacheItem) { + return cachedResult.item as string; + } + const tokens = tokenize({ css: value }); + const values = parseTokens(tokens, opt); + let resolvedValue: string = calc(values.join(''), { + toCanonicalUnits: true + }); + if (REG_FN_VAR_START.test(value)) { + if (REG_TYPE_DIM_PCT.test(resolvedValue)) { + const [, val, unit] = resolvedValue.match( + REG_TYPE_DIM_PCT + ) as MatchedRegExp; + resolvedValue = `${roundToPrecision(Number(val), HEX)}${unit}`; + } + // wrap with `calc()` + if ( + resolvedValue && + !REG_FN_VAR_START.test(resolvedValue) && + format === VAL_SPEC + ) { + resolvedValue = `calc(${resolvedValue})`; + } + } + if (format === VAL_SPEC) { + if (/\s[-+*/]\s/.test(resolvedValue) && !resolvedValue.includes('NaN')) { + resolvedValue = serializeCalc(resolvedValue, opt); + } else if (REG_FN_CALC_NUM.test(resolvedValue)) { + const [, val] = resolvedValue.match(REG_FN_CALC_NUM) as MatchedRegExp; + resolvedValue = `calc(${roundToPrecision(Number(val), HEX)})`; + } + } + setCache(cacheKey, resolvedValue); + return resolvedValue; +}; diff --git a/node_modules/@asamuzakjp/css-color/src/js/css-gradient.ts b/node_modules/@asamuzakjp/css-color/src/js/css-gradient.ts new file mode 100644 index 00000000..4f57567e --- /dev/null +++ b/node_modules/@asamuzakjp/css-color/src/js/css-gradient.ts @@ -0,0 +1,384 @@ +/** + * css-gradient + */ + +import { CacheItem, createCacheKey, getCache, setCache } from './cache'; +import { resolveColor } from './resolve'; +import { isString } from './common'; +import { MatchedRegExp, Options } from './typedef'; +import { isColor, splitValue } from './util'; + +/* constants */ +import { + ANGLE, + CS_HUE, + CS_RECT, + LENGTH, + NUM, + NUM_POSITIVE, + PCT, + VAL_COMP, + VAL_SPEC +} from './constant'; +const NAMESPACE = 'css-gradient'; +const DIM_ANGLE = `${NUM}(?:${ANGLE})`; +const DIM_ANGLE_PCT = `${DIM_ANGLE}|${PCT}`; +const DIM_LEN = `${NUM}(?:${LENGTH})|0`; +const DIM_LEN_PCT = `${DIM_LEN}|${PCT}`; +const DIM_LEN_PCT_POSI = `${NUM_POSITIVE}(?:${LENGTH}|%)|0`; +const DIM_LEN_POSI = `${NUM_POSITIVE}(?:${LENGTH})|0`; +const CTR = 'center'; +const L_R = 'left|right'; +const T_B = 'top|bottom'; +const S_E = 'start|end'; +const AXIS_X = `${L_R}|x-(?:${S_E})`; +const AXIS_Y = `${T_B}|y-(?:${S_E})`; +const BLOCK = `block-(?:${S_E})`; +const INLINE = `inline-(?:${S_E})`; +const POS_1 = `${CTR}|${AXIS_X}|${AXIS_Y}|${BLOCK}|${INLINE}|${DIM_LEN_PCT}`; +const POS_2 = [ + `(?:${CTR}|${AXIS_X})\\s+(?:${CTR}|${AXIS_Y})`, + `(?:${CTR}|${AXIS_Y})\\s+(?:${CTR}|${AXIS_X})`, + `(?:${CTR}|${AXIS_X}|${DIM_LEN_PCT})\\s+(?:${CTR}|${AXIS_Y}|${DIM_LEN_PCT})`, + `(?:${CTR}|${BLOCK})\\s+(?:${CTR}|${INLINE})`, + `(?:${CTR}|${INLINE})\\s+(?:${CTR}|${BLOCK})`, + `(?:${CTR}|${S_E})\\s+(?:${CTR}|${S_E})` +].join('|'); +const POS_4 = [ + `(?:${AXIS_X})\\s+(?:${DIM_LEN_PCT})\\s+(?:${AXIS_Y})\\s+(?:${DIM_LEN_PCT})`, + `(?:${AXIS_Y})\\s+(?:${DIM_LEN_PCT})\\s+(?:${AXIS_X})\\s+(?:${DIM_LEN_PCT})`, + `(?:${BLOCK})\\s+(?:${DIM_LEN_PCT})\\s+(?:${INLINE})\\s+(?:${DIM_LEN_PCT})`, + `(?:${INLINE})\\s+(?:${DIM_LEN_PCT})\\s+(?:${BLOCK})\\s+(?:${DIM_LEN_PCT})`, + `(?:${S_E})\\s+(?:${DIM_LEN_PCT})\\s+(?:${S_E})\\s+(?:${DIM_LEN_PCT})` +].join('|'); +const RAD_EXTENT = '(?:clos|farth)est-(?:corner|side)'; +const RAD_SIZE = [ + `${RAD_EXTENT}(?:\\s+${RAD_EXTENT})?`, + `${DIM_LEN_POSI}`, + `(?:${DIM_LEN_PCT_POSI})\\s+(?:${DIM_LEN_PCT_POSI})` +].join('|'); +const RAD_SHAPE = 'circle|ellipse'; +const FROM_ANGLE = `from\\s+${DIM_ANGLE}`; +const AT_POSITION = `at\\s+(?:${POS_1}|${POS_2}|${POS_4})`; +const TO_SIDE_CORNER = `to\\s+(?:(?:${L_R})(?:\\s(?:${T_B}))?|(?:${T_B})(?:\\s(?:${L_R}))?)`; +const IN_COLOR_SPACE = `in\\s+(?:${CS_RECT}|${CS_HUE})`; + +/* type definitions */ +/** + * @type ColorStopList - list of color stops + */ +type ColorStopList = [string, string, ...string[]]; + +/** + * @typedef ValidateGradientLine - validate gradient line + * @property line - gradient line + * @property valid - result + */ +interface ValidateGradientLine { + line: string; + valid: boolean; +} + +/** + * @typedef ValidateColorStops - validate color stops + * @property colorStops - list of color stops + * @property valid - result + */ +interface ValidateColorStops { + colorStops: string[]; + valid: boolean; +} + +/** + * @typedef Gradient - parsed CSS gradient + * @property value - input value + * @property type - gradient type + * @property [gradientLine] - gradient line + * @property colorStopList - list of color stops + */ +interface Gradient { + value: string; + type: string; + gradientLine?: string; + colorStopList: ColorStopList; +} + +/* regexp */ +const REG_GRAD = /^(?:repeating-)?(?:conic|linear|radial)-gradient\(/; +const REG_GRAD_CAPT = /^((?:repeating-)?(?:conic|linear|radial)-gradient)\(/; + +/** + * get gradient type + * @param value - gradient value + * @returns gradient type + */ +export const getGradientType = (value: string): string => { + if (isString(value)) { + value = value.trim(); + if (REG_GRAD.test(value)) { + const [, type] = value.match(REG_GRAD_CAPT) as MatchedRegExp; + return type; + } + } + return ''; +}; + +/** + * validate gradient line + * @param value - gradient line value + * @param type - gradient type + * @returns result + */ +export const validateGradientLine = ( + value: string, + type: string +): ValidateGradientLine => { + if (isString(value) && isString(type)) { + value = value.trim(); + type = type.trim(); + let lineSyntax = ''; + const defaultValues = []; + if (/^(?:repeating-)?linear-gradient$/.test(type)) { + /* + * = [ + * [ | to ] || + * + * ] + */ + lineSyntax = [ + `(?:${DIM_ANGLE}|${TO_SIDE_CORNER})(?:\\s+${IN_COLOR_SPACE})?`, + `${IN_COLOR_SPACE}(?:\\s+(?:${DIM_ANGLE}|${TO_SIDE_CORNER}))?` + ].join('|'); + defaultValues.push(/to\s+bottom/); + } else if (/^(?:repeating-)?radial-gradient$/.test(type)) { + /* + * = [ + * [ [ || ]? [ at ]? ] || + * ]? + */ + lineSyntax = [ + `(?:${RAD_SHAPE})(?:\\s+(?:${RAD_SIZE}))?(?:\\s+${AT_POSITION})?(?:\\s+${IN_COLOR_SPACE})?`, + `(?:${RAD_SIZE})(?:\\s+(?:${RAD_SHAPE}))?(?:\\s+${AT_POSITION})?(?:\\s+${IN_COLOR_SPACE})?`, + `${AT_POSITION}(?:\\s+${IN_COLOR_SPACE})?`, + `${IN_COLOR_SPACE}(?:\\s+${RAD_SHAPE})(?:\\s+(?:${RAD_SIZE}))?(?:\\s+${AT_POSITION})?`, + `${IN_COLOR_SPACE}(?:\\s+${RAD_SIZE})(?:\\s+(?:${RAD_SHAPE}))?(?:\\s+${AT_POSITION})?`, + `${IN_COLOR_SPACE}(?:\\s+${AT_POSITION})?` + ].join('|'); + defaultValues.push(/ellipse/, /farthest-corner/, /at\s+center/); + } else if (/^(?:repeating-)?conic-gradient$/.test(type)) { + /* + * = [ + * [ [ from ]? [ at ]? ] || + * + * ] + */ + lineSyntax = [ + `${FROM_ANGLE}(?:\\s+${AT_POSITION})?(?:\\s+${IN_COLOR_SPACE})?`, + `${AT_POSITION}(?:\\s+${IN_COLOR_SPACE})?`, + `${IN_COLOR_SPACE}(?:\\s+${FROM_ANGLE})?(?:\\s+${AT_POSITION})?` + ].join('|'); + defaultValues.push(/at\s+center/); + } + if (lineSyntax) { + const reg = new RegExp(`^(?:${lineSyntax})$`); + const valid = reg.test(value); + if (valid) { + let line = value; + for (const defaultValue of defaultValues) { + line = line.replace(defaultValue, ''); + } + line = line.replace(/\s{2,}/g, ' ').trim(); + return { + line, + valid + }; + } + return { + valid, + line: value + }; + } + } + return { + line: value, + valid: false + }; +}; + +/** + * validate color stop list + * @param list + * @param type + * @param [opt] + * @returns result + */ +export const validateColorStopList = ( + list: string[], + type: string, + opt: Options = {} +): ValidateColorStops => { + if (Array.isArray(list) && list.length > 1) { + const dimension = /^(?:repeating-)?conic-gradient$/.test(type) + ? DIM_ANGLE_PCT + : DIM_LEN_PCT; + const regColorHint = new RegExp(`^(?:${dimension})$`); + const regDimension = new RegExp(`(?:\\s+(?:${dimension})){1,2}$`); + const valueTypes = []; + const valueList = []; + for (const item of list) { + if (isString(item)) { + if (regColorHint.test(item)) { + valueTypes.push('hint'); + valueList.push(item); + } else { + const itemColor = item.replace(regDimension, ''); + if (isColor(itemColor, { format: VAL_SPEC })) { + const resolvedColor = resolveColor(itemColor, opt) as string; + valueTypes.push('color'); + valueList.push(item.replace(itemColor, resolvedColor)); + } else { + return { + colorStops: list, + valid: false + }; + } + } + } + } + const valid = /^color(?:,(?:hint,)?color)+$/.test(valueTypes.join(',')); + return { + valid, + colorStops: valueList + }; + } + return { + colorStops: list, + valid: false + }; +}; + +/** + * parse CSS gradient + * @param value - gradient value + * @param [opt] - options + * @returns parsed result + */ +export const parseGradient = ( + value: string, + opt: Options = {} +): Gradient | null => { + if (isString(value)) { + value = value.trim(); + const cacheKey: string = createCacheKey( + { + namespace: NAMESPACE, + name: 'parseGradient', + value + }, + opt + ); + const cachedResult = getCache(cacheKey); + if (cachedResult instanceof CacheItem) { + if (cachedResult.isNull) { + return null; + } + return cachedResult.item as Gradient; + } + const type = getGradientType(value); + const gradValue = value.replace(REG_GRAD, '').replace(/\)$/, ''); + if (type && gradValue) { + const [lineOrColorStop = '', ...itemList] = splitValue(gradValue, { + delimiter: ',' + }); + const dimension = /^(?:repeating-)?conic-gradient$/.test(type) + ? DIM_ANGLE_PCT + : DIM_LEN_PCT; + const regDimension = new RegExp(`(?:\\s+(?:${dimension})){1,2}$`); + let colorStop = ''; + if (regDimension.test(lineOrColorStop)) { + const itemColor = lineOrColorStop.replace(regDimension, ''); + if (isColor(itemColor, { format: VAL_SPEC })) { + const resolvedColor = resolveColor(itemColor, opt) as string; + colorStop = lineOrColorStop.replace(itemColor, resolvedColor); + } + } else if (isColor(lineOrColorStop, { format: VAL_SPEC })) { + colorStop = resolveColor(lineOrColorStop, opt) as string; + } + if (colorStop) { + itemList.unshift(colorStop); + const { colorStops, valid } = validateColorStopList( + itemList, + type, + opt + ); + if (valid) { + const res: Gradient = { + value, + type, + colorStopList: colorStops as ColorStopList + }; + setCache(cacheKey, res); + return res; + } + } else if (itemList.length > 1) { + const { line: gradientLine, valid: validLine } = validateGradientLine( + lineOrColorStop, + type + ); + const { colorStops, valid: validColorStops } = validateColorStopList( + itemList, + type, + opt + ); + if (validLine && validColorStops) { + const res: Gradient = { + value, + type, + gradientLine, + colorStopList: colorStops as ColorStopList + }; + setCache(cacheKey, res); + return res; + } + } + } + setCache(cacheKey, null); + return null; + } + return null; +}; + +/** + * resolve CSS gradient + * @param value - CSS value + * @param [opt] - options + * @returns result + */ +export const resolveGradient = (value: string, opt: Options = {}): string => { + const { format = VAL_COMP } = opt; + const gradient = parseGradient(value, opt); + if (gradient) { + const { type = '', gradientLine = '', colorStopList = [] } = gradient; + if (type && Array.isArray(colorStopList) && colorStopList.length > 1) { + if (gradientLine) { + return `${type}(${gradientLine}, ${colorStopList.join(', ')})`; + } + return `${type}(${colorStopList.join(', ')})`; + } + } + if (format === VAL_SPEC) { + return ''; + } + return 'none'; +}; + +/** + * is CSS gradient + * @param value - CSS value + * @param [opt] - options + * @returns result + */ +export const isGradient = (value: string, opt: Options = {}): boolean => { + const gradient = parseGradient(value, opt); + return gradient !== null; +}; diff --git a/node_modules/@asamuzakjp/css-color/src/js/css-var.ts b/node_modules/@asamuzakjp/css-color/src/js/css-var.ts new file mode 100644 index 00000000..ef4a3f18 --- /dev/null +++ b/node_modules/@asamuzakjp/css-color/src/js/css-var.ts @@ -0,0 +1,250 @@ +/** + * css-var + */ + +import { CSSToken, TokenType, tokenize } from '@csstools/css-tokenizer'; +import { + CacheItem, + NullObject, + createCacheKey, + getCache, + setCache +} from './cache'; +import { isString } from './common'; +import { cssCalc } from './css-calc'; +import { isColor } from './util'; +import { Options } from './typedef'; + +/* constants */ +import { FN_VAR, SYN_FN_CALC, SYN_FN_VAR, VAL_SPEC } from './constant'; +const { + CloseParen: PAREN_CLOSE, + Comment: COMMENT, + EOF, + Ident: IDENT, + Whitespace: W_SPACE +} = TokenType; +const NAMESPACE = 'css-var'; + +/* regexp */ +const REG_FN_CALC = new RegExp(SYN_FN_CALC); +const REG_FN_VAR = new RegExp(SYN_FN_VAR); + +/** + * resolve custom property + * @param tokens - CSS tokens + * @param [opt] - options + * @returns result - [tokens, resolvedValue] + */ +export function resolveCustomProperty( + tokens: CSSToken[], + opt: Options = {} +): [CSSToken[], string] { + if (!Array.isArray(tokens)) { + throw new TypeError(`${tokens} is not an array.`); + } + const { customProperty = {} } = opt; + const items: string[] = []; + while (tokens.length) { + const token = tokens.shift(); + if (!Array.isArray(token)) { + throw new TypeError(`${token} is not an array.`); + } + const [type, value] = token as [TokenType, string]; + // end of var() + if (type === PAREN_CLOSE) { + break; + } + // nested var() + if (value === FN_VAR) { + const [restTokens, item] = resolveCustomProperty(tokens, opt); + tokens = restTokens; + if (item) { + items.push(item); + } + } else if (type === IDENT) { + if (value.startsWith('--')) { + let item; + if (Object.hasOwn(customProperty, value)) { + item = customProperty[value] as string; + } else if (typeof customProperty.callback === 'function') { + item = customProperty.callback(value); + } + if (item) { + items.push(item); + } + } else if (value) { + items.push(value); + } + } + } + let resolveAsColor = false; + if (items.length > 1) { + const lastValue = items[items.length - 1]; + resolveAsColor = isColor(lastValue); + } + let resolvedValue = ''; + for (let item of items) { + item = item.trim(); + if (REG_FN_VAR.test(item)) { + // recurse resolveVar() + const resolvedItem = resolveVar(item, opt); + if (isString(resolvedItem)) { + if (resolveAsColor) { + if (isColor(resolvedItem)) { + resolvedValue = resolvedItem; + } + } else { + resolvedValue = resolvedItem; + } + } + } else if (REG_FN_CALC.test(item)) { + item = cssCalc(item, opt); + if (resolveAsColor) { + if (isColor(item)) { + resolvedValue = item; + } + } else { + resolvedValue = item; + } + } else if ( + item && + !/^(?:inherit|initial|revert(?:-layer)?|unset)$/.test(item) + ) { + if (resolveAsColor) { + if (isColor(item)) { + resolvedValue = item; + } + } else { + resolvedValue = item; + } + } + if (resolvedValue) { + break; + } + } + return [tokens, resolvedValue]; +} + +/** + * parse tokens + * @param tokens - CSS tokens + * @param [opt] - options + * @returns parsed tokens + */ +export function parseTokens( + tokens: CSSToken[], + opt: Options = {} +): string[] | NullObject { + const res: string[] = []; + while (tokens.length) { + const token = tokens.shift(); + const [type = '', value = ''] = token as [TokenType, string]; + if (value === FN_VAR) { + const [restTokens, resolvedValue] = resolveCustomProperty(tokens, opt); + if (!resolvedValue) { + return new NullObject(); + } + tokens = restTokens; + res.push(resolvedValue); + } else { + switch (type) { + case PAREN_CLOSE: { + if (res.length) { + const lastValue = res[res.length - 1]; + if (lastValue === ' ') { + res.splice(-1, 1, value); + } else { + res.push(value); + } + } else { + res.push(value); + } + break; + } + case W_SPACE: { + if (res.length) { + const lastValue = res[res.length - 1]; + if ( + isString(lastValue) && + !lastValue.endsWith('(') && + lastValue !== ' ' + ) { + res.push(value); + } + } + break; + } + default: { + if (type !== COMMENT && type !== EOF) { + res.push(value); + } + } + } + } + } + return res; +} + +/** + * resolve CSS var() + * @param value - CSS value including var() + * @param [opt] - options + * @returns resolved value + */ +export function resolveVar( + value: string, + opt: Options = {} +): string | NullObject { + const { format = '' } = opt; + if (isString(value)) { + if (!REG_FN_VAR.test(value) || format === VAL_SPEC) { + return value; + } + value = value.trim(); + } else { + throw new TypeError(`${value} is not a string.`); + } + const cacheKey: string = createCacheKey( + { + namespace: NAMESPACE, + name: 'resolveVar', + value + }, + opt + ); + const cachedResult = getCache(cacheKey); + if (cachedResult instanceof CacheItem) { + if (cachedResult.isNull) { + return cachedResult as NullObject; + } + return cachedResult.item as string; + } + const tokens = tokenize({ css: value }); + const values = parseTokens(tokens, opt); + if (Array.isArray(values)) { + let color = values.join(''); + if (REG_FN_CALC.test(color)) { + color = cssCalc(color, opt); + } + setCache(cacheKey, color); + return color; + } else { + setCache(cacheKey, null); + return new NullObject(); + } +} + +/** + * CSS var() + * @param value - CSS value including var() + * @param [opt] - options + * @returns resolved value + */ +export const cssVar = (value: string, opt: Options = {}): string => { + const resolvedValue = resolveVar(value, opt); + if (isString(resolvedValue)) { + return resolvedValue; + } + return ''; +}; diff --git a/node_modules/@asamuzakjp/css-color/src/js/relative-color.ts b/node_modules/@asamuzakjp/css-color/src/js/relative-color.ts new file mode 100644 index 00000000..9a20728e --- /dev/null +++ b/node_modules/@asamuzakjp/css-color/src/js/relative-color.ts @@ -0,0 +1,635 @@ +/** + * relative-color + */ + +import { SyntaxFlag, color as colorParser } from '@csstools/css-color-parser'; +import { + ComponentValue, + parseComponentValue +} from '@csstools/css-parser-algorithms'; +import { CSSToken, TokenType, tokenize } from '@csstools/css-tokenizer'; +import { + CacheItem, + NullObject, + createCacheKey, + getCache, + setCache +} from './cache'; +import { NAMED_COLORS, convertColorToRgb } from './color'; +import { isString, isStringOrNumber } from './common'; +import { resolveDimension, serializeCalc } from './css-calc'; +import { resolveColor } from './resolve'; +import { roundToPrecision, splitValue } from './util'; +import { + ColorChannels, + MatchedRegExp, + Options, + StringColorChannels +} from './typedef'; + +/* constants */ +import { + CS_LAB, + CS_LCH, + FN_LIGHT_DARK, + FN_REL, + FN_REL_CAPT, + FN_VAR, + NONE, + SYN_COLOR_TYPE, + SYN_FN_MATH_START, + SYN_FN_VAR, + SYN_MIX, + VAL_SPEC +} from './constant'; +const { + CloseParen: PAREN_CLOSE, + Comment: COMMENT, + Delim: DELIM, + Dimension: DIM, + EOF, + Function: FUNC, + Ident: IDENT, + Number: NUM, + OpenParen: PAREN_OPEN, + Percentage: PCT, + Whitespace: W_SPACE +} = TokenType; +const { HasNoneKeywords: KEY_NONE } = SyntaxFlag; +const NAMESPACE = 'relative-color'; + +/* numeric constants */ +const OCT = 8; +const DEC = 10; +const HEX = 16; +const MAX_PCT = 100; +const MAX_RGB = 255; + +/* type definitions */ +/** + * @type NumberOrStringColorChannels - color channel + */ +type NumberOrStringColorChannels = ColorChannels & StringColorChannels; + +/* regexp */ +const REG_COLOR_CAPT = new RegExp( + `^${FN_REL}(${SYN_COLOR_TYPE}|${SYN_MIX})\\s+` +); +const REG_CS_HSL = /(?:hsla?|hwb)$/; +const REG_CS_CIE = new RegExp(`^(?:${CS_LAB}|${CS_LCH})$`); +const REG_FN_CALC_SUM = /^(?:abs|sig?n|cos|tan)\(/; +const REG_FN_MATH_START = new RegExp(SYN_FN_MATH_START); +const REG_FN_REL = new RegExp(FN_REL); +const REG_FN_REL_CAPT = new RegExp(`^${FN_REL_CAPT}`); +const REG_FN_REL_START = new RegExp(`^${FN_REL}`); +const REG_FN_VAR = new RegExp(SYN_FN_VAR); + +/** + * resolve relative color channels + * @param tokens - CSS tokens + * @param [opt] - options + * @returns resolved color channels + */ +export function resolveColorChannels( + tokens: CSSToken[], + opt: Options = {} +): NumberOrStringColorChannels | NullObject { + if (!Array.isArray(tokens)) { + throw new TypeError(`${tokens} is not an array.`); + } + const { colorSpace = '', format = '' } = opt; + const colorChannels = new Map([ + ['color', ['r', 'g', 'b', 'alpha']], + ['hsl', ['h', 's', 'l', 'alpha']], + ['hsla', ['h', 's', 'l', 'alpha']], + ['hwb', ['h', 'w', 'b', 'alpha']], + ['lab', ['l', 'a', 'b', 'alpha']], + ['lch', ['l', 'c', 'h', 'alpha']], + ['oklab', ['l', 'a', 'b', 'alpha']], + ['oklch', ['l', 'c', 'h', 'alpha']], + ['rgb', ['r', 'g', 'b', 'alpha']], + ['rgba', ['r', 'g', 'b', 'alpha']] + ]); + const colorChannel = colorChannels.get(colorSpace); + // invalid color channel + if (!colorChannel) { + return new NullObject(); + } + const mathFunc = new Set(); + const channels: [ + (number | string)[], + (number | string)[], + (number | string)[], + (number | string)[] + ] = [[], [], [], []]; + let i = 0; + let nest = 0; + let func = ''; + let precededPct = false; + while (tokens.length) { + const token = tokens.shift(); + if (!Array.isArray(token)) { + throw new TypeError(`${token} is not an array.`); + } + const [type, value, , , detail] = token as [ + TokenType, + string, + number, + number, + { value: string | number } | undefined + ]; + const channel = channels[i]; + if (Array.isArray(channel)) { + switch (type) { + case DELIM: { + if (func) { + if ( + (value === '+' || value === '-') && + precededPct && + !REG_FN_CALC_SUM.test(func) + ) { + return new NullObject(); + } + precededPct = false; + channel.push(value); + } + break; + } + case DIM: { + if (!func || !REG_FN_CALC_SUM.test(func)) { + return new NullObject(); + } + const resolvedValue = resolveDimension(token, opt); + if (isString(resolvedValue)) { + channel.push(resolvedValue); + } else { + channel.push(value); + } + break; + } + case FUNC: { + channel.push(value); + func = value; + nest++; + if (REG_FN_MATH_START.test(value)) { + mathFunc.add(nest); + } + break; + } + case IDENT: { + // invalid channel key + if (!colorChannel.includes(value)) { + return new NullObject(); + } + channel.push(value); + if (!func) { + i++; + } + break; + } + case NUM: { + channel.push(Number(detail?.value)); + if (!func) { + i++; + } + break; + } + case PAREN_OPEN: { + channel.push(value); + nest++; + break; + } + case PAREN_CLOSE: { + if (func) { + const lastValue = channel[channel.length - 1]; + if (lastValue === ' ') { + channel.splice(-1, 1, value); + } else { + channel.push(value); + } + if (mathFunc.has(nest)) { + mathFunc.delete(nest); + } + nest--; + if (nest === 0) { + func = ''; + i++; + } + } + break; + } + case PCT: { + if (!func) { + return new NullObject(); + } else if (!REG_FN_CALC_SUM.test(func)) { + const lastValue = channel.toReversed().find(v => v !== ' '); + if (lastValue === '+' || lastValue === '-') { + return new NullObject(); + } else if (lastValue === '*' || lastValue === '/') { + precededPct = false; + } else { + precededPct = true; + } + } + channel.push(Number(detail?.value) / MAX_PCT); + if (!func) { + i++; + } + break; + } + case W_SPACE: { + if (channel.length && func) { + const lastValue = channel[channel.length - 1]; + if (typeof lastValue === 'number') { + channel.push(value); + } else if ( + isString(lastValue) && + !lastValue.endsWith('(') && + lastValue !== ' ' + ) { + channel.push(value); + } + } + break; + } + default: { + if (type !== COMMENT && type !== EOF && func) { + channel.push(value); + } + } + } + } + } + const channelValues = []; + for (const channel of channels) { + if (channel.length === 1) { + const [resolvedValue] = channel; + if (isStringOrNumber(resolvedValue)) { + channelValues.push(resolvedValue); + } + } else if (channel.length) { + const resolvedValue = serializeCalc(channel.join(''), { + format + }); + channelValues.push(resolvedValue); + } + } + return channelValues as NumberOrStringColorChannels; +} + +/** + * extract origin color + * @param value - CSS color value + * @param [opt] - options + * @returns origin color value + */ +export function extractOriginColor( + value: string, + opt: Options = {} +): string | NullObject { + const { colorScheme = 'normal', currentColor = '', format = '' } = opt; + if (isString(value)) { + value = value.toLowerCase().trim(); + if (!value) { + return new NullObject(); + } + if (!REG_FN_REL_START.test(value)) { + return value; + } + } else { + return new NullObject(); + } + const cacheKey: string = createCacheKey( + { + namespace: NAMESPACE, + name: 'extractOriginColor', + value + }, + opt + ); + const cachedResult = getCache(cacheKey); + if (cachedResult instanceof CacheItem) { + if (cachedResult.isNull) { + return cachedResult as NullObject; + } + return cachedResult.item as string; + } + if (/currentcolor/.test(value)) { + if (currentColor) { + value = value.replace(/currentcolor/g, currentColor); + } else { + setCache(cacheKey, null); + return new NullObject(); + } + } + let colorSpace = ''; + if (REG_FN_REL_CAPT.test(value)) { + [, colorSpace] = value.match(REG_FN_REL_CAPT) as MatchedRegExp; + } + opt.colorSpace = colorSpace; + if (value.includes(FN_LIGHT_DARK)) { + const colorParts = value + .replace(new RegExp(`^${colorSpace}\\(`), '') + .replace(/\)$/, ''); + const [, originColor = ''] = splitValue(colorParts); + const specifiedOriginColor = resolveColor(originColor, { + colorScheme, + format: VAL_SPEC + }) as string; + if (specifiedOriginColor === '') { + setCache(cacheKey, null); + return new NullObject(); + } + if (format === VAL_SPEC) { + value = value.replace(originColor, specifiedOriginColor); + } else { + const resolvedOriginColor = resolveColor(specifiedOriginColor, opt); + if (isString(resolvedOriginColor)) { + value = value.replace(originColor, resolvedOriginColor); + } + } + } + if (REG_COLOR_CAPT.test(value)) { + const [, originColor] = value.match(REG_COLOR_CAPT) as MatchedRegExp; + const [, restValue] = value.split(originColor) as MatchedRegExp; + if (/^[a-z]+$/.test(originColor)) { + if ( + !/^transparent$/.test(originColor) && + !Object.hasOwn(NAMED_COLORS, originColor) + ) { + setCache(cacheKey, null); + return new NullObject(); + } + } else if (format === VAL_SPEC) { + const resolvedOriginColor = resolveColor(originColor, opt); + if (isString(resolvedOriginColor)) { + value = value.replace(originColor, resolvedOriginColor); + } + } + if (format === VAL_SPEC) { + const tokens = tokenize({ css: restValue }); + const channelValues = resolveColorChannels(tokens, opt); + if (channelValues instanceof NullObject) { + setCache(cacheKey, null); + return channelValues; + } + const [v1, v2, v3, v4] = channelValues; + let channelValue = ''; + if (isStringOrNumber(v4)) { + channelValue = ` ${v1} ${v2} ${v3} / ${v4})`; + } else { + channelValue = ` ${channelValues.join(' ')})`; + } + if (restValue !== channelValue) { + value = value.replace(restValue, channelValue); + } + } + // nested relative color + } else { + const [, restValue] = value.split(REG_FN_REL_START) as MatchedRegExp; + const tokens = tokenize({ css: restValue }); + const originColor: string[] = []; + let nest = 0; + while (tokens.length) { + const [type, tokenValue] = tokens.shift() as [TokenType, string]; + switch (type) { + case FUNC: + case PAREN_OPEN: { + originColor.push(tokenValue); + nest++; + break; + } + case PAREN_CLOSE: { + const lastValue = originColor[originColor.length - 1]; + if (lastValue === ' ') { + originColor.splice(-1, 1, tokenValue); + } else if (isString(lastValue)) { + originColor.push(tokenValue); + } + nest--; + break; + } + case W_SPACE: { + const lastValue = originColor[originColor.length - 1]; + if ( + isString(lastValue) && + !lastValue.endsWith('(') && + lastValue !== ' ' + ) { + originColor.push(tokenValue); + } + break; + } + default: { + if (type !== COMMENT && type !== EOF) { + originColor.push(tokenValue); + } + } + } + if (nest === 0) { + break; + } + } + const resolvedOriginColor = resolveRelativeColor( + originColor.join('').trim(), + opt + ); + if (resolvedOriginColor instanceof NullObject) { + setCache(cacheKey, null); + return resolvedOriginColor; + } + const channelValues = resolveColorChannels(tokens, opt); + if (channelValues instanceof NullObject) { + setCache(cacheKey, null); + return channelValues; + } + const [v1, v2, v3, v4] = channelValues; + let channelValue = ''; + if (isStringOrNumber(v4)) { + channelValue = ` ${v1} ${v2} ${v3} / ${v4})`; + } else { + channelValue = ` ${channelValues.join(' ')})`; + } + value = value.replace(restValue, `${resolvedOriginColor}${channelValue}`); + } + setCache(cacheKey, value); + return value; +} + +/** + * resolve relative color + * @param value - CSS relative color value + * @param [opt] - options + * @returns resolved value + */ +export function resolveRelativeColor( + value: string, + opt: Options = {} +): string | NullObject { + const { format = '' } = opt; + if (isString(value)) { + if (REG_FN_VAR.test(value)) { + if (format === VAL_SPEC) { + return value; + // var() must be resolved before resolveRelativeColor() + } else { + throw new SyntaxError(`Unexpected token ${FN_VAR} found.`); + } + } else if (!REG_FN_REL.test(value)) { + return value; + } + value = value.toLowerCase().trim(); + } else { + throw new TypeError(`${value} is not a string.`); + } + const cacheKey: string = createCacheKey( + { + namespace: NAMESPACE, + name: 'resolveRelativeColor', + value + }, + opt + ); + const cachedResult = getCache(cacheKey); + if (cachedResult instanceof CacheItem) { + if (cachedResult.isNull) { + return cachedResult as NullObject; + } + return cachedResult.item as string; + } + const originColor = extractOriginColor(value, opt); + if (originColor instanceof NullObject) { + setCache(cacheKey, null); + return originColor; + } + value = originColor; + if (format === VAL_SPEC) { + if (value.startsWith('rgba(')) { + value = value.replace(/^rgba\(/, 'rgb('); + } else if (value.startsWith('hsla(')) { + value = value.replace(/^hsla\(/, 'hsl('); + } + return value; + } + const tokens = tokenize({ css: value }); + const components = parseComponentValue(tokens) as ComponentValue; + const parsedComponents = colorParser(components); + if (!parsedComponents) { + setCache(cacheKey, null); + return new NullObject(); + } + const { + alpha: alphaComponent, + channels: channelsComponent, + colorNotation, + syntaxFlags + } = parsedComponents; + let alpha: number | string; + if (Number.isNaN(Number(alphaComponent))) { + if (syntaxFlags instanceof Set && syntaxFlags.has(KEY_NONE)) { + alpha = NONE; + } else { + alpha = 0; + } + } else { + alpha = roundToPrecision(Number(alphaComponent), OCT); + } + let v1: number | string; + let v2: number | string; + let v3: number | string; + [v1, v2, v3] = channelsComponent; + let resolvedValue; + if (REG_CS_CIE.test(colorNotation)) { + const hasNone = syntaxFlags instanceof Set && syntaxFlags.has(KEY_NONE); + if (Number.isNaN(v1)) { + if (hasNone) { + v1 = NONE; + } else { + v1 = 0; + } + } else { + v1 = roundToPrecision(v1, HEX); + } + if (Number.isNaN(v2)) { + if (hasNone) { + v2 = NONE; + } else { + v2 = 0; + } + } else { + v2 = roundToPrecision(v2, HEX); + } + if (Number.isNaN(v3)) { + if (hasNone) { + v3 = NONE; + } else { + v3 = 0; + } + } else { + v3 = roundToPrecision(v3, HEX); + } + if (alpha === 1) { + resolvedValue = `${colorNotation}(${v1} ${v2} ${v3})`; + } else { + resolvedValue = `${colorNotation}(${v1} ${v2} ${v3} / ${alpha})`; + } + } else if (REG_CS_HSL.test(colorNotation)) { + if (Number.isNaN(v1)) { + v1 = 0; + } + if (Number.isNaN(v2)) { + v2 = 0; + } + if (Number.isNaN(v3)) { + v3 = 0; + } + let [r, g, b] = convertColorToRgb( + `${colorNotation}(${v1} ${v2} ${v3} / ${alpha})` + ) as ColorChannels; + r = roundToPrecision(r / MAX_RGB, DEC); + g = roundToPrecision(g / MAX_RGB, DEC); + b = roundToPrecision(b / MAX_RGB, DEC); + if (alpha === 1) { + resolvedValue = `color(srgb ${r} ${g} ${b})`; + } else { + resolvedValue = `color(srgb ${r} ${g} ${b} / ${alpha})`; + } + } else { + const cs = colorNotation === 'rgb' ? 'srgb' : colorNotation; + const hasNone = syntaxFlags instanceof Set && syntaxFlags.has(KEY_NONE); + if (Number.isNaN(v1)) { + if (hasNone) { + v1 = NONE; + } else { + v1 = 0; + } + } else { + v1 = roundToPrecision(v1, DEC); + } + if (Number.isNaN(v2)) { + if (hasNone) { + v2 = NONE; + } else { + v2 = 0; + } + } else { + v2 = roundToPrecision(v2, DEC); + } + if (Number.isNaN(v3)) { + if (hasNone) { + v3 = NONE; + } else { + v3 = 0; + } + } else { + v3 = roundToPrecision(v3, DEC); + } + if (alpha === 1) { + resolvedValue = `color(${cs} ${v1} ${v2} ${v3})`; + } else { + resolvedValue = `color(${cs} ${v1} ${v2} ${v3} / ${alpha})`; + } + } + setCache(cacheKey, resolvedValue); + return resolvedValue; +} diff --git a/node_modules/@asamuzakjp/css-color/src/js/resolve.ts b/node_modules/@asamuzakjp/css-color/src/js/resolve.ts new file mode 100644 index 00000000..fea9de3a --- /dev/null +++ b/node_modules/@asamuzakjp/css-color/src/js/resolve.ts @@ -0,0 +1,443 @@ +/** + * resolve + */ + +import { + CacheItem, + NullObject, + createCacheKey, + getCache, + setCache +} from './cache'; +import { + convertRgbToHex, + resolveColorFunc, + resolveColorMix, + resolveColorValue +} from './color'; +import { isString } from './common'; +import { cssCalc } from './css-calc'; +import { resolveVar } from './css-var'; +import { resolveRelativeColor } from './relative-color'; +import { splitValue } from './util'; +import { + ComputedColorChannels, + Options, + SpecifiedColorChannels +} from './typedef'; + +/* constants */ +import { + FN_COLOR, + FN_MIX, + SYN_FN_CALC, + SYN_FN_LIGHT_DARK, + SYN_FN_REL, + SYN_FN_VAR, + VAL_COMP, + VAL_SPEC +} from './constant'; +const NAMESPACE = 'resolve'; +const RGB_TRANSPARENT = 'rgba(0, 0, 0, 0)'; + +/* regexp */ +const REG_FN_CALC = new RegExp(SYN_FN_CALC); +const REG_FN_LIGHT_DARK = new RegExp(SYN_FN_LIGHT_DARK); +const REG_FN_REL = new RegExp(SYN_FN_REL); +const REG_FN_VAR = new RegExp(SYN_FN_VAR); + +/** + * resolve color + * @param value - CSS color value + * @param [opt] - options + * @returns resolved color + */ +export const resolveColor = ( + value: string, + opt: Options = {} +): string | NullObject => { + if (isString(value)) { + value = value.trim(); + } else { + throw new TypeError(`${value} is not a string.`); + } + const { + colorScheme = 'normal', + currentColor = '', + format = VAL_COMP, + nullable = false + } = opt; + const cacheKey: string = createCacheKey( + { + namespace: NAMESPACE, + name: 'resolve', + value + }, + opt + ); + const cachedResult = getCache(cacheKey); + if (cachedResult instanceof CacheItem) { + if (cachedResult.isNull) { + return cachedResult as NullObject; + } + return cachedResult.item as string; + } + if (REG_FN_VAR.test(value)) { + if (format === VAL_SPEC) { + setCache(cacheKey, value); + return value; + } + const resolvedValue = resolveVar(value, opt); + if (resolvedValue instanceof NullObject) { + switch (format) { + case 'hex': + case 'hexAlpha': { + setCache(cacheKey, resolvedValue); + return resolvedValue; + } + default: { + if (nullable) { + setCache(cacheKey, resolvedValue); + return resolvedValue; + } + const res = RGB_TRANSPARENT; + setCache(cacheKey, res); + return res; + } + } + } else { + value = resolvedValue; + } + } + if (opt.format !== format) { + opt.format = format; + } + value = value.toLowerCase(); + if (REG_FN_LIGHT_DARK.test(value) && value.endsWith(')')) { + const colorParts = value.replace(REG_FN_LIGHT_DARK, '').replace(/\)$/, ''); + const [light = '', dark = ''] = splitValue(colorParts, { + delimiter: ',' + }); + if (light && dark) { + if (format === VAL_SPEC) { + const lightColor = resolveColor(light, opt); + const darkColor = resolveColor(dark, opt); + let res; + if (lightColor && darkColor) { + res = `light-dark(${lightColor}, ${darkColor})`; + } else { + res = ''; + } + setCache(cacheKey, res); + return res; + } + let resolvedValue; + if (colorScheme === 'dark') { + resolvedValue = resolveColor(dark, opt); + } else { + resolvedValue = resolveColor(light, opt); + } + let res; + if (resolvedValue instanceof NullObject) { + if (nullable) { + res = resolvedValue; + } else { + res = RGB_TRANSPARENT; + } + } else { + res = resolvedValue; + } + setCache(cacheKey, res); + return res; + } + // invalid value + switch (format) { + case VAL_SPEC: { + setCache(cacheKey, ''); + return ''; + } + case 'hex': + case 'hexAlpha': { + setCache(cacheKey, null); + return new NullObject(); + } + case VAL_COMP: + default: { + const res = RGB_TRANSPARENT; + setCache(cacheKey, res); + return res; + } + } + } + if (REG_FN_REL.test(value)) { + const resolvedValue = resolveRelativeColor(value, opt); + if (format === VAL_COMP) { + let res; + if (resolvedValue instanceof NullObject) { + if (nullable) { + res = resolvedValue; + } else { + res = RGB_TRANSPARENT; + } + } else { + res = resolvedValue; + } + setCache(cacheKey, res); + return res; + } + if (format === VAL_SPEC) { + let res = ''; + if (resolvedValue instanceof NullObject) { + res = ''; + } else { + res = resolvedValue; + } + setCache(cacheKey, res); + return res; + } + if (resolvedValue instanceof NullObject) { + value = ''; + } else { + value = resolvedValue; + } + } + if (REG_FN_CALC.test(value)) { + value = cssCalc(value, opt); + } + let cs = ''; + let r = NaN; + let g = NaN; + let b = NaN; + let alpha = NaN; + if (value === 'transparent') { + switch (format) { + case VAL_SPEC: { + setCache(cacheKey, value); + return value; + } + case 'hex': { + setCache(cacheKey, null); + return new NullObject(); + } + case 'hexAlpha': { + const res = '#00000000'; + setCache(cacheKey, res); + return res; + } + case VAL_COMP: + default: { + const res = RGB_TRANSPARENT; + setCache(cacheKey, res); + return res; + } + } + } else if (value === 'currentcolor') { + if (format === VAL_SPEC) { + setCache(cacheKey, value); + return value; + } + if (currentColor) { + let resolvedValue; + if (currentColor.startsWith(FN_MIX)) { + resolvedValue = resolveColorMix(currentColor, opt); + } else if (currentColor.startsWith(FN_COLOR)) { + resolvedValue = resolveColorFunc(currentColor, opt); + } else { + resolvedValue = resolveColorValue(currentColor, opt); + } + if (resolvedValue instanceof NullObject) { + setCache(cacheKey, resolvedValue); + return resolvedValue; + } + [cs, r, g, b, alpha] = resolvedValue as ComputedColorChannels; + } else if (format === VAL_COMP) { + const res = RGB_TRANSPARENT; + setCache(cacheKey, res); + return res; + } + } else if (format === VAL_SPEC) { + if (value.startsWith(FN_MIX)) { + const res = resolveColorMix(value, opt) as string; + setCache(cacheKey, res); + return res; + } else if (value.startsWith(FN_COLOR)) { + const [scs, rr, gg, bb, aa] = resolveColorFunc( + value, + opt + ) as SpecifiedColorChannels; + let res = ''; + if (aa === 1) { + res = `color(${scs} ${rr} ${gg} ${bb})`; + } else { + res = `color(${scs} ${rr} ${gg} ${bb} / ${aa})`; + } + setCache(cacheKey, res); + return res; + } else { + const rgb = resolveColorValue(value, opt); + if (isString(rgb)) { + setCache(cacheKey, rgb); + return rgb; + } + const [scs, rr, gg, bb, aa] = rgb as SpecifiedColorChannels; + let res = ''; + if (scs === 'rgb') { + if (aa === 1) { + res = `${scs}(${rr}, ${gg}, ${bb})`; + } else { + res = `${scs}a(${rr}, ${gg}, ${bb}, ${aa})`; + } + } else if (aa === 1) { + res = `${scs}(${rr} ${gg} ${bb})`; + } else { + res = `${scs}(${rr} ${gg} ${bb} / ${aa})`; + } + setCache(cacheKey, res); + return res; + } + } else if (value.startsWith(FN_MIX)) { + if (/currentcolor/.test(value)) { + if (currentColor) { + value = value.replace(/currentcolor/g, currentColor); + } + } + if (/transparent/.test(value)) { + value = value.replace(/transparent/g, RGB_TRANSPARENT); + } + const resolvedValue = resolveColorMix(value, opt); + if (resolvedValue instanceof NullObject) { + setCache(cacheKey, resolvedValue); + return resolvedValue; + } + [cs, r, g, b, alpha] = resolvedValue as ComputedColorChannels; + } else if (value.startsWith(FN_COLOR)) { + const resolvedValue = resolveColorFunc(value, opt); + if (resolvedValue instanceof NullObject) { + setCache(cacheKey, resolvedValue); + return resolvedValue; + } + [cs, r, g, b, alpha] = resolvedValue as ComputedColorChannels; + } else if (value) { + const resolvedValue = resolveColorValue(value, opt); + if (resolvedValue instanceof NullObject) { + setCache(cacheKey, resolvedValue); + return resolvedValue; + } + [cs, r, g, b, alpha] = resolvedValue as ComputedColorChannels; + } + let res = ''; + switch (format) { + case 'hex': { + if ( + Number.isNaN(r) || + Number.isNaN(g) || + Number.isNaN(b) || + Number.isNaN(alpha) || + alpha === 0 + ) { + setCache(cacheKey, null); + return new NullObject(); + } + res = convertRgbToHex([r, g, b, 1]); + break; + } + case 'hexAlpha': { + if ( + Number.isNaN(r) || + Number.isNaN(g) || + Number.isNaN(b) || + Number.isNaN(alpha) + ) { + setCache(cacheKey, null); + return new NullObject(); + } + res = convertRgbToHex([r, g, b, alpha]); + break; + } + case VAL_COMP: + default: { + switch (cs) { + case 'rgb': { + if (alpha === 1) { + res = `${cs}(${r}, ${g}, ${b})`; + } else { + res = `${cs}a(${r}, ${g}, ${b}, ${alpha})`; + } + break; + } + case 'lab': + case 'lch': + case 'oklab': + case 'oklch': { + if (alpha === 1) { + res = `${cs}(${r} ${g} ${b})`; + } else { + res = `${cs}(${r} ${g} ${b} / ${alpha})`; + } + break; + } + // color() + default: { + if (alpha === 1) { + res = `color(${cs} ${r} ${g} ${b})`; + } else { + res = `color(${cs} ${r} ${g} ${b} / ${alpha})`; + } + } + } + } + } + setCache(cacheKey, res); + return res; +}; + +/** + * resolve CSS color + * @param value + * - CSS color value + * - system colors are not supported + * @param [opt] - options + * @param [opt.currentColor] + * - color to use for `currentcolor` keyword + * - if omitted, it will be treated as a missing color + * i.e. `rgb(none none none / none)` + * @param [opt.customProperty] + * - custom properties + * - pair of `--` prefixed property name and value, + * e.g. `customProperty: { '--some-color': '#0000ff' }` + * - and/or `callback` function to get the value of the custom property, + * e.g. `customProperty: { callback: someDeclaration.getPropertyValue }` + * @param [opt.dimension] + * - dimension, convert relative length to pixels + * - pair of unit and it's value as a number in pixels, + * e.g. `dimension: { em: 12, rem: 16, vw: 10.26 }` + * - and/or `callback` function to get the value as a number in pixels, + * e.g. `dimension: { callback: convertUnitToPixel }` + * @param [opt.format] + * - output format, one of below + * - `computedValue` (default), [computed value][139] of the color + * - `specifiedValue`, [specified value][140] of the color + * - `hex`, hex color notation, i.e. `rrggbb` + * - `hexAlpha`, hex color notation with alpha channel, i.e. `#rrggbbaa` + * @returns + * - one of rgba?(), #rrggbb(aa)?, color-name, '(empty-string)', + * color(color-space r g b / alpha), color(color-space x y z / alpha), + * lab(l a b / alpha), lch(l c h / alpha), oklab(l a b / alpha), + * oklch(l c h / alpha), null + * - in `computedValue`, values are numbers, however `rgb()` values are + * integers + * - in `specifiedValue`, returns `empty string` for unknown and/or invalid + * color + * - in `hex`, returns `null` for `transparent`, and also returns `null` if + * any of `r`, `g`, `b`, `alpha` is not a number + * - in `hexAlpha`, returns `#00000000` for `transparent`, + * however returns `null` if any of `r`, `g`, `b`, `alpha` is not a number + */ +export const resolve = (value: string, opt: Options = {}): string | null => { + opt.nullable = false; + const resolvedValue = resolveColor(value, opt); + if (resolvedValue instanceof NullObject) { + return null; + } + return resolvedValue as string; +}; diff --git a/node_modules/@asamuzakjp/css-color/src/js/typedef.ts b/node_modules/@asamuzakjp/css-color/src/js/typedef.ts new file mode 100644 index 00000000..007363eb --- /dev/null +++ b/node_modules/@asamuzakjp/css-color/src/js/typedef.ts @@ -0,0 +1,88 @@ +/** + * typedef + */ + +/* type definitions */ +/** + * @typedef Options - options + * @property [alpha] - enable alpha + * @property [colorSpace] - color space + * @property [currentColor] - color for currentcolor + * @property [customProperty] - custom properties + * @property [d50] - white point in d50 + * @property [dimension] - dimension + * @property [format] - output format + * @property [key] - key + */ +export interface Options { + alpha?: boolean; + colorScheme?: string; + colorSpace?: string; + currentColor?: string; + customProperty?: Record string)>; + d50?: boolean; + delimiter?: string | string[]; + dimension?: Record number)>; + format?: string; + nullable?: boolean; + preserveComment?: boolean; +} + +/** + * @type ColorChannels - color channels + */ +export type ColorChannels = [x: number, y: number, z: number, alpha: number]; + +/** + * @type StringColorChannels - color channels + */ +export type StringColorChannels = [ + x: string, + y: string, + z: string, + alpha: string | undefined +]; + +/** + * @type StringColorSpacedChannels - specified value + */ +export type StringColorSpacedChannels = [ + cs: string, + x: string, + y: string, + z: string, + alpha: string | undefined +]; + +/** + * @type ComputedColorChannels - computed value + */ +export type ComputedColorChannels = [ + cs: string, + x: number, + y: number, + z: number, + alpha: number +]; + +/** + * @type SpecifiedColorChannels - specified value + */ +export type SpecifiedColorChannels = [ + cs: string, + x: number | string, + y: number | string, + z: number | string, + alpha: number | string +]; + +/** + * @type MatchedRegExp - matched regexp array + */ +export type MatchedRegExp = [ + match: string, + gr1: string, + gr2: string, + gr3: string, + gr4: string +]; diff --git a/node_modules/@asamuzakjp/css-color/src/js/util.ts b/node_modules/@asamuzakjp/css-color/src/js/util.ts new file mode 100644 index 00000000..0ca502c4 --- /dev/null +++ b/node_modules/@asamuzakjp/css-color/src/js/util.ts @@ -0,0 +1,488 @@ +/** + * util + */ + +import { TokenType, tokenize } from '@csstools/css-tokenizer'; +import { CacheItem, createCacheKey, getCache, setCache } from './cache'; +import { isString } from './common'; +import { resolveColor } from './resolve'; +import { Options } from './typedef'; + +/* constants */ +import { NAMED_COLORS } from './color'; +import { SYN_COLOR_TYPE, SYN_MIX, VAL_SPEC } from './constant'; +const { + CloseParen: PAREN_CLOSE, + Comma: COMMA, + Comment: COMMENT, + Delim: DELIM, + EOF, + Function: FUNC, + Ident: IDENT, + OpenParen: PAREN_OPEN, + Whitespace: W_SPACE +} = TokenType; +const NAMESPACE = 'util'; + +/* numeric constants */ +const DEC = 10; +const HEX = 16; +const DEG = 360; +const DEG_HALF = 180; + +/* regexp */ +const REG_COLOR = new RegExp(`^(?:${SYN_COLOR_TYPE})$`); +const REG_FN_COLOR = + /^(?:(?:ok)?l(?:ab|ch)|color(?:-mix)?|hsla?|hwb|rgba?|var)\(/; +const REG_MIX = new RegExp(SYN_MIX); + +/** + * split value + * NOTE: comments are stripped, it can be preserved if, in the options param, + * `delimiter` is either ',' or '/' and with `preserveComment` set to `true` + * @param value - CSS value + * @param [opt] - options + * @returns array of values + */ +export const splitValue = (value: string, opt: Options = {}): string[] => { + if (isString(value)) { + value = value.trim(); + } else { + throw new TypeError(`${value} is not a string.`); + } + const { delimiter = ' ', preserveComment = false } = opt; + const cacheKey: string = createCacheKey( + { + namespace: NAMESPACE, + name: 'splitValue', + value + }, + { + delimiter, + preserveComment + } + ); + const cachedResult = getCache(cacheKey); + if (cachedResult instanceof CacheItem) { + return cachedResult.item as string[]; + } + let regDelimiter; + if (delimiter === ',') { + regDelimiter = /^,$/; + } else if (delimiter === '/') { + regDelimiter = /^\/$/; + } else { + regDelimiter = /^\s+$/; + } + const tokens = tokenize({ css: value }); + let nest = 0; + let str = ''; + const res: string[] = []; + while (tokens.length) { + const [type, value] = tokens.shift() as [TokenType, string]; + switch (type) { + case COMMA: { + if (regDelimiter.test(value)) { + if (nest === 0) { + res.push(str.trim()); + str = ''; + } else { + str += value; + } + } else { + str += value; + } + break; + } + case DELIM: { + if (regDelimiter.test(value)) { + if (nest === 0) { + res.push(str.trim()); + str = ''; + } else { + str += value; + } + } else { + str += value; + } + break; + } + case COMMENT: { + if (preserveComment && (delimiter === ',' || delimiter === '/')) { + str += value; + } + break; + } + case FUNC: + case PAREN_OPEN: { + str += value; + nest++; + break; + } + case PAREN_CLOSE: { + str += value; + nest--; + break; + } + case W_SPACE: { + if (regDelimiter.test(value)) { + if (nest === 0) { + if (str) { + res.push(str.trim()); + str = ''; + } + } else { + str += ' '; + } + } else if (!str.endsWith(' ')) { + str += ' '; + } + break; + } + default: { + if (type === EOF) { + res.push(str.trim()); + str = ''; + } else { + str += value; + } + } + } + } + setCache(cacheKey, res); + return res; +}; + +/** + * extract dashed-ident tokens + * @param value - CSS value + * @returns array of dashed-ident tokens + */ +export const extractDashedIdent = (value: string): string[] => { + if (isString(value)) { + value = value.trim(); + } else { + throw new TypeError(`${value} is not a string.`); + } + const cacheKey: string = createCacheKey({ + namespace: NAMESPACE, + name: 'extractDashedIdent', + value + }); + const cachedResult = getCache(cacheKey); + if (cachedResult instanceof CacheItem) { + return cachedResult.item as string[]; + } + const tokens = tokenize({ css: value }); + const items = new Set(); + while (tokens.length) { + const [type, value] = tokens.shift() as [TokenType, string]; + if (type === IDENT && value.startsWith('--')) { + items.add(value); + } + } + const res = [...items] as string[]; + setCache(cacheKey, res); + return res; +}; + +/** + * is color + * @param value - CSS value + * @param [opt] - options + * @returns result + */ +export const isColor = (value: unknown, opt: Options = {}): boolean => { + if (isString(value)) { + value = value.toLowerCase().trim(); + if (value && isString(value)) { + if (/^[a-z]+$/.test(value)) { + if ( + /^(?:currentcolor|transparent)$/.test(value) || + Object.hasOwn(NAMED_COLORS, value) + ) { + return true; + } + } else if (REG_COLOR.test(value) || REG_MIX.test(value)) { + return true; + } else if (REG_FN_COLOR.test(value)) { + opt.nullable = true; + if (!opt.format) { + opt.format = VAL_SPEC; + } + const resolvedValue = resolveColor(value, opt); + if (resolvedValue) { + return true; + } + } + } + } + return false; +}; + +/** + * value to JSON string + * @param value - CSS value + * @param [func] - stringify function + * @returns stringified value in JSON notation + */ +export const valueToJsonString = ( + value: unknown, + func: boolean = false +): string => { + if (typeof value === 'undefined') { + return ''; + } + const res = JSON.stringify(value, (_key, val) => { + let replacedValue; + if (typeof val === 'undefined') { + replacedValue = null; + } else if (typeof val === 'function') { + if (func) { + replacedValue = val.toString().replace(/\s/g, '').substring(0, HEX); + } else { + replacedValue = val.name; + } + } else if (val instanceof Map || val instanceof Set) { + replacedValue = [...val]; + } else if (typeof val === 'bigint') { + replacedValue = val.toString(); + } else { + replacedValue = val; + } + return replacedValue; + }); + return res; +}; + +/** + * round to specified precision + * @param value - numeric value + * @param bit - minimum bits + * @returns rounded value + */ +export const roundToPrecision = (value: number, bit: number = 0): number => { + if (!Number.isFinite(value)) { + throw new TypeError(`${value} is not a finite number.`); + } + if (!Number.isFinite(bit)) { + throw new TypeError(`${bit} is not a finite number.`); + } else if (bit < 0 || bit > HEX) { + throw new RangeError(`${bit} is not between 0 and ${HEX}.`); + } + if (bit === 0) { + return Math.round(value); + } + let val; + if (bit === HEX) { + val = value.toPrecision(6); + } else if (bit < DEC) { + val = value.toPrecision(4); + } else { + val = value.toPrecision(5); + } + return parseFloat(val); +}; + +/** + * interpolate hue + * @param hueA - hue value + * @param hueB - hue value + * @param arc - shorter | longer | increasing | decreasing + * @returns result - [hueA, hueB] + */ +export const interpolateHue = ( + hueA: number, + hueB: number, + arc: string = 'shorter' +): [number, number] => { + if (!Number.isFinite(hueA)) { + throw new TypeError(`${hueA} is not a finite number.`); + } + if (!Number.isFinite(hueB)) { + throw new TypeError(`${hueB} is not a finite number.`); + } + switch (arc) { + case 'decreasing': { + if (hueB > hueA) { + hueA += DEG; + } + break; + } + case 'increasing': { + if (hueB < hueA) { + hueB += DEG; + } + break; + } + case 'longer': { + if (hueB > hueA && hueB < hueA + DEG_HALF) { + hueA += DEG; + } else if (hueB > hueA + DEG_HALF * -1 && hueB <= hueA) { + hueB += DEG; + } + break; + } + case 'shorter': + default: { + if (hueB > hueA + DEG_HALF) { + hueA += DEG; + } else if (hueB < hueA + DEG_HALF * -1) { + hueB += DEG; + } + } + } + return [hueA, hueB]; +}; + +/* absolute font size to pixel ratio */ +const absoluteFontSize = new Map([ + ['xx-small', 9 / 16], + ['x-small', 5 / 8], + ['small', 13 / 16], + ['medium', 1], + ['large', 9 / 8], + ['x-large', 3 / 2], + ['xx-large', 2], + ['xxx-large', 3] +]); + +/* relative font size to pixel ratio */ +const relativeFontSize = new Map([ + ['smaller', 1 / 1.2], + ['larger', 1.2] +]); + +/* absolute length to pixel ratio */ +const absoluteLength = new Map([ + ['cm', 96 / 2.54], + ['mm', 96 / 2.54 / 10], + ['q', 96 / 2.54 / 40], + ['in', 96], + ['pc', 96 / 6], + ['pt', 96 / 72], + ['px', 1] +]); + +/* relative length to pixel ratio */ +const relativeLength = new Map([ + ['rcap', 1], + ['rch', 0.5], + ['rem', 1], + ['rex', 0.5], + ['ric', 1], + ['rlh', 1.2] +]); + +/** + * resolve length in pixels + * @param value - value + * @param unit - unit + * @param [opt] - options + * @returns pixelated value + */ +export const resolveLengthInPixels = ( + value: number | string, + unit: string | undefined, + opt: Options = {} +): number => { + const { dimension = {} } = opt; + const { callback, em, rem, vh, vw } = dimension as { + callback: (K: string) => number; + em: number; + rem: number; + vh: number; + vw: number; + }; + if (isString(value)) { + value = value.toLowerCase().trim(); + if (absoluteFontSize.has(value)) { + return Number(absoluteFontSize.get(value)) * rem; + } else if (relativeFontSize.has(value)) { + return Number(relativeFontSize.get(value)) * em; + } + return Number.NaN; + } else if (Number.isFinite(value) && unit) { + if (Object.hasOwn(dimension, unit)) { + return value * Number(dimension[unit]); + } else if (typeof callback === 'function') { + return value * callback(unit); + } else if (absoluteLength.has(unit)) { + return value * Number(absoluteLength.get(unit)); + } else if (relativeLength.has(unit)) { + return value * Number(relativeLength.get(unit)) * rem; + } else if (relativeLength.has(`r${unit}`)) { + return value * Number(relativeLength.get(`r${unit}`)) * em; + } else { + switch (unit) { + case 'vb': + case 'vi': { + return value * vw; + } + case 'vmax': { + if (vh > vw) { + return value * vh; + } + return value * vw; + } + case 'vmin': { + if (vh < vw) { + return value * vh; + } + return value * vw; + } + default: { + // unsupported or invalid unit + return Number.NaN; + } + } + } + } + // unsupported or invalid value + return Number.NaN; +}; + +/** + * is absolute size or length + * @param value - value + * @param unit - unit + * @returns result + */ +export const isAbsoluteSizeOrLength = ( + value: number | string, + unit: string | undefined +): boolean => { + if (isString(value)) { + value = value.toLowerCase().trim(); + return absoluteFontSize.has(value); + } else if (isString(unit)) { + unit = unit.toLowerCase().trim(); + return absoluteLength.has(unit); + } + return value === 0; +}; + +/** + * is absolute font size + * @param value - value + * @returns result + */ +export const isAbsoluteFontSize = (value: unknown): boolean => { + if (isString(value)) { + const size = value.toLowerCase().trim() as string; + if (/^[a-z-]+$/.test(size)) { + return absoluteFontSize.has(size); + } else { + const [, val, unit] = /^(\d+(?:\.\d+)?|\.\d+)([a-z-]+)?$/.exec( + size + ) as RegExpExecArray; + if (unit) { + return absoluteLength.has(unit); + } else if (val) { + const num = parseFloat(val); + return num === 0; + } + } + } + return false; +}; diff --git a/node_modules/@asamuzakjp/dom-selector/LICENSE b/node_modules/@asamuzakjp/dom-selector/LICENSE new file mode 100644 index 00000000..f3f97a30 --- /dev/null +++ b/node_modules/@asamuzakjp/dom-selector/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 asamuzaK (Kazz) + +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. diff --git a/node_modules/@asamuzakjp/dom-selector/README.md b/node_modules/@asamuzakjp/dom-selector/README.md new file mode 100644 index 00000000..50099f37 --- /dev/null +++ b/node_modules/@asamuzakjp/dom-selector/README.md @@ -0,0 +1,324 @@ +# DOM Selector + +[![build](https://github.com/asamuzaK/domSelector/actions/workflows/node.js.yml/badge.svg)](https://github.com/asamuzaK/domSelector/actions/workflows/node.js.yml) +[![CodeQL](https://github.com/asamuzaK/domSelector/actions/workflows/github-code-scanning/codeql/badge.svg)](https://github.com/asamuzaK/domSelector/actions/workflows/github-code-scanning/codeql) +[![npm (scoped)](https://img.shields.io/npm/v/@asamuzakjp/dom-selector)](https://www.npmjs.com/package/@asamuzakjp/dom-selector) + +A CSS selector engine. + +## Install + +```console +npm i @asamuzakjp/dom-selector +``` + +## Usage + +```javascript +import { DOMSelector } from '@asamuzakjp/dom-selector'; +import { JSDOM } from 'jsdom'; + +const { window } = new JSDOM(); +const { + closest, matches, querySelector, querySelectorAll +} = new DOMSelector(window); +``` + + + +### matches(selector, node, opt) + +matches - equivalent to [Element.matches()][64] + +#### Parameters + +- `selector` **[string][59]** CSS selector +- `node` **[object][60]** Element node +- `opt` **[object][60]?** options + - `opt.noexcept` **[boolean][61]?** no exception + - `opt.warn` **[boolean][61]?** console warn e.g. unsupported pseudo-class + +Returns **[boolean][61]** `true` if matched, `false` otherwise + + +### closest(selector, node, opt) + +closest - equivalent to [Element.closest()][65] + +#### Parameters + +- `selector` **[string][59]** CSS selector +- `node` **[object][60]** Element node +- `opt` **[object][60]?** options + - `opt.noexcept` **[boolean][61]?** no exception + - `opt.warn` **[boolean][61]?** console warn e.g. unsupported pseudo-class + +Returns **[object][60]?** matched node + + +### querySelector(selector, node, opt) + +querySelector - equivalent to [Document.querySelector()][66], [DocumentFragment.querySelector()][67] and [Element.querySelector()][68] + +#### Parameters + +- `selector` **[string][59]** CSS selector +- `node` **[object][60]** Document, DocumentFragment or Element node +- `opt` **[object][60]?** options + - `opt.noexcept` **[boolean][61]?** no exception + - `opt.warn` **[boolean][61]?** console warn e.g. unsupported pseudo-class + +Returns **[object][60]?** matched node + + +### querySelectorAll(selector, node, opt) + +querySelectorAll - equivalent to [Document.querySelectorAll()][69], [DocumentFragment.querySelectorAll()][70] and [Element.querySelectorAll()][71] +**NOTE**: returns Array, not NodeList + +#### Parameters + +- `selector` **[string][59]** CSS selector +- `node` **[object][60]** Document, DocumentFragment or Element node +- `opt` **[object][60]?** options + - `opt.noexcept` **[boolean][61]?** no exception + - `opt.warn` **[boolean][61]?** console warn e.g. unsupported pseudo-class + +Returns **[Array][62]<([object][60] \| [undefined][63])>** array of matched nodes + + +## Monkey patch jsdom + +``` javascript +import { DOMSelector } from '@asamuzakjp/dom-selector'; +import { JSDOM } from 'jsdom'; + +const dom = new JSDOM('', { + runScripts: 'dangerously', + url: 'http://localhost/', + beforeParse: window => { + const domSelector = new DOMSelector(window); + + const matches = domSelector.matches.bind(domSelector); + window.Element.prototype.matches = function (...args) { + if (!args.length) { + throw new window.TypeError('1 argument required, but only 0 present.'); + } + const [selector] = args; + return matches(selector, this); + }; + + const closest = domSelector.closest.bind(domSelector); + window.Element.prototype.closest = function (...args) { + if (!args.length) { + throw new window.TypeError('1 argument required, but only 0 present.'); + } + const [selector] = args; + return closest(selector, this); + }; + + const querySelector = domSelector.querySelector.bind(domSelector); + window.Document.prototype.querySelector = function (...args) { + if (!args.length) { + throw new window.TypeError('1 argument required, but only 0 present.'); + } + const [selector] = args; + return querySelector(selector, this); + }; + window.DocumentFragment.prototype.querySelector = function (...args) { + if (!args.length) { + throw new window.TypeError('1 argument required, but only 0 present.'); + } + const [selector] = args; + return querySelector(selector, this); + }; + window.Element.prototype.querySelector = function (...args) { + if (!args.length) { + throw new window.TypeError('1 argument required, but only 0 present.'); + } + const [selector] = args; + return querySelector(selector, this); + }; + + const querySelectorAll = domSelector.querySelectorAll.bind(domSelector); + window.Document.prototype.querySelectorAll = function (...args) { + if (!args.length) { + throw new window.TypeError('1 argument required, but only 0 present.'); + } + const [selector] = args; + return querySelectorAll(selector, this); + }; + window.DocumentFragment.prototype.querySelectorAll = function (...args) { + if (!args.length) { + throw new window.TypeError('1 argument required, but only 0 present.'); + } + const [selector] = args; + return querySelectorAll(selector, this); + }; + window.Element.prototype.querySelectorAll = function (...args) { + if (!args.length) { + throw new window.TypeError('1 argument required, but only 0 present.'); + } + const [selector] = args; + return querySelectorAll(selector, this); + }; + } +}); +``` + + +## Supported CSS selectors + +|Pattern|Supported|Note| +|:--------|:-------:|:--------| +|\*|✓| | +|E|✓| | +|ns\|E|✓| | +|\*\|E|✓| | +|\|E|✓| | +|E F|✓| | +|E > F|✓| | +|E + F|✓| | +|E ~ F|✓| | +|F \|\| E|Unsupported| | +|E.warning|✓| | +|E#myid|✓| | +|E\[foo\]|✓| | +|E\[foo="bar"\]|✓| | +|E\[foo="bar" i\]|✓| | +|E\[foo="bar" s\]|✓| | +|E\[foo~="bar"\]|✓| | +|E\[foo^="bar"\]|✓| | +|E\[foo$="bar"\]|✓| | +|E\[foo*="bar"\]|✓| | +|E\[foo\|="en"\]|✓| | +|E:is(s1, s2, …)|✓| | +|E:not(s1, s2, …)|✓| | +|E:where(s1, s2, …)|✓| | +|E:has(rs1, rs2, …)|✓| | +|E:defined|Partially supported|Matching with MathML is not yet supported.| +|E:dir(ltr)|✓| | +|E:lang(en)|✓| | +|E:any‑link|✓| | +|E:link|✓| | +|E:visited|✓|Returns `false` or `null` to prevent fingerprinting.| +|E:local‑link|✓| | +|E:target|✓| | +|E:target‑within|✓| | +|E:scope|✓| | +|E:hover|✓| | +|E:active|✓| | +|E:focus|✓| | +|E:focus‑visible|✓| | +|E:focus‑within|✓| | +|E:current|Unsupported| | +|E:current(s)|Unsupported| | +|E:past|Unsupported| | +|E:future|Unsupported| | +|E:open
E:closed|Partially supported|Matching with <select>, e.g. `select:open`, is not supported.| +|E:popover-open|Unsupported| | +|E:enabled
E:disabled|✓| | +|E:read‑write
E:read‑only|✓| | +|E:placeholder‑shown|✓| | +|E:default|✓| | +|E:checked|✓| | +|E:indeterminate|✓| | +|E:blank|Unsupported| | +|E:valid
E:invalid|✓| | +|E:in-range
E:out-of-range|✓| | +|E:required
E:optional|✓| | +|E:user‑valid
E:user‑invalid|Unsupported| | +|E:root|✓| | +|E:empty|✓| | +|E:nth‑child(n [of S]?)|✓| | +|E:nth‑last‑child(n [of S]?)|✓| | +|E:first‑child|✓| | +|E:last‑child|✓| | +|E:only‑child|✓| | +|E:nth‑of‑type(n)|✓| | +|E:nth‑last‑of‑type(n)|✓| | +|E:first‑of‑type|✓| | +|E:last‑of‑type|✓| | +|E:only‑of‑type|✓| | +|E:nth‑col(n)|Unsupported| | +|E:nth‑last‑col(n)|Unsupported| | +|CE:state(v)|✓|*1| +|:host|✓| | +|:host(s)|✓| | +|:host(:state(v))|✓|*1| +|:host:has(rs1, rs2, ...)|✓| | +|:host(s):has(rs1, rs2, ...)|✓| | +|:host‑context(s)|✓| | +|:host‑context(s):has(rs1, rs2, ...)|✓| | +|&|✓|Only supports outermost `&`, i.e. equivalent to `:scope`| + +*1: `ElementInternals.states`, i.e. `CustomStateSet`, is not implemented in jsdom, so you need to apply a patch in the custom element constructor. + +``` javascript +class LabeledCheckbox extends window.HTMLElement { + #internals; + constructor() { + super(); + this.#internals = this.attachInternals(); + // patch CustomStateSet + if (!this.#internals.states) { + this.#internals.states = new Set(); + } + this.addEventListener('click', this._onClick.bind(this)); + } + get checked() { + return this.#internals.states.has('checked'); + } + set checked(flag) { + if (flag) { + this.#internals.states.add('checked'); + } else { + this.#internals.states.delete('checked'); + } + } + _onClick(event) { + this.checked = !this.checked; + } +} +``` + + +## Performance + +See [benchmark](https://github.com/asamuzaK/domSelector/actions/workflows/benchmark.yml) for the latest results. + + +## Acknowledgments + +The following resources have been of great help in the development of the DOM Selector. + +- [CSSTree](https://github.com/csstree/csstree) +- [selery](https://github.com/danburzo/selery) +- [jsdom](https://github.com/jsdom/jsdom) +- [nwsapi](https://github.com/dperini/nwsapi) + +--- +Copyright (c) 2023 [asamuzaK (Kazz)](https://github.com/asamuzaK/) + + +[1]: #matches +[2]: #parameters +[3]: #closest +[4]: #parameters-1 +[5]: #queryselector +[6]: #parameters-2 +[7]: #queryselectorall +[8]: #parameters-3 +[59]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String +[60]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object +[61]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean +[62]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array +[63]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/undefined +[64]: https://developer.mozilla.org/docs/Web/API/Element/matches +[65]: https://developer.mozilla.org/docs/Web/API/Element/closest +[66]: https://developer.mozilla.org/docs/Web/API/Document/querySelector +[67]: https://developer.mozilla.org/docs/Web/API/DocumentFragment/querySelector +[68]: https://developer.mozilla.org/docs/Web/API/Element/querySelector +[69]: https://developer.mozilla.org/docs/Web/API/Document/querySelectorAll +[70]: https://developer.mozilla.org/docs/Web/API/DocumentFragment/querySelectorAll +[71]: https://developer.mozilla.org/docs/Web/API/Element/querySelectorAll diff --git a/node_modules/@asamuzakjp/dom-selector/package.json b/node_modules/@asamuzakjp/dom-selector/package.json new file mode 100644 index 00000000..3cda9db0 --- /dev/null +++ b/node_modules/@asamuzakjp/dom-selector/package.json @@ -0,0 +1,75 @@ +{ + "name": "@asamuzakjp/dom-selector", + "description": "A CSS selector engine.", + "author": "asamuzaK", + "license": "MIT", + "homepage": "https://github.com/asamuzaK/domSelector#readme", + "bugs": { + "url": "https://github.com/asamuzaK/domSelector/issues" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/asamuzaK/domSelector.git" + }, + "files": [ + "src", + "types" + ], + "type": "module", + "exports": { + ".": { + "types": "./types/index.d.ts", + "default": "./src/index.js" + }, + "./package.json": "./package.json" + }, + "dependencies": { + "@asamuzakjp/nwsapi": "^2.3.9", + "bidi-js": "^1.0.3", + "css-tree": "^3.2.1", + "is-potential-custom-element-name": "^1.0.1", + "lru-cache": "^11.2.7" + }, + "devDependencies": { + "@types/css-tree": "^2.3.11", + "benchmark": "^2.1.4", + "c8": "^11.0.0", + "chai": "^6.2.2", + "commander": "^14.0.3", + "eslint": "^9.39.4", + "eslint-config-prettier": "^10.1.8", + "eslint-plugin-jsdoc": "^62.8.0", + "eslint-plugin-prettier": "^5.5.5", + "eslint-plugin-regexp": "^3.1.0", + "eslint-plugin-unicorn": "^63.0.0", + "globals": "^17.4.0", + "jsdom": "^29.0.1", + "mocha": "^11.7.5", + "neostandard": "^0.13.0", + "prettier": "^3.8.1", + "sinon": "^21.0.3", + "typescript": "^5.9.3", + "wpt-runner": "^6.1.0" + }, + "overrides": { + "c8": { + "yargs": "^18.0.0" + }, + "jsdom": "$jsdom", + "serialize-javascript": "^7.0.4" + }, + "scripts": { + "bench": "node benchmark/bench.js", + "bench:sizzle": "node benchmark/bench-sizzle.js", + "build": "npm run tsc && npm run lint && npm test", + "lint": "eslint --fix .", + "test": "c8 --reporter=text mocha --parallel --exit test/**/*.test.js", + "test:wpt": "node test/wpt/wpt-runner.js", + "tsc": "node scripts/index clean --dir=types -i && npx tsc", + "update:wpt": "git submodule update --init --recursive --remote" + }, + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + }, + "version": "7.0.4" +} diff --git a/node_modules/@asamuzakjp/dom-selector/src/index.js b/node_modules/@asamuzakjp/dom-selector/src/index.js new file mode 100644 index 00000000..b9050817 --- /dev/null +++ b/node_modules/@asamuzakjp/dom-selector/src/index.js @@ -0,0 +1,348 @@ +/*! + * DOM Selector - A CSS selector engine. + * @license MIT + * @copyright asamuzaK (Kazz) + * @see {@link https://github.com/asamuzaK/domSelector/blob/main/LICENSE} + */ + +/* import */ +import { LRUCache } from 'lru-cache'; +import { Finder } from './js/finder.js'; +import { filterSelector, getType, initNwsapi } from './js/utility.js'; + +/* constants */ +import { + DOCUMENT_NODE, + DOCUMENT_FRAGMENT_NODE, + ELEMENT_NODE, + TARGET_ALL, + TARGET_FIRST, + TARGET_LINEAL, + TARGET_SELF +} from './js/constant.js'; +const MAX_CACHE = 1024; + +/** + * @typedef {object} CheckResult + * @property {boolean} match - The match result. + * @property {string?} pseudoElement - The pseudo-element, if any. + * @property {object?} ast - The AST object. + */ + +/* DOMSelector */ +export class DOMSelector { + /* private fields */ + #window; + #document; + #finder; + #idlUtils; + #nwsapi; + #cache; + + /** + * Creates an instance of DOMSelector. + * @param {Window} window - The window object. + * @param {Document} document - The document object. + * @param {object} [opt] - Options. + */ + constructor(window, document, opt = {}) { + const { idlUtils } = opt; + this.#window = window; + this.#document = document ?? window.document; + this.#finder = new Finder(window); + this.#idlUtils = idlUtils; + this.#nwsapi = initNwsapi(window, document); + this.#cache = new LRUCache({ + max: MAX_CACHE + }); + } + + /** + * Clears the internal cache of finder results. + * @returns {void} + */ + clear = () => { + this.#finder.clearResults(true); + }; + + /** + * Checks if an element matches a CSS selector. + * @param {string} selector - The CSS selector to check against. + * @param {Element} node - The element node to check. + * @param {object} [opt] - Optional parameters. + * @returns {CheckResult} An object containing the check result. + */ + check = (selector, node, opt = {}) => { + if (!node?.nodeType) { + const e = new this.#window.TypeError(`Unexpected type ${getType(node)}`); + return this.#finder.onError(e, opt); + } else if (node.nodeType !== ELEMENT_NODE) { + const e = new this.#window.TypeError(`Unexpected node ${node.nodeName}`); + return this.#finder.onError(e, opt); + } + const document = node.ownerDocument; + if ( + document === this.#document && + document.contentType === 'text/html' && + document.documentElement && + node.parentNode + ) { + const cacheKey = `check_${selector}`; + let filterMatches = false; + if (this.#cache.has(cacheKey)) { + filterMatches = this.#cache.get(cacheKey); + } else { + filterMatches = filterSelector(selector, TARGET_SELF); + this.#cache.set(cacheKey, filterMatches); + } + if (filterMatches) { + try { + const n = this.#idlUtils ? this.#idlUtils.wrapperForImpl(node) : node; + const match = this.#nwsapi.match(selector, n); + let ast = null; + if (match) { + const astCacheKey = `check_ast_${selector}`; + if (this.#cache.has(astCacheKey)) { + ast = this.#cache.get(astCacheKey); + } else { + ast = this.#finder.getAST(selector); + this.#cache.set(astCacheKey, ast); + } + } + return { + match, + ast, + pseudoElement: null + }; + } catch (e) { + // fall through + } + } + } + if (this.#idlUtils) { + node = this.#idlUtils.wrapperForImpl(node); + } + opt.check = true; + opt.noexcept = true; + opt.warn = false; + return this.#finder.setup(selector, node, opt).find(TARGET_SELF); + }; + + /** + * Returns true if the element matches the selector. + * @param {string} selector - The CSS selector to match against. + * @param {Element} node - The element node to test. + * @param {object} [opt] - Optional parameters. + * @returns {boolean} `true` if the element matches, or `false` otherwise. + */ + matches = (selector, node, opt = {}) => { + if (!node?.nodeType) { + const e = new this.#window.TypeError(`Unexpected type ${getType(node)}`); + return this.#finder.onError(e, opt); + } else if (node.nodeType !== ELEMENT_NODE) { + const e = new this.#window.TypeError(`Unexpected node ${node.nodeName}`); + return this.#finder.onError(e, opt); + } + const document = node.ownerDocument; + if ( + document === this.#document && + document.contentType === 'text/html' && + document.documentElement && + node.parentNode + ) { + const cacheKey = `matches_${selector}`; + let filterMatches = false; + if (this.#cache.has(cacheKey)) { + filterMatches = this.#cache.get(cacheKey); + } else { + filterMatches = filterSelector(selector, TARGET_SELF); + this.#cache.set(cacheKey, filterMatches); + } + if (filterMatches) { + try { + const n = this.#idlUtils ? this.#idlUtils.wrapperForImpl(node) : node; + return this.#nwsapi.match(selector, n); + } catch (e) { + // fall through + } + } + } + let res; + try { + if (this.#idlUtils) { + node = this.#idlUtils.wrapperForImpl(node); + } + const nodes = this.#finder.setup(selector, node, opt).find(TARGET_SELF); + res = nodes.size; + } catch (e) { + this.#finder.onError(e, opt); + } + return !!res; + }; + + /** + * Traverses up the DOM tree to find the first node that matches the selector. + * @param {string} selector - The CSS selector to match against. + * @param {Element} node - The element from which to start traversing. + * @param {object} [opt] - Optional parameters. + * @returns {?Element} The first matching ancestor element, or `null`. + */ + closest = (selector, node, opt = {}) => { + if (!node?.nodeType) { + const e = new this.#window.TypeError(`Unexpected type ${getType(node)}`); + return this.#finder.onError(e, opt); + } else if (node.nodeType !== ELEMENT_NODE) { + const e = new this.#window.TypeError(`Unexpected node ${node.nodeName}`); + return this.#finder.onError(e, opt); + } + const document = node.ownerDocument; + if ( + document === this.#document && + document.contentType === 'text/html' && + document.documentElement && + node.parentNode + ) { + const cacheKey = `closest_${selector}`; + let filterMatches = false; + if (this.#cache.has(cacheKey)) { + filterMatches = this.#cache.get(cacheKey); + } else { + filterMatches = filterSelector(selector, TARGET_LINEAL); + this.#cache.set(cacheKey, filterMatches); + } + if (filterMatches) { + try { + const n = this.#idlUtils ? this.#idlUtils.wrapperForImpl(node) : node; + return this.#nwsapi.closest(selector, n); + } catch (e) { + // fall through + } + } + } + let res; + try { + if (this.#idlUtils) { + node = this.#idlUtils.wrapperForImpl(node); + } + const nodes = this.#finder.setup(selector, node, opt).find(TARGET_LINEAL); + if (nodes.size) { + let refNode = node; + while (refNode) { + if (nodes.has(refNode)) { + res = refNode; + break; + } + refNode = refNode.parentNode; + } + } + } catch (e) { + this.#finder.onError(e, opt); + } + return res ?? null; + }; + + /** + * Returns the first element within the subtree that matches the selector. + * @param {string} selector - The CSS selector to match. + * @param {Document|DocumentFragment|Element} node - The node to find within. + * @param {object} [opt] - Optional parameters. + * @returns {?Element} The first matching element, or `null`. + */ + querySelector = (selector, node, opt = {}) => { + if (!node?.nodeType) { + const e = new this.#window.TypeError(`Unexpected type ${getType(node)}`); + return this.#finder.onError(e, opt); + } + const document = + node.nodeType === DOCUMENT_NODE ? node : node.ownerDocument; + if ( + document === this.#document && + document.contentType === 'text/html' && + document.documentElement && + (node.nodeType !== DOCUMENT_FRAGMENT_NODE || !node.host) + ) { + const cacheKey = `querySelector_${selector}`; + let filterMatches = false; + if (this.#cache.has(cacheKey)) { + filterMatches = this.#cache.get(cacheKey); + } else { + filterMatches = filterSelector(selector, TARGET_FIRST); + this.#cache.set(cacheKey, filterMatches); + } + if (filterMatches) { + try { + const n = this.#idlUtils ? this.#idlUtils.wrapperForImpl(node) : node; + return this.#nwsapi.first(selector, n); + } catch (e) { + // fall through + } + } + } + let res; + try { + if (this.#idlUtils) { + node = this.#idlUtils.wrapperForImpl(node); + } + const nodes = this.#finder.setup(selector, node, opt).find(TARGET_FIRST); + if (nodes.size) { + [res] = [...nodes]; + } + } catch (e) { + this.#finder.onError(e, opt); + } + return res ?? null; + }; + + /** + * Returns an array of elements within the subtree that match the selector. + * Note: This method returns an Array, not a NodeList. + * @param {string} selector - The CSS selector to match. + * @param {Document|DocumentFragment|Element} node - The node to find within. + * @param {object} [opt] - Optional parameters. + * @returns {Array} An array of elements, or an empty array. + */ + querySelectorAll = (selector, node, opt = {}) => { + if (!node?.nodeType) { + const e = new this.#window.TypeError(`Unexpected type ${getType(node)}`); + return this.#finder.onError(e, opt); + } + const document = + node.nodeType === DOCUMENT_NODE ? node : node.ownerDocument; + if ( + document === this.#document && + document.contentType === 'text/html' && + document.documentElement && + (node.nodeType !== DOCUMENT_FRAGMENT_NODE || !node.host) + ) { + const cacheKey = `querySelectorAll_${selector}`; + let filterMatches = false; + if (this.#cache.has(cacheKey)) { + filterMatches = this.#cache.get(cacheKey); + } else { + filterMatches = filterSelector(selector, TARGET_ALL); + this.#cache.set(cacheKey, filterMatches); + } + if (filterMatches) { + try { + const n = this.#idlUtils ? this.#idlUtils.wrapperForImpl(node) : node; + return this.#nwsapi.select(selector, n); + } catch (e) { + // fall through + } + } + } + let res; + try { + if (this.#idlUtils) { + node = this.#idlUtils.wrapperForImpl(node); + } + const nodes = this.#finder.setup(selector, node, opt).find(TARGET_ALL); + if (nodes.size) { + res = [...nodes]; + } + } catch (e) { + this.#finder.onError(e, opt); + } + return res ?? []; + }; +} diff --git a/node_modules/@asamuzakjp/dom-selector/src/js/constant.js b/node_modules/@asamuzakjp/dom-selector/src/js/constant.js new file mode 100644 index 00000000..02986ecf --- /dev/null +++ b/node_modules/@asamuzakjp/dom-selector/src/js/constant.js @@ -0,0 +1,129 @@ +/** + * constant.js + */ + +/* string */ +export const ATRULE = 'Atrule'; +export const ATTR_SELECTOR = 'AttributeSelector'; +export const CLASS_SELECTOR = 'ClassSelector'; +export const COMBINATOR = 'Combinator'; +export const IDENT = 'Identifier'; +export const ID_SELECTOR = 'IdSelector'; +export const NOT_SUPPORTED_ERR = 'NotSupportedError'; +export const NTH = 'Nth'; +export const OPERATOR = 'Operator'; +export const PS_CLASS_SELECTOR = 'PseudoClassSelector'; +export const PS_ELEMENT_SELECTOR = 'PseudoElementSelector'; +export const RULE = 'Rule'; +export const SCOPE = 'Scope'; +export const SELECTOR = 'Selector'; +export const SELECTOR_LIST = 'SelectorList'; +export const STRING = 'String'; +export const SYNTAX_ERR = 'SyntaxError'; +export const TARGET_ALL = 'all'; +export const TARGET_FIRST = 'first'; +export const TARGET_LINEAL = 'lineal'; +export const TARGET_SELF = 'self'; +export const TYPE_SELECTOR = 'TypeSelector'; + +/* numeric */ +export const BIT_01 = 1; +export const BIT_02 = 2; +export const BIT_04 = 4; +export const BIT_08 = 8; +export const BIT_16 = 0x10; +export const BIT_32 = 0x20; +export const BIT_FFFF = 0xffff; +export const DUO = 2; +export const HEX = 16; +export const TYPE_FROM = 8; +export const TYPE_TO = -1; + +/* Node */ +export const ELEMENT_NODE = 1; +export const TEXT_NODE = 3; +export const DOCUMENT_NODE = 9; +export const DOCUMENT_FRAGMENT_NODE = 11; +export const DOCUMENT_POSITION_PRECEDING = 2; +export const DOCUMENT_POSITION_CONTAINS = 8; +export const DOCUMENT_POSITION_CONTAINED_BY = 0x10; + +/* NodeFilter */ +export const SHOW_ALL = 0xffffffff; +export const SHOW_CONTAINER = 0x501; +export const SHOW_DOCUMENT = 0x100; +export const SHOW_DOCUMENT_FRAGMENT = 0x400; +export const SHOW_ELEMENT = 1; + +/* selectors */ +export const ALPHA_NUM = '[A-Z\\d]+'; +export const CHILD_IDX = '(?:first|last|only)-(?:child|of-type)'; +export const DIGIT = '(?:0|[1-9]\\d*)'; +export const LANG_PART = `(?:-${ALPHA_NUM})*`; +export const PSEUDO_CLASS = `(?:any-)?link|${CHILD_IDX}|checked|empty|indeterminate|read-(?:only|write)|target`; +export const ANB = `[+-]?(?:${DIGIT}n?|n)|(?:[+-]?${DIGIT})?n\\s*[+-]\\s*${DIGIT}`; +// combinators +export const COMBO = '\\s?[\\s>~+]\\s?'; +export const DESCEND = '\\s?[\\s>]\\s?'; +export const SIBLING = '\\s?[+~]\\s?'; +// LOGIC_IS: :is() +export const LOGIC_IS = `:is\\(\\s*[^)]+\\s*\\)`; +// N_TH: excludes An+B with selector list, e.g. :nth-child(2n+1 of .foo) +export const N_TH = `nth-(?:last-)?(?:child|of-type)\\(\\s*(?:even|odd|${ANB})\\s*\\)`; +// SUB_TYPE: attr, id, class, pseudo-class, note that [foo|=bar] is excluded +export const SUB_TYPE = '\\[[^|\\]]+\\]|[#.:][\\w-]+'; +export const SUB_TYPE_WO_PSEUDO = '\\[[^|\\]]+\\]|[#.][\\w-]+'; +// TAG_TYPE: *, tag +export const TAG_TYPE = '\\*|[A-Za-z][\\w-]*'; +export const TAG_TYPE_I = '\\*|[A-Z][\\w-]*'; +export const COMPOUND = `(?:${TAG_TYPE}|(?:${TAG_TYPE})?(?:${SUB_TYPE})+)`; +export const COMPOUND_L = `(?:${TAG_TYPE}|(?:${TAG_TYPE})?(?:${SUB_TYPE}|${LOGIC_IS})+)`; +export const COMPOUND_I = `(?:${TAG_TYPE_I}|(?:${TAG_TYPE_I})?(?:${SUB_TYPE})+)`; +export const COMPOUND_WO_PSEUDO = `(?:${TAG_TYPE}|(?:${TAG_TYPE})?(?:${SUB_TYPE_WO_PSEUDO})+)`; +export const COMPLEX = `${COMPOUND}(?:${COMBO}${COMPOUND})*`; +export const COMPLEX_L = `${COMPOUND_L}(?:${COMBO}${COMPOUND_L})*`; +export const HAS_COMPOUND = `has\\([\\s>]?\\s*${COMPOUND_WO_PSEUDO}\\s*\\)`; +export const LOGIC_COMPOUND = `(?:is|not)\\(\\s*${COMPOUND_L}(?:\\s*,\\s*${COMPOUND_L})*\\s*\\)`; +export const LOGIC_COMPLEX = `(?:is|not)\\(\\s*${COMPLEX_L}(?:\\s*,\\s*${COMPLEX_L})*\\s*\\)`; + +/* forms and input types */ +export const FORM_PARTS = Object.freeze([ + 'button', + 'input', + 'select', + 'textarea' +]); +export const INPUT_BUTTON = Object.freeze(['button', 'reset', 'submit']); +export const INPUT_CHECK = Object.freeze(['checkbox', 'radio']); +export const INPUT_DATE = Object.freeze([ + 'date', + 'datetime-local', + 'month', + 'time', + 'week' +]); +export const INPUT_TEXT = Object.freeze([ + 'email', + 'password', + 'search', + 'tel', + 'text', + 'url' +]); +export const INPUT_EDIT = Object.freeze([ + ...INPUT_DATE, + ...INPUT_TEXT, + 'number' +]); +export const INPUT_LTR = Object.freeze([ + ...INPUT_CHECK, + 'color', + 'date', + 'image', + 'number', + 'range', + 'time' +]); + +/* logical combination pseudo-classes */ +export const KEYS_LOGICAL = new Set(['has', 'is', 'not', 'where']); diff --git a/node_modules/@asamuzakjp/dom-selector/src/js/finder.js b/node_modules/@asamuzakjp/dom-selector/src/js/finder.js new file mode 100644 index 00000000..70c66fbb --- /dev/null +++ b/node_modules/@asamuzakjp/dom-selector/src/js/finder.js @@ -0,0 +1,3122 @@ +/** + * finder.js + */ + +/* import */ +import { + matchAttributeSelector, + matchDirectionPseudoClass, + matchDisabledPseudoClass, + matchLanguagePseudoClass, + matchPseudoElementSelector, + matchReadOnlyPseudoClass, + matchTypeSelector +} from './matcher.js'; +import { + findAST, + generateCSS, + parseSelector, + sortAST, + unescapeSelector, + walkAST +} from './parser.js'; +import { + filterNodesByAnB, + findLogicalWithNestedHas, + generateException, + isCustomElement, + isFocusVisible, + isFocusableArea, + isVisible, + resolveContent, + sortNodes, + traverseNode +} from './utility.js'; + +/* constants */ +import { + ATTR_SELECTOR, + CLASS_SELECTOR, + COMBINATOR, + DOCUMENT_FRAGMENT_NODE, + ELEMENT_NODE, + FORM_PARTS, + ID_SELECTOR, + INPUT_CHECK, + INPUT_DATE, + INPUT_EDIT, + INPUT_TEXT, + KEYS_LOGICAL, + NOT_SUPPORTED_ERR, + PS_CLASS_SELECTOR, + PS_ELEMENT_SELECTOR, + SHOW_ALL, + SHOW_CONTAINER, + SYNTAX_ERR, + TARGET_ALL, + TARGET_FIRST, + TARGET_LINEAL, + TARGET_SELF, + TEXT_NODE, + TYPE_SELECTOR +} from './constant.js'; +const DIR_NEXT = 'next'; +const DIR_PREV = 'prev'; +const KEYS_FORM = new Set([...FORM_PARTS, 'fieldset', 'form']); +const KEYS_FORM_PS_VALID = new Set([...FORM_PARTS, 'form']); +const KEYS_INPUT_CHECK = new Set(INPUT_CHECK); +const KEYS_INPUT_PLACEHOLDER = new Set([...INPUT_TEXT, 'number']); +const KEYS_INPUT_RANGE = new Set([...INPUT_DATE, 'number', 'range']); +const KEYS_INPUT_REQUIRED = new Set([...INPUT_CHECK, ...INPUT_EDIT, 'file']); +const KEYS_INPUT_RESET = new Set(['button', 'reset']); +const KEYS_INPUT_SUBMIT = new Set(['image', 'submit']); +const KEYS_MODIFIER = new Set([ + 'Alt', + 'AltGraph', + 'CapsLock', + 'Control', + 'Fn', + 'FnLock', + 'Hyper', + 'Meta', + 'NumLock', + 'ScrollLock', + 'Shift', + 'Super', + 'Symbol', + 'SymbolLock' +]); +const KEYS_PS_UNCACHE = new Set([ + 'any-link', + 'defined', + 'dir', + 'link', + 'scope' +]); +const KEYS_PS_NTH_OF_TYPE = new Set([ + 'first-of-type', + 'last-of-type', + 'only-of-type' +]); + +/** + * Finder + * NOTE: #ast[i] corresponds to #nodes[i] + */ +export class Finder { + /* private fields */ + #ast; + #astCache; + #check; + #descendant; + #document; + #documentCache; + #documentURL; + #event; + #eventHandlers; + #focus; + #invalidate; + #invalidateResults; + #lastFocusVisible; + #node; + #nodeWalker; + #nodes; + #noexcept; + #pseudoElement; + #results; + #root; + #rootWalker; + #scoped; + #selector; + #selectorAST; + #shadow; + #verifyShadowHost; + #walkers; + #warn; + #window; + + /** + * constructor + * @param {object} window - The window object. + */ + constructor(window) { + this.#window = window; + this.#astCache = new WeakMap(); + this.#documentCache = new WeakMap(); + this.#event = null; + this.#focus = null; + this.#lastFocusVisible = null; + this.#eventHandlers = new Set([ + { + keys: ['focus', 'focusin'], + handler: this._handleFocusEvent + }, + { + keys: ['keydown', 'keyup'], + handler: this._handleKeyboardEvent + }, + { + keys: ['mouseover', 'mousedown', 'mouseup', 'click', 'mouseout'], + handler: this._handleMouseEvent + } + ]); + this._registerEventListeners(); + this.clearResults(true); + } + + /** + * Handles errors. + * @param {Error} e - The error object. + * @param {object} [opt] - Options. + * @param {boolean} [opt.noexcept] - If true, exceptions are not thrown. + * @throws {Error} Throws an error. + * @returns {void} + */ + onError = (e, opt = {}) => { + const noexcept = opt.noexcept ?? this.#noexcept; + if (noexcept) { + return; + } + const isDOMException = + e instanceof DOMException || e instanceof this.#window.DOMException; + if (isDOMException) { + if (e.name === NOT_SUPPORTED_ERR) { + if (this.#warn) { + console.warn(e.message); + } + return; + } + throw new this.#window.DOMException(e.message, e.name); + } + if (e.name in this.#window) { + throw new this.#window[e.name](e.message, { cause: e }); + } + throw e; + }; + + /** + * Sets up the finder. + * @param {string} selector - The CSS selector. + * @param {object} node - Document, DocumentFragment, or Element. + * @param {object} [opt] - Options. + * @param {boolean} [opt.check] - Indicates if running in internal check(). + * @param {boolean} [opt.noexcept] - If true, exceptions are not thrown. + * @param {boolean} [opt.warn] - If true, console warnings are enabled. + * @returns {object} The finder instance. + */ + setup = (selector, node, opt = {}) => { + const { check, noexcept, warn } = opt; + this.#check = !!check; + this.#noexcept = !!noexcept; + this.#warn = !!warn; + [this.#document, this.#root, this.#shadow] = resolveContent(node); + this.#documentURL = null; + this.#node = node; + this.#scoped = + this.#node !== this.#root && this.#node.nodeType === ELEMENT_NODE; + this.#selector = selector; + this.#pseudoElement = []; + this.#walkers = new WeakMap(); + this.#nodeWalker = null; + this.#rootWalker = null; + this.#verifyShadowHost = null; + this.clearResults(); + return this; + }; + + /** + * Clear cached results. + * @param {boolean} all - clear all results + * @returns {void} + */ + clearResults = (all = false) => { + this.#invalidateResults = new WeakMap(); + if (all) { + this.#results = new WeakMap(); + } + }; + + /** + * Handles focus events. + * @private + * @param {Event} evt - The event object. + * @returns {void} + */ + _handleFocusEvent = evt => { + this.#focus = evt; + }; + + /** + * Handles keyboard events. + * @private + * @param {Event} evt - The event object. + * @returns {void} + */ + _handleKeyboardEvent = evt => { + const { key } = evt; + if (!KEYS_MODIFIER.has(key)) { + this.#event = evt; + } + }; + + /** + * Handles mouse events. + * @private + * @param {Event} evt - The event object. + * @returns {void} + */ + _handleMouseEvent = evt => { + this.#event = evt; + }; + + /** + * Registers event listeners. + * @private + * @returns {Array.} An array of return values from addEventListener. + */ + _registerEventListeners = () => { + const func = []; + for (const eventHandler of this.#eventHandlers) { + const { keys, handler } = eventHandler; + const l = keys.length; + for (let i = 0; i < l; i++) { + const key = keys[i]; + func.push( + this.#window.addEventListener(key, handler, { + capture: true, + passive: true + }) + ); + } + } + return func; + }; + + /** + * Processes selector branches into the internal AST structure. + * @private + * @param {Array.>} branches - The branches from walkAST. + * @param {string} selector - The original selector for error reporting. + * @returns {{ast: Array, descendant: boolean}} + * An object with the AST, descendant flag. + */ + _processSelectorBranches = (branches, selector) => { + let descendant = false; + const ast = []; + const l = branches.length; + for (let i = 0; i < l; i++) { + const items = [...branches[i]]; + const branch = []; + let item = items.shift(); + if (item && item.type !== COMBINATOR) { + const leaves = new Set(); + while (item) { + if (item.type === COMBINATOR) { + const [nextItem] = items; + if (!nextItem || nextItem.type === COMBINATOR) { + const msg = `Invalid selector ${selector}`; + this.onError(generateException(msg, SYNTAX_ERR, this.#window)); + // Stop processing on invalid selector. + return { ast: [], descendant: false, invalidate: false }; + } + if (item.name === ' ' || item.name === '>') { + descendant = true; + } + branch.push({ combo: item, leaves: sortAST(leaves) }); + leaves.clear(); + } else { + if (item.name && typeof item.name === 'string') { + const unescapedName = unescapeSelector(item.name); + if (unescapedName !== item.name) { + item.name = unescapedName; + } + if (/[|:]/.test(unescapedName)) { + item.namespace = true; + } + } + leaves.add(item); + } + if (items.length) { + item = items.shift(); + } else { + branch.push({ combo: null, leaves: sortAST(leaves) }); + leaves.clear(); + break; + } + } + } + ast.push({ branch, dir: null, filtered: false, find: false }); + } + return { ast, descendant }; + }; + + /** + * Corresponds AST and nodes. + * @private + * @param {string} selector - The CSS selector. + * @returns {Array.>} An array with the AST and nodes. + */ + _correspond = selector => { + const nodes = []; + this.#descendant = false; + this.#invalidate = false; + let ast; + if (this.#documentCache.has(this.#document)) { + const cachedItem = this.#documentCache.get(this.#document); + if (cachedItem && cachedItem.has(`${selector}`)) { + const item = cachedItem.get(`${selector}`); + ast = item.ast; + this.#descendant = item.descendant; + this.#invalidate = item.invalidate; + } + } + if (ast) { + const l = ast.length; + for (let i = 0; i < l; i++) { + ast[i].dir = null; + ast[i].filtered = false; + ast[i].find = false; + nodes[i] = []; + } + } else { + this.#selectorAST = parseSelector(selector); + const { branches, info } = walkAST(this.#selectorAST, true); + const { + hasHasPseudoFunc, + hasLogicalPseudoFunc, + hasNthChildOfSelector, + hasStatePseudoClass + } = info; + this.#invalidate = + hasHasPseudoFunc || + hasStatePseudoClass || + !!(hasLogicalPseudoFunc && hasNthChildOfSelector); + const processed = this._processSelectorBranches(branches, selector); + ast = processed.ast; + this.#descendant = processed.descendant; + let cachedItem; + if (this.#documentCache.has(this.#document)) { + cachedItem = this.#documentCache.get(this.#document); + } else { + cachedItem = new Map(); + } + cachedItem.set(`${selector}`, { + ast, + descendant: this.#descendant, + invalidate: this.#invalidate + }); + this.#documentCache.set(this.#document, cachedItem); + // Initialize nodes array for each branch. + for (let i = 0; i < ast.length; i++) { + nodes[i] = []; + } + } + return [ast, nodes]; + }; + + /** + * Creates a TreeWalker. + * @private + * @param {object} node - The Document, DocumentFragment, or Element node. + * @param {object} [opt] - Options. + * @param {boolean} [opt.force] - Force creation of a new TreeWalker. + * @param {number} [opt.whatToShow] - The NodeFilter whatToShow value. + * @returns {object} The TreeWalker object. + */ + _createTreeWalker = (node, opt = {}) => { + const { force = false, whatToShow = SHOW_CONTAINER } = opt; + if (force) { + return this.#document.createTreeWalker(node, whatToShow); + } else if (this.#walkers.has(node)) { + return this.#walkers.get(node); + } + const walker = this.#document.createTreeWalker(node, whatToShow); + this.#walkers.set(node, walker); + return walker; + }; + + /** + * Gets selector branches from cache or parses them. + * @private + * @param {object} selector - The AST. + * @returns {Array.>} The selector branches. + */ + _getSelectorBranches = selector => { + if (this.#astCache.has(selector)) { + return this.#astCache.get(selector); + } + const { branches } = walkAST(selector); + this.#astCache.set(selector, branches); + return branches; + }; + + /** + * Gets the children of a node, optionally filtered by a selector. + * @private + * @param {object} parentNode - The parent element. + * @param {Array.>} selectorBranches - The selector branches. + * @param {object} opt - Options. + * @returns {Array.} An array of child nodes. + */ + _getFilteredChildren = (parentNode, selectorBranches, opt) => { + const children = []; + const walker = this._createTreeWalker(parentNode, { force: true }); + let childNode = walker.firstChild(); + while (childNode) { + if (selectorBranches) { + let isMatch = false; + const l = selectorBranches.length; + for (let i = 0; i < l; i++) { + const leaves = selectorBranches[i]; + if (this._matchLeaves(leaves, childNode, opt)) { + isMatch = true; + break; + } + } + if (isMatch) { + if (this.#node === childNode) { + children.push(childNode); + } else if (isVisible(childNode)) { + children.push(childNode); + } + } + } else { + children.push(childNode); + } + childNode = walker.nextSibling(); + } + return children; + }; + + /** + * Collects nth-child nodes. + * @private + * @param {object} anb - An+B options. + * @param {number} anb.a - The 'a' value. + * @param {number} anb.b - The 'b' value. + * @param {boolean} [anb.reverse] - If true, reverses the order. + * @param {object} [anb.selector] - The AST. + * @param {object} node - The Element node. + * @param {object} opt - Options. + * @returns {Set.} A collection of matched nodes. + */ + _collectNthChild = (anb, node, opt) => { + const { a, b, selector } = anb; + const { parentNode } = node; + if (!parentNode) { + const matchedNode = new Set(); + if (node === this.#root && a * 1 + b * 1 === 1) { + if (selector) { + const selectorBranches = this._getSelectorBranches(selector); + const l = selectorBranches.length; + for (let i = 0; i < l; i++) { + const leaves = selectorBranches[i]; + if (this._matchLeaves(leaves, node, opt)) { + matchedNode.add(node); + break; + } + } + } else { + matchedNode.add(node); + } + } + return matchedNode; + } + const selectorBranches = selector + ? this._getSelectorBranches(selector) + : null; + const children = this._getFilteredChildren( + parentNode, + selectorBranches, + opt + ); + const matchedNodes = filterNodesByAnB(children, anb); + return new Set(matchedNodes); + }; + + /** + * Collects nth-of-type nodes. + * @private + * @param {object} anb - An+B options. + * @param {number} anb.a - The 'a' value. + * @param {number} anb.b - The 'b' value. + * @param {boolean} [anb.reverse] - If true, reverses the order. + * @param {object} node - The Element node. + * @returns {Set.} A collection of matched nodes. + */ + _collectNthOfType = (anb, node) => { + const { parentNode } = node; + if (!parentNode) { + if (node === this.#root && anb.a * 1 + anb.b * 1 === 1) { + return new Set([node]); + } + return new Set(); + } + const typedSiblings = []; + const walker = this._createTreeWalker(parentNode, { force: true }); + let sibling = walker.firstChild(); + while (sibling) { + if ( + sibling.localName === node.localName && + sibling.namespaceURI === node.namespaceURI && + sibling.prefix === node.prefix + ) { + typedSiblings.push(sibling); + } + sibling = walker.nextSibling(); + } + const matchedNodes = filterNodesByAnB(typedSiblings, anb); + return new Set(matchedNodes); + }; + + /** + * Matches An+B. + * @private + * @param {object} ast - The AST. + * @param {object} node - The Element node. + * @param {string} nthName - The name of the nth pseudo-class. + * @param {object} opt - Options. + * @returns {Set.} A collection of matched nodes. + */ + _matchAnPlusB = (ast, node, nthName, opt) => { + const { + nth: { a, b, name: nthIdentName }, + selector + } = ast; + const anbMap = new Map(); + if (nthIdentName) { + if (nthIdentName === 'even') { + anbMap.set('a', 2); + anbMap.set('b', 0); + } else if (nthIdentName === 'odd') { + anbMap.set('a', 2); + anbMap.set('b', 1); + } + if (nthName.indexOf('last') > -1) { + anbMap.set('reverse', true); + } + } else { + if (typeof a === 'string' && /-?\d+/.test(a)) { + anbMap.set('a', a * 1); + } else { + anbMap.set('a', 0); + } + if (typeof b === 'string' && /-?\d+/.test(b)) { + anbMap.set('b', b * 1); + } else { + anbMap.set('b', 0); + } + if (nthName.indexOf('last') > -1) { + anbMap.set('reverse', true); + } + } + if (nthName === 'nth-child' || nthName === 'nth-last-child') { + if (selector) { + anbMap.set('selector', selector); + } + const anb = Object.fromEntries(anbMap); + const nodes = this._collectNthChild(anb, node, opt); + return nodes; + } else if (nthName === 'nth-of-type' || nthName === 'nth-last-of-type') { + const anb = Object.fromEntries(anbMap); + const nodes = this._collectNthOfType(anb, node); + return nodes; + } + return new Set(); + }; + + /** + * Matches the :has() pseudo-class function. + * @private + * @param {Array.} astLeaves - The AST leaves. + * @param {object} node - The Element node. + * @param {object} [opt] - Options. + * @returns {boolean} The result. + */ + _matchHasPseudoFunc = (astLeaves, node, opt = {}) => { + if (Array.isArray(astLeaves) && astLeaves.length) { + // Prepare a copy to avoid astLeaves being consumed. + const leaves = [...astLeaves]; + const [leaf] = leaves; + const { type: leafType } = leaf; + let combo; + if (leafType === COMBINATOR) { + combo = leaves.shift(); + } else { + combo = { + name: ' ', + type: COMBINATOR + }; + } + const twigLeaves = []; + while (leaves.length) { + const [item] = leaves; + const { type: itemType } = item; + if (itemType === COMBINATOR) { + break; + } else { + twigLeaves.push(leaves.shift()); + } + } + const twig = { + combo, + leaves: twigLeaves + }; + opt.dir = DIR_NEXT; + const nodes = this._collectCombinatorMatches(twig, node, opt, []); + if (nodes.length) { + if (leaves.length) { + let bool = false; + for (const nextNode of nodes) { + bool = this._matchHasPseudoFunc(leaves, nextNode, opt); + if (bool) { + break; + } + } + return bool; + } + return true; + } + } + return false; + }; + + /** + * Evaluates the :has() pseudo-class. + * @private + * @param {object} astData - The AST data. + * @param {object} node - The Element node. + * @param {object} [opt] - Options. + * @returns {?object} The matched node. + */ + _evaluateHasPseudo = (astData, node, opt = {}) => { + const { branches } = astData; + let bool = false; + const l = branches.length; + for (let i = 0; i < l; i++) { + const leaves = branches[i]; + bool = this._matchHasPseudoFunc(leaves, node, opt); + if (bool) { + break; + } + } + if (!bool) { + return null; + } + if ( + (opt.isShadowRoot || this.#shadow) && + node.nodeType === DOCUMENT_FRAGMENT_NODE + ) { + return this.#verifyShadowHost ? node : null; + } + return node; + }; + + /** + * Matches logical pseudo-class functions. + * @private + * @param {object} astData - The AST data. + * @param {object} node - The Element node. + * @param {object} [opt] - Options. + * @returns {?object} The matched node. + */ + _matchLogicalPseudoFunc = (astData, node, opt = {}) => { + const { astName, branches, twigBranches } = astData; + // Handle :has(). + if (astName === 'has') { + return this._evaluateHasPseudo(astData, node, opt); + } + // Handle :is(), :not(), :where(). + const isShadowRoot = + (opt.isShadowRoot || this.#shadow) && + node.nodeType === DOCUMENT_FRAGMENT_NODE; + // Check for invalid shadow root. + if (isShadowRoot) { + let invalid = false; + for (const branch of branches) { + if (branch.length > 1) { + invalid = true; + break; + } else if (astName === 'not') { + const [{ type: childAstType }] = branch; + if (childAstType !== PS_CLASS_SELECTOR) { + invalid = true; + break; + } + } + } + if (invalid) { + return null; + } + } + opt.forgive = astName === 'is' || astName === 'where'; + const l = twigBranches.length; + let bool; + for (let i = 0; i < l; i++) { + const branch = twigBranches[i]; + const lastIndex = branch.length - 1; + const { leaves } = branch[lastIndex]; + bool = this._matchLeaves(leaves, node, opt); + if (bool && lastIndex > 0) { + let nextNodes = new Set([node]); + for (let j = lastIndex - 1; j >= 0; j--) { + const twig = branch[j]; + const arr = []; + opt.dir = DIR_PREV; + for (const nextNode of nextNodes) { + this._collectCombinatorMatches(twig, nextNode, opt, arr); + } + if (arr.length) { + if (j === 0) { + bool = true; + } else { + nextNodes = new Set(arr); + } + } else { + bool = false; + break; + } + } + } + if (bool) { + break; + } + } + if (astName === 'not') { + if (bool) { + return null; + } + return node; + } else if (bool) { + return node; + } + return null; + }; + + /** + * Matches pseudo-class selector. + * @private + * @see https://html.spec.whatwg.org/#pseudo-classes + * @param {object} ast - The AST. + * @param {object} node - The Element node. + * @param {object} [opt] - Options. + * @param {boolean} [opt.forgive] - Ignores unknown or invalid selectors. + * @param {boolean} [opt.warn] - If true, console warnings are enabled. + * @returns {Set.} A collection of matched nodes. + */ + _matchPseudoClassSelector(ast, node, opt = {}) { + const { children: astChildren, name: astName } = ast; + const { localName, parentNode } = node; + const { forgive, warn = this.#warn } = opt; + const matched = new Set(); + // :has(), :is(), :not(), :where() + if (Array.isArray(astChildren) && KEYS_LOGICAL.has(astName)) { + if (!astChildren.length && astName !== 'is' && astName !== 'where') { + const css = generateCSS(ast); + const msg = `Invalid selector ${css}`; + return this.onError(generateException(msg, SYNTAX_ERR, this.#window)); + } + let astData; + if (this.#astCache.has(ast)) { + astData = this.#astCache.get(ast); + } else { + const { branches } = walkAST(ast); + if (astName === 'has') { + // Check for nested :has(). + let forgiven = false; + const l = astChildren.length; + for (let i = 0; i < l; i++) { + const child = astChildren[i]; + const item = findAST(child, findLogicalWithNestedHas); + if (item) { + const itemName = item.name; + if (itemName === 'is' || itemName === 'where') { + forgiven = true; + break; + } else { + const css = generateCSS(ast); + const msg = `Invalid selector ${css}`; + return this.onError( + generateException(msg, SYNTAX_ERR, this.#window) + ); + } + } + } + if (forgiven) { + return matched; + } + astData = { + astName, + branches + }; + } else { + const twigBranches = []; + const l = branches.length; + for (let i = 0; i < l; i++) { + const [...leaves] = branches[i]; + const branch = []; + const leavesSet = new Set(); + let item = leaves.shift(); + while (item) { + if (item.type === COMBINATOR) { + branch.push({ + combo: item, + leaves: [...leavesSet] + }); + leavesSet.clear(); + } else if (item) { + leavesSet.add(item); + } + if (leaves.length) { + item = leaves.shift(); + } else { + branch.push({ + combo: null, + leaves: [...leavesSet] + }); + leavesSet.clear(); + break; + } + } + twigBranches.push(branch); + } + astData = { + astName, + branches, + twigBranches + }; + this.#astCache.set(ast, astData); + } + } + const res = this._matchLogicalPseudoFunc(astData, node, opt); + if (res) { + matched.add(res); + } + } else if (Array.isArray(astChildren)) { + // :nth-child(), :nth-last-child(), nth-of-type(), :nth-last-of-type() + if (/^nth-(?:last-)?(?:child|of-type)$/.test(astName)) { + if (astChildren.length !== 1) { + const css = generateCSS(ast); + return this.onError( + generateException( + `Invalid selector ${css}`, + SYNTAX_ERR, + this.#window + ) + ); + } + const [branch] = astChildren; + const nodes = this._matchAnPlusB(branch, node, astName, opt); + return nodes; + } else { + switch (astName) { + // :dir() + case 'dir': { + if (astChildren.length !== 1) { + const css = generateCSS(ast); + return this.onError( + generateException( + `Invalid selector ${css}`, + SYNTAX_ERR, + this.#window + ) + ); + } + const [astChild] = astChildren; + const res = matchDirectionPseudoClass(astChild, node); + if (res) { + matched.add(node); + } + break; + } + // :lang() + case 'lang': { + if (!astChildren.length) { + const css = generateCSS(ast); + return this.onError( + generateException( + `Invalid selector ${css}`, + SYNTAX_ERR, + this.#window + ) + ); + } + let bool; + for (const astChild of astChildren) { + bool = matchLanguagePseudoClass(astChild, node); + if (bool) { + break; + } + } + if (bool) { + matched.add(node); + } + break; + } + // :state() + case 'state': { + if (isCustomElement(node)) { + const [{ value: stateValue }] = astChildren; + if (stateValue) { + if (node[stateValue]) { + matched.add(node); + } else { + for (const i in node) { + const prop = node[i]; + if (prop instanceof this.#window.ElementInternals) { + if (prop?.states?.has(stateValue)) { + matched.add(node); + } + break; + } + } + } + } + } + break; + } + case 'current': + case 'heading': + case 'nth-col': + case 'nth-last-col': { + if (warn) { + this.onError( + generateException( + `Unsupported pseudo-class :${astName}()`, + NOT_SUPPORTED_ERR, + this.#window + ) + ); + } + break; + } + // Ignore :host() and :host-context(). + case 'host': + case 'host-context': { + break; + } + // Deprecated in CSS Selectors 3. + case 'contains': { + if (warn) { + this.onError( + generateException( + `Unknown pseudo-class :${astName}()`, + NOT_SUPPORTED_ERR, + this.#window + ) + ); + } + break; + } + default: { + if (!forgive) { + this.onError( + generateException( + `Unknown pseudo-class :${astName}()`, + SYNTAX_ERR, + this.#window + ) + ); + } + } + } + } + } else if (KEYS_PS_NTH_OF_TYPE.has(astName)) { + if (node === this.#root) { + matched.add(node); + } else if (parentNode) { + switch (astName) { + case 'first-of-type': { + const [node1] = this._collectNthOfType( + { + a: 0, + b: 1 + }, + node + ); + if (node1) { + matched.add(node1); + } + break; + } + case 'last-of-type': { + const [node1] = this._collectNthOfType( + { + a: 0, + b: 1, + reverse: true + }, + node + ); + if (node1) { + matched.add(node1); + } + break; + } + // 'only-of-type' is handled by default. + default: { + const [node1] = this._collectNthOfType( + { + a: 0, + b: 1 + }, + node + ); + if (node1 === node) { + const [node2] = this._collectNthOfType( + { + a: 0, + b: 1, + reverse: true + }, + node + ); + if (node2 === node) { + matched.add(node); + } + } + } + } + } + } else { + switch (astName) { + case 'disabled': + case 'enabled': { + const isMatch = matchDisabledPseudoClass(astName, node); + if (isMatch) { + matched.add(node); + } + break; + } + case 'read-only': + case 'read-write': { + const isMatch = matchReadOnlyPseudoClass(astName, node); + if (isMatch) { + matched.add(node); + } + break; + } + case 'any-link': + case 'link': { + if ( + (localName === 'a' || localName === 'area') && + node.hasAttribute('href') + ) { + matched.add(node); + } + break; + } + case 'local-link': { + if ( + (localName === 'a' || localName === 'area') && + node.hasAttribute('href') + ) { + if (!this.#documentURL) { + this.#documentURL = new URL(this.#document.URL); + } + const { href, origin, pathname } = this.#documentURL; + const attrURL = new URL(node.getAttribute('href'), href); + if (attrURL.origin === origin && attrURL.pathname === pathname) { + matched.add(node); + } + } + break; + } + case 'visited': { + // prevent fingerprinting + break; + } + case 'hover': { + const { target, type } = this.#event ?? {}; + if ( + /^(?:click|mouse(?:down|over|up))$/.test(type) && + node.contains(target) + ) { + matched.add(node); + } + break; + } + case 'active': { + const { buttons, target, type } = this.#event ?? {}; + if (type === 'mousedown' && buttons & 1 && node.contains(target)) { + matched.add(node); + } + break; + } + case 'target': { + if (!this.#documentURL) { + this.#documentURL = new URL(this.#document.URL); + } + const { hash } = this.#documentURL; + if ( + node.id && + hash === `#${node.id}` && + this.#document.contains(node) + ) { + matched.add(node); + } + break; + } + case 'target-within': { + if (!this.#documentURL) { + this.#documentURL = new URL(this.#document.URL); + } + const { hash } = this.#documentURL; + if (hash) { + const id = hash.replace(/^#/, ''); + let current = this.#document.getElementById(id); + while (current) { + if (current === node) { + matched.add(node); + break; + } + current = current.parentNode; + } + } + break; + } + case 'scope': { + if (this.#node.nodeType === ELEMENT_NODE) { + if (!this.#shadow && node === this.#node) { + matched.add(node); + } + } else if (node === this.#document.documentElement) { + matched.add(node); + } + break; + } + case 'focus': { + const activeElement = this.#document.activeElement; + if (node === activeElement && isFocusableArea(node)) { + matched.add(node); + } else if (activeElement.shadowRoot) { + const activeShadowElement = activeElement.shadowRoot.activeElement; + let current = activeShadowElement; + while (current) { + if (current.nodeType === DOCUMENT_FRAGMENT_NODE) { + const { host } = current; + if (host === activeElement) { + if (isFocusableArea(node)) { + matched.add(node); + } else { + matched.add(host); + } + } + break; + } else { + current = current.parentNode; + } + } + } + break; + } + case 'focus-visible': { + if (node === this.#document.activeElement && isFocusableArea(node)) { + let bool; + if (isFocusVisible(node)) { + bool = true; + } else if (this.#focus) { + const { relatedTarget, target: focusTarget } = this.#focus; + if (focusTarget === node) { + if (isFocusVisible(relatedTarget)) { + bool = true; + } else if (this.#event) { + const { + altKey: eventAltKey, + ctrlKey: eventCtrlKey, + key: eventKey, + metaKey: eventMetaKey, + target: eventTarget, + type: eventType + } = this.#event; + // this.#event is irrelevant if eventTarget === relatedTarget + if (eventTarget === relatedTarget) { + if (this.#lastFocusVisible === null) { + bool = true; + } else if (focusTarget === this.#lastFocusVisible) { + bool = true; + } + } else if (eventKey === 'Tab') { + if ( + (eventType === 'keydown' && eventTarget !== node) || + (eventType === 'keyup' && eventTarget === node) + ) { + if (eventTarget === focusTarget) { + if (this.#lastFocusVisible === null) { + bool = true; + } else if ( + eventTarget === this.#lastFocusVisible && + relatedTarget === null + ) { + bool = true; + } + } else { + bool = true; + } + } + } else if (eventKey) { + if ( + (eventType === 'keydown' || eventType === 'keyup') && + !eventAltKey && + !eventCtrlKey && + !eventMetaKey && + eventTarget === node + ) { + bool = true; + } + } + } else if ( + relatedTarget === null || + relatedTarget === this.#lastFocusVisible + ) { + bool = true; + } + } + } + if (bool) { + this.#lastFocusVisible = node; + matched.add(node); + } else if (this.#lastFocusVisible === node) { + this.#lastFocusVisible = null; + } + } + break; + } + case 'focus-within': { + const activeElement = this.#document.activeElement; + if (node.contains(activeElement) && isFocusableArea(activeElement)) { + matched.add(node); + } else if (activeElement.shadowRoot) { + const activeShadowElement = activeElement.shadowRoot.activeElement; + if (node.contains(activeShadowElement)) { + matched.add(node); + } else { + let current = activeShadowElement; + while (current) { + if (current.nodeType === DOCUMENT_FRAGMENT_NODE) { + const { host } = current; + if (host === activeElement && node.contains(host)) { + matched.add(node); + } + break; + } else { + current = current.parentNode; + } + } + } + } + break; + } + case 'open': + case 'closed': { + if (localName === 'details' || localName === 'dialog') { + if (node.hasAttribute('open')) { + if (astName === 'open') { + matched.add(node); + } + } else if (astName === 'closed') { + matched.add(node); + } + } + break; + } + case 'placeholder-shown': { + let placeholder; + if (node.placeholder) { + placeholder = node.placeholder; + } else if (node.hasAttribute('placeholder')) { + placeholder = node.getAttribute('placeholder'); + } + if (typeof placeholder === 'string' && !/[\r\n]/.test(placeholder)) { + let targetNode; + if (localName === 'textarea') { + targetNode = node; + } else if (localName === 'input') { + if (node.hasAttribute('type')) { + if (KEYS_INPUT_PLACEHOLDER.has(node.getAttribute('type'))) { + targetNode = node; + } + } else { + targetNode = node; + } + } + if (targetNode && node.value === '') { + matched.add(node); + } + } + break; + } + case 'checked': { + const attrType = node.getAttribute('type'); + if ( + (node.checked && + localName === 'input' && + (attrType === 'checkbox' || attrType === 'radio')) || + (node.selected && localName === 'option') + ) { + matched.add(node); + } + break; + } + case 'indeterminate': { + if ( + (node.indeterminate && + localName === 'input' && + node.type === 'checkbox') || + (localName === 'progress' && !node.hasAttribute('value')) + ) { + matched.add(node); + } else if ( + localName === 'input' && + node.type === 'radio' && + !node.hasAttribute('checked') + ) { + const nodeName = node.name; + let parent = node.parentNode; + while (parent) { + if (parent.localName === 'form') { + break; + } + parent = parent.parentNode; + } + if (!parent) { + parent = this.#document.documentElement; + } + const walker = this._createTreeWalker(parent); + let refNode = traverseNode(parent, walker); + refNode = walker.firstChild(); + let checked; + while (refNode) { + if ( + refNode.localName === 'input' && + refNode.getAttribute('type') === 'radio' + ) { + if (refNode.hasAttribute('name')) { + if (refNode.getAttribute('name') === nodeName) { + checked = !!refNode.checked; + } + } else { + checked = !!refNode.checked; + } + if (checked) { + break; + } + } + refNode = walker.nextNode(); + } + if (!checked) { + matched.add(node); + } + } + break; + } + case 'default': { + // button[type="submit"], input[type="submit"], input[type="image"] + const attrType = node.getAttribute('type'); + if ( + (localName === 'button' && + !(node.hasAttribute('type') && KEYS_INPUT_RESET.has(attrType))) || + (localName === 'input' && + node.hasAttribute('type') && + KEYS_INPUT_SUBMIT.has(attrType)) + ) { + let form = node.parentNode; + while (form) { + if (form.localName === 'form') { + break; + } + form = form.parentNode; + } + if (form) { + const walker = this._createTreeWalker(form); + let refNode = traverseNode(form, walker); + refNode = walker.firstChild(); + while (refNode) { + const nodeName = refNode.localName; + const nodeAttrType = refNode.getAttribute('type'); + let m; + if (nodeName === 'button') { + m = !( + refNode.hasAttribute('type') && + KEYS_INPUT_RESET.has(nodeAttrType) + ); + } else if (nodeName === 'input') { + m = + refNode.hasAttribute('type') && + KEYS_INPUT_SUBMIT.has(nodeAttrType); + } + if (m) { + if (refNode === node) { + matched.add(node); + } + break; + } + refNode = walker.nextNode(); + } + } + // input[type="checkbox"], input[type="radio"] + } else if ( + localName === 'input' && + node.hasAttribute('type') && + node.hasAttribute('checked') && + KEYS_INPUT_CHECK.has(attrType) + ) { + matched.add(node); + // option + } else if (localName === 'option' && node.hasAttribute('selected')) { + matched.add(node); + } + break; + } + case 'valid': + case 'invalid': { + if (KEYS_FORM_PS_VALID.has(localName)) { + let valid; + if (node.checkValidity()) { + if (node.maxLength >= 0) { + if (node.maxLength >= node.value.length) { + valid = true; + } + } else { + valid = true; + } + } + if (valid) { + if (astName === 'valid') { + matched.add(node); + } + } else if (astName === 'invalid') { + matched.add(node); + } + } else if (localName === 'fieldset') { + const walker = this._createTreeWalker(node); + let refNode = traverseNode(node, walker); + refNode = walker.firstChild(); + let valid; + if (!refNode) { + valid = true; + } else { + while (refNode) { + if (KEYS_FORM_PS_VALID.has(refNode.localName)) { + if (refNode.checkValidity()) { + if (refNode.maxLength >= 0) { + valid = refNode.maxLength >= refNode.value.length; + } else { + valid = true; + } + } else { + valid = false; + } + if (!valid) { + break; + } + } + refNode = walker.nextNode(); + } + } + if (valid) { + if (astName === 'valid') { + matched.add(node); + } + } else if (astName === 'invalid') { + matched.add(node); + } + } + break; + } + case 'in-range': + case 'out-of-range': { + const attrType = node.getAttribute('type'); + if ( + localName === 'input' && + !(node.readOnly || node.hasAttribute('readonly')) && + !(node.disabled || node.hasAttribute('disabled')) && + KEYS_INPUT_RANGE.has(attrType) + ) { + const flowed = + node.validity.rangeUnderflow || node.validity.rangeOverflow; + if (astName === 'out-of-range' && flowed) { + matched.add(node); + } else if ( + astName === 'in-range' && + !flowed && + (node.hasAttribute('min') || + node.hasAttribute('max') || + attrType === 'range') + ) { + matched.add(node); + } + } + break; + } + case 'required': + case 'optional': { + let required; + let optional; + if (localName === 'select' || localName === 'textarea') { + if (node.required || node.hasAttribute('required')) { + required = true; + } else { + optional = true; + } + } else if (localName === 'input') { + if (node.hasAttribute('type')) { + const attrType = node.getAttribute('type'); + if (KEYS_INPUT_REQUIRED.has(attrType)) { + if (node.required || node.hasAttribute('required')) { + required = true; + } else { + optional = true; + } + } else { + optional = true; + } + } else if (node.required || node.hasAttribute('required')) { + required = true; + } else { + optional = true; + } + } + if (astName === 'required' && required) { + matched.add(node); + } else if (astName === 'optional' && optional) { + matched.add(node); + } + break; + } + case 'root': { + if (node === this.#document.documentElement) { + matched.add(node); + } + break; + } + case 'empty': { + if (node.hasChildNodes()) { + const walker = this._createTreeWalker(node, { + force: true, + whatToShow: SHOW_ALL + }); + let refNode = walker.firstChild(); + let bool; + while (refNode) { + bool = + refNode.nodeType !== ELEMENT_NODE && + refNode.nodeType !== TEXT_NODE; + if (!bool) { + break; + } + refNode = walker.nextSibling(); + } + if (bool) { + matched.add(node); + } + } else { + matched.add(node); + } + break; + } + case 'first-child': { + if ( + (parentNode && node === parentNode.firstElementChild) || + node === this.#root + ) { + matched.add(node); + } + break; + } + case 'last-child': { + if ( + (parentNode && node === parentNode.lastElementChild) || + node === this.#root + ) { + matched.add(node); + } + break; + } + case 'only-child': { + if ( + (parentNode && + node === parentNode.firstElementChild && + node === parentNode.lastElementChild) || + node === this.#root + ) { + matched.add(node); + } + break; + } + case 'defined': { + if (node.hasAttribute('is') || localName.includes('-')) { + if (isCustomElement(node)) { + matched.add(node); + } + // NOTE: MathMLElement is not implemented in jsdom. + } else if ( + node instanceof this.#window.HTMLElement || + node instanceof this.#window.SVGElement + ) { + matched.add(node); + } + break; + } + case 'popover-open': { + // FIXME: not implemented in jsdom + // @see https://github.com/jsdom/jsdom/issues/3721 + /* + if (node.popover && isVisible(node)) { + matched.add(node); + } + */ + break; + } + // Ignore :host. + case 'host': { + break; + } + // Legacy pseudo-elements. + case 'after': + case 'before': + case 'first-letter': + case 'first-line': { + if (warn) { + this.onError( + generateException( + `Unsupported pseudo-element ::${astName}`, + NOT_SUPPORTED_ERR, + this.#window + ) + ); + } + break; + } + // Not supported. + case 'autofill': + case 'blank': + case 'buffering': + case 'current': + case 'fullscreen': + case 'future': + case 'has-slotted': + case 'heading': + case 'modal': + case 'muted': + case 'past': + case 'paused': + case 'picture-in-picture': + case 'playing': + case 'seeking': + case 'stalled': + case 'user-invalid': + case 'user-valid': + case 'volume-locked': + case '-webkit-autofill': { + if (warn) { + this.onError( + generateException( + `Unsupported pseudo-class :${astName}`, + NOT_SUPPORTED_ERR, + this.#window + ) + ); + } + break; + } + default: { + if (astName.startsWith('-webkit-')) { + if (warn) { + this.onError( + generateException( + `Unsupported pseudo-class :${astName}`, + NOT_SUPPORTED_ERR, + this.#window + ) + ); + } + } else if (!forgive) { + this.onError( + generateException( + `Unknown pseudo-class :${astName}`, + SYNTAX_ERR, + this.#window + ) + ); + } + } + } + } + return matched; + } + + /** + * Evaluates the :host() pseudo-class. + * @private + * @param {Array.} leaves - The AST leaves. + * @param {object} host - The host element. + * @param {object} ast - The original AST for error reporting. + * @returns {boolean} True if matched. + */ + _evaluateHostPseudo = (leaves, host, ast) => { + const l = leaves.length; + for (let i = 0; i < l; i++) { + const leaf = leaves[i]; + if (leaf.type === COMBINATOR) { + const css = generateCSS(ast); + const msg = `Invalid selector ${css}`; + this.onError(generateException(msg, SYNTAX_ERR, this.#window)); + return false; + } + if (!this._matchSelector(leaf, host).has(host)) { + return false; + } + } + return true; + }; + + /** + * Evaluates the :host-context() pseudo-class. + * @private + * @param {Array.} leaves - The AST leaves. + * @param {object} host - The host element. + * @param {object} ast - The original AST for error reporting. + * @returns {boolean} True if matched. + */ + _evaluateHostContextPseudo = (leaves, host, ast) => { + let parent = host; + while (parent) { + let bool; + const l = leaves.length; + for (let i = 0; i < l; i++) { + const leaf = leaves[i]; + if (leaf.type === COMBINATOR) { + const css = generateCSS(ast); + const msg = `Invalid selector ${css}`; + this.onError(generateException(msg, SYNTAX_ERR, this.#window)); + return false; + } + bool = this._matchSelector(leaf, parent).has(parent); + if (!bool) { + break; + } + } + if (bool) { + return true; + } + parent = parent.parentNode; + } + return false; + }; + + /** + * Matches shadow host pseudo-classes. + * @private + * @param {object} ast - The AST. + * @param {object} node - The DocumentFragment node. + * @returns {?object} The matched node. + */ + _matchShadowHostPseudoClass = (ast, node) => { + const { children: astChildren, name: astName } = ast; + // Handle simple pseudo-class (no arguments). + if (!Array.isArray(astChildren)) { + if (astName === 'host') { + return node; + } + const msg = `Invalid selector :${astName}`; + return this.onError(generateException(msg, SYNTAX_ERR, this.#window)); + } + // Handle functional pseudo-class like :host(...). + if (astName !== 'host' && astName !== 'host-context') { + const msg = `Invalid selector :${astName}()`; + return this.onError(generateException(msg, SYNTAX_ERR, this.#window)); + } + if (astChildren.length !== 1) { + const css = generateCSS(ast); + const msg = `Invalid selector ${css}`; + return this.onError(generateException(msg, SYNTAX_ERR, this.#window)); + } + const { host } = node; + const { branches } = walkAST(astChildren[0]); + const [branch] = branches; + const [...leaves] = branch; + let isMatch = false; + if (astName === 'host') { + isMatch = this._evaluateHostPseudo(leaves, host, ast); + // astName === 'host-context'. + } else { + isMatch = this._evaluateHostContextPseudo(leaves, host, ast); + } + return isMatch ? node : null; + }; + + /** + * Matches a selector for element nodes. + * @private + * @param {object} ast - The AST. + * @param {object} node - The Element node. + * @param {object} opt - Options. + * @returns {Set.} A collection of matched nodes. + */ + _matchSelectorForElement = (ast, node, opt) => { + const { type: astType } = ast; + const astName = unescapeSelector(ast.name); + const matched = new Set(); + switch (astType) { + case ATTR_SELECTOR: { + if (matchAttributeSelector(ast, node, opt)) { + matched.add(node); + } + break; + } + case ID_SELECTOR: { + if (node.id === astName) { + matched.add(node); + } + break; + } + case CLASS_SELECTOR: { + if (node.classList.contains(astName)) { + matched.add(node); + } + break; + } + case PS_CLASS_SELECTOR: { + return this._matchPseudoClassSelector(ast, node, opt); + } + case TYPE_SELECTOR: { + if (matchTypeSelector(ast, node, opt)) { + matched.add(node); + } + break; + } + // PS_ELEMENT_SELECTOR is handled by default. + default: { + try { + if (this.#check) { + const css = generateCSS(ast); + this.#pseudoElement.push(css); + matched.add(node); + } else { + matchPseudoElementSelector(astName, astType, opt); + } + } catch (e) { + this.onError(e); + } + } + } + return matched; + }; + + /** + * Matches a selector for a shadow root. + * @private + * @param {object} ast - The AST. + * @param {object} node - The DocumentFragment node. + * @param {object} [opt] - Options. + * @returns {Set.} A collection of matched nodes. + */ + _matchSelectorForShadowRoot = (ast, node, opt = {}) => { + const { name: astName } = ast; + if (KEYS_LOGICAL.has(astName)) { + opt.isShadowRoot = true; + return this._matchPseudoClassSelector(ast, node, opt); + } + const matched = new Set(); + if (astName === 'host' || astName === 'host-context') { + const res = this._matchShadowHostPseudoClass(ast, node, opt); + if (res) { + this.#verifyShadowHost = true; + matched.add(res); + } + } + return matched; + }; + + /** + * Matches a selector. + * @private + * @param {object} ast - The AST. + * @param {object} node - The Document, DocumentFragment, or Element node. + * @param {object} opt - Options. + * @returns {Set.} A collection of matched nodes. + */ + _matchSelector = (ast, node, opt) => { + if (node.nodeType === ELEMENT_NODE) { + return this._matchSelectorForElement(ast, node, opt); + } + if ( + this.#shadow && + node.nodeType === DOCUMENT_FRAGMENT_NODE && + ast.type === PS_CLASS_SELECTOR + ) { + return this._matchSelectorForShadowRoot(ast, node, opt); + } + return new Set(); + }; + + /** + * Matches leaves. + * @private + * @param {Array.} leaves - The AST leaves. + * @param {object} node - The node. + * @param {object} opt - Options. + * @returns {boolean} The result. + */ + _matchLeaves = (leaves, node, opt) => { + const results = this.#invalidate ? this.#invalidateResults : this.#results; + let result = results.get(leaves); + if (result && result.has(node)) { + const { matched } = result.get(node); + return matched; + } + let cacheable = true; + if (node.nodeType === ELEMENT_NODE && KEYS_FORM.has(node.localName)) { + cacheable = false; + } + let bool; + const l = leaves.length; + for (let i = 0; i < l; i++) { + const leaf = leaves[i]; + switch (leaf.type) { + case ATTR_SELECTOR: + case ID_SELECTOR: { + cacheable = false; + break; + } + case PS_CLASS_SELECTOR: { + if (KEYS_PS_UNCACHE.has(leaf.name)) { + cacheable = false; + } + break; + } + default: { + // No action needed for other types. + } + } + bool = this._matchSelector(leaf, node, opt).has(node); + if (!bool) { + break; + } + } + if (cacheable) { + if (!result) { + result = new WeakMap(); + } + result.set(node, { + matched: bool + }); + results.set(leaves, result); + } + return bool; + }; + + /** + * Traverses all descendant nodes and collects matches. + * @private + * @param {object} baseNode - The base Element node or Element.shadowRoot. + * @param {Array.} leaves - The AST leaves. + * @param {object} opt - Options. + * @returns {Set.} A collection of matched nodes. + */ + _traverseAllDescendants = (baseNode, leaves, opt) => { + const walker = this._createTreeWalker(baseNode); + traverseNode(baseNode, walker); + let currentNode = walker.firstChild(); + const nodes = new Set(); + while (currentNode) { + if (this._matchLeaves(leaves, currentNode, opt)) { + nodes.add(currentNode); + } + currentNode = walker.nextNode(); + } + return nodes; + }; + + /** + * Finds descendant nodes. + * @private + * @param {Array.} leaves - The AST leaves. + * @param {object} baseNode - The base Element node or Element.shadowRoot. + * @param {object} opt - Options. + * @returns {Set.} A collection of matched nodes. + */ + _findDescendantNodes = (leaves, baseNode, opt) => { + const [leaf, ...filterLeaves] = leaves; + const { type: leafType } = leaf; + switch (leafType) { + case ID_SELECTOR: { + const canUseGetElementById = + !this.#shadow && + baseNode.nodeType === ELEMENT_NODE && + this.#root.nodeType !== ELEMENT_NODE; + if (canUseGetElementById) { + const leafName = unescapeSelector(leaf.name); + const nodes = new Set(); + const foundNode = this.#root.getElementById(leafName); + if ( + foundNode && + foundNode !== baseNode && + baseNode.contains(foundNode) + ) { + const isCompoundSelector = filterLeaves.length > 0; + if ( + !isCompoundSelector || + this._matchLeaves(filterLeaves, foundNode, opt) + ) { + nodes.add(foundNode); + } + } + return nodes; + } + // Fallback to default traversal if fast path is not applicable. + return this._traverseAllDescendants(baseNode, leaves, opt); + } + case PS_ELEMENT_SELECTOR: { + const leafName = unescapeSelector(leaf.name); + matchPseudoElementSelector(leafName, leafType, opt); + return new Set(); + } + default: { + return this._traverseAllDescendants(baseNode, leaves, opt); + } + } + }; + + /** + * Collects combinator matches into an array without creating intermediate sets. + * @private + * @param {object} twig - The twig object. + * @param {object} node - The Element node. + * @param {object} [opt] - Options. + * @param {string} [opt.dir] - The find direction. + * @param {Array.} matched - The collector array. + * @returns {Array.} The collector array. + */ + _collectCombinatorMatches = (twig, node, opt = {}, matched = []) => { + const { + combo: { name: comboName }, + leaves + } = twig; + const { dir } = opt; + switch (comboName) { + case '+': { + const refNode = + dir === DIR_NEXT + ? node.nextElementSibling + : node.previousElementSibling; + if (refNode && this._matchLeaves(leaves, refNode, opt)) { + matched.push(refNode); + } + break; + } + case '~': { + let refNode = + dir === DIR_NEXT + ? node.nextElementSibling + : node.previousElementSibling; + while (refNode) { + if (this._matchLeaves(leaves, refNode, opt)) { + matched.push(refNode); + } + refNode = + dir === DIR_NEXT + ? refNode.nextElementSibling + : refNode.previousElementSibling; + } + break; + } + case '>': { + if (dir === DIR_NEXT) { + let refNode = node.firstElementChild; + while (refNode) { + if (this._matchLeaves(leaves, refNode, opt)) { + matched.push(refNode); + } + refNode = refNode.nextElementSibling; + } + } else { + const { parentNode } = node; + if (parentNode && this._matchLeaves(leaves, parentNode, opt)) { + matched.push(parentNode); + } + } + break; + } + case ' ': + default: { + if (dir === DIR_NEXT) { + for (const refNode of this._findDescendantNodes(leaves, node, opt)) { + matched.push(refNode); + } + } else { + const ancestors = []; + let refNode = node.parentNode; + while (refNode) { + if (this._matchLeaves(leaves, refNode, opt)) { + ancestors.push(refNode); + } + refNode = refNode.parentNode; + } + if (ancestors.length) { + matched.push(...ancestors.reverse()); + } + } + } + } + return matched; + }; + + /** + * Matches a combinator. + * @private + * @param {object} twig - The twig object. + * @param {object} node - The Element node. + * @param {object} opt - Options. + * @returns {Set.} A collection of matched nodes. + */ + _matchCombinator = (twig, node, opt) => + new Set(this._collectCombinatorMatches(twig, node, opt)); + + /** + * Traverses with a TreeWalker and collects nodes matching the leaves. + * @private + * @param {TreeWalker} walker - The TreeWalker instance to use. + * @param {Array} leaves - The AST leaves to match against. + * @param {object} [opt] - Traversal options. + * @param {Node} [opt.boundaryNode] - The node to stop traversal at. + * @param {boolean} [opt.force] - Force traversal to the next node. + * @param {Node} [opt.startNode] - The node to start traversal from. + * @param {string} [opt.targetType] - The type of target ('all' or 'first'). + * @returns {Array.} An array of matched nodes. + */ + _traverseAndCollectNodes = (walker, leaves, opt = {}) => { + const { boundaryNode, force, startNode, targetType } = opt; + const collectedNodes = []; + let currentNode = traverseNode(startNode, walker, !!force); + if (!currentNode) { + return []; + } + // Adjust starting node. + if (currentNode.nodeType !== ELEMENT_NODE) { + currentNode = walker.nextNode(); + } else if (currentNode === startNode && currentNode !== this.#root) { + currentNode = walker.nextNode(); + } + const matchOpt = { + warn: this.#warn + }; + while (currentNode) { + // Stop when we reach the boundary. + if (boundaryNode) { + if (currentNode === boundaryNode) { + break; + } else if ( + targetType === TARGET_ALL && + !boundaryNode.contains(currentNode) + ) { + break; + } + } + if ( + this._matchLeaves(leaves, currentNode, matchOpt) && + currentNode !== this.#node + ) { + collectedNodes.push(currentNode); + // Stop after the first match if not collecting all. + if (targetType !== TARGET_ALL) { + break; + } + } + currentNode = walker.nextNode(); + } + return collectedNodes; + }; + + /** + * Finds matched node(s) preceding this.#node. + * @private + * @param {Array.} leaves - The AST leaves. + * @param {object} node - The node to start from. + * @param {object} [opt] - Options. + * @param {boolean} [opt.force] - If true, traverses only to the next node. + * @param {string} [opt.targetType] - The target type. + * @returns {Array.} A collection of matched nodes. + */ + _findPrecede = (leaves, node, opt = {}) => { + const { force, targetType } = opt; + if (!this.#rootWalker) { + this.#rootWalker = this._createTreeWalker(this.#root); + } + return this._traverseAndCollectNodes(this.#rootWalker, leaves, { + force, + targetType, + boundaryNode: this.#node, + startNode: node + }); + }; + + /** + * Finds matched node(s) in #nodeWalker. + * @private + * @param {Array.} leaves - The AST leaves. + * @param {object} node - The node to start from. + * @param {object} [opt] - Options. + * @param {boolean} [opt.precede] - If true, finds preceding nodes. + * @returns {Array.} A collection of matched nodes. + */ + _findNodeWalker = (leaves, node, opt = {}) => { + const { precede, ...traversalOpts } = opt; + if (precede) { + const precedeNodes = this._findPrecede(leaves, this.#root, opt); + if (precedeNodes.length) { + return precedeNodes; + } + } + if (!this.#nodeWalker) { + this.#nodeWalker = this._createTreeWalker(this.#node); + } + return this._traverseAndCollectNodes(this.#nodeWalker, leaves, { + startNode: node, + ...traversalOpts + }); + }; + + /** + * Matches the node itself. + * @private + * @param {Array} leaves - The AST leaves. + * @returns {Array} An array containing [nodes, filtered, pseudoElement]. + */ + _matchSelf = leaves => { + const matched = this._matchLeaves(leaves, this.#node, { + check: this.#check, + warn: this.#warn + }); + const nodes = matched ? [this.#node] : []; + return [nodes, matched, this.#pseudoElement]; + }; + + /** + * Finds lineal nodes (self and ancestors). + * @private + * @param {Array} leaves - The AST leaves. + * @param {object} [opt] - Options. + * @param {boolean} [opt.complex] - If true, the selector is complex. + * @returns {Array} An array containing [nodes, filtered]. + */ + _findLineal = (leaves, opt = {}) => { + const { complex } = opt; + const nodes = []; + const matchOpts = { warn: this.#warn }; + const selfMatched = this._matchLeaves(leaves, this.#node, matchOpts); + if (selfMatched) { + nodes.push(this.#node); + } + if (!selfMatched || complex) { + let currentNode = this.#node.parentNode; + while (currentNode) { + if (this._matchLeaves(leaves, currentNode, matchOpts)) { + nodes.push(currentNode); + } + currentNode = currentNode.parentNode; + } + } + const filtered = nodes.length > 0; + return [nodes, filtered]; + }; + + /** + * Finds entry nodes for pseudo-element selectors. + * @private + * @param {object} leaf - The pseudo-element leaf from the AST. + * @param {Array.} filterLeaves - Leaves for compound selectors. + * @param {string} targetType - The type of target to find. + * @returns {object} The result { nodes, filtered, pending }. + */ + _findEntryNodesForPseudoElement = (leaf, filterLeaves, targetType) => { + let nodes = []; + let filtered = false; + if (targetType === TARGET_SELF && this.#check) { + const css = generateCSS(leaf); + this.#pseudoElement.push(css); + if (filterLeaves.length) { + [nodes, filtered] = this._matchSelf(filterLeaves); + } else { + nodes.push(this.#node); + filtered = true; + } + } else { + matchPseudoElementSelector(leaf.name, leaf.type, { warn: this.#warn }); + } + return { nodes, filtered, pending: false }; + }; + + /** + * Finds entry nodes for ID selectors. + * @private + * @param {object} twig - The current twig from the AST branch. + * @param {string} targetType - The type of target to find. + * @param {object} [opt] - Options. + * @param {boolean} [opt.complex] - If true, the selector is complex. + * @param {boolean} [opt.precede] - If true, finds preceding nodes. + * @returns {object} The result { nodes, filtered, pending }. + */ + _findEntryNodesForId = (twig, targetType, opt = {}) => { + const { leaves } = twig; + const [leaf, ...filterLeaves] = leaves; + const { complex, precede } = opt; + let nodes = []; + let filtered = false; + if (targetType === TARGET_SELF) { + [nodes, filtered] = this._matchSelf(leaves); + } else if (targetType === TARGET_LINEAL) { + [nodes, filtered] = this._findLineal(leaves, { complex }); + } else if ( + targetType === TARGET_FIRST && + this.#root.nodeType !== ELEMENT_NODE + ) { + const node = this.#root.getElementById(leaf.name); + if (node) { + if (filterLeaves.length) { + if (this._matchLeaves(filterLeaves, node, { warn: this.#warn })) { + nodes.push(node); + filtered = true; + } + } else { + nodes.push(node); + filtered = true; + } + } + } else { + nodes = this._findNodeWalker(leaves, this.#node, { precede, targetType }); + filtered = nodes.length > 0; + } + return { nodes, filtered, pending: false }; + }; + + /** + * Finds entry nodes for class selectors. + * @private + * @param {Array.} leaves - The AST leaves for the selector. + * @param {string} targetType - The type of target to find. + * @param {object} [opt] - Options. + * @param {boolean} [opt.complex] - If true, the selector is complex. + * @param {boolean} [opt.precede] - If true, finds preceding nodes. + * @returns {object} The result { nodes, filtered, pending }. + */ + _findEntryNodesForClass = (leaves, targetType, opt = {}) => { + const { complex, precede } = opt; + let nodes = []; + let filtered = false; + if (targetType === TARGET_SELF) { + [nodes, filtered] = this._matchSelf(leaves); + } else if (targetType === TARGET_LINEAL) { + [nodes, filtered] = this._findLineal(leaves, { complex }); + } else { + nodes = this._findNodeWalker(leaves, this.#node, { precede, targetType }); + filtered = nodes.length > 0; + } + return { nodes, filtered, pending: false }; + }; + + /** + * Finds entry nodes for type selectors. + * @private + * @param {Array.} leaves - The AST leaves for the selector. + * @param {string} targetType - The type of target to find. + * @param {object} [opt] - Options. + * @param {boolean} [opt.complex] - If true, the selector is complex. + * @param {boolean} [opt.precede] - If true, finds preceding nodes. + * @returns {object} The result { nodes, filtered, pending }. + */ + _findEntryNodesForType = (leaves, targetType, opt = {}) => { + const { complex, precede } = opt; + let nodes = []; + let filtered = false; + if (targetType === TARGET_SELF) { + [nodes, filtered] = this._matchSelf(leaves); + } else if (targetType === TARGET_LINEAL) { + [nodes, filtered] = this._findLineal(leaves, { complex }); + } else { + nodes = this._findNodeWalker(leaves, this.#node, { precede, targetType }); + filtered = nodes.length > 0; + } + return { nodes, filtered, pending: false }; + }; + + /** + * Finds entry nodes for other selector types (default case). + * @private + * @param {object} twig - The current twig from the AST branch. + * @param {string} targetType - The type of target to find. + * @param {object} [opt] - Options. + * @param {boolean} [opt.complex] - If true, the selector is complex. + * @param {boolean} [opt.precede] - If true, finds preceding nodes. + * @returns {object} The result { nodes, filtered, pending }. + */ + _findEntryNodesForOther = (twig, targetType, opt = {}) => { + const { leaves } = twig; + const [leaf, ...filterLeaves] = leaves; + const { complex, precede } = opt; + let nodes = []; + let filtered = false; + let pending = false; + if (targetType !== TARGET_LINEAL && /host(?:-context)?/.test(leaf.name)) { + let shadowRoot = null; + if (this.#shadow && this.#node.nodeType === DOCUMENT_FRAGMENT_NODE) { + shadowRoot = this._matchShadowHostPseudoClass(leaf, this.#node); + } else if (filterLeaves.length && this.#node.nodeType === ELEMENT_NODE) { + shadowRoot = this._matchShadowHostPseudoClass( + leaf, + this.#node.shadowRoot + ); + } + if (shadowRoot) { + let bool = true; + const l = filterLeaves.length; + for (let i = 0; i < l; i++) { + const filterLeaf = filterLeaves[i]; + switch (filterLeaf.name) { + case 'host': + case 'host-context': { + const matchedNode = this._matchShadowHostPseudoClass( + filterLeaf, + shadowRoot + ); + bool = matchedNode === shadowRoot; + break; + } + case 'has': { + bool = this._matchPseudoClassSelector( + filterLeaf, + shadowRoot, + {} + ).has(shadowRoot); + break; + } + default: { + bool = false; + } + } + if (!bool) { + break; + } + } + if (bool) { + nodes.push(shadowRoot); + filtered = true; + } + } + } else if (targetType === TARGET_SELF) { + [nodes, filtered] = this._matchSelf(leaves); + } else if (targetType === TARGET_LINEAL) { + [nodes, filtered] = this._findLineal(leaves, { complex }); + } else if (targetType === TARGET_FIRST) { + nodes = this._findNodeWalker(leaves, this.#node, { precede, targetType }); + filtered = nodes.length > 0; + } else { + pending = true; + } + return { nodes, filtered, pending }; + }; + + /** + * Finds entry nodes. + * @private + * @param {object} twig - The twig object. + * @param {string} targetType - The target type. + * @param {object} [opt] - Options. + * @param {boolean} [opt.complex] - If true, the selector is complex. + * @param {string} [opt.dir] - The find direction. + * @returns {object} An object with nodes and their state. + */ + _findEntryNodes = (twig, targetType, opt = {}) => { + const { leaves } = twig; + const [leaf, ...filterLeaves] = leaves; + const { complex = false, dir = DIR_PREV } = opt; + const precede = + dir === DIR_NEXT && + this.#node.nodeType === ELEMENT_NODE && + this.#node !== this.#root; + let result; + switch (leaf.type) { + case PS_ELEMENT_SELECTOR: { + result = this._findEntryNodesForPseudoElement( + leaf, + filterLeaves, + targetType + ); + break; + } + case ID_SELECTOR: { + result = this._findEntryNodesForId(twig, targetType, { + complex, + precede + }); + break; + } + case CLASS_SELECTOR: { + result = this._findEntryNodesForClass(leaves, targetType, { + complex, + precede + }); + break; + } + case TYPE_SELECTOR: { + result = this._findEntryNodesForType(leaves, targetType, { + complex, + precede + }); + break; + } + default: { + result = this._findEntryNodesForOther(twig, targetType, { + complex, + precede + }); + } + } + return { + compound: filterLeaves.length > 0, + filtered: result.filtered, + nodes: result.nodes, + pending: result.pending + }; + }; + + /** + * Determines the direction and starting twig for a selector branch. + * @private + * @param {Array.} branch - The AST branch. + * @param {string} targetType - The type of target to find. + * @returns {object} An object with the direction and starting twig. + */ + _determineTraversalStrategy = (branch, targetType) => { + const branchLen = branch.length; + const firstTwig = branch[0]; + const lastTwig = branch[branchLen - 1]; + if (branchLen === 1) { + return { dir: DIR_PREV, twig: firstTwig }; + } + // Complex selector (branchLen > 1). + const { + leaves: [{ name: firstName, type: firstType }] + } = firstTwig; + const { + leaves: [{ name: lastName, type: lastType }] + } = lastTwig; + const { combo: firstCombo } = firstTwig; + if ( + this.#selector.includes(':scope') || + lastType === PS_ELEMENT_SELECTOR || + lastType === ID_SELECTOR + ) { + return { dir: DIR_PREV, twig: lastTwig }; + } + if (firstType === ID_SELECTOR) { + return { dir: DIR_NEXT, twig: firstTwig }; + } + if (firstName === '*' && firstType === TYPE_SELECTOR) { + return { dir: DIR_PREV, twig: lastTwig }; + } + if (lastName === '*' && lastType === TYPE_SELECTOR) { + return { dir: DIR_NEXT, twig: firstTwig }; + } + if (branchLen === 2) { + if (targetType === TARGET_FIRST) { + return { dir: DIR_PREV, twig: lastTwig }; + } + const { name: comboName } = firstCombo; + if (comboName === '+' || comboName === '~') { + return { dir: DIR_PREV, twig: lastTwig }; + } + } else if (branchLen > 2 && this.#scoped && targetType === TARGET_FIRST) { + if (lastType === TYPE_SELECTOR) { + return { dir: DIR_PREV, twig: lastTwig }; + } + let isChildOrDescendant = false; + for (const { combo } of branch) { + if (combo) { + const { name: comboName } = combo; + isChildOrDescendant = comboName === '>' || comboName === ' '; + if (!isChildOrDescendant) { + break; + } + } + } + if (isChildOrDescendant) { + return { dir: DIR_PREV, twig: lastTwig }; + } + } + // Default strategy for complex selectors. + return { dir: DIR_NEXT, twig: firstTwig }; + }; + + /** + * Processes pending items not resolved with a direct strategy. + * @private + * @param {Set.} pendingItems - The set of pending items. + */ + _processPendingItems = pendingItems => { + if (!pendingItems.size) { + return; + } + if (!this.#rootWalker) { + this.#rootWalker = this._createTreeWalker(this.#root); + } + const walker = this.#rootWalker; + let node = this.#root; + if (this.#scoped) { + node = this.#node; + } + let nextNode = traverseNode(node, walker); + while (nextNode) { + const isWithinScope = + this.#node.nodeType !== ELEMENT_NODE || + nextNode === this.#node || + this.#node.contains(nextNode); + if (isWithinScope) { + for (const pendingItem of pendingItems) { + const { leaves } = pendingItem.get('twig'); + if (this._matchLeaves(leaves, nextNode, { warn: this.#warn })) { + const index = pendingItem.get('index'); + this.#ast[index].filtered = true; + this.#ast[index].find = true; + this.#nodes[index].push(nextNode); + } + } + } else if (this.#scoped) { + break; + } + nextNode = walker.nextNode(); + } + }; + + /** + * Collects nodes. + * @private + * @param {string} targetType - The target type. + * @returns {Array.>} An array containing the AST and nodes. + */ + _collectNodes = targetType => { + [this.#ast, this.#nodes] = this._correspond(this.#selector); + const ast = this.#ast.values(); + if (targetType === TARGET_ALL || targetType === TARGET_FIRST) { + const pendingItems = new Set(); + let i = 0; + for (const { branch } of ast) { + const complex = branch.length > 1; + const { dir, twig } = this._determineTraversalStrategy( + branch, + targetType + ); + const { compound, filtered, nodes, pending } = this._findEntryNodes( + twig, + targetType, + { complex, dir } + ); + if (nodes.length) { + this.#ast[i].find = true; + this.#nodes[i] = nodes; + } else if (pending) { + pendingItems.add( + new Map([ + ['index', i], + ['twig', twig] + ]) + ); + } + this.#ast[i].dir = dir; + this.#ast[i].filtered = filtered || !compound; + i++; + } + this._processPendingItems(pendingItems); + } else { + let i = 0; + for (const { branch } of ast) { + const twig = branch[branch.length - 1]; + const complex = branch.length > 1; + const dir = DIR_PREV; + const { compound, filtered, nodes } = this._findEntryNodes( + twig, + targetType, + { complex, dir } + ); + if (nodes.length) { + this.#ast[i].find = true; + this.#nodes[i] = nodes; + } + this.#ast[i].dir = dir; + this.#ast[i].filtered = filtered || !compound; + i++; + } + } + return [this.#ast, this.#nodes]; + }; + + /** + * Gets combined nodes. + * @private + * @param {object} twig - The twig object. + * @param {object} nodes - A collection of nodes. + * @param {string} dir - The direction. + * @returns {Array.} A collection of matched nodes. + */ + _getCombinedNodes = (twig, nodes, dir) => { + const arr = []; + for (const node of nodes) { + this._collectCombinatorMatches( + twig, + node, + { dir, warn: this.#warn }, + arr + ); + } + return arr; + }; + + /** + * Matches a node in the 'next' direction. + * @private + * @param {Array} branch - The branch. + * @param {Set.} nodes - A collection of Element nodes. + * @param {object} [opt] - Options. + * @param {object} [opt.combo] - The combo object. + * @param {number} [opt.index] - The index. + * @returns {?object} The matched node. + */ + _matchNodeNext = (branch, nodes, opt = {}) => { + const { combo, index } = opt; + const { combo: nextCombo, leaves } = branch[index]; + const twig = { + combo, + leaves + }; + const nextNodes = this._getCombinedNodes(twig, nodes, DIR_NEXT); + if (nextNodes.length) { + if (index === branch.length - 1) { + if (nextNodes.length === 1) { + return nextNodes[0]; + } + const [nextNode] = sortNodes(nextNodes); + return nextNode; + } + return this._matchNodeNext(branch, nextNodes, { + combo: nextCombo, + index: index + 1 + }); + } + return null; + }; + + /** + * Matches a node in the 'previous' direction. + * @private + * @param {Array} branch - The branch. + * @param {object} node - The Element node. + * @param {object} [opt] - Options. + * @param {number} [opt.index] - The index. + * @returns {?object} The node. + */ + _matchNodePrev = (branch, node, opt = {}) => { + const { index } = opt; + const twig = branch[index]; + const nextNodes = this._getCombinedNodes(twig, [node], DIR_PREV); + if (nextNodes.length) { + if (index === 0) { + return node; + } + let matched; + for (const nextNode of nextNodes) { + matched = this._matchNodePrev(branch, nextNode, { + index: index - 1 + }); + if (matched) { + break; + } + } + if (matched) { + return node; + } + } + return null; + }; + + /** + * Processes a complex selector branch to find all matching nodes. + * @private + * @param {Array} branch - The selector branch from the AST. + * @param {Array} entryNodes - The initial set of nodes to start from. + * @param {string} dir - The direction of traversal ('next' or 'prev'). + * @returns {Set.} A set of all matched nodes. + */ + _processComplexBranchAll = (branch, entryNodes, dir) => { + const matchedNodes = new Set(); + const branchLen = branch.length; + const lastIndex = branchLen - 1; + + if (dir === DIR_NEXT) { + const { combo: firstCombo } = branch[0]; + for (const node of entryNodes) { + let combo = firstCombo; + let nextNodes = [node]; + for (let j = 1; j < branchLen; j++) { + const { combo: nextCombo, leaves } = branch[j]; + const twig = { combo, leaves }; + const nodesArr = this._getCombinedNodes(twig, nextNodes, dir); + if (nodesArr.length) { + if (j === lastIndex) { + for (const nextNode of nodesArr) { + matchedNodes.add(nextNode); + } + } + combo = nextCombo; + nextNodes = nodesArr; + } else { + break; + } + } + } + // DIR_PREV + } else { + for (const node of entryNodes) { + let nextNodes = [node]; + for (let j = lastIndex - 1; j >= 0; j--) { + const twig = branch[j]; + const nodesArr = this._getCombinedNodes(twig, nextNodes, dir); + if (nodesArr.length) { + // The entry node is the final match + if (j === 0) { + matchedNodes.add(node); + } + nextNodes = nodesArr; + } else { + break; + } + } + } + } + return matchedNodes; + }; + + /** + * Processes a complex selector branch to find the first matching node. + * @private + * @param {Array} branch - The selector branch from the AST. + * @param {Array} entryNodes - The initial set of nodes to start from. + * @param {string} dir - The direction of traversal ('next' or 'prev'). + * @param {string} targetType - The type of search (e.g., 'first'). + * @returns {?object} The first matched node, or null. + */ + _processComplexBranchFirst = (branch, entryNodes, dir, targetType) => { + const branchLen = branch.length; + const lastIndex = branchLen - 1; + // DIR_NEXT logic for finding the first match. + if (dir === DIR_NEXT) { + const { combo: entryCombo } = branch[0]; + for (const node of entryNodes) { + const matchedNode = this._matchNodeNext(branch, new Set([node]), { + combo: entryCombo, + index: 1 + }); + if (matchedNode) { + if (this.#node.nodeType === ELEMENT_NODE) { + if ( + matchedNode !== this.#node && + this.#node.contains(matchedNode) + ) { + return matchedNode; + } + } else { + return matchedNode; + } + } + } + // Fallback logic if no direct match found. + const { leaves: entryLeaves } = branch[0]; + const [entryNode] = entryNodes; + if (this.#node.contains(entryNode)) { + let [refNode] = this._findNodeWalker(entryLeaves, entryNode, { + targetType + }); + while (refNode) { + const matchedNode = this._matchNodeNext(branch, new Set([refNode]), { + combo: entryCombo, + index: 1 + }); + if (matchedNode) { + if (this.#node.nodeType === ELEMENT_NODE) { + if ( + matchedNode !== this.#node && + this.#node.contains(matchedNode) + ) { + return matchedNode; + } + } else { + return matchedNode; + } + } + [refNode] = this._findNodeWalker(entryLeaves, refNode, { + targetType, + force: true + }); + } + } + // DIR_PREV logic for finding the first match. + } else { + for (const node of entryNodes) { + const matchedNode = this._matchNodePrev(branch, node, { + index: lastIndex - 1 + }); + if (matchedNode) { + return matchedNode; + } + } + // Fallback for TARGET_FIRST. + if (targetType === TARGET_FIRST) { + const { leaves: entryLeaves } = branch[lastIndex]; + const [entryNode] = entryNodes; + let [refNode] = this._findNodeWalker(entryLeaves, entryNode, { + targetType + }); + while (refNode) { + const matchedNode = this._matchNodePrev(branch, refNode, { + index: lastIndex - 1 + }); + if (matchedNode) { + return refNode; + } + [refNode] = this._findNodeWalker(entryLeaves, refNode, { + targetType, + force: true + }); + } + } + } + return null; + }; + + /** + * Finds matched nodes. + * @param {string} targetType - The target type. + * @returns {Set.} A collection of matched nodes. + */ + find = targetType => { + let collection; + try { + collection = this._collectNodes(targetType); + } catch (e) { + if (this.#check) { + let pseudoElement; + if (this.#pseudoElement.length) { + pseudoElement = this.#pseudoElement.join(''); + } else { + pseudoElement = null; + } + return { + pseudoElement, + match: false, + ast: this.#selectorAST ?? null + }; + } else { + throw e; + } + } + const [[...branches], collectedNodes] = collection; + const l = branches.length; + let sort = + l > 1 && targetType === TARGET_ALL && this.#selector.includes(':scope'); + let nodes = new Set(); + for (let i = 0; i < l; i++) { + const { branch, dir, find } = branches[i]; + if (!branch.length || !find) { + continue; + } + const entryNodes = collectedNodes[i]; + const lastIndex = branch.length - 1; + // Handle simple selectors (no combinators). + if (lastIndex === 0) { + if ( + (targetType === TARGET_ALL || targetType === TARGET_FIRST) && + this.#node.nodeType === ELEMENT_NODE + ) { + for (const node of entryNodes) { + if (node !== this.#node && this.#node.contains(node)) { + nodes.add(node); + if (targetType === TARGET_FIRST) { + break; + } + } + } + } else if (targetType === TARGET_ALL) { + if (nodes.size) { + for (const node of entryNodes) { + nodes.add(node); + } + sort = true; + } else { + nodes = new Set(entryNodes); + } + } else { + if (entryNodes.length) { + nodes.add(entryNodes[0]); + } + } + // Handle complex selectors. + } else { + if (targetType === TARGET_ALL) { + const newNodes = this._processComplexBranchAll( + branch, + entryNodes, + dir + ); + if (nodes.size) { + for (const newNode of newNodes) { + nodes.add(newNode); + } + sort = true; + } else { + nodes = newNodes; + } + } else { + const matchedNode = this._processComplexBranchFirst( + branch, + entryNodes, + dir, + targetType + ); + if (matchedNode) { + nodes.add(matchedNode); + } + } + } + } + if (this.#check) { + const match = !!nodes.size; + let pseudoElement; + if (this.#pseudoElement.length) { + pseudoElement = this.#pseudoElement.join(''); + } else { + pseudoElement = null; + } + return { + match, + pseudoElement, + ast: this.#selectorAST + }; + } + if (targetType === TARGET_FIRST || targetType === TARGET_ALL) { + nodes.delete(this.#node); + } + if ((sort || targetType === TARGET_FIRST) && nodes.size > 1) { + return new Set(sortNodes(nodes)); + } + return nodes; + }; + + /** + * Gets AST for selector. + * @param {string} selector - The selector text. + * @returns {object} The AST for the selector. + */ + getAST = selector => { + return parseSelector(selector); + }; +} diff --git a/node_modules/@asamuzakjp/dom-selector/src/js/matcher.js b/node_modules/@asamuzakjp/dom-selector/src/js/matcher.js new file mode 100644 index 00000000..ad482379 --- /dev/null +++ b/node_modules/@asamuzakjp/dom-selector/src/js/matcher.js @@ -0,0 +1,591 @@ +/** + * matcher.js + */ + +/* import */ +import { generateCSS, parseAstName, unescapeSelector } from './parser.js'; +import { + generateException, + getDirectionality, + getLanguageAttribute, + getType, + isContentEditable, + isCustomElement, + isNamespaceDeclared +} from './utility.js'; + +/* constants */ +import { + ALPHA_NUM, + FORM_PARTS, + IDENT, + INPUT_EDIT, + LANG_PART, + NOT_SUPPORTED_ERR, + PS_ELEMENT_SELECTOR, + STRING, + SYNTAX_ERR +} from './constant.js'; +const KEYS_FORM_PS_DISABLED = new Set([ + ...FORM_PARTS, + 'fieldset', + 'optgroup', + 'option' +]); +const KEYS_INPUT_EDIT = new Set(INPUT_EDIT); +const REG_LANG_VALID = new RegExp(`^(?:\\*-)?${ALPHA_NUM}${LANG_PART}$`, 'i'); + +/** + * Validates a pseudo-element selector. + * @param {string} astName - The name of the pseudo-element from the AST. + * @param {string} astType - The type of the selector from the AST. + * @param {object} [opt] - Optional parameters. + * @param {boolean} [opt.forgive] - If true, ignores unknown pseudo-elements. + * @param {boolean} [opt.warn] - If true, throws an error for unsupported ones. + * @throws {DOMException} If the selector is invalid or unsupported. + * @returns {void} + */ +export const matchPseudoElementSelector = (astName, astType, opt = {}) => { + const { forgive, globalObject, warn } = opt; + if (astType !== PS_ELEMENT_SELECTOR) { + // Ensure the AST node is a pseudo-element selector. + throw new TypeError(`Unexpected ast type ${getType(astType)}`); + } + switch (astName) { + case 'after': + case 'backdrop': + case 'before': + case 'cue': + case 'cue-region': + case 'first-letter': + case 'first-line': + case 'file-selector-button': + case 'marker': + case 'placeholder': + case 'selection': + case 'target-text': { + // Warn if the pseudo-element is known but unsupported. + if (warn) { + throw generateException( + `Unsupported pseudo-element ::${astName}`, + NOT_SUPPORTED_ERR, + globalObject + ); + } + break; + } + case 'part': + case 'slotted': { + // Warn if the functional pseudo-element is known but unsupported. + if (warn) { + throw generateException( + `Unsupported pseudo-element ::${astName}()`, + NOT_SUPPORTED_ERR, + globalObject + ); + } + break; + } + default: { + // Handle vendor-prefixed or unknown pseudo-elements. + if (astName.startsWith('-webkit-')) { + if (warn) { + throw generateException( + `Unsupported pseudo-element ::${astName}`, + NOT_SUPPORTED_ERR, + globalObject + ); + } + // Throw an error for unknown pseudo-elements if not forgiven. + } else if (!forgive) { + throw generateException( + `Unknown pseudo-element ::${astName}`, + SYNTAX_ERR, + globalObject + ); + } + } + } +}; + +/** + * Matches the :dir() pseudo-class against an element's directionality. + * @param {object} ast - The AST object for the pseudo-class. + * @param {object} node - The element node to match against. + * @throws {TypeError} If the AST does not contain a valid direction value. + * @returns {boolean} - True if the directionality matches, otherwise false. + */ +export const matchDirectionPseudoClass = (ast, node) => { + const { name } = ast; + // The :dir() pseudo-class requires a direction argument (e.g., "ltr"). + if (!name) { + const type = name === '' ? '(empty String)' : getType(name); + throw new TypeError(`Unexpected ast type ${type}`); + } + // Get the computed directionality of the element. + const dir = getDirectionality(node); + // Compare the expected direction with the element's actual direction. + return name === dir; +}; + +/** + * Matches the :lang() pseudo-class against an element's language. + * @see https://datatracker.ietf.org/doc/html/rfc4647#section-3.3.1 + * @param {object} ast - The AST object for the pseudo-class. + * @param {object} node - The element node to match against. + * @returns {boolean} - True if the language matches, otherwise false. + */ +export const matchLanguagePseudoClass = (ast, node) => { + const { name, type, value } = ast; + let langPattern; + // Determine the language pattern from the AST. + if (type === STRING && value) { + langPattern = value; + } else if (type === IDENT && name) { + langPattern = unescapeSelector(name); + } + // If no valid language pattern is provided, it cannot match. + if (typeof langPattern !== 'string') { + return false; + } + // Get the effective language attribute for the current node. + const elementLang = getLanguageAttribute(node); + // If the element has no language, it cannot match a specific pattern. + if (elementLang === null) { + return false; + } + // Handle the universal selector '*' for :lang. + if (langPattern === '*') { + // It matches any language unless attribute is not empty. + return elementLang !== ''; + } + // Validate the provided language pattern structure. + if (!REG_LANG_VALID.test(langPattern)) { + return false; + } + // Build a regex for extended language range matching. + let matcherRegex; + if (langPattern.indexOf('-') > -1) { + // Handle complex patterns with wildcards and sub-tags (e.g., '*-US'). + const [langMain, langSub, ...langRest] = langPattern.split('-'); + const extendedMain = + langMain === '*' ? `${ALPHA_NUM}${LANG_PART}` : `${langMain}${LANG_PART}`; + const extendedSub = `-${langSub}${LANG_PART}`; + let extendedRest = ''; + // Use a standard for loop for performance as per the rules. + for (let i = 0; i < langRest.length; i++) { + extendedRest += `-${langRest[i]}${LANG_PART}`; + } + matcherRegex = new RegExp( + `^${extendedMain}${extendedSub}${extendedRest}$`, + 'i' + ); + } else { + // Handle simple language patterns (e.g., 'en'). + matcherRegex = new RegExp(`^${langPattern}${LANG_PART}$`, 'i'); + } + // Test the element's language against the constructed regex. + return matcherRegex.test(elementLang); +}; + +/** + * Matches the :disabled and :enabled pseudo-classes. + * @param {string} astName - pseudo-class name + * @param {object} node - Element node + * @returns {boolean} - True if matched + */ +export const matchDisabledPseudoClass = (astName, node) => { + const { localName, parentNode } = node; + if ( + !KEYS_FORM_PS_DISABLED.has(localName) && + !isCustomElement(node, { formAssociated: true }) + ) { + return false; + } + let isDisabled = false; + if (node.disabled || node.hasAttribute('disabled')) { + isDisabled = true; + } else if (localName === 'option') { + if ( + parentNode && + parentNode.localName === 'optgroup' && + (parentNode.disabled || parentNode.hasAttribute('disabled')) + ) { + isDisabled = true; + } + } else if (localName !== 'optgroup') { + let current = parentNode; + while (current) { + if ( + current.localName === 'fieldset' && + (current.disabled || current.hasAttribute('disabled')) + ) { + // The first in a disabled
is not disabled. + let legend; + let element = current.firstElementChild; + while (element) { + if (element.localName === 'legend') { + legend = element; + break; + } + element = element.nextElementSibling; + } + if (!legend || !legend.contains(node)) { + isDisabled = true; + } + // Found the containing fieldset, stop searching up. + break; + } + current = current.parentNode; + } + } + if (astName === 'disabled') { + return isDisabled; + } + return !isDisabled; +}; + +/** + * Match the :read-only and :read-write pseudo-classes + * @param {string} astName - pseudo-class name + * @param {object} node - Element node + * @returns {boolean} - True if matched + */ +export const matchReadOnlyPseudoClass = (astName, node) => { + const { localName } = node; + let isReadOnly = false; + switch (localName) { + case 'textarea': + case 'input': { + const isEditableInput = !node.type || KEYS_INPUT_EDIT.has(node.type); + if (localName === 'textarea' || isEditableInput) { + isReadOnly = + node.readOnly || + node.hasAttribute('readonly') || + node.disabled || + node.hasAttribute('disabled'); + } else { + // Non-editable input types are always read-only + isReadOnly = true; + } + break; + } + default: { + isReadOnly = !isContentEditable(node); + } + } + if (astName === 'read-only') { + return isReadOnly; + } + return !isReadOnly; +}; + +/** + * Matches an attribute selector against an element. + * This function handles various attribute matchers like '=', '~=', '^=', etc., + * and considers namespaces and case sensitivity based on document type. + * @param {object} ast - The AST for the attribute selector. + * @param {object} node - The element node to match against. + * @param {object} [opt] - Optional parameters. + * @param {boolean} [opt.check] - True if running in an internal check. + * @param {boolean} [opt.forgive] - True to forgive certain syntax errors. + * @returns {boolean} - True if the attribute selector matches, otherwise false. + */ +export const matchAttributeSelector = (ast, node, opt = {}) => { + const { + flags: astFlags, + matcher: astMatcher, + name: astName, + value: astValue + } = ast; + const { check, forgive, globalObject } = opt; + // Validate selector flags ('i' or 's'). + if (typeof astFlags === 'string' && !/^[is]$/i.test(astFlags) && !forgive) { + const css = generateCSS(ast); + throw generateException( + `Invalid selector ${css}`, + SYNTAX_ERR, + globalObject + ); + } + const { attributes } = node; + // An element with no attributes cannot match. + if (!attributes || !attributes.length) { + return false; + } + // Determine case sensitivity based on document type and flags. + let caseInsensitive; + if (node.ownerDocument.contentType === 'text/html') { + if (typeof astFlags === 'string' && /^s$/i.test(astFlags)) { + caseInsensitive = false; + } else { + caseInsensitive = true; + } + } else if (typeof astFlags === 'string' && /^i$/i.test(astFlags)) { + caseInsensitive = true; + } else { + caseInsensitive = false; + } + // Prepare the attribute name from the selector for matching. + let astAttrName = unescapeSelector(astName.name); + if (caseInsensitive) { + astAttrName = astAttrName.toLowerCase(); + } + // A set to store the values of attributes whose names match. + const attrValues = new Set(); + // Handle namespaced attribute names (e.g., [*|attr], [ns|attr]). + if (astAttrName.indexOf('|') > -1) { + const { prefix: astPrefix, localName: astLocalName } = + parseAstName(astAttrName); + for (const item of attributes) { + let { name: itemName, value: itemValue } = item; + if (caseInsensitive) { + itemName = itemName.toLowerCase(); + itemValue = itemValue.toLowerCase(); + } + const colonIdx = itemName.indexOf(':'); + switch (astPrefix) { + case '': { + if (astLocalName === itemName) { + attrValues.add(itemValue); + } + break; + } + case '*': { + if (colonIdx > -1) { + const itemLocalName = itemName + .substring(colonIdx + 1) + .replace(/^:/, ''); + if (itemLocalName === astLocalName) { + attrValues.add(itemValue); + } + } else if (astLocalName === itemName) { + attrValues.add(itemValue); + } + break; + } + default: { + if (!check) { + if (forgive) { + return false; + } + const css = generateCSS(ast); + throw generateException( + `Invalid selector ${css}`, + SYNTAX_ERR, + globalObject + ); + } + if (colonIdx > -1) { + const itemPrefix = itemName.substring(0, colonIdx); + const itemLocalName = itemName + .substring(colonIdx + 1) + .replace(/^:/, ''); + // Ignore the 'xml:lang' attribute. + if (itemPrefix === 'xml' && itemLocalName === 'lang') { + continue; + } else if ( + astPrefix === itemPrefix && + astLocalName === itemLocalName + ) { + const namespaceDeclared = isNamespaceDeclared(astPrefix, node); + if (namespaceDeclared) { + attrValues.add(itemValue); + } + } + } + } + } + } + // Handle non-namespaced attribute names. + } else { + for (let { name: itemName, value: itemValue } of attributes) { + if (caseInsensitive) { + itemName = itemName.toLowerCase(); + itemValue = itemValue.toLowerCase(); + } + const colonIdx = itemName.indexOf(':'); + if (colonIdx > -1) { + const itemPrefix = itemName.substring(0, colonIdx); + const itemLocalName = itemName + .substring(colonIdx + 1) + .replace(/^:/, ''); + // The attribute is starting with ':'. + if (!itemPrefix && astAttrName === `:${itemLocalName}`) { + attrValues.add(itemValue); + // Ignore the 'xml:lang' attribute. + } else if (itemPrefix === 'xml' && itemLocalName === 'lang') { + continue; + } else if (astAttrName === itemLocalName) { + attrValues.add(itemValue); + } + } else if (astAttrName === itemName) { + attrValues.add(itemValue); + } + } + } + if (!attrValues.size) { + return false; + } + // Prepare the value from the selector's RHS for comparison. + const { name: astIdentValue, value: astStringValue } = astValue ?? {}; + let attrValue; + if (astIdentValue) { + if (caseInsensitive) { + attrValue = astIdentValue.toLowerCase().replace(/\\(?!\\)/g, ''); + } else { + attrValue = astIdentValue.replace(/\\(?!\\)/g, ''); + } + } else if (astStringValue) { + if (caseInsensitive) { + attrValue = astStringValue.toLowerCase().replace(/\\(?!\\)/g, ''); + } else { + attrValue = astStringValue.replace(/\\(?!\\)/g, ''); + } + } else if (astStringValue === '') { + attrValue = astStringValue; + } + // Perform the final match based on the specified matcher. + switch (astMatcher) { + case '=': { + return typeof attrValue === 'string' && attrValues.has(attrValue); + } + case '~=': { + if (attrValue && typeof attrValue === 'string') { + for (const value of attrValues) { + const item = new Set(value.split(/\s+/)); + if (item.has(attrValue)) { + return true; + } + } + } + return false; + } + case '|=': { + if (attrValue && typeof attrValue === 'string') { + for (const value of attrValues) { + if (value === attrValue || value.startsWith(`${attrValue}-`)) { + return true; + } + } + } + return false; + } + case '^=': { + if (attrValue && typeof attrValue === 'string') { + for (const value of attrValues) { + if (value.startsWith(`${attrValue}`)) { + return true; + } + } + } + return false; + } + case '$=': { + if (attrValue && typeof attrValue === 'string') { + for (const value of attrValues) { + if (value.endsWith(`${attrValue}`)) { + return true; + } + } + } + return false; + } + case '*=': { + if (attrValue && typeof attrValue === 'string') { + for (const value of attrValues) { + if (value.includes(`${attrValue}`)) { + return true; + } + } + } + return false; + } + case null: + default: { + // This case handles attribute existence checks (e.g., '[disabled]'). + return true; + } + } +}; + +/** + * match type selector + * @param {object} ast - AST + * @param {object} node - Element node + * @param {object} [opt] - options + * @param {boolean} [opt.check] - running in internal check() + * @param {boolean} [opt.forgive] - forgive undeclared namespace + * @returns {boolean} - result + */ +export const matchTypeSelector = (ast, node, opt = {}) => { + const astName = unescapeSelector(ast.name); + const { localName, namespaceURI, prefix } = node; + const { check, forgive, globalObject } = opt; + let { prefix: astPrefix, localName: astLocalName } = parseAstName( + astName, + node + ); + const isHTML = + node.ownerDocument.contentType === 'text/html' && + (!namespaceURI || namespaceURI === 'http://www.w3.org/1999/xhtml'); + if (isHTML && localName === astLocalName && !astName.includes('|')) { + return true; + } + const firstChar = localName.charCodeAt(0); + const isAlphabet = + (firstChar >= 65 && firstChar <= 90) || + (firstChar >= 97 && firstChar <= 122); + if (isHTML && isAlphabet) { + astPrefix = astPrefix.toLowerCase(); + astLocalName = astLocalName.toLowerCase(); + } + let nodePrefix; + let nodeLocalName; + const colonIdx = localName.indexOf(':'); + if (colonIdx > -1) { + nodePrefix = localName.substring(0, colonIdx); + nodeLocalName = localName.substring(colonIdx + 1); + } else { + nodePrefix = prefix || ''; + nodeLocalName = localName; + } + const isUniversal = astLocalName === '*'; + switch (astPrefix) { + case '': { + return ( + !nodePrefix && + !namespaceURI && + (isUniversal || astLocalName === nodeLocalName) + ); + } + case '*': { + return isUniversal || astLocalName === nodeLocalName; + } + default: { + if (!check) { + if (forgive) { + return false; + } + const css = generateCSS(ast); + throw generateException( + `Invalid selector ${css}`, + SYNTAX_ERR, + globalObject + ); + } + const astNS = node.lookupNamespaceURI(astPrefix); + const nodeNS = node.lookupNamespaceURI(nodePrefix); + if (astNS === nodeNS && astPrefix === nodePrefix) { + return isUniversal || astLocalName === nodeLocalName; + } else if (!forgive && !astNS) { + throw generateException( + `Undeclared namespace ${astPrefix}`, + SYNTAX_ERR, + globalObject + ); + } + return false; + } + } +}; diff --git a/node_modules/@asamuzakjp/dom-selector/src/js/parser.js b/node_modules/@asamuzakjp/dom-selector/src/js/parser.js new file mode 100644 index 00000000..bfee8a64 --- /dev/null +++ b/node_modules/@asamuzakjp/dom-selector/src/js/parser.js @@ -0,0 +1,434 @@ +/** + * parser.js + */ + +/* import */ +import * as cssTree from 'css-tree'; +import { getType } from './utility.js'; + +/* constants */ +import { + ATTR_SELECTOR, + BIT_01, + BIT_02, + BIT_04, + BIT_08, + BIT_16, + BIT_32, + BIT_FFFF, + CLASS_SELECTOR, + DUO, + HEX, + ID_SELECTOR, + KEYS_LOGICAL, + NTH, + PS_CLASS_SELECTOR, + PS_ELEMENT_SELECTOR, + SELECTOR, + SYNTAX_ERR, + TYPE_SELECTOR +} from './constant.js'; +const AST_SORT_ORDER = new Map([ + [PS_ELEMENT_SELECTOR, BIT_01], + [ID_SELECTOR, BIT_02], + [CLASS_SELECTOR, BIT_04], + [TYPE_SELECTOR, BIT_08], + [ATTR_SELECTOR, BIT_16], + [PS_CLASS_SELECTOR, BIT_32] +]); +const KEYS_PS_CLASS_STATE = new Set([ + 'checked', + 'closed', + 'disabled', + 'empty', + 'enabled', + 'in-range', + 'indeterminate', + 'invalid', + 'open', + 'out-of-range', + 'placeholder-shown', + 'read-only', + 'read-write', + 'valid' +]); +const KEYS_SHADOW_HOST = new Set(['host', 'host-context']); +const REG_EMPTY_PS_FUNC = + /(?<=:(?:dir|has|host(?:-context)?|is|lang|not|nth-(?:last-)?(?:child|of-type)|where))\(\s+\)/g; +const REG_SHADOW_PS_ELEMENT = /^part|slotted$/; +const U_FFFD = '\uFFFD'; + +/** + * Unescapes a CSS selector string. + * @param {string} selector - The CSS selector to unescape. + * @returns {string} The unescaped selector string. + */ +export const unescapeSelector = (selector = '') => { + if (typeof selector === 'string' && selector.indexOf('\\', 0) >= 0) { + const arr = selector.split('\\'); + const selectorItems = [arr[0]]; + const l = arr.length; + for (let i = 1; i < l; i++) { + const item = arr[i]; + if (item === '' && i === l - 1) { + selectorItems.push(U_FFFD); + } else { + const hexExists = /^([\da-f]{1,6}\s?)/i.exec(item); + if (hexExists) { + const [, hex] = hexExists; + let str; + try { + const low = parseInt('D800', HEX); + const high = parseInt('DFFF', HEX); + const deci = parseInt(hex, HEX); + if (deci === 0 || (deci >= low && deci <= high)) { + str = U_FFFD; + } else { + str = String.fromCodePoint(deci); + } + } catch (e) { + str = U_FFFD; + } + let postStr = ''; + if (item.length > hex.length) { + postStr = item.substring(hex.length); + } + selectorItems.push(`${str}${postStr}`); + // whitespace + } else if (/^[\n\r\f]/.test(item)) { + selectorItems.push(`\\${item}`); + } else { + selectorItems.push(item); + } + } + } + return selectorItems.join(''); + } + return selector; +}; + +/** + * Preprocesses a selector string according to the specification. + * @see https://drafts.csswg.org/css-syntax-3/#input-preprocessing + * @param {string} value - The value to preprocess. + * @returns {string} The preprocessed selector string. + */ +export const preprocess = value => { + // Non-string values will be converted to string. + if (typeof value !== 'string') { + if (value === undefined || value === null) { + return getType(value).toLowerCase(); + } else if (Array.isArray(value)) { + return value.join(','); + } else if (Object.hasOwn(value, 'toString')) { + return value.toString(); + } else { + throw new DOMException(`Invalid selector ${value}`, SYNTAX_ERR); + } + } + let selector = value; + let index = 0; + while (index >= 0) { + // @see https://drafts.csswg.org/selectors/#id-selectors + index = selector.indexOf('#', index); + if (index < 0) { + break; + } + const preHash = selector.substring(0, index + 1); + let postHash = selector.substring(index + 1); + const codePoint = postHash.codePointAt(0); + if (codePoint > BIT_FFFF) { + const str = `\\${codePoint.toString(HEX)} `; + if (postHash.length === DUO) { + postHash = str; + } else { + postHash = `${str}${postHash.substring(DUO)}`; + } + } + selector = `${preHash}${postHash}`; + index++; + } + selector = selector + .replace(/\f|\r\n?/g, '\n') + .replace(/[\0\uD800-\uDFFF]|\\$/g, U_FFFD); + if (selector === '&') { + return ''; + } + return selector.replace(/\x26/g, ':scope'); +}; + +/** + * Creates an Abstract Syntax Tree (AST) from a CSS selector string. + * @param {string} sel - The CSS selector string. + * @returns {object} The parsed AST object. + */ +export const parseSelector = sel => { + const selector = preprocess(sel); + // invalid selectors + if (/^$|^\s*>|,\s*$/.test(selector)) { + throw new DOMException(`Invalid selector ${selector}`, SYNTAX_ERR); + } + try { + return cssTree.parse(selector, { + context: 'selectorList' + }); + } catch (e) { + const { message } = e; + if ( + /^(?:"\]"|Attribute selector [()\s,=~^$*|]+) is expected$/.test( + message + ) && + !selector.endsWith(']') + ) { + const index = selector.lastIndexOf('['); + const selPart = selector.substring(index); + if (selPart.includes('"')) { + const quotes = selPart.match(/"/g).length; + if (quotes % 2) { + return parseSelector(`${selector}"]`); + } + return parseSelector(`${selector}]`); + } + return parseSelector(`${selector}]`); + } else if (message === '")" is expected') { + // workaround for https://github.com/csstree/csstree/issues/283 + if (REG_EMPTY_PS_FUNC.test(selector)) { + return parseSelector(`${selector.replaceAll(REG_EMPTY_PS_FUNC, '()')}`); + } else if (!selector.endsWith(')')) { + return parseSelector(`${selector})`); + } else { + throw new DOMException(`Invalid selector ${selector}`, SYNTAX_ERR); + } + } else { + throw new DOMException(`Invalid selector ${selector}`, SYNTAX_ERR); + } + } +}; + +/** + * Walks the provided AST to collect selector branches and gather information + * about its contents. + * @param {object} ast - The AST to traverse. + * @param {boolean} toObject - True if converts ast to object, false otherwise. + * @returns {{branches: Array, info: object}} An object containing the selector branches and info. + */ +export const walkAST = (ast = {}, toObject = false) => { + const branches = new Set(); + const info = { + hasForgivenPseudoFunc: false, + hasHasPseudoFunc: false, + hasLogicalPseudoFunc: false, + hasNotPseudoFunc: false, + hasNthChildOfSelector: false, + hasNestedSelector: false, + hasStatePseudoClass: false + }; + const opt = { + enter(node) { + switch (node.type) { + case CLASS_SELECTOR: { + if (/^-?\d/.test(node.name)) { + throw new DOMException( + `Invalid selector .${node.name}`, + SYNTAX_ERR + ); + } + break; + } + case ID_SELECTOR: { + if (/^-?\d/.test(node.name)) { + throw new DOMException( + `Invalid selector #${node.name}`, + SYNTAX_ERR + ); + } + break; + } + case PS_CLASS_SELECTOR: { + if (KEYS_LOGICAL.has(node.name)) { + info.hasNestedSelector = true; + info.hasLogicalPseudoFunc = true; + if (node.name === 'has') { + info.hasHasPseudoFunc = true; + } else if (node.name === 'not') { + info.hasNotPseudoFunc = true; + } else { + info.hasForgivenPseudoFunc = true; + } + } else if (KEYS_PS_CLASS_STATE.has(node.name)) { + info.hasStatePseudoClass = true; + } else if ( + KEYS_SHADOW_HOST.has(node.name) && + Array.isArray(node.children) && + node.children.length + ) { + info.hasNestedSelector = true; + } + break; + } + case PS_ELEMENT_SELECTOR: { + if (REG_SHADOW_PS_ELEMENT.test(node.name)) { + info.hasNestedSelector = true; + } + break; + } + case NTH: { + if (node.selector) { + info.hasNestedSelector = true; + info.hasNthChildOfSelector = true; + } + break; + } + case SELECTOR: { + branches.add(node.children); + break; + } + default: + } + } + }; + const clonedAst = cssTree.clone(ast); + cssTree.walk(toObject ? cssTree.toPlainObject(clonedAst) : clonedAst, opt); + if (info.hasNestedSelector === true) { + cssTree.findAll(clonedAst, (node, item, list) => { + if (list) { + if (node.type === PS_CLASS_SELECTOR && KEYS_LOGICAL.has(node.name)) { + const itemList = list.filter(i => { + const { name, type } = i; + return type === PS_CLASS_SELECTOR && KEYS_LOGICAL.has(name); + }); + for (const { children } of itemList) { + // SelectorList + for (const { children: grandChildren } of children) { + // Selector + for (const { children: greatGrandChildren } of grandChildren) { + if (branches.has(greatGrandChildren)) { + branches.delete(greatGrandChildren); + } + } + } + } + } else if ( + node.type === PS_CLASS_SELECTOR && + KEYS_SHADOW_HOST.has(node.name) && + Array.isArray(node.children) && + node.children.length + ) { + const itemList = list.filter(i => { + const { children, name, type } = i; + const res = + type === PS_CLASS_SELECTOR && + KEYS_SHADOW_HOST.has(name) && + Array.isArray(children) && + children.length; + return res; + }); + for (const { children } of itemList) { + // Selector + for (const { children: grandChildren } of children) { + if (branches.has(grandChildren)) { + branches.delete(grandChildren); + } + } + } + } else if ( + node.type === PS_ELEMENT_SELECTOR && + REG_SHADOW_PS_ELEMENT.test(node.name) + ) { + const itemList = list.filter(i => { + const { name, type } = i; + const res = + type === PS_ELEMENT_SELECTOR && REG_SHADOW_PS_ELEMENT.test(name); + return res; + }); + for (const { children } of itemList) { + // Selector + for (const { children: grandChildren } of children) { + if (branches.has(grandChildren)) { + branches.delete(grandChildren); + } + } + } + } else if (node.type === NTH && node.selector) { + const itemList = list.filter(i => { + const { selector, type } = i; + const res = type === NTH && selector; + return res; + }); + for (const { selector } of itemList) { + const { children } = selector; + // Selector + for (const { children: grandChildren } of children) { + if (branches.has(grandChildren)) { + branches.delete(grandChildren); + } + } + } + } + } + }); + } + return { + info, + branches: [...branches] + }; +}; + +/** + * Comparison function for sorting AST nodes based on specificity. + * @param {object} a - The first AST node. + * @param {object} b - The second AST node. + * @returns {number} -1, 0 or 1, depending on the sort order. + */ +export const compareASTNodes = (a, b) => { + const bitA = AST_SORT_ORDER.get(a.type); + const bitB = AST_SORT_ORDER.get(b.type); + if (bitA === bitB) { + return 0; + } else if (bitA > bitB) { + return 1; + } else { + return -1; + } +}; + +/** + * Sorts a collection of AST nodes based on CSS specificity rules. + * @param {Array} asts - A collection of AST nodes to sort. + * @returns {Array} A new array containing the sorted AST nodes. + */ +export const sortAST = asts => { + const arr = [...asts]; + if (arr.length > 1) { + arr.sort(compareASTNodes); + } + return arr; +}; + +/** + * Parses a type selector's name, which may include a namespace prefix. + * @param {string} selector - The type selector name (e.g., 'ns|E' or 'E'). + * @returns {{prefix: string, localName: string}} An object with `prefix` and + * `localName` properties. + */ +export const parseAstName = selector => { + let prefix; + let localName; + if (selector && typeof selector === 'string') { + if (selector.indexOf('|') > -1) { + [prefix, localName] = selector.split('|'); + } else { + prefix = '*'; + localName = selector; + } + } else { + throw new DOMException(`Invalid selector ${selector}`, SYNTAX_ERR); + } + return { + prefix, + localName + }; +}; + +/* Re-exported from css-tree. */ +export { find as findAST, generate as generateCSS } from 'css-tree'; diff --git a/node_modules/@asamuzakjp/dom-selector/src/js/utility.js b/node_modules/@asamuzakjp/dom-selector/src/js/utility.js new file mode 100644 index 00000000..c4c9f667 --- /dev/null +++ b/node_modules/@asamuzakjp/dom-selector/src/js/utility.js @@ -0,0 +1,1113 @@ +/** + * utility.js + */ + +/* import */ +import nwsapi from '@asamuzakjp/nwsapi'; +import bidiFactory from 'bidi-js'; +import * as cssTree from 'css-tree'; +import isCustomElementName from 'is-potential-custom-element-name'; + +/* constants */ +import { + ATRULE, + COMBO, + COMPOUND_I, + DESCEND, + DOCUMENT_FRAGMENT_NODE, + DOCUMENT_NODE, + DOCUMENT_POSITION_CONTAINS, + DOCUMENT_POSITION_PRECEDING, + ELEMENT_NODE, + HAS_COMPOUND, + INPUT_BUTTON, + INPUT_EDIT, + INPUT_LTR, + INPUT_TEXT, + KEYS_LOGICAL, + LOGIC_COMPLEX, + LOGIC_COMPOUND, + N_TH, + PSEUDO_CLASS, + RULE, + SCOPE, + SELECTOR_LIST, + TAG_TYPE, + TARGET_ALL, + TARGET_FIRST, + TEXT_NODE, + TYPE_FROM, + TYPE_TO +} from './constant.js'; +const KEYS_DIR_AUTO = new Set([...INPUT_BUTTON, ...INPUT_TEXT, 'hidden']); +const KEYS_DIR_LTR = new Set(INPUT_LTR); +const KEYS_INPUT_EDIT = new Set(INPUT_EDIT); +const KEYS_NODE_DIR_EXCLUDE = new Set(['bdi', 'script', 'style', 'textarea']); +const KEYS_NODE_FOCUSABLE = new Set(['button', 'select', 'textarea']); +const KEYS_NODE_FOCUSABLE_SVG = new Set([ + 'clipPath', + 'defs', + 'desc', + 'linearGradient', + 'marker', + 'mask', + 'metadata', + 'pattern', + 'radialGradient', + 'script', + 'style', + 'symbol', + 'title' +]); +const REG_ATTR_SIMPLE = /^\[[A-Z\d-]{1,255}(?:="?[A-Z\d\s-]{1,255}"?)?\]$/i; +const REG_TAG_SIMPLE = new RegExp(`^(?:${TAG_TYPE})$`); +const REG_EXCLUDE_BASIC = + /[|\\]|::|[^\u0021-\u007F\s]|\[\s*[\w$*=^|~-]+(?:(?:"[\w$*=^|~\s'-]+"|'[\w$*=^|~\s"-]+')?(?:\s+[\w$*=^|~-]+)+|"[^"\]]{1,255}|'[^'\]]{1,255})\s*\]|:(?:is|where)\(\s*\)/; +const REG_COMPLEX = new RegExp(`${COMPOUND_I}${COMBO}${COMPOUND_I}`, 'i'); +const REG_DESCEND = new RegExp(`${COMPOUND_I}${DESCEND}${COMPOUND_I}`, 'i'); +const REG_LOGIC_COMPLEX = new RegExp( + `:(?!${PSEUDO_CLASS}|${N_TH}|${LOGIC_COMPLEX})` +); +const REG_LOGIC_COMPOUND = new RegExp( + `:(?!${PSEUDO_CLASS}|${N_TH}|${LOGIC_COMPOUND})` +); +const REG_LOGIC_HAS_COMPOUND = new RegExp( + `:(?!${PSEUDO_CLASS}|${N_TH}|${LOGIC_COMPOUND}|${HAS_COMPOUND})` +); +const REG_END_WITH_HAS = new RegExp(`:${HAS_COMPOUND}$`); +const REG_WO_LOGICAL = new RegExp(`:(?!${PSEUDO_CLASS}|${N_TH})`); +const REG_IS_HTML = /^(?:application\/xhtml\+x|text\/ht)ml$/; +const REG_IS_XML = + /^(?:application\/(?:[\w\-.]+\+)?|image\/[\w\-.]+\+|text\/)xml$/; + +/** + * Manages state for extracting nested selectors from a CSS AST. + */ +class SelectorExtractor { + constructor() { + this.selectors = []; + this.isScoped = false; + } + + /** + * Walker enter function. + * @param {object} node - The AST node. + */ + enter(node) { + switch (node.type) { + case ATRULE: { + if (node.name === 'scope') { + this.isScoped = true; + } + break; + } + case SCOPE: { + const { children, type } = node.root; + const arr = []; + if (type === SELECTOR_LIST) { + for (const child of children) { + const selector = cssTree.generate(child); + arr.push(selector); + } + this.selectors.push(arr); + } + break; + } + case RULE: { + const { children, type } = node.prelude; + const arr = []; + if (type === SELECTOR_LIST) { + let hasAmp = false; + for (const child of children) { + const selector = cssTree.generate(child); + if (this.isScoped && !hasAmp) { + hasAmp = /\x26/.test(selector); + } + arr.push(selector); + } + if (this.isScoped) { + if (hasAmp) { + this.selectors.push(arr); + /* FIXME: + } else { + this.selectors = arr; + this.isScoped = false; + */ + } + } else { + this.selectors.push(arr); + } + } + } + } + } + + /** + * Walker leave function. + * @param {object} node - The AST node. + */ + leave(node) { + if (node.type === ATRULE) { + if (node.name === 'scope') { + this.isScoped = false; + } + } + } +} + +/** + * Get type of an object. + * @param {object} o - Object to check. + * @returns {string} - Type of the object. + */ +export const getType = o => + Object.prototype.toString.call(o).slice(TYPE_FROM, TYPE_TO); + +/** + * Verify array contents. + * @param {Array} arr - The array. + * @param {string} type - Expected type, e.g. 'String'. + * @throws {TypeError} - Throws if array or its items are of unexpected type. + * @returns {Array} - The verified array. + */ +export const verifyArray = (arr, type) => { + if (!Array.isArray(arr)) { + throw new TypeError(`Unexpected type ${getType(arr)}`); + } + if (typeof type !== 'string') { + throw new TypeError(`Unexpected type ${getType(type)}`); + } + for (const item of arr) { + if (getType(item) !== type) { + throw new TypeError(`Unexpected type ${getType(item)}`); + } + } + return arr; +}; + +/** + * Generate a DOMException. + * @param {string} msg - The error message. + * @param {string} name - The error name. + * @param {object} globalObject - The global object (e.g., window). + * @returns {DOMException} The generated DOMException object. + */ +export const generateException = (msg, name, globalObject = globalThis) => { + return new globalObject.DOMException(msg, name); +}; + +/** + * Find a nested :has() pseudo-class. + * @param {object} leaf - The AST leaf to check. + * @returns {?object} The leaf if it's :has, otherwise null. + */ +export const findNestedHas = leaf => { + return leaf.name === 'has'; +}; + +/** + * Find a logical pseudo-class that contains a nested :has(). + * @param {object} leaf - The AST leaf to check. + * @returns {?object} The leaf if it matches, otherwise null. + */ +export const findLogicalWithNestedHas = leaf => { + if (KEYS_LOGICAL.has(leaf.name) && cssTree.find(leaf, findNestedHas)) { + return leaf; + } + return null; +}; + +/** + * Filter a list of nodes based on An+B logic + * @param {Array.} nodes - array of nodes to filter + * @param {object} anb - An+B options + * @param {number} anb.a - a + * @param {number} anb.b - b + * @param {boolean} [anb.reverse] - reverse order + * @returns {Array.} - array of matched nodes + */ +export const filterNodesByAnB = (nodes, anb) => { + const { a, b, reverse } = anb; + const processedNodes = reverse ? [...nodes].reverse() : nodes; + const l = nodes.length; + const matched = []; + if (a === 0) { + if (b > 0 && b <= l) { + matched.push(processedNodes[b - 1]); + } + return matched; + } + let startIndex = b - 1; + if (a > 0) { + while (startIndex < 0) { + startIndex += a; + } + for (let i = startIndex; i < l; i += a) { + matched.push(processedNodes[i]); + } + } else if (startIndex >= 0) { + for (let i = startIndex; i >= 0; i += a) { + matched.push(processedNodes[i]); + } + return matched.reverse(); + } + return matched; +}; + +/** + * Resolve content document, root node, and check if it's in a shadow DOM. + * @param {object} node - Document, DocumentFragment, or Element node. + * @returns {Array.} - [document, root, isInShadow]. + */ +export const resolveContent = node => { + if (!node?.nodeType) { + throw new TypeError(`Unexpected type ${getType(node)}`); + } + let document; + let root; + let shadow; + switch (node.nodeType) { + case DOCUMENT_NODE: { + document = node; + root = node; + break; + } + case DOCUMENT_FRAGMENT_NODE: { + const { host, mode, ownerDocument } = node; + document = ownerDocument; + root = node; + shadow = host && (mode === 'close' || mode === 'open'); + break; + } + case ELEMENT_NODE: { + document = node.ownerDocument; + let refNode = node; + while (refNode) { + const { host, mode, nodeType, parentNode } = refNode; + if (nodeType === DOCUMENT_FRAGMENT_NODE) { + shadow = host && (mode === 'close' || mode === 'open'); + break; + } else if (parentNode) { + refNode = parentNode; + } else { + break; + } + } + root = refNode; + break; + } + default: { + throw new TypeError(`Unexpected node ${node.nodeName}`); + } + } + return [document, root, !!shadow]; +}; + +/** + * Traverse node tree with a TreeWalker. + * @param {object} node - The target node. + * @param {object} walker - The TreeWalker instance. + * @param {boolean} [force] - Traverse only to the next node. + * @returns {?object} - The current node if found, otherwise null. + */ +export const traverseNode = (node, walker, force = false) => { + if (!node?.nodeType) { + throw new TypeError(`Unexpected type ${getType(node)}`); + } + if (!walker) { + return null; + } + let refNode = walker.currentNode; + if (refNode === node) { + return refNode; + } else if (force || refNode.contains(node)) { + refNode = walker.nextNode(); + while (refNode) { + if (refNode === node) { + break; + } + refNode = walker.nextNode(); + } + return refNode; + } else { + if (refNode !== walker.root) { + let bool; + while (refNode) { + if (refNode === node) { + bool = true; + break; + } else if (refNode === walker.root || refNode.contains(node)) { + break; + } + refNode = walker.parentNode(); + } + if (bool) { + return refNode; + } + } + if (node.nodeType === ELEMENT_NODE) { + let bool; + while (refNode) { + if (refNode === node) { + bool = true; + break; + } + refNode = walker.nextNode(); + } + if (bool) { + return refNode; + } + } + } + return null; +}; + +/** + * Check if a node is a custom element. + * @param {object} node - The Element node. + * @param {object} [opt] - Options. + * @returns {boolean} - True if it's a custom element. + */ +export const isCustomElement = (node, opt = {}) => { + if (!node?.nodeType) { + throw new TypeError(`Unexpected type ${getType(node)}`); + } + if (node.nodeType !== ELEMENT_NODE) { + return false; + } + const { localName, ownerDocument } = node; + const { formAssociated } = opt; + const window = ownerDocument.defaultView; + let elmConstructor; + const attr = node.getAttribute('is'); + if (attr) { + elmConstructor = + isCustomElementName(attr) && window.customElements.get(attr); + } else { + elmConstructor = + isCustomElementName(localName) && window.customElements.get(localName); + } + if (elmConstructor) { + if (formAssociated) { + return !!elmConstructor.formAssociated; + } + return true; + } + return false; +}; + +/** + * Get slotted text content. + * @param {object} node - The Element node (likely a ). + * @returns {?string} - The text content. + */ +export const getSlottedTextContent = node => { + if (!node?.nodeType) { + throw new TypeError(`Unexpected type ${getType(node)}`); + } + if (typeof node.assignedNodes !== 'function') { + return null; + } + const nodes = node.assignedNodes(); + if (nodes.length) { + let text = ''; + const l = nodes.length; + for (let i = 0; i < l; i++) { + const item = nodes[i]; + text = item.textContent.trim(); + if (text) { + break; + } + } + return text; + } + return node.textContent.trim(); +}; + +/** + * Get directionality of a node. + * @see https://html.spec.whatwg.org/multipage/dom.html#the-dir-attribute + * @param {object} node - The Element node. + * @returns {?string} - 'ltr' or 'rtl'. + */ +export const getDirectionality = node => { + if (!node?.nodeType) { + throw new TypeError(`Unexpected type ${getType(node)}`); + } + if (node.nodeType !== ELEMENT_NODE) { + return null; + } + const { dir: dirAttr, localName, parentNode } = node; + const { getEmbeddingLevels } = bidiFactory(); + if (dirAttr === 'ltr' || dirAttr === 'rtl') { + return dirAttr; + } else if (dirAttr === 'auto') { + let text = ''; + switch (localName) { + case 'input': { + if (!node.type || KEYS_DIR_AUTO.has(node.type)) { + text = node.value; + } else if (KEYS_DIR_LTR.has(node.type)) { + return 'ltr'; + } + break; + } + case 'slot': { + text = getSlottedTextContent(node); + break; + } + case 'textarea': { + text = node.value; + break; + } + default: { + const items = [].slice.call(node.childNodes); + for (const item of items) { + const { + dir: itemDir, + localName: itemLocalName, + nodeType: itemNodeType, + textContent: itemTextContent + } = item; + if (itemNodeType === TEXT_NODE) { + text = itemTextContent.trim(); + } else if ( + itemNodeType === ELEMENT_NODE && + !KEYS_NODE_DIR_EXCLUDE.has(itemLocalName) && + (!itemDir || (itemDir !== 'ltr' && itemDir !== 'rtl')) + ) { + if (itemLocalName === 'slot') { + text = getSlottedTextContent(item); + } else { + text = itemTextContent.trim(); + } + } + if (text) { + break; + } + } + } + } + if (text) { + const { + paragraphs: [{ level }] + } = getEmbeddingLevels(text); + if (level % 2 === 1) { + return 'rtl'; + } + } else if (parentNode) { + const { nodeType: parentNodeType } = parentNode; + if (parentNodeType === ELEMENT_NODE) { + return getDirectionality(parentNode); + } + } + } else if (localName === 'input' && node.type === 'tel') { + return 'ltr'; + } else if (localName === 'bdi') { + const text = node.textContent.trim(); + if (text) { + const { + paragraphs: [{ level }] + } = getEmbeddingLevels(text); + if (level % 2 === 1) { + return 'rtl'; + } + } + } else if (parentNode) { + if (localName === 'slot') { + const text = getSlottedTextContent(node); + if (text) { + const { + paragraphs: [{ level }] + } = getEmbeddingLevels(text); + if (level % 2 === 1) { + return 'rtl'; + } + return 'ltr'; + } + } + const { nodeType: parentNodeType } = parentNode; + if (parentNodeType === ELEMENT_NODE) { + return getDirectionality(parentNode); + } + } + return 'ltr'; +}; + +/** + * Traverses up the DOM tree to find the language attribute for a node. + * It checks for 'lang' in HTML and 'xml:lang' in XML contexts. + * @param {object} node - The starting element node. + * @returns {string|null} The language attribute value, or null if not found. + */ +export const getLanguageAttribute = node => { + if (!node?.nodeType) { + throw new TypeError(`Unexpected type ${getType(node)}`); + } + if (node.nodeType !== ELEMENT_NODE) { + return null; + } + const { contentType } = node.ownerDocument; + const isHtml = REG_IS_HTML.test(contentType); + const isXml = REG_IS_XML.test(contentType); + let isShadow = false; + // Traverse up from the current node to the root. + let current = node; + while (current) { + // Check if the current node is an element. + switch (current.nodeType) { + case ELEMENT_NODE: { + // Check for and return the language attribute if present. + if (isHtml && current.hasAttribute('lang')) { + return current.getAttribute('lang'); + } else if (isXml && current.hasAttribute('xml:lang')) { + return current.getAttribute('xml:lang'); + } + break; + } + case DOCUMENT_FRAGMENT_NODE: { + // Continue traversal if the current node is a shadow root. + if (current.host) { + isShadow = true; + } + break; + } + case DOCUMENT_NODE: + default: { + // Stop if we reach the root document node. + return null; + } + } + if (isShadow) { + current = current.host; + isShadow = false; + } else if (current.parentNode) { + current = current.parentNode; + } else { + break; + } + } + // No language attribute was found in the hierarchy. + return null; +}; + +/** + * Check if content is editable. + * NOTE: Not implemented in jsdom https://github.com/jsdom/jsdom/issues/1670 + * @param {object} node - The Element node. + * @returns {boolean} - True if content is editable. + */ +export const isContentEditable = node => { + if (!node?.nodeType) { + throw new TypeError(`Unexpected type ${getType(node)}`); + } + if (node.nodeType !== ELEMENT_NODE) { + return false; + } + if (typeof node.isContentEditable === 'boolean') { + return node.isContentEditable; + } else if (node.ownerDocument.designMode === 'on') { + return true; + } else { + let attr; + if (node.hasAttribute('contenteditable')) { + attr = node.getAttribute('contenteditable'); + } else { + attr = 'inherit'; + } + switch (attr) { + case '': + case 'true': { + return true; + } + case 'plaintext-only': { + // FIXME: + // @see https://github.com/w3c/editing/issues/470 + // @see https://github.com/whatwg/html/issues/10651 + return true; + } + case 'false': { + return false; + } + default: { + if (node?.parentNode?.nodeType === ELEMENT_NODE) { + return isContentEditable(node.parentNode); + } + return false; + } + } + } +}; + +/** + * Check if a node is visible. + * @param {object} node - The Element node. + * @returns {boolean} - True if the node is visible. + */ +export const isVisible = node => { + if (node?.nodeType !== ELEMENT_NODE) { + return false; + } + // TODO: switch to node.checkVisibility() + const window = node.ownerDocument.defaultView; + const { display, visibility } = window.getComputedStyle(node); + return display !== 'none' && visibility === 'visible'; +}; + +/** + * Check if focus is visible on the node. + * @param {object} node - The Element node. + * @returns {boolean} - True if focus is visible. + */ +export const isFocusVisible = node => { + if (node?.nodeType !== ELEMENT_NODE) { + return false; + } + const { localName, type } = node; + switch (localName) { + case 'input': { + if (!type || KEYS_INPUT_EDIT.has(type)) { + return true; + } + return false; + } + case 'textarea': { + return true; + } + default: { + return isContentEditable(node); + } + } +}; + +/** + * Check if an area is focusable. + * @param {object} node - The Element node. + * @returns {boolean} - True if the area is focusable. + */ +export const isFocusableArea = node => { + if (node?.nodeType !== ELEMENT_NODE) { + return false; + } + if (!node.isConnected) { + return false; + } + const window = node.ownerDocument.defaultView; + if (node instanceof window.HTMLElement) { + if (Number.isInteger(parseInt(node.getAttribute('tabindex')))) { + return true; + } + if (isContentEditable(node)) { + return true; + } + const { localName, parentNode } = node; + switch (localName) { + case 'a': { + if (node.href || node.hasAttribute('href')) { + return true; + } + return false; + } + case 'iframe': { + return true; + } + case 'input': { + if ( + node.disabled || + node.hasAttribute('disabled') || + node.hidden || + node.hasAttribute('hidden') + ) { + return false; + } + return true; + } + case 'summary': { + if (parentNode.localName === 'details') { + let child = parentNode.firstElementChild; + let bool = false; + while (child) { + if (child.localName === 'summary') { + bool = child === node; + break; + } + child = child.nextElementSibling; + } + return bool; + } + return false; + } + default: { + if ( + KEYS_NODE_FOCUSABLE.has(localName) && + !(node.disabled || node.hasAttribute('disabled')) + ) { + return true; + } + } + } + } else if (node instanceof window.SVGElement) { + if (Number.isInteger(parseInt(node.getAttributeNS(null, 'tabindex')))) { + const ns = 'http://www.w3.org/2000/svg'; + let bool; + let refNode = node; + while (refNode.namespaceURI === ns) { + bool = KEYS_NODE_FOCUSABLE_SVG.has(refNode.localName); + if (bool) { + break; + } + if (refNode?.parentNode?.namespaceURI === ns) { + refNode = refNode.parentNode; + } else { + break; + } + } + if (bool) { + return false; + } + return true; + } + if ( + node.localName === 'a' && + (node.href || node.hasAttributeNS(null, 'href')) + ) { + return true; + } + } + return false; +}; + +/** + * Check if a node is focusable. + * NOTE: Not applied, needs fix in jsdom itself. + * @see https://github.com/whatwg/html/pull/8392 + * @see https://phabricator.services.mozilla.com/D156219 + * @see https://github.com/jsdom/jsdom/issues/3029 + * @see https://github.com/jsdom/jsdom/issues/3464 + * @param {object} node - The Element node. + * @returns {boolean} - True if the node is focusable. + */ +export const isFocusable = node => { + if (node?.nodeType !== ELEMENT_NODE) { + return false; + } + const window = node.ownerDocument.defaultView; + let refNode = node; + let res = true; + while (refNode) { + if (refNode.disabled || refNode.hasAttribute('disabled')) { + res = false; + break; + } + if (refNode.hidden || refNode.hasAttribute('hidden')) { + res = false; + } + const { contentVisibility, display, visibility } = + window.getComputedStyle(refNode); + if ( + display === 'none' || + visibility !== 'visible' || + (contentVisibility === 'hidden' && refNode !== node) + ) { + res = false; + } else { + res = true; + } + if (res && refNode?.parentNode?.nodeType === ELEMENT_NODE) { + refNode = refNode.parentNode; + } else { + break; + } + } + return res; +}; + +/** + * Get namespace URI. + * @param {string} ns - The namespace prefix. + * @param {object} node - The Element node. + * @returns {?string} - The namespace URI. + */ +export const getNamespaceURI = (ns, node) => { + if (typeof ns !== 'string') { + throw new TypeError(`Unexpected type ${getType(ns)}`); + } else if (!node?.nodeType) { + throw new TypeError(`Unexpected type ${getType(node)}`); + } + if (!ns || node.nodeType !== ELEMENT_NODE) { + return null; + } + const { attributes } = node; + let res; + for (const attr of attributes) { + const { name, namespaceURI, prefix, value } = attr; + if (name === `xmlns:${ns}`) { + res = value; + } else if (prefix === ns) { + res = namespaceURI; + } + if (res) { + break; + } + } + return res ?? null; +}; + +/** + * Check if a namespace is declared. + * @param {string} ns - The namespace. + * @param {object} node - The Element node. + * @returns {boolean} - True if the namespace is declared. + */ +export const isNamespaceDeclared = (ns = '', node = {}) => { + if (!ns || typeof ns !== 'string' || node?.nodeType !== ELEMENT_NODE) { + return false; + } + if (node.lookupNamespaceURI(ns)) { + return true; + } + const root = node.ownerDocument.documentElement; + let parent = node; + let res; + while (parent) { + res = getNamespaceURI(ns, parent); + if (res || parent === root) { + break; + } + parent = parent.parentNode; + } + return !!res; +}; + +/** + * Check if nodeA precedes and/or contains nodeB. + * @param {object} nodeA - The first Element node. + * @param {object} nodeB - The second Element node. + * @returns {boolean} - True if nodeA precedes nodeB. + */ +export const isPreceding = (nodeA, nodeB) => { + if (!nodeA?.nodeType) { + throw new TypeError(`Unexpected type ${getType(nodeA)}`); + } else if (!nodeB?.nodeType) { + throw new TypeError(`Unexpected type ${getType(nodeB)}`); + } + if (nodeA.nodeType !== ELEMENT_NODE || nodeB.nodeType !== ELEMENT_NODE) { + return false; + } + const posBit = nodeB.compareDocumentPosition(nodeA); + const res = + posBit & DOCUMENT_POSITION_PRECEDING || posBit & DOCUMENT_POSITION_CONTAINS; + return !!res; +}; + +/** + * Comparison function for sorting nodes based on document position. + * @param {object} a - The first node. + * @param {object} b - The second node. + * @returns {number} - Sort order. + */ +export const compareNodes = (a, b) => { + if (isPreceding(b, a)) { + return 1; + } + return -1; +}; + +/** + * Sort a collection of nodes. + * @param {Array.|Set.} nodes - Collection of nodes. + * @returns {Array.} - Collection of sorted nodes. + */ +export const sortNodes = (nodes = []) => { + const arr = [...nodes]; + if (arr.length > 1) { + arr.sort(compareNodes); + } + return arr; +}; + +/** + * Concat an array of nested selectors into an equivalent single selector. + * @param {Array.>} selectors - [parents, children, ...]. + * @returns {string} - The concatenated selector. + */ +export const concatNestedSelectors = selectors => { + if (!Array.isArray(selectors)) { + throw new TypeError(`Unexpected type ${getType(selectors)}`); + } + let selector = ''; + if (selectors.length) { + const revSelectors = selectors.toReversed(); + let child = verifyArray(revSelectors.shift(), 'String'); + if (child.length === 1) { + [child] = child; + } + while (revSelectors.length) { + const parentArr = verifyArray(revSelectors.shift(), 'String'); + if (!parentArr.length) { + continue; + } + let parent; + if (parentArr.length === 1) { + [parent] = parentArr; + if (!/^[>~+]/.test(parent) && /[\s>~+]/.test(parent)) { + parent = `:is(${parent})`; + } + } else { + parent = `:is(${parentArr.join(', ')})`; + } + if (selector.includes('\x26')) { + selector = selector.replace(/\x26/g, parent); + } + if (Array.isArray(child)) { + const items = []; + for (let item of child) { + if (item.includes('\x26')) { + if (/^[>~+]/.test(item)) { + item = `${parent} ${item.replace(/\x26/g, parent)} ${selector}`; + } else { + item = `${item.replace(/\x26/g, parent)} ${selector}`; + } + } else { + item = `${parent} ${item} ${selector}`; + } + items.push(item.trim()); + } + selector = items.join(', '); + } else if (revSelectors.length) { + selector = `${child} ${selector}`; + } else { + if (child.includes('\x26')) { + if (/^[>~+]/.test(child)) { + selector = `${parent} ${child.replace(/\x26/g, parent)} ${selector}`; + } else { + selector = `${child.replace(/\x26/g, parent)} ${selector}`; + } + } else { + selector = `${parent} ${child} ${selector}`; + } + } + selector = selector.trim(); + if (revSelectors.length) { + child = parentArr.length > 1 ? parentArr : parent; + } else { + break; + } + } + selector = selector.replace(/\x26/g, ':scope').trim(); + } + return selector; +}; + +/** + * Extract nested selectors from CSSRule.cssText. + * @param {string} css - CSSRule.cssText. + * @returns {Array.>} - Array of nested selectors. + */ +export const extractNestedSelectors = css => { + const ast = cssTree.parse(css, { + context: 'rule' + }); + const extractor = new SelectorExtractor(); + cssTree.walk(ast, { + enter: extractor.enter.bind(extractor), + leave: extractor.leave.bind(extractor) + }); + return extractor.selectors; +}; + +/** + * Initialize nwsapi. + * @param {object} window - The Window object. + * @param {object} document - The Document object. + * @returns {object} - The nwsapi instance. + */ +export const initNwsapi = (window, document) => { + if (!window?.DOMException) { + throw new TypeError(`Unexpected global object ${getType(window)}`); + } + if (document?.nodeType !== DOCUMENT_NODE) { + document = window.document; + } + const nw = nwsapi({ + document, + DOMException: window.DOMException + }); + nw.configure({ + LOGERRORS: false + }); + return nw; +}; + +/** + * Filter a selector for use with nwsapi. + * @param {string} selector - The selector string. + * @param {string} target - The target type. + * @returns {boolean} - True if the selector is valid for nwsapi. + */ +export const filterSelector = (selector, target) => { + const isQuerySelectorAll = target === TARGET_ALL; + if ( + !selector || + typeof selector !== 'string' || + /null|undefined/.test(selector) + ) { + return false; + } + // Exclude missing close square bracket. + if (selector.includes('[')) { + const index = selector.lastIndexOf('['); + const sel = selector.substring(index); + if (sel.indexOf(']') < 0) { + return false; + } + } + // Match only simple attribute selector for TARGET_FIRST. + if (target === TARGET_FIRST) { + if (REG_ATTR_SIMPLE.test(selector)) { + return true; + } + return false; + } + + // Exclude simple tag selector for TARGET_ALL + if (target === TARGET_ALL && REG_TAG_SIMPLE.test(selector)) { + return false; + } + + // Exclude various complex or unsupported selectors. + // - selectors containing '/' + // - namespaced selectors + // - escaped selectors + // - pseudo-element selectors + // - selectors containing non-ASCII + // - selectors containing control character other than whitespace + // - attribute selectors with case flag, e.g. [attr i] + // - attribute selectors with unclosed quotes + // - empty :is() or :where() + if (selector.includes('/') || REG_EXCLUDE_BASIC.test(selector)) { + return false; + } + // Include pseudo-classes that are known to work correctly. + if (selector.includes(':')) { + if (isQuerySelectorAll && REG_DESCEND.test(selector)) { + return false; + } + const complex = isQuerySelectorAll ? false : REG_COMPLEX.test(selector); + if (!isQuerySelectorAll && /:has\(/.test(selector)) { + if (!complex || REG_LOGIC_HAS_COMPOUND.test(selector)) { + return false; + } + return REG_END_WITH_HAS.test(selector); + } else if (/:(?:is|not)\(/.test(selector)) { + if (complex) { + return !REG_LOGIC_COMPLEX.test(selector); + } else { + return !REG_LOGIC_COMPOUND.test(selector); + } + } else { + return !REG_WO_LOGICAL.test(selector); + } + } + return true; +}; diff --git a/node_modules/@asamuzakjp/dom-selector/types/index.d.ts b/node_modules/@asamuzakjp/dom-selector/types/index.d.ts new file mode 100644 index 00000000..61db0eca --- /dev/null +++ b/node_modules/@asamuzakjp/dom-selector/types/index.d.ts @@ -0,0 +1,15 @@ +export class DOMSelector { + constructor(window: Window, document: Document, opt?: object); + clear: () => void; + check: (selector: string, node: Element, opt?: object) => CheckResult; + matches: (selector: string, node: Element, opt?: object) => boolean; + closest: (selector: string, node: Element, opt?: object) => Element | null; + querySelector: (selector: string, node: Document | DocumentFragment | Element, opt?: object) => Element | null; + querySelectorAll: (selector: string, node: Document | DocumentFragment | Element, opt?: object) => Array; + #private; +} +export type CheckResult = { + match: boolean; + pseudoElement: string | null; + ast: object | null; +}; diff --git a/node_modules/@asamuzakjp/dom-selector/types/js/constant.d.ts b/node_modules/@asamuzakjp/dom-selector/types/js/constant.d.ts new file mode 100644 index 00000000..f999a789 --- /dev/null +++ b/node_modules/@asamuzakjp/dom-selector/types/js/constant.d.ts @@ -0,0 +1,77 @@ +export const ATRULE: "Atrule"; +export const ATTR_SELECTOR: "AttributeSelector"; +export const CLASS_SELECTOR: "ClassSelector"; +export const COMBINATOR: "Combinator"; +export const IDENT: "Identifier"; +export const ID_SELECTOR: "IdSelector"; +export const NOT_SUPPORTED_ERR: "NotSupportedError"; +export const NTH: "Nth"; +export const OPERATOR: "Operator"; +export const PS_CLASS_SELECTOR: "PseudoClassSelector"; +export const PS_ELEMENT_SELECTOR: "PseudoElementSelector"; +export const RULE: "Rule"; +export const SCOPE: "Scope"; +export const SELECTOR: "Selector"; +export const SELECTOR_LIST: "SelectorList"; +export const STRING: "String"; +export const SYNTAX_ERR: "SyntaxError"; +export const TARGET_ALL: "all"; +export const TARGET_FIRST: "first"; +export const TARGET_LINEAL: "lineal"; +export const TARGET_SELF: "self"; +export const TYPE_SELECTOR: "TypeSelector"; +export const BIT_01: 1; +export const BIT_02: 2; +export const BIT_04: 4; +export const BIT_08: 8; +export const BIT_16: 16; +export const BIT_32: 32; +export const BIT_FFFF: 65535; +export const DUO: 2; +export const HEX: 16; +export const TYPE_FROM: 8; +export const TYPE_TO: -1; +export const ELEMENT_NODE: 1; +export const TEXT_NODE: 3; +export const DOCUMENT_NODE: 9; +export const DOCUMENT_FRAGMENT_NODE: 11; +export const DOCUMENT_POSITION_PRECEDING: 2; +export const DOCUMENT_POSITION_CONTAINS: 8; +export const DOCUMENT_POSITION_CONTAINED_BY: 16; +export const SHOW_ALL: 4294967295; +export const SHOW_CONTAINER: 1281; +export const SHOW_DOCUMENT: 256; +export const SHOW_DOCUMENT_FRAGMENT: 1024; +export const SHOW_ELEMENT: 1; +export const ALPHA_NUM: "[A-Z\\d]+"; +export const CHILD_IDX: "(?:first|last|only)-(?:child|of-type)"; +export const DIGIT: "(?:0|[1-9]\\d*)"; +export const LANG_PART: "(?:-[A-Z\\d]+)*"; +export const PSEUDO_CLASS: "(?:any-)?link|(?:first|last|only)-(?:child|of-type)|checked|empty|indeterminate|read-(?:only|write)|target"; +export const ANB: "[+-]?(?:(?:0|[1-9]\\d*)n?|n)|(?:[+-]?(?:0|[1-9]\\d*))?n\\s*[+-]\\s*(?:0|[1-9]\\d*)"; +export const COMBO: "\\s?[\\s>~+]\\s?"; +export const DESCEND: "\\s?[\\s>]\\s?"; +export const SIBLING: "\\s?[+~]\\s?"; +export const LOGIC_IS: ":is\\(\\s*[^)]+\\s*\\)"; +export const N_TH: "nth-(?:last-)?(?:child|of-type)\\(\\s*(?:even|odd|[+-]?(?:(?:0|[1-9]\\d*)n?|n)|(?:[+-]?(?:0|[1-9]\\d*))?n\\s*[+-]\\s*(?:0|[1-9]\\d*))\\s*\\)"; +export const SUB_TYPE: "\\[[^|\\]]+\\]|[#.:][\\w-]+"; +export const SUB_TYPE_WO_PSEUDO: "\\[[^|\\]]+\\]|[#.][\\w-]+"; +export const TAG_TYPE: "\\*|[A-Za-z][\\w-]*"; +export const TAG_TYPE_I: "\\*|[A-Z][\\w-]*"; +export const COMPOUND: "(?:\\*|[A-Za-z][\\w-]*|(?:\\*|[A-Za-z][\\w-]*)?(?:\\[[^|\\]]+\\]|[#.:][\\w-]+)+)"; +export const COMPOUND_L: "(?:\\*|[A-Za-z][\\w-]*|(?:\\*|[A-Za-z][\\w-]*)?(?:\\[[^|\\]]+\\]|[#.:][\\w-]+|:is\\(\\s*[^)]+\\s*\\))+)"; +export const COMPOUND_I: "(?:\\*|[A-Z][\\w-]*|(?:\\*|[A-Z][\\w-]*)?(?:\\[[^|\\]]+\\]|[#.:][\\w-]+)+)"; +export const COMPOUND_WO_PSEUDO: "(?:\\*|[A-Za-z][\\w-]*|(?:\\*|[A-Za-z][\\w-]*)?(?:\\[[^|\\]]+\\]|[#.][\\w-]+)+)"; +export const COMPLEX: "(?:\\*|[A-Za-z][\\w-]*|(?:\\*|[A-Za-z][\\w-]*)?(?:\\[[^|\\]]+\\]|[#.:][\\w-]+)+)(?:\\s?[\\s>~+]\\s?(?:\\*|[A-Za-z][\\w-]*|(?:\\*|[A-Za-z][\\w-]*)?(?:\\[[^|\\]]+\\]|[#.:][\\w-]+)+))*"; +export const COMPLEX_L: "(?:\\*|[A-Za-z][\\w-]*|(?:\\*|[A-Za-z][\\w-]*)?(?:\\[[^|\\]]+\\]|[#.:][\\w-]+|:is\\(\\s*[^)]+\\s*\\))+)(?:\\s?[\\s>~+]\\s?(?:\\*|[A-Za-z][\\w-]*|(?:\\*|[A-Za-z][\\w-]*)?(?:\\[[^|\\]]+\\]|[#.:][\\w-]+|:is\\(\\s*[^)]+\\s*\\))+))*"; +export const HAS_COMPOUND: "has\\([\\s>]?\\s*(?:\\*|[A-Za-z][\\w-]*|(?:\\*|[A-Za-z][\\w-]*)?(?:\\[[^|\\]]+\\]|[#.][\\w-]+)+)\\s*\\)"; +export const LOGIC_COMPOUND: "(?:is|not)\\(\\s*(?:\\*|[A-Za-z][\\w-]*|(?:\\*|[A-Za-z][\\w-]*)?(?:\\[[^|\\]]+\\]|[#.:][\\w-]+|:is\\(\\s*[^)]+\\s*\\))+)(?:\\s*,\\s*(?:\\*|[A-Za-z][\\w-]*|(?:\\*|[A-Za-z][\\w-]*)?(?:\\[[^|\\]]+\\]|[#.:][\\w-]+|:is\\(\\s*[^)]+\\s*\\))+))*\\s*\\)"; +export const LOGIC_COMPLEX: "(?:is|not)\\(\\s*(?:\\*|[A-Za-z][\\w-]*|(?:\\*|[A-Za-z][\\w-]*)?(?:\\[[^|\\]]+\\]|[#.:][\\w-]+|:is\\(\\s*[^)]+\\s*\\))+)(?:\\s?[\\s>~+]\\s?(?:\\*|[A-Za-z][\\w-]*|(?:\\*|[A-Za-z][\\w-]*)?(?:\\[[^|\\]]+\\]|[#.:][\\w-]+|:is\\(\\s*[^)]+\\s*\\))+))*(?:\\s*,\\s*(?:\\*|[A-Za-z][\\w-]*|(?:\\*|[A-Za-z][\\w-]*)?(?:\\[[^|\\]]+\\]|[#.:][\\w-]+|:is\\(\\s*[^)]+\\s*\\))+)(?:\\s?[\\s>~+]\\s?(?:\\*|[A-Za-z][\\w-]*|(?:\\*|[A-Za-z][\\w-]*)?(?:\\[[^|\\]]+\\]|[#.:][\\w-]+|:is\\(\\s*[^)]+\\s*\\))+))*)*\\s*\\)"; +export const FORM_PARTS: readonly string[]; +export const INPUT_BUTTON: readonly string[]; +export const INPUT_CHECK: readonly string[]; +export const INPUT_DATE: readonly string[]; +export const INPUT_TEXT: readonly string[]; +export const INPUT_EDIT: readonly string[]; +export const INPUT_LTR: readonly string[]; +export const KEYS_LOGICAL: Set; diff --git a/node_modules/@asamuzakjp/dom-selector/types/js/finder.d.ts b/node_modules/@asamuzakjp/dom-selector/types/js/finder.d.ts new file mode 100644 index 00000000..9667b7bc --- /dev/null +++ b/node_modules/@asamuzakjp/dom-selector/types/js/finder.d.ts @@ -0,0 +1,61 @@ +export class Finder { + constructor(window: object); + onError: (e: Error, opt?: { + noexcept?: boolean; + }) => void; + setup: (selector: string, node: object, opt?: { + check?: boolean; + noexcept?: boolean; + warn?: boolean; + }) => object; + clearResults: (all?: boolean) => void; + private _handleFocusEvent; + private _handleKeyboardEvent; + private _handleMouseEvent; + private _registerEventListeners; + private _processSelectorBranches; + private _correspond; + private _createTreeWalker; + private _getSelectorBranches; + private _getFilteredChildren; + private _collectNthChild; + private _collectNthOfType; + private _matchAnPlusB; + private _matchHasPseudoFunc; + private _evaluateHasPseudo; + private _matchLogicalPseudoFunc; + private _matchPseudoClassSelector; + private _evaluateHostPseudo; + private _evaluateHostContextPseudo; + private _matchShadowHostPseudoClass; + private _matchSelectorForElement; + private _matchSelectorForShadowRoot; + private _matchSelector; + private _matchLeaves; + private _traverseAllDescendants; + private _findDescendantNodes; + private _collectCombinatorMatches; + private _matchCombinator; + private _traverseAndCollectNodes; + private _findPrecede; + private _findNodeWalker; + private _matchSelf; + private _findLineal; + private _findEntryNodesForPseudoElement; + private _findEntryNodesForId; + private _findEntryNodesForClass; + private _findEntryNodesForType; + private _findEntryNodesForOther; + private _findEntryNodes; + private _determineTraversalStrategy; + private _processPendingItems; + private _collectNodes; + private _getCombinedNodes; + private _matchNodeNext; + private _matchNodePrev; + private _processComplexBranchAll; + private _processComplexBranchFirst; + find: (targetType: string) => Set; + getAST: (selector: string) => object; + #private; +} diff --git a/node_modules/@asamuzakjp/dom-selector/types/js/matcher.d.ts b/node_modules/@asamuzakjp/dom-selector/types/js/matcher.d.ts new file mode 100644 index 00000000..e1966b05 --- /dev/null +++ b/node_modules/@asamuzakjp/dom-selector/types/js/matcher.d.ts @@ -0,0 +1,16 @@ +export function matchPseudoElementSelector(astName: string, astType: string, opt?: { + forgive?: boolean; + warn?: boolean; +}): void; +export function matchDirectionPseudoClass(ast: object, node: object): boolean; +export function matchLanguagePseudoClass(ast: object, node: object): boolean; +export function matchDisabledPseudoClass(astName: string, node: object): boolean; +export function matchReadOnlyPseudoClass(astName: string, node: object): boolean; +export function matchAttributeSelector(ast: object, node: object, opt?: { + check?: boolean; + forgive?: boolean; +}): boolean; +export function matchTypeSelector(ast: object, node: object, opt?: { + check?: boolean; + forgive?: boolean; +}): boolean; diff --git a/node_modules/@asamuzakjp/dom-selector/types/js/parser.d.ts b/node_modules/@asamuzakjp/dom-selector/types/js/parser.d.ts new file mode 100644 index 00000000..20b07824 --- /dev/null +++ b/node_modules/@asamuzakjp/dom-selector/types/js/parser.d.ts @@ -0,0 +1,14 @@ +export function unescapeSelector(selector?: string): string; +export function preprocess(value: string): string; +export function parseSelector(sel: string): object; +export function walkAST(ast?: object, toObject?: boolean): { + branches: Array; + info: object; +}; +export function compareASTNodes(a: object, b: object): number; +export function sortAST(asts: Array): Array; +export function parseAstName(selector: string): { + prefix: string; + localName: string; +}; +export { find as findAST, generate as generateCSS } from "css-tree"; diff --git a/node_modules/@asamuzakjp/dom-selector/types/js/utility.d.ts b/node_modules/@asamuzakjp/dom-selector/types/js/utility.d.ts new file mode 100644 index 00000000..fe627593 --- /dev/null +++ b/node_modules/@asamuzakjp/dom-selector/types/js/utility.d.ts @@ -0,0 +1,30 @@ +export function getType(o: object): string; +export function verifyArray(arr: any[], type: string): any[]; +export function generateException(msg: string, name: string, globalObject?: object): DOMException; +export function findNestedHas(leaf: object): object | null; +export function findLogicalWithNestedHas(leaf: object): object | null; +export function filterNodesByAnB(nodes: Array, anb: { + a: number; + b: number; + reverse?: boolean; +}): Array; +export function resolveContent(node: object): Array; +export function traverseNode(node: object, walker: object, force?: boolean): object | null; +export function isCustomElement(node: object, opt?: object): boolean; +export function getSlottedTextContent(node: object): string | null; +export function getDirectionality(node: object): string | null; +export function getLanguageAttribute(node: object): string | null; +export function isContentEditable(node: object): boolean; +export function isVisible(node: object): boolean; +export function isFocusVisible(node: object): boolean; +export function isFocusableArea(node: object): boolean; +export function isFocusable(node: object): boolean; +export function getNamespaceURI(ns: string, node: object): string | null; +export function isNamespaceDeclared(ns?: string, node?: object): boolean; +export function isPreceding(nodeA: object, nodeB: object): boolean; +export function compareNodes(a: object, b: object): number; +export function sortNodes(nodes?: Array | Set): Array; +export function concatNestedSelectors(selectors: Array>): string; +export function extractNestedSelectors(css: string): Array>; +export function initNwsapi(window: object, document: object): object; +export function filterSelector(selector: string, target: string): boolean; diff --git a/node_modules/@asamuzakjp/nwsapi/LICENSE b/node_modules/@asamuzakjp/nwsapi/LICENSE new file mode 100644 index 00000000..cc3621a8 --- /dev/null +++ b/node_modules/@asamuzakjp/nwsapi/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2007-2019 Diego Perini (http://www.iport.it/) + +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. diff --git a/node_modules/@asamuzakjp/nwsapi/README.md b/node_modules/@asamuzakjp/nwsapi/README.md new file mode 100644 index 00000000..f74b87d8 --- /dev/null +++ b/node_modules/@asamuzakjp/nwsapi/README.md @@ -0,0 +1,132 @@ +# [NWSAPI](http://dperini.github.io/nwsapi/) + +Fast CSS Selectors API Engine + +![](https://img.shields.io/npm/v/nwsapi.svg?colorB=orange&style=flat) ![](https://img.shields.io/github/tag/dperini/nwsapi.svg?style=flat) ![](https://img.shields.io/npm/dw/nwsapi.svg?style=flat) ![](https://img.shields.io/github/issues/dperini/nwsapi.svg?style=flat) + +NWSAPI is the development progress of [NWMATCHER](https://github.com/dperini/nwmatcher) aiming at [Selectors Level 4](https://www.w3.org/TR/selectors-4/) conformance. It has been completely reworked to be easily extended and maintained. It is a right-to-left selector parser and compiler written in pure Javascript with no external dependencies. It was initially thought as a cross browser library to improve event delegation and web page scraping in various frameworks but it has become a popular replacement of the native CSS selection and matching functionality in newer browsers and headless environments. + +It uses [regular expressions](https://en.wikipedia.org/wiki/Regular_expression) to parse CSS selector strings and [metaprogramming](https://en.wikipedia.org/wiki/Metaprogramming) to transforms these selector strings into Javascript function resolvers. This process is executed only once for each selector string allowing memoization of the function resolvers and achieving unmatched performances. + +## Installation + +To include NWSAPI in a standard web page: + +```html + +``` + +To include NWSAPI in a standard web page and automatically replace the native QSA: + +```html + +``` + +To use NWSAPI with Node.js: + +``` +$ npm install nwsapi +``` + +NWSAPI currently supports browsers (as a global, `NW.Dom`) and headless environments (as a CommonJS module). + + +## Supported Selectors + +Here is a list of all the CSS2/CSS3/CSS4 [Supported selectors](https://github.com/dperini/nwsapi/wiki/CSS-supported-selectors). + + +## Features and Compliance + +You can read more about NWSAPI [features and compliance](https://github.com/dperini/nwsapi/wiki/Features-and-compliance) on the wiki. + + +## API + +### DOM Selection + +#### `ancestor( selector, context, callback )` + +Returns a reference to the nearest ancestor element matching `selector`, starting at `context`. Returns `null` if no element is found. If `callback` is provided, it is invoked for the matched element. + +#### `first( selector, context, callback )` + +Returns a reference to the first element matching `selector`, starting at `context`. Returns `null` if no element matches. If `callback` is provided, it is invoked for the matched element. + +#### `match( selector, element, callback )` + +Returns `true` if `element` matches `selector`, starting at `context`; returns `false` otherwise. If `callback` is provided, it is invoked for the matched element. + +#### `select( selector, context, callback )` + +Returns an array of all the elements matching `selector`, starting at `context`; returns empty `Array` otherwise. If `callback` is provided, it is invoked for each matching element. + + +### DOM Helpers + +#### `byId( id, from )` + +Returns a reference to the first element with ID `id`, optionally filtered to descendants of the element `from`. + +#### `byTag( tag, from )` + +Returns an array of elements having the specified tag name `tag`, optionally filtered to descendants of the element `from`. + +#### `byClass( class, from )` + +Returns an array of elements having the specified class name `class`, optionally filtered to descendants of the element `from`. + + +### Engine Configuration + +#### `configure( options )` + +The following is the list of currently available configuration options, their default values and descriptions, they are boolean flags that can be set to `true` or `false`: + +* `IDS_DUPES`: true - true to allow using multiple elements having the same id, false to disallow +* `LIVECACHE`: true - true for caching both results and resolvers, false for caching only resolvers +* `MIXEDCASE`: true - true to match tag names case insensitive, false to match using case sensitive +* `LOGERRORS`: true - true to print errors and warnings to the console, false to mute both of them + + +### Examples on extending the basic functionalities + +#### `configure( { : [ true | false ] } )` + +Disable logging errors/warnings to console, disallow duplicate ids. Example: + +```js +NW.Dom.configure( { LOGERRORS: false, IDS_DUPES: false } ); +``` +NOTE: NW.Dom.configure() without parameters return the current configuration. + +#### `registerCombinator( symbol, resolver )` + +Registers a new symbol and its matching resolver in the combinators table. Example: + +```js +NW.Dom.registerCombinator( '^', 'e.parentElement' ); +``` + +#### `registerOperator( symbol, resolver )` + +Registers a new symbol and its matching resolver in the attribute operators table. Example: + +```js +NW.Dom.registerOperator( '!=', { p1: '^', p2: '$', p3: 'false' } ); +``` + +#### `registerSelector( name, rexp, func )` + +Registers a new selector, the matching RE and the resolver function, in the selectors table. Example: + +```js +NW.Dom.registerSelector('Controls', /^\:(control)(.*)/i, + (function(global) { + return function(match, source, mode, callback) { + var status = true; + source = 'if(/^(button|input|select|textarea)/i.test(e.nodeName)){' + source + '}'; + return { 'source': source, 'status': status }; + }; + })(this)); +``` diff --git a/node_modules/@asamuzakjp/nwsapi/package.json b/node_modules/@asamuzakjp/nwsapi/package.json new file mode 100644 index 00000000..6a44b9c7 --- /dev/null +++ b/node_modules/@asamuzakjp/nwsapi/package.json @@ -0,0 +1,43 @@ +{ + "name": "@asamuzakjp/nwsapi", + "version": "2.3.9", + "description": "Fast CSS Selectors API Engine", + "homepage": "http://javascript.nwbox.com/nwsapi/", + "main": "./src/nwsapi", + "keywords": [ + "css", + "css3", + "css4", + "matcher", + "selector" + ], + "licenses": [ + { + "type": "MIT", + "url": "http://javascript.nwbox.com/nwsapi/MIT-LICENSE" + } + ], + "license": "MIT", + "author": { + "name": "Diego Perini", + "email": "diego.perini@gmail.com", + "web": "http://www.iport.it/" + }, + "maintainers": [ + { + "name": "Diego Perini", + "email": "diego.perini@gmail.com", + "web": "http://www.iport.it/" + } + ], + "bugs": { + "url": "http://github.com/dperini/nwsapi/issues" + }, + "repository": { + "type": "git", + "url": "git://github.com/dperini/nwsapi.git" + }, + "scripts": { + "lint": "eslint ./src/nwsapi.js" + } +} diff --git a/node_modules/@asamuzakjp/nwsapi/src/nwsapi.js b/node_modules/@asamuzakjp/nwsapi/src/nwsapi.js new file mode 100644 index 00000000..e118fd5e --- /dev/null +++ b/node_modules/@asamuzakjp/nwsapi/src/nwsapi.js @@ -0,0 +1,1855 @@ +/** + * Forked and modified from nwsapi@2.2.2 + * - Export to cjs only + * - Remove ./modules directory + * - Remove unused exported properties + * - Remove unused pseudo-classes + * - Remove Snapshot.root and resolve document.documentElement on runtime + * - Use `let` and `const` as much as possible + * - Use `===` and `!==` + * - Fix `:nth-of-type()` + * - Fix function source for :root, :target and :indeterminate pseudo-classes + * - Fix + * - Support complex selectors within `:is()` and `:not()` + * - Add ::slotted() and ::part() to pseudo-elements list + * - Add isContentEditable() function + * - Add createMatchingParensRegex() function from upstream + * - Invalidate cache for :has() pseudo class + * - Optimize some regular expressions + */ +/* + * Copyright (C) 2007-2019 Diego Perini + * All rights reserved. + * + * nwsapi.js - Fast CSS Selectors API Engine + * + * Author: Diego Perini + * Version: 2.2.0 + * Created: 20070722 + * Release: 20220901 + * + * License: + * http://javascript.nwbox.com/nwsapi/MIT-LICENSE + * Download: + * http://javascript.nwbox.com/nwsapi/nwsapi.js + */ + +(function Export(global, factory) { + 'use strict'; + module.exports = factory; +})(this, function Factory(global, Export) { + const version = 'nwsapi-2.2.2'; + + let doc = global.document; + + /** + * Generate a regex that matches a balanced set of parentheses. + * Outermost parentheses are excluded so any amount of children can be handled. + * See https://stackoverflow.com/a/35271017 for reference + * + * @param {number} depth + * @return {string} + */ + function createMatchingParensRegex(depth = 1) { + const out = '\\([^)(]*?(?:'.repeat(depth) + '\\([^)(]*?\\)' + '[^)(]*?)*?\\)'.repeat(depth); + // remove outermost escaped parens + return out.slice(2, out.length - 2); + } + + const CFG = { + // extensions + operators: '[~*^$|]=|=', + combinators: '[\\s>+~](?=[^>+~])' + }; + + const NOT = { + // not enclosed in double/single/parens/square + doubleEnc: '(?=(?:[^"]*"[^"]*")*[^"]*$)', + singleEnc: "(?=(?:[^']*'[^']*')*[^']*$)", + parensEnc: '(?![^\\x28]*\\x29)', + squareEnc: '(?![^\\x5b]*\\x5d)' + }; + + const REX = { + // regular expressions + hasEscapes: /\\/, + hexNumbers: /^[0-9a-f]/i, + escOrQuote: /^\\|[\x22\x27]/, + regExpChar: /(?:(?!\\)[\\^$.*+?()[\]{}|/])/g, + trimSpaces: /[\r\n\f]|^\s+|\s+$/g, + commaGroup: RegExp('(\\s{0,255},\\s{0,255})' + NOT.squareEnc + NOT.parensEnc, 'g'), + splitGroup: /((?:\x28[^\x29]{0,255}\x29|\[[^\]]{0,255}\]|\\.|[^,])+)/g, + fixEscapes: /\\([0-9a-f]{1,6}\s?|.)|([\x22\x27])/gi, + combineWSP: RegExp('\\s{1,255}' + NOT.singleEnc + NOT.doubleEnc, 'g'), + tabCharWSP: RegExp('(\\s?\\t{1,255}\\s?)' + NOT.singleEnc + NOT.doubleEnc, 'g'), + pseudosWSP: RegExp('\\s{1,255}([-+])\\s{1,255}' + NOT.squareEnc, 'g') + }; + + const STD = { + combinator: /\s?([>+~])\s?/g, + apimethods: /^(?:[a-z]+|\*)\|/i, + namespaces: /(\*|[a-z]+)\|[-a-z]+/i + }; + + const GROUPS = { + // pseudo-classes requiring parameters + logicalsel: '(is|where|matches|not|has)(?:\\x28\\s?(' + createMatchingParensRegex(3) + ')\\s?\\x29)', + treestruct: '(nth(?:-last)?(?:-child|-of-type))(?:\\x28\\s?(even|odd|(?:[-+]?\\d*)(?:n\\s?[-+]?\\s?\\d*)?)\\s?(?:\\x29|$))', + // pseudo-classes not requiring parameters + locationpc: '(any-link|link|visited|target)\\b', + structural: '(root|empty|(?:(?:first|last|only)(?:-child|-of-type)))\\b', + inputstate: '(enabled|disabled|read-(?:only|write)|placeholder-shown|default)\\b', + inputvalue: '(checked|indeterminate)\\b', + // pseudo-classes for parsing only selectors + pseudoNop: '(autofill|-webkit-autofill)\\b', + // pseudo-elements starting with single colon (:) + pseudoSng: '(after|before|first-letter|first-line)\\b', + // pseudo-elements starting with double colon (::) + pseudoDbl: ':(after|before|first-letter|first-line|selection|part|placeholder|slotted|-webkit-[-a-z0-9]{2,})\\b' + }; + + const Patterns = { + // pseudo-classes + treestruct: RegExp('^:(?:' + GROUPS.treestruct + ')(.*)', 'i'), + structural: RegExp('^:(?:' + GROUPS.structural + ')(.*)', 'i'), + inputstate: RegExp('^:(?:' + GROUPS.inputstate + ')(.*)', 'i'), + inputvalue: RegExp('^:(?:' + GROUPS.inputvalue + ')(.*)', 'i'), + locationpc: RegExp('^:(?:' + GROUPS.locationpc + ')(.*)', 'i'), + logicalsel: RegExp('^:(?:' + GROUPS.logicalsel + ')(.*)', 'i'), + pseudoNop: RegExp('^:(?:' + GROUPS.pseudoNop + ')(.*)', 'i'), + pseudoSng: RegExp('^:(?:' + GROUPS.pseudoSng + ')(.*)', 'i'), + pseudoDbl: RegExp('^:(?:' + GROUPS.pseudoDbl + ')(.*)', 'i'), + // combinator symbols + children: /^\s?>\s?(.*)/, + adjacent: /^\s?\+\s?(.*)/, + relative: /^\s?~\s?(.*)/, + ancestor: /^\s+(.*)/, + // universal & namespace + universal: /^\*(.*)/, + namespace: /^(\w+|\*)?\|(.*)/ + }; + + // emulate firefox error strings + const qsNotArgs = 'Not enough arguments'; + const qsInvalid = ' is not a valid selector'; + + // detect structural pseudo-classes in selectors + const reNthElem = /(:nth(?:-last)?-child)/i; + const reNthType = /(:nth(?:-last)?-of-type)/i; + + // placeholder for global regexp + let reOptimizer; + let reValidator; + + // special handling configuration flags + const Config = { + IDS_DUPES: true, + MIXEDCASE: true, + LOGERRORS: true, + VERBOSITY: true + }; + + let NAMESPACE; + let QUIRKS_MODE; + let HTML_DOCUMENT; + + const ATTR_STD_OPS = { + '=': 1, + '^=': 1, + '$=': 1, + '|=': 1, + '*=': 1, + '~=': 1 + }; + + const HTML_TABLE = { + accept: 1, + 'accept-charset': 1, + align: 1, + alink: 1, + axis: 1, + bgcolor: 1, + charset: 1, + checked: 1, + clear: 1, + codetype: 1, + color: 1, + compact: 1, + declare: 1, + defer: 1, + dir: 1, + direction: 1, + disabled: 1, + enctype: 1, + face: 1, + frame: 1, + hreflang: 1, + 'http-equiv': 1, + lang: 1, + language: 1, + link: 1, + media: 1, + method: 1, + multiple: 1, + nohref: 1, + noresize: 1, + noshade: 1, + nowrap: 1, + readonly: 1, + rel: 1, + rev: 1, + rules: 1, + scope: 1, + scrolling: 1, + selected: 1, + shape: 1, + target: 1, + text: 1, + type: 1, + valign: 1, + valuetype: 1, + vlink: 1 + }; + + const Combinators = {}; + + const Selectors = {}; + + const Operators = { + '=': { + p1: '^', + p2: '$', + p3: 'true' + }, + '^=': { + p1: '^', + p2: '', + p3: 'true' + }, + '$=': { + p1: '', + p2: '$', + p3: 'true' + }, + '*=': { + p1: '', + p2: '', + p3: 'true' + }, + '|=': { + p1: '^', + p2: '(-|$)', + p3: 'true' + }, + '~=': { + p1: '(^|\\s)', + p2: '(\\s|$)', + p3: 'true' + } + }; + + const concatCall = function (nodes, callback) { + let i = 0; + const l = nodes.length; + const list = Array(l); + while (l > i) { + if (callback(list[i] = nodes[i]) === false) { + break; + } + ++i; + } + return list; + }; + + const concatList = function (list, nodes) { + let i = -1; + let l = nodes.length; + while (l--) { + list[list.length] = nodes[++i]; + } + return list; + }; + + let hasDupes = false; + + const documentOrder = function (a, b) { + if (!hasDupes && a === b) { + hasDupes = true; + return 0; + } + return a.compareDocumentPosition(b) & 4 ? -1 : 1; + }; + + const unique = function (nodes) { + let i = 0; + let j = -1; + let l = nodes.length + 1; + const list = []; + while (--l) { + if (nodes[i++] === nodes[i]) { + continue; + } + list[++j] = nodes[i - 1]; + } + hasDupes = false; + return list; + }; + + // check context for mixed content + const hasMixedCaseTagNames = function (context) { + const api = 'getElementsByTagNameNS'; + + // current host context (ownerDocument) + context = context.ownerDocument || context; + + // documentElement (root) element namespace or default html/xhtml namespace + const ns = context.documentElement && context.documentElement.namespaceURI + ? context.documentElement.namespaceURI + : 'http://www.w3.org/1999/xhtml'; + + // checking the number of non HTML nodes in the document + return (context[api]('*', '*').length - context[api](ns, '*').length) > 0; + }; + + // check if the document type is HTML + const isHTML = function (node) { + const doc = node.ownerDocument || node; + return doc.nodeType === 9 && doc.contentType === 'text/html'; + }; + + // convert single codepoint to UTF-16 encoding + const codePointToUTF16 = function (codePoint) { + // out of range, use replacement character + if (codePoint < 1 || codePoint > 0x10ffff || + (codePoint > 0xd7ff && codePoint < 0xe000)) { + return '\\ufffd'; + } + // javascript strings are UTF-16 encoded + if (codePoint < 0x10000) { + const lowHex = '000' + codePoint.toString(16); + return '\\u' + lowHex.substr(lowHex.length - 4); + } + // supplementary high + low surrogates + return '\\u' + (((codePoint - 0x10000) >> 0x0a) + 0xd800).toString(16) + + '\\u' + (((codePoint - 0x10000) % 0x400) + 0xdc00).toString(16); + }; + + // convert single codepoint to string + const stringFromCodePoint = function (codePoint) { + // out of range, use replacement character + if (codePoint < 1 || codePoint > 0x10ffff || + (codePoint > 0xd7ff && codePoint < 0xe000)) { + return '\ufffd'; + } + if (codePoint < 0x10000) { + return String.fromCharCode(codePoint); + } + return String.fromCodePoint(codePoint); + }; + + // convert escape sequence in a CSS string or identifier + // to javascript string with javascript escape sequences + const convertEscapes = function (str) { + return REX.hasEscapes.test(str) + ? str.replace(REX.fixEscapes, function (substring, p1, p2) { + // unescaped " or ' + return p2 + ? '\\' + p2 + // javascript strings are UTF-16 encoded + : REX.hexNumbers.test(p1) + ? codePointToUTF16(parseInt(p1, 16)) + // \' \" + : REX.escOrQuote.test(p1) + ? substring + // \g \h \. \# etc + : p1; + }) + : str; + }; + + // convert escape sequence in a CSS string or identifier + // to javascript string with characters representations + const unescapeIdentifier = function (str) { + return REX.hasEscapes.test(str) + ? str.replace(REX.fixEscapes, function (substring, p1, p2) { + // unescaped " or ' + return p2 || (REX.hexNumbers.test(p1) + ? stringFromCodePoint(parseInt(p1, 16)) + // \' \" + : REX.escOrQuote.test(p1) + ? substring + // \g \h \. \# etc + : p1); + }) + : str; + }; + + // empty set + const none = []; + + // cached lambdas + const matchLambdas = {}; + const selectLambdas = {}; + + // cached resolvers + let matchResolvers = {}; + let selectResolvers = {}; + + const method = { + '#': 'getElementById', + '*': 'getElementsByTagName', + '|': 'getElementsByTagNameNS', + '.': 'getElementsByClassName' + }; + + // find duplicate ids using iterative walk + const byIdRaw = function (id, context) { + let node = context; + const nodes = []; + let next = node.firstElementChild; + while ((node = next)) { + node.id === id && nodes.push(node); + if ((next = node.firstElementChild || node.nextElementSibling)) { + continue; + } + while (!next && (node = node.parentElement) && node !== context) { + next = node.nextElementSibling; + } + } + return nodes; + }; + + // context agnostic getElementById + const byId = function (id, context) { + let e; + const api = method['#']; + + // duplicates id allowed + if (Config.IDS_DUPES === false) { + if (api in context) { + e = context[api](id); + return e ? [e] : none; + } + } else if ('all' in context) { + if ((e = context.all[id])) { + if (e.nodeType === 1) { + return e.getAttribute('id') !== id ? [] : [e]; + } else if (id === 'length') { + e = context[api](id); + return e ? [e] : none; + } + const nodes = []; + for (let i = 0, l = e.length; l > i; ++i) { + if (e[i].id === id) { + nodes.push(e[i]); + } + } + return nodes.length ? nodes : none; + } else { + return none; + } + } + + return byIdRaw(id, context); + }; + + // context agnostic getElementsByTagName + const byTag = function (tag, context) { + let e; + let nodes; + const api = method['*']; + + // DOCUMENT_NODE (9) & ELEMENT_NODE (1) + if (api in context) { + return Array.prototype.slice.call(context[api](tag)); + } else { + tag = tag.toLowerCase(); + // DOCUMENT_FRAGMENT_NODE (11) + if ((e = context.firstElementChild)) { + if (!(e.nextElementSibling || tag === '*' || e.localName === tag)) { + return Array.prototype.slice.call(e[api](tag)); + } else { + nodes = []; + do { + if (tag === '*' || e.localName === tag) { + nodes.push(e); + } + concatList(nodes, e[api](tag)); + } while ((e = e.nextElementSibling)); + } + } else { + nodes = none; + } + } + return nodes; + }; + + // context agnostic getElementsByClassName + const byClass = function (cls, context) { + let e; + let nodes; + const api = method['.']; + let reCls; + // DOCUMENT_NODE (9) & ELEMENT_NODE (1) + if (api in context) { + return Array.prototype.slice.call(context[api](cls)); + } else { + // DOCUMENT_FRAGMENT_NODE (11) + if ((e = context.firstElementChild)) { + reCls = RegExp('(^|\\s)' + cls + '(\\s|$)', QUIRKS_MODE ? 'i' : ''); + if (!(e.nextElementSibling || reCls.test(e.className))) { + return Array.prototype.slice.call(e[api](cls)); + } else { + nodes = []; + do { + if (reCls.test(e.className)) { + nodes.push(e); + } + concatList(nodes, e[api](cls)); + } while ((e = e.nextElementSibling)); + } + } else nodes = none; + } + return nodes; + }; + + const compat = { + '#': function (c, n) { + REX.hasEscapes.test(n) && (n = unescapeIdentifier(n)); + return function (e, f) { + return byId(n, c); + }; + }, + '*': function (c, n) { + REX.hasEscapes.test(n) && (n = unescapeIdentifier(n)); + return function (e, f) { + return byTag(n, c); + }; + }, + '|': function (c, n) { + REX.hasEscapes.test(n) && (n = unescapeIdentifier(n)); + return function (e, f) { + return byTag(n, c); + }; + }, + '.': function (c, n) { + REX.hasEscapes.test(n) && (n = unescapeIdentifier(n)); + return function (e, f) { + return byClass(n, c); + }; + } + }; + + // namespace aware hasAttribute + // helper for XML/XHTML documents + const hasAttributeNS = function (e, name) { + let i; + let l; + const attr = e.getAttributeNames(); + name = RegExp(':?' + name + '$', HTML_DOCUMENT ? 'i' : ''); + for (i = 0, l = attr.length; l > i; ++i) { + if (name.test(attr[i])) { + return true; + } + } + return false; + }; + + // fast resolver for the :nth-child() and :nth-last-child() pseudo-classes + const nthElement = (function () { + let idx = 0; + let len = 0; + let set = 0; + let parent; + let parents = []; + let nodes = []; + return function (element, dir) { + // ensure caches are emptied after each run, invoking with dir = 2 + if (dir === 2) { + idx = 0; len = 0; set = 0; nodes = []; parents = []; parent = undefined; + return -1; + } + let e, i, j, k, l; + if (parent === element.parentElement) { + i = set; j = idx; l = len; + } else { + l = parents.length; + parent = element.parentElement; + for (i = -1, j = 0, k = l - 1; l > j; ++j, --k) { + if (parents[j] === parent) { + i = j; + break; + } + if (parents[k] === parent) { + i = k; + break; + } + } + if (i < 0) { + parents[i = l] = parent; + l = 0; nodes[i] = []; + e = (parent && parent.firstElementChild) || element; + while (e) { + nodes[i][l] = e; + if (e === element) { + j = l; + } + e = e.nextElementSibling; + ++l; + } + set = i; idx = 0; len = l; + if (l < 2) { + return l; + } + } else { + l = nodes[i].length; + set = i; + } + } + if (element !== nodes[i][j] && element !== nodes[i][j = 0]) { + for (j = 0, e = nodes[i], k = l - 1; l > j; ++j, --k) { + if (e[j] === element) { + break; + } + if (e[k] === element) { + j = k; + break; + } + } + } + idx = j + 1; len = l; + return dir ? l - j : idx; + }; + })(); + + // fast resolver for the :nth-of-type() and :nth-last-of-type() pseudo-classes + const nthOfType = (function () { + let idx = 0; + let len = 0; + let set = 0; + let parent; + let parents = []; + let nodes = []; + return function (element, dir) { + // ensure caches are emptied after each run, invoking with dir = 2 + if (dir === 2) { + idx = 0; len = 0; set = 0; nodes = []; parents = []; parent = undefined; + return -1; + } + const name = element.localName; + const nsURI = element.namespaceURI; + if (nsURI !== 'http://www.w3.org/1999/xhtml') { + idx = 0; len = 0; set = 0; nodes = []; parents = []; parent = undefined; + } + let e; + let i; + let j; + let k; + let l; + if (nodes[set] && nodes[set][name] && parent === element.parentElement) { + i = set; + j = idx; + l = len; + } else { + l = parents.length; + parent = element.parentElement; + for (i = -1, j = 0, k = l - 1; l > j; ++j, --k) { + if (parents[j] === parent) { + i = j; + break; + } + if (parents[k] === parent) { + i = k; + break; + } + } + if (i < 0 || !nodes[i][name]) { + parents[i = l] = parent; + nodes[i] || (nodes[i] = Object()); + l = 0; nodes[i][name] = []; + e = (parent && parent.firstElementChild) || element; + while (e) { + if (e === element) { + j = l; + } + if (e.localName === name && e.namespaceURI === nsURI) { + nodes[i][name][l] = e; + ++l; + } + e = e.nextElementSibling; + } + set = i; idx = j; len = l; + if (l < 2) { + return l; + } + } else { + l = nodes[i][name].length; + set = i; + } + } + if (element !== nodes[i][name][j] && element !== nodes[i][name][j = 0]) { + for (j = 0, e = nodes[i][name], k = l - 1; l > j; ++j, --k) { + if (e[j] === element) { + break; + } + if (e[k] === element) { + j = k; + break; + } + } + } + idx = j + 1; len = l; + return dir ? l - j : idx; + }; + })(); + + // check if the node is the target + const isTarget = function (node) { + const doc = node.ownerDocument || node; + const { hash } = new URL(doc.URL); + if (node.id && hash === `#${node.id}` && doc.contains(node)) { + return true; + } + return false; + }; + + // check if node is indeterminate + const isIndeterminate = function (node) { + if ((node.indeterminate && node.localName === 'input' && + node.type === 'checkbox') || + (node.localName === 'progress' && !node.hasAttribute('value'))) { + return true; + } + if (node.localName === 'input' && node.type === 'radio' && + !node.hasAttribute('checked')) { + const nodeName = node.name; + let parent = node.parentNode; + while (parent) { + if (parent.localName === 'form') { + break; + } + parent = parent.parentNode; + } + if (!parent) { + const doc = node.ownerDocument; + parent = doc.documentElement; + } + const items = parent.getElementsByTagName('input'); + const l = items.length; + let checked; + for (let i = 0; i < l; i++) { + const item = items[i]; + if (item.getAttribute('type') === 'radio') { + if (nodeName) { + if (item.getAttribute('name') === nodeName) { + checked = !!item.checked; + } + } else if (!item.hasAttribute('name')) { + checked = !!item.checked; + } + if (checked) { + break; + } + } + } + if (!checked) { + return true; + } + } + return false; + }; + + // check if node content is editable + const isContentEditable = function (node) { + let attrValue = 'inherit'; + if (node.hasAttribute('contenteditable')) { + attrValue = node.getAttribute('contenteditable'); + } + switch (attrValue) { + case '': + case 'plaintext-only': + case 'true': + return true; + case 'false': + return false; + default: + if (node.parentNode && node.parentNode.nodeType === 1) { + return isContentEditable(node.parentNode); + } + return false; + } + }; + + // build validation regexps used by the engine + const setIdentifierSyntax = function () { + // + // NOTE: SPECIAL CASES IN CSS SYNTAX PARSING RULES + // + // The https://drafts.csswg.org/css-syntax/#typedef-eof-token + // allow mangled|unclosed selector syntax at the end of selectors strings + // + // Literal equivalent hex representations of the characters: " ' ` ] ) + // + // \\x22 = " - double quotes \\x5b = [ - open square bracket + // \\x27 = ' - single quote \\x5d = ] - closed square bracket + // \\x60 = ` - back tick \\x28 = ( - open round parens + // \\x5c = \ - back slash \\x29 = ) - closed round parens + // + // using hex format prevents false matches of opened/closed instances + // pairs, coloring breakage and other editors highlightning problems. + // + + // @see https://drafts.csswg.org/css-syntax-3/#ident-token-diagram + const nonascii = '[^\\x00-\\x9f]'; + const esctoken = '\\\\(?:[^\\r\\n\\f\\da-f]|[\\da-f]{1,6}\\s{0,255})'; + const identifier = + '(?:--|-?(?:[a-z_]|' + nonascii + '|' + esctoken + '))' + + '(?:[\\w-]|' + nonascii + '|' + esctoken + ')*'; + + const pseudonames = '[-\\w]+'; + const pseudoparms = '(?:[-+]?\\d*)(?:n\\s?[-+]?\\s?\\d*)'; + const doublequote = '"[^"\\\\]*(?:\\\\.[^"\\\\]*)*(?:"|$)'; + const singlequote = "'[^'\\\\]*(?:\\\\.[^'\\\\]*)*(?:'|$)"; + + const attrparser = identifier + '|' + doublequote + '|' + singlequote; + + const attrvalues = '([\\x22\\x27]?)((?!\\3)*|(?:\\\\?.)*?)(?:\\3|$)'; + + const attributes = + '\\[' + + // attribute presence + '(?:\\*\\|)?\\s?(' + identifier + '(?::' + identifier + ')?)\\s?' + + '(?:(' + CFG.operators + ')\\s?(?:' + attrparser + '))?' + + // attribute case sensitivity + '(?:\\s?\\b(i))?\\s?' + + '(?:\\]|$)'; + + const attrmatcher = attributes.replace(attrparser, attrvalues); + + const pseudoclass = + '(?:\\x28\\s*' + + '(?:' + pseudoparms + '?)?|' + + // universal * & + // namespace *|* + '[*|]|' + + '(?:' + + '(?::' + pseudonames + '(?:\\x28' + pseudoparms + '?(?:\\x29|$))?)|' + + '(?:[.#]?' + identifier + ')|' + + '(?:' + attributes + ')' + + ')+|' + + '\\s?[>+~]\\s?|' + + '\\s?,\\s?|' + + '\\s|' + + '\\x29|$' + + ')*'; + + const standardValidator = + '(?=\\s?[^>+~(){}<])' + + '(?:' + + // universal * & + // namespace *|* + '\\*|\\||' + + '(?:[.#]?' + identifier + ')+|' + + '(?:' + attributes + ')+|' + + '(?:::?' + pseudonames + pseudoclass + ')|' + + '(?:\\s?' + CFG.combinators + '\\s?)|' + + '\\s?,\\s?|' + + '\\s?' + + ')+'; + + // the following global RE is used to return the + // deepest localName in selector strings and then + // use it to retrieve all possible matching nodes + // that will be filtered by compiled resolvers + reOptimizer = RegExp( + '(?:([.:#*]?)(' + identifier + ')' + + '(?::[-\\w]+|\\[[^\\]]+(?:\\]|$)|\\x28[^\\x29]+(?:\\x29|$))*' + + ')$', 'i'); + + // global + reValidator = RegExp(standardValidator, 'gi'); + + Patterns.id = RegExp('^#(' + identifier + ')(.*)', 'i'); + Patterns.tagName = RegExp('^(' + identifier + ')(.*)', 'i'); + Patterns.className = RegExp('^\\.(' + identifier + ')(.*)', 'i'); + Patterns.attribute = RegExp('^(?:' + attrmatcher + ')(.*)'); + }; + + // configure the engine to use special handling + const configure = function (option, clear) { + if (typeof option === 'string') { + return !!Config[option]; + } + if (typeof option !== 'object') { + return Config; + } + for (const i in option) { + Config[i] = !!option[i]; + } + // clear lambda cache + if (clear) { + matchResolvers = {}; + selectResolvers = {}; + } + setIdentifierSyntax(); + return true; + }; + + // centralized error and exceptions handling + const emit = function (message, proto) { + let err; + if (Config.VERBOSITY) { + if (global[proto]) { + err = new global[proto](message); + } else { + err = new global.DOMException(message, 'SyntaxError'); + } + throw err; + } + if (Config.LOGERRORS && console && console.log) { + console.log(message); + } + }; + + // passed to resolvers + const Snapshot = { + doc: null, + from: null, + byTag: null, + first: null, + match: null, + ancestor: null, + nthOfType: null, + nthElement: null, + hasAttributeNS: null, + isTarget: null, + isIndeterminate: null, + isContentEditable: null + }; + + // context + let lastContext; + + const switchContext = function (context, force) { + const oldDoc = doc; + doc = context.ownerDocument || context; + if (force || oldDoc !== doc) { + // force a new check for each document change + // performed before the next select operation + HTML_DOCUMENT = isHTML(doc); + QUIRKS_MODE = HTML_DOCUMENT && doc.compatMode.indexOf('CSS') < 0; + NAMESPACE = doc.documentElement && doc.documentElement.namespaceURI; + Snapshot.doc = doc; + } + Snapshot.from = context; + return context; + }; + + // selector + let lastMatched; + let lastSelected; + + const F_INIT = '"use strict";return function Resolver(c,f,x,r)'; + + const S_HEAD = 'var e,n,o,j=r.length-1,k=-1'; + const M_HEAD = 'var e,n,o'; + + const S_LOOP = 'main:while((e=c[++k]))'; + const N_LOOP = 'main:while((e=c.item(++k)))'; + const M_LOOP = 'e=c;'; + + const S_BODY = 'r[++j]=c[k];'; + const N_BODY = 'r[++j]=c.item(k);'; + const M_BODY = ''; + + const S_TAIL = 'continue main;'; + const M_TAIL = 'r=true;'; + + const S_TEST = 'if(f(c[k])){break main;}'; + const N_TEST = 'if(f(c.item(k))){break main;}'; + const M_TEST = 'f(c);'; + + let S_VARS = []; + let M_VARS = []; + + // build conditional code to check components of selector strings + const compileSelector = function (expression, source, mode, callback) { + // N is the negation pseudo-class flag + // D is the default inverted negation flag + let a; + let b; + let n; + let f; + let name; + let NS; + const N = ''; + const D = '!'; + let compat; + let expr; + let match; + let result; + let status; + let symbol; + let test; + let type; + let selector = expression; + let vars; + + // original 'select' or 'match' selector string before normalization + const selectorString = mode ? lastSelected : lastMatched; + + // isolate selector combinators/components and normalize whitespace + selector = selector.replace(STD.combinator, '$1'); // .replace(STD.whitespace, ' '); + + let selectorRecursion = true; + while (selector) { + // get namespace prefix if present or get first char of selector + symbol = STD.apimethods.test(selector) ? '|' : selector[0]; + + switch (symbol) { + // universal resolver + case '*': + match = selector.match(Patterns.universal); + if (N === '!') { + source = 'if(' + N + 'true' + '){' + source + '}'; + } + break; + // id resolver + case '#': + match = selector.match(Patterns.id); + source = 'if(' + N + '(/^' + match[1] + '$/.test(e.getAttribute("id"))' + + ')){' + source + '}'; + break; + // class name resolver + case '.': + match = selector.match(Patterns.className); + compat = (QUIRKS_MODE ? 'i' : '') + '.test(e.getAttribute("class"))'; + source = 'if(' + N + '(/(^|\\s)' + match[1] + '(\\s|$)/' + compat + + ')){' + source + '}'; + break; + // tag name resolver + case (/[_a-z]/i.test(symbol) ? symbol : undefined): + match = selector.match(Patterns.tagName); + source = 'if(' + N + '(e.localName' + + (Config.MIXEDCASE || hasMixedCaseTagNames(doc) + ? '=="' + match[1].toLowerCase() + '"' + : '=="' + match[1].toUpperCase() + '"') + + ')){' + source + '}'; + break; + // namespace resolver + case '|': + match = selector.match(Patterns.namespace); + if (match[1] === '*') { + source = 'if(' + N + 'true){' + source + '}'; + } else if (!match[1]) { + source = 'if(' + N + '(!e.namespaceURI)){' + source + '}'; + } else if (typeof match[1] === 'string' && doc.documentElement && + doc.documentElement.prefix === match[1]) { + source = 'if(' + N + '(e.namespaceURI=="' + NAMESPACE + '")){' + source + '}'; + } else { + emit('\'' + selectorString + '\'' + qsInvalid); + } + break; + // attributes resolver + case '[': + match = selector.match(Patterns.attribute); + NS = match[0].match(STD.namespaces); + name = match[1]; + expr = name.split(':'); + expr = expr.length === 2 ? expr[1] : expr[0]; + if (match[2] && !(test = Operators[match[2]])) { + emit('\'' + selectorString + '\'' + qsInvalid); + return ''; + } + if (match[4] === '') { + test = match[2] === '~=' + ? { p1: '^\\s', p2: '+$', p3: 'true' } + : match[2] in ATTR_STD_OPS && match[2] !== '~=' + ? { p1: '^', p2: '$', p3: 'true' } + : test; + } else if (match[2] === '~=' && match[4].includes(' ')) { + // whitespace separated list but value contains space + source = 'if(' + N + 'false){' + source + '}'; + break; + } else if (match[4]) { + match[4] = convertEscapes(match[4]).replace(REX.regExpChar, '\\$&'); + } + type = match[5] === 'i' || (HTML_DOCUMENT && HTML_TABLE[expr.toLowerCase()]) + ? 'i' + : ''; + source = + 'if(' + N + '(' + + (!match[2] + ? (NS ? 's.hasAttributeNS(e,"' + name + '")' : 'e.hasAttribute&&e.hasAttribute("' + name + '")') + : !match[4] && ATTR_STD_OPS[match[2]] && match[2] !== '~=' + ? 'e.getAttribute&&e.getAttribute("' + name + '")==""' + : '(/' + test.p1 + match[4] + test.p2 + '/' + type + ').test(e.getAttribute&&e.getAttribute("' + name + '"))==' + test.p3) + + ')){' + source + '}'; + break; + // *** General sibling combinator + // E ~ F (F relative sibling of E) + case '~': + match = selector.match(Patterns.relative); + source = 'n=e;while((e=e.previousElementSibling)){' + source + '}e=n;'; + break; + // *** Adjacent sibling combinator + // E + F (F adiacent sibling of E) + case '+': + match = selector.match(Patterns.adjacent); + source = 'n=e;if((e=e.previousElementSibling)){' + source + '}e=n;'; + break; + // *** Descendant combinator + // E F (E ancestor of F) + case '\x09': + case '\x20': + match = selector.match(Patterns.ancestor); + source = 'n=e;while((e=e.parentElement)){' + source + '}e=n;'; + break; + // *** Child combinator + // E > F (F children of E) + case '>': + match = selector.match(Patterns.children); + source = 'n=e;if((e=e.parentElement)){' + source + '}e=n;'; + break; + // *** user supplied combinators extensions + case (symbol in Combinators ? symbol : undefined): + // for other registered combinators extensions + match[match.length - 1] = '*'; + source = Combinators[symbol](match) + source; + break; + // *** tree-structural pseudo-classes + // :root, :empty, :first-child, :last-child, :only-child, :first-of-type, :last-of-type, :only-of-type + case ':': + if ((match = selector.match(Patterns.structural))) { + match[1] = match[1].toLowerCase(); + switch (match[1]) { + case 'root': + // there can only be one :root element, so exit the loop once found + source = 'if(' + N + '(e===s.doc.documentElement)){' + source + (mode ? 'break main;' : '') + '}'; + break; + case 'empty': + // matches elements that don't contain elements or text nodes + source = 'n=e.firstChild;while(n&&!(/1|3/).test(n.nodeType)){n=n.nextSibling}if(' + D + 'n){' + source + '}'; + break; + // *** child-indexed pseudo-classes + // :first-child, :last-child, :only-child + case 'only-child': + source = 'if(' + N + '(!e.nextElementSibling&&!e.previousElementSibling)){' + source + '}'; + break; + case 'last-child': + source = 'if(' + N + '(!e.nextElementSibling)){' + source + '}'; + break; + case 'first-child': + source = 'if(' + N + '(!e.previousElementSibling)){' + source + '}'; + break; + // *** typed child-indexed pseudo-classes + // :only-of-type, :last-of-type, :first-of-type + case 'only-of-type': + source = 'o=e.localName;' + + 'n=e;while((n=n.nextElementSibling)&&n.localName!=o);if(!n){' + + 'n=e;while((n=n.previousElementSibling)&&n.localName!=o);}if(' + D + 'n){' + source + '}'; + break; + case 'last-of-type': + source = 'n=e;o=e.localName;while((n=n.nextElementSibling)&&n.localName!=o);if(' + D + 'n){' + source + '}'; + break; + case 'first-of-type': + source = 'n=e;o=e.localName;while((n=n.previousElementSibling)&&n.localName!=o);if(' + D + 'n){' + source + '}'; + break; + default: + emit('\'' + selectorString + '\'' + qsInvalid); + } + // *** child-indexed & typed child-indexed pseudo-classes + // :nth-child, :nth-of-type, :nth-last-child, :nth-last-of-type + } else if ((match = selector.match(Patterns.treestruct))) { + match[1] = match[1].toLowerCase(); + switch (match[1]) { + case 'nth-child': + case 'nth-of-type': + case 'nth-last-child': + case 'nth-last-of-type': + expr = /-of-type/i.test(match[1]); + if (match[1] && match[2]) { + type = /last/i.test(match[1]); + if (match[2] === 'n') { + source = 'if(' + N + 'true){' + source + '}'; + break; + } else if (match[2] === '1') { + test = type ? 'next' : 'previous'; + source = expr + ? 'n=e;o=e.localName;' + + 'while((n=n.' + test + 'ElementSibling)&&n.localName!=o);if(' + D + 'n){' + source + '}' + : 'if(' + N + '!e.' + test + 'ElementSibling){' + source + '}'; + break; + } else if (match[2] === 'even' || match[2] === '2n0' || match[2] === '2n+0' || match[2] === '2n') { + test = 'n%2==0'; + } else if (match[2] === 'odd' || match[2] === '2n1' || match[2] === '2n+1') { + test = 'n%2==1'; + } else { + f = /n/i.test(match[2]); + n = match[2].split('n'); + a = parseInt(n[0], 10) || 0; + b = parseInt(n[1], 10) || 0; + if (n[0] === '-') { + a = -1; + } + if (n[0] === '+') { + a = +1; + } + test = (b ? '(n' + (b > 0 ? '-' : '+') + Math.abs(b) + ')' : 'n') + '%' + a + '==0'; + test = a >= +1 + ? (f + ? 'n>' + (b - 1) + (Math.abs(a) !== 1 + ? '&&' + test + : '') + : 'n==' + a) + : a <= -1 + ? (f + ? 'n<' + (b + 1) + (Math.abs(a) !== 1 + ? '&&' + test + : '') + : 'n==' + a) + : a === 0 + ? (n[0] + ? 'n==' + b + : 'n>' + (b - 1)) + : 'false'; + } + expr = expr ? 'OfType' : 'Element'; + type = type ? 'true' : 'false'; + source = 'n=s.nth' + expr + '(e,' + type + ');if(' + N + '(' + test + ')){' + source + '}'; + } else { + emit('\'' + selectorString + '\'' + qsInvalid); + } + break; + default: + emit('\'' + selectorString + '\'' + qsInvalid); + } + // *** logical combination pseudo-classes + // :is( s1, [ s2, ... ]), :not( s1, [ s2, ... ]) + } else if ((match = selector.match(Patterns.logicalsel))) { + match[1] = match[1].toLowerCase(); + expr = match[2].replace(REX.CommaGroup, ',').replace(REX.TrimSpaces, ''); + switch (match[1]) { + // FIXME: + case 'is': + case 'where': + case 'matches': + source = 'if(s.match("' + expr.replace(/\x22/g, '\\"') + '",e)){' + source + '}'; + break; + // FIXME: + case 'not': + source = 'if(!s.match("' + expr.replace(/\x22/g, '\\"') + '",e)){' + source + '}'; + break; + // FIXME: + case 'has': + // clear cache + matchResolvers = {}; + source = 'if(e.querySelector(":scope ' + expr.replace(/\x22/g, '\\"') + '")){' + source + '}'; + break; + default: + emit('\'' + selectorString + '\'' + qsInvalid); + } + // *** location pseudo-classes + // :any-link, :link, :visited, :target + } else if ((match = selector.match(Patterns.locationpc))) { + match[1] = match[1].toLowerCase(); + switch (match[1]) { + case 'any-link': + source = 'if(' + N + '(/^a|area$/i.test(e.localName)&&e.hasAttribute("href")||e.visited)){' + source + '}'; + break; + case 'link': + source = 'if(' + N + '(/^a|area$/i.test(e.localName)&&e.hasAttribute("href"))){' + source + '}'; + break; + // FIXME: + case 'visited': + source = 'if(' + N + '(/^a|area$/i.test(e.localName)&&e.hasAttribute("href")&&e.visited)){' + source + '}'; + break; + case 'target': + source = 'if(s.isTarget(e)){' + source + '}'; + break; + default: + emit('\'' + selectorString + '\'' + qsInvalid); + } + // *** user interface and form pseudo-classes + // :enabled, :disabled, :read-only, :read-write, :placeholder-shown, :default + } else if ((match = selector.match(Patterns.inputstate))) { + match[1] = match[1].toLowerCase(); + switch (match[1]) { + // FIXME: lacks custom element support + case 'enabled': + source = 'if((("form" in e||/^optgroup$/i.test(e.localName))&&"disabled" in e &&e.disabled===false' + + ')){' + source + '}'; + break; + // FIXME: lacks custom element support + case 'disabled': + // https://html.spec.whatwg.org/#enabling-and-disabling-form-controls:-the-disabled-attribute + source = 'if((("form" in e||/^optgroup$/i.test(e.localName))&&"disabled" in e)){' + + // F is true if any of the fieldset elements in the ancestry chain has the disabled attribute specified + // L is true if the first legend element of the fieldset contains the element + 'var x=0,N=[],F=false,L=false;' + + 'if(!(/^(optgroup|option)$/i.test(e.localName))){' + + 'n=e.parentElement;' + + 'while(n){' + + 'if(n.localName==="fieldset"){' + + 'N[x++]=n;' + + 'if(n.disabled===true){' + + 'F=true;' + + 'break;' + + '}' + + '}' + + 'n=n.parentElement;' + + '}' + + 'for(var x=0;x + // assert: e.type is in double-colon format, like ::after + } else if ((match = selector.match(Patterns.pseudoDbl))) { + source = 'if(e.element&&e.type.toLowerCase()=="' + + match[0].toLowerCase() + '"){e=e.element;' + source + '}'; + // placeholder for parsed only no-op selectors + } else if ((match = selector.match(Patterns.pseudoNop))) { + source = 'if(' + N + 'false' + '){' + source + '}'; + } else { + // reset + expr = false; + status = false; + // process registered selector extensions + for (expr in Selectors) { + if ((match = selector.match(Selectors[expr].Expression))) { + result = Selectors[expr].Callback(match, source, mode, callback); + if ('match' in result) { + match = result.match; + } + vars = result.modvar; + if (mode) { + // add extra select() vars + vars && !S_VARS.includes(vars) && S_VARS.push(vars); + } else { + // add extra match() vars + vars && M_VARS.includes(vars) && M_VARS.push(vars); + } + // extension source code + source = result.source; + // extension status code + status = result.status; + // break on status error + if (status) { break; } + } + } + if (!status) { + emit('unknown pseudo-class selector \'' + selector + '\''); + return ''; + } + if (!expr) { + emit('unknown token in selector \'' + selector + '\''); + return ''; + } + } + break; + default: + selectorRecursion = false; + emit('\'' + selectorString + '\'' + qsInvalid); + } + // end of switch symbol + if (!selectorRecursion) { + break; + } + if (!match) { + emit('\'' + selectorString + '\'' + qsInvalid); + return ''; + } + + // pop last component + selector = match.pop(); + } + // end of while selector + + return source; + }; + + // compile groups or single selector strings into + // executable functions for matching or selecting + const compile = function (selector, mode, callback) { + let head = ''; let loop = ''; let macro = ''; let source = ''; let vars = ''; + + // 'mode' can be boolean or null + // true = select / false = match + // null to use collection.item() + switch (mode) { + case true: + if (selectLambdas[selector]) { + return selectLambdas[selector]; + } + macro = S_BODY + (callback ? S_TEST : '') + S_TAIL; + head = S_HEAD; + loop = S_LOOP; + break; + case false: + if (matchLambdas[selector]) { + return matchLambdas[selector]; + } + macro = M_BODY + (callback ? M_TEST : '') + M_TAIL; + head = M_HEAD; + loop = M_LOOP; + break; + case null: + if (selectLambdas[selector]) { + return selectLambdas[selector]; + } + macro = N_BODY + (callback ? N_TEST : '') + S_TAIL; + head = S_HEAD; + loop = N_LOOP; + break; + default: + } + + source = compileSelector(selector, macro, mode, callback); + + loop += (mode || mode === null) ? '{' + source + '}' : source; + + if ((mode || mode === null) && selector.includes(':nth')) { + loop += reNthElem.test(selector) ? 's.nthElement(null, 2);' : ''; + loop += reNthType.test(selector) ? 's.nthOfType(null, 2);' : ''; + } + + if (S_VARS[0] || M_VARS[0]) { + vars = ',' + (S_VARS.join(',') || M_VARS.join(',')); + S_VARS = []; + M_VARS = []; + } + + const factory = Function('s', F_INIT + '{' + head + vars + ';' + loop + 'return r;}')(Snapshot); + + return mode || mode === null ? (selectLambdas[selector] = factory) : (matchLambdas[selector] = factory); + }; + + // optimize selectors avoiding duplicated checks + const optimize = function (selector, token) { + const index = token.index; + const length = token[1].length + token[2].length; + return selector.slice(0, index) + + (' >+~'.indexOf(selector.charAt(index - 1)) > -1 + ? (':['.indexOf(selector.charAt(index + length + 1)) > -1 + ? '*' + : '') + : '') + selector.slice(index + length - (token[1] === '*' ? 1 : 0)); + }; + + // prepare factory resolvers and closure collections + const collect = function (selectors, context, callback) { + let i; + let l; + const seen = { }; + let token = ['', '*', '*']; + const optimized = selectors; + const factory = []; + const htmlset = []; + const nodeset = []; + let results = []; + let type; + + for (i = 0, l = selectors.length; l > i; ++i) { + if (!seen[selectors[i]] && (seen[selectors[i]] = true)) { + type = selectors[i].match(reOptimizer); + if (type && type[1] !== ':' && (token = type)) { + token[1] || (token[1] = '*'); + optimized[i] = optimize(optimized[i], token); + } else { + token = ['', '*', '*']; + } + } + + nodeset[i] = token[1] + token[2]; + htmlset[i] = compat[token[1]](context, token[2]); + factory[i] = compile(optimized[i], true, null); + + factory[i] + ? factory[i](htmlset[i](), callback, context, results) + : results.concat(htmlset[i]()); + } + + if (l > 1) { + results.sort(documentOrder); + hasDupes && (results = unique(results)); + } + + return { + callback, + context, + factory, + htmlset, + nodeset, + results + }; + }; + + // replace ':scope' pseudo-class with element references + const makeref = function (selectors, element) { + // DOCUMENT_NODE (9) + if (element.nodeType === 9) { + element = element.documentElement; + } + + return selectors.replace(/:scope/gi, + element.localName + + (element.id ? '#' + element.id : '') + + (element.className ? '.' + element.classList[0] : '')); + }; + + const matchAssert = function (f, element, callback) { + let r = false; + for (let i = 0, l = f.length; l > i; ++i) { + f[i](element, callback, null, false) && (r = true); + } + return r; + }; + + const matchCollect = function (selectors, callback) { + const f = []; + for (let i = 0, l = selectors.length; l > i; ++i) { + f[i] = compile(selectors[i], false, callback); + } + return { factory: f }; + }; + + // equivalent of w3c 'matches' method + const match = function _matches(selectors, element, callback) { + let expressions; + + if (element && !/:has\(/.test(selectors) && matchResolvers[selectors]) { + return matchAssert(matchResolvers[selectors].factory, element, callback); + } + + lastMatched = selectors; + + // arguments validation + if (arguments.length === 0) { + emit(qsNotArgs, 'TypeError'); + return Config.VERBOSITY ? undefined : false; + } else if (arguments[0] === '') { + emit('\'\'' + qsInvalid); + return Config.VERBOSITY ? undefined : false; + } + + // input NULL or UNDEFINED + if (typeof selectors !== 'string') { + selectors = '' + selectors; + } + + if ((/:scope/i).test(selectors)) { + selectors = makeref(selectors, element); + } + + // normalize input string + const parsed = selectors + .replace(/\0|\\$/g, '\ufffd') + .replace(REX.combineWSP, '\x20') + .replace(REX.pseudosWSP, '$1') + .replace(REX.tabCharWSP, '\t') + .replace(REX.commaGroup, ',') + .replace(REX.trimSpaces, ''); + + // parse, validate and split possible compound selectors + if ((expressions = parsed.match(reValidator)) && expressions.join('') === parsed) { + expressions = parsed.match(REX.splitGroup); + if (parsed[parsed.length - 1] === ',') { + emit(qsInvalid); + return Config.VERBOSITY ? undefined : false; + } + } else { + emit('\'' + selectors + '\'' + qsInvalid); + return Config.VERBOSITY ? undefined : false; + } + + matchResolvers[selectors] = matchCollect(expressions, callback); + + return matchAssert(matchResolvers[selectors].factory, element, callback); + }; + + // equivalent of w3c 'closest' method + const ancestor = function _closest(selectors, element, callback) { + if ((/:scope/i).test(selectors)) { + selectors = makeref(selectors, element); + } + + while (element) { + if (match(selectors, element, callback)) break; + element = element.parentElement; + } + return element; + }; + + // equivalent of w3c 'querySelectorAll' method + const select = function _querySelectorAll(selectors, context, callback) { + let expressions; let nodes = []; let resolver; + + context || (context = doc); + + if (selectors) { + if ((resolver = selectResolvers[selectors])) { + if (resolver.context === context && resolver.callback === callback) { + const f = resolver.factory; + const h = resolver.htmlset; + const n = resolver.nodeset; + if (n.length > 1) { + const l = n.length; + for (let i = 0, l = n.length, list; l > i; ++i) { + list = compat[n[i][0]](context, n[i].slice(1))(); + if (f[i] !== null) { + f[i](list, callback, context, nodes); + } else { + nodes = nodes.concat(list); + } + } + if (l > 1 && nodes.length > 1) { + nodes.sort(documentOrder); + hasDupes && (nodes = unique(nodes)); + } + } else { + if (f[0]) { + nodes = f[0](h[0](), callback, context, nodes); + } else { + nodes = h[0](); + } + } + return typeof callback === 'function' + ? concatCall(nodes, callback) + : nodes; + } + } + } + + lastSelected = selectors; + + // arguments validation + if (arguments.length === 0) { + emit(qsNotArgs, 'TypeError'); + return Config.VERBOSITY ? undefined : none; + } else if (arguments[0] === '') { + emit('\'\'' + qsInvalid); + return Config.VERBOSITY ? undefined : none; + } else if (lastContext !== context) { + lastContext = switchContext(context); + } + + // input NULL or UNDEFINED + if (typeof selectors !== 'string') { + selectors = '' + selectors; + } + + if ((/:scope/i).test(selectors)) { + selectors = makeref(selectors, context); + } + + // normalize input string + const parsed = selectors + .replace(/\0|\\$/g, '\ufffd') + .replace(REX.combineWSP, '\x20') + .replace(REX.pseudosWSP, '$1') + .replace(REX.tabCharWSP, '\t') + .replace(REX.commaGroup, ',') + .replace(REX.trimSpaces, ''); + + // parse, validate and split possible compound selectors + if ((expressions = parsed.match(reValidator)) && expressions.join('') === parsed) { + expressions = parsed.match(REX.splitGroup); + if (parsed[parsed.length - 1] === ',') { + emit(qsInvalid); + return Config.VERBOSITY ? undefined : false; + } + } else { + emit('\'' + selectors + '\'' + qsInvalid); + return Config.VERBOSITY ? undefined : false; + } + + // save/reuse factory and closure collection + selectResolvers[selectors] = collect(expressions, context, callback); + + nodes = selectResolvers[selectors].results; + + return typeof callback === 'function' + ? concatCall(nodes, callback) + : nodes; + }; + + // equivalent of w3c 'querySelector' method + const first = function _querySelector(selectors, context, callback) { + if (arguments.length === 0) { + emit(qsNotArgs, 'TypeError'); + } + return select(selectors, context, typeof callback === 'function' + ? function firstMatch(element) { + callback(element); + return false; + } + : function firstMatch() { + return false; + } + )[0] || null; + }; + + // execute the engine initialization code + const initialize = function (d) { + setIdentifierSyntax(); + lastContext = switchContext(d, true); + Snapshot.doc = doc; + Snapshot.from = doc; + Snapshot.byTag = byTag; + Snapshot.first = first; + Snapshot.match = match; + Snapshot.ancestor = ancestor; + Snapshot.nthOfType = nthOfType; + Snapshot.nthElement = nthElement; + Snapshot.hasAttributeNS = hasAttributeNS; + Snapshot.isTarget = isTarget; + Snapshot.isIndeterminate = isIndeterminate; + Snapshot.isContentEditable = isContentEditable; + }; + + initialize(doc); + + // public exported methods/objects + const Dom = { + // exported engine methods + Version: version, + configure, + match, + closest: ancestor, + first, + select + }; + + return Dom; +}); diff --git a/node_modules/@babel/code-frame/LICENSE b/node_modules/@babel/code-frame/LICENSE new file mode 100644 index 00000000..f31575ec --- /dev/null +++ b/node_modules/@babel/code-frame/LICENSE @@ -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. diff --git a/node_modules/@babel/code-frame/README.md b/node_modules/@babel/code-frame/README.md new file mode 100644 index 00000000..71607551 --- /dev/null +++ b/node_modules/@babel/code-frame/README.md @@ -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/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 +``` diff --git a/node_modules/@babel/code-frame/lib/index.js b/node_modules/@babel/code-frame/lib/index.js new file mode 100644 index 00000000..9c5db406 --- /dev/null +++ b/node_modules/@babel/code-frame/lib/index.js @@ -0,0 +1,217 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var picocolors = require('picocolors'); +var jsTokens = require('js-tokens'); +var helperValidatorIdentifier = require('@babel/helper-validator-identifier'); + +function isColorSupported() { + return (typeof process === "object" && (process.env.FORCE_COLOR === "0" || process.env.FORCE_COLOR === "false") ? false : picocolors.isColorSupported + ); +} +const compose = (f, g) => v => f(g(v)); +function buildDefs(colors) { + return { + keyword: colors.cyan, + capitalized: colors.yellow, + jsxIdentifier: colors.yellow, + punctuator: colors.yellow, + number: colors.magenta, + string: colors.green, + regex: colors.magenta, + comment: colors.gray, + invalid: compose(compose(colors.white, colors.bgRed), colors.bold), + gutter: colors.gray, + marker: compose(colors.red, colors.bold), + message: compose(colors.red, colors.bold), + reset: colors.reset + }; +} +const defsOn = buildDefs(picocolors.createColors(true)); +const defsOff = buildDefs(picocolors.createColors(false)); +function getDefs(enabled) { + return enabled ? defsOn : defsOff; +} + +const sometimesKeywords = new Set(["as", "async", "from", "get", "of", "set"]); +const NEWLINE$1 = /\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") { + const tokenValue = token.value; + if (helperValidatorIdentifier.isKeyword(tokenValue) || helperValidatorIdentifier.isStrictReservedWord(tokenValue, true) || sometimesKeywords.has(tokenValue)) { + return "keyword"; + } + if (JSX_TAG.test(tokenValue) && (text[offset - 1] === "<" || text.slice(offset - 2, offset) === " defs[type](str)).join("\n"); + } else { + highlighted += value; + } + } + return highlighted; +} + +let deprecationWarningShown = false; +const NEWLINE = /\r\n|[\n\r\u2028\u2029]/; +function getMarkerLines(loc, source, opts, startLineBaseZero) { + 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 - startLineBaseZero; + const startColumn = startLoc.column; + const endLine = endLoc.line - startLineBaseZero; + 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 shouldHighlight = opts.forceColor || isColorSupported() && opts.highlightCode; + const startLineBaseZero = (opts.startLine || 1) - 1; + const defs = getDefs(shouldHighlight); + const lines = rawLines.split(NEWLINE); + const { + start, + end, + markerLines + } = getMarkerLines(loc, lines, opts, startLineBaseZero); + const hasColumns = loc.start && typeof loc.start.column === "number"; + const numberMaxWidth = String(end + startLineBaseZero).length; + const highlightedLines = shouldHighlight ? highlight(rawLines) : rawLines; + let frame = highlightedLines.split(NEWLINE, end).slice(start, end).map((line, index) => { + const number = start + 1 + index; + const paddedNumber = ` ${number + startLineBaseZero}`.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 ", defs.gutter(gutter.replace(/\d/g, " ")), " ", markerSpacing, defs.marker("^").repeat(numberOfMarkers)].join(""); + if (lastMarkerLine && opts.message) { + markerLine += " " + defs.message(opts.message); + } + } + return [defs.marker(">"), defs.gutter(gutter), line.length > 0 ? ` ${line}` : "", markerLine].join(""); + } else { + return ` ${defs.gutter(gutter)}${line.length > 0 ? ` ${line}` : ""}`; + } + }).join("\n"); + if (opts.message && !hasColumns) { + frame = `${" ".repeat(numberMaxWidth + 1)}${opts.message}\n${frame}`; + } + if (shouldHighlight) { + return defs.reset(frame); + } else { + return frame; + } +} +function index (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); +} + +exports.codeFrameColumns = codeFrameColumns; +exports.default = index; +exports.highlight = highlight; +//# sourceMappingURL=index.js.map diff --git a/node_modules/@babel/code-frame/lib/index.js.map b/node_modules/@babel/code-frame/lib/index.js.map new file mode 100644 index 00000000..6b85ae49 --- /dev/null +++ b/node_modules/@babel/code-frame/lib/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sources":["../src/defs.ts","../src/highlight.ts","../src/index.ts"],"sourcesContent":["import picocolors, { createColors } from \"picocolors\";\nimport type { Colors, Formatter } from \"picocolors/types\";\n\nexport function isColorSupported() {\n return (\n // See https://github.com/alexeyraspopov/picocolors/issues/62\n typeof process === \"object\" &&\n (process.env.FORCE_COLOR === \"0\" || process.env.FORCE_COLOR === \"false\")\n ? false\n : picocolors.isColorSupported\n );\n}\n\nexport type InternalTokenType =\n | \"keyword\"\n | \"capitalized\"\n | \"jsxIdentifier\"\n | \"punctuator\"\n | \"number\"\n | \"string\"\n | \"regex\"\n | \"comment\"\n | \"invalid\";\n\ntype UITokens = \"gutter\" | \"marker\" | \"message\";\n\nexport type Defs = Record;\n\nconst compose: (f: (gv: U) => V, g: (v: T) => U) => (v: T) => V =\n (f, g) => v =>\n f(g(v));\n\n/**\n * Styles for token types.\n */\nfunction buildDefs(colors: Colors): Defs {\n return {\n keyword: colors.cyan,\n capitalized: colors.yellow,\n jsxIdentifier: colors.yellow,\n punctuator: colors.yellow,\n number: colors.magenta,\n string: colors.green,\n regex: colors.magenta,\n comment: colors.gray,\n invalid: compose(compose(colors.white, colors.bgRed), colors.bold),\n\n gutter: colors.gray,\n marker: compose(colors.red, colors.bold),\n message: compose(colors.red, colors.bold),\n\n reset: colors.reset,\n };\n}\n\nconst defsOn = buildDefs(createColors(true));\nconst defsOff = buildDefs(createColors(false));\n\nexport function getDefs(enabled: boolean): Defs {\n return enabled ? defsOn : defsOff;\n}\n","import type { Token as JSToken, JSXToken } from \"js-tokens\";\nimport jsTokens from \"js-tokens\";\n// We inline this package\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport * as charCodes from \"charcodes\";\n\nimport {\n isStrictReservedWord,\n isKeyword,\n} from \"@babel/helper-validator-identifier\";\n\nimport { getDefs, type InternalTokenType } from \"./defs.ts\";\n\n/**\n * Names that are always allowed as identifiers, but also appear as keywords\n * within certain syntactic productions.\n *\n * https://tc39.es/ecma262/#sec-keywords-and-reserved-words\n *\n * `target` has been omitted since it is very likely going to be a false\n * positive.\n */\nconst sometimesKeywords = new Set([\"as\", \"async\", \"from\", \"get\", \"of\", \"set\"]);\n\ntype Token = {\n type: InternalTokenType | \"uncolored\";\n value: string;\n};\n\n/**\n * RegExp to test for newlines in terminal.\n */\nconst NEWLINE = /\\r\\n|[\\n\\r\\u2028\\u2029]/;\n\n/**\n * RegExp to test for the three types of brackets.\n */\nconst BRACKET = /^[()[\\]{}]$/;\n\nlet tokenize: (\n text: string,\n) => Generator<{ type: InternalTokenType | \"uncolored\"; value: string }>;\n\nif (process.env.BABEL_8_BREAKING) {\n /**\n * Get the type of token, specifying punctuator type.\n */\n const getTokenType = function (\n token: JSToken | JSXToken,\n ): InternalTokenType | \"uncolored\" {\n if (token.type === \"IdentifierName\") {\n const tokenValue = token.value;\n if (\n isKeyword(tokenValue) ||\n isStrictReservedWord(tokenValue, true) ||\n sometimesKeywords.has(tokenValue)\n ) {\n return \"keyword\";\n }\n\n const firstChar = tokenValue.charCodeAt(0);\n if (firstChar < 128) {\n // ASCII characters\n if (\n firstChar >= charCodes.uppercaseA &&\n firstChar <= charCodes.uppercaseZ\n ) {\n return \"capitalized\";\n }\n } else {\n const firstChar = String.fromCodePoint(tokenValue.codePointAt(0));\n if (firstChar !== firstChar.toLowerCase()) {\n return \"capitalized\";\n }\n }\n }\n\n if (token.type === \"Punctuator\" && BRACKET.test(token.value)) {\n return \"uncolored\";\n }\n\n if (token.type === \"Invalid\" && token.value === \"@\") {\n return \"punctuator\";\n }\n\n switch (token.type) {\n case \"NumericLiteral\":\n return \"number\";\n\n case \"StringLiteral\":\n case \"JSXString\":\n case \"NoSubstitutionTemplate\":\n return \"string\";\n\n case \"RegularExpressionLiteral\":\n return \"regex\";\n\n case \"Punctuator\":\n case \"JSXPunctuator\":\n return \"punctuator\";\n\n case \"MultiLineComment\":\n case \"SingleLineComment\":\n return \"comment\";\n\n case \"Invalid\":\n case \"JSXInvalid\":\n return \"invalid\";\n\n case \"JSXIdentifier\":\n return \"jsxIdentifier\";\n\n default:\n return \"uncolored\";\n }\n };\n\n /**\n * Turn a string of JS into an array of objects.\n */\n tokenize = function* (text: string): Generator {\n for (const token of jsTokens(text, { jsx: true })) {\n switch (token.type) {\n case \"TemplateHead\":\n yield { type: \"string\", value: token.value.slice(0, -2) };\n yield { type: \"punctuator\", value: \"${\" };\n break;\n\n case \"TemplateMiddle\":\n yield { type: \"punctuator\", value: \"}\" };\n yield { type: \"string\", value: token.value.slice(1, -2) };\n yield { type: \"punctuator\", value: \"${\" };\n break;\n\n case \"TemplateTail\":\n yield { type: \"punctuator\", value: \"}\" };\n yield { type: \"string\", value: token.value.slice(1) };\n break;\n\n default:\n yield {\n type: getTokenType(token),\n value: token.value,\n };\n }\n }\n };\n} else {\n /**\n * RegExp to test for what seems to be a JSX tag name.\n */\n const JSX_TAG = /^[a-z][\\w-]*$/i;\n\n // The token here is defined in js-tokens@4. However we don't bother\n // typing it since the whole block will be removed in Babel 8\n const getTokenType = function (token: any, offset: number, text: string) {\n if (token.type === \"name\") {\n const tokenValue = token.value;\n if (\n isKeyword(tokenValue) ||\n isStrictReservedWord(tokenValue, true) ||\n sometimesKeywords.has(tokenValue)\n ) {\n return \"keyword\";\n }\n\n if (\n JSX_TAG.test(tokenValue) &&\n (text[offset - 1] === \"<\" || text.slice(offset - 2, offset) === \" defs[type as InternalTokenType](str))\n .join(\"\\n\");\n } else {\n highlighted += value;\n }\n }\n\n return highlighted;\n}\n","import { getDefs, isColorSupported } from \"./defs.ts\";\nimport { highlight } from \"./highlight.ts\";\n\nexport { highlight };\n\nlet deprecationWarningShown = false;\n\ntype Location = {\n column: number;\n line: number;\n};\n\ntype NodeLocation = {\n end?: Location;\n start: Location;\n};\n\nexport interface Options {\n /** Syntax highlight the code as JavaScript for terminals. default: false */\n highlightCode?: boolean;\n /** The number of lines to show above the error. default: 2 */\n linesAbove?: number;\n /** The number of lines to show below the error. default: 3 */\n linesBelow?: number;\n /** The line number corresponding to the first line in `rawLines`. default: 1 */\n startLine?: number;\n /**\n * Forcibly syntax highlight the code as JavaScript (for non-terminals);\n * overrides highlightCode.\n * default: false\n */\n forceColor?: boolean;\n /**\n * Pass in a string to be displayed inline (if possible) next to the\n * highlighted location in the code. If it can't be positioned inline,\n * it will be placed above the code frame.\n * default: nothing\n */\n message?: string;\n}\n\n/**\n * RegExp to test for newlines in terminal.\n */\n\nconst NEWLINE = /\\r\\n|[\\n\\r\\u2028\\u2029]/;\n\n/**\n * Extract what lines should be marked and highlighted.\n */\n\ntype MarkerLines = Record;\n\nfunction getMarkerLines(\n loc: NodeLocation,\n source: string[],\n opts: Options,\n startLineBaseZero: number,\n): {\n start: number;\n end: number;\n markerLines: MarkerLines;\n} {\n const startLoc: Location = {\n column: 0,\n line: -1,\n ...loc.start,\n };\n const endLoc: Location = {\n ...startLoc,\n ...loc.end,\n };\n const { linesAbove = 2, linesBelow = 3 } = opts || {};\n const startLine = startLoc.line - startLineBaseZero;\n const startColumn = startLoc.column;\n const endLine = endLoc.line - startLineBaseZero;\n const endColumn = endLoc.column;\n\n let start = Math.max(startLine - (linesAbove + 1), 0);\n let end = Math.min(source.length, endLine + linesBelow);\n\n if (startLine === -1) {\n start = 0;\n }\n\n if (endLine === -1) {\n end = source.length;\n }\n\n const lineDiff = endLine - startLine;\n const markerLines: MarkerLines = {};\n\n if (lineDiff) {\n for (let i = 0; i <= lineDiff; i++) {\n const lineNumber = i + startLine;\n\n if (!startColumn) {\n markerLines[lineNumber] = true;\n } else if (i === 0) {\n const sourceLength = source[lineNumber - 1].length;\n\n markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1];\n } else if (i === lineDiff) {\n markerLines[lineNumber] = [0, endColumn];\n } else {\n const sourceLength = source[lineNumber - i].length;\n\n markerLines[lineNumber] = [0, sourceLength];\n }\n }\n } else {\n if (startColumn === endColumn) {\n if (startColumn) {\n markerLines[startLine] = [startColumn, 0];\n } else {\n markerLines[startLine] = true;\n }\n } else {\n markerLines[startLine] = [startColumn, endColumn - startColumn];\n }\n }\n\n return { start, end, markerLines };\n}\n\nexport function codeFrameColumns(\n rawLines: string,\n loc: NodeLocation,\n opts: Options = {},\n): string {\n const shouldHighlight =\n opts.forceColor || (isColorSupported() && opts.highlightCode);\n const startLineBaseZero = (opts.startLine || 1) - 1;\n const defs = getDefs(shouldHighlight);\n\n const lines = rawLines.split(NEWLINE);\n const { start, end, markerLines } = getMarkerLines(\n loc,\n lines,\n opts,\n startLineBaseZero,\n );\n const hasColumns = loc.start && typeof loc.start.column === \"number\";\n\n const numberMaxWidth = String(end + startLineBaseZero).length;\n\n const highlightedLines = shouldHighlight ? highlight(rawLines) : rawLines;\n\n let frame = highlightedLines\n .split(NEWLINE, end)\n .slice(start, end)\n .map((line, index) => {\n const number = start + 1 + index;\n const paddedNumber = ` ${number + startLineBaseZero}`.slice(\n -numberMaxWidth,\n );\n const gutter = ` ${paddedNumber} |`;\n const hasMarker = markerLines[number];\n const lastMarkerLine = !markerLines[number + 1];\n if (hasMarker) {\n let markerLine = \"\";\n if (Array.isArray(hasMarker)) {\n const markerSpacing = line\n .slice(0, Math.max(hasMarker[0] - 1, 0))\n .replace(/[^\\t]/g, \" \");\n const numberOfMarkers = hasMarker[1] || 1;\n\n markerLine = [\n \"\\n \",\n defs.gutter(gutter.replace(/\\d/g, \" \")),\n \" \",\n markerSpacing,\n defs.marker(\"^\").repeat(numberOfMarkers),\n ].join(\"\");\n\n if (lastMarkerLine && opts.message) {\n markerLine += \" \" + defs.message(opts.message);\n }\n }\n return [\n defs.marker(\">\"),\n defs.gutter(gutter),\n line.length > 0 ? ` ${line}` : \"\",\n markerLine,\n ].join(\"\");\n } else {\n return ` ${defs.gutter(gutter)}${line.length > 0 ? ` ${line}` : \"\"}`;\n }\n })\n .join(\"\\n\");\n\n if (opts.message && !hasColumns) {\n frame = `${\" \".repeat(numberMaxWidth + 1)}${opts.message}\\n${frame}`;\n }\n\n if (shouldHighlight) {\n return defs.reset(frame);\n } else {\n return frame;\n }\n}\n\n/**\n * Create a code frame, adding line numbers, code highlighting, and pointing to a given position.\n */\n\nexport default function (\n rawLines: string,\n lineNumber: number,\n colNumber?: number | null,\n opts: Options = {},\n): string {\n if (!deprecationWarningShown) {\n deprecationWarningShown = true;\n\n const message =\n \"Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`.\";\n\n if (process.emitWarning) {\n // A string is directly supplied to emitWarning, because when supplying an\n // Error object node throws in the tests because of different contexts\n process.emitWarning(message, \"DeprecationWarning\");\n } else {\n const deprecationError = new Error(message);\n deprecationError.name = \"DeprecationWarning\";\n console.warn(new Error(message));\n }\n }\n\n colNumber = Math.max(colNumber, 0);\n\n const location: NodeLocation = {\n start: { column: colNumber, line: lineNumber },\n };\n\n return codeFrameColumns(rawLines, location, opts);\n}\n"],"names":["isColorSupported","process","env","FORCE_COLOR","picocolors","compose","f","g","v","buildDefs","colors","keyword","cyan","capitalized","yellow","jsxIdentifier","punctuator","number","magenta","string","green","regex","comment","gray","invalid","white","bgRed","bold","gutter","marker","red","message","reset","defsOn","createColors","defsOff","getDefs","enabled","sometimesKeywords","Set","NEWLINE","BRACKET","tokenize","JSX_TAG","getTokenType","token","offset","text","type","tokenValue","value","isKeyword","isStrictReservedWord","has","test","slice","firstChar","String","fromCodePoint","codePointAt","toLowerCase","match","jsTokens","default","exec","matchToToken","index","highlight","defs","highlighted","split","map","str","join","deprecationWarningShown","getMarkerLines","loc","source","opts","startLineBaseZero","startLoc","Object","assign","column","line","start","endLoc","end","linesAbove","linesBelow","startLine","startColumn","endLine","endColumn","Math","max","min","length","lineDiff","markerLines","i","lineNumber","sourceLength","codeFrameColumns","rawLines","shouldHighlight","forceColor","highlightCode","lines","hasColumns","numberMaxWidth","highlightedLines","frame","paddedNumber","hasMarker","lastMarkerLine","markerLine","Array","isArray","markerSpacing","replace","numberOfMarkers","repeat","colNumber","emitWarning","deprecationError","Error","name","console","warn","location"],"mappings":";;;;;;;;AAGO,SAASA,gBAAgBA,GAAG;EACjC,QAEE,OAAOC,OAAO,KAAK,QAAQ,KACxBA,OAAO,CAACC,GAAG,CAACC,WAAW,KAAK,GAAG,IAAIF,OAAO,CAACC,GAAG,CAACC,WAAW,KAAK,OAAO,CAAC,GACtE,KAAK,GACLC,UAAU,CAACJ,gBAAAA;AAAgB,IAAA;AAEnC,CAAA;AAiBA,MAAMK,OAAkE,GACtEA,CAACC,CAAC,EAAEC,CAAC,KAAKC,CAAC,IACTF,CAAC,CAACC,CAAC,CAACC,CAAC,CAAC,CAAC,CAAA;AAKX,SAASC,SAASA,CAACC,MAAc,EAAQ;EACvC,OAAO;IACLC,OAAO,EAAED,MAAM,CAACE,IAAI;IACpBC,WAAW,EAAEH,MAAM,CAACI,MAAM;IAC1BC,aAAa,EAAEL,MAAM,CAACI,MAAM;IAC5BE,UAAU,EAAEN,MAAM,CAACI,MAAM;IACzBG,MAAM,EAAEP,MAAM,CAACQ,OAAO;IACtBC,MAAM,EAAET,MAAM,CAACU,KAAK;IACpBC,KAAK,EAAEX,MAAM,CAACQ,OAAO;IACrBI,OAAO,EAAEZ,MAAM,CAACa,IAAI;AACpBC,IAAAA,OAAO,EAAEnB,OAAO,CAACA,OAAO,CAACK,MAAM,CAACe,KAAK,EAAEf,MAAM,CAACgB,KAAK,CAAC,EAAEhB,MAAM,CAACiB,IAAI,CAAC;IAElEC,MAAM,EAAElB,MAAM,CAACa,IAAI;IACnBM,MAAM,EAAExB,OAAO,CAACK,MAAM,CAACoB,GAAG,EAAEpB,MAAM,CAACiB,IAAI,CAAC;IACxCI,OAAO,EAAE1B,OAAO,CAACK,MAAM,CAACoB,GAAG,EAAEpB,MAAM,CAACiB,IAAI,CAAC;IAEz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AO,CAAA,EAAA,EAAKiF,KAAK,CAAE,CAAA,CAAA;AACtE,GAAA;AAEA,EAAA,IAAIP,eAAe,EAAE;AACnB,IAAA,OAAOrC,IAAI,CAACpC,KAAK,CAACgF,KAAK,CAAC,CAAA;AAC1B,GAAC,MAAM;AACL,IAAA,OAAOA,KAAK,CAAA;AACd,GAAA;AACF,CAAA;AAMe,cAAA,EACbR,QAAgB,EAChBH,UAAkB,EAClBsB,SAAyB,EACzB7C,IAAa,GAAG,EAAE,EACV;EACR,IAAI,CAACJ,uBAAuB,EAAE;AAC5BA,IAAAA,uBAAuB,GAAG,IAAI,CAAA;IAE9B,MAAM3C,OAAO,GACX,qGAAqG,CAAA;IAEvG,IAAI9B,OAAO,CAAC2H,WAAW,EAAE;AAGvB3H,MAAAA,OAAO,CAAC2H,WAAW,CAAC7F,OAAO,EAAE,oBAAoB,CAAC,CAAA;AACpD,KAAC,MAAM;AACL,MAAA,MAAM8F,gBAAgB,GAAG,IAAIC,KAAK,CAAC/F,OAAO,CAAC,CAAA;MAC3C8F,gBAAgB,CAACE,IAAI,GAAG,oBAAoB,CAAA;MAC5CC,OAAO,CAACC,IAAI,CAAC,IAAIH,KAAK,CAAC/F,OAAO,CAAC,CAAC,CAAA;AAClC,KAAA;AACF,GAAA;EAEA4F,SAAS,GAAG7B,IAAI,CAACC,GAAG,CAAC4B,SAAS,EAAE,CAAC,CAAC,CAAA;AAElC,EAAA,MAAMO,QAAsB,GAAG;AAC7B7C,IAAAA,KAAK,EAAE;AAAEF,MAAAA,MAAM,EAAEwC,SAAS;AAAEvC,MAAAA,IAAI,EAAEiB,UAAAA;AAAW,KAAA;GAC9C,CAAA;AAED,EAAA,OAAOE,gBAAgB,CAACC,QAAQ,EAAE0B,QAAQ,EAAEpD,IAAI,CAAC,CAAA;AACnD;;;;;;"} \ No newline at end of file diff --git a/node_modules/@babel/code-frame/package.json b/node_modules/@babel/code-frame/package.json new file mode 100644 index 00000000..d78a9474 --- /dev/null +++ b/node_modules/@babel/code-frame/package.json @@ -0,0 +1,32 @@ +{ + "name": "@babel/code-frame", + "version": "7.29.0", + "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/helper-validator-identifier": "^7.28.5", + "js-tokens": "^4.0.0", + "picocolors": "^1.1.1" + }, + "devDependencies": { + "charcodes": "^0.2.0", + "import-meta-resolve": "^4.1.0", + "strip-ansi": "^4.0.0" + }, + "engines": { + "node": ">=6.9.0" + }, + "type": "commonjs" +} \ No newline at end of file diff --git a/node_modules/@babel/helper-string-parser/LICENSE b/node_modules/@babel/helper-string-parser/LICENSE new file mode 100644 index 00000000..f31575ec --- /dev/null +++ b/node_modules/@babel/helper-string-parser/LICENSE @@ -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. diff --git a/node_modules/@babel/helper-string-parser/README.md b/node_modules/@babel/helper-string-parser/README.md new file mode 100644 index 00000000..771b4700 --- /dev/null +++ b/node_modules/@babel/helper-string-parser/README.md @@ -0,0 +1,19 @@ +# @babel/helper-string-parser + +> A utility package to parse strings + +See our website [@babel/helper-string-parser](https://babeljs.io/docs/babel-helper-string-parser) for more information. + +## Install + +Using npm: + +```sh +npm install --save @babel/helper-string-parser +``` + +or using yarn: + +```sh +yarn add @babel/helper-string-parser +``` diff --git a/node_modules/@babel/helper-string-parser/lib/index.js b/node_modules/@babel/helper-string-parser/lib/index.js new file mode 100644 index 00000000..2d941155 --- /dev/null +++ b/node_modules/@babel/helper-string-parser/lib/index.js @@ -0,0 +1,295 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.readCodePoint = readCodePoint; +exports.readInt = readInt; +exports.readStringContents = readStringContents; +var _isDigit = function isDigit(code) { + return code >= 48 && code <= 57; +}; +const forbiddenNumericSeparatorSiblings = { + decBinOct: new Set([46, 66, 69, 79, 95, 98, 101, 111]), + hex: new Set([46, 88, 95, 120]) +}; +const isAllowedNumericSeparatorSibling = { + bin: ch => ch === 48 || ch === 49, + oct: ch => ch >= 48 && ch <= 55, + dec: ch => ch >= 48 && ch <= 57, + hex: ch => ch >= 48 && ch <= 57 || ch >= 65 && ch <= 70 || ch >= 97 && ch <= 102 +}; +function readStringContents(type, input, pos, lineStart, curLine, errors) { + const initialPos = pos; + const initialLineStart = lineStart; + const initialCurLine = curLine; + let out = ""; + let firstInvalidLoc = null; + let chunkStart = pos; + const { + length + } = input; + for (;;) { + if (pos >= length) { + errors.unterminated(initialPos, initialLineStart, initialCurLine); + out += input.slice(chunkStart, pos); + break; + } + const ch = input.charCodeAt(pos); + if (isStringEnd(type, ch, input, pos)) { + out += input.slice(chunkStart, pos); + break; + } + if (ch === 92) { + out += input.slice(chunkStart, pos); + const res = readEscapedChar(input, pos, lineStart, curLine, type === "template", errors); + if (res.ch === null && !firstInvalidLoc) { + firstInvalidLoc = { + pos, + lineStart, + curLine + }; + } else { + out += res.ch; + } + ({ + pos, + lineStart, + curLine + } = res); + chunkStart = pos; + } else if (ch === 8232 || ch === 8233) { + ++pos; + ++curLine; + lineStart = pos; + } else if (ch === 10 || ch === 13) { + if (type === "template") { + out += input.slice(chunkStart, pos) + "\n"; + ++pos; + if (ch === 13 && input.charCodeAt(pos) === 10) { + ++pos; + } + ++curLine; + chunkStart = lineStart = pos; + } else { + errors.unterminated(initialPos, initialLineStart, initialCurLine); + } + } else { + ++pos; + } + } + return { + pos, + str: out, + firstInvalidLoc, + lineStart, + curLine, + containsInvalid: !!firstInvalidLoc + }; +} +function isStringEnd(type, ch, input, pos) { + if (type === "template") { + return ch === 96 || ch === 36 && input.charCodeAt(pos + 1) === 123; + } + return ch === (type === "double" ? 34 : 39); +} +function readEscapedChar(input, pos, lineStart, curLine, inTemplate, errors) { + const throwOnInvalid = !inTemplate; + pos++; + const res = ch => ({ + pos, + ch, + lineStart, + curLine + }); + const ch = input.charCodeAt(pos++); + switch (ch) { + case 110: + return res("\n"); + case 114: + return res("\r"); + case 120: + { + let code; + ({ + code, + pos + } = readHexChar(input, pos, lineStart, curLine, 2, false, throwOnInvalid, errors)); + return res(code === null ? null : String.fromCharCode(code)); + } + case 117: + { + let code; + ({ + code, + pos + } = readCodePoint(input, pos, lineStart, curLine, throwOnInvalid, errors)); + return res(code === null ? null : String.fromCodePoint(code)); + } + case 116: + return res("\t"); + case 98: + return res("\b"); + case 118: + return res("\u000b"); + case 102: + return res("\f"); + case 13: + if (input.charCodeAt(pos) === 10) { + ++pos; + } + case 10: + lineStart = pos; + ++curLine; + case 8232: + case 8233: + return res(""); + case 56: + case 57: + if (inTemplate) { + return res(null); + } else { + errors.strictNumericEscape(pos - 1, lineStart, curLine); + } + default: + if (ch >= 48 && ch <= 55) { + const startPos = pos - 1; + const match = /^[0-7]+/.exec(input.slice(startPos, pos + 2)); + let octalStr = match[0]; + let octal = parseInt(octalStr, 8); + if (octal > 255) { + octalStr = octalStr.slice(0, -1); + octal = parseInt(octalStr, 8); + } + pos += octalStr.length - 1; + const next = input.charCodeAt(pos); + if (octalStr !== "0" || next === 56 || next === 57) { + if (inTemplate) { + return res(null); + } else { + errors.strictNumericEscape(startPos, lineStart, curLine); + } + } + return res(String.fromCharCode(octal)); + } + return res(String.fromCharCode(ch)); + } +} +function readHexChar(input, pos, lineStart, curLine, len, forceLen, throwOnInvalid, errors) { + const initialPos = pos; + let n; + ({ + n, + pos + } = readInt(input, pos, lineStart, curLine, 16, len, forceLen, false, errors, !throwOnInvalid)); + if (n === null) { + if (throwOnInvalid) { + errors.invalidEscapeSequence(initialPos, lineStart, curLine); + } else { + pos = initialPos - 1; + } + } + return { + code: n, + pos + }; +} +function readInt(input, pos, lineStart, curLine, radix, len, forceLen, allowNumSeparator, errors, bailOnError) { + const start = pos; + const forbiddenSiblings = radix === 16 ? forbiddenNumericSeparatorSiblings.hex : forbiddenNumericSeparatorSiblings.decBinOct; + const isAllowedSibling = radix === 16 ? isAllowedNumericSeparatorSibling.hex : radix === 10 ? isAllowedNumericSeparatorSibling.dec : radix === 8 ? isAllowedNumericSeparatorSibling.oct : isAllowedNumericSeparatorSibling.bin; + let invalid = false; + let total = 0; + for (let i = 0, e = len == null ? Infinity : len; i < e; ++i) { + const code = input.charCodeAt(pos); + let val; + if (code === 95 && allowNumSeparator !== "bail") { + const prev = input.charCodeAt(pos - 1); + const next = input.charCodeAt(pos + 1); + if (!allowNumSeparator) { + if (bailOnError) return { + n: null, + pos + }; + errors.numericSeparatorInEscapeSequence(pos, lineStart, curLine); + } else if (Number.isNaN(next) || !isAllowedSibling(next) || forbiddenSiblings.has(prev) || forbiddenSiblings.has(next)) { + if (bailOnError) return { + n: null, + pos + }; + errors.unexpectedNumericSeparator(pos, lineStart, curLine); + } + ++pos; + continue; + } + if (code >= 97) { + val = code - 97 + 10; + } else if (code >= 65) { + val = code - 65 + 10; + } else if (_isDigit(code)) { + val = code - 48; + } else { + val = Infinity; + } + if (val >= radix) { + if (val <= 9 && bailOnError) { + return { + n: null, + pos + }; + } else if (val <= 9 && errors.invalidDigit(pos, lineStart, curLine, radix)) { + val = 0; + } else if (forceLen) { + val = 0; + invalid = true; + } else { + break; + } + } + ++pos; + total = total * radix + val; + } + if (pos === start || len != null && pos - start !== len || invalid) { + return { + n: null, + pos + }; + } + return { + n: total, + pos + }; +} +function readCodePoint(input, pos, lineStart, curLine, throwOnInvalid, errors) { + const ch = input.charCodeAt(pos); + let code; + if (ch === 123) { + ++pos; + ({ + code, + pos + } = readHexChar(input, pos, lineStart, curLine, input.indexOf("}", pos) - pos, true, throwOnInvalid, errors)); + ++pos; + if (code !== null && code > 0x10ffff) { + if (throwOnInvalid) { + errors.invalidCodePoint(pos, lineStart, curLine); + } else { + return { + code: null, + pos + }; + } + } + } else { + ({ + code, + pos + } = readHexChar(input, pos, lineStart, curLine, 4, false, throwOnInvalid, errors)); + } + return { + code, + pos + }; +} + +//# sourceMappingURL=index.js.map diff --git a/node_modules/@babel/helper-string-parser/lib/index.js.map b/node_modules/@babel/helper-string-parser/lib/index.js.map new file mode 100644 index 00000000..cd50797f --- /dev/null +++ b/node_modules/@babel/helper-string-parser/lib/index.js.map @@ -0,0 +1 @@ +{"version":3,"names":["isDigit","code","forbiddenNumericSeparatorSiblings","decBinOct","Set","hex","isAllowedNumericSeparatorSibling","bin","ch","oct","dec","readStringContents","type","input","pos","lineStart","curLine","errors","initialPos","initialLineStart","initialCurLine","out","firstInvalidLoc","chunkStart","length","unterminated","slice","charCodeAt","isStringEnd","res","readEscapedChar","str","containsInvalid","inTemplate","throwOnInvalid","readHexChar","String","fromCharCode","readCodePoint","fromCodePoint","strictNumericEscape","startPos","match","exec","octalStr","octal","parseInt","next","len","forceLen","n","readInt","invalidEscapeSequence","radix","allowNumSeparator","bailOnError","start","forbiddenSiblings","isAllowedSibling","invalid","total","i","e","Infinity","val","prev","numericSeparatorInEscapeSequence","Number","isNaN","has","unexpectedNumericSeparator","_isDigit","invalidDigit","indexOf","invalidCodePoint"],"sources":["../src/index.ts"],"sourcesContent":["// We inline this package\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport * as charCodes from \"charcodes\";\n\n// The following character codes are forbidden from being\n// an immediate sibling of NumericLiteralSeparator _\nconst forbiddenNumericSeparatorSiblings = {\n decBinOct: new Set([\n charCodes.dot,\n charCodes.uppercaseB,\n charCodes.uppercaseE,\n charCodes.uppercaseO,\n charCodes.underscore, // multiple separators are not allowed\n charCodes.lowercaseB,\n charCodes.lowercaseE,\n charCodes.lowercaseO,\n ]),\n hex: new Set([\n charCodes.dot,\n charCodes.uppercaseX,\n charCodes.underscore, // multiple separators are not allowed\n charCodes.lowercaseX,\n ]),\n};\n\nconst isAllowedNumericSeparatorSibling = {\n // 0 - 1\n bin: (ch: number) => ch === charCodes.digit0 || ch === charCodes.digit1,\n\n // 0 - 7\n oct: (ch: number) => ch >= charCodes.digit0 && ch <= charCodes.digit7,\n\n // 0 - 9\n dec: (ch: number) => ch >= charCodes.digit0 && ch <= charCodes.digit9,\n\n // 0 - 9, A - F, a - f,\n hex: (ch: number) =>\n (ch >= charCodes.digit0 && ch <= charCodes.digit9) ||\n (ch >= charCodes.uppercaseA && ch <= charCodes.uppercaseF) ||\n (ch >= charCodes.lowercaseA && ch <= charCodes.lowercaseF),\n};\n\nexport type StringContentsErrorHandlers = EscapedCharErrorHandlers & {\n unterminated(\n initialPos: number,\n initialLineStart: number,\n initialCurLine: number,\n ): void;\n};\n\nexport function readStringContents(\n type: \"single\" | \"double\" | \"template\",\n input: string,\n pos: number,\n lineStart: number,\n curLine: number,\n errors: StringContentsErrorHandlers,\n) {\n const initialPos = pos;\n const initialLineStart = lineStart;\n const initialCurLine = curLine;\n\n let out = \"\";\n let firstInvalidLoc = null;\n let chunkStart = pos;\n const { length } = input;\n for (;;) {\n if (pos >= length) {\n errors.unterminated(initialPos, initialLineStart, initialCurLine);\n out += input.slice(chunkStart, pos);\n break;\n }\n const ch = input.charCodeAt(pos);\n if (isStringEnd(type, ch, input, pos)) {\n out += input.slice(chunkStart, pos);\n break;\n }\n if (ch === charCodes.backslash) {\n out += input.slice(chunkStart, pos);\n const res = readEscapedChar(\n input,\n pos,\n lineStart,\n curLine,\n type === \"template\",\n errors,\n );\n if (res.ch === null && !firstInvalidLoc) {\n firstInvalidLoc = { pos, lineStart, curLine };\n } else {\n out += res.ch;\n }\n ({ pos, lineStart, curLine } = res);\n chunkStart = pos;\n } else if (\n ch === charCodes.lineSeparator ||\n ch === charCodes.paragraphSeparator\n ) {\n ++pos;\n ++curLine;\n lineStart = pos;\n } else if (ch === charCodes.lineFeed || ch === charCodes.carriageReturn) {\n if (type === \"template\") {\n out += input.slice(chunkStart, pos) + \"\\n\";\n ++pos;\n if (\n ch === charCodes.carriageReturn &&\n input.charCodeAt(pos) === charCodes.lineFeed\n ) {\n ++pos;\n }\n ++curLine;\n chunkStart = lineStart = pos;\n } else {\n errors.unterminated(initialPos, initialLineStart, initialCurLine);\n }\n } else {\n ++pos;\n }\n }\n return process.env.BABEL_8_BREAKING\n ? { pos, str: out, firstInvalidLoc, lineStart, curLine }\n : {\n pos,\n str: out,\n firstInvalidLoc,\n lineStart,\n curLine,\n containsInvalid: !!firstInvalidLoc,\n };\n}\n\nfunction isStringEnd(\n type: \"single\" | \"double\" | \"template\",\n ch: number,\n input: string,\n pos: number,\n) {\n if (type === \"template\") {\n return (\n ch === charCodes.graveAccent ||\n (ch === charCodes.dollarSign &&\n input.charCodeAt(pos + 1) === charCodes.leftCurlyBrace)\n );\n }\n return (\n ch === (type === \"double\" ? charCodes.quotationMark : charCodes.apostrophe)\n );\n}\n\ntype EscapedCharErrorHandlers = HexCharErrorHandlers &\n CodePointErrorHandlers & {\n strictNumericEscape(pos: number, lineStart: number, curLine: number): void;\n };\n\nfunction readEscapedChar(\n input: string,\n pos: number,\n lineStart: number,\n curLine: number,\n inTemplate: boolean,\n errors: EscapedCharErrorHandlers,\n) {\n const throwOnInvalid = !inTemplate;\n pos++; // skip '\\'\n\n const res = (ch: string | null) => ({ pos, ch, lineStart, curLine });\n\n const ch = input.charCodeAt(pos++);\n switch (ch) {\n case charCodes.lowercaseN:\n return res(\"\\n\");\n case charCodes.lowercaseR:\n return res(\"\\r\");\n case charCodes.lowercaseX: {\n let code;\n ({ code, pos } = readHexChar(\n input,\n pos,\n lineStart,\n curLine,\n 2,\n false,\n throwOnInvalid,\n errors,\n ));\n return res(code === null ? null : String.fromCharCode(code));\n }\n case charCodes.lowercaseU: {\n let code;\n ({ code, pos } = readCodePoint(\n input,\n pos,\n lineStart,\n curLine,\n throwOnInvalid,\n errors,\n ));\n return res(code === null ? null : String.fromCodePoint(code));\n }\n case charCodes.lowercaseT:\n return res(\"\\t\");\n case charCodes.lowercaseB:\n return res(\"\\b\");\n case charCodes.lowercaseV:\n return res(\"\\u000b\");\n case charCodes.lowercaseF:\n return res(\"\\f\");\n case charCodes.carriageReturn:\n if (input.charCodeAt(pos) === charCodes.lineFeed) {\n ++pos;\n }\n // fall through\n case charCodes.lineFeed:\n lineStart = pos;\n ++curLine;\n // fall through\n case charCodes.lineSeparator:\n case charCodes.paragraphSeparator:\n return res(\"\");\n case charCodes.digit8:\n case charCodes.digit9:\n if (inTemplate) {\n return res(null);\n } else {\n errors.strictNumericEscape(pos - 1, lineStart, curLine);\n }\n // fall through\n default:\n if (ch >= charCodes.digit0 && ch <= charCodes.digit7) {\n const startPos = pos - 1;\n const match = /^[0-7]+/.exec(input.slice(startPos, pos + 2));\n\n let octalStr = match[0];\n\n let octal = parseInt(octalStr, 8);\n if (octal > 255) {\n octalStr = octalStr.slice(0, -1);\n octal = parseInt(octalStr, 8);\n }\n pos += octalStr.length - 1;\n const next = input.charCodeAt(pos);\n if (\n octalStr !== \"0\" ||\n next === charCodes.digit8 ||\n next === charCodes.digit9\n ) {\n if (inTemplate) {\n return res(null);\n } else {\n errors.strictNumericEscape(startPos, lineStart, curLine);\n }\n }\n\n return res(String.fromCharCode(octal));\n }\n\n return res(String.fromCharCode(ch));\n }\n}\n\ntype HexCharErrorHandlers = IntErrorHandlers & {\n invalidEscapeSequence(pos: number, lineStart: number, curLine: number): void;\n};\n\n// Used to read character escape sequences ('\\x', '\\u').\nfunction readHexChar(\n input: string,\n pos: number,\n lineStart: number,\n curLine: number,\n len: number,\n forceLen: boolean,\n throwOnInvalid: boolean,\n errors: HexCharErrorHandlers,\n) {\n const initialPos = pos;\n let n;\n ({ n, pos } = readInt(\n input,\n pos,\n lineStart,\n curLine,\n 16,\n len,\n forceLen,\n false,\n errors,\n /* bailOnError */ !throwOnInvalid,\n ));\n if (n === null) {\n if (throwOnInvalid) {\n errors.invalidEscapeSequence(initialPos, lineStart, curLine);\n } else {\n pos = initialPos - 1;\n }\n }\n return { code: n, pos };\n}\n\nexport type IntErrorHandlers = {\n numericSeparatorInEscapeSequence(\n pos: number,\n lineStart: number,\n curLine: number,\n ): void;\n unexpectedNumericSeparator(\n pos: number,\n lineStart: number,\n curLine: number,\n ): void;\n // It can return \"true\" to indicate that the error was handled\n // and the int parsing should continue.\n invalidDigit(\n pos: number,\n lineStart: number,\n curLine: number,\n radix: number,\n ): boolean;\n};\n\nexport function readInt(\n input: string,\n pos: number,\n lineStart: number,\n curLine: number,\n radix: number,\n len: number | undefined,\n forceLen: boolean,\n allowNumSeparator: boolean | \"bail\",\n errors: IntErrorHandlers,\n bailOnError: boolean,\n) {\n const start = pos;\n const forbiddenSiblings =\n radix === 16\n ? forbiddenNumericSeparatorSiblings.hex\n : forbiddenNumericSeparatorSiblings.decBinOct;\n const isAllowedSibling =\n radix === 16\n ? isAllowedNumericSeparatorSibling.hex\n : radix === 10\n ? isAllowedNumericSeparatorSibling.dec\n : radix === 8\n ? isAllowedNumericSeparatorSibling.oct\n : isAllowedNumericSeparatorSibling.bin;\n\n let invalid = false;\n let total = 0;\n\n for (let i = 0, e = len == null ? Infinity : len; i < e; ++i) {\n const code = input.charCodeAt(pos);\n let val;\n\n if (code === charCodes.underscore && allowNumSeparator !== \"bail\") {\n const prev = input.charCodeAt(pos - 1);\n const next = input.charCodeAt(pos + 1);\n\n if (!allowNumSeparator) {\n if (bailOnError) return { n: null, pos };\n errors.numericSeparatorInEscapeSequence(pos, lineStart, curLine);\n } else if (\n Number.isNaN(next) ||\n !isAllowedSibling(next) ||\n forbiddenSiblings.has(prev) ||\n forbiddenSiblings.has(next)\n ) {\n if (bailOnError) return { n: null, pos };\n errors.unexpectedNumericSeparator(pos, lineStart, curLine);\n }\n\n // Ignore this _ character\n ++pos;\n continue;\n }\n\n if (code >= charCodes.lowercaseA) {\n val = code - charCodes.lowercaseA + charCodes.lineFeed;\n } else if (code >= charCodes.uppercaseA) {\n val = code - charCodes.uppercaseA + charCodes.lineFeed;\n } else if (charCodes.isDigit(code)) {\n val = code - charCodes.digit0; // 0-9\n } else {\n val = Infinity;\n }\n if (val >= radix) {\n // If we found a digit which is too big, errors.invalidDigit can return true to avoid\n // breaking the loop (this is used for error recovery).\n if (val <= 9 && bailOnError) {\n return { n: null, pos };\n } else if (\n val <= 9 &&\n errors.invalidDigit(pos, lineStart, curLine, radix)\n ) {\n val = 0;\n } else if (forceLen) {\n val = 0;\n invalid = true;\n } else {\n break;\n }\n }\n ++pos;\n total = total * radix + val;\n }\n if (pos === start || (len != null && pos - start !== len) || invalid) {\n return { n: null, pos };\n }\n\n return { n: total, pos };\n}\n\nexport type CodePointErrorHandlers = HexCharErrorHandlers & {\n invalidCodePoint(pos: number, lineStart: number, curLine: number): void;\n};\n\nexport function readCodePoint(\n input: string,\n pos: number,\n lineStart: number,\n curLine: number,\n throwOnInvalid: boolean,\n errors: CodePointErrorHandlers,\n) {\n const ch = input.charCodeAt(pos);\n let code;\n\n if (ch === charCodes.leftCurlyBrace) {\n ++pos;\n ({ code, pos } = readHexChar(\n input,\n pos,\n lineStart,\n curLine,\n input.indexOf(\"}\", pos) - pos,\n true,\n throwOnInvalid,\n errors,\n ));\n ++pos;\n if (code !== null && code > 0x10ffff) {\n if (throwOnInvalid) {\n errors.invalidCodePoint(pos, lineStart, curLine);\n } else {\n return { code: null, pos };\n }\n }\n } else {\n ({ code, pos } = readHexChar(\n input,\n pos,\n lineStart,\n curLine,\n 4,\n false,\n throwOnInvalid,\n errors,\n ));\n }\n return { code, pos };\n}\n"],"mappings":";;;;;;;;eAAA,SAASA,OAAOA,CAACC,IAAI,EAAE;EACrB,OAAOA,IAAI,MAAU,IAAIA,IAAI,MAAU;AACzC,CAAC;AAID,MAAMC,iCAAiC,GAAG;EACxCC,SAAS,EAAE,IAAIC,GAAG,CAAS,kCAS1B,CAAC;EACFC,GAAG,EAAE,IAAID,GAAG,CAAS,iBAKpB;AACH,CAAC;AAED,MAAME,gCAAgC,GAAG;EAEvCC,GAAG,EAAGC,EAAU,IAAKA,EAAE,OAAqB,IAAIA,EAAE,OAAqB;EAGvEC,GAAG,EAAGD,EAAU,IAAKA,EAAE,MAAoB,IAAIA,EAAE,MAAoB;EAGrEE,GAAG,EAAGF,EAAU,IAAKA,EAAE,MAAoB,IAAIA,EAAE,MAAoB;EAGrEH,GAAG,EAAGG,EAAU,IACbA,EAAE,MAAoB,IAAIA,EAAE,MAAoB,IAChDA,EAAE,MAAwB,IAAIA,EAAE,MAAyB,IACzDA,EAAE,MAAwB,IAAIA,EAAE;AACrC,CAAC;AAUM,SAASG,kBAAkBA,CAChCC,IAAsC,EACtCC,KAAa,EACbC,GAAW,EACXC,SAAiB,EACjBC,OAAe,EACfC,MAAmC,EACnC;EACA,MAAMC,UAAU,GAAGJ,GAAG;EACtB,MAAMK,gBAAgB,GAAGJ,SAAS;EAClC,MAAMK,cAAc,GAAGJ,OAAO;EAE9B,IAAIK,GAAG,GAAG,EAAE;EACZ,IAAIC,eAAe,GAAG,IAAI;EAC1B,IAAIC,UAAU,GAAGT,GAAG;EACpB,MAAM;IAAEU;EAAO,CAAC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5D,GAAG,EAAEC,SAAS,EAAEC,OAAO,CAAC;MAClD,CAAC,MAAM;QACL,OAAO;UAAEf,IAAI,EAAE,IAAI;UAAEa;QAAI,CAAC;MAC5B;IACF;EACF,CAAC,MAAM;IACL,CAAC;MAAEb,IAAI;MAAEa;IAAI,CAAC,GAAGqB,WAAW,CAC1BtB,KAAK,EACLC,GAAG,EACHC,SAAS,EACTC,OAAO,EACP,CAAC,EACD,KAAK,EACLkB,cAAc,EACdjB,MACF,CAAC;EACH;EACA,OAAO;IAAEhB,IAAI;IAAEa;EAAI,CAAC;AACtB","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/helper-string-parser/package.json b/node_modules/@babel/helper-string-parser/package.json new file mode 100644 index 00000000..c4c86e4f --- /dev/null +++ b/node_modules/@babel/helper-string-parser/package.json @@ -0,0 +1,31 @@ +{ + "name": "@babel/helper-string-parser", + "version": "7.27.1", + "description": "A utility package to parse strings", + "repository": { + "type": "git", + "url": "https://github.com/babel/babel.git", + "directory": "packages/babel-helper-string-parser" + }, + "homepage": "https://babel.dev/docs/en/next/babel-helper-string-parser", + "license": "MIT", + "publishConfig": { + "access": "public" + }, + "main": "./lib/index.js", + "devDependencies": { + "charcodes": "^0.2.0" + }, + "engines": { + "node": ">=6.9.0" + }, + "author": "The Babel Team (https://babel.dev/team)", + "exports": { + ".": { + "types": "./lib/index.d.ts", + "default": "./lib/index.js" + }, + "./package.json": "./package.json" + }, + "type": "commonjs" +} \ No newline at end of file diff --git a/node_modules/@babel/helper-validator-identifier/LICENSE b/node_modules/@babel/helper-validator-identifier/LICENSE new file mode 100644 index 00000000..f31575ec --- /dev/null +++ b/node_modules/@babel/helper-validator-identifier/LICENSE @@ -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. diff --git a/node_modules/@babel/helper-validator-identifier/README.md b/node_modules/@babel/helper-validator-identifier/README.md new file mode 100644 index 00000000..05c19e64 --- /dev/null +++ b/node_modules/@babel/helper-validator-identifier/README.md @@ -0,0 +1,19 @@ +# @babel/helper-validator-identifier + +> Validate identifier/keywords name + +See our website [@babel/helper-validator-identifier](https://babeljs.io/docs/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 +``` diff --git a/node_modules/@babel/helper-validator-identifier/lib/identifier.js b/node_modules/@babel/helper-validator-identifier/lib/identifier.js new file mode 100644 index 00000000..b12e6e4b --- /dev/null +++ b/node_modules/@babel/helper-validator-identifier/lib/identifier.js @@ -0,0 +1,70 @@ +"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-\u088f\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\u0c5c\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdc-\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-\u1c8a\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-\ua7dc\ua7f1-\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 = "\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\u0897-\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-\u1add\u1ae0-\u1aeb\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\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\u30fb\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\uff65"; +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, 4, 51, 13, 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, 7, 25, 39, 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, 39, 27, 10, 22, 251, 41, 7, 1, 17, 5, 57, 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, 31, 9, 2, 0, 3, 0, 2, 37, 2, 0, 26, 0, 2, 0, 45, 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, 200, 32, 32, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 24, 43, 261, 18, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 26, 3994, 6, 582, 6842, 29, 1763, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 433, 44, 212, 63, 33, 24, 3, 24, 45, 74, 6, 0, 67, 12, 65, 1, 2, 0, 15, 4, 10, 7381, 42, 31, 98, 114, 8702, 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, 229, 29, 3, 0, 208, 30, 2, 2, 2, 1, 2, 6, 3, 4, 10, 1, 225, 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, 4381, 3, 5773, 3, 7472, 16, 621, 2467, 541, 1507, 4938, 6, 8489]; +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, 7, 9, 32, 4, 318, 1, 78, 5, 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, 68, 8, 2, 0, 3, 0, 2, 3, 2, 4, 2, 0, 15, 1, 83, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 7, 19, 58, 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, 199, 7, 137, 9, 54, 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, 55, 9, 266, 3, 10, 1, 2, 0, 49, 6, 4, 4, 14, 10, 5350, 0, 7, 14, 11465, 27, 2343, 9, 87, 9, 39, 4, 60, 6, 26, 9, 535, 9, 470, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4178, 9, 519, 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, 245, 1, 2, 9, 233, 0, 3, 0, 8, 1, 6, 0, 475, 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 diff --git a/node_modules/@babel/helper-validator-identifier/lib/identifier.js.map b/node_modules/@babel/helper-validator-identifier/lib/identifier.js.map new file mode 100644 index 00000000..71d32ff2 --- /dev/null +++ b/node_modules/@babel/helper-validator-identifier/lib/identifier.js.map @@ -0,0 +1 @@ +{"version":3,"names":["nonASCIIidentifierStartChars","nonASCIIidentifierChars","nonASCIIidentifierStart","RegExp","nonASCIIidentifier","astralIdentifierStartCodes","astralIdentifierCodes","isInAstralSet","code","set","pos","i","length","isIdentifierStart","test","String","fromCharCode","isIdentifierChar","isIdentifierName","name","isFirst","cp","charCodeAt","trail"],"sources":["../src/identifier.ts"],"sourcesContent":["// We inline this package\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport * as charCodes from \"charcodes\";\n\n// ## Character categories\n\n// Big ugly regular expressions that match characters in the\n// whitespace, identifier, and identifier-start categories. These\n// are only applied when a character is found to actually have a\n// code point between 0x80 and 0xffff.\n// Generated by `scripts/generate-identifier-regex.cjs`.\n\n/* prettier-ignore */\nlet 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-\\u088f\\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\\u0c5c\\u0c5d\\u0c60\\u0c61\\u0c80\\u0c85-\\u0c8c\\u0c8e-\\u0c90\\u0c92-\\u0ca8\\u0caa-\\u0cb3\\u0cb5-\\u0cb9\\u0cbd\\u0cdc-\\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-\\u1c8a\\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-\\ua7dc\\ua7f1-\\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\";\n/* prettier-ignore */\nlet nonASCIIidentifierChars = \"\\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\\u0897-\\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-\\u1add\\u1ae0-\\u1aeb\\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\\u200c\\u200d\\u203f\\u2040\\u2054\\u20d0-\\u20dc\\u20e1\\u20e5-\\u20f0\\u2cef-\\u2cf1\\u2d7f\\u2de0-\\u2dff\\u302a-\\u302f\\u3099\\u309a\\u30fb\\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\\uff65\";\n\nconst nonASCIIidentifierStart = new RegExp(\n \"[\" + nonASCIIidentifierStartChars + \"]\",\n);\nconst nonASCIIidentifier = new RegExp(\n \"[\" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + \"]\",\n);\n\nnonASCIIidentifierStartChars = nonASCIIidentifierChars = null;\n\n// These are a run-length and offset-encoded representation of the\n// >0xffff code points that are a valid part of identifiers. The\n// offset starts at 0x10000, and each pair of numbers represents an\n// offset to the next range, and then a size of the range. They were\n// generated by `scripts/generate-identifier-regex.cjs`.\n/* prettier-ignore */\nconst 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,4,51,13,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,7,25,39,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,39,27,10,22,251,41,7,1,17,5,57,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,31,9,2,0,3,0,2,37,2,0,26,0,2,0,45,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,200,32,32,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,24,43,261,18,16,0,2,12,2,33,125,0,80,921,103,110,18,195,2637,96,16,1071,18,5,26,3994,6,582,6842,29,1763,568,8,30,18,78,18,29,19,47,17,3,32,20,6,18,433,44,212,63,33,24,3,24,45,74,6,0,67,12,65,1,2,0,15,4,10,7381,42,31,98,114,8702,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,229,29,3,0,208,30,2,2,2,1,2,6,3,4,10,1,225,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,4381,3,5773,3,7472,16,621,2467,541,1507,4938,6,8489];\n/* prettier-ignore */\nconst 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,7,9,32,4,318,1,78,5,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,68,8,2,0,3,0,2,3,2,4,2,0,15,1,83,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,7,19,58,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,199,7,137,9,54,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,55,9,266,3,10,1,2,0,49,6,4,4,14,10,5350,0,7,14,11465,27,2343,9,87,9,39,4,60,6,26,9,535,9,470,0,2,54,8,3,82,0,12,1,19628,1,4178,9,519,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,245,1,2,9,233,0,3,0,8,1,6,0,475,6,110,6,6,9,4759,9,787719,239];\n\n// This has a complexity linear to the value of the code. The\n// assumption is that looking up astral identifier characters is\n// rare.\nfunction isInAstralSet(code: number, set: readonly number[]): boolean {\n let pos = 0x10000;\n for (let i = 0, length = set.length; i < length; i += 2) {\n pos += set[i];\n if (pos > code) return false;\n\n pos += set[i + 1];\n if (pos >= code) return true;\n }\n return false;\n}\n\n// Test whether a given character code starts an identifier.\n\nexport function isIdentifierStart(code: number): boolean {\n if (code < charCodes.uppercaseA) return code === charCodes.dollarSign;\n if (code <= charCodes.uppercaseZ) return true;\n if (code < charCodes.lowercaseA) return code === charCodes.underscore;\n if (code <= charCodes.lowercaseZ) return true;\n if (code <= 0xffff) {\n return (\n code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code))\n );\n }\n return isInAstralSet(code, astralIdentifierStartCodes);\n}\n\n// Test whether a given character is part of an identifier.\n\nexport function isIdentifierChar(code: number): boolean {\n if (code < charCodes.digit0) return code === charCodes.dollarSign;\n if (code < charCodes.colon) return true;\n if (code < charCodes.uppercaseA) return false;\n if (code <= charCodes.uppercaseZ) return true;\n if (code < charCodes.lowercaseA) return code === charCodes.underscore;\n if (code <= charCodes.lowercaseZ) return true;\n if (code <= 0xffff) {\n return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));\n }\n return (\n isInAstralSet(code, astralIdentifierStartCodes) ||\n isInAstralSet(code, astralIdentifierCodes)\n );\n}\n\n// Test whether a given string is a valid identifier name\n\nexport function isIdentifierName(name: string): boolean {\n let isFirst = true;\n for (let i = 0; i < name.length; i++) {\n // The implementation is based on\n // https://source.chromium.org/chromium/chromium/src/+/master:v8/src/builtins/builtins-string-gen.cc;l=1455;drc=221e331b49dfefadbc6fa40b0c68e6f97606d0b3;bpv=0;bpt=1\n // We reimplement `codePointAt` because `codePointAt` is a V8 builtin which is not inlined by TurboFan (as of M91)\n // since `name` is mostly ASCII, an inlined `charCodeAt` wins here\n let cp = name.charCodeAt(i);\n if ((cp & 0xfc00) === 0xd800 && i + 1 < name.length) {\n const trail = name.charCodeAt(++i);\n if ((trail & 0xfc00) === 0xdc00) {\n cp = 0x10000 + ((cp & 0x3ff) << 10) + (trail & 0x3ff);\n }\n }\n if (isFirst) {\n isFirst = false;\n if (!isIdentifierStart(cp)) {\n return false;\n }\n } else if (!isIdentifierChar(cp)) {\n return false;\n }\n }\n return !isFirst;\n}\n"],"mappings":";;;;;;;;AAaA,IAAIA,4BAA4B,GAAG,spIAAspI;AAEzrI,IAAIC,uBAAuB,GAAG,4lFAA4lF;AAE1nF,MAAMC,uBAAuB,GAAG,IAAIC,MAAM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;MAClC,IAAI,CAACY,KAAK,GAAG,MAAM,MAAM,MAAM,EAAE;QAC/BF,EAAE,GAAG,OAAO,IAAI,CAACA,EAAE,GAAG,KAAK,KAAK,EAAE,CAAC,IAAIE,KAAK,GAAG,KAAK,CAAC;MACvD;IACF;IACA,IAAIH,OAAO,EAAE;MACXA,OAAO,GAAG,KAAK;MACf,IAAI,CAACP,iBAAiB,CAACQ,EAAE,CAAC,EAAE;QAC1B,OAAO,KAAK;MACd;IACF,CAAC,MAAM,IAAI,CAACJ,gBAAgB,CAACI,EAAE,CAAC,EAAE;MAChC,OAAO,KAAK;IACd;EACF;EACA,OAAO,CAACD,OAAO;AACjB","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/helper-validator-identifier/lib/index.js b/node_modules/@babel/helper-validator-identifier/lib/index.js new file mode 100644 index 00000000..76b22822 --- /dev/null +++ b/node_modules/@babel/helper-validator-identifier/lib/index.js @@ -0,0 +1,57 @@ +"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.js"); +var _keyword = require("./keyword.js"); + +//# sourceMappingURL=index.js.map diff --git a/node_modules/@babel/helper-validator-identifier/lib/index.js.map b/node_modules/@babel/helper-validator-identifier/lib/index.js.map new file mode 100644 index 00000000..d985f3b9 --- /dev/null +++ b/node_modules/@babel/helper-validator-identifier/lib/index.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_identifier","require","_keyword"],"sources":["../src/index.ts"],"sourcesContent":["export {\n isIdentifierName,\n isIdentifierChar,\n isIdentifierStart,\n} from \"./identifier.ts\";\nexport {\n isReservedWord,\n isStrictBindOnlyReservedWord,\n isStrictBindReservedWord,\n isStrictReservedWord,\n isKeyword,\n} from \"./keyword.ts\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAAA,WAAA,GAAAC,OAAA;AAKA,IAAAC,QAAA,GAAAD,OAAA","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/helper-validator-identifier/lib/keyword.js b/node_modules/@babel/helper-validator-identifier/lib/keyword.js new file mode 100644 index 00000000..054cf847 --- /dev/null +++ b/node_modules/@babel/helper-validator-identifier/lib/keyword.js @@ -0,0 +1,35 @@ +"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 diff --git a/node_modules/@babel/helper-validator-identifier/lib/keyword.js.map b/node_modules/@babel/helper-validator-identifier/lib/keyword.js.map new file mode 100644 index 00000000..3471f78c --- /dev/null +++ b/node_modules/@babel/helper-validator-identifier/lib/keyword.js.map @@ -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,OAAO,EACP,MAAM,EACN,OAAO,EACP,UAAU,EACV,UAAU,EACV,SAAS,EACT,IAAI,EACJ,MAAM,EACN,SAAS,EACT,KAAK,EACL,UAAU,EACV,IAAI,EACJ,QAAQ,EACR,QAAQ,EACR,OAAO,EACP,KAAK,EACL,KAAK,EACL,OAAO,EACP,OAAO,EACP,MAAM,EACN,KAAK,EACL,MAAM,EACN,OAAO,EACP,OAAO,EACP,SAAS,EACT,QAAQ,EACR,QAAQ,EACR,MAAM,EACN,MAAM,EACN,OAAO,EACP,IAAI,EACJ,YAAY,EACZ,QAAQ,EACR,MAAM,EACN,QAAQ,CACT;EACDC,MAAM,EAAE,CACN,YAAY,EACZ,WAAW,EACX,KAAK,EACL,SAAS,EACT,SAAS,EACT,WAAW,EACX,QAAQ,EACR,QAAQ,EACR,OAAO,CACR;EACDC,UAAU,EAAE,CAAC,MAAM,EAAE,WAAW;AAClC,CAAC;AACD,MAAMC,QAAQ,GAAG,IAAIC,GAAG,CAACL,aAAa,CAACC,OAAO,CAAC;AAC/C,MAAMK,sBAAsB,GAAG,IAAID,GAAG,CAACL,aAAa,CAACE,MAAM,CAAC;AAC5D,MAAMK,0BAA0B,GAAG,IAAIF,GAAG,CAACL,aAAa,CAACG,UAAU,CAAC;AAK7D,SAASK,cAAcA,CAACC,IAAY,EAAEC,QAAiB,EAAW;EACvE,OAAQA,QAAQ,IAAID,IAAI,KAAK,OAAO,IAAKA,IAAI,KAAK,MAAM;AAC1D;AAOO,SAASE,oBAAoBA,CAACF,IAAY,EAAEC,QAAiB,EAAW;EAC7E,OAAOF,cAAc,CAACC,IAAI,EAAEC,QAAQ,CAAC,IAAIJ,sBAAsB,CAACM,GAAG,CAACH,IAAI,CAAC;AAC3E;AAMO,SAASI,4BAA4BA,CAACJ,IAAY,EAAW;EAClE,OAAOF,0BAA0B,CAACK,GAAG,CAACH,IAAI,CAAC;AAC7C;AAOO,SAASK,wBAAwBA,CACtCL,IAAY,EACZC,QAAiB,EACR;EACT,OACEC,oBAAoB,CAACF,IAAI,EAAEC,QAAQ,CAAC,IAAIG,4BAA4B,CAACJ,IAAI,CAAC;AAE9E;AAEO,SAASM,SAASA,CAACN,IAAY,EAAW;EAC/C,OAAOL,QAAQ,CAACQ,GAAG,CAACH,IAAI,CAAC;AAC3B","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/helper-validator-identifier/package.json b/node_modules/@babel/helper-validator-identifier/package.json new file mode 100644 index 00000000..1aea38db --- /dev/null +++ b/node_modules/@babel/helper-validator-identifier/package.json @@ -0,0 +1,31 @@ +{ + "name": "@babel/helper-validator-identifier", + "version": "7.28.5", + "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": { + ".": { + "types": "./lib/index.d.ts", + "default": "./lib/index.js" + }, + "./package.json": "./package.json" + }, + "devDependencies": { + "@unicode/unicode-17.0.0": "^1.6.10", + "charcodes": "^0.2.0" + }, + "engines": { + "node": ">=6.9.0" + }, + "author": "The Babel Team (https://babel.dev/team)", + "type": "commonjs" +} \ No newline at end of file diff --git a/node_modules/@babel/parser/CHANGELOG.md b/node_modules/@babel/parser/CHANGELOG.md new file mode 100644 index 00000000..b3840ac8 --- /dev/null +++ b/node_modules/@babel/parser/CHANGELOG.md @@ -0,0 +1,1073 @@ +# Changelog + +> **Tags:** +> - :boom: [Breaking Change] +> - :eyeglasses: [Spec Compliance] +> - :rocket: [New Feature] +> - :bug: [Bug Fix] +> - :memo: [Documentation] +> - :house: [Internal] +> - :nail_care: [Polish] + +> Semver Policy: https://github.com/babel/babel/tree/main/packages/babel-parser#semver + +_Note: Gaps between patch versions are faulty, broken or test releases._ + +See the [Babel Changelog](https://github.com/babel/babel/blob/main/CHANGELOG.md) for the pre-6.8.0 version Changelog. + +## 6.17.1 (2017-05-10) + +### :bug: Bug Fix + * Fix typo in flow spread operator error (Brian Ng) + * Fixed invalid number literal parsing ([#473](https://github.com/babel/babylon/pull/473)) (Alex Kuzmenko) + * Fix number parser ([#433](https://github.com/babel/babylon/pull/433)) (Alex Kuzmenko) + * Ensure non pattern shorthand props are checked for reserved words ([#479](https://github.com/babel/babylon/pull/479)) (Brian Ng) + * Remove jsx context when parsing arrow functions ([#475](https://github.com/babel/babylon/pull/475)) (Brian Ng) + * Allow super in class properties ([#499](https://github.com/babel/babylon/pull/499)) (Brian Ng) + * Allow flow class field to be named constructor ([#510](https://github.com/babel/babylon/pull/510)) (Brian Ng) + +## 6.17.0 (2017-04-20) + +### :bug: Bug Fix + * Cherry-pick #418 to 6.x ([#476](https://github.com/babel/babylon/pull/476)) (Sebastian McKenzie) + * Add support for invalid escapes in tagged templates ([#274](https://github.com/babel/babylon/pull/274)) (Kevin Gibbons) + * Throw error if new.target is used outside of a function ([#402](https://github.com/babel/babylon/pull/402)) (Brian Ng) + * Fix parsing of class properties ([#351](https://github.com/babel/babylon/pull/351)) (Kevin Gibbons) + * Fix parsing yield with dynamicImport ([#383](https://github.com/babel/babylon/pull/383)) (Brian Ng) + * Ensure consistent start args for parseParenItem ([#386](https://github.com/babel/babylon/pull/386)) (Brian Ng) + +## 7.0.0-beta.8 (2017-04-04) + +### New Feature +* Add support for flow type spread (#418) (Conrad Buck) +* Allow statics in flow interfaces (#427) (Brian Ng) + +### Bug Fix +* Fix predicate attachment to match flow parser (#428) (Brian Ng) +* Add extra.raw back to JSXText and JSXAttribute (#344) (Alex Rattray) +* Fix rest parameters with array and objects (#424) (Brian Ng) +* Fix number parser (#433) (Alex Kuzmenko) + +### Docs +* Fix CONTRIBUTING.md [skip ci] (#432) (Alex Kuzmenko) + +### Internal +* Use babel-register script when running babel smoke tests (#442) (Brian Ng) + +## 7.0.0-beta.7 (2017-03-22) + +### Spec Compliance +* Remove babylon plugin for template revision since it's stage-4 (#426) (Henry Zhu) + +### Bug Fix + +* Fix push-pop logic in flow (#405) (Daniel Tschinder) + +## 7.0.0-beta.6 (2017-03-21) + +### New Feature +* Add support for invalid escapes in tagged templates (#274) (Kevin Gibbons) + +### Polish +* Improves error message when super is called outside of constructor (#408) (Arshabh Kumar Agarwal) + +### Docs + +* [7.0] Moved value field in spec from ObjectMember to ObjectProperty as ObjectMethod's don't have it (#415) [skip ci] (James Browning) + +## 7.0.0-beta.5 (2017-03-21) + +### Bug Fix +* Throw error if new.target is used outside of a function (#402) (Brian Ng) +* Fix parsing of class properties (#351) (Kevin Gibbons) + +### Other + * Test runner: Detect extra property in 'actual' but not in 'expected'. (#407) (Andy) + * Optimize travis builds (#419) (Daniel Tschinder) + * Update codecov to 2.0 (#412) (Daniel Tschinder) + * Fix spec for ClassMethod: It doesn't have a function, it *is* a function. (#406) [skip ci] (Andy) + * Changed Non-existent RestPattern to RestElement which is what is actually parsed (#409) [skip ci] (James Browning) + * Upgrade flow to 0.41 (Daniel Tschinder) + * Fix watch command (#403) (Brian Ng) + * Update yarn lock (Daniel Tschinder) + * Fix watch command (#403) (Brian Ng) + * chore(package): update flow-bin to version 0.41.0 (#395) (greenkeeper[bot]) + * Add estree test for correct order of directives (Daniel Tschinder) + * Add DoExpression to spec (#364) (Alex Kuzmenko) + * Mention cloning of repository in CONTRIBUTING.md (#391) [skip ci] (Sumedh Nimkarde) + * Explain how to run only one test (#389) [skip ci] (Aaron Ang) + + ## 7.0.0-beta.4 (2017-03-01) + +* Don't consume async when checking for async func decl (#377) (Brian Ng) +* add `ranges` option [skip ci] (Henry Zhu) +* Don't parse class properties without initializers when classProperties is disabled and Flow is enabled (#300) (Andrew Levine) + +## 7.0.0-beta.3 (2017-02-28) + +- [7.0] Change RestProperty/SpreadProperty to RestElement/SpreadElement (#384) +- Merge changes from 6.x + +## 7.0.0-beta.2 (2017-02-20) + +- estree: correctly change literals in all cases (#368) (Daniel Tschinder) + +## 7.0.0-beta.1 (2017-02-20) + +- Fix negative number literal typeannotations (#366) (Daniel Tschinder) +- Update contributing with more test info [skip ci] (#355) (Brian Ng) + +## 7.0.0-beta.0 (2017-02-15) + +- Reintroduce Variance node (#333) (Daniel Tschinder) +- Rename NumericLiteralTypeAnnotation to NumberLiteralTypeAnnotation (#332) (Charles Pick) +- [7.0] Remove ForAwaitStatement, add await flag to ForOfStatement (#349) (Brandon Dail) +- chore(package): update ava to version 0.18.0 (#345) (greenkeeper[bot]) +- chore(package): update babel-plugin-istanbul to version 4.0.0 (#350) (greenkeeper[bot]) +- Change location of ObjectTypeIndexer to match flow (#228) (Daniel Tschinder) +- Rename flow AST Type ExistentialTypeParam to ExistsTypeAnnotation (#322) (Toru Kobayashi) +- Revert "Temporary rollback for erroring on trailing comma with spread (#154)" (#290) (Daniel Tschinder) +- Remove classConstructorCall plugin (#291) (Brian Ng) +- Update yarn.lock (Daniel Tschinder) +- Update cross-env to 3.x (Daniel Tschinder) +- [7.0] Remove node 0.10, 0.12 and 5 from Travis (#284) (Sergey Rubanov) +- Remove `String.fromCodePoint` shim (#279) (Mathias Bynens) + +## 6.16.1 (2017-02-23) + +### :bug: Regression + +- Revert "Fix export default async function to be FunctionDeclaration" ([#375](https://github.com/babel/babylon/pull/375)) + +Need to modify Babel for this AST node change, so moving to 7.0. + +- Revert "Don't parse class properties without initializers when classProperties plugin is disabled, and Flow is enabled" ([#376](https://github.com/babel/babylon/pull/376)) + +[react-native](https://github.com/facebook/react-native/issues/12542) broke with this so we reverted. + +## 6.16.0 (2017-02-23) + +### :rocket: New Feature + +***ESTree*** compatibility as plugin ([#277](https://github.com/babel/babylon/pull/277)) (Daniel Tschinder) + +We finally introduce a new compatibility layer for ESTree. To put babylon into ESTree-compatible mode the new plugin `estree` can be enabled. In this mode the parser will output an AST that is compliant to the specs of [ESTree](https://github.com/estree/estree/) + +We highly recommend everyone who uses babylon outside of babel to use this plugin. This will make it much easier for users to switch between different ESTree-compatible parsers. We so far tested several projects with different parsers and exchanged their parser to babylon and in nearly all cases it worked out of the box. Some other estree-compatible parsers include `acorn`, `esprima`, `espree`, `flow-parser`, etc. + +To enable `estree` mode simply add the plugin in the config: +```json +{ + "plugins": [ "estree" ] +} +``` + +If you want to migrate your project from non-ESTree mode to ESTree, have a look at our [Readme](https://github.com/babel/babylon/#output), where all deviations are mentioned. + +Add a parseExpression public method ([#213](https://github.com/babel/babylon/pull/213)) (jeromew) + +Babylon exports a new function to parse a single expression + +```js +import { parseExpression } from 'babylon'; + +const ast = parseExpression('x || y && z', options); +``` + +The returned AST will only consist of the expression. The options are the same as for `parse()` + +Add startLine option ([#346](https://github.com/babel/babylon/pull/346)) (Raphael Mu) + +A new option was added to babylon allowing to change the initial linenumber for the first line which is usually `1`. +Changing this for example to `100` will make line `1` of the input source to be marked as line `100`, line `2` as `101`, line `3` as `102`, ... + +Function predicate declaration ([#103](https://github.com/babel/babylon/pull/103)) (Panagiotis Vekris) + +Added support for function predicates which flow introduced in version 0.33.0 + +```js +declare function is_number(x: mixed): boolean %checks(typeof x === "number"); +``` + +Allow imports in declare module ([#315](https://github.com/babel/babylon/pull/315)) (Daniel Tschinder) + +Added support for imports within module declarations which flow introduced in version 0.37.0 + +```js +declare module "C" { + import type { DT } from "D"; + declare export type CT = { D: DT }; +} +``` + +### :eyeglasses: Spec Compliance + +Forbid semicolons after decorators in classes ([#352](https://github.com/babel/babylon/pull/352)) (Kevin Gibbons) + +This example now correctly throws an error when there is a semicolon after the decorator: + +```js +class A { +@a; +foo(){} +} +``` + +Keywords are not allowed as local specifier ([#307](https://github.com/babel/babylon/pull/307)) (Daniel Tschinder) + +Using keywords in imports is not allowed anymore: + +```js +import { default } from "foo"; +import { a as debugger } from "foo"; +``` + +Do not allow overwritting of primitive types ([#314](https://github.com/babel/babylon/pull/314)) (Daniel Tschinder) + +In flow it is now forbidden to overwrite the primitive types `"any"`, `"mixed"`, `"empty"`, `"bool"`, `"boolean"`, `"number"`, `"string"`, `"void"` and `"null"` with your own type declaration. + +Disallow import type { type a } from … ([#305](https://github.com/babel/babylon/pull/305)) (Daniel Tschinder) + +The following code now correctly throws an error + +```js +import type { type a } from "foo"; +``` + +Don't parse class properties without initializers when classProperties is disabled and Flow is enabled ([#300](https://github.com/babel/babylon/pull/300)) (Andrew Levine) + +Ensure that you enable the `classProperties` plugin in order to enable correct parsing of class properties. Prior to this version it was possible to parse them by enabling the `flow` plugin but this was not intended the behaviour. + +If you enable the flow plugin you can only define the type of the class properties, but not initialize them. + +Fix export default async function to be FunctionDeclaration ([#324](https://github.com/babel/babylon/pull/324)) (Daniel Tschinder) + +Parsing the following code now returns a `FunctionDeclaration` AST node instead of `FunctionExpression`. + +```js +export default async function bar() {}; +``` + +### :nail_care: Polish + +Improve error message on attempt to destructure named import ([#288](https://github.com/babel/babylon/pull/288)) (Brian Ng) + +### :bug: Bug Fix + +Fix negative number literal typeannotations ([#366](https://github.com/babel/babylon/pull/366)) (Daniel Tschinder) + +Ensure takeDecorators is called on exported class ([#358](https://github.com/babel/babylon/pull/358)) (Brian Ng) + +ESTree: correctly change literals in all cases ([#368](https://github.com/babel/babylon/pull/368)) (Daniel Tschinder) + +Correctly convert RestProperty to Assignable ([#339](https://github.com/babel/babylon/pull/339)) (Daniel Tschinder) + +Fix #321 by allowing question marks in type params ([#338](https://github.com/babel/babylon/pull/338)) (Daniel Tschinder) + +Fix #336 by correctly setting arrow-param ([#337](https://github.com/babel/babylon/pull/337)) (Daniel Tschinder) + +Fix parse error when destructuring `set` with default value ([#317](https://github.com/babel/babylon/pull/317)) (Brian Ng) + +Fix ObjectTypeCallProperty static ([#298](https://github.com/babel/babylon/pull/298)) (Dan Harper) + + +### :house: Internal + +Fix generator-method-with-computed-name spec ([#360](https://github.com/babel/babylon/pull/360)) (Alex Rattray) + +Fix flow type-parameter-declaration test with unintended semantic ([#361](https://github.com/babel/babylon/pull/361)) (Alex Rattray) + +Cleanup and splitup parser functions ([#295](https://github.com/babel/babylon/pull/295)) (Daniel Tschinder) + +chore(package): update flow-bin to version 0.38.0 ([#313](https://github.com/babel/babylon/pull/313)) (greenkeeper[bot]) + +Call inner function instead of 1:1 copy to plugin ([#294](https://github.com/babel/babylon/pull/294)) (Daniel Tschinder) + +Update eslint-config-babel to the latest version 🚀 ([#299](https://github.com/babel/babylon/pull/299)) (greenkeeper[bot]) + +Update eslint-config-babel to the latest version 🚀 ([#293](https://github.com/babel/babylon/pull/293)) (greenkeeper[bot]) + +devDeps: remove eslint-plugin-babel ([#292](https://github.com/babel/babylon/pull/292)) (Kai Cataldo) + +Correct indent eslint rule config ([#276](https://github.com/babel/babylon/pull/276)) (Daniel Tschinder) + +Fail tests that have expected.json and throws-option ([#285](https://github.com/babel/babylon/pull/285)) (Daniel Tschinder) + +### :memo: Documentation + +Update contributing with more test info [skip ci] ([#355](https://github.com/babel/babylon/pull/355)) (Brian Ng) + +Update API documentation ([#330](https://github.com/babel/babylon/pull/330)) (Timothy Gu) + +Added keywords to package.json ([#323](https://github.com/babel/babylon/pull/323)) (Dmytro) + +AST spec: fix casing of `RegExpLiteral` ([#318](https://github.com/babel/babylon/pull/318)) (Mathias Bynens) + +## 6.15.0 (2017-01-10) + +### :eyeglasses: Spec Compliance + +Add support for Flow shorthand import type ([#267](https://github.com/babel/babylon/pull/267)) (Jeff Morrison) + +This change implements flows new shorthand import syntax +and where previously you had to write this code: + +```js +import {someValue} from "blah"; +import type {someType} from "blah"; +import typeof {someOtherValue} from "blah"; +``` + +you can now write it like this: + +```js +import { + someValue, + type someType, + typeof someOtherValue, +} from "blah"; +``` + +For more information look at [this](https://github.com/facebook/flow/pull/2890) pull request. + +flow: allow leading pipes in all positions ([#256](https://github.com/babel/babylon/pull/256)) (Vladimir Kurchatkin) + +This change now allows a leading pipe everywhere types can be used: +```js +var f = (x): | 1 | 2 => 1; +``` + +Throw error when exporting non-declaration ([#241](https://github.com/babel/babylon/pull/241)) (Kai Cataldo) + +Previously babylon parsed the following exports, although they are not valid: +```js +export typeof foo; +export new Foo(); +export function() {}; +export for (;;); +export while(foo); +``` + +### :bug: Bug Fix + +Don't set inType flag when parsing property names ([#266](https://github.com/babel/babylon/pull/266)) (Vladimir Kurchatkin) + +This fixes parsing of this case: + +```js +const map = { + [age <= 17] : 'Too young' +}; +``` + +Fix source location for JSXEmptyExpression nodes (fixes #248) ([#249](https://github.com/babel/babylon/pull/249)) (James Long) + +The following case produced an invalid AST +```js +
{/* foo */}
+``` + +Use fromCodePoint to convert high value unicode entities ([#243](https://github.com/babel/babylon/pull/243)) (Ryan Duffy) + +When high value unicode entities (e.g. 💩) were used in the input source code they are now correctly encoded in the resulting AST. + +Rename folder to avoid Windows-illegal characters ([#281](https://github.com/babel/babylon/pull/281)) (Ryan Plant) + +Allow this.state.clone() when parsing decorators ([#262](https://github.com/babel/babylon/pull/262)) (Alex Rattray) + +### :house: Internal + +User external-helpers ([#254](https://github.com/babel/babylon/pull/254)) (Daniel Tschinder) + +Add watch script for dev ([#234](https://github.com/babel/babylon/pull/234)) (Kai Cataldo) + +Freeze current plugins list for "*" option, and remove from README.md ([#245](https://github.com/babel/babylon/pull/245)) (Andrew Levine) + +Prepare tests for multiple fixture runners. ([#240](https://github.com/babel/babylon/pull/240)) (Daniel Tschinder) + +Add some test coverage for decorators stage-0 plugin ([#250](https://github.com/babel/babylon/pull/250)) (Andrew Levine) + +Refactor tokenizer types file ([#263](https://github.com/babel/babylon/pull/263)) (Sven SAULEAU) + +Update eslint-config-babel to the latest version 🚀 ([#273](https://github.com/babel/babylon/pull/273)) (greenkeeper[bot]) + +chore(package): update rollup to version 0.41.0 ([#272](https://github.com/babel/babylon/pull/272)) (greenkeeper[bot]) + +chore(package): update flow-bin to version 0.37.0 ([#255](https://github.com/babel/babylon/pull/255)) (greenkeeper[bot]) + +## 6.14.1 (2016-11-17) + +### :bug: Bug Fix + +Allow `"plugins": ["*"]` ([#229](https://github.com/babel/babylon/pull/229)) (Daniel Tschinder) + +```js +{ + "plugins": ["*"] +} +``` + +Will include all parser plugins instead of specifying each one individually. Useful for tools like babel-eslint, jscodeshift, and ast-explorer. + +## 6.14.0 (2016-11-16) + +### :eyeglasses: Spec Compliance + +Throw error for reserved words `enum` and `await` ([#195](https://github.com/babel/babylon/pull/195)) (Kai Cataldo) + +[11.6.2.2 Future Reserved Words](http://www.ecma-international.org/ecma-262/6.0/#sec-future-reserved-words) + +Babylon will throw for more reserved words such as `enum` or `await` (in strict mode). + +``` +class enum {} // throws +class await {} // throws in strict mode (module) +``` + +Optional names for function types and object type indexers ([#197](https://github.com/babel/babylon/pull/197)) (Gabe Levi) + +So where you used to have to write + +```js +type A = (x: string, y: boolean) => number; +type B = (z: string) => number; +type C = { [key: string]: number }; +``` + +you can now write (with flow 0.34.0) + +```js +type A = (string, boolean) => number; +type B = string => number; +type C = { [string]: number }; +``` + +Parse flow nested array type annotations like `number[][]` ([#219](https://github.com/babel/babylon/pull/219)) (Bernhard Häussner) + +Supports these form now of specifying array types: + +```js +var a: number[][][][]; +var b: string[][]; +``` + +### :bug: Bug Fix + +Correctly eat semicolon at the end of `DelcareModuleExports` ([#223](https://github.com/babel/babylon/pull/223)) (Daniel Tschinder) + +``` +declare module "foo" { declare module.exports: number } +declare module "foo" { declare module.exports: number; } // also allowed now +``` + +### :house: Internal + + * Count Babel tests towards Babylon code coverage ([#182](https://github.com/babel/babylon/pull/182)) (Moti Zilberman) + * Fix strange line endings ([#214](https://github.com/babel/babylon/pull/214)) (Thomas Grainger) + * Add node 7 (Daniel Tschinder) + * chore(package): update flow-bin to version 0.34.0 ([#204](https://github.com/babel/babylon/pull/204)) (Greenkeeper) + +## v6.13.1 (2016-10-26) + +### :nail_care: Polish + +- Use rollup for bundling to speed up startup time ([#190](https://github.com/babel/babylon/pull/190)) ([@drewml](https://github.com/DrewML)) + +```js +const babylon = require('babylon'); +const ast = babylon.parse('var foo = "lol";'); +``` + +With that test case, there was a ~95ms savings by removing the need for node to build/traverse the dependency graph. + +**Without bundling** +![image](https://cloud.githubusercontent.com/assets/5233399/19420264/3133497e-93ad-11e6-9a6a-2da59c4f5c13.png) + +**With bundling** +![image](https://cloud.githubusercontent.com/assets/5233399/19420267/388f556e-93ad-11e6-813e-7c5c396be322.png) + +- add clean command [skip ci] ([#201](https://github.com/babel/babylon/pull/201)) (Henry Zhu) +- add ForAwaitStatement (async generator already added) [skip ci] ([#196](https://github.com/babel/babylon/pull/196)) (Henry Zhu) + +## v6.13.0 (2016-10-21) + +### :eyeglasses: Spec Compliance + +Property variance type annotations for Flow plugin ([#161](https://github.com/babel/babylon/pull/161)) (Sam Goldman) + +> See https://flowtype.org/docs/variance.html for more information + +```js +type T = { +p: T }; +interface T { -p: T }; +declare class T { +[k:K]: V }; +class T { -[k:K]: V }; +class C2 { +p: T = e }; +``` + +Raise error on duplicate definition of __proto__ ([#183](https://github.com/babel/babylon/pull/183)) (Moti Zilberman) + +```js +({ __proto__: 1, __proto__: 2 }) // Throws an error now +``` + +### :bug: Bug Fix + +Flow: Allow class properties to be named `static` ([#184](https://github.com/babel/babylon/pull/184)) (Moti Zilberman) + +```js +declare class A { + static: T; +} +``` + +Allow "async" as identifier for object literal property shorthand ([#187](https://github.com/babel/babylon/pull/187)) (Andrew Levine) + +```js +var foo = { async, bar }; +``` + +### :nail_care: Polish + +Fix flowtype and add inType to state ([#189](https://github.com/babel/babylon/pull/189)) (Daniel Tschinder) + +> This improves the performance slightly (because of hidden classes) + +### :house: Internal + +Fix .gitattributes line ending setting ([#191](https://github.com/babel/babylon/pull/191)) (Moti Zilberman) + +Increase test coverage ([#175](https://github.com/babel/babylon/pull/175) (Moti Zilberman) + +Readd missin .eslinignore for IDEs (Daniel Tschinder) + +Error on missing expected.json fixture in CI ([#188](https://github.com/babel/babylon/pull/188)) (Moti Zilberman) + +Add .gitattributes and .editorconfig for LF line endings ([#179](https://github.com/babel/babylon/pull/179)) (Moti Zilberman) + +Fixes two tests that are failing after the merge of #172 ([#177](https://github.com/babel/babylon/pull/177)) (Moti Zilberman) + +## v6.12.0 (2016-10-14) + +### :eyeglasses: Spec Compliance + +Implement import() syntax ([#163](https://github.com/babel/babylon/pull/163)) (Jordan Gensler) + +#### Dynamic Import + +- Proposal Repo: https://github.com/domenic/proposal-dynamic-import +- Championed by [@domenic](https://github.com/domenic) +- stage-2 +- [sept-28 tc39 notes](https://github.com/rwaldron/tc39-notes/blob/master/es7/2016-09/sept-28.md#113a-import) + +> This repository contains a proposal for adding a "function-like" import() module loading syntactic form to JavaScript + +```js +import(`./section-modules/${link.dataset.entryModule}.js`) +.then(module => { + module.loadPageInto(main); +}) +``` + +Add EmptyTypeAnnotation ([#171](https://github.com/babel/babylon/pull/171)) (Sam Goldman) + +#### EmptyTypeAnnotation + +Just wasn't covered before. + +```js +type T = empty; +``` + +### :bug: Bug Fix + +Fix crash when exporting with destructuring and sparse array ([#170](https://github.com/babel/babylon/pull/170)) (Jeroen Engels) + +```js +// was failing due to sparse array +export const { foo: [ ,, qux7 ] } = bar; +``` + +Allow keyword in Flow object declaration property names with type parameters ([#146](https://github.com/babel/babylon/pull/146)) (Dan Harper) + +```js +declare class X { + foobar(): void; + static foobar(): void; +} +``` + +Allow keyword in object/class property names with Flow type parameters ([#145](https://github.com/babel/babylon/pull/145)) (Dan Harper) + +```js +class Foo { + delete(item: T): T { + return item; + } +} +``` + +Allow typeAnnotations for yield expressions ([#174](https://github.com/babel/babylon/pull/174))) (Daniel Tschinder) + +```js +function *foo() { + const x = (yield 5: any); +} +``` + +### :nail_care: Polish + +Annotate more errors with expected token ([#172](https://github.com/babel/babylon/pull/172))) (Moti Zilberman) + +```js +// Unexpected token, expected ; (1:6) +{ set 1 } +``` + +### :house: Internal + +Remove kcheck ([#173](https://github.com/babel/babylon/pull/173))) (Daniel Tschinder) + +Also run flow, linting, babel tests on separate instances (add back node 0.10) + +## v6.11.6 (2016-10-12) + +### :bug: Bug Fix/Regression + +Fix crash when exporting with destructuring and sparse array ([#170](https://github.com/babel/babylon/pull/170)) (Jeroen Engels) + +```js +// was failing with `Cannot read property 'type' of null` because of null identifiers +export const { foo: [ ,, qux7 ] } = bar; +``` + +## v6.11.5 (2016-10-12) + +### :eyeglasses: Spec Compliance + +Fix: Check for duplicate named exports in exported destructuring assignments ([#144](https://github.com/babel/babylon/pull/144)) (Kai Cataldo) + +```js +// `foo` has already been exported. Exported identifiers must be unique. (2:20) +export function foo() {}; +export const { a: [{foo}] } = bar; +``` + +Fix: Check for duplicate named exports in exported rest elements/properties ([#164](https://github.com/babel/babylon/pull/164)) (Kai Cataldo) + +```js +// `foo` has already been exported. Exported identifiers must be unique. (2:22) +export const foo = 1; +export const [bar, ...foo] = baz; +``` + +### :bug: Bug Fix + +Fix: Allow identifier `async` for default param in arrow expression ([#165](https://github.com/babel/babylon/pull/165)) (Kai Cataldo) + +```js +// this is ok now +const test = ({async = true}) => {}; +``` + +### :nail_care: Polish + +Babylon will now print out the token it's expecting if there's a `SyntaxError` ([#150](https://github.com/babel/babylon/pull/150)) (Daniel Tschinder) + +```bash +# So in the case of a missing ending curly (`}`) +Module build failed: SyntaxError: Unexpected token, expected } (30:0) + 28 | } + 29 | +> 30 | + | ^ +``` + +## v6.11.4 (2016-10-03) + +Temporary rollback for erroring on trailing comma with spread (#154) (Henry Zhu) + +## v6.11.3 (2016-10-01) + +### :eyeglasses: Spec Compliance + +Add static errors for object rest (#149) ([@danez](https://github.com/danez)) + +> https://github.com/sebmarkbage/ecmascript-rest-spread + +Object rest copies the *rest* of properties from the right hand side `obj` starting from the left to right. + +```js +let { x, y, ...z } = { x: 1, y: 2, z: 3 }; +// x = 1 +// y = 2 +// z = { z: 3 } +``` + +#### New Syntax Errors: + +**SyntaxError**: The rest element has to be the last element when destructuring (1:10) +```bash +> 1 | let { ...x, y, z } = { x: 1, y: 2, z: 3}; + | ^ +# Previous behavior: +# x = { x: 1, y: 2, z: 3 } +# y = 2 +# z = 3 +``` + +Before, this was just a more verbose way of shallow copying `obj` since it doesn't actually do what you think. + +**SyntaxError**: Cannot have multiple rest elements when destructuring (1:13) + +```bash +> 1 | let { x, ...y, ...z } = { x: 1, y: 2, z: 3}; + | ^ +# Previous behavior: +# x = 1 +# y = { y: 2, z: 3 } +# z = { y: 2, z: 3 } +``` + +Before y and z would just be the same value anyway so there is no reason to need to have both. + +**SyntaxError**: A trailing comma is not permitted after the rest element (1:16) + +```js +let { x, y, ...z, } = obj; +``` + +The rationale for this is that the use case for trailing comma is that you can add something at the end without affecting the line above. Since a RestProperty always has to be the last property it doesn't make sense. + +--- + +get / set are valid property names in default assignment (#142) ([@jezell](https://github.com/jezell)) + +```js +// valid +function something({ set = null, get = null }) {} +``` + +## v6.11.2 (2016-09-23) + +### Bug Fix + +- [#139](https://github.com/babel/babylon/issues/139) Don't do the duplicate check if not an identifier (#140) @hzoo + +```js +// regression with duplicate export check +SyntaxError: ./typography.js: `undefined` has already been exported. Exported identifiers must be unique. (22:13) + 20 | + 21 | export const { rhythm } = typography; +> 22 | export const { TypographyStyle } = typography +``` + +Bail out for now, and make a change to account for destructuring in the next release. + +## 6.11.1 (2016-09-22) + +### Bug Fix +- [#137](https://github.com/babel/babylon/pull/137) - Fix a regression with duplicate exports - it was erroring on all keys in `Object.prototype`. @danez + +```javascript +export toString from './toString'; +``` + +```bash +`toString` has already been exported. Exported identifiers must be unique. (1:7) +> 1 | export toString from './toString'; + | ^ + 2 | +``` + +## 6.11.0 (2016-09-22) + +### Spec Compliance (will break CI) + +- Disallow duplicate named exports ([#107](https://github.com/babel/babylon/pull/107)) @kaicataldo + +```js +// Only one default export allowed per module. (2:9) +export default function() {}; +export { foo as default }; + +// Only one default export allowed per module. (2:0) +export default {}; +export default function() {}; + +// `Foo` has already been exported. Exported identifiers must be unique. (2:0) +export { Foo }; +export class Foo {}; +``` + +### New Feature (Syntax) + +- Add support for computed class property names ([#121](https://github.com/babel/babylon/pull/121)) @motiz88 + +```js +// AST +interface ClassProperty <: Node { + type: "ClassProperty"; + key: Identifier; + value: Expression; + computed: boolean; // added +} +``` + +```js +// with "plugins": ["classProperties"] +class Foo { + [x] + ['y'] +} + +class Bar { + [p] + [m] () {} +} + ``` + +### Bug Fix + +- Fix `static` property falling through in the declare class Flow AST ([#135](https://github.com/babel/babylon/pull/135)) @danharper + +```js +declare class X { + a: number; + static b: number; // static + c: number; // this was being marked as static in the AST as well +} +``` + +### Polish + +- Rephrase "assigning/binding to rvalue" errors to include context ([#119](https://github.com/babel/babylon/pull/119)) @motiz88 + +```js +// Used to error with: +// SyntaxError: Assigning to rvalue (1:0) + +// Now: +// Invalid left-hand side in assignment expression (1:0) +3 = 4 + +// Invalid left-hand side in for-in statement (1:5) +for (+i in {}); +``` + +### Internal + +- Fix call to `this.parseMaybeAssign` with correct arguments ([#133](https://github.com/babel/babylon/pull/133)) @danez +- Add semver note to changelog ([#131](https://github.com/babel/babylon/pull/131)) @hzoo + +## 6.10.0 (2016-09-19) + +> We plan to include some spec compliance bugs in patch versions. An example was the multiple default exports issue. + +### Spec Compliance + +* Implement ES2016 check for simple parameter list in strict mode ([#106](https://github.com/babel/babylon/pull/106)) (Timothy Gu) + +> It is a Syntax Error if ContainsUseStrict of FunctionBody is true and IsSimpleParameterList of FormalParameters is false. https://tc39.github.io/ecma262/2016/#sec-function-definitions-static-semantics-early-errors + +More Context: [tc39-notes](https://github.com/rwaldron/tc39-notes/blob/master/es7/2015-07/july-29.md#611-the-scope-of-use-strict-with-respect-to-destructuring-in-parameter-lists) + +For example: + +```js +// this errors because it uses destructuring and default parameters +// in a function with a "use strict" directive +function a([ option1, option2 ] = []) { + "use strict"; +} + ``` + +The solution would be to use a top level "use strict" or to remove the destructuring or default parameters when using a function + "use strict" or to. + +### New Feature + +* Exact object type annotations for Flow plugin ([#104](https://github.com/babel/babylon/pull/104)) (Basil Hosmer) + +Added to flow in https://github.com/facebook/flow/commit/c710c40aa2a115435098d6c0dfeaadb023cd39b8 + +Looks like: + +```js +var a : {| x: number, y: string |} = { x: 0, y: 'foo' }; +``` + +### Bug Fixes + +* Include `typeParameter` location in `ArrowFunctionExpression` ([#126](https://github.com/babel/babylon/pull/126)) (Daniel Tschinder) +* Error on invalid flow type annotation with default assignment ([#122](https://github.com/babel/babylon/pull/122)) (Dan Harper) +* Fix Flow return types on arrow functions ([#124](https://github.com/babel/babylon/pull/124)) (Dan Harper) + +### Misc + +* Add tests for export extensions ([#127](https://github.com/babel/babylon/pull/127)) (Daniel Tschinder) +* Fix Contributing guidelines [skip ci] (Daniel Tschinder) + +## 6.9.2 (2016-09-09) + +The only change is to remove the `babel-runtime` dependency by compiling with Babel's ES2015 loose mode. So using babylon standalone should be smaller. + +## 6.9.1 (2016-08-23) + +This release contains mainly small bugfixes but also updates babylons default mode to es2017. The features for `exponentiationOperator`, `asyncFunctions` and `trailingFunctionCommas` which previously needed to be activated via plugin are now enabled by default and the plugins are now no-ops. + +### Bug Fixes + +- Fix issues with default object params in async functions ([#96](https://github.com/babel/babylon/pull/96)) @danez +- Fix issues with flow-types and async function ([#95](https://github.com/babel/babylon/pull/95)) @danez +- Fix arrow functions with destructuring, types & default value ([#94](https://github.com/babel/babylon/pull/94)) @danharper +- Fix declare class with qualified type identifier ([#97](https://github.com/babel/babylon/pull/97)) @danez +- Remove exponentiationOperator, asyncFunctions, trailingFunctionCommas plugins and enable them by default ([#98](https://github.com/babel/babylon/pull/98)) @danez + +## 6.9.0 (2016-08-16) + +### New syntax support + +- Add JSX spread children ([#42](https://github.com/babel/babylon/pull/42)) @calebmer + +(Be aware that React is not going to support this syntax) + +```js +
+ {...todos.map(todo => )} +
+``` + +- Add support for declare module.exports ([#72](https://github.com/babel/babylon/pull/72)) @danez + +```js +declare module "foo" { + declare module.exports: {} +} +``` + +### New Features + +- If supplied, attach filename property to comment node loc. ([#80](https://github.com/babel/babylon/pull/80)) @divmain +- Add identifier name to node loc field ([#90](https://github.com/babel/babylon/pull/90)) @kittens + +### Bug Fixes + +- Fix exponential operator to behave according to spec ([#75](https://github.com/babel/babylon/pull/75)) @danez +- Fix lookahead to not add comments to arrays which are not cloned ([#76](https://github.com/babel/babylon/pull/76)) @danez +- Fix accidental fall-through in Flow type parsing. ([#82](https://github.com/babel/babylon/pull/82)) @xiemaisi +- Only allow declares inside declare module ([#73](https://github.com/babel/babylon/pull/73)) @danez +- Small fix for parsing type parameter declarations ([#83](https://github.com/babel/babylon/pull/83)) @gabelevi +- Fix arrow param locations with flow types ([#57](https://github.com/babel/babylon/pull/57)) @danez +- Fixes SyntaxError position with flow optional type ([#65](https://github.com/babel/babylon/pull/65)) @danez + +### Internal + +- Add codecoverage to tests @danez +- Fix tests to not save expected output if we expect the test to fail @danez +- Make a shallow clone of babel for testing @danez +- chore(package): update cross-env to version 2.0.0 ([#77](https://github.com/babel/babylon/pull/77)) @greenkeeperio-bot +- chore(package): update ava to version 0.16.0 ([#86](https://github.com/babel/babylon/pull/86)) @greenkeeperio-bot +- chore(package): update babel-plugin-istanbul to version 2.0.0 ([#89](https://github.com/babel/babylon/pull/89)) @greenkeeperio-bot +- chore(package): update nyc to version 8.0.0 ([#88](https://github.com/babel/babylon/pull/88)) @greenkeeperio-bot + +## 6.8.4 (2016-07-06) + +### Bug Fixes + +- Fix the location of params, when flow and default value used ([#68](https://github.com/babel/babylon/pull/68)) @danez + +## 6.8.3 (2016-07-02) + +### Bug Fixes + +- Fix performance regression introduced in 6.8.2 with conditionals ([#63](https://github.com/babel/babylon/pull/63)) @danez + +## 6.8.2 (2016-06-24) + +### Bug Fixes + +- Fix parse error with yielding jsx elements in generators `function* it() { yield ; }` ([#31](https://github.com/babel/babylon/pull/31)) @eldereal +- When cloning nodes do not clone its comments ([#24](https://github.com/babel/babylon/pull/24)) @danez +- Fix parse errors when using arrow functions with an spread element and return type `(...props): void => {}` ([#10](https://github.com/babel/babylon/pull/10)) @danez +- Fix leading comments added from previous node ([#23](https://github.com/babel/babylon/pull/23)) @danez +- Fix parse errors with flow's optional arguments `(arg?) => {}` ([#19](https://github.com/babel/babylon/pull/19)) @danez +- Support negative numeric type literals @kittens +- Remove line terminator restriction after await keyword @kittens +- Remove grouped type arrow restriction as it seems flow no longer has it @kittens +- Fix parse error with generic methods that have the name `get` or `set` `class foo { get() {} }` ([#55](https://github.com/babel/babylon/pull/55)) @vkurchatkin +- Fix parse error with arrow functions that have flow type parameter declarations `(x: T): T => x;` ([#54](https://github.com/babel/babylon/pull/54)) @gabelevi + +### Documentation + +- Document AST differences from ESTree ([#41](https://github.com/babel/babylon/pull/41)) @nene +- Move ast spec from babel/babel ([#46](https://github.com/babel/babylon/pull/46)) @hzoo + +### Internal + +- Enable skipped tests ([#16](https://github.com/babel/babylon/pull/16)) @danez +- Add script to test latest version of babylon with babel ([#21](https://github.com/babel/babylon/pull/21)) @danez +- Upgrade test runner ava @kittens +- Add missing generate-identifier-regex script @kittens +- Rename parser context types @kittens +- Add node v6 to travis testing @hzoo +- Update to Unicode v9 ([#45](https://github.com/babel/babylon/pull/45)) @mathiasbynens + +## 6.8.1 (2016-06-06) + +### New Feature + +- Parse type parameter declarations with defaults like `type Foo = T` + +### Bug Fixes +- Type parameter declarations need 1 or more type parameters. +- The existential type `*` is not a valid type parameter. +- The existential type `*` is a primary type + +### Spec Compliance +- The param list for type parameter declarations now consists of `TypeParameter` nodes +- New `TypeParameter` AST Node (replaces using the `Identifier` node before) + +``` +interface TypeParameter <: Node { + bound: TypeAnnotation; + default: TypeAnnotation; + name: string; + variance: "plus" | "minus"; +} +``` + +## 6.8.0 (2016-05-02) + +#### New Feature + +##### Parse Method Parameter Decorators ([#12](https://github.com/babel/babylon/pull/12)) + +> [Method Parameter Decorators](https://goo.gl/8MmCMG) is now a TC39 [stage 0 proposal](https://github.com/tc39/ecma262/blob/master/stage0.md). + +Examples: + +```js +class Foo { + constructor(@foo() x, @bar({ a: 123 }) @baz() y) {} +} + +export default function func(@foo() x, @bar({ a: 123 }) @baz() y) {} + +var obj = { + method(@foo() x, @bar({ a: 123 }) @baz() y) {} +}; +``` + +##### Parse for-await statements (w/ `asyncGenerators` plugin) ([#17](https://github.com/babel/babylon/pull/17)) + +There is also a new node type, `ForAwaitStatement`. + +> [Async generators and for-await](https://github.com/tc39/proposal-async-iteration) are now a [stage 2 proposal](https://github.com/tc39/ecma262#current-proposals). + +Example: + +```js +async function f() { + for await (let x of y); +} +``` diff --git a/node_modules/@babel/parser/LICENSE b/node_modules/@babel/parser/LICENSE new file mode 100644 index 00000000..d4c7fc58 --- /dev/null +++ b/node_modules/@babel/parser/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2012-2014 by various contributors (see AUTHORS) + +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. diff --git a/node_modules/@babel/parser/README.md b/node_modules/@babel/parser/README.md new file mode 100644 index 00000000..a9463e81 --- /dev/null +++ b/node_modules/@babel/parser/README.md @@ -0,0 +1,19 @@ +# @babel/parser + +> A JavaScript parser + +See our website [@babel/parser](https://babeljs.io/docs/babel-parser) for more information or the [issues](https://github.com/babel/babel/issues?utf8=%E2%9C%93&q=is%3Aissue+label%3A%22pkg%3A%20parser%22+is%3Aopen) associated with this package. + +## Install + +Using npm: + +```sh +npm install --save-dev @babel/parser +``` + +or using yarn: + +```sh +yarn add @babel/parser --dev +``` diff --git a/node_modules/@babel/parser/bin/babel-parser.js b/node_modules/@babel/parser/bin/babel-parser.js new file mode 100755 index 00000000..4808c5ee --- /dev/null +++ b/node_modules/@babel/parser/bin/babel-parser.js @@ -0,0 +1,15 @@ +#!/usr/bin/env node +/* eslint-disable no-var, unicorn/prefer-node-protocol */ + +var parser = require(".."); +var fs = require("fs"); + +var filename = process.argv[2]; +if (!filename) { + console.error("no filename specified"); +} else { + var file = fs.readFileSync(filename, "utf8"); + var ast = parser.parse(file); + + console.log(JSON.stringify(ast, null, " ")); +} diff --git a/node_modules/@babel/parser/lib/index.js b/node_modules/@babel/parser/lib/index.js new file mode 100644 index 00000000..154aba2a --- /dev/null +++ b/node_modules/@babel/parser/lib/index.js @@ -0,0 +1,14582 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +function _objectWithoutPropertiesLoose(r, e) { + if (null == r) return {}; + var t = {}; + for (var n in r) if ({}.hasOwnProperty.call(r, n)) { + if (-1 !== e.indexOf(n)) continue; + t[n] = r[n]; + } + return t; +} +class Position { + constructor(line, col, index) { + this.line = void 0; + this.column = void 0; + this.index = void 0; + this.line = line; + this.column = col; + this.index = index; + } +} +class SourceLocation { + constructor(start, end) { + this.start = void 0; + this.end = void 0; + this.filename = void 0; + this.identifierName = void 0; + this.start = start; + this.end = end; + } +} +function createPositionWithColumnOffset(position, columnOffset) { + const { + line, + column, + index + } = position; + return new Position(line, column + columnOffset, index + columnOffset); +} +const code = "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED"; +var ModuleErrors = { + ImportMetaOutsideModule: { + message: `import.meta may appear only with 'sourceType: "module"'`, + code + }, + ImportOutsideModule: { + message: `'import' and 'export' may appear only with 'sourceType: "module"'`, + code + } +}; +const NodeDescriptions = { + ArrayPattern: "array destructuring pattern", + AssignmentExpression: "assignment expression", + AssignmentPattern: "assignment expression", + ArrowFunctionExpression: "arrow function expression", + ConditionalExpression: "conditional expression", + CatchClause: "catch clause", + ForOfStatement: "for-of statement", + ForInStatement: "for-in statement", + ForStatement: "for-loop", + FormalParameters: "function parameter list", + Identifier: "identifier", + ImportSpecifier: "import specifier", + ImportDefaultSpecifier: "import default specifier", + ImportNamespaceSpecifier: "import namespace specifier", + ObjectPattern: "object destructuring pattern", + ParenthesizedExpression: "parenthesized expression", + RestElement: "rest element", + UpdateExpression: { + true: "prefix operation", + false: "postfix operation" + }, + VariableDeclarator: "variable declaration", + YieldExpression: "yield expression" +}; +const toNodeDescription = node => node.type === "UpdateExpression" ? NodeDescriptions.UpdateExpression[`${node.prefix}`] : NodeDescriptions[node.type]; +var StandardErrors = { + AccessorIsGenerator: ({ + kind + }) => `A ${kind}ter cannot be a generator.`, + ArgumentsInClass: "'arguments' is only allowed in functions and class methods.", + AsyncFunctionInSingleStatementContext: "Async functions can only be declared at the top level or inside a block.", + AwaitBindingIdentifier: "Can not use 'await' as identifier inside an async function.", + AwaitBindingIdentifierInStaticBlock: "Can not use 'await' as identifier inside a static block.", + AwaitExpressionFormalParameter: "'await' is not allowed in async function parameters.", + AwaitUsingNotInAsyncContext: "'await using' is only allowed within async functions and at the top levels of modules.", + AwaitNotInAsyncContext: "'await' is only allowed within async functions and at the top levels of modules.", + BadGetterArity: "A 'get' accessor must not have any formal parameters.", + BadSetterArity: "A 'set' accessor must have exactly one formal parameter.", + BadSetterRestParameter: "A 'set' accessor function argument must not be a rest parameter.", + ConstructorClassField: "Classes may not have a field named 'constructor'.", + ConstructorClassPrivateField: "Classes may not have a private field named '#constructor'.", + ConstructorIsAccessor: "Class constructor may not be an accessor.", + ConstructorIsAsync: "Constructor can't be an async function.", + ConstructorIsGenerator: "Constructor can't be a generator.", + DeclarationMissingInitializer: ({ + kind + }) => `Missing initializer in ${kind} declaration.`, + DecoratorArgumentsOutsideParentheses: "Decorator arguments must be moved inside parentheses: use '@(decorator(args))' instead of '@(decorator)(args)'.", + DecoratorBeforeExport: "Decorators must be placed *before* the 'export' keyword. Remove the 'decoratorsBeforeExport: true' option to use the 'export @decorator class {}' syntax.", + DecoratorsBeforeAfterExport: "Decorators can be placed *either* before or after the 'export' keyword, but not in both locations at the same time.", + DecoratorConstructor: "Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?", + DecoratorExportClass: "Decorators must be placed *after* the 'export' keyword. Remove the 'decoratorsBeforeExport: false' option to use the '@decorator export class {}' syntax.", + DecoratorSemicolon: "Decorators must not be followed by a semicolon.", + DecoratorStaticBlock: "Decorators can't be used with a static block.", + DeferImportRequiresNamespace: 'Only `import defer * as x from "./module"` is valid.', + DeletePrivateField: "Deleting a private field is not allowed.", + DestructureNamedImport: "ES2015 named imports do not destructure. Use another statement for destructuring after the import.", + DuplicateConstructor: "Duplicate constructor in the same class.", + DuplicateDefaultExport: "Only one default export allowed per module.", + DuplicateExport: ({ + exportName + }) => `\`${exportName}\` has already been exported. Exported identifiers must be unique.`, + DuplicateProto: "Redefinition of __proto__ property.", + DuplicateRegExpFlags: "Duplicate regular expression flag.", + ElementAfterRest: "Rest element must be last element.", + EscapedCharNotAnIdentifier: "Invalid Unicode escape.", + ExportBindingIsString: ({ + localName, + exportName + }) => `A string literal cannot be used as an exported binding without \`from\`.\n- Did you mean \`export { '${localName}' as '${exportName}' } from 'some-module'\`?`, + ExportDefaultFromAsIdentifier: "'from' is not allowed as an identifier after 'export default'.", + ForInOfLoopInitializer: ({ + type + }) => `'${type === "ForInStatement" ? "for-in" : "for-of"}' loop variable declaration may not have an initializer.`, + ForInUsing: "For-in loop may not start with 'using' declaration.", + ForOfAsync: "The left-hand side of a for-of loop may not be 'async'.", + ForOfLet: "The left-hand side of a for-of loop may not start with 'let'.", + GeneratorInSingleStatementContext: "Generators can only be declared at the top level or inside a block.", + IllegalBreakContinue: ({ + type + }) => `Unsyntactic ${type === "BreakStatement" ? "break" : "continue"}.`, + IllegalLanguageModeDirective: "Illegal 'use strict' directive in function with non-simple parameter list.", + IllegalReturn: "'return' outside of function.", + ImportAttributesUseAssert: "The `assert` keyword in import attributes is deprecated and it has been replaced by the `with` keyword. You can enable the `deprecatedImportAssert` parser plugin to suppress this error.", + ImportBindingIsString: ({ + importName + }) => `A string literal cannot be used as an imported binding.\n- Did you mean \`import { "${importName}" as foo }\`?`, + ImportCallArity: `\`import()\` requires exactly one or two arguments.`, + ImportCallNotNewExpression: "Cannot use new with import(...).", + ImportCallSpreadArgument: "`...` is not allowed in `import()`.", + ImportJSONBindingNotDefault: "A JSON module can only be imported with `default`.", + ImportReflectionHasAssertion: "`import module x` cannot have assertions.", + ImportReflectionNotBinding: 'Only `import module x from "./module"` is valid.', + IncompatibleRegExpUVFlags: "The 'u' and 'v' regular expression flags cannot be enabled at the same time.", + InvalidBigIntLiteral: "Invalid BigIntLiteral.", + InvalidCodePoint: "Code point out of bounds.", + InvalidCoverDiscardElement: "'void' must be followed by an expression when not used in a binding position.", + InvalidCoverInitializedName: "Invalid shorthand property initializer.", + InvalidDecimal: "Invalid decimal.", + InvalidDigit: ({ + radix + }) => `Expected number in radix ${radix}.`, + InvalidEscapeSequence: "Bad character escape sequence.", + InvalidEscapeSequenceTemplate: "Invalid escape sequence in template.", + InvalidEscapedReservedWord: ({ + reservedWord + }) => `Escape sequence in keyword ${reservedWord}.`, + InvalidIdentifier: ({ + identifierName + }) => `Invalid identifier ${identifierName}.`, + InvalidLhs: ({ + ancestor + }) => `Invalid left-hand side in ${toNodeDescription(ancestor)}.`, + InvalidLhsBinding: ({ + ancestor + }) => `Binding invalid left-hand side in ${toNodeDescription(ancestor)}.`, + InvalidLhsOptionalChaining: ({ + ancestor + }) => `Invalid optional chaining in the left-hand side of ${toNodeDescription(ancestor)}.`, + InvalidNumber: "Invalid number.", + InvalidOrMissingExponent: "Floating-point numbers require a valid exponent after the 'e'.", + InvalidOrUnexpectedToken: ({ + unexpected + }) => `Unexpected character '${unexpected}'.`, + InvalidParenthesizedAssignment: "Invalid parenthesized assignment pattern.", + InvalidPrivateFieldResolution: ({ + identifierName + }) => `Private name #${identifierName} is not defined.`, + InvalidPropertyBindingPattern: "Binding member expression.", + InvalidRecordProperty: "Only properties and spread elements are allowed in record definitions.", + InvalidRestAssignmentPattern: "Invalid rest operator's argument.", + LabelRedeclaration: ({ + labelName + }) => `Label '${labelName}' is already declared.`, + LetInLexicalBinding: "'let' is disallowed as a lexically bound name.", + LineTerminatorBeforeArrow: "No line break is allowed before '=>'.", + MalformedRegExpFlags: "Invalid regular expression flag.", + MissingClassName: "A class name is required.", + MissingEqInAssignment: "Only '=' operator can be used for specifying default value.", + MissingSemicolon: "Missing semicolon.", + MissingPlugin: ({ + missingPlugin + }) => `This experimental syntax requires enabling the parser plugin: ${missingPlugin.map(name => JSON.stringify(name)).join(", ")}.`, + MissingOneOfPlugins: ({ + missingPlugin + }) => `This experimental syntax requires enabling one of the following parser plugin(s): ${missingPlugin.map(name => JSON.stringify(name)).join(", ")}.`, + MissingUnicodeEscape: "Expecting Unicode escape sequence \\uXXXX.", + MixingCoalesceWithLogical: "Nullish coalescing operator(??) requires parens when mixing with logical operators.", + ModuleAttributeDifferentFromType: "The only accepted module attribute is `type`.", + ModuleAttributeInvalidValue: "Only string literals are allowed as module attribute values.", + ModuleAttributesWithDuplicateKeys: ({ + key + }) => `Duplicate key "${key}" is not allowed in module attributes.`, + ModuleExportNameHasLoneSurrogate: ({ + surrogateCharCode + }) => `An export name cannot include a lone surrogate, found '\\u${surrogateCharCode.toString(16)}'.`, + ModuleExportUndefined: ({ + localName + }) => `Export '${localName}' is not defined.`, + MultipleDefaultsInSwitch: "Multiple default clauses.", + NewlineAfterThrow: "Illegal newline after throw.", + NoCatchOrFinally: "Missing catch or finally clause.", + NumberIdentifier: "Identifier directly after number.", + NumericSeparatorInEscapeSequence: "Numeric separators are not allowed inside unicode escape sequences or hex escape sequences.", + ObsoleteAwaitStar: "'await*' has been removed from the async functions proposal. Use Promise.all() instead.", + OptionalChainingNoNew: "Constructors in/after an Optional Chain are not allowed.", + OptionalChainingNoTemplate: "Tagged Template Literals are not allowed in optionalChain.", + OverrideOnConstructor: "'override' modifier cannot appear on a constructor declaration.", + ParamDupe: "Argument name clash.", + PatternHasAccessor: "Object pattern can't contain getter or setter.", + PatternHasMethod: "Object pattern can't contain methods.", + PrivateInExpectedIn: ({ + identifierName + }) => `Private names are only allowed in property accesses (\`obj.#${identifierName}\`) or in \`in\` expressions (\`#${identifierName} in obj\`).`, + PrivateNameRedeclaration: ({ + identifierName + }) => `Duplicate private name #${identifierName}.`, + RecordExpressionBarIncorrectEndSyntaxType: "Record expressions ending with '|}' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.", + RecordExpressionBarIncorrectStartSyntaxType: "Record expressions starting with '{|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.", + RecordExpressionHashIncorrectStartSyntaxType: "Record expressions starting with '#{' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.", + RecordNoProto: "'__proto__' is not allowed in Record expressions.", + RestTrailingComma: "Unexpected trailing comma after rest element.", + SloppyFunction: "In non-strict mode code, functions can only be declared at top level or inside a block.", + SloppyFunctionAnnexB: "In non-strict mode code, functions can only be declared at top level, inside a block, or as the body of an if statement.", + SourcePhaseImportRequiresDefault: 'Only `import source x from "./module"` is valid.', + StaticPrototype: "Classes may not have static property named prototype.", + SuperNotAllowed: "`super()` is only valid inside a class constructor of a subclass. Maybe a typo in the method name ('constructor') or not extending another class?", + SuperPrivateField: "Private fields can't be accessed on super.", + TrailingDecorator: "Decorators must be attached to a class element.", + TupleExpressionBarIncorrectEndSyntaxType: "Tuple expressions ending with '|]' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.", + TupleExpressionBarIncorrectStartSyntaxType: "Tuple expressions starting with '[|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.", + TupleExpressionHashIncorrectStartSyntaxType: "Tuple expressions starting with '#[' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.", + UnexpectedArgumentPlaceholder: "Unexpected argument placeholder.", + UnexpectedAwaitAfterPipelineBody: 'Unexpected "await" after pipeline body; await must have parentheses in minimal proposal.', + UnexpectedDigitAfterHash: "Unexpected digit after hash token.", + UnexpectedImportExport: "'import' and 'export' may only appear at the top level.", + UnexpectedKeyword: ({ + keyword + }) => `Unexpected keyword '${keyword}'.`, + UnexpectedLeadingDecorator: "Leading decorators must be attached to a class declaration.", + UnexpectedLexicalDeclaration: "Lexical declaration cannot appear in a single-statement context.", + UnexpectedNewTarget: "`new.target` can only be used in functions or class properties.", + UnexpectedNumericSeparator: "A numeric separator is only allowed between two digits.", + UnexpectedPrivateField: "Unexpected private name.", + UnexpectedReservedWord: ({ + reservedWord + }) => `Unexpected reserved word '${reservedWord}'.`, + UnexpectedSuper: "'super' is only allowed in object methods and classes.", + UnexpectedToken: ({ + expected, + unexpected + }) => `Unexpected token${unexpected ? ` '${unexpected}'.` : ""}${expected ? `, expected "${expected}"` : ""}`, + UnexpectedTokenUnaryExponentiation: "Illegal expression. Wrap left hand side or entire exponentiation in parentheses.", + UnexpectedUsingDeclaration: "Using declaration cannot appear in the top level when source type is `script` or in the bare case statement.", + UnexpectedVoidPattern: "Unexpected void binding.", + UnsupportedBind: "Binding should be performed on object property.", + UnsupportedDecoratorExport: "A decorated export must export a class declaration.", + UnsupportedDefaultExport: "Only expressions, functions or classes are allowed as the `default` export.", + UnsupportedImport: "`import` can only be used in `import()` or `import.meta`.", + UnsupportedMetaProperty: ({ + target, + onlyValidPropertyName + }) => `The only valid meta property for ${target} is ${target}.${onlyValidPropertyName}.`, + UnsupportedParameterDecorator: "Decorators cannot be used to decorate parameters.", + UnsupportedPropertyDecorator: "Decorators cannot be used to decorate object literal properties.", + UnsupportedSuper: "'super' can only be used with function calls (i.e. super()) or in property accesses (i.e. super.prop or super[prop]).", + UnterminatedComment: "Unterminated comment.", + UnterminatedRegExp: "Unterminated regular expression.", + UnterminatedString: "Unterminated string constant.", + UnterminatedTemplate: "Unterminated template.", + UsingDeclarationExport: "Using declaration cannot be exported.", + UsingDeclarationHasBindingPattern: "Using declaration cannot have destructuring patterns.", + VarRedeclaration: ({ + identifierName + }) => `Identifier '${identifierName}' has already been declared.`, + VoidPatternCatchClauseParam: "A void binding can not be the catch clause parameter. Use `try { ... } catch { ... }` if you want to discard the caught error.", + VoidPatternInitializer: "A void binding may not have an initializer.", + YieldBindingIdentifier: "Can not use 'yield' as identifier inside a generator.", + YieldInParameter: "Yield expression is not allowed in formal parameters.", + YieldNotInGeneratorFunction: "'yield' is only allowed within generator functions.", + ZeroDigitNumericSeparator: "Numeric separator can not be used after leading 0." +}; +var StrictModeErrors = { + StrictDelete: "Deleting local variable in strict mode.", + StrictEvalArguments: ({ + referenceName + }) => `Assigning to '${referenceName}' in strict mode.`, + StrictEvalArgumentsBinding: ({ + bindingName + }) => `Binding '${bindingName}' in strict mode.`, + StrictFunction: "In strict mode code, functions can only be declared at top level or inside a block.", + StrictNumericEscape: "The only valid numeric escape in strict mode is '\\0'.", + StrictOctalLiteral: "Legacy octal literals are not allowed in strict mode.", + StrictWith: "'with' in strict mode." +}; +var ParseExpressionErrors = { + ParseExpressionEmptyInput: "Unexpected parseExpression() input: The input is empty or contains only comments.", + ParseExpressionExpectsEOF: ({ + unexpected + }) => `Unexpected parseExpression() input: The input should contain exactly one expression, but the first expression is followed by the unexpected character \`${String.fromCodePoint(unexpected)}\`.` +}; +const UnparenthesizedPipeBodyDescriptions = new Set(["ArrowFunctionExpression", "AssignmentExpression", "ConditionalExpression", "YieldExpression"]); +var PipelineOperatorErrors = Object.assign({ + PipeBodyIsTighter: "Unexpected yield after pipeline body; any yield expression acting as Hack-style pipe body must be parenthesized due to its loose operator precedence.", + PipeTopicRequiresHackPipes: 'Topic reference is used, but the pipelineOperator plugin was not passed a "proposal": "hack" or "smart" option.', + PipeTopicUnbound: "Topic reference is unbound; it must be inside a pipe body.", + PipeTopicUnconfiguredToken: ({ + token + }) => `Invalid topic token ${token}. In order to use ${token} as a topic reference, the pipelineOperator plugin must be configured with { "proposal": "hack", "topicToken": "${token}" }.`, + PipeTopicUnused: "Hack-style pipe body does not contain a topic reference; Hack-style pipes must use topic at least once.", + PipeUnparenthesizedBody: ({ + type + }) => `Hack-style pipe body cannot be an unparenthesized ${toNodeDescription({ + type + })}; please wrap it in parentheses.` +}, { + PipelineBodyNoArrow: 'Unexpected arrow "=>" after pipeline body; arrow function in pipeline body must be parenthesized.', + PipelineBodySequenceExpression: "Pipeline body may not be a comma-separated sequence expression.", + PipelineHeadSequenceExpression: "Pipeline head should not be a comma-separated sequence expression.", + PipelineTopicUnused: "Pipeline is in topic style but does not use topic reference.", + PrimaryTopicNotAllowed: "Topic reference was used in a lexical context without topic binding.", + PrimaryTopicRequiresSmartPipeline: 'Topic reference is used, but the pipelineOperator plugin was not passed a "proposal": "hack" or "smart" option.' +}); +const _excluded = ["message"]; +function defineHidden(obj, key, value) { + Object.defineProperty(obj, key, { + enumerable: false, + configurable: true, + value + }); +} +function toParseErrorConstructor({ + toMessage, + code, + reasonCode, + syntaxPlugin +}) { + const hasMissingPlugin = reasonCode === "MissingPlugin" || reasonCode === "MissingOneOfPlugins"; + const oldReasonCodes = { + AccessorCannotDeclareThisParameter: "AccesorCannotDeclareThisParameter", + AccessorCannotHaveTypeParameters: "AccesorCannotHaveTypeParameters", + ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference: "ConstInitiailizerMustBeStringOrNumericLiteralOrLiteralEnumReference", + SetAccessorCannotHaveOptionalParameter: "SetAccesorCannotHaveOptionalParameter", + SetAccessorCannotHaveRestParameter: "SetAccesorCannotHaveRestParameter", + SetAccessorCannotHaveReturnType: "SetAccesorCannotHaveReturnType" + }; + if (oldReasonCodes[reasonCode]) { + reasonCode = oldReasonCodes[reasonCode]; + } + return function constructor(loc, details) { + const error = new SyntaxError(); + error.code = code; + error.reasonCode = reasonCode; + error.loc = loc; + error.pos = loc.index; + error.syntaxPlugin = syntaxPlugin; + if (hasMissingPlugin) { + error.missingPlugin = details.missingPlugin; + } + defineHidden(error, "clone", function clone(overrides = {}) { + var _overrides$loc; + const { + line, + column, + index + } = (_overrides$loc = overrides.loc) != null ? _overrides$loc : loc; + return constructor(new Position(line, column, index), Object.assign({}, details, overrides.details)); + }); + defineHidden(error, "details", details); + Object.defineProperty(error, "message", { + configurable: true, + get() { + const message = `${toMessage(details)} (${loc.line}:${loc.column})`; + this.message = message; + return message; + }, + set(value) { + Object.defineProperty(this, "message", { + value, + writable: true + }); + } + }); + return error; + }; +} +function ParseErrorEnum(argument, syntaxPlugin) { + if (Array.isArray(argument)) { + return parseErrorTemplates => ParseErrorEnum(parseErrorTemplates, argument[0]); + } + const ParseErrorConstructors = {}; + for (const reasonCode of Object.keys(argument)) { + const template = argument[reasonCode]; + const _ref = typeof template === "string" ? { + message: () => template + } : typeof template === "function" ? { + message: template + } : template, + { + message + } = _ref, + rest = _objectWithoutPropertiesLoose(_ref, _excluded); + const toMessage = typeof message === "string" ? () => message : message; + ParseErrorConstructors[reasonCode] = toParseErrorConstructor(Object.assign({ + code: "BABEL_PARSER_SYNTAX_ERROR", + reasonCode, + toMessage + }, syntaxPlugin ? { + syntaxPlugin + } : {}, rest)); + } + return ParseErrorConstructors; +} +const Errors = Object.assign({}, ParseErrorEnum(ModuleErrors), ParseErrorEnum(StandardErrors), ParseErrorEnum(StrictModeErrors), ParseErrorEnum(ParseExpressionErrors), ParseErrorEnum`pipelineOperator`(PipelineOperatorErrors)); +function createDefaultOptions() { + return { + sourceType: "script", + sourceFilename: undefined, + startIndex: 0, + startColumn: 0, + startLine: 1, + allowAwaitOutsideFunction: false, + allowReturnOutsideFunction: false, + allowNewTargetOutsideFunction: false, + allowImportExportEverywhere: false, + allowSuperOutsideMethod: false, + allowUndeclaredExports: false, + allowYieldOutsideFunction: false, + plugins: [], + strictMode: undefined, + ranges: false, + tokens: false, + createImportExpressions: false, + createParenthesizedExpressions: false, + errorRecovery: false, + attachComment: true, + annexB: true + }; +} +function getOptions(opts) { + const options = createDefaultOptions(); + if (opts == null) { + return options; + } + if (opts.annexB != null && opts.annexB !== false) { + throw new Error("The `annexB` option can only be set to `false`."); + } + for (const key of Object.keys(options)) { + if (opts[key] != null) options[key] = opts[key]; + } + if (options.startLine === 1) { + if (opts.startIndex == null && options.startColumn > 0) { + options.startIndex = options.startColumn; + } else if (opts.startColumn == null && options.startIndex > 0) { + options.startColumn = options.startIndex; + } + } else if (opts.startColumn == null || opts.startIndex == null) { + if (opts.startIndex != null) { + throw new Error("With a `startLine > 1` you must also specify `startIndex` and `startColumn`."); + } + } + if (options.sourceType === "commonjs") { + if (opts.allowAwaitOutsideFunction != null) { + throw new Error("The `allowAwaitOutsideFunction` option cannot be used with `sourceType: 'commonjs'`."); + } + if (opts.allowReturnOutsideFunction != null) { + throw new Error("`sourceType: 'commonjs'` implies `allowReturnOutsideFunction: true`, please remove the `allowReturnOutsideFunction` option or use `sourceType: 'script'`."); + } + if (opts.allowNewTargetOutsideFunction != null) { + throw new Error("`sourceType: 'commonjs'` implies `allowNewTargetOutsideFunction: true`, please remove the `allowNewTargetOutsideFunction` option or use `sourceType: 'script'`."); + } + } + return options; +} +const { + defineProperty +} = Object; +const toUnenumerable = (object, key) => { + if (object) { + defineProperty(object, key, { + enumerable: false, + value: object[key] + }); + } +}; +function toESTreeLocation(node) { + toUnenumerable(node.loc.start, "index"); + toUnenumerable(node.loc.end, "index"); + return node; +} +var estree = superClass => class ESTreeParserMixin extends superClass { + parse() { + const file = toESTreeLocation(super.parse()); + if (this.optionFlags & 256) { + file.tokens = file.tokens.map(toESTreeLocation); + } + return file; + } + parseRegExpLiteral({ + pattern, + flags + }) { + let regex = null; + try { + regex = new RegExp(pattern, flags); + } catch (_) {} + const node = this.estreeParseLiteral(regex); + node.regex = { + pattern, + flags + }; + return node; + } + parseBigIntLiteral(value) { + let bigInt; + try { + bigInt = BigInt(value); + } catch (_unused) { + bigInt = null; + } + const node = this.estreeParseLiteral(bigInt); + node.bigint = String(node.value || value); + return node; + } + parseDecimalLiteral(value) { + const decimal = null; + const node = this.estreeParseLiteral(decimal); + node.decimal = String(node.value || value); + return node; + } + estreeParseLiteral(value) { + return this.parseLiteral(value, "Literal"); + } + parseStringLiteral(value) { + return this.estreeParseLiteral(value); + } + parseNumericLiteral(value) { + return this.estreeParseLiteral(value); + } + parseNullLiteral() { + return this.estreeParseLiteral(null); + } + parseBooleanLiteral(value) { + return this.estreeParseLiteral(value); + } + estreeParseChainExpression(node, endLoc) { + const chain = this.startNodeAtNode(node); + chain.expression = node; + return this.finishNodeAt(chain, "ChainExpression", endLoc); + } + directiveToStmt(directive) { + const expression = directive.value; + delete directive.value; + this.castNodeTo(expression, "Literal"); + expression.raw = expression.extra.raw; + expression.value = expression.extra.expressionValue; + const stmt = this.castNodeTo(directive, "ExpressionStatement"); + stmt.expression = expression; + stmt.directive = expression.extra.rawValue; + delete expression.extra; + return stmt; + } + fillOptionalPropertiesForTSESLint(node) {} + cloneEstreeStringLiteral(node) { + const { + start, + end, + loc, + range, + raw, + value + } = node; + const cloned = Object.create(node.constructor.prototype); + cloned.type = "Literal"; + cloned.start = start; + cloned.end = end; + cloned.loc = loc; + cloned.range = range; + cloned.raw = raw; + cloned.value = value; + return cloned; + } + initFunction(node, isAsync) { + super.initFunction(node, isAsync); + node.expression = false; + } + checkDeclaration(node) { + if (node != null && this.isObjectProperty(node)) { + this.checkDeclaration(node.value); + } else { + super.checkDeclaration(node); + } + } + getObjectOrClassMethodParams(method) { + return method.value.params; + } + isValidDirective(stmt) { + var _stmt$expression$extr; + return stmt.type === "ExpressionStatement" && stmt.expression.type === "Literal" && typeof stmt.expression.value === "string" && !((_stmt$expression$extr = stmt.expression.extra) != null && _stmt$expression$extr.parenthesized); + } + parseBlockBody(node, allowDirectives, topLevel, end, afterBlockParse) { + super.parseBlockBody(node, allowDirectives, topLevel, end, afterBlockParse); + const directiveStatements = node.directives.map(d => this.directiveToStmt(d)); + node.body = directiveStatements.concat(node.body); + delete node.directives; + } + parsePrivateName() { + const node = super.parsePrivateName(); + if (!this.getPluginOption("estree", "classFeatures")) { + return node; + } + return this.convertPrivateNameToPrivateIdentifier(node); + } + convertPrivateNameToPrivateIdentifier(node) { + const name = super.getPrivateNameSV(node); + delete node.id; + node.name = name; + return this.castNodeTo(node, "PrivateIdentifier"); + } + isPrivateName(node) { + if (!this.getPluginOption("estree", "classFeatures")) { + return super.isPrivateName(node); + } + return node.type === "PrivateIdentifier"; + } + getPrivateNameSV(node) { + if (!this.getPluginOption("estree", "classFeatures")) { + return super.getPrivateNameSV(node); + } + return node.name; + } + parseLiteral(value, type) { + const node = super.parseLiteral(value, type); + node.raw = node.extra.raw; + delete node.extra; + return node; + } + parseFunctionBody(node, allowExpression, isMethod = false) { + super.parseFunctionBody(node, allowExpression, isMethod); + node.expression = node.body.type !== "BlockStatement"; + } + parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) { + let funcNode = this.startNode(); + funcNode.kind = node.kind; + funcNode = super.parseMethod(funcNode, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope); + delete funcNode.kind; + const { + typeParameters + } = node; + if (typeParameters) { + delete node.typeParameters; + funcNode.typeParameters = typeParameters; + this.resetStartLocationFromNode(funcNode, typeParameters); + } + const valueNode = this.castNodeTo(funcNode, "FunctionExpression"); + node.value = valueNode; + if (type === "ClassPrivateMethod") { + node.computed = false; + } + if (type === "ObjectMethod") { + if (node.kind === "method") { + node.kind = "init"; + } + node.shorthand = false; + return this.finishNode(node, "Property"); + } else { + return this.finishNode(node, "MethodDefinition"); + } + } + nameIsConstructor(key) { + if (key.type === "Literal") return key.value === "constructor"; + return super.nameIsConstructor(key); + } + parseClassProperty(...args) { + const propertyNode = super.parseClassProperty(...args); + if (!this.getPluginOption("estree", "classFeatures")) { + return propertyNode; + } + this.castNodeTo(propertyNode, "PropertyDefinition"); + return propertyNode; + } + parseClassPrivateProperty(...args) { + const propertyNode = super.parseClassPrivateProperty(...args); + if (!this.getPluginOption("estree", "classFeatures")) { + return propertyNode; + } + this.castNodeTo(propertyNode, "PropertyDefinition"); + propertyNode.computed = false; + return propertyNode; + } + parseClassAccessorProperty(node) { + const accessorPropertyNode = super.parseClassAccessorProperty(node); + if (!this.getPluginOption("estree", "classFeatures")) { + return accessorPropertyNode; + } + if (accessorPropertyNode.abstract && this.hasPlugin("typescript")) { + delete accessorPropertyNode.abstract; + this.castNodeTo(accessorPropertyNode, "TSAbstractAccessorProperty"); + } else { + this.castNodeTo(accessorPropertyNode, "AccessorProperty"); + } + return accessorPropertyNode; + } + parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors) { + const node = super.parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors); + if (node) { + node.kind = "init"; + this.castNodeTo(node, "Property"); + } + return node; + } + finishObjectProperty(node) { + node.kind = "init"; + return this.finishNode(node, "Property"); + } + isValidLVal(type, disallowCallExpression, isUnparenthesizedInAssign, binding) { + return type === "Property" ? "value" : super.isValidLVal(type, disallowCallExpression, isUnparenthesizedInAssign, binding); + } + isAssignable(node, isBinding) { + if (node != null && this.isObjectProperty(node)) { + return this.isAssignable(node.value, isBinding); + } + return super.isAssignable(node, isBinding); + } + toAssignable(node, isLHS = false) { + if (node != null && this.isObjectProperty(node)) { + const { + key, + value + } = node; + if (this.isPrivateName(key)) { + this.classScope.usePrivateName(this.getPrivateNameSV(key), key.loc.start); + } + this.toAssignable(value, isLHS); + } else { + super.toAssignable(node, isLHS); + } + } + toAssignableObjectExpressionProp(prop, isLast, isLHS) { + if (prop.type === "Property" && (prop.kind === "get" || prop.kind === "set")) { + this.raise(Errors.PatternHasAccessor, prop.key); + } else if (prop.type === "Property" && prop.method) { + this.raise(Errors.PatternHasMethod, prop.key); + } else { + super.toAssignableObjectExpressionProp(prop, isLast, isLHS); + } + } + finishCallExpression(unfinished, optional) { + const node = super.finishCallExpression(unfinished, optional); + if (node.callee.type === "Import") { + var _ref, _ref2; + this.castNodeTo(node, "ImportExpression"); + node.source = node.arguments[0]; + node.options = (_ref = node.arguments[1]) != null ? _ref : null; + node.attributes = (_ref2 = node.arguments[1]) != null ? _ref2 : null; + delete node.arguments; + delete node.callee; + } else if (node.type === "OptionalCallExpression") { + this.castNodeTo(node, "CallExpression"); + } else { + node.optional = false; + } + return node; + } + toReferencedArguments(node) { + if (node.type === "ImportExpression") { + return; + } + super.toReferencedArguments(node); + } + parseExport(unfinished, decorators) { + const exportStartLoc = this.state.lastTokStartLoc; + const node = super.parseExport(unfinished, decorators); + switch (node.type) { + case "ExportAllDeclaration": + node.exported = null; + break; + case "ExportNamedDeclaration": + if (node.specifiers.length === 1 && node.specifiers[0].type === "ExportNamespaceSpecifier") { + this.castNodeTo(node, "ExportAllDeclaration"); + node.exported = node.specifiers[0].exported; + delete node.specifiers; + } + case "ExportDefaultDeclaration": + { + var _declaration$decorato; + const { + declaration + } = node; + if ((declaration == null ? void 0 : declaration.type) === "ClassDeclaration" && ((_declaration$decorato = declaration.decorators) == null ? void 0 : _declaration$decorato.length) > 0 && declaration.start === node.start) { + this.resetStartLocation(node, exportStartLoc); + } + } + break; + } + return node; + } + stopParseSubscript(base, state) { + const node = super.stopParseSubscript(base, state); + if (state.optionalChainMember) { + return this.estreeParseChainExpression(node, base.loc.end); + } + return node; + } + parseMember(base, startLoc, state, computed, optional) { + const node = super.parseMember(base, startLoc, state, computed, optional); + if (node.type === "OptionalMemberExpression") { + this.castNodeTo(node, "MemberExpression"); + } else { + node.optional = false; + } + return node; + } + isOptionalMemberExpression(node) { + if (node.type === "ChainExpression") { + return node.expression.type === "MemberExpression"; + } + return super.isOptionalMemberExpression(node); + } + hasPropertyAsPrivateName(node) { + if (node.type === "ChainExpression") { + node = node.expression; + } + return super.hasPropertyAsPrivateName(node); + } + isObjectProperty(node) { + return node.type === "Property" && node.kind === "init" && !node.method; + } + isObjectMethod(node) { + return node.type === "Property" && (node.method || node.kind === "get" || node.kind === "set"); + } + castNodeTo(node, type) { + const result = super.castNodeTo(node, type); + this.fillOptionalPropertiesForTSESLint(result); + return result; + } + cloneIdentifier(node) { + const cloned = super.cloneIdentifier(node); + this.fillOptionalPropertiesForTSESLint(cloned); + return cloned; + } + cloneStringLiteral(node) { + if (node.type === "Literal") { + return this.cloneEstreeStringLiteral(node); + } + return super.cloneStringLiteral(node); + } + finishNodeAt(node, type, endLoc) { + return toESTreeLocation(super.finishNodeAt(node, type, endLoc)); + } + finishNode(node, type) { + const result = super.finishNode(node, type); + this.fillOptionalPropertiesForTSESLint(result); + return result; + } + resetStartLocation(node, startLoc) { + super.resetStartLocation(node, startLoc); + toESTreeLocation(node); + } + resetEndLocation(node, endLoc = this.state.lastTokEndLoc) { + super.resetEndLocation(node, endLoc); + toESTreeLocation(node); + } +}; +class TokContext { + constructor(token, preserveSpace) { + this.token = void 0; + this.preserveSpace = void 0; + this.token = token; + this.preserveSpace = !!preserveSpace; + } +} +const types = { + brace: new TokContext("{"), + j_oTag: new TokContext("...", true) +}; +types.template = new TokContext("`", true); +const beforeExpr = true; +const startsExpr = true; +const isLoop = true; +const isAssign = true; +const prefix = true; +const postfix = true; +class ExportedTokenType { + constructor(label, conf = {}) { + this.label = void 0; + this.keyword = void 0; + this.beforeExpr = void 0; + this.startsExpr = void 0; + this.rightAssociative = void 0; + this.isLoop = void 0; + this.isAssign = void 0; + this.prefix = void 0; + this.postfix = void 0; + this.binop = void 0; + this.label = label; + this.keyword = conf.keyword; + this.beforeExpr = !!conf.beforeExpr; + this.startsExpr = !!conf.startsExpr; + this.rightAssociative = !!conf.rightAssociative; + this.isLoop = !!conf.isLoop; + this.isAssign = !!conf.isAssign; + this.prefix = !!conf.prefix; + this.postfix = !!conf.postfix; + this.binop = conf.binop != null ? conf.binop : null; + this.updateContext = null; + } +} +const keywords$1 = new Map(); +function createKeyword(name, options = {}) { + options.keyword = name; + const token = createToken(name, options); + keywords$1.set(name, token); + return token; +} +function createBinop(name, binop) { + return createToken(name, { + beforeExpr, + binop + }); +} +let tokenTypeCounter = -1; +const tokenTypes = []; +const tokenLabels = []; +const tokenBinops = []; +const tokenBeforeExprs = []; +const tokenStartsExprs = []; +const tokenPrefixes = []; +function createToken(name, options = {}) { + var _options$binop, _options$beforeExpr, _options$startsExpr, _options$prefix; + ++tokenTypeCounter; + tokenLabels.push(name); + tokenBinops.push((_options$binop = options.binop) != null ? _options$binop : -1); + tokenBeforeExprs.push((_options$beforeExpr = options.beforeExpr) != null ? _options$beforeExpr : false); + tokenStartsExprs.push((_options$startsExpr = options.startsExpr) != null ? _options$startsExpr : false); + tokenPrefixes.push((_options$prefix = options.prefix) != null ? _options$prefix : false); + tokenTypes.push(new ExportedTokenType(name, options)); + return tokenTypeCounter; +} +function createKeywordLike(name, options = {}) { + var _options$binop2, _options$beforeExpr2, _options$startsExpr2, _options$prefix2; + ++tokenTypeCounter; + keywords$1.set(name, tokenTypeCounter); + tokenLabels.push(name); + tokenBinops.push((_options$binop2 = options.binop) != null ? _options$binop2 : -1); + tokenBeforeExprs.push((_options$beforeExpr2 = options.beforeExpr) != null ? _options$beforeExpr2 : false); + tokenStartsExprs.push((_options$startsExpr2 = options.startsExpr) != null ? _options$startsExpr2 : false); + tokenPrefixes.push((_options$prefix2 = options.prefix) != null ? _options$prefix2 : false); + tokenTypes.push(new ExportedTokenType("name", options)); + return tokenTypeCounter; +} +const tt = { + bracketL: createToken("[", { + beforeExpr, + startsExpr + }), + bracketHashL: createToken("#[", { + beforeExpr, + startsExpr + }), + bracketBarL: createToken("[|", { + beforeExpr, + startsExpr + }), + bracketR: createToken("]"), + bracketBarR: createToken("|]"), + braceL: createToken("{", { + beforeExpr, + startsExpr + }), + braceBarL: createToken("{|", { + beforeExpr, + startsExpr + }), + braceHashL: createToken("#{", { + beforeExpr, + startsExpr + }), + braceR: createToken("}"), + braceBarR: createToken("|}"), + parenL: createToken("(", { + beforeExpr, + startsExpr + }), + parenR: createToken(")"), + comma: createToken(",", { + beforeExpr + }), + semi: createToken(";", { + beforeExpr + }), + colon: createToken(":", { + beforeExpr + }), + doubleColon: createToken("::", { + beforeExpr + }), + dot: createToken("."), + question: createToken("?", { + beforeExpr + }), + questionDot: createToken("?."), + arrow: createToken("=>", { + beforeExpr + }), + template: createToken("template"), + ellipsis: createToken("...", { + beforeExpr + }), + backQuote: createToken("`", { + startsExpr + }), + dollarBraceL: createToken("${", { + beforeExpr, + startsExpr + }), + templateTail: createToken("...`", { + startsExpr + }), + templateNonTail: createToken("...${", { + beforeExpr, + startsExpr + }), + at: createToken("@"), + hash: createToken("#", { + startsExpr + }), + interpreterDirective: createToken("#!..."), + eq: createToken("=", { + beforeExpr, + isAssign + }), + assign: createToken("_=", { + beforeExpr, + isAssign + }), + slashAssign: createToken("_=", { + beforeExpr, + isAssign + }), + xorAssign: createToken("_=", { + beforeExpr, + isAssign + }), + moduloAssign: createToken("_=", { + beforeExpr, + isAssign + }), + incDec: createToken("++/--", { + prefix, + postfix, + startsExpr + }), + bang: createToken("!", { + beforeExpr, + prefix, + startsExpr + }), + tilde: createToken("~", { + beforeExpr, + prefix, + startsExpr + }), + doubleCaret: createToken("^^", { + startsExpr + }), + doubleAt: createToken("@@", { + startsExpr + }), + pipeline: createBinop("|>", 0), + nullishCoalescing: createBinop("??", 1), + logicalOR: createBinop("||", 1), + logicalAND: createBinop("&&", 2), + bitwiseOR: createBinop("|", 3), + bitwiseXOR: createBinop("^", 4), + bitwiseAND: createBinop("&", 5), + equality: createBinop("==/!=/===/!==", 6), + lt: createBinop("/<=/>=", 7), + gt: createBinop("/<=/>=", 7), + relational: createBinop("/<=/>=", 7), + bitShift: createBinop("<>/>>>", 8), + bitShiftL: createBinop("<>/>>>", 8), + bitShiftR: createBinop("<>/>>>", 8), + plusMin: createToken("+/-", { + beforeExpr, + binop: 9, + prefix, + startsExpr + }), + modulo: createToken("%", { + binop: 10, + startsExpr + }), + star: createToken("*", { + binop: 10 + }), + slash: createBinop("/", 10), + exponent: createToken("**", { + beforeExpr, + binop: 11, + rightAssociative: true + }), + _in: createKeyword("in", { + beforeExpr, + binop: 7 + }), + _instanceof: createKeyword("instanceof", { + beforeExpr, + binop: 7 + }), + _break: createKeyword("break"), + _case: createKeyword("case", { + beforeExpr + }), + _catch: createKeyword("catch"), + _continue: createKeyword("continue"), + _debugger: createKeyword("debugger"), + _default: createKeyword("default", { + beforeExpr + }), + _else: createKeyword("else", { + beforeExpr + }), + _finally: createKeyword("finally"), + _function: createKeyword("function", { + startsExpr + }), + _if: createKeyword("if"), + _return: createKeyword("return", { + beforeExpr + }), + _switch: createKeyword("switch"), + _throw: createKeyword("throw", { + beforeExpr, + prefix, + startsExpr + }), + _try: createKeyword("try"), + _var: createKeyword("var"), + _const: createKeyword("const"), + _with: createKeyword("with"), + _new: createKeyword("new", { + beforeExpr, + startsExpr + }), + _this: createKeyword("this", { + startsExpr + }), + _super: createKeyword("super", { + startsExpr + }), + _class: createKeyword("class", { + startsExpr + }), + _extends: createKeyword("extends", { + beforeExpr + }), + _export: createKeyword("export"), + _import: createKeyword("import", { + startsExpr + }), + _null: createKeyword("null", { + startsExpr + }), + _true: createKeyword("true", { + startsExpr + }), + _false: createKeyword("false", { + startsExpr + }), + _typeof: createKeyword("typeof", { + beforeExpr, + prefix, + startsExpr + }), + _void: createKeyword("void", { + beforeExpr, + prefix, + startsExpr + }), + _delete: createKeyword("delete", { + beforeExpr, + prefix, + startsExpr + }), + _do: createKeyword("do", { + isLoop, + beforeExpr + }), + _for: createKeyword("for", { + isLoop + }), + _while: createKeyword("while", { + isLoop + }), + _as: createKeywordLike("as", { + startsExpr + }), + _assert: createKeywordLike("assert", { + startsExpr + }), + _async: createKeywordLike("async", { + startsExpr + }), + _await: createKeywordLike("await", { + startsExpr + }), + _defer: createKeywordLike("defer", { + startsExpr + }), + _from: createKeywordLike("from", { + startsExpr + }), + _get: createKeywordLike("get", { + startsExpr + }), + _let: createKeywordLike("let", { + startsExpr + }), + _meta: createKeywordLike("meta", { + startsExpr + }), + _of: createKeywordLike("of", { + startsExpr + }), + _sent: createKeywordLike("sent", { + startsExpr + }), + _set: createKeywordLike("set", { + startsExpr + }), + _source: createKeywordLike("source", { + startsExpr + }), + _static: createKeywordLike("static", { + startsExpr + }), + _using: createKeywordLike("using", { + startsExpr + }), + _yield: createKeywordLike("yield", { + startsExpr + }), + _asserts: createKeywordLike("asserts", { + startsExpr + }), + _checks: createKeywordLike("checks", { + startsExpr + }), + _exports: createKeywordLike("exports", { + startsExpr + }), + _global: createKeywordLike("global", { + startsExpr + }), + _implements: createKeywordLike("implements", { + startsExpr + }), + _intrinsic: createKeywordLike("intrinsic", { + startsExpr + }), + _infer: createKeywordLike("infer", { + startsExpr + }), + _is: createKeywordLike("is", { + startsExpr + }), + _mixins: createKeywordLike("mixins", { + startsExpr + }), + _proto: createKeywordLike("proto", { + startsExpr + }), + _require: createKeywordLike("require", { + startsExpr + }), + _satisfies: createKeywordLike("satisfies", { + startsExpr + }), + _keyof: createKeywordLike("keyof", { + startsExpr + }), + _readonly: createKeywordLike("readonly", { + startsExpr + }), + _unique: createKeywordLike("unique", { + startsExpr + }), + _abstract: createKeywordLike("abstract", { + startsExpr + }), + _declare: createKeywordLike("declare", { + startsExpr + }), + _enum: createKeywordLike("enum", { + startsExpr + }), + _module: createKeywordLike("module", { + startsExpr + }), + _namespace: createKeywordLike("namespace", { + startsExpr + }), + _interface: createKeywordLike("interface", { + startsExpr + }), + _type: createKeywordLike("type", { + startsExpr + }), + _opaque: createKeywordLike("opaque", { + startsExpr + }), + name: createToken("name", { + startsExpr + }), + placeholder: createToken("%%", { + startsExpr + }), + string: createToken("string", { + startsExpr + }), + num: createToken("num", { + startsExpr + }), + bigint: createToken("bigint", { + startsExpr + }), + decimal: createToken("decimal", { + startsExpr + }), + regexp: createToken("regexp", { + startsExpr + }), + privateName: createToken("#name", { + startsExpr + }), + eof: createToken("eof"), + jsxName: createToken("jsxName"), + jsxText: createToken("jsxText", { + beforeExpr + }), + jsxTagStart: createToken("jsxTagStart", { + startsExpr + }), + jsxTagEnd: createToken("jsxTagEnd") +}; +function tokenIsIdentifier(token) { + return token >= 93 && token <= 133; +} +function tokenKeywordOrIdentifierIsKeyword(token) { + return token <= 92; +} +function tokenIsKeywordOrIdentifier(token) { + return token >= 58 && token <= 133; +} +function tokenIsLiteralPropertyName(token) { + return token >= 58 && token <= 137; +} +function tokenComesBeforeExpression(token) { + return tokenBeforeExprs[token]; +} +function tokenCanStartExpression(token) { + return tokenStartsExprs[token]; +} +function tokenIsAssignment(token) { + return token >= 29 && token <= 33; +} +function tokenIsFlowInterfaceOrTypeOrOpaque(token) { + return token >= 129 && token <= 131; +} +function tokenIsLoop(token) { + return token >= 90 && token <= 92; +} +function tokenIsKeyword(token) { + return token >= 58 && token <= 92; +} +function tokenIsOperator(token) { + return token >= 39 && token <= 59; +} +function tokenIsPostfix(token) { + return token === 34; +} +function tokenIsPrefix(token) { + return tokenPrefixes[token]; +} +function tokenIsTSTypeOperator(token) { + return token >= 121 && token <= 123; +} +function tokenIsTSDeclarationStart(token) { + return token >= 124 && token <= 130; +} +function tokenLabelName(token) { + return tokenLabels[token]; +} +function tokenOperatorPrecedence(token) { + return tokenBinops[token]; +} +function tokenIsRightAssociative(token) { + return token === 57; +} +function tokenIsTemplate(token) { + return token >= 24 && token <= 25; +} +function getExportedToken(token) { + return tokenTypes[token]; +} +tokenTypes[8].updateContext = context => { + context.pop(); +}; +tokenTypes[5].updateContext = tokenTypes[7].updateContext = tokenTypes[23].updateContext = context => { + context.push(types.brace); +}; +tokenTypes[22].updateContext = context => { + if (context[context.length - 1] === types.template) { + context.pop(); + } else { + context.push(types.template); + } +}; +tokenTypes[143].updateContext = context => { + context.push(types.j_expr, types.j_oTag); +}; +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-\u088f\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\u0c5c\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdc-\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-\u1c8a\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-\ua7dc\ua7f1-\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 = "\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\u0897-\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-\u1add\u1ae0-\u1aeb\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\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\u30fb\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\uff65"; +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, 4, 51, 13, 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, 7, 25, 39, 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, 39, 27, 10, 22, 251, 41, 7, 1, 17, 5, 57, 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, 31, 9, 2, 0, 3, 0, 2, 37, 2, 0, 26, 0, 2, 0, 45, 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, 200, 32, 32, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 24, 43, 261, 18, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 26, 3994, 6, 582, 6842, 29, 1763, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 433, 44, 212, 63, 33, 24, 3, 24, 45, 74, 6, 0, 67, 12, 65, 1, 2, 0, 15, 4, 10, 7381, 42, 31, 98, 114, 8702, 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, 229, 29, 3, 0, 208, 30, 2, 2, 2, 1, 2, 6, 3, 4, 10, 1, 225, 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, 4381, 3, 5773, 3, 7472, 16, 621, 2467, 541, 1507, 4938, 6, 8489]; +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, 7, 9, 32, 4, 318, 1, 78, 5, 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, 68, 8, 2, 0, 3, 0, 2, 3, 2, 4, 2, 0, 15, 1, 83, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 7, 19, 58, 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, 199, 7, 137, 9, 54, 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, 55, 9, 266, 3, 10, 1, 2, 0, 49, 6, 4, 4, 14, 10, 5350, 0, 7, 14, 11465, 27, 2343, 9, 87, 9, 39, 4, 60, 6, 26, 9, 535, 9, 470, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4178, 9, 519, 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, 245, 1, 2, 9, 233, 0, 3, 0, 8, 1, 6, 0, 475, 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); +} +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); +} +function isIteratorStart(current, next, next2) { + return current === 64 && next === 64 && isIdentifierStart(next2); +} +const reservedWordLikeSet = new Set(["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", "implements", "interface", "let", "package", "private", "protected", "public", "static", "yield", "eval", "arguments", "enum", "await"]); +function canBeReservedWord(word) { + return reservedWordLikeSet.has(word); +} +class Scope { + constructor(flags) { + this.flags = 0; + this.names = new Map(); + this.firstLexicalName = ""; + this.flags = flags; + } +} +class ScopeHandler { + constructor(parser, inModule) { + this.parser = void 0; + this.scopeStack = []; + this.inModule = void 0; + this.undefinedExports = new Map(); + this.parser = parser; + this.inModule = inModule; + } + get inTopLevel() { + return (this.currentScope().flags & 1) > 0; + } + get inFunction() { + return (this.currentVarScopeFlags() & 2) > 0; + } + get allowSuper() { + return (this.currentThisScopeFlags() & 16) > 0; + } + get allowDirectSuper() { + return (this.currentThisScopeFlags() & 32) > 0; + } + get allowNewTarget() { + return (this.currentThisScopeFlags() & 512) > 0; + } + get inClass() { + return (this.currentThisScopeFlags() & 64) > 0; + } + get inClassAndNotInNonArrowFunction() { + const flags = this.currentThisScopeFlags(); + return (flags & 64) > 0 && (flags & 2) === 0; + } + get inStaticBlock() { + for (let i = this.scopeStack.length - 1;; i--) { + const { + flags + } = this.scopeStack[i]; + if (flags & 128) { + return true; + } + if (flags & (1667 | 64)) { + return false; + } + } + } + get inNonArrowFunction() { + return (this.currentThisScopeFlags() & 2) > 0; + } + get inBareCaseStatement() { + return (this.currentScope().flags & 256) > 0; + } + get treatFunctionsAsVar() { + return this.treatFunctionsAsVarInScope(this.currentScope()); + } + createScope(flags) { + return new Scope(flags); + } + enter(flags) { + this.scopeStack.push(this.createScope(flags)); + } + exit() { + const scope = this.scopeStack.pop(); + return scope.flags; + } + treatFunctionsAsVarInScope(scope) { + return !!(scope.flags & (2 | 128) || !this.parser.inModule && scope.flags & 1); + } + declareName(name, bindingType, loc) { + let scope = this.currentScope(); + if (bindingType & 8 || bindingType & 16) { + this.checkRedeclarationInScope(scope, name, bindingType, loc); + let type = scope.names.get(name) || 0; + if (bindingType & 16) { + type = type | 4; + } else { + if (!scope.firstLexicalName) { + scope.firstLexicalName = name; + } + type = type | 2; + } + scope.names.set(name, type); + if (bindingType & 8) { + this.maybeExportDefined(scope, name); + } + } else if (bindingType & 4) { + for (let i = this.scopeStack.length - 1; i >= 0; --i) { + scope = this.scopeStack[i]; + this.checkRedeclarationInScope(scope, name, bindingType, loc); + scope.names.set(name, (scope.names.get(name) || 0) | 1); + this.maybeExportDefined(scope, name); + if (scope.flags & 1667) break; + } + } + if (this.parser.inModule && scope.flags & 1) { + this.undefinedExports.delete(name); + } + } + maybeExportDefined(scope, name) { + if (this.parser.inModule && scope.flags & 1) { + this.undefinedExports.delete(name); + } + } + checkRedeclarationInScope(scope, name, bindingType, loc) { + if (this.isRedeclaredInScope(scope, name, bindingType)) { + this.parser.raise(Errors.VarRedeclaration, loc, { + identifierName: name + }); + } + } + isRedeclaredInScope(scope, name, bindingType) { + if (!(bindingType & 1)) return false; + if (bindingType & 8) { + return scope.names.has(name); + } + const type = scope.names.get(name) || 0; + if (bindingType & 16) { + return (type & 2) > 0 || !this.treatFunctionsAsVarInScope(scope) && (type & 1) > 0; + } + return (type & 2) > 0 && !(scope.flags & 8 && scope.firstLexicalName === name) || !this.treatFunctionsAsVarInScope(scope) && (type & 4) > 0; + } + checkLocalExport(id) { + const { + name + } = id; + const topLevelScope = this.scopeStack[0]; + if (!topLevelScope.names.has(name)) { + this.undefinedExports.set(name, id.loc.start); + } + } + currentScope() { + return this.scopeStack[this.scopeStack.length - 1]; + } + currentVarScopeFlags() { + for (let i = this.scopeStack.length - 1;; i--) { + const { + flags + } = this.scopeStack[i]; + if (flags & 1667) { + return flags; + } + } + } + currentThisScopeFlags() { + for (let i = this.scopeStack.length - 1;; i--) { + const { + flags + } = this.scopeStack[i]; + if (flags & (1667 | 64) && !(flags & 4)) { + return flags; + } + } + } +} +class FlowScope extends Scope { + constructor(...args) { + super(...args); + this.declareFunctions = new Set(); + } +} +class FlowScopeHandler extends ScopeHandler { + createScope(flags) { + return new FlowScope(flags); + } + declareName(name, bindingType, loc) { + const scope = this.currentScope(); + if (bindingType & 2048) { + this.checkRedeclarationInScope(scope, name, bindingType, loc); + this.maybeExportDefined(scope, name); + scope.declareFunctions.add(name); + return; + } + super.declareName(name, bindingType, loc); + } + isRedeclaredInScope(scope, name, bindingType) { + if (super.isRedeclaredInScope(scope, name, bindingType)) return true; + if (bindingType & 2048 && !scope.declareFunctions.has(name)) { + const type = scope.names.get(name); + return (type & 4) > 0 || (type & 2) > 0; + } + return false; + } + checkLocalExport(id) { + if (!this.scopeStack[0].declareFunctions.has(id.name)) { + super.checkLocalExport(id); + } + } +} +const reservedTypes = new Set(["_", "any", "bool", "boolean", "empty", "extends", "false", "interface", "mixed", "null", "number", "static", "string", "true", "typeof", "void"]); +const FlowErrors = ParseErrorEnum`flow`({ + AmbiguousConditionalArrow: "Ambiguous expression: wrap the arrow functions in parentheses to disambiguate.", + AmbiguousDeclareModuleKind: "Found both `declare module.exports` and `declare export` in the same module. Modules can only have 1 since they are either an ES module or they are a CommonJS module.", + AssignReservedType: ({ + reservedType + }) => `Cannot overwrite reserved type ${reservedType}.`, + DeclareClassElement: "The `declare` modifier can only appear on class fields.", + DeclareClassFieldInitializer: "Initializers are not allowed in fields with the `declare` modifier.", + DuplicateDeclareModuleExports: "Duplicate `declare module.exports` statement.", + EnumBooleanMemberNotInitialized: ({ + memberName, + enumName + }) => `Boolean enum members need to be initialized. Use either \`${memberName} = true,\` or \`${memberName} = false,\` in enum \`${enumName}\`.`, + EnumDuplicateMemberName: ({ + memberName, + enumName + }) => `Enum member names need to be unique, but the name \`${memberName}\` has already been used before in enum \`${enumName}\`.`, + EnumInconsistentMemberValues: ({ + enumName + }) => `Enum \`${enumName}\` has inconsistent member initializers. Either use no initializers, or consistently use literals (either booleans, numbers, or strings) for all member initializers.`, + EnumInvalidExplicitType: ({ + invalidEnumType, + enumName + }) => `Enum type \`${invalidEnumType}\` is not valid. Use one of \`boolean\`, \`number\`, \`string\`, or \`symbol\` in enum \`${enumName}\`.`, + EnumInvalidExplicitTypeUnknownSupplied: ({ + enumName + }) => `Supplied enum type is not valid. Use one of \`boolean\`, \`number\`, \`string\`, or \`symbol\` in enum \`${enumName}\`.`, + EnumInvalidMemberInitializerPrimaryType: ({ + enumName, + memberName, + explicitType + }) => `Enum \`${enumName}\` has type \`${explicitType}\`, so the initializer of \`${memberName}\` needs to be a ${explicitType} literal.`, + EnumInvalidMemberInitializerSymbolType: ({ + enumName, + memberName + }) => `Symbol enum members cannot be initialized. Use \`${memberName},\` in enum \`${enumName}\`.`, + EnumInvalidMemberInitializerUnknownType: ({ + enumName, + memberName + }) => `The enum member initializer for \`${memberName}\` needs to be a literal (either a boolean, number, or string) in enum \`${enumName}\`.`, + EnumInvalidMemberName: ({ + enumName, + memberName, + suggestion + }) => `Enum member names cannot start with lowercase 'a' through 'z'. Instead of using \`${memberName}\`, consider using \`${suggestion}\`, in enum \`${enumName}\`.`, + EnumNumberMemberNotInitialized: ({ + enumName, + memberName + }) => `Number enum members need to be initialized, e.g. \`${memberName} = 1\` in enum \`${enumName}\`.`, + EnumStringMemberInconsistentlyInitialized: ({ + enumName + }) => `String enum members need to consistently either all use initializers, or use no initializers, in enum \`${enumName}\`.`, + GetterMayNotHaveThisParam: "A getter cannot have a `this` parameter.", + ImportReflectionHasImportType: "An `import module` declaration can not use `type` or `typeof` keyword.", + ImportTypeShorthandOnlyInPureImport: "The `type` and `typeof` keywords on named imports can only be used on regular `import` statements. It cannot be used with `import type` or `import typeof` statements.", + InexactInsideExact: "Explicit inexact syntax cannot appear inside an explicit exact object type.", + InexactInsideNonObject: "Explicit inexact syntax cannot appear in class or interface definitions.", + InexactVariance: "Explicit inexact syntax cannot have variance.", + InvalidNonTypeImportInDeclareModule: "Imports within a `declare module` body must always be `import type` or `import typeof`.", + MissingTypeParamDefault: "Type parameter declaration needs a default, since a preceding type parameter declaration has a default.", + NestedDeclareModule: "`declare module` cannot be used inside another `declare module`.", + NestedFlowComment: "Cannot have a flow comment inside another flow comment.", + PatternIsOptional: Object.assign({ + message: "A binding pattern parameter cannot be optional in an implementation signature." + }, { + reasonCode: "OptionalBindingPattern" + }), + SetterMayNotHaveThisParam: "A setter cannot have a `this` parameter.", + SpreadVariance: "Spread properties cannot have variance.", + ThisParamAnnotationRequired: "A type annotation is required for the `this` parameter.", + ThisParamBannedInConstructor: "Constructors cannot have a `this` parameter; constructors don't bind `this` like other functions.", + ThisParamMayNotBeOptional: "The `this` parameter cannot be optional.", + ThisParamMustBeFirst: "The `this` parameter must be the first function parameter.", + ThisParamNoDefault: "The `this` parameter may not have a default value.", + TypeBeforeInitializer: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.", + TypeCastInPattern: "The type cast expression is expected to be wrapped with parenthesis.", + UnexpectedExplicitInexactInObject: "Explicit inexact syntax must appear at the end of an inexact object.", + UnexpectedReservedType: ({ + reservedType + }) => `Unexpected reserved type ${reservedType}.`, + UnexpectedReservedUnderscore: "`_` is only allowed as a type argument to call or new.", + UnexpectedSpaceBetweenModuloChecks: "Spaces between `%` and `checks` are not allowed here.", + UnexpectedSpreadType: "Spread operator cannot appear in class or interface definitions.", + UnexpectedSubtractionOperand: 'Unexpected token, expected "number" or "bigint".', + UnexpectedTokenAfterTypeParameter: "Expected an arrow function after this type parameter declaration.", + UnexpectedTypeParameterBeforeAsyncArrowFunction: "Type parameters must come after the async keyword, e.g. instead of ` async () => {}`, use `async () => {}`.", + UnsupportedDeclareExportKind: ({ + unsupportedExportKind, + suggestion + }) => `\`declare export ${unsupportedExportKind}\` is not supported. Use \`${suggestion}\` instead.`, + UnsupportedStatementInDeclareModule: "Only declares and type imports are allowed inside declare module.", + UnterminatedFlowComment: "Unterminated flow-comment." +}); +function isEsModuleType(bodyElement) { + return bodyElement.type === "DeclareExportAllDeclaration" || bodyElement.type === "DeclareExportDeclaration" && (!bodyElement.declaration || bodyElement.declaration.type !== "TypeAlias" && bodyElement.declaration.type !== "InterfaceDeclaration"); +} +function hasTypeImportKind(node) { + return node.importKind === "type" || node.importKind === "typeof"; +} +const exportSuggestions = { + const: "declare export var", + let: "declare export var", + type: "export type", + interface: "export interface" +}; +function partition(list, test) { + const list1 = []; + const list2 = []; + for (let i = 0; i < list.length; i++) { + (test(list[i], i, list) ? list1 : list2).push(list[i]); + } + return [list1, list2]; +} +const FLOW_PRAGMA_REGEX = /\*?\s*@((?:no)?flow)\b/; +var flow = superClass => class FlowParserMixin extends superClass { + constructor(...args) { + super(...args); + this.flowPragma = undefined; + } + getScopeHandler() { + return FlowScopeHandler; + } + shouldParseTypes() { + return this.getPluginOption("flow", "all") || this.flowPragma === "flow"; + } + finishToken(type, val) { + if (type !== 134 && type !== 13 && type !== 28) { + if (this.flowPragma === undefined) { + this.flowPragma = null; + } + } + super.finishToken(type, val); + } + addComment(comment) { + if (this.flowPragma === undefined) { + const matches = FLOW_PRAGMA_REGEX.exec(comment.value); + if (!matches) ;else if (matches[1] === "flow") { + this.flowPragma = "flow"; + } else if (matches[1] === "noflow") { + this.flowPragma = "noflow"; + } else { + throw new Error("Unexpected flow pragma"); + } + } + super.addComment(comment); + } + flowParseTypeInitialiser(tok) { + const oldInType = this.state.inType; + this.state.inType = true; + this.expect(tok || 14); + const type = this.flowParseType(); + this.state.inType = oldInType; + return type; + } + flowParsePredicate() { + const node = this.startNode(); + const moduloLoc = this.state.startLoc; + this.next(); + this.expectContextual(110); + if (this.state.lastTokStartLoc.index > moduloLoc.index + 1) { + this.raise(FlowErrors.UnexpectedSpaceBetweenModuloChecks, moduloLoc); + } + if (this.eat(10)) { + node.value = super.parseExpression(); + this.expect(11); + return this.finishNode(node, "DeclaredPredicate"); + } else { + return this.finishNode(node, "InferredPredicate"); + } + } + flowParseTypeAndPredicateInitialiser() { + const oldInType = this.state.inType; + this.state.inType = true; + this.expect(14); + let type = null; + let predicate = null; + if (this.match(54)) { + this.state.inType = oldInType; + predicate = this.flowParsePredicate(); + } else { + type = this.flowParseType(); + this.state.inType = oldInType; + if (this.match(54)) { + predicate = this.flowParsePredicate(); + } + } + return [type, predicate]; + } + flowParseDeclareClass(node) { + this.next(); + this.flowParseInterfaceish(node, true); + return this.finishNode(node, "DeclareClass"); + } + flowParseDeclareFunction(node) { + this.next(); + const id = node.id = this.parseIdentifier(); + const typeNode = this.startNode(); + const typeContainer = this.startNode(); + if (this.match(47)) { + typeNode.typeParameters = this.flowParseTypeParameterDeclaration(); + } else { + typeNode.typeParameters = null; + } + this.expect(10); + const tmp = this.flowParseFunctionTypeParams(); + typeNode.params = tmp.params; + typeNode.rest = tmp.rest; + typeNode.this = tmp._this; + this.expect(11); + [typeNode.returnType, node.predicate] = this.flowParseTypeAndPredicateInitialiser(); + typeContainer.typeAnnotation = this.finishNode(typeNode, "FunctionTypeAnnotation"); + id.typeAnnotation = this.finishNode(typeContainer, "TypeAnnotation"); + this.resetEndLocation(id); + this.semicolon(); + this.scope.declareName(node.id.name, 2048, node.id.loc.start); + return this.finishNode(node, "DeclareFunction"); + } + flowParseDeclare(node, insideModule) { + if (this.match(80)) { + return this.flowParseDeclareClass(node); + } else if (this.match(68)) { + return this.flowParseDeclareFunction(node); + } else if (this.match(74)) { + return this.flowParseDeclareVariable(node); + } else if (this.eatContextual(127)) { + if (this.match(16)) { + return this.flowParseDeclareModuleExports(node); + } else { + if (insideModule) { + this.raise(FlowErrors.NestedDeclareModule, this.state.lastTokStartLoc); + } + return this.flowParseDeclareModule(node); + } + } else if (this.isContextual(130)) { + return this.flowParseDeclareTypeAlias(node); + } else if (this.isContextual(131)) { + return this.flowParseDeclareOpaqueType(node); + } else if (this.isContextual(129)) { + return this.flowParseDeclareInterface(node); + } else if (this.match(82)) { + return this.flowParseDeclareExportDeclaration(node, insideModule); + } + throw this.unexpected(); + } + flowParseDeclareVariable(node) { + this.next(); + node.id = this.flowParseTypeAnnotatableIdentifier(true); + this.scope.declareName(node.id.name, 5, node.id.loc.start); + this.semicolon(); + return this.finishNode(node, "DeclareVariable"); + } + flowParseDeclareModule(node) { + this.scope.enter(0); + if (this.match(134)) { + node.id = super.parseExprAtom(); + } else { + node.id = this.parseIdentifier(); + } + const bodyNode = node.body = this.startNode(); + const body = bodyNode.body = []; + this.expect(5); + while (!this.match(8)) { + const bodyNode = this.startNode(); + if (this.match(83)) { + this.next(); + if (!this.isContextual(130) && !this.match(87)) { + this.raise(FlowErrors.InvalidNonTypeImportInDeclareModule, this.state.lastTokStartLoc); + } + body.push(super.parseImport(bodyNode)); + } else { + this.expectContextual(125, FlowErrors.UnsupportedStatementInDeclareModule); + body.push(this.flowParseDeclare(bodyNode, true)); + } + } + this.scope.exit(); + this.expect(8); + this.finishNode(bodyNode, "BlockStatement"); + let kind = null; + let hasModuleExport = false; + body.forEach(bodyElement => { + if (isEsModuleType(bodyElement)) { + if (kind === "CommonJS") { + this.raise(FlowErrors.AmbiguousDeclareModuleKind, bodyElement); + } + kind = "ES"; + } else if (bodyElement.type === "DeclareModuleExports") { + if (hasModuleExport) { + this.raise(FlowErrors.DuplicateDeclareModuleExports, bodyElement); + } + if (kind === "ES") { + this.raise(FlowErrors.AmbiguousDeclareModuleKind, bodyElement); + } + kind = "CommonJS"; + hasModuleExport = true; + } + }); + node.kind = kind || "CommonJS"; + return this.finishNode(node, "DeclareModule"); + } + flowParseDeclareExportDeclaration(node, insideModule) { + this.expect(82); + if (this.eat(65)) { + if (this.match(68) || this.match(80)) { + node.declaration = this.flowParseDeclare(this.startNode()); + } else { + node.declaration = this.flowParseType(); + this.semicolon(); + } + node.default = true; + return this.finishNode(node, "DeclareExportDeclaration"); + } else { + if (this.match(75) || this.isLet() || (this.isContextual(130) || this.isContextual(129)) && !insideModule) { + const label = this.state.value; + throw this.raise(FlowErrors.UnsupportedDeclareExportKind, this.state.startLoc, { + unsupportedExportKind: label, + suggestion: exportSuggestions[label] + }); + } + if (this.match(74) || this.match(68) || this.match(80) || this.isContextual(131)) { + node.declaration = this.flowParseDeclare(this.startNode()); + node.default = false; + return this.finishNode(node, "DeclareExportDeclaration"); + } else if (this.match(55) || this.match(5) || this.isContextual(129) || this.isContextual(130) || this.isContextual(131)) { + node = this.parseExport(node, null); + if (node.type === "ExportNamedDeclaration") { + node.default = false; + delete node.exportKind; + return this.castNodeTo(node, "DeclareExportDeclaration"); + } else { + return this.castNodeTo(node, "DeclareExportAllDeclaration"); + } + } + } + throw this.unexpected(); + } + flowParseDeclareModuleExports(node) { + this.next(); + this.expectContextual(111); + node.typeAnnotation = this.flowParseTypeAnnotation(); + this.semicolon(); + return this.finishNode(node, "DeclareModuleExports"); + } + flowParseDeclareTypeAlias(node) { + this.next(); + const finished = this.flowParseTypeAlias(node); + this.castNodeTo(finished, "DeclareTypeAlias"); + return finished; + } + flowParseDeclareOpaqueType(node) { + this.next(); + const finished = this.flowParseOpaqueType(node, true); + this.castNodeTo(finished, "DeclareOpaqueType"); + return finished; + } + flowParseDeclareInterface(node) { + this.next(); + this.flowParseInterfaceish(node, false); + return this.finishNode(node, "DeclareInterface"); + } + flowParseInterfaceish(node, isClass) { + node.id = this.flowParseRestrictedIdentifier(!isClass, true); + this.scope.declareName(node.id.name, isClass ? 17 : 8201, node.id.loc.start); + if (this.match(47)) { + node.typeParameters = this.flowParseTypeParameterDeclaration(); + } else { + node.typeParameters = null; + } + node.extends = []; + if (this.eat(81)) { + do { + node.extends.push(this.flowParseInterfaceExtends()); + } while (!isClass && this.eat(12)); + } + if (isClass) { + node.implements = []; + node.mixins = []; + if (this.eatContextual(117)) { + do { + node.mixins.push(this.flowParseInterfaceExtends()); + } while (this.eat(12)); + } + if (this.eatContextual(113)) { + do { + node.implements.push(this.flowParseInterfaceExtends()); + } while (this.eat(12)); + } + } + node.body = this.flowParseObjectType({ + allowStatic: isClass, + allowExact: false, + allowSpread: false, + allowProto: isClass, + allowInexact: false + }); + } + flowParseInterfaceExtends() { + const node = this.startNode(); + node.id = this.flowParseQualifiedTypeIdentifier(); + if (this.match(47)) { + node.typeParameters = this.flowParseTypeParameterInstantiation(); + } else { + node.typeParameters = null; + } + return this.finishNode(node, "InterfaceExtends"); + } + flowParseInterface(node) { + this.flowParseInterfaceish(node, false); + return this.finishNode(node, "InterfaceDeclaration"); + } + checkNotUnderscore(word) { + if (word === "_") { + this.raise(FlowErrors.UnexpectedReservedUnderscore, this.state.startLoc); + } + } + checkReservedType(word, startLoc, declaration) { + if (!reservedTypes.has(word)) return; + this.raise(declaration ? FlowErrors.AssignReservedType : FlowErrors.UnexpectedReservedType, startLoc, { + reservedType: word + }); + } + flowParseRestrictedIdentifier(liberal, declaration) { + this.checkReservedType(this.state.value, this.state.startLoc, declaration); + return this.parseIdentifier(liberal); + } + flowParseTypeAlias(node) { + node.id = this.flowParseRestrictedIdentifier(false, true); + this.scope.declareName(node.id.name, 8201, node.id.loc.start); + if (this.match(47)) { + node.typeParameters = this.flowParseTypeParameterDeclaration(); + } else { + node.typeParameters = null; + } + node.right = this.flowParseTypeInitialiser(29); + this.semicolon(); + return this.finishNode(node, "TypeAlias"); + } + flowParseOpaqueType(node, declare) { + this.expectContextual(130); + node.id = this.flowParseRestrictedIdentifier(true, true); + this.scope.declareName(node.id.name, 8201, node.id.loc.start); + if (this.match(47)) { + node.typeParameters = this.flowParseTypeParameterDeclaration(); + } else { + node.typeParameters = null; + } + node.supertype = null; + if (this.match(14)) { + node.supertype = this.flowParseTypeInitialiser(14); + } + node.impltype = null; + if (!declare) { + node.impltype = this.flowParseTypeInitialiser(29); + } + this.semicolon(); + return this.finishNode(node, "OpaqueType"); + } + flowParseTypeParameter(requireDefault = false) { + const nodeStartLoc = this.state.startLoc; + const node = this.startNode(); + const variance = this.flowParseVariance(); + const ident = this.flowParseTypeAnnotatableIdentifier(); + node.name = ident.name; + node.variance = variance; + node.bound = ident.typeAnnotation; + if (this.match(29)) { + this.eat(29); + node.default = this.flowParseType(); + } else { + if (requireDefault) { + this.raise(FlowErrors.MissingTypeParamDefault, nodeStartLoc); + } + } + return this.finishNode(node, "TypeParameter"); + } + flowParseTypeParameterDeclaration() { + const oldInType = this.state.inType; + const node = this.startNode(); + node.params = []; + this.state.inType = true; + if (this.match(47) || this.match(143)) { + this.next(); + } else { + this.unexpected(); + } + let defaultRequired = false; + do { + const typeParameter = this.flowParseTypeParameter(defaultRequired); + node.params.push(typeParameter); + if (typeParameter.default) { + defaultRequired = true; + } + if (!this.match(48)) { + this.expect(12); + } + } while (!this.match(48)); + this.expect(48); + this.state.inType = oldInType; + return this.finishNode(node, "TypeParameterDeclaration"); + } + flowInTopLevelContext(cb) { + if (this.curContext() !== types.brace) { + const oldContext = this.state.context; + this.state.context = [oldContext[0]]; + try { + return cb(); + } finally { + this.state.context = oldContext; + } + } else { + return cb(); + } + } + flowParseTypeParameterInstantiationInExpression() { + if (this.reScan_lt() !== 47) return; + return this.flowParseTypeParameterInstantiation(); + } + flowParseTypeParameterInstantiation() { + const node = this.startNode(); + const oldInType = this.state.inType; + this.state.inType = true; + node.params = []; + this.flowInTopLevelContext(() => { + this.expect(47); + const oldNoAnonFunctionType = this.state.noAnonFunctionType; + this.state.noAnonFunctionType = false; + while (!this.match(48)) { + node.params.push(this.flowParseType()); + if (!this.match(48)) { + this.expect(12); + } + } + this.state.noAnonFunctionType = oldNoAnonFunctionType; + }); + this.state.inType = oldInType; + if (!this.state.inType && this.curContext() === types.brace) { + this.reScan_lt_gt(); + } + this.expect(48); + return this.finishNode(node, "TypeParameterInstantiation"); + } + flowParseTypeParameterInstantiationCallOrNew() { + if (this.reScan_lt() !== 47) return null; + const node = this.startNode(); + const oldInType = this.state.inType; + node.params = []; + this.state.inType = true; + this.expect(47); + while (!this.match(48)) { + node.params.push(this.flowParseTypeOrImplicitInstantiation()); + if (!this.match(48)) { + this.expect(12); + } + } + this.expect(48); + this.state.inType = oldInType; + return this.finishNode(node, "TypeParameterInstantiation"); + } + flowParseInterfaceType() { + const node = this.startNode(); + this.expectContextual(129); + node.extends = []; + if (this.eat(81)) { + do { + node.extends.push(this.flowParseInterfaceExtends()); + } while (this.eat(12)); + } + node.body = this.flowParseObjectType({ + allowStatic: false, + allowExact: false, + allowSpread: false, + allowProto: false, + allowInexact: false + }); + return this.finishNode(node, "InterfaceTypeAnnotation"); + } + flowParseObjectPropertyKey() { + return this.match(135) || this.match(134) ? super.parseExprAtom() : this.parseIdentifier(true); + } + flowParseObjectTypeIndexer(node, isStatic, variance) { + node.static = isStatic; + if (this.lookahead().type === 14) { + node.id = this.flowParseObjectPropertyKey(); + node.key = this.flowParseTypeInitialiser(); + } else { + node.id = null; + node.key = this.flowParseType(); + } + this.expect(3); + node.value = this.flowParseTypeInitialiser(); + node.variance = variance; + return this.finishNode(node, "ObjectTypeIndexer"); + } + flowParseObjectTypeInternalSlot(node, isStatic) { + node.static = isStatic; + node.id = this.flowParseObjectPropertyKey(); + this.expect(3); + this.expect(3); + if (this.match(47) || this.match(10)) { + node.method = true; + node.optional = false; + node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.loc.start)); + } else { + node.method = false; + if (this.eat(17)) { + node.optional = true; + } + node.value = this.flowParseTypeInitialiser(); + } + return this.finishNode(node, "ObjectTypeInternalSlot"); + } + flowParseObjectTypeMethodish(node) { + node.params = []; + node.rest = null; + node.typeParameters = null; + node.this = null; + if (this.match(47)) { + node.typeParameters = this.flowParseTypeParameterDeclaration(); + } + this.expect(10); + if (this.match(78)) { + node.this = this.flowParseFunctionTypeParam(true); + node.this.name = null; + if (!this.match(11)) { + this.expect(12); + } + } + while (!this.match(11) && !this.match(21)) { + node.params.push(this.flowParseFunctionTypeParam(false)); + if (!this.match(11)) { + this.expect(12); + } + } + if (this.eat(21)) { + node.rest = this.flowParseFunctionTypeParam(false); + } + this.expect(11); + node.returnType = this.flowParseTypeInitialiser(); + return this.finishNode(node, "FunctionTypeAnnotation"); + } + flowParseObjectTypeCallProperty(node, isStatic) { + const valueNode = this.startNode(); + node.static = isStatic; + node.value = this.flowParseObjectTypeMethodish(valueNode); + return this.finishNode(node, "ObjectTypeCallProperty"); + } + flowParseObjectType({ + allowStatic, + allowExact, + allowSpread, + allowProto, + allowInexact + }) { + const oldInType = this.state.inType; + this.state.inType = true; + const nodeStart = this.startNode(); + nodeStart.callProperties = []; + nodeStart.properties = []; + nodeStart.indexers = []; + nodeStart.internalSlots = []; + let endDelim; + let exact; + let inexact = false; + if (allowExact && this.match(6)) { + this.expect(6); + endDelim = 9; + exact = true; + } else { + this.expect(5); + endDelim = 8; + exact = false; + } + nodeStart.exact = exact; + while (!this.match(endDelim)) { + let isStatic = false; + let protoStartLoc = null; + let inexactStartLoc = null; + const node = this.startNode(); + if (allowProto && this.isContextual(118)) { + const lookahead = this.lookahead(); + if (lookahead.type !== 14 && lookahead.type !== 17) { + this.next(); + protoStartLoc = this.state.startLoc; + allowStatic = false; + } + } + if (allowStatic && this.isContextual(106)) { + const lookahead = this.lookahead(); + if (lookahead.type !== 14 && lookahead.type !== 17) { + this.next(); + isStatic = true; + } + } + const variance = this.flowParseVariance(); + if (this.eat(0)) { + if (protoStartLoc != null) { + this.unexpected(protoStartLoc); + } + if (this.eat(0)) { + if (variance) { + this.unexpected(variance.loc.start); + } + nodeStart.internalSlots.push(this.flowParseObjectTypeInternalSlot(node, isStatic)); + } else { + nodeStart.indexers.push(this.flowParseObjectTypeIndexer(node, isStatic, variance)); + } + } else if (this.match(10) || this.match(47)) { + if (protoStartLoc != null) { + this.unexpected(protoStartLoc); + } + if (variance) { + this.unexpected(variance.loc.start); + } + nodeStart.callProperties.push(this.flowParseObjectTypeCallProperty(node, isStatic)); + } else { + let kind = "init"; + if (this.isContextual(99) || this.isContextual(104)) { + const lookahead = this.lookahead(); + if (tokenIsLiteralPropertyName(lookahead.type)) { + kind = this.state.value; + this.next(); + } + } + const propOrInexact = this.flowParseObjectTypeProperty(node, isStatic, protoStartLoc, variance, kind, allowSpread, allowInexact != null ? allowInexact : !exact); + if (propOrInexact === null) { + inexact = true; + inexactStartLoc = this.state.lastTokStartLoc; + } else { + nodeStart.properties.push(propOrInexact); + } + } + this.flowObjectTypeSemicolon(); + if (inexactStartLoc && !this.match(8) && !this.match(9)) { + this.raise(FlowErrors.UnexpectedExplicitInexactInObject, inexactStartLoc); + } + } + this.expect(endDelim); + if (allowSpread) { + nodeStart.inexact = inexact; + } + const out = this.finishNode(nodeStart, "ObjectTypeAnnotation"); + this.state.inType = oldInType; + return out; + } + flowParseObjectTypeProperty(node, isStatic, protoStartLoc, variance, kind, allowSpread, allowInexact) { + if (this.eat(21)) { + const isInexactToken = this.match(12) || this.match(13) || this.match(8) || this.match(9); + if (isInexactToken) { + if (!allowSpread) { + this.raise(FlowErrors.InexactInsideNonObject, this.state.lastTokStartLoc); + } else if (!allowInexact) { + this.raise(FlowErrors.InexactInsideExact, this.state.lastTokStartLoc); + } + if (variance) { + this.raise(FlowErrors.InexactVariance, variance); + } + return null; + } + if (!allowSpread) { + this.raise(FlowErrors.UnexpectedSpreadType, this.state.lastTokStartLoc); + } + if (protoStartLoc != null) { + this.unexpected(protoStartLoc); + } + if (variance) { + this.raise(FlowErrors.SpreadVariance, variance); + } + node.argument = this.flowParseType(); + return this.finishNode(node, "ObjectTypeSpreadProperty"); + } else { + node.key = this.flowParseObjectPropertyKey(); + node.static = isStatic; + node.proto = protoStartLoc != null; + node.kind = kind; + let optional = false; + if (this.match(47) || this.match(10)) { + node.method = true; + if (protoStartLoc != null) { + this.unexpected(protoStartLoc); + } + if (variance) { + this.unexpected(variance.loc.start); + } + node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.loc.start)); + if (kind === "get" || kind === "set") { + this.flowCheckGetterSetterParams(node); + } + if (!allowSpread && node.key.name === "constructor" && node.value.this) { + this.raise(FlowErrors.ThisParamBannedInConstructor, node.value.this); + } + } else { + if (kind !== "init") this.unexpected(); + node.method = false; + if (this.eat(17)) { + optional = true; + } + node.value = this.flowParseTypeInitialiser(); + node.variance = variance; + } + node.optional = optional; + return this.finishNode(node, "ObjectTypeProperty"); + } + } + flowCheckGetterSetterParams(property) { + const paramCount = property.kind === "get" ? 0 : 1; + const length = property.value.params.length + (property.value.rest ? 1 : 0); + if (property.value.this) { + this.raise(property.kind === "get" ? FlowErrors.GetterMayNotHaveThisParam : FlowErrors.SetterMayNotHaveThisParam, property.value.this); + } + if (length !== paramCount) { + this.raise(property.kind === "get" ? Errors.BadGetterArity : Errors.BadSetterArity, property); + } + if (property.kind === "set" && property.value.rest) { + this.raise(Errors.BadSetterRestParameter, property); + } + } + flowObjectTypeSemicolon() { + if (!this.eat(13) && !this.eat(12) && !this.match(8) && !this.match(9)) { + this.unexpected(); + } + } + flowParseQualifiedTypeIdentifier(startLoc, id) { + startLoc != null ? startLoc : startLoc = this.state.startLoc; + let node = id || this.flowParseRestrictedIdentifier(true); + while (this.eat(16)) { + const node2 = this.startNodeAt(startLoc); + node2.qualification = node; + node2.id = this.flowParseRestrictedIdentifier(true); + node = this.finishNode(node2, "QualifiedTypeIdentifier"); + } + return node; + } + flowParseGenericType(startLoc, id) { + const node = this.startNodeAt(startLoc); + node.typeParameters = null; + node.id = this.flowParseQualifiedTypeIdentifier(startLoc, id); + if (this.match(47)) { + node.typeParameters = this.flowParseTypeParameterInstantiation(); + } + return this.finishNode(node, "GenericTypeAnnotation"); + } + flowParseTypeofType() { + const node = this.startNode(); + this.expect(87); + node.argument = this.flowParsePrimaryType(); + return this.finishNode(node, "TypeofTypeAnnotation"); + } + flowParseTupleType() { + const node = this.startNode(); + node.types = []; + this.expect(0); + while (this.state.pos < this.length && !this.match(3)) { + node.types.push(this.flowParseType()); + if (this.match(3)) break; + this.expect(12); + } + this.expect(3); + return this.finishNode(node, "TupleTypeAnnotation"); + } + flowParseFunctionTypeParam(first) { + let name = null; + let optional = false; + let typeAnnotation = null; + const node = this.startNode(); + const lh = this.lookahead(); + const isThis = this.state.type === 78; + if (lh.type === 14 || lh.type === 17) { + if (isThis && !first) { + this.raise(FlowErrors.ThisParamMustBeFirst, node); + } + name = this.parseIdentifier(isThis); + if (this.eat(17)) { + optional = true; + if (isThis) { + this.raise(FlowErrors.ThisParamMayNotBeOptional, node); + } + } + typeAnnotation = this.flowParseTypeInitialiser(); + } else { + typeAnnotation = this.flowParseType(); + } + node.name = name; + node.optional = optional; + node.typeAnnotation = typeAnnotation; + return this.finishNode(node, "FunctionTypeParam"); + } + reinterpretTypeAsFunctionTypeParam(type) { + const node = this.startNodeAt(type.loc.start); + node.name = null; + node.optional = false; + node.typeAnnotation = type; + return this.finishNode(node, "FunctionTypeParam"); + } + flowParseFunctionTypeParams(params = []) { + let rest = null; + let _this = null; + if (this.match(78)) { + _this = this.flowParseFunctionTypeParam(true); + _this.name = null; + if (!this.match(11)) { + this.expect(12); + } + } + while (!this.match(11) && !this.match(21)) { + params.push(this.flowParseFunctionTypeParam(false)); + if (!this.match(11)) { + this.expect(12); + } + } + if (this.eat(21)) { + rest = this.flowParseFunctionTypeParam(false); + } + return { + params, + rest, + _this + }; + } + flowIdentToTypeAnnotation(startLoc, node, id) { + switch (id.name) { + case "any": + return this.finishNode(node, "AnyTypeAnnotation"); + case "bool": + case "boolean": + return this.finishNode(node, "BooleanTypeAnnotation"); + case "mixed": + return this.finishNode(node, "MixedTypeAnnotation"); + case "empty": + return this.finishNode(node, "EmptyTypeAnnotation"); + case "number": + return this.finishNode(node, "NumberTypeAnnotation"); + case "string": + return this.finishNode(node, "StringTypeAnnotation"); + case "symbol": + return this.finishNode(node, "SymbolTypeAnnotation"); + default: + this.checkNotUnderscore(id.name); + return this.flowParseGenericType(startLoc, id); + } + } + flowParsePrimaryType() { + const startLoc = this.state.startLoc; + const node = this.startNode(); + let tmp; + let type; + let isGroupedType = false; + const oldNoAnonFunctionType = this.state.noAnonFunctionType; + switch (this.state.type) { + case 5: + return this.flowParseObjectType({ + allowStatic: false, + allowExact: false, + allowSpread: true, + allowProto: false, + allowInexact: true + }); + case 6: + return this.flowParseObjectType({ + allowStatic: false, + allowExact: true, + allowSpread: true, + allowProto: false, + allowInexact: false + }); + case 0: + this.state.noAnonFunctionType = false; + type = this.flowParseTupleType(); + this.state.noAnonFunctionType = oldNoAnonFunctionType; + return type; + case 47: + { + const node = this.startNode(); + node.typeParameters = this.flowParseTypeParameterDeclaration(); + this.expect(10); + tmp = this.flowParseFunctionTypeParams(); + node.params = tmp.params; + node.rest = tmp.rest; + node.this = tmp._this; + this.expect(11); + this.expect(19); + node.returnType = this.flowParseType(); + return this.finishNode(node, "FunctionTypeAnnotation"); + } + case 10: + { + const node = this.startNode(); + this.next(); + if (!this.match(11) && !this.match(21)) { + if (tokenIsIdentifier(this.state.type) || this.match(78)) { + const token = this.lookahead().type; + isGroupedType = token !== 17 && token !== 14; + } else { + isGroupedType = true; + } + } + if (isGroupedType) { + this.state.noAnonFunctionType = false; + type = this.flowParseType(); + this.state.noAnonFunctionType = oldNoAnonFunctionType; + if (this.state.noAnonFunctionType || !(this.match(12) || this.match(11) && this.lookahead().type === 19)) { + this.expect(11); + return type; + } else { + this.eat(12); + } + } + if (type) { + tmp = this.flowParseFunctionTypeParams([this.reinterpretTypeAsFunctionTypeParam(type)]); + } else { + tmp = this.flowParseFunctionTypeParams(); + } + node.params = tmp.params; + node.rest = tmp.rest; + node.this = tmp._this; + this.expect(11); + this.expect(19); + node.returnType = this.flowParseType(); + node.typeParameters = null; + return this.finishNode(node, "FunctionTypeAnnotation"); + } + case 134: + return this.parseLiteral(this.state.value, "StringLiteralTypeAnnotation"); + case 85: + case 86: + node.value = this.match(85); + this.next(); + return this.finishNode(node, "BooleanLiteralTypeAnnotation"); + case 53: + if (this.state.value === "-") { + this.next(); + if (this.match(135)) { + return this.parseLiteralAtNode(-this.state.value, "NumberLiteralTypeAnnotation", node); + } + if (this.match(136)) { + return this.parseLiteralAtNode(-this.state.value, "BigIntLiteralTypeAnnotation", node); + } + throw this.raise(FlowErrors.UnexpectedSubtractionOperand, this.state.startLoc); + } + throw this.unexpected(); + case 135: + return this.parseLiteral(this.state.value, "NumberLiteralTypeAnnotation"); + case 136: + return this.parseLiteral(this.state.value, "BigIntLiteralTypeAnnotation"); + case 88: + this.next(); + return this.finishNode(node, "VoidTypeAnnotation"); + case 84: + this.next(); + return this.finishNode(node, "NullLiteralTypeAnnotation"); + case 78: + this.next(); + return this.finishNode(node, "ThisTypeAnnotation"); + case 55: + this.next(); + return this.finishNode(node, "ExistsTypeAnnotation"); + case 87: + return this.flowParseTypeofType(); + default: + if (tokenIsKeyword(this.state.type)) { + const label = tokenLabelName(this.state.type); + this.next(); + return super.createIdentifier(node, label); + } else if (tokenIsIdentifier(this.state.type)) { + if (this.isContextual(129)) { + return this.flowParseInterfaceType(); + } + return this.flowIdentToTypeAnnotation(startLoc, node, this.parseIdentifier()); + } + } + throw this.unexpected(); + } + flowParsePostfixType() { + const startLoc = this.state.startLoc; + let type = this.flowParsePrimaryType(); + let seenOptionalIndexedAccess = false; + while ((this.match(0) || this.match(18)) && !this.canInsertSemicolon()) { + const node = this.startNodeAt(startLoc); + const optional = this.eat(18); + seenOptionalIndexedAccess = seenOptionalIndexedAccess || optional; + this.expect(0); + if (!optional && this.match(3)) { + node.elementType = type; + this.next(); + type = this.finishNode(node, "ArrayTypeAnnotation"); + } else { + node.objectType = type; + node.indexType = this.flowParseType(); + this.expect(3); + if (seenOptionalIndexedAccess) { + node.optional = optional; + type = this.finishNode(node, "OptionalIndexedAccessType"); + } else { + type = this.finishNode(node, "IndexedAccessType"); + } + } + } + return type; + } + flowParsePrefixType() { + const node = this.startNode(); + if (this.eat(17)) { + node.typeAnnotation = this.flowParsePrefixType(); + return this.finishNode(node, "NullableTypeAnnotation"); + } else { + return this.flowParsePostfixType(); + } + } + flowParseAnonFunctionWithoutParens() { + const param = this.flowParsePrefixType(); + if (!this.state.noAnonFunctionType && this.eat(19)) { + const node = this.startNodeAt(param.loc.start); + node.params = [this.reinterpretTypeAsFunctionTypeParam(param)]; + node.rest = null; + node.this = null; + node.returnType = this.flowParseType(); + node.typeParameters = null; + return this.finishNode(node, "FunctionTypeAnnotation"); + } + return param; + } + flowParseIntersectionType() { + const node = this.startNode(); + this.eat(45); + const type = this.flowParseAnonFunctionWithoutParens(); + node.types = [type]; + while (this.eat(45)) { + node.types.push(this.flowParseAnonFunctionWithoutParens()); + } + return node.types.length === 1 ? type : this.finishNode(node, "IntersectionTypeAnnotation"); + } + flowParseUnionType() { + const node = this.startNode(); + this.eat(43); + const type = this.flowParseIntersectionType(); + node.types = [type]; + while (this.eat(43)) { + node.types.push(this.flowParseIntersectionType()); + } + return node.types.length === 1 ? type : this.finishNode(node, "UnionTypeAnnotation"); + } + flowParseType() { + const oldInType = this.state.inType; + this.state.inType = true; + const type = this.flowParseUnionType(); + this.state.inType = oldInType; + return type; + } + flowParseTypeOrImplicitInstantiation() { + if (this.state.type === 132 && this.state.value === "_") { + const startLoc = this.state.startLoc; + const node = this.parseIdentifier(); + return this.flowParseGenericType(startLoc, node); + } else { + return this.flowParseType(); + } + } + flowParseTypeAnnotation() { + const node = this.startNode(); + node.typeAnnotation = this.flowParseTypeInitialiser(); + return this.finishNode(node, "TypeAnnotation"); + } + flowParseTypeAnnotatableIdentifier(allowPrimitiveOverride) { + const ident = allowPrimitiveOverride ? this.parseIdentifier() : this.flowParseRestrictedIdentifier(); + if (this.match(14)) { + ident.typeAnnotation = this.flowParseTypeAnnotation(); + this.resetEndLocation(ident); + } + return ident; + } + typeCastToParameter(node) { + node.expression.typeAnnotation = node.typeAnnotation; + this.resetEndLocation(node.expression, node.typeAnnotation.loc.end); + return node.expression; + } + flowParseVariance() { + let variance = null; + if (this.match(53)) { + variance = this.startNode(); + if (this.state.value === "+") { + variance.kind = "plus"; + } else { + variance.kind = "minus"; + } + this.next(); + return this.finishNode(variance, "Variance"); + } + return variance; + } + parseFunctionBody(node, allowExpressionBody, isMethod = false) { + if (allowExpressionBody) { + this.forwardNoArrowParamsConversionAt(node, () => super.parseFunctionBody(node, true, isMethod)); + return; + } + super.parseFunctionBody(node, false, isMethod); + } + parseFunctionBodyAndFinish(node, type, isMethod = false) { + if (this.match(14)) { + const typeNode = this.startNode(); + [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser(); + node.returnType = typeNode.typeAnnotation ? this.finishNode(typeNode, "TypeAnnotation") : null; + } + return super.parseFunctionBodyAndFinish(node, type, isMethod); + } + parseStatementLike(flags) { + if (this.state.strict && this.isContextual(129)) { + const lookahead = this.lookahead(); + if (tokenIsKeywordOrIdentifier(lookahead.type)) { + const node = this.startNode(); + this.next(); + return this.flowParseInterface(node); + } + } else if (this.isContextual(126)) { + const node = this.startNode(); + this.next(); + return this.flowParseEnumDeclaration(node); + } + const stmt = super.parseStatementLike(flags); + if (this.flowPragma === undefined && !this.isValidDirective(stmt)) { + this.flowPragma = null; + } + return stmt; + } + parseExpressionStatement(node, expr, decorators) { + if (expr.type === "Identifier") { + if (expr.name === "declare") { + if (this.match(80) || tokenIsIdentifier(this.state.type) || this.match(68) || this.match(74) || this.match(82)) { + return this.flowParseDeclare(node); + } + } else if (tokenIsIdentifier(this.state.type)) { + if (expr.name === "interface") { + return this.flowParseInterface(node); + } else if (expr.name === "type") { + return this.flowParseTypeAlias(node); + } else if (expr.name === "opaque") { + return this.flowParseOpaqueType(node, false); + } + } + } + return super.parseExpressionStatement(node, expr, decorators); + } + shouldParseExportDeclaration() { + const { + type + } = this.state; + if (type === 126 || tokenIsFlowInterfaceOrTypeOrOpaque(type)) { + return !this.state.containsEsc; + } + return super.shouldParseExportDeclaration(); + } + isExportDefaultSpecifier() { + const { + type + } = this.state; + if (type === 126 || tokenIsFlowInterfaceOrTypeOrOpaque(type)) { + return this.state.containsEsc; + } + return super.isExportDefaultSpecifier(); + } + parseExportDefaultExpression() { + if (this.isContextual(126)) { + const node = this.startNode(); + this.next(); + return this.flowParseEnumDeclaration(node); + } + return super.parseExportDefaultExpression(); + } + parseConditional(expr, startLoc, refExpressionErrors) { + if (!this.match(17)) return expr; + if (this.state.maybeInArrowParameters) { + const nextCh = this.lookaheadCharCode(); + if (nextCh === 44 || nextCh === 61 || nextCh === 58 || nextCh === 41) { + this.setOptionalParametersError(refExpressionErrors); + return expr; + } + } + this.expect(17); + const state = this.state.clone(); + const originalNoArrowAt = this.state.noArrowAt; + const node = this.startNodeAt(startLoc); + let { + consequent, + failed + } = this.tryParseConditionalConsequent(); + let [valid, invalid] = this.getArrowLikeExpressions(consequent); + if (failed || invalid.length > 0) { + const noArrowAt = [...originalNoArrowAt]; + if (invalid.length > 0) { + this.state = state; + this.state.noArrowAt = noArrowAt; + for (let i = 0; i < invalid.length; i++) { + noArrowAt.push(invalid[i].start); + } + ({ + consequent, + failed + } = this.tryParseConditionalConsequent()); + [valid, invalid] = this.getArrowLikeExpressions(consequent); + } + if (failed && valid.length > 1) { + this.raise(FlowErrors.AmbiguousConditionalArrow, state.startLoc); + } + if (failed && valid.length === 1) { + this.state = state; + noArrowAt.push(valid[0].start); + this.state.noArrowAt = noArrowAt; + ({ + consequent, + failed + } = this.tryParseConditionalConsequent()); + } + } + this.getArrowLikeExpressions(consequent, true); + this.state.noArrowAt = originalNoArrowAt; + this.expect(14); + node.test = expr; + node.consequent = consequent; + node.alternate = this.forwardNoArrowParamsConversionAt(node, () => this.parseMaybeAssign(undefined, undefined)); + return this.finishNode(node, "ConditionalExpression"); + } + tryParseConditionalConsequent() { + this.state.noArrowParamsConversionAt.push(this.state.start); + const consequent = this.parseMaybeAssignAllowIn(); + const failed = !this.match(14); + this.state.noArrowParamsConversionAt.pop(); + return { + consequent, + failed + }; + } + getArrowLikeExpressions(node, disallowInvalid) { + const stack = [node]; + const arrows = []; + while (stack.length !== 0) { + const node = stack.pop(); + if (node.type === "ArrowFunctionExpression" && node.body.type !== "BlockStatement") { + if (node.typeParameters || !node.returnType) { + this.finishArrowValidation(node); + } else { + arrows.push(node); + } + stack.push(node.body); + } else if (node.type === "ConditionalExpression") { + stack.push(node.consequent); + stack.push(node.alternate); + } + } + if (disallowInvalid) { + arrows.forEach(node => this.finishArrowValidation(node)); + return [arrows, []]; + } + return partition(arrows, node => node.params.every(param => this.isAssignable(param, true))); + } + finishArrowValidation(node) { + var _node$extra; + this.toAssignableList(node.params, (_node$extra = node.extra) == null ? void 0 : _node$extra.trailingCommaLoc, false); + this.scope.enter(514 | 4); + super.checkParams(node, false, true); + this.scope.exit(); + } + forwardNoArrowParamsConversionAt(node, parse) { + let result; + if (this.state.noArrowParamsConversionAt.includes(this.offsetToSourcePos(node.start))) { + this.state.noArrowParamsConversionAt.push(this.state.start); + result = parse(); + this.state.noArrowParamsConversionAt.pop(); + } else { + result = parse(); + } + return result; + } + parseParenItem(node, startLoc) { + const newNode = super.parseParenItem(node, startLoc); + if (this.eat(17)) { + newNode.optional = true; + this.resetEndLocation(node); + } + if (this.match(14)) { + const typeCastNode = this.startNodeAt(startLoc); + typeCastNode.expression = newNode; + typeCastNode.typeAnnotation = this.flowParseTypeAnnotation(); + return this.finishNode(typeCastNode, "TypeCastExpression"); + } + return newNode; + } + assertModuleNodeAllowed(node) { + if (node.type === "ImportDeclaration" && (node.importKind === "type" || node.importKind === "typeof") || node.type === "ExportNamedDeclaration" && node.exportKind === "type" || node.type === "ExportAllDeclaration" && node.exportKind === "type") { + return; + } + super.assertModuleNodeAllowed(node); + } + parseExportDeclaration(node) { + if (this.isContextual(130)) { + node.exportKind = "type"; + const declarationNode = this.startNode(); + this.next(); + if (this.match(5)) { + node.specifiers = this.parseExportSpecifiers(true); + super.parseExportFrom(node); + return null; + } else { + return this.flowParseTypeAlias(declarationNode); + } + } else if (this.isContextual(131)) { + node.exportKind = "type"; + const declarationNode = this.startNode(); + this.next(); + return this.flowParseOpaqueType(declarationNode, false); + } else if (this.isContextual(129)) { + node.exportKind = "type"; + const declarationNode = this.startNode(); + this.next(); + return this.flowParseInterface(declarationNode); + } else if (this.isContextual(126)) { + node.exportKind = "value"; + const declarationNode = this.startNode(); + this.next(); + return this.flowParseEnumDeclaration(declarationNode); + } else { + return super.parseExportDeclaration(node); + } + } + eatExportStar(node) { + if (super.eatExportStar(node)) return true; + if (this.isContextual(130) && this.lookahead().type === 55) { + node.exportKind = "type"; + this.next(); + this.next(); + return true; + } + return false; + } + maybeParseExportNamespaceSpecifier(node) { + const { + startLoc + } = this.state; + const hasNamespace = super.maybeParseExportNamespaceSpecifier(node); + if (hasNamespace && node.exportKind === "type") { + this.unexpected(startLoc); + } + return hasNamespace; + } + parseClassId(node, isStatement, optionalId) { + super.parseClassId(node, isStatement, optionalId); + if (this.match(47)) { + node.typeParameters = this.flowParseTypeParameterDeclaration(); + } + } + parseClassMember(classBody, member, state) { + const { + startLoc + } = this.state; + if (this.isContextual(125)) { + if (super.parseClassMemberFromModifier(classBody, member)) { + return; + } + member.declare = true; + } + super.parseClassMember(classBody, member, state); + if (member.declare) { + if (member.type !== "ClassProperty" && member.type !== "ClassPrivateProperty" && member.type !== "PropertyDefinition") { + this.raise(FlowErrors.DeclareClassElement, startLoc); + } else if (member.value) { + this.raise(FlowErrors.DeclareClassFieldInitializer, member.value); + } + } + } + isIterator(word) { + return word === "iterator" || word === "asyncIterator"; + } + readIterator() { + const word = super.readWord1(); + const fullWord = "@@" + word; + if (!this.isIterator(word) || !this.state.inType) { + this.raise(Errors.InvalidIdentifier, this.state.curPosition(), { + identifierName: fullWord + }); + } + this.finishToken(132, fullWord); + } + getTokenFromCode(code) { + const next = this.input.charCodeAt(this.state.pos + 1); + if (code === 123 && next === 124) { + this.finishOp(6, 2); + } else if (this.state.inType && (code === 62 || code === 60)) { + this.finishOp(code === 62 ? 48 : 47, 1); + } else if (this.state.inType && code === 63) { + if (next === 46) { + this.finishOp(18, 2); + } else { + this.finishOp(17, 1); + } + } else if (isIteratorStart(code, next, this.input.charCodeAt(this.state.pos + 2))) { + this.state.pos += 2; + this.readIterator(); + } else { + super.getTokenFromCode(code); + } + } + isAssignable(node, isBinding) { + if (node.type === "TypeCastExpression") { + return this.isAssignable(node.expression, isBinding); + } else { + return super.isAssignable(node, isBinding); + } + } + toAssignable(node, isLHS = false) { + if (!isLHS && node.type === "AssignmentExpression" && node.left.type === "TypeCastExpression") { + node.left = this.typeCastToParameter(node.left); + } + super.toAssignable(node, isLHS); + } + toAssignableList(exprList, trailingCommaLoc, isLHS) { + for (let i = 0; i < exprList.length; i++) { + const expr = exprList[i]; + if ((expr == null ? void 0 : expr.type) === "TypeCastExpression") { + exprList[i] = this.typeCastToParameter(expr); + } + } + super.toAssignableList(exprList, trailingCommaLoc, isLHS); + } + toReferencedList(exprList, isParenthesizedExpr) { + for (let i = 0; i < exprList.length; i++) { + var _expr$extra; + const expr = exprList[i]; + if (expr && expr.type === "TypeCastExpression" && !((_expr$extra = expr.extra) != null && _expr$extra.parenthesized) && (exprList.length > 1 || !isParenthesizedExpr)) { + this.raise(FlowErrors.TypeCastInPattern, expr.typeAnnotation); + } + } + return exprList; + } + parseArrayLike(close, isTuple, refExpressionErrors) { + const node = super.parseArrayLike(close, isTuple, refExpressionErrors); + if (refExpressionErrors != null && !this.state.maybeInArrowParameters) { + this.toReferencedList(node.elements); + } + return node; + } + isValidLVal(type, disallowCallExpression, isParenthesized, binding) { + return type === "TypeCastExpression" || super.isValidLVal(type, disallowCallExpression, isParenthesized, binding); + } + parseClassProperty(node) { + if (this.match(14)) { + node.typeAnnotation = this.flowParseTypeAnnotation(); + } + return super.parseClassProperty(node); + } + parseClassPrivateProperty(node) { + if (this.match(14)) { + node.typeAnnotation = this.flowParseTypeAnnotation(); + } + return super.parseClassPrivateProperty(node); + } + isClassMethod() { + return this.match(47) || super.isClassMethod(); + } + isClassProperty() { + return this.match(14) || super.isClassProperty(); + } + isNonstaticConstructor(method) { + return !this.match(14) && super.isNonstaticConstructor(method); + } + pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) { + if (method.variance) { + this.unexpected(method.variance.loc.start); + } + delete method.variance; + if (this.match(47)) { + method.typeParameters = this.flowParseTypeParameterDeclaration(); + } + super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper); + if (method.params && isConstructor) { + const params = method.params; + if (params.length > 0 && this.isThisParam(params[0])) { + this.raise(FlowErrors.ThisParamBannedInConstructor, method); + } + } else if (method.type === "MethodDefinition" && isConstructor && method.value.params) { + const params = method.value.params; + if (params.length > 0 && this.isThisParam(params[0])) { + this.raise(FlowErrors.ThisParamBannedInConstructor, method); + } + } + } + pushClassPrivateMethod(classBody, method, isGenerator, isAsync) { + if (method.variance) { + this.unexpected(method.variance.loc.start); + } + delete method.variance; + if (this.match(47)) { + method.typeParameters = this.flowParseTypeParameterDeclaration(); + } + super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync); + } + parseClassSuper(node) { + super.parseClassSuper(node); + if (node.superClass && (this.match(47) || this.match(51))) { + node.superTypeParameters = this.flowParseTypeParameterInstantiationInExpression(); + } + if (this.isContextual(113)) { + this.next(); + const implemented = node.implements = []; + do { + const node = this.startNode(); + node.id = this.flowParseRestrictedIdentifier(true); + if (this.match(47)) { + node.typeParameters = this.flowParseTypeParameterInstantiation(); + } else { + node.typeParameters = null; + } + implemented.push(this.finishNode(node, "ClassImplements")); + } while (this.eat(12)); + } + } + checkGetterSetterParams(method) { + super.checkGetterSetterParams(method); + const params = this.getObjectOrClassMethodParams(method); + if (params.length > 0) { + const param = params[0]; + if (this.isThisParam(param) && method.kind === "get") { + this.raise(FlowErrors.GetterMayNotHaveThisParam, param); + } else if (this.isThisParam(param)) { + this.raise(FlowErrors.SetterMayNotHaveThisParam, param); + } + } + } + parsePropertyNamePrefixOperator(node) { + node.variance = this.flowParseVariance(); + } + parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) { + if (prop.variance) { + this.unexpected(prop.variance.loc.start); + } + delete prop.variance; + let typeParameters; + if (this.match(47) && !isAccessor) { + typeParameters = this.flowParseTypeParameterDeclaration(); + if (!this.match(10)) this.unexpected(); + } + const result = super.parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors); + if (typeParameters) { + (result.value || result).typeParameters = typeParameters; + } + return result; + } + parseFunctionParamType(param) { + if (this.eat(17)) { + if (param.type !== "Identifier") { + this.raise(FlowErrors.PatternIsOptional, param); + } + if (this.isThisParam(param)) { + this.raise(FlowErrors.ThisParamMayNotBeOptional, param); + } + param.optional = true; + } + if (this.match(14)) { + param.typeAnnotation = this.flowParseTypeAnnotation(); + } else if (this.isThisParam(param)) { + this.raise(FlowErrors.ThisParamAnnotationRequired, param); + } + if (this.match(29) && this.isThisParam(param)) { + this.raise(FlowErrors.ThisParamNoDefault, param); + } + this.resetEndLocation(param); + return param; + } + parseMaybeDefault(startLoc, left) { + const node = super.parseMaybeDefault(startLoc, left); + if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) { + this.raise(FlowErrors.TypeBeforeInitializer, node.typeAnnotation); + } + return node; + } + checkImportReflection(node) { + super.checkImportReflection(node); + if (node.module && node.importKind !== "value") { + this.raise(FlowErrors.ImportReflectionHasImportType, node.specifiers[0].loc.start); + } + } + parseImportSpecifierLocal(node, specifier, type) { + specifier.local = hasTypeImportKind(node) ? this.flowParseRestrictedIdentifier(true, true) : this.parseIdentifier(); + node.specifiers.push(this.finishImportSpecifier(specifier, type)); + } + isPotentialImportPhase(isExport) { + if (super.isPotentialImportPhase(isExport)) return true; + if (this.isContextual(130)) { + if (!isExport) return true; + const ch = this.lookaheadCharCode(); + return ch === 123 || ch === 42; + } + return !isExport && this.isContextual(87); + } + applyImportPhase(node, isExport, phase, loc) { + super.applyImportPhase(node, isExport, phase, loc); + if (isExport) { + if (!phase && this.match(65)) { + return; + } + node.exportKind = phase === "type" ? phase : "value"; + } else { + if (phase === "type" && this.match(55)) this.unexpected(); + node.importKind = phase === "type" || phase === "typeof" ? phase : "value"; + } + } + parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, bindingType) { + const firstIdent = specifier.imported; + let specifierTypeKind = null; + if (firstIdent.type === "Identifier") { + if (firstIdent.name === "type") { + specifierTypeKind = "type"; + } else if (firstIdent.name === "typeof") { + specifierTypeKind = "typeof"; + } + } + let isBinding = false; + if (this.isContextual(93) && !this.isLookaheadContextual("as")) { + const as_ident = this.parseIdentifier(true); + if (specifierTypeKind !== null && !tokenIsKeywordOrIdentifier(this.state.type)) { + specifier.imported = as_ident; + specifier.importKind = specifierTypeKind; + specifier.local = this.cloneIdentifier(as_ident); + } else { + specifier.imported = firstIdent; + specifier.importKind = null; + specifier.local = this.parseIdentifier(); + } + } else { + if (specifierTypeKind !== null && tokenIsKeywordOrIdentifier(this.state.type)) { + specifier.imported = this.parseIdentifier(true); + specifier.importKind = specifierTypeKind; + } else { + if (importedIsString) { + throw this.raise(Errors.ImportBindingIsString, specifier, { + importName: firstIdent.value + }); + } + specifier.imported = firstIdent; + specifier.importKind = null; + } + if (this.eatContextual(93)) { + specifier.local = this.parseIdentifier(); + } else { + isBinding = true; + specifier.local = this.cloneIdentifier(specifier.imported); + } + } + const specifierIsTypeImport = hasTypeImportKind(specifier); + if (isInTypeOnlyImport && specifierIsTypeImport) { + this.raise(FlowErrors.ImportTypeShorthandOnlyInPureImport, specifier); + } + if (isInTypeOnlyImport || specifierIsTypeImport) { + this.checkReservedType(specifier.local.name, specifier.local.loc.start, true); + } + if (isBinding && !isInTypeOnlyImport && !specifierIsTypeImport) { + this.checkReservedWord(specifier.local.name, specifier.loc.start, true, true); + } + return this.finishImportSpecifier(specifier, "ImportSpecifier"); + } + parseBindingAtom() { + switch (this.state.type) { + case 78: + return this.parseIdentifier(true); + default: + return super.parseBindingAtom(); + } + } + parseFunctionParams(node, isConstructor) { + const kind = node.kind; + if (kind !== "get" && kind !== "set" && this.match(47)) { + node.typeParameters = this.flowParseTypeParameterDeclaration(); + } + super.parseFunctionParams(node, isConstructor); + } + parseVarId(decl, kind) { + super.parseVarId(decl, kind); + if (this.match(14)) { + decl.id.typeAnnotation = this.flowParseTypeAnnotation(); + this.resetEndLocation(decl.id); + } + } + parseAsyncArrowFromCallExpression(node, call) { + if (this.match(14)) { + const oldNoAnonFunctionType = this.state.noAnonFunctionType; + this.state.noAnonFunctionType = true; + node.returnType = this.flowParseTypeAnnotation(); + this.state.noAnonFunctionType = oldNoAnonFunctionType; + } + return super.parseAsyncArrowFromCallExpression(node, call); + } + shouldParseAsyncArrow() { + return this.match(14) || super.shouldParseAsyncArrow(); + } + parseMaybeAssign(refExpressionErrors, afterLeftParse) { + var _jsx; + let state = null; + let jsx; + if (this.hasPlugin("jsx") && (this.match(143) || this.match(47))) { + state = this.state.clone(); + jsx = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse), state); + if (!jsx.error) return jsx.node; + const { + context + } = this.state; + const currentContext = context[context.length - 1]; + if (currentContext === types.j_oTag || currentContext === types.j_expr) { + context.pop(); + } + } + if ((_jsx = jsx) != null && _jsx.error || this.match(47)) { + var _jsx2, _jsx3; + state = state || this.state.clone(); + let typeParameters; + const arrow = this.tryParse(abort => { + var _arrowExpression$extr; + typeParameters = this.flowParseTypeParameterDeclaration(); + const arrowExpression = this.forwardNoArrowParamsConversionAt(typeParameters, () => { + const result = super.parseMaybeAssign(refExpressionErrors, afterLeftParse); + this.resetStartLocationFromNode(result, typeParameters); + return result; + }); + if ((_arrowExpression$extr = arrowExpression.extra) != null && _arrowExpression$extr.parenthesized) abort(); + const expr = this.maybeUnwrapTypeCastExpression(arrowExpression); + if (expr.type !== "ArrowFunctionExpression") abort(); + expr.typeParameters = typeParameters; + this.resetStartLocationFromNode(expr, typeParameters); + return arrowExpression; + }, state); + let arrowExpression = null; + if (arrow.node && this.maybeUnwrapTypeCastExpression(arrow.node).type === "ArrowFunctionExpression") { + if (!arrow.error && !arrow.aborted) { + if (arrow.node.async) { + this.raise(FlowErrors.UnexpectedTypeParameterBeforeAsyncArrowFunction, typeParameters); + } + return arrow.node; + } + arrowExpression = arrow.node; + } + if ((_jsx2 = jsx) != null && _jsx2.node) { + this.state = jsx.failState; + return jsx.node; + } + if (arrowExpression) { + this.state = arrow.failState; + return arrowExpression; + } + if ((_jsx3 = jsx) != null && _jsx3.thrown) throw jsx.error; + if (arrow.thrown) throw arrow.error; + throw this.raise(FlowErrors.UnexpectedTokenAfterTypeParameter, typeParameters); + } + return super.parseMaybeAssign(refExpressionErrors, afterLeftParse); + } + parseArrow(node) { + if (this.match(14)) { + const result = this.tryParse(() => { + const oldNoAnonFunctionType = this.state.noAnonFunctionType; + this.state.noAnonFunctionType = true; + const typeNode = this.startNode(); + [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser(); + this.state.noAnonFunctionType = oldNoAnonFunctionType; + if (this.canInsertSemicolon()) this.unexpected(); + if (!this.match(19)) this.unexpected(); + return typeNode; + }); + if (result.thrown) return null; + if (result.error) this.state = result.failState; + node.returnType = result.node.typeAnnotation ? this.finishNode(result.node, "TypeAnnotation") : null; + } + return super.parseArrow(node); + } + shouldParseArrow(params) { + return this.match(14) || super.shouldParseArrow(params); + } + setArrowFunctionParameters(node, params) { + if (this.state.noArrowParamsConversionAt.includes(this.offsetToSourcePos(node.start))) { + node.params = params; + } else { + super.setArrowFunctionParameters(node, params); + } + } + checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged = true) { + if (isArrowFunction && this.state.noArrowParamsConversionAt.includes(this.offsetToSourcePos(node.start))) { + return; + } + for (let i = 0; i < node.params.length; i++) { + if (this.isThisParam(node.params[i]) && i > 0) { + this.raise(FlowErrors.ThisParamMustBeFirst, node.params[i]); + } + } + super.checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged); + } + parseParenAndDistinguishExpression(canBeArrow) { + return super.parseParenAndDistinguishExpression(canBeArrow && !this.state.noArrowAt.includes(this.sourceToOffsetPos(this.state.start))); + } + parseSubscripts(base, startLoc, noCalls) { + if (base.type === "Identifier" && base.name === "async" && this.state.noArrowAt.includes(startLoc.index)) { + this.next(); + const node = this.startNodeAt(startLoc); + node.callee = base; + node.arguments = super.parseCallExpressionArguments(); + base = this.finishNode(node, "CallExpression"); + } else if (base.type === "Identifier" && base.name === "async" && this.match(47)) { + const state = this.state.clone(); + const arrow = this.tryParse(abort => this.parseAsyncArrowWithTypeParameters(startLoc) || abort(), state); + if (!arrow.error && !arrow.aborted) return arrow.node; + const result = this.tryParse(() => super.parseSubscripts(base, startLoc, noCalls), state); + if (result.node && !result.error) return result.node; + if (arrow.node) { + this.state = arrow.failState; + return arrow.node; + } + if (result.node) { + this.state = result.failState; + return result.node; + } + throw arrow.error || result.error; + } + return super.parseSubscripts(base, startLoc, noCalls); + } + parseSubscript(base, startLoc, noCalls, subscriptState) { + if (this.match(18) && this.isLookaheadToken_lt()) { + subscriptState.optionalChainMember = true; + if (noCalls) { + subscriptState.stop = true; + return base; + } + this.next(); + const node = this.startNodeAt(startLoc); + node.callee = base; + node.typeArguments = this.flowParseTypeParameterInstantiationInExpression(); + this.expect(10); + node.arguments = this.parseCallExpressionArguments(); + node.optional = true; + return this.finishCallExpression(node, true); + } else if (!noCalls && this.shouldParseTypes() && (this.match(47) || this.match(51))) { + const node = this.startNodeAt(startLoc); + node.callee = base; + const result = this.tryParse(() => { + node.typeArguments = this.flowParseTypeParameterInstantiationCallOrNew(); + this.expect(10); + node.arguments = super.parseCallExpressionArguments(); + if (subscriptState.optionalChainMember) { + node.optional = false; + } + return this.finishCallExpression(node, subscriptState.optionalChainMember); + }); + if (result.node) { + if (result.error) this.state = result.failState; + return result.node; + } + } + return super.parseSubscript(base, startLoc, noCalls, subscriptState); + } + parseNewCallee(node) { + super.parseNewCallee(node); + let targs = null; + if (this.shouldParseTypes() && this.match(47)) { + targs = this.tryParse(() => this.flowParseTypeParameterInstantiationCallOrNew()).node; + } + node.typeArguments = targs; + } + parseAsyncArrowWithTypeParameters(startLoc) { + const node = this.startNodeAt(startLoc); + this.parseFunctionParams(node, false); + if (!this.parseArrow(node)) return; + return super.parseArrowExpression(node, undefined, true); + } + readToken_mult_modulo(code) { + const next = this.input.charCodeAt(this.state.pos + 1); + if (code === 42 && next === 47 && this.state.hasFlowComment) { + this.state.hasFlowComment = false; + this.state.pos += 2; + this.nextToken(); + return; + } + super.readToken_mult_modulo(code); + } + readToken_pipe_amp(code) { + const next = this.input.charCodeAt(this.state.pos + 1); + if (code === 124 && next === 125) { + this.finishOp(9, 2); + return; + } + super.readToken_pipe_amp(code); + } + parseTopLevel(file, program) { + const fileNode = super.parseTopLevel(file, program); + if (this.state.hasFlowComment) { + this.raise(FlowErrors.UnterminatedFlowComment, this.state.curPosition()); + } + return fileNode; + } + skipBlockComment() { + if (this.hasPlugin("flowComments") && this.skipFlowComment()) { + if (this.state.hasFlowComment) { + throw this.raise(FlowErrors.NestedFlowComment, this.state.startLoc); + } + this.hasFlowCommentCompletion(); + const commentSkip = this.skipFlowComment(); + if (commentSkip) { + this.state.pos += commentSkip; + this.state.hasFlowComment = true; + } + return; + } + return super.skipBlockComment(this.state.hasFlowComment ? "*-/" : "*/"); + } + skipFlowComment() { + const { + pos + } = this.state; + let shiftToFirstNonWhiteSpace = 2; + while ([32, 9].includes(this.input.charCodeAt(pos + shiftToFirstNonWhiteSpace))) { + shiftToFirstNonWhiteSpace++; + } + const ch2 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos); + const ch3 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos + 1); + if (ch2 === 58 && ch3 === 58) { + return shiftToFirstNonWhiteSpace + 2; + } + if (this.input.slice(shiftToFirstNonWhiteSpace + pos, shiftToFirstNonWhiteSpace + pos + 12) === "flow-include") { + return shiftToFirstNonWhiteSpace + 12; + } + if (ch2 === 58 && ch3 !== 58) { + return shiftToFirstNonWhiteSpace; + } + return false; + } + hasFlowCommentCompletion() { + const end = this.input.indexOf("*/", this.state.pos); + if (end === -1) { + throw this.raise(Errors.UnterminatedComment, this.state.curPosition()); + } + } + flowEnumErrorBooleanMemberNotInitialized(loc, { + enumName, + memberName + }) { + this.raise(FlowErrors.EnumBooleanMemberNotInitialized, loc, { + memberName, + enumName + }); + } + flowEnumErrorInvalidMemberInitializer(loc, enumContext) { + return this.raise(!enumContext.explicitType ? FlowErrors.EnumInvalidMemberInitializerUnknownType : enumContext.explicitType === "symbol" ? FlowErrors.EnumInvalidMemberInitializerSymbolType : FlowErrors.EnumInvalidMemberInitializerPrimaryType, loc, enumContext); + } + flowEnumErrorNumberMemberNotInitialized(loc, details) { + this.raise(FlowErrors.EnumNumberMemberNotInitialized, loc, details); + } + flowEnumErrorStringMemberInconsistentlyInitialized(node, details) { + this.raise(FlowErrors.EnumStringMemberInconsistentlyInitialized, node, details); + } + flowEnumMemberInit() { + const startLoc = this.state.startLoc; + const endOfInit = () => this.match(12) || this.match(8); + switch (this.state.type) { + case 135: + { + const literal = this.parseNumericLiteral(this.state.value); + if (endOfInit()) { + return { + type: "number", + loc: literal.loc.start, + value: literal + }; + } + return { + type: "invalid", + loc: startLoc + }; + } + case 134: + { + const literal = this.parseStringLiteral(this.state.value); + if (endOfInit()) { + return { + type: "string", + loc: literal.loc.start, + value: literal + }; + } + return { + type: "invalid", + loc: startLoc + }; + } + case 85: + case 86: + { + const literal = this.parseBooleanLiteral(this.match(85)); + if (endOfInit()) { + return { + type: "boolean", + loc: literal.loc.start, + value: literal + }; + } + return { + type: "invalid", + loc: startLoc + }; + } + default: + return { + type: "invalid", + loc: startLoc + }; + } + } + flowEnumMemberRaw() { + const loc = this.state.startLoc; + const id = this.parseIdentifier(true); + const init = this.eat(29) ? this.flowEnumMemberInit() : { + type: "none", + loc + }; + return { + id, + init + }; + } + flowEnumCheckExplicitTypeMismatch(loc, context, expectedType) { + const { + explicitType + } = context; + if (explicitType === null) { + return; + } + if (explicitType !== expectedType) { + this.flowEnumErrorInvalidMemberInitializer(loc, context); + } + } + flowEnumMembers({ + enumName, + explicitType + }) { + const seenNames = new Set(); + const members = { + booleanMembers: [], + numberMembers: [], + stringMembers: [], + defaultedMembers: [] + }; + let hasUnknownMembers = false; + while (!this.match(8)) { + if (this.eat(21)) { + hasUnknownMembers = true; + break; + } + const memberNode = this.startNode(); + const { + id, + init + } = this.flowEnumMemberRaw(); + const memberName = id.name; + if (memberName === "") { + continue; + } + if (/^[a-z]/.test(memberName)) { + this.raise(FlowErrors.EnumInvalidMemberName, id, { + memberName, + suggestion: memberName[0].toUpperCase() + memberName.slice(1), + enumName + }); + } + if (seenNames.has(memberName)) { + this.raise(FlowErrors.EnumDuplicateMemberName, id, { + memberName, + enumName + }); + } + seenNames.add(memberName); + const context = { + enumName, + explicitType, + memberName + }; + memberNode.id = id; + switch (init.type) { + case "boolean": + { + this.flowEnumCheckExplicitTypeMismatch(init.loc, context, "boolean"); + memberNode.init = init.value; + members.booleanMembers.push(this.finishNode(memberNode, "EnumBooleanMember")); + break; + } + case "number": + { + this.flowEnumCheckExplicitTypeMismatch(init.loc, context, "number"); + memberNode.init = init.value; + members.numberMembers.push(this.finishNode(memberNode, "EnumNumberMember")); + break; + } + case "string": + { + this.flowEnumCheckExplicitTypeMismatch(init.loc, context, "string"); + memberNode.init = init.value; + members.stringMembers.push(this.finishNode(memberNode, "EnumStringMember")); + break; + } + case "invalid": + { + throw this.flowEnumErrorInvalidMemberInitializer(init.loc, context); + } + case "none": + { + switch (explicitType) { + case "boolean": + this.flowEnumErrorBooleanMemberNotInitialized(init.loc, context); + break; + case "number": + this.flowEnumErrorNumberMemberNotInitialized(init.loc, context); + break; + default: + members.defaultedMembers.push(this.finishNode(memberNode, "EnumDefaultedMember")); + } + } + } + if (!this.match(8)) { + this.expect(12); + } + } + return { + members, + hasUnknownMembers + }; + } + flowEnumStringMembers(initializedMembers, defaultedMembers, { + enumName + }) { + if (initializedMembers.length === 0) { + return defaultedMembers; + } else if (defaultedMembers.length === 0) { + return initializedMembers; + } else if (defaultedMembers.length > initializedMembers.length) { + for (const member of initializedMembers) { + this.flowEnumErrorStringMemberInconsistentlyInitialized(member, { + enumName + }); + } + return defaultedMembers; + } else { + for (const member of defaultedMembers) { + this.flowEnumErrorStringMemberInconsistentlyInitialized(member, { + enumName + }); + } + return initializedMembers; + } + } + flowEnumParseExplicitType({ + enumName + }) { + if (!this.eatContextual(102)) return null; + if (!tokenIsIdentifier(this.state.type)) { + throw this.raise(FlowErrors.EnumInvalidExplicitTypeUnknownSupplied, this.state.startLoc, { + enumName + }); + } + const { + value + } = this.state; + this.next(); + if (value !== "boolean" && value !== "number" && value !== "string" && value !== "symbol") { + this.raise(FlowErrors.EnumInvalidExplicitType, this.state.startLoc, { + enumName, + invalidEnumType: value + }); + } + return value; + } + flowEnumBody(node, id) { + const enumName = id.name; + const nameLoc = id.loc.start; + const explicitType = this.flowEnumParseExplicitType({ + enumName + }); + this.expect(5); + const { + members, + hasUnknownMembers + } = this.flowEnumMembers({ + enumName, + explicitType + }); + node.hasUnknownMembers = hasUnknownMembers; + switch (explicitType) { + case "boolean": + node.explicitType = true; + node.members = members.booleanMembers; + this.expect(8); + return this.finishNode(node, "EnumBooleanBody"); + case "number": + node.explicitType = true; + node.members = members.numberMembers; + this.expect(8); + return this.finishNode(node, "EnumNumberBody"); + case "string": + node.explicitType = true; + node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, { + enumName + }); + this.expect(8); + return this.finishNode(node, "EnumStringBody"); + case "symbol": + node.members = members.defaultedMembers; + this.expect(8); + return this.finishNode(node, "EnumSymbolBody"); + default: + { + const empty = () => { + node.members = []; + this.expect(8); + return this.finishNode(node, "EnumStringBody"); + }; + node.explicitType = false; + const boolsLen = members.booleanMembers.length; + const numsLen = members.numberMembers.length; + const strsLen = members.stringMembers.length; + const defaultedLen = members.defaultedMembers.length; + if (!boolsLen && !numsLen && !strsLen && !defaultedLen) { + return empty(); + } else if (!boolsLen && !numsLen) { + node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, { + enumName + }); + this.expect(8); + return this.finishNode(node, "EnumStringBody"); + } else if (!numsLen && !strsLen && boolsLen >= defaultedLen) { + for (const member of members.defaultedMembers) { + this.flowEnumErrorBooleanMemberNotInitialized(member.loc.start, { + enumName, + memberName: member.id.name + }); + } + node.members = members.booleanMembers; + this.expect(8); + return this.finishNode(node, "EnumBooleanBody"); + } else if (!boolsLen && !strsLen && numsLen >= defaultedLen) { + for (const member of members.defaultedMembers) { + this.flowEnumErrorNumberMemberNotInitialized(member.loc.start, { + enumName, + memberName: member.id.name + }); + } + node.members = members.numberMembers; + this.expect(8); + return this.finishNode(node, "EnumNumberBody"); + } else { + this.raise(FlowErrors.EnumInconsistentMemberValues, nameLoc, { + enumName + }); + return empty(); + } + } + } + } + flowParseEnumDeclaration(node) { + const id = this.parseIdentifier(); + node.id = id; + node.body = this.flowEnumBody(this.startNode(), id); + return this.finishNode(node, "EnumDeclaration"); + } + jsxParseOpeningElementAfterName(node) { + if (this.shouldParseTypes()) { + if (this.match(47) || this.match(51)) { + node.typeArguments = this.flowParseTypeParameterInstantiationInExpression(); + } + } + return super.jsxParseOpeningElementAfterName(node); + } + isLookaheadToken_lt() { + const next = this.nextTokenStart(); + if (this.input.charCodeAt(next) === 60) { + const afterNext = this.input.charCodeAt(next + 1); + return afterNext !== 60 && afterNext !== 61; + } + return false; + } + reScan_lt_gt() { + const { + type + } = this.state; + if (type === 47) { + this.state.pos -= 1; + this.readToken_lt(); + } else if (type === 48) { + this.state.pos -= 1; + this.readToken_gt(); + } + } + reScan_lt() { + const { + type + } = this.state; + if (type === 51) { + this.state.pos -= 2; + this.finishOp(47, 1); + return 47; + } + return type; + } + maybeUnwrapTypeCastExpression(node) { + return node.type === "TypeCastExpression" ? node.expression : node; + } +}; +const entities = { + __proto__: null, + quot: "\u0022", + amp: "&", + apos: "\u0027", + lt: "<", + gt: ">", + nbsp: "\u00A0", + iexcl: "\u00A1", + cent: "\u00A2", + pound: "\u00A3", + curren: "\u00A4", + yen: "\u00A5", + brvbar: "\u00A6", + sect: "\u00A7", + uml: "\u00A8", + copy: "\u00A9", + ordf: "\u00AA", + laquo: "\u00AB", + not: "\u00AC", + shy: "\u00AD", + reg: "\u00AE", + macr: "\u00AF", + deg: "\u00B0", + plusmn: "\u00B1", + sup2: "\u00B2", + sup3: "\u00B3", + acute: "\u00B4", + micro: "\u00B5", + para: "\u00B6", + middot: "\u00B7", + cedil: "\u00B8", + sup1: "\u00B9", + ordm: "\u00BA", + raquo: "\u00BB", + frac14: "\u00BC", + frac12: "\u00BD", + frac34: "\u00BE", + iquest: "\u00BF", + Agrave: "\u00C0", + Aacute: "\u00C1", + Acirc: "\u00C2", + Atilde: "\u00C3", + Auml: "\u00C4", + Aring: "\u00C5", + AElig: "\u00C6", + Ccedil: "\u00C7", + Egrave: "\u00C8", + Eacute: "\u00C9", + Ecirc: "\u00CA", + Euml: "\u00CB", + Igrave: "\u00CC", + Iacute: "\u00CD", + Icirc: "\u00CE", + Iuml: "\u00CF", + ETH: "\u00D0", + Ntilde: "\u00D1", + Ograve: "\u00D2", + Oacute: "\u00D3", + Ocirc: "\u00D4", + Otilde: "\u00D5", + Ouml: "\u00D6", + times: "\u00D7", + Oslash: "\u00D8", + Ugrave: "\u00D9", + Uacute: "\u00DA", + Ucirc: "\u00DB", + Uuml: "\u00DC", + Yacute: "\u00DD", + THORN: "\u00DE", + szlig: "\u00DF", + agrave: "\u00E0", + aacute: "\u00E1", + acirc: "\u00E2", + atilde: "\u00E3", + auml: "\u00E4", + aring: "\u00E5", + aelig: "\u00E6", + ccedil: "\u00E7", + egrave: "\u00E8", + eacute: "\u00E9", + ecirc: "\u00EA", + euml: "\u00EB", + igrave: "\u00EC", + iacute: "\u00ED", + icirc: "\u00EE", + iuml: "\u00EF", + eth: "\u00F0", + ntilde: "\u00F1", + ograve: "\u00F2", + oacute: "\u00F3", + ocirc: "\u00F4", + otilde: "\u00F5", + ouml: "\u00F6", + divide: "\u00F7", + oslash: "\u00F8", + ugrave: "\u00F9", + uacute: "\u00FA", + ucirc: "\u00FB", + uuml: "\u00FC", + yacute: "\u00FD", + thorn: "\u00FE", + yuml: "\u00FF", + OElig: "\u0152", + oelig: "\u0153", + Scaron: "\u0160", + scaron: "\u0161", + Yuml: "\u0178", + fnof: "\u0192", + circ: "\u02C6", + tilde: "\u02DC", + Alpha: "\u0391", + Beta: "\u0392", + Gamma: "\u0393", + Delta: "\u0394", + Epsilon: "\u0395", + Zeta: "\u0396", + Eta: "\u0397", + Theta: "\u0398", + Iota: "\u0399", + Kappa: "\u039A", + Lambda: "\u039B", + Mu: "\u039C", + Nu: "\u039D", + Xi: "\u039E", + Omicron: "\u039F", + Pi: "\u03A0", + Rho: "\u03A1", + Sigma: "\u03A3", + Tau: "\u03A4", + Upsilon: "\u03A5", + Phi: "\u03A6", + Chi: "\u03A7", + Psi: "\u03A8", + Omega: "\u03A9", + alpha: "\u03B1", + beta: "\u03B2", + gamma: "\u03B3", + delta: "\u03B4", + epsilon: "\u03B5", + zeta: "\u03B6", + eta: "\u03B7", + theta: "\u03B8", + iota: "\u03B9", + kappa: "\u03BA", + lambda: "\u03BB", + mu: "\u03BC", + nu: "\u03BD", + xi: "\u03BE", + omicron: "\u03BF", + pi: "\u03C0", + rho: "\u03C1", + sigmaf: "\u03C2", + sigma: "\u03C3", + tau: "\u03C4", + upsilon: "\u03C5", + phi: "\u03C6", + chi: "\u03C7", + psi: "\u03C8", + omega: "\u03C9", + thetasym: "\u03D1", + upsih: "\u03D2", + piv: "\u03D6", + ensp: "\u2002", + emsp: "\u2003", + thinsp: "\u2009", + zwnj: "\u200C", + zwj: "\u200D", + lrm: "\u200E", + rlm: "\u200F", + ndash: "\u2013", + mdash: "\u2014", + lsquo: "\u2018", + rsquo: "\u2019", + sbquo: "\u201A", + ldquo: "\u201C", + rdquo: "\u201D", + bdquo: "\u201E", + dagger: "\u2020", + Dagger: "\u2021", + bull: "\u2022", + hellip: "\u2026", + permil: "\u2030", + prime: "\u2032", + Prime: "\u2033", + lsaquo: "\u2039", + rsaquo: "\u203A", + oline: "\u203E", + frasl: "\u2044", + euro: "\u20AC", + image: "\u2111", + weierp: "\u2118", + real: "\u211C", + trade: "\u2122", + alefsym: "\u2135", + larr: "\u2190", + uarr: "\u2191", + rarr: "\u2192", + darr: "\u2193", + harr: "\u2194", + crarr: "\u21B5", + lArr: "\u21D0", + uArr: "\u21D1", + rArr: "\u21D2", + dArr: "\u21D3", + hArr: "\u21D4", + forall: "\u2200", + part: "\u2202", + exist: "\u2203", + empty: "\u2205", + nabla: "\u2207", + isin: "\u2208", + notin: "\u2209", + ni: "\u220B", + prod: "\u220F", + sum: "\u2211", + minus: "\u2212", + lowast: "\u2217", + radic: "\u221A", + prop: "\u221D", + infin: "\u221E", + ang: "\u2220", + and: "\u2227", + or: "\u2228", + cap: "\u2229", + cup: "\u222A", + int: "\u222B", + there4: "\u2234", + sim: "\u223C", + cong: "\u2245", + asymp: "\u2248", + ne: "\u2260", + equiv: "\u2261", + le: "\u2264", + ge: "\u2265", + sub: "\u2282", + sup: "\u2283", + nsub: "\u2284", + sube: "\u2286", + supe: "\u2287", + oplus: "\u2295", + otimes: "\u2297", + perp: "\u22A5", + sdot: "\u22C5", + lceil: "\u2308", + rceil: "\u2309", + lfloor: "\u230A", + rfloor: "\u230B", + lang: "\u2329", + rang: "\u232A", + loz: "\u25CA", + spades: "\u2660", + clubs: "\u2663", + hearts: "\u2665", + diams: "\u2666" +}; +const lineBreak = /\r\n|[\r\n\u2028\u2029]/; +const lineBreakG = new RegExp(lineBreak.source, "g"); +function isNewLine(code) { + switch (code) { + case 10: + case 13: + case 8232: + case 8233: + return true; + default: + return false; + } +} +function hasNewLine(input, start, end) { + for (let i = start; i < end; i++) { + if (isNewLine(input.charCodeAt(i))) { + return true; + } + } + return false; +} +const skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g; +const skipWhiteSpaceInLine = /(?:[^\S\n\r\u2028\u2029]|\/\/.*|\/\*.*?\*\/)*/g; +function isWhitespace(code) { + switch (code) { + case 0x0009: + case 0x000b: + case 0x000c: + case 32: + case 160: + case 5760: + case 0x2000: + case 0x2001: + case 0x2002: + case 0x2003: + case 0x2004: + case 0x2005: + case 0x2006: + case 0x2007: + case 0x2008: + case 0x2009: + case 0x200a: + case 0x202f: + case 0x205f: + case 0x3000: + case 0xfeff: + return true; + default: + return false; + } +} +const JsxErrors = ParseErrorEnum`jsx`({ + AttributeIsEmpty: "JSX attributes must only be assigned a non-empty expression.", + MissingClosingTagElement: ({ + openingTagName + }) => `Expected corresponding JSX closing tag for <${openingTagName}>.`, + MissingClosingTagFragment: "Expected corresponding JSX closing tag for <>.", + UnexpectedSequenceExpression: "Sequence expressions cannot be directly nested inside JSX. Did you mean to wrap it in parentheses (...)?", + UnexpectedToken: ({ + unexpected, + HTMLEntity + }) => `Unexpected token \`${unexpected}\`. Did you mean \`${HTMLEntity}\` or \`{'${unexpected}'}\`?`, + UnsupportedJsxValue: "JSX value should be either an expression or a quoted JSX text.", + UnterminatedJsxContent: "Unterminated JSX contents.", + UnwrappedAdjacentJSXElements: "Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...?" +}); +function isFragment(object) { + return object ? object.type === "JSXOpeningFragment" || object.type === "JSXClosingFragment" : false; +} +function getQualifiedJSXName(object) { + if (object.type === "JSXIdentifier") { + return object.name; + } + if (object.type === "JSXNamespacedName") { + return object.namespace.name + ":" + object.name.name; + } + if (object.type === "JSXMemberExpression") { + return getQualifiedJSXName(object.object) + "." + getQualifiedJSXName(object.property); + } + throw new Error("Node had unexpected type: " + object.type); +} +var jsx = superClass => class JSXParserMixin extends superClass { + jsxReadToken() { + let out = ""; + let chunkStart = this.state.pos; + for (;;) { + if (this.state.pos >= this.length) { + throw this.raise(JsxErrors.UnterminatedJsxContent, this.state.startLoc); + } + const ch = this.input.charCodeAt(this.state.pos); + switch (ch) { + case 60: + case 123: + if (this.state.pos === this.state.start) { + if (ch === 60 && this.state.canStartJSXElement) { + ++this.state.pos; + this.finishToken(143); + } else { + super.getTokenFromCode(ch); + } + return; + } + out += this.input.slice(chunkStart, this.state.pos); + this.finishToken(142, out); + return; + case 38: + out += this.input.slice(chunkStart, this.state.pos); + out += this.jsxReadEntity(); + chunkStart = this.state.pos; + break; + case 62: + case 125: + default: + if (isNewLine(ch)) { + out += this.input.slice(chunkStart, this.state.pos); + out += this.jsxReadNewLine(true); + chunkStart = this.state.pos; + } else { + ++this.state.pos; + } + } + } + } + jsxReadNewLine(normalizeCRLF) { + const ch = this.input.charCodeAt(this.state.pos); + let out; + ++this.state.pos; + if (ch === 13 && this.input.charCodeAt(this.state.pos) === 10) { + ++this.state.pos; + out = normalizeCRLF ? "\n" : "\r\n"; + } else { + out = String.fromCharCode(ch); + } + ++this.state.curLine; + this.state.lineStart = this.state.pos; + return out; + } + jsxReadString(quote) { + let out = ""; + let chunkStart = ++this.state.pos; + for (;;) { + if (this.state.pos >= this.length) { + throw this.raise(Errors.UnterminatedString, this.state.startLoc); + } + const ch = this.input.charCodeAt(this.state.pos); + if (ch === quote) break; + if (ch === 38) { + out += this.input.slice(chunkStart, this.state.pos); + out += this.jsxReadEntity(); + chunkStart = this.state.pos; + } else if (isNewLine(ch)) { + out += this.input.slice(chunkStart, this.state.pos); + out += this.jsxReadNewLine(false); + chunkStart = this.state.pos; + } else { + ++this.state.pos; + } + } + out += this.input.slice(chunkStart, this.state.pos++); + this.finishToken(134, out); + } + jsxReadEntity() { + const startPos = ++this.state.pos; + if (this.codePointAtPos(this.state.pos) === 35) { + ++this.state.pos; + let radix = 10; + if (this.codePointAtPos(this.state.pos) === 120) { + radix = 16; + ++this.state.pos; + } + const codePoint = this.readInt(radix, undefined, false, "bail"); + if (codePoint !== null && this.codePointAtPos(this.state.pos) === 59) { + ++this.state.pos; + return String.fromCodePoint(codePoint); + } + } else { + let count = 0; + let semi = false; + while (count++ < 10 && this.state.pos < this.length && !(semi = this.codePointAtPos(this.state.pos) === 59)) { + ++this.state.pos; + } + if (semi) { + const desc = this.input.slice(startPos, this.state.pos); + const entity = entities[desc]; + ++this.state.pos; + if (entity) { + return entity; + } + } + } + this.state.pos = startPos; + return "&"; + } + jsxReadWord() { + let ch; + const start = this.state.pos; + do { + ch = this.input.charCodeAt(++this.state.pos); + } while (isIdentifierChar(ch) || ch === 45); + this.finishToken(141, this.input.slice(start, this.state.pos)); + } + jsxParseIdentifier() { + const node = this.startNode(); + if (this.match(141)) { + node.name = this.state.value; + } else if (tokenIsKeyword(this.state.type)) { + node.name = tokenLabelName(this.state.type); + } else { + this.unexpected(); + } + this.next(); + return this.finishNode(node, "JSXIdentifier"); + } + jsxParseNamespacedName() { + const startLoc = this.state.startLoc; + const name = this.jsxParseIdentifier(); + if (!this.eat(14)) return name; + const node = this.startNodeAt(startLoc); + node.namespace = name; + node.name = this.jsxParseIdentifier(); + return this.finishNode(node, "JSXNamespacedName"); + } + jsxParseElementName() { + const startLoc = this.state.startLoc; + let node = this.jsxParseNamespacedName(); + if (node.type === "JSXNamespacedName") { + return node; + } + while (this.eat(16)) { + const newNode = this.startNodeAt(startLoc); + newNode.object = node; + newNode.property = this.jsxParseIdentifier(); + node = this.finishNode(newNode, "JSXMemberExpression"); + } + return node; + } + jsxParseAttributeValue() { + let node; + switch (this.state.type) { + case 5: + node = this.startNode(); + this.setContext(types.brace); + this.next(); + node = this.jsxParseExpressionContainer(node, types.j_oTag); + if (node.expression.type === "JSXEmptyExpression") { + this.raise(JsxErrors.AttributeIsEmpty, node); + } + return node; + case 143: + case 134: + return this.parseExprAtom(); + default: + throw this.raise(JsxErrors.UnsupportedJsxValue, this.state.startLoc); + } + } + jsxParseEmptyExpression() { + const node = this.startNodeAt(this.state.lastTokEndLoc); + return this.finishNodeAt(node, "JSXEmptyExpression", this.state.startLoc); + } + jsxParseSpreadChild(node) { + this.next(); + node.expression = this.parseExpression(); + this.setContext(types.j_expr); + this.state.canStartJSXElement = true; + this.expect(8); + return this.finishNode(node, "JSXSpreadChild"); + } + jsxParseExpressionContainer(node, previousContext) { + if (this.match(8)) { + node.expression = this.jsxParseEmptyExpression(); + } else { + const expression = this.parseExpression(); + node.expression = expression; + } + this.setContext(previousContext); + this.state.canStartJSXElement = true; + this.expect(8); + return this.finishNode(node, "JSXExpressionContainer"); + } + jsxParseAttribute() { + const node = this.startNode(); + if (this.match(5)) { + this.setContext(types.brace); + this.next(); + this.expect(21); + node.argument = this.parseMaybeAssignAllowIn(); + this.setContext(types.j_oTag); + this.state.canStartJSXElement = true; + this.expect(8); + return this.finishNode(node, "JSXSpreadAttribute"); + } + node.name = this.jsxParseNamespacedName(); + node.value = this.eat(29) ? this.jsxParseAttributeValue() : null; + return this.finishNode(node, "JSXAttribute"); + } + jsxParseOpeningElementAt(startLoc) { + const node = this.startNodeAt(startLoc); + if (this.eat(144)) { + return this.finishNode(node, "JSXOpeningFragment"); + } + node.name = this.jsxParseElementName(); + return this.jsxParseOpeningElementAfterName(node); + } + jsxParseOpeningElementAfterName(node) { + const attributes = []; + while (!this.match(56) && !this.match(144)) { + attributes.push(this.jsxParseAttribute()); + } + node.attributes = attributes; + node.selfClosing = this.eat(56); + this.expect(144); + return this.finishNode(node, "JSXOpeningElement"); + } + jsxParseClosingElementAt(startLoc) { + const node = this.startNodeAt(startLoc); + if (this.eat(144)) { + return this.finishNode(node, "JSXClosingFragment"); + } + node.name = this.jsxParseElementName(); + this.expect(144); + return this.finishNode(node, "JSXClosingElement"); + } + jsxParseElementAt(startLoc) { + const node = this.startNodeAt(startLoc); + const children = []; + const openingElement = this.jsxParseOpeningElementAt(startLoc); + let closingElement = null; + if (!openingElement.selfClosing) { + contents: for (;;) { + switch (this.state.type) { + case 143: + startLoc = this.state.startLoc; + this.next(); + if (this.eat(56)) { + closingElement = this.jsxParseClosingElementAt(startLoc); + break contents; + } + children.push(this.jsxParseElementAt(startLoc)); + break; + case 142: + children.push(this.parseLiteral(this.state.value, "JSXText")); + break; + case 5: + { + const node = this.startNode(); + this.setContext(types.brace); + this.next(); + if (this.match(21)) { + children.push(this.jsxParseSpreadChild(node)); + } else { + children.push(this.jsxParseExpressionContainer(node, types.j_expr)); + } + break; + } + default: + this.unexpected(); + } + } + if (isFragment(openingElement) && !isFragment(closingElement) && closingElement !== null) { + this.raise(JsxErrors.MissingClosingTagFragment, closingElement); + } else if (!isFragment(openingElement) && isFragment(closingElement)) { + this.raise(JsxErrors.MissingClosingTagElement, closingElement, { + openingTagName: getQualifiedJSXName(openingElement.name) + }); + } else if (!isFragment(openingElement) && !isFragment(closingElement)) { + if (getQualifiedJSXName(closingElement.name) !== getQualifiedJSXName(openingElement.name)) { + this.raise(JsxErrors.MissingClosingTagElement, closingElement, { + openingTagName: getQualifiedJSXName(openingElement.name) + }); + } + } + } + if (isFragment(openingElement)) { + node.openingFragment = openingElement; + node.closingFragment = closingElement; + } else { + node.openingElement = openingElement; + node.closingElement = closingElement; + } + node.children = children; + if (this.match(47)) { + throw this.raise(JsxErrors.UnwrappedAdjacentJSXElements, this.state.startLoc); + } + return isFragment(openingElement) ? this.finishNode(node, "JSXFragment") : this.finishNode(node, "JSXElement"); + } + jsxParseElement() { + const startLoc = this.state.startLoc; + this.next(); + return this.jsxParseElementAt(startLoc); + } + setContext(newContext) { + const { + context + } = this.state; + context[context.length - 1] = newContext; + } + parseExprAtom(refExpressionErrors) { + if (this.match(143)) { + return this.jsxParseElement(); + } else if (this.match(47) && this.input.charCodeAt(this.state.pos) !== 33) { + this.replaceToken(143); + return this.jsxParseElement(); + } else { + return super.parseExprAtom(refExpressionErrors); + } + } + skipSpace() { + const curContext = this.curContext(); + if (!curContext.preserveSpace) super.skipSpace(); + } + getTokenFromCode(code) { + const context = this.curContext(); + if (context === types.j_expr) { + this.jsxReadToken(); + return; + } + if (context === types.j_oTag || context === types.j_cTag) { + if (isIdentifierStart(code)) { + this.jsxReadWord(); + return; + } + if (code === 62) { + ++this.state.pos; + this.finishToken(144); + return; + } + if ((code === 34 || code === 39) && context === types.j_oTag) { + this.jsxReadString(code); + return; + } + } + if (code === 60 && this.state.canStartJSXElement && this.input.charCodeAt(this.state.pos + 1) !== 33) { + ++this.state.pos; + this.finishToken(143); + return; + } + super.getTokenFromCode(code); + } + updateContext(prevType) { + const { + context, + type + } = this.state; + if (type === 56 && prevType === 143) { + context.splice(-2, 2, types.j_cTag); + this.state.canStartJSXElement = false; + } else if (type === 143) { + context.push(types.j_oTag); + } else if (type === 144) { + const out = context[context.length - 1]; + if (out === types.j_oTag && prevType === 56 || out === types.j_cTag) { + context.pop(); + this.state.canStartJSXElement = context[context.length - 1] === types.j_expr; + } else { + this.setContext(types.j_expr); + this.state.canStartJSXElement = true; + } + } else { + this.state.canStartJSXElement = tokenComesBeforeExpression(type); + } + } +}; +class TypeScriptScope extends Scope { + constructor(...args) { + super(...args); + this.tsNames = new Map(); + } +} +class TypeScriptScopeHandler extends ScopeHandler { + constructor(...args) { + super(...args); + this.importsStack = []; + } + createScope(flags) { + this.importsStack.push(new Set()); + return new TypeScriptScope(flags); + } + enter(flags) { + if (flags === 1024) { + this.importsStack.push(new Set()); + } + super.enter(flags); + } + exit() { + const flags = super.exit(); + if (flags === 1024) { + this.importsStack.pop(); + } + return flags; + } + hasImport(name, allowShadow) { + const len = this.importsStack.length; + if (this.importsStack[len - 1].has(name)) { + return true; + } + if (!allowShadow && len > 1) { + for (let i = 0; i < len - 1; i++) { + if (this.importsStack[i].has(name)) return true; + } + } + return false; + } + declareName(name, bindingType, loc) { + if (bindingType & 4096) { + if (this.hasImport(name, true)) { + this.parser.raise(Errors.VarRedeclaration, loc, { + identifierName: name + }); + } + this.importsStack[this.importsStack.length - 1].add(name); + return; + } + const scope = this.currentScope(); + let type = scope.tsNames.get(name) || 0; + if (bindingType & 1024) { + this.maybeExportDefined(scope, name); + scope.tsNames.set(name, type | 16); + return; + } + super.declareName(name, bindingType, loc); + if (bindingType & 2) { + if (!(bindingType & 1)) { + this.checkRedeclarationInScope(scope, name, bindingType, loc); + this.maybeExportDefined(scope, name); + } + type = type | 1; + } + if (bindingType & 256) { + type = type | 2; + } + if (bindingType & 512) { + type = type | 4; + } + if (bindingType & 128) { + type = type | 8; + } + if (type) scope.tsNames.set(name, type); + } + isRedeclaredInScope(scope, name, bindingType) { + const type = scope.tsNames.get(name); + if ((type & 2) > 0) { + if (bindingType & 256) { + const isConst = !!(bindingType & 512); + const wasConst = (type & 4) > 0; + return isConst !== wasConst; + } + return true; + } + if (bindingType & 128 && (type & 8) > 0) { + if (scope.names.get(name) & 2) { + return !!(bindingType & 1); + } else { + return false; + } + } + if (bindingType & 2 && (type & 1) > 0) { + return true; + } + return super.isRedeclaredInScope(scope, name, bindingType); + } + checkLocalExport(id) { + const { + name + } = id; + if (this.hasImport(name)) return; + const len = this.scopeStack.length; + for (let i = len - 1; i >= 0; i--) { + const scope = this.scopeStack[i]; + const type = scope.tsNames.get(name); + if ((type & 1) > 0 || (type & 16) > 0) { + return; + } + } + super.checkLocalExport(id); + } +} +class ProductionParameterHandler { + constructor() { + this.stacks = []; + } + enter(flags) { + this.stacks.push(flags); + } + exit() { + this.stacks.pop(); + } + currentFlags() { + return this.stacks[this.stacks.length - 1]; + } + get hasAwait() { + return (this.currentFlags() & 2) > 0; + } + get hasYield() { + return (this.currentFlags() & 1) > 0; + } + get hasReturn() { + return (this.currentFlags() & 4) > 0; + } + get hasIn() { + return (this.currentFlags() & 8) > 0; + } +} +function functionFlags(isAsync, isGenerator) { + return (isAsync ? 2 : 0) | (isGenerator ? 1 : 0); +} +class BaseParser { + constructor() { + this.sawUnambiguousESM = false; + this.ambiguousScriptDifferentAst = false; + } + sourceToOffsetPos(sourcePos) { + return sourcePos + this.startIndex; + } + offsetToSourcePos(offsetPos) { + return offsetPos - this.startIndex; + } + hasPlugin(pluginConfig) { + if (typeof pluginConfig === "string") { + return this.plugins.has(pluginConfig); + } else { + const [pluginName, pluginOptions] = pluginConfig; + if (!this.hasPlugin(pluginName)) { + return false; + } + const actualOptions = this.plugins.get(pluginName); + for (const key of Object.keys(pluginOptions)) { + if ((actualOptions == null ? void 0 : actualOptions[key]) !== pluginOptions[key]) { + return false; + } + } + return true; + } + } + getPluginOption(plugin, name) { + var _this$plugins$get; + return (_this$plugins$get = this.plugins.get(plugin)) == null ? void 0 : _this$plugins$get[name]; + } +} +function setTrailingComments(node, comments) { + if (node.trailingComments === undefined) { + node.trailingComments = comments; + } else { + node.trailingComments.unshift(...comments); + } +} +function setLeadingComments(node, comments) { + if (node.leadingComments === undefined) { + node.leadingComments = comments; + } else { + node.leadingComments.unshift(...comments); + } +} +function setInnerComments(node, comments) { + if (node.innerComments === undefined) { + node.innerComments = comments; + } else { + node.innerComments.unshift(...comments); + } +} +function adjustInnerComments(node, elements, commentWS) { + let lastElement = null; + let i = elements.length; + while (lastElement === null && i > 0) { + lastElement = elements[--i]; + } + if (lastElement === null || lastElement.start > commentWS.start) { + setInnerComments(node, commentWS.comments); + } else { + setTrailingComments(lastElement, commentWS.comments); + } +} +class CommentsParser extends BaseParser { + addComment(comment) { + if (this.filename) comment.loc.filename = this.filename; + const { + commentsLen + } = this.state; + if (this.comments.length !== commentsLen) { + this.comments.length = commentsLen; + } + this.comments.push(comment); + this.state.commentsLen++; + } + processComment(node) { + const { + commentStack + } = this.state; + const commentStackLength = commentStack.length; + if (commentStackLength === 0) return; + let i = commentStackLength - 1; + const lastCommentWS = commentStack[i]; + if (lastCommentWS.start === node.end) { + lastCommentWS.leadingNode = node; + i--; + } + const { + start: nodeStart + } = node; + for (; i >= 0; i--) { + const commentWS = commentStack[i]; + const commentEnd = commentWS.end; + if (commentEnd > nodeStart) { + commentWS.containingNode = node; + this.finalizeComment(commentWS); + commentStack.splice(i, 1); + } else { + if (commentEnd === nodeStart) { + commentWS.trailingNode = node; + } + break; + } + } + } + finalizeComment(commentWS) { + var _node$options; + const { + comments + } = commentWS; + if (commentWS.leadingNode !== null || commentWS.trailingNode !== null) { + if (commentWS.leadingNode !== null) { + setTrailingComments(commentWS.leadingNode, comments); + } + if (commentWS.trailingNode !== null) { + setLeadingComments(commentWS.trailingNode, comments); + } + } else { + const node = commentWS.containingNode; + const commentStart = commentWS.start; + if (this.input.charCodeAt(this.offsetToSourcePos(commentStart) - 1) === 44) { + switch (node.type) { + case "ObjectExpression": + case "ObjectPattern": + adjustInnerComments(node, node.properties, commentWS); + break; + case "CallExpression": + case "OptionalCallExpression": + adjustInnerComments(node, node.arguments, commentWS); + break; + case "ImportExpression": + adjustInnerComments(node, [node.source, (_node$options = node.options) != null ? _node$options : null], commentWS); + break; + case "FunctionDeclaration": + case "FunctionExpression": + case "ArrowFunctionExpression": + case "ObjectMethod": + case "ClassMethod": + case "ClassPrivateMethod": + adjustInnerComments(node, node.params, commentWS); + break; + case "ArrayExpression": + case "ArrayPattern": + adjustInnerComments(node, node.elements, commentWS); + break; + case "ExportNamedDeclaration": + case "ImportDeclaration": + adjustInnerComments(node, node.specifiers, commentWS); + break; + case "TSEnumDeclaration": + adjustInnerComments(node, node.members, commentWS); + break; + case "TSEnumBody": + adjustInnerComments(node, node.members, commentWS); + break; + default: + { + if (node.type === "RecordExpression") { + adjustInnerComments(node, node.properties, commentWS); + break; + } + if (node.type === "TupleExpression") { + adjustInnerComments(node, node.elements, commentWS); + break; + } + setInnerComments(node, comments); + } + } + } else { + setInnerComments(node, comments); + } + } + } + finalizeRemainingComments() { + const { + commentStack + } = this.state; + for (let i = commentStack.length - 1; i >= 0; i--) { + this.finalizeComment(commentStack[i]); + } + this.state.commentStack = []; + } + resetPreviousNodeTrailingComments(node) { + const { + commentStack + } = this.state; + const { + length + } = commentStack; + if (length === 0) return; + const commentWS = commentStack[length - 1]; + if (commentWS.leadingNode === node) { + commentWS.leadingNode = null; + } + } + takeSurroundingComments(node, start, end) { + const { + commentStack + } = this.state; + const commentStackLength = commentStack.length; + if (commentStackLength === 0) return; + let i = commentStackLength - 1; + for (; i >= 0; i--) { + const commentWS = commentStack[i]; + const commentEnd = commentWS.end; + const commentStart = commentWS.start; + if (commentStart === end) { + commentWS.leadingNode = node; + } else if (commentEnd === start) { + commentWS.trailingNode = node; + } else if (commentEnd < start) { + break; + } + } + } +} +class State { + constructor() { + this.flags = 1024; + this.startIndex = void 0; + this.curLine = void 0; + this.lineStart = void 0; + this.startLoc = void 0; + this.endLoc = void 0; + this.errors = []; + this.potentialArrowAt = -1; + this.noArrowAt = []; + this.noArrowParamsConversionAt = []; + this.topicContext = { + maxNumOfResolvableTopics: 0, + maxTopicIndex: null + }; + this.labels = []; + this.commentsLen = 0; + this.commentStack = []; + this.pos = 0; + this.type = 140; + this.value = null; + this.start = 0; + this.end = 0; + this.lastTokEndLoc = null; + this.lastTokStartLoc = null; + this.context = [types.brace]; + this.firstInvalidTemplateEscapePos = null; + this.strictErrors = new Map(); + this.tokensLength = 0; + } + get strict() { + return (this.flags & 1) > 0; + } + set strict(v) { + if (v) this.flags |= 1;else this.flags &= -2; + } + init({ + strictMode, + sourceType, + startIndex, + startLine, + startColumn + }) { + this.strict = strictMode === false ? false : strictMode === true ? true : sourceType === "module"; + this.startIndex = startIndex; + this.curLine = startLine; + this.lineStart = -startColumn; + this.startLoc = this.endLoc = new Position(startLine, startColumn, startIndex); + } + get maybeInArrowParameters() { + return (this.flags & 2) > 0; + } + set maybeInArrowParameters(v) { + if (v) this.flags |= 2;else this.flags &= -3; + } + get inType() { + return (this.flags & 4) > 0; + } + set inType(v) { + if (v) this.flags |= 4;else this.flags &= -5; + } + get noAnonFunctionType() { + return (this.flags & 8) > 0; + } + set noAnonFunctionType(v) { + if (v) this.flags |= 8;else this.flags &= -9; + } + get hasFlowComment() { + return (this.flags & 16) > 0; + } + set hasFlowComment(v) { + if (v) this.flags |= 16;else this.flags &= -17; + } + get isAmbientContext() { + return (this.flags & 32) > 0; + } + set isAmbientContext(v) { + if (v) this.flags |= 32;else this.flags &= -33; + } + get inAbstractClass() { + return (this.flags & 64) > 0; + } + set inAbstractClass(v) { + if (v) this.flags |= 64;else this.flags &= -65; + } + get inDisallowConditionalTypesContext() { + return (this.flags & 128) > 0; + } + set inDisallowConditionalTypesContext(v) { + if (v) this.flags |= 128;else this.flags &= -129; + } + get soloAwait() { + return (this.flags & 256) > 0; + } + set soloAwait(v) { + if (v) this.flags |= 256;else this.flags &= -257; + } + get inFSharpPipelineDirectBody() { + return (this.flags & 512) > 0; + } + set inFSharpPipelineDirectBody(v) { + if (v) this.flags |= 512;else this.flags &= -513; + } + get canStartJSXElement() { + return (this.flags & 1024) > 0; + } + set canStartJSXElement(v) { + if (v) this.flags |= 1024;else this.flags &= -1025; + } + get containsEsc() { + return (this.flags & 2048) > 0; + } + set containsEsc(v) { + if (v) this.flags |= 2048;else this.flags &= -2049; + } + get hasTopLevelAwait() { + return (this.flags & 4096) > 0; + } + set hasTopLevelAwait(v) { + if (v) this.flags |= 4096;else this.flags &= -4097; + } + curPosition() { + return new Position(this.curLine, this.pos - this.lineStart, this.pos + this.startIndex); + } + clone() { + const state = new State(); + state.flags = this.flags; + state.startIndex = this.startIndex; + state.curLine = this.curLine; + state.lineStart = this.lineStart; + state.startLoc = this.startLoc; + state.endLoc = this.endLoc; + state.errors = this.errors.slice(); + state.potentialArrowAt = this.potentialArrowAt; + state.noArrowAt = this.noArrowAt.slice(); + state.noArrowParamsConversionAt = this.noArrowParamsConversionAt.slice(); + state.topicContext = this.topicContext; + state.labels = this.labels.slice(); + state.commentsLen = this.commentsLen; + state.commentStack = this.commentStack.slice(); + state.pos = this.pos; + state.type = this.type; + state.value = this.value; + state.start = this.start; + state.end = this.end; + state.lastTokEndLoc = this.lastTokEndLoc; + state.lastTokStartLoc = this.lastTokStartLoc; + state.context = this.context.slice(); + state.firstInvalidTemplateEscapePos = this.firstInvalidTemplateEscapePos; + state.strictErrors = this.strictErrors; + state.tokensLength = this.tokensLength; + return state; + } +} +var _isDigit = function isDigit(code) { + return code >= 48 && code <= 57; +}; +const forbiddenNumericSeparatorSiblings = { + decBinOct: new Set([46, 66, 69, 79, 95, 98, 101, 111]), + hex: new Set([46, 88, 95, 120]) +}; +const isAllowedNumericSeparatorSibling = { + bin: ch => ch === 48 || ch === 49, + oct: ch => ch >= 48 && ch <= 55, + dec: ch => ch >= 48 && ch <= 57, + hex: ch => ch >= 48 && ch <= 57 || ch >= 65 && ch <= 70 || ch >= 97 && ch <= 102 +}; +function readStringContents(type, input, pos, lineStart, curLine, errors) { + const initialPos = pos; + const initialLineStart = lineStart; + const initialCurLine = curLine; + let out = ""; + let firstInvalidLoc = null; + let chunkStart = pos; + const { + length + } = input; + for (;;) { + if (pos >= length) { + errors.unterminated(initialPos, initialLineStart, initialCurLine); + out += input.slice(chunkStart, pos); + break; + } + const ch = input.charCodeAt(pos); + if (isStringEnd(type, ch, input, pos)) { + out += input.slice(chunkStart, pos); + break; + } + if (ch === 92) { + out += input.slice(chunkStart, pos); + const res = readEscapedChar(input, pos, lineStart, curLine, type === "template", errors); + if (res.ch === null && !firstInvalidLoc) { + firstInvalidLoc = { + pos, + lineStart, + curLine + }; + } else { + out += res.ch; + } + ({ + pos, + lineStart, + curLine + } = res); + chunkStart = pos; + } else if (ch === 8232 || ch === 8233) { + ++pos; + ++curLine; + lineStart = pos; + } else if (ch === 10 || ch === 13) { + if (type === "template") { + out += input.slice(chunkStart, pos) + "\n"; + ++pos; + if (ch === 13 && input.charCodeAt(pos) === 10) { + ++pos; + } + ++curLine; + chunkStart = lineStart = pos; + } else { + errors.unterminated(initialPos, initialLineStart, initialCurLine); + } + } else { + ++pos; + } + } + return { + pos, + str: out, + firstInvalidLoc, + lineStart, + curLine, + containsInvalid: !!firstInvalidLoc + }; +} +function isStringEnd(type, ch, input, pos) { + if (type === "template") { + return ch === 96 || ch === 36 && input.charCodeAt(pos + 1) === 123; + } + return ch === (type === "double" ? 34 : 39); +} +function readEscapedChar(input, pos, lineStart, curLine, inTemplate, errors) { + const throwOnInvalid = !inTemplate; + pos++; + const res = ch => ({ + pos, + ch, + lineStart, + curLine + }); + const ch = input.charCodeAt(pos++); + switch (ch) { + case 110: + return res("\n"); + case 114: + return res("\r"); + case 120: + { + let code; + ({ + code, + pos + } = readHexChar(input, pos, lineStart, curLine, 2, false, throwOnInvalid, errors)); + return res(code === null ? null : String.fromCharCode(code)); + } + case 117: + { + let code; + ({ + code, + pos + } = readCodePoint(input, pos, lineStart, curLine, throwOnInvalid, errors)); + return res(code === null ? null : String.fromCodePoint(code)); + } + case 116: + return res("\t"); + case 98: + return res("\b"); + case 118: + return res("\u000b"); + case 102: + return res("\f"); + case 13: + if (input.charCodeAt(pos) === 10) { + ++pos; + } + case 10: + lineStart = pos; + ++curLine; + case 8232: + case 8233: + return res(""); + case 56: + case 57: + if (inTemplate) { + return res(null); + } else { + errors.strictNumericEscape(pos - 1, lineStart, curLine); + } + default: + if (ch >= 48 && ch <= 55) { + const startPos = pos - 1; + const match = /^[0-7]+/.exec(input.slice(startPos, pos + 2)); + let octalStr = match[0]; + let octal = parseInt(octalStr, 8); + if (octal > 255) { + octalStr = octalStr.slice(0, -1); + octal = parseInt(octalStr, 8); + } + pos += octalStr.length - 1; + const next = input.charCodeAt(pos); + if (octalStr !== "0" || next === 56 || next === 57) { + if (inTemplate) { + return res(null); + } else { + errors.strictNumericEscape(startPos, lineStart, curLine); + } + } + return res(String.fromCharCode(octal)); + } + return res(String.fromCharCode(ch)); + } +} +function readHexChar(input, pos, lineStart, curLine, len, forceLen, throwOnInvalid, errors) { + const initialPos = pos; + let n; + ({ + n, + pos + } = readInt(input, pos, lineStart, curLine, 16, len, forceLen, false, errors, !throwOnInvalid)); + if (n === null) { + if (throwOnInvalid) { + errors.invalidEscapeSequence(initialPos, lineStart, curLine); + } else { + pos = initialPos - 1; + } + } + return { + code: n, + pos + }; +} +function readInt(input, pos, lineStart, curLine, radix, len, forceLen, allowNumSeparator, errors, bailOnError) { + const start = pos; + const forbiddenSiblings = radix === 16 ? forbiddenNumericSeparatorSiblings.hex : forbiddenNumericSeparatorSiblings.decBinOct; + const isAllowedSibling = radix === 16 ? isAllowedNumericSeparatorSibling.hex : radix === 10 ? isAllowedNumericSeparatorSibling.dec : radix === 8 ? isAllowedNumericSeparatorSibling.oct : isAllowedNumericSeparatorSibling.bin; + let invalid = false; + let total = 0; + for (let i = 0, e = len == null ? Infinity : len; i < e; ++i) { + const code = input.charCodeAt(pos); + let val; + if (code === 95 && allowNumSeparator !== "bail") { + const prev = input.charCodeAt(pos - 1); + const next = input.charCodeAt(pos + 1); + if (!allowNumSeparator) { + if (bailOnError) return { + n: null, + pos + }; + errors.numericSeparatorInEscapeSequence(pos, lineStart, curLine); + } else if (Number.isNaN(next) || !isAllowedSibling(next) || forbiddenSiblings.has(prev) || forbiddenSiblings.has(next)) { + if (bailOnError) return { + n: null, + pos + }; + errors.unexpectedNumericSeparator(pos, lineStart, curLine); + } + ++pos; + continue; + } + if (code >= 97) { + val = code - 97 + 10; + } else if (code >= 65) { + val = code - 65 + 10; + } else if (_isDigit(code)) { + val = code - 48; + } else { + val = Infinity; + } + if (val >= radix) { + if (val <= 9 && bailOnError) { + return { + n: null, + pos + }; + } else if (val <= 9 && errors.invalidDigit(pos, lineStart, curLine, radix)) { + val = 0; + } else if (forceLen) { + val = 0; + invalid = true; + } else { + break; + } + } + ++pos; + total = total * radix + val; + } + if (pos === start || len != null && pos - start !== len || invalid) { + return { + n: null, + pos + }; + } + return { + n: total, + pos + }; +} +function readCodePoint(input, pos, lineStart, curLine, throwOnInvalid, errors) { + const ch = input.charCodeAt(pos); + let code; + if (ch === 123) { + ++pos; + ({ + code, + pos + } = readHexChar(input, pos, lineStart, curLine, input.indexOf("}", pos) - pos, true, throwOnInvalid, errors)); + ++pos; + if (code !== null && code > 0x10ffff) { + if (throwOnInvalid) { + errors.invalidCodePoint(pos, lineStart, curLine); + } else { + return { + code: null, + pos + }; + } + } + } else { + ({ + code, + pos + } = readHexChar(input, pos, lineStart, curLine, 4, false, throwOnInvalid, errors)); + } + return { + code, + pos + }; +} +function buildPosition(pos, lineStart, curLine) { + return new Position(curLine, pos - lineStart, pos); +} +const VALID_REGEX_FLAGS = new Set([103, 109, 115, 105, 121, 117, 100, 118]); +class Token { + constructor(state) { + const startIndex = state.startIndex || 0; + this.type = state.type; + this.value = state.value; + this.start = startIndex + state.start; + this.end = startIndex + state.end; + this.loc = new SourceLocation(state.startLoc, state.endLoc); + } +} +class Tokenizer extends CommentsParser { + constructor(options, input) { + super(); + this.isLookahead = void 0; + this.tokens = []; + this.errorHandlers_readInt = { + invalidDigit: (pos, lineStart, curLine, radix) => { + if (!(this.optionFlags & 2048)) return false; + this.raise(Errors.InvalidDigit, buildPosition(pos, lineStart, curLine), { + radix + }); + return true; + }, + numericSeparatorInEscapeSequence: this.errorBuilder(Errors.NumericSeparatorInEscapeSequence), + unexpectedNumericSeparator: this.errorBuilder(Errors.UnexpectedNumericSeparator) + }; + this.errorHandlers_readCodePoint = Object.assign({}, this.errorHandlers_readInt, { + invalidEscapeSequence: this.errorBuilder(Errors.InvalidEscapeSequence), + invalidCodePoint: this.errorBuilder(Errors.InvalidCodePoint) + }); + this.errorHandlers_readStringContents_string = Object.assign({}, this.errorHandlers_readCodePoint, { + strictNumericEscape: (pos, lineStart, curLine) => { + this.recordStrictModeErrors(Errors.StrictNumericEscape, buildPosition(pos, lineStart, curLine)); + }, + unterminated: (pos, lineStart, curLine) => { + throw this.raise(Errors.UnterminatedString, buildPosition(pos - 1, lineStart, curLine)); + } + }); + this.errorHandlers_readStringContents_template = Object.assign({}, this.errorHandlers_readCodePoint, { + strictNumericEscape: this.errorBuilder(Errors.StrictNumericEscape), + unterminated: (pos, lineStart, curLine) => { + throw this.raise(Errors.UnterminatedTemplate, buildPosition(pos, lineStart, curLine)); + } + }); + this.state = new State(); + this.state.init(options); + this.input = input; + this.length = input.length; + this.comments = []; + this.isLookahead = false; + } + pushToken(token) { + this.tokens.length = this.state.tokensLength; + this.tokens.push(token); + ++this.state.tokensLength; + } + next() { + this.checkKeywordEscapes(); + if (this.optionFlags & 256) { + this.pushToken(new Token(this.state)); + } + this.state.lastTokEndLoc = this.state.endLoc; + this.state.lastTokStartLoc = this.state.startLoc; + this.nextToken(); + } + eat(type) { + if (this.match(type)) { + this.next(); + return true; + } else { + return false; + } + } + match(type) { + return this.state.type === type; + } + createLookaheadState(state) { + return { + pos: state.pos, + value: null, + type: state.type, + start: state.start, + end: state.end, + context: [this.curContext()], + inType: state.inType, + startLoc: state.startLoc, + lastTokEndLoc: state.lastTokEndLoc, + curLine: state.curLine, + lineStart: state.lineStart, + curPosition: state.curPosition + }; + } + lookahead() { + const old = this.state; + this.state = this.createLookaheadState(old); + this.isLookahead = true; + this.nextToken(); + this.isLookahead = false; + const curr = this.state; + this.state = old; + return curr; + } + nextTokenStart() { + return this.nextTokenStartSince(this.state.pos); + } + nextTokenStartSince(pos) { + skipWhiteSpace.lastIndex = pos; + return skipWhiteSpace.test(this.input) ? skipWhiteSpace.lastIndex : pos; + } + lookaheadCharCode() { + return this.lookaheadCharCodeSince(this.state.pos); + } + lookaheadCharCodeSince(pos) { + return this.input.charCodeAt(this.nextTokenStartSince(pos)); + } + nextTokenInLineStart() { + return this.nextTokenInLineStartSince(this.state.pos); + } + nextTokenInLineStartSince(pos) { + skipWhiteSpaceInLine.lastIndex = pos; + return skipWhiteSpaceInLine.test(this.input) ? skipWhiteSpaceInLine.lastIndex : pos; + } + lookaheadInLineCharCode() { + return this.input.charCodeAt(this.nextTokenInLineStart()); + } + codePointAtPos(pos) { + let cp = this.input.charCodeAt(pos); + if ((cp & 0xfc00) === 0xd800 && ++pos < this.input.length) { + const trail = this.input.charCodeAt(pos); + if ((trail & 0xfc00) === 0xdc00) { + cp = 0x10000 + ((cp & 0x3ff) << 10) + (trail & 0x3ff); + } + } + return cp; + } + setStrict(strict) { + this.state.strict = strict; + if (strict) { + this.state.strictErrors.forEach(([toParseError, at]) => this.raise(toParseError, at)); + this.state.strictErrors.clear(); + } + } + curContext() { + return this.state.context[this.state.context.length - 1]; + } + nextToken() { + this.skipSpace(); + this.state.start = this.state.pos; + if (!this.isLookahead) this.state.startLoc = this.state.curPosition(); + if (this.state.pos >= this.length) { + this.finishToken(140); + return; + } + this.getTokenFromCode(this.codePointAtPos(this.state.pos)); + } + skipBlockComment(commentEnd) { + let startLoc; + if (!this.isLookahead) startLoc = this.state.curPosition(); + const start = this.state.pos; + const end = this.input.indexOf(commentEnd, start + 2); + if (end === -1) { + throw this.raise(Errors.UnterminatedComment, this.state.curPosition()); + } + this.state.pos = end + commentEnd.length; + lineBreakG.lastIndex = start + 2; + while (lineBreakG.test(this.input) && lineBreakG.lastIndex <= end) { + ++this.state.curLine; + this.state.lineStart = lineBreakG.lastIndex; + } + if (this.isLookahead) return; + const comment = { + type: "CommentBlock", + value: this.input.slice(start + 2, end), + start: this.sourceToOffsetPos(start), + end: this.sourceToOffsetPos(end + commentEnd.length), + loc: new SourceLocation(startLoc, this.state.curPosition()) + }; + if (this.optionFlags & 256) this.pushToken(comment); + return comment; + } + skipLineComment(startSkip) { + const start = this.state.pos; + let startLoc; + if (!this.isLookahead) startLoc = this.state.curPosition(); + let ch = this.input.charCodeAt(this.state.pos += startSkip); + if (this.state.pos < this.length) { + while (!isNewLine(ch) && ++this.state.pos < this.length) { + ch = this.input.charCodeAt(this.state.pos); + } + } + if (this.isLookahead) return; + const end = this.state.pos; + const value = this.input.slice(start + startSkip, end); + const comment = { + type: "CommentLine", + value, + start: this.sourceToOffsetPos(start), + end: this.sourceToOffsetPos(end), + loc: new SourceLocation(startLoc, this.state.curPosition()) + }; + if (this.optionFlags & 256) this.pushToken(comment); + return comment; + } + skipSpace() { + const spaceStart = this.state.pos; + const comments = this.optionFlags & 4096 ? [] : null; + loop: while (this.state.pos < this.length) { + const ch = this.input.charCodeAt(this.state.pos); + switch (ch) { + case 32: + case 160: + case 9: + ++this.state.pos; + break; + case 13: + if (this.input.charCodeAt(this.state.pos + 1) === 10) { + ++this.state.pos; + } + case 10: + case 8232: + case 8233: + ++this.state.pos; + ++this.state.curLine; + this.state.lineStart = this.state.pos; + break; + case 47: + switch (this.input.charCodeAt(this.state.pos + 1)) { + case 42: + { + const comment = this.skipBlockComment("*/"); + if (comment !== undefined) { + this.addComment(comment); + comments == null || comments.push(comment); + } + break; + } + case 47: + { + const comment = this.skipLineComment(2); + if (comment !== undefined) { + this.addComment(comment); + comments == null || comments.push(comment); + } + break; + } + default: + break loop; + } + break; + default: + if (isWhitespace(ch)) { + ++this.state.pos; + } else if (ch === 45 && !this.inModule && this.optionFlags & 8192) { + const pos = this.state.pos; + if (this.input.charCodeAt(pos + 1) === 45 && this.input.charCodeAt(pos + 2) === 62 && (spaceStart === 0 || this.state.lineStart > spaceStart)) { + const comment = this.skipLineComment(3); + if (comment !== undefined) { + this.addComment(comment); + comments == null || comments.push(comment); + } + } else { + break loop; + } + } else if (ch === 60 && !this.inModule && this.optionFlags & 8192) { + const pos = this.state.pos; + if (this.input.charCodeAt(pos + 1) === 33 && this.input.charCodeAt(pos + 2) === 45 && this.input.charCodeAt(pos + 3) === 45) { + const comment = this.skipLineComment(4); + if (comment !== undefined) { + this.addComment(comment); + comments == null || comments.push(comment); + } + } else { + break loop; + } + } else { + break loop; + } + } + } + if ((comments == null ? void 0 : comments.length) > 0) { + const end = this.state.pos; + const commentWhitespace = { + start: this.sourceToOffsetPos(spaceStart), + end: this.sourceToOffsetPos(end), + comments: comments, + leadingNode: null, + trailingNode: null, + containingNode: null + }; + this.state.commentStack.push(commentWhitespace); + } + } + finishToken(type, val) { + this.state.end = this.state.pos; + this.state.endLoc = this.state.curPosition(); + const prevType = this.state.type; + this.state.type = type; + this.state.value = val; + if (!this.isLookahead) { + this.updateContext(prevType); + } + } + replaceToken(type) { + this.state.type = type; + this.updateContext(); + } + readToken_numberSign() { + if (this.state.pos === 0 && this.readToken_interpreter()) { + return; + } + const nextPos = this.state.pos + 1; + const next = this.codePointAtPos(nextPos); + if (next >= 48 && next <= 57) { + throw this.raise(Errors.UnexpectedDigitAfterHash, this.state.curPosition()); + } + if (next === 123 || next === 91 && this.hasPlugin("recordAndTuple")) { + this.expectPlugin("recordAndTuple"); + if (this.getPluginOption("recordAndTuple", "syntaxType") === "bar") { + throw this.raise(next === 123 ? Errors.RecordExpressionHashIncorrectStartSyntaxType : Errors.TupleExpressionHashIncorrectStartSyntaxType, this.state.curPosition()); + } + this.state.pos += 2; + if (next === 123) { + this.finishToken(7); + } else { + this.finishToken(1); + } + } else if (isIdentifierStart(next)) { + ++this.state.pos; + this.finishToken(139, this.readWord1(next)); + } else if (next === 92) { + ++this.state.pos; + this.finishToken(139, this.readWord1()); + } else { + this.finishOp(27, 1); + } + } + readToken_dot() { + const next = this.input.charCodeAt(this.state.pos + 1); + if (next >= 48 && next <= 57) { + this.readNumber(true); + return; + } + if (next === 46 && this.input.charCodeAt(this.state.pos + 2) === 46) { + this.state.pos += 3; + this.finishToken(21); + } else { + ++this.state.pos; + this.finishToken(16); + } + } + readToken_slash() { + const next = this.input.charCodeAt(this.state.pos + 1); + if (next === 61) { + this.finishOp(31, 2); + } else { + this.finishOp(56, 1); + } + } + readToken_interpreter() { + if (this.state.pos !== 0 || this.length < 2) return false; + let ch = this.input.charCodeAt(this.state.pos + 1); + if (ch !== 33) return false; + const start = this.state.pos; + this.state.pos += 1; + while (!isNewLine(ch) && ++this.state.pos < this.length) { + ch = this.input.charCodeAt(this.state.pos); + } + const value = this.input.slice(start + 2, this.state.pos); + this.finishToken(28, value); + return true; + } + readToken_mult_modulo(code) { + let type = code === 42 ? 55 : 54; + let width = 1; + let next = this.input.charCodeAt(this.state.pos + 1); + if (code === 42 && next === 42) { + width++; + next = this.input.charCodeAt(this.state.pos + 2); + type = 57; + } + if (next === 61 && !this.state.inType) { + width++; + type = code === 37 ? 33 : 30; + } + this.finishOp(type, width); + } + readToken_pipe_amp(code) { + const next = this.input.charCodeAt(this.state.pos + 1); + if (next === code) { + if (this.input.charCodeAt(this.state.pos + 2) === 61) { + this.finishOp(30, 3); + } else { + this.finishOp(code === 124 ? 41 : 42, 2); + } + return; + } + if (code === 124) { + if (next === 62) { + this.finishOp(39, 2); + return; + } + if (this.hasPlugin("recordAndTuple") && next === 125) { + if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") { + throw this.raise(Errors.RecordExpressionBarIncorrectEndSyntaxType, this.state.curPosition()); + } + this.state.pos += 2; + this.finishToken(9); + return; + } + if (this.hasPlugin("recordAndTuple") && next === 93) { + if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") { + throw this.raise(Errors.TupleExpressionBarIncorrectEndSyntaxType, this.state.curPosition()); + } + this.state.pos += 2; + this.finishToken(4); + return; + } + } + if (next === 61) { + this.finishOp(30, 2); + return; + } + this.finishOp(code === 124 ? 43 : 45, 1); + } + readToken_caret() { + const next = this.input.charCodeAt(this.state.pos + 1); + if (next === 61 && !this.state.inType) { + this.finishOp(32, 2); + } else if (next === 94 && this.hasPlugin(["pipelineOperator", { + proposal: "hack", + topicToken: "^^" + }])) { + this.finishOp(37, 2); + const lookaheadCh = this.input.codePointAt(this.state.pos); + if (lookaheadCh === 94) { + this.unexpected(); + } + } else { + this.finishOp(44, 1); + } + } + readToken_atSign() { + const next = this.input.charCodeAt(this.state.pos + 1); + if (next === 64 && this.hasPlugin(["pipelineOperator", { + proposal: "hack", + topicToken: "@@" + }])) { + this.finishOp(38, 2); + } else { + this.finishOp(26, 1); + } + } + readToken_plus_min(code) { + const next = this.input.charCodeAt(this.state.pos + 1); + if (next === code) { + this.finishOp(34, 2); + return; + } + if (next === 61) { + this.finishOp(30, 2); + } else { + this.finishOp(53, 1); + } + } + readToken_lt() { + const { + pos + } = this.state; + const next = this.input.charCodeAt(pos + 1); + if (next === 60) { + if (this.input.charCodeAt(pos + 2) === 61) { + this.finishOp(30, 3); + return; + } + this.finishOp(51, 2); + return; + } + if (next === 61) { + this.finishOp(49, 2); + return; + } + this.finishOp(47, 1); + } + readToken_gt() { + const { + pos + } = this.state; + const next = this.input.charCodeAt(pos + 1); + if (next === 62) { + const size = this.input.charCodeAt(pos + 2) === 62 ? 3 : 2; + if (this.input.charCodeAt(pos + size) === 61) { + this.finishOp(30, size + 1); + return; + } + this.finishOp(52, size); + return; + } + if (next === 61) { + this.finishOp(49, 2); + return; + } + this.finishOp(48, 1); + } + readToken_eq_excl(code) { + const next = this.input.charCodeAt(this.state.pos + 1); + if (next === 61) { + this.finishOp(46, this.input.charCodeAt(this.state.pos + 2) === 61 ? 3 : 2); + return; + } + if (code === 61 && next === 62) { + this.state.pos += 2; + this.finishToken(19); + return; + } + this.finishOp(code === 61 ? 29 : 35, 1); + } + readToken_question() { + const next = this.input.charCodeAt(this.state.pos + 1); + const next2 = this.input.charCodeAt(this.state.pos + 2); + if (next === 63) { + if (next2 === 61) { + this.finishOp(30, 3); + } else { + this.finishOp(40, 2); + } + } else if (next === 46 && !(next2 >= 48 && next2 <= 57)) { + this.state.pos += 2; + this.finishToken(18); + } else { + ++this.state.pos; + this.finishToken(17); + } + } + getTokenFromCode(code) { + switch (code) { + case 46: + this.readToken_dot(); + return; + case 40: + ++this.state.pos; + this.finishToken(10); + return; + case 41: + ++this.state.pos; + this.finishToken(11); + return; + case 59: + ++this.state.pos; + this.finishToken(13); + return; + case 44: + ++this.state.pos; + this.finishToken(12); + return; + case 91: + if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) { + if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") { + throw this.raise(Errors.TupleExpressionBarIncorrectStartSyntaxType, this.state.curPosition()); + } + this.state.pos += 2; + this.finishToken(2); + } else { + ++this.state.pos; + this.finishToken(0); + } + return; + case 93: + ++this.state.pos; + this.finishToken(3); + return; + case 123: + if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) { + if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") { + throw this.raise(Errors.RecordExpressionBarIncorrectStartSyntaxType, this.state.curPosition()); + } + this.state.pos += 2; + this.finishToken(6); + } else { + ++this.state.pos; + this.finishToken(5); + } + return; + case 125: + ++this.state.pos; + this.finishToken(8); + return; + case 58: + if (this.hasPlugin("functionBind") && this.input.charCodeAt(this.state.pos + 1) === 58) { + this.finishOp(15, 2); + } else { + ++this.state.pos; + this.finishToken(14); + } + return; + case 63: + this.readToken_question(); + return; + case 96: + this.readTemplateToken(); + return; + case 48: + { + const next = this.input.charCodeAt(this.state.pos + 1); + if (next === 120 || next === 88) { + this.readRadixNumber(16); + return; + } + if (next === 111 || next === 79) { + this.readRadixNumber(8); + return; + } + if (next === 98 || next === 66) { + this.readRadixNumber(2); + return; + } + } + case 49: + case 50: + case 51: + case 52: + case 53: + case 54: + case 55: + case 56: + case 57: + this.readNumber(false); + return; + case 34: + case 39: + this.readString(code); + return; + case 47: + this.readToken_slash(); + return; + case 37: + case 42: + this.readToken_mult_modulo(code); + return; + case 124: + case 38: + this.readToken_pipe_amp(code); + return; + case 94: + this.readToken_caret(); + return; + case 43: + case 45: + this.readToken_plus_min(code); + return; + case 60: + this.readToken_lt(); + return; + case 62: + this.readToken_gt(); + return; + case 61: + case 33: + this.readToken_eq_excl(code); + return; + case 126: + this.finishOp(36, 1); + return; + case 64: + this.readToken_atSign(); + return; + case 35: + this.readToken_numberSign(); + return; + case 92: + this.readWord(); + return; + default: + if (isIdentifierStart(code)) { + this.readWord(code); + return; + } + } + throw this.raise(Errors.InvalidOrUnexpectedToken, this.state.curPosition(), { + unexpected: String.fromCodePoint(code) + }); + } + finishOp(type, size) { + const str = this.input.slice(this.state.pos, this.state.pos + size); + this.state.pos += size; + this.finishToken(type, str); + } + readRegexp() { + const startLoc = this.state.startLoc; + const start = this.state.start + 1; + let escaped, inClass; + let { + pos + } = this.state; + for (;; ++pos) { + if (pos >= this.length) { + throw this.raise(Errors.UnterminatedRegExp, createPositionWithColumnOffset(startLoc, 1)); + } + const ch = this.input.charCodeAt(pos); + if (isNewLine(ch)) { + throw this.raise(Errors.UnterminatedRegExp, createPositionWithColumnOffset(startLoc, 1)); + } + if (escaped) { + escaped = false; + } else { + if (ch === 91) { + inClass = true; + } else if (ch === 93 && inClass) { + inClass = false; + } else if (ch === 47 && !inClass) { + break; + } + escaped = ch === 92; + } + } + const content = this.input.slice(start, pos); + ++pos; + let mods = ""; + const nextPos = () => createPositionWithColumnOffset(startLoc, pos + 2 - start); + while (pos < this.length) { + const cp = this.codePointAtPos(pos); + const char = String.fromCharCode(cp); + if (VALID_REGEX_FLAGS.has(cp)) { + if (cp === 118) { + if (mods.includes("u")) { + this.raise(Errors.IncompatibleRegExpUVFlags, nextPos()); + } + } else if (cp === 117) { + if (mods.includes("v")) { + this.raise(Errors.IncompatibleRegExpUVFlags, nextPos()); + } + } + if (mods.includes(char)) { + this.raise(Errors.DuplicateRegExpFlags, nextPos()); + } + } else if (isIdentifierChar(cp) || cp === 92) { + this.raise(Errors.MalformedRegExpFlags, nextPos()); + } else { + break; + } + ++pos; + mods += char; + } + this.state.pos = pos; + this.finishToken(138, { + pattern: content, + flags: mods + }); + } + readInt(radix, len, forceLen = false, allowNumSeparator = true) { + const { + n, + pos + } = readInt(this.input, this.state.pos, this.state.lineStart, this.state.curLine, radix, len, forceLen, allowNumSeparator, this.errorHandlers_readInt, false); + this.state.pos = pos; + return n; + } + readRadixNumber(radix) { + const start = this.state.pos; + const startLoc = this.state.curPosition(); + let isBigInt = false; + this.state.pos += 2; + const val = this.readInt(radix); + if (val == null) { + this.raise(Errors.InvalidDigit, createPositionWithColumnOffset(startLoc, 2), { + radix + }); + } + const next = this.input.charCodeAt(this.state.pos); + if (next === 110) { + ++this.state.pos; + isBigInt = true; + } else if (next === 109) { + throw this.raise(Errors.InvalidDecimal, startLoc); + } + if (isIdentifierStart(this.codePointAtPos(this.state.pos))) { + throw this.raise(Errors.NumberIdentifier, this.state.curPosition()); + } + if (isBigInt) { + const str = this.input.slice(start, this.state.pos).replace(/[_n]/g, ""); + this.finishToken(136, str); + return; + } + this.finishToken(135, val); + } + readNumber(startsWithDot) { + const start = this.state.pos; + const startLoc = this.state.curPosition(); + let isFloat = false; + let isBigInt = false; + let hasExponent = false; + let isOctal = false; + if (!startsWithDot && this.readInt(10) === null) { + this.raise(Errors.InvalidNumber, this.state.curPosition()); + } + const hasLeadingZero = this.state.pos - start >= 2 && this.input.charCodeAt(start) === 48; + if (hasLeadingZero) { + const integer = this.input.slice(start, this.state.pos); + this.recordStrictModeErrors(Errors.StrictOctalLiteral, startLoc); + if (!this.state.strict) { + const underscorePos = integer.indexOf("_"); + if (underscorePos > 0) { + this.raise(Errors.ZeroDigitNumericSeparator, createPositionWithColumnOffset(startLoc, underscorePos)); + } + } + isOctal = hasLeadingZero && !/[89]/.test(integer); + } + let next = this.input.charCodeAt(this.state.pos); + if (next === 46 && !isOctal) { + ++this.state.pos; + this.readInt(10); + isFloat = true; + next = this.input.charCodeAt(this.state.pos); + } + if ((next === 69 || next === 101) && !isOctal) { + next = this.input.charCodeAt(++this.state.pos); + if (next === 43 || next === 45) { + ++this.state.pos; + } + if (this.readInt(10) === null) { + this.raise(Errors.InvalidOrMissingExponent, startLoc); + } + isFloat = true; + hasExponent = true; + next = this.input.charCodeAt(this.state.pos); + } + if (next === 110) { + if (isFloat || hasLeadingZero) { + this.raise(Errors.InvalidBigIntLiteral, startLoc); + } + ++this.state.pos; + isBigInt = true; + } + if (next === 109) { + this.expectPlugin("decimal", this.state.curPosition()); + if (hasExponent || hasLeadingZero) { + this.raise(Errors.InvalidDecimal, startLoc); + } + ++this.state.pos; + var isDecimal = true; + } + if (isIdentifierStart(this.codePointAtPos(this.state.pos))) { + throw this.raise(Errors.NumberIdentifier, this.state.curPosition()); + } + const str = this.input.slice(start, this.state.pos).replace(/[_mn]/g, ""); + if (isBigInt) { + this.finishToken(136, str); + return; + } + if (isDecimal) { + this.finishToken(137, str); + return; + } + const val = isOctal ? parseInt(str, 8) : parseFloat(str); + this.finishToken(135, val); + } + readCodePoint(throwOnInvalid) { + const { + code, + pos + } = readCodePoint(this.input, this.state.pos, this.state.lineStart, this.state.curLine, throwOnInvalid, this.errorHandlers_readCodePoint); + this.state.pos = pos; + return code; + } + readString(quote) { + const { + str, + pos, + curLine, + lineStart + } = readStringContents(quote === 34 ? "double" : "single", this.input, this.state.pos + 1, this.state.lineStart, this.state.curLine, this.errorHandlers_readStringContents_string); + this.state.pos = pos + 1; + this.state.lineStart = lineStart; + this.state.curLine = curLine; + this.finishToken(134, str); + } + readTemplateContinuation() { + if (!this.match(8)) { + this.unexpected(null, 8); + } + this.state.pos--; + this.readTemplateToken(); + } + readTemplateToken() { + const opening = this.input[this.state.pos]; + const { + str, + firstInvalidLoc, + pos, + curLine, + lineStart + } = readStringContents("template", this.input, this.state.pos + 1, this.state.lineStart, this.state.curLine, this.errorHandlers_readStringContents_template); + this.state.pos = pos + 1; + this.state.lineStart = lineStart; + this.state.curLine = curLine; + if (firstInvalidLoc) { + this.state.firstInvalidTemplateEscapePos = new Position(firstInvalidLoc.curLine, firstInvalidLoc.pos - firstInvalidLoc.lineStart, this.sourceToOffsetPos(firstInvalidLoc.pos)); + } + if (this.input.codePointAt(pos) === 96) { + this.finishToken(24, firstInvalidLoc ? null : opening + str + "`"); + } else { + this.state.pos++; + this.finishToken(25, firstInvalidLoc ? null : opening + str + "${"); + } + } + recordStrictModeErrors(toParseError, at) { + const index = at.index; + if (this.state.strict && !this.state.strictErrors.has(index)) { + this.raise(toParseError, at); + } else { + this.state.strictErrors.set(index, [toParseError, at]); + } + } + readWord1(firstCode) { + this.state.containsEsc = false; + let word = ""; + const start = this.state.pos; + let chunkStart = this.state.pos; + if (firstCode !== undefined) { + this.state.pos += firstCode <= 0xffff ? 1 : 2; + } + while (this.state.pos < this.length) { + const ch = this.codePointAtPos(this.state.pos); + if (isIdentifierChar(ch)) { + this.state.pos += ch <= 0xffff ? 1 : 2; + } else if (ch === 92) { + this.state.containsEsc = true; + word += this.input.slice(chunkStart, this.state.pos); + const escStart = this.state.curPosition(); + const identifierCheck = this.state.pos === start ? isIdentifierStart : isIdentifierChar; + if (this.input.charCodeAt(++this.state.pos) !== 117) { + this.raise(Errors.MissingUnicodeEscape, this.state.curPosition()); + chunkStart = this.state.pos - 1; + continue; + } + ++this.state.pos; + const esc = this.readCodePoint(true); + if (esc !== null) { + if (!identifierCheck(esc)) { + this.raise(Errors.EscapedCharNotAnIdentifier, escStart); + } + word += String.fromCodePoint(esc); + } + chunkStart = this.state.pos; + } else { + break; + } + } + return word + this.input.slice(chunkStart, this.state.pos); + } + readWord(firstCode) { + const word = this.readWord1(firstCode); + const type = keywords$1.get(word); + if (type !== undefined) { + this.finishToken(type, tokenLabelName(type)); + } else { + this.finishToken(132, word); + } + } + checkKeywordEscapes() { + const { + type + } = this.state; + if (tokenIsKeyword(type) && this.state.containsEsc) { + this.raise(Errors.InvalidEscapedReservedWord, this.state.startLoc, { + reservedWord: tokenLabelName(type) + }); + } + } + raise(toParseError, at, details = {}) { + const loc = at instanceof Position ? at : at.loc.start; + const error = toParseError(loc, details); + if (!(this.optionFlags & 2048)) throw error; + if (!this.isLookahead) this.state.errors.push(error); + return error; + } + raiseOverwrite(toParseError, at, details = {}) { + const loc = at instanceof Position ? at : at.loc.start; + const pos = loc.index; + const errors = this.state.errors; + for (let i = errors.length - 1; i >= 0; i--) { + const error = errors[i]; + if (error.loc.index === pos) { + return errors[i] = toParseError(loc, details); + } + if (error.loc.index < pos) break; + } + return this.raise(toParseError, at, details); + } + updateContext(prevType) {} + unexpected(loc, type) { + throw this.raise(Errors.UnexpectedToken, loc != null ? loc : this.state.startLoc, { + expected: type ? tokenLabelName(type) : null + }); + } + expectPlugin(pluginName, loc) { + if (this.hasPlugin(pluginName)) { + return true; + } + throw this.raise(Errors.MissingPlugin, loc != null ? loc : this.state.startLoc, { + missingPlugin: [pluginName] + }); + } + expectOnePlugin(pluginNames) { + if (!pluginNames.some(name => this.hasPlugin(name))) { + throw this.raise(Errors.MissingOneOfPlugins, this.state.startLoc, { + missingPlugin: pluginNames + }); + } + } + errorBuilder(error) { + return (pos, lineStart, curLine) => { + this.raise(error, buildPosition(pos, lineStart, curLine)); + }; + } +} +class ClassScope { + constructor() { + this.privateNames = new Set(); + this.loneAccessors = new Map(); + this.undefinedPrivateNames = new Map(); + } +} +class ClassScopeHandler { + constructor(parser) { + this.parser = void 0; + this.stack = []; + this.undefinedPrivateNames = new Map(); + this.parser = parser; + } + current() { + return this.stack[this.stack.length - 1]; + } + enter() { + this.stack.push(new ClassScope()); + } + exit() { + const oldClassScope = this.stack.pop(); + const current = this.current(); + for (const [name, loc] of Array.from(oldClassScope.undefinedPrivateNames)) { + if (current) { + if (!current.undefinedPrivateNames.has(name)) { + current.undefinedPrivateNames.set(name, loc); + } + } else { + this.parser.raise(Errors.InvalidPrivateFieldResolution, loc, { + identifierName: name + }); + } + } + } + declarePrivateName(name, elementType, loc) { + const { + privateNames, + loneAccessors, + undefinedPrivateNames + } = this.current(); + let redefined = privateNames.has(name); + if (elementType & 3) { + const accessor = redefined && loneAccessors.get(name); + if (accessor) { + const oldStatic = accessor & 4; + const newStatic = elementType & 4; + const oldKind = accessor & 3; + const newKind = elementType & 3; + redefined = oldKind === newKind || oldStatic !== newStatic; + if (!redefined) loneAccessors.delete(name); + } else if (!redefined) { + loneAccessors.set(name, elementType); + } + } + if (redefined) { + this.parser.raise(Errors.PrivateNameRedeclaration, loc, { + identifierName: name + }); + } + privateNames.add(name); + undefinedPrivateNames.delete(name); + } + usePrivateName(name, loc) { + let classScope; + for (classScope of this.stack) { + if (classScope.privateNames.has(name)) return; + } + if (classScope) { + classScope.undefinedPrivateNames.set(name, loc); + } else { + this.parser.raise(Errors.InvalidPrivateFieldResolution, loc, { + identifierName: name + }); + } + } +} +class ExpressionScope { + constructor(type = 0) { + this.type = type; + } + canBeArrowParameterDeclaration() { + return this.type === 2 || this.type === 1; + } + isCertainlyParameterDeclaration() { + return this.type === 3; + } +} +class ArrowHeadParsingScope extends ExpressionScope { + constructor(type) { + super(type); + this.declarationErrors = new Map(); + } + recordDeclarationError(ParsingErrorClass, at) { + const index = at.index; + this.declarationErrors.set(index, [ParsingErrorClass, at]); + } + clearDeclarationError(index) { + this.declarationErrors.delete(index); + } + iterateErrors(iterator) { + this.declarationErrors.forEach(iterator); + } +} +class ExpressionScopeHandler { + constructor(parser) { + this.parser = void 0; + this.stack = [new ExpressionScope()]; + this.parser = parser; + } + enter(scope) { + this.stack.push(scope); + } + exit() { + this.stack.pop(); + } + recordParameterInitializerError(toParseError, node) { + const origin = node.loc.start; + const { + stack + } = this; + let i = stack.length - 1; + let scope = stack[i]; + while (!scope.isCertainlyParameterDeclaration()) { + if (scope.canBeArrowParameterDeclaration()) { + scope.recordDeclarationError(toParseError, origin); + } else { + return; + } + scope = stack[--i]; + } + this.parser.raise(toParseError, origin); + } + recordArrowParameterBindingError(error, node) { + const { + stack + } = this; + const scope = stack[stack.length - 1]; + const origin = node.loc.start; + if (scope.isCertainlyParameterDeclaration()) { + this.parser.raise(error, origin); + } else if (scope.canBeArrowParameterDeclaration()) { + scope.recordDeclarationError(error, origin); + } else { + return; + } + } + recordAsyncArrowParametersError(at) { + const { + stack + } = this; + let i = stack.length - 1; + let scope = stack[i]; + while (scope.canBeArrowParameterDeclaration()) { + if (scope.type === 2) { + scope.recordDeclarationError(Errors.AwaitBindingIdentifier, at); + } + scope = stack[--i]; + } + } + validateAsPattern() { + const { + stack + } = this; + const currentScope = stack[stack.length - 1]; + if (!currentScope.canBeArrowParameterDeclaration()) return; + currentScope.iterateErrors(([toParseError, loc]) => { + this.parser.raise(toParseError, loc); + let i = stack.length - 2; + let scope = stack[i]; + while (scope.canBeArrowParameterDeclaration()) { + scope.clearDeclarationError(loc.index); + scope = stack[--i]; + } + }); + } +} +function newParameterDeclarationScope() { + return new ExpressionScope(3); +} +function newArrowHeadScope() { + return new ArrowHeadParsingScope(1); +} +function newAsyncArrowScope() { + return new ArrowHeadParsingScope(2); +} +function newExpressionScope() { + return new ExpressionScope(); +} +class UtilParser extends Tokenizer { + addExtra(node, key, value, enumerable = true) { + if (!node) return; + let { + extra + } = node; + if (extra == null) { + extra = {}; + node.extra = extra; + } + if (enumerable) { + extra[key] = value; + } else { + Object.defineProperty(extra, key, { + enumerable, + value + }); + } + } + isContextual(token) { + return this.state.type === token && !this.state.containsEsc; + } + isUnparsedContextual(nameStart, name) { + if (this.input.startsWith(name, nameStart)) { + const nextCh = this.input.charCodeAt(nameStart + name.length); + return !(isIdentifierChar(nextCh) || (nextCh & 0xfc00) === 0xd800); + } + return false; + } + isLookaheadContextual(name) { + const next = this.nextTokenStart(); + return this.isUnparsedContextual(next, name); + } + eatContextual(token) { + if (this.isContextual(token)) { + this.next(); + return true; + } + return false; + } + expectContextual(token, toParseError) { + if (!this.eatContextual(token)) { + if (toParseError != null) { + throw this.raise(toParseError, this.state.startLoc); + } + this.unexpected(null, token); + } + } + canInsertSemicolon() { + return this.match(140) || this.match(8) || this.hasPrecedingLineBreak(); + } + hasPrecedingLineBreak() { + return hasNewLine(this.input, this.offsetToSourcePos(this.state.lastTokEndLoc.index), this.state.start); + } + hasFollowingLineBreak() { + return hasNewLine(this.input, this.state.end, this.nextTokenStart()); + } + isLineTerminator() { + return this.eat(13) || this.canInsertSemicolon(); + } + semicolon(allowAsi = true) { + if (allowAsi ? this.isLineTerminator() : this.eat(13)) return; + this.raise(Errors.MissingSemicolon, this.state.lastTokEndLoc); + } + expect(type, loc) { + if (!this.eat(type)) { + this.unexpected(loc, type); + } + } + tryParse(fn, oldState = this.state.clone()) { + const abortSignal = { + node: null + }; + try { + const node = fn((node = null) => { + abortSignal.node = node; + throw abortSignal; + }); + if (this.state.errors.length > oldState.errors.length) { + const failState = this.state; + this.state = oldState; + this.state.tokensLength = failState.tokensLength; + return { + node, + error: failState.errors[oldState.errors.length], + thrown: false, + aborted: false, + failState + }; + } + return { + node: node, + error: null, + thrown: false, + aborted: false, + failState: null + }; + } catch (error) { + const failState = this.state; + this.state = oldState; + if (error instanceof SyntaxError) { + return { + node: null, + error, + thrown: true, + aborted: false, + failState + }; + } + if (error === abortSignal) { + return { + node: abortSignal.node, + error: null, + thrown: false, + aborted: true, + failState + }; + } + throw error; + } + } + checkExpressionErrors(refExpressionErrors, andThrow) { + if (!refExpressionErrors) return false; + const { + shorthandAssignLoc, + doubleProtoLoc, + privateKeyLoc, + optionalParametersLoc, + voidPatternLoc + } = refExpressionErrors; + const hasErrors = !!shorthandAssignLoc || !!doubleProtoLoc || !!optionalParametersLoc || !!privateKeyLoc || !!voidPatternLoc; + if (!andThrow) { + return hasErrors; + } + if (shorthandAssignLoc != null) { + this.raise(Errors.InvalidCoverInitializedName, shorthandAssignLoc); + } + if (doubleProtoLoc != null) { + this.raise(Errors.DuplicateProto, doubleProtoLoc); + } + if (privateKeyLoc != null) { + this.raise(Errors.UnexpectedPrivateField, privateKeyLoc); + } + if (optionalParametersLoc != null) { + this.unexpected(optionalParametersLoc); + } + if (voidPatternLoc != null) { + this.raise(Errors.InvalidCoverDiscardElement, voidPatternLoc); + } + } + isLiteralPropertyName() { + return tokenIsLiteralPropertyName(this.state.type); + } + isPrivateName(node) { + return node.type === "PrivateName"; + } + getPrivateNameSV(node) { + return node.id.name; + } + hasPropertyAsPrivateName(node) { + return (node.type === "MemberExpression" || node.type === "OptionalMemberExpression") && this.isPrivateName(node.property); + } + isObjectProperty(node) { + return node.type === "ObjectProperty"; + } + isObjectMethod(node) { + return node.type === "ObjectMethod"; + } + initializeScopes(inModule = this.options.sourceType === "module") { + const oldLabels = this.state.labels; + this.state.labels = []; + const oldExportedIdentifiers = this.exportedIdentifiers; + this.exportedIdentifiers = new Set(); + const oldInModule = this.inModule; + this.inModule = inModule; + const oldScope = this.scope; + const ScopeHandler = this.getScopeHandler(); + this.scope = new ScopeHandler(this, inModule); + const oldProdParam = this.prodParam; + this.prodParam = new ProductionParameterHandler(); + const oldClassScope = this.classScope; + this.classScope = new ClassScopeHandler(this); + const oldExpressionScope = this.expressionScope; + this.expressionScope = new ExpressionScopeHandler(this); + return () => { + this.state.labels = oldLabels; + this.exportedIdentifiers = oldExportedIdentifiers; + this.inModule = oldInModule; + this.scope = oldScope; + this.prodParam = oldProdParam; + this.classScope = oldClassScope; + this.expressionScope = oldExpressionScope; + }; + } + enterInitialScopes() { + let paramFlags = 0; + if (this.inModule || this.optionFlags & 1) { + paramFlags |= 2; + } + if (this.optionFlags & 32) { + paramFlags |= 1; + } + const isCommonJS = !this.inModule && this.options.sourceType === "commonjs"; + if (isCommonJS || this.optionFlags & 2) { + paramFlags |= 4; + } + this.prodParam.enter(paramFlags); + let scopeFlags = isCommonJS ? 514 : 1; + if (this.optionFlags & 4) { + scopeFlags |= 512; + } + this.scope.enter(scopeFlags); + } + checkDestructuringPrivate(refExpressionErrors) { + const { + privateKeyLoc + } = refExpressionErrors; + if (privateKeyLoc !== null) { + this.expectPlugin("destructuringPrivate", privateKeyLoc); + } + } +} +class ExpressionErrors { + constructor() { + this.shorthandAssignLoc = null; + this.doubleProtoLoc = null; + this.privateKeyLoc = null; + this.optionalParametersLoc = null; + this.voidPatternLoc = null; + } +} +class Node { + constructor(parser, pos, loc) { + this.type = ""; + this.start = pos; + this.end = 0; + this.loc = new SourceLocation(loc); + if ((parser == null ? void 0 : parser.optionFlags) & 128) this.range = [pos, 0]; + if (parser != null && parser.filename) this.loc.filename = parser.filename; + } +} +const NodePrototype = Node.prototype; +NodePrototype.__clone = function () { + const newNode = new Node(undefined, this.start, this.loc.start); + const keys = Object.keys(this); + for (let i = 0, length = keys.length; i < length; i++) { + const key = keys[i]; + if (key !== "leadingComments" && key !== "trailingComments" && key !== "innerComments") { + newNode[key] = this[key]; + } + } + return newNode; +}; +class NodeUtils extends UtilParser { + startNode() { + const loc = this.state.startLoc; + return new Node(this, loc.index, loc); + } + startNodeAt(loc) { + return new Node(this, loc.index, loc); + } + startNodeAtNode(type) { + return this.startNodeAt(type.loc.start); + } + finishNode(node, type) { + return this.finishNodeAt(node, type, this.state.lastTokEndLoc); + } + finishNodeAt(node, type, endLoc) { + node.type = type; + node.end = endLoc.index; + node.loc.end = endLoc; + if (this.optionFlags & 128) node.range[1] = endLoc.index; + if (this.optionFlags & 4096) { + this.processComment(node); + } + return node; + } + resetStartLocation(node, startLoc) { + node.start = startLoc.index; + node.loc.start = startLoc; + if (this.optionFlags & 128) node.range[0] = startLoc.index; + } + resetEndLocation(node, endLoc = this.state.lastTokEndLoc) { + node.end = endLoc.index; + node.loc.end = endLoc; + if (this.optionFlags & 128) node.range[1] = endLoc.index; + } + resetStartLocationFromNode(node, locationNode) { + this.resetStartLocation(node, locationNode.loc.start); + } + castNodeTo(node, type) { + node.type = type; + return node; + } + cloneIdentifier(node) { + const { + type, + start, + end, + loc, + range, + name + } = node; + const cloned = Object.create(NodePrototype); + cloned.type = type; + cloned.start = start; + cloned.end = end; + cloned.loc = loc; + cloned.range = range; + cloned.name = name; + if (node.extra) cloned.extra = node.extra; + return cloned; + } + cloneStringLiteral(node) { + const { + type, + start, + end, + loc, + range, + extra + } = node; + const cloned = Object.create(NodePrototype); + cloned.type = type; + cloned.start = start; + cloned.end = end; + cloned.loc = loc; + cloned.range = range; + cloned.extra = extra; + cloned.value = node.value; + return cloned; + } +} +const unwrapParenthesizedExpression = node => { + return node.type === "ParenthesizedExpression" ? unwrapParenthesizedExpression(node.expression) : node; +}; +class LValParser extends NodeUtils { + toAssignable(node, isLHS = false) { + var _node$extra, _node$extra3; + let parenthesized = undefined; + if (node.type === "ParenthesizedExpression" || (_node$extra = node.extra) != null && _node$extra.parenthesized) { + parenthesized = unwrapParenthesizedExpression(node); + if (isLHS) { + if (parenthesized.type === "Identifier") { + this.expressionScope.recordArrowParameterBindingError(Errors.InvalidParenthesizedAssignment, node); + } else if (parenthesized.type !== "CallExpression" && parenthesized.type !== "MemberExpression" && !this.isOptionalMemberExpression(parenthesized)) { + this.raise(Errors.InvalidParenthesizedAssignment, node); + } + } else { + this.raise(Errors.InvalidParenthesizedAssignment, node); + } + } + switch (node.type) { + case "Identifier": + case "ObjectPattern": + case "ArrayPattern": + case "AssignmentPattern": + case "RestElement": + case "VoidPattern": + break; + case "ObjectExpression": + this.castNodeTo(node, "ObjectPattern"); + for (let i = 0, length = node.properties.length, last = length - 1; i < length; i++) { + var _node$extra2; + const prop = node.properties[i]; + const isLast = i === last; + this.toAssignableObjectExpressionProp(prop, isLast, isLHS); + if (isLast && prop.type === "RestElement" && (_node$extra2 = node.extra) != null && _node$extra2.trailingCommaLoc) { + this.raise(Errors.RestTrailingComma, node.extra.trailingCommaLoc); + } + } + break; + case "ObjectProperty": + { + const { + key, + value + } = node; + if (this.isPrivateName(key)) { + this.classScope.usePrivateName(this.getPrivateNameSV(key), key.loc.start); + } + this.toAssignable(value, isLHS); + break; + } + case "SpreadElement": + { + throw new Error("Internal @babel/parser error (this is a bug, please report it)." + " SpreadElement should be converted by .toAssignable's caller."); + } + case "ArrayExpression": + this.castNodeTo(node, "ArrayPattern"); + this.toAssignableList(node.elements, (_node$extra3 = node.extra) == null ? void 0 : _node$extra3.trailingCommaLoc, isLHS); + break; + case "AssignmentExpression": + if (node.operator !== "=") { + this.raise(Errors.MissingEqInAssignment, node.left.loc.end); + } + this.castNodeTo(node, "AssignmentPattern"); + delete node.operator; + if (node.left.type === "VoidPattern") { + this.raise(Errors.VoidPatternInitializer, node.left); + } + this.toAssignable(node.left, isLHS); + break; + case "ParenthesizedExpression": + this.toAssignable(parenthesized, isLHS); + break; + } + } + toAssignableObjectExpressionProp(prop, isLast, isLHS) { + if (prop.type === "ObjectMethod") { + this.raise(prop.kind === "get" || prop.kind === "set" ? Errors.PatternHasAccessor : Errors.PatternHasMethod, prop.key); + } else if (prop.type === "SpreadElement") { + this.castNodeTo(prop, "RestElement"); + const arg = prop.argument; + this.checkToRestConversion(arg, false); + this.toAssignable(arg, isLHS); + if (!isLast) { + this.raise(Errors.RestTrailingComma, prop); + } + } else { + this.toAssignable(prop, isLHS); + } + } + toAssignableList(exprList, trailingCommaLoc, isLHS) { + const end = exprList.length - 1; + for (let i = 0; i <= end; i++) { + const elt = exprList[i]; + if (!elt) continue; + this.toAssignableListItem(exprList, i, isLHS); + if (elt.type === "RestElement") { + if (i < end) { + this.raise(Errors.RestTrailingComma, elt); + } else if (trailingCommaLoc) { + this.raise(Errors.RestTrailingComma, trailingCommaLoc); + } + } + } + } + toAssignableListItem(exprList, index, isLHS) { + const node = exprList[index]; + if (node.type === "SpreadElement") { + this.castNodeTo(node, "RestElement"); + const arg = node.argument; + this.checkToRestConversion(arg, true); + this.toAssignable(arg, isLHS); + } else { + this.toAssignable(node, isLHS); + } + } + isAssignable(node, isBinding) { + switch (node.type) { + case "Identifier": + case "ObjectPattern": + case "ArrayPattern": + case "AssignmentPattern": + case "RestElement": + case "VoidPattern": + return true; + case "ObjectExpression": + { + const last = node.properties.length - 1; + return node.properties.every((prop, i) => { + return prop.type !== "ObjectMethod" && (i === last || prop.type !== "SpreadElement") && this.isAssignable(prop); + }); + } + case "ObjectProperty": + return this.isAssignable(node.value); + case "SpreadElement": + return this.isAssignable(node.argument); + case "ArrayExpression": + return node.elements.every(element => element === null || this.isAssignable(element)); + case "AssignmentExpression": + return node.operator === "="; + case "ParenthesizedExpression": + return this.isAssignable(node.expression); + case "MemberExpression": + case "OptionalMemberExpression": + return !isBinding; + default: + return false; + } + } + toReferencedList(exprList, isParenthesizedExpr) { + return exprList; + } + toReferencedListDeep(exprList, isParenthesizedExpr) { + this.toReferencedList(exprList, isParenthesizedExpr); + for (const expr of exprList) { + if ((expr == null ? void 0 : expr.type) === "ArrayExpression") { + this.toReferencedListDeep(expr.elements); + } + } + } + parseSpread(refExpressionErrors) { + const node = this.startNode(); + this.next(); + node.argument = this.parseMaybeAssignAllowIn(refExpressionErrors, undefined); + return this.finishNode(node, "SpreadElement"); + } + parseRestBinding() { + const node = this.startNode(); + this.next(); + const argument = this.parseBindingAtom(); + if (argument.type === "VoidPattern") { + this.raise(Errors.UnexpectedVoidPattern, argument); + } + node.argument = argument; + return this.finishNode(node, "RestElement"); + } + parseBindingAtom() { + switch (this.state.type) { + case 0: + { + const node = this.startNode(); + this.next(); + node.elements = this.parseBindingList(3, 93, 1); + return this.finishNode(node, "ArrayPattern"); + } + case 5: + return this.parseObjectLike(8, true); + case 88: + return this.parseVoidPattern(null); + } + return this.parseIdentifier(); + } + parseBindingList(close, closeCharCode, flags) { + const allowEmpty = flags & 1; + const elts = []; + let first = true; + while (!this.eat(close)) { + if (first) { + first = false; + } else { + this.expect(12); + } + if (allowEmpty && this.match(12)) { + elts.push(null); + } else if (this.eat(close)) { + break; + } else if (this.match(21)) { + let rest = this.parseRestBinding(); + if (this.hasPlugin("flow") || flags & 2) { + rest = this.parseFunctionParamType(rest); + } + elts.push(rest); + if (!this.checkCommaAfterRest(closeCharCode)) { + this.expect(close); + break; + } + } else { + const decorators = []; + if (flags & 2) { + if (this.match(26) && this.hasPlugin("decorators")) { + this.raise(Errors.UnsupportedParameterDecorator, this.state.startLoc); + } + while (this.match(26)) { + decorators.push(this.parseDecorator()); + } + } + elts.push(this.parseBindingElement(flags, decorators)); + } + } + return elts; + } + parseBindingRestProperty(prop) { + this.next(); + if (this.hasPlugin("discardBinding") && this.match(88)) { + prop.argument = this.parseVoidPattern(null); + this.raise(Errors.UnexpectedVoidPattern, prop.argument); + } else { + prop.argument = this.parseIdentifier(); + } + this.checkCommaAfterRest(125); + return this.finishNode(prop, "RestElement"); + } + parseBindingProperty() { + const { + type, + startLoc + } = this.state; + if (type === 21) { + return this.parseBindingRestProperty(this.startNode()); + } + const prop = this.startNode(); + if (type === 139) { + this.expectPlugin("destructuringPrivate", startLoc); + this.classScope.usePrivateName(this.state.value, startLoc); + prop.key = this.parsePrivateName(); + } else { + this.parsePropertyName(prop); + } + prop.method = false; + return this.parseObjPropValue(prop, startLoc, false, false, true, false); + } + parseBindingElement(flags, decorators) { + const left = this.parseMaybeDefault(); + if (this.hasPlugin("flow") || flags & 2) { + this.parseFunctionParamType(left); + } + if (decorators.length) { + left.decorators = decorators; + this.resetStartLocationFromNode(left, decorators[0]); + } + const elt = this.parseMaybeDefault(left.loc.start, left); + return elt; + } + parseFunctionParamType(param) { + return param; + } + parseMaybeDefault(startLoc, left) { + startLoc != null ? startLoc : startLoc = this.state.startLoc; + left = left != null ? left : this.parseBindingAtom(); + if (!this.eat(29)) return left; + const node = this.startNodeAt(startLoc); + if (left.type === "VoidPattern") { + this.raise(Errors.VoidPatternInitializer, left); + } + node.left = left; + node.right = this.parseMaybeAssignAllowIn(); + return this.finishNode(node, "AssignmentPattern"); + } + isValidLVal(type, disallowCallExpression, isUnparenthesizedInAssign, binding) { + switch (type) { + case "AssignmentPattern": + return "left"; + case "RestElement": + return "argument"; + case "ObjectProperty": + return "value"; + case "ParenthesizedExpression": + return "expression"; + case "ArrayPattern": + return "elements"; + case "ObjectPattern": + return "properties"; + case "VoidPattern": + return true; + case "CallExpression": + if (!disallowCallExpression && !this.state.strict && this.optionFlags & 8192) { + return true; + } + } + return false; + } + isOptionalMemberExpression(expression) { + return expression.type === "OptionalMemberExpression"; + } + checkLVal(expression, ancestor, binding = 64, checkClashes = false, strictModeChanged = false, hasParenthesizedAncestor = false, disallowCallExpression = false) { + var _expression$extra; + const type = expression.type; + if (this.isObjectMethod(expression)) return; + const isOptionalMemberExpression = this.isOptionalMemberExpression(expression); + if (isOptionalMemberExpression || type === "MemberExpression") { + if (isOptionalMemberExpression) { + this.expectPlugin("optionalChainingAssign", expression.loc.start); + if (ancestor.type !== "AssignmentExpression") { + this.raise(Errors.InvalidLhsOptionalChaining, expression, { + ancestor + }); + } + } + if (binding !== 64) { + this.raise(Errors.InvalidPropertyBindingPattern, expression); + } + return; + } + if (type === "Identifier") { + this.checkIdentifier(expression, binding, strictModeChanged); + const { + name + } = expression; + if (checkClashes) { + if (checkClashes.has(name)) { + this.raise(Errors.ParamDupe, expression); + } else { + checkClashes.add(name); + } + } + return; + } else if (type === "VoidPattern" && ancestor.type === "CatchClause") { + this.raise(Errors.VoidPatternCatchClauseParam, expression); + } + const unwrappedExpression = unwrapParenthesizedExpression(expression); + disallowCallExpression || (disallowCallExpression = unwrappedExpression.type === "CallExpression" && (unwrappedExpression.callee.type === "Import" || unwrappedExpression.callee.type === "Super")); + const validity = this.isValidLVal(type, disallowCallExpression, !(hasParenthesizedAncestor || (_expression$extra = expression.extra) != null && _expression$extra.parenthesized) && ancestor.type === "AssignmentExpression", binding); + if (validity === true) return; + if (validity === false) { + const ParseErrorClass = binding === 64 ? Errors.InvalidLhs : Errors.InvalidLhsBinding; + this.raise(ParseErrorClass, expression, { + ancestor + }); + return; + } + let key, isParenthesizedExpression; + if (typeof validity === "string") { + key = validity; + isParenthesizedExpression = type === "ParenthesizedExpression"; + } else { + [key, isParenthesizedExpression] = validity; + } + const nextAncestor = type === "ArrayPattern" || type === "ObjectPattern" ? { + type + } : ancestor; + const val = expression[key]; + if (Array.isArray(val)) { + for (const child of val) { + if (child) { + this.checkLVal(child, nextAncestor, binding, checkClashes, strictModeChanged, isParenthesizedExpression, true); + } + } + } else if (val) { + this.checkLVal(val, nextAncestor, binding, checkClashes, strictModeChanged, isParenthesizedExpression, disallowCallExpression); + } + } + checkIdentifier(at, bindingType, strictModeChanged = false) { + if (this.state.strict && (strictModeChanged ? isStrictBindReservedWord(at.name, this.inModule) : isStrictBindOnlyReservedWord(at.name))) { + if (bindingType === 64) { + this.raise(Errors.StrictEvalArguments, at, { + referenceName: at.name + }); + } else { + this.raise(Errors.StrictEvalArgumentsBinding, at, { + bindingName: at.name + }); + } + } + if (bindingType & 8192 && at.name === "let") { + this.raise(Errors.LetInLexicalBinding, at); + } + if (!(bindingType & 64)) { + this.declareNameFromIdentifier(at, bindingType); + } + } + declareNameFromIdentifier(identifier, binding) { + this.scope.declareName(identifier.name, binding, identifier.loc.start); + } + checkToRestConversion(node, allowPattern) { + switch (node.type) { + case "ParenthesizedExpression": + this.checkToRestConversion(node.expression, allowPattern); + break; + case "Identifier": + case "MemberExpression": + break; + case "ArrayExpression": + case "ObjectExpression": + if (allowPattern) break; + default: + this.raise(Errors.InvalidRestAssignmentPattern, node); + } + } + checkCommaAfterRest(close) { + if (!this.match(12)) { + return false; + } + this.raise(this.lookaheadCharCode() === close ? Errors.RestTrailingComma : Errors.ElementAfterRest, this.state.startLoc); + return true; + } +} +const keywordAndTSRelationalOperator = /in(?:stanceof)?|as|satisfies/y; +function nonNull(x) { + if (x == null) { + throw new Error(`Unexpected ${x} value.`); + } + return x; +} +function assert(x) { + if (!x) { + throw new Error("Assert fail"); + } +} +const TSErrors = ParseErrorEnum`typescript`({ + AbstractMethodHasImplementation: ({ + methodName + }) => `Method '${methodName}' cannot have an implementation because it is marked abstract.`, + AbstractPropertyHasInitializer: ({ + propertyName + }) => `Property '${propertyName}' cannot have an initializer because it is marked abstract.`, + AccessorCannotBeOptional: "An 'accessor' property cannot be declared optional.", + AccessorCannotDeclareThisParameter: "'get' and 'set' accessors cannot declare 'this' parameters.", + AccessorCannotHaveTypeParameters: "An accessor cannot have type parameters.", + ClassMethodHasDeclare: "Class methods cannot have the 'declare' modifier.", + ClassMethodHasReadonly: "Class methods cannot have the 'readonly' modifier.", + ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference: "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference.", + ConstructorHasTypeParameters: "Type parameters cannot appear on a constructor declaration.", + DeclareAccessor: ({ + kind + }) => `'declare' is not allowed in ${kind}ters.`, + DeclareClassFieldHasInitializer: "Initializers are not allowed in ambient contexts.", + DeclareFunctionHasImplementation: "An implementation cannot be declared in ambient contexts.", + DuplicateAccessibilityModifier: ({ + modifier + }) => `Accessibility modifier already seen: '${modifier}'.`, + DuplicateModifier: ({ + modifier + }) => `Duplicate modifier: '${modifier}'.`, + EmptyHeritageClauseType: ({ + token + }) => `'${token}' list cannot be empty.`, + EmptyTypeArguments: "Type argument list cannot be empty.", + EmptyTypeParameters: "Type parameter list cannot be empty.", + ExpectedAmbientAfterExportDeclare: "'export declare' must be followed by an ambient declaration.", + ImportAliasHasImportType: "An import alias can not use 'import type'.", + ImportReflectionHasImportType: "An `import module` declaration can not use `type` modifier", + IncompatibleModifiers: ({ + modifiers + }) => `'${modifiers[0]}' modifier cannot be used with '${modifiers[1]}' modifier.`, + IndexSignatureHasAbstract: "Index signatures cannot have the 'abstract' modifier.", + IndexSignatureHasAccessibility: ({ + modifier + }) => `Index signatures cannot have an accessibility modifier ('${modifier}').`, + IndexSignatureHasDeclare: "Index signatures cannot have the 'declare' modifier.", + IndexSignatureHasOverride: "'override' modifier cannot appear on an index signature.", + IndexSignatureHasStatic: "Index signatures cannot have the 'static' modifier.", + InitializerNotAllowedInAmbientContext: "Initializers are not allowed in ambient contexts.", + InvalidHeritageClauseType: ({ + token + }) => `'${token}' list can only include identifiers or qualified-names with optional type arguments.`, + InvalidModifierOnAwaitUsingDeclaration: modifier => `'${modifier}' modifier cannot appear on an await using declaration.`, + InvalidModifierOnTypeMember: ({ + modifier + }) => `'${modifier}' modifier cannot appear on a type member.`, + InvalidModifierOnTypeParameter: ({ + modifier + }) => `'${modifier}' modifier cannot appear on a type parameter.`, + InvalidModifierOnTypeParameterPositions: ({ + modifier + }) => `'${modifier}' modifier can only appear on a type parameter of a class, interface or type alias.`, + InvalidModifierOnUsingDeclaration: modifier => `'${modifier}' modifier cannot appear on a using declaration.`, + InvalidModifiersOrder: ({ + orderedModifiers + }) => `'${orderedModifiers[0]}' modifier must precede '${orderedModifiers[1]}' modifier.`, + InvalidPropertyAccessAfterInstantiationExpression: "Invalid property access after an instantiation expression. " + "You can either wrap the instantiation expression in parentheses, or delete the type arguments.", + InvalidTupleMemberLabel: "Tuple members must be labeled with a simple identifier.", + MissingInterfaceName: "'interface' declarations must be followed by an identifier.", + NonAbstractClassHasAbstractMethod: "Abstract methods can only appear within an abstract class.", + NonClassMethodPropertyHasAbstractModifier: "'abstract' modifier can only appear on a class, method, or property declaration.", + OptionalTypeBeforeRequired: "A required element cannot follow an optional element.", + OverrideNotInSubClass: "This member cannot have an 'override' modifier because its containing class does not extend another class.", + PatternIsOptional: "A binding pattern parameter cannot be optional in an implementation signature.", + PrivateElementHasAbstract: "Private elements cannot have the 'abstract' modifier.", + PrivateElementHasAccessibility: ({ + modifier + }) => `Private elements cannot have an accessibility modifier ('${modifier}').`, + ReadonlyForMethodSignature: "'readonly' modifier can only appear on a property declaration or index signature.", + ReservedArrowTypeParam: "This syntax is reserved in files with the .mts or .cts extension. Add a trailing comma, as in `() => ...`.", + ReservedTypeAssertion: "This syntax is reserved in files with the .mts or .cts extension. Use an `as` expression instead.", + SetAccessorCannotHaveOptionalParameter: "A 'set' accessor cannot have an optional parameter.", + SetAccessorCannotHaveRestParameter: "A 'set' accessor cannot have rest parameter.", + SetAccessorCannotHaveReturnType: "A 'set' accessor cannot have a return type annotation.", + SingleTypeParameterWithoutTrailingComma: ({ + typeParameterName + }) => `Single type parameter ${typeParameterName} should have a trailing comma. Example usage: <${typeParameterName},>.`, + StaticBlockCannotHaveModifier: "Static class blocks cannot have any modifier.", + TupleOptionalAfterType: "A labeled tuple optional element must be declared using a question mark after the name and before the colon (`name?: type`), rather than after the type (`name: type?`).", + TypeAnnotationAfterAssign: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.", + TypeImportCannotSpecifyDefaultAndNamed: "A type-only import can specify a default import or named bindings, but not both.", + TypeModifierIsUsedInTypeExports: "The 'type' modifier cannot be used on a named export when 'export type' is used on its export statement.", + TypeModifierIsUsedInTypeImports: "The 'type' modifier cannot be used on a named import when 'import type' is used on its import statement.", + UnexpectedParameterModifier: "A parameter property is only allowed in a constructor implementation.", + UnexpectedReadonly: "'readonly' type modifier is only permitted on array and tuple literal types.", + UnexpectedTypeAnnotation: "Did not expect a type annotation here.", + UnexpectedTypeCastInParameter: "Unexpected type cast in parameter position.", + UnsupportedImportTypeArgument: "Argument in a type import must be a string literal.", + UnsupportedParameterPropertyKind: "A parameter property may not be declared using a binding pattern.", + UnsupportedSignatureParameterKind: ({ + type + }) => `Name in a signature must be an Identifier, ObjectPattern or ArrayPattern, instead got ${type}.`, + UsingDeclarationInAmbientContext: kind => `'${kind}' declarations are not allowed in ambient contexts.` +}); +function keywordTypeFromName(value) { + switch (value) { + case "any": + return "TSAnyKeyword"; + case "boolean": + return "TSBooleanKeyword"; + case "bigint": + return "TSBigIntKeyword"; + case "never": + return "TSNeverKeyword"; + case "number": + return "TSNumberKeyword"; + case "object": + return "TSObjectKeyword"; + case "string": + return "TSStringKeyword"; + case "symbol": + return "TSSymbolKeyword"; + case "undefined": + return "TSUndefinedKeyword"; + case "unknown": + return "TSUnknownKeyword"; + default: + return undefined; + } +} +function tsIsAccessModifier(modifier) { + return modifier === "private" || modifier === "public" || modifier === "protected"; +} +function tsIsVarianceAnnotations(modifier) { + return modifier === "in" || modifier === "out"; +} +var typescript = superClass => class TypeScriptParserMixin extends superClass { + constructor(...args) { + super(...args); + this.tsParseInOutModifiers = this.tsParseModifiers.bind(this, { + allowedModifiers: ["in", "out"], + disallowedModifiers: ["const", "public", "private", "protected", "readonly", "declare", "abstract", "override"], + errorTemplate: TSErrors.InvalidModifierOnTypeParameter + }); + this.tsParseConstModifier = this.tsParseModifiers.bind(this, { + allowedModifiers: ["const"], + disallowedModifiers: ["in", "out"], + errorTemplate: TSErrors.InvalidModifierOnTypeParameterPositions + }); + this.tsParseInOutConstModifiers = this.tsParseModifiers.bind(this, { + allowedModifiers: ["in", "out", "const"], + disallowedModifiers: ["public", "private", "protected", "readonly", "declare", "abstract", "override"], + errorTemplate: TSErrors.InvalidModifierOnTypeParameter + }); + } + getScopeHandler() { + return TypeScriptScopeHandler; + } + tsIsIdentifier() { + return tokenIsIdentifier(this.state.type); + } + tsTokenCanFollowModifier() { + return this.match(0) || this.match(5) || this.match(55) || this.match(21) || this.match(139) || this.isLiteralPropertyName(); + } + tsNextTokenOnSameLineAndCanFollowModifier() { + this.next(); + if (this.hasPrecedingLineBreak()) { + return false; + } + return this.tsTokenCanFollowModifier(); + } + tsNextTokenCanFollowModifier() { + if (this.match(106)) { + this.next(); + return this.tsTokenCanFollowModifier(); + } + return this.tsNextTokenOnSameLineAndCanFollowModifier(); + } + tsParseModifier(allowedModifiers, stopOnStartOfClassStaticBlock, hasSeenStaticModifier) { + if (!tokenIsIdentifier(this.state.type) && this.state.type !== 58 && this.state.type !== 75) { + return undefined; + } + const modifier = this.state.value; + if (allowedModifiers.includes(modifier)) { + if (hasSeenStaticModifier && this.match(106)) { + return undefined; + } + if (stopOnStartOfClassStaticBlock && this.tsIsStartOfStaticBlocks()) { + return undefined; + } + if (this.tsTryParse(this.tsNextTokenCanFollowModifier.bind(this))) { + return modifier; + } + } + return undefined; + } + tsParseModifiers({ + allowedModifiers, + disallowedModifiers, + stopOnStartOfClassStaticBlock, + errorTemplate = TSErrors.InvalidModifierOnTypeMember + }, modified) { + const enforceOrder = (loc, modifier, before, after) => { + if (modifier === before && modified[after]) { + this.raise(TSErrors.InvalidModifiersOrder, loc, { + orderedModifiers: [before, after] + }); + } + }; + const incompatible = (loc, modifier, mod1, mod2) => { + if (modified[mod1] && modifier === mod2 || modified[mod2] && modifier === mod1) { + this.raise(TSErrors.IncompatibleModifiers, loc, { + modifiers: [mod1, mod2] + }); + } + }; + for (;;) { + const { + startLoc + } = this.state; + const modifier = this.tsParseModifier(allowedModifiers.concat(disallowedModifiers != null ? disallowedModifiers : []), stopOnStartOfClassStaticBlock, modified.static); + if (!modifier) break; + if (tsIsAccessModifier(modifier)) { + if (modified.accessibility) { + this.raise(TSErrors.DuplicateAccessibilityModifier, startLoc, { + modifier + }); + } else { + enforceOrder(startLoc, modifier, modifier, "override"); + enforceOrder(startLoc, modifier, modifier, "static"); + enforceOrder(startLoc, modifier, modifier, "readonly"); + modified.accessibility = modifier; + } + } else if (tsIsVarianceAnnotations(modifier)) { + if (modified[modifier]) { + this.raise(TSErrors.DuplicateModifier, startLoc, { + modifier + }); + } + modified[modifier] = true; + enforceOrder(startLoc, modifier, "in", "out"); + } else { + if (hasOwnProperty.call(modified, modifier)) { + this.raise(TSErrors.DuplicateModifier, startLoc, { + modifier + }); + } else { + enforceOrder(startLoc, modifier, "static", "readonly"); + enforceOrder(startLoc, modifier, "static", "override"); + enforceOrder(startLoc, modifier, "override", "readonly"); + enforceOrder(startLoc, modifier, "abstract", "override"); + incompatible(startLoc, modifier, "declare", "override"); + incompatible(startLoc, modifier, "static", "abstract"); + } + modified[modifier] = true; + } + if (disallowedModifiers != null && disallowedModifiers.includes(modifier)) { + this.raise(errorTemplate, startLoc, { + modifier + }); + } + } + } + tsIsListTerminator(kind) { + switch (kind) { + case "EnumMembers": + case "TypeMembers": + return this.match(8); + case "HeritageClauseElement": + return this.match(5); + case "TupleElementTypes": + return this.match(3); + case "TypeParametersOrArguments": + return this.match(48); + } + } + tsParseList(kind, parseElement) { + const result = []; + while (!this.tsIsListTerminator(kind)) { + result.push(parseElement()); + } + return result; + } + tsParseDelimitedList(kind, parseElement, refTrailingCommaPos) { + return nonNull(this.tsParseDelimitedListWorker(kind, parseElement, true, refTrailingCommaPos)); + } + tsParseDelimitedListWorker(kind, parseElement, expectSuccess, refTrailingCommaPos) { + const result = []; + let trailingCommaPos = -1; + for (;;) { + if (this.tsIsListTerminator(kind)) { + break; + } + trailingCommaPos = -1; + const element = parseElement(); + if (element == null) { + return undefined; + } + result.push(element); + if (this.eat(12)) { + trailingCommaPos = this.state.lastTokStartLoc.index; + continue; + } + if (this.tsIsListTerminator(kind)) { + break; + } + if (expectSuccess) { + this.expect(12); + } + return undefined; + } + if (refTrailingCommaPos) { + refTrailingCommaPos.value = trailingCommaPos; + } + return result; + } + tsParseBracketedList(kind, parseElement, bracket, skipFirstToken, refTrailingCommaPos) { + if (!skipFirstToken) { + if (bracket) { + this.expect(0); + } else { + this.expect(47); + } + } + const result = this.tsParseDelimitedList(kind, parseElement, refTrailingCommaPos); + if (bracket) { + this.expect(3); + } else { + this.expect(48); + } + return result; + } + tsParseImportType() { + const node = this.startNode(); + this.expect(83); + this.expect(10); + if (!this.match(134)) { + this.raise(TSErrors.UnsupportedImportTypeArgument, this.state.startLoc); + node.argument = super.parseExprAtom(); + } else { + node.argument = this.parseStringLiteral(this.state.value); + } + if (this.eat(12)) { + node.options = this.tsParseImportTypeOptions(); + } else { + node.options = null; + } + this.expect(11); + if (this.eat(16)) { + node.qualifier = this.tsParseEntityName(1 | 2); + } + if (this.match(47)) { + node.typeParameters = this.tsParseTypeArguments(); + } + return this.finishNode(node, "TSImportType"); + } + tsParseImportTypeOptions() { + const node = this.startNode(); + this.expect(5); + const withProperty = this.startNode(); + if (this.isContextual(76)) { + withProperty.method = false; + withProperty.key = this.parseIdentifier(true); + withProperty.computed = false; + withProperty.shorthand = false; + } else { + this.unexpected(null, 76); + } + this.expect(14); + withProperty.value = this.tsParseImportTypeWithPropertyValue(); + node.properties = [this.finishObjectProperty(withProperty)]; + this.eat(12); + this.expect(8); + return this.finishNode(node, "ObjectExpression"); + } + tsParseImportTypeWithPropertyValue() { + const node = this.startNode(); + const properties = []; + this.expect(5); + while (!this.match(8)) { + const type = this.state.type; + if (tokenIsIdentifier(type) || type === 134) { + properties.push(super.parsePropertyDefinition(null)); + } else { + this.unexpected(); + } + this.eat(12); + } + node.properties = properties; + this.next(); + return this.finishNode(node, "ObjectExpression"); + } + tsParseEntityName(flags) { + let entity; + if (flags & 1 && this.match(78)) { + if (flags & 2) { + entity = this.parseIdentifier(true); + } else { + const node = this.startNode(); + this.next(); + entity = this.finishNode(node, "ThisExpression"); + } + } else { + entity = this.parseIdentifier(!!(flags & 1)); + } + while (this.eat(16)) { + const node = this.startNodeAtNode(entity); + node.left = entity; + node.right = this.parseIdentifier(!!(flags & 1)); + entity = this.finishNode(node, "TSQualifiedName"); + } + return entity; + } + tsParseTypeReference() { + const node = this.startNode(); + node.typeName = this.tsParseEntityName(1); + if (!this.hasPrecedingLineBreak() && this.match(47)) { + node.typeParameters = this.tsParseTypeArguments(); + } + return this.finishNode(node, "TSTypeReference"); + } + tsParseThisTypePredicate(lhs) { + this.next(); + const node = this.startNodeAtNode(lhs); + node.parameterName = lhs; + node.typeAnnotation = this.tsParseTypeAnnotation(false); + node.asserts = false; + return this.finishNode(node, "TSTypePredicate"); + } + tsParseThisTypeNode() { + const node = this.startNode(); + this.next(); + return this.finishNode(node, "TSThisType"); + } + tsParseTypeQuery() { + const node = this.startNode(); + this.expect(87); + if (this.match(83)) { + node.exprName = this.tsParseImportType(); + } else { + node.exprName = this.tsParseEntityName(1 | 2); + } + if (!this.hasPrecedingLineBreak() && this.match(47)) { + node.typeParameters = this.tsParseTypeArguments(); + } + return this.finishNode(node, "TSTypeQuery"); + } + tsParseTypeParameter(parseModifiers) { + const node = this.startNode(); + parseModifiers(node); + node.name = this.tsParseTypeParameterName(); + node.constraint = this.tsEatThenParseType(81); + node.default = this.tsEatThenParseType(29); + return this.finishNode(node, "TSTypeParameter"); + } + tsTryParseTypeParameters(parseModifiers) { + if (this.match(47)) { + return this.tsParseTypeParameters(parseModifiers); + } + } + tsParseTypeParameters(parseModifiers) { + const node = this.startNode(); + if (this.match(47) || this.match(143)) { + this.next(); + } else { + this.unexpected(); + } + const refTrailingCommaPos = { + value: -1 + }; + node.params = this.tsParseBracketedList("TypeParametersOrArguments", this.tsParseTypeParameter.bind(this, parseModifiers), false, true, refTrailingCommaPos); + if (node.params.length === 0) { + this.raise(TSErrors.EmptyTypeParameters, node); + } + if (refTrailingCommaPos.value !== -1) { + this.addExtra(node, "trailingComma", refTrailingCommaPos.value); + } + return this.finishNode(node, "TSTypeParameterDeclaration"); + } + tsFillSignature(returnToken, signature) { + const returnTokenRequired = returnToken === 19; + const paramsKey = "parameters"; + const returnTypeKey = "typeAnnotation"; + signature.typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier); + this.expect(10); + signature[paramsKey] = this.tsParseBindingListForSignature(); + if (returnTokenRequired) { + signature[returnTypeKey] = this.tsParseTypeOrTypePredicateAnnotation(returnToken); + } else if (this.match(returnToken)) { + signature[returnTypeKey] = this.tsParseTypeOrTypePredicateAnnotation(returnToken); + } + } + tsParseBindingListForSignature() { + const list = super.parseBindingList(11, 41, 2); + for (const pattern of list) { + const { + type + } = pattern; + if (type === "AssignmentPattern" || type === "TSParameterProperty") { + this.raise(TSErrors.UnsupportedSignatureParameterKind, pattern, { + type + }); + } + } + return list; + } + tsParseTypeMemberSemicolon() { + if (!this.eat(12) && !this.isLineTerminator()) { + this.expect(13); + } + } + tsParseSignatureMember(kind, node) { + this.tsFillSignature(14, node); + this.tsParseTypeMemberSemicolon(); + return this.finishNode(node, kind); + } + tsIsUnambiguouslyIndexSignature() { + this.next(); + if (tokenIsIdentifier(this.state.type)) { + this.next(); + return this.match(14); + } + return false; + } + tsTryParseIndexSignature(node) { + if (!(this.match(0) && this.tsLookAhead(this.tsIsUnambiguouslyIndexSignature.bind(this)))) { + return; + } + this.expect(0); + const id = this.parseIdentifier(); + id.typeAnnotation = this.tsParseTypeAnnotation(); + this.resetEndLocation(id); + this.expect(3); + node.parameters = [id]; + const type = this.tsTryParseTypeAnnotation(); + if (type) node.typeAnnotation = type; + this.tsParseTypeMemberSemicolon(); + return this.finishNode(node, "TSIndexSignature"); + } + tsParsePropertyOrMethodSignature(node, readonly) { + if (this.eat(17)) node.optional = true; + if (this.match(10) || this.match(47)) { + if (readonly) { + this.raise(TSErrors.ReadonlyForMethodSignature, node); + } + const method = node; + if (method.kind && this.match(47)) { + this.raise(TSErrors.AccessorCannotHaveTypeParameters, this.state.curPosition()); + } + this.tsFillSignature(14, method); + this.tsParseTypeMemberSemicolon(); + const paramsKey = "parameters"; + const returnTypeKey = "typeAnnotation"; + if (method.kind === "get") { + if (method[paramsKey].length > 0) { + this.raise(Errors.BadGetterArity, this.state.curPosition()); + if (this.isThisParam(method[paramsKey][0])) { + this.raise(TSErrors.AccessorCannotDeclareThisParameter, this.state.curPosition()); + } + } + } else if (method.kind === "set") { + if (method[paramsKey].length !== 1) { + this.raise(Errors.BadSetterArity, this.state.curPosition()); + } else { + const firstParameter = method[paramsKey][0]; + if (this.isThisParam(firstParameter)) { + this.raise(TSErrors.AccessorCannotDeclareThisParameter, this.state.curPosition()); + } + if (firstParameter.type === "Identifier" && firstParameter.optional) { + this.raise(TSErrors.SetAccessorCannotHaveOptionalParameter, this.state.curPosition()); + } + if (firstParameter.type === "RestElement") { + this.raise(TSErrors.SetAccessorCannotHaveRestParameter, this.state.curPosition()); + } + } + if (method[returnTypeKey]) { + this.raise(TSErrors.SetAccessorCannotHaveReturnType, method[returnTypeKey]); + } + } else { + method.kind = "method"; + } + return this.finishNode(method, "TSMethodSignature"); + } else { + const property = node; + if (readonly) property.readonly = true; + const type = this.tsTryParseTypeAnnotation(); + if (type) property.typeAnnotation = type; + this.tsParseTypeMemberSemicolon(); + return this.finishNode(property, "TSPropertySignature"); + } + } + tsParseTypeMember() { + const node = this.startNode(); + if (this.match(10) || this.match(47)) { + return this.tsParseSignatureMember("TSCallSignatureDeclaration", node); + } + if (this.match(77)) { + const id = this.startNode(); + this.next(); + if (this.match(10) || this.match(47)) { + return this.tsParseSignatureMember("TSConstructSignatureDeclaration", node); + } else { + node.key = this.createIdentifier(id, "new"); + return this.tsParsePropertyOrMethodSignature(node, false); + } + } + this.tsParseModifiers({ + allowedModifiers: ["readonly"], + disallowedModifiers: ["declare", "abstract", "private", "protected", "public", "static", "override"] + }, node); + const idx = this.tsTryParseIndexSignature(node); + if (idx) { + return idx; + } + super.parsePropertyName(node); + if (!node.computed && node.key.type === "Identifier" && (node.key.name === "get" || node.key.name === "set") && this.tsTokenCanFollowModifier()) { + node.kind = node.key.name; + super.parsePropertyName(node); + if (!this.match(10) && !this.match(47)) { + this.unexpected(null, 10); + } + } + return this.tsParsePropertyOrMethodSignature(node, !!node.readonly); + } + tsParseTypeLiteral() { + const node = this.startNode(); + node.members = this.tsParseObjectTypeMembers(); + return this.finishNode(node, "TSTypeLiteral"); + } + tsParseObjectTypeMembers() { + this.expect(5); + const members = this.tsParseList("TypeMembers", this.tsParseTypeMember.bind(this)); + this.expect(8); + return members; + } + tsIsStartOfMappedType() { + this.next(); + if (this.eat(53)) { + return this.isContextual(122); + } + if (this.isContextual(122)) { + this.next(); + } + if (!this.match(0)) { + return false; + } + this.next(); + if (!this.tsIsIdentifier()) { + return false; + } + this.next(); + return this.match(58); + } + tsParseMappedType() { + const node = this.startNode(); + this.expect(5); + if (this.match(53)) { + node.readonly = this.state.value; + this.next(); + this.expectContextual(122); + } else if (this.eatContextual(122)) { + node.readonly = true; + } + this.expect(0); + const typeParameter = this.startNode(); + typeParameter.name = this.tsParseTypeParameterName(); + typeParameter.constraint = this.tsExpectThenParseType(58); + node.typeParameter = this.finishNode(typeParameter, "TSTypeParameter"); + node.nameType = this.eatContextual(93) ? this.tsParseType() : null; + this.expect(3); + if (this.match(53)) { + node.optional = this.state.value; + this.next(); + this.expect(17); + } else if (this.eat(17)) { + node.optional = true; + } + node.typeAnnotation = this.tsTryParseType(); + this.semicolon(); + this.expect(8); + return this.finishNode(node, "TSMappedType"); + } + tsParseTupleType() { + const node = this.startNode(); + node.elementTypes = this.tsParseBracketedList("TupleElementTypes", this.tsParseTupleElementType.bind(this), true, false); + let seenOptionalElement = false; + node.elementTypes.forEach(elementNode => { + const { + type + } = elementNode; + if (seenOptionalElement && type !== "TSRestType" && type !== "TSOptionalType" && !(type === "TSNamedTupleMember" && elementNode.optional)) { + this.raise(TSErrors.OptionalTypeBeforeRequired, elementNode); + } + seenOptionalElement || (seenOptionalElement = type === "TSNamedTupleMember" && elementNode.optional || type === "TSOptionalType"); + }); + return this.finishNode(node, "TSTupleType"); + } + tsParseTupleElementType() { + const restStartLoc = this.state.startLoc; + const rest = this.eat(21); + const { + startLoc + } = this.state; + let labeled; + let label; + let optional; + let type; + const isWord = tokenIsKeywordOrIdentifier(this.state.type); + const chAfterWord = isWord ? this.lookaheadCharCode() : null; + if (chAfterWord === 58) { + labeled = true; + optional = false; + label = this.parseIdentifier(true); + this.expect(14); + type = this.tsParseType(); + } else if (chAfterWord === 63) { + optional = true; + const wordName = this.state.value; + const typeOrLabel = this.tsParseNonArrayType(); + if (this.lookaheadCharCode() === 58) { + labeled = true; + label = this.createIdentifier(this.startNodeAt(startLoc), wordName); + this.expect(17); + this.expect(14); + type = this.tsParseType(); + } else { + labeled = false; + type = typeOrLabel; + this.expect(17); + } + } else { + type = this.tsParseType(); + optional = this.eat(17); + labeled = this.eat(14); + } + if (labeled) { + let labeledNode; + if (label) { + labeledNode = this.startNodeAt(startLoc); + labeledNode.optional = optional; + labeledNode.label = label; + labeledNode.elementType = type; + if (this.eat(17)) { + labeledNode.optional = true; + this.raise(TSErrors.TupleOptionalAfterType, this.state.lastTokStartLoc); + } + } else { + labeledNode = this.startNodeAt(startLoc); + labeledNode.optional = optional; + this.raise(TSErrors.InvalidTupleMemberLabel, type); + labeledNode.label = type; + labeledNode.elementType = this.tsParseType(); + } + type = this.finishNode(labeledNode, "TSNamedTupleMember"); + } else if (optional) { + const optionalTypeNode = this.startNodeAt(startLoc); + optionalTypeNode.typeAnnotation = type; + type = this.finishNode(optionalTypeNode, "TSOptionalType"); + } + if (rest) { + const restNode = this.startNodeAt(restStartLoc); + restNode.typeAnnotation = type; + type = this.finishNode(restNode, "TSRestType"); + } + return type; + } + tsParseParenthesizedType() { + const node = this.startNode(); + this.expect(10); + node.typeAnnotation = this.tsParseType(); + this.expect(11); + return this.finishNode(node, "TSParenthesizedType"); + } + tsParseFunctionOrConstructorType(type, abstract) { + const node = this.startNode(); + if (type === "TSConstructorType") { + node.abstract = !!abstract; + if (abstract) this.next(); + this.next(); + } + this.tsInAllowConditionalTypesContext(() => this.tsFillSignature(19, node)); + return this.finishNode(node, type); + } + tsParseLiteralTypeNode() { + const node = this.startNode(); + switch (this.state.type) { + case 135: + case 136: + case 134: + case 85: + case 86: + node.literal = super.parseExprAtom(); + break; + default: + this.unexpected(); + } + return this.finishNode(node, "TSLiteralType"); + } + tsParseTemplateLiteralType() { + const node = this.startNode(); + node.literal = super.parseTemplate(false); + return this.finishNode(node, "TSLiteralType"); + } + parseTemplateSubstitution() { + if (this.state.inType) return this.tsParseType(); + return super.parseTemplateSubstitution(); + } + tsParseThisTypeOrThisTypePredicate() { + const thisKeyword = this.tsParseThisTypeNode(); + if (this.isContextual(116) && !this.hasPrecedingLineBreak()) { + return this.tsParseThisTypePredicate(thisKeyword); + } else { + return thisKeyword; + } + } + tsParseNonArrayType() { + switch (this.state.type) { + case 134: + case 135: + case 136: + case 85: + case 86: + return this.tsParseLiteralTypeNode(); + case 53: + if (this.state.value === "-") { + const node = this.startNode(); + const nextToken = this.lookahead(); + if (nextToken.type !== 135 && nextToken.type !== 136) { + this.unexpected(); + } + node.literal = this.parseMaybeUnary(); + return this.finishNode(node, "TSLiteralType"); + } + break; + case 78: + return this.tsParseThisTypeOrThisTypePredicate(); + case 87: + return this.tsParseTypeQuery(); + case 83: + return this.tsParseImportType(); + case 5: + return this.tsLookAhead(this.tsIsStartOfMappedType.bind(this)) ? this.tsParseMappedType() : this.tsParseTypeLiteral(); + case 0: + return this.tsParseTupleType(); + case 10: + return this.tsParseParenthesizedType(); + case 25: + case 24: + return this.tsParseTemplateLiteralType(); + default: + { + const { + type + } = this.state; + if (tokenIsIdentifier(type) || type === 88 || type === 84) { + const nodeType = type === 88 ? "TSVoidKeyword" : type === 84 ? "TSNullKeyword" : keywordTypeFromName(this.state.value); + if (nodeType !== undefined && this.lookaheadCharCode() !== 46) { + const node = this.startNode(); + this.next(); + return this.finishNode(node, nodeType); + } + return this.tsParseTypeReference(); + } + } + } + throw this.unexpected(); + } + tsParseArrayTypeOrHigher() { + const { + startLoc + } = this.state; + let type = this.tsParseNonArrayType(); + while (!this.hasPrecedingLineBreak() && this.eat(0)) { + if (this.match(3)) { + const node = this.startNodeAt(startLoc); + node.elementType = type; + this.expect(3); + type = this.finishNode(node, "TSArrayType"); + } else { + const node = this.startNodeAt(startLoc); + node.objectType = type; + node.indexType = this.tsParseType(); + this.expect(3); + type = this.finishNode(node, "TSIndexedAccessType"); + } + } + return type; + } + tsParseTypeOperator() { + const node = this.startNode(); + const operator = this.state.value; + this.next(); + node.operator = operator; + node.typeAnnotation = this.tsParseTypeOperatorOrHigher(); + if (operator === "readonly") { + this.tsCheckTypeAnnotationForReadOnly(node); + } + return this.finishNode(node, "TSTypeOperator"); + } + tsCheckTypeAnnotationForReadOnly(node) { + switch (node.typeAnnotation.type) { + case "TSTupleType": + case "TSArrayType": + return; + default: + this.raise(TSErrors.UnexpectedReadonly, node); + } + } + tsParseInferType() { + const node = this.startNode(); + this.expectContextual(115); + const typeParameter = this.startNode(); + typeParameter.name = this.tsParseTypeParameterName(); + typeParameter.constraint = this.tsTryParse(() => this.tsParseConstraintForInferType()); + node.typeParameter = this.finishNode(typeParameter, "TSTypeParameter"); + return this.finishNode(node, "TSInferType"); + } + tsParseConstraintForInferType() { + if (this.eat(81)) { + const constraint = this.tsInDisallowConditionalTypesContext(() => this.tsParseType()); + if (this.state.inDisallowConditionalTypesContext || !this.match(17)) { + return constraint; + } + } + } + tsParseTypeOperatorOrHigher() { + const isTypeOperator = tokenIsTSTypeOperator(this.state.type) && !this.state.containsEsc; + return isTypeOperator ? this.tsParseTypeOperator() : this.isContextual(115) ? this.tsParseInferType() : this.tsInAllowConditionalTypesContext(() => this.tsParseArrayTypeOrHigher()); + } + tsParseUnionOrIntersectionType(kind, parseConstituentType, operator) { + const node = this.startNode(); + const hasLeadingOperator = this.eat(operator); + const types = []; + do { + types.push(parseConstituentType()); + } while (this.eat(operator)); + if (types.length === 1 && !hasLeadingOperator) { + return types[0]; + } + node.types = types; + return this.finishNode(node, kind); + } + tsParseIntersectionTypeOrHigher() { + return this.tsParseUnionOrIntersectionType("TSIntersectionType", this.tsParseTypeOperatorOrHigher.bind(this), 45); + } + tsParseUnionTypeOrHigher() { + return this.tsParseUnionOrIntersectionType("TSUnionType", this.tsParseIntersectionTypeOrHigher.bind(this), 43); + } + tsIsStartOfFunctionType() { + if (this.match(47)) { + return true; + } + return this.match(10) && this.tsLookAhead(this.tsIsUnambiguouslyStartOfFunctionType.bind(this)); + } + tsSkipParameterStart() { + if (tokenIsIdentifier(this.state.type) || this.match(78)) { + this.next(); + return true; + } + if (this.match(5)) { + const { + errors + } = this.state; + const previousErrorCount = errors.length; + try { + this.parseObjectLike(8, true); + return errors.length === previousErrorCount; + } catch (_unused) { + return false; + } + } + if (this.match(0)) { + this.next(); + const { + errors + } = this.state; + const previousErrorCount = errors.length; + try { + super.parseBindingList(3, 93, 1); + return errors.length === previousErrorCount; + } catch (_unused2) { + return false; + } + } + return false; + } + tsIsUnambiguouslyStartOfFunctionType() { + this.next(); + if (this.match(11) || this.match(21)) { + return true; + } + if (this.tsSkipParameterStart()) { + if (this.match(14) || this.match(12) || this.match(17) || this.match(29)) { + return true; + } + if (this.match(11)) { + this.next(); + if (this.match(19)) { + return true; + } + } + } + return false; + } + tsParseTypeOrTypePredicateAnnotation(returnToken) { + return this.tsInType(() => { + const t = this.startNode(); + this.expect(returnToken); + const node = this.startNode(); + const asserts = !!this.tsTryParse(this.tsParseTypePredicateAsserts.bind(this)); + if (asserts && this.match(78)) { + let thisTypePredicate = this.tsParseThisTypeOrThisTypePredicate(); + if (thisTypePredicate.type === "TSThisType") { + node.parameterName = thisTypePredicate; + node.asserts = true; + node.typeAnnotation = null; + thisTypePredicate = this.finishNode(node, "TSTypePredicate"); + } else { + this.resetStartLocationFromNode(thisTypePredicate, node); + thisTypePredicate.asserts = true; + } + t.typeAnnotation = thisTypePredicate; + return this.finishNode(t, "TSTypeAnnotation"); + } + const typePredicateVariable = this.tsIsIdentifier() && this.tsTryParse(this.tsParseTypePredicatePrefix.bind(this)); + if (!typePredicateVariable) { + if (!asserts) { + return this.tsParseTypeAnnotation(false, t); + } + node.parameterName = this.parseIdentifier(); + node.asserts = asserts; + node.typeAnnotation = null; + t.typeAnnotation = this.finishNode(node, "TSTypePredicate"); + return this.finishNode(t, "TSTypeAnnotation"); + } + const type = this.tsParseTypeAnnotation(false); + node.parameterName = typePredicateVariable; + node.typeAnnotation = type; + node.asserts = asserts; + t.typeAnnotation = this.finishNode(node, "TSTypePredicate"); + return this.finishNode(t, "TSTypeAnnotation"); + }); + } + tsTryParseTypeOrTypePredicateAnnotation() { + if (this.match(14)) { + return this.tsParseTypeOrTypePredicateAnnotation(14); + } + } + tsTryParseTypeAnnotation() { + if (this.match(14)) { + return this.tsParseTypeAnnotation(); + } + } + tsTryParseType() { + return this.tsEatThenParseType(14); + } + tsParseTypePredicatePrefix() { + const id = this.parseIdentifier(); + if (this.isContextual(116) && !this.hasPrecedingLineBreak()) { + this.next(); + return id; + } + } + tsParseTypePredicateAsserts() { + if (this.state.type !== 109) { + return false; + } + const containsEsc = this.state.containsEsc; + this.next(); + if (!tokenIsIdentifier(this.state.type) && !this.match(78)) { + return false; + } + if (containsEsc) { + this.raise(Errors.InvalidEscapedReservedWord, this.state.lastTokStartLoc, { + reservedWord: "asserts" + }); + } + return true; + } + tsParseTypeAnnotation(eatColon = true, t = this.startNode()) { + this.tsInType(() => { + if (eatColon) this.expect(14); + t.typeAnnotation = this.tsParseType(); + }); + return this.finishNode(t, "TSTypeAnnotation"); + } + tsParseType() { + assert(this.state.inType); + const type = this.tsParseNonConditionalType(); + if (this.state.inDisallowConditionalTypesContext || this.hasPrecedingLineBreak() || !this.eat(81)) { + return type; + } + const node = this.startNodeAtNode(type); + node.checkType = type; + node.extendsType = this.tsInDisallowConditionalTypesContext(() => this.tsParseNonConditionalType()); + this.expect(17); + node.trueType = this.tsInAllowConditionalTypesContext(() => this.tsParseType()); + this.expect(14); + node.falseType = this.tsInAllowConditionalTypesContext(() => this.tsParseType()); + return this.finishNode(node, "TSConditionalType"); + } + isAbstractConstructorSignature() { + return this.isContextual(124) && this.isLookaheadContextual("new"); + } + tsParseNonConditionalType() { + if (this.tsIsStartOfFunctionType()) { + return this.tsParseFunctionOrConstructorType("TSFunctionType"); + } + if (this.match(77)) { + return this.tsParseFunctionOrConstructorType("TSConstructorType"); + } else if (this.isAbstractConstructorSignature()) { + return this.tsParseFunctionOrConstructorType("TSConstructorType", true); + } + return this.tsParseUnionTypeOrHigher(); + } + tsParseTypeAssertion() { + if (this.getPluginOption("typescript", "disallowAmbiguousJSXLike")) { + this.raise(TSErrors.ReservedTypeAssertion, this.state.startLoc); + } + const node = this.startNode(); + node.typeAnnotation = this.tsInType(() => { + this.next(); + return this.match(75) ? this.tsParseTypeReference() : this.tsParseType(); + }); + this.expect(48); + node.expression = this.parseMaybeUnary(); + return this.finishNode(node, "TSTypeAssertion"); + } + tsParseHeritageClause(token) { + const originalStartLoc = this.state.startLoc; + const delimitedList = this.tsParseDelimitedList("HeritageClauseElement", () => { + const node = this.startNode(); + node.expression = this.tsParseEntityName(1 | 2); + if (this.match(47)) { + node.typeParameters = this.tsParseTypeArguments(); + } + return this.finishNode(node, "TSExpressionWithTypeArguments"); + }); + if (!delimitedList.length) { + this.raise(TSErrors.EmptyHeritageClauseType, originalStartLoc, { + token + }); + } + return delimitedList; + } + tsParseInterfaceDeclaration(node, properties = {}) { + if (this.hasFollowingLineBreak()) return null; + this.expectContextual(129); + if (properties.declare) node.declare = true; + if (tokenIsIdentifier(this.state.type)) { + node.id = this.parseIdentifier(); + this.checkIdentifier(node.id, 130); + } else { + node.id = null; + this.raise(TSErrors.MissingInterfaceName, this.state.startLoc); + } + node.typeParameters = this.tsTryParseTypeParameters(this.tsParseInOutConstModifiers); + if (this.eat(81)) { + node.extends = this.tsParseHeritageClause("extends"); + } + const body = this.startNode(); + body.body = this.tsInType(this.tsParseObjectTypeMembers.bind(this)); + node.body = this.finishNode(body, "TSInterfaceBody"); + return this.finishNode(node, "TSInterfaceDeclaration"); + } + tsParseTypeAliasDeclaration(node) { + node.id = this.parseIdentifier(); + this.checkIdentifier(node.id, 2); + node.typeAnnotation = this.tsInType(() => { + node.typeParameters = this.tsTryParseTypeParameters(this.tsParseInOutModifiers); + this.expect(29); + if (this.isContextual(114) && this.lookaheadCharCode() !== 46) { + const node = this.startNode(); + this.next(); + return this.finishNode(node, "TSIntrinsicKeyword"); + } + return this.tsParseType(); + }); + this.semicolon(); + return this.finishNode(node, "TSTypeAliasDeclaration"); + } + tsInTopLevelContext(cb) { + if (this.curContext() !== types.brace) { + const oldContext = this.state.context; + this.state.context = [oldContext[0]]; + try { + return cb(); + } finally { + this.state.context = oldContext; + } + } else { + return cb(); + } + } + tsInType(cb) { + const oldInType = this.state.inType; + this.state.inType = true; + try { + return cb(); + } finally { + this.state.inType = oldInType; + } + } + tsInDisallowConditionalTypesContext(cb) { + const oldInDisallowConditionalTypesContext = this.state.inDisallowConditionalTypesContext; + this.state.inDisallowConditionalTypesContext = true; + try { + return cb(); + } finally { + this.state.inDisallowConditionalTypesContext = oldInDisallowConditionalTypesContext; + } + } + tsInAllowConditionalTypesContext(cb) { + const oldInDisallowConditionalTypesContext = this.state.inDisallowConditionalTypesContext; + this.state.inDisallowConditionalTypesContext = false; + try { + return cb(); + } finally { + this.state.inDisallowConditionalTypesContext = oldInDisallowConditionalTypesContext; + } + } + tsEatThenParseType(token) { + if (this.match(token)) { + return this.tsNextThenParseType(); + } + } + tsExpectThenParseType(token) { + return this.tsInType(() => { + this.expect(token); + return this.tsParseType(); + }); + } + tsNextThenParseType() { + return this.tsInType(() => { + this.next(); + return this.tsParseType(); + }); + } + tsParseEnumMember() { + const node = this.startNode(); + node.id = this.match(134) ? super.parseStringLiteral(this.state.value) : this.parseIdentifier(true); + if (this.eat(29)) { + node.initializer = super.parseMaybeAssignAllowIn(); + } + return this.finishNode(node, "TSEnumMember"); + } + tsParseEnumDeclaration(node, properties = {}) { + if (properties.const) node.const = true; + if (properties.declare) node.declare = true; + this.expectContextual(126); + node.id = this.parseIdentifier(); + this.checkIdentifier(node.id, node.const ? 8971 : 8459); + this.expect(5); + node.members = this.tsParseDelimitedList("EnumMembers", this.tsParseEnumMember.bind(this)); + this.expect(8); + return this.finishNode(node, "TSEnumDeclaration"); + } + tsParseEnumBody() { + const node = this.startNode(); + this.expect(5); + node.members = this.tsParseDelimitedList("EnumMembers", this.tsParseEnumMember.bind(this)); + this.expect(8); + return this.finishNode(node, "TSEnumBody"); + } + tsParseModuleBlock() { + const node = this.startNode(); + this.scope.enter(0); + this.expect(5); + super.parseBlockOrModuleBlockBody(node.body = [], undefined, true, 8); + this.scope.exit(); + return this.finishNode(node, "TSModuleBlock"); + } + tsParseModuleOrNamespaceDeclaration(node, nested = false) { + node.id = this.parseIdentifier(); + if (!nested) { + this.checkIdentifier(node.id, 1024); + } + if (this.eat(16)) { + const inner = this.startNode(); + this.tsParseModuleOrNamespaceDeclaration(inner, true); + node.body = inner; + } else { + this.scope.enter(1024); + this.prodParam.enter(0); + node.body = this.tsParseModuleBlock(); + this.prodParam.exit(); + this.scope.exit(); + } + return this.finishNode(node, "TSModuleDeclaration"); + } + tsParseAmbientExternalModuleDeclaration(node) { + if (this.isContextual(112)) { + node.kind = "global"; + node.global = true; + node.id = this.parseIdentifier(); + } else if (this.match(134)) { + node.kind = "module"; + node.id = super.parseStringLiteral(this.state.value); + } else { + this.unexpected(); + } + if (this.match(5)) { + this.scope.enter(1024); + this.prodParam.enter(0); + node.body = this.tsParseModuleBlock(); + this.prodParam.exit(); + this.scope.exit(); + } else { + this.semicolon(); + } + return this.finishNode(node, "TSModuleDeclaration"); + } + tsParseImportEqualsDeclaration(node, maybeDefaultIdentifier, isExport) { + node.isExport = isExport || false; + node.id = maybeDefaultIdentifier || this.parseIdentifier(); + this.checkIdentifier(node.id, 4096); + this.expect(29); + const moduleReference = this.tsParseModuleReference(); + if (node.importKind === "type" && moduleReference.type !== "TSExternalModuleReference") { + this.raise(TSErrors.ImportAliasHasImportType, moduleReference); + } + node.moduleReference = moduleReference; + this.semicolon(); + return this.finishNode(node, "TSImportEqualsDeclaration"); + } + tsIsExternalModuleReference() { + return this.isContextual(119) && this.lookaheadCharCode() === 40; + } + tsParseModuleReference() { + return this.tsIsExternalModuleReference() ? this.tsParseExternalModuleReference() : this.tsParseEntityName(0); + } + tsParseExternalModuleReference() { + const node = this.startNode(); + this.expectContextual(119); + this.expect(10); + if (!this.match(134)) { + this.unexpected(); + } + node.expression = super.parseExprAtom(); + this.expect(11); + this.sawUnambiguousESM = true; + return this.finishNode(node, "TSExternalModuleReference"); + } + tsLookAhead(f) { + const state = this.state.clone(); + const res = f(); + this.state = state; + return res; + } + tsTryParseAndCatch(f) { + const result = this.tryParse(abort => f() || abort()); + if (result.aborted || !result.node) return; + if (result.error) this.state = result.failState; + return result.node; + } + tsTryParse(f) { + const state = this.state.clone(); + const result = f(); + if (result !== undefined && result !== false) { + return result; + } + this.state = state; + } + tsTryParseDeclare(node) { + if (this.isLineTerminator()) { + return; + } + const startType = this.state.type; + return this.tsInAmbientContext(() => { + switch (startType) { + case 68: + node.declare = true; + return super.parseFunctionStatement(node, false, false); + case 80: + node.declare = true; + return this.parseClass(node, true, false); + case 126: + return this.tsParseEnumDeclaration(node, { + declare: true + }); + case 112: + return this.tsParseAmbientExternalModuleDeclaration(node); + case 100: + if (this.state.containsEsc) { + return; + } + case 75: + case 74: + if (!this.match(75) || !this.isLookaheadContextual("enum")) { + node.declare = true; + return this.parseVarStatement(node, this.state.value, true); + } + this.expect(75); + return this.tsParseEnumDeclaration(node, { + const: true, + declare: true + }); + case 107: + if (this.isUsing()) { + this.raise(TSErrors.InvalidModifierOnUsingDeclaration, this.state.startLoc, "declare"); + node.declare = true; + return this.parseVarStatement(node, "using", true); + } + break; + case 96: + if (this.isAwaitUsing()) { + this.raise(TSErrors.InvalidModifierOnAwaitUsingDeclaration, this.state.startLoc, "declare"); + node.declare = true; + this.next(); + return this.parseVarStatement(node, "await using", true); + } + break; + case 129: + { + const result = this.tsParseInterfaceDeclaration(node, { + declare: true + }); + if (result) return result; + } + default: + if (tokenIsIdentifier(startType)) { + return this.tsParseDeclaration(node, this.state.type, true, null); + } + } + }); + } + tsTryParseExportDeclaration() { + return this.tsParseDeclaration(this.startNode(), this.state.type, true, null); + } + tsParseDeclaration(node, type, next, decorators) { + switch (type) { + case 124: + if (this.tsCheckLineTerminator(next) && (this.match(80) || tokenIsIdentifier(this.state.type))) { + return this.tsParseAbstractDeclaration(node, decorators); + } + break; + case 127: + if (this.tsCheckLineTerminator(next)) { + if (this.match(134)) { + return this.tsParseAmbientExternalModuleDeclaration(node); + } else if (tokenIsIdentifier(this.state.type)) { + node.kind = "module"; + return this.tsParseModuleOrNamespaceDeclaration(node); + } + } + break; + case 128: + if (this.tsCheckLineTerminator(next) && tokenIsIdentifier(this.state.type)) { + node.kind = "namespace"; + return this.tsParseModuleOrNamespaceDeclaration(node); + } + break; + case 130: + if (this.tsCheckLineTerminator(next) && tokenIsIdentifier(this.state.type)) { + return this.tsParseTypeAliasDeclaration(node); + } + break; + } + } + tsCheckLineTerminator(next) { + if (next) { + if (this.hasFollowingLineBreak()) return false; + this.next(); + return true; + } + return !this.isLineTerminator(); + } + tsTryParseGenericAsyncArrowFunction(startLoc) { + if (!this.match(47)) return; + const oldMaybeInArrowParameters = this.state.maybeInArrowParameters; + this.state.maybeInArrowParameters = true; + const res = this.tsTryParseAndCatch(() => { + const node = this.startNodeAt(startLoc); + node.typeParameters = this.tsParseTypeParameters(this.tsParseConstModifier); + super.parseFunctionParams(node); + node.returnType = this.tsTryParseTypeOrTypePredicateAnnotation(); + this.expect(19); + return node; + }); + this.state.maybeInArrowParameters = oldMaybeInArrowParameters; + if (!res) return; + return super.parseArrowExpression(res, null, true); + } + tsParseTypeArgumentsInExpression() { + if (this.reScan_lt() !== 47) return; + return this.tsParseTypeArguments(); + } + tsParseTypeArguments() { + const node = this.startNode(); + node.params = this.tsInType(() => this.tsInTopLevelContext(() => { + this.expect(47); + return this.tsParseDelimitedList("TypeParametersOrArguments", this.tsParseType.bind(this)); + })); + if (node.params.length === 0) { + this.raise(TSErrors.EmptyTypeArguments, node); + } else if (!this.state.inType && this.curContext() === types.brace) { + this.reScan_lt_gt(); + } + this.expect(48); + return this.finishNode(node, "TSTypeParameterInstantiation"); + } + tsIsDeclarationStart() { + return tokenIsTSDeclarationStart(this.state.type); + } + isExportDefaultSpecifier() { + if (this.tsIsDeclarationStart()) return false; + return super.isExportDefaultSpecifier(); + } + parseBindingElement(flags, decorators) { + const startLoc = decorators.length ? decorators[0].loc.start : this.state.startLoc; + const modified = {}; + this.tsParseModifiers({ + allowedModifiers: ["public", "private", "protected", "override", "readonly"] + }, modified); + const accessibility = modified.accessibility; + const override = modified.override; + const readonly = modified.readonly; + if (!(flags & 4) && (accessibility || readonly || override)) { + this.raise(TSErrors.UnexpectedParameterModifier, startLoc); + } + const left = this.parseMaybeDefault(); + if (flags & 2) { + this.parseFunctionParamType(left); + } + const elt = this.parseMaybeDefault(left.loc.start, left); + if (accessibility || readonly || override) { + const pp = this.startNodeAt(startLoc); + if (decorators.length) { + pp.decorators = decorators; + } + if (accessibility) pp.accessibility = accessibility; + if (readonly) pp.readonly = readonly; + if (override) pp.override = override; + if (elt.type !== "Identifier" && elt.type !== "AssignmentPattern") { + this.raise(TSErrors.UnsupportedParameterPropertyKind, pp); + } + pp.parameter = elt; + return this.finishNode(pp, "TSParameterProperty"); + } + if (decorators.length) { + left.decorators = decorators; + } + return elt; + } + isSimpleParameter(node) { + return node.type === "TSParameterProperty" && super.isSimpleParameter(node.parameter) || super.isSimpleParameter(node); + } + tsDisallowOptionalPattern(node) { + for (const param of node.params) { + if (param.type !== "Identifier" && param.optional && !this.state.isAmbientContext) { + this.raise(TSErrors.PatternIsOptional, param); + } + } + } + setArrowFunctionParameters(node, params, trailingCommaLoc) { + super.setArrowFunctionParameters(node, params, trailingCommaLoc); + this.tsDisallowOptionalPattern(node); + } + parseFunctionBodyAndFinish(node, type, isMethod = false) { + if (this.match(14)) { + node.returnType = this.tsParseTypeOrTypePredicateAnnotation(14); + } + const bodilessType = type === "FunctionDeclaration" ? "TSDeclareFunction" : type === "ClassMethod" || type === "ClassPrivateMethod" ? "TSDeclareMethod" : undefined; + if (bodilessType && !this.match(5) && this.isLineTerminator()) { + return this.finishNode(node, bodilessType); + } + if (bodilessType === "TSDeclareFunction" && this.state.isAmbientContext) { + this.raise(TSErrors.DeclareFunctionHasImplementation, node); + if (node.declare) { + return super.parseFunctionBodyAndFinish(node, bodilessType, isMethod); + } + } + this.tsDisallowOptionalPattern(node); + return super.parseFunctionBodyAndFinish(node, type, isMethod); + } + registerFunctionStatementId(node) { + if (!node.body && node.id) { + this.checkIdentifier(node.id, 1024); + } else { + super.registerFunctionStatementId(node); + } + } + tsCheckForInvalidTypeCasts(items) { + items.forEach(node => { + if ((node == null ? void 0 : node.type) === "TSTypeCastExpression") { + this.raise(TSErrors.UnexpectedTypeAnnotation, node.typeAnnotation); + } + }); + } + toReferencedList(exprList, isInParens) { + this.tsCheckForInvalidTypeCasts(exprList); + return exprList; + } + parseArrayLike(close, isTuple, refExpressionErrors) { + const node = super.parseArrayLike(close, isTuple, refExpressionErrors); + if (node.type === "ArrayExpression") { + this.tsCheckForInvalidTypeCasts(node.elements); + } + return node; + } + parseSubscript(base, startLoc, noCalls, state) { + if (!this.hasPrecedingLineBreak() && this.match(35)) { + this.state.canStartJSXElement = false; + this.next(); + const nonNullExpression = this.startNodeAt(startLoc); + nonNullExpression.expression = base; + return this.finishNode(nonNullExpression, "TSNonNullExpression"); + } + let isOptionalCall = false; + if (this.match(18) && this.lookaheadCharCode() === 60) { + if (noCalls) { + state.stop = true; + return base; + } + state.optionalChainMember = isOptionalCall = true; + this.next(); + } + if (this.match(47) || this.match(51)) { + let missingParenErrorLoc; + const result = this.tsTryParseAndCatch(() => { + if (!noCalls && this.atPossibleAsyncArrow(base)) { + const asyncArrowFn = this.tsTryParseGenericAsyncArrowFunction(startLoc); + if (asyncArrowFn) { + state.stop = true; + return asyncArrowFn; + } + } + const typeArguments = this.tsParseTypeArgumentsInExpression(); + if (!typeArguments) return; + if (isOptionalCall && !this.match(10)) { + missingParenErrorLoc = this.state.curPosition(); + return; + } + if (tokenIsTemplate(this.state.type)) { + const result = super.parseTaggedTemplateExpression(base, startLoc, state); + result.typeParameters = typeArguments; + return result; + } + if (!noCalls && this.eat(10)) { + const node = this.startNodeAt(startLoc); + node.callee = base; + node.arguments = this.parseCallExpressionArguments(); + this.tsCheckForInvalidTypeCasts(node.arguments); + node.typeParameters = typeArguments; + if (state.optionalChainMember) { + node.optional = isOptionalCall; + } + return this.finishCallExpression(node, state.optionalChainMember); + } + const tokenType = this.state.type; + if (tokenType === 48 || tokenType === 52 || tokenType !== 10 && tokenType !== 93 && tokenType !== 120 && tokenCanStartExpression(tokenType) && !this.hasPrecedingLineBreak()) { + return; + } + const node = this.startNodeAt(startLoc); + node.expression = base; + node.typeParameters = typeArguments; + return this.finishNode(node, "TSInstantiationExpression"); + }); + if (missingParenErrorLoc) { + this.unexpected(missingParenErrorLoc, 10); + } + if (result) { + if (result.type === "TSInstantiationExpression") { + if (this.match(16) || this.match(18) && this.lookaheadCharCode() !== 40) { + this.raise(TSErrors.InvalidPropertyAccessAfterInstantiationExpression, this.state.startLoc); + } + if (!this.match(16) && !this.match(18)) { + result.expression = super.stopParseSubscript(base, state); + } + } + return result; + } + } + return super.parseSubscript(base, startLoc, noCalls, state); + } + parseNewCallee(node) { + var _callee$extra; + super.parseNewCallee(node); + const { + callee + } = node; + if (callee.type === "TSInstantiationExpression" && !((_callee$extra = callee.extra) != null && _callee$extra.parenthesized)) { + node.typeParameters = callee.typeParameters; + node.callee = callee.expression; + } + } + parseExprOp(left, leftStartLoc, minPrec) { + let isSatisfies; + if (tokenOperatorPrecedence(58) > minPrec && !this.hasPrecedingLineBreak() && (this.isContextual(93) || (isSatisfies = this.isContextual(120)))) { + const node = this.startNodeAt(leftStartLoc); + node.expression = left; + node.typeAnnotation = this.tsInType(() => { + this.next(); + if (this.match(75)) { + if (isSatisfies) { + this.raise(Errors.UnexpectedKeyword, this.state.startLoc, { + keyword: "const" + }); + } + return this.tsParseTypeReference(); + } + return this.tsParseType(); + }); + this.finishNode(node, isSatisfies ? "TSSatisfiesExpression" : "TSAsExpression"); + this.reScan_lt_gt(); + return this.parseExprOp(node, leftStartLoc, minPrec); + } + return super.parseExprOp(left, leftStartLoc, minPrec); + } + checkReservedWord(word, startLoc, checkKeywords, isBinding) { + if (!this.state.isAmbientContext) { + super.checkReservedWord(word, startLoc, checkKeywords, isBinding); + } + } + checkImportReflection(node) { + super.checkImportReflection(node); + if (node.module && node.importKind !== "value") { + this.raise(TSErrors.ImportReflectionHasImportType, node.specifiers[0].loc.start); + } + } + checkDuplicateExports() {} + isPotentialImportPhase(isExport) { + if (super.isPotentialImportPhase(isExport)) return true; + if (this.isContextual(130)) { + const ch = this.lookaheadCharCode(); + return isExport ? ch === 123 || ch === 42 : ch !== 61; + } + return !isExport && this.isContextual(87); + } + applyImportPhase(node, isExport, phase, loc) { + super.applyImportPhase(node, isExport, phase, loc); + if (isExport) { + node.exportKind = phase === "type" ? "type" : "value"; + } else { + node.importKind = phase === "type" || phase === "typeof" ? phase : "value"; + } + } + parseImport(node) { + if (this.match(134)) { + node.importKind = "value"; + return super.parseImport(node); + } + let importNode; + if (tokenIsIdentifier(this.state.type) && this.lookaheadCharCode() === 61) { + node.importKind = "value"; + return this.tsParseImportEqualsDeclaration(node); + } else if (this.isContextual(130)) { + const maybeDefaultIdentifier = this.parseMaybeImportPhase(node, false); + if (this.lookaheadCharCode() === 61) { + return this.tsParseImportEqualsDeclaration(node, maybeDefaultIdentifier); + } else { + importNode = super.parseImportSpecifiersAndAfter(node, maybeDefaultIdentifier); + } + } else { + importNode = super.parseImport(node); + } + if (importNode.importKind === "type" && importNode.specifiers.length > 1 && importNode.specifiers[0].type === "ImportDefaultSpecifier") { + this.raise(TSErrors.TypeImportCannotSpecifyDefaultAndNamed, importNode); + } + return importNode; + } + parseExport(node, decorators) { + if (this.match(83)) { + const nodeImportEquals = node; + this.next(); + let maybeDefaultIdentifier = null; + if (this.isContextual(130) && this.isPotentialImportPhase(false)) { + maybeDefaultIdentifier = this.parseMaybeImportPhase(nodeImportEquals, false); + } else { + nodeImportEquals.importKind = "value"; + } + const declaration = this.tsParseImportEqualsDeclaration(nodeImportEquals, maybeDefaultIdentifier, true); + return declaration; + } else if (this.eat(29)) { + const assign = node; + assign.expression = super.parseExpression(); + this.semicolon(); + this.sawUnambiguousESM = true; + return this.finishNode(assign, "TSExportAssignment"); + } else if (this.eatContextual(93)) { + const decl = node; + this.expectContextual(128); + decl.id = this.parseIdentifier(); + this.semicolon(); + return this.finishNode(decl, "TSNamespaceExportDeclaration"); + } else { + return super.parseExport(node, decorators); + } + } + isAbstractClass() { + return this.isContextual(124) && this.isLookaheadContextual("class"); + } + parseExportDefaultExpression() { + if (this.isAbstractClass()) { + const cls = this.startNode(); + this.next(); + cls.abstract = true; + return this.parseClass(cls, true, true); + } + if (this.match(129)) { + const result = this.tsParseInterfaceDeclaration(this.startNode()); + if (result) return result; + } + return super.parseExportDefaultExpression(); + } + parseVarStatement(node, kind, allowMissingInitializer = false) { + const { + isAmbientContext + } = this.state; + const declaration = super.parseVarStatement(node, kind, allowMissingInitializer || isAmbientContext); + if (!isAmbientContext) return declaration; + if (!node.declare && (kind === "using" || kind === "await using")) { + this.raiseOverwrite(TSErrors.UsingDeclarationInAmbientContext, node, kind); + return declaration; + } + for (const { + id, + init + } of declaration.declarations) { + if (!init) continue; + if (kind === "var" || kind === "let" || !!id.typeAnnotation) { + this.raise(TSErrors.InitializerNotAllowedInAmbientContext, init); + } else if (!isValidAmbientConstInitializer(init, this.hasPlugin("estree"))) { + this.raise(TSErrors.ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference, init); + } + } + return declaration; + } + parseStatementContent(flags, decorators) { + if (!this.state.containsEsc) { + switch (this.state.type) { + case 75: + { + if (this.isLookaheadContextual("enum")) { + const node = this.startNode(); + this.expect(75); + return this.tsParseEnumDeclaration(node, { + const: true + }); + } + break; + } + case 124: + case 125: + { + if (this.nextTokenIsIdentifierAndNotTSRelationalOperatorOnSameLine()) { + const token = this.state.type; + const node = this.startNode(); + this.next(); + const declaration = token === 125 ? this.tsTryParseDeclare(node) : this.tsParseAbstractDeclaration(node, decorators); + if (declaration) { + if (token === 125) { + declaration.declare = true; + } + return declaration; + } else { + node.expression = this.createIdentifier(this.startNodeAt(node.loc.start), token === 125 ? "declare" : "abstract"); + this.semicolon(false); + return this.finishNode(node, "ExpressionStatement"); + } + } + break; + } + case 126: + return this.tsParseEnumDeclaration(this.startNode()); + case 112: + { + const nextCh = this.lookaheadCharCode(); + if (nextCh === 123) { + const node = this.startNode(); + return this.tsParseAmbientExternalModuleDeclaration(node); + } + break; + } + case 129: + { + const result = this.tsParseInterfaceDeclaration(this.startNode()); + if (result) return result; + break; + } + case 127: + { + if (this.nextTokenIsIdentifierOrStringLiteralOnSameLine()) { + const node = this.startNode(); + this.next(); + return this.tsParseDeclaration(node, 127, false, decorators); + } + break; + } + case 128: + { + if (this.nextTokenIsIdentifierOnSameLine()) { + const node = this.startNode(); + this.next(); + return this.tsParseDeclaration(node, 128, false, decorators); + } + break; + } + case 130: + { + if (this.nextTokenIsIdentifierOnSameLine()) { + const node = this.startNode(); + this.next(); + return this.tsParseTypeAliasDeclaration(node); + } + break; + } + } + } + return super.parseStatementContent(flags, decorators); + } + parseAccessModifier() { + return this.tsParseModifier(["public", "protected", "private"]); + } + tsHasSomeModifiers(member, modifiers) { + return modifiers.some(modifier => { + if (tsIsAccessModifier(modifier)) { + return member.accessibility === modifier; + } + return !!member[modifier]; + }); + } + tsIsStartOfStaticBlocks() { + return this.isContextual(106) && this.lookaheadCharCode() === 123; + } + parseClassMember(classBody, member, state) { + const modifiers = ["declare", "private", "public", "protected", "override", "abstract", "readonly", "static"]; + this.tsParseModifiers({ + allowedModifiers: modifiers, + disallowedModifiers: ["in", "out"], + stopOnStartOfClassStaticBlock: true, + errorTemplate: TSErrors.InvalidModifierOnTypeParameterPositions + }, member); + const callParseClassMemberWithIsStatic = () => { + if (this.tsIsStartOfStaticBlocks()) { + this.next(); + this.next(); + if (this.tsHasSomeModifiers(member, modifiers)) { + this.raise(TSErrors.StaticBlockCannotHaveModifier, this.state.curPosition()); + } + super.parseClassStaticBlock(classBody, member); + } else { + this.parseClassMemberWithIsStatic(classBody, member, state, !!member.static); + } + }; + if (member.declare) { + this.tsInAmbientContext(callParseClassMemberWithIsStatic); + } else { + callParseClassMemberWithIsStatic(); + } + } + parseClassMemberWithIsStatic(classBody, member, state, isStatic) { + const idx = this.tsTryParseIndexSignature(member); + if (idx) { + classBody.body.push(idx); + if (member.abstract) { + this.raise(TSErrors.IndexSignatureHasAbstract, member); + } + if (member.accessibility) { + this.raise(TSErrors.IndexSignatureHasAccessibility, member, { + modifier: member.accessibility + }); + } + if (member.declare) { + this.raise(TSErrors.IndexSignatureHasDeclare, member); + } + if (member.override) { + this.raise(TSErrors.IndexSignatureHasOverride, member); + } + return; + } + if (!this.state.inAbstractClass && member.abstract) { + this.raise(TSErrors.NonAbstractClassHasAbstractMethod, member); + } + if (member.override) { + if (!state.hadSuperClass) { + this.raise(TSErrors.OverrideNotInSubClass, member); + } + } + super.parseClassMemberWithIsStatic(classBody, member, state, isStatic); + } + parsePostMemberNameModifiers(methodOrProp) { + const optional = this.eat(17); + if (optional) methodOrProp.optional = true; + if (methodOrProp.readonly && this.match(10)) { + this.raise(TSErrors.ClassMethodHasReadonly, methodOrProp); + } + if (methodOrProp.declare && this.match(10)) { + this.raise(TSErrors.ClassMethodHasDeclare, methodOrProp); + } + } + shouldParseExportDeclaration() { + if (this.tsIsDeclarationStart()) return true; + return super.shouldParseExportDeclaration(); + } + parseConditional(expr, startLoc, refExpressionErrors) { + if (!this.match(17)) return expr; + if (this.state.maybeInArrowParameters) { + const nextCh = this.lookaheadCharCode(); + if (nextCh === 44 || nextCh === 61 || nextCh === 58 || nextCh === 41) { + this.setOptionalParametersError(refExpressionErrors); + return expr; + } + } + return super.parseConditional(expr, startLoc, refExpressionErrors); + } + parseParenItem(node, startLoc) { + const newNode = super.parseParenItem(node, startLoc); + if (this.eat(17)) { + newNode.optional = true; + this.resetEndLocation(node); + } + if (this.match(14)) { + const typeCastNode = this.startNodeAt(startLoc); + typeCastNode.expression = node; + typeCastNode.typeAnnotation = this.tsParseTypeAnnotation(); + return this.finishNode(typeCastNode, "TSTypeCastExpression"); + } + return node; + } + parseExportDeclaration(node) { + if (!this.state.isAmbientContext && this.isContextual(125)) { + return this.tsInAmbientContext(() => this.parseExportDeclaration(node)); + } + const startLoc = this.state.startLoc; + const isDeclare = this.eatContextual(125); + if (isDeclare && (this.isContextual(125) || !this.shouldParseExportDeclaration())) { + throw this.raise(TSErrors.ExpectedAmbientAfterExportDeclare, this.state.startLoc); + } + const isIdentifier = tokenIsIdentifier(this.state.type); + const declaration = isIdentifier && this.tsTryParseExportDeclaration() || super.parseExportDeclaration(node); + if (!declaration) return null; + if (declaration.type === "TSInterfaceDeclaration" || declaration.type === "TSTypeAliasDeclaration" || isDeclare) { + node.exportKind = "type"; + } + if (isDeclare && declaration.type !== "TSImportEqualsDeclaration") { + this.resetStartLocation(declaration, startLoc); + declaration.declare = true; + } + return declaration; + } + parseClassId(node, isStatement, optionalId, bindingType) { + if ((!isStatement || optionalId) && this.isContextual(113)) { + return; + } + super.parseClassId(node, isStatement, optionalId, node.declare ? 1024 : 8331); + const typeParameters = this.tsTryParseTypeParameters(this.tsParseInOutConstModifiers); + if (typeParameters) node.typeParameters = typeParameters; + } + parseClassPropertyAnnotation(node) { + if (!node.optional) { + if (this.eat(35)) { + node.definite = true; + } else if (this.eat(17)) { + node.optional = true; + } + } + const type = this.tsTryParseTypeAnnotation(); + if (type) node.typeAnnotation = type; + } + parseClassProperty(node) { + this.parseClassPropertyAnnotation(node); + if (this.state.isAmbientContext && !(node.readonly && !node.typeAnnotation) && this.match(29)) { + this.raise(TSErrors.DeclareClassFieldHasInitializer, this.state.startLoc); + } + if (node.abstract && this.match(29)) { + const { + key + } = node; + this.raise(TSErrors.AbstractPropertyHasInitializer, this.state.startLoc, { + propertyName: key.type === "Identifier" && !node.computed ? key.name : `[${this.input.slice(this.offsetToSourcePos(key.start), this.offsetToSourcePos(key.end))}]` + }); + } + return super.parseClassProperty(node); + } + parseClassPrivateProperty(node) { + if (node.abstract) { + this.raise(TSErrors.PrivateElementHasAbstract, node); + } + if (node.accessibility) { + this.raise(TSErrors.PrivateElementHasAccessibility, node, { + modifier: node.accessibility + }); + } + this.parseClassPropertyAnnotation(node); + return super.parseClassPrivateProperty(node); + } + parseClassAccessorProperty(node) { + this.parseClassPropertyAnnotation(node); + if (node.optional) { + this.raise(TSErrors.AccessorCannotBeOptional, node); + } + return super.parseClassAccessorProperty(node); + } + pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) { + const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier); + if (typeParameters && isConstructor) { + this.raise(TSErrors.ConstructorHasTypeParameters, typeParameters); + } + const { + declare = false, + kind + } = method; + if (declare && (kind === "get" || kind === "set")) { + this.raise(TSErrors.DeclareAccessor, method, { + kind + }); + } + if (typeParameters) method.typeParameters = typeParameters; + super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper); + } + pushClassPrivateMethod(classBody, method, isGenerator, isAsync) { + const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier); + if (typeParameters) method.typeParameters = typeParameters; + super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync); + } + declareClassPrivateMethodInScope(node, kind) { + if (node.type === "TSDeclareMethod") return; + if (node.type === "MethodDefinition" && node.value.body == null) { + return; + } + super.declareClassPrivateMethodInScope(node, kind); + } + parseClassSuper(node) { + super.parseClassSuper(node); + if (node.superClass) { + if (node.superClass.type === "TSInstantiationExpression") { + const tsInstantiationExpression = node.superClass; + const superClass = tsInstantiationExpression.expression; + this.takeSurroundingComments(superClass, superClass.start, superClass.end); + const superTypeArguments = tsInstantiationExpression.typeParameters; + this.takeSurroundingComments(superTypeArguments, superTypeArguments.start, superTypeArguments.end); + node.superClass = superClass; + node.superTypeParameters = superTypeArguments; + } else if (this.match(47) || this.match(51)) { + node.superTypeParameters = this.tsParseTypeArgumentsInExpression(); + } + } + if (this.eatContextual(113)) { + node.implements = this.tsParseHeritageClause("implements"); + } + } + parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) { + const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier); + if (typeParameters) prop.typeParameters = typeParameters; + return super.parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors); + } + parseFunctionParams(node, isConstructor) { + const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier); + if (typeParameters) node.typeParameters = typeParameters; + super.parseFunctionParams(node, isConstructor); + } + parseVarId(decl, kind) { + super.parseVarId(decl, kind); + if (decl.id.type === "Identifier" && !this.hasPrecedingLineBreak() && this.eat(35)) { + decl.definite = true; + } + const type = this.tsTryParseTypeAnnotation(); + if (type) { + decl.id.typeAnnotation = type; + this.resetEndLocation(decl.id); + } + } + parseAsyncArrowFromCallExpression(node, call) { + if (this.match(14)) { + node.returnType = this.tsParseTypeAnnotation(); + } + return super.parseAsyncArrowFromCallExpression(node, call); + } + parseMaybeAssign(refExpressionErrors, afterLeftParse) { + var _jsx, _jsx2, _typeCast, _jsx3, _typeCast2; + let state; + let jsx; + let typeCast; + if (this.hasPlugin("jsx") && (this.match(143) || this.match(47))) { + state = this.state.clone(); + jsx = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse), state); + if (!jsx.error) return jsx.node; + const { + context + } = this.state; + const currentContext = context[context.length - 1]; + if (currentContext === types.j_oTag || currentContext === types.j_expr) { + context.pop(); + } + } + if (!((_jsx = jsx) != null && _jsx.error) && !this.match(47)) { + return super.parseMaybeAssign(refExpressionErrors, afterLeftParse); + } + if (!state || state === this.state) state = this.state.clone(); + let typeParameters; + const arrow = this.tryParse(abort => { + var _expr$extra, _typeParameters; + typeParameters = this.tsParseTypeParameters(this.tsParseConstModifier); + const expr = super.parseMaybeAssign(refExpressionErrors, afterLeftParse); + if (expr.type !== "ArrowFunctionExpression" || (_expr$extra = expr.extra) != null && _expr$extra.parenthesized) { + abort(); + } + if (((_typeParameters = typeParameters) == null ? void 0 : _typeParameters.params.length) !== 0) { + this.resetStartLocationFromNode(expr, typeParameters); + } + expr.typeParameters = typeParameters; + return expr; + }, state); + if (!arrow.error && !arrow.aborted) { + if (typeParameters) this.reportReservedArrowTypeParam(typeParameters); + return arrow.node; + } + if (!jsx) { + assert(!this.hasPlugin("jsx")); + typeCast = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse), state); + if (!typeCast.error) return typeCast.node; + } + if ((_jsx2 = jsx) != null && _jsx2.node) { + this.state = jsx.failState; + return jsx.node; + } + if (arrow.node) { + this.state = arrow.failState; + if (typeParameters) this.reportReservedArrowTypeParam(typeParameters); + return arrow.node; + } + if ((_typeCast = typeCast) != null && _typeCast.node) { + this.state = typeCast.failState; + return typeCast.node; + } + throw ((_jsx3 = jsx) == null ? void 0 : _jsx3.error) || arrow.error || ((_typeCast2 = typeCast) == null ? void 0 : _typeCast2.error); + } + reportReservedArrowTypeParam(node) { + var _node$extra2; + if (node.params.length === 1 && !node.params[0].constraint && !((_node$extra2 = node.extra) != null && _node$extra2.trailingComma) && this.getPluginOption("typescript", "disallowAmbiguousJSXLike")) { + this.raise(TSErrors.ReservedArrowTypeParam, node); + } + } + parseMaybeUnary(refExpressionErrors, sawUnary) { + if (!this.hasPlugin("jsx") && this.match(47)) { + return this.tsParseTypeAssertion(); + } + return super.parseMaybeUnary(refExpressionErrors, sawUnary); + } + parseArrow(node) { + if (this.match(14)) { + const result = this.tryParse(abort => { + const returnType = this.tsParseTypeOrTypePredicateAnnotation(14); + if (this.canInsertSemicolon() || !this.match(19)) abort(); + return returnType; + }); + if (result.aborted) return; + if (!result.thrown) { + if (result.error) this.state = result.failState; + node.returnType = result.node; + } + } + return super.parseArrow(node); + } + parseFunctionParamType(param) { + if (this.eat(17)) { + param.optional = true; + } + const type = this.tsTryParseTypeAnnotation(); + if (type) param.typeAnnotation = type; + this.resetEndLocation(param); + return param; + } + isAssignable(node, isBinding) { + switch (node.type) { + case "TSTypeCastExpression": + return this.isAssignable(node.expression, isBinding); + case "TSParameterProperty": + return true; + default: + return super.isAssignable(node, isBinding); + } + } + toAssignable(node, isLHS = false) { + switch (node.type) { + case "ParenthesizedExpression": + this.toAssignableParenthesizedExpression(node, isLHS); + break; + case "TSAsExpression": + case "TSSatisfiesExpression": + case "TSNonNullExpression": + case "TSTypeAssertion": + if (isLHS) { + this.expressionScope.recordArrowParameterBindingError(TSErrors.UnexpectedTypeCastInParameter, node); + } else { + this.raise(TSErrors.UnexpectedTypeCastInParameter, node); + } + this.toAssignable(node.expression, isLHS); + break; + case "AssignmentExpression": + if (!isLHS && node.left.type === "TSTypeCastExpression") { + node.left = this.typeCastToParameter(node.left); + } + default: + super.toAssignable(node, isLHS); + } + } + toAssignableParenthesizedExpression(node, isLHS) { + switch (node.expression.type) { + case "TSAsExpression": + case "TSSatisfiesExpression": + case "TSNonNullExpression": + case "TSTypeAssertion": + case "ParenthesizedExpression": + this.toAssignable(node.expression, isLHS); + break; + default: + super.toAssignable(node, isLHS); + } + } + checkToRestConversion(node, allowPattern) { + switch (node.type) { + case "TSAsExpression": + case "TSSatisfiesExpression": + case "TSTypeAssertion": + case "TSNonNullExpression": + this.checkToRestConversion(node.expression, false); + break; + default: + super.checkToRestConversion(node, allowPattern); + } + } + isValidLVal(type, disallowCallExpression, isUnparenthesizedInAssign, binding) { + switch (type) { + case "TSTypeCastExpression": + return true; + case "TSParameterProperty": + return "parameter"; + case "TSNonNullExpression": + return "expression"; + case "TSAsExpression": + case "TSSatisfiesExpression": + case "TSTypeAssertion": + return (binding !== 64 || !isUnparenthesizedInAssign) && ["expression", true]; + default: + return super.isValidLVal(type, disallowCallExpression, isUnparenthesizedInAssign, binding); + } + } + parseBindingAtom() { + if (this.state.type === 78) { + return this.parseIdentifier(true); + } + return super.parseBindingAtom(); + } + parseMaybeDecoratorArguments(expr, startLoc) { + if (this.match(47) || this.match(51)) { + const typeArguments = this.tsParseTypeArgumentsInExpression(); + if (this.match(10)) { + const call = super.parseMaybeDecoratorArguments(expr, startLoc); + call.typeParameters = typeArguments; + return call; + } + this.unexpected(null, 10); + } + return super.parseMaybeDecoratorArguments(expr, startLoc); + } + checkCommaAfterRest(close) { + if (this.state.isAmbientContext && this.match(12) && this.lookaheadCharCode() === close) { + this.next(); + return false; + } + return super.checkCommaAfterRest(close); + } + isClassMethod() { + return this.match(47) || super.isClassMethod(); + } + isClassProperty() { + return this.match(35) || this.match(14) || super.isClassProperty(); + } + parseMaybeDefault(startLoc, left) { + const node = super.parseMaybeDefault(startLoc, left); + if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) { + this.raise(TSErrors.TypeAnnotationAfterAssign, node.typeAnnotation); + } + return node; + } + getTokenFromCode(code) { + if (this.state.inType) { + if (code === 62) { + this.finishOp(48, 1); + return; + } + if (code === 60) { + this.finishOp(47, 1); + return; + } + } + super.getTokenFromCode(code); + } + reScan_lt_gt() { + const { + type + } = this.state; + if (type === 47) { + this.state.pos -= 1; + this.readToken_lt(); + } else if (type === 48) { + this.state.pos -= 1; + this.readToken_gt(); + } + } + reScan_lt() { + const { + type + } = this.state; + if (type === 51) { + this.state.pos -= 2; + this.finishOp(47, 1); + return 47; + } + return type; + } + toAssignableListItem(exprList, index, isLHS) { + const node = exprList[index]; + if (node.type === "TSTypeCastExpression") { + exprList[index] = this.typeCastToParameter(node); + } + super.toAssignableListItem(exprList, index, isLHS); + } + typeCastToParameter(node) { + node.expression.typeAnnotation = node.typeAnnotation; + this.resetEndLocation(node.expression, node.typeAnnotation.loc.end); + return node.expression; + } + shouldParseArrow(params) { + if (this.match(14)) { + return params.every(expr => this.isAssignable(expr, true)); + } + return super.shouldParseArrow(params); + } + shouldParseAsyncArrow() { + return this.match(14) || super.shouldParseAsyncArrow(); + } + canHaveLeadingDecorator() { + return super.canHaveLeadingDecorator() || this.isAbstractClass(); + } + jsxParseOpeningElementAfterName(node) { + if (this.match(47) || this.match(51)) { + const typeArguments = this.tsTryParseAndCatch(() => this.tsParseTypeArgumentsInExpression()); + if (typeArguments) { + node.typeParameters = typeArguments; + } + } + return super.jsxParseOpeningElementAfterName(node); + } + getGetterSetterExpectedParamCount(method) { + const baseCount = super.getGetterSetterExpectedParamCount(method); + const params = this.getObjectOrClassMethodParams(method); + const firstParam = params[0]; + const hasContextParam = firstParam && this.isThisParam(firstParam); + return hasContextParam ? baseCount + 1 : baseCount; + } + parseCatchClauseParam() { + const param = super.parseCatchClauseParam(); + const type = this.tsTryParseTypeAnnotation(); + if (type) { + param.typeAnnotation = type; + this.resetEndLocation(param); + } + return param; + } + tsInAmbientContext(cb) { + const { + isAmbientContext: oldIsAmbientContext, + strict: oldStrict + } = this.state; + this.state.isAmbientContext = true; + this.state.strict = false; + try { + return cb(); + } finally { + this.state.isAmbientContext = oldIsAmbientContext; + this.state.strict = oldStrict; + } + } + parseClass(node, isStatement, optionalId) { + const oldInAbstractClass = this.state.inAbstractClass; + this.state.inAbstractClass = !!node.abstract; + try { + return super.parseClass(node, isStatement, optionalId); + } finally { + this.state.inAbstractClass = oldInAbstractClass; + } + } + tsParseAbstractDeclaration(node, decorators) { + if (this.match(80)) { + node.abstract = true; + return this.maybeTakeDecorators(decorators, this.parseClass(node, true, false)); + } else if (this.isContextual(129)) { + if (!this.hasFollowingLineBreak()) { + node.abstract = true; + this.raise(TSErrors.NonClassMethodPropertyHasAbstractModifier, node); + return this.tsParseInterfaceDeclaration(node); + } else { + return null; + } + } + throw this.unexpected(null, 80); + } + parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope) { + const method = super.parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope); + if (method.abstract || method.type === "TSAbstractMethodDefinition") { + const hasEstreePlugin = this.hasPlugin("estree"); + const methodFn = hasEstreePlugin ? method.value : method; + if (methodFn.body) { + const { + key + } = method; + this.raise(TSErrors.AbstractMethodHasImplementation, method, { + methodName: key.type === "Identifier" && !method.computed ? key.name : `[${this.input.slice(this.offsetToSourcePos(key.start), this.offsetToSourcePos(key.end))}]` + }); + } + } + return method; + } + tsParseTypeParameterName() { + const typeName = this.parseIdentifier(); + return typeName.name; + } + shouldParseAsAmbientContext() { + return !!this.getPluginOption("typescript", "dts"); + } + parse() { + if (this.shouldParseAsAmbientContext()) { + this.state.isAmbientContext = true; + } + return super.parse(); + } + getExpression() { + if (this.shouldParseAsAmbientContext()) { + this.state.isAmbientContext = true; + } + return super.getExpression(); + } + parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly) { + if (!isString && isMaybeTypeOnly) { + this.parseTypeOnlyImportExportSpecifier(node, false, isInTypeExport); + return this.finishNode(node, "ExportSpecifier"); + } + node.exportKind = "value"; + return super.parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly); + } + parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, bindingType) { + if (!importedIsString && isMaybeTypeOnly) { + this.parseTypeOnlyImportExportSpecifier(specifier, true, isInTypeOnlyImport); + return this.finishNode(specifier, "ImportSpecifier"); + } + specifier.importKind = "value"; + return super.parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, isInTypeOnlyImport ? 4098 : 4096); + } + parseTypeOnlyImportExportSpecifier(node, isImport, isInTypeOnlyImportExport) { + const leftOfAsKey = isImport ? "imported" : "local"; + const rightOfAsKey = isImport ? "local" : "exported"; + let leftOfAs = node[leftOfAsKey]; + let rightOfAs; + let hasTypeSpecifier = false; + let canParseAsKeyword = true; + const loc = leftOfAs.loc.start; + if (this.isContextual(93)) { + const firstAs = this.parseIdentifier(); + if (this.isContextual(93)) { + const secondAs = this.parseIdentifier(); + if (tokenIsKeywordOrIdentifier(this.state.type)) { + hasTypeSpecifier = true; + leftOfAs = firstAs; + rightOfAs = isImport ? this.parseIdentifier() : this.parseModuleExportName(); + canParseAsKeyword = false; + } else { + rightOfAs = secondAs; + canParseAsKeyword = false; + } + } else if (tokenIsKeywordOrIdentifier(this.state.type)) { + canParseAsKeyword = false; + rightOfAs = isImport ? this.parseIdentifier() : this.parseModuleExportName(); + } else { + hasTypeSpecifier = true; + leftOfAs = firstAs; + } + } else if (tokenIsKeywordOrIdentifier(this.state.type)) { + hasTypeSpecifier = true; + if (isImport) { + leftOfAs = this.parseIdentifier(true); + if (!this.isContextual(93)) { + this.checkReservedWord(leftOfAs.name, leftOfAs.loc.start, true, true); + } + } else { + leftOfAs = this.parseModuleExportName(); + } + } + if (hasTypeSpecifier && isInTypeOnlyImportExport) { + this.raise(isImport ? TSErrors.TypeModifierIsUsedInTypeImports : TSErrors.TypeModifierIsUsedInTypeExports, loc); + } + node[leftOfAsKey] = leftOfAs; + node[rightOfAsKey] = rightOfAs; + const kindKey = isImport ? "importKind" : "exportKind"; + node[kindKey] = hasTypeSpecifier ? "type" : "value"; + if (canParseAsKeyword && this.eatContextual(93)) { + node[rightOfAsKey] = isImport ? this.parseIdentifier() : this.parseModuleExportName(); + } + if (!node[rightOfAsKey]) { + node[rightOfAsKey] = this.cloneIdentifier(node[leftOfAsKey]); + } + if (isImport) { + this.checkIdentifier(node[rightOfAsKey], hasTypeSpecifier ? 4098 : 4096); + } + } + fillOptionalPropertiesForTSESLint(node) { + var _node$directive, _node$decorators, _node$optional, _node$typeAnnotation, _node$accessibility, _node$decorators2, _node$override, _node$readonly, _node$static, _node$declare, _node$returnType, _node$typeParameters, _node$optional2, _node$optional3, _node$accessibility2, _node$readonly2, _node$static2, _node$declare2, _node$definite, _node$readonly3, _node$typeAnnotation2, _node$accessibility3, _node$decorators3, _node$override2, _node$optional4, _node$id, _node$abstract, _node$declare3, _node$decorators4, _node$implements, _node$superTypeArgume, _node$typeParameters2, _node$declare4, _node$definite2, _node$const, _node$declare5, _node$computed, _node$qualifier, _node$options, _node$declare6, _node$extends, _node$optional5, _node$readonly4, _node$declare7, _node$global, _node$const2, _node$in, _node$out; + switch (node.type) { + case "ExpressionStatement": + (_node$directive = node.directive) != null ? _node$directive : node.directive = undefined; + return; + case "RestElement": + node.value = undefined; + case "Identifier": + case "ArrayPattern": + case "AssignmentPattern": + case "ObjectPattern": + (_node$decorators = node.decorators) != null ? _node$decorators : node.decorators = []; + (_node$optional = node.optional) != null ? _node$optional : node.optional = false; + (_node$typeAnnotation = node.typeAnnotation) != null ? _node$typeAnnotation : node.typeAnnotation = undefined; + return; + case "TSParameterProperty": + (_node$accessibility = node.accessibility) != null ? _node$accessibility : node.accessibility = undefined; + (_node$decorators2 = node.decorators) != null ? _node$decorators2 : node.decorators = []; + (_node$override = node.override) != null ? _node$override : node.override = false; + (_node$readonly = node.readonly) != null ? _node$readonly : node.readonly = false; + (_node$static = node.static) != null ? _node$static : node.static = false; + return; + case "TSEmptyBodyFunctionExpression": + node.body = null; + case "TSDeclareFunction": + case "FunctionDeclaration": + case "FunctionExpression": + case "ClassMethod": + case "ClassPrivateMethod": + (_node$declare = node.declare) != null ? _node$declare : node.declare = false; + (_node$returnType = node.returnType) != null ? _node$returnType : node.returnType = undefined; + (_node$typeParameters = node.typeParameters) != null ? _node$typeParameters : node.typeParameters = undefined; + return; + case "Property": + (_node$optional2 = node.optional) != null ? _node$optional2 : node.optional = false; + return; + case "TSMethodSignature": + case "TSPropertySignature": + (_node$optional3 = node.optional) != null ? _node$optional3 : node.optional = false; + case "TSIndexSignature": + (_node$accessibility2 = node.accessibility) != null ? _node$accessibility2 : node.accessibility = undefined; + (_node$readonly2 = node.readonly) != null ? _node$readonly2 : node.readonly = false; + (_node$static2 = node.static) != null ? _node$static2 : node.static = false; + return; + case "TSAbstractPropertyDefinition": + case "PropertyDefinition": + case "TSAbstractAccessorProperty": + case "AccessorProperty": + (_node$declare2 = node.declare) != null ? _node$declare2 : node.declare = false; + (_node$definite = node.definite) != null ? _node$definite : node.definite = false; + (_node$readonly3 = node.readonly) != null ? _node$readonly3 : node.readonly = false; + (_node$typeAnnotation2 = node.typeAnnotation) != null ? _node$typeAnnotation2 : node.typeAnnotation = undefined; + case "TSAbstractMethodDefinition": + case "MethodDefinition": + (_node$accessibility3 = node.accessibility) != null ? _node$accessibility3 : node.accessibility = undefined; + (_node$decorators3 = node.decorators) != null ? _node$decorators3 : node.decorators = []; + (_node$override2 = node.override) != null ? _node$override2 : node.override = false; + (_node$optional4 = node.optional) != null ? _node$optional4 : node.optional = false; + return; + case "ClassExpression": + (_node$id = node.id) != null ? _node$id : node.id = null; + case "ClassDeclaration": + (_node$abstract = node.abstract) != null ? _node$abstract : node.abstract = false; + (_node$declare3 = node.declare) != null ? _node$declare3 : node.declare = false; + (_node$decorators4 = node.decorators) != null ? _node$decorators4 : node.decorators = []; + (_node$implements = node.implements) != null ? _node$implements : node.implements = []; + (_node$superTypeArgume = node.superTypeArguments) != null ? _node$superTypeArgume : node.superTypeArguments = undefined; + (_node$typeParameters2 = node.typeParameters) != null ? _node$typeParameters2 : node.typeParameters = undefined; + return; + case "TSTypeAliasDeclaration": + case "VariableDeclaration": + (_node$declare4 = node.declare) != null ? _node$declare4 : node.declare = false; + return; + case "VariableDeclarator": + (_node$definite2 = node.definite) != null ? _node$definite2 : node.definite = false; + return; + case "TSEnumDeclaration": + (_node$const = node.const) != null ? _node$const : node.const = false; + (_node$declare5 = node.declare) != null ? _node$declare5 : node.declare = false; + return; + case "TSEnumMember": + (_node$computed = node.computed) != null ? _node$computed : node.computed = false; + return; + case "TSImportType": + (_node$qualifier = node.qualifier) != null ? _node$qualifier : node.qualifier = null; + (_node$options = node.options) != null ? _node$options : node.options = null; + return; + case "TSInterfaceDeclaration": + (_node$declare6 = node.declare) != null ? _node$declare6 : node.declare = false; + (_node$extends = node.extends) != null ? _node$extends : node.extends = []; + return; + case "TSMappedType": + (_node$optional5 = node.optional) != null ? _node$optional5 : node.optional = false; + (_node$readonly4 = node.readonly) != null ? _node$readonly4 : node.readonly = undefined; + return; + case "TSModuleDeclaration": + (_node$declare7 = node.declare) != null ? _node$declare7 : node.declare = false; + (_node$global = node.global) != null ? _node$global : node.global = node.kind === "global"; + return; + case "TSTypeParameter": + (_node$const2 = node.const) != null ? _node$const2 : node.const = false; + (_node$in = node.in) != null ? _node$in : node.in = false; + (_node$out = node.out) != null ? _node$out : node.out = false; + return; + } + } + chStartsBindingIdentifierAndNotRelationalOperator(ch, pos) { + if (isIdentifierStart(ch)) { + keywordAndTSRelationalOperator.lastIndex = pos; + if (keywordAndTSRelationalOperator.test(this.input)) { + const endCh = this.codePointAtPos(keywordAndTSRelationalOperator.lastIndex); + if (!isIdentifierChar(endCh) && endCh !== 92) { + return false; + } + } + return true; + } else if (ch === 92) { + return true; + } else { + return false; + } + } + nextTokenIsIdentifierAndNotTSRelationalOperatorOnSameLine() { + const next = this.nextTokenInLineStart(); + const nextCh = this.codePointAtPos(next); + return this.chStartsBindingIdentifierAndNotRelationalOperator(nextCh, next); + } + nextTokenIsIdentifierOrStringLiteralOnSameLine() { + const next = this.nextTokenInLineStart(); + const nextCh = this.codePointAtPos(next); + return this.chStartsBindingIdentifier(nextCh, next) || nextCh === 34 || nextCh === 39; + } +}; +function isPossiblyLiteralEnum(expression) { + if (expression.type !== "MemberExpression") return false; + const { + computed, + property + } = expression; + if (computed && property.type !== "StringLiteral" && (property.type !== "TemplateLiteral" || property.expressions.length > 0)) { + return false; + } + return isUncomputedMemberExpressionChain(expression.object); +} +function isValidAmbientConstInitializer(expression, estree) { + var _expression$extra; + const { + type + } = expression; + if ((_expression$extra = expression.extra) != null && _expression$extra.parenthesized) { + return false; + } + if (estree) { + if (type === "Literal") { + const { + value + } = expression; + if (typeof value === "string" || typeof value === "boolean") { + return true; + } + } + } else { + if (type === "StringLiteral" || type === "BooleanLiteral") { + return true; + } + } + if (isNumber(expression, estree) || isNegativeNumber(expression, estree)) { + return true; + } + if (type === "TemplateLiteral" && expression.expressions.length === 0) { + return true; + } + if (isPossiblyLiteralEnum(expression)) { + return true; + } + return false; +} +function isNumber(expression, estree) { + if (estree) { + return expression.type === "Literal" && (typeof expression.value === "number" || "bigint" in expression); + } + return expression.type === "NumericLiteral" || expression.type === "BigIntLiteral"; +} +function isNegativeNumber(expression, estree) { + if (expression.type === "UnaryExpression") { + const { + operator, + argument + } = expression; + if (operator === "-" && isNumber(argument, estree)) { + return true; + } + } + return false; +} +function isUncomputedMemberExpressionChain(expression) { + if (expression.type === "Identifier") return true; + if (expression.type !== "MemberExpression" || expression.computed) { + return false; + } + return isUncomputedMemberExpressionChain(expression.object); +} +const PlaceholderErrors = ParseErrorEnum`placeholders`({ + ClassNameIsRequired: "A class name is required.", + UnexpectedSpace: "Unexpected space in placeholder." +}); +var placeholders = superClass => class PlaceholdersParserMixin extends superClass { + parsePlaceholder(expectedNode) { + if (this.match(133)) { + const node = this.startNode(); + this.next(); + this.assertNoSpace(); + node.name = super.parseIdentifier(true); + this.assertNoSpace(); + this.expect(133); + return this.finishPlaceholder(node, expectedNode); + } + } + finishPlaceholder(node, expectedNode) { + let placeholder = node; + if (!placeholder.expectedNode || !placeholder.type) { + placeholder = this.finishNode(placeholder, "Placeholder"); + } + placeholder.expectedNode = expectedNode; + return placeholder; + } + getTokenFromCode(code) { + if (code === 37 && this.input.charCodeAt(this.state.pos + 1) === 37) { + this.finishOp(133, 2); + } else { + super.getTokenFromCode(code); + } + } + parseExprAtom(refExpressionErrors) { + return this.parsePlaceholder("Expression") || super.parseExprAtom(refExpressionErrors); + } + parseIdentifier(liberal) { + return this.parsePlaceholder("Identifier") || super.parseIdentifier(liberal); + } + checkReservedWord(word, startLoc, checkKeywords, isBinding) { + if (word !== undefined) { + super.checkReservedWord(word, startLoc, checkKeywords, isBinding); + } + } + cloneIdentifier(node) { + const cloned = super.cloneIdentifier(node); + if (cloned.type === "Placeholder") { + cloned.expectedNode = node.expectedNode; + } + return cloned; + } + cloneStringLiteral(node) { + if (node.type === "Placeholder") { + return this.cloneIdentifier(node); + } + return super.cloneStringLiteral(node); + } + parseBindingAtom() { + return this.parsePlaceholder("Pattern") || super.parseBindingAtom(); + } + isValidLVal(type, disallowCallExpression, isParenthesized, binding) { + return type === "Placeholder" || super.isValidLVal(type, disallowCallExpression, isParenthesized, binding); + } + toAssignable(node, isLHS) { + if (node && node.type === "Placeholder" && node.expectedNode === "Expression") { + node.expectedNode = "Pattern"; + } else { + super.toAssignable(node, isLHS); + } + } + chStartsBindingIdentifier(ch, pos) { + if (super.chStartsBindingIdentifier(ch, pos)) { + return true; + } + const next = this.nextTokenStart(); + if (this.input.charCodeAt(next) === 37 && this.input.charCodeAt(next + 1) === 37) { + return true; + } + return false; + } + verifyBreakContinue(node, isBreak) { + var _node$label; + if (((_node$label = node.label) == null ? void 0 : _node$label.type) === "Placeholder") return; + super.verifyBreakContinue(node, isBreak); + } + parseExpressionStatement(node, expr) { + var _expr$extra; + if (expr.type !== "Placeholder" || (_expr$extra = expr.extra) != null && _expr$extra.parenthesized) { + return super.parseExpressionStatement(node, expr); + } + if (this.match(14)) { + const stmt = node; + stmt.label = this.finishPlaceholder(expr, "Identifier"); + this.next(); + stmt.body = super.parseStatementOrSloppyAnnexBFunctionDeclaration(); + return this.finishNode(stmt, "LabeledStatement"); + } + this.semicolon(); + const stmtPlaceholder = node; + stmtPlaceholder.name = expr.name; + return this.finishPlaceholder(stmtPlaceholder, "Statement"); + } + parseBlock(allowDirectives, createNewLexicalScope, afterBlockParse) { + return this.parsePlaceholder("BlockStatement") || super.parseBlock(allowDirectives, createNewLexicalScope, afterBlockParse); + } + parseFunctionId(requireId) { + return this.parsePlaceholder("Identifier") || super.parseFunctionId(requireId); + } + parseClass(node, isStatement, optionalId) { + const type = isStatement ? "ClassDeclaration" : "ClassExpression"; + this.next(); + const oldStrict = this.state.strict; + const placeholder = this.parsePlaceholder("Identifier"); + if (placeholder) { + if (this.match(81) || this.match(133) || this.match(5)) { + node.id = placeholder; + } else if (optionalId || !isStatement) { + node.id = null; + node.body = this.finishPlaceholder(placeholder, "ClassBody"); + return this.finishNode(node, type); + } else { + throw this.raise(PlaceholderErrors.ClassNameIsRequired, this.state.startLoc); + } + } else { + this.parseClassId(node, isStatement, optionalId); + } + super.parseClassSuper(node); + node.body = this.parsePlaceholder("ClassBody") || super.parseClassBody(!!node.superClass, oldStrict); + return this.finishNode(node, type); + } + parseExport(node, decorators) { + const placeholder = this.parsePlaceholder("Identifier"); + if (!placeholder) return super.parseExport(node, decorators); + const node2 = node; + if (!this.isContextual(98) && !this.match(12)) { + node2.specifiers = []; + node2.source = null; + node2.declaration = this.finishPlaceholder(placeholder, "Declaration"); + return this.finishNode(node2, "ExportNamedDeclaration"); + } + this.expectPlugin("exportDefaultFrom"); + const specifier = this.startNode(); + specifier.exported = placeholder; + node2.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")]; + return super.parseExport(node2, decorators); + } + isExportDefaultSpecifier() { + if (this.match(65)) { + const next = this.nextTokenStart(); + if (this.isUnparsedContextual(next, "from")) { + if (this.input.startsWith(tokenLabelName(133), this.nextTokenStartSince(next + 4))) { + return true; + } + } + } + return super.isExportDefaultSpecifier(); + } + maybeParseExportDefaultSpecifier(node, maybeDefaultIdentifier) { + var _specifiers; + if ((_specifiers = node.specifiers) != null && _specifiers.length) { + return true; + } + return super.maybeParseExportDefaultSpecifier(node, maybeDefaultIdentifier); + } + checkExport(node) { + const { + specifiers + } = node; + if (specifiers != null && specifiers.length) { + node.specifiers = specifiers.filter(node => node.exported.type === "Placeholder"); + } + super.checkExport(node); + node.specifiers = specifiers; + } + parseImport(node) { + const placeholder = this.parsePlaceholder("Identifier"); + if (!placeholder) return super.parseImport(node); + node.specifiers = []; + if (!this.isContextual(98) && !this.match(12)) { + node.source = this.finishPlaceholder(placeholder, "StringLiteral"); + this.semicolon(); + return this.finishNode(node, "ImportDeclaration"); + } + const specifier = this.startNodeAtNode(placeholder); + specifier.local = placeholder; + node.specifiers.push(this.finishNode(specifier, "ImportDefaultSpecifier")); + if (this.eat(12)) { + const hasStarImport = this.maybeParseStarImportSpecifier(node); + if (!hasStarImport) this.parseNamedImportSpecifiers(node); + } + this.expectContextual(98); + node.source = this.parseImportSource(); + this.semicolon(); + return this.finishNode(node, "ImportDeclaration"); + } + parseImportSource() { + return this.parsePlaceholder("StringLiteral") || super.parseImportSource(); + } + assertNoSpace() { + if (this.state.start > this.offsetToSourcePos(this.state.lastTokEndLoc.index)) { + this.raise(PlaceholderErrors.UnexpectedSpace, this.state.lastTokEndLoc); + } + } +}; +var v8intrinsic = superClass => class V8IntrinsicMixin extends superClass { + parseV8Intrinsic() { + if (this.match(54)) { + const v8IntrinsicStartLoc = this.state.startLoc; + const node = this.startNode(); + this.next(); + if (tokenIsIdentifier(this.state.type)) { + const name = this.parseIdentifierName(); + const identifier = this.createIdentifier(node, name); + this.castNodeTo(identifier, "V8IntrinsicIdentifier"); + if (this.match(10)) { + return identifier; + } + } + this.unexpected(v8IntrinsicStartLoc); + } + } + parseExprAtom(refExpressionErrors) { + return this.parseV8Intrinsic() || super.parseExprAtom(refExpressionErrors); + } +}; +const PIPELINE_PROPOSALS = ["minimal", "fsharp", "hack", "smart"]; +const TOPIC_TOKENS = ["^^", "@@", "^", "%", "#"]; +function validatePlugins(pluginsMap) { + if (pluginsMap.has("decorators")) { + if (pluginsMap.has("decorators-legacy")) { + throw new Error("Cannot use the decorators and decorators-legacy plugin together"); + } + const decoratorsBeforeExport = pluginsMap.get("decorators").decoratorsBeforeExport; + if (decoratorsBeforeExport != null && typeof decoratorsBeforeExport !== "boolean") { + throw new Error("'decoratorsBeforeExport' must be a boolean, if specified."); + } + const allowCallParenthesized = pluginsMap.get("decorators").allowCallParenthesized; + if (allowCallParenthesized != null && typeof allowCallParenthesized !== "boolean") { + throw new Error("'allowCallParenthesized' must be a boolean."); + } + } + if (pluginsMap.has("flow") && pluginsMap.has("typescript")) { + throw new Error("Cannot combine flow and typescript plugins."); + } + if (pluginsMap.has("placeholders") && pluginsMap.has("v8intrinsic")) { + throw new Error("Cannot combine placeholders and v8intrinsic plugins."); + } + if (pluginsMap.has("pipelineOperator")) { + var _pluginsMap$get2; + const proposal = pluginsMap.get("pipelineOperator").proposal; + if (!PIPELINE_PROPOSALS.includes(proposal)) { + const proposalList = PIPELINE_PROPOSALS.map(p => `"${p}"`).join(", "); + throw new Error(`"pipelineOperator" requires "proposal" option whose value must be one of: ${proposalList}.`); + } + if (proposal === "hack") { + var _pluginsMap$get; + if (pluginsMap.has("placeholders")) { + throw new Error("Cannot combine placeholders plugin and Hack-style pipes."); + } + if (pluginsMap.has("v8intrinsic")) { + throw new Error("Cannot combine v8intrinsic plugin and Hack-style pipes."); + } + const topicToken = pluginsMap.get("pipelineOperator").topicToken; + if (!TOPIC_TOKENS.includes(topicToken)) { + const tokenList = TOPIC_TOKENS.map(t => `"${t}"`).join(", "); + throw new Error(`"pipelineOperator" in "proposal": "hack" mode also requires a "topicToken" option whose value must be one of: ${tokenList}.`); + } + if (topicToken === "#" && ((_pluginsMap$get = pluginsMap.get("recordAndTuple")) == null ? void 0 : _pluginsMap$get.syntaxType) === "hash") { + throw new Error(`Plugin conflict between \`["pipelineOperator", { proposal: "hack", topicToken: "#" }]\` and \`${JSON.stringify(["recordAndTuple", pluginsMap.get("recordAndTuple")])}\`.`); + } + } else if (proposal === "smart" && ((_pluginsMap$get2 = pluginsMap.get("recordAndTuple")) == null ? void 0 : _pluginsMap$get2.syntaxType) === "hash") { + throw new Error(`Plugin conflict between \`["pipelineOperator", { proposal: "smart" }]\` and \`${JSON.stringify(["recordAndTuple", pluginsMap.get("recordAndTuple")])}\`.`); + } + } + if (pluginsMap.has("moduleAttributes")) { + if (pluginsMap.has("deprecatedImportAssert") || pluginsMap.has("importAssertions")) { + throw new Error("Cannot combine importAssertions, deprecatedImportAssert and moduleAttributes plugins."); + } + const moduleAttributesVersionPluginOption = pluginsMap.get("moduleAttributes").version; + if (moduleAttributesVersionPluginOption !== "may-2020") { + throw new Error("The 'moduleAttributes' plugin requires a 'version' option," + " representing the last proposal update. Currently, the" + " only supported value is 'may-2020'."); + } + } + if (pluginsMap.has("importAssertions")) { + if (pluginsMap.has("deprecatedImportAssert")) { + throw new Error("Cannot combine importAssertions and deprecatedImportAssert plugins."); + } + } + if (pluginsMap.has("deprecatedImportAssert")) ;else if (pluginsMap.has("importAttributes") && pluginsMap.get("importAttributes").deprecatedAssertSyntax) { + pluginsMap.set("deprecatedImportAssert", {}); + } + if (pluginsMap.has("recordAndTuple")) { + const syntaxType = pluginsMap.get("recordAndTuple").syntaxType; + if (syntaxType != null) { + const RECORD_AND_TUPLE_SYNTAX_TYPES = ["hash", "bar"]; + if (!RECORD_AND_TUPLE_SYNTAX_TYPES.includes(syntaxType)) { + throw new Error("The 'syntaxType' option of the 'recordAndTuple' plugin must be one of: " + RECORD_AND_TUPLE_SYNTAX_TYPES.map(p => `'${p}'`).join(", ")); + } + } + } + if (pluginsMap.has("asyncDoExpressions") && !pluginsMap.has("doExpressions")) { + const error = new Error("'asyncDoExpressions' requires 'doExpressions', please add 'doExpressions' to parser plugins."); + error.missingPlugins = "doExpressions"; + throw error; + } + if (pluginsMap.has("optionalChainingAssign") && pluginsMap.get("optionalChainingAssign").version !== "2023-07") { + throw new Error("The 'optionalChainingAssign' plugin requires a 'version' option," + " representing the last proposal update. Currently, the" + " only supported value is '2023-07'."); + } + if (pluginsMap.has("discardBinding") && pluginsMap.get("discardBinding").syntaxType !== "void") { + throw new Error("The 'discardBinding' plugin requires a 'syntaxType' option. Currently the only supported value is 'void'."); + } +} +const mixinPlugins = { + estree, + jsx, + flow, + typescript, + v8intrinsic, + placeholders +}; +const mixinPluginNames = Object.keys(mixinPlugins); +class ExpressionParser extends LValParser { + checkProto(prop, isRecord, sawProto, refExpressionErrors) { + if (prop.type === "SpreadElement" || this.isObjectMethod(prop) || prop.computed || prop.shorthand) { + return sawProto; + } + const key = prop.key; + const name = key.type === "Identifier" ? key.name : key.value; + if (name === "__proto__") { + if (isRecord) { + this.raise(Errors.RecordNoProto, key); + return true; + } + if (sawProto) { + if (refExpressionErrors) { + if (refExpressionErrors.doubleProtoLoc === null) { + refExpressionErrors.doubleProtoLoc = key.loc.start; + } + } else { + this.raise(Errors.DuplicateProto, key); + } + } + return true; + } + return sawProto; + } + shouldExitDescending(expr, potentialArrowAt) { + return expr.type === "ArrowFunctionExpression" && this.offsetToSourcePos(expr.start) === potentialArrowAt; + } + getExpression() { + this.enterInitialScopes(); + this.nextToken(); + if (this.match(140)) { + throw this.raise(Errors.ParseExpressionEmptyInput, this.state.startLoc); + } + const expr = this.parseExpression(); + if (!this.match(140)) { + throw this.raise(Errors.ParseExpressionExpectsEOF, this.state.startLoc, { + unexpected: this.input.codePointAt(this.state.start) + }); + } + this.finalizeRemainingComments(); + expr.comments = this.comments; + expr.errors = this.state.errors; + if (this.optionFlags & 256) { + expr.tokens = this.tokens; + } + return expr; + } + parseExpression(disallowIn, refExpressionErrors) { + if (disallowIn) { + return this.disallowInAnd(() => this.parseExpressionBase(refExpressionErrors)); + } + return this.allowInAnd(() => this.parseExpressionBase(refExpressionErrors)); + } + parseExpressionBase(refExpressionErrors) { + const startLoc = this.state.startLoc; + const expr = this.parseMaybeAssign(refExpressionErrors); + if (this.match(12)) { + const node = this.startNodeAt(startLoc); + node.expressions = [expr]; + while (this.eat(12)) { + node.expressions.push(this.parseMaybeAssign(refExpressionErrors)); + } + this.toReferencedList(node.expressions); + return this.finishNode(node, "SequenceExpression"); + } + return expr; + } + parseMaybeAssignDisallowIn(refExpressionErrors, afterLeftParse) { + return this.disallowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse)); + } + parseMaybeAssignAllowIn(refExpressionErrors, afterLeftParse) { + return this.allowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse)); + } + setOptionalParametersError(refExpressionErrors) { + refExpressionErrors.optionalParametersLoc = this.state.startLoc; + } + parseMaybeAssign(refExpressionErrors, afterLeftParse) { + const startLoc = this.state.startLoc; + const isYield = this.isContextual(108); + if (isYield) { + if (this.prodParam.hasYield) { + this.next(); + let left = this.parseYield(startLoc); + if (afterLeftParse) { + left = afterLeftParse.call(this, left, startLoc); + } + return left; + } + } + let ownExpressionErrors; + if (refExpressionErrors) { + ownExpressionErrors = false; + } else { + refExpressionErrors = new ExpressionErrors(); + ownExpressionErrors = true; + } + const { + type + } = this.state; + if (type === 10 || tokenIsIdentifier(type)) { + this.state.potentialArrowAt = this.state.start; + } + let left = this.parseMaybeConditional(refExpressionErrors); + if (afterLeftParse) { + left = afterLeftParse.call(this, left, startLoc); + } + if (tokenIsAssignment(this.state.type)) { + const node = this.startNodeAt(startLoc); + const operator = this.state.value; + node.operator = operator; + if (this.match(29)) { + this.toAssignable(left, true); + node.left = left; + const startIndex = startLoc.index; + if (refExpressionErrors.doubleProtoLoc != null && refExpressionErrors.doubleProtoLoc.index >= startIndex) { + refExpressionErrors.doubleProtoLoc = null; + } + if (refExpressionErrors.shorthandAssignLoc != null && refExpressionErrors.shorthandAssignLoc.index >= startIndex) { + refExpressionErrors.shorthandAssignLoc = null; + } + if (refExpressionErrors.privateKeyLoc != null && refExpressionErrors.privateKeyLoc.index >= startIndex) { + this.checkDestructuringPrivate(refExpressionErrors); + refExpressionErrors.privateKeyLoc = null; + } + if (refExpressionErrors.voidPatternLoc != null && refExpressionErrors.voidPatternLoc.index >= startIndex) { + refExpressionErrors.voidPatternLoc = null; + } + } else { + node.left = left; + } + this.next(); + node.right = this.parseMaybeAssign(); + this.checkLVal(left, this.finishNode(node, "AssignmentExpression"), undefined, undefined, undefined, undefined, operator === "||=" || operator === "&&=" || operator === "??="); + return node; + } else if (ownExpressionErrors) { + this.checkExpressionErrors(refExpressionErrors, true); + } + if (isYield) { + const { + type + } = this.state; + const startsExpr = this.hasPlugin("v8intrinsic") ? tokenCanStartExpression(type) : tokenCanStartExpression(type) && !this.match(54); + if (startsExpr && !this.isAmbiguousPrefixOrIdentifier()) { + this.raiseOverwrite(Errors.YieldNotInGeneratorFunction, startLoc); + return this.parseYield(startLoc); + } + } + return left; + } + parseMaybeConditional(refExpressionErrors) { + const startLoc = this.state.startLoc; + const potentialArrowAt = this.state.potentialArrowAt; + const expr = this.parseExprOps(refExpressionErrors); + if (this.shouldExitDescending(expr, potentialArrowAt)) { + return expr; + } + return this.parseConditional(expr, startLoc, refExpressionErrors); + } + parseConditional(expr, startLoc, refExpressionErrors) { + if (this.eat(17)) { + const node = this.startNodeAt(startLoc); + node.test = expr; + node.consequent = this.parseMaybeAssignAllowIn(); + this.expect(14); + node.alternate = this.parseMaybeAssign(); + return this.finishNode(node, "ConditionalExpression"); + } + return expr; + } + parseMaybeUnaryOrPrivate(refExpressionErrors) { + return this.match(139) ? this.parsePrivateName() : this.parseMaybeUnary(refExpressionErrors); + } + parseExprOps(refExpressionErrors) { + const startLoc = this.state.startLoc; + const potentialArrowAt = this.state.potentialArrowAt; + const expr = this.parseMaybeUnaryOrPrivate(refExpressionErrors); + if (this.shouldExitDescending(expr, potentialArrowAt)) { + return expr; + } + return this.parseExprOp(expr, startLoc, -1); + } + parseExprOp(left, leftStartLoc, minPrec) { + if (this.isPrivateName(left)) { + const value = this.getPrivateNameSV(left); + if (minPrec >= tokenOperatorPrecedence(58) || !this.prodParam.hasIn || !this.match(58)) { + this.raise(Errors.PrivateInExpectedIn, left, { + identifierName: value + }); + } + this.classScope.usePrivateName(value, left.loc.start); + } + const op = this.state.type; + if (tokenIsOperator(op) && (this.prodParam.hasIn || !this.match(58))) { + let prec = tokenOperatorPrecedence(op); + if (prec > minPrec) { + if (op === 39) { + this.expectPlugin("pipelineOperator"); + if (this.state.inFSharpPipelineDirectBody) { + return left; + } + this.checkPipelineAtInfixOperator(left, leftStartLoc); + } + const node = this.startNodeAt(leftStartLoc); + node.left = left; + node.operator = this.state.value; + const logical = op === 41 || op === 42; + const coalesce = op === 40; + if (coalesce) { + prec = tokenOperatorPrecedence(42); + } + this.next(); + if (op === 39 && this.hasPlugin(["pipelineOperator", { + proposal: "minimal" + }])) { + if (this.state.type === 96 && this.prodParam.hasAwait) { + throw this.raise(Errors.UnexpectedAwaitAfterPipelineBody, this.state.startLoc); + } + } + node.right = this.parseExprOpRightExpr(op, prec); + const finishedNode = this.finishNode(node, logical || coalesce ? "LogicalExpression" : "BinaryExpression"); + const nextOp = this.state.type; + if (coalesce && (nextOp === 41 || nextOp === 42) || logical && nextOp === 40) { + throw this.raise(Errors.MixingCoalesceWithLogical, this.state.startLoc); + } + return this.parseExprOp(finishedNode, leftStartLoc, minPrec); + } + } + return left; + } + parseExprOpRightExpr(op, prec) { + const startLoc = this.state.startLoc; + switch (op) { + case 39: + switch (this.getPluginOption("pipelineOperator", "proposal")) { + case "hack": + return this.withTopicBindingContext(() => { + return this.parseHackPipeBody(); + }); + case "fsharp": + return this.withSoloAwaitPermittingContext(() => { + return this.parseFSharpPipelineBody(prec); + }); + } + if (this.getPluginOption("pipelineOperator", "proposal") === "smart") { + return this.withTopicBindingContext(() => { + if (this.prodParam.hasYield && this.isContextual(108)) { + throw this.raise(Errors.PipeBodyIsTighter, this.state.startLoc); + } + return this.parseSmartPipelineBodyInStyle(this.parseExprOpBaseRightExpr(op, prec), startLoc); + }); + } + default: + return this.parseExprOpBaseRightExpr(op, prec); + } + } + parseExprOpBaseRightExpr(op, prec) { + const startLoc = this.state.startLoc; + return this.parseExprOp(this.parseMaybeUnaryOrPrivate(), startLoc, tokenIsRightAssociative(op) ? prec - 1 : prec); + } + parseHackPipeBody() { + var _body$extra; + const { + startLoc + } = this.state; + const body = this.parseMaybeAssign(); + const requiredParentheses = UnparenthesizedPipeBodyDescriptions.has(body.type); + if (requiredParentheses && !((_body$extra = body.extra) != null && _body$extra.parenthesized)) { + this.raise(Errors.PipeUnparenthesizedBody, startLoc, { + type: body.type + }); + } + if (!this.topicReferenceWasUsedInCurrentContext()) { + this.raise(Errors.PipeTopicUnused, startLoc); + } + return body; + } + checkExponentialAfterUnary(node) { + if (this.match(57)) { + this.raise(Errors.UnexpectedTokenUnaryExponentiation, node.argument); + } + } + parseMaybeUnary(refExpressionErrors, sawUnary) { + const startLoc = this.state.startLoc; + const isAwait = this.isContextual(96); + if (isAwait && this.recordAwaitIfAllowed()) { + this.next(); + const expr = this.parseAwait(startLoc); + if (!sawUnary) this.checkExponentialAfterUnary(expr); + return expr; + } + const update = this.match(34); + const node = this.startNode(); + if (tokenIsPrefix(this.state.type)) { + node.operator = this.state.value; + node.prefix = true; + if (this.match(72)) { + this.expectPlugin("throwExpressions"); + } + const isDelete = this.match(89); + this.next(); + node.argument = this.parseMaybeUnary(null, true); + this.checkExpressionErrors(refExpressionErrors, true); + if (this.state.strict && isDelete) { + const arg = node.argument; + if (arg.type === "Identifier") { + this.raise(Errors.StrictDelete, node); + } else if (this.hasPropertyAsPrivateName(arg)) { + this.raise(Errors.DeletePrivateField, node); + } + } + if (!update) { + if (!sawUnary) { + this.checkExponentialAfterUnary(node); + } + return this.finishNode(node, "UnaryExpression"); + } + } + const expr = this.parseUpdate(node, update, refExpressionErrors); + if (isAwait) { + const { + type + } = this.state; + const startsExpr = this.hasPlugin("v8intrinsic") ? tokenCanStartExpression(type) : tokenCanStartExpression(type) && !this.match(54); + if (startsExpr && !this.isAmbiguousPrefixOrIdentifier()) { + this.raiseOverwrite(Errors.AwaitNotInAsyncContext, startLoc); + return this.parseAwait(startLoc); + } + } + return expr; + } + parseUpdate(node, update, refExpressionErrors) { + if (update) { + const updateExpressionNode = node; + this.checkLVal(updateExpressionNode.argument, this.finishNode(updateExpressionNode, "UpdateExpression")); + return node; + } + const startLoc = this.state.startLoc; + let expr = this.parseExprSubscripts(refExpressionErrors); + if (this.checkExpressionErrors(refExpressionErrors, false)) return expr; + while (tokenIsPostfix(this.state.type) && !this.canInsertSemicolon()) { + const node = this.startNodeAt(startLoc); + node.operator = this.state.value; + node.prefix = false; + node.argument = expr; + this.next(); + this.checkLVal(expr, expr = this.finishNode(node, "UpdateExpression")); + } + return expr; + } + parseExprSubscripts(refExpressionErrors) { + const startLoc = this.state.startLoc; + const potentialArrowAt = this.state.potentialArrowAt; + const expr = this.parseExprAtom(refExpressionErrors); + if (this.shouldExitDescending(expr, potentialArrowAt)) { + return expr; + } + return this.parseSubscripts(expr, startLoc); + } + parseSubscripts(base, startLoc, noCalls) { + const state = { + optionalChainMember: false, + maybeAsyncArrow: this.atPossibleAsyncArrow(base), + stop: false + }; + do { + base = this.parseSubscript(base, startLoc, noCalls, state); + state.maybeAsyncArrow = false; + } while (!state.stop); + return base; + } + parseSubscript(base, startLoc, noCalls, state) { + const { + type + } = this.state; + if (!noCalls && type === 15) { + return this.parseBind(base, startLoc, noCalls, state); + } else if (tokenIsTemplate(type)) { + return this.parseTaggedTemplateExpression(base, startLoc, state); + } + let optional = false; + if (type === 18) { + if (noCalls) { + this.raise(Errors.OptionalChainingNoNew, this.state.startLoc); + if (this.lookaheadCharCode() === 40) { + return this.stopParseSubscript(base, state); + } + } + state.optionalChainMember = optional = true; + this.next(); + } + if (!noCalls && this.match(10)) { + return this.parseCoverCallAndAsyncArrowHead(base, startLoc, state, optional); + } else { + const computed = this.eat(0); + if (computed || optional || this.eat(16)) { + return this.parseMember(base, startLoc, state, computed, optional); + } else { + return this.stopParseSubscript(base, state); + } + } + } + stopParseSubscript(base, state) { + state.stop = true; + return base; + } + parseMember(base, startLoc, state, computed, optional) { + const node = this.startNodeAt(startLoc); + node.object = base; + node.computed = computed; + if (computed) { + node.property = this.parseExpression(); + this.expect(3); + } else if (this.match(139)) { + if (base.type === "Super") { + this.raise(Errors.SuperPrivateField, startLoc); + } + this.classScope.usePrivateName(this.state.value, this.state.startLoc); + node.property = this.parsePrivateName(); + } else { + node.property = this.parseIdentifier(true); + } + if (state.optionalChainMember) { + node.optional = optional; + return this.finishNode(node, "OptionalMemberExpression"); + } else { + return this.finishNode(node, "MemberExpression"); + } + } + parseBind(base, startLoc, noCalls, state) { + const node = this.startNodeAt(startLoc); + node.object = base; + this.next(); + node.callee = this.parseNoCallExpr(); + state.stop = true; + return this.parseSubscripts(this.finishNode(node, "BindExpression"), startLoc, noCalls); + } + parseCoverCallAndAsyncArrowHead(base, startLoc, state, optional) { + const oldMaybeInArrowParameters = this.state.maybeInArrowParameters; + let refExpressionErrors = null; + this.state.maybeInArrowParameters = true; + this.next(); + const node = this.startNodeAt(startLoc); + node.callee = base; + const { + maybeAsyncArrow, + optionalChainMember + } = state; + if (maybeAsyncArrow) { + this.expressionScope.enter(newAsyncArrowScope()); + refExpressionErrors = new ExpressionErrors(); + } + if (optionalChainMember) { + node.optional = optional; + } + if (optional) { + node.arguments = this.parseCallExpressionArguments(); + } else { + node.arguments = this.parseCallExpressionArguments(base.type !== "Super", node, refExpressionErrors); + } + let finishedNode = this.finishCallExpression(node, optionalChainMember); + if (maybeAsyncArrow && this.shouldParseAsyncArrow() && !optional) { + state.stop = true; + this.checkDestructuringPrivate(refExpressionErrors); + this.expressionScope.validateAsPattern(); + this.expressionScope.exit(); + finishedNode = this.parseAsyncArrowFromCallExpression(this.startNodeAt(startLoc), finishedNode); + } else { + if (maybeAsyncArrow) { + this.checkExpressionErrors(refExpressionErrors, true); + this.expressionScope.exit(); + } + this.toReferencedArguments(finishedNode); + } + this.state.maybeInArrowParameters = oldMaybeInArrowParameters; + return finishedNode; + } + toReferencedArguments(node, isParenthesizedExpr) { + this.toReferencedListDeep(node.arguments, isParenthesizedExpr); + } + parseTaggedTemplateExpression(base, startLoc, state) { + const node = this.startNodeAt(startLoc); + node.tag = base; + node.quasi = this.parseTemplate(true); + if (state.optionalChainMember) { + this.raise(Errors.OptionalChainingNoTemplate, startLoc); + } + return this.finishNode(node, "TaggedTemplateExpression"); + } + atPossibleAsyncArrow(base) { + return base.type === "Identifier" && base.name === "async" && this.state.lastTokEndLoc.index === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && this.offsetToSourcePos(base.start) === this.state.potentialArrowAt; + } + finishCallExpression(node, optional) { + if (node.callee.type === "Import") { + if (node.arguments.length === 0 || node.arguments.length > 2) { + this.raise(Errors.ImportCallArity, node); + } else { + for (const arg of node.arguments) { + if (arg.type === "SpreadElement") { + this.raise(Errors.ImportCallSpreadArgument, arg); + } + } + } + } + return this.finishNode(node, optional ? "OptionalCallExpression" : "CallExpression"); + } + parseCallExpressionArguments(allowPlaceholder, nodeForExtra, refExpressionErrors) { + const elts = []; + let first = true; + const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody; + this.state.inFSharpPipelineDirectBody = false; + while (!this.eat(11)) { + if (first) { + first = false; + } else { + this.expect(12); + if (this.match(11)) { + if (nodeForExtra) { + this.addTrailingCommaExtraToNode(nodeForExtra); + } + this.next(); + break; + } + } + elts.push(this.parseExprListItem(11, false, refExpressionErrors, allowPlaceholder)); + } + this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody; + return elts; + } + shouldParseAsyncArrow() { + return this.match(19) && !this.canInsertSemicolon(); + } + parseAsyncArrowFromCallExpression(node, call) { + var _call$extra; + this.resetPreviousNodeTrailingComments(call); + this.expect(19); + this.parseArrowExpression(node, call.arguments, true, (_call$extra = call.extra) == null ? void 0 : _call$extra.trailingCommaLoc); + if (call.innerComments) { + setInnerComments(node, call.innerComments); + } + if (call.callee.trailingComments) { + setInnerComments(node, call.callee.trailingComments); + } + return node; + } + parseNoCallExpr() { + const startLoc = this.state.startLoc; + return this.parseSubscripts(this.parseExprAtom(), startLoc, true); + } + parseExprAtom(refExpressionErrors) { + let node; + let decorators = null; + const { + type + } = this.state; + switch (type) { + case 79: + return this.parseSuper(); + case 83: + node = this.startNode(); + this.next(); + if (this.match(16)) { + return this.parseImportMetaPropertyOrPhaseCall(node); + } + if (this.match(10)) { + if (this.optionFlags & 512) { + return this.parseImportCall(node); + } else { + return this.finishNode(node, "Import"); + } + } else { + this.raise(Errors.UnsupportedImport, this.state.lastTokStartLoc); + return this.finishNode(node, "Import"); + } + case 78: + node = this.startNode(); + this.next(); + return this.finishNode(node, "ThisExpression"); + case 90: + { + return this.parseDo(this.startNode(), false); + } + case 56: + case 31: + { + this.readRegexp(); + return this.parseRegExpLiteral(this.state.value); + } + case 135: + return this.parseNumericLiteral(this.state.value); + case 136: + return this.parseBigIntLiteral(this.state.value); + case 134: + return this.parseStringLiteral(this.state.value); + case 84: + return this.parseNullLiteral(); + case 85: + return this.parseBooleanLiteral(true); + case 86: + return this.parseBooleanLiteral(false); + case 10: + { + const canBeArrow = this.state.potentialArrowAt === this.state.start; + return this.parseParenAndDistinguishExpression(canBeArrow); + } + case 0: + { + return this.parseArrayLike(3, false, refExpressionErrors); + } + case 5: + { + return this.parseObjectLike(8, false, false, refExpressionErrors); + } + case 68: + return this.parseFunctionOrFunctionSent(); + case 26: + decorators = this.parseDecorators(); + case 80: + return this.parseClass(this.maybeTakeDecorators(decorators, this.startNode()), false); + case 77: + return this.parseNewOrNewTarget(); + case 25: + case 24: + return this.parseTemplate(false); + case 15: + { + node = this.startNode(); + this.next(); + node.object = null; + const callee = node.callee = this.parseNoCallExpr(); + if (callee.type === "MemberExpression") { + return this.finishNode(node, "BindExpression"); + } else { + throw this.raise(Errors.UnsupportedBind, callee); + } + } + case 139: + { + this.raise(Errors.PrivateInExpectedIn, this.state.startLoc, { + identifierName: this.state.value + }); + return this.parsePrivateName(); + } + case 33: + { + return this.parseTopicReferenceThenEqualsSign(54, "%"); + } + case 32: + { + return this.parseTopicReferenceThenEqualsSign(44, "^"); + } + case 37: + case 38: + { + return this.parseTopicReference("hack"); + } + case 44: + case 54: + case 27: + { + const pipeProposal = this.getPluginOption("pipelineOperator", "proposal"); + if (pipeProposal) { + return this.parseTopicReference(pipeProposal); + } + throw this.unexpected(); + } + case 47: + { + const lookaheadCh = this.input.codePointAt(this.nextTokenStart()); + if (isIdentifierStart(lookaheadCh) || lookaheadCh === 62) { + throw this.expectOnePlugin(["jsx", "flow", "typescript"]); + } + throw this.unexpected(); + } + default: + if (type === 137) { + return this.parseDecimalLiteral(this.state.value); + } else if (type === 2 || type === 1) { + return this.parseArrayLike(this.state.type === 2 ? 4 : 3, true); + } else if (type === 6 || type === 7) { + return this.parseObjectLike(this.state.type === 6 ? 9 : 8, false, true); + } + if (tokenIsIdentifier(type)) { + if (this.isContextual(127) && this.lookaheadInLineCharCode() === 123) { + return this.parseModuleExpression(); + } + const canBeArrow = this.state.potentialArrowAt === this.state.start; + const containsEsc = this.state.containsEsc; + const id = this.parseIdentifier(); + if (!containsEsc && id.name === "async" && !this.canInsertSemicolon()) { + const { + type + } = this.state; + if (type === 68) { + this.resetPreviousNodeTrailingComments(id); + this.next(); + return this.parseAsyncFunctionExpression(this.startNodeAtNode(id)); + } else if (tokenIsIdentifier(type)) { + if (canBeArrow && this.lookaheadCharCode() === 61) { + return this.parseAsyncArrowUnaryFunction(this.startNodeAtNode(id)); + } else { + return id; + } + } else if (type === 90) { + this.resetPreviousNodeTrailingComments(id); + return this.parseDo(this.startNodeAtNode(id), true); + } + } + if (canBeArrow && this.match(19) && !this.canInsertSemicolon()) { + this.next(); + return this.parseArrowExpression(this.startNodeAtNode(id), [id], false); + } + return id; + } else { + throw this.unexpected(); + } + } + } + parseTopicReferenceThenEqualsSign(topicTokenType, topicTokenValue) { + const pipeProposal = this.getPluginOption("pipelineOperator", "proposal"); + if (pipeProposal) { + this.state.type = topicTokenType; + this.state.value = topicTokenValue; + this.state.pos--; + this.state.end--; + this.state.endLoc = createPositionWithColumnOffset(this.state.endLoc, -1); + return this.parseTopicReference(pipeProposal); + } + throw this.unexpected(); + } + parseTopicReference(pipeProposal) { + const node = this.startNode(); + const startLoc = this.state.startLoc; + const tokenType = this.state.type; + this.next(); + return this.finishTopicReference(node, startLoc, pipeProposal, tokenType); + } + finishTopicReference(node, startLoc, pipeProposal, tokenType) { + if (this.testTopicReferenceConfiguration(pipeProposal, startLoc, tokenType)) { + if (pipeProposal === "hack") { + if (!this.topicReferenceIsAllowedInCurrentContext()) { + this.raise(Errors.PipeTopicUnbound, startLoc); + } + this.registerTopicReference(); + return this.finishNode(node, "TopicReference"); + } else { + if (!this.topicReferenceIsAllowedInCurrentContext()) { + this.raise(Errors.PrimaryTopicNotAllowed, startLoc); + } + this.registerTopicReference(); + return this.finishNode(node, "PipelinePrimaryTopicReference"); + } + } else { + throw this.raise(Errors.PipeTopicUnconfiguredToken, startLoc, { + token: tokenLabelName(tokenType) + }); + } + } + testTopicReferenceConfiguration(pipeProposal, startLoc, tokenType) { + switch (pipeProposal) { + case "hack": + { + return this.hasPlugin(["pipelineOperator", { + topicToken: tokenLabelName(tokenType) + }]); + } + case "smart": + return tokenType === 27; + default: + throw this.raise(Errors.PipeTopicRequiresHackPipes, startLoc); + } + } + parseAsyncArrowUnaryFunction(node) { + this.prodParam.enter(functionFlags(true, this.prodParam.hasYield)); + const params = [this.parseIdentifier()]; + this.prodParam.exit(); + if (this.hasPrecedingLineBreak()) { + this.raise(Errors.LineTerminatorBeforeArrow, this.state.curPosition()); + } + this.expect(19); + return this.parseArrowExpression(node, params, true); + } + parseDo(node, isAsync) { + this.expectPlugin("doExpressions"); + if (isAsync) { + this.expectPlugin("asyncDoExpressions"); + } + node.async = isAsync; + this.next(); + const oldLabels = this.state.labels; + this.state.labels = []; + if (isAsync) { + this.prodParam.enter(2); + node.body = this.parseBlock(); + this.prodParam.exit(); + } else { + node.body = this.parseBlock(); + } + this.state.labels = oldLabels; + return this.finishNode(node, "DoExpression"); + } + parseSuper() { + const node = this.startNode(); + this.next(); + if (this.match(10) && !this.scope.allowDirectSuper) { + if (!(this.optionFlags & 16)) { + this.raise(Errors.SuperNotAllowed, node); + } + } else if (!this.scope.allowSuper) { + if (!(this.optionFlags & 16)) { + this.raise(Errors.UnexpectedSuper, node); + } + } + if (!this.match(10) && !this.match(0) && !this.match(16)) { + this.raise(Errors.UnsupportedSuper, node); + } + return this.finishNode(node, "Super"); + } + parsePrivateName() { + const node = this.startNode(); + const id = this.startNodeAt(createPositionWithColumnOffset(this.state.startLoc, 1)); + const name = this.state.value; + this.next(); + node.id = this.createIdentifier(id, name); + return this.finishNode(node, "PrivateName"); + } + parseFunctionOrFunctionSent() { + const node = this.startNode(); + this.next(); + if (this.prodParam.hasYield && this.match(16)) { + const meta = this.createIdentifier(this.startNodeAtNode(node), "function"); + this.next(); + if (this.match(103)) { + this.expectPlugin("functionSent"); + } else if (!this.hasPlugin("functionSent")) { + this.unexpected(); + } + return this.parseMetaProperty(node, meta, "sent"); + } + return this.parseFunction(node); + } + parseMetaProperty(node, meta, propertyName) { + node.meta = meta; + const containsEsc = this.state.containsEsc; + node.property = this.parseIdentifier(true); + if (node.property.name !== propertyName || containsEsc) { + this.raise(Errors.UnsupportedMetaProperty, node.property, { + target: meta.name, + onlyValidPropertyName: propertyName + }); + } + return this.finishNode(node, "MetaProperty"); + } + parseImportMetaPropertyOrPhaseCall(node) { + this.next(); + if (this.isContextual(105) || this.isContextual(97)) { + const isSource = this.isContextual(105); + this.expectPlugin(isSource ? "sourcePhaseImports" : "deferredImportEvaluation"); + this.next(); + node.phase = isSource ? "source" : "defer"; + return this.parseImportCall(node); + } else { + const id = this.createIdentifierAt(this.startNodeAtNode(node), "import", this.state.lastTokStartLoc); + if (this.isContextual(101)) { + if (!this.inModule) { + this.raise(Errors.ImportMetaOutsideModule, id); + } + this.sawUnambiguousESM = true; + } + return this.parseMetaProperty(node, id, "meta"); + } + } + parseLiteralAtNode(value, type, node) { + this.addExtra(node, "rawValue", value); + this.addExtra(node, "raw", this.input.slice(this.offsetToSourcePos(node.start), this.state.end)); + node.value = value; + this.next(); + return this.finishNode(node, type); + } + parseLiteral(value, type) { + const node = this.startNode(); + return this.parseLiteralAtNode(value, type, node); + } + parseStringLiteral(value) { + return this.parseLiteral(value, "StringLiteral"); + } + parseNumericLiteral(value) { + return this.parseLiteral(value, "NumericLiteral"); + } + parseBigIntLiteral(value) { + return this.parseLiteral(value, "BigIntLiteral"); + } + parseDecimalLiteral(value) { + return this.parseLiteral(value, "DecimalLiteral"); + } + parseRegExpLiteral(value) { + const node = this.startNode(); + this.addExtra(node, "raw", this.input.slice(this.offsetToSourcePos(node.start), this.state.end)); + node.pattern = value.pattern; + node.flags = value.flags; + this.next(); + return this.finishNode(node, "RegExpLiteral"); + } + parseBooleanLiteral(value) { + const node = this.startNode(); + node.value = value; + this.next(); + return this.finishNode(node, "BooleanLiteral"); + } + parseNullLiteral() { + const node = this.startNode(); + this.next(); + return this.finishNode(node, "NullLiteral"); + } + parseParenAndDistinguishExpression(canBeArrow) { + const startLoc = this.state.startLoc; + let val; + this.next(); + this.expressionScope.enter(newArrowHeadScope()); + const oldMaybeInArrowParameters = this.state.maybeInArrowParameters; + const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody; + this.state.maybeInArrowParameters = true; + this.state.inFSharpPipelineDirectBody = false; + const innerStartLoc = this.state.startLoc; + const exprList = []; + const refExpressionErrors = new ExpressionErrors(); + let first = true; + let spreadStartLoc; + let optionalCommaStartLoc; + while (!this.match(11)) { + if (first) { + first = false; + } else { + this.expect(12, refExpressionErrors.optionalParametersLoc === null ? null : refExpressionErrors.optionalParametersLoc); + if (this.match(11)) { + optionalCommaStartLoc = this.state.startLoc; + break; + } + } + if (this.match(21)) { + const spreadNodeStartLoc = this.state.startLoc; + spreadStartLoc = this.state.startLoc; + exprList.push(this.parseParenItem(this.parseRestBinding(), spreadNodeStartLoc)); + if (!this.checkCommaAfterRest(41)) { + break; + } + } else { + exprList.push(this.parseMaybeAssignAllowInOrVoidPattern(11, refExpressionErrors, this.parseParenItem)); + } + } + const innerEndLoc = this.state.lastTokEndLoc; + this.expect(11); + this.state.maybeInArrowParameters = oldMaybeInArrowParameters; + this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody; + let arrowNode = this.startNodeAt(startLoc); + if (canBeArrow && this.shouldParseArrow(exprList) && (arrowNode = this.parseArrow(arrowNode))) { + this.checkDestructuringPrivate(refExpressionErrors); + this.expressionScope.validateAsPattern(); + this.expressionScope.exit(); + this.parseArrowExpression(arrowNode, exprList, false); + return arrowNode; + } + this.expressionScope.exit(); + if (!exprList.length) { + this.unexpected(this.state.lastTokStartLoc); + } + if (optionalCommaStartLoc) this.unexpected(optionalCommaStartLoc); + if (spreadStartLoc) this.unexpected(spreadStartLoc); + this.checkExpressionErrors(refExpressionErrors, true); + this.toReferencedListDeep(exprList, true); + if (exprList.length > 1) { + val = this.startNodeAt(innerStartLoc); + val.expressions = exprList; + this.finishNode(val, "SequenceExpression"); + this.resetEndLocation(val, innerEndLoc); + } else { + val = exprList[0]; + } + return this.wrapParenthesis(startLoc, val); + } + wrapParenthesis(startLoc, expression) { + if (!(this.optionFlags & 1024)) { + this.addExtra(expression, "parenthesized", true); + this.addExtra(expression, "parenStart", startLoc.index); + this.takeSurroundingComments(expression, startLoc.index, this.state.lastTokEndLoc.index); + return expression; + } + const parenExpression = this.startNodeAt(startLoc); + parenExpression.expression = expression; + return this.finishNode(parenExpression, "ParenthesizedExpression"); + } + shouldParseArrow(params) { + return !this.canInsertSemicolon(); + } + parseArrow(node) { + if (this.eat(19)) { + return node; + } + } + parseParenItem(node, startLoc) { + return node; + } + parseNewOrNewTarget() { + const node = this.startNode(); + this.next(); + if (this.match(16)) { + const meta = this.createIdentifier(this.startNodeAtNode(node), "new"); + this.next(); + const metaProp = this.parseMetaProperty(node, meta, "target"); + if (!this.scope.allowNewTarget) { + this.raise(Errors.UnexpectedNewTarget, metaProp); + } + return metaProp; + } + return this.parseNew(node); + } + parseNew(node) { + this.parseNewCallee(node); + if (this.eat(10)) { + const args = this.parseExprList(11); + this.toReferencedList(args); + node.arguments = args; + } else { + node.arguments = []; + } + return this.finishNode(node, "NewExpression"); + } + parseNewCallee(node) { + const isImport = this.match(83); + const callee = this.parseNoCallExpr(); + node.callee = callee; + if (isImport && (callee.type === "Import" || callee.type === "ImportExpression")) { + this.raise(Errors.ImportCallNotNewExpression, callee); + } + } + parseTemplateElement(isTagged) { + const { + start, + startLoc, + end, + value + } = this.state; + const elemStart = start + 1; + const elem = this.startNodeAt(createPositionWithColumnOffset(startLoc, 1)); + if (value === null) { + if (!isTagged) { + this.raise(Errors.InvalidEscapeSequenceTemplate, createPositionWithColumnOffset(this.state.firstInvalidTemplateEscapePos, 1)); + } + } + const isTail = this.match(24); + const endOffset = isTail ? -1 : -2; + const elemEnd = end + endOffset; + elem.value = { + raw: this.input.slice(elemStart, elemEnd).replace(/\r\n?/g, "\n"), + cooked: value === null ? null : value.slice(1, endOffset) + }; + elem.tail = isTail; + this.next(); + const finishedNode = this.finishNode(elem, "TemplateElement"); + this.resetEndLocation(finishedNode, createPositionWithColumnOffset(this.state.lastTokEndLoc, endOffset)); + return finishedNode; + } + parseTemplate(isTagged) { + const node = this.startNode(); + let curElt = this.parseTemplateElement(isTagged); + const quasis = [curElt]; + const substitutions = []; + while (!curElt.tail) { + substitutions.push(this.parseTemplateSubstitution()); + this.readTemplateContinuation(); + quasis.push(curElt = this.parseTemplateElement(isTagged)); + } + node.expressions = substitutions; + node.quasis = quasis; + return this.finishNode(node, "TemplateLiteral"); + } + parseTemplateSubstitution() { + return this.parseExpression(); + } + parseObjectLike(close, isPattern, isRecord, refExpressionErrors) { + if (isRecord) { + this.expectPlugin("recordAndTuple"); + } + const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody; + this.state.inFSharpPipelineDirectBody = false; + let sawProto = false; + let first = true; + const node = this.startNode(); + node.properties = []; + this.next(); + while (!this.match(close)) { + if (first) { + first = false; + } else { + this.expect(12); + if (this.match(close)) { + this.addTrailingCommaExtraToNode(node); + break; + } + } + let prop; + if (isPattern) { + prop = this.parseBindingProperty(); + } else { + prop = this.parsePropertyDefinition(refExpressionErrors); + sawProto = this.checkProto(prop, isRecord, sawProto, refExpressionErrors); + } + if (isRecord && !this.isObjectProperty(prop) && prop.type !== "SpreadElement") { + this.raise(Errors.InvalidRecordProperty, prop); + } + if (prop.shorthand) { + this.addExtra(prop, "shorthand", true); + } + node.properties.push(prop); + } + this.next(); + this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody; + let type = "ObjectExpression"; + if (isPattern) { + type = "ObjectPattern"; + } else if (isRecord) { + type = "RecordExpression"; + } + return this.finishNode(node, type); + } + addTrailingCommaExtraToNode(node) { + this.addExtra(node, "trailingComma", this.state.lastTokStartLoc.index); + this.addExtra(node, "trailingCommaLoc", this.state.lastTokStartLoc, false); + } + maybeAsyncOrAccessorProp(prop) { + return !prop.computed && prop.key.type === "Identifier" && (this.isLiteralPropertyName() || this.match(0) || this.match(55)); + } + parsePropertyDefinition(refExpressionErrors) { + let decorators = []; + if (this.match(26)) { + if (this.hasPlugin("decorators")) { + this.raise(Errors.UnsupportedPropertyDecorator, this.state.startLoc); + } + while (this.match(26)) { + decorators.push(this.parseDecorator()); + } + } + const prop = this.startNode(); + let isAsync = false; + let isAccessor = false; + let startLoc; + if (this.match(21)) { + if (decorators.length) this.unexpected(); + return this.parseSpread(); + } + if (decorators.length) { + prop.decorators = decorators; + decorators = []; + } + prop.method = false; + if (refExpressionErrors) { + startLoc = this.state.startLoc; + } + let isGenerator = this.eat(55); + this.parsePropertyNamePrefixOperator(prop); + const containsEsc = this.state.containsEsc; + this.parsePropertyName(prop, refExpressionErrors); + if (!isGenerator && !containsEsc && this.maybeAsyncOrAccessorProp(prop)) { + const { + key + } = prop; + const keyName = key.name; + if (keyName === "async" && !this.hasPrecedingLineBreak()) { + isAsync = true; + this.resetPreviousNodeTrailingComments(key); + isGenerator = this.eat(55); + this.parsePropertyName(prop); + } + if (keyName === "get" || keyName === "set") { + isAccessor = true; + this.resetPreviousNodeTrailingComments(key); + prop.kind = keyName; + if (this.match(55)) { + isGenerator = true; + this.raise(Errors.AccessorIsGenerator, this.state.curPosition(), { + kind: keyName + }); + this.next(); + } + this.parsePropertyName(prop); + } + } + return this.parseObjPropValue(prop, startLoc, isGenerator, isAsync, false, isAccessor, refExpressionErrors); + } + getGetterSetterExpectedParamCount(method) { + return method.kind === "get" ? 0 : 1; + } + getObjectOrClassMethodParams(method) { + return method.params; + } + checkGetterSetterParams(method) { + var _params; + const paramCount = this.getGetterSetterExpectedParamCount(method); + const params = this.getObjectOrClassMethodParams(method); + if (params.length !== paramCount) { + this.raise(method.kind === "get" ? Errors.BadGetterArity : Errors.BadSetterArity, method); + } + if (method.kind === "set" && ((_params = params[params.length - 1]) == null ? void 0 : _params.type) === "RestElement") { + this.raise(Errors.BadSetterRestParameter, method); + } + } + parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) { + if (isAccessor) { + const finishedProp = this.parseMethod(prop, isGenerator, false, false, false, "ObjectMethod"); + this.checkGetterSetterParams(finishedProp); + return finishedProp; + } + if (isAsync || isGenerator || this.match(10)) { + if (isPattern) this.unexpected(); + prop.kind = "method"; + prop.method = true; + return this.parseMethod(prop, isGenerator, isAsync, false, false, "ObjectMethod"); + } + } + parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors) { + prop.shorthand = false; + if (this.eat(14)) { + prop.value = isPattern ? this.parseMaybeDefault(this.state.startLoc) : this.parseMaybeAssignAllowInOrVoidPattern(8, refExpressionErrors); + return this.finishObjectProperty(prop); + } + if (!prop.computed && prop.key.type === "Identifier") { + this.checkReservedWord(prop.key.name, prop.key.loc.start, true, false); + if (isPattern) { + prop.value = this.parseMaybeDefault(startLoc, this.cloneIdentifier(prop.key)); + } else if (this.match(29)) { + const shorthandAssignLoc = this.state.startLoc; + if (refExpressionErrors != null) { + if (refExpressionErrors.shorthandAssignLoc === null) { + refExpressionErrors.shorthandAssignLoc = shorthandAssignLoc; + } + } else { + this.raise(Errors.InvalidCoverInitializedName, shorthandAssignLoc); + } + prop.value = this.parseMaybeDefault(startLoc, this.cloneIdentifier(prop.key)); + } else { + prop.value = this.cloneIdentifier(prop.key); + } + prop.shorthand = true; + return this.finishObjectProperty(prop); + } + } + finishObjectProperty(node) { + return this.finishNode(node, "ObjectProperty"); + } + parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) { + const node = this.parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) || this.parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors); + if (!node) this.unexpected(); + return node; + } + parsePropertyName(prop, refExpressionErrors) { + if (this.eat(0)) { + prop.computed = true; + prop.key = this.parseMaybeAssignAllowIn(); + this.expect(3); + } else { + const { + type, + value + } = this.state; + let key; + if (tokenIsKeywordOrIdentifier(type)) { + key = this.parseIdentifier(true); + } else { + switch (type) { + case 135: + key = this.parseNumericLiteral(value); + break; + case 134: + key = this.parseStringLiteral(value); + break; + case 136: + key = this.parseBigIntLiteral(value); + break; + case 139: + { + const privateKeyLoc = this.state.startLoc; + if (refExpressionErrors != null) { + if (refExpressionErrors.privateKeyLoc === null) { + refExpressionErrors.privateKeyLoc = privateKeyLoc; + } + } else { + this.raise(Errors.UnexpectedPrivateField, privateKeyLoc); + } + key = this.parsePrivateName(); + break; + } + default: + if (type === 137) { + key = this.parseDecimalLiteral(value); + break; + } + this.unexpected(); + } + } + prop.key = key; + if (type !== 139) { + prop.computed = false; + } + } + } + initFunction(node, isAsync) { + node.id = null; + node.generator = false; + node.async = isAsync; + } + parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) { + this.initFunction(node, isAsync); + node.generator = isGenerator; + this.scope.enter(514 | 16 | (inClassScope ? 576 : 0) | (allowDirectSuper ? 32 : 0)); + this.prodParam.enter(functionFlags(isAsync, node.generator)); + this.parseFunctionParams(node, isConstructor); + const finishedNode = this.parseFunctionBodyAndFinish(node, type, true); + this.prodParam.exit(); + this.scope.exit(); + return finishedNode; + } + parseArrayLike(close, isTuple, refExpressionErrors) { + if (isTuple) { + this.expectPlugin("recordAndTuple"); + } + const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody; + this.state.inFSharpPipelineDirectBody = false; + const node = this.startNode(); + this.next(); + node.elements = this.parseExprList(close, !isTuple, refExpressionErrors, node); + this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody; + return this.finishNode(node, isTuple ? "TupleExpression" : "ArrayExpression"); + } + parseArrowExpression(node, params, isAsync, trailingCommaLoc) { + this.scope.enter(514 | 4); + let flags = functionFlags(isAsync, false); + if (!this.match(5) && this.prodParam.hasIn) { + flags |= 8; + } + this.prodParam.enter(flags); + this.initFunction(node, isAsync); + const oldMaybeInArrowParameters = this.state.maybeInArrowParameters; + if (params) { + this.state.maybeInArrowParameters = true; + this.setArrowFunctionParameters(node, params, trailingCommaLoc); + } + this.state.maybeInArrowParameters = false; + this.parseFunctionBody(node, true); + this.prodParam.exit(); + this.scope.exit(); + this.state.maybeInArrowParameters = oldMaybeInArrowParameters; + return this.finishNode(node, "ArrowFunctionExpression"); + } + setArrowFunctionParameters(node, params, trailingCommaLoc) { + this.toAssignableList(params, trailingCommaLoc, false); + node.params = params; + } + parseFunctionBodyAndFinish(node, type, isMethod = false) { + this.parseFunctionBody(node, false, isMethod); + return this.finishNode(node, type); + } + parseFunctionBody(node, allowExpression, isMethod = false) { + const isExpression = allowExpression && !this.match(5); + this.expressionScope.enter(newExpressionScope()); + if (isExpression) { + node.body = this.parseMaybeAssign(); + this.checkParams(node, false, allowExpression, false); + } else { + const oldStrict = this.state.strict; + const oldLabels = this.state.labels; + this.state.labels = []; + this.prodParam.enter(this.prodParam.currentFlags() | 4); + node.body = this.parseBlock(true, false, hasStrictModeDirective => { + const nonSimple = !this.isSimpleParamList(node.params); + if (hasStrictModeDirective && nonSimple) { + this.raise(Errors.IllegalLanguageModeDirective, (node.kind === "method" || node.kind === "constructor") && !!node.key ? node.key.loc.end : node); + } + const strictModeChanged = !oldStrict && this.state.strict; + this.checkParams(node, !this.state.strict && !allowExpression && !isMethod && !nonSimple, allowExpression, strictModeChanged); + if (this.state.strict && node.id) { + this.checkIdentifier(node.id, 65, strictModeChanged); + } + }); + this.prodParam.exit(); + this.state.labels = oldLabels; + } + this.expressionScope.exit(); + } + isSimpleParameter(node) { + return node.type === "Identifier"; + } + isSimpleParamList(params) { + for (let i = 0, len = params.length; i < len; i++) { + if (!this.isSimpleParameter(params[i])) return false; + } + return true; + } + checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged = true) { + const checkClashes = !allowDuplicates && new Set(); + const formalParameters = { + type: "FormalParameters" + }; + for (const param of node.params) { + this.checkLVal(param, formalParameters, 5, checkClashes, strictModeChanged); + } + } + parseExprList(close, allowEmpty, refExpressionErrors, nodeForExtra) { + const elts = []; + let first = true; + while (!this.eat(close)) { + if (first) { + first = false; + } else { + this.expect(12); + if (this.match(close)) { + if (nodeForExtra) { + this.addTrailingCommaExtraToNode(nodeForExtra); + } + this.next(); + break; + } + } + elts.push(this.parseExprListItem(close, allowEmpty, refExpressionErrors)); + } + return elts; + } + parseExprListItem(close, allowEmpty, refExpressionErrors, allowPlaceholder) { + let elt; + if (this.match(12)) { + if (!allowEmpty) { + this.raise(Errors.UnexpectedToken, this.state.curPosition(), { + unexpected: "," + }); + } + elt = null; + } else if (this.match(21)) { + const spreadNodeStartLoc = this.state.startLoc; + elt = this.parseParenItem(this.parseSpread(refExpressionErrors), spreadNodeStartLoc); + } else if (this.match(17)) { + this.expectPlugin("partialApplication"); + if (!allowPlaceholder) { + this.raise(Errors.UnexpectedArgumentPlaceholder, this.state.startLoc); + } + const node = this.startNode(); + this.next(); + elt = this.finishNode(node, "ArgumentPlaceholder"); + } else { + elt = this.parseMaybeAssignAllowInOrVoidPattern(close, refExpressionErrors, this.parseParenItem); + } + return elt; + } + parseIdentifier(liberal) { + const node = this.startNode(); + const name = this.parseIdentifierName(liberal); + return this.createIdentifier(node, name); + } + createIdentifier(node, name) { + node.name = name; + node.loc.identifierName = name; + return this.finishNode(node, "Identifier"); + } + createIdentifierAt(node, name, endLoc) { + node.name = name; + node.loc.identifierName = name; + return this.finishNodeAt(node, "Identifier", endLoc); + } + parseIdentifierName(liberal) { + let name; + const { + startLoc, + type + } = this.state; + if (tokenIsKeywordOrIdentifier(type)) { + name = this.state.value; + } else { + this.unexpected(); + } + const tokenIsKeyword = tokenKeywordOrIdentifierIsKeyword(type); + if (liberal) { + if (tokenIsKeyword) { + this.replaceToken(132); + } + } else { + this.checkReservedWord(name, startLoc, tokenIsKeyword, false); + } + this.next(); + return name; + } + checkReservedWord(word, startLoc, checkKeywords, isBinding) { + if (word.length > 10) { + return; + } + if (!canBeReservedWord(word)) { + return; + } + if (checkKeywords && isKeyword(word)) { + this.raise(Errors.UnexpectedKeyword, startLoc, { + keyword: word + }); + return; + } + const reservedTest = !this.state.strict ? isReservedWord : isBinding ? isStrictBindReservedWord : isStrictReservedWord; + if (reservedTest(word, this.inModule)) { + this.raise(Errors.UnexpectedReservedWord, startLoc, { + reservedWord: word + }); + return; + } else if (word === "yield") { + if (this.prodParam.hasYield) { + this.raise(Errors.YieldBindingIdentifier, startLoc); + return; + } + } else if (word === "await") { + if (this.prodParam.hasAwait) { + this.raise(Errors.AwaitBindingIdentifier, startLoc); + return; + } + if (this.scope.inStaticBlock) { + this.raise(Errors.AwaitBindingIdentifierInStaticBlock, startLoc); + return; + } + this.expressionScope.recordAsyncArrowParametersError(startLoc); + } else if (word === "arguments") { + if (this.scope.inClassAndNotInNonArrowFunction) { + this.raise(Errors.ArgumentsInClass, startLoc); + return; + } + } + } + recordAwaitIfAllowed() { + const isAwaitAllowed = this.prodParam.hasAwait; + if (isAwaitAllowed && !this.scope.inFunction) { + this.state.hasTopLevelAwait = true; + } + return isAwaitAllowed; + } + parseAwait(startLoc) { + const node = this.startNodeAt(startLoc); + this.expressionScope.recordParameterInitializerError(Errors.AwaitExpressionFormalParameter, node); + if (this.eat(55)) { + this.raise(Errors.ObsoleteAwaitStar, node); + } + if (!this.scope.inFunction && !(this.optionFlags & 1)) { + if (this.isAmbiguousPrefixOrIdentifier()) { + this.ambiguousScriptDifferentAst = true; + } else { + this.sawUnambiguousESM = true; + } + } + if (!this.state.soloAwait) { + node.argument = this.parseMaybeUnary(null, true); + } + return this.finishNode(node, "AwaitExpression"); + } + isAmbiguousPrefixOrIdentifier() { + if (this.hasPrecedingLineBreak()) return true; + const { + type + } = this.state; + return type === 53 || type === 10 || type === 0 || tokenIsTemplate(type) || type === 102 && !this.state.containsEsc || type === 138 || type === 56 || this.hasPlugin("v8intrinsic") && type === 54; + } + parseYield(startLoc) { + const node = this.startNodeAt(startLoc); + this.expressionScope.recordParameterInitializerError(Errors.YieldInParameter, node); + let delegating = false; + let argument = null; + if (!this.hasPrecedingLineBreak()) { + delegating = this.eat(55); + switch (this.state.type) { + case 13: + case 140: + case 8: + case 11: + case 3: + case 9: + case 14: + case 12: + if (!delegating) break; + default: + argument = this.parseMaybeAssign(); + } + } + node.delegate = delegating; + node.argument = argument; + return this.finishNode(node, "YieldExpression"); + } + parseImportCall(node) { + this.next(); + node.source = this.parseMaybeAssignAllowIn(); + node.options = null; + if (this.eat(12)) { + if (!this.match(11)) { + node.options = this.parseMaybeAssignAllowIn(); + if (this.eat(12)) { + this.addTrailingCommaExtraToNode(node.options); + if (!this.match(11)) { + do { + this.parseMaybeAssignAllowIn(); + } while (this.eat(12) && !this.match(11)); + this.raise(Errors.ImportCallArity, node); + } + } + } else { + this.addTrailingCommaExtraToNode(node.source); + } + } + this.expect(11); + return this.finishNode(node, "ImportExpression"); + } + checkPipelineAtInfixOperator(left, leftStartLoc) { + if (this.hasPlugin(["pipelineOperator", { + proposal: "smart" + }])) { + if (left.type === "SequenceExpression") { + this.raise(Errors.PipelineHeadSequenceExpression, leftStartLoc); + } + } + } + parseSmartPipelineBodyInStyle(childExpr, startLoc) { + if (this.isSimpleReference(childExpr)) { + const bodyNode = this.startNodeAt(startLoc); + bodyNode.callee = childExpr; + return this.finishNode(bodyNode, "PipelineBareFunction"); + } else { + const bodyNode = this.startNodeAt(startLoc); + this.checkSmartPipeTopicBodyEarlyErrors(startLoc); + bodyNode.expression = childExpr; + return this.finishNode(bodyNode, "PipelineTopicExpression"); + } + } + isSimpleReference(expression) { + switch (expression.type) { + case "MemberExpression": + return !expression.computed && this.isSimpleReference(expression.object); + case "Identifier": + return true; + default: + return false; + } + } + checkSmartPipeTopicBodyEarlyErrors(startLoc) { + if (this.match(19)) { + throw this.raise(Errors.PipelineBodyNoArrow, this.state.startLoc); + } + if (!this.topicReferenceWasUsedInCurrentContext()) { + this.raise(Errors.PipelineTopicUnused, startLoc); + } + } + withTopicBindingContext(callback) { + const outerContextTopicState = this.state.topicContext; + this.state.topicContext = { + maxNumOfResolvableTopics: 1, + maxTopicIndex: null + }; + try { + return callback(); + } finally { + this.state.topicContext = outerContextTopicState; + } + } + withSmartMixTopicForbiddingContext(callback) { + if (this.hasPlugin(["pipelineOperator", { + proposal: "smart" + }])) { + const outerContextTopicState = this.state.topicContext; + this.state.topicContext = { + maxNumOfResolvableTopics: 0, + maxTopicIndex: null + }; + try { + return callback(); + } finally { + this.state.topicContext = outerContextTopicState; + } + } else { + return callback(); + } + } + withSoloAwaitPermittingContext(callback) { + const outerContextSoloAwaitState = this.state.soloAwait; + this.state.soloAwait = true; + try { + return callback(); + } finally { + this.state.soloAwait = outerContextSoloAwaitState; + } + } + allowInAnd(callback) { + const flags = this.prodParam.currentFlags(); + const prodParamToSet = 8 & ~flags; + if (prodParamToSet) { + this.prodParam.enter(flags | 8); + try { + return callback(); + } finally { + this.prodParam.exit(); + } + } + return callback(); + } + disallowInAnd(callback) { + const flags = this.prodParam.currentFlags(); + const prodParamToClear = 8 & flags; + if (prodParamToClear) { + this.prodParam.enter(flags & ~8); + try { + return callback(); + } finally { + this.prodParam.exit(); + } + } + return callback(); + } + registerTopicReference() { + this.state.topicContext.maxTopicIndex = 0; + } + topicReferenceIsAllowedInCurrentContext() { + return this.state.topicContext.maxNumOfResolvableTopics >= 1; + } + topicReferenceWasUsedInCurrentContext() { + return this.state.topicContext.maxTopicIndex != null && this.state.topicContext.maxTopicIndex >= 0; + } + parseFSharpPipelineBody(prec) { + const startLoc = this.state.startLoc; + this.state.potentialArrowAt = this.state.start; + const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody; + this.state.inFSharpPipelineDirectBody = true; + const ret = this.parseExprOp(this.parseMaybeUnaryOrPrivate(), startLoc, prec); + this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody; + return ret; + } + parseModuleExpression() { + this.expectPlugin("moduleBlocks"); + const node = this.startNode(); + this.next(); + if (!this.match(5)) { + this.unexpected(null, 5); + } + const program = this.startNodeAt(this.state.endLoc); + this.next(); + const revertScopes = this.initializeScopes(true); + this.enterInitialScopes(); + try { + node.body = this.parseProgram(program, 8, "module"); + } finally { + revertScopes(); + } + return this.finishNode(node, "ModuleExpression"); + } + parseVoidPattern(refExpressionErrors) { + this.expectPlugin("discardBinding"); + const node = this.startNode(); + if (refExpressionErrors != null) { + refExpressionErrors.voidPatternLoc = this.state.startLoc; + } + this.next(); + return this.finishNode(node, "VoidPattern"); + } + parseMaybeAssignAllowInOrVoidPattern(close, refExpressionErrors, afterLeftParse) { + if (refExpressionErrors != null && this.match(88)) { + const nextCode = this.lookaheadCharCode(); + if (nextCode === 44 || nextCode === (close === 3 ? 93 : close === 8 ? 125 : 41) || nextCode === 61) { + return this.parseMaybeDefault(this.state.startLoc, this.parseVoidPattern(refExpressionErrors)); + } + } + return this.parseMaybeAssignAllowIn(refExpressionErrors, afterLeftParse); + } + parsePropertyNamePrefixOperator(prop) {} +} +const loopLabel = { + kind: 1 + }, + switchLabel = { + kind: 2 + }; +const loneSurrogate = /[\uD800-\uDFFF]/u; +const keywordRelationalOperator = /in(?:stanceof)?/y; +function babel7CompatTokens(tokens, input, startIndex) { + for (let i = 0; i < tokens.length; i++) { + const token = tokens[i]; + const { + type + } = token; + if (typeof type === "number") { + if (type === 139) { + const { + loc, + start, + value, + end + } = token; + const hashEndPos = start + 1; + const hashEndLoc = createPositionWithColumnOffset(loc.start, 1); + tokens.splice(i, 1, new Token({ + type: getExportedToken(27), + value: "#", + start: start, + end: hashEndPos, + startLoc: loc.start, + endLoc: hashEndLoc + }), new Token({ + type: getExportedToken(132), + value: value, + start: hashEndPos, + end: end, + startLoc: hashEndLoc, + endLoc: loc.end + })); + i++; + continue; + } + if (tokenIsTemplate(type)) { + const { + loc, + start, + value, + end + } = token; + const backquoteEnd = start + 1; + const backquoteEndLoc = createPositionWithColumnOffset(loc.start, 1); + let startToken; + if (input.charCodeAt(start - startIndex) === 96) { + startToken = new Token({ + type: getExportedToken(22), + value: "`", + start: start, + end: backquoteEnd, + startLoc: loc.start, + endLoc: backquoteEndLoc + }); + } else { + startToken = new Token({ + type: getExportedToken(8), + value: "}", + start: start, + end: backquoteEnd, + startLoc: loc.start, + endLoc: backquoteEndLoc + }); + } + let templateValue, templateElementEnd, templateElementEndLoc, endToken; + if (type === 24) { + templateElementEnd = end - 1; + templateElementEndLoc = createPositionWithColumnOffset(loc.end, -1); + templateValue = value === null ? null : value.slice(1, -1); + endToken = new Token({ + type: getExportedToken(22), + value: "`", + start: templateElementEnd, + end: end, + startLoc: templateElementEndLoc, + endLoc: loc.end + }); + } else { + templateElementEnd = end - 2; + templateElementEndLoc = createPositionWithColumnOffset(loc.end, -2); + templateValue = value === null ? null : value.slice(1, -2); + endToken = new Token({ + type: getExportedToken(23), + value: "${", + start: templateElementEnd, + end: end, + startLoc: templateElementEndLoc, + endLoc: loc.end + }); + } + tokens.splice(i, 1, startToken, new Token({ + type: getExportedToken(20), + value: templateValue, + start: backquoteEnd, + end: templateElementEnd, + startLoc: backquoteEndLoc, + endLoc: templateElementEndLoc + }), endToken); + i += 2; + continue; + } + token.type = getExportedToken(type); + } + } + return tokens; +} +class StatementParser extends ExpressionParser { + parseTopLevel(file, program) { + file.program = this.parseProgram(program, 140, this.options.sourceType === "module" ? "module" : "script"); + file.comments = this.comments; + if (this.optionFlags & 256) { + file.tokens = babel7CompatTokens(this.tokens, this.input, this.startIndex); + } + return this.finishNode(file, "File"); + } + parseProgram(program, end, sourceType) { + program.sourceType = sourceType; + program.interpreter = this.parseInterpreterDirective(); + this.parseBlockBody(program, true, true, end); + if (this.inModule) { + if (!(this.optionFlags & 64) && this.scope.undefinedExports.size > 0) { + for (const [localName, at] of Array.from(this.scope.undefinedExports)) { + this.raise(Errors.ModuleExportUndefined, at, { + localName + }); + } + } + this.addExtra(program, "topLevelAwait", this.state.hasTopLevelAwait); + } + let finishedProgram; + if (end === 140) { + finishedProgram = this.finishNode(program, "Program"); + } else { + finishedProgram = this.finishNodeAt(program, "Program", createPositionWithColumnOffset(this.state.startLoc, -1)); + } + return finishedProgram; + } + stmtToDirective(stmt) { + const directive = this.castNodeTo(stmt, "Directive"); + const directiveLiteral = this.castNodeTo(stmt.expression, "DirectiveLiteral"); + const expressionValue = directiveLiteral.value; + const raw = this.input.slice(this.offsetToSourcePos(directiveLiteral.start), this.offsetToSourcePos(directiveLiteral.end)); + const val = directiveLiteral.value = raw.slice(1, -1); + this.addExtra(directiveLiteral, "raw", raw); + this.addExtra(directiveLiteral, "rawValue", val); + this.addExtra(directiveLiteral, "expressionValue", expressionValue); + directive.value = directiveLiteral; + delete stmt.expression; + return directive; + } + parseInterpreterDirective() { + if (!this.match(28)) { + return null; + } + const node = this.startNode(); + node.value = this.state.value; + this.next(); + return this.finishNode(node, "InterpreterDirective"); + } + isLet() { + if (!this.isContextual(100)) { + return false; + } + return this.hasFollowingBindingAtom(); + } + isUsing() { + if (!this.isContextual(107)) { + return false; + } + return this.nextTokenIsIdentifierOnSameLine(); + } + isForUsing() { + if (!this.isContextual(107)) { + return false; + } + const next = this.nextTokenInLineStart(); + const nextCh = this.codePointAtPos(next); + if (this.isUnparsedContextual(next, "of")) { + const nextCharAfterOf = this.lookaheadCharCodeSince(next + 2); + if (nextCharAfterOf !== 61 && nextCharAfterOf !== 58 && nextCharAfterOf !== 59) { + return false; + } + } + if (this.chStartsBindingIdentifier(nextCh, next) || this.isUnparsedContextual(next, "void")) { + return true; + } + return false; + } + nextTokenIsIdentifierOnSameLine() { + const next = this.nextTokenInLineStart(); + const nextCh = this.codePointAtPos(next); + return this.chStartsBindingIdentifier(nextCh, next); + } + isAwaitUsing() { + if (!this.isContextual(96)) { + return false; + } + let next = this.nextTokenInLineStart(); + if (this.isUnparsedContextual(next, "using")) { + next = this.nextTokenInLineStartSince(next + 5); + const nextCh = this.codePointAtPos(next); + if (this.chStartsBindingIdentifier(nextCh, next)) { + return true; + } + } + return false; + } + chStartsBindingIdentifier(ch, pos) { + if (isIdentifierStart(ch)) { + keywordRelationalOperator.lastIndex = pos; + if (keywordRelationalOperator.test(this.input)) { + const endCh = this.codePointAtPos(keywordRelationalOperator.lastIndex); + if (!isIdentifierChar(endCh) && endCh !== 92) { + return false; + } + } + return true; + } else if (ch === 92) { + return true; + } else { + return false; + } + } + chStartsBindingPattern(ch) { + return ch === 91 || ch === 123; + } + hasFollowingBindingAtom() { + const next = this.nextTokenStart(); + const nextCh = this.codePointAtPos(next); + return this.chStartsBindingPattern(nextCh) || this.chStartsBindingIdentifier(nextCh, next); + } + hasInLineFollowingBindingIdentifierOrBrace() { + const next = this.nextTokenInLineStart(); + const nextCh = this.codePointAtPos(next); + return nextCh === 123 || this.chStartsBindingIdentifier(nextCh, next); + } + allowsUsing() { + return (this.scope.inModule || !this.scope.inTopLevel) && !this.scope.inBareCaseStatement; + } + parseModuleItem() { + return this.parseStatementLike(1 | 2 | 4 | 8); + } + parseStatementListItem() { + return this.parseStatementLike(2 | 4 | (!this.options.annexB || this.state.strict ? 0 : 8)); + } + parseStatementOrSloppyAnnexBFunctionDeclaration(allowLabeledFunction = false) { + let flags = 0; + if (this.options.annexB && !this.state.strict) { + flags |= 4; + if (allowLabeledFunction) { + flags |= 8; + } + } + return this.parseStatementLike(flags); + } + parseStatement() { + return this.parseStatementLike(0); + } + parseStatementLike(flags) { + let decorators = null; + if (this.match(26)) { + decorators = this.parseDecorators(true); + } + return this.parseStatementContent(flags, decorators); + } + parseStatementContent(flags, decorators) { + const startType = this.state.type; + const node = this.startNode(); + const allowDeclaration = !!(flags & 2); + const allowFunctionDeclaration = !!(flags & 4); + const topLevel = flags & 1; + switch (startType) { + case 60: + return this.parseBreakContinueStatement(node, true); + case 63: + return this.parseBreakContinueStatement(node, false); + case 64: + return this.parseDebuggerStatement(node); + case 90: + return this.parseDoWhileStatement(node); + case 91: + return this.parseForStatement(node); + case 68: + if (this.lookaheadCharCode() === 46) break; + if (!allowFunctionDeclaration) { + this.raise(this.state.strict ? Errors.StrictFunction : this.options.annexB ? Errors.SloppyFunctionAnnexB : Errors.SloppyFunction, this.state.startLoc); + } + return this.parseFunctionStatement(node, false, !allowDeclaration && allowFunctionDeclaration); + case 80: + if (!allowDeclaration) this.unexpected(); + return this.parseClass(this.maybeTakeDecorators(decorators, node), true); + case 69: + return this.parseIfStatement(node); + case 70: + return this.parseReturnStatement(node); + case 71: + return this.parseSwitchStatement(node); + case 72: + return this.parseThrowStatement(node); + case 73: + return this.parseTryStatement(node); + case 96: + if (this.isAwaitUsing()) { + if (!this.allowsUsing()) { + this.raise(Errors.UnexpectedUsingDeclaration, node); + } else if (!allowDeclaration) { + this.raise(Errors.UnexpectedLexicalDeclaration, node); + } else if (!this.recordAwaitIfAllowed()) { + this.raise(Errors.AwaitUsingNotInAsyncContext, node); + } + this.next(); + return this.parseVarStatement(node, "await using"); + } + break; + case 107: + if (this.state.containsEsc || !this.hasInLineFollowingBindingIdentifierOrBrace()) { + break; + } + if (!this.allowsUsing()) { + this.raise(Errors.UnexpectedUsingDeclaration, this.state.startLoc); + } else if (!allowDeclaration) { + this.raise(Errors.UnexpectedLexicalDeclaration, this.state.startLoc); + } + return this.parseVarStatement(node, "using"); + case 100: + { + if (this.state.containsEsc) { + break; + } + const next = this.nextTokenStart(); + const nextCh = this.codePointAtPos(next); + if (nextCh !== 91) { + if (!allowDeclaration && this.hasFollowingLineBreak()) break; + if (!this.chStartsBindingIdentifier(nextCh, next) && nextCh !== 123) { + break; + } + } + } + case 75: + { + if (!allowDeclaration) { + this.raise(Errors.UnexpectedLexicalDeclaration, this.state.startLoc); + } + } + case 74: + { + const kind = this.state.value; + return this.parseVarStatement(node, kind); + } + case 92: + return this.parseWhileStatement(node); + case 76: + return this.parseWithStatement(node); + case 5: + return this.parseBlock(); + case 13: + return this.parseEmptyStatement(node); + case 83: + { + const nextTokenCharCode = this.lookaheadCharCode(); + if (nextTokenCharCode === 40 || nextTokenCharCode === 46) { + break; + } + } + case 82: + { + if (!(this.optionFlags & 8) && !topLevel) { + this.raise(Errors.UnexpectedImportExport, this.state.startLoc); + } + this.next(); + let result; + if (startType === 83) { + result = this.parseImport(node); + } else { + result = this.parseExport(node, decorators); + } + this.assertModuleNodeAllowed(result); + return result; + } + default: + { + if (this.isAsyncFunction()) { + if (!allowDeclaration) { + this.raise(Errors.AsyncFunctionInSingleStatementContext, this.state.startLoc); + } + this.next(); + return this.parseFunctionStatement(node, true, !allowDeclaration && allowFunctionDeclaration); + } + } + } + const maybeName = this.state.value; + const expr = this.parseExpression(); + if (tokenIsIdentifier(startType) && expr.type === "Identifier" && this.eat(14)) { + return this.parseLabeledStatement(node, maybeName, expr, flags); + } else { + return this.parseExpressionStatement(node, expr, decorators); + } + } + assertModuleNodeAllowed(node) { + if (!(this.optionFlags & 8) && !this.inModule) { + this.raise(Errors.ImportOutsideModule, node); + } + } + decoratorsEnabledBeforeExport() { + if (this.hasPlugin("decorators-legacy")) return true; + return this.hasPlugin("decorators") && this.getPluginOption("decorators", "decoratorsBeforeExport") !== false; + } + maybeTakeDecorators(maybeDecorators, classNode, exportNode) { + if (maybeDecorators) { + var _classNode$decorators; + if ((_classNode$decorators = classNode.decorators) != null && _classNode$decorators.length) { + if (typeof this.getPluginOption("decorators", "decoratorsBeforeExport") !== "boolean") { + this.raise(Errors.DecoratorsBeforeAfterExport, classNode.decorators[0]); + } + classNode.decorators.unshift(...maybeDecorators); + } else { + classNode.decorators = maybeDecorators; + } + this.resetStartLocationFromNode(classNode, maybeDecorators[0]); + if (exportNode) this.resetStartLocationFromNode(exportNode, classNode); + } + return classNode; + } + canHaveLeadingDecorator() { + return this.match(80); + } + parseDecorators(allowExport) { + const decorators = []; + do { + decorators.push(this.parseDecorator()); + } while (this.match(26)); + if (this.match(82)) { + if (!allowExport) { + this.unexpected(); + } + if (!this.decoratorsEnabledBeforeExport()) { + this.raise(Errors.DecoratorExportClass, this.state.startLoc); + } + } else if (!this.canHaveLeadingDecorator()) { + throw this.raise(Errors.UnexpectedLeadingDecorator, this.state.startLoc); + } + return decorators; + } + parseDecorator() { + this.expectOnePlugin(["decorators", "decorators-legacy"]); + const node = this.startNode(); + this.next(); + if (this.hasPlugin("decorators")) { + const startLoc = this.state.startLoc; + let expr; + if (this.match(10)) { + const startLoc = this.state.startLoc; + this.next(); + expr = this.parseExpression(); + this.expect(11); + expr = this.wrapParenthesis(startLoc, expr); + const paramsStartLoc = this.state.startLoc; + node.expression = this.parseMaybeDecoratorArguments(expr, startLoc); + if (this.getPluginOption("decorators", "allowCallParenthesized") === false && node.expression !== expr) { + this.raise(Errors.DecoratorArgumentsOutsideParentheses, paramsStartLoc); + } + } else { + expr = this.parseIdentifier(false); + while (this.eat(16)) { + const node = this.startNodeAt(startLoc); + node.object = expr; + if (this.match(139)) { + this.classScope.usePrivateName(this.state.value, this.state.startLoc); + node.property = this.parsePrivateName(); + } else { + node.property = this.parseIdentifier(true); + } + node.computed = false; + expr = this.finishNode(node, "MemberExpression"); + } + node.expression = this.parseMaybeDecoratorArguments(expr, startLoc); + } + } else { + node.expression = this.parseExprSubscripts(); + } + return this.finishNode(node, "Decorator"); + } + parseMaybeDecoratorArguments(expr, startLoc) { + if (this.eat(10)) { + const node = this.startNodeAt(startLoc); + node.callee = expr; + node.arguments = this.parseCallExpressionArguments(); + this.toReferencedList(node.arguments); + return this.finishNode(node, "CallExpression"); + } + return expr; + } + parseBreakContinueStatement(node, isBreak) { + this.next(); + if (this.isLineTerminator()) { + node.label = null; + } else { + node.label = this.parseIdentifier(); + this.semicolon(); + } + this.verifyBreakContinue(node, isBreak); + return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement"); + } + verifyBreakContinue(node, isBreak) { + let i; + for (i = 0; i < this.state.labels.length; ++i) { + const lab = this.state.labels[i]; + if (node.label == null || lab.name === node.label.name) { + if (lab.kind != null && (isBreak || lab.kind === 1)) { + break; + } + if (node.label && isBreak) break; + } + } + if (i === this.state.labels.length) { + const type = isBreak ? "BreakStatement" : "ContinueStatement"; + this.raise(Errors.IllegalBreakContinue, node, { + type + }); + } + } + parseDebuggerStatement(node) { + this.next(); + this.semicolon(); + return this.finishNode(node, "DebuggerStatement"); + } + parseHeaderExpression() { + this.expect(10); + const val = this.parseExpression(); + this.expect(11); + return val; + } + parseDoWhileStatement(node) { + this.next(); + this.state.labels.push(loopLabel); + node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement()); + this.state.labels.pop(); + this.expect(92); + node.test = this.parseHeaderExpression(); + this.eat(13); + return this.finishNode(node, "DoWhileStatement"); + } + parseForStatement(node) { + this.next(); + this.state.labels.push(loopLabel); + let awaitAt = null; + if (this.isContextual(96) && this.recordAwaitIfAllowed()) { + awaitAt = this.state.startLoc; + this.next(); + } + this.scope.enter(0); + this.expect(10); + if (this.match(13)) { + if (awaitAt !== null) { + this.unexpected(awaitAt); + } + return this.parseFor(node, null); + } + const startsWithLet = this.isContextual(100); + { + const startsWithAwaitUsing = this.isAwaitUsing(); + const starsWithUsingDeclaration = startsWithAwaitUsing || this.isForUsing(); + const isLetOrUsing = startsWithLet && this.hasFollowingBindingAtom() || starsWithUsingDeclaration; + if (this.match(74) || this.match(75) || isLetOrUsing) { + const initNode = this.startNode(); + let kind; + if (startsWithAwaitUsing) { + kind = "await using"; + if (!this.recordAwaitIfAllowed()) { + this.raise(Errors.AwaitUsingNotInAsyncContext, this.state.startLoc); + } + this.next(); + } else { + kind = this.state.value; + } + this.next(); + this.parseVar(initNode, true, kind); + const init = this.finishNode(initNode, "VariableDeclaration"); + const isForIn = this.match(58); + if (isForIn && starsWithUsingDeclaration) { + this.raise(Errors.ForInUsing, init); + } + if ((isForIn || this.isContextual(102)) && init.declarations.length === 1) { + return this.parseForIn(node, init, awaitAt); + } + if (awaitAt !== null) { + this.unexpected(awaitAt); + } + return this.parseFor(node, init); + } + } + const startsWithAsync = this.isContextual(95); + const refExpressionErrors = new ExpressionErrors(); + const init = this.parseExpression(true, refExpressionErrors); + const isForOf = this.isContextual(102); + if (isForOf) { + if (startsWithLet) { + this.raise(Errors.ForOfLet, init); + } + if (awaitAt === null && startsWithAsync && init.type === "Identifier") { + this.raise(Errors.ForOfAsync, init); + } + } + if (isForOf || this.match(58)) { + this.checkDestructuringPrivate(refExpressionErrors); + this.toAssignable(init, true); + const type = isForOf ? "ForOfStatement" : "ForInStatement"; + this.checkLVal(init, { + type + }); + return this.parseForIn(node, init, awaitAt); + } else { + this.checkExpressionErrors(refExpressionErrors, true); + } + if (awaitAt !== null) { + this.unexpected(awaitAt); + } + return this.parseFor(node, init); + } + parseFunctionStatement(node, isAsync, isHangingDeclaration) { + this.next(); + return this.parseFunction(node, 1 | (isHangingDeclaration ? 2 : 0) | (isAsync ? 8 : 0)); + } + parseIfStatement(node) { + this.next(); + node.test = this.parseHeaderExpression(); + node.consequent = this.parseStatementOrSloppyAnnexBFunctionDeclaration(); + node.alternate = this.eat(66) ? this.parseStatementOrSloppyAnnexBFunctionDeclaration() : null; + return this.finishNode(node, "IfStatement"); + } + parseReturnStatement(node) { + if (!this.prodParam.hasReturn) { + this.raise(Errors.IllegalReturn, this.state.startLoc); + } + this.next(); + if (this.isLineTerminator()) { + node.argument = null; + } else { + node.argument = this.parseExpression(); + this.semicolon(); + } + return this.finishNode(node, "ReturnStatement"); + } + parseSwitchStatement(node) { + this.next(); + node.discriminant = this.parseHeaderExpression(); + const cases = node.cases = []; + this.expect(5); + this.state.labels.push(switchLabel); + this.scope.enter(256); + let cur; + for (let sawDefault; !this.match(8);) { + if (this.match(61) || this.match(65)) { + const isCase = this.match(61); + if (cur) this.finishNode(cur, "SwitchCase"); + cases.push(cur = this.startNode()); + cur.consequent = []; + this.next(); + if (isCase) { + cur.test = this.parseExpression(); + } else { + if (sawDefault) { + this.raise(Errors.MultipleDefaultsInSwitch, this.state.lastTokStartLoc); + } + sawDefault = true; + cur.test = null; + } + this.expect(14); + } else { + if (cur) { + cur.consequent.push(this.parseStatementListItem()); + } else { + this.unexpected(); + } + } + } + this.scope.exit(); + if (cur) this.finishNode(cur, "SwitchCase"); + this.next(); + this.state.labels.pop(); + return this.finishNode(node, "SwitchStatement"); + } + parseThrowStatement(node) { + this.next(); + if (this.hasPrecedingLineBreak()) { + this.raise(Errors.NewlineAfterThrow, this.state.lastTokEndLoc); + } + node.argument = this.parseExpression(); + this.semicolon(); + return this.finishNode(node, "ThrowStatement"); + } + parseCatchClauseParam() { + const param = this.parseBindingAtom(); + this.scope.enter(this.options.annexB && param.type === "Identifier" ? 8 : 0); + this.checkLVal(param, { + type: "CatchClause" + }, 9); + return param; + } + parseTryStatement(node) { + this.next(); + node.block = this.parseBlock(); + node.handler = null; + if (this.match(62)) { + const clause = this.startNode(); + this.next(); + if (this.match(10)) { + this.expect(10); + clause.param = this.parseCatchClauseParam(); + this.expect(11); + } else { + clause.param = null; + this.scope.enter(0); + } + clause.body = this.withSmartMixTopicForbiddingContext(() => this.parseBlock(false, false)); + this.scope.exit(); + node.handler = this.finishNode(clause, "CatchClause"); + } + node.finalizer = this.eat(67) ? this.parseBlock() : null; + if (!node.handler && !node.finalizer) { + this.raise(Errors.NoCatchOrFinally, node); + } + return this.finishNode(node, "TryStatement"); + } + parseVarStatement(node, kind, allowMissingInitializer = false) { + this.next(); + this.parseVar(node, false, kind, allowMissingInitializer); + this.semicolon(); + return this.finishNode(node, "VariableDeclaration"); + } + parseWhileStatement(node) { + this.next(); + node.test = this.parseHeaderExpression(); + this.state.labels.push(loopLabel); + node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement()); + this.state.labels.pop(); + return this.finishNode(node, "WhileStatement"); + } + parseWithStatement(node) { + if (this.state.strict) { + this.raise(Errors.StrictWith, this.state.startLoc); + } + this.next(); + node.object = this.parseHeaderExpression(); + node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement()); + return this.finishNode(node, "WithStatement"); + } + parseEmptyStatement(node) { + this.next(); + return this.finishNode(node, "EmptyStatement"); + } + parseLabeledStatement(node, maybeName, expr, flags) { + for (const label of this.state.labels) { + if (label.name === maybeName) { + this.raise(Errors.LabelRedeclaration, expr, { + labelName: maybeName + }); + } + } + const kind = tokenIsLoop(this.state.type) ? 1 : this.match(71) ? 2 : null; + for (let i = this.state.labels.length - 1; i >= 0; i--) { + const label = this.state.labels[i]; + if (label.statementStart === node.start) { + label.statementStart = this.sourceToOffsetPos(this.state.start); + label.kind = kind; + } else { + break; + } + } + this.state.labels.push({ + name: maybeName, + kind: kind, + statementStart: this.sourceToOffsetPos(this.state.start) + }); + node.body = flags & 8 ? this.parseStatementOrSloppyAnnexBFunctionDeclaration(true) : this.parseStatement(); + this.state.labels.pop(); + node.label = expr; + return this.finishNode(node, "LabeledStatement"); + } + parseExpressionStatement(node, expr, decorators) { + node.expression = expr; + this.semicolon(); + return this.finishNode(node, "ExpressionStatement"); + } + parseBlock(allowDirectives = false, createNewLexicalScope = true, afterBlockParse) { + const node = this.startNode(); + if (allowDirectives) { + this.state.strictErrors.clear(); + } + this.expect(5); + if (createNewLexicalScope) { + this.scope.enter(0); + } + this.parseBlockBody(node, allowDirectives, false, 8, afterBlockParse); + if (createNewLexicalScope) { + this.scope.exit(); + } + return this.finishNode(node, "BlockStatement"); + } + isValidDirective(stmt) { + return stmt.type === "ExpressionStatement" && stmt.expression.type === "StringLiteral" && !stmt.expression.extra.parenthesized; + } + parseBlockBody(node, allowDirectives, topLevel, end, afterBlockParse) { + const body = node.body = []; + const directives = node.directives = []; + this.parseBlockOrModuleBlockBody(body, allowDirectives ? directives : undefined, topLevel, end, afterBlockParse); + } + parseBlockOrModuleBlockBody(body, directives, topLevel, end, afterBlockParse) { + const oldStrict = this.state.strict; + let hasStrictModeDirective = false; + let parsedNonDirective = false; + while (!this.match(end)) { + const stmt = topLevel ? this.parseModuleItem() : this.parseStatementListItem(); + if (directives && !parsedNonDirective) { + if (this.isValidDirective(stmt)) { + const directive = this.stmtToDirective(stmt); + directives.push(directive); + if (!hasStrictModeDirective && directive.value.value === "use strict") { + hasStrictModeDirective = true; + this.setStrict(true); + } + continue; + } + parsedNonDirective = true; + this.state.strictErrors.clear(); + } + body.push(stmt); + } + afterBlockParse == null || afterBlockParse.call(this, hasStrictModeDirective); + if (!oldStrict) { + this.setStrict(false); + } + this.next(); + } + parseFor(node, init) { + node.init = init; + this.semicolon(false); + node.test = this.match(13) ? null : this.parseExpression(); + this.semicolon(false); + node.update = this.match(11) ? null : this.parseExpression(); + this.expect(11); + node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement()); + this.scope.exit(); + this.state.labels.pop(); + return this.finishNode(node, "ForStatement"); + } + parseForIn(node, init, awaitAt) { + const isForIn = this.match(58); + this.next(); + if (isForIn) { + if (awaitAt !== null) this.unexpected(awaitAt); + } else { + node.await = awaitAt !== null; + } + if (init.type === "VariableDeclaration" && init.declarations[0].init != null && (!isForIn || !this.options.annexB || this.state.strict || init.kind !== "var" || init.declarations[0].id.type !== "Identifier")) { + this.raise(Errors.ForInOfLoopInitializer, init, { + type: isForIn ? "ForInStatement" : "ForOfStatement" + }); + } + if (init.type === "AssignmentPattern") { + this.raise(Errors.InvalidLhs, init, { + ancestor: { + type: "ForStatement" + } + }); + } + node.left = init; + node.right = isForIn ? this.parseExpression() : this.parseMaybeAssignAllowIn(); + this.expect(11); + node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement()); + this.scope.exit(); + this.state.labels.pop(); + return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement"); + } + parseVar(node, isFor, kind, allowMissingInitializer = false) { + const declarations = node.declarations = []; + node.kind = kind; + for (;;) { + const decl = this.startNode(); + this.parseVarId(decl, kind); + decl.init = !this.eat(29) ? null : isFor ? this.parseMaybeAssignDisallowIn() : this.parseMaybeAssignAllowIn(); + if (decl.init === null && !allowMissingInitializer) { + if (decl.id.type !== "Identifier" && !(isFor && (this.match(58) || this.isContextual(102)))) { + this.raise(Errors.DeclarationMissingInitializer, this.state.lastTokEndLoc, { + kind: "destructuring" + }); + } else if ((kind === "const" || kind === "using" || kind === "await using") && !(this.match(58) || this.isContextual(102))) { + this.raise(Errors.DeclarationMissingInitializer, this.state.lastTokEndLoc, { + kind + }); + } + } + declarations.push(this.finishNode(decl, "VariableDeclarator")); + if (!this.eat(12)) break; + } + return node; + } + parseVarId(decl, kind) { + const id = this.parseBindingAtom(); + if (kind === "using" || kind === "await using") { + if (id.type === "ArrayPattern" || id.type === "ObjectPattern") { + this.raise(Errors.UsingDeclarationHasBindingPattern, id.loc.start); + } + } else { + if (id.type === "VoidPattern") { + this.raise(Errors.UnexpectedVoidPattern, id.loc.start); + } + } + this.checkLVal(id, { + type: "VariableDeclarator" + }, kind === "var" ? 5 : 8201); + decl.id = id; + } + parseAsyncFunctionExpression(node) { + return this.parseFunction(node, 8); + } + parseFunction(node, flags = 0) { + const hangingDeclaration = flags & 2; + const isDeclaration = !!(flags & 1); + const requireId = isDeclaration && !(flags & 4); + const isAsync = !!(flags & 8); + this.initFunction(node, isAsync); + if (this.match(55)) { + if (hangingDeclaration) { + this.raise(Errors.GeneratorInSingleStatementContext, this.state.startLoc); + } + this.next(); + node.generator = true; + } + if (isDeclaration) { + node.id = this.parseFunctionId(requireId); + } + const oldMaybeInArrowParameters = this.state.maybeInArrowParameters; + this.state.maybeInArrowParameters = false; + this.scope.enter(514); + this.prodParam.enter(functionFlags(isAsync, node.generator)); + if (!isDeclaration) { + node.id = this.parseFunctionId(); + } + this.parseFunctionParams(node, false); + this.withSmartMixTopicForbiddingContext(() => { + this.parseFunctionBodyAndFinish(node, isDeclaration ? "FunctionDeclaration" : "FunctionExpression"); + }); + this.prodParam.exit(); + this.scope.exit(); + if (isDeclaration && !hangingDeclaration) { + this.registerFunctionStatementId(node); + } + this.state.maybeInArrowParameters = oldMaybeInArrowParameters; + return node; + } + parseFunctionId(requireId) { + return requireId || tokenIsIdentifier(this.state.type) ? this.parseIdentifier() : null; + } + parseFunctionParams(node, isConstructor) { + this.expect(10); + this.expressionScope.enter(newParameterDeclarationScope()); + node.params = this.parseBindingList(11, 41, 2 | (isConstructor ? 4 : 0)); + this.expressionScope.exit(); + } + registerFunctionStatementId(node) { + if (!node.id) return; + this.scope.declareName(node.id.name, !this.options.annexB || this.state.strict || node.generator || node.async ? this.scope.treatFunctionsAsVar ? 5 : 8201 : 17, node.id.loc.start); + } + parseClass(node, isStatement, optionalId) { + this.next(); + const oldStrict = this.state.strict; + this.state.strict = true; + this.parseClassId(node, isStatement, optionalId); + this.parseClassSuper(node); + node.body = this.parseClassBody(!!node.superClass, oldStrict); + return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression"); + } + isClassProperty() { + return this.match(29) || this.match(13) || this.match(8); + } + isClassMethod() { + return this.match(10); + } + nameIsConstructor(key) { + return key.type === "Identifier" && key.name === "constructor" || key.type === "StringLiteral" && key.value === "constructor"; + } + isNonstaticConstructor(method) { + return !method.computed && !method.static && this.nameIsConstructor(method.key); + } + parseClassBody(hadSuperClass, oldStrict) { + this.classScope.enter(); + const state = { + hadConstructor: false, + hadSuperClass + }; + let decorators = []; + const classBody = this.startNode(); + classBody.body = []; + this.expect(5); + this.withSmartMixTopicForbiddingContext(() => { + while (!this.match(8)) { + if (this.eat(13)) { + if (decorators.length > 0) { + throw this.raise(Errors.DecoratorSemicolon, this.state.lastTokEndLoc); + } + continue; + } + if (this.match(26)) { + decorators.push(this.parseDecorator()); + continue; + } + const member = this.startNode(); + if (decorators.length) { + member.decorators = decorators; + this.resetStartLocationFromNode(member, decorators[0]); + decorators = []; + } + this.parseClassMember(classBody, member, state); + if (member.kind === "constructor" && member.decorators && member.decorators.length > 0) { + this.raise(Errors.DecoratorConstructor, member); + } + } + }); + this.state.strict = oldStrict; + this.next(); + if (decorators.length) { + throw this.raise(Errors.TrailingDecorator, this.state.startLoc); + } + this.classScope.exit(); + return this.finishNode(classBody, "ClassBody"); + } + parseClassMemberFromModifier(classBody, member) { + const key = this.parseIdentifier(true); + if (this.isClassMethod()) { + const method = member; + method.kind = "method"; + method.computed = false; + method.key = key; + method.static = false; + this.pushClassMethod(classBody, method, false, false, false, false); + return true; + } else if (this.isClassProperty()) { + const prop = member; + prop.computed = false; + prop.key = key; + prop.static = false; + classBody.body.push(this.parseClassProperty(prop)); + return true; + } + this.resetPreviousNodeTrailingComments(key); + return false; + } + parseClassMember(classBody, member, state) { + const isStatic = this.isContextual(106); + if (isStatic) { + if (this.parseClassMemberFromModifier(classBody, member)) { + return; + } + if (this.eat(5)) { + this.parseClassStaticBlock(classBody, member); + return; + } + } + this.parseClassMemberWithIsStatic(classBody, member, state, isStatic); + } + parseClassMemberWithIsStatic(classBody, member, state, isStatic) { + const publicMethod = member; + const privateMethod = member; + const publicProp = member; + const privateProp = member; + const accessorProp = member; + const method = publicMethod; + const publicMember = publicMethod; + member.static = isStatic; + this.parsePropertyNamePrefixOperator(member); + if (this.eat(55)) { + method.kind = "method"; + const isPrivateName = this.match(139); + this.parseClassElementName(method); + this.parsePostMemberNameModifiers(method); + if (isPrivateName) { + this.pushClassPrivateMethod(classBody, privateMethod, true, false); + return; + } + if (this.isNonstaticConstructor(publicMethod)) { + this.raise(Errors.ConstructorIsGenerator, publicMethod.key); + } + this.pushClassMethod(classBody, publicMethod, true, false, false, false); + return; + } + const isContextual = !this.state.containsEsc && tokenIsIdentifier(this.state.type); + const key = this.parseClassElementName(member); + const maybeContextualKw = isContextual ? key.name : null; + const isPrivate = this.isPrivateName(key); + const maybeQuestionTokenStartLoc = this.state.startLoc; + this.parsePostMemberNameModifiers(publicMember); + if (this.isClassMethod()) { + method.kind = "method"; + if (isPrivate) { + this.pushClassPrivateMethod(classBody, privateMethod, false, false); + return; + } + const isConstructor = this.isNonstaticConstructor(publicMethod); + let allowsDirectSuper = false; + if (isConstructor) { + publicMethod.kind = "constructor"; + if (state.hadConstructor && !this.hasPlugin("typescript")) { + this.raise(Errors.DuplicateConstructor, key); + } + if (isConstructor && this.hasPlugin("typescript") && member.override) { + this.raise(Errors.OverrideOnConstructor, key); + } + state.hadConstructor = true; + allowsDirectSuper = state.hadSuperClass; + } + this.pushClassMethod(classBody, publicMethod, false, false, isConstructor, allowsDirectSuper); + } else if (this.isClassProperty()) { + if (isPrivate) { + this.pushClassPrivateProperty(classBody, privateProp); + } else { + this.pushClassProperty(classBody, publicProp); + } + } else if (maybeContextualKw === "async" && !this.isLineTerminator()) { + this.resetPreviousNodeTrailingComments(key); + const isGenerator = this.eat(55); + if (publicMember.optional) { + this.unexpected(maybeQuestionTokenStartLoc); + } + method.kind = "method"; + const isPrivate = this.match(139); + this.parseClassElementName(method); + this.parsePostMemberNameModifiers(publicMember); + if (isPrivate) { + this.pushClassPrivateMethod(classBody, privateMethod, isGenerator, true); + } else { + if (this.isNonstaticConstructor(publicMethod)) { + this.raise(Errors.ConstructorIsAsync, publicMethod.key); + } + this.pushClassMethod(classBody, publicMethod, isGenerator, true, false, false); + } + } else if ((maybeContextualKw === "get" || maybeContextualKw === "set") && !(this.match(55) && this.isLineTerminator())) { + this.resetPreviousNodeTrailingComments(key); + method.kind = maybeContextualKw; + const isPrivate = this.match(139); + this.parseClassElementName(publicMethod); + if (isPrivate) { + this.pushClassPrivateMethod(classBody, privateMethod, false, false); + } else { + if (this.isNonstaticConstructor(publicMethod)) { + this.raise(Errors.ConstructorIsAccessor, publicMethod.key); + } + this.pushClassMethod(classBody, publicMethod, false, false, false, false); + } + this.checkGetterSetterParams(publicMethod); + } else if (maybeContextualKw === "accessor" && !this.isLineTerminator()) { + this.expectPlugin("decoratorAutoAccessors"); + this.resetPreviousNodeTrailingComments(key); + const isPrivate = this.match(139); + this.parseClassElementName(publicProp); + this.pushClassAccessorProperty(classBody, accessorProp, isPrivate); + } else if (this.isLineTerminator()) { + if (isPrivate) { + this.pushClassPrivateProperty(classBody, privateProp); + } else { + this.pushClassProperty(classBody, publicProp); + } + } else { + this.unexpected(); + } + } + parseClassElementName(member) { + const { + type, + value + } = this.state; + if ((type === 132 || type === 134) && member.static && value === "prototype") { + this.raise(Errors.StaticPrototype, this.state.startLoc); + } + if (type === 139) { + if (value === "constructor") { + this.raise(Errors.ConstructorClassPrivateField, this.state.startLoc); + } + const key = this.parsePrivateName(); + member.key = key; + return key; + } + this.parsePropertyName(member); + return member.key; + } + parseClassStaticBlock(classBody, member) { + var _member$decorators; + this.scope.enter(576 | 128 | 16); + const oldLabels = this.state.labels; + this.state.labels = []; + this.prodParam.enter(0); + const body = member.body = []; + this.parseBlockOrModuleBlockBody(body, undefined, false, 8); + this.prodParam.exit(); + this.scope.exit(); + this.state.labels = oldLabels; + classBody.body.push(this.finishNode(member, "StaticBlock")); + if ((_member$decorators = member.decorators) != null && _member$decorators.length) { + this.raise(Errors.DecoratorStaticBlock, member); + } + } + pushClassProperty(classBody, prop) { + if (!prop.computed && this.nameIsConstructor(prop.key)) { + this.raise(Errors.ConstructorClassField, prop.key); + } + classBody.body.push(this.parseClassProperty(prop)); + } + pushClassPrivateProperty(classBody, prop) { + const node = this.parseClassPrivateProperty(prop); + classBody.body.push(node); + this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), 0, node.key.loc.start); + } + pushClassAccessorProperty(classBody, prop, isPrivate) { + if (!isPrivate && !prop.computed && this.nameIsConstructor(prop.key)) { + this.raise(Errors.ConstructorClassField, prop.key); + } + const node = this.parseClassAccessorProperty(prop); + classBody.body.push(node); + if (isPrivate) { + this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), 0, node.key.loc.start); + } + } + pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) { + classBody.body.push(this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true)); + } + pushClassPrivateMethod(classBody, method, isGenerator, isAsync) { + const node = this.parseMethod(method, isGenerator, isAsync, false, false, "ClassPrivateMethod", true); + classBody.body.push(node); + const kind = node.kind === "get" ? node.static ? 6 : 2 : node.kind === "set" ? node.static ? 5 : 1 : 0; + this.declareClassPrivateMethodInScope(node, kind); + } + declareClassPrivateMethodInScope(node, kind) { + this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), kind, node.key.loc.start); + } + parsePostMemberNameModifiers(methodOrProp) {} + parseClassPrivateProperty(node) { + this.parseInitializer(node); + this.semicolon(); + return this.finishNode(node, "ClassPrivateProperty"); + } + parseClassProperty(node) { + this.parseInitializer(node); + this.semicolon(); + return this.finishNode(node, "ClassProperty"); + } + parseClassAccessorProperty(node) { + this.parseInitializer(node); + this.semicolon(); + return this.finishNode(node, "ClassAccessorProperty"); + } + parseInitializer(node) { + this.scope.enter(576 | 16); + this.expressionScope.enter(newExpressionScope()); + this.prodParam.enter(0); + node.value = this.eat(29) ? this.parseMaybeAssignAllowIn() : null; + this.expressionScope.exit(); + this.prodParam.exit(); + this.scope.exit(); + } + parseClassId(node, isStatement, optionalId, bindingType = 8331) { + if (tokenIsIdentifier(this.state.type)) { + node.id = this.parseIdentifier(); + if (isStatement) { + this.declareNameFromIdentifier(node.id, bindingType); + } + } else { + if (optionalId || !isStatement) { + node.id = null; + } else { + throw this.raise(Errors.MissingClassName, this.state.startLoc); + } + } + } + parseClassSuper(node) { + node.superClass = this.eat(81) ? this.parseExprSubscripts() : null; + } + parseExport(node, decorators) { + const maybeDefaultIdentifier = this.parseMaybeImportPhase(node, true); + const hasDefault = this.maybeParseExportDefaultSpecifier(node, maybeDefaultIdentifier); + const parseAfterDefault = !hasDefault || this.eat(12); + const hasStar = parseAfterDefault && this.eatExportStar(node); + const hasNamespace = hasStar && this.maybeParseExportNamespaceSpecifier(node); + const parseAfterNamespace = parseAfterDefault && (!hasNamespace || this.eat(12)); + const isFromRequired = hasDefault || hasStar; + if (hasStar && !hasNamespace) { + if (hasDefault) this.unexpected(); + if (decorators) { + throw this.raise(Errors.UnsupportedDecoratorExport, node); + } + this.parseExportFrom(node, true); + this.sawUnambiguousESM = true; + return this.finishNode(node, "ExportAllDeclaration"); + } + const hasSpecifiers = this.maybeParseExportNamedSpecifiers(node); + if (hasDefault && parseAfterDefault && !hasStar && !hasSpecifiers) { + this.unexpected(null, 5); + } + if (hasNamespace && parseAfterNamespace) { + this.unexpected(null, 98); + } + let hasDeclaration; + if (isFromRequired || hasSpecifiers) { + hasDeclaration = false; + if (decorators) { + throw this.raise(Errors.UnsupportedDecoratorExport, node); + } + this.parseExportFrom(node, isFromRequired); + } else { + hasDeclaration = this.maybeParseExportDeclaration(node); + } + if (isFromRequired || hasSpecifiers || hasDeclaration) { + var _node2$declaration; + const node2 = node; + this.checkExport(node2, true, false, !!node2.source); + if (((_node2$declaration = node2.declaration) == null ? void 0 : _node2$declaration.type) === "ClassDeclaration") { + this.maybeTakeDecorators(decorators, node2.declaration, node2); + } else if (decorators) { + throw this.raise(Errors.UnsupportedDecoratorExport, node); + } + this.sawUnambiguousESM = true; + return this.finishNode(node2, "ExportNamedDeclaration"); + } + if (this.eat(65)) { + const node2 = node; + const decl = this.parseExportDefaultExpression(); + node2.declaration = decl; + if (decl.type === "ClassDeclaration") { + this.maybeTakeDecorators(decorators, decl, node2); + } else if (decorators) { + throw this.raise(Errors.UnsupportedDecoratorExport, node); + } + this.checkExport(node2, true, true); + this.sawUnambiguousESM = true; + return this.finishNode(node2, "ExportDefaultDeclaration"); + } + throw this.unexpected(null, 5); + } + eatExportStar(node) { + return this.eat(55); + } + maybeParseExportDefaultSpecifier(node, maybeDefaultIdentifier) { + if (maybeDefaultIdentifier || this.isExportDefaultSpecifier()) { + this.expectPlugin("exportDefaultFrom", maybeDefaultIdentifier == null ? void 0 : maybeDefaultIdentifier.loc.start); + const id = maybeDefaultIdentifier || this.parseIdentifier(true); + const specifier = this.startNodeAtNode(id); + specifier.exported = id; + node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")]; + return true; + } + return false; + } + maybeParseExportNamespaceSpecifier(node) { + if (this.isContextual(93)) { + var _ref, _ref$specifiers; + (_ref$specifiers = (_ref = node).specifiers) != null ? _ref$specifiers : _ref.specifiers = []; + const specifier = this.startNodeAt(this.state.lastTokStartLoc); + this.next(); + specifier.exported = this.parseModuleExportName(); + node.specifiers.push(this.finishNode(specifier, "ExportNamespaceSpecifier")); + return true; + } + return false; + } + maybeParseExportNamedSpecifiers(node) { + if (this.match(5)) { + const node2 = node; + if (!node2.specifiers) node2.specifiers = []; + const isTypeExport = node2.exportKind === "type"; + node2.specifiers.push(...this.parseExportSpecifiers(isTypeExport)); + node2.source = null; + if (this.hasPlugin("importAssertions")) { + node2.assertions = []; + } else { + node2.attributes = []; + } + node2.declaration = null; + return true; + } + return false; + } + maybeParseExportDeclaration(node) { + if (this.shouldParseExportDeclaration()) { + node.specifiers = []; + node.source = null; + if (this.hasPlugin("importAssertions")) { + node.assertions = []; + } else { + node.attributes = []; + } + node.declaration = this.parseExportDeclaration(node); + return true; + } + return false; + } + isAsyncFunction() { + if (!this.isContextual(95)) return false; + const next = this.nextTokenInLineStart(); + return this.isUnparsedContextual(next, "function"); + } + parseExportDefaultExpression() { + const expr = this.startNode(); + if (this.match(68)) { + this.next(); + return this.parseFunction(expr, 1 | 4); + } else if (this.isAsyncFunction()) { + this.next(); + this.next(); + return this.parseFunction(expr, 1 | 4 | 8); + } + if (this.match(80)) { + return this.parseClass(expr, true, true); + } + if (this.match(26)) { + if (this.hasPlugin("decorators") && this.getPluginOption("decorators", "decoratorsBeforeExport") === true) { + this.raise(Errors.DecoratorBeforeExport, this.state.startLoc); + } + return this.parseClass(this.maybeTakeDecorators(this.parseDecorators(false), this.startNode()), true, true); + } + if (this.match(75) || this.match(74) || this.isLet() || this.isUsing() || this.isAwaitUsing()) { + throw this.raise(Errors.UnsupportedDefaultExport, this.state.startLoc); + } + const res = this.parseMaybeAssignAllowIn(); + this.semicolon(); + return res; + } + parseExportDeclaration(node) { + if (this.match(80)) { + const node = this.parseClass(this.startNode(), true, false); + return node; + } + return this.parseStatementListItem(); + } + isExportDefaultSpecifier() { + const { + type + } = this.state; + if (tokenIsIdentifier(type)) { + if (type === 95 && !this.state.containsEsc || type === 100) { + return false; + } + if ((type === 130 || type === 129) && !this.state.containsEsc) { + const next = this.nextTokenStart(); + const nextChar = this.input.charCodeAt(next); + if (nextChar === 123 || this.chStartsBindingIdentifier(nextChar, next) && !this.input.startsWith("from", next)) { + this.expectOnePlugin(["flow", "typescript"]); + return false; + } + } + } else if (!this.match(65)) { + return false; + } + const next = this.nextTokenStart(); + const hasFrom = this.isUnparsedContextual(next, "from"); + if (this.input.charCodeAt(next) === 44 || tokenIsIdentifier(this.state.type) && hasFrom) { + return true; + } + if (this.match(65) && hasFrom) { + const nextAfterFrom = this.input.charCodeAt(this.nextTokenStartSince(next + 4)); + return nextAfterFrom === 34 || nextAfterFrom === 39; + } + return false; + } + parseExportFrom(node, expect) { + if (this.eatContextual(98)) { + node.source = this.parseImportSource(); + this.checkExport(node); + this.maybeParseImportAttributes(node); + this.checkJSONModuleImport(node); + } else if (expect) { + this.unexpected(); + } + this.semicolon(); + } + shouldParseExportDeclaration() { + const { + type + } = this.state; + if (type === 26) { + this.expectOnePlugin(["decorators", "decorators-legacy"]); + if (this.hasPlugin("decorators")) { + if (this.getPluginOption("decorators", "decoratorsBeforeExport") === true) { + this.raise(Errors.DecoratorBeforeExport, this.state.startLoc); + } + return true; + } + } + if (this.isUsing()) { + this.raise(Errors.UsingDeclarationExport, this.state.startLoc); + return true; + } + if (this.isAwaitUsing()) { + this.raise(Errors.UsingDeclarationExport, this.state.startLoc); + return true; + } + return type === 74 || type === 75 || type === 68 || type === 80 || this.isLet() || this.isAsyncFunction(); + } + checkExport(node, checkNames, isDefault, isFrom) { + if (checkNames) { + var _node$specifiers; + if (isDefault) { + this.checkDuplicateExports(node, "default"); + if (this.hasPlugin("exportDefaultFrom")) { + var _declaration$extra; + const declaration = node.declaration; + if (declaration.type === "Identifier" && declaration.name === "from" && declaration.end - declaration.start === 4 && !((_declaration$extra = declaration.extra) != null && _declaration$extra.parenthesized)) { + this.raise(Errors.ExportDefaultFromAsIdentifier, declaration); + } + } + } else if ((_node$specifiers = node.specifiers) != null && _node$specifiers.length) { + for (const specifier of node.specifiers) { + const { + exported + } = specifier; + const exportName = exported.type === "Identifier" ? exported.name : exported.value; + this.checkDuplicateExports(specifier, exportName); + if (!isFrom && specifier.local) { + const { + local + } = specifier; + if (local.type !== "Identifier") { + this.raise(Errors.ExportBindingIsString, specifier, { + localName: local.value, + exportName + }); + } else { + this.checkReservedWord(local.name, local.loc.start, true, false); + this.scope.checkLocalExport(local); + } + } + } + } else if (node.declaration) { + const decl = node.declaration; + if (decl.type === "FunctionDeclaration" || decl.type === "ClassDeclaration") { + const { + id + } = decl; + if (!id) throw new Error("Assertion failure"); + this.checkDuplicateExports(node, id.name); + } else if (decl.type === "VariableDeclaration") { + for (const declaration of decl.declarations) { + this.checkDeclaration(declaration.id); + } + } + } + } + } + checkDeclaration(node) { + if (node.type === "Identifier") { + this.checkDuplicateExports(node, node.name); + } else if (node.type === "ObjectPattern") { + for (const prop of node.properties) { + this.checkDeclaration(prop); + } + } else if (node.type === "ArrayPattern") { + for (const elem of node.elements) { + if (elem) { + this.checkDeclaration(elem); + } + } + } else if (node.type === "ObjectProperty") { + this.checkDeclaration(node.value); + } else if (node.type === "RestElement") { + this.checkDeclaration(node.argument); + } else if (node.type === "AssignmentPattern") { + this.checkDeclaration(node.left); + } + } + checkDuplicateExports(node, exportName) { + if (this.exportedIdentifiers.has(exportName)) { + if (exportName === "default") { + this.raise(Errors.DuplicateDefaultExport, node); + } else { + this.raise(Errors.DuplicateExport, node, { + exportName + }); + } + } + this.exportedIdentifiers.add(exportName); + } + parseExportSpecifiers(isInTypeExport) { + const nodes = []; + let first = true; + this.expect(5); + while (!this.eat(8)) { + if (first) { + first = false; + } else { + this.expect(12); + if (this.eat(8)) break; + } + const isMaybeTypeOnly = this.isContextual(130); + const isString = this.match(134); + const node = this.startNode(); + node.local = this.parseModuleExportName(); + nodes.push(this.parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly)); + } + return nodes; + } + parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly) { + if (this.eatContextual(93)) { + node.exported = this.parseModuleExportName(); + } else if (isString) { + node.exported = this.cloneStringLiteral(node.local); + } else if (!node.exported) { + node.exported = this.cloneIdentifier(node.local); + } + return this.finishNode(node, "ExportSpecifier"); + } + parseModuleExportName() { + if (this.match(134)) { + const result = this.parseStringLiteral(this.state.value); + const surrogate = loneSurrogate.exec(result.value); + if (surrogate) { + this.raise(Errors.ModuleExportNameHasLoneSurrogate, result, { + surrogateCharCode: surrogate[0].charCodeAt(0) + }); + } + return result; + } + return this.parseIdentifier(true); + } + isJSONModuleImport(node) { + if (node.assertions != null) { + return node.assertions.some(({ + key, + value + }) => { + return value.value === "json" && (key.type === "Identifier" ? key.name === "type" : key.value === "type"); + }); + } + return false; + } + checkImportReflection(node) { + const { + specifiers + } = node; + const singleBindingType = specifiers.length === 1 ? specifiers[0].type : null; + if (node.phase === "source") { + if (singleBindingType !== "ImportDefaultSpecifier") { + this.raise(Errors.SourcePhaseImportRequiresDefault, specifiers[0].loc.start); + } + } else if (node.phase === "defer") { + if (singleBindingType !== "ImportNamespaceSpecifier") { + this.raise(Errors.DeferImportRequiresNamespace, specifiers[0].loc.start); + } + } else if (node.module) { + var _node$assertions; + if (singleBindingType !== "ImportDefaultSpecifier") { + this.raise(Errors.ImportReflectionNotBinding, specifiers[0].loc.start); + } + if (((_node$assertions = node.assertions) == null ? void 0 : _node$assertions.length) > 0) { + this.raise(Errors.ImportReflectionHasAssertion, specifiers[0].loc.start); + } + } + } + checkJSONModuleImport(node) { + if (this.isJSONModuleImport(node) && node.type !== "ExportAllDeclaration") { + const { + specifiers + } = node; + if (specifiers != null) { + const nonDefaultNamedSpecifier = specifiers.find(specifier => { + let imported; + if (specifier.type === "ExportSpecifier") { + imported = specifier.local; + } else if (specifier.type === "ImportSpecifier") { + imported = specifier.imported; + } + if (imported !== undefined) { + return imported.type === "Identifier" ? imported.name !== "default" : imported.value !== "default"; + } + }); + if (nonDefaultNamedSpecifier !== undefined) { + this.raise(Errors.ImportJSONBindingNotDefault, nonDefaultNamedSpecifier.loc.start); + } + } + } + } + isPotentialImportPhase(isExport) { + if (isExport) return false; + return this.isContextual(105) || this.isContextual(97) || this.isContextual(127); + } + applyImportPhase(node, isExport, phase, loc) { + if (isExport) { + return; + } + if (phase === "module") { + this.expectPlugin("importReflection", loc); + node.module = true; + } else if (this.hasPlugin("importReflection")) { + node.module = false; + } + if (phase === "source") { + this.expectPlugin("sourcePhaseImports", loc); + node.phase = "source"; + } else if (phase === "defer") { + this.expectPlugin("deferredImportEvaluation", loc); + node.phase = "defer"; + } else if (this.hasPlugin("sourcePhaseImports")) { + node.phase = null; + } + } + parseMaybeImportPhase(node, isExport) { + if (!this.isPotentialImportPhase(isExport)) { + this.applyImportPhase(node, isExport, null); + return null; + } + const phaseIdentifier = this.startNode(); + const phaseIdentifierName = this.parseIdentifierName(true); + const { + type + } = this.state; + const isImportPhase = tokenIsKeywordOrIdentifier(type) ? type !== 98 || this.lookaheadCharCode() === 102 : type !== 12; + if (isImportPhase) { + this.applyImportPhase(node, isExport, phaseIdentifierName, phaseIdentifier.loc.start); + return null; + } else { + this.applyImportPhase(node, isExport, null); + return this.createIdentifier(phaseIdentifier, phaseIdentifierName); + } + } + isPrecedingIdImportPhase(phase) { + const { + type + } = this.state; + return tokenIsIdentifier(type) ? type !== 98 || this.lookaheadCharCode() === 102 : type !== 12; + } + parseImport(node) { + if (this.match(134)) { + return this.parseImportSourceAndAttributes(node); + } + return this.parseImportSpecifiersAndAfter(node, this.parseMaybeImportPhase(node, false)); + } + parseImportSpecifiersAndAfter(node, maybeDefaultIdentifier) { + node.specifiers = []; + const hasDefault = this.maybeParseDefaultImportSpecifier(node, maybeDefaultIdentifier); + const parseNext = !hasDefault || this.eat(12); + const hasStar = parseNext && this.maybeParseStarImportSpecifier(node); + if (parseNext && !hasStar) this.parseNamedImportSpecifiers(node); + this.expectContextual(98); + return this.parseImportSourceAndAttributes(node); + } + parseImportSourceAndAttributes(node) { + var _node$specifiers2; + (_node$specifiers2 = node.specifiers) != null ? _node$specifiers2 : node.specifiers = []; + node.source = this.parseImportSource(); + this.maybeParseImportAttributes(node); + this.checkImportReflection(node); + this.checkJSONModuleImport(node); + this.semicolon(); + this.sawUnambiguousESM = true; + return this.finishNode(node, "ImportDeclaration"); + } + parseImportSource() { + if (!this.match(134)) this.unexpected(); + return this.parseExprAtom(); + } + parseImportSpecifierLocal(node, specifier, type) { + specifier.local = this.parseIdentifier(); + node.specifiers.push(this.finishImportSpecifier(specifier, type)); + } + finishImportSpecifier(specifier, type, bindingType = 8201) { + this.checkLVal(specifier.local, { + type + }, bindingType); + return this.finishNode(specifier, type); + } + parseImportAttributes() { + this.expect(5); + const attrs = []; + const attrNames = new Set(); + do { + if (this.match(8)) { + break; + } + const node = this.startNode(); + const keyName = this.state.value; + if (attrNames.has(keyName)) { + this.raise(Errors.ModuleAttributesWithDuplicateKeys, this.state.startLoc, { + key: keyName + }); + } + attrNames.add(keyName); + if (this.match(134)) { + node.key = this.parseStringLiteral(keyName); + } else { + node.key = this.parseIdentifier(true); + } + this.expect(14); + if (!this.match(134)) { + throw this.raise(Errors.ModuleAttributeInvalidValue, this.state.startLoc); + } + node.value = this.parseStringLiteral(this.state.value); + attrs.push(this.finishNode(node, "ImportAttribute")); + } while (this.eat(12)); + this.expect(8); + return attrs; + } + parseModuleAttributes() { + const attrs = []; + const attributes = new Set(); + do { + const node = this.startNode(); + node.key = this.parseIdentifier(true); + if (node.key.name !== "type") { + this.raise(Errors.ModuleAttributeDifferentFromType, node.key); + } + if (attributes.has(node.key.name)) { + this.raise(Errors.ModuleAttributesWithDuplicateKeys, node.key, { + key: node.key.name + }); + } + attributes.add(node.key.name); + this.expect(14); + if (!this.match(134)) { + throw this.raise(Errors.ModuleAttributeInvalidValue, this.state.startLoc); + } + node.value = this.parseStringLiteral(this.state.value); + attrs.push(this.finishNode(node, "ImportAttribute")); + } while (this.eat(12)); + return attrs; + } + maybeParseImportAttributes(node) { + let attributes; + var useWith = false; + if (this.match(76)) { + if (this.hasPrecedingLineBreak() && this.lookaheadCharCode() === 40) { + return; + } + this.next(); + if (this.hasPlugin("moduleAttributes")) { + attributes = this.parseModuleAttributes(); + this.addExtra(node, "deprecatedWithLegacySyntax", true); + } else { + attributes = this.parseImportAttributes(); + } + useWith = true; + } else if (this.isContextual(94) && !this.hasPrecedingLineBreak()) { + if (!this.hasPlugin("deprecatedImportAssert") && !this.hasPlugin("importAssertions")) { + this.raise(Errors.ImportAttributesUseAssert, this.state.startLoc); + } + if (!this.hasPlugin("importAssertions")) { + this.addExtra(node, "deprecatedAssertSyntax", true); + } + this.next(); + attributes = this.parseImportAttributes(); + } else { + attributes = []; + } + if (!useWith && this.hasPlugin("importAssertions")) { + node.assertions = attributes; + } else { + node.attributes = attributes; + } + } + maybeParseDefaultImportSpecifier(node, maybeDefaultIdentifier) { + if (maybeDefaultIdentifier) { + const specifier = this.startNodeAtNode(maybeDefaultIdentifier); + specifier.local = maybeDefaultIdentifier; + node.specifiers.push(this.finishImportSpecifier(specifier, "ImportDefaultSpecifier")); + return true; + } else if (tokenIsKeywordOrIdentifier(this.state.type)) { + this.parseImportSpecifierLocal(node, this.startNode(), "ImportDefaultSpecifier"); + return true; + } + return false; + } + maybeParseStarImportSpecifier(node) { + if (this.match(55)) { + const specifier = this.startNode(); + this.next(); + this.expectContextual(93); + this.parseImportSpecifierLocal(node, specifier, "ImportNamespaceSpecifier"); + return true; + } + return false; + } + parseNamedImportSpecifiers(node) { + let first = true; + this.expect(5); + while (!this.eat(8)) { + if (first) { + first = false; + } else { + if (this.eat(14)) { + throw this.raise(Errors.DestructureNamedImport, this.state.startLoc); + } + this.expect(12); + if (this.eat(8)) break; + } + const specifier = this.startNode(); + const importedIsString = this.match(134); + const isMaybeTypeOnly = this.isContextual(130); + specifier.imported = this.parseModuleExportName(); + const importSpecifier = this.parseImportSpecifier(specifier, importedIsString, node.importKind === "type" || node.importKind === "typeof", isMaybeTypeOnly, undefined); + node.specifiers.push(importSpecifier); + } + } + parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, bindingType) { + if (this.eatContextual(93)) { + specifier.local = this.parseIdentifier(); + } else { + const { + imported + } = specifier; + if (importedIsString) { + throw this.raise(Errors.ImportBindingIsString, specifier, { + importName: imported.value + }); + } + this.checkReservedWord(imported.name, specifier.loc.start, true, true); + if (!specifier.local) { + specifier.local = this.cloneIdentifier(imported); + } + } + return this.finishImportSpecifier(specifier, "ImportSpecifier", bindingType); + } + isThisParam(param) { + return param.type === "Identifier" && param.name === "this"; + } +} +class Parser extends StatementParser { + constructor(options, input, pluginsMap) { + const normalizedOptions = getOptions(options); + super(normalizedOptions, input); + this.options = normalizedOptions; + this.initializeScopes(); + this.plugins = pluginsMap; + this.filename = normalizedOptions.sourceFilename; + this.startIndex = normalizedOptions.startIndex; + let optionFlags = 0; + if (normalizedOptions.allowAwaitOutsideFunction) { + optionFlags |= 1; + } + if (normalizedOptions.allowReturnOutsideFunction) { + optionFlags |= 2; + } + if (normalizedOptions.allowImportExportEverywhere) { + optionFlags |= 8; + } + if (normalizedOptions.allowSuperOutsideMethod) { + optionFlags |= 16; + } + if (normalizedOptions.allowUndeclaredExports) { + optionFlags |= 64; + } + if (normalizedOptions.allowNewTargetOutsideFunction) { + optionFlags |= 4; + } + if (normalizedOptions.allowYieldOutsideFunction) { + optionFlags |= 32; + } + if (normalizedOptions.ranges) { + optionFlags |= 128; + } + if (normalizedOptions.tokens) { + optionFlags |= 256; + } + if (normalizedOptions.createImportExpressions) { + optionFlags |= 512; + } + if (normalizedOptions.createParenthesizedExpressions) { + optionFlags |= 1024; + } + if (normalizedOptions.errorRecovery) { + optionFlags |= 2048; + } + if (normalizedOptions.attachComment) { + optionFlags |= 4096; + } + if (normalizedOptions.annexB) { + optionFlags |= 8192; + } + this.optionFlags = optionFlags; + } + getScopeHandler() { + return ScopeHandler; + } + parse() { + this.enterInitialScopes(); + const file = this.startNode(); + const program = this.startNode(); + this.nextToken(); + file.errors = null; + const result = this.parseTopLevel(file, program); + result.errors = this.state.errors; + result.comments.length = this.state.commentsLen; + return result; + } +} +function parse(input, options) { + var _options; + if (((_options = options) == null ? void 0 : _options.sourceType) === "unambiguous") { + options = Object.assign({}, options); + try { + options.sourceType = "module"; + const parser = getParser(options, input); + const ast = parser.parse(); + if (parser.sawUnambiguousESM) { + return ast; + } + if (parser.ambiguousScriptDifferentAst) { + try { + options.sourceType = "script"; + return getParser(options, input).parse(); + } catch (_unused) {} + } else { + ast.program.sourceType = "script"; + } + return ast; + } catch (moduleError) { + try { + options.sourceType = "script"; + return getParser(options, input).parse(); + } catch (_unused2) {} + throw moduleError; + } + } else { + return getParser(options, input).parse(); + } +} +function parseExpression(input, options) { + const parser = getParser(options, input); + if (parser.options.strictMode) { + parser.state.strict = true; + } + return parser.getExpression(); +} +function generateExportedTokenTypes(internalTokenTypes) { + const tokenTypes = {}; + for (const typeName of Object.keys(internalTokenTypes)) { + tokenTypes[typeName] = getExportedToken(internalTokenTypes[typeName]); + } + return tokenTypes; +} +const tokTypes = generateExportedTokenTypes(tt); +function getParser(options, input) { + let cls = Parser; + const pluginsMap = new Map(); + if (options != null && options.plugins) { + for (const plugin of options.plugins) { + let name, opts; + if (typeof plugin === "string") { + name = plugin; + } else { + [name, opts] = plugin; + } + if (!pluginsMap.has(name)) { + pluginsMap.set(name, opts || {}); + } + } + validatePlugins(pluginsMap); + cls = getParserClass(pluginsMap); + } + return new cls(options, input, pluginsMap); +} +const parserClassCache = new Map(); +function getParserClass(pluginsMap) { + const pluginList = []; + for (const name of mixinPluginNames) { + if (pluginsMap.has(name)) { + pluginList.push(name); + } + } + const key = pluginList.join("|"); + let cls = parserClassCache.get(key); + if (!cls) { + cls = Parser; + for (const plugin of pluginList) { + cls = mixinPlugins[plugin](cls); + } + parserClassCache.set(key, cls); + } + return cls; +} +exports.parse = parse; +exports.parseExpression = parseExpression; +exports.tokTypes = tokTypes; +//# sourceMappingURL=index.js.map diff --git a/node_modules/@babel/parser/lib/index.js.map b/node_modules/@babel/parser/lib/index.js.map new file mode 100644 index 00000000..deeef61a --- /dev/null +++ b/node_modules/@babel/parser/lib/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sources":["../src/util/location.ts","../src/parse-error/module-errors.ts","../src/parse-error/to-node-description.ts","../src/parse-error/standard-errors.ts","../src/parse-error/strict-mode-errors.ts","../src/parse-error/parse-expression-errors.ts","../src/parse-error/pipeline-operator-errors.ts","../src/parse-error.ts","../src/options.ts","../src/plugins/estree.ts","../src/tokenizer/context.ts","../src/tokenizer/types.ts","../../babel-helper-validator-identifier/src/identifier.ts","../../babel-helper-validator-identifier/src/keyword.ts","../src/util/identifier.ts","../src/util/scope.ts","../src/plugins/flow/scope.ts","../src/plugins/flow/index.ts","../src/plugins/jsx/xhtml.ts","../src/util/whitespace.ts","../src/plugins/jsx/index.ts","../src/plugins/typescript/scope.ts","../src/util/production-parameter.ts","../src/parser/base.ts","../src/parser/comments.ts","../src/tokenizer/state.ts","../../babel-helper-string-parser/src/index.ts","../src/tokenizer/index.ts","../src/util/class-scope.ts","../src/util/expression-scope.ts","../src/parser/util.ts","../src/parser/node.ts","../src/parser/lval.ts","../src/plugins/typescript/index.ts","../src/plugins/placeholders.ts","../src/plugins/v8intrinsic.ts","../src/plugin-utils.ts","../src/parser/expression.ts","../src/parser/statement.ts","../src/parser/index.ts","../src/index.ts"],"sourcesContent":["export type Pos = {\n start: number;\n};\n\n// These are used when `options.locations` is on, for the\n// `startLoc` and `endLoc` properties.\n\nexport class Position {\n line: number;\n column: number;\n index: number;\n\n constructor(line: number, col: number, index: number) {\n this.line = line;\n this.column = col;\n this.index = index;\n }\n}\n\nexport class SourceLocation {\n start: Position;\n end: Position;\n filename: string | undefined;\n identifierName: string | undefined | null;\n\n constructor(start: Position, end?: Position) {\n this.start = start;\n // (may start as null, but initialized later)\n this.end = end!;\n }\n}\n\n/**\n * creates a new position with a non-zero column offset from the given position.\n * This function should be only be used when we create AST node out of the token\n * boundaries, such as TemplateElement ends before tt.templateNonTail. This\n * function does not skip whitespaces.\n */\nexport function createPositionWithColumnOffset(\n position: Position,\n columnOffset: number,\n) {\n const { line, column, index } = position;\n return new Position(line, column + columnOffset, index + columnOffset);\n}\n","import type { ParseErrorTemplates } from \"../parse-error.ts\";\n\nconst code = \"BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED\";\n\nexport default {\n ImportMetaOutsideModule: {\n message: `import.meta may appear only with 'sourceType: \"module\"'`,\n code,\n },\n ImportOutsideModule: {\n message: `'import' and 'export' may appear only with 'sourceType: \"module\"'`,\n code,\n },\n} satisfies ParseErrorTemplates;\n","const NodeDescriptions = {\n ArrayPattern: \"array destructuring pattern\",\n AssignmentExpression: \"assignment expression\",\n AssignmentPattern: \"assignment expression\",\n ArrowFunctionExpression: \"arrow function expression\",\n ConditionalExpression: \"conditional expression\",\n CatchClause: \"catch clause\",\n ForOfStatement: \"for-of statement\",\n ForInStatement: \"for-in statement\",\n ForStatement: \"for-loop\",\n FormalParameters: \"function parameter list\",\n Identifier: \"identifier\",\n ImportSpecifier: \"import specifier\",\n ImportDefaultSpecifier: \"import default specifier\",\n ImportNamespaceSpecifier: \"import namespace specifier\",\n ObjectPattern: \"object destructuring pattern\",\n ParenthesizedExpression: \"parenthesized expression\",\n RestElement: \"rest element\",\n UpdateExpression: {\n true: \"prefix operation\",\n false: \"postfix operation\",\n },\n VariableDeclarator: \"variable declaration\",\n YieldExpression: \"yield expression\",\n};\n\ntype NodeTypesWithDescriptions = keyof Omit<\n typeof NodeDescriptions,\n \"UpdateExpression\"\n>;\n\ntype NodeWithDescription =\n | {\n type: \"UpdateExpression\";\n prefix: boolean;\n }\n | {\n type: NodeTypesWithDescriptions;\n };\n\nconst toNodeDescription = (node: NodeWithDescription) =>\n node.type === \"UpdateExpression\"\n ? NodeDescriptions.UpdateExpression[`${node.prefix}`]\n : NodeDescriptions[node.type];\n\nexport default toNodeDescription;\n","import type { ParseErrorTemplates } from \"../parse-error.ts\";\nimport toNodeDescription from \"./to-node-description.ts\";\n\nexport type LValAncestor =\n | { type: \"UpdateExpression\"; prefix: boolean }\n | {\n type:\n | \"ArrayPattern\"\n | \"AssignmentExpression\"\n | \"CatchClause\"\n | \"ForOfStatement\"\n | \"FormalParameters\"\n | \"ForInStatement\"\n | \"ForStatement\"\n | \"ImportSpecifier\"\n | \"ImportNamespaceSpecifier\"\n | \"ImportDefaultSpecifier\"\n | \"ParenthesizedExpression\"\n | \"ObjectPattern\"\n | \"RestElement\"\n | \"VariableDeclarator\";\n };\n\nexport default {\n AccessorIsGenerator: ({ kind }: { kind: \"get\" | \"set\" }) =>\n `A ${kind}ter cannot be a generator.`,\n ArgumentsInClass:\n \"'arguments' is only allowed in functions and class methods.\",\n AsyncFunctionInSingleStatementContext:\n \"Async functions can only be declared at the top level or inside a block.\",\n AwaitBindingIdentifier:\n \"Can not use 'await' as identifier inside an async function.\",\n AwaitBindingIdentifierInStaticBlock:\n \"Can not use 'await' as identifier inside a static block.\",\n AwaitExpressionFormalParameter:\n \"'await' is not allowed in async function parameters.\",\n AwaitUsingNotInAsyncContext:\n \"'await using' is only allowed within async functions and at the top levels of modules.\",\n AwaitNotInAsyncContext:\n \"'await' is only allowed within async functions and at the top levels of modules.\",\n BadGetterArity: \"A 'get' accessor must not have any formal parameters.\",\n BadSetterArity: \"A 'set' accessor must have exactly one formal parameter.\",\n BadSetterRestParameter:\n \"A 'set' accessor function argument must not be a rest parameter.\",\n ConstructorClassField: \"Classes may not have a field named 'constructor'.\",\n ConstructorClassPrivateField:\n \"Classes may not have a private field named '#constructor'.\",\n ConstructorIsAccessor: \"Class constructor may not be an accessor.\",\n ConstructorIsAsync: \"Constructor can't be an async function.\",\n ConstructorIsGenerator: \"Constructor can't be a generator.\",\n DeclarationMissingInitializer: ({\n kind,\n }: {\n kind: \"await using\" | \"const\" | \"destructuring\" | \"using\";\n }) => `Missing initializer in ${kind} declaration.`,\n DecoratorArgumentsOutsideParentheses:\n \"Decorator arguments must be moved inside parentheses: use '@(decorator(args))' instead of '@(decorator)(args)'.\",\n DecoratorBeforeExport:\n \"Decorators must be placed *before* the 'export' keyword. Remove the 'decoratorsBeforeExport: true' option to use the 'export @decorator class {}' syntax.\",\n DecoratorsBeforeAfterExport:\n \"Decorators can be placed *either* before or after the 'export' keyword, but not in both locations at the same time.\",\n DecoratorConstructor:\n \"Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?\",\n DecoratorExportClass:\n \"Decorators must be placed *after* the 'export' keyword. Remove the 'decoratorsBeforeExport: false' option to use the '@decorator export class {}' syntax.\",\n DecoratorSemicolon: \"Decorators must not be followed by a semicolon.\",\n DecoratorStaticBlock: \"Decorators can't be used with a static block.\",\n DeferImportRequiresNamespace:\n 'Only `import defer * as x from \"./module\"` is valid.',\n DeletePrivateField: \"Deleting a private field is not allowed.\",\n DestructureNamedImport:\n \"ES2015 named imports do not destructure. Use another statement for destructuring after the import.\",\n DuplicateConstructor: \"Duplicate constructor in the same class.\",\n DuplicateDefaultExport: \"Only one default export allowed per module.\",\n DuplicateExport: ({ exportName }: { exportName: string }) =>\n `\\`${exportName}\\` has already been exported. Exported identifiers must be unique.`,\n DuplicateProto: \"Redefinition of __proto__ property.\",\n DuplicateRegExpFlags: \"Duplicate regular expression flag.\",\n ElementAfterRest: \"Rest element must be last element.\",\n EscapedCharNotAnIdentifier: \"Invalid Unicode escape.\",\n ExportBindingIsString: ({\n localName,\n exportName,\n }: {\n localName: string;\n exportName: string;\n }) =>\n `A string literal cannot be used as an exported binding without \\`from\\`.\\n- Did you mean \\`export { '${localName}' as '${exportName}' } from 'some-module'\\`?`,\n ExportDefaultFromAsIdentifier:\n \"'from' is not allowed as an identifier after 'export default'.\",\n\n ForInOfLoopInitializer: ({\n type,\n }: {\n type: \"ForInStatement\" | \"ForOfStatement\";\n }) =>\n `'${\n type === \"ForInStatement\" ? \"for-in\" : \"for-of\"\n }' loop variable declaration may not have an initializer.`,\n ForInUsing: \"For-in loop may not start with 'using' declaration.\",\n\n ForOfAsync: \"The left-hand side of a for-of loop may not be 'async'.\",\n ForOfLet: \"The left-hand side of a for-of loop may not start with 'let'.\",\n GeneratorInSingleStatementContext:\n \"Generators can only be declared at the top level or inside a block.\",\n\n IllegalBreakContinue: ({\n type,\n }: {\n type: \"BreakStatement\" | \"ContinueStatement\";\n }) => `Unsyntactic ${type === \"BreakStatement\" ? \"break\" : \"continue\"}.`,\n\n IllegalLanguageModeDirective:\n \"Illegal 'use strict' directive in function with non-simple parameter list.\",\n IllegalReturn: \"'return' outside of function.\",\n ImportAttributesUseAssert:\n \"The `assert` keyword in import attributes is deprecated and it has been replaced by the `with` keyword. You can enable the `deprecatedImportAssert` parser plugin to suppress this error.\",\n ImportBindingIsString: ({ importName }: { importName: string }) =>\n `A string literal cannot be used as an imported binding.\\n- Did you mean \\`import { \"${importName}\" as foo }\\`?`,\n ImportCallArity: `\\`import()\\` requires exactly one or two arguments.`,\n ImportCallNotNewExpression: \"Cannot use new with import(...).\",\n ImportCallSpreadArgument: \"`...` is not allowed in `import()`.\",\n ImportJSONBindingNotDefault:\n \"A JSON module can only be imported with `default`.\",\n ImportReflectionHasAssertion: \"`import module x` cannot have assertions.\",\n ImportReflectionNotBinding:\n 'Only `import module x from \"./module\"` is valid.',\n IncompatibleRegExpUVFlags:\n \"The 'u' and 'v' regular expression flags cannot be enabled at the same time.\",\n InvalidBigIntLiteral: \"Invalid BigIntLiteral.\",\n InvalidCodePoint: \"Code point out of bounds.\",\n InvalidCoverDiscardElement:\n \"'void' must be followed by an expression when not used in a binding position.\",\n InvalidCoverInitializedName: \"Invalid shorthand property initializer.\",\n InvalidDecimal: \"Invalid decimal.\",\n InvalidDigit: ({ radix }: { radix: number }) =>\n `Expected number in radix ${radix}.`,\n InvalidEscapeSequence: \"Bad character escape sequence.\",\n InvalidEscapeSequenceTemplate: \"Invalid escape sequence in template.\",\n InvalidEscapedReservedWord: ({ reservedWord }: { reservedWord: string }) =>\n `Escape sequence in keyword ${reservedWord}.`,\n InvalidIdentifier: ({ identifierName }: { identifierName: string }) =>\n `Invalid identifier ${identifierName}.`,\n InvalidLhs: ({ ancestor }: { ancestor: LValAncestor }) =>\n `Invalid left-hand side in ${toNodeDescription(ancestor)}.`,\n InvalidLhsBinding: ({ ancestor }: { ancestor: LValAncestor }) =>\n `Binding invalid left-hand side in ${toNodeDescription(ancestor)}.`,\n InvalidLhsOptionalChaining: ({ ancestor }: { ancestor: LValAncestor }) =>\n `Invalid optional chaining in the left-hand side of ${toNodeDescription(\n ancestor,\n )}.`,\n InvalidNumber: \"Invalid number.\",\n InvalidOrMissingExponent:\n \"Floating-point numbers require a valid exponent after the 'e'.\",\n InvalidOrUnexpectedToken: ({ unexpected }: { unexpected: string }) =>\n `Unexpected character '${unexpected}'.`,\n InvalidParenthesizedAssignment: \"Invalid parenthesized assignment pattern.\",\n InvalidPrivateFieldResolution: ({\n identifierName,\n }: {\n identifierName: string;\n }) => `Private name #${identifierName} is not defined.`,\n InvalidPropertyBindingPattern: \"Binding member expression.\",\n InvalidRecordProperty:\n \"Only properties and spread elements are allowed in record definitions.\",\n InvalidRestAssignmentPattern: \"Invalid rest operator's argument.\",\n LabelRedeclaration: ({ labelName }: { labelName: string }) =>\n `Label '${labelName}' is already declared.`,\n LetInLexicalBinding: \"'let' is disallowed as a lexically bound name.\",\n LineTerminatorBeforeArrow: \"No line break is allowed before '=>'.\",\n MalformedRegExpFlags: \"Invalid regular expression flag.\",\n MissingClassName: \"A class name is required.\",\n MissingEqInAssignment:\n \"Only '=' operator can be used for specifying default value.\",\n MissingSemicolon: \"Missing semicolon.\",\n MissingPlugin: ({ missingPlugin }: { missingPlugin: [string] }) =>\n `This experimental syntax requires enabling the parser plugin: ${missingPlugin\n .map(name => JSON.stringify(name))\n .join(\", \")}.`,\n // FIXME: Would be nice to make this \"missingPlugins\" instead.\n // Also, seems like we can drop the \"(s)\" from the message and just make it \"s\".\n MissingOneOfPlugins: ({ missingPlugin }: { missingPlugin: string[] }) =>\n `This experimental syntax requires enabling one of the following parser plugin(s): ${missingPlugin\n .map(name => JSON.stringify(name))\n .join(\", \")}.`,\n MissingUnicodeEscape: \"Expecting Unicode escape sequence \\\\uXXXX.\",\n MixingCoalesceWithLogical:\n \"Nullish coalescing operator(??) requires parens when mixing with logical operators.\",\n ModuleAttributeDifferentFromType:\n \"The only accepted module attribute is `type`.\",\n ModuleAttributeInvalidValue:\n \"Only string literals are allowed as module attribute values.\",\n ModuleAttributesWithDuplicateKeys: ({ key }: { key: string }) =>\n `Duplicate key \"${key}\" is not allowed in module attributes.`,\n ModuleExportNameHasLoneSurrogate: ({\n surrogateCharCode,\n }: {\n surrogateCharCode: number;\n }) =>\n `An export name cannot include a lone surrogate, found '\\\\u${surrogateCharCode.toString(\n 16,\n )}'.`,\n ModuleExportUndefined: ({ localName }: { localName: string }) =>\n `Export '${localName}' is not defined.`,\n MultipleDefaultsInSwitch: \"Multiple default clauses.\",\n NewlineAfterThrow: \"Illegal newline after throw.\",\n NoCatchOrFinally: \"Missing catch or finally clause.\",\n NumberIdentifier: \"Identifier directly after number.\",\n NumericSeparatorInEscapeSequence:\n \"Numeric separators are not allowed inside unicode escape sequences or hex escape sequences.\",\n ObsoleteAwaitStar:\n \"'await*' has been removed from the async functions proposal. Use Promise.all() instead.\",\n OptionalChainingNoNew:\n \"Constructors in/after an Optional Chain are not allowed.\",\n OptionalChainingNoTemplate:\n \"Tagged Template Literals are not allowed in optionalChain.\",\n OverrideOnConstructor:\n \"'override' modifier cannot appear on a constructor declaration.\",\n ParamDupe: \"Argument name clash.\",\n PatternHasAccessor: \"Object pattern can't contain getter or setter.\",\n PatternHasMethod: \"Object pattern can't contain methods.\",\n PrivateInExpectedIn: ({ identifierName }: { identifierName: string }) =>\n `Private names are only allowed in property accesses (\\`obj.#${identifierName}\\`) or in \\`in\\` expressions (\\`#${identifierName} in obj\\`).`,\n PrivateNameRedeclaration: ({ identifierName }: { identifierName: string }) =>\n `Duplicate private name #${identifierName}.`,\n RecordExpressionBarIncorrectEndSyntaxType:\n \"Record expressions ending with '|}' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.\",\n RecordExpressionBarIncorrectStartSyntaxType:\n \"Record expressions starting with '{|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.\",\n RecordExpressionHashIncorrectStartSyntaxType:\n \"Record expressions starting with '#{' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.\",\n RecordNoProto: \"'__proto__' is not allowed in Record expressions.\",\n RestTrailingComma: \"Unexpected trailing comma after rest element.\",\n SloppyFunction:\n \"In non-strict mode code, functions can only be declared at top level or inside a block.\",\n SloppyFunctionAnnexB:\n \"In non-strict mode code, functions can only be declared at top level, inside a block, or as the body of an if statement.\",\n SourcePhaseImportRequiresDefault:\n 'Only `import source x from \"./module\"` is valid.',\n StaticPrototype: \"Classes may not have static property named prototype.\",\n SuperNotAllowed:\n \"`super()` is only valid inside a class constructor of a subclass. Maybe a typo in the method name ('constructor') or not extending another class?\",\n SuperPrivateField: \"Private fields can't be accessed on super.\",\n TrailingDecorator: \"Decorators must be attached to a class element.\",\n TupleExpressionBarIncorrectEndSyntaxType:\n \"Tuple expressions ending with '|]' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.\",\n TupleExpressionBarIncorrectStartSyntaxType:\n \"Tuple expressions starting with '[|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.\",\n TupleExpressionHashIncorrectStartSyntaxType:\n \"Tuple expressions starting with '#[' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.\",\n UnexpectedArgumentPlaceholder: \"Unexpected argument placeholder.\",\n UnexpectedAwaitAfterPipelineBody:\n 'Unexpected \"await\" after pipeline body; await must have parentheses in minimal proposal.',\n UnexpectedDigitAfterHash: \"Unexpected digit after hash token.\",\n UnexpectedImportExport:\n \"'import' and 'export' may only appear at the top level.\",\n UnexpectedKeyword: ({ keyword }: { keyword: string }) =>\n `Unexpected keyword '${keyword}'.`,\n UnexpectedLeadingDecorator:\n \"Leading decorators must be attached to a class declaration.\",\n UnexpectedLexicalDeclaration:\n \"Lexical declaration cannot appear in a single-statement context.\",\n UnexpectedNewTarget:\n \"`new.target` can only be used in functions or class properties.\",\n UnexpectedNumericSeparator:\n \"A numeric separator is only allowed between two digits.\",\n UnexpectedPrivateField: \"Unexpected private name.\",\n UnexpectedReservedWord: ({ reservedWord }: { reservedWord: string }) =>\n `Unexpected reserved word '${reservedWord}'.`,\n UnexpectedSuper: \"'super' is only allowed in object methods and classes.\",\n UnexpectedToken: ({\n expected,\n unexpected,\n }: {\n expected?: string | null;\n unexpected?: string | null;\n }) =>\n `Unexpected token${unexpected ? ` '${unexpected}'.` : \"\"}${\n expected ? `, expected \"${expected}\"` : \"\"\n }`,\n UnexpectedTokenUnaryExponentiation:\n \"Illegal expression. Wrap left hand side or entire exponentiation in parentheses.\",\n UnexpectedUsingDeclaration:\n \"Using declaration cannot appear in the top level when source type is `script` or in the bare case statement.\",\n UnexpectedVoidPattern: \"Unexpected void binding.\",\n UnsupportedBind: \"Binding should be performed on object property.\",\n UnsupportedDecoratorExport:\n \"A decorated export must export a class declaration.\",\n UnsupportedDefaultExport:\n \"Only expressions, functions or classes are allowed as the `default` export.\",\n UnsupportedImport:\n \"`import` can only be used in `import()` or `import.meta`.\",\n UnsupportedMetaProperty: ({\n target,\n onlyValidPropertyName,\n }: {\n target: string;\n onlyValidPropertyName: string;\n }) =>\n `The only valid meta property for ${target} is ${target}.${onlyValidPropertyName}.`,\n UnsupportedParameterDecorator:\n \"Decorators cannot be used to decorate parameters.\",\n UnsupportedPropertyDecorator:\n \"Decorators cannot be used to decorate object literal properties.\",\n UnsupportedSuper:\n \"'super' can only be used with function calls (i.e. super()) or in property accesses (i.e. super.prop or super[prop]).\",\n UnterminatedComment: \"Unterminated comment.\",\n UnterminatedRegExp: \"Unterminated regular expression.\",\n UnterminatedString: \"Unterminated string constant.\",\n UnterminatedTemplate: \"Unterminated template.\",\n UsingDeclarationExport: \"Using declaration cannot be exported.\",\n UsingDeclarationHasBindingPattern:\n \"Using declaration cannot have destructuring patterns.\",\n VarRedeclaration: ({ identifierName }: { identifierName: string }) =>\n `Identifier '${identifierName}' has already been declared.`,\n VoidPatternCatchClauseParam:\n \"A void binding can not be the catch clause parameter. Use `try { ... } catch { ... }` if you want to discard the caught error.\",\n VoidPatternInitializer: \"A void binding may not have an initializer.\",\n YieldBindingIdentifier:\n \"Can not use 'yield' as identifier inside a generator.\",\n YieldInParameter: \"Yield expression is not allowed in formal parameters.\",\n YieldNotInGeneratorFunction:\n \"'yield' is only allowed within generator functions.\",\n ZeroDigitNumericSeparator:\n \"Numeric separator can not be used after leading 0.\",\n} satisfies ParseErrorTemplates;\n","import type { ParseErrorTemplates } from \"../parse-error\";\n\nexport default {\n StrictDelete: \"Deleting local variable in strict mode.\",\n\n // `referenceName` is the StringValue[1] of an IdentifierReference[2], which\n // is represented as just an `Identifier`[3] in the Babel AST.\n // 1. https://tc39.es/ecma262/#sec-static-semantics-stringvalue\n // 2. https://tc39.es/ecma262/#prod-IdentifierReference\n // 3. https://github.com/babel/babel/blob/main/packages/babel-parser/ast/spec.md#identifier\n StrictEvalArguments: ({ referenceName }: { referenceName: string }) =>\n `Assigning to '${referenceName}' in strict mode.`,\n\n // `bindingName` is the StringValue[1] of a BindingIdentifier[2], which is\n // represented as just an `Identifier`[3] in the Babel AST.\n // 1. https://tc39.es/ecma262/#sec-static-semantics-stringvalue\n // 2. https://tc39.es/ecma262/#prod-BindingIdentifier\n // 3. https://github.com/babel/babel/blob/main/packages/babel-parser/ast/spec.md#identifier\n StrictEvalArgumentsBinding: ({ bindingName }: { bindingName: string }) =>\n `Binding '${bindingName}' in strict mode.`,\n\n StrictFunction:\n \"In strict mode code, functions can only be declared at top level or inside a block.\",\n\n StrictNumericEscape: \"The only valid numeric escape in strict mode is '\\\\0'.\",\n\n StrictOctalLiteral: \"Legacy octal literals are not allowed in strict mode.\",\n\n StrictWith: \"'with' in strict mode.\",\n} satisfies ParseErrorTemplates;\n","import type { ParseErrorTemplates } from \"../parse-error.ts\";\n\nexport default {\n ParseExpressionEmptyInput:\n \"Unexpected parseExpression() input: The input is empty or contains only comments.\",\n ParseExpressionExpectsEOF: ({ unexpected }: { unexpected: number }) =>\n `Unexpected parseExpression() input: The input should contain exactly one expression, but the first expression is followed by the unexpected character \\`${String.fromCodePoint(unexpected)}\\`.`,\n} satisfies ParseErrorTemplates;\n","import type { ParseErrorTemplates } from \"../parse-error.ts\";\nimport toNodeDescription from \"./to-node-description.ts\";\n\nexport const UnparenthesizedPipeBodyDescriptions = new Set([\n \"ArrowFunctionExpression\",\n \"AssignmentExpression\",\n \"ConditionalExpression\",\n \"YieldExpression\",\n] as const);\n\ntype GetSetMemberType> =\n T extends Set ? M : unknown;\n\nexport type UnparenthesizedPipeBodyTypes = GetSetMemberType<\n typeof UnparenthesizedPipeBodyDescriptions\n>;\n\nexport default {\n // This error is only used by the smart-mix proposal\n PipeBodyIsTighter:\n \"Unexpected yield after pipeline body; any yield expression acting as Hack-style pipe body must be parenthesized due to its loose operator precedence.\",\n PipeTopicRequiresHackPipes: process.env.BABEL_8_BREAKING\n ? 'Topic references are only supported when using the `\"proposal\": \"hack\"` version of the pipeline proposal.'\n : 'Topic reference is used, but the pipelineOperator plugin was not passed a \"proposal\": \"hack\" or \"smart\" option.',\n PipeTopicUnbound:\n \"Topic reference is unbound; it must be inside a pipe body.\",\n PipeTopicUnconfiguredToken: ({ token }: { token: string }) =>\n `Invalid topic token ${token}. In order to use ${token} as a topic reference, the pipelineOperator plugin must be configured with { \"proposal\": \"hack\", \"topicToken\": \"${token}\" }.`,\n PipeTopicUnused:\n \"Hack-style pipe body does not contain a topic reference; Hack-style pipes must use topic at least once.\",\n PipeUnparenthesizedBody: ({ type }: { type: UnparenthesizedPipeBodyTypes }) =>\n `Hack-style pipe body cannot be an unparenthesized ${toNodeDescription({\n type,\n })}; please wrap it in parentheses.`,\n\n ...(process.env.BABEL_8_BREAKING\n ? {}\n : {\n // Messages whose codes start with “Pipeline” or “PrimaryTopic”\n // are retained for backwards compatibility\n // with the deprecated smart-mix pipe operator proposal plugin.\n // They are subject to removal in a future major version.\n PipelineBodyNoArrow:\n 'Unexpected arrow \"=>\" after pipeline body; arrow function in pipeline body must be parenthesized.',\n PipelineBodySequenceExpression:\n \"Pipeline body may not be a comma-separated sequence expression.\",\n PipelineHeadSequenceExpression:\n \"Pipeline head should not be a comma-separated sequence expression.\",\n PipelineTopicUnused:\n \"Pipeline is in topic style but does not use topic reference.\",\n PrimaryTopicNotAllowed:\n \"Topic reference was used in a lexical context without topic binding.\",\n PrimaryTopicRequiresSmartPipeline:\n 'Topic reference is used, but the pipelineOperator plugin was not passed a \"proposal\": \"hack\" or \"smart\" option.',\n }),\n} satisfies ParseErrorTemplates;\n","import { Position } from \"./util/location.ts\";\n\ntype SyntaxPlugin =\n | \"flow\"\n | \"typescript\"\n | \"jsx\"\n | \"pipelineOperator\"\n | \"placeholders\";\n\ntype ParseErrorCode =\n | \"BABEL_PARSER_SYNTAX_ERROR\"\n | \"BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED\";\n\n// Babel uses \"normal\" SyntaxErrors for it's errors, but adds some extra\n// functionality. This functionality is defined in the\n// `ParseErrorSpecification` interface below. We may choose to change to someday\n// give our errors their own full-blown class, but until then this allow us to\n// keep all the desirable properties of SyntaxErrors (like their name in stack\n// traces, etc.), and also allows us to punt on any publicly facing\n// class-hierarchy decisions until Babel 8.\ninterface ParseErrorSpecification {\n // Look, these *could* be readonly, but then Flow complains when we initially\n // set them. We could do a whole dance and make a special interface that's not\n // readonly for when we create the error, then cast it to the readonly\n // interface for public use, but the previous implementation didn't have them\n // as readonly, so let's just not worry about it for now.\n code: ParseErrorCode;\n reasonCode: string;\n syntaxPlugin?: SyntaxPlugin;\n missingPlugin?: string | string[];\n loc: Position;\n details: ErrorDetails;\n\n // We should consider removing this as it now just contains the same\n // information as `loc.index`.\n pos: number;\n}\n\nexport type ParseError = SyntaxError &\n ParseErrorSpecification;\n\n// By `ParseErrorConstructor`, we mean something like the new-less style\n// `ErrorConstructor`[1], since `ParseError`'s are not themselves actually\n// separate classes from `SyntaxError`'s.\n//\n// 1. https://github.com/microsoft/TypeScript/blob/v4.5.5/lib/lib.es5.d.ts#L1027\nexport type ParseErrorConstructor = (\n loc: Position,\n details: ErrorDetails,\n) => ParseError;\n\ntype ToMessage = (self: ErrorDetails) => string;\n\ntype ParseErrorCredentials = {\n code: string;\n reasonCode: string;\n syntaxPlugin?: SyntaxPlugin;\n toMessage: ToMessage;\n};\n\nfunction defineHidden(obj: object, key: string, value: unknown) {\n Object.defineProperty(obj, key, {\n enumerable: false,\n configurable: true,\n value,\n });\n}\n\nfunction toParseErrorConstructor({\n toMessage,\n code,\n reasonCode,\n syntaxPlugin,\n}: ParseErrorCredentials): ParseErrorConstructor {\n const hasMissingPlugin =\n reasonCode === \"MissingPlugin\" || reasonCode === \"MissingOneOfPlugins\";\n\n if (!process.env.BABEL_8_BREAKING) {\n const oldReasonCodes: Record = {\n AccessorCannotDeclareThisParameter: \"AccesorCannotDeclareThisParameter\",\n AccessorCannotHaveTypeParameters: \"AccesorCannotHaveTypeParameters\",\n ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference:\n \"ConstInitiailizerMustBeStringOrNumericLiteralOrLiteralEnumReference\",\n SetAccessorCannotHaveOptionalParameter:\n \"SetAccesorCannotHaveOptionalParameter\",\n SetAccessorCannotHaveRestParameter: \"SetAccesorCannotHaveRestParameter\",\n SetAccessorCannotHaveReturnType: \"SetAccesorCannotHaveReturnType\",\n };\n if (oldReasonCodes[reasonCode]) {\n reasonCode = oldReasonCodes[reasonCode];\n }\n }\n\n return function constructor(loc: Position, details: ErrorDetails) {\n const error: ParseError = new SyntaxError() as any;\n\n error.code = code as ParseErrorCode;\n error.reasonCode = reasonCode;\n error.loc = loc;\n error.pos = loc.index;\n\n error.syntaxPlugin = syntaxPlugin;\n if (hasMissingPlugin) {\n error.missingPlugin = (details as any).missingPlugin;\n }\n\n type Overrides = {\n loc?: Position;\n details?: ErrorDetails;\n };\n defineHidden(error, \"clone\", function clone(overrides: Overrides = {}) {\n const { line, column, index } = overrides.loc ?? loc;\n return constructor(new Position(line, column, index), {\n ...details,\n ...overrides.details,\n });\n });\n\n defineHidden(error, \"details\", details);\n\n Object.defineProperty(error, \"message\", {\n configurable: true,\n get(this: ParseError): string {\n const message = `${toMessage(details)} (${loc.line}:${loc.column})`;\n this.message = message;\n return message;\n },\n set(value: string) {\n Object.defineProperty(this, \"message\", { value, writable: true });\n },\n });\n\n return error;\n };\n}\n\ntype ParseErrorTemplate =\n | string\n | ToMessage\n | { message: string | ToMessage; code?: ParseErrorCode };\n\nexport type ParseErrorTemplates = Record;\n\n// This is the templated form of `ParseErrorEnum`.\n//\n// Note: We could factor out the return type calculation into something like\n// `ParseErrorConstructor`, and then we could\n// reuse it in the non-templated form of `ParseErrorEnum`, but TypeScript\n// doesn't seem to drill down that far when showing you the computed type of\n// an object in an editor, so we'll leave it inlined for now.\nexport function ParseErrorEnum(a: TemplateStringsArray): <\n T extends ParseErrorTemplates,\n>(\n parseErrorTemplates: T,\n) => {\n [K in keyof T]: ParseErrorConstructor<\n T[K] extends { message: string | ToMessage }\n ? T[K][\"message\"] extends ToMessage\n ? Parameters[0]\n : object\n : T[K] extends ToMessage\n ? Parameters[0]\n : object\n >;\n};\n\nexport function ParseErrorEnum(\n parseErrorTemplates: T,\n syntaxPlugin?: SyntaxPlugin,\n): {\n [K in keyof T]: ParseErrorConstructor<\n T[K] extends { message: string | ToMessage }\n ? T[K][\"message\"] extends ToMessage\n ? Parameters[0]\n : object\n : T[K] extends ToMessage\n ? Parameters[0]\n : object\n >;\n};\n\n// You call `ParseErrorEnum` with a mapping from `ReasonCode`'s to either:\n//\n// 1. a static error message,\n// 2. `toMessage` functions that define additional necessary `details` needed by\n// the `ParseError`, or\n// 3. Objects that contain a `message` of one of the above and overridden `code`\n// and/or `reasonCode`:\n//\n// ParseErrorEnum `optionalSyntaxPlugin` ({\n// ErrorWithStaticMessage: \"message\",\n// ErrorWithDynamicMessage: ({ type } : { type: string }) => `${type}`),\n// ErrorWithOverriddenCodeAndOrReasonCode: {\n// message: ({ type }: { type: string }) => `${type}`),\n// code: \"AN_ERROR_CODE\",\n// ...(BABEL_8_BREAKING ? { } : { reasonCode: \"CustomErrorReasonCode\" })\n// }\n// });\n//\nexport function ParseErrorEnum(\n argument: TemplateStringsArray | ParseErrorTemplates,\n syntaxPlugin?: SyntaxPlugin,\n) {\n // If the first parameter is an array, that means we were called with a tagged\n // template literal. Extract the syntaxPlugin from this, and call again in\n // the \"normalized\" form.\n if (Array.isArray(argument)) {\n return (parseErrorTemplates: ParseErrorTemplates) =>\n ParseErrorEnum(parseErrorTemplates, argument[0]);\n }\n\n const ParseErrorConstructors = {} as Record<\n string,\n ParseErrorConstructor\n >;\n\n for (const reasonCode of Object.keys(argument)) {\n const template = (argument as ParseErrorTemplates)[reasonCode];\n const { message, ...rest } =\n typeof template === \"string\"\n ? { message: () => template }\n : typeof template === \"function\"\n ? { message: template }\n : template;\n const toMessage = typeof message === \"string\" ? () => message : message;\n\n ParseErrorConstructors[reasonCode] = toParseErrorConstructor({\n code: \"BABEL_PARSER_SYNTAX_ERROR\",\n reasonCode,\n toMessage,\n ...(syntaxPlugin ? { syntaxPlugin } : {}),\n ...rest,\n });\n }\n\n return ParseErrorConstructors;\n}\n\nimport ModuleErrors from \"./parse-error/module-errors.ts\";\nimport StandardErrors from \"./parse-error/standard-errors.ts\";\nimport StrictModeErrors from \"./parse-error/strict-mode-errors.ts\";\nimport ParseExpressionErrors from \"./parse-error/parse-expression-errors.ts\";\nimport PipelineOperatorErrors from \"./parse-error/pipeline-operator-errors.ts\";\n\nexport const Errors = {\n ...ParseErrorEnum(ModuleErrors),\n ...ParseErrorEnum(StandardErrors),\n ...ParseErrorEnum(StrictModeErrors),\n ...ParseErrorEnum(ParseExpressionErrors),\n ...ParseErrorEnum`pipelineOperator`(PipelineOperatorErrors),\n};\n\nexport type { LValAncestor } from \"./parse-error/standard-errors.ts\";\n","import type { Plugin } from \"./plugin-utils.ts\";\n\n// A second optional argument can be given to further configure\n// the parser process. These options are recognized:\n\nexport type SourceType = \"script\" | \"commonjs\" | \"module\" | \"unambiguous\";\n\nexport interface Options {\n /**\n * By default, import and export declarations can only appear at a program's top level.\n * Setting this option to true allows them anywhere where a statement is allowed.\n */\n allowImportExportEverywhere?: boolean;\n\n /**\n * By default, await use is not allowed outside of an async function.\n * Set this to true to accept such code.\n */\n allowAwaitOutsideFunction?: boolean;\n\n /**\n * By default, a return statement at the top level raises an error.\n * Set this to true to accept such code.\n */\n allowReturnOutsideFunction?: boolean;\n\n /**\n * By default, new.target use is not allowed outside of a function or class.\n * Set this to true to accept such code.\n */\n allowNewTargetOutsideFunction?: boolean;\n\n /**\n * By default, super calls are not allowed outside of a method.\n * Set this to true to accept such code.\n */\n allowSuperOutsideMethod?: boolean;\n\n /**\n * By default, exported identifiers must refer to a declared variable.\n * Set this to true to allow export statements to reference undeclared variables.\n */\n allowUndeclaredExports?: boolean;\n\n /**\n * By default, yield use is not allowed outside of a generator function.\n * Set this to true to accept such code.\n */\n\n allowYieldOutsideFunction?: boolean;\n\n /**\n * By default, Babel parser JavaScript code according to Annex B syntax.\n * Set this to `false` to disable such behavior.\n */\n annexB?: boolean;\n\n /**\n * By default, Babel attaches comments to adjacent AST nodes.\n * When this option is set to false, comments are not attached.\n * It can provide up to 30% performance improvement when the input code has many comments.\n * @babel/eslint-parser will set it for you.\n * It is not recommended to use attachComment: false with Babel transform,\n * as doing so removes all the comments in output code, and renders annotations such as\n * /* istanbul ignore next *\\/ nonfunctional.\n */\n attachComment?: boolean;\n\n /**\n * By default, Babel always throws an error when it finds some invalid code.\n * When this option is set to true, it will store the parsing error and\n * try to continue parsing the invalid input file.\n */\n errorRecovery?: boolean;\n\n /**\n * Indicate the mode the code should be parsed in.\n * Can be one of \"script\", \"commonjs\", \"module\", or \"unambiguous\". Defaults to \"script\".\n * \"unambiguous\" will make @babel/parser attempt to guess, based on the presence\n * of ES6 import or export statements.\n * Files with ES6 imports and exports are considered \"module\" and are otherwise \"script\".\n *\n * Use \"commonjs\" to parse code that is intended to be run in a CommonJS environment such as Node.js.\n */\n sourceType?: SourceType;\n\n /**\n * Correlate output AST nodes with their source filename.\n * Useful when generating code and source maps from the ASTs of multiple input files.\n */\n sourceFilename?: string;\n\n /**\n * By default, all source indexes start from 0.\n * You can provide a start index to alternatively start with.\n * Useful for integration with other source tools.\n */\n startIndex?: number;\n\n /**\n * By default, the first line of code parsed is treated as line 1.\n * You can provide a line number to alternatively start with.\n * Useful for integration with other source tools.\n */\n startLine?: number;\n\n /**\n * By default, the parsed code is treated as if it starts from line 1, column 0.\n * You can provide a column number to alternatively start with.\n * Useful for integration with other source tools.\n */\n startColumn?: number;\n\n /**\n * Array containing the plugins that you want to enable.\n */\n plugins?: Plugin[];\n\n /**\n * Should the parser work in strict mode.\n * Defaults to true if sourceType === 'module'. Otherwise, false.\n */\n strictMode?: boolean;\n\n /**\n * Adds a ranges property to each node: [node.start, node.end]\n */\n ranges?: boolean;\n\n /**\n * Adds all parsed tokens to a tokens property on the File node.\n */\n tokens?: boolean;\n\n /**\n * By default, the parser adds information about parentheses by setting\n * `extra.parenthesized` to `true` as needed.\n * When this option is `true` the parser creates `ParenthesizedExpression`\n * AST nodes instead of using the `extra` property.\n */\n createParenthesizedExpressions?: boolean;\n\n /**\n * The default is false in Babel 7 and true in Babel 8\n * Set this to true to parse it as an `ImportExpression` node.\n * Otherwise `import(foo)` is parsed as `CallExpression(Import, [Identifier(foo)])`.\n */\n createImportExpressions?: boolean;\n}\n\nexport const enum OptionFlags {\n AllowAwaitOutsideFunction = 1 << 0,\n AllowReturnOutsideFunction = 1 << 1,\n AllowNewTargetOutsideFunction = 1 << 2,\n AllowImportExportEverywhere = 1 << 3,\n AllowSuperOutsideMethod = 1 << 4,\n AllowYieldOutsideFunction = 1 << 5,\n AllowUndeclaredExports = 1 << 6,\n Ranges = 1 << 7,\n Tokens = 1 << 8,\n CreateImportExpressions = 1 << 9,\n CreateParenthesizedExpressions = 1 << 10,\n ErrorRecovery = 1 << 11,\n AttachComment = 1 << 12,\n AnnexB = 1 << 13,\n}\n\ntype KeepOptionalKeys = \"sourceFilename\" | \"strictMode\";\nexport type OptionsWithDefaults = Omit, KeepOptionalKeys> &\n Pick;\n\nfunction createDefaultOptions(): OptionsWithDefaults {\n return {\n // Source type (\"script\" or \"module\") for different semantics\n sourceType: \"script\",\n // Source filename.\n sourceFilename: undefined,\n // Index (0-based) from which to start counting source. Useful for\n // integration with other tools.\n startIndex: 0,\n // Column (0-based) from which to start counting source. Useful for\n // integration with other tools.\n startColumn: 0,\n // Line (1-based) from which to start counting source. Useful for\n // integration with other tools.\n startLine: 1,\n // When enabled, await at the top level is not considered an\n // error.\n allowAwaitOutsideFunction: false,\n // When enabled, a return at the top level is not considered an\n // error.\n allowReturnOutsideFunction: false,\n // When enabled, new.target outside a function or class is not\n // considered an error.\n allowNewTargetOutsideFunction: false,\n // When enabled, import/export statements are not constrained to\n // appearing at the top of the program.\n allowImportExportEverywhere: false,\n // When enabled, super outside a method is not considered an error.\n allowSuperOutsideMethod: false,\n // When enabled, export statements can reference undeclared variables.\n allowUndeclaredExports: false,\n allowYieldOutsideFunction: false,\n // An array of plugins to enable\n plugins: [],\n // TODO\n strictMode: undefined,\n // Nodes have their start and end characters offsets recorded in\n // `start` and `end` properties (directly on the node, rather than\n // the `loc` object, which holds line/column data. To also add a\n // [semi-standardized][range] `range` property holding a `[start,\n // end]` array with the same numbers, set the `ranges` option to\n // `true`.\n //\n // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678\n ranges: false,\n // Adds all parsed tokens to a `tokens` property on the `File` node\n tokens: false,\n // Whether to create ImportExpression AST nodes (if false\n // `import(foo)` will be parsed as CallExpression(Import, [Identifier(foo)])\n createImportExpressions: process.env.BABEL_8_BREAKING ? true : false,\n // Whether to create ParenthesizedExpression AST nodes (if false\n // the parser sets extra.parenthesized on the expression nodes instead).\n createParenthesizedExpressions: false,\n // When enabled, errors are attached to the AST instead of being directly thrown.\n // Some errors will still throw, because @babel/parser can't always recover.\n errorRecovery: false,\n // When enabled, comments will be attached to adjacent AST nodes as one of\n // `leadingComments`, `trailingComments` and `innerComments`. The comment attachment\n // is vital to preserve comments after transform. If you don't print AST back,\n // consider set this option to `false` for performance\n attachComment: true,\n // When enabled, the parser will support Annex B syntax.\n // https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers\n annexB: true,\n };\n}\n\n// Interpret and default an options object\n\nexport function getOptions(opts?: Options | null): OptionsWithDefaults {\n // https://github.com/babel/babel/pull/16918\n // `options` is accessed frequently, please make sure it is a fast object.\n // `%ToFastProperties` can make it a fast object, but the performance is the same as the slow object.\n const options: any = createDefaultOptions();\n\n if (opts == null) {\n return options;\n }\n if (opts.annexB != null && opts.annexB !== false) {\n throw new Error(\"The `annexB` option can only be set to `false`.\");\n }\n\n for (const key of Object.keys(options) as (keyof Options)[]) {\n if (opts[key] != null) options[key] = opts[key];\n }\n\n if (options.startLine === 1) {\n if (opts.startIndex == null && options.startColumn > 0) {\n options.startIndex = options.startColumn;\n } else if (opts.startColumn == null && options.startIndex > 0) {\n options.startColumn = options.startIndex;\n }\n } else if (opts.startColumn == null || opts.startIndex == null) {\n if (opts.startIndex != null || process.env.BABEL_8_BREAKING) {\n throw new Error(\n \"With a `startLine > 1` you must also specify `startIndex` and `startColumn`.\",\n );\n }\n }\n\n if (options.sourceType === \"commonjs\") {\n if (opts.allowAwaitOutsideFunction != null) {\n throw new Error(\n \"The `allowAwaitOutsideFunction` option cannot be used with `sourceType: 'commonjs'`.\",\n );\n }\n if (opts.allowReturnOutsideFunction != null) {\n throw new Error(\n \"`sourceType: 'commonjs'` implies `allowReturnOutsideFunction: true`, please remove the `allowReturnOutsideFunction` option or use `sourceType: 'script'`.\",\n );\n }\n if (opts.allowNewTargetOutsideFunction != null) {\n throw new Error(\n \"`sourceType: 'commonjs'` implies `allowNewTargetOutsideFunction: true`, please remove the `allowNewTargetOutsideFunction` option or use `sourceType: 'script'`.\",\n );\n }\n }\n\n return options;\n}\n","import type { TokenType } from \"../tokenizer/types.ts\";\nimport type Parser from \"../parser/index.ts\";\nimport type * as N from \"../types.ts\";\nimport type { Node as NodeType, NodeBase } from \"../types.ts\";\nimport type { Position } from \"../util/location.ts\";\nimport { Errors } from \"../parse-error.ts\";\nimport type { Undone } from \"../parser/node.ts\";\nimport type { BindingFlag } from \"../util/scopeflags.ts\";\nimport { OptionFlags } from \"../options.ts\";\nimport type { ExpressionErrors } from \"../parser/util.ts\";\nimport type { ParseResult, File } from \"../index.ts\";\n\nconst { defineProperty } = Object;\nconst toUnenumerable = (object: any, key: string) => {\n if (object) {\n defineProperty(object, key, { enumerable: false, value: object[key] });\n }\n};\n\nfunction toESTreeLocation(node: any) {\n toUnenumerable(node.loc.start, \"index\");\n toUnenumerable(node.loc.end, \"index\");\n\n return node;\n}\n\nexport default (superClass: typeof Parser) =>\n class ESTreeParserMixin extends superClass implements Parser {\n parse(): ParseResult {\n const file = toESTreeLocation(super.parse());\n\n if (this.optionFlags & OptionFlags.Tokens) {\n file.tokens = file.tokens.map(toESTreeLocation);\n }\n\n return file;\n }\n\n // @ts-expect-error ESTree plugin changes node types\n parseRegExpLiteral({ pattern, flags }): N.EstreeRegExpLiteral {\n let regex: RegExp | null = null;\n try {\n regex = new RegExp(pattern, flags);\n } catch (_) {\n // In environments that don't support these flags value will\n // be null as the regex can't be represented natively.\n }\n const node = this.estreeParseLiteral(regex);\n node.regex = { pattern, flags };\n\n return node;\n }\n\n // @ts-expect-error ESTree plugin changes node types\n parseBigIntLiteral(value: any): N.Node {\n // https://github.com/estree/estree/blob/master/es2020.md#bigintliteral\n let bigInt: bigint | null;\n try {\n bigInt = BigInt(value);\n } catch {\n bigInt = null;\n }\n const node = this.estreeParseLiteral(bigInt);\n node.bigint = String(node.value || value);\n\n return node;\n }\n\n // @ts-expect-error ESTree plugin changes node types\n parseDecimalLiteral(value: any): N.Node {\n // https://github.com/estree/estree/blob/master/experimental/decimal.md\n // todo: use BigDecimal when node supports it.\n const decimal: null = null;\n const node = this.estreeParseLiteral(decimal);\n node.decimal = String(node.value || value);\n\n return node;\n }\n\n estreeParseLiteral(value: any) {\n // @ts-expect-error ESTree plugin changes node types\n return this.parseLiteral(value, \"Literal\");\n }\n\n // @ts-expect-error ESTree plugin changes node types\n parseStringLiteral(value: any): N.Node {\n return this.estreeParseLiteral(value);\n }\n\n parseNumericLiteral(value: any): any {\n return this.estreeParseLiteral(value);\n }\n\n // @ts-expect-error ESTree plugin changes node types\n parseNullLiteral(): N.Node {\n return this.estreeParseLiteral(null);\n }\n\n parseBooleanLiteral(value: boolean): N.BooleanLiteral {\n // @ts-expect-error ESTree plugin changes node types\n return this.estreeParseLiteral(value);\n }\n\n // https://github.com/estree/estree/blob/master/es2020.md#chainexpression\n estreeParseChainExpression(\n node: N.Expression,\n endLoc: Position,\n ): N.EstreeChainExpression {\n const chain = this.startNodeAtNode(node);\n chain.expression = node;\n return this.finishNodeAt(chain, \"ChainExpression\", endLoc);\n }\n\n // Cast a Directive to an ExpressionStatement. Mutates the input Directive.\n directiveToStmt(directive: N.Directive): N.ExpressionStatement {\n const expression = directive.value as any as N.EstreeLiteral;\n // @ts-expect-error delete non-optional properties\n delete directive.value;\n\n this.castNodeTo(expression, \"Literal\");\n expression.raw = expression.extra!.raw;\n expression.value = expression.extra!.expressionValue;\n\n const stmt = this.castNodeTo(directive, \"ExpressionStatement\");\n stmt.expression = expression;\n stmt.directive = expression.extra!.rawValue;\n\n delete expression.extra;\n\n return stmt;\n }\n\n /**\n * The TS-ESLint always define optional AST properties, here we provide the\n * default value for such properties immediately after `finishNode` was invoked.\n * This hook will be implemented by the typescript plugin.\n *\n * Note: This hook should be manually invoked when we change the `type` of a given AST\n * node, to ensure that the optional properties are correctly filled.\n * @param node The AST node finished by finishNode\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n fillOptionalPropertiesForTSESLint(node: NodeType) {}\n\n cloneEstreeStringLiteral(node: N.EstreeLiteral): N.EstreeLiteral {\n const { start, end, loc, range, raw, value } = node;\n const cloned = Object.create(node.constructor.prototype);\n cloned.type = \"Literal\";\n cloned.start = start;\n cloned.end = end;\n cloned.loc = loc;\n cloned.range = range;\n cloned.raw = raw;\n cloned.value = value;\n return cloned;\n }\n\n // ==================================\n // Overrides\n // ==================================\n\n initFunction(node: N.BodilessFunctionOrMethodBase, isAsync: boolean): void {\n super.initFunction(node, isAsync);\n node.expression = false;\n }\n\n checkDeclaration(node: N.Pattern | N.ObjectProperty): void {\n if (node != null && this.isObjectProperty(node)) {\n // @ts-expect-error plugin typings\n this.checkDeclaration((node as unknown as N.EstreeProperty).value);\n } else {\n super.checkDeclaration(node);\n }\n }\n\n getObjectOrClassMethodParams(method: N.ObjectMethod | N.ClassMethod) {\n return (method as unknown as N.EstreeMethodDefinition).value.params;\n }\n\n isValidDirective(stmt: N.Statement): stmt is N.ExpressionStatement {\n return (\n stmt.type === \"ExpressionStatement\" &&\n stmt.expression.type === \"Literal\" &&\n typeof stmt.expression.value === \"string\" &&\n !stmt.expression.extra?.parenthesized\n );\n }\n\n parseBlockBody(\n node: N.BlockStatementLike,\n allowDirectives: boolean | undefined | null,\n topLevel: boolean,\n end: TokenType,\n afterBlockParse?: (hasStrictModeDirective: boolean) => void,\n ): void {\n super.parseBlockBody(\n node,\n allowDirectives,\n topLevel,\n end,\n afterBlockParse,\n );\n\n const directiveStatements = node.directives.map(d =>\n this.directiveToStmt(d),\n );\n // @ts-expect-error estree plugin typings\n node.body = directiveStatements.concat(node.body);\n // @ts-expect-error delete non-optional properties\n delete node.directives;\n }\n\n parsePrivateName(): any {\n const node = super.parsePrivateName();\n if (!process.env.BABEL_8_BREAKING) {\n if (!this.getPluginOption(\"estree\", \"classFeatures\")) {\n return node;\n }\n }\n return this.convertPrivateNameToPrivateIdentifier(node);\n }\n\n convertPrivateNameToPrivateIdentifier(\n node: N.PrivateName,\n ): N.EstreePrivateIdentifier {\n const name = super.getPrivateNameSV(node);\n // @ts-expect-error delete non-optional properties\n delete node.id;\n // @ts-expect-error mutate AST types\n node.name = name;\n return this.castNodeTo(node, \"PrivateIdentifier\");\n }\n\n // @ts-expect-error ESTree plugin changes node types\n isPrivateName(node: N.Node): node is N.EstreePrivateIdentifier {\n if (!process.env.BABEL_8_BREAKING) {\n if (!this.getPluginOption(\"estree\", \"classFeatures\")) {\n return super.isPrivateName(node);\n }\n }\n return node.type === \"PrivateIdentifier\";\n }\n\n // @ts-expect-error ESTree plugin changes node types\n getPrivateNameSV(node: N.EstreePrivateIdentifier): string {\n if (!process.env.BABEL_8_BREAKING) {\n if (!this.getPluginOption(\"estree\", \"classFeatures\")) {\n return super.getPrivateNameSV(node as unknown as N.PrivateName);\n }\n }\n return node.name;\n }\n\n // @ts-expect-error plugin may override interfaces\n parseLiteral(value: any, type: T[\"type\"]): T {\n const node = super.parseLiteral(value, type);\n // @ts-expect-error mutating AST types\n node.raw = node.extra.raw;\n delete node.extra;\n\n return node;\n }\n\n parseFunctionBody(\n node: N.Function,\n allowExpression?: boolean | null,\n isMethod: boolean = false,\n ): void {\n super.parseFunctionBody(node, allowExpression, isMethod);\n node.expression = node.body.type !== \"BlockStatement\";\n }\n\n // @ts-expect-error plugin may override interfaces\n parseMethod<\n T extends N.ClassPrivateMethod | N.ObjectMethod | N.ClassMethod,\n >(\n node: Undone,\n isGenerator: boolean,\n isAsync: boolean,\n isConstructor: boolean,\n allowDirectSuper: boolean,\n type: T[\"type\"],\n inClassScope: boolean = false,\n ):\n | N.EstreeProperty\n | N.EstreeMethodDefinition\n | N.EstreeTSAbstractMethodDefinition {\n let funcNode = this.startNode();\n funcNode.kind = node.kind; // provide kind, so super method correctly sets state\n funcNode = super.parseMethod(\n funcNode,\n isGenerator,\n isAsync,\n isConstructor,\n allowDirectSuper,\n type,\n inClassScope,\n );\n // @ts-expect-error delete non-optional properties\n delete funcNode.kind;\n const { typeParameters } = node;\n if (typeParameters) {\n delete node.typeParameters;\n funcNode.typeParameters = typeParameters;\n this.resetStartLocationFromNode(funcNode, typeParameters);\n }\n const valueNode = this.castNodeTo(\n funcNode as N.MethodLike,\n process.env.BABEL_8_BREAKING &&\n this.hasPlugin(\"typescript\") &&\n !funcNode.body\n ? \"TSEmptyBodyFunctionExpression\"\n : \"FunctionExpression\",\n );\n (\n node as unknown as Undone<\n | N.EstreeProperty\n | N.EstreeMethodDefinition\n | N.EstreeTSAbstractMethodDefinition\n >\n ).value = valueNode;\n if (type === \"ClassPrivateMethod\") {\n node.computed = false;\n }\n if (process.env.BABEL_8_BREAKING && this.hasPlugin(\"typescript\")) {\n // @ts-expect-error todo(flow->ts) property not defined for all types in union\n if (node.abstract) {\n // @ts-expect-error remove abstract from TSAbstractMethodDefinition\n delete node.abstract;\n return this.finishNode(\n // @ts-expect-error cast methods to estree types\n node as Undone,\n \"TSAbstractMethodDefinition\",\n );\n }\n }\n if (type === \"ObjectMethod\") {\n if ((node as any as N.ObjectMethod).kind === \"method\") {\n (node as any as N.EstreeProperty).kind = \"init\";\n }\n (node as any as N.EstreeProperty).shorthand = false;\n return this.finishNode(\n // @ts-expect-error cast methods to estree types\n node as Undone,\n \"Property\",\n );\n } else {\n return this.finishNode(\n // @ts-expect-error cast methods to estree types\n node as Undone,\n \"MethodDefinition\",\n );\n }\n }\n\n nameIsConstructor(key: N.Expression | N.PrivateName): boolean {\n if (key.type === \"Literal\") return key.value === \"constructor\";\n return super.nameIsConstructor(key);\n }\n\n parseClassProperty(...args: [N.ClassProperty]): any {\n const propertyNode = super.parseClassProperty(...args);\n if (!process.env.BABEL_8_BREAKING) {\n if (!this.getPluginOption(\"estree\", \"classFeatures\")) {\n return propertyNode as unknown as N.EstreePropertyDefinition;\n }\n }\n if (\n process.env.BABEL_8_BREAKING &&\n propertyNode.abstract &&\n this.hasPlugin(\"typescript\")\n ) {\n delete propertyNode.abstract;\n this.castNodeTo(propertyNode, \"TSAbstractPropertyDefinition\");\n } else {\n this.castNodeTo(propertyNode, \"PropertyDefinition\");\n }\n return propertyNode;\n }\n\n parseClassPrivateProperty(...args: [N.ClassPrivateProperty]): any {\n const propertyNode = super.parseClassPrivateProperty(...args);\n if (!process.env.BABEL_8_BREAKING) {\n if (!this.getPluginOption(\"estree\", \"classFeatures\")) {\n return propertyNode as unknown as N.EstreePropertyDefinition;\n }\n }\n if (\n process.env.BABEL_8_BREAKING &&\n propertyNode.abstract &&\n this.hasPlugin(\"typescript\")\n ) {\n this.castNodeTo(propertyNode, \"TSAbstractPropertyDefinition\");\n } else {\n this.castNodeTo(propertyNode, \"PropertyDefinition\");\n }\n propertyNode.computed = false;\n return propertyNode;\n }\n\n parseClassAccessorProperty(\n this: Parser,\n node: N.ClassAccessorProperty,\n ): any {\n const accessorPropertyNode = super.parseClassAccessorProperty(node);\n if (!process.env.BABEL_8_BREAKING) {\n if (!this.getPluginOption(\"estree\", \"classFeatures\")) {\n return accessorPropertyNode;\n }\n }\n if (accessorPropertyNode.abstract && this.hasPlugin(\"typescript\")) {\n delete accessorPropertyNode.abstract;\n this.castNodeTo(accessorPropertyNode, \"TSAbstractAccessorProperty\");\n } else {\n this.castNodeTo(accessorPropertyNode, \"AccessorProperty\");\n }\n return accessorPropertyNode;\n }\n\n parseObjectProperty(\n prop: N.ObjectProperty,\n startLoc: Position | undefined | null,\n isPattern: boolean,\n refExpressionErrors?: ExpressionErrors | null,\n ): N.ObjectProperty | undefined | null {\n const node: N.EstreeProperty = super.parseObjectProperty(\n prop,\n startLoc,\n isPattern,\n refExpressionErrors,\n ) as any;\n\n if (node) {\n node.kind = \"init\";\n this.castNodeTo(node, \"Property\");\n }\n\n return node as any;\n }\n\n finishObjectProperty(node: Undone): N.ObjectProperty {\n (node as unknown as Undone).kind = \"init\";\n return this.finishNode(\n node as unknown as Undone,\n \"Property\",\n ) as any;\n }\n\n isValidLVal(\n type: string,\n disallowCallExpression: boolean,\n isUnparenthesizedInAssign: boolean,\n binding: BindingFlag,\n ) {\n return type === \"Property\"\n ? \"value\"\n : super.isValidLVal(\n type,\n disallowCallExpression,\n isUnparenthesizedInAssign,\n binding,\n );\n }\n\n isAssignable(node: N.Node, isBinding?: boolean): boolean {\n if (node != null && this.isObjectProperty(node)) {\n return this.isAssignable(node.value, isBinding);\n }\n return super.isAssignable(node, isBinding);\n }\n\n toAssignable(node: N.Node, isLHS: boolean = false): void {\n if (node != null && this.isObjectProperty(node)) {\n const { key, value } = node;\n if (this.isPrivateName(key)) {\n this.classScope.usePrivateName(\n this.getPrivateNameSV(key),\n key.loc.start,\n );\n }\n this.toAssignable(value, isLHS);\n } else {\n super.toAssignable(node, isLHS);\n }\n }\n\n toAssignableObjectExpressionProp(\n prop: N.Node,\n isLast: boolean,\n isLHS: boolean,\n ) {\n if (\n prop.type === \"Property\" &&\n (prop.kind === \"get\" || prop.kind === \"set\")\n ) {\n this.raise(Errors.PatternHasAccessor, prop.key);\n } else if (prop.type === \"Property\" && prop.method) {\n this.raise(Errors.PatternHasMethod, prop.key);\n } else {\n super.toAssignableObjectExpressionProp(prop, isLast, isLHS);\n }\n }\n\n finishCallExpression(\n unfinished: Undone,\n optional: boolean,\n ): T {\n const node = super.finishCallExpression(unfinished, optional);\n\n if (node.callee.type === \"Import\") {\n this.castNodeTo(node, \"ImportExpression\");\n (node as N.Node as N.EstreeImportExpression).source = node\n .arguments[0] as N.Expression;\n (node as N.Node as N.EstreeImportExpression).options =\n (node.arguments[1] as N.Expression) ?? null;\n if (!process.env.BABEL_8_BREAKING) {\n // compatibility with previous ESTree AST\n (node as N.Node as N.EstreeImportExpression).attributes =\n (node.arguments[1] as N.Expression) ?? null;\n }\n // arguments isn't optional in the type definition\n // @ts-expect-error delete non-optional properties\n delete node.arguments;\n // callee isn't optional in the type definition\n // @ts-expect-error delete non-optional properties\n delete node.callee;\n } else if (node.type === \"OptionalCallExpression\") {\n this.castNodeTo(node, \"CallExpression\");\n } else {\n node.optional = false;\n }\n\n return node;\n }\n\n toReferencedArguments(\n node:\n | N.CallExpression\n | N.OptionalCallExpression\n | N.EstreeImportExpression,\n /* isParenthesizedExpr?: boolean, */\n ) {\n // ImportExpressions do not have an arguments array.\n if (node.type === \"ImportExpression\") {\n return;\n }\n\n super.toReferencedArguments(node);\n }\n\n parseExport(\n unfinished: Undone,\n decorators: N.Decorator[] | null,\n ) {\n const exportStartLoc = this.state.lastTokStartLoc!;\n const node = super.parseExport(unfinished, decorators);\n\n switch (node.type) {\n case \"ExportAllDeclaration\":\n // @ts-expect-error mutating AST types\n node.exported = null;\n break;\n\n case \"ExportNamedDeclaration\":\n if (\n node.specifiers.length === 1 &&\n node.specifiers[0].type === \"ExportNamespaceSpecifier\"\n ) {\n this.castNodeTo(node, \"ExportAllDeclaration\");\n // @ts-expect-error mutating AST types\n node.exported = node.specifiers[0].exported;\n // @ts-expect-error The ESTree AST shape differs from the Babel AST\n delete node.specifiers;\n }\n\n // fallthrough\n case \"ExportDefaultDeclaration\":\n {\n const { declaration } = node;\n if (\n declaration?.type === \"ClassDeclaration\" &&\n // @ts-expect-error comparing undefined and number\n declaration.decorators?.length > 0 &&\n // decorator comes before export\n declaration.start === node.start\n ) {\n this.resetStartLocation(\n node,\n // For compatibility with ESLint's keyword-spacing rule, which assumes that an\n // export declaration must start with export.\n // https://github.com/babel/babel/issues/15085\n // Here we reset export declaration's start to be the start of the export token\n exportStartLoc,\n );\n }\n }\n\n break;\n }\n\n return node;\n }\n\n stopParseSubscript(base: N.Expression, state: N.ParseSubscriptState) {\n const node = super.stopParseSubscript(base, state);\n if (state.optionalChainMember) {\n return this.estreeParseChainExpression(node, base.loc.end);\n }\n return node;\n }\n\n parseMember(\n base: N.Expression,\n startLoc: Position,\n state: N.ParseSubscriptState,\n computed: boolean,\n optional: boolean,\n ) {\n const node = super.parseMember(base, startLoc, state, computed, optional);\n if (node.type === \"OptionalMemberExpression\") {\n this.castNodeTo(node, \"MemberExpression\");\n } else {\n node.optional = false;\n }\n return node;\n }\n\n isOptionalMemberExpression(node: N.Node) {\n if (node.type === \"ChainExpression\") {\n return node.expression.type === \"MemberExpression\";\n }\n return super.isOptionalMemberExpression(node);\n }\n\n hasPropertyAsPrivateName(node: N.Node): boolean {\n if (node.type === \"ChainExpression\") {\n node = node.expression;\n }\n return super.hasPropertyAsPrivateName(node);\n }\n\n // @ts-expect-error ESTree plugin changes node types\n isObjectProperty(node: N.Node): node is N.EstreeProperty {\n return node.type === \"Property\" && node.kind === \"init\" && !node.method;\n }\n\n // @ts-expect-error ESTree plugin changes node types\n isObjectMethod(node: N.Node): node is N.EstreeProperty {\n return (\n node.type === \"Property\" &&\n (node.method || node.kind === \"get\" || node.kind === \"set\")\n );\n }\n\n /* ============================================================ *\n * parser/node.ts *\n * ============================================================ */\n\n castNodeTo(\n node: N.Node,\n type: T,\n ): Extract {\n const result = super.castNodeTo(node, type);\n this.fillOptionalPropertiesForTSESLint(result);\n return result;\n }\n\n cloneIdentifier(node: T): T {\n const cloned = super.cloneIdentifier(node);\n this.fillOptionalPropertiesForTSESLint(cloned);\n return cloned;\n }\n\n cloneStringLiteral<\n T extends N.EstreeLiteral | N.StringLiteral | N.Placeholder,\n >(node: T): T {\n if (node.type === \"Literal\") {\n return this.cloneEstreeStringLiteral(node) as T;\n }\n return super.cloneStringLiteral(node);\n }\n\n finishNodeAt(\n node: Undone,\n type: T[\"type\"],\n endLoc: Position,\n ): T {\n return toESTreeLocation(super.finishNodeAt(node, type, endLoc));\n }\n\n // Override for TS-ESLint that does not allow optional AST properties\n finishNode(node: Undone, type: T[\"type\"]): T {\n const result = super.finishNode(node, type);\n this.fillOptionalPropertiesForTSESLint(result);\n return result;\n }\n\n resetStartLocation(node: N.Node, startLoc: Position) {\n super.resetStartLocation(node, startLoc);\n toESTreeLocation(node);\n }\n\n resetEndLocation(\n node: NodeBase,\n endLoc: Position = this.state.lastTokEndLoc!,\n ): void {\n super.resetEndLocation(node, endLoc);\n toESTreeLocation(node);\n }\n };\n","// The token context is used in JSX plugin to track\n// jsx tag / jsx text / normal JavaScript expression\n\nexport class TokContext {\n constructor(token: string, preserveSpace?: boolean) {\n this.token = token;\n this.preserveSpace = !!preserveSpace;\n }\n\n token: string;\n preserveSpace: boolean;\n}\n\nconst types: Record = {\n brace: new TokContext(\"{\"), // normal JavaScript expression\n j_oTag: new TokContext(\"...\", true), // JSX expressions\n};\n\nif (!process.env.BABEL_8_BREAKING) {\n types.template = new TokContext(\"`\", true);\n}\n\nexport { types };\n","import { types as tc, type TokContext } from \"./context.ts\";\n// ## Token types\n\n// The assignment of fine-grained, information-carrying type objects\n// allows the tokenizer to store the information it has about a\n// token in a way that is very cheap for the parser to look up.\n\n// All token type variables start with an underscore, to make them\n// easy to recognize.\n\n// The `beforeExpr` property is used to disambiguate between 1) binary\n// expression (<) and JSX Tag start (); 2) object literal and JSX\n// texts. It is set on the `updateContext` function in the JSX plugin.\n\n// The `startsExpr` property is used to determine whether an expression\n// may be the “argument” subexpression of a `yield` expression or\n// `yield` statement. It is set on all token types that may be at the\n// start of a subexpression.\n\n// `isLoop` marks a keyword as starting a loop, which is important\n// to know when parsing a label, in order to allow or disallow\n// continue jumps to that label.\n\nconst beforeExpr = true;\nconst startsExpr = true;\nconst isLoop = true;\nconst isAssign = true;\nconst prefix = true;\nconst postfix = true;\n\ntype TokenOptions = {\n keyword?: string;\n beforeExpr?: boolean;\n startsExpr?: boolean;\n rightAssociative?: boolean;\n isLoop?: boolean;\n isAssign?: boolean;\n prefix?: boolean;\n postfix?: boolean;\n binop?: number | null;\n};\n\n// Internally the tokenizer stores token as a number\nexport type TokenType = number;\n\n// The `ExportedTokenType` is exported via `tokTypes` and accessible\n// when `tokens: true` is enabled. Unlike internal token type, it provides\n// metadata of the tokens.\nexport class ExportedTokenType {\n label: string;\n keyword: string | undefined | null;\n beforeExpr: boolean;\n startsExpr: boolean;\n rightAssociative: boolean;\n isLoop: boolean;\n isAssign: boolean;\n prefix: boolean;\n postfix: boolean;\n binop: number | undefined | null;\n // todo(Babel 8): remove updateContext from exposed token layout\n declare updateContext: ((context: TokContext[]) => void) | undefined | null;\n\n constructor(label: string, conf: TokenOptions = {}) {\n this.label = label;\n this.keyword = conf.keyword;\n this.beforeExpr = !!conf.beforeExpr;\n this.startsExpr = !!conf.startsExpr;\n this.rightAssociative = !!conf.rightAssociative;\n this.isLoop = !!conf.isLoop;\n this.isAssign = !!conf.isAssign;\n this.prefix = !!conf.prefix;\n this.postfix = !!conf.postfix;\n this.binop = conf.binop != null ? conf.binop : null;\n if (!process.env.BABEL_8_BREAKING) {\n this.updateContext = null;\n }\n }\n}\n\n// A map from keyword/keyword-like string value to the token type\nexport const keywords = new Map();\n\nfunction createKeyword(name: string, options: TokenOptions = {}): TokenType {\n options.keyword = name;\n const token = createToken(name, options);\n keywords.set(name, token);\n return token;\n}\n\nfunction createBinop(name: string, binop: number) {\n return createToken(name, { beforeExpr, binop });\n}\n\nlet tokenTypeCounter = -1;\nexport const tokenTypes: ExportedTokenType[] = [];\nconst tokenLabels: string[] = [];\nconst tokenBinops: number[] = [];\nconst tokenBeforeExprs: boolean[] = [];\nconst tokenStartsExprs: boolean[] = [];\nconst tokenPrefixes: boolean[] = [];\n\nfunction createToken(name: string, options: TokenOptions = {}): TokenType {\n ++tokenTypeCounter;\n tokenLabels.push(name);\n tokenBinops.push(options.binop ?? -1);\n tokenBeforeExprs.push(options.beforeExpr ?? false);\n tokenStartsExprs.push(options.startsExpr ?? false);\n tokenPrefixes.push(options.prefix ?? false);\n tokenTypes.push(new ExportedTokenType(name, options));\n\n return tokenTypeCounter;\n}\n\nfunction createKeywordLike(\n name: string,\n options: TokenOptions = {},\n): TokenType {\n ++tokenTypeCounter;\n keywords.set(name, tokenTypeCounter);\n tokenLabels.push(name);\n tokenBinops.push(options.binop ?? -1);\n tokenBeforeExprs.push(options.beforeExpr ?? false);\n tokenStartsExprs.push(options.startsExpr ?? false);\n tokenPrefixes.push(options.prefix ?? false);\n // In the exported token type, we set the label as \"name\" for backward compatibility with Babel 7\n tokenTypes.push(new ExportedTokenType(\"name\", options));\n\n return tokenTypeCounter;\n}\n\n// For performance the token type helpers depend on the following declarations order.\n// When adding new token types, please also check if the token helpers need update.\n\nexport type InternalTokenTypes = typeof tt;\n\nexport const tt = {\n // Punctuation token types.\n bracketL: createToken(\"[\", { beforeExpr, startsExpr }),\n // TODO: Remove this in Babel 8\n bracketHashL: createToken(\"#[\", { beforeExpr, startsExpr }),\n // TODO: Remove this in Babel 8\n bracketBarL: createToken(\"[|\", { beforeExpr, startsExpr }),\n bracketR: createToken(\"]\"),\n // TODO: Remove this in Babel 8\n bracketBarR: createToken(\"|]\"),\n braceL: createToken(\"{\", { beforeExpr, startsExpr }),\n // TODO: Remove this in Babel 8\n braceBarL: createToken(\"{|\", { beforeExpr, startsExpr }),\n // TODO: Remove this in Babel 8\n braceHashL: createToken(\"#{\", { beforeExpr, startsExpr }),\n braceR: createToken(\"}\"),\n braceBarR: createToken(\"|}\"),\n parenL: createToken(\"(\", { beforeExpr, startsExpr }),\n parenR: createToken(\")\"),\n comma: createToken(\",\", { beforeExpr }),\n semi: createToken(\";\", { beforeExpr }),\n colon: createToken(\":\", { beforeExpr }),\n doubleColon: createToken(\"::\", { beforeExpr }),\n dot: createToken(\".\"),\n question: createToken(\"?\", { beforeExpr }),\n questionDot: createToken(\"?.\"),\n arrow: createToken(\"=>\", { beforeExpr }),\n template: createToken(\"template\"),\n ellipsis: createToken(\"...\", { beforeExpr }),\n backQuote: createToken(\"`\", { startsExpr }),\n dollarBraceL: createToken(\"${\", { beforeExpr, startsExpr }),\n // start: isTemplate\n templateTail: createToken(\"...`\", { startsExpr }),\n templateNonTail: createToken(\"...${\", { beforeExpr, startsExpr }),\n // end: isTemplate\n at: createToken(\"@\"),\n hash: createToken(\"#\", { startsExpr }),\n\n // Special hashbang token.\n interpreterDirective: createToken(\"#!...\"),\n\n // Operators. These carry several kinds of properties to help the\n // parser use them properly (the presence of these properties is\n // what categorizes them as operators).\n //\n // `binop`, when present, specifies that this operator is a binary\n // operator, and will refer to its precedence.\n //\n // `prefix` and `postfix` mark the operator as a prefix or postfix\n // unary operator.\n //\n // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as\n // binary operators with a very low precedence, that should result\n // in AssignmentExpression nodes.\n\n // start: isAssign\n eq: createToken(\"=\", { beforeExpr, isAssign }),\n assign: createToken(\"_=\", { beforeExpr, isAssign }),\n slashAssign: createToken(\"_=\", { beforeExpr, isAssign }),\n // These are only needed to support % and ^ as a Hack-pipe topic token.\n // When the proposal settles on a token, the others can be merged with\n // tt.assign.\n xorAssign: createToken(\"_=\", { beforeExpr, isAssign }),\n moduloAssign: createToken(\"_=\", { beforeExpr, isAssign }),\n // end: isAssign\n\n incDec: createToken(\"++/--\", { prefix, postfix, startsExpr }),\n bang: createToken(\"!\", { beforeExpr, prefix, startsExpr }),\n tilde: createToken(\"~\", { beforeExpr, prefix, startsExpr }),\n\n // More possible topic tokens.\n // When the proposal settles on a token, at least one of these may be removed.\n doubleCaret: createToken(\"^^\", { startsExpr }),\n doubleAt: createToken(\"@@\", { startsExpr }),\n\n // start: isBinop\n pipeline: createBinop(\"|>\", 0),\n nullishCoalescing: createBinop(\"??\", 1),\n logicalOR: createBinop(\"||\", 1),\n logicalAND: createBinop(\"&&\", 2),\n bitwiseOR: createBinop(\"|\", 3),\n bitwiseXOR: createBinop(\"^\", 4),\n bitwiseAND: createBinop(\"&\", 5),\n equality: createBinop(\"==/!=/===/!==\", 6),\n lt: createBinop(\"/<=/>=\", 7),\n gt: createBinop(\"/<=/>=\", 7),\n relational: createBinop(\"/<=/>=\", 7),\n bitShift: createBinop(\"<>/>>>\", 8),\n bitShiftL: createBinop(\"<>/>>>\", 8),\n bitShiftR: createBinop(\"<>/>>>\", 8),\n plusMin: createToken(\"+/-\", { beforeExpr, binop: 9, prefix, startsExpr }),\n // startsExpr: required by v8intrinsic plugin\n modulo: createToken(\"%\", { binop: 10, startsExpr }),\n // unset `beforeExpr` as it can be `function *`\n star: createToken(\"*\", { binop: 10 }),\n slash: createBinop(\"/\", 10),\n exponent: createToken(\"**\", {\n beforeExpr,\n binop: 11,\n rightAssociative: true,\n }),\n\n // Keywords\n // Don't forget to update packages/babel-helper-validator-identifier/src/keyword.js\n // when new keywords are added\n // start: isLiteralPropertyName\n // start: isKeyword\n _in: createKeyword(\"in\", { beforeExpr, binop: 7 }),\n _instanceof: createKeyword(\"instanceof\", { beforeExpr, binop: 7 }),\n // end: isBinop\n _break: createKeyword(\"break\"),\n _case: createKeyword(\"case\", { beforeExpr }),\n _catch: createKeyword(\"catch\"),\n _continue: createKeyword(\"continue\"),\n _debugger: createKeyword(\"debugger\"),\n _default: createKeyword(\"default\", { beforeExpr }),\n _else: createKeyword(\"else\", { beforeExpr }),\n _finally: createKeyword(\"finally\"),\n _function: createKeyword(\"function\", { startsExpr }),\n _if: createKeyword(\"if\"),\n _return: createKeyword(\"return\", { beforeExpr }),\n _switch: createKeyword(\"switch\"),\n _throw: createKeyword(\"throw\", { beforeExpr, prefix, startsExpr }),\n _try: createKeyword(\"try\"),\n _var: createKeyword(\"var\"),\n _const: createKeyword(\"const\"),\n _with: createKeyword(\"with\"),\n _new: createKeyword(\"new\", { beforeExpr, startsExpr }),\n _this: createKeyword(\"this\", { startsExpr }),\n _super: createKeyword(\"super\", { startsExpr }),\n _class: createKeyword(\"class\", { startsExpr }),\n _extends: createKeyword(\"extends\", { beforeExpr }),\n _export: createKeyword(\"export\"),\n _import: createKeyword(\"import\", { startsExpr }),\n _null: createKeyword(\"null\", { startsExpr }),\n _true: createKeyword(\"true\", { startsExpr }),\n _false: createKeyword(\"false\", { startsExpr }),\n _typeof: createKeyword(\"typeof\", { beforeExpr, prefix, startsExpr }),\n _void: createKeyword(\"void\", { beforeExpr, prefix, startsExpr }),\n _delete: createKeyword(\"delete\", { beforeExpr, prefix, startsExpr }),\n // start: isLoop\n _do: createKeyword(\"do\", { isLoop, beforeExpr }),\n _for: createKeyword(\"for\", { isLoop }),\n _while: createKeyword(\"while\", { isLoop }),\n // end: isLoop\n // end: isKeyword\n\n // Primary literals\n // start: isIdentifier\n _as: createKeywordLike(\"as\", { startsExpr }),\n _assert: createKeywordLike(\"assert\", { startsExpr }),\n _async: createKeywordLike(\"async\", { startsExpr }),\n _await: createKeywordLike(\"await\", { startsExpr }),\n _defer: createKeywordLike(\"defer\", { startsExpr }),\n _from: createKeywordLike(\"from\", { startsExpr }),\n _get: createKeywordLike(\"get\", { startsExpr }),\n _let: createKeywordLike(\"let\", { startsExpr }),\n _meta: createKeywordLike(\"meta\", { startsExpr }),\n _of: createKeywordLike(\"of\", { startsExpr }),\n _sent: createKeywordLike(\"sent\", { startsExpr }),\n _set: createKeywordLike(\"set\", { startsExpr }),\n _source: createKeywordLike(\"source\", { startsExpr }),\n _static: createKeywordLike(\"static\", { startsExpr }),\n _using: createKeywordLike(\"using\", { startsExpr }),\n _yield: createKeywordLike(\"yield\", { startsExpr }),\n\n // Flow and TypeScript Keywordlike\n _asserts: createKeywordLike(\"asserts\", { startsExpr }),\n _checks: createKeywordLike(\"checks\", { startsExpr }),\n _exports: createKeywordLike(\"exports\", { startsExpr }),\n _global: createKeywordLike(\"global\", { startsExpr }),\n _implements: createKeywordLike(\"implements\", { startsExpr }),\n _intrinsic: createKeywordLike(\"intrinsic\", { startsExpr }),\n _infer: createKeywordLike(\"infer\", { startsExpr }),\n _is: createKeywordLike(\"is\", { startsExpr }),\n _mixins: createKeywordLike(\"mixins\", { startsExpr }),\n _proto: createKeywordLike(\"proto\", { startsExpr }),\n _require: createKeywordLike(\"require\", { startsExpr }),\n _satisfies: createKeywordLike(\"satisfies\", { startsExpr }),\n // start: isTSTypeOperator\n _keyof: createKeywordLike(\"keyof\", { startsExpr }),\n _readonly: createKeywordLike(\"readonly\", { startsExpr }),\n _unique: createKeywordLike(\"unique\", { startsExpr }),\n // end: isTSTypeOperator\n // start: isTSDeclarationStart\n _abstract: createKeywordLike(\"abstract\", { startsExpr }),\n _declare: createKeywordLike(\"declare\", { startsExpr }),\n _enum: createKeywordLike(\"enum\", { startsExpr }),\n _module: createKeywordLike(\"module\", { startsExpr }),\n _namespace: createKeywordLike(\"namespace\", { startsExpr }),\n // start: isFlowInterfaceOrTypeOrOpaque\n _interface: createKeywordLike(\"interface\", { startsExpr }),\n _type: createKeywordLike(\"type\", { startsExpr }),\n // end: isTSDeclarationStart\n _opaque: createKeywordLike(\"opaque\", { startsExpr }),\n // end: isFlowInterfaceOrTypeOrOpaque\n name: createToken(\"name\", { startsExpr }),\n\n // placeholder plugin\n placeholder: createToken(\"%%\", { startsExpr }),\n // end: isIdentifier\n\n string: createToken(\"string\", { startsExpr }),\n num: createToken(\"num\", { startsExpr }),\n bigint: createToken(\"bigint\", { startsExpr }),\n // TODO: Remove this in Babel 8\n decimal: createToken(\"decimal\", { startsExpr }),\n // end: isLiteralPropertyName\n regexp: createToken(\"regexp\", { startsExpr }),\n privateName: createToken(\"#name\", { startsExpr }),\n eof: createToken(\"eof\"),\n\n // jsx plugin\n jsxName: createToken(\"jsxName\"),\n jsxText: createToken(\"jsxText\", { beforeExpr }),\n jsxTagStart: createToken(\"jsxTagStart\", { startsExpr }),\n jsxTagEnd: createToken(\"jsxTagEnd\"),\n} as const;\n\nexport function tokenIsIdentifier(token: TokenType): boolean {\n return token >= tt._as && token <= tt.placeholder;\n}\n\nexport function tokenKeywordOrIdentifierIsKeyword(token: TokenType): boolean {\n // we can remove the token >= tt._in check when we\n // know a token is either keyword or identifier\n return token <= tt._while;\n}\n\nexport function tokenIsKeywordOrIdentifier(token: TokenType): boolean {\n return token >= tt._in && token <= tt.placeholder;\n}\n\nexport function tokenIsLiteralPropertyName(token: TokenType): boolean {\n return token >= tt._in && token <= tt.decimal;\n}\n\nexport function tokenComesBeforeExpression(token: TokenType): boolean {\n return tokenBeforeExprs[token];\n}\n\nexport function tokenCanStartExpression(token: TokenType): boolean {\n return tokenStartsExprs[token];\n}\n\nexport function tokenIsAssignment(token: TokenType): boolean {\n return token >= tt.eq && token <= tt.moduloAssign;\n}\n\nexport function tokenIsFlowInterfaceOrTypeOrOpaque(token: TokenType): boolean {\n return token >= tt._interface && token <= tt._opaque;\n}\n\nexport function tokenIsLoop(token: TokenType): boolean {\n return token >= tt._do && token <= tt._while;\n}\n\nexport function tokenIsKeyword(token: TokenType): boolean {\n return token >= tt._in && token <= tt._while;\n}\n\nexport function tokenIsOperator(token: TokenType): boolean {\n return token >= tt.pipeline && token <= tt._instanceof;\n}\n\nexport function tokenIsPostfix(token: TokenType): boolean {\n return token === tt.incDec;\n}\n\nexport function tokenIsPrefix(token: TokenType): boolean {\n return tokenPrefixes[token];\n}\n\nexport function tokenIsTSTypeOperator(token: TokenType): boolean {\n return token >= tt._keyof && token <= tt._unique;\n}\n\nexport function tokenIsTSDeclarationStart(token: TokenType): boolean {\n return token >= tt._abstract && token <= tt._type;\n}\n\nexport function tokenLabelName(token: TokenType): string {\n return tokenLabels[token];\n}\n\nexport function tokenOperatorPrecedence(token: TokenType): number {\n return tokenBinops[token];\n}\n\nexport function tokenIsBinaryOperator(token: TokenType): boolean {\n return tokenBinops[token] !== -1;\n}\n\nexport function tokenIsRightAssociative(token: TokenType): boolean {\n return token === tt.exponent;\n}\n\nexport function tokenIsTemplate(token: TokenType): boolean {\n return token >= tt.templateTail && token <= tt.templateNonTail;\n}\n\nexport function getExportedToken(token: TokenType): ExportedTokenType {\n return tokenTypes[token];\n}\n\nexport function isTokenType(obj: any): boolean {\n return typeof obj === \"number\";\n}\n\nif (!process.env.BABEL_8_BREAKING) {\n tokenTypes[tt.braceR].updateContext = context => {\n context.pop();\n };\n\n tokenTypes[tt.braceL].updateContext =\n tokenTypes[tt.braceHashL].updateContext =\n tokenTypes[tt.dollarBraceL].updateContext =\n context => {\n context.push(tc.brace);\n };\n\n tokenTypes[tt.backQuote].updateContext = context => {\n if (context[context.length - 1] === tc.template) {\n context.pop();\n } else {\n context.push(tc.template);\n }\n };\n\n tokenTypes[tt.jsxTagStart].updateContext = context => {\n context.push(tc.j_expr, tc.j_oTag);\n };\n}\n","// We inline this package\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport * as charCodes from \"charcodes\";\n\n// ## Character categories\n\n// Big ugly regular expressions that match characters in the\n// whitespace, identifier, and identifier-start categories. These\n// are only applied when a character is found to actually have a\n// code point between 0x80 and 0xffff.\n// Generated by `scripts/generate-identifier-regex.cjs`.\n\n/* prettier-ignore */\nlet 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-\\u088f\\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\\u0c5c\\u0c5d\\u0c60\\u0c61\\u0c80\\u0c85-\\u0c8c\\u0c8e-\\u0c90\\u0c92-\\u0ca8\\u0caa-\\u0cb3\\u0cb5-\\u0cb9\\u0cbd\\u0cdc-\\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-\\u1c8a\\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-\\ua7dc\\ua7f1-\\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\";\n/* prettier-ignore */\nlet nonASCIIidentifierChars = \"\\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\\u0897-\\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-\\u1add\\u1ae0-\\u1aeb\\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\\u200c\\u200d\\u203f\\u2040\\u2054\\u20d0-\\u20dc\\u20e1\\u20e5-\\u20f0\\u2cef-\\u2cf1\\u2d7f\\u2de0-\\u2dff\\u302a-\\u302f\\u3099\\u309a\\u30fb\\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\\uff65\";\n\nconst nonASCIIidentifierStart = new RegExp(\n \"[\" + nonASCIIidentifierStartChars + \"]\",\n);\nconst nonASCIIidentifier = new RegExp(\n \"[\" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + \"]\",\n);\n\nnonASCIIidentifierStartChars = nonASCIIidentifierChars = null;\n\n// These are a run-length and offset-encoded representation of the\n// >0xffff code points that are a valid part of identifiers. The\n// offset starts at 0x10000, and each pair of numbers represents an\n// offset to the next range, and then a size of the range. They were\n// generated by `scripts/generate-identifier-regex.cjs`.\n/* prettier-ignore */\nconst 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,4,51,13,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,7,25,39,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,39,27,10,22,251,41,7,1,17,5,57,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,31,9,2,0,3,0,2,37,2,0,26,0,2,0,45,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,200,32,32,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,24,43,261,18,16,0,2,12,2,33,125,0,80,921,103,110,18,195,2637,96,16,1071,18,5,26,3994,6,582,6842,29,1763,568,8,30,18,78,18,29,19,47,17,3,32,20,6,18,433,44,212,63,33,24,3,24,45,74,6,0,67,12,65,1,2,0,15,4,10,7381,42,31,98,114,8702,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,229,29,3,0,208,30,2,2,2,1,2,6,3,4,10,1,225,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,4381,3,5773,3,7472,16,621,2467,541,1507,4938,6,8489];\n/* prettier-ignore */\nconst 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,7,9,32,4,318,1,78,5,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,68,8,2,0,3,0,2,3,2,4,2,0,15,1,83,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,7,19,58,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,199,7,137,9,54,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,55,9,266,3,10,1,2,0,49,6,4,4,14,10,5350,0,7,14,11465,27,2343,9,87,9,39,4,60,6,26,9,535,9,470,0,2,54,8,3,82,0,12,1,19628,1,4178,9,519,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,245,1,2,9,233,0,3,0,8,1,6,0,475,6,110,6,6,9,4759,9,787719,239];\n\n// This has a complexity linear to the value of the code. The\n// assumption is that looking up astral identifier characters is\n// rare.\nfunction isInAstralSet(code: number, set: readonly number[]): boolean {\n let pos = 0x10000;\n for (let i = 0, length = set.length; i < length; i += 2) {\n pos += set[i];\n if (pos > code) return false;\n\n pos += set[i + 1];\n if (pos >= code) return true;\n }\n return false;\n}\n\n// Test whether a given character code starts an identifier.\n\nexport function isIdentifierStart(code: number): boolean {\n if (code < charCodes.uppercaseA) return code === charCodes.dollarSign;\n if (code <= charCodes.uppercaseZ) return true;\n if (code < charCodes.lowercaseA) return code === charCodes.underscore;\n if (code <= charCodes.lowercaseZ) return true;\n if (code <= 0xffff) {\n return (\n code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code))\n );\n }\n return isInAstralSet(code, astralIdentifierStartCodes);\n}\n\n// Test whether a given character is part of an identifier.\n\nexport function isIdentifierChar(code: number): boolean {\n if (code < charCodes.digit0) return code === charCodes.dollarSign;\n if (code < charCodes.colon) return true;\n if (code < charCodes.uppercaseA) return false;\n if (code <= charCodes.uppercaseZ) return true;\n if (code < charCodes.lowercaseA) return code === charCodes.underscore;\n if (code <= charCodes.lowercaseZ) return true;\n if (code <= 0xffff) {\n return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));\n }\n return (\n isInAstralSet(code, astralIdentifierStartCodes) ||\n isInAstralSet(code, astralIdentifierCodes)\n );\n}\n\n// Test whether a given string is a valid identifier name\n\nexport function isIdentifierName(name: string): boolean {\n let isFirst = true;\n for (let i = 0; i < name.length; i++) {\n // The implementation is based on\n // https://source.chromium.org/chromium/chromium/src/+/master:v8/src/builtins/builtins-string-gen.cc;l=1455;drc=221e331b49dfefadbc6fa40b0c68e6f97606d0b3;bpv=0;bpt=1\n // We reimplement `codePointAt` because `codePointAt` is a V8 builtin which is not inlined by TurboFan (as of M91)\n // since `name` is mostly ASCII, an inlined `charCodeAt` wins here\n let cp = name.charCodeAt(i);\n if ((cp & 0xfc00) === 0xd800 && i + 1 < name.length) {\n const trail = name.charCodeAt(++i);\n if ((trail & 0xfc00) === 0xdc00) {\n cp = 0x10000 + ((cp & 0x3ff) << 10) + (trail & 0x3ff);\n }\n }\n if (isFirst) {\n isFirst = false;\n if (!isIdentifierStart(cp)) {\n return false;\n }\n } else if (!isIdentifierChar(cp)) {\n return false;\n }\n }\n return !isFirst;\n}\n","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","import * as charCodes from \"charcodes\";\nimport { isIdentifierStart } from \"@babel/helper-validator-identifier\";\n\nexport {\n isIdentifierStart,\n isIdentifierChar,\n isReservedWord,\n isStrictBindOnlyReservedWord,\n isStrictBindReservedWord,\n isStrictReservedWord,\n isKeyword,\n} from \"@babel/helper-validator-identifier\";\n\nexport const keywordRelationalOperator = /^in(stanceof)?$/;\n\n// Test whether a current state character code and next character code is @\n\nexport function isIteratorStart(\n current: number,\n next: number,\n next2: number,\n): boolean {\n return (\n current === charCodes.atSign &&\n next === charCodes.atSign &&\n isIdentifierStart(next2)\n );\n}\n\n// This is the comprehensive set of JavaScript reserved words\n// If a word is in this set, it could be a reserved word,\n// depending on sourceType/strictMode/binding info. In other words\n// if a word is not in this set, it is not a reserved word under\n// any circumstance.\nconst reservedWordLikeSet = new Set([\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 // strict\n \"implements\",\n \"interface\",\n \"let\",\n \"package\",\n \"private\",\n \"protected\",\n \"public\",\n \"static\",\n \"yield\",\n // strictBind\n \"eval\",\n \"arguments\",\n // reservedWorkLike\n \"enum\",\n \"await\",\n]);\n\nexport function canBeReservedWord(word: string): boolean {\n return reservedWordLikeSet.has(word);\n}\n","import { ScopeFlag, BindingFlag } from \"./scopeflags.ts\";\nimport type { Position } from \"./location.ts\";\nimport type * as N from \"../types.ts\";\nimport { Errors } from \"../parse-error.ts\";\nimport type Tokenizer from \"../tokenizer/index.ts\";\n\nexport const enum NameType {\n // var-declared names in the current lexical scope\n Var = 1 << 0,\n // lexically-declared names in the current lexical scope\n Lexical = 1 << 1,\n // lexically-declared FunctionDeclaration names in the current lexical scope\n Function = 1 << 2,\n}\n\n// Start an AST node, attaching a start offset.\nexport class Scope {\n flags: ScopeFlag = 0;\n names = new Map();\n firstLexicalName = \"\";\n\n constructor(flags: ScopeFlag) {\n this.flags = flags;\n }\n}\n\n// The functions in this module keep track of declared variables in the\n// current scope in order to detect duplicate variable names.\nexport default class ScopeHandler {\n parser: Tokenizer;\n scopeStack: IScope[] = [];\n inModule: boolean;\n undefinedExports = new Map();\n\n constructor(parser: Tokenizer, inModule: boolean) {\n this.parser = parser;\n this.inModule = inModule;\n }\n\n get inTopLevel() {\n return (this.currentScope().flags & ScopeFlag.PROGRAM) > 0;\n }\n get inFunction() {\n return (this.currentVarScopeFlags() & ScopeFlag.FUNCTION_BASE) > 0;\n }\n get allowSuper() {\n return (this.currentThisScopeFlags() & ScopeFlag.SUPER) > 0;\n }\n get allowDirectSuper() {\n return (this.currentThisScopeFlags() & ScopeFlag.DIRECT_SUPER) > 0;\n }\n get allowNewTarget() {\n return (this.currentThisScopeFlags() & ScopeFlag.NEW_TARGET) > 0;\n }\n get inClass() {\n return (this.currentThisScopeFlags() & ScopeFlag.CLASS_BASE) > 0;\n }\n get inClassAndNotInNonArrowFunction() {\n const flags = this.currentThisScopeFlags();\n return (\n (flags & ScopeFlag.CLASS_BASE) > 0 &&\n (flags & ScopeFlag.FUNCTION_BASE) === 0\n );\n }\n get inStaticBlock() {\n for (let i = this.scopeStack.length - 1; ; i--) {\n const { flags } = this.scopeStack[i];\n if (flags & ScopeFlag.STATIC_BLOCK) {\n return true;\n }\n if (flags & (ScopeFlag.VAR | ScopeFlag.CLASS_BASE)) {\n // function body, module body, class property initializers\n return false;\n }\n }\n }\n get inNonArrowFunction() {\n return (this.currentThisScopeFlags() & ScopeFlag.FUNCTION_BASE) > 0;\n }\n get inBareCaseStatement() {\n return (this.currentScope().flags & ScopeFlag.SWITCH) > 0;\n }\n get treatFunctionsAsVar() {\n return this.treatFunctionsAsVarInScope(this.currentScope());\n }\n\n createScope(flags: ScopeFlag): Scope {\n return new Scope(flags);\n }\n\n enter(flags: ScopeFlag) {\n /*:: +createScope: (flags:ScopeFlag) => IScope; */\n // @ts-expect-error This method will be overwritten by subclasses\n this.scopeStack.push(this.createScope(flags));\n }\n\n exit(): ScopeFlag {\n const scope = this.scopeStack.pop()!;\n return scope.flags;\n }\n\n // The spec says:\n // > At the top level of a function, or script, function declarations are\n // > treated like var declarations rather than like lexical declarations.\n treatFunctionsAsVarInScope(scope: IScope): boolean {\n return !!(\n scope.flags & (ScopeFlag.FUNCTION_BASE | ScopeFlag.STATIC_BLOCK) ||\n (!this.parser.inModule && scope.flags & ScopeFlag.PROGRAM)\n );\n }\n\n declareName(name: string, bindingType: BindingFlag, loc: Position) {\n let scope = this.currentScope();\n if (\n bindingType & BindingFlag.SCOPE_LEXICAL ||\n bindingType & BindingFlag.SCOPE_FUNCTION\n ) {\n this.checkRedeclarationInScope(scope, name, bindingType, loc);\n\n let type = scope.names.get(name) || 0;\n\n if (bindingType & BindingFlag.SCOPE_FUNCTION) {\n type = type | NameType.Function;\n } else {\n if (!scope.firstLexicalName) {\n scope.firstLexicalName = name;\n }\n type = type | NameType.Lexical;\n }\n\n scope.names.set(name, type);\n\n if (bindingType & BindingFlag.SCOPE_LEXICAL) {\n this.maybeExportDefined(scope, name);\n }\n } else if (bindingType & BindingFlag.SCOPE_VAR) {\n for (let i = this.scopeStack.length - 1; i >= 0; --i) {\n scope = this.scopeStack[i];\n this.checkRedeclarationInScope(scope, name, bindingType, loc);\n scope.names.set(name, (scope.names.get(name) || 0) | NameType.Var);\n this.maybeExportDefined(scope, name);\n\n if (scope.flags & ScopeFlag.VAR) break;\n }\n }\n if (this.parser.inModule && scope.flags & ScopeFlag.PROGRAM) {\n this.undefinedExports.delete(name);\n }\n }\n\n maybeExportDefined(scope: IScope, name: string) {\n if (this.parser.inModule && scope.flags & ScopeFlag.PROGRAM) {\n this.undefinedExports.delete(name);\n }\n }\n\n checkRedeclarationInScope(\n scope: IScope,\n name: string,\n bindingType: BindingFlag,\n loc: Position,\n ) {\n if (this.isRedeclaredInScope(scope, name, bindingType)) {\n this.parser.raise(Errors.VarRedeclaration, loc, {\n identifierName: name,\n });\n }\n }\n\n isRedeclaredInScope(\n scope: IScope,\n name: string,\n bindingType: BindingFlag,\n ): boolean {\n if (!(bindingType & BindingFlag.KIND_VALUE)) return false;\n\n if (bindingType & BindingFlag.SCOPE_LEXICAL) {\n return scope.names.has(name);\n }\n\n const type = scope.names.get(name) || 0;\n\n if (bindingType & BindingFlag.SCOPE_FUNCTION) {\n return (\n (type & NameType.Lexical) > 0 ||\n (!this.treatFunctionsAsVarInScope(scope) && (type & NameType.Var) > 0)\n );\n }\n\n return (\n ((type & NameType.Lexical) > 0 &&\n // Annex B.3.4\n // https://tc39.es/ecma262/#sec-variablestatements-in-catch-blocks\n !(\n scope.flags & ScopeFlag.SIMPLE_CATCH &&\n scope.firstLexicalName === name\n )) ||\n (!this.treatFunctionsAsVarInScope(scope) &&\n (type & NameType.Function) > 0)\n );\n }\n\n checkLocalExport(id: N.Identifier) {\n const { name } = id;\n const topLevelScope = this.scopeStack[0];\n if (!topLevelScope.names.has(name)) {\n this.undefinedExports.set(name, id.loc.start);\n }\n }\n\n currentScope(): IScope {\n return this.scopeStack[this.scopeStack.length - 1];\n }\n\n currentVarScopeFlags(): ScopeFlag {\n for (let i = this.scopeStack.length - 1; ; i--) {\n const { flags } = this.scopeStack[i];\n if (flags & ScopeFlag.VAR) {\n return flags;\n }\n }\n }\n\n // Could be useful for `arguments`, `this`, `new.target`, `super()`, `super.property`, and `super[property]`.\n currentThisScopeFlags(): ScopeFlag {\n for (let i = this.scopeStack.length - 1; ; i--) {\n const { flags } = this.scopeStack[i];\n if (\n flags & (ScopeFlag.VAR | ScopeFlag.CLASS_BASE) &&\n !(flags & ScopeFlag.ARROW)\n ) {\n return flags;\n }\n }\n }\n}\n","import type { Position } from \"../../util/location.ts\";\nimport ScopeHandler, { NameType, Scope } from \"../../util/scope.ts\";\nimport { BindingFlag, type ScopeFlag } from \"../../util/scopeflags.ts\";\nimport type * as N from \"../../types.ts\";\n\n// Reference implementation: https://github.com/facebook/flow/blob/23aeb2a2ef6eb4241ce178fde5d8f17c5f747fb5/src/typing/env.ml#L536-L584\nclass FlowScope extends Scope {\n // declare function foo(): type;\n declareFunctions = new Set();\n}\n\nexport default class FlowScopeHandler extends ScopeHandler {\n createScope(flags: ScopeFlag): FlowScope {\n return new FlowScope(flags);\n }\n\n declareName(name: string, bindingType: BindingFlag, loc: Position) {\n const scope = this.currentScope();\n if (bindingType & BindingFlag.FLAG_FLOW_DECLARE_FN) {\n this.checkRedeclarationInScope(scope, name, bindingType, loc);\n this.maybeExportDefined(scope, name);\n scope.declareFunctions.add(name);\n return;\n }\n\n super.declareName(name, bindingType, loc);\n }\n\n isRedeclaredInScope(\n scope: FlowScope,\n name: string,\n bindingType: BindingFlag,\n ): boolean {\n if (super.isRedeclaredInScope(scope, name, bindingType)) return true;\n\n if (\n bindingType & BindingFlag.FLAG_FLOW_DECLARE_FN &&\n !scope.declareFunctions.has(name)\n ) {\n const type = scope.names.get(name)!;\n return (type & NameType.Function) > 0 || (type & NameType.Lexical) > 0;\n }\n\n return false;\n }\n\n checkLocalExport(id: N.Identifier) {\n if (!this.scopeStack[0].declareFunctions.has(id.name)) {\n super.checkLocalExport(id);\n }\n }\n}\n","/*:: declare var invariant; */\n\nimport type Parser from \"../../parser/index.ts\";\nimport {\n tokenIsIdentifier,\n tokenIsKeyword,\n tokenIsKeywordOrIdentifier,\n tokenIsLiteralPropertyName,\n tokenLabelName,\n tt,\n type TokenType,\n tokenIsFlowInterfaceOrTypeOrOpaque,\n} from \"../../tokenizer/types.ts\";\nimport type * as N from \"../../types.ts\";\nimport type { Position } from \"../../util/location.ts\";\nimport { types as tc } from \"../../tokenizer/context.ts\";\nimport * as charCodes from \"charcodes\";\nimport { isIteratorStart } from \"../../util/identifier.ts\";\nimport FlowScopeHandler from \"./scope.ts\";\nimport { BindingFlag, ScopeFlag } from \"../../util/scopeflags.ts\";\nimport type { ExpressionErrors } from \"../../parser/util.ts\";\nimport type { ParseStatementFlag } from \"../../parser/statement.ts\";\nimport { Errors, ParseErrorEnum } from \"../../parse-error.ts\";\nimport type { Undone } from \"../../parser/node.ts\";\nimport type { ClassWithMixin, IJSXParserMixin } from \"../jsx/index.ts\";\n\nconst reservedTypes = new Set([\n \"_\",\n \"any\",\n \"bool\",\n \"boolean\",\n \"empty\",\n \"extends\",\n \"false\",\n \"interface\",\n \"mixed\",\n \"null\",\n \"number\",\n \"static\",\n \"string\",\n \"true\",\n \"typeof\",\n \"void\",\n]);\n\n/* eslint sort-keys: \"error\" */\n// The Errors key follows https://github.com/facebook/flow/blob/master/src/parser/parse_error.ml unless it does not exist\nconst FlowErrors = ParseErrorEnum`flow`({\n AmbiguousConditionalArrow:\n \"Ambiguous expression: wrap the arrow functions in parentheses to disambiguate.\",\n AmbiguousDeclareModuleKind:\n \"Found both `declare module.exports` and `declare export` in the same module. Modules can only have 1 since they are either an ES module or they are a CommonJS module.\",\n // TODO: When we get proper string enums in typescript make this ReservedType.\n // Not really worth it to do the whole $Values dance with reservedTypes set.\n AssignReservedType: ({ reservedType }: { reservedType: string }) =>\n `Cannot overwrite reserved type ${reservedType}.`,\n DeclareClassElement:\n \"The `declare` modifier can only appear on class fields.\",\n DeclareClassFieldInitializer:\n \"Initializers are not allowed in fields with the `declare` modifier.\",\n DuplicateDeclareModuleExports:\n \"Duplicate `declare module.exports` statement.\",\n EnumBooleanMemberNotInitialized: ({\n memberName,\n enumName,\n }: {\n memberName: string;\n enumName: string;\n }) =>\n `Boolean enum members need to be initialized. Use either \\`${memberName} = true,\\` or \\`${memberName} = false,\\` in enum \\`${enumName}\\`.`,\n EnumDuplicateMemberName: ({\n memberName,\n enumName,\n }: {\n memberName: string;\n enumName: string;\n }) =>\n `Enum member names need to be unique, but the name \\`${memberName}\\` has already been used before in enum \\`${enumName}\\`.`,\n EnumInconsistentMemberValues: ({ enumName }: { enumName: string }) =>\n `Enum \\`${enumName}\\` has inconsistent member initializers. Either use no initializers, or consistently use literals (either booleans, numbers, or strings) for all member initializers.`,\n EnumInvalidExplicitType: ({\n invalidEnumType,\n enumName,\n }: {\n invalidEnumType: string;\n enumName: string;\n }) =>\n `Enum type \\`${invalidEnumType}\\` is not valid. Use one of \\`boolean\\`, \\`number\\`, \\`string\\`, or \\`symbol\\` in enum \\`${enumName}\\`.`,\n EnumInvalidExplicitTypeUnknownSupplied: ({\n enumName,\n }: {\n enumName: string;\n }) =>\n `Supplied enum type is not valid. Use one of \\`boolean\\`, \\`number\\`, \\`string\\`, or \\`symbol\\` in enum \\`${enumName}\\`.`,\n\n // TODO: When moving to typescript, we should either have each of the\n // following errors only accept the specific strings they want:\n //\n // ...PrimaryType: explicitType: \"string\" | \"number\" | \"boolean\"\n // ...SymbolType: explicitType: \"symbol\"\n // ...UnknownType: explicitType: null\n //\n // Or, alternatively, merge these three errors together into one\n // `EnumInvalidMemberInitializer` error that can accept `EnumExplicitType`\n // without alteration, and then just have its message change based on the\n // explicitType.\n EnumInvalidMemberInitializerPrimaryType: ({\n enumName,\n memberName,\n explicitType,\n }: {\n enumName: string;\n memberName: string;\n explicitType: EnumExplicitType;\n }) =>\n `Enum \\`${enumName}\\` has type \\`${explicitType}\\`, so the initializer of \\`${memberName}\\` needs to be a ${explicitType} literal.`,\n EnumInvalidMemberInitializerSymbolType: ({\n enumName,\n memberName,\n }: {\n enumName: string;\n memberName: string;\n explicitType: EnumExplicitType;\n }) =>\n `Symbol enum members cannot be initialized. Use \\`${memberName},\\` in enum \\`${enumName}\\`.`,\n EnumInvalidMemberInitializerUnknownType: ({\n enumName,\n memberName,\n }: {\n enumName: string;\n memberName: string;\n explicitType: EnumExplicitType;\n }) =>\n `The enum member initializer for \\`${memberName}\\` needs to be a literal (either a boolean, number, or string) in enum \\`${enumName}\\`.`,\n EnumInvalidMemberName: ({\n enumName,\n memberName,\n suggestion,\n }: {\n enumName: string;\n memberName: string;\n suggestion: string;\n }) =>\n `Enum member names cannot start with lowercase 'a' through 'z'. Instead of using \\`${memberName}\\`, consider using \\`${suggestion}\\`, in enum \\`${enumName}\\`.`,\n EnumNumberMemberNotInitialized: ({\n enumName,\n memberName,\n }: {\n enumName: string;\n memberName: string;\n }) =>\n `Number enum members need to be initialized, e.g. \\`${memberName} = 1\\` in enum \\`${enumName}\\`.`,\n EnumStringMemberInconsistentlyInitialized: ({\n enumName,\n }: {\n enumName: string;\n }) =>\n `String enum members need to consistently either all use initializers, or use no initializers, in enum \\`${enumName}\\`.`,\n GetterMayNotHaveThisParam: \"A getter cannot have a `this` parameter.\",\n ImportReflectionHasImportType:\n \"An `import module` declaration can not use `type` or `typeof` keyword.\",\n ImportTypeShorthandOnlyInPureImport:\n \"The `type` and `typeof` keywords on named imports can only be used on regular `import` statements. It cannot be used with `import type` or `import typeof` statements.\",\n InexactInsideExact:\n \"Explicit inexact syntax cannot appear inside an explicit exact object type.\",\n InexactInsideNonObject:\n \"Explicit inexact syntax cannot appear in class or interface definitions.\",\n InexactVariance: \"Explicit inexact syntax cannot have variance.\",\n InvalidNonTypeImportInDeclareModule:\n \"Imports within a `declare module` body must always be `import type` or `import typeof`.\",\n MissingTypeParamDefault:\n \"Type parameter declaration needs a default, since a preceding type parameter declaration has a default.\",\n NestedDeclareModule:\n \"`declare module` cannot be used inside another `declare module`.\",\n NestedFlowComment: \"Cannot have a flow comment inside another flow comment.\",\n PatternIsOptional: {\n message:\n \"A binding pattern parameter cannot be optional in an implementation signature.\",\n // For consistency in TypeScript and Flow error codes\n ...(!process.env.BABEL_8_BREAKING\n ? { reasonCode: \"OptionalBindingPattern\" }\n : {}),\n },\n SetterMayNotHaveThisParam: \"A setter cannot have a `this` parameter.\",\n SpreadVariance: \"Spread properties cannot have variance.\",\n ThisParamAnnotationRequired:\n \"A type annotation is required for the `this` parameter.\",\n ThisParamBannedInConstructor:\n \"Constructors cannot have a `this` parameter; constructors don't bind `this` like other functions.\",\n ThisParamMayNotBeOptional: \"The `this` parameter cannot be optional.\",\n ThisParamMustBeFirst:\n \"The `this` parameter must be the first function parameter.\",\n ThisParamNoDefault: \"The `this` parameter may not have a default value.\",\n TypeBeforeInitializer:\n \"Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.\",\n TypeCastInPattern:\n \"The type cast expression is expected to be wrapped with parenthesis.\",\n UnexpectedExplicitInexactInObject:\n \"Explicit inexact syntax must appear at the end of an inexact object.\",\n UnexpectedReservedType: ({ reservedType }: { reservedType: string }) =>\n `Unexpected reserved type ${reservedType}.`,\n UnexpectedReservedUnderscore:\n \"`_` is only allowed as a type argument to call or new.\",\n UnexpectedSpaceBetweenModuloChecks:\n \"Spaces between `%` and `checks` are not allowed here.\",\n UnexpectedSpreadType:\n \"Spread operator cannot appear in class or interface definitions.\",\n UnexpectedSubtractionOperand:\n 'Unexpected token, expected \"number\" or \"bigint\".',\n UnexpectedTokenAfterTypeParameter:\n \"Expected an arrow function after this type parameter declaration.\",\n UnexpectedTypeParameterBeforeAsyncArrowFunction:\n \"Type parameters must come after the async keyword, e.g. instead of ` async () => {}`, use `async () => {}`.\",\n UnsupportedDeclareExportKind: ({\n unsupportedExportKind,\n suggestion,\n }: {\n unsupportedExportKind: string;\n suggestion: string;\n }) =>\n `\\`declare export ${unsupportedExportKind}\\` is not supported. Use \\`${suggestion}\\` instead.`,\n UnsupportedStatementInDeclareModule:\n \"Only declares and type imports are allowed inside declare module.\",\n UnterminatedFlowComment: \"Unterminated flow-comment.\",\n});\n/* eslint-disable sort-keys */\n\nfunction isEsModuleType(bodyElement: N.Node): boolean {\n return (\n bodyElement.type === \"DeclareExportAllDeclaration\" ||\n (bodyElement.type === \"DeclareExportDeclaration\" &&\n (!bodyElement.declaration ||\n (bodyElement.declaration.type !== \"TypeAlias\" &&\n bodyElement.declaration.type !== \"InterfaceDeclaration\")))\n );\n}\n\nfunction hasTypeImportKind(\n node: Undone,\n): boolean {\n return node.importKind === \"type\" || node.importKind === \"typeof\";\n}\n\nconst exportSuggestions = {\n const: \"declare export var\",\n let: \"declare export var\",\n type: \"export type\",\n interface: \"export interface\",\n};\n\n// Like Array#filter, but returns a tuple [ acceptedElements, discardedElements ]\nfunction partition(\n list: T[],\n test: (c: T, b: number, a: T[]) => boolean | undefined | null,\n): [T[], T[]] {\n const list1: T[] = [];\n const list2: T[] = [];\n for (let i = 0; i < list.length; i++) {\n (test(list[i], i, list) ? list1 : list2).push(list[i]);\n }\n return [list1, list2];\n}\n\nconst FLOW_PRAGMA_REGEX = /\\*?\\s*@((?:no)?flow)\\b/;\n\n// Flow enums types\ntype EnumExplicitType = null | \"boolean\" | \"number\" | \"string\" | \"symbol\";\n\ntype EnumContext = {\n enumName: string;\n explicitType: EnumExplicitType;\n memberName: string;\n};\n\ntype EnumMemberInit =\n | {\n type: \"number\";\n loc: Position;\n value: N.Node;\n }\n | {\n type: \"string\";\n loc: Position;\n value: N.Node;\n }\n | {\n type: \"boolean\";\n loc: Position;\n value: N.Node;\n }\n | {\n type: \"invalid\";\n loc: Position;\n }\n | {\n type: \"none\";\n loc: Position;\n };\n\nexport default (superClass: ClassWithMixin) =>\n class FlowParserMixin extends superClass implements Parser {\n // The value of the @flow/@noflow pragma. Initially undefined, transitions\n // to \"@flow\" or \"@noflow\" if we see a pragma. Transitions to null if we are\n // past the initial comment.\n flowPragma: void | null | \"flow\" | \"noflow\" = undefined;\n\n getScopeHandler(): new (...args: any) => FlowScopeHandler {\n return FlowScopeHandler;\n }\n\n shouldParseTypes(): boolean {\n return this.getPluginOption(\"flow\", \"all\") || this.flowPragma === \"flow\";\n }\n\n finishToken(type: TokenType, val: any): void {\n if (\n type !== tt.string &&\n type !== tt.semi &&\n type !== tt.interpreterDirective\n ) {\n if (this.flowPragma === undefined) {\n this.flowPragma = null;\n }\n }\n super.finishToken(type, val);\n }\n\n addComment(comment: N.Comment): void {\n if (this.flowPragma === undefined) {\n // Try to parse a flow pragma.\n const matches = FLOW_PRAGMA_REGEX.exec(comment.value);\n if (!matches) {\n // do nothing\n } else if (matches[1] === \"flow\") {\n this.flowPragma = \"flow\";\n } else if (matches[1] === \"noflow\") {\n this.flowPragma = \"noflow\";\n } else {\n throw new Error(\"Unexpected flow pragma\");\n }\n }\n super.addComment(comment);\n }\n\n flowParseTypeInitialiser(tok?: TokenType): N.FlowType {\n const oldInType = this.state.inType;\n this.state.inType = true;\n this.expect(tok || tt.colon);\n\n const type = this.flowParseType();\n this.state.inType = oldInType;\n return type;\n }\n\n flowParsePredicate(): N.FlowPredicate {\n const node = this.startNode();\n const moduloLoc = this.state.startLoc;\n this.next(); // eat `%`\n this.expectContextual(tt._checks);\n // Force '%' and 'checks' to be adjacent\n if (this.state.lastTokStartLoc!.index > moduloLoc.index + 1) {\n this.raise(FlowErrors.UnexpectedSpaceBetweenModuloChecks, moduloLoc);\n }\n if (this.eat(tt.parenL)) {\n node.value = super.parseExpression();\n this.expect(tt.parenR);\n return this.finishNode(node, \"DeclaredPredicate\");\n } else {\n return this.finishNode(node, \"InferredPredicate\");\n }\n }\n\n flowParseTypeAndPredicateInitialiser(): [\n N.FlowType | null,\n N.FlowPredicate | null,\n ] {\n const oldInType = this.state.inType;\n this.state.inType = true;\n this.expect(tt.colon);\n let type = null;\n let predicate = null;\n if (this.match(tt.modulo)) {\n this.state.inType = oldInType;\n predicate = this.flowParsePredicate();\n } else {\n type = this.flowParseType();\n this.state.inType = oldInType;\n if (this.match(tt.modulo)) {\n predicate = this.flowParsePredicate();\n }\n }\n return [type, predicate];\n }\n\n flowParseDeclareClass(\n node: Undone,\n ): N.FlowDeclareClass {\n this.next();\n this.flowParseInterfaceish(node, /*isClass*/ true);\n return this.finishNode(node, \"DeclareClass\");\n }\n\n flowParseDeclareFunction(\n node: Undone,\n ): N.FlowDeclareFunction {\n this.next();\n\n const id = (node.id = this.parseIdentifier());\n\n const typeNode = this.startNode();\n const typeContainer = this.startNode();\n\n if (this.match(tt.lt)) {\n typeNode.typeParameters = this.flowParseTypeParameterDeclaration();\n } else {\n typeNode.typeParameters = null;\n }\n\n this.expect(tt.parenL);\n const tmp = this.flowParseFunctionTypeParams();\n typeNode.params = tmp.params;\n typeNode.rest = tmp.rest;\n typeNode.this = tmp._this;\n this.expect(tt.parenR);\n\n [typeNode.returnType, node.predicate] =\n this.flowParseTypeAndPredicateInitialiser();\n\n typeContainer.typeAnnotation = this.finishNode(\n typeNode,\n \"FunctionTypeAnnotation\",\n );\n\n id.typeAnnotation = this.finishNode(typeContainer, \"TypeAnnotation\");\n\n this.resetEndLocation(id);\n this.semicolon();\n\n this.scope.declareName(\n node.id.name,\n BindingFlag.TYPE_FLOW_DECLARE_FN,\n node.id.loc.start,\n );\n\n return this.finishNode(node, \"DeclareFunction\");\n }\n\n flowParseDeclare(\n node: Undone,\n insideModule?: boolean,\n ): N.FlowDeclare {\n if (this.match(tt._class)) {\n return this.flowParseDeclareClass(node);\n } else if (this.match(tt._function)) {\n return this.flowParseDeclareFunction(node);\n } else if (this.match(tt._var)) {\n return this.flowParseDeclareVariable(node);\n } else if (this.eatContextual(tt._module)) {\n if (this.match(tt.dot)) {\n return this.flowParseDeclareModuleExports(node);\n } else {\n if (insideModule) {\n this.raise(\n FlowErrors.NestedDeclareModule,\n this.state.lastTokStartLoc!,\n );\n }\n return this.flowParseDeclareModule(node);\n }\n } else if (this.isContextual(tt._type)) {\n return this.flowParseDeclareTypeAlias(node);\n } else if (this.isContextual(tt._opaque)) {\n return this.flowParseDeclareOpaqueType(node);\n } else if (this.isContextual(tt._interface)) {\n return this.flowParseDeclareInterface(node);\n } else if (this.match(tt._export)) {\n return this.flowParseDeclareExportDeclaration(node, insideModule);\n }\n throw this.unexpected();\n }\n\n flowParseDeclareVariable(\n node: Undone,\n ): N.FlowDeclareVariable {\n this.next();\n node.id = this.flowParseTypeAnnotatableIdentifier(\n /*allowPrimitiveOverride*/ true,\n );\n this.scope.declareName(\n node.id.name,\n BindingFlag.TYPE_VAR,\n node.id.loc.start,\n );\n this.semicolon();\n return this.finishNode(node, \"DeclareVariable\");\n }\n\n flowParseDeclareModule(\n node: Undone,\n ): N.FlowDeclareModule {\n this.scope.enter(ScopeFlag.OTHER);\n\n if (this.match(tt.string)) {\n node.id = super.parseExprAtom();\n } else {\n node.id = this.parseIdentifier();\n }\n\n const bodyNode = (node.body = this.startNode());\n const body: N.Statement[] = (bodyNode.body = []);\n this.expect(tt.braceL);\n while (!this.match(tt.braceR)) {\n const bodyNode = this.startNode();\n\n if (this.match(tt._import)) {\n this.next();\n if (!this.isContextual(tt._type) && !this.match(tt._typeof)) {\n this.raise(\n FlowErrors.InvalidNonTypeImportInDeclareModule,\n this.state.lastTokStartLoc!,\n );\n }\n body.push(super.parseImport(bodyNode));\n } else {\n this.expectContextual(\n tt._declare,\n FlowErrors.UnsupportedStatementInDeclareModule,\n );\n body.push(this.flowParseDeclare(bodyNode, true));\n }\n }\n\n this.scope.exit();\n\n this.expect(tt.braceR);\n\n this.finishNode(bodyNode, \"BlockStatement\");\n\n let kind: \"CommonJS\" | \"ES\" | null = null;\n let hasModuleExport = false;\n body.forEach(bodyElement => {\n if (isEsModuleType(bodyElement)) {\n if (kind === \"CommonJS\") {\n this.raise(FlowErrors.AmbiguousDeclareModuleKind, bodyElement);\n }\n kind = \"ES\";\n } else if (bodyElement.type === \"DeclareModuleExports\") {\n if (hasModuleExport) {\n this.raise(FlowErrors.DuplicateDeclareModuleExports, bodyElement);\n }\n if (kind === \"ES\") {\n this.raise(FlowErrors.AmbiguousDeclareModuleKind, bodyElement);\n }\n kind = \"CommonJS\";\n hasModuleExport = true;\n }\n });\n\n node.kind = kind || \"CommonJS\";\n return this.finishNode(node, \"DeclareModule\");\n }\n\n flowParseDeclareExportDeclaration(\n node: Undone,\n insideModule?: boolean | null,\n ): N.FlowDeclareExportDeclaration {\n this.expect(tt._export);\n\n if (this.eat(tt._default)) {\n if (this.match(tt._function) || this.match(tt._class)) {\n // declare export default class ...\n // declare export default function ...\n node.declaration = this.flowParseDeclare(this.startNode());\n } else {\n // declare export default [type];\n node.declaration = this.flowParseType();\n this.semicolon();\n }\n node.default = true;\n\n return this.finishNode(node, \"DeclareExportDeclaration\");\n } else {\n if (\n this.match(tt._const) ||\n this.isLet() ||\n ((this.isContextual(tt._type) || this.isContextual(tt._interface)) &&\n !insideModule)\n ) {\n const label = this.state.value as\n | \"const\"\n | \"let\"\n | \"type\"\n | \"interface\";\n throw this.raise(\n FlowErrors.UnsupportedDeclareExportKind,\n this.state.startLoc,\n {\n unsupportedExportKind: label,\n suggestion: exportSuggestions[label],\n },\n );\n }\n\n if (\n this.match(tt._var) || // declare export var ...\n this.match(tt._function) || // declare export function ...\n this.match(tt._class) || // declare export class ...\n this.isContextual(tt._opaque) // declare export opaque ..\n ) {\n node.declaration = this.flowParseDeclare(this.startNode());\n node.default = false;\n\n return this.finishNode(node, \"DeclareExportDeclaration\");\n } else if (\n this.match(tt.star) || // declare export * from ''\n this.match(tt.braceL) || // declare export {} ...\n this.isContextual(tt._interface) || // declare export interface ...\n this.isContextual(tt._type) || // declare export type ...\n this.isContextual(tt._opaque) // declare export opaque type ...\n ) {\n node = this.parseExport(\n node as Undone,\n /* decorators */ null,\n );\n if (node.type === \"ExportNamedDeclaration\") {\n node.default = false;\n delete node.exportKind;\n return this.castNodeTo(\n node as N.ExportNamedDeclaration,\n \"DeclareExportDeclaration\",\n );\n } else {\n return this.castNodeTo(\n node as N.ExportAllDeclaration,\n \"DeclareExportAllDeclaration\",\n );\n }\n }\n }\n\n throw this.unexpected();\n }\n\n flowParseDeclareModuleExports(\n node: Undone,\n ): N.FlowDeclareModuleExports {\n this.next();\n this.expectContextual(tt._exports);\n node.typeAnnotation = this.flowParseTypeAnnotation();\n this.semicolon();\n\n return this.finishNode(node, \"DeclareModuleExports\");\n }\n\n flowParseDeclareTypeAlias(\n node: Undone,\n ): N.FlowDeclareTypeAlias {\n this.next();\n const finished = this.flowParseTypeAlias(\n node,\n ) as unknown as N.FlowDeclareTypeAlias;\n // Don't do finishNode as we don't want to process comments twice\n this.castNodeTo(finished, \"DeclareTypeAlias\");\n return finished;\n }\n\n flowParseDeclareOpaqueType(\n node: Undone,\n ): N.FlowDeclareOpaqueType {\n this.next();\n const finished = this.flowParseOpaqueType(\n node,\n true,\n ) as unknown as N.FlowDeclareOpaqueType;\n // Don't do finishNode as we don't want to process comments twice\n this.castNodeTo(finished, \"DeclareOpaqueType\");\n return finished;\n }\n\n flowParseDeclareInterface(\n node: Undone,\n ): N.FlowDeclareInterface {\n this.next();\n this.flowParseInterfaceish(node, /* isClass */ false);\n return this.finishNode(node, \"DeclareInterface\");\n }\n\n // Interfaces\n\n flowParseInterfaceish(node: Undone, isClass: boolean): void {\n node.id = this.flowParseRestrictedIdentifier(\n /* liberal */ !isClass,\n /* declaration */ true,\n );\n\n this.scope.declareName(\n node.id.name,\n isClass ? BindingFlag.TYPE_FUNCTION : BindingFlag.TYPE_LEXICAL,\n node.id.loc.start,\n );\n\n if (this.match(tt.lt)) {\n node.typeParameters = this.flowParseTypeParameterDeclaration();\n } else {\n node.typeParameters = null;\n }\n\n node.extends = [];\n\n if (this.eat(tt._extends)) {\n do {\n node.extends.push(this.flowParseInterfaceExtends());\n } while (!isClass && this.eat(tt.comma));\n }\n\n if (isClass) {\n node.implements = [];\n node.mixins = [];\n\n if (this.eatContextual(tt._mixins)) {\n do {\n node.mixins.push(this.flowParseInterfaceExtends());\n } while (this.eat(tt.comma));\n }\n\n if (this.eatContextual(tt._implements)) {\n do {\n node.implements.push(this.flowParseInterfaceExtends());\n } while (this.eat(tt.comma));\n }\n }\n\n node.body = this.flowParseObjectType({\n allowStatic: isClass,\n allowExact: false,\n allowSpread: false,\n allowProto: isClass,\n allowInexact: false,\n });\n }\n\n flowParseInterfaceExtends(): N.FlowInterfaceExtends {\n const node = this.startNode();\n\n node.id = this.flowParseQualifiedTypeIdentifier();\n if (this.match(tt.lt)) {\n node.typeParameters = this.flowParseTypeParameterInstantiation();\n } else {\n node.typeParameters = null;\n }\n\n return this.finishNode(node, \"InterfaceExtends\");\n }\n\n flowParseInterface(node: Undone): N.FlowInterface {\n this.flowParseInterfaceish(node, /* isClass */ false);\n return this.finishNode(node, \"InterfaceDeclaration\");\n }\n\n checkNotUnderscore(word: string) {\n if (word === \"_\") {\n this.raise(\n FlowErrors.UnexpectedReservedUnderscore,\n this.state.startLoc,\n );\n }\n }\n\n checkReservedType(word: string, startLoc: Position, declaration?: boolean) {\n if (!reservedTypes.has(word)) return;\n\n this.raise(\n declaration\n ? FlowErrors.AssignReservedType\n : FlowErrors.UnexpectedReservedType,\n startLoc,\n {\n reservedType: word,\n },\n );\n }\n\n flowParseRestrictedIdentifier(\n liberal?: boolean,\n declaration?: boolean,\n ): N.Identifier {\n this.checkReservedType(\n this.state.value,\n this.state.startLoc,\n declaration,\n );\n return this.parseIdentifier(liberal);\n }\n\n // Type aliases\n\n flowParseTypeAlias(node: Undone): N.FlowTypeAlias {\n node.id = this.flowParseRestrictedIdentifier(\n /* liberal */ false,\n /* declaration */ true,\n );\n this.scope.declareName(\n node.id.name,\n BindingFlag.TYPE_LEXICAL,\n node.id.loc.start,\n );\n\n if (this.match(tt.lt)) {\n node.typeParameters = this.flowParseTypeParameterDeclaration();\n } else {\n node.typeParameters = null;\n }\n\n node.right = this.flowParseTypeInitialiser(tt.eq);\n this.semicolon();\n\n return this.finishNode(node, \"TypeAlias\");\n }\n\n flowParseOpaqueType(\n node: Undone,\n declare: boolean,\n ): N.FlowOpaqueType {\n this.expectContextual(tt._type);\n node.id = this.flowParseRestrictedIdentifier(\n /* liberal */ true,\n /* declaration */ true,\n );\n this.scope.declareName(\n node.id.name,\n BindingFlag.TYPE_LEXICAL,\n node.id.loc.start,\n );\n\n if (this.match(tt.lt)) {\n node.typeParameters = this.flowParseTypeParameterDeclaration();\n } else {\n node.typeParameters = null;\n }\n\n // Parse the supertype\n node.supertype = null;\n if (this.match(tt.colon)) {\n node.supertype = this.flowParseTypeInitialiser(tt.colon);\n }\n\n node.impltype = null;\n if (!declare) {\n node.impltype = this.flowParseTypeInitialiser(tt.eq);\n }\n this.semicolon();\n\n return this.finishNode(node, \"OpaqueType\");\n }\n\n // Type annotations\n\n flowParseTypeParameter(requireDefault: boolean = false): N.TypeParameter {\n const nodeStartLoc = this.state.startLoc;\n\n const node = this.startNode();\n\n const variance = this.flowParseVariance();\n\n const ident = this.flowParseTypeAnnotatableIdentifier();\n node.name = ident.name;\n // @ts-expect-error migrate to Babel types\n node.variance = variance;\n // @ts-expect-error migrate to Babel types\n node.bound = ident.typeAnnotation;\n\n if (this.match(tt.eq)) {\n this.eat(tt.eq);\n // @ts-expect-error migrate to Babel types\n node.default = this.flowParseType();\n } else {\n if (requireDefault) {\n this.raise(FlowErrors.MissingTypeParamDefault, nodeStartLoc);\n }\n }\n\n return this.finishNode(node, \"TypeParameter\");\n }\n\n flowParseTypeParameterDeclaration(): N.TypeParameterDeclaration {\n const oldInType = this.state.inType;\n const node = this.startNode();\n node.params = [];\n\n this.state.inType = true;\n\n // istanbul ignore else: this condition is already checked at all call sites\n if (this.match(tt.lt) || this.match(tt.jsxTagStart)) {\n this.next();\n } else {\n this.unexpected();\n }\n\n let defaultRequired = false;\n\n do {\n const typeParameter = this.flowParseTypeParameter(defaultRequired);\n\n node.params.push(typeParameter);\n\n if (typeParameter.default) {\n defaultRequired = true;\n }\n\n if (!this.match(tt.gt)) {\n this.expect(tt.comma);\n }\n } while (!this.match(tt.gt));\n this.expect(tt.gt);\n\n this.state.inType = oldInType;\n\n return this.finishNode(node, \"TypeParameterDeclaration\");\n }\n\n // Parse in top level normal context if we are in a JSX context\n flowInTopLevelContext(cb: () => T): T {\n if (this.curContext() !== tc.brace) {\n const oldContext = this.state.context;\n this.state.context = [oldContext[0]];\n try {\n return cb();\n } finally {\n this.state.context = oldContext;\n }\n } else {\n return cb();\n }\n }\n\n // Used when parsing type arguments from ES or JSX productions, where the first token\n // has been created without state.inType. Thus we need to re-scan the lt token.\n flowParseTypeParameterInstantiationInExpression():\n | N.TypeParameterInstantiation\n | undefined {\n if (this.reScan_lt() !== tt.lt) return;\n return this.flowParseTypeParameterInstantiation();\n }\n\n flowParseTypeParameterInstantiation(): N.TypeParameterInstantiation {\n const node = this.startNode();\n const oldInType = this.state.inType;\n\n this.state.inType = true;\n node.params = [];\n this.flowInTopLevelContext(() => {\n this.expect(tt.lt);\n const oldNoAnonFunctionType = this.state.noAnonFunctionType;\n this.state.noAnonFunctionType = false;\n while (!this.match(tt.gt)) {\n node.params.push(this.flowParseType());\n if (!this.match(tt.gt)) {\n this.expect(tt.comma);\n }\n }\n this.state.noAnonFunctionType = oldNoAnonFunctionType;\n });\n\n this.state.inType = oldInType;\n if (!this.state.inType && this.curContext() === tc.brace) {\n // rescan `>` when we are no longer in type context and JSX parsing context\n // since it was tokenized when `inType` is `true`.\n this.reScan_lt_gt();\n }\n this.expect(tt.gt);\n\n return this.finishNode(node, \"TypeParameterInstantiation\");\n }\n\n flowParseTypeParameterInstantiationCallOrNew(): N.TypeParameterInstantiation | null {\n if (this.reScan_lt() !== tt.lt) return null;\n const node = this.startNode();\n const oldInType = this.state.inType;\n node.params = [];\n\n this.state.inType = true;\n\n this.expect(tt.lt);\n while (!this.match(tt.gt)) {\n node.params.push(this.flowParseTypeOrImplicitInstantiation());\n if (!this.match(tt.gt)) {\n this.expect(tt.comma);\n }\n }\n this.expect(tt.gt);\n\n this.state.inType = oldInType;\n\n return this.finishNode(node, \"TypeParameterInstantiation\");\n }\n\n flowParseInterfaceType(): N.FlowInterfaceType {\n const node = this.startNode();\n this.expectContextual(tt._interface);\n\n node.extends = [];\n if (this.eat(tt._extends)) {\n do {\n node.extends.push(this.flowParseInterfaceExtends());\n } while (this.eat(tt.comma));\n }\n\n node.body = this.flowParseObjectType({\n allowStatic: false,\n allowExact: false,\n allowSpread: false,\n allowProto: false,\n allowInexact: false,\n });\n\n return this.finishNode(node, \"InterfaceTypeAnnotation\");\n }\n\n flowParseObjectPropertyKey(): N.Expression {\n return this.match(tt.num) || this.match(tt.string)\n ? super.parseExprAtom()\n : this.parseIdentifier(true);\n }\n\n flowParseObjectTypeIndexer(\n node: Undone,\n isStatic: boolean,\n variance?: N.FlowVariance | null,\n ): N.FlowObjectTypeIndexer {\n node.static = isStatic;\n\n // Note: bracketL has already been consumed\n if (this.lookahead().type === tt.colon) {\n node.id = this.flowParseObjectPropertyKey();\n node.key = this.flowParseTypeInitialiser();\n } else {\n node.id = null;\n node.key = this.flowParseType();\n }\n this.expect(tt.bracketR);\n node.value = this.flowParseTypeInitialiser();\n node.variance = variance;\n\n return this.finishNode(node, \"ObjectTypeIndexer\");\n }\n\n flowParseObjectTypeInternalSlot(\n node: Undone,\n isStatic: boolean,\n ): N.FlowObjectTypeInternalSlot {\n node.static = isStatic;\n // Note: both bracketL have already been consumed\n node.id = this.flowParseObjectPropertyKey();\n this.expect(tt.bracketR);\n this.expect(tt.bracketR);\n if (this.match(tt.lt) || this.match(tt.parenL)) {\n node.method = true;\n node.optional = false;\n node.value = this.flowParseObjectTypeMethodish(\n this.startNodeAt(node.loc.start),\n );\n } else {\n node.method = false;\n if (this.eat(tt.question)) {\n node.optional = true;\n }\n node.value = this.flowParseTypeInitialiser();\n }\n return this.finishNode(node, \"ObjectTypeInternalSlot\");\n }\n\n flowParseObjectTypeMethodish(\n node: Undone,\n ): N.FlowFunctionTypeAnnotation {\n node.params = [];\n node.rest = null;\n node.typeParameters = null;\n node.this = null;\n\n if (this.match(tt.lt)) {\n node.typeParameters = this.flowParseTypeParameterDeclaration();\n }\n\n this.expect(tt.parenL);\n if (this.match(tt._this)) {\n node.this = this.flowParseFunctionTypeParam(/* first */ true);\n // match Flow parser behavior\n node.this.name = null;\n if (!this.match(tt.parenR)) {\n this.expect(tt.comma);\n }\n }\n while (!this.match(tt.parenR) && !this.match(tt.ellipsis)) {\n node.params.push(this.flowParseFunctionTypeParam(false));\n if (!this.match(tt.parenR)) {\n this.expect(tt.comma);\n }\n }\n\n if (this.eat(tt.ellipsis)) {\n node.rest = this.flowParseFunctionTypeParam(false);\n }\n this.expect(tt.parenR);\n node.returnType = this.flowParseTypeInitialiser();\n\n return this.finishNode(node, \"FunctionTypeAnnotation\");\n }\n\n flowParseObjectTypeCallProperty(\n node: Undone,\n isStatic: boolean,\n ): N.FlowObjectTypeCallProperty {\n const valueNode = this.startNode();\n node.static = isStatic;\n node.value = this.flowParseObjectTypeMethodish(valueNode);\n return this.finishNode(node, \"ObjectTypeCallProperty\");\n }\n\n flowParseObjectType({\n allowStatic,\n allowExact,\n allowSpread,\n allowProto,\n allowInexact,\n }: {\n allowStatic: boolean;\n allowExact: boolean;\n allowSpread: boolean;\n allowProto: boolean;\n allowInexact: boolean;\n }): N.FlowObjectTypeAnnotation {\n const oldInType = this.state.inType;\n this.state.inType = true;\n\n const nodeStart = this.startNode();\n\n nodeStart.callProperties = [];\n nodeStart.properties = [];\n nodeStart.indexers = [];\n nodeStart.internalSlots = [];\n\n let endDelim;\n let exact;\n let inexact = false;\n if (allowExact && this.match(tt.braceBarL)) {\n this.expect(tt.braceBarL);\n endDelim = tt.braceBarR;\n exact = true;\n } else {\n this.expect(tt.braceL);\n endDelim = tt.braceR;\n exact = false;\n }\n\n nodeStart.exact = exact;\n\n while (!this.match(endDelim)) {\n let isStatic = false;\n let protoStartLoc: Position | undefined | null = null;\n let inexactStartLoc: Position | undefined | null = null;\n const node = this.startNode();\n\n if (allowProto && this.isContextual(tt._proto)) {\n const lookahead = this.lookahead();\n\n if (lookahead.type !== tt.colon && lookahead.type !== tt.question) {\n this.next();\n protoStartLoc = this.state.startLoc;\n allowStatic = false;\n }\n }\n\n if (allowStatic && this.isContextual(tt._static)) {\n const lookahead = this.lookahead();\n\n // static is a valid identifier name\n if (lookahead.type !== tt.colon && lookahead.type !== tt.question) {\n this.next();\n isStatic = true;\n }\n }\n\n const variance = this.flowParseVariance();\n\n if (this.eat(tt.bracketL)) {\n if (protoStartLoc != null) {\n this.unexpected(protoStartLoc);\n }\n if (this.eat(tt.bracketL)) {\n if (variance) {\n this.unexpected(variance.loc.start);\n }\n nodeStart.internalSlots.push(\n this.flowParseObjectTypeInternalSlot(node, isStatic),\n );\n } else {\n nodeStart.indexers.push(\n this.flowParseObjectTypeIndexer(node, isStatic, variance),\n );\n }\n } else if (this.match(tt.parenL) || this.match(tt.lt)) {\n if (protoStartLoc != null) {\n this.unexpected(protoStartLoc);\n }\n if (variance) {\n this.unexpected(variance.loc.start);\n }\n nodeStart.callProperties.push(\n this.flowParseObjectTypeCallProperty(node, isStatic),\n );\n } else {\n let kind = \"init\";\n\n if (this.isContextual(tt._get) || this.isContextual(tt._set)) {\n const lookahead = this.lookahead();\n if (tokenIsLiteralPropertyName(lookahead.type)) {\n kind = this.state.value;\n this.next();\n }\n }\n\n const propOrInexact = this.flowParseObjectTypeProperty(\n node,\n isStatic,\n protoStartLoc,\n variance,\n kind,\n allowSpread,\n allowInexact ?? !exact,\n );\n\n if (propOrInexact === null) {\n inexact = true;\n inexactStartLoc = this.state.lastTokStartLoc;\n } else {\n nodeStart.properties.push(propOrInexact);\n }\n }\n\n this.flowObjectTypeSemicolon();\n\n if (\n inexactStartLoc &&\n !this.match(tt.braceR) &&\n !this.match(tt.braceBarR)\n ) {\n this.raise(\n FlowErrors.UnexpectedExplicitInexactInObject,\n inexactStartLoc,\n );\n }\n }\n\n this.expect(endDelim);\n\n /* The inexact flag should only be added on ObjectTypeAnnotations that\n * are not the body of an interface, declare interface, or declare class.\n * Since spreads are only allowed in object types, checking that is\n * sufficient here.\n */\n if (allowSpread) {\n nodeStart.inexact = inexact;\n }\n\n const out = this.finishNode(nodeStart, \"ObjectTypeAnnotation\");\n\n this.state.inType = oldInType;\n\n return out;\n }\n\n flowParseObjectTypeProperty(\n node: Undone,\n isStatic: boolean,\n protoStartLoc: Position | undefined | null,\n variance: N.FlowVariance | undefined | null,\n kind: string,\n allowSpread: boolean,\n allowInexact: boolean,\n ): N.FlowObjectTypeProperty | N.FlowObjectTypeSpreadProperty | null {\n if (this.eat(tt.ellipsis)) {\n const isInexactToken =\n this.match(tt.comma) ||\n this.match(tt.semi) ||\n this.match(tt.braceR) ||\n this.match(tt.braceBarR);\n\n if (isInexactToken) {\n if (!allowSpread) {\n this.raise(\n FlowErrors.InexactInsideNonObject,\n this.state.lastTokStartLoc!,\n );\n } else if (!allowInexact) {\n this.raise(\n FlowErrors.InexactInsideExact,\n this.state.lastTokStartLoc!,\n );\n }\n if (variance) {\n this.raise(FlowErrors.InexactVariance, variance);\n }\n\n return null;\n }\n\n if (!allowSpread) {\n this.raise(\n FlowErrors.UnexpectedSpreadType,\n this.state.lastTokStartLoc!,\n );\n }\n if (protoStartLoc != null) {\n this.unexpected(protoStartLoc);\n }\n if (variance) {\n this.raise(FlowErrors.SpreadVariance, variance);\n }\n\n node.argument = this.flowParseType();\n return this.finishNode(node, \"ObjectTypeSpreadProperty\");\n } else {\n node.key = this.flowParseObjectPropertyKey();\n node.static = isStatic;\n node.proto = protoStartLoc != null;\n node.kind = kind;\n\n let optional = false;\n if (this.match(tt.lt) || this.match(tt.parenL)) {\n // This is a method property\n node.method = true;\n\n if (protoStartLoc != null) {\n this.unexpected(protoStartLoc);\n }\n if (variance) {\n this.unexpected(variance.loc.start);\n }\n\n node.value = this.flowParseObjectTypeMethodish(\n this.startNodeAt(node.loc.start),\n );\n if (kind === \"get\" || kind === \"set\") {\n this.flowCheckGetterSetterParams(node);\n }\n /** Declared classes/interfaces do not allow spread */\n if (\n !allowSpread &&\n node.key.name === \"constructor\" &&\n node.value.this\n ) {\n this.raise(\n FlowErrors.ThisParamBannedInConstructor,\n node.value.this,\n );\n }\n } else {\n if (kind !== \"init\") this.unexpected();\n\n node.method = false;\n\n if (this.eat(tt.question)) {\n optional = true;\n }\n node.value = this.flowParseTypeInitialiser();\n node.variance = variance;\n }\n\n node.optional = optional;\n\n return this.finishNode(node, \"ObjectTypeProperty\");\n }\n }\n\n // This is similar to checkGetterSetterParams, but as\n // @babel/parser uses non estree properties we cannot reuse it here\n flowCheckGetterSetterParams(\n property: Undone<\n N.FlowObjectTypeProperty | N.FlowObjectTypeSpreadProperty\n >,\n ): void {\n const paramCount = property.kind === \"get\" ? 0 : 1;\n const length =\n property.value.params.length + (property.value.rest ? 1 : 0);\n\n if (property.value.this) {\n this.raise(\n property.kind === \"get\"\n ? FlowErrors.GetterMayNotHaveThisParam\n : FlowErrors.SetterMayNotHaveThisParam,\n property.value.this,\n );\n }\n\n if (length !== paramCount) {\n this.raise(\n property.kind === \"get\"\n ? Errors.BadGetterArity\n : Errors.BadSetterArity,\n property,\n );\n }\n\n if (property.kind === \"set\" && property.value.rest) {\n this.raise(Errors.BadSetterRestParameter, property);\n }\n }\n\n flowObjectTypeSemicolon(): void {\n if (\n !this.eat(tt.semi) &&\n !this.eat(tt.comma) &&\n !this.match(tt.braceR) &&\n !this.match(tt.braceBarR)\n ) {\n this.unexpected();\n }\n }\n\n flowParseQualifiedTypeIdentifier(\n startLoc?: Position,\n id?: N.Identifier,\n ): N.FlowQualifiedTypeIdentifier | N.Identifier {\n startLoc ??= this.state.startLoc;\n let node: N.Identifier | N.FlowQualifiedTypeIdentifier =\n id || this.flowParseRestrictedIdentifier(true);\n\n while (this.eat(tt.dot)) {\n const node2 = this.startNodeAt(startLoc);\n node2.qualification = node;\n node2.id = this.flowParseRestrictedIdentifier(true);\n node = this.finishNode(node2, \"QualifiedTypeIdentifier\");\n }\n\n return node;\n }\n\n flowParseGenericType(\n startLoc: Position,\n id: N.Identifier,\n ): N.FlowGenericTypeAnnotation {\n const node = this.startNodeAt(startLoc);\n\n node.typeParameters = null;\n node.id = this.flowParseQualifiedTypeIdentifier(startLoc, id);\n\n if (this.match(tt.lt)) {\n node.typeParameters = this.flowParseTypeParameterInstantiation();\n }\n\n return this.finishNode(node, \"GenericTypeAnnotation\");\n }\n\n flowParseTypeofType(): N.FlowTypeofTypeAnnotation {\n const node = this.startNode();\n this.expect(tt._typeof);\n node.argument = this.flowParsePrimaryType();\n return this.finishNode(node, \"TypeofTypeAnnotation\");\n }\n\n flowParseTupleType(): N.FlowTupleTypeAnnotation {\n const node = this.startNode();\n node.types = [];\n this.expect(tt.bracketL);\n // We allow trailing commas\n while (this.state.pos < this.length && !this.match(tt.bracketR)) {\n node.types.push(this.flowParseType());\n if (this.match(tt.bracketR)) break;\n this.expect(tt.comma);\n }\n this.expect(tt.bracketR);\n return this.finishNode(node, \"TupleTypeAnnotation\");\n }\n\n flowParseFunctionTypeParam(first: boolean): N.FlowFunctionTypeParam {\n let name = null;\n let optional = false;\n let typeAnnotation = null;\n const node = this.startNode();\n const lh = this.lookahead();\n const isThis = this.state.type === tt._this;\n\n if (lh.type === tt.colon || lh.type === tt.question) {\n if (isThis && !first) {\n this.raise(FlowErrors.ThisParamMustBeFirst, node);\n }\n name = this.parseIdentifier(isThis);\n if (this.eat(tt.question)) {\n optional = true;\n if (isThis) {\n this.raise(FlowErrors.ThisParamMayNotBeOptional, node);\n }\n }\n typeAnnotation = this.flowParseTypeInitialiser();\n } else {\n typeAnnotation = this.flowParseType();\n }\n node.name = name;\n node.optional = optional;\n node.typeAnnotation = typeAnnotation;\n return this.finishNode(node, \"FunctionTypeParam\");\n }\n\n reinterpretTypeAsFunctionTypeParam(\n type: N.FlowType,\n ): N.FlowFunctionTypeParam {\n const node = this.startNodeAt(type.loc.start);\n node.name = null;\n node.optional = false;\n node.typeAnnotation = type;\n return this.finishNode(node, \"FunctionTypeParam\");\n }\n\n flowParseFunctionTypeParams(params: N.FlowFunctionTypeParam[] = []): {\n params: N.FlowFunctionTypeParam[];\n rest: N.FlowFunctionTypeParam | undefined | null;\n _this: N.FlowFunctionTypeParam | undefined | null;\n } {\n let rest: N.FlowFunctionTypeParam | undefined | null = null;\n let _this: N.FlowFunctionTypeParam | undefined | null = null;\n if (this.match(tt._this)) {\n _this = this.flowParseFunctionTypeParam(/* first */ true);\n // match Flow parser behavior\n _this.name = null;\n if (!this.match(tt.parenR)) {\n this.expect(tt.comma);\n }\n }\n while (!this.match(tt.parenR) && !this.match(tt.ellipsis)) {\n params.push(this.flowParseFunctionTypeParam(false));\n if (!this.match(tt.parenR)) {\n this.expect(tt.comma);\n }\n }\n if (this.eat(tt.ellipsis)) {\n rest = this.flowParseFunctionTypeParam(false);\n }\n return { params, rest, _this };\n }\n\n flowIdentToTypeAnnotation(\n startLoc: Position,\n node: Undone,\n id: N.Identifier,\n ): N.FlowType {\n switch (id.name) {\n case \"any\":\n return this.finishNode(node, \"AnyTypeAnnotation\");\n\n case \"bool\":\n case \"boolean\":\n return this.finishNode(node, \"BooleanTypeAnnotation\");\n\n case \"mixed\":\n return this.finishNode(node, \"MixedTypeAnnotation\");\n\n case \"empty\":\n return this.finishNode(node, \"EmptyTypeAnnotation\");\n\n case \"number\":\n return this.finishNode(node, \"NumberTypeAnnotation\");\n\n case \"string\":\n return this.finishNode(node, \"StringTypeAnnotation\");\n\n case \"symbol\":\n return this.finishNode(node, \"SymbolTypeAnnotation\");\n\n default:\n this.checkNotUnderscore(id.name);\n return this.flowParseGenericType(startLoc, id);\n }\n }\n\n // The parsing of types roughly parallels the parsing of expressions, and\n // primary types are kind of like primary expressions...they're the\n // primitives with which other types are constructed.\n flowParsePrimaryType(): N.FlowType {\n const startLoc = this.state.startLoc;\n const node = this.startNode();\n let tmp;\n let type;\n let isGroupedType = false;\n const oldNoAnonFunctionType = this.state.noAnonFunctionType;\n\n switch (this.state.type) {\n case tt.braceL:\n return this.flowParseObjectType({\n allowStatic: false,\n allowExact: false,\n allowSpread: true,\n allowProto: false,\n allowInexact: true,\n });\n\n case tt.braceBarL:\n return this.flowParseObjectType({\n allowStatic: false,\n allowExact: true,\n allowSpread: true,\n allowProto: false,\n allowInexact: false,\n });\n\n case tt.bracketL:\n this.state.noAnonFunctionType = false;\n type = this.flowParseTupleType();\n this.state.noAnonFunctionType = oldNoAnonFunctionType;\n return type;\n\n case tt.lt: {\n const node = this.startNode();\n node.typeParameters = this.flowParseTypeParameterDeclaration();\n this.expect(tt.parenL);\n tmp = this.flowParseFunctionTypeParams();\n node.params = tmp.params;\n node.rest = tmp.rest;\n node.this = tmp._this;\n this.expect(tt.parenR);\n\n this.expect(tt.arrow);\n\n node.returnType = this.flowParseType();\n\n return this.finishNode(node, \"FunctionTypeAnnotation\");\n }\n\n case tt.parenL: {\n const node = this.startNode();\n this.next();\n\n // Check to see if this is actually a grouped type\n if (!this.match(tt.parenR) && !this.match(tt.ellipsis)) {\n if (tokenIsIdentifier(this.state.type) || this.match(tt._this)) {\n const token = this.lookahead().type;\n isGroupedType = token !== tt.question && token !== tt.colon;\n } else {\n isGroupedType = true;\n }\n }\n\n if (isGroupedType) {\n this.state.noAnonFunctionType = false;\n type = this.flowParseType();\n this.state.noAnonFunctionType = oldNoAnonFunctionType;\n\n // A `,` or a `) =>` means this is an anonymous function type\n if (\n this.state.noAnonFunctionType ||\n !(\n this.match(tt.comma) ||\n (this.match(tt.parenR) && this.lookahead().type === tt.arrow)\n )\n ) {\n this.expect(tt.parenR);\n return type;\n } else {\n // Eat a comma if there is one\n this.eat(tt.comma);\n }\n }\n\n if (type) {\n tmp = this.flowParseFunctionTypeParams([\n this.reinterpretTypeAsFunctionTypeParam(type),\n ]);\n } else {\n tmp = this.flowParseFunctionTypeParams();\n }\n\n node.params = tmp.params;\n node.rest = tmp.rest;\n node.this = tmp._this;\n\n this.expect(tt.parenR);\n\n this.expect(tt.arrow);\n\n node.returnType = this.flowParseType();\n\n node.typeParameters = null;\n\n return this.finishNode(node, \"FunctionTypeAnnotation\");\n }\n\n case tt.string:\n return this.parseLiteral(\n this.state.value,\n \"StringLiteralTypeAnnotation\",\n );\n\n case tt._true:\n case tt._false:\n node.value = this.match(tt._true);\n this.next();\n return this.finishNode(\n node as Undone,\n \"BooleanLiteralTypeAnnotation\",\n );\n\n case tt.plusMin:\n if (this.state.value === \"-\") {\n this.next();\n if (this.match(tt.num)) {\n return this.parseLiteralAtNode(\n -this.state.value,\n \"NumberLiteralTypeAnnotation\",\n node,\n );\n }\n\n if (this.match(tt.bigint)) {\n return this.parseLiteralAtNode(\n -this.state.value,\n \"BigIntLiteralTypeAnnotation\",\n node,\n );\n }\n\n throw this.raise(\n FlowErrors.UnexpectedSubtractionOperand,\n this.state.startLoc,\n );\n }\n throw this.unexpected();\n case tt.num:\n return this.parseLiteral(\n this.state.value,\n \"NumberLiteralTypeAnnotation\",\n );\n\n case tt.bigint:\n return this.parseLiteral(\n this.state.value,\n \"BigIntLiteralTypeAnnotation\",\n );\n\n case tt._void:\n this.next();\n return this.finishNode(node, \"VoidTypeAnnotation\");\n\n case tt._null:\n this.next();\n return this.finishNode(node, \"NullLiteralTypeAnnotation\");\n\n case tt._this:\n this.next();\n return this.finishNode(node, \"ThisTypeAnnotation\");\n\n case tt.star:\n this.next();\n return this.finishNode(node, \"ExistsTypeAnnotation\");\n\n case tt._typeof:\n return this.flowParseTypeofType();\n\n default:\n if (tokenIsKeyword(this.state.type)) {\n const label = tokenLabelName(this.state.type);\n this.next();\n return super.createIdentifier(node as Undone, label);\n } else if (tokenIsIdentifier(this.state.type)) {\n if (this.isContextual(tt._interface)) {\n return this.flowParseInterfaceType();\n }\n\n return this.flowIdentToTypeAnnotation(\n startLoc,\n node,\n this.parseIdentifier(),\n );\n }\n }\n\n throw this.unexpected();\n }\n\n flowParsePostfixType(): N.FlowType {\n const startLoc = this.state.startLoc;\n let type = this.flowParsePrimaryType();\n let seenOptionalIndexedAccess = false;\n while (\n (this.match(tt.bracketL) || this.match(tt.questionDot)) &&\n !this.canInsertSemicolon()\n ) {\n const node = this.startNodeAt(startLoc);\n const optional = this.eat(tt.questionDot);\n seenOptionalIndexedAccess = seenOptionalIndexedAccess || optional;\n this.expect(tt.bracketL);\n if (!optional && this.match(tt.bracketR)) {\n node.elementType = type;\n this.next(); // eat `]`\n type = this.finishNode(node, \"ArrayTypeAnnotation\");\n } else {\n node.objectType = type;\n node.indexType = this.flowParseType();\n this.expect(tt.bracketR);\n if (seenOptionalIndexedAccess) {\n node.optional = optional;\n type = this.finishNode(\n // @ts-expect-error todo(flow->ts)\n node,\n \"OptionalIndexedAccessType\",\n );\n } else {\n type = this.finishNode(\n // @ts-expect-error todo(flow->ts)\n node,\n \"IndexedAccessType\",\n );\n }\n }\n }\n return type;\n }\n\n flowParsePrefixType(): N.FlowType {\n const node = this.startNode();\n if (this.eat(tt.question)) {\n node.typeAnnotation = this.flowParsePrefixType();\n return this.finishNode(node, \"NullableTypeAnnotation\");\n } else {\n return this.flowParsePostfixType();\n }\n }\n\n flowParseAnonFunctionWithoutParens(): N.FlowType {\n const param = this.flowParsePrefixType();\n if (!this.state.noAnonFunctionType && this.eat(tt.arrow)) {\n // TODO: This should be a type error. Passing in a SourceLocation, and it expects a Position.\n const node = this.startNodeAt(\n param.loc.start,\n );\n node.params = [this.reinterpretTypeAsFunctionTypeParam(param)];\n node.rest = null;\n node.this = null;\n node.returnType = this.flowParseType();\n node.typeParameters = null;\n return this.finishNode(node, \"FunctionTypeAnnotation\");\n }\n return param;\n }\n\n flowParseIntersectionType(): N.FlowType {\n const node = this.startNode();\n this.eat(tt.bitwiseAND);\n const type = this.flowParseAnonFunctionWithoutParens();\n node.types = [type];\n while (this.eat(tt.bitwiseAND)) {\n node.types.push(this.flowParseAnonFunctionWithoutParens());\n }\n return node.types.length === 1\n ? type\n : this.finishNode(node, \"IntersectionTypeAnnotation\");\n }\n\n flowParseUnionType(): N.FlowType {\n const node = this.startNode();\n this.eat(tt.bitwiseOR);\n const type = this.flowParseIntersectionType();\n node.types = [type];\n while (this.eat(tt.bitwiseOR)) {\n node.types.push(this.flowParseIntersectionType());\n }\n return node.types.length === 1\n ? type\n : this.finishNode(node, \"UnionTypeAnnotation\");\n }\n\n flowParseType(): N.FlowType {\n const oldInType = this.state.inType;\n this.state.inType = true;\n const type = this.flowParseUnionType();\n this.state.inType = oldInType;\n return type;\n }\n\n flowParseTypeOrImplicitInstantiation(): N.FlowType {\n if (this.state.type === tt.name && this.state.value === \"_\") {\n const startLoc = this.state.startLoc;\n const node = this.parseIdentifier();\n return this.flowParseGenericType(startLoc, node);\n } else {\n return this.flowParseType();\n }\n }\n\n flowParseTypeAnnotation(): N.TypeAnnotation {\n const node = this.startNode();\n node.typeAnnotation = this.flowParseTypeInitialiser();\n return this.finishNode(node, \"TypeAnnotation\");\n }\n\n flowParseTypeAnnotatableIdentifier(\n allowPrimitiveOverride?: boolean,\n ): N.Identifier {\n const ident = allowPrimitiveOverride\n ? this.parseIdentifier()\n : this.flowParseRestrictedIdentifier();\n if (this.match(tt.colon)) {\n ident.typeAnnotation = this.flowParseTypeAnnotation();\n this.resetEndLocation(ident);\n }\n return ident;\n }\n\n typeCastToParameter(node: N.TypeCastExpression): N.Expression {\n (node.expression as N.Identifier).typeAnnotation = node.typeAnnotation;\n\n this.resetEndLocation(node.expression, node.typeAnnotation.loc.end);\n\n return node.expression;\n }\n\n flowParseVariance(): N.FlowVariance | undefined | null {\n let variance = null;\n if (this.match(tt.plusMin)) {\n variance = this.startNode();\n if (this.state.value === \"+\") {\n variance.kind = \"plus\";\n } else {\n variance.kind = \"minus\";\n }\n this.next();\n return this.finishNode(variance, \"Variance\");\n }\n return variance;\n }\n\n // ==================================\n // Overrides\n // ==================================\n\n parseFunctionBody(\n node: N.Function,\n allowExpressionBody?: boolean | null,\n isMethod: boolean = false,\n ): void {\n if (allowExpressionBody) {\n this.forwardNoArrowParamsConversionAt(node, () =>\n super.parseFunctionBody(node, true, isMethod),\n );\n return;\n }\n\n super.parseFunctionBody(node, false, isMethod);\n }\n\n parseFunctionBodyAndFinish<\n T extends\n | N.Function\n | N.TSDeclareMethod\n | N.TSDeclareFunction\n | N.ClassPrivateMethod,\n >(node: Undone, type: T[\"type\"], isMethod: boolean = false): T {\n if (this.match(tt.colon)) {\n const typeNode = this.startNode();\n\n [\n typeNode.typeAnnotation,\n // @ts-expect-error predicate may not exist\n node.predicate,\n ] = this.flowParseTypeAndPredicateInitialiser() as [\n N.FlowType,\n N.FlowPredicate,\n ];\n\n node.returnType = typeNode.typeAnnotation\n ? this.finishNode(typeNode, \"TypeAnnotation\")\n : null;\n }\n\n return super.parseFunctionBodyAndFinish(node, type, isMethod);\n }\n\n // interfaces and enums\n parseStatementLike(flags: ParseStatementFlag): N.Statement {\n // strict mode handling of `interface` since it's a reserved word\n if (this.state.strict && this.isContextual(tt._interface)) {\n const lookahead = this.lookahead();\n if (tokenIsKeywordOrIdentifier(lookahead.type)) {\n const node = this.startNode();\n this.next();\n return this.flowParseInterface(node);\n }\n } else if (this.isContextual(tt._enum)) {\n const node = this.startNode();\n this.next();\n return this.flowParseEnumDeclaration(node);\n }\n const stmt = super.parseStatementLike(flags);\n // We will parse a flow pragma in any comment before the first statement.\n if (this.flowPragma === undefined && !this.isValidDirective(stmt)) {\n this.flowPragma = null;\n }\n return stmt;\n }\n\n // declares, interfaces and type aliases\n parseExpressionStatement(\n node: N.ExpressionStatement,\n expr: N.Expression,\n decorators: N.Decorator[] | null,\n ): N.ExpressionStatement {\n if (expr.type === \"Identifier\") {\n if (expr.name === \"declare\") {\n if (\n this.match(tt._class) ||\n tokenIsIdentifier(this.state.type) ||\n this.match(tt._function) ||\n this.match(tt._var) ||\n this.match(tt._export)\n ) {\n // @ts-expect-error: refine typings\n return this.flowParseDeclare(node);\n }\n } else if (tokenIsIdentifier(this.state.type)) {\n if (expr.name === \"interface\") {\n // @ts-expect-error: refine typings\n return this.flowParseInterface(node);\n } else if (expr.name === \"type\") {\n // @ts-expect-error: refine typings\n return this.flowParseTypeAlias(node);\n } else if (expr.name === \"opaque\") {\n // @ts-expect-error: refine typings\n return this.flowParseOpaqueType(node, false);\n }\n }\n }\n\n return super.parseExpressionStatement(node, expr, decorators);\n }\n\n // export type\n shouldParseExportDeclaration(): boolean {\n const { type } = this.state;\n if (type === tt._enum || tokenIsFlowInterfaceOrTypeOrOpaque(type)) {\n return !this.state.containsEsc;\n }\n return super.shouldParseExportDeclaration();\n }\n\n isExportDefaultSpecifier(): boolean {\n const { type } = this.state;\n if (type === tt._enum || tokenIsFlowInterfaceOrTypeOrOpaque(type)) {\n return this.state.containsEsc;\n }\n\n return super.isExportDefaultSpecifier();\n }\n\n parseExportDefaultExpression() {\n if (this.isContextual(tt._enum)) {\n const node = this.startNode();\n this.next();\n return this.flowParseEnumDeclaration(node);\n }\n return super.parseExportDefaultExpression();\n }\n\n parseConditional(\n expr: N.Expression,\n\n startLoc: Position,\n refExpressionErrors?: ExpressionErrors | null,\n ): N.Expression {\n if (!this.match(tt.question)) return expr;\n\n if (this.state.maybeInArrowParameters) {\n const nextCh = this.lookaheadCharCode();\n // These tokens cannot start an expression, so if one of them follows\n // ? then we are probably in an arrow function parameters list and we\n // don't parse the conditional expression.\n if (\n nextCh === charCodes.comma || // (a?, b) => c\n nextCh === charCodes.equalsTo || // (a? = b) => c\n nextCh === charCodes.colon || // (a?: b) => c\n nextCh === charCodes.rightParenthesis // (a?) => c\n ) {\n /*:: invariant(refExpressionErrors != null) */\n this.setOptionalParametersError(refExpressionErrors!);\n return expr;\n }\n }\n\n this.expect(tt.question);\n const state = this.state.clone();\n const originalNoArrowAt = this.state.noArrowAt;\n const node = this.startNodeAt(startLoc);\n let { consequent, failed } = this.tryParseConditionalConsequent();\n let [valid, invalid] = this.getArrowLikeExpressions(consequent);\n\n if (failed || invalid.length > 0) {\n const noArrowAt = [...originalNoArrowAt];\n\n if (invalid.length > 0) {\n this.state = state;\n this.state.noArrowAt = noArrowAt;\n\n for (let i = 0; i < invalid.length; i++) {\n noArrowAt.push(invalid[i].start);\n }\n\n ({ consequent, failed } = this.tryParseConditionalConsequent());\n [valid, invalid] = this.getArrowLikeExpressions(consequent);\n }\n\n if (failed && valid.length > 1) {\n // if there are two or more possible correct ways of parsing, throw an\n // error.\n // e.g. Source: a ? (b): c => (d): e => f\n // Result 1: a ? b : (c => ((d): e => f))\n // Result 2: a ? ((b): c => d) : (e => f)\n this.raise(FlowErrors.AmbiguousConditionalArrow, state.startLoc);\n }\n\n if (failed && valid.length === 1) {\n this.state = state;\n noArrowAt.push(valid[0].start);\n this.state.noArrowAt = noArrowAt;\n ({ consequent, failed } = this.tryParseConditionalConsequent());\n }\n }\n\n this.getArrowLikeExpressions(consequent, true);\n\n this.state.noArrowAt = originalNoArrowAt;\n this.expect(tt.colon);\n\n node.test = expr;\n node.consequent = consequent;\n node.alternate = this.forwardNoArrowParamsConversionAt(node, () =>\n this.parseMaybeAssign(undefined, undefined),\n );\n\n return this.finishNode(node, \"ConditionalExpression\");\n }\n\n tryParseConditionalConsequent(): {\n consequent: N.Expression;\n failed: boolean;\n } {\n this.state.noArrowParamsConversionAt.push(this.state.start);\n\n const consequent = this.parseMaybeAssignAllowIn();\n const failed = !this.match(tt.colon);\n\n this.state.noArrowParamsConversionAt.pop();\n\n return { consequent, failed };\n }\n\n // Given an expression, walks through out its arrow functions whose body is\n // an expression and through out conditional expressions. It returns every\n // function which has been parsed with a return type but could have been\n // parenthesized expressions.\n // These functions are separated into two arrays: one containing the ones\n // whose parameters can be converted to assignable lists, one containing the\n // others.\n getArrowLikeExpressions(\n node: N.Expression,\n disallowInvalid?: boolean,\n ): [N.ArrowFunctionExpression[], N.ArrowFunctionExpression[]] {\n const stack = [node];\n const arrows: N.ArrowFunctionExpression[] = [];\n\n while (stack.length !== 0) {\n const node = stack.pop()!;\n if (\n node.type === \"ArrowFunctionExpression\" &&\n node.body.type !== \"BlockStatement\"\n ) {\n if (node.typeParameters || !node.returnType) {\n // This is an arrow expression without ambiguity, so check its parameters\n this.finishArrowValidation(node);\n } else {\n arrows.push(node);\n }\n stack.push(node.body);\n } else if (node.type === \"ConditionalExpression\") {\n stack.push(node.consequent);\n stack.push(node.alternate);\n }\n }\n\n if (disallowInvalid) {\n arrows.forEach(node => this.finishArrowValidation(node));\n return [arrows, []];\n }\n\n return partition(arrows, node =>\n node.params.every(param => this.isAssignable(param, true)),\n );\n }\n\n finishArrowValidation(node: N.ArrowFunctionExpression) {\n this.toAssignableList(\n // node.params is Expression[] instead of $ReadOnlyArray because it\n // has not been converted yet.\n node.params as any as N.Expression[],\n node.extra?.trailingCommaLoc,\n /* isLHS */ false,\n );\n // Enter scope, as checkParams defines bindings\n this.scope.enter(ScopeFlag.FUNCTION | ScopeFlag.ARROW);\n // Use super's method to force the parameters to be checked\n super.checkParams(node, false, true);\n this.scope.exit();\n }\n\n forwardNoArrowParamsConversionAt(\n node: Undone,\n parse: () => T,\n ): T {\n let result: T;\n if (\n this.state.noArrowParamsConversionAt.includes(\n this.offsetToSourcePos(node.start),\n )\n ) {\n this.state.noArrowParamsConversionAt.push(this.state.start);\n result = parse();\n this.state.noArrowParamsConversionAt.pop();\n } else {\n result = parse();\n }\n\n return result;\n }\n\n parseParenItem(\n node: T,\n startLoc: Position,\n ): T | N.TypeCastExpression | N.TsTypeCastExpression {\n const newNode = super.parseParenItem(node, startLoc);\n if (this.eat(tt.question)) {\n (newNode as N.Identifier).optional = true;\n // Include questionmark in location of node\n // Don't use this.finishNode() as otherwise we might process comments twice and\n // include already consumed parens\n this.resetEndLocation(node);\n }\n\n if (this.match(tt.colon)) {\n const typeCastNode = this.startNodeAt(startLoc);\n typeCastNode.expression = newNode as N.Expression;\n typeCastNode.typeAnnotation = this.flowParseTypeAnnotation();\n\n return this.finishNode(typeCastNode, \"TypeCastExpression\");\n }\n\n return newNode;\n }\n\n assertModuleNodeAllowed(node: N.Node) {\n if (\n (node.type === \"ImportDeclaration\" &&\n (node.importKind === \"type\" || node.importKind === \"typeof\")) ||\n (node.type === \"ExportNamedDeclaration\" &&\n node.exportKind === \"type\") ||\n (node.type === \"ExportAllDeclaration\" && node.exportKind === \"type\")\n ) {\n // Allow Flowtype imports and exports in all conditions because\n // Flow itself does not care about 'sourceType'.\n return;\n }\n\n super.assertModuleNodeAllowed(node);\n }\n\n parseExportDeclaration(\n node: N.ExportNamedDeclaration,\n ): N.Declaration | undefined | null {\n if (this.isContextual(tt._type)) {\n node.exportKind = \"type\";\n\n const declarationNode = this.startNode();\n this.next();\n\n if (this.match(tt.braceL)) {\n // export type { foo, bar };\n node.specifiers = this.parseExportSpecifiers(\n /* isInTypeExport */ true,\n );\n super.parseExportFrom(node);\n return null;\n } else {\n // export type Foo = Bar;\n // @ts-expect-error: refine typings\n return this.flowParseTypeAlias(declarationNode);\n }\n } else if (this.isContextual(tt._opaque)) {\n node.exportKind = \"type\";\n\n const declarationNode = this.startNode();\n this.next();\n // export opaque type Foo = Bar;\n // @ts-expect-error: refine typings\n return this.flowParseOpaqueType(declarationNode, false);\n } else if (this.isContextual(tt._interface)) {\n node.exportKind = \"type\";\n const declarationNode = this.startNode();\n this.next();\n // @ts-expect-error: refine typings\n return this.flowParseInterface(declarationNode);\n } else if (this.isContextual(tt._enum)) {\n node.exportKind = \"value\";\n const declarationNode = this.startNode();\n this.next();\n // @ts-expect-error: refine typings\n return this.flowParseEnumDeclaration(declarationNode);\n } else {\n return super.parseExportDeclaration(node);\n }\n }\n\n eatExportStar(\n node: Undone,\n ): node is Undone {\n if (super.eatExportStar(node)) return true;\n\n if (this.isContextual(tt._type) && this.lookahead().type === tt.star) {\n (\n node as Undone\n ).exportKind = \"type\";\n this.next();\n this.next();\n return true;\n }\n\n return false;\n }\n\n maybeParseExportNamespaceSpecifier(\n node: Undone,\n ): node is Undone {\n const { startLoc } = this.state;\n const hasNamespace = super.maybeParseExportNamespaceSpecifier(node);\n if (hasNamespace && node.exportKind === \"type\") {\n this.unexpected(startLoc);\n }\n return hasNamespace;\n }\n\n parseClassId(\n node: N.Class,\n isStatement: boolean,\n optionalId?: boolean | null,\n ) {\n super.parseClassId(node, isStatement, optionalId);\n if (this.match(tt.lt)) {\n node.typeParameters = this.flowParseTypeParameterDeclaration();\n }\n }\n\n parseClassMember(\n classBody: N.ClassBody,\n member: any,\n state: N.ParseClassMemberState,\n ): void {\n const { startLoc } = this.state;\n if (this.isContextual(tt._declare)) {\n if (super.parseClassMemberFromModifier(classBody, member)) {\n // 'declare' is a class element name\n return;\n }\n\n member.declare = true;\n }\n\n super.parseClassMember(classBody, member, state);\n\n if (member.declare) {\n if (\n member.type !== \"ClassProperty\" &&\n member.type !== \"ClassPrivateProperty\" &&\n member.type !== \"PropertyDefinition\" // Used by estree plugin\n ) {\n this.raise(FlowErrors.DeclareClassElement, startLoc);\n } else if (member.value) {\n this.raise(FlowErrors.DeclareClassFieldInitializer, member.value);\n }\n }\n }\n\n isIterator(word: string): boolean {\n return word === \"iterator\" || word === \"asyncIterator\";\n }\n\n readIterator(): void {\n const word = super.readWord1();\n const fullWord = \"@@\" + word;\n\n // Allow @@iterator and @@asyncIterator as a identifier only inside type\n if (!this.isIterator(word) || !this.state.inType) {\n this.raise(Errors.InvalidIdentifier, this.state.curPosition(), {\n identifierName: fullWord,\n });\n }\n\n this.finishToken(tt.name, fullWord);\n }\n\n // ensure that inside flow types, we bypass the jsx parser plugin\n getTokenFromCode(code: number): void {\n const next = this.input.charCodeAt(this.state.pos + 1);\n if (code === charCodes.leftCurlyBrace && next === charCodes.verticalBar) {\n this.finishOp(tt.braceBarL, 2);\n } else if (\n this.state.inType &&\n (code === charCodes.greaterThan || code === charCodes.lessThan)\n ) {\n this.finishOp(code === charCodes.greaterThan ? tt.gt : tt.lt, 1);\n } else if (this.state.inType && code === charCodes.questionMark) {\n if (next === charCodes.dot) {\n this.finishOp(tt.questionDot, 2);\n } else {\n // allow double nullable types in Flow: ??string\n this.finishOp(tt.question, 1);\n }\n } else if (\n isIteratorStart(code, next, this.input.charCodeAt(this.state.pos + 2))\n ) {\n this.state.pos += 2; // eat \"@@\"\n this.readIterator();\n } else {\n super.getTokenFromCode(code);\n }\n }\n\n isAssignable(node: N.Node, isBinding?: boolean): boolean {\n if (node.type === \"TypeCastExpression\") {\n return this.isAssignable(node.expression, isBinding);\n } else {\n return super.isAssignable(node, isBinding);\n }\n }\n\n toAssignable(node: N.Node, isLHS: boolean = false): void {\n if (\n !isLHS &&\n node.type === \"AssignmentExpression\" &&\n node.left.type === \"TypeCastExpression\"\n ) {\n node.left = this.typeCastToParameter(node.left) as N.Assignable;\n }\n super.toAssignable(node, isLHS);\n }\n\n // turn type casts that we found in function parameter head into type annotated params\n toAssignableList(\n exprList: N.Expression[],\n trailingCommaLoc: Position | undefined | null,\n isLHS: boolean,\n ): void {\n for (let i = 0; i < exprList.length; i++) {\n const expr = exprList[i];\n if (expr?.type === \"TypeCastExpression\") {\n exprList[i] = this.typeCastToParameter(expr);\n }\n }\n super.toAssignableList(exprList, trailingCommaLoc, isLHS);\n }\n\n // this is a list of nodes, from something like a call expression, we need to filter the\n // type casts that we've found that are illegal in this context\n toReferencedList(\n exprList:\n | readonly (N.Expression | N.SpreadElement | null)[]\n | readonly (N.Expression | N.RestElement)[],\n isParenthesizedExpr?: boolean,\n ):\n | readonly (N.Expression | N.SpreadElement | null)[]\n | readonly (N.Expression | N.RestElement)[] {\n for (let i = 0; i < exprList.length; i++) {\n const expr = exprList[i];\n if (\n expr &&\n expr.type === \"TypeCastExpression\" &&\n !expr.extra?.parenthesized &&\n (exprList.length > 1 || !isParenthesizedExpr)\n ) {\n this.raise(FlowErrors.TypeCastInPattern, expr.typeAnnotation);\n }\n }\n\n return exprList;\n }\n\n parseArrayLike(\n close: TokenType,\n isTuple: boolean,\n refExpressionErrors?: ExpressionErrors | null,\n ): N.ArrayExpression | N.TupleExpression {\n const node = super.parseArrayLike(close, isTuple, refExpressionErrors);\n\n // This could be an array pattern:\n // ([a: string, b: string]) => {}\n // In this case, we don't have to call toReferencedList. We will\n // call it, if needed, when we are sure that it is a parenthesized\n // expression by calling toReferencedListDeep.\n if (refExpressionErrors != null && !this.state.maybeInArrowParameters) {\n this.toReferencedList(node.elements);\n }\n\n return node;\n }\n\n isValidLVal(\n type: string,\n disallowCallExpression: boolean,\n isParenthesized: boolean,\n binding: BindingFlag,\n ) {\n return (\n type === \"TypeCastExpression\" ||\n super.isValidLVal(\n type,\n disallowCallExpression,\n isParenthesized,\n binding,\n )\n );\n }\n\n // parse class property type annotations\n parseClassProperty(node: N.ClassProperty): N.ClassProperty {\n if (this.match(tt.colon)) {\n node.typeAnnotation = this.flowParseTypeAnnotation();\n }\n return super.parseClassProperty(node);\n }\n\n parseClassPrivateProperty(\n node: N.ClassPrivateProperty,\n ): N.ClassPrivateProperty {\n if (this.match(tt.colon)) {\n node.typeAnnotation = this.flowParseTypeAnnotation();\n }\n return super.parseClassPrivateProperty(node);\n }\n\n // determine whether or not we're currently in the position where a class method would appear\n isClassMethod(): boolean {\n return this.match(tt.lt) || super.isClassMethod();\n }\n\n // determine whether or not we're currently in the position where a class property would appear\n isClassProperty(): boolean {\n return this.match(tt.colon) || super.isClassProperty();\n }\n\n isNonstaticConstructor(method: N.ClassMethod | N.ClassProperty): boolean {\n return !this.match(tt.colon) && super.isNonstaticConstructor(method);\n }\n\n // parse type parameters for class methods\n pushClassMethod(\n classBody: N.ClassBody,\n method: N.ClassMethod,\n isGenerator: boolean,\n isAsync: boolean,\n isConstructor: boolean,\n allowsDirectSuper: boolean,\n ): void {\n if ((method as any).variance) {\n this.unexpected((method as any).variance.loc.start);\n }\n delete (method as any).variance;\n if (this.match(tt.lt)) {\n method.typeParameters = this.flowParseTypeParameterDeclaration();\n }\n\n super.pushClassMethod(\n classBody,\n method,\n isGenerator,\n isAsync,\n isConstructor,\n allowsDirectSuper,\n );\n\n if (method.params && isConstructor) {\n const params = method.params;\n if (params.length > 0 && this.isThisParam(params[0])) {\n this.raise(FlowErrors.ThisParamBannedInConstructor, method);\n }\n // estree support\n } else if (\n // @ts-expect-error TS does not know about the fact that estree can replace ClassMethod with MethodDefinition\n method.type === \"MethodDefinition\" &&\n isConstructor &&\n // @ts-expect-error estree\n method.value.params\n ) {\n // @ts-expect-error estree\n const params = method.value.params;\n if (params.length > 0 && this.isThisParam(params[0])) {\n this.raise(FlowErrors.ThisParamBannedInConstructor, method);\n }\n }\n }\n\n pushClassPrivateMethod(\n classBody: N.ClassBody,\n method: N.ClassPrivateMethod,\n isGenerator: boolean,\n isAsync: boolean,\n ): void {\n if ((method as any).variance) {\n this.unexpected((method as any).variance.loc.start);\n }\n delete (method as any).variance;\n if (this.match(tt.lt)) {\n method.typeParameters = this.flowParseTypeParameterDeclaration();\n }\n\n super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);\n }\n\n // parse a the super class type parameters and implements\n parseClassSuper(node: N.Class): void {\n super.parseClassSuper(node);\n if (\n node.superClass &&\n (this.match(tt.lt) ||\n // handles `class extends C<`\n this.match(tt.bitShiftL))\n ) {\n if (process.env.BABEL_8_BREAKING) {\n node.superTypeArguments =\n this.flowParseTypeParameterInstantiationInExpression();\n } else {\n node.superTypeParameters =\n this.flowParseTypeParameterInstantiationInExpression();\n }\n }\n if (this.isContextual(tt._implements)) {\n this.next();\n const implemented: N.FlowClassImplements[] = (node.implements = []);\n do {\n const node = this.startNode();\n node.id = this.flowParseRestrictedIdentifier(/*liberal*/ true);\n if (this.match(tt.lt)) {\n node.typeParameters = this.flowParseTypeParameterInstantiation();\n } else {\n node.typeParameters = null;\n }\n implemented.push(this.finishNode(node, \"ClassImplements\"));\n } while (this.eat(tt.comma));\n }\n }\n\n checkGetterSetterParams(method: N.ObjectMethod | N.ClassMethod): void {\n super.checkGetterSetterParams(method);\n const params = this.getObjectOrClassMethodParams(method);\n if (params.length > 0) {\n const param = params[0];\n if (this.isThisParam(param) && method.kind === \"get\") {\n this.raise(FlowErrors.GetterMayNotHaveThisParam, param);\n } else if (this.isThisParam(param)) {\n this.raise(FlowErrors.SetterMayNotHaveThisParam, param);\n }\n }\n }\n\n parsePropertyNamePrefixOperator(\n node: N.ObjectOrClassMember | N.ClassMember,\n ): void {\n node.variance = this.flowParseVariance();\n }\n\n // parse type parameters for object method shorthand\n parseObjPropValue(\n prop: Undone,\n startLoc: Position | undefined | null,\n isGenerator: boolean,\n isAsync: boolean,\n isPattern: boolean,\n isAccessor: boolean,\n refExpressionErrors?: ExpressionErrors | null,\n ): T {\n if ((prop as any).variance) {\n this.unexpected((prop as any).variance.loc.start);\n }\n delete (prop as any).variance;\n\n let typeParameters;\n\n // method shorthand\n if (this.match(tt.lt) && !isAccessor) {\n typeParameters = this.flowParseTypeParameterDeclaration();\n if (!this.match(tt.parenL)) this.unexpected();\n }\n\n const result = super.parseObjPropValue(\n prop,\n startLoc,\n isGenerator,\n isAsync,\n isPattern,\n isAccessor,\n refExpressionErrors,\n );\n\n // add typeParameters if we found them\n if (typeParameters) {\n // @ts-expect-error: refine typings\n (result.value || result).typeParameters = typeParameters;\n }\n return result;\n }\n\n parseFunctionParamType(param: N.Pattern): N.Pattern {\n if (this.eat(tt.question)) {\n if (param.type !== \"Identifier\") {\n this.raise(FlowErrors.PatternIsOptional, param);\n }\n if (this.isThisParam(param)) {\n this.raise(FlowErrors.ThisParamMayNotBeOptional, param);\n }\n\n (param as any as N.Identifier).optional = true;\n }\n if (this.match(tt.colon)) {\n param.typeAnnotation = this.flowParseTypeAnnotation();\n } else if (this.isThisParam(param)) {\n this.raise(FlowErrors.ThisParamAnnotationRequired, param);\n }\n\n if (this.match(tt.eq) && this.isThisParam(param)) {\n this.raise(FlowErrors.ThisParamNoDefault, param);\n }\n\n this.resetEndLocation(param);\n return param;\n }\n\n parseMaybeDefault

(\n startLoc?: Position | null,\n left?: P | null,\n ): P | N.AssignmentPattern {\n const node = super.parseMaybeDefault(startLoc, left);\n\n if (\n node.type === \"AssignmentPattern\" &&\n node.typeAnnotation &&\n node.right.start < node.typeAnnotation.start\n ) {\n this.raise(FlowErrors.TypeBeforeInitializer, node.typeAnnotation);\n }\n\n return node;\n }\n\n checkImportReflection(node: Undone) {\n super.checkImportReflection(node);\n if (node.module && node.importKind !== \"value\") {\n this.raise(\n FlowErrors.ImportReflectionHasImportType,\n node.specifiers[0].loc.start,\n );\n }\n }\n\n parseImportSpecifierLocal<\n T extends\n | N.ImportSpecifier\n | N.ImportDefaultSpecifier\n | N.ImportNamespaceSpecifier,\n >(node: N.ImportDeclaration, specifier: Undone, type: T[\"type\"]): void {\n specifier.local = hasTypeImportKind(node)\n ? this.flowParseRestrictedIdentifier(\n /* liberal */ true,\n /* declaration */ true,\n )\n : this.parseIdentifier();\n\n node.specifiers.push(this.finishImportSpecifier(specifier, type));\n }\n\n isPotentialImportPhase(isExport: boolean): boolean {\n if (super.isPotentialImportPhase(isExport)) return true;\n if (this.isContextual(tt._type)) {\n if (!isExport) return true;\n const ch = this.lookaheadCharCode();\n return ch === charCodes.leftCurlyBrace || ch === charCodes.asterisk;\n }\n return !isExport && this.isContextual(tt._typeof);\n }\n\n applyImportPhase(\n node: Undone,\n isExport: boolean,\n phase: string | null,\n loc?: Position,\n ): void {\n super.applyImportPhase(node, isExport, phase, loc);\n if (isExport) {\n if (!phase && this.match(tt._default)) {\n // TODO: Align with our TS AST and always add .exportKind\n return;\n }\n (node as N.ExportNamedDeclaration).exportKind =\n phase === \"type\" ? phase : \"value\";\n } else {\n if (phase === \"type\" && this.match(tt.star)) this.unexpected();\n (node as N.ImportDeclaration).importKind =\n phase === \"type\" || phase === \"typeof\" ? phase : \"value\";\n }\n }\n\n // parse import-type/typeof shorthand\n parseImportSpecifier(\n specifier: any,\n importedIsString: boolean,\n isInTypeOnlyImport: boolean,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n isMaybeTypeOnly: boolean,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n bindingType: BindingFlag | undefined,\n ): N.ImportSpecifier {\n const firstIdent = specifier.imported;\n\n let specifierTypeKind = null;\n if (firstIdent.type === \"Identifier\") {\n if (firstIdent.name === \"type\") {\n specifierTypeKind = \"type\";\n } else if (firstIdent.name === \"typeof\") {\n specifierTypeKind = \"typeof\";\n }\n }\n\n let isBinding = false;\n if (this.isContextual(tt._as) && !this.isLookaheadContextual(\"as\")) {\n const as_ident = this.parseIdentifier(true);\n if (\n specifierTypeKind !== null &&\n !tokenIsKeywordOrIdentifier(this.state.type)\n ) {\n // `import {type as ,` or `import {type as }`\n specifier.imported = as_ident;\n specifier.importKind = specifierTypeKind;\n specifier.local = this.cloneIdentifier(as_ident);\n } else {\n // `import {type as foo`\n specifier.imported = firstIdent;\n specifier.importKind = null;\n specifier.local = this.parseIdentifier();\n }\n } else {\n if (\n specifierTypeKind !== null &&\n tokenIsKeywordOrIdentifier(this.state.type)\n ) {\n // `import {type foo`\n specifier.imported = this.parseIdentifier(true);\n specifier.importKind = specifierTypeKind;\n } else {\n if (importedIsString) {\n /*:: invariant(firstIdent instanceof N.StringLiteral) */\n throw this.raise(Errors.ImportBindingIsString, specifier, {\n importName: firstIdent.value,\n });\n }\n /*:: invariant(firstIdent instanceof N.Node) */\n specifier.imported = firstIdent;\n specifier.importKind = null;\n }\n\n if (this.eatContextual(tt._as)) {\n specifier.local = this.parseIdentifier();\n } else {\n isBinding = true;\n specifier.local = this.cloneIdentifier(specifier.imported);\n }\n }\n\n const specifierIsTypeImport = hasTypeImportKind(specifier);\n\n if (isInTypeOnlyImport && specifierIsTypeImport) {\n this.raise(FlowErrors.ImportTypeShorthandOnlyInPureImport, specifier);\n }\n\n if (isInTypeOnlyImport || specifierIsTypeImport) {\n this.checkReservedType(\n specifier.local.name,\n specifier.local.loc.start,\n /* declaration */ true,\n );\n }\n\n if (isBinding && !isInTypeOnlyImport && !specifierIsTypeImport) {\n this.checkReservedWord(\n specifier.local.name,\n specifier.loc.start,\n true,\n true,\n );\n }\n\n return this.finishImportSpecifier(specifier, \"ImportSpecifier\");\n }\n\n parseBindingAtom(): N.Pattern {\n switch (this.state.type) {\n case tt._this:\n // \"this\" may be the name of a parameter, so allow it.\n return this.parseIdentifier(/* liberal */ true);\n default:\n return super.parseBindingAtom();\n }\n }\n\n // parse function type parameters - function foo() {}\n parseFunctionParams(\n node: Undone,\n isConstructor: boolean,\n ): void {\n // @ts-expect-error kind may not index node\n const kind = node.kind;\n if (kind !== \"get\" && kind !== \"set\" && this.match(tt.lt)) {\n node.typeParameters = this.flowParseTypeParameterDeclaration();\n }\n super.parseFunctionParams(node, isConstructor);\n }\n\n // parse flow type annotations on variable declarator heads - let foo: string = bar\n parseVarId(\n decl: N.VariableDeclarator,\n kind: \"var\" | \"let\" | \"const\" | \"using\" | \"await using\",\n ): void {\n super.parseVarId(decl, kind);\n if (this.match(tt.colon)) {\n decl.id.typeAnnotation = this.flowParseTypeAnnotation();\n this.resetEndLocation(decl.id); // set end position to end of type\n }\n }\n\n // parse the return type of an async arrow function - let foo = (async (): number => {});\n parseAsyncArrowFromCallExpression(\n node: N.ArrowFunctionExpression,\n call: N.CallExpression,\n ): N.ArrowFunctionExpression {\n if (this.match(tt.colon)) {\n const oldNoAnonFunctionType = this.state.noAnonFunctionType;\n this.state.noAnonFunctionType = true;\n node.returnType = this.flowParseTypeAnnotation();\n this.state.noAnonFunctionType = oldNoAnonFunctionType;\n }\n\n return super.parseAsyncArrowFromCallExpression(node, call);\n }\n\n // todo description\n shouldParseAsyncArrow(): boolean {\n return this.match(tt.colon) || super.shouldParseAsyncArrow();\n }\n\n // We need to support type parameter declarations for arrow functions. This\n // is tricky. There are three situations we need to handle\n //\n // 1. This is either JSX or an arrow function. We'll try JSX first. If that\n // fails, we'll try an arrow function. If that fails, we'll throw the JSX\n // error.\n // 2. This is an arrow function. We'll parse the type parameter declaration,\n // parse the rest, make sure the rest is an arrow function, and go from\n // there\n // 3. This is neither. Just call the super method\n parseMaybeAssign(\n refExpressionErrors?: ExpressionErrors | null,\n afterLeftParse?: Function,\n ): N.Expression {\n let state = null;\n\n let jsx;\n\n if (\n this.hasPlugin(\"jsx\") &&\n (this.match(tt.jsxTagStart) || this.match(tt.lt))\n ) {\n state = this.state.clone();\n\n jsx = this.tryParse(\n () => super.parseMaybeAssign(refExpressionErrors, afterLeftParse),\n state,\n );\n\n /*:: invariant(!jsx.aborted) */\n /*:: invariant(jsx.node != null) */\n if (!jsx.error) return jsx.node!;\n\n // Remove `tc.j_expr` and `tc.j_oTag` from context added\n // by parsing `jsxTagStart` to stop the JSX plugin from\n // messing with the tokens\n const { context } = this.state;\n const currentContext = context[context.length - 1];\n if (currentContext === tc.j_oTag || currentContext === tc.j_expr) {\n context.pop();\n }\n }\n\n if (jsx?.error || this.match(tt.lt)) {\n state = state || this.state.clone();\n\n let typeParameters: N.TypeParameterDeclaration;\n\n const arrow = this.tryParse((abort: () => never) => {\n typeParameters = this.flowParseTypeParameterDeclaration();\n\n const arrowExpression = this.forwardNoArrowParamsConversionAt(\n typeParameters,\n () => {\n const result = super.parseMaybeAssign(\n refExpressionErrors,\n afterLeftParse,\n );\n\n this.resetStartLocationFromNode(result, typeParameters);\n\n return result;\n },\n );\n\n // (() => {});\n // (() => {}: any);\n if (arrowExpression.extra?.parenthesized) abort();\n\n // The above can return a TypeCastExpression when the arrow\n // expression is not wrapped in parens. See also `this.parseParenItem`.\n // (() => {}: any);\n const expr = this.maybeUnwrapTypeCastExpression(arrowExpression);\n\n if (expr.type !== \"ArrowFunctionExpression\") abort();\n\n expr.typeParameters = typeParameters;\n this.resetStartLocationFromNode(expr, typeParameters);\n\n return arrowExpression;\n }, state);\n\n let arrowExpression:\n | N.ArrowFunctionExpression\n | N.TypeCastExpression\n | undefined\n | null = null;\n\n if (\n arrow.node &&\n this.maybeUnwrapTypeCastExpression(arrow.node).type ===\n \"ArrowFunctionExpression\"\n ) {\n if (!arrow.error && !arrow.aborted) {\n // async () => {}\n // @ts-expect-error: refine tryParse typings\n if (arrow.node.async) {\n /*:: invariant(typeParameters) */\n this.raise(\n FlowErrors.UnexpectedTypeParameterBeforeAsyncArrowFunction,\n typeParameters!,\n );\n }\n return arrow.node;\n }\n\n // @ts-expect-error: refine typings\n arrowExpression = arrow.node;\n }\n\n // If we are here, both JSX and Flow parsing attempts failed.\n // Give the precedence to the JSX error, except if JSX had an\n // unrecoverable error while Flow didn't.\n // If the error is recoverable, we can only re-report it if there is\n // a node we can return.\n\n if (jsx?.node) {\n /*:: invariant(jsx.failState) */\n this.state = jsx.failState;\n return jsx.node;\n }\n\n if (arrowExpression) {\n /*:: invariant(arrow.failState) */\n this.state = arrow.failState!;\n return arrowExpression;\n }\n\n if (jsx?.thrown) throw jsx.error;\n if (arrow.thrown) throw arrow.error;\n\n /*:: invariant(typeParameters) */\n throw this.raise(\n FlowErrors.UnexpectedTokenAfterTypeParameter,\n typeParameters!,\n );\n }\n\n return super.parseMaybeAssign(refExpressionErrors, afterLeftParse);\n }\n\n // handle return types for arrow functions\n parseArrow(\n node: Undone,\n ): Undone | undefined | null {\n if (this.match(tt.colon)) {\n // @ts-expect-error todo(flow->ts)\n const result = this.tryParse(() => {\n const oldNoAnonFunctionType = this.state.noAnonFunctionType;\n this.state.noAnonFunctionType = true;\n\n const typeNode = this.startNode();\n\n [\n typeNode.typeAnnotation,\n // @ts-expect-error (destructuring not supported yet)\n node.predicate,\n ] = this.flowParseTypeAndPredicateInitialiser() as [\n N.FlowType,\n N.FlowPredicate,\n ];\n\n this.state.noAnonFunctionType = oldNoAnonFunctionType;\n\n if (this.canInsertSemicolon()) this.unexpected();\n if (!this.match(tt.arrow)) this.unexpected();\n\n return typeNode;\n });\n\n if (result.thrown) return null;\n /*:: invariant(result.node) */\n\n if (result.error) this.state = result.failState;\n\n // assign after it is clear it is an arrow\n // @ts-expect-error todo(flow->ts)\n node.returnType = result.node.typeAnnotation\n ? this.finishNode(result.node!, \"TypeAnnotation\")\n : null;\n }\n\n return super.parseArrow(node);\n }\n\n shouldParseArrow(params: N.Node[]): boolean {\n return this.match(tt.colon) || super.shouldParseArrow(params);\n }\n\n setArrowFunctionParameters(\n node: Undone,\n params:\n | (N.Expression | N.SpreadElement)[]\n | (N.Expression | N.RestElement)[],\n ): void {\n if (\n this.state.noArrowParamsConversionAt.includes(\n this.offsetToSourcePos(node.start),\n )\n ) {\n node.params = params as N.ArrowFunctionExpression[\"params\"];\n } else {\n super.setArrowFunctionParameters(node, params);\n }\n }\n\n checkParams(\n node: N.Function,\n allowDuplicates: boolean,\n isArrowFunction?: boolean | null,\n strictModeChanged: boolean = true,\n ): void {\n if (\n isArrowFunction &&\n this.state.noArrowParamsConversionAt.includes(\n this.offsetToSourcePos(node.start),\n )\n ) {\n return;\n }\n\n // ensure the `this` param is first, if it exists\n for (let i = 0; i < node.params.length; i++) {\n if (this.isThisParam(node.params[i]) && i > 0) {\n this.raise(FlowErrors.ThisParamMustBeFirst, node.params[i]);\n }\n }\n\n super.checkParams(\n node,\n allowDuplicates,\n isArrowFunction,\n strictModeChanged,\n );\n }\n\n parseParenAndDistinguishExpression(canBeArrow: boolean): N.Expression {\n return super.parseParenAndDistinguishExpression(\n canBeArrow &&\n !this.state.noArrowAt.includes(\n this.sourceToOffsetPos(this.state.start),\n ),\n );\n }\n\n parseSubscripts(\n base: N.Expression,\n startLoc: Position,\n noCalls?: boolean | null,\n ): N.Expression {\n if (\n base.type === \"Identifier\" &&\n base.name === \"async\" &&\n this.state.noArrowAt.includes(startLoc.index)\n ) {\n this.next();\n\n const node = this.startNodeAt(startLoc);\n node.callee = base;\n node.arguments = super.parseCallExpressionArguments();\n base = this.finishNode(node, \"CallExpression\");\n } else if (\n base.type === \"Identifier\" &&\n base.name === \"async\" &&\n this.match(tt.lt)\n ) {\n const state = this.state.clone();\n const arrow = this.tryParse(\n abort => this.parseAsyncArrowWithTypeParameters(startLoc) || abort(),\n state,\n );\n\n /*:: invariant(arrow.node != null) */\n // @ts-expect-error: refine tryParse typings\n if (!arrow.error && !arrow.aborted) return arrow.node;\n\n const result = this.tryParse(\n () => super.parseSubscripts(base, startLoc, noCalls),\n state,\n );\n\n if (result.node && !result.error) return result.node;\n\n if (arrow.node) {\n this.state = arrow.failState;\n // @ts-expect-error: refine tryParse typings\n return arrow.node;\n }\n\n if (result.node) {\n this.state = result.failState!;\n return result.node;\n }\n\n throw arrow.error || result.error!;\n }\n\n return super.parseSubscripts(base, startLoc, noCalls);\n }\n\n parseSubscript(\n base: N.Expression,\n startLoc: Position,\n noCalls: boolean | undefined | null,\n subscriptState: N.ParseSubscriptState,\n ): N.Expression {\n if (this.match(tt.questionDot) && this.isLookaheadToken_lt()) {\n subscriptState.optionalChainMember = true;\n if (noCalls) {\n subscriptState.stop = true;\n return base;\n }\n this.next();\n const node = this.startNodeAt(startLoc);\n node.callee = base;\n node.typeArguments =\n this.flowParseTypeParameterInstantiationInExpression();\n this.expect(tt.parenL);\n node.arguments = this.parseCallExpressionArguments();\n node.optional = true;\n return this.finishCallExpression(node, /* optional */ true);\n } else if (\n !noCalls &&\n this.shouldParseTypes() &&\n (this.match(tt.lt) ||\n // also handles `new C<`\n this.match(tt.bitShiftL))\n ) {\n const node = this.startNodeAt<\n N.OptionalCallExpression | N.CallExpression\n >(startLoc);\n node.callee = base;\n\n const result = this.tryParse(() => {\n node.typeArguments =\n this.flowParseTypeParameterInstantiationCallOrNew();\n this.expect(tt.parenL);\n node.arguments = super.parseCallExpressionArguments();\n if (subscriptState.optionalChainMember) {\n (node as Undone).optional = false;\n }\n return this.finishCallExpression(\n node,\n subscriptState.optionalChainMember,\n );\n });\n\n if (result.node) {\n if (result.error) this.state = result.failState;\n return result.node;\n }\n }\n\n return super.parseSubscript(base, startLoc, noCalls, subscriptState);\n }\n\n parseNewCallee(node: N.NewExpression): void {\n super.parseNewCallee(node);\n\n let targs = null;\n if (this.shouldParseTypes() && this.match(tt.lt)) {\n targs = this.tryParse(() =>\n this.flowParseTypeParameterInstantiationCallOrNew(),\n ).node;\n }\n node.typeArguments = targs;\n }\n\n parseAsyncArrowWithTypeParameters(\n startLoc: Position,\n ): N.ArrowFunctionExpression | undefined | null {\n const node = this.startNodeAt(startLoc);\n this.parseFunctionParams(node, false);\n if (!this.parseArrow(node)) return;\n return super.parseArrowExpression(\n node,\n /* params */ undefined,\n /* isAsync */ true,\n );\n }\n\n readToken_mult_modulo(code: number): void {\n const next = this.input.charCodeAt(this.state.pos + 1);\n if (\n code === charCodes.asterisk &&\n next === charCodes.slash &&\n this.state.hasFlowComment\n ) {\n this.state.hasFlowComment = false;\n this.state.pos += 2;\n this.nextToken();\n return;\n }\n\n super.readToken_mult_modulo(code);\n }\n\n readToken_pipe_amp(code: number): void {\n const next = this.input.charCodeAt(this.state.pos + 1);\n if (\n code === charCodes.verticalBar &&\n next === charCodes.rightCurlyBrace\n ) {\n // '|}'\n this.finishOp(tt.braceBarR, 2);\n return;\n }\n\n super.readToken_pipe_amp(code);\n }\n\n parseTopLevel(file: N.File, program: N.Program): N.File {\n const fileNode = super.parseTopLevel(file, program);\n if (this.state.hasFlowComment) {\n this.raise(\n FlowErrors.UnterminatedFlowComment,\n this.state.curPosition(),\n );\n }\n return fileNode;\n }\n\n skipBlockComment(): N.CommentBlock | undefined {\n if (this.hasPlugin(\"flowComments\") && this.skipFlowComment()) {\n if (this.state.hasFlowComment) {\n throw this.raise(FlowErrors.NestedFlowComment, this.state.startLoc);\n }\n this.hasFlowCommentCompletion();\n const commentSkip = this.skipFlowComment();\n if (commentSkip) {\n this.state.pos += commentSkip;\n this.state.hasFlowComment = true;\n }\n return;\n }\n\n return super.skipBlockComment(this.state.hasFlowComment ? \"*-/\" : \"*/\");\n }\n\n skipFlowComment(): number | false {\n const { pos } = this.state;\n let shiftToFirstNonWhiteSpace = 2;\n while (\n [charCodes.space, charCodes.tab].includes(\n // @ts-expect-error testing whether a number is included\n this.input.charCodeAt(pos + shiftToFirstNonWhiteSpace),\n )\n ) {\n shiftToFirstNonWhiteSpace++;\n }\n\n const ch2 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos);\n const ch3 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos + 1);\n\n if (ch2 === charCodes.colon && ch3 === charCodes.colon) {\n return shiftToFirstNonWhiteSpace + 2; // check for /*::\n }\n if (\n this.input.slice(\n shiftToFirstNonWhiteSpace + pos,\n shiftToFirstNonWhiteSpace + pos + 12,\n ) === \"flow-include\"\n ) {\n return shiftToFirstNonWhiteSpace + 12; // check for /*flow-include\n }\n if (ch2 === charCodes.colon && ch3 !== charCodes.colon) {\n return shiftToFirstNonWhiteSpace; // check for /*:, advance up to :\n }\n return false;\n }\n\n hasFlowCommentCompletion(): void {\n const end = this.input.indexOf(\"*/\", this.state.pos);\n if (end === -1) {\n throw this.raise(Errors.UnterminatedComment, this.state.curPosition());\n }\n }\n\n // Flow enum parsing\n\n flowEnumErrorBooleanMemberNotInitialized(\n loc: Position,\n {\n enumName,\n memberName,\n }: {\n enumName: string;\n memberName: string;\n },\n ): void {\n this.raise(FlowErrors.EnumBooleanMemberNotInitialized, loc, {\n memberName,\n enumName,\n });\n }\n\n flowEnumErrorInvalidMemberInitializer(\n loc: Position,\n enumContext: EnumContext,\n ) {\n return this.raise(\n !enumContext.explicitType\n ? FlowErrors.EnumInvalidMemberInitializerUnknownType\n : enumContext.explicitType === \"symbol\"\n ? FlowErrors.EnumInvalidMemberInitializerSymbolType\n : FlowErrors.EnumInvalidMemberInitializerPrimaryType,\n loc,\n enumContext,\n );\n }\n\n flowEnumErrorNumberMemberNotInitialized(\n loc: Position,\n details: {\n enumName: string;\n memberName: string;\n },\n ): void {\n this.raise(FlowErrors.EnumNumberMemberNotInitialized, loc, details);\n }\n\n flowEnumErrorStringMemberInconsistentlyInitialized(\n node: N.Node,\n details: {\n enumName: string;\n },\n ): void {\n this.raise(\n FlowErrors.EnumStringMemberInconsistentlyInitialized,\n node,\n details,\n );\n }\n\n flowEnumMemberInit(): EnumMemberInit {\n const startLoc = this.state.startLoc;\n const endOfInit = () => this.match(tt.comma) || this.match(tt.braceR);\n switch (this.state.type) {\n case tt.num: {\n const literal = this.parseNumericLiteral(this.state.value);\n if (endOfInit()) {\n return { type: \"number\", loc: literal.loc.start, value: literal };\n }\n return { type: \"invalid\", loc: startLoc };\n }\n case tt.string: {\n const literal = this.parseStringLiteral(this.state.value);\n if (endOfInit()) {\n return { type: \"string\", loc: literal.loc.start, value: literal };\n }\n return { type: \"invalid\", loc: startLoc };\n }\n case tt._true:\n case tt._false: {\n const literal = this.parseBooleanLiteral(this.match(tt._true));\n if (endOfInit()) {\n return {\n type: \"boolean\",\n loc: literal.loc.start,\n value: literal,\n };\n }\n return { type: \"invalid\", loc: startLoc };\n }\n default:\n return { type: \"invalid\", loc: startLoc };\n }\n }\n\n flowEnumMemberRaw(): {\n id: N.Identifier;\n init: EnumMemberInit;\n } {\n const loc = this.state.startLoc;\n const id = this.parseIdentifier(true);\n const init = this.eat(tt.eq)\n ? this.flowEnumMemberInit()\n : { type: \"none\" as const, loc };\n return { id, init };\n }\n\n flowEnumCheckExplicitTypeMismatch(\n loc: Position,\n context: EnumContext,\n expectedType: EnumExplicitType,\n ): void {\n const { explicitType } = context;\n if (explicitType === null) {\n return;\n }\n if (explicitType !== expectedType) {\n this.flowEnumErrorInvalidMemberInitializer(loc, context);\n }\n }\n\n flowEnumMembers({\n enumName,\n explicitType,\n }: {\n enumName: string;\n explicitType: EnumExplicitType;\n }): {\n members: {\n booleanMembers: Extract<\n N.FlowEnumMember,\n { type: \"EnumBooleanMember\" }\n >[];\n numberMembers: Extract<\n N.FlowEnumMember,\n { type: \"EnumNumberMember\" }\n >[];\n stringMembers: Extract<\n N.FlowEnumMember,\n { type: \"EnumStringMember\" }\n >[];\n defaultedMembers: Extract<\n N.FlowEnumMember,\n { type: \"EnumDefaultedMember\" }\n >[];\n };\n hasUnknownMembers: boolean;\n } {\n const seenNames = new Set();\n const members = {\n booleanMembers: [],\n numberMembers: [],\n stringMembers: [],\n defaultedMembers: [],\n };\n let hasUnknownMembers = false;\n while (!this.match(tt.braceR)) {\n if (this.eat(tt.ellipsis)) {\n hasUnknownMembers = true;\n break;\n }\n const memberNode = this.startNode();\n const { id, init } = this.flowEnumMemberRaw();\n const memberName = id.name;\n if (memberName === \"\") {\n continue;\n }\n if (/^[a-z]/.test(memberName)) {\n this.raise(FlowErrors.EnumInvalidMemberName, id, {\n memberName,\n suggestion: memberName[0].toUpperCase() + memberName.slice(1),\n enumName,\n });\n }\n if (seenNames.has(memberName)) {\n this.raise(FlowErrors.EnumDuplicateMemberName, id, {\n memberName,\n enumName,\n });\n }\n seenNames.add(memberName);\n const context = { enumName, explicitType, memberName };\n memberNode.id = id;\n switch (init.type) {\n case \"boolean\": {\n this.flowEnumCheckExplicitTypeMismatch(\n init.loc,\n context,\n \"boolean\",\n );\n memberNode.init = init.value;\n members.booleanMembers.push(\n // @ts-expect-error NodeAny not supported\n this.finishNode(memberNode, \"EnumBooleanMember\"),\n );\n break;\n }\n case \"number\": {\n this.flowEnumCheckExplicitTypeMismatch(init.loc, context, \"number\");\n memberNode.init = init.value;\n members.numberMembers.push(\n // @ts-expect-error NodeAny not supported\n this.finishNode(memberNode, \"EnumNumberMember\"),\n );\n break;\n }\n case \"string\": {\n this.flowEnumCheckExplicitTypeMismatch(init.loc, context, \"string\");\n memberNode.init = init.value;\n members.stringMembers.push(\n // @ts-expect-error NodeAny not supported\n this.finishNode(memberNode, \"EnumStringMember\"),\n );\n break;\n }\n case \"invalid\": {\n throw this.flowEnumErrorInvalidMemberInitializer(init.loc, context);\n }\n case \"none\": {\n switch (explicitType) {\n case \"boolean\":\n this.flowEnumErrorBooleanMemberNotInitialized(\n init.loc,\n context,\n );\n break;\n case \"number\":\n this.flowEnumErrorNumberMemberNotInitialized(init.loc, context);\n break;\n default:\n members.defaultedMembers.push(\n // @ts-expect-error NodeAny not supported\n this.finishNode(memberNode, \"EnumDefaultedMember\"),\n );\n }\n }\n }\n\n if (!this.match(tt.braceR)) {\n this.expect(tt.comma);\n }\n }\n return { members, hasUnknownMembers };\n }\n\n flowEnumStringMembers(\n initializedMembers: N.Node[],\n defaultedMembers: N.Node[],\n {\n enumName,\n }: {\n enumName: string;\n },\n ): N.Node[] {\n if (initializedMembers.length === 0) {\n return defaultedMembers;\n } else if (defaultedMembers.length === 0) {\n return initializedMembers;\n } else if (defaultedMembers.length > initializedMembers.length) {\n for (const member of initializedMembers) {\n this.flowEnumErrorStringMemberInconsistentlyInitialized(member, {\n enumName,\n });\n }\n return defaultedMembers;\n } else {\n for (const member of defaultedMembers) {\n this.flowEnumErrorStringMemberInconsistentlyInitialized(member, {\n enumName,\n });\n }\n return initializedMembers;\n }\n }\n\n flowEnumParseExplicitType({\n enumName,\n }: {\n enumName: string;\n }): EnumExplicitType {\n if (!this.eatContextual(tt._of)) return null;\n\n if (!tokenIsIdentifier(this.state.type)) {\n throw this.raise(\n FlowErrors.EnumInvalidExplicitTypeUnknownSupplied,\n this.state.startLoc,\n {\n enumName,\n },\n );\n }\n\n const { value } = this.state;\n this.next();\n\n if (\n value !== \"boolean\" &&\n value !== \"number\" &&\n value !== \"string\" &&\n value !== \"symbol\"\n ) {\n this.raise(FlowErrors.EnumInvalidExplicitType, this.state.startLoc, {\n enumName,\n invalidEnumType: value,\n });\n }\n\n return value;\n }\n\n flowEnumBody(node: Undone, id: N.Identifier): N.Node {\n const enumName = id.name;\n const nameLoc = id.loc.start;\n const explicitType = this.flowEnumParseExplicitType({ enumName });\n this.expect(tt.braceL);\n const { members, hasUnknownMembers } = this.flowEnumMembers({\n enumName,\n explicitType,\n });\n node.hasUnknownMembers = hasUnknownMembers;\n\n switch (explicitType) {\n case \"boolean\":\n node.explicitType = true;\n node.members = members.booleanMembers;\n this.expect(tt.braceR);\n return this.finishNode(node, \"EnumBooleanBody\");\n case \"number\":\n node.explicitType = true;\n node.members = members.numberMembers;\n this.expect(tt.braceR);\n return this.finishNode(node, \"EnumNumberBody\");\n case \"string\":\n node.explicitType = true;\n node.members = this.flowEnumStringMembers(\n members.stringMembers,\n members.defaultedMembers,\n { enumName },\n );\n this.expect(tt.braceR);\n return this.finishNode(node, \"EnumStringBody\");\n case \"symbol\":\n node.members = members.defaultedMembers;\n this.expect(tt.braceR);\n return this.finishNode(node, \"EnumSymbolBody\");\n default: {\n // `explicitType` is `null`\n const empty = () => {\n node.members = [];\n this.expect(tt.braceR);\n return this.finishNode(node, \"EnumStringBody\");\n };\n node.explicitType = false;\n\n const boolsLen = members.booleanMembers.length;\n const numsLen = members.numberMembers.length;\n const strsLen = members.stringMembers.length;\n const defaultedLen = members.defaultedMembers.length;\n\n if (!boolsLen && !numsLen && !strsLen && !defaultedLen) {\n return empty();\n } else if (!boolsLen && !numsLen) {\n node.members = this.flowEnumStringMembers(\n members.stringMembers,\n members.defaultedMembers,\n { enumName },\n );\n this.expect(tt.braceR);\n return this.finishNode(node, \"EnumStringBody\");\n } else if (!numsLen && !strsLen && boolsLen >= defaultedLen) {\n for (const member of members.defaultedMembers) {\n this.flowEnumErrorBooleanMemberNotInitialized(member.loc.start, {\n enumName,\n memberName: member.id.name,\n });\n }\n node.members = members.booleanMembers;\n this.expect(tt.braceR);\n return this.finishNode(node, \"EnumBooleanBody\");\n } else if (!boolsLen && !strsLen && numsLen >= defaultedLen) {\n for (const member of members.defaultedMembers) {\n this.flowEnumErrorNumberMemberNotInitialized(member.loc.start, {\n enumName,\n memberName: member.id.name,\n });\n }\n node.members = members.numberMembers;\n this.expect(tt.braceR);\n return this.finishNode(node, \"EnumNumberBody\");\n } else {\n this.raise(FlowErrors.EnumInconsistentMemberValues, nameLoc, {\n enumName,\n });\n return empty();\n }\n }\n }\n }\n\n flowParseEnumDeclaration(\n node: Undone,\n ): N.FlowEnumDeclaration {\n const id = this.parseIdentifier();\n node.id = id;\n node.body = this.flowEnumBody(this.startNode(), id);\n return this.finishNode(node, \"EnumDeclaration\");\n }\n\n jsxParseOpeningElementAfterName(\n node: N.JSXOpeningElement,\n ): N.JSXOpeningElement {\n if (this.shouldParseTypes()) {\n if (this.match(tt.lt) || this.match(tt.bitShiftL)) {\n node.typeArguments =\n this.flowParseTypeParameterInstantiationInExpression();\n }\n }\n\n return super.jsxParseOpeningElementAfterName(node);\n }\n\n // check if the next token is a tt.lt\n isLookaheadToken_lt(): boolean {\n const next = this.nextTokenStart();\n if (this.input.charCodeAt(next) === charCodes.lessThan) {\n const afterNext = this.input.charCodeAt(next + 1);\n return (\n afterNext !== charCodes.lessThan && afterNext !== charCodes.equalsTo\n );\n }\n return false;\n }\n\n // used after we have finished parsing types\n reScan_lt_gt() {\n const { type } = this.state;\n if (type === tt.lt) {\n this.state.pos -= 1;\n this.readToken_lt();\n } else if (type === tt.gt) {\n this.state.pos -= 1;\n this.readToken_gt();\n }\n }\n\n reScan_lt() {\n const { type } = this.state;\n if (type === tt.bitShiftL) {\n this.state.pos -= 2;\n this.finishOp(tt.lt, 1);\n return tt.lt;\n }\n return type;\n }\n\n maybeUnwrapTypeCastExpression(node: N.Node) {\n return node.type === \"TypeCastExpression\" ? node.expression : node;\n }\n };\n","const entities: Record = {\n // @ts-expect-error __proto__ is not an actual property: https://github.com/microsoft/TypeScript/issues/38385\n __proto__: null,\n quot: \"\\u0022\",\n amp: \"&\",\n apos: \"\\u0027\",\n lt: \"<\",\n gt: \">\",\n nbsp: \"\\u00A0\",\n iexcl: \"\\u00A1\",\n cent: \"\\u00A2\",\n pound: \"\\u00A3\",\n curren: \"\\u00A4\",\n yen: \"\\u00A5\",\n brvbar: \"\\u00A6\",\n sect: \"\\u00A7\",\n uml: \"\\u00A8\",\n copy: \"\\u00A9\",\n ordf: \"\\u00AA\",\n laquo: \"\\u00AB\",\n not: \"\\u00AC\",\n shy: \"\\u00AD\",\n reg: \"\\u00AE\",\n macr: \"\\u00AF\",\n deg: \"\\u00B0\",\n plusmn: \"\\u00B1\",\n sup2: \"\\u00B2\",\n sup3: \"\\u00B3\",\n acute: \"\\u00B4\",\n micro: \"\\u00B5\",\n para: \"\\u00B6\",\n middot: \"\\u00B7\",\n cedil: \"\\u00B8\",\n sup1: \"\\u00B9\",\n ordm: \"\\u00BA\",\n raquo: \"\\u00BB\",\n frac14: \"\\u00BC\",\n frac12: \"\\u00BD\",\n frac34: \"\\u00BE\",\n iquest: \"\\u00BF\",\n Agrave: \"\\u00C0\",\n Aacute: \"\\u00C1\",\n Acirc: \"\\u00C2\",\n Atilde: \"\\u00C3\",\n Auml: \"\\u00C4\",\n Aring: \"\\u00C5\",\n AElig: \"\\u00C6\",\n Ccedil: \"\\u00C7\",\n Egrave: \"\\u00C8\",\n Eacute: \"\\u00C9\",\n Ecirc: \"\\u00CA\",\n Euml: \"\\u00CB\",\n Igrave: \"\\u00CC\",\n Iacute: \"\\u00CD\",\n Icirc: \"\\u00CE\",\n Iuml: \"\\u00CF\",\n ETH: \"\\u00D0\",\n Ntilde: \"\\u00D1\",\n Ograve: \"\\u00D2\",\n Oacute: \"\\u00D3\",\n Ocirc: \"\\u00D4\",\n Otilde: \"\\u00D5\",\n Ouml: \"\\u00D6\",\n times: \"\\u00D7\",\n Oslash: \"\\u00D8\",\n Ugrave: \"\\u00D9\",\n Uacute: \"\\u00DA\",\n Ucirc: \"\\u00DB\",\n Uuml: \"\\u00DC\",\n Yacute: \"\\u00DD\",\n THORN: \"\\u00DE\",\n szlig: \"\\u00DF\",\n agrave: \"\\u00E0\",\n aacute: \"\\u00E1\",\n acirc: \"\\u00E2\",\n atilde: \"\\u00E3\",\n auml: \"\\u00E4\",\n aring: \"\\u00E5\",\n aelig: \"\\u00E6\",\n ccedil: \"\\u00E7\",\n egrave: \"\\u00E8\",\n eacute: \"\\u00E9\",\n ecirc: \"\\u00EA\",\n euml: \"\\u00EB\",\n igrave: \"\\u00EC\",\n iacute: \"\\u00ED\",\n icirc: \"\\u00EE\",\n iuml: \"\\u00EF\",\n eth: \"\\u00F0\",\n ntilde: \"\\u00F1\",\n ograve: \"\\u00F2\",\n oacute: \"\\u00F3\",\n ocirc: \"\\u00F4\",\n otilde: \"\\u00F5\",\n ouml: \"\\u00F6\",\n divide: \"\\u00F7\",\n oslash: \"\\u00F8\",\n ugrave: \"\\u00F9\",\n uacute: \"\\u00FA\",\n ucirc: \"\\u00FB\",\n uuml: \"\\u00FC\",\n yacute: \"\\u00FD\",\n thorn: \"\\u00FE\",\n yuml: \"\\u00FF\",\n OElig: \"\\u0152\",\n oelig: \"\\u0153\",\n Scaron: \"\\u0160\",\n scaron: \"\\u0161\",\n Yuml: \"\\u0178\",\n fnof: \"\\u0192\",\n circ: \"\\u02C6\",\n tilde: \"\\u02DC\",\n Alpha: \"\\u0391\",\n Beta: \"\\u0392\",\n Gamma: \"\\u0393\",\n Delta: \"\\u0394\",\n Epsilon: \"\\u0395\",\n Zeta: \"\\u0396\",\n Eta: \"\\u0397\",\n Theta: \"\\u0398\",\n Iota: \"\\u0399\",\n Kappa: \"\\u039A\",\n Lambda: \"\\u039B\",\n Mu: \"\\u039C\",\n Nu: \"\\u039D\",\n Xi: \"\\u039E\",\n Omicron: \"\\u039F\",\n Pi: \"\\u03A0\",\n Rho: \"\\u03A1\",\n Sigma: \"\\u03A3\",\n Tau: \"\\u03A4\",\n Upsilon: \"\\u03A5\",\n Phi: \"\\u03A6\",\n Chi: \"\\u03A7\",\n Psi: \"\\u03A8\",\n Omega: \"\\u03A9\",\n alpha: \"\\u03B1\",\n beta: \"\\u03B2\",\n gamma: \"\\u03B3\",\n delta: \"\\u03B4\",\n epsilon: \"\\u03B5\",\n zeta: \"\\u03B6\",\n eta: \"\\u03B7\",\n theta: \"\\u03B8\",\n iota: \"\\u03B9\",\n kappa: \"\\u03BA\",\n lambda: \"\\u03BB\",\n mu: \"\\u03BC\",\n nu: \"\\u03BD\",\n xi: \"\\u03BE\",\n omicron: \"\\u03BF\",\n pi: \"\\u03C0\",\n rho: \"\\u03C1\",\n sigmaf: \"\\u03C2\",\n sigma: \"\\u03C3\",\n tau: \"\\u03C4\",\n upsilon: \"\\u03C5\",\n phi: \"\\u03C6\",\n chi: \"\\u03C7\",\n psi: \"\\u03C8\",\n omega: \"\\u03C9\",\n thetasym: \"\\u03D1\",\n upsih: \"\\u03D2\",\n piv: \"\\u03D6\",\n ensp: \"\\u2002\",\n emsp: \"\\u2003\",\n thinsp: \"\\u2009\",\n zwnj: \"\\u200C\",\n zwj: \"\\u200D\",\n lrm: \"\\u200E\",\n rlm: \"\\u200F\",\n ndash: \"\\u2013\",\n mdash: \"\\u2014\",\n lsquo: \"\\u2018\",\n rsquo: \"\\u2019\",\n sbquo: \"\\u201A\",\n ldquo: \"\\u201C\",\n rdquo: \"\\u201D\",\n bdquo: \"\\u201E\",\n dagger: \"\\u2020\",\n Dagger: \"\\u2021\",\n bull: \"\\u2022\",\n hellip: \"\\u2026\",\n permil: \"\\u2030\",\n prime: \"\\u2032\",\n Prime: \"\\u2033\",\n lsaquo: \"\\u2039\",\n rsaquo: \"\\u203A\",\n oline: \"\\u203E\",\n frasl: \"\\u2044\",\n euro: \"\\u20AC\",\n image: \"\\u2111\",\n weierp: \"\\u2118\",\n real: \"\\u211C\",\n trade: \"\\u2122\",\n alefsym: \"\\u2135\",\n larr: \"\\u2190\",\n uarr: \"\\u2191\",\n rarr: \"\\u2192\",\n darr: \"\\u2193\",\n harr: \"\\u2194\",\n crarr: \"\\u21B5\",\n lArr: \"\\u21D0\",\n uArr: \"\\u21D1\",\n rArr: \"\\u21D2\",\n dArr: \"\\u21D3\",\n hArr: \"\\u21D4\",\n forall: \"\\u2200\",\n part: \"\\u2202\",\n exist: \"\\u2203\",\n empty: \"\\u2205\",\n nabla: \"\\u2207\",\n isin: \"\\u2208\",\n notin: \"\\u2209\",\n ni: \"\\u220B\",\n prod: \"\\u220F\",\n sum: \"\\u2211\",\n minus: \"\\u2212\",\n lowast: \"\\u2217\",\n radic: \"\\u221A\",\n prop: \"\\u221D\",\n infin: \"\\u221E\",\n ang: \"\\u2220\",\n and: \"\\u2227\",\n or: \"\\u2228\",\n cap: \"\\u2229\",\n cup: \"\\u222A\",\n int: \"\\u222B\",\n there4: \"\\u2234\",\n sim: \"\\u223C\",\n cong: \"\\u2245\",\n asymp: \"\\u2248\",\n ne: \"\\u2260\",\n equiv: \"\\u2261\",\n le: \"\\u2264\",\n ge: \"\\u2265\",\n sub: \"\\u2282\",\n sup: \"\\u2283\",\n nsub: \"\\u2284\",\n sube: \"\\u2286\",\n supe: \"\\u2287\",\n oplus: \"\\u2295\",\n otimes: \"\\u2297\",\n perp: \"\\u22A5\",\n sdot: \"\\u22C5\",\n lceil: \"\\u2308\",\n rceil: \"\\u2309\",\n lfloor: \"\\u230A\",\n rfloor: \"\\u230B\",\n lang: \"\\u2329\",\n rang: \"\\u232A\",\n loz: \"\\u25CA\",\n spades: \"\\u2660\",\n clubs: \"\\u2663\",\n hearts: \"\\u2665\",\n diams: \"\\u2666\",\n} as const;\nexport default entities;\n","import * as charCodes from \"charcodes\";\n\n// Matches a whole line break (where CRLF is considered a single\n// line break). Used to count lines.\nexport const lineBreak = /\\r\\n|[\\r\\n\\u2028\\u2029]/;\nexport const lineBreakG = new RegExp(lineBreak.source, \"g\");\n\n// https://tc39.github.io/ecma262/#sec-line-terminators\nexport function isNewLine(code: number): boolean {\n switch (code) {\n case charCodes.lineFeed:\n case charCodes.carriageReturn:\n case charCodes.lineSeparator:\n case charCodes.paragraphSeparator:\n return true;\n\n default:\n return false;\n }\n}\n\nexport function hasNewLine(input: string, start: number, end: number): boolean {\n for (let i = start; i < end; i++) {\n if (isNewLine(input.charCodeAt(i))) {\n return true;\n }\n }\n return false;\n}\n\nexport const skipWhiteSpace = /(?:\\s|\\/\\/.*|\\/\\*[^]*?\\*\\/)*/g;\n\nexport const skipWhiteSpaceInLine =\n /(?:[^\\S\\n\\r\\u2028\\u2029]|\\/\\/.*|\\/\\*.*?\\*\\/)*/g;\n\n// https://tc39.github.io/ecma262/#sec-white-space\nexport function isWhitespace(code: number): boolean {\n switch (code) {\n case 0x0009: // CHARACTER TABULATION\n case 0x000b: // LINE TABULATION\n case 0x000c: // FORM FEED\n case charCodes.space:\n case charCodes.nonBreakingSpace:\n case charCodes.oghamSpaceMark:\n case 0x2000: // EN QUAD\n case 0x2001: // EM QUAD\n case 0x2002: // EN SPACE\n case 0x2003: // EM SPACE\n case 0x2004: // THREE-PER-EM SPACE\n case 0x2005: // FOUR-PER-EM SPACE\n case 0x2006: // SIX-PER-EM SPACE\n case 0x2007: // FIGURE SPACE\n case 0x2008: // PUNCTUATION SPACE\n case 0x2009: // THIN SPACE\n case 0x200a: // HAIR SPACE\n case 0x202f: // NARROW NO-BREAK SPACE\n case 0x205f: // MEDIUM MATHEMATICAL SPACE\n case 0x3000: // IDEOGRAPHIC SPACE\n case 0xfeff: // ZERO WIDTH NO-BREAK SPACE\n return true;\n\n default:\n return false;\n }\n}\n","import * as charCodes from \"charcodes\";\n\nimport XHTMLEntities from \"./xhtml.ts\";\nimport type Parser from \"../../parser/index.ts\";\nimport type { ExpressionErrors } from \"../../parser/util.ts\";\nimport {\n tokenComesBeforeExpression,\n tokenIsKeyword,\n tokenLabelName,\n type TokenType,\n tt,\n} from \"../../tokenizer/types.ts\";\nimport type { TokContext } from \"../../tokenizer/context.ts\";\nimport { types as tc } from \"../../tokenizer/context.ts\";\nimport type * as N from \"../../types.ts\";\nimport { isIdentifierChar, isIdentifierStart } from \"../../util/identifier.ts\";\nimport type { Position } from \"../../util/location.ts\";\nimport { isNewLine } from \"../../util/whitespace.ts\";\nimport { Errors, ParseErrorEnum } from \"../../parse-error.ts\";\nimport type { Undone } from \"../../parser/node.ts\";\n\n/* eslint sort-keys: \"error\" */\nconst JsxErrors = ParseErrorEnum`jsx`({\n AttributeIsEmpty:\n \"JSX attributes must only be assigned a non-empty expression.\",\n MissingClosingTagElement: ({ openingTagName }: { openingTagName: string }) =>\n `Expected corresponding JSX closing tag for <${openingTagName}>.`,\n MissingClosingTagFragment: \"Expected corresponding JSX closing tag for <>.\",\n UnexpectedSequenceExpression:\n \"Sequence expressions cannot be directly nested inside JSX. Did you mean to wrap it in parentheses (...)?\",\n // FIXME: Unify with Errors.UnexpectedToken\n UnexpectedToken: ({\n unexpected,\n HTMLEntity,\n }: {\n unexpected: string;\n HTMLEntity: string;\n }) =>\n `Unexpected token \\`${unexpected}\\`. Did you mean \\`${HTMLEntity}\\` or \\`{'${unexpected}'}\\`?`,\n UnsupportedJsxValue:\n \"JSX value should be either an expression or a quoted JSX text.\",\n UnterminatedJsxContent: \"Unterminated JSX contents.\",\n UnwrappedAdjacentJSXElements:\n \"Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...?\",\n});\n\n/* eslint-disable sort-keys */\n\nfunction isFragment(object?: N.JSXTag | null): object is N.JSXFragmentTag {\n return object\n ? object.type === \"JSXOpeningFragment\" ||\n object.type === \"JSXClosingFragment\"\n : false;\n}\n\n// Transforms JSX element name to string.\n\nfunction getQualifiedJSXName(\n object: N.JSXIdentifier | N.JSXNamespacedName | N.JSXMemberExpression,\n): string {\n if (object.type === \"JSXIdentifier\") {\n return object.name;\n }\n\n if (object.type === \"JSXNamespacedName\") {\n return object.namespace.name + \":\" + object.name.name;\n }\n\n if (object.type === \"JSXMemberExpression\") {\n return (\n getQualifiedJSXName(object.object) +\n \".\" +\n getQualifiedJSXName(object.property)\n );\n }\n\n // istanbul ignore next\n // @ts-expect-error - object is 'never'\n throw new Error(\"Node had unexpected type: \" + object.type);\n}\n\nexport interface IJSXParserMixin {\n jsxParseOpeningElementAfterName(\n node: N.JSXOpeningElement,\n ): N.JSXOpeningElement;\n}\n\nexport type ClassWithMixin<\n T extends new (...args: any) => any,\n M extends object,\n> = T extends new (...args: infer P) => infer I\n ? new (...args: P) => I & M\n : never;\n\nexport default (superClass: typeof Parser) =>\n class JSXParserMixin extends superClass implements Parser, IJSXParserMixin {\n // Reads inline JSX contents token.\n\n jsxReadToken(): void {\n let out = \"\";\n let chunkStart = this.state.pos;\n for (;;) {\n if (this.state.pos >= this.length) {\n throw this.raise(\n JsxErrors.UnterminatedJsxContent,\n this.state.startLoc,\n );\n }\n\n const ch = this.input.charCodeAt(this.state.pos);\n\n switch (ch) {\n case charCodes.lessThan:\n case charCodes.leftCurlyBrace:\n if (this.state.pos === this.state.start) {\n if (ch === charCodes.lessThan && this.state.canStartJSXElement) {\n ++this.state.pos;\n this.finishToken(tt.jsxTagStart);\n } else {\n super.getTokenFromCode(ch);\n }\n return;\n }\n out += this.input.slice(chunkStart, this.state.pos);\n this.finishToken(tt.jsxText, out);\n return;\n\n case charCodes.ampersand:\n out += this.input.slice(chunkStart, this.state.pos);\n out += this.jsxReadEntity();\n chunkStart = this.state.pos;\n break;\n\n case charCodes.greaterThan:\n case charCodes.rightCurlyBrace:\n if (process.env.BABEL_8_BREAKING) {\n this.raise(JsxErrors.UnexpectedToken, this.state.curPosition(), {\n unexpected: this.input[this.state.pos],\n HTMLEntity:\n ch === charCodes.rightCurlyBrace ? \"}\" : \">\",\n });\n }\n /* falls through */\n\n default:\n if (isNewLine(ch)) {\n out += this.input.slice(chunkStart, this.state.pos);\n out += this.jsxReadNewLine(true);\n chunkStart = this.state.pos;\n } else {\n ++this.state.pos;\n }\n }\n }\n }\n\n jsxReadNewLine(normalizeCRLF: boolean): string {\n const ch = this.input.charCodeAt(this.state.pos);\n let out;\n ++this.state.pos;\n if (\n ch === charCodes.carriageReturn &&\n this.input.charCodeAt(this.state.pos) === charCodes.lineFeed\n ) {\n ++this.state.pos;\n out = normalizeCRLF ? \"\\n\" : \"\\r\\n\";\n } else {\n out = String.fromCharCode(ch);\n }\n ++this.state.curLine;\n this.state.lineStart = this.state.pos;\n\n return out;\n }\n\n jsxReadString(quote: number): void {\n let out = \"\";\n let chunkStart = ++this.state.pos;\n for (;;) {\n if (this.state.pos >= this.length) {\n throw this.raise(Errors.UnterminatedString, this.state.startLoc);\n }\n\n const ch = this.input.charCodeAt(this.state.pos);\n if (ch === quote) break;\n if (ch === charCodes.ampersand) {\n out += this.input.slice(chunkStart, this.state.pos);\n out += this.jsxReadEntity();\n chunkStart = this.state.pos;\n } else if (isNewLine(ch)) {\n out += this.input.slice(chunkStart, this.state.pos);\n out += this.jsxReadNewLine(false);\n chunkStart = this.state.pos;\n } else {\n ++this.state.pos;\n }\n }\n out += this.input.slice(chunkStart, this.state.pos++);\n this.finishToken(tt.string, out);\n }\n\n jsxReadEntity(): string {\n const startPos = ++this.state.pos;\n if (this.codePointAtPos(this.state.pos) === charCodes.numberSign) {\n ++this.state.pos;\n\n let radix = 10;\n if (this.codePointAtPos(this.state.pos) === charCodes.lowercaseX) {\n radix = 16;\n ++this.state.pos;\n }\n\n const codePoint = this.readInt(\n radix,\n /* len */ undefined,\n /* forceLen */ false,\n /* allowNumSeparator */ \"bail\",\n );\n if (\n codePoint !== null &&\n this.codePointAtPos(this.state.pos) === charCodes.semicolon\n ) {\n ++this.state.pos;\n return String.fromCodePoint(codePoint);\n }\n } else {\n let count = 0;\n let semi = false;\n while (\n count++ < 10 &&\n this.state.pos < this.length &&\n !(semi = this.codePointAtPos(this.state.pos) === charCodes.semicolon)\n ) {\n ++this.state.pos;\n }\n\n if (semi) {\n const desc = this.input.slice(startPos, this.state.pos);\n const entity = XHTMLEntities[desc];\n ++this.state.pos;\n\n if (entity) {\n return entity;\n }\n }\n }\n\n // Not a valid entity\n this.state.pos = startPos;\n return \"&\";\n }\n\n // Read a JSX identifier (valid tag or attribute name).\n //\n // Optimized version since JSX identifiers can\"t contain\n // escape characters and so can be read as single slice.\n // Also assumes that first character was already checked\n // by isIdentifierStart in readToken.\n\n jsxReadWord(): void {\n let ch;\n const start = this.state.pos;\n do {\n ch = this.input.charCodeAt(++this.state.pos);\n } while (isIdentifierChar(ch) || ch === charCodes.dash);\n this.finishToken(tt.jsxName, this.input.slice(start, this.state.pos));\n }\n\n // Parse next token as JSX identifier\n\n jsxParseIdentifier(): N.JSXIdentifier {\n const node = this.startNode();\n if (this.match(tt.jsxName)) {\n node.name = this.state.value;\n } else if (tokenIsKeyword(this.state.type)) {\n node.name = tokenLabelName(this.state.type);\n } else {\n this.unexpected();\n }\n this.next();\n return this.finishNode(node, \"JSXIdentifier\");\n }\n\n // Parse namespaced identifier.\n\n jsxParseNamespacedName(): N.JSXNamespacedName | N.JSXIdentifier {\n const startLoc = this.state.startLoc;\n const name = this.jsxParseIdentifier();\n if (!this.eat(tt.colon)) return name;\n\n const node = this.startNodeAt(startLoc);\n node.namespace = name;\n node.name = this.jsxParseIdentifier();\n return this.finishNode(node, \"JSXNamespacedName\");\n }\n\n // Parses element name in any form - namespaced, member\n // or single identifier.\n\n jsxParseElementName():\n | N.JSXIdentifier\n | N.JSXNamespacedName\n | N.JSXMemberExpression {\n const startLoc = this.state.startLoc;\n let node: N.JSXIdentifier | N.JSXNamespacedName | N.JSXMemberExpression =\n this.jsxParseNamespacedName();\n if (node.type === \"JSXNamespacedName\") {\n return node;\n }\n while (this.eat(tt.dot)) {\n const newNode = this.startNodeAt(startLoc);\n newNode.object = node;\n newNode.property = this.jsxParseIdentifier();\n node = this.finishNode(newNode, \"JSXMemberExpression\");\n }\n return node;\n }\n\n // Parses any type of JSX attribute value.\n\n jsxParseAttributeValue():\n | N.JSXExpressionContainer\n | N.JSXElement\n | N.StringLiteral {\n let node;\n switch (this.state.type) {\n case tt.braceL:\n node = this.startNode();\n this.setContext(tc.brace);\n this.next();\n node = this.jsxParseExpressionContainer(node, tc.j_oTag);\n if (node.expression.type === \"JSXEmptyExpression\") {\n this.raise(JsxErrors.AttributeIsEmpty, node);\n }\n return node;\n\n case tt.jsxTagStart:\n case tt.string:\n return this.parseExprAtom() as N.JSXElement | N.StringLiteral;\n\n default:\n throw this.raise(JsxErrors.UnsupportedJsxValue, this.state.startLoc);\n }\n }\n\n // JSXEmptyExpression is unique type since it doesn't actually parse anything,\n // and so it should start at the end of last read token (left brace) and finish\n // at the beginning of the next one (right brace).\n\n jsxParseEmptyExpression(): N.JSXEmptyExpression {\n const node = this.startNodeAt(this.state.lastTokEndLoc!);\n return this.finishNodeAt(node, \"JSXEmptyExpression\", this.state.startLoc);\n }\n\n // Parse JSX spread child\n\n jsxParseSpreadChild(node: Undone): N.JSXSpreadChild {\n this.next(); // ellipsis\n node.expression = this.parseExpression();\n this.setContext(tc.j_expr);\n this.state.canStartJSXElement = true;\n this.expect(tt.braceR);\n\n return this.finishNode(node, \"JSXSpreadChild\");\n }\n\n // Parses JSX expression enclosed into curly brackets.\n\n jsxParseExpressionContainer(\n node: Undone,\n previousContext: TokContext,\n ): N.JSXExpressionContainer {\n if (this.match(tt.braceR)) {\n node.expression = this.jsxParseEmptyExpression();\n } else {\n const expression = this.parseExpression();\n\n if (process.env.BABEL_8_BREAKING) {\n if (\n expression.type === \"SequenceExpression\" &&\n !expression.extra?.parenthesized\n ) {\n this.raise(\n JsxErrors.UnexpectedSequenceExpression,\n expression.expressions[1],\n );\n }\n }\n\n node.expression = expression;\n }\n this.setContext(previousContext);\n this.state.canStartJSXElement = true;\n this.expect(tt.braceR);\n\n return this.finishNode(node, \"JSXExpressionContainer\");\n }\n\n // Parses following JSX attribute name-value pair.\n\n jsxParseAttribute(): N.JSXAttribute | N.JSXSpreadAttribute {\n const node = this.startNode();\n if (this.match(tt.braceL)) {\n this.setContext(tc.brace);\n this.next();\n this.expect(tt.ellipsis);\n node.argument = this.parseMaybeAssignAllowIn();\n this.setContext(tc.j_oTag);\n this.state.canStartJSXElement = true;\n this.expect(tt.braceR);\n return this.finishNode(node, \"JSXSpreadAttribute\");\n }\n node.name = this.jsxParseNamespacedName();\n node.value = this.eat(tt.eq) ? this.jsxParseAttributeValue() : null;\n return this.finishNode(node, \"JSXAttribute\");\n }\n\n // Parses JSX opening tag starting after \"<\".\n\n jsxParseOpeningElementAt(\n startLoc: Position,\n ): N.JSXOpeningElement | N.JSXOpeningFragment {\n const node = this.startNodeAt(\n startLoc,\n );\n if (this.eat(tt.jsxTagEnd)) {\n return this.finishNode(node, \"JSXOpeningFragment\");\n }\n node.name = this.jsxParseElementName();\n return this.jsxParseOpeningElementAfterName(\n node as Undone,\n );\n }\n\n jsxParseOpeningElementAfterName(\n node: Undone,\n ): N.JSXOpeningElement {\n const attributes: (N.JSXAttribute | N.JSXSpreadAttribute)[] = [];\n while (!this.match(tt.slash) && !this.match(tt.jsxTagEnd)) {\n attributes.push(this.jsxParseAttribute());\n }\n node.attributes = attributes;\n node.selfClosing = this.eat(tt.slash);\n this.expect(tt.jsxTagEnd);\n return this.finishNode(node, \"JSXOpeningElement\");\n }\n\n // Parses JSX closing tag starting after \"(\n startLoc,\n );\n if (this.eat(tt.jsxTagEnd)) {\n return this.finishNode(node, \"JSXClosingFragment\");\n }\n node.name = this.jsxParseElementName();\n this.expect(tt.jsxTagEnd);\n return this.finishNode(node, \"JSXClosingElement\");\n }\n\n // Parses entire JSX element, including it\"s opening tag\n // (starting after \"<\"), attributes, contents and closing tag.\n\n jsxParseElementAt(startLoc: Position): N.JSXElement | N.JSXFragment {\n const node = this.startNodeAt(startLoc);\n const children = [];\n const openingElement = this.jsxParseOpeningElementAt(startLoc);\n let closingElement = null;\n\n if (!openingElement.selfClosing) {\n contents: for (;;) {\n switch (this.state.type) {\n case tt.jsxTagStart:\n startLoc = this.state.startLoc;\n this.next();\n if (this.eat(tt.slash)) {\n closingElement = this.jsxParseClosingElementAt(startLoc);\n break contents;\n }\n children.push(this.jsxParseElementAt(startLoc));\n break;\n\n case tt.jsxText:\n children.push(this.parseLiteral(this.state.value, \"JSXText\"));\n break;\n\n case tt.braceL: {\n const node = this.startNode<\n N.JSXSpreadChild | N.JSXExpressionContainer\n >();\n this.setContext(tc.brace);\n this.next();\n if (this.match(tt.ellipsis)) {\n children.push(this.jsxParseSpreadChild(node));\n } else {\n children.push(\n this.jsxParseExpressionContainer(node, tc.j_expr),\n );\n }\n\n break;\n }\n // istanbul ignore next - should never happen\n default:\n this.unexpected();\n }\n }\n\n if (\n isFragment(openingElement) &&\n !isFragment(closingElement) &&\n closingElement !== null\n ) {\n this.raise(JsxErrors.MissingClosingTagFragment, closingElement);\n } else if (!isFragment(openingElement) && isFragment(closingElement)) {\n this.raise(JsxErrors.MissingClosingTagElement, closingElement, {\n openingTagName: getQualifiedJSXName(openingElement.name),\n });\n } else if (!isFragment(openingElement) && !isFragment(closingElement)) {\n if (\n getQualifiedJSXName(closingElement.name) !==\n getQualifiedJSXName(openingElement.name)\n ) {\n this.raise(JsxErrors.MissingClosingTagElement, closingElement, {\n openingTagName: getQualifiedJSXName(openingElement.name),\n });\n }\n }\n }\n\n if (isFragment(openingElement)) {\n node.openingFragment = openingElement;\n node.closingFragment = closingElement;\n } else {\n node.openingElement = openingElement;\n node.closingElement = closingElement;\n }\n node.children = children;\n if (this.match(tt.lt)) {\n throw this.raise(\n JsxErrors.UnwrappedAdjacentJSXElements,\n this.state.startLoc,\n );\n }\n\n return isFragment(openingElement)\n ? this.finishNode(node, \"JSXFragment\")\n : this.finishNode(node, \"JSXElement\");\n }\n\n // Parses entire JSX element from current position.\n\n jsxParseElement(): N.JSXElement | N.JSXFragment {\n const startLoc = this.state.startLoc;\n this.next();\n return this.jsxParseElementAt(startLoc);\n }\n\n setContext(newContext: TokContext) {\n const { context } = this.state;\n context[context.length - 1] = newContext;\n }\n\n // ==================================\n // Overrides\n // ==================================\n\n parseExprAtom(refExpressionErrors?: ExpressionErrors | null): N.Expression {\n if (this.match(tt.jsxTagStart)) {\n return this.jsxParseElement();\n } else if (\n this.match(tt.lt) &&\n this.input.charCodeAt(this.state.pos) !== charCodes.exclamationMark\n ) {\n // In case we encounter an lt token here it will always be the start of\n // jsx as the lt sign is not allowed in places that expect an expression\n this.replaceToken(tt.jsxTagStart);\n return this.jsxParseElement();\n } else {\n return super.parseExprAtom(refExpressionErrors);\n }\n }\n\n skipSpace() {\n const curContext = this.curContext();\n if (!curContext.preserveSpace) super.skipSpace();\n }\n\n getTokenFromCode(code: number): void {\n const context = this.curContext();\n\n if (context === tc.j_expr) {\n this.jsxReadToken();\n return;\n }\n\n if (context === tc.j_oTag || context === tc.j_cTag) {\n if (isIdentifierStart(code)) {\n this.jsxReadWord();\n return;\n }\n\n if (code === charCodes.greaterThan) {\n ++this.state.pos;\n this.finishToken(tt.jsxTagEnd);\n return;\n }\n\n if (\n (code === charCodes.quotationMark || code === charCodes.apostrophe) &&\n context === tc.j_oTag\n ) {\n this.jsxReadString(code);\n return;\n }\n }\n\n if (\n code === charCodes.lessThan &&\n this.state.canStartJSXElement &&\n this.input.charCodeAt(this.state.pos + 1) !== charCodes.exclamationMark\n ) {\n ++this.state.pos;\n this.finishToken(tt.jsxTagStart);\n return;\n }\n\n super.getTokenFromCode(code);\n }\n\n updateContext(prevType: TokenType): void {\n const { context, type } = this.state;\n if (type === tt.slash && prevType === tt.jsxTagStart) {\n // do not consider JSX expr -> JSX open tag -> ... anymore\n // reconsider as closing tag context\n context.splice(-2, 2, tc.j_cTag);\n this.state.canStartJSXElement = false;\n } else if (type === tt.jsxTagStart) {\n // start opening tag context\n context.push(tc.j_oTag);\n } else if (type === tt.jsxTagEnd) {\n const out = context[context.length - 1];\n if ((out === tc.j_oTag && prevType === tt.slash) || out === tc.j_cTag) {\n context.pop();\n this.state.canStartJSXElement =\n context[context.length - 1] === tc.j_expr;\n } else {\n this.setContext(tc.j_expr);\n this.state.canStartJSXElement = true;\n }\n } else {\n this.state.canStartJSXElement = tokenComesBeforeExpression(type);\n }\n }\n };\n","import type { Position } from \"../../util/location.ts\";\nimport ScopeHandler, { NameType, Scope } from \"../../util/scope.ts\";\nimport { BindingFlag, ScopeFlag } from \"../../util/scopeflags.ts\";\nimport type * as N from \"../../types.ts\";\nimport { Errors } from \"../../parse-error.ts\";\n\nconst enum TsNameType {\n Types = 1 << 0,\n // enums (which are also in .types)\n Enums = 1 << 1,\n // const enums (which are also in .enums and .types)\n ConstEnums = 1 << 2,\n // classes (which are also in .lexical) and interface (which are also in .types)\n Classes = 1 << 3,\n // namespaces and ambient functions (or classes) are too difficult to track,\n // especially without type analysis.\n // We need to track them anyway, to avoid \"X is not defined\" errors\n // when exporting them.\n ExportOnlyBindings = 1 << 4,\n}\n\nclass TypeScriptScope extends Scope {\n tsNames = new Map();\n}\n\n// See https://github.com/babel/babel/pull/9766#discussion_r268920730 for an\n// explanation of how typescript handles scope.\n\nexport default class TypeScriptScopeHandler extends ScopeHandler {\n importsStack: Set[] = [];\n\n createScope(flags: ScopeFlag): TypeScriptScope {\n this.importsStack.push(new Set()); // Always keep the top-level scope for export checks.\n\n return new TypeScriptScope(flags);\n }\n\n enter(flags: ScopeFlag): void {\n if (flags === ScopeFlag.TS_MODULE) {\n this.importsStack.push(new Set());\n }\n\n super.enter(flags);\n }\n\n exit() {\n const flags = super.exit();\n\n if (flags === ScopeFlag.TS_MODULE) {\n this.importsStack.pop();\n }\n\n return flags;\n }\n\n hasImport(name: string, allowShadow?: boolean) {\n const len = this.importsStack.length;\n if (this.importsStack[len - 1].has(name)) {\n return true;\n }\n if (!allowShadow && len > 1) {\n for (let i = 0; i < len - 1; i++) {\n if (this.importsStack[i].has(name)) return true;\n }\n }\n return false;\n }\n\n declareName(name: string, bindingType: BindingFlag, loc: Position) {\n if (bindingType & BindingFlag.FLAG_TS_IMPORT) {\n if (this.hasImport(name, true)) {\n this.parser.raise(Errors.VarRedeclaration, loc, {\n identifierName: name,\n });\n }\n this.importsStack[this.importsStack.length - 1].add(name);\n return;\n }\n\n const scope = this.currentScope();\n let type = scope.tsNames.get(name) || 0;\n\n if (bindingType & BindingFlag.FLAG_TS_EXPORT_ONLY) {\n this.maybeExportDefined(scope, name);\n scope.tsNames.set(name, type | TsNameType.ExportOnlyBindings);\n return;\n }\n\n super.declareName(name, bindingType, loc);\n\n if (bindingType & BindingFlag.KIND_TYPE) {\n if (!(bindingType & BindingFlag.KIND_VALUE)) {\n // \"Value\" bindings have already been registered by the superclass.\n this.checkRedeclarationInScope(scope, name, bindingType, loc);\n this.maybeExportDefined(scope, name);\n }\n type = type | TsNameType.Types;\n }\n if (bindingType & BindingFlag.FLAG_TS_ENUM) {\n type = type | TsNameType.Enums;\n }\n if (bindingType & BindingFlag.FLAG_TS_CONST_ENUM) {\n type = type | TsNameType.ConstEnums;\n }\n if (bindingType & BindingFlag.FLAG_CLASS) {\n type = type | TsNameType.Classes;\n }\n if (type) scope.tsNames.set(name, type);\n }\n\n isRedeclaredInScope(\n scope: TypeScriptScope,\n name: string,\n bindingType: BindingFlag,\n ): boolean {\n const type = scope.tsNames.get(name)!;\n if ((type & TsNameType.Enums) > 0) {\n if (bindingType & BindingFlag.FLAG_TS_ENUM) {\n // Enums can be merged with other enums if they are both\n // const or both non-const.\n const isConst = !!(bindingType & BindingFlag.FLAG_TS_CONST_ENUM);\n const wasConst = (type & TsNameType.ConstEnums) > 0;\n return isConst !== wasConst;\n }\n return true;\n }\n if (\n bindingType & BindingFlag.FLAG_CLASS &&\n (type & TsNameType.Classes) > 0\n ) {\n if (scope.names.get(name)! & NameType.Lexical) {\n // Classes can be merged with interfaces\n return !!(bindingType & BindingFlag.KIND_VALUE);\n } else {\n // Interface can be merged with other classes or interfaces\n return false;\n }\n }\n if (bindingType & BindingFlag.KIND_TYPE && (type & TsNameType.Types) > 0) {\n return true;\n }\n\n return super.isRedeclaredInScope(scope, name, bindingType);\n }\n\n checkLocalExport(id: N.Identifier) {\n const { name } = id;\n\n if (this.hasImport(name)) return;\n\n const len = this.scopeStack.length;\n for (let i = len - 1; i >= 0; i--) {\n const scope = this.scopeStack[i];\n const type = scope.tsNames.get(name)!;\n if (\n (type & TsNameType.Types) > 0 ||\n (type & TsNameType.ExportOnlyBindings) > 0\n ) {\n return;\n }\n }\n\n super.checkLocalExport(id);\n }\n}\n","// ProductionParameterHandler is a stack fashioned production parameter tracker\n// https://tc39.es/ecma262/#sec-grammar-notation\n// The tracked parameters are defined above.\n//\n// Whenever [+Await]/[+Yield] appears in the right-hand sides of a production,\n// we must enter a new tracking stack. For example when parsing\n//\n// AsyncFunctionDeclaration [Yield, Await]:\n// async [no LineTerminator here] function BindingIdentifier[?Yield, ?Await]\n// ( FormalParameters[~Yield, +Await] ) { AsyncFunctionBody }\n//\n// we must follow such process:\n//\n// 1. parse async keyword\n// 2. parse function keyword\n// 3. parse bindingIdentifier <= inherit current parameters: [?Await]\n// 4. enter new stack with (PARAM_AWAIT)\n// 5. parse formal parameters <= must have [Await] parameter [+Await]\n// 6. parse function body\n// 7. exit current stack\n\nexport const enum ParamKind {\n // Initial Parameter flags\n PARAM = 0b0000,\n // track [Yield] production parameter\n PARAM_YIELD = 0b0001,\n // track [Await] production parameter\n PARAM_AWAIT = 0b0010,\n // track [Return] production parameter\n PARAM_RETURN = 0b0100,\n // track [In] production parameter\n PARAM_IN = 0b1000,\n}\n\n// todo(flow->ts) - check if more granular type can be used,\n// type below is not good because things like PARAM_AWAIT|PARAM_YIELD are not included\n// export type ParamKind =\n// | typeof PARAM\n// | typeof PARAM_AWAIT\n// | typeof PARAM_IN\n// | typeof PARAM_RETURN\n// | typeof PARAM_YIELD;\n\nexport default class ProductionParameterHandler {\n stacks: ParamKind[] = [];\n enter(flags: ParamKind) {\n this.stacks.push(flags);\n }\n\n exit() {\n this.stacks.pop();\n }\n\n currentFlags(): ParamKind {\n return this.stacks[this.stacks.length - 1];\n }\n\n get hasAwait(): boolean {\n return (this.currentFlags() & ParamKind.PARAM_AWAIT) > 0;\n }\n\n get hasYield(): boolean {\n return (this.currentFlags() & ParamKind.PARAM_YIELD) > 0;\n }\n\n get hasReturn(): boolean {\n return (this.currentFlags() & ParamKind.PARAM_RETURN) > 0;\n }\n\n get hasIn(): boolean {\n return (this.currentFlags() & ParamKind.PARAM_IN) > 0;\n }\n}\n\nexport function functionFlags(\n isAsync: boolean,\n isGenerator: boolean,\n): ParamKind {\n return (\n (isAsync ? ParamKind.PARAM_AWAIT : 0) |\n (isGenerator ? ParamKind.PARAM_YIELD : 0)\n );\n}\n","import type { OptionFlags, Options } from \"../options.ts\";\nimport type State from \"../tokenizer/state.ts\";\nimport type { PluginsMap } from \"./index.ts\";\nimport type ScopeHandler from \"../util/scope.ts\";\nimport type ExpressionScopeHandler from \"../util/expression-scope.ts\";\nimport type ClassScopeHandler from \"../util/class-scope.ts\";\nimport type ProductionParameterHandler from \"../util/production-parameter.ts\";\nimport type {\n ParserPluginWithOptions,\n PluginConfig,\n PluginOptions,\n} from \"../typings.ts\";\nimport type * as N from \"../types.ts\";\n\nexport default class BaseParser {\n // Properties set by constructor in index.js\n declare options: Options;\n declare optionFlags: OptionFlags;\n declare inModule: boolean;\n declare scope: ScopeHandler;\n declare classScope: ClassScopeHandler;\n declare prodParam: ProductionParameterHandler;\n declare expressionScope: ExpressionScopeHandler;\n declare plugins: PluginsMap;\n declare filename: string | undefined | null;\n declare startIndex: number;\n // Names of exports store. `default` is stored as a name for both\n // `export default foo;` and `export { foo as default };`.\n declare exportedIdentifiers: Set;\n sawUnambiguousESM: boolean = false;\n ambiguousScriptDifferentAst: boolean = false;\n\n // Initialized by Tokenizer\n declare state: State;\n // input and length are not in state as they are constant and we do\n // not want to ever copy them, which happens if state gets cloned\n declare input: string;\n declare length: number;\n // Comment store for Program.comments\n declare comments: N.Comment[];\n\n sourceToOffsetPos(sourcePos: number) {\n return sourcePos + this.startIndex;\n }\n\n offsetToSourcePos(offsetPos: number) {\n return offsetPos - this.startIndex;\n }\n\n // This method accepts either a string (plugin name) or an array pair\n // (plugin name and options object). If an options object is given,\n // then each value is non-recursively checked for identity with that\n // plugin’s actual option value.\n hasPlugin(pluginConfig: PluginConfig): boolean {\n if (typeof pluginConfig === \"string\") {\n return this.plugins.has(pluginConfig);\n } else {\n const [pluginName, pluginOptions] = pluginConfig;\n if (!this.hasPlugin(pluginName)) {\n return false;\n }\n const actualOptions = this.plugins.get(pluginName);\n for (const key of Object.keys(\n pluginOptions,\n ) as (keyof typeof pluginOptions)[]) {\n if (actualOptions?.[key] !== pluginOptions[key]) {\n return false;\n }\n }\n return true;\n }\n }\n\n getPluginOption<\n PluginName extends ParserPluginWithOptions[0],\n OptionName extends keyof PluginOptions,\n >(plugin: PluginName, name: OptionName) {\n return (this.plugins.get(plugin) as null | PluginOptions)?.[\n name\n ];\n }\n}\n","/*:: declare var invariant; */\n\nimport BaseParser from \"./base.ts\";\nimport type { Comment, Node } from \"../types.ts\";\nimport * as charCodes from \"charcodes\";\nimport type { Undone } from \"./node.ts\";\n\n/**\n * A whitespace token containing comments\n */\nexport type CommentWhitespace = {\n /**\n * the start of the whitespace token.\n */\n start: number;\n /**\n * the end of the whitespace token.\n */\n end: number;\n /**\n * the containing comments\n */\n comments: Comment[];\n /**\n * the immediately preceding AST node of the whitespace token\n */\n leadingNode: Node | null;\n /**\n * the immediately following AST node of the whitespace token\n */\n trailingNode: Node | null;\n /**\n * the innermost AST node containing the whitespace with minimal size (|end - start|)\n */\n containingNode: Node | null;\n};\n\n/**\n * Merge comments with node's trailingComments or assign comments to be\n * trailingComments. New comments will be placed before old comments\n * because the commentStack is enumerated reversely.\n */\nfunction setTrailingComments(node: Undone, comments: Comment[]) {\n if (node.trailingComments === undefined) {\n node.trailingComments = comments;\n } else {\n node.trailingComments.unshift(...comments);\n }\n}\n\n/**\n * Merge comments with node's leadingComments or assign comments to be\n * leadingComments. New comments will be placed before old comments\n * because the commentStack is enumerated reversely.\n */\nfunction setLeadingComments(node: Undone, comments: Comment[]) {\n if (node.leadingComments === undefined) {\n node.leadingComments = comments;\n } else {\n node.leadingComments.unshift(...comments);\n }\n}\n\n/**\n * Merge comments with node's innerComments or assign comments to be\n * innerComments. New comments will be placed before old comments\n * because the commentStack is enumerated reversely.\n */\nexport function setInnerComments(node: Undone, comments: Comment[]) {\n if (node.innerComments === undefined) {\n node.innerComments = comments;\n } else {\n node.innerComments.unshift(...comments);\n }\n}\n\n/**\n * Given node and elements array, if elements has non-null element,\n * merge comments to its trailingComments, otherwise merge comments\n * to node's innerComments\n */\nfunction adjustInnerComments(\n node: Undone,\n elements: (Node | null)[],\n commentWS: CommentWhitespace,\n) {\n let lastElement = null;\n let i = elements.length;\n while (lastElement === null && i > 0) {\n lastElement = elements[--i];\n }\n if (lastElement === null || lastElement.start > commentWS.start) {\n setInnerComments(node, commentWS.comments);\n } else {\n setTrailingComments(lastElement, commentWS.comments);\n }\n}\n\nexport default class CommentsParser extends BaseParser {\n addComment(comment: Comment): void {\n if (this.filename) comment.loc.filename = this.filename;\n const { commentsLen } = this.state;\n if (this.comments.length !== commentsLen) {\n this.comments.length = commentsLen;\n }\n this.comments.push(comment);\n this.state.commentsLen++;\n }\n\n /**\n * Given a newly created AST node _n_, attach _n_ to a comment whitespace _w_ if applicable\n * {@see {@link CommentWhitespace}}\n */\n processComment(node: Node): void {\n const { commentStack } = this.state;\n const commentStackLength = commentStack.length;\n if (commentStackLength === 0) return;\n let i = commentStackLength - 1;\n const lastCommentWS = commentStack[i];\n\n if (lastCommentWS.start === node.end) {\n lastCommentWS.leadingNode = node;\n i--;\n }\n\n const { start: nodeStart } = node;\n // invariant: for all 0 <= j <= i, let c = commentStack[j], c must satisfy c.end < node.end\n for (; i >= 0; i--) {\n const commentWS = commentStack[i];\n const commentEnd = commentWS.end;\n if (commentEnd > nodeStart) {\n // by definition of commentWhiteSpace, this implies commentWS.start > nodeStart\n // so node can be a containingNode candidate. At this time we can finalize the comment\n // whitespace, because\n // 1) its leadingNode or trailingNode, if exists, will not change\n // 2) its containingNode have been assigned and will not change because it is the\n // innermost minimal-sized AST node\n commentWS.containingNode = node;\n this.finalizeComment(commentWS);\n commentStack.splice(i, 1);\n } else {\n if (commentEnd === nodeStart) {\n commentWS.trailingNode = node;\n }\n // stop the loop when commentEnd <= nodeStart\n break;\n }\n }\n }\n\n /**\n * Assign the comments of comment whitespaces to related AST nodes.\n * Also adjust innerComments following trailing comma.\n */\n finalizeComment(commentWS: CommentWhitespace) {\n const { comments } = commentWS;\n if (commentWS.leadingNode !== null || commentWS.trailingNode !== null) {\n if (commentWS.leadingNode !== null) {\n setTrailingComments(commentWS.leadingNode, comments);\n }\n if (commentWS.trailingNode !== null) {\n setLeadingComments(commentWS.trailingNode, comments);\n }\n } else {\n /*:: invariant(commentWS.containingNode !== null) */\n const node = commentWS.containingNode!;\n const commentStart = commentWS.start;\n if (\n this.input.charCodeAt(this.offsetToSourcePos(commentStart) - 1) ===\n charCodes.comma\n ) {\n // If a commentWhitespace follows a comma and the containingNode allows\n // list structures with trailing comma, merge it to the trailingComment\n // of the last non-null list element\n switch (node.type) {\n case \"ObjectExpression\":\n case \"ObjectPattern\":\n adjustInnerComments(node, node.properties, commentWS);\n break;\n case \"CallExpression\":\n case \"OptionalCallExpression\":\n adjustInnerComments(node, node.arguments, commentWS);\n break;\n case \"ImportExpression\":\n adjustInnerComments(\n node,\n [node.source, node.options ?? null],\n commentWS,\n );\n break;\n case \"FunctionDeclaration\":\n case \"FunctionExpression\":\n case \"ArrowFunctionExpression\":\n case \"ObjectMethod\":\n case \"ClassMethod\":\n case \"ClassPrivateMethod\":\n adjustInnerComments(node, node.params, commentWS);\n break;\n case \"ArrayExpression\":\n case \"ArrayPattern\":\n adjustInnerComments(node, node.elements, commentWS);\n break;\n case \"ExportNamedDeclaration\":\n case \"ImportDeclaration\":\n adjustInnerComments(node, node.specifiers, commentWS);\n break;\n case \"TSEnumDeclaration\":\n if (!process.env.BABEL_8_BREAKING) {\n adjustInnerComments(node, node.members!, commentWS);\n } else {\n setInnerComments(node, comments);\n }\n break;\n case \"TSEnumBody\":\n adjustInnerComments(node, node.members, commentWS);\n break;\n default: {\n if (!process.env.BABEL_8_BREAKING) {\n if (node.type === \"RecordExpression\") {\n adjustInnerComments(node, node.properties, commentWS);\n break;\n }\n if (node.type === \"TupleExpression\") {\n adjustInnerComments(node, node.elements, commentWS);\n break;\n }\n }\n setInnerComments(node, comments);\n }\n }\n } else {\n setInnerComments(node, comments);\n }\n }\n }\n\n /**\n * Drains remaining commentStack and applies finalizeComment\n * to each comment whitespace. Used only in parseExpression\n * where the top level AST node is _not_ Program\n * {@see {@link CommentsParser#finalizeComment}}\n */\n finalizeRemainingComments() {\n const { commentStack } = this.state;\n for (let i = commentStack.length - 1; i >= 0; i--) {\n this.finalizeComment(commentStack[i]);\n }\n this.state.commentStack = [];\n }\n\n /* eslint-disable no-irregular-whitespace */\n /**\n * Reset previous node trailing comments. Used in object / class\n * property parsing. We parse `async`, `static`, `set` and `get`\n * as an identifier but may reinterpret it into an async/static/accessor\n * method later. In this case the identifier is not part of the AST and we\n * should sync the knowledge to commentStacks\n *\n * For example, when parsing\n * ```\n * async /* 1 *​/ function f() {}\n * ```\n * the comment whitespace `/* 1 *​/` has leading node Identifier(async). When\n * we see the function token, we create a Function node and mark `/* 1 *​/` as\n * inner comments. So `/* 1 *​/` should be detached from the Identifier node.\n *\n * @param node the last finished AST node _before_ current token\n */\n /* eslint-enable no-irregular-whitespace */\n resetPreviousNodeTrailingComments(node: Node) {\n const { commentStack } = this.state;\n const { length } = commentStack;\n if (length === 0) return;\n const commentWS = commentStack[length - 1];\n if (commentWS.leadingNode === node) {\n commentWS.leadingNode = null;\n }\n }\n\n /**\n * Attach a node to the comment whitespaces right before/after\n * the given range.\n *\n * This is used to properly attach comments around parenthesized\n * expressions as leading/trailing comments of the inner expression.\n */\n takeSurroundingComments(node: Node, start: number, end: number) {\n const { commentStack } = this.state;\n const commentStackLength = commentStack.length;\n if (commentStackLength === 0) return;\n let i = commentStackLength - 1;\n\n for (; i >= 0; i--) {\n const commentWS = commentStack[i];\n const commentEnd = commentWS.end;\n const commentStart = commentWS.start;\n\n if (commentStart === end) {\n commentWS.leadingNode = node;\n } else if (commentEnd === start) {\n commentWS.trailingNode = node;\n } else if (commentEnd < start) {\n break;\n }\n }\n }\n}\n","import type { OptionsWithDefaults } from \"../options.ts\";\nimport type { CommentWhitespace } from \"../parser/comments\";\nimport { Position } from \"../util/location.ts\";\n\nimport { types as ct, type TokContext } from \"./context.ts\";\nimport { tt, type TokenType } from \"./types.ts\";\nimport type { Errors } from \"../parse-error.ts\";\nimport type { ParseError } from \"../parse-error.ts\";\n\nexport type DeferredStrictError =\n | typeof Errors.StrictNumericEscape\n | typeof Errors.StrictOctalLiteral;\n\ntype TopicContextState = {\n // When a topic binding has been currently established,\n // then this is 1. Otherwise, it is 0. This is forwards compatible\n // with a future plugin for multiple lexical topics.\n maxNumOfResolvableTopics: number;\n // When a topic binding has been currently established, and if that binding\n // has been used as a topic reference `#`, then this is 0. Otherwise, it is\n // `null`. This is forwards compatible with a future plugin for multiple\n // lexical topics.\n maxTopicIndex: null | 0;\n};\n\nexport const enum LoopLabelKind {\n Loop = 1,\n Switch = 2,\n}\n\ndeclare const bit: import(\"../../../../scripts/babel-plugin-bit-decorator/types.d.ts\").BitDecorator;\n\nexport default class State {\n @bit.storage flags: number = 0;\n\n @bit accessor strict = false;\n\n startIndex!: number;\n curLine!: number;\n lineStart!: number;\n\n // And, if locations are used, the {line, column} object\n // corresponding to those offsets\n startLoc!: Position;\n endLoc!: Position;\n\n init({\n strictMode,\n sourceType,\n startIndex,\n startLine,\n startColumn,\n }: OptionsWithDefaults): void {\n this.strict =\n strictMode === false\n ? false\n : strictMode === true\n ? true\n : sourceType === \"module\";\n\n this.startIndex = startIndex;\n this.curLine = startLine;\n this.lineStart = -startColumn;\n this.startLoc = this.endLoc = new Position(\n startLine,\n startColumn,\n startIndex,\n );\n }\n\n errors: ParseError[] = [];\n\n // Used to signify the start of a potential arrow function\n potentialArrowAt: number = -1;\n\n // Used to signify the start of an expression which looks like a\n // typed arrow function, but it isn't\n // e.g. a ? (b) : c => d\n // ^\n noArrowAt: number[] = [];\n\n // Used to signify the start of an expression whose params, if it looks like\n // an arrow function, shouldn't be converted to assignable nodes.\n // This is used to defer the validation of typed arrow functions inside\n // conditional expressions.\n // e.g. a ? (b) : c => d\n // ^\n noArrowParamsConversionAt: number[] = [];\n\n // Flags to track\n @bit accessor maybeInArrowParameters = false;\n @bit accessor inType = false;\n @bit accessor noAnonFunctionType = false;\n @bit accessor hasFlowComment = false;\n @bit accessor isAmbientContext = false;\n @bit accessor inAbstractClass = false;\n @bit accessor inDisallowConditionalTypesContext = false;\n\n // For the Hack-style pipelines plugin\n topicContext: TopicContextState = {\n maxNumOfResolvableTopics: 0,\n maxTopicIndex: null,\n };\n\n // For the F#-style pipelines plugin\n @bit accessor soloAwait = false;\n @bit accessor inFSharpPipelineDirectBody = false;\n\n // Labels in scope.\n labels: {\n kind: LoopLabelKind | null;\n name?: string | null;\n statementStart?: number;\n }[] = [];\n\n commentsLen = 0;\n // Comment attachment store\n commentStack: CommentWhitespace[] = [];\n\n // The current position of the tokenizer in the input.\n pos: number = 0;\n\n // Properties of the current token:\n // Its type\n type: TokenType = tt.eof;\n\n // For tokens that include more information than their type, the value\n value: any = null;\n\n // Its start and end offset\n start: number = 0;\n end: number = 0;\n\n // Position information for the previous token\n // this is initialized when generating the second token.\n lastTokEndLoc: Position | null = null;\n // this is initialized when generating the second token.\n lastTokStartLoc: Position | null = null;\n\n // The context stack is used to track whether the apostrophe \"`\" starts\n // or ends a string template\n context: TokContext[] = [ct.brace];\n\n // Used to track whether a JSX element is allowed to form\n @bit accessor canStartJSXElement = true;\n\n // Used to signal to callers of `readWord1` whether the word\n // contained any escape sequences. This is needed because words with\n // escape sequences must not be interpreted as keywords.\n @bit accessor containsEsc = false;\n\n // Used to track invalid escape sequences in template literals,\n // that must be reported if the template is not tagged.\n firstInvalidTemplateEscapePos: null | Position = null;\n\n @bit accessor hasTopLevelAwait = false;\n\n // This property is used to track the following errors\n // - StrictNumericEscape\n // - StrictOctalLiteral\n //\n // in a literal that occurs prior to/immediately after a \"use strict\" directive.\n\n // todo(JLHwung): set strictErrors to null and avoid recording string errors\n // after a non-directive is parsed\n strictErrors = new Map();\n\n // Tokens length in token store\n tokensLength: number = 0;\n\n /**\n * When we add a new property, we must manually update the `clone` method\n * @see State#clone\n */\n\n curPosition(): Position {\n return new Position(\n this.curLine,\n this.pos - this.lineStart,\n this.pos + this.startIndex,\n );\n }\n\n clone(): State {\n const state = new State();\n state.flags = this.flags;\n state.startIndex = this.startIndex;\n state.curLine = this.curLine;\n state.lineStart = this.lineStart;\n state.startLoc = this.startLoc;\n state.endLoc = this.endLoc;\n state.errors = this.errors.slice();\n state.potentialArrowAt = this.potentialArrowAt;\n state.noArrowAt = this.noArrowAt.slice();\n state.noArrowParamsConversionAt = this.noArrowParamsConversionAt.slice();\n state.topicContext = this.topicContext;\n state.labels = this.labels.slice();\n state.commentsLen = this.commentsLen;\n state.commentStack = this.commentStack.slice();\n state.pos = this.pos;\n state.type = this.type;\n state.value = this.value;\n state.start = this.start;\n state.end = this.end;\n state.lastTokEndLoc = this.lastTokEndLoc;\n state.lastTokStartLoc = this.lastTokStartLoc;\n state.context = this.context.slice();\n state.firstInvalidTemplateEscapePos = this.firstInvalidTemplateEscapePos;\n state.strictErrors = this.strictErrors;\n state.tokensLength = this.tokensLength;\n\n return state;\n }\n}\n\nexport type LookaheadState = {\n pos: number;\n value: any;\n type: TokenType;\n start: number;\n end: number;\n context: TokContext[];\n startLoc: Position;\n lastTokEndLoc: Position | null;\n curLine: number;\n lineStart: number;\n curPosition: State[\"curPosition\"];\n /* Used only in readToken_mult_modulo */\n inType: boolean;\n // These boolean properties are not initialized in createLookaheadState()\n // instead they will only be set by the tokenizer\n containsEsc?: boolean;\n};\n","// We inline this package\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport * as charCodes from \"charcodes\";\n\n// The following character codes are forbidden from being\n// an immediate sibling of NumericLiteralSeparator _\nconst forbiddenNumericSeparatorSiblings = {\n decBinOct: new Set([\n charCodes.dot,\n charCodes.uppercaseB,\n charCodes.uppercaseE,\n charCodes.uppercaseO,\n charCodes.underscore, // multiple separators are not allowed\n charCodes.lowercaseB,\n charCodes.lowercaseE,\n charCodes.lowercaseO,\n ]),\n hex: new Set([\n charCodes.dot,\n charCodes.uppercaseX,\n charCodes.underscore, // multiple separators are not allowed\n charCodes.lowercaseX,\n ]),\n};\n\nconst isAllowedNumericSeparatorSibling = {\n // 0 - 1\n bin: (ch: number) => ch === charCodes.digit0 || ch === charCodes.digit1,\n\n // 0 - 7\n oct: (ch: number) => ch >= charCodes.digit0 && ch <= charCodes.digit7,\n\n // 0 - 9\n dec: (ch: number) => ch >= charCodes.digit0 && ch <= charCodes.digit9,\n\n // 0 - 9, A - F, a - f,\n hex: (ch: number) =>\n (ch >= charCodes.digit0 && ch <= charCodes.digit9) ||\n (ch >= charCodes.uppercaseA && ch <= charCodes.uppercaseF) ||\n (ch >= charCodes.lowercaseA && ch <= charCodes.lowercaseF),\n};\n\nexport type StringContentsErrorHandlers = EscapedCharErrorHandlers & {\n unterminated(\n initialPos: number,\n initialLineStart: number,\n initialCurLine: number,\n ): void;\n};\n\nexport function readStringContents(\n type: \"single\" | \"double\" | \"template\",\n input: string,\n pos: number,\n lineStart: number,\n curLine: number,\n errors: StringContentsErrorHandlers,\n) {\n const initialPos = pos;\n const initialLineStart = lineStart;\n const initialCurLine = curLine;\n\n let out = \"\";\n let firstInvalidLoc = null;\n let chunkStart = pos;\n const { length } = input;\n for (;;) {\n if (pos >= length) {\n errors.unterminated(initialPos, initialLineStart, initialCurLine);\n out += input.slice(chunkStart, pos);\n break;\n }\n const ch = input.charCodeAt(pos);\n if (isStringEnd(type, ch, input, pos)) {\n out += input.slice(chunkStart, pos);\n break;\n }\n if (ch === charCodes.backslash) {\n out += input.slice(chunkStart, pos);\n const res = readEscapedChar(\n input,\n pos,\n lineStart,\n curLine,\n type === \"template\",\n errors,\n );\n if (res.ch === null && !firstInvalidLoc) {\n firstInvalidLoc = { pos, lineStart, curLine };\n } else {\n out += res.ch;\n }\n ({ pos, lineStart, curLine } = res);\n chunkStart = pos;\n } else if (\n ch === charCodes.lineSeparator ||\n ch === charCodes.paragraphSeparator\n ) {\n ++pos;\n ++curLine;\n lineStart = pos;\n } else if (ch === charCodes.lineFeed || ch === charCodes.carriageReturn) {\n if (type === \"template\") {\n out += input.slice(chunkStart, pos) + \"\\n\";\n ++pos;\n if (\n ch === charCodes.carriageReturn &&\n input.charCodeAt(pos) === charCodes.lineFeed\n ) {\n ++pos;\n }\n ++curLine;\n chunkStart = lineStart = pos;\n } else {\n errors.unterminated(initialPos, initialLineStart, initialCurLine);\n }\n } else {\n ++pos;\n }\n }\n return process.env.BABEL_8_BREAKING\n ? { pos, str: out, firstInvalidLoc, lineStart, curLine }\n : {\n pos,\n str: out,\n firstInvalidLoc,\n lineStart,\n curLine,\n containsInvalid: !!firstInvalidLoc,\n };\n}\n\nfunction isStringEnd(\n type: \"single\" | \"double\" | \"template\",\n ch: number,\n input: string,\n pos: number,\n) {\n if (type === \"template\") {\n return (\n ch === charCodes.graveAccent ||\n (ch === charCodes.dollarSign &&\n input.charCodeAt(pos + 1) === charCodes.leftCurlyBrace)\n );\n }\n return (\n ch === (type === \"double\" ? charCodes.quotationMark : charCodes.apostrophe)\n );\n}\n\ntype EscapedCharErrorHandlers = HexCharErrorHandlers &\n CodePointErrorHandlers & {\n strictNumericEscape(pos: number, lineStart: number, curLine: number): void;\n };\n\nfunction readEscapedChar(\n input: string,\n pos: number,\n lineStart: number,\n curLine: number,\n inTemplate: boolean,\n errors: EscapedCharErrorHandlers,\n) {\n const throwOnInvalid = !inTemplate;\n pos++; // skip '\\'\n\n const res = (ch: string | null) => ({ pos, ch, lineStart, curLine });\n\n const ch = input.charCodeAt(pos++);\n switch (ch) {\n case charCodes.lowercaseN:\n return res(\"\\n\");\n case charCodes.lowercaseR:\n return res(\"\\r\");\n case charCodes.lowercaseX: {\n let code;\n ({ code, pos } = readHexChar(\n input,\n pos,\n lineStart,\n curLine,\n 2,\n false,\n throwOnInvalid,\n errors,\n ));\n return res(code === null ? null : String.fromCharCode(code));\n }\n case charCodes.lowercaseU: {\n let code;\n ({ code, pos } = readCodePoint(\n input,\n pos,\n lineStart,\n curLine,\n throwOnInvalid,\n errors,\n ));\n return res(code === null ? null : String.fromCodePoint(code));\n }\n case charCodes.lowercaseT:\n return res(\"\\t\");\n case charCodes.lowercaseB:\n return res(\"\\b\");\n case charCodes.lowercaseV:\n return res(\"\\u000b\");\n case charCodes.lowercaseF:\n return res(\"\\f\");\n case charCodes.carriageReturn:\n if (input.charCodeAt(pos) === charCodes.lineFeed) {\n ++pos;\n }\n // fall through\n case charCodes.lineFeed:\n lineStart = pos;\n ++curLine;\n // fall through\n case charCodes.lineSeparator:\n case charCodes.paragraphSeparator:\n return res(\"\");\n case charCodes.digit8:\n case charCodes.digit9:\n if (inTemplate) {\n return res(null);\n } else {\n errors.strictNumericEscape(pos - 1, lineStart, curLine);\n }\n // fall through\n default:\n if (ch >= charCodes.digit0 && ch <= charCodes.digit7) {\n const startPos = pos - 1;\n const match = /^[0-7]+/.exec(input.slice(startPos, pos + 2));\n\n let octalStr = match[0];\n\n let octal = parseInt(octalStr, 8);\n if (octal > 255) {\n octalStr = octalStr.slice(0, -1);\n octal = parseInt(octalStr, 8);\n }\n pos += octalStr.length - 1;\n const next = input.charCodeAt(pos);\n if (\n octalStr !== \"0\" ||\n next === charCodes.digit8 ||\n next === charCodes.digit9\n ) {\n if (inTemplate) {\n return res(null);\n } else {\n errors.strictNumericEscape(startPos, lineStart, curLine);\n }\n }\n\n return res(String.fromCharCode(octal));\n }\n\n return res(String.fromCharCode(ch));\n }\n}\n\ntype HexCharErrorHandlers = IntErrorHandlers & {\n invalidEscapeSequence(pos: number, lineStart: number, curLine: number): void;\n};\n\n// Used to read character escape sequences ('\\x', '\\u').\nfunction readHexChar(\n input: string,\n pos: number,\n lineStart: number,\n curLine: number,\n len: number,\n forceLen: boolean,\n throwOnInvalid: boolean,\n errors: HexCharErrorHandlers,\n) {\n const initialPos = pos;\n let n;\n ({ n, pos } = readInt(\n input,\n pos,\n lineStart,\n curLine,\n 16,\n len,\n forceLen,\n false,\n errors,\n /* bailOnError */ !throwOnInvalid,\n ));\n if (n === null) {\n if (throwOnInvalid) {\n errors.invalidEscapeSequence(initialPos, lineStart, curLine);\n } else {\n pos = initialPos - 1;\n }\n }\n return { code: n, pos };\n}\n\nexport type IntErrorHandlers = {\n numericSeparatorInEscapeSequence(\n pos: number,\n lineStart: number,\n curLine: number,\n ): void;\n unexpectedNumericSeparator(\n pos: number,\n lineStart: number,\n curLine: number,\n ): void;\n // It can return \"true\" to indicate that the error was handled\n // and the int parsing should continue.\n invalidDigit(\n pos: number,\n lineStart: number,\n curLine: number,\n radix: number,\n ): boolean;\n};\n\nexport function readInt(\n input: string,\n pos: number,\n lineStart: number,\n curLine: number,\n radix: number,\n len: number | undefined,\n forceLen: boolean,\n allowNumSeparator: boolean | \"bail\",\n errors: IntErrorHandlers,\n bailOnError: boolean,\n) {\n const start = pos;\n const forbiddenSiblings =\n radix === 16\n ? forbiddenNumericSeparatorSiblings.hex\n : forbiddenNumericSeparatorSiblings.decBinOct;\n const isAllowedSibling =\n radix === 16\n ? isAllowedNumericSeparatorSibling.hex\n : radix === 10\n ? isAllowedNumericSeparatorSibling.dec\n : radix === 8\n ? isAllowedNumericSeparatorSibling.oct\n : isAllowedNumericSeparatorSibling.bin;\n\n let invalid = false;\n let total = 0;\n\n for (let i = 0, e = len == null ? Infinity : len; i < e; ++i) {\n const code = input.charCodeAt(pos);\n let val;\n\n if (code === charCodes.underscore && allowNumSeparator !== \"bail\") {\n const prev = input.charCodeAt(pos - 1);\n const next = input.charCodeAt(pos + 1);\n\n if (!allowNumSeparator) {\n if (bailOnError) return { n: null, pos };\n errors.numericSeparatorInEscapeSequence(pos, lineStart, curLine);\n } else if (\n Number.isNaN(next) ||\n !isAllowedSibling(next) ||\n forbiddenSiblings.has(prev) ||\n forbiddenSiblings.has(next)\n ) {\n if (bailOnError) return { n: null, pos };\n errors.unexpectedNumericSeparator(pos, lineStart, curLine);\n }\n\n // Ignore this _ character\n ++pos;\n continue;\n }\n\n if (code >= charCodes.lowercaseA) {\n val = code - charCodes.lowercaseA + charCodes.lineFeed;\n } else if (code >= charCodes.uppercaseA) {\n val = code - charCodes.uppercaseA + charCodes.lineFeed;\n } else if (charCodes.isDigit(code)) {\n val = code - charCodes.digit0; // 0-9\n } else {\n val = Infinity;\n }\n if (val >= radix) {\n // If we found a digit which is too big, errors.invalidDigit can return true to avoid\n // breaking the loop (this is used for error recovery).\n if (val <= 9 && bailOnError) {\n return { n: null, pos };\n } else if (\n val <= 9 &&\n errors.invalidDigit(pos, lineStart, curLine, radix)\n ) {\n val = 0;\n } else if (forceLen) {\n val = 0;\n invalid = true;\n } else {\n break;\n }\n }\n ++pos;\n total = total * radix + val;\n }\n if (pos === start || (len != null && pos - start !== len) || invalid) {\n return { n: null, pos };\n }\n\n return { n: total, pos };\n}\n\nexport type CodePointErrorHandlers = HexCharErrorHandlers & {\n invalidCodePoint(pos: number, lineStart: number, curLine: number): void;\n};\n\nexport function readCodePoint(\n input: string,\n pos: number,\n lineStart: number,\n curLine: number,\n throwOnInvalid: boolean,\n errors: CodePointErrorHandlers,\n) {\n const ch = input.charCodeAt(pos);\n let code;\n\n if (ch === charCodes.leftCurlyBrace) {\n ++pos;\n ({ code, pos } = readHexChar(\n input,\n pos,\n lineStart,\n curLine,\n input.indexOf(\"}\", pos) - pos,\n true,\n throwOnInvalid,\n errors,\n ));\n ++pos;\n if (code !== null && code > 0x10ffff) {\n if (throwOnInvalid) {\n errors.invalidCodePoint(pos, lineStart, curLine);\n } else {\n return { code: null, pos };\n }\n }\n } else {\n ({ code, pos } = readHexChar(\n input,\n pos,\n lineStart,\n curLine,\n 4,\n false,\n throwOnInvalid,\n errors,\n ));\n }\n return { code, pos };\n}\n","/*:: declare var invariant; */\n\nimport type { OptionsWithDefaults } from \"../options.ts\";\nimport { OptionFlags } from \"../options.ts\";\nimport {\n Position,\n SourceLocation,\n createPositionWithColumnOffset,\n} from \"../util/location.ts\";\nimport CommentsParser, { type CommentWhitespace } from \"../parser/comments.ts\";\nimport type * as N from \"../types.ts\";\nimport * as charCodes from \"charcodes\";\nimport { isIdentifierStart, isIdentifierChar } from \"../util/identifier.ts\";\nimport {\n tokenIsKeyword,\n tokenLabelName,\n tt,\n keywords as keywordTypes,\n type TokenType,\n} from \"./types.ts\";\nimport type { TokContext } from \"./context.ts\";\nimport {\n Errors,\n type ParseError,\n type ParseErrorConstructor,\n} from \"../parse-error.ts\";\nimport {\n lineBreakG,\n isNewLine,\n isWhitespace,\n skipWhiteSpace,\n skipWhiteSpaceInLine,\n} from \"../util/whitespace.ts\";\nimport State from \"./state.ts\";\nimport type { LookaheadState, DeferredStrictError } from \"./state.ts\";\nimport type { Undone } from \"../parser/node.ts\";\nimport type { Node } from \"../types.ts\";\n\nimport {\n readInt,\n readCodePoint,\n readStringContents,\n type IntErrorHandlers,\n type CodePointErrorHandlers,\n type StringContentsErrorHandlers,\n} from \"@babel/helper-string-parser\";\n\nimport type { Plugin } from \"../typings.ts\";\n\nfunction buildPosition(pos: number, lineStart: number, curLine: number) {\n return new Position(curLine, pos - lineStart, pos);\n}\n\nconst VALID_REGEX_FLAGS = new Set([\n charCodes.lowercaseG,\n charCodes.lowercaseM,\n charCodes.lowercaseS,\n charCodes.lowercaseI,\n charCodes.lowercaseY,\n charCodes.lowercaseU,\n charCodes.lowercaseD,\n charCodes.lowercaseV,\n]);\n\n// Object type used to represent tokens. Note that normally, tokens\n// simply exist as properties on the parser object. This is only\n// used for the onToken callback and the external tokenizer.\n\nexport class Token {\n constructor(state: State) {\n const startIndex = state.startIndex || 0;\n this.type = state.type;\n this.value = state.value;\n this.start = startIndex + state.start;\n this.end = startIndex + state.end;\n this.loc = new SourceLocation(state.startLoc, state.endLoc);\n }\n\n declare type: TokenType;\n declare value: any;\n declare start: number;\n declare end: number;\n declare loc: SourceLocation;\n}\n\n// ## Tokenizer\n\nexport default abstract class Tokenizer extends CommentsParser {\n isLookahead: boolean;\n\n // Token store.\n tokens: (Token | N.Comment)[] = [];\n\n constructor(options: OptionsWithDefaults, input: string) {\n super();\n this.state = new State();\n this.state.init(options);\n this.input = input;\n this.length = input.length;\n this.comments = [];\n this.isLookahead = false;\n }\n\n pushToken(token: Token | N.Comment) {\n // Pop out invalid tokens trapped by try-catch parsing.\n // Those parsing branches are mainly created by typescript and flow plugins.\n this.tokens.length = this.state.tokensLength;\n this.tokens.push(token);\n ++this.state.tokensLength;\n }\n\n // Move to the next token\n\n next(): void {\n this.checkKeywordEscapes();\n if (this.optionFlags & OptionFlags.Tokens) {\n this.pushToken(new Token(this.state));\n }\n\n this.state.lastTokEndLoc = this.state.endLoc;\n this.state.lastTokStartLoc = this.state.startLoc;\n this.nextToken();\n }\n\n eat(type: TokenType): boolean {\n if (this.match(type)) {\n this.next();\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * Whether current token matches given type\n */\n match(type: TokenType): boolean {\n return this.state.type === type;\n }\n\n /**\n * Create a LookaheadState from current parser state\n */\n createLookaheadState(state: State): LookaheadState {\n return {\n pos: state.pos,\n value: null,\n type: state.type,\n start: state.start,\n end: state.end,\n context: [this.curContext()],\n inType: state.inType,\n startLoc: state.startLoc,\n lastTokEndLoc: state.lastTokEndLoc,\n curLine: state.curLine,\n lineStart: state.lineStart,\n curPosition: state.curPosition,\n };\n }\n\n /**\n * lookahead peeks the next token, skipping changes to token context and\n * comment stack. For performance it returns a limited LookaheadState\n * instead of full parser state.\n *\n * The { column, line } Loc info is not included in lookahead since such usage\n * is rare. Although it may return other location properties e.g. `curLine` and\n * `lineStart`, these properties are not listed in the LookaheadState interface\n * and thus the returned value is _NOT_ reliable.\n *\n * The tokenizer should make best efforts to avoid using any parser state\n * other than those defined in LookaheadState\n */\n lookahead(): LookaheadState {\n const old = this.state;\n // @ts-expect-error For performance we use a simplified tokenizer state structure\n this.state = this.createLookaheadState(old);\n\n this.isLookahead = true;\n this.nextToken();\n this.isLookahead = false;\n\n const curr = this.state;\n this.state = old;\n return curr;\n }\n\n nextTokenStart(): number {\n return this.nextTokenStartSince(this.state.pos);\n }\n\n nextTokenStartSince(pos: number): number {\n skipWhiteSpace.lastIndex = pos;\n return skipWhiteSpace.test(this.input) ? skipWhiteSpace.lastIndex : pos;\n }\n\n lookaheadCharCode(): number {\n return this.lookaheadCharCodeSince(this.state.pos);\n }\n\n lookaheadCharCodeSince(pos: number): number {\n return this.input.charCodeAt(this.nextTokenStartSince(pos));\n }\n\n /**\n * Similar to nextToken, but it will stop at line break when it is seen before the next token\n *\n * @returns {number} position of the next token start or line break, whichever is seen first.\n * @memberof Tokenizer\n */\n nextTokenInLineStart(): number {\n return this.nextTokenInLineStartSince(this.state.pos);\n }\n\n nextTokenInLineStartSince(pos: number): number {\n skipWhiteSpaceInLine.lastIndex = pos;\n return skipWhiteSpaceInLine.test(this.input)\n ? skipWhiteSpaceInLine.lastIndex\n : pos;\n }\n\n /**\n * Similar to lookaheadCharCode, but it will return the char code of line break if it is\n * seen before the next token\n *\n * @returns {number} char code of the next token start or line break, whichever is seen first.\n * @memberof Tokenizer\n */\n lookaheadInLineCharCode(): number {\n return this.input.charCodeAt(this.nextTokenInLineStart());\n }\n\n codePointAtPos(pos: number): number {\n // The implementation is based on\n // https://source.chromium.org/chromium/chromium/src/+/master:v8/src/builtins/builtins-string-gen.cc;l=1455;drc=221e331b49dfefadbc6fa40b0c68e6f97606d0b3;bpv=0;bpt=1\n // We reimplement `codePointAt` because `codePointAt` is a V8 builtin which is not inlined by TurboFan (as of M91)\n // since `input` is mostly ASCII, an inlined `charCodeAt` wins here\n let cp = this.input.charCodeAt(pos);\n if ((cp & 0xfc00) === 0xd800 && ++pos < this.input.length) {\n const trail = this.input.charCodeAt(pos);\n if ((trail & 0xfc00) === 0xdc00) {\n cp = 0x10000 + ((cp & 0x3ff) << 10) + (trail & 0x3ff);\n }\n }\n return cp;\n }\n\n // Toggle strict mode. Re-reads the next number or string to please\n // pedantic tests (`\"use strict\"; 010;` should fail).\n\n setStrict(strict: boolean): void {\n this.state.strict = strict;\n if (strict) {\n // Throw an error for any string decimal escape found before/immediately\n // after a \"use strict\" directive. Strict mode will be set at parse\n // time for any literals that occur after the next node of the strict\n // directive.\n this.state.strictErrors.forEach(([toParseError, at]) =>\n this.raise(toParseError, at),\n );\n this.state.strictErrors.clear();\n }\n }\n\n curContext(): TokContext {\n return this.state.context[this.state.context.length - 1];\n }\n\n // Read a single token, updating the parser object's token-related properties.\n nextToken(): void {\n this.skipSpace();\n this.state.start = this.state.pos;\n if (!this.isLookahead) this.state.startLoc = this.state.curPosition();\n if (this.state.pos >= this.length) {\n this.finishToken(tt.eof);\n return;\n }\n\n this.getTokenFromCode(this.codePointAtPos(this.state.pos));\n }\n\n // Skips a block comment, whose end is marked by commentEnd.\n // *-/ is used by the Flow plugin, when parsing block comments nested\n // inside Flow comments.\n skipBlockComment(commentEnd: \"*/\" | \"*-/\"): N.CommentBlock | undefined {\n let startLoc;\n if (!this.isLookahead) startLoc = this.state.curPosition();\n const start = this.state.pos;\n const end = this.input.indexOf(commentEnd, start + 2);\n if (end === -1) {\n // We have to call this again here because startLoc may not be set...\n // This seems to be for performance reasons:\n // https://github.com/babel/babel/commit/acf2a10899f696a8aaf34df78bf9725b5ea7f2da\n throw this.raise(Errors.UnterminatedComment, this.state.curPosition());\n }\n\n this.state.pos = end + commentEnd.length;\n lineBreakG.lastIndex = start + 2;\n while (lineBreakG.test(this.input) && lineBreakG.lastIndex <= end) {\n ++this.state.curLine;\n this.state.lineStart = lineBreakG.lastIndex;\n }\n\n // If we are doing a lookahead right now we need to advance the position (above code)\n // but we do not want to push the comment to the state.\n if (this.isLookahead) return;\n /*:: invariant(startLoc) */\n\n const comment: N.CommentBlock = {\n type: \"CommentBlock\",\n value: this.input.slice(start + 2, end),\n start: this.sourceToOffsetPos(start),\n end: this.sourceToOffsetPos(end + commentEnd.length),\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n loc: new SourceLocation(startLoc!, this.state.curPosition()),\n };\n if (this.optionFlags & OptionFlags.Tokens) this.pushToken(comment);\n return comment;\n }\n\n skipLineComment(startSkip: number): N.CommentLine | undefined {\n const start = this.state.pos;\n let startLoc;\n if (!this.isLookahead) startLoc = this.state.curPosition();\n let ch = this.input.charCodeAt((this.state.pos += startSkip));\n if (this.state.pos < this.length) {\n while (!isNewLine(ch) && ++this.state.pos < this.length) {\n ch = this.input.charCodeAt(this.state.pos);\n }\n }\n\n // If we are doing a lookahead right now we need to advance the position (above code)\n // but we do not want to push the comment to the state.\n if (this.isLookahead) return;\n\n const end = this.state.pos;\n const value = this.input.slice(start + startSkip, end);\n\n const comment: N.CommentLine = {\n type: \"CommentLine\",\n value,\n start: this.sourceToOffsetPos(start),\n end: this.sourceToOffsetPos(end),\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n loc: new SourceLocation(startLoc!, this.state.curPosition()),\n };\n if (this.optionFlags & OptionFlags.Tokens) this.pushToken(comment);\n return comment;\n }\n\n // Called at the start of the parse and after every token. Skips\n // whitespace and comments, and.\n\n skipSpace(): void {\n const spaceStart = this.state.pos;\n const comments: N.Comment[] | null =\n this.optionFlags & OptionFlags.AttachComment ? [] : null;\n loop: while (this.state.pos < this.length) {\n const ch = this.input.charCodeAt(this.state.pos);\n switch (ch) {\n case charCodes.space:\n case charCodes.nonBreakingSpace:\n case charCodes.tab:\n ++this.state.pos;\n break;\n case charCodes.carriageReturn:\n if (\n this.input.charCodeAt(this.state.pos + 1) === charCodes.lineFeed\n ) {\n ++this.state.pos;\n }\n // fall through\n case charCodes.lineFeed:\n case charCodes.lineSeparator:\n case charCodes.paragraphSeparator:\n ++this.state.pos;\n ++this.state.curLine;\n this.state.lineStart = this.state.pos;\n break;\n\n case charCodes.slash:\n switch (this.input.charCodeAt(this.state.pos + 1)) {\n case charCodes.asterisk: {\n const comment = this.skipBlockComment(\"*/\");\n if (comment !== undefined) {\n this.addComment(comment);\n comments?.push(comment);\n }\n break;\n }\n\n case charCodes.slash: {\n const comment = this.skipLineComment(2);\n if (comment !== undefined) {\n this.addComment(comment);\n comments?.push(comment);\n }\n break;\n }\n\n default:\n break loop;\n }\n break;\n\n default:\n if (isWhitespace(ch)) {\n ++this.state.pos;\n } else if (\n ch === charCodes.dash &&\n !this.inModule &&\n this.optionFlags & OptionFlags.AnnexB\n ) {\n const pos = this.state.pos;\n if (\n this.input.charCodeAt(pos + 1) === charCodes.dash &&\n this.input.charCodeAt(pos + 2) === charCodes.greaterThan &&\n (spaceStart === 0 || this.state.lineStart > spaceStart)\n ) {\n // A `-->` line comment\n const comment = this.skipLineComment(3);\n if (comment !== undefined) {\n this.addComment(comment);\n comments?.push(comment);\n }\n } else {\n break loop;\n }\n } else if (\n ch === charCodes.lessThan &&\n !this.inModule &&\n this.optionFlags & OptionFlags.AnnexB\n ) {\n const pos = this.state.pos;\n if (\n this.input.charCodeAt(pos + 1) === charCodes.exclamationMark &&\n this.input.charCodeAt(pos + 2) === charCodes.dash &&\n this.input.charCodeAt(pos + 3) === charCodes.dash\n ) {\n // `")}function gr(){this.token(14,"\n\n return {\n type: 'CDC',\n loc: this.getLocation(start, this.tokenStart)\n };\n}\n\nexport function generate() {\n this.token(CDC, '-->');\n}\n", "import { CDO } from '../../tokenizer/index.js';\n\nexport const name = 'CDO';\nexport const structure = [];\n\nexport function parse() {\n const start = this.tokenStart;\n\n this.eat(CDO); // \n child = this.CDC();\n break;\n\n // CSS Syntax Module Level 3\n // \u00A72.2 Error handling\n // At the \"top level\" of a stylesheet, an starts an at-rule.\n case AtKeyword:\n child = this.parseWithFallback(this.Atrule, consumeRaw);\n break;\n\n // Anything else starts a qualified rule ...\n default:\n child = this.parseWithFallback(this.Rule, consumeRaw);\n }\n\n children.push(child);\n }\n\n return {\n type: 'StyleSheet',\n loc: this.getLocation(start, this.tokenStart),\n children\n };\n}\n\nexport function generate(node) {\n this.children(node);\n}\n", "import {\n LeftParenthesis,\n RightParenthesis\n} from '../../tokenizer/index.js';\n\nexport const name = 'SupportsDeclaration';\nexport const structure = {\n declaration: 'Declaration'\n};\n\nexport function parse() {\n const start = this.tokenStart;\n\n this.eat(LeftParenthesis);\n this.skipSC();\n\n const declaration = this.Declaration();\n\n if (!this.eof) {\n this.eat(RightParenthesis);\n }\n\n return {\n type: 'SupportsDeclaration',\n loc: this.getLocation(start, this.tokenStart),\n declaration\n };\n}\n\nexport function generate(node) {\n this.token(LeftParenthesis, '(');\n this.node(node.declaration);\n this.token(RightParenthesis, ')');\n}\n", "import { Ident } from '../../tokenizer/index.js';\n\nconst ASTERISK = 0x002A; // U+002A ASTERISK (*)\nconst VERTICALLINE = 0x007C; // U+007C VERTICAL LINE (|)\n\nfunction eatIdentifierOrAsterisk() {\n if (this.tokenType !== Ident &&\n this.isDelim(ASTERISK) === false) {\n this.error('Identifier or asterisk is expected');\n }\n\n this.next();\n}\n\nexport const name = 'TypeSelector';\nexport const structure = {\n name: String\n};\n\n// ident\n// ident|ident\n// ident|*\n// *\n// *|ident\n// *|*\n// |ident\n// |*\nexport function parse() {\n const start = this.tokenStart;\n\n if (this.isDelim(VERTICALLINE)) {\n this.next();\n eatIdentifierOrAsterisk.call(this);\n } else {\n eatIdentifierOrAsterisk.call(this);\n\n if (this.isDelim(VERTICALLINE)) {\n this.next();\n eatIdentifierOrAsterisk.call(this);\n }\n }\n\n return {\n type: 'TypeSelector',\n loc: this.getLocation(start, this.tokenStart),\n name: this.substrToCursor(start)\n };\n}\n\nexport function generate(node) {\n this.tokenize(node.name);\n}\n", "import {\n isHexDigit,\n Ident,\n Number,\n Dimension\n} from '../../tokenizer/index.js';\n\nconst PLUSSIGN = 0x002B; // U+002B PLUS SIGN (+)\nconst HYPHENMINUS = 0x002D; // U+002D HYPHEN-MINUS (-)\nconst QUESTIONMARK = 0x003F; // U+003F QUESTION MARK (?)\n\nfunction eatHexSequence(offset, allowDash) {\n let len = 0;\n\n for (let pos = this.tokenStart + offset; pos < this.tokenEnd; pos++) {\n const code = this.charCodeAt(pos);\n\n if (code === HYPHENMINUS && allowDash && len !== 0) {\n eatHexSequence.call(this, offset + len + 1, false);\n return -1;\n }\n\n if (!isHexDigit(code)) {\n this.error(\n allowDash && len !== 0\n ? 'Hyphen minus' + (len < 6 ? ' or hex digit' : '') + ' is expected'\n : (len < 6 ? 'Hex digit is expected' : 'Unexpected input'),\n pos\n );\n }\n\n if (++len > 6) {\n this.error('Too many hex digits', pos);\n };\n }\n\n this.next();\n return len;\n}\n\nfunction eatQuestionMarkSequence(max) {\n let count = 0;\n\n while (this.isDelim(QUESTIONMARK)) {\n if (++count > max) {\n this.error('Too many question marks');\n }\n\n this.next();\n }\n}\n\nfunction startsWith(code) {\n if (this.charCodeAt(this.tokenStart) !== code) {\n this.error((code === PLUSSIGN ? 'Plus sign' : 'Hyphen minus') + ' is expected');\n }\n}\n\n// https://drafts.csswg.org/css-syntax/#urange\n// Informally, the production has three forms:\n// U+0001\n// Defines a range consisting of a single code point, in this case the code point \"1\".\n// U+0001-00ff\n// Defines a range of codepoints between the first and the second value, in this case\n// the range between \"1\" and \"ff\" (255 in decimal) inclusive.\n// U+00??\n// Defines a range of codepoints where the \"?\" characters range over all hex digits,\n// in this case defining the same as the value U+0000-00ff.\n// In each form, a maximum of 6 digits is allowed for each hexadecimal number (if you treat \"?\" as a hexadecimal digit).\n//\n// =\n// u '+' '?'* |\n// u '?'* |\n// u '?'* |\n// u |\n// u |\n// u '+' '?'+\nfunction scanUnicodeRange() {\n let hexLength = 0;\n\n switch (this.tokenType) {\n case Number:\n // u '?'*\n // u \n // u \n hexLength = eatHexSequence.call(this, 1, true);\n\n if (this.isDelim(QUESTIONMARK)) {\n eatQuestionMarkSequence.call(this, 6 - hexLength);\n break;\n }\n\n if (this.tokenType === Dimension ||\n this.tokenType === Number) {\n startsWith.call(this, HYPHENMINUS);\n eatHexSequence.call(this, 1, false);\n break;\n }\n\n break;\n\n case Dimension:\n // u '?'*\n hexLength = eatHexSequence.call(this, 1, true);\n\n if (hexLength > 0) {\n eatQuestionMarkSequence.call(this, 6 - hexLength);\n }\n\n break;\n\n default:\n // u '+' '?'*\n // u '+' '?'+\n this.eatDelim(PLUSSIGN);\n\n if (this.tokenType === Ident) {\n hexLength = eatHexSequence.call(this, 0, true);\n if (hexLength > 0) {\n eatQuestionMarkSequence.call(this, 6 - hexLength);\n }\n break;\n }\n\n if (this.isDelim(QUESTIONMARK)) {\n this.next();\n eatQuestionMarkSequence.call(this, 5);\n break;\n }\n\n this.error('Hex digit or question mark is expected');\n }\n}\n\nexport const name = 'UnicodeRange';\nexport const structure = {\n value: String\n};\n\nexport function parse() {\n const start = this.tokenStart;\n\n // U or u\n this.eatIdent('u');\n scanUnicodeRange.call(this);\n\n return {\n type: 'UnicodeRange',\n loc: this.getLocation(start, this.tokenStart),\n value: this.substrToCursor(start)\n };\n}\n\nexport function generate(node) {\n this.tokenize(node.value);\n}\n", "import {\n isHexDigit,\n isWhiteSpace,\n isValidEscape,\n consumeEscaped,\n decodeEscaped\n} from '../tokenizer/index.js';\n\nconst SPACE = 0x0020; // U+0020 SPACE\nconst REVERSE_SOLIDUS = 0x005c; // U+005C REVERSE SOLIDUS (\\)\nconst QUOTATION_MARK = 0x0022; // \"\nconst APOSTROPHE = 0x0027; // '\nconst LEFTPARENTHESIS = 0x0028; // U+0028 LEFT PARENTHESIS (()\nconst RIGHTPARENTHESIS = 0x0029; // U+0029 RIGHT PARENTHESIS ())\n\nexport function decode(str) {\n const len = str.length;\n let start = 4; // length of \"url(\"\n let end = str.charCodeAt(len - 1) === RIGHTPARENTHESIS ? len - 2 : len - 1;\n let decoded = '';\n\n while (start < end && isWhiteSpace(str.charCodeAt(start))) {\n start++;\n }\n\n while (start < end && isWhiteSpace(str.charCodeAt(end))) {\n end--;\n }\n\n for (let i = start; i <= end; i++) {\n let code = str.charCodeAt(i);\n\n if (code === REVERSE_SOLIDUS) {\n // special case at the ending\n if (i === end) {\n // if the next input code point is EOF, do nothing\n // otherwise include last left parenthesis as escaped\n if (i !== len - 1) {\n decoded = str.substr(i + 1);\n }\n break;\n }\n\n code = str.charCodeAt(++i);\n\n // consume escaped\n if (isValidEscape(REVERSE_SOLIDUS, code)) {\n const escapeStart = i - 1;\n const escapeEnd = consumeEscaped(str, escapeStart);\n\n i = escapeEnd - 1;\n decoded += decodeEscaped(str.substring(escapeStart + 1, escapeEnd));\n } else {\n // \\r\\n\n if (code === 0x000d && str.charCodeAt(i + 1) === 0x000a) {\n i++;\n }\n }\n } else {\n decoded += str[i];\n }\n }\n\n return decoded;\n}\n\nexport function encode(str) {\n let encoded = '';\n let wsBeforeHexIsNeeded = false;\n\n for (let i = 0; i < str.length; i++) {\n const code = str.charCodeAt(i);\n\n // If the character is NULL (U+0000), then the REPLACEMENT CHARACTER (U+FFFD).\n if (code === 0x0000) {\n encoded += '\\uFFFD';\n continue;\n }\n\n // If the character is in the range [\\1-\\1f] (U+0001 to U+001F) or is U+007F,\n // the character escaped as code point.\n // Note: Do not compare with 0x0001 since 0x0000 is precessed before\n if (code <= 0x001f || code === 0x007F) {\n encoded += '\\\\' + code.toString(16);\n wsBeforeHexIsNeeded = true;\n continue;\n }\n\n if (code === SPACE ||\n code === REVERSE_SOLIDUS ||\n code === QUOTATION_MARK ||\n code === APOSTROPHE ||\n code === LEFTPARENTHESIS ||\n code === RIGHTPARENTHESIS) {\n encoded += '\\\\' + str.charAt(i);\n wsBeforeHexIsNeeded = false;\n } else {\n if (wsBeforeHexIsNeeded && isHexDigit(code)) {\n encoded += ' ';\n }\n\n encoded += str.charAt(i);\n wsBeforeHexIsNeeded = false;\n }\n }\n\n return 'url(' + encoded + ')';\n}\n", "import * as url from '../../utils/url.js';\nimport * as string from '../../utils/string.js';\nimport {\n Function as FunctionToken,\n String as StringToken,\n Url,\n RightParenthesis\n} from '../../tokenizer/index.js';\n\nexport const name = 'Url';\nexport const structure = {\n value: String\n};\n\n// | )\nexport function parse() {\n const start = this.tokenStart;\n let value;\n\n switch (this.tokenType) {\n case Url:\n value = url.decode(this.consume(Url));\n break;\n\n case FunctionToken:\n if (!this.cmpStr(this.tokenStart, this.tokenEnd, 'url(')) {\n this.error('Function name must be `url`');\n }\n\n this.eat(FunctionToken);\n this.skipSC();\n value = string.decode(this.consume(StringToken));\n this.skipSC();\n if (!this.eof) {\n this.eat(RightParenthesis);\n }\n break;\n\n default:\n this.error('Url or Function is expected');\n }\n\n return {\n type: 'Url',\n loc: this.getLocation(start, this.tokenStart),\n value\n };\n}\n\nexport function generate(node) {\n this.token(Url, url.encode(node.value));\n}\n", "export const name = 'Value';\nexport const structure = {\n children: [[]]\n};\n\nexport function parse() {\n const start = this.tokenStart;\n const children = this.readSequence(this.scope.Value);\n\n return {\n type: 'Value',\n loc: this.getLocation(start, this.tokenStart),\n children\n };\n}\n\nexport function generate(node) {\n this.children(node);\n}\n", "import { WhiteSpace } from '../../tokenizer/index.js';\n\nconst SPACE = Object.freeze({\n type: 'WhiteSpace',\n loc: null,\n value: ' '\n});\n\nexport const name = 'WhiteSpace';\nexport const structure = {\n value: String\n};\n\nexport function parse() {\n this.eat(WhiteSpace);\n return SPACE;\n\n // return {\n // type: 'WhiteSpace',\n // loc: this.getLocation(this.tokenStart, this.tokenEnd),\n // value: this.consume(WHITESPACE)\n // };\n}\n\nexport function generate(node) {\n this.token(WhiteSpace, node.value);\n}\n", "import * as node from '../node/index-generate.js';\n\nexport default {\n node\n};\n", "import { createGenerator } from './create.js';\nimport config from '../syntax/config/generator.js';\n\nexport default createGenerator(config);\n", "//\n// list\n// \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n// \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500head \u2502\n// \u2502 \u2502 tail\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n// \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2502\n// \u25BC \u25BC\n// item item item item\n// \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n// null \u25C0\u2500\u2500\u253C\u2500prev \u2502\u25C0\u2500\u2500\u2500\u253C\u2500prev \u2502\u25C0\u2500\u2500\u2500\u253C\u2500prev \u2502\u25C0\u2500\u2500\u2500\u253C\u2500prev \u2502\n// \u2502 next\u2500\u253C\u2500\u2500\u2500\u25B6\u2502 next\u2500\u253C\u2500\u2500\u2500\u25B6\u2502 next\u2500\u253C\u2500\u2500\u2500\u25B6\u2502 next\u2500\u253C\u2500\u2500\u25B6 null\n// \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2524 \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2524 \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2524 \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n// \u2502 data \u2502 \u2502 data \u2502 \u2502 data \u2502 \u2502 data \u2502\n// \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n//\n\nlet releasedCursors = null;\n\nexport class List {\n static createItem(data) {\n return {\n prev: null,\n next: null,\n data\n };\n }\n\n constructor() {\n this.head = null;\n this.tail = null;\n this.cursor = null;\n }\n createItem(data) {\n return List.createItem(data);\n }\n\n // cursor helpers\n allocateCursor(prev, next) {\n let cursor;\n\n if (releasedCursors !== null) {\n cursor = releasedCursors;\n releasedCursors = releasedCursors.cursor;\n cursor.prev = prev;\n cursor.next = next;\n cursor.cursor = this.cursor;\n } else {\n cursor = {\n prev,\n next,\n cursor: this.cursor\n };\n }\n\n this.cursor = cursor;\n\n return cursor;\n }\n releaseCursor() {\n const { cursor } = this;\n\n this.cursor = cursor.cursor;\n cursor.prev = null;\n cursor.next = null;\n cursor.cursor = releasedCursors;\n releasedCursors = cursor;\n }\n updateCursors(prevOld, prevNew, nextOld, nextNew) {\n let { cursor } = this;\n\n while (cursor !== null) {\n if (cursor.prev === prevOld) {\n cursor.prev = prevNew;\n }\n\n if (cursor.next === nextOld) {\n cursor.next = nextNew;\n }\n\n cursor = cursor.cursor;\n }\n }\n *[Symbol.iterator]() {\n for (let cursor = this.head; cursor !== null; cursor = cursor.next) {\n yield cursor.data;\n }\n }\n\n // getters\n get size() {\n let size = 0;\n\n for (let cursor = this.head; cursor !== null; cursor = cursor.next) {\n size++;\n }\n\n return size;\n }\n get isEmpty() {\n return this.head === null;\n }\n get first() {\n return this.head && this.head.data;\n }\n get last() {\n return this.tail && this.tail.data;\n }\n\n // convertors\n fromArray(array) {\n let cursor = null;\n this.head = null;\n\n for (let data of array) {\n const item = List.createItem(data);\n\n if (cursor !== null) {\n cursor.next = item;\n } else {\n this.head = item;\n }\n\n item.prev = cursor;\n cursor = item;\n }\n\n this.tail = cursor;\n return this;\n }\n toArray() {\n return [...this];\n }\n toJSON() {\n return [...this];\n }\n\n // array-like methods\n forEach(fn, thisArg = this) {\n // push cursor\n const cursor = this.allocateCursor(null, this.head);\n\n while (cursor.next !== null) {\n const item = cursor.next;\n cursor.next = item.next;\n fn.call(thisArg, item.data, item, this);\n }\n\n // pop cursor\n this.releaseCursor();\n }\n forEachRight(fn, thisArg = this) {\n // push cursor\n const cursor = this.allocateCursor(this.tail, null);\n\n while (cursor.prev !== null) {\n const item = cursor.prev;\n cursor.prev = item.prev;\n fn.call(thisArg, item.data, item, this);\n }\n\n // pop cursor\n this.releaseCursor();\n }\n reduce(fn, initialValue, thisArg = this) {\n // push cursor\n let cursor = this.allocateCursor(null, this.head);\n let acc = initialValue;\n let item;\n\n while (cursor.next !== null) {\n item = cursor.next;\n cursor.next = item.next;\n\n acc = fn.call(thisArg, acc, item.data, item, this);\n }\n\n // pop cursor\n this.releaseCursor();\n\n return acc;\n }\n reduceRight(fn, initialValue, thisArg = this) {\n // push cursor\n let cursor = this.allocateCursor(this.tail, null);\n let acc = initialValue;\n let item;\n\n while (cursor.prev !== null) {\n item = cursor.prev;\n cursor.prev = item.prev;\n\n acc = fn.call(thisArg, acc, item.data, item, this);\n }\n\n // pop cursor\n this.releaseCursor();\n\n return acc;\n }\n some(fn, thisArg = this) {\n for (let cursor = this.head; cursor !== null; cursor = cursor.next) {\n if (fn.call(thisArg, cursor.data, cursor, this)) {\n return true;\n }\n }\n\n return false;\n }\n map(fn, thisArg = this) {\n const result = new List();\n\n for (let cursor = this.head; cursor !== null; cursor = cursor.next) {\n result.appendData(fn.call(thisArg, cursor.data, cursor, this));\n }\n\n return result;\n }\n filter(fn, thisArg = this) {\n const result = new List();\n\n for (let cursor = this.head; cursor !== null; cursor = cursor.next) {\n if (fn.call(thisArg, cursor.data, cursor, this)) {\n result.appendData(cursor.data);\n }\n }\n\n return result;\n }\n\n nextUntil(start, fn, thisArg = this) {\n if (start === null) {\n return;\n }\n\n // push cursor\n const cursor = this.allocateCursor(null, start);\n\n while (cursor.next !== null) {\n const item = cursor.next;\n cursor.next = item.next;\n if (fn.call(thisArg, item.data, item, this)) {\n break;\n }\n }\n\n // pop cursor\n this.releaseCursor();\n }\n prevUntil(start, fn, thisArg = this) {\n if (start === null) {\n return;\n }\n\n // push cursor\n const cursor = this.allocateCursor(start, null);\n\n while (cursor.prev !== null) {\n const item = cursor.prev;\n cursor.prev = item.prev;\n if (fn.call(thisArg, item.data, item, this)) {\n break;\n }\n }\n\n // pop cursor\n this.releaseCursor();\n }\n\n // mutation\n clear() {\n this.head = null;\n this.tail = null;\n }\n copy() {\n const result = new List();\n\n for (let data of this) {\n result.appendData(data);\n }\n\n return result;\n }\n prepend(item) {\n // head\n // ^\n // item\n this.updateCursors(null, item, this.head, item);\n\n // insert to the beginning of the list\n if (this.head !== null) {\n // new item <- first item\n this.head.prev = item;\n // new item -> first item\n item.next = this.head;\n } else {\n // if list has no head, then it also has no tail\n // in this case tail points to the new item\n this.tail = item;\n }\n\n // head always points to new item\n this.head = item;\n return this;\n }\n prependData(data) {\n return this.prepend(List.createItem(data));\n }\n append(item) {\n return this.insert(item);\n }\n appendData(data) {\n return this.insert(List.createItem(data));\n }\n insert(item, before = null) {\n if (before !== null) {\n // prev before\n // ^\n // item\n this.updateCursors(before.prev, item, before, item);\n\n if (before.prev === null) {\n // insert to the beginning of list\n if (this.head !== before) {\n throw new Error('before doesn\\'t belong to list');\n }\n // since head points to before therefore list doesn't empty\n // no need to check tail\n this.head = item;\n before.prev = item;\n item.next = before;\n this.updateCursors(null, item);\n } else {\n // insert between two items\n before.prev.next = item;\n item.prev = before.prev;\n before.prev = item;\n item.next = before;\n }\n } else {\n // tail\n // ^\n // item\n this.updateCursors(this.tail, item, null, item);\n\n // insert to the ending of the list\n if (this.tail !== null) {\n // last item -> new item\n this.tail.next = item;\n // last item <- new item\n item.prev = this.tail;\n } else {\n // if list has no tail, then it also has no head\n // in this case head points to new item\n this.head = item;\n }\n\n // tail always points to new item\n this.tail = item;\n }\n\n return this;\n }\n insertData(data, before) {\n return this.insert(List.createItem(data), before);\n }\n remove(item) {\n // item\n // ^\n // prev next\n this.updateCursors(item, item.prev, item, item.next);\n\n if (item.prev !== null) {\n item.prev.next = item.next;\n } else {\n if (this.head !== item) {\n throw new Error('item doesn\\'t belong to list');\n }\n\n this.head = item.next;\n }\n\n if (item.next !== null) {\n item.next.prev = item.prev;\n } else {\n if (this.tail !== item) {\n throw new Error('item doesn\\'t belong to list');\n }\n\n this.tail = item.prev;\n }\n\n item.prev = null;\n item.next = null;\n\n return item;\n }\n push(data) {\n this.insert(List.createItem(data));\n }\n pop() {\n return this.tail !== null ? this.remove(this.tail) : null;\n }\n unshift(data) {\n this.prepend(List.createItem(data));\n }\n shift() {\n return this.head !== null ? this.remove(this.head) : null;\n }\n prependList(list) {\n return this.insertList(list, this.head);\n }\n appendList(list) {\n return this.insertList(list);\n }\n insertList(list, before) {\n // ignore empty lists\n if (list.head === null) {\n return this;\n }\n\n if (before !== undefined && before !== null) {\n this.updateCursors(before.prev, list.tail, before, list.head);\n\n // insert in the middle of dist list\n if (before.prev !== null) {\n // before.prev <-> list.head\n before.prev.next = list.head;\n list.head.prev = before.prev;\n } else {\n this.head = list.head;\n }\n\n before.prev = list.tail;\n list.tail.next = before;\n } else {\n this.updateCursors(this.tail, list.tail, null, list.head);\n\n // insert to end of the list\n if (this.tail !== null) {\n // if destination list has a tail, then it also has a head,\n // but head doesn't change\n // dest tail -> source head\n this.tail.next = list.head;\n // dest tail <- source head\n list.head.prev = this.tail;\n } else {\n // if list has no a tail, then it also has no a head\n // in this case points head to new item\n this.head = list.head;\n }\n\n // tail always start point to new item\n this.tail = list.tail;\n }\n\n list.head = null;\n list.tail = null;\n return this;\n }\n replace(oldItem, newItemOrList) {\n if ('head' in newItemOrList) {\n this.insertList(newItemOrList, oldItem);\n } else {\n this.insert(newItemOrList, oldItem);\n }\n\n this.remove(oldItem);\n }\n}\n", "export function createCustomError(name, message) {\n // use Object.create(), because some VMs prevent setting line/column otherwise\n // (iOS Safari 10 even throws an exception)\n const error = Object.create(SyntaxError.prototype);\n const errorStack = new Error();\n\n return Object.assign(error, {\n name,\n message,\n get stack() {\n return (errorStack.stack || '').replace(/^(.+\\n){1,3}/, `${name}: ${message}\\n`);\n }\n });\n};\n", "import { createCustomError } from '../utils/create-custom-error.js';\n\nconst MAX_LINE_LENGTH = 100;\nconst OFFSET_CORRECTION = 60;\nconst TAB_REPLACEMENT = ' ';\n\nfunction sourceFragment({ source, line, column, baseLine, baseColumn }, extraLines) {\n function processLines(start, end) {\n return lines\n .slice(start, end)\n .map((line, idx) =>\n String(start + idx + 1).padStart(maxNumLength) + ' |' + line\n ).join('\\n');\n }\n\n const prelines = '\\n'.repeat(Math.max(baseLine - 1, 0));\n const precolumns = ' '.repeat(Math.max(baseColumn - 1, 0));\n const lines = (prelines + precolumns + source).split(/\\r\\n?|\\n|\\f/);\n const startLine = Math.max(1, line - extraLines) - 1;\n const endLine = Math.min(line + extraLines, lines.length + 1);\n const maxNumLength = Math.max(4, String(endLine).length) + 1;\n let cutLeft = 0;\n\n // column correction according to replaced tab before column\n column += (TAB_REPLACEMENT.length - 1) * (lines[line - 1].substr(0, column - 1).match(/\\t/g) || []).length;\n\n if (column > MAX_LINE_LENGTH) {\n cutLeft = column - OFFSET_CORRECTION + 3;\n column = OFFSET_CORRECTION - 2;\n }\n\n for (let i = startLine; i <= endLine; i++) {\n if (i >= 0 && i < lines.length) {\n lines[i] = lines[i].replace(/\\t/g, TAB_REPLACEMENT);\n lines[i] =\n (cutLeft > 0 && lines[i].length > cutLeft ? '\\u2026' : '') +\n lines[i].substr(cutLeft, MAX_LINE_LENGTH - 2) +\n (lines[i].length > cutLeft + MAX_LINE_LENGTH - 1 ? '\\u2026' : '');\n }\n }\n\n return [\n processLines(startLine, line),\n new Array(column + maxNumLength + 2).join('-') + '^',\n processLines(line, endLine)\n ].filter(Boolean)\n .join('\\n')\n .replace(/^(\\s+\\d+\\s+\\|\\n)+/, '')\n .replace(/\\n(\\s+\\d+\\s+\\|)+$/, '');\n}\n\nexport function SyntaxError(message, source, offset, line, column, baseLine = 1, baseColumn = 1) {\n const error = Object.assign(createCustomError('SyntaxError', message), {\n source,\n offset,\n line,\n column,\n sourceFragment(extraLines) {\n return sourceFragment({ source, line, column, baseLine, baseColumn }, isNaN(extraLines) ? 0 : extraLines);\n },\n get formattedMessage() {\n return (\n `Parse error: ${message}\\n` +\n sourceFragment({ source, line, column, baseLine, baseColumn }, 2)\n );\n }\n });\n\n return error;\n}\n", "import { WhiteSpace, Comment } from '../tokenizer/index.js';\n\nexport function readSequence(recognizer) {\n const children = this.createList();\n let space = false;\n const context = {\n recognizer\n };\n\n while (!this.eof) {\n switch (this.tokenType) {\n case Comment:\n this.next();\n continue;\n\n case WhiteSpace:\n space = true;\n this.next();\n continue;\n }\n\n let child = recognizer.getNode.call(this, context);\n\n if (child === undefined) {\n break;\n }\n\n if (space) {\n if (recognizer.onWhiteSpace) {\n recognizer.onWhiteSpace.call(this, child, children, context);\n }\n space = false;\n }\n\n children.push(child);\n }\n\n if (space && recognizer.onWhiteSpace) {\n recognizer.onWhiteSpace.call(this, null, children, context);\n }\n\n return children;\n};\n", "import { List } from '../utils/List.js';\nimport { SyntaxError } from './SyntaxError.js';\nimport {\n tokenize,\n OffsetToLocation,\n TokenStream,\n tokenNames,\n\n consumeNumber,\n findWhiteSpaceStart,\n cmpChar,\n cmpStr,\n\n WhiteSpace,\n Comment,\n Ident,\n Function as FunctionToken,\n Url,\n Hash,\n Percentage,\n Number as NumberToken\n} from '../tokenizer/index.js';\nimport { readSequence } from './sequence.js';\n\nconst NOOP = () => {};\nconst EXCLAMATIONMARK = 0x0021; // U+0021 EXCLAMATION MARK (!)\nconst NUMBERSIGN = 0x0023; // U+0023 NUMBER SIGN (#)\nconst SEMICOLON = 0x003B; // U+003B SEMICOLON (;)\nconst LEFTCURLYBRACKET = 0x007B; // U+007B LEFT CURLY BRACKET ({)\nconst NULL = 0;\n\nfunction createParseContext(name) {\n return function() {\n return this[name]();\n };\n}\n\nfunction fetchParseValues(dict) {\n const result = Object.create(null);\n\n for (const name of Object.keys(dict)) {\n const item = dict[name];\n const fn = item.parse || item;\n\n if (fn) {\n result[name] = fn;\n }\n }\n\n return result;\n}\n\nfunction processConfig(config) {\n const parseConfig = {\n context: Object.create(null),\n features: Object.assign(Object.create(null), config.features),\n scope: Object.assign(Object.create(null), config.scope),\n atrule: fetchParseValues(config.atrule),\n pseudo: fetchParseValues(config.pseudo),\n node: fetchParseValues(config.node)\n };\n\n for (const [name, context] of Object.entries(config.parseContext)) {\n switch (typeof context) {\n case 'function':\n parseConfig.context[name] = context;\n break;\n\n case 'string':\n parseConfig.context[name] = createParseContext(context);\n break;\n }\n }\n\n return {\n config: parseConfig,\n ...parseConfig,\n ...parseConfig.node\n };\n}\n\nexport function createParser(config) {\n let source = '';\n let filename = '';\n let needPositions = false;\n let onParseError = NOOP;\n let onParseErrorThrow = false;\n\n const locationMap = new OffsetToLocation();\n const parser = Object.assign(new TokenStream(), processConfig(config || {}), {\n parseAtrulePrelude: true,\n parseRulePrelude: true,\n parseValue: true,\n parseCustomProperty: false,\n\n readSequence,\n\n consumeUntilBalanceEnd: () => 0,\n consumeUntilLeftCurlyBracket(code) {\n return code === LEFTCURLYBRACKET ? 1 : 0;\n },\n consumeUntilLeftCurlyBracketOrSemicolon(code) {\n return code === LEFTCURLYBRACKET || code === SEMICOLON ? 1 : 0;\n },\n consumeUntilExclamationMarkOrSemicolon(code) {\n return code === EXCLAMATIONMARK || code === SEMICOLON ? 1 : 0;\n },\n consumeUntilSemicolonIncluded(code) {\n return code === SEMICOLON ? 2 : 0;\n },\n\n createList() {\n return new List();\n },\n createSingleNodeList(node) {\n return new List().appendData(node);\n },\n getFirstListNode(list) {\n return list && list.first;\n },\n getLastListNode(list) {\n return list && list.last;\n },\n\n parseWithFallback(consumer, fallback) {\n const startIndex = this.tokenIndex;\n\n try {\n return consumer.call(this);\n } catch (e) {\n if (onParseErrorThrow) {\n throw e;\n }\n\n this.skip(startIndex - this.tokenIndex);\n const fallbackNode = fallback.call(this);\n\n onParseErrorThrow = true;\n onParseError(e, fallbackNode);\n onParseErrorThrow = false;\n\n return fallbackNode;\n }\n },\n\n lookupNonWSType(offset) {\n let type;\n\n do {\n type = this.lookupType(offset++);\n if (type !== WhiteSpace && type !== Comment) {\n return type;\n }\n } while (type !== NULL);\n\n return NULL;\n },\n\n charCodeAt(offset) {\n return offset >= 0 && offset < source.length ? source.charCodeAt(offset) : 0;\n },\n substring(offsetStart, offsetEnd) {\n return source.substring(offsetStart, offsetEnd);\n },\n substrToCursor(start) {\n return this.source.substring(start, this.tokenStart);\n },\n\n cmpChar(offset, charCode) {\n return cmpChar(source, offset, charCode);\n },\n cmpStr(offsetStart, offsetEnd, str) {\n return cmpStr(source, offsetStart, offsetEnd, str);\n },\n\n consume(tokenType) {\n const start = this.tokenStart;\n\n this.eat(tokenType);\n\n return this.substrToCursor(start);\n },\n consumeFunctionName() {\n const name = source.substring(this.tokenStart, this.tokenEnd - 1);\n\n this.eat(FunctionToken);\n\n return name;\n },\n consumeNumber(type) {\n const number = source.substring(this.tokenStart, consumeNumber(source, this.tokenStart));\n\n this.eat(type);\n\n return number;\n },\n\n eat(tokenType) {\n if (this.tokenType !== tokenType) {\n const tokenName = tokenNames[tokenType].slice(0, -6).replace(/-/g, ' ').replace(/^./, m => m.toUpperCase());\n let message = `${/[[\\](){}]/.test(tokenName) ? `\"${tokenName}\"` : tokenName} is expected`;\n let offset = this.tokenStart;\n\n // tweak message and offset\n switch (tokenType) {\n case Ident:\n // when identifier is expected but there is a function or url\n if (this.tokenType === FunctionToken || this.tokenType === Url) {\n offset = this.tokenEnd - 1;\n message = 'Identifier is expected but function found';\n } else {\n message = 'Identifier is expected';\n }\n break;\n\n case Hash:\n if (this.isDelim(NUMBERSIGN)) {\n this.next();\n offset++;\n message = 'Name is expected';\n }\n break;\n\n case Percentage:\n if (this.tokenType === NumberToken) {\n offset = this.tokenEnd;\n message = 'Percent sign is expected';\n }\n break;\n }\n\n this.error(message, offset);\n }\n\n this.next();\n },\n eatIdent(name) {\n if (this.tokenType !== Ident || this.lookupValue(0, name) === false) {\n this.error(`Identifier \"${name}\" is expected`);\n }\n\n this.next();\n },\n eatDelim(code) {\n if (!this.isDelim(code)) {\n this.error(`Delim \"${String.fromCharCode(code)}\" is expected`);\n }\n\n this.next();\n },\n\n getLocation(start, end) {\n if (needPositions) {\n return locationMap.getLocationRange(\n start,\n end,\n filename\n );\n }\n\n return null;\n },\n getLocationFromList(list) {\n if (needPositions) {\n const head = this.getFirstListNode(list);\n const tail = this.getLastListNode(list);\n return locationMap.getLocationRange(\n head !== null ? head.loc.start.offset - locationMap.startOffset : this.tokenStart,\n tail !== null ? tail.loc.end.offset - locationMap.startOffset : this.tokenStart,\n filename\n );\n }\n\n return null;\n },\n\n error(message, offset) {\n const location = typeof offset !== 'undefined' && offset < source.length\n ? locationMap.getLocation(offset)\n : this.eof\n ? locationMap.getLocation(findWhiteSpaceStart(source, source.length - 1))\n : locationMap.getLocation(this.tokenStart);\n\n throw new SyntaxError(\n message || 'Unexpected input',\n source,\n location.offset,\n location.line,\n location.column,\n locationMap.startLine,\n locationMap.startColumn\n );\n }\n });\n\n const parse = function(source_, options) {\n source = source_;\n options = options || {};\n\n parser.setSource(source, tokenize);\n locationMap.setSource(\n source,\n options.offset,\n options.line,\n options.column\n );\n\n filename = options.filename || '';\n needPositions = Boolean(options.positions);\n onParseError = typeof options.onParseError === 'function' ? options.onParseError : NOOP;\n onParseErrorThrow = false;\n\n parser.parseAtrulePrelude = 'parseAtrulePrelude' in options ? Boolean(options.parseAtrulePrelude) : true;\n parser.parseRulePrelude = 'parseRulePrelude' in options ? Boolean(options.parseRulePrelude) : true;\n parser.parseValue = 'parseValue' in options ? Boolean(options.parseValue) : true;\n parser.parseCustomProperty = 'parseCustomProperty' in options ? Boolean(options.parseCustomProperty) : false;\n\n const { context = 'default', onComment } = options;\n\n if (context in parser.context === false) {\n throw new Error('Unknown context `' + context + '`');\n }\n\n if (typeof onComment === 'function') {\n parser.forEachToken((type, start, end) => {\n if (type === Comment) {\n const loc = parser.getLocation(start, end);\n const value = cmpStr(source, end - 2, end, '*/')\n ? source.slice(start + 2, end - 2)\n : source.slice(start + 2, end);\n\n onComment(value, loc);\n }\n });\n }\n\n const ast = parser.context[context].call(parser, options);\n\n if (!parser.eof) {\n parser.error();\n }\n\n return ast;\n };\n\n return Object.assign(parse, {\n SyntaxError,\n config: parser.config\n });\n};\n", "import {\n Delim,\n Ident,\n Dimension,\n Percentage,\n Number as NumberToken,\n Hash,\n Colon,\n LeftSquareBracket\n} from '../../tokenizer/index.js';\n\nconst NUMBERSIGN = 0x0023; // U+0023 NUMBER SIGN (#)\nconst AMPERSAND = 0x0026; // U+0026 AMPERSAND (&)\nconst ASTERISK = 0x002A; // U+002A ASTERISK (*)\nconst PLUSSIGN = 0x002B; // U+002B PLUS SIGN (+)\nconst SOLIDUS = 0x002F; // U+002F SOLIDUS (/)\nconst FULLSTOP = 0x002E; // U+002E FULL STOP (.)\nconst GREATERTHANSIGN = 0x003E; // U+003E GREATER-THAN SIGN (>)\nconst VERTICALLINE = 0x007C; // U+007C VERTICAL LINE (|)\nconst TILDE = 0x007E; // U+007E TILDE (~)\n\nfunction onWhiteSpace(next, children) {\n if (children.last !== null && children.last.type !== 'Combinator' &&\n next !== null && next.type !== 'Combinator') {\n children.push({ // FIXME: this.Combinator() should be used instead\n type: 'Combinator',\n loc: null,\n name: ' '\n });\n }\n}\n\nfunction getNode() {\n switch (this.tokenType) {\n case LeftSquareBracket:\n return this.AttributeSelector();\n\n case Hash:\n return this.IdSelector();\n\n case Colon:\n if (this.lookupType(1) === Colon) {\n return this.PseudoElementSelector();\n } else {\n return this.PseudoClassSelector();\n }\n\n case Ident:\n return this.TypeSelector();\n\n case NumberToken:\n case Percentage:\n return this.Percentage();\n\n case Dimension:\n // throws when .123ident\n if (this.charCodeAt(this.tokenStart) === FULLSTOP) {\n this.error('Identifier is expected', this.tokenStart + 1);\n }\n break;\n\n case Delim: {\n const code = this.charCodeAt(this.tokenStart);\n\n switch (code) {\n case PLUSSIGN:\n case GREATERTHANSIGN:\n case TILDE:\n case SOLIDUS: // /deep/\n return this.Combinator();\n\n case FULLSTOP:\n return this.ClassSelector();\n\n case ASTERISK:\n case VERTICALLINE:\n return this.TypeSelector();\n\n case NUMBERSIGN:\n return this.IdSelector();\n\n case AMPERSAND:\n return this.NestingSelector();\n }\n\n break;\n }\n }\n};\n\nexport default {\n onWhiteSpace,\n getNode\n};\n", "import { Comma, String as StringToken, Ident, RightParenthesis } from '../../tokenizer/index.js';\n\nexport function parseLanguageRangeList() {\n const children = this.createList();\n\n this.skipSC();\n\n loop: while (!this.eof) {\n switch (this.tokenType) {\n case Ident:\n children.push(this.Identifier());\n break;\n\n case StringToken:\n children.push(this.String());\n break;\n\n case Comma:\n children.push(this.Operator());\n break;\n\n case RightParenthesis:\n break loop;\n\n default:\n this.error('Identifier, string or comma is expected');\n }\n\n this.skipSC();\n }\n\n return children;\n}\n", "import { parseLanguageRangeList } from './lang.js';\n\nconst selectorList = {\n parse() {\n return this.createSingleNodeList(\n this.SelectorList()\n );\n }\n};\n\nconst selector = {\n parse() {\n return this.createSingleNodeList(\n this.Selector()\n );\n }\n};\n\nconst identList = {\n parse() {\n return this.createSingleNodeList(\n this.Identifier()\n );\n }\n};\n\nconst langList = {\n parse: parseLanguageRangeList\n};\n\nconst nth = {\n parse() {\n return this.createSingleNodeList(\n this.Nth()\n );\n }\n};\n\nexport default {\n 'dir': identList,\n 'has': selectorList,\n 'lang': langList,\n 'matches': selectorList,\n 'is': selectorList,\n '-moz-any': selectorList,\n '-webkit-any': selectorList,\n 'where': selectorList,\n 'not': selectorList,\n 'nth-child': nth,\n 'nth-last-child': nth,\n 'nth-last-of-type': nth,\n 'nth-of-type': nth,\n 'slotted': selector,\n 'host': selector,\n 'host-context': selector\n};\n", "export { parse as AnPlusB } from './AnPlusB.js';\nexport { parse as AttributeSelector } from './AttributeSelector.js';\nexport { parse as ClassSelector } from './ClassSelector.js';\nexport { parse as Combinator } from './Combinator.js';\nexport { parse as Identifier } from './Identifier.js';\nexport { parse as IdSelector } from './IdSelector.js';\nexport { parse as NestingSelector } from './NestingSelector.js';\nexport { parse as Nth } from './Nth.js';\nexport { parse as Operator } from './Operator.js';\nexport { parse as Percentage } from './Percentage.js';\nexport { parse as PseudoClassSelector } from './PseudoClassSelector.js';\nexport { parse as PseudoElementSelector } from './PseudoElementSelector.js';\nexport { parse as Raw } from './Raw.js';\nexport { parse as Selector } from './Selector.js';\nexport { parse as SelectorList } from './SelectorList.js';\nexport { parse as String } from './String.js';\nexport { parse as TypeSelector } from './TypeSelector.js';\n", "import { Selector } from '../scope/index.js';\nimport pseudo from '../pseudo/index.js';\nimport * as node from '../node/index-parse-selector.js';\n\nexport default {\n parseContext: {\n default: 'SelectorList',\n selectorList: 'SelectorList',\n selector: 'Selector'\n },\n scope: { Selector },\n atrule: {},\n pseudo,\n node\n};\n", "import { createParser } from './create.js';\nimport config from '../syntax/config/parser-selector.js';\n\nexport default createParser(config);\n", "const compare = (s1, s2) => {\n if (s1.a === s2.a) {\n if (s1.b === s2.b) {\n return s1.c - s2.c;\n }\n return s1.b - s2.b;\n }\n return s1.a - s2.a;\n};\n\nconst equals = (s1, s2) => {\n return compare(s1, s2) === 0;\n};\n\nconst greaterThan = (s1, s2) => {\n return compare(s1, s2) > 0;\n};\n\nconst lessThan = (s1, s2) => {\n return compare(s1, s2) < 0;\n};\n\nexport { compare, equals, greaterThan, lessThan };\n", "import { compare } from './compare.js';\n\nconst sort = (specificities, order = 'ASC') => {\n const sorted = specificities.sort(compare);\n\n if (order === 'DESC') {\n return sorted.reverse();\n }\n\n return sorted;\n};\n\nconst sortAsc = (...specificities) => {\n return sort(specificities, 'ASC');\n};\n\nconst sortDesc = (...specificities) => {\n return sort(specificities, 'DESC');\n};\n\nexport { sortAsc, sortDesc };\n", "import { sortAsc, sortDesc } from './sort.js';\n\nconst max = (...specificities) => {\n const sorted = sortDesc(...specificities);\n return sorted[0];\n};\n\nconst min = (...specificities) => {\n const sorted = sortAsc(...specificities);\n return sorted[0];\n};\n\nexport { max, min };\n", "import parse from 'css-tree/selector-parser';\nimport Specificity from '../index.js';\nimport { max } from './../util/index.js';\n\n/** @param {import('css-tree').Selector} selectorAST */\nconst calculateForAST = (selectorAST) => {\n // Quit while you're ahead\n if (!selectorAST || selectorAST.type !== 'Selector') {\n throw new TypeError(`Passed in source is not a Selector AST`);\n }\n\n // https://www.w3.org/TR/selectors-4/#specificity-rules\n let a = 0; /* ID Selectors */\n let b = 0; /* Class selectors, Attributes selectors, and Pseudo-classes */\n let c = 0; /* Type selectors and Pseudo-elements */\n\n selectorAST.children.forEach((child) => {\n switch (child.type) {\n case 'IdSelector':\n a += 1;\n break;\n\n case 'AttributeSelector':\n case 'ClassSelector':\n b += 1;\n break;\n\n case 'PseudoClassSelector':\n switch (child.name.toLowerCase()) {\n // \u201CThe specificity of a :where() pseudo-class is replaced by zero.\u201D\n case 'where':\n // Noop :)\n break;\n\n case '-webkit-any':\n case 'any':\n if (child.children?.first) {\n b += 1;\n }\n break;\n\n // \u201CThe specificity of an :is(), :not(), or :has() pseudo-class is replaced by the specificity of the most specific complex selector in its selector list argument.\u201C\n case '-moz-any':\n case 'is':\n case 'matches':\n case 'not':\n case 'has':\n if (child.children?.first) {\n // Calculate Specificity from nested SelectorList\n const max1 = max(...calculate(child.children.first));\n\n // Adjust orig specificity\n a += max1.a;\n b += max1.b;\n c += max1.c;\n }\n\n break;\n\n // \u201CThe specificity of an :nth-child() or :nth-last-child() selector is the specificity of the pseudo class itself (counting as one pseudo-class selector) plus the specificity of the most specific complex selector in its selector list argument\u201D\n case 'nth-child':\n case 'nth-last-child':\n b += 1;\n\n if (child.children?.first?.selector) {\n // Calculate Specificity from SelectorList\n const max2 = max(...calculate(child.children.first.selector));\n\n // Adjust orig specificity\n a += max2.a;\n b += max2.b;\n c += max2.c;\n }\n break;\n\n // \u201CThe specificity of :host is that of a pseudo-class. The specificity of :host() is that of a pseudo-class, plus the specificity of its argument.\u201D\n // \u201CThe specificity of :host-context() is that of a pseudo-class, plus the specificity of its argument.\u201D\n case 'host-context':\n case 'host':\n b += 1;\n\n if (child.children?.first?.children) {\n // Workaround to a css-tree bug in which it allows complex selectors instead of only compound selectors\n // We work around it by filtering out any Combinator and successive Selectors\n const childAST = { type: 'Selector', children: [] };\n let foundCombinator = false;\n child.children.first.children.forEach((entry) => {\n if (foundCombinator) return false;\n if (entry.type === 'Combinator') {\n foundCombinator = true;\n return false;\n }\n childAST.children.push(entry);\n });\n\n // Calculate Specificity from Selector\n const childSpecificity = calculate(childAST)[0];\n\n // Adjust orig specificity\n a += childSpecificity.a;\n b += childSpecificity.b;\n c += childSpecificity.c;\n }\n break;\n\n // Improper use of Pseudo-Class Selectors instead of a Pseudo-Element\n // @ref https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-elements#index\n case 'after':\n case 'before':\n case 'first-letter':\n case 'first-line':\n c += 1;\n break;\n\n default:\n b += 1;\n break;\n }\n break;\n\n case 'PseudoElementSelector':\n switch (child.name) {\n // \u201CThe specificity of ::slotted() is that of a pseudo-element, plus the specificity of its argument.\u201D\n case 'slotted':\n c += 1;\n\n if (child.children?.first?.children) {\n // Workaround to a css-tree bug in which it allows complex selectors instead of only compound selectors\n // We work around it by filtering out any Combinator and successive Selectors\n const childAST = { type: 'Selector', children: [] };\n let foundCombinator = false;\n child.children.first.children.forEach((entry) => {\n if (foundCombinator) return false;\n if (entry.type === 'Combinator') {\n foundCombinator = true;\n return false;\n }\n childAST.children.push(entry);\n });\n\n // Calculate Specificity from Selector\n const childSpecificity = calculate(childAST)[0];\n\n // Adjust orig specificity\n a += childSpecificity.a;\n b += childSpecificity.b;\n c += childSpecificity.c;\n }\n break;\n\n case 'view-transition-group':\n case 'view-transition-image-pair':\n case 'view-transition-old':\n case 'view-transition-new':\n // The specificity of a view-transition selector with a * argument is zero.\n if (child.children?.first?.value === '*') {\n break;\n }\n // The specificity of a view-transition selector with an argument is the same\n // as for other pseudo - elements, and is equivalent to a type selector.\n c += 1;\n break;\n\n default:\n c += 1;\n break;\n }\n break;\n\n case 'TypeSelector':\n // Omit namespace\n let typeSelector = child.name;\n if (typeSelector.includes('|')) {\n typeSelector = typeSelector.split('|')[1];\n }\n\n // \u201CIgnore the universal selector\u201D\n if (typeSelector !== '*') {\n c += 1;\n }\n break;\n\n default:\n // NOOP\n break;\n }\n });\n\n return new Specificity({ a, b, c }, selectorAST);\n};\n\nconst convertToAST = (source) => {\n // The passed in argument was a String.\n // ~> Let's try and parse to an AST\n if (typeof source === 'string' || source instanceof String) {\n try {\n return parse(source, {\n context: 'selectorList',\n });\n } catch (e) {\n throw new TypeError(`Could not convert passed in source '${source}' to SelectorList: ${e.message}`);\n }\n }\n\n // The passed in argument was an Object.\n // ~> Let's verify if it's a AST of the type Selector or SelectorList\n if (source instanceof Object) {\n if (source.type && ['Selector', 'SelectorList'].includes(source.type)) {\n return source;\n }\n\n // Manually parsing subtree when the child is of the type Raw, most likely due to https://github.com/csstree/csstree/issues/151\n if (source.type && source.type === 'Raw') {\n try {\n return parse(source.value, {\n context: 'selectorList',\n });\n } catch (e) {\n throw new TypeError(`Could not convert passed in source to SelectorList: ${e.message}`);\n }\n }\n\n throw new TypeError(`Passed in source is an Object but no AST / AST of the type Selector or SelectorList`);\n }\n\n throw new TypeError(`Passed in source is not a String nor an Object. I don't know what to do with it.`);\n};\n\n/**\n * @param {string} selector\n * @returns {Specificity[]}\n */\nconst calculate = (selector) => {\n // Quit while you're ahead\n if (!selector) {\n return [];\n }\n\n // Make sure we have a SelectorList AST\n // If not, an exception will be thrown\n const ast = convertToAST(selector);\n\n // Selector?\n if (ast.type === 'Selector') {\n return [calculateForAST(selector)];\n }\n\n // SelectorList?\n // ~> Calculate Specificity for each contained Selector\n if (ast.type === 'SelectorList') {\n const specificities = [];\n ast.children.forEach((childAST) => {\n const specificity = calculateForAST(childAST);\n specificities.push(specificity);\n });\n return specificities;\n }\n};\n\nexport { calculate, calculateForAST };\n"], + "mappings": "wwBAAA,eAOA,GAAI,IAAe,mEAAmE,MAAM,IAK5F,GAAQ,OAAS,SAAU,EAAQ,CACjC,GAAI,GAAK,GAAU,EAAS,GAAa,OACvC,MAAO,IAAa,GAEtB,KAAM,IAAI,WAAU,6BAA+B,IAOrD,GAAQ,OAAS,SAAU,EAAU,CACnC,GAAI,GAAO,GACP,EAAO,GAEP,EAAU,GACV,EAAU,IAEV,EAAO,GACP,EAAO,GAEP,EAAO,GACP,EAAQ,GAER,EAAe,GACf,EAAe,GAGnB,MAAI,IAAQ,GAAY,GAAY,EAC1B,EAAW,EAIjB,GAAW,GAAY,GAAY,EAC7B,EAAW,EAAU,EAI3B,GAAQ,GAAY,GAAY,EAC1B,EAAW,EAAO,EAIxB,GAAY,EACP,GAIL,GAAY,EACP,GAI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,QACvD,KAAK,SAIZ,KAAK,mBAAoB,SACrB,KAAK,SAAS,OAAS,WAChB,GAAS,KAAK,UAKtB,GAGX,UAAW,CACP,MAAO,MAAK,MAGhB,SAAU,CACN,MAAO,CAAC,KAAK,MAAM,EAAG,KAAK,MAAM,EAAG,KAAK,MAAM,GAGnD,UAAW,CACP,MAAO,IAAI,KAAK,MAAM,KAAK,KAAK,MAAM,KAAK,KAAK,MAAM,KAG1D,QAAS,CACL,MAAO,CACH,SAAU,KAAK,iBACf,SAAU,KAAK,WACf,QAAS,KAAK,UACd,SAAU,KAAK,YAIvB,UAAU,EAAkB,CACxB,MAAO,IAAO,KAAM,GAGxB,cAAc,EAAkB,CAC5B,MAAO,IAAY,KAAM,GAG7B,WAAW,EAAkB,CACzB,MAAO,IAAS,KAAM,SAGnB,WAAU,EAAU,CACvB,MAAO,IAAU,SAGd,iBAAgB,EAAU,CAC7B,MAAO,IAAgB,SAGpB,SAAQ,EAAI,EAAI,CACnB,MAAO,IAAQ,EAAI,SAGhB,QAAO,EAAI,EAAI,CAClB,MAAO,IAAO,EAAI,SAGf,UAAS,EAAI,EAAI,CACpB,MAAO,IAAS,EAAI,SAGjB,aAAY,EAAI,EAAI,CACvB,MAAO,IAAY,EAAI,SAGpB,QAAO,EAAe,CACzB,MAAO,IAAI,GAAG,SAGX,QAAO,EAAe,CACzB,MAAO,IAAI,GAAG,SAGX,YAAW,EAAe,CAC7B,MAAO,IAAQ,GAAG,SAGf,aAAY,EAAe,CAC9B,MAAO,IAAS,GAAG,KAIpB,GAAQ", + "names": [] +} diff --git a/node_modules/@bramus/specificity/dist/index.js b/node_modules/@bramus/specificity/dist/index.js new file mode 100644 index 00000000..b56a1f39 --- /dev/null +++ b/node_modules/@bramus/specificity/dist/index.js @@ -0,0 +1,8 @@ +var jn=Object.create;var Tt=Object.defineProperty;var zn=Object.getOwnPropertyDescriptor;var Kn=Object.getOwnPropertyNames;var Qn=Object.getPrototypeOf,$n=Object.prototype.hasOwnProperty;var Xn=e=>Tt(e,"__esModule",{value:!0});var lt=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),$t=(e,t)=>{for(var r in t)Tt(e,r,{get:t[r],enumerable:!0})},Jn=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Kn(t))!$n.call(e,s)&&(r||s!=="default")&&Tt(e,s,{get:()=>t[s],enumerable:!(n=zn(t,s))||n.enumerable});return e},Zn=(e,t)=>Jn(Xn(Tt(e!=null?jn(Qn(e)):{},"default",!t&&e&&e.__esModule?{get:()=>e.default,enumerable:!0}:{value:e,enumerable:!0})),e);var _e=lt(se=>{var Oe="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");se.encode=function(e){if(0<=e&&e{var Me=_e(),oe=5,Be=1<>1;return t?-r:r}ae.encode=function(t){var r="",n,s=ci(t);do n=s&Ue,s>>>=oe,s>0&&(n|=We),r+=Me.encode(n);while(s>0);return r};ae.decode=function(t,r,n){var s=t.length,o=0,a=0,h,l;do{if(r>=s)throw new Error("Expected more digits in base 64 VLQ value.");if(l=Me.decode(t.charCodeAt(r++)),l===-1)throw new Error("Invalid base64 digit: "+t.charAt(r-1));h=!!(l&We),l&=Ue,o=o+(l<{function hi(e,t,r){if(t in e)return e[t];if(arguments.length===3)return r;throw new Error('"'+t+'" is a required argument.')}N.getArg=hi;var He=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/,ui=/^data:.+\,.+$/;function Ct(e){var t=e.match(He);return t?{scheme:t[1],auth:t[2],host:t[3],port:t[4],path:t[5]}:null}N.urlParse=Ct;function ft(e){var t="";return e.scheme&&(t+=e.scheme+":"),t+="//",e.auth&&(t+=e.auth+"@"),e.host&&(t+=e.host),e.port&&(t+=":"+e.port),e.path&&(t+=e.path),t}N.urlGenerate=ft;var fi=32;function pi(e){var t=[];return function(r){for(var n=0;nfi&&t.pop(),o}}var ce=pi(function(t){var r=t,n=Ct(t);if(n){if(!n.path)return t;r=n.path}for(var s=N.isAbsolute(r),o=[],a=0,h=0;;)if(a=h,h=r.indexOf("/",a),h===-1){o.push(r.slice(a));break}else for(o.push(r.slice(a,h));h=0;h--)l=o[h],l==="."?o.splice(h,1):l===".."?i++:i>0&&(l===""?(o.splice(h+1,i),i=0):(o.splice(h,2),i--));return r=o.join("/"),r===""&&(r=s?"/":"."),n?(n.path=r,ft(n)):r});N.normalize=ce;function Ge(e,t){e===""&&(e="."),t===""&&(t=".");var r=Ct(t),n=Ct(e);if(n&&(e=n.path||"/"),r&&!r.scheme)return n&&(r.scheme=n.scheme),ft(r);if(r||t.match(ui))return t;if(n&&!n.host&&!n.path)return n.host=t,ft(n);var s=t.charAt(0)==="/"?t:ce(e.replace(/\/+$/,"")+"/"+t);return n?(n.path=s,ft(n)):s}N.join=Ge;N.isAbsolute=function(e){return e.charAt(0)==="/"||He.test(e)};function mi(e,t){e===""&&(e="."),e=e.replace(/\/$/,"");for(var r=0;t.indexOf(e+"/")!==0;){var n=e.lastIndexOf("/");if(n<0||(e=e.slice(0,n),e.match(/^([^\/]+:\/)?\/*$/)))return t;++r}return Array(r+1).join("../")+t.substr(e.length+1)}N.relative=mi;var qe=function(){var e=Object.create(null);return!("__proto__"in e)}();function Ye(e){return e}function di(e){return je(e)?"$"+e:e}N.toSetString=qe?Ye:di;function xi(e){return je(e)?e.slice(1):e}N.fromSetString=qe?Ye:xi;function je(e){if(!e)return!1;var t=e.length;if(t<9||e.charCodeAt(t-1)!==95||e.charCodeAt(t-2)!==95||e.charCodeAt(t-3)!==111||e.charCodeAt(t-4)!==116||e.charCodeAt(t-5)!==111||e.charCodeAt(t-6)!==114||e.charCodeAt(t-7)!==112||e.charCodeAt(t-8)!==95||e.charCodeAt(t-9)!==95)return!1;for(var r=t-10;r>=0;r--)if(e.charCodeAt(r)!==36)return!1;return!0}function ki(e,t,r){var n=K(e.source,t.source);return n!==0||(n=e.originalLine-t.originalLine,n!==0)||(n=e.originalColumn-t.originalColumn,n!==0||r)||(n=e.generatedColumn-t.generatedColumn,n!==0)||(n=e.generatedLine-t.generatedLine,n!==0)?n:K(e.name,t.name)}N.compareByOriginalPositions=ki;function Si(e,t,r){var n;return n=e.originalLine-t.originalLine,n!==0||(n=e.originalColumn-t.originalColumn,n!==0||r)||(n=e.generatedColumn-t.generatedColumn,n!==0)||(n=e.generatedLine-t.generatedLine,n!==0)?n:K(e.name,t.name)}N.compareByOriginalPositionsNoSource=Si;function gi(e,t,r){var n=e.generatedLine-t.generatedLine;return n!==0||(n=e.generatedColumn-t.generatedColumn,n!==0||r)||(n=K(e.source,t.source),n!==0)||(n=e.originalLine-t.originalLine,n!==0)||(n=e.originalColumn-t.originalColumn,n!==0)?n:K(e.name,t.name)}N.compareByGeneratedPositionsDeflated=gi;function Ci(e,t,r){var n=e.generatedColumn-t.generatedColumn;return n!==0||r||(n=K(e.source,t.source),n!==0)||(n=e.originalLine-t.originalLine,n!==0)||(n=e.originalColumn-t.originalColumn,n!==0)?n:K(e.name,t.name)}N.compareByGeneratedPositionsDeflatedNoLine=Ci;function K(e,t){return e===t?0:e===null?1:t===null?-1:e>t?1:-1}function yi(e,t){var r=e.generatedLine-t.generatedLine;return r!==0||(r=e.generatedColumn-t.generatedColumn,r!==0)||(r=K(e.source,t.source),r!==0)||(r=e.originalLine-t.originalLine,r!==0)||(r=e.originalColumn-t.originalColumn,r!==0)?r:K(e.name,t.name)}N.compareByGeneratedPositionsInflated=yi;function bi(e){return JSON.parse(e.replace(/^\)]}'[^\n]*\n/,""))}N.parseSourceMapInput=bi;function Li(e,t,r){if(t=t||"",e&&(e[e.length-1]!=="/"&&t[0]!=="/"&&(e+="/"),t=e+t),r){var n=Ct(r);if(!n)throw new Error("sourceMapURL could not be parsed");if(n.path){var s=n.path.lastIndexOf("/");s>=0&&(n.path=n.path.substring(0,s+1))}t=Ge(ft(n),t)}return ce(t)}N.computeSourceURL=Li});var Ke=lt(ze=>{var le=Bt(),he=Object.prototype.hasOwnProperty,it=typeof Map<"u";function Q(){this._array=[],this._set=it?new Map:Object.create(null)}Q.fromArray=function(t,r){for(var n=new Q,s=0,o=t.length;s=0)return r}else{var n=le.toSetString(t);if(he.call(this._set,n))return this._set[n]}throw new Error('"'+t+'" is not in the set.')};Q.prototype.at=function(t){if(t>=0&&t{var Qe=Bt();function Ti(e,t){var r=e.generatedLine,n=t.generatedLine,s=e.generatedColumn,o=t.generatedColumn;return n>r||n==r&&o>=s||Qe.compareByGeneratedPositionsInflated(e,t)<=0}function Ut(){this._array=[],this._sorted=!0,this._last={generatedLine:-1,generatedColumn:0}}Ut.prototype.unsortedForEach=function(t,r){this._array.forEach(t,r)};Ut.prototype.add=function(t){Ti(this._last,t)?(this._last=t,this._array.push(t)):(this._sorted=!1,this._array.push(t))};Ut.prototype.toArray=function(){return this._sorted||(this._array.sort(Qe.compareByGeneratedPositionsInflated),this._sorted=!0),this._array};$e.MappingList=Ut});var Ze=lt(Je=>{var yt=Ve(),v=Bt(),Wt=Ke().ArraySet,vi=Xe().MappingList;function W(e){e||(e={}),this._file=v.getArg(e,"file",null),this._sourceRoot=v.getArg(e,"sourceRoot",null),this._skipValidation=v.getArg(e,"skipValidation",!1),this._sources=new Wt,this._names=new Wt,this._mappings=new vi,this._sourcesContents=null}W.prototype._version=3;W.fromSourceMap=function(t){var r=t.sourceRoot,n=new W({file:t.file,sourceRoot:r});return t.eachMapping(function(s){var o={generated:{line:s.generatedLine,column:s.generatedColumn}};s.source!=null&&(o.source=s.source,r!=null&&(o.source=v.relative(r,o.source)),o.original={line:s.originalLine,column:s.originalColumn},s.name!=null&&(o.name=s.name)),n.addMapping(o)}),t.sources.forEach(function(s){var o=s;r!==null&&(o=v.relative(r,s)),n._sources.has(o)||n._sources.add(o);var a=t.sourceContentFor(s);a!=null&&n.setSourceContent(s,a)}),n};W.prototype.addMapping=function(t){var r=v.getArg(t,"generated"),n=v.getArg(t,"original",null),s=v.getArg(t,"source",null),o=v.getArg(t,"name",null);this._skipValidation||this._validateMapping(r,n,s,o),s!=null&&(s=String(s),this._sources.has(s)||this._sources.add(s)),o!=null&&(o=String(o),this._names.has(o)||this._names.add(o)),this._mappings.add({generatedLine:r.line,generatedColumn:r.column,originalLine:n!=null&&n.line,originalColumn:n!=null&&n.column,source:s,name:o})};W.prototype.setSourceContent=function(t,r){var n=t;this._sourceRoot!=null&&(n=v.relative(this._sourceRoot,n)),r!=null?(this._sourcesContents||(this._sourcesContents=Object.create(null)),this._sourcesContents[v.toSetString(n)]=r):this._sourcesContents&&(delete this._sourcesContents[v.toSetString(n)],Object.keys(this._sourcesContents).length===0&&(this._sourcesContents=null))};W.prototype.applySourceMap=function(t,r,n){var s=r;if(r==null){if(t.file==null)throw new Error(`SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map's "file" property. Both were omitted.`);s=t.file}var o=this._sourceRoot;o!=null&&(s=v.relative(o,s));var a=new Wt,h=new Wt;this._mappings.unsortedForEach(function(l){if(l.source===s&&l.originalLine!=null){var i=t.originalPositionFor({line:l.originalLine,column:l.originalColumn});i.source!=null&&(l.source=i.source,n!=null&&(l.source=v.join(n,l.source)),o!=null&&(l.source=v.relative(o,l.source)),l.originalLine=i.line,l.originalColumn=i.column,i.name!=null&&(l.name=i.name))}var c=l.source;c!=null&&!a.has(c)&&a.add(c);var f=l.name;f!=null&&!h.has(f)&&h.add(f)},this),this._sources=a,this._names=h,t.sources.forEach(function(l){var i=t.sourceContentFor(l);i!=null&&(n!=null&&(l=v.join(n,l)),o!=null&&(l=v.relative(o,l)),this.setSourceContent(l,i))},this)};W.prototype._validateMapping=function(t,r,n,s){if(r&&typeof r.line!="number"&&typeof r.column!="number")throw new Error("original.line and original.column are not numbers -- you probably meant to omit the original mapping entirely and only map the generated position. If so, pass null for the original mapping instead of an object with empty or null values.");if(!(t&&"line"in t&&"column"in t&&t.line>0&&t.column>=0&&!r&&!n&&!s)){if(t&&"line"in t&&"column"in t&&r&&"line"in r&&"column"in r&&t.line>0&&t.column>=0&&r.line>0&&r.column>=0&&n)return;throw new Error("Invalid mapping: "+JSON.stringify({generated:t,source:n,original:r,name:s}))}};W.prototype._serializeMappings=function(){for(var t=0,r=1,n=0,s=0,o=0,a=0,h="",l,i,c,f,k=this._mappings.toArray(),S=0,T=k.length;S0){if(!v.compareByGeneratedPositionsInflated(i,k[S-1]))continue;l+=","}l+=yt.encode(i.generatedColumn-t),t=i.generatedColumn,i.source!=null&&(f=this._sources.indexOf(i.source),l+=yt.encode(f-a),a=f,l+=yt.encode(i.originalLine-1-s),s=i.originalLine-1,l+=yt.encode(i.originalColumn-n),n=i.originalColumn,i.name!=null&&(c=this._names.indexOf(i.name),l+=yt.encode(c-o),o=c)),h+=l}return h};W.prototype._generateSourcesContent=function(t,r){return t.map(function(n){if(!this._sourcesContents)return null;r!=null&&(n=v.relative(r,n));var s=v.toSetString(n);return Object.prototype.hasOwnProperty.call(this._sourcesContents,s)?this._sourcesContents[s]:null},this)};W.prototype.toJSON=function(){var t={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};return this._file!=null&&(t.file=this._file),this._sourceRoot!=null&&(t.sourceRoot=this._sourceRoot),this._sourcesContents&&(t.sourcesContent=this._generateSourcesContent(t.sources,t.sourceRoot)),t};W.prototype.toString=function(){return JSON.stringify(this.toJSON())};Je.SourceMapGenerator=W});function I(e){return e>=48&&e<=57}function z(e){return I(e)||e>=65&&e<=70||e>=97&&e<=102}function Et(e){return e>=65&&e<=90}function ti(e){return e>=97&&e<=122}function ei(e){return Et(e)||ti(e)}function ri(e){return e>=128}function vt(e){return ei(e)||ri(e)||e===95}function wt(e){return vt(e)||I(e)||e===45}function ni(e){return e>=0&&e<=8||e===11||e>=14&&e<=31||e===127}function dt(e){return e===10||e===13||e===12}function $(e){return dt(e)||e===32||e===9}function R(e,t){return!(e!==92||dt(t)||t===0)}function At(e,t,r){return e===45?vt(t)||t===45||R(t,r):vt(e)?!0:e===92?R(e,t):!1}function Nt(e,t,r){return e===43||e===45?I(t)?2:t===46&&I(r)?3:0:e===46?I(t)?2:0:I(e)?1:0}function It(e){return e===65279||e===65534?1:0}var Xt=new Array(128),ii=128,xt=130,Jt=131,Dt=132,Zt=133;for(let e=0;ee.length)return!1;for(let s=t;s=0&&$(e.charCodeAt(t));t--);return t+1}function kt(e,t){for(;t=55296&&t<=57343||t>1114111)&&(t=65533),String.fromCodePoint(t)}var gt=["EOF-token","ident-token","function-token","at-keyword-token","hash-token","string-token","bad-string-token","url-token","bad-url-token","delim-token","number-token","percentage-token","dimension-token","whitespace-token","CDO-token","CDC-token","colon-token","semicolon-token","comma-token","[-token","]-token","(-token",")-token","{-token","}-token","comment-token"];function ut(e=null,t){return e===null||e.length0?It(t.charCodeAt(0)):0,s=ut(e.lines,r),o=ut(e.columns,r),a=e.startLine,h=e.startColumn;for(let l=n;l{}){t=String(t||"");let n=t.length,s=ut(this.offsetAndType,t.length+1),o=ut(this.balance,t.length+1),a=0,h=0,l=0,i=-1;for(this.offsetAndType=null,this.balance=null,r(t,(c,f,k)=>{switch(c){default:o[a]=n;break;case h:{let S=l&M;for(l=o[S],h=l>>V,o[a]=S,o[S++]=a;S>V:0}lookupTypeNonSC(t){for(let r=this.tokenIndex;r>V;if(n!==13&&n!==25&&t--===0)return n}return 0}lookupOffset(t){return t+=this.tokenIndex,t>V;if(n!==13&&n!==25&&t--===0)return r-this.tokenIndex}return 0}lookupValue(t,r){return t+=this.tokenIndex,t0?t>V,this.tokenEnd=r&M):(this.tokenIndex=this.tokenCount,this.next())}next(){let t=this.tokenIndex+1;t>V,this.tokenEnd=t&M):(this.eof=!0,this.tokenIndex=this.tokenCount,this.tokenType=0,this.tokenStart=this.tokenEnd=this.source.length)}skipSC(){for(;this.tokenType===13||this.tokenType===25;)this.next()}skipUntilBalanced(t,r){let n=t,s,o;t:for(;n0?this.offsetAndType[n-1]&M:this.firstCharOffset,r(this.source.charCodeAt(o))){case 1:break t;case 2:n++;break t;default:this.balance[s]===n&&(n=s)}}this.skip(n-this.tokenIndex)}forEachToken(t){for(let r=0,n=this.firstCharOffset;r>V;n=a,t(h,s,a,r)}}dump(){let t=new Array(this.tokenCount);return this.forEachToken((r,n,s,o)=>{t[o]={idx:o,type:gt[r],chunk:this.source.substring(n,s),balance:this.balance[o]}}),t}};function Mt(e,t){function r(f){return f=e.length){ife,spec:()=>Ni});var Ei=43,wi=45,ue=(e,t)=>{if(e===9&&(e=t),typeof e=="string"){let r=e.charCodeAt(0);return r>127?32768:r<<8}return e},nr=[[1,1],[1,2],[1,7],[1,8],[1,"-"],[1,10],[1,11],[1,12],[1,15],[1,21],[3,1],[3,2],[3,7],[3,8],[3,"-"],[3,10],[3,11],[3,12],[3,15],[4,1],[4,2],[4,7],[4,8],[4,"-"],[4,10],[4,11],[4,12],[4,15],[12,1],[12,2],[12,7],[12,8],[12,"-"],[12,10],[12,11],[12,12],[12,15],["#",1],["#",2],["#",7],["#",8],["#","-"],["#",10],["#",11],["#",12],["#",15],["-",1],["-",2],["-",7],["-",8],["-","-"],["-",10],["-",11],["-",12],["-",15],[10,1],[10,2],[10,7],[10,8],[10,10],[10,11],[10,12],[10,"%"],[10,15],["@",1],["@",2],["@",7],["@",8],["@","-"],["@",15],[".",10],[".",11],[".",12],["+",10],["+",11],["+",12],["/","*"]],Ai=nr.concat([[1,4],[12,4],[4,4],[3,21],[3,5],[3,16],[11,11],[11,12],[11,2],[11,"-"],[22,1],[22,2],[22,11],[22,12],[22,4],[22,"-"]]);function ir(e){let t=new Set(e.map(([r,n])=>ue(r)<<16|ue(n)));return function(r,n,s){let o=ue(n,s),a=s.charCodeAt(0);return(a===wi&&n!==1&&n!==2&&n!==15||a===Ei?t.has(r<<16|a<<8):t.has(r<<16|o))&&this.emit(" ",13,!0),o}}var Ni=ir(nr),fe=ir(Ai);var Ii=92;function Di(e,t){if(typeof t=="function"){let r=null;e.children.forEach(n=>{r!==null&&t.call(this,r),this.node(n),r=n});return}e.children.forEach(this.node,this)}function Pi(e){Mt(e,(t,r,n)=>{this.token(t,e.slice(r,n))})}function sr(e){let t=new Map;for(let[r,n]of Object.entries(e.node))typeof(n.generate||n)=="function"&&t.set(r,n.generate||n);return function(r,n){let s="",o=0,a={node(l){if(t.has(l.type))t.get(l.type).call(h,l);else throw new Error("Unknown node type: "+l.type)},tokenBefore:fe,token(l,i){o=this.tokenBefore(o,l,i),this.emit(i,l,!1),l===9&&i.charCodeAt(0)===Ii&&this.emit(` +`,13,!0)},emit(l){s+=l},result(){return s}};n&&(typeof n.decorator=="function"&&(a=n.decorator(a)),n.sourceMap&&(a=rr(a)),n.mode in Vt&&(a.tokenBefore=Vt[n.mode]));let h={node:l=>a.node(l),children:Di,token:(l,i)=>a.token(l,i),tokenize:Pi};return a.node(r),a.result()}}var Se={};$t(Se,{AnPlusB:()=>ar,Atrule:()=>cr,AtrulePrelude:()=>lr,AttributeSelector:()=>fr,Block:()=>pr,Brackets:()=>mr,CDC:()=>dr,CDO:()=>xr,ClassSelector:()=>Sr,Combinator:()=>yr,Comment:()=>br,Condition:()=>Lr,Declaration:()=>Tr,DeclarationList:()=>vr,Dimension:()=>Er,Feature:()=>wr,FeatureFunction:()=>Ar,FeatureRange:()=>Nr,Function:()=>Ir,GeneralEnclosed:()=>Dr,Hash:()=>Pr,IdSelector:()=>_r,Identifier:()=>Rr,Layer:()=>Mr,LayerList:()=>Br,MediaQuery:()=>Ur,MediaQueryList:()=>Wr,NestingSelector:()=>Hr,Nth:()=>qr,Number:()=>Yr,Operator:()=>zr,Parentheses:()=>Kr,Percentage:()=>$r,PseudoClassSelector:()=>Jr,PseudoElementSelector:()=>tn,Ratio:()=>en,Raw:()=>nn,Rule:()=>sn,Scope:()=>on,Selector:()=>cn,SelectorList:()=>hn,String:()=>dn,StyleSheet:()=>xn,SupportsDeclaration:()=>kn,TypeSelector:()=>Cn,UnicodeRange:()=>yn,Url:()=>Ln,Value:()=>Tn,WhiteSpace:()=>vn});var Y=43,_=45,Ht=110,st=!0,Fi=!1;function Gt(e,t){let r=this.tokenStart+e,n=this.charCodeAt(r);for((n===Y||n===_)&&(t&&this.error("Number sign is not allowed"),r++);r0&&this.skip(e),t===0&&(r=this.charCodeAt(this.tokenStart),r!==Y&&r!==_&&this.error("Number sign is expected")),pt.call(this,t!==0),t===_?"-"+this.consume(10):this.consume(10)}function or(){let e=this.tokenStart,t=null,r=null;if(this.tokenType===10)pt.call(this,Fi),r=this.consume(10);else if(this.tokenType===1&&this.cmpChar(this.tokenStart,_))switch(t="-1",Z.call(this,1,Ht),this.tokenEnd-this.tokenStart){case 2:this.next(),r=pe.call(this);break;case 3:Z.call(this,2,_),this.next(),this.skipSC(),pt.call(this,st),r="-"+this.consume(10);break;default:Z.call(this,2,_),Gt.call(this,3,st),this.next(),r=this.substrToCursor(e+2)}else if(this.tokenType===1||this.isDelim(Y)&&this.lookupType(1)===1){let n=0;switch(t="1",this.isDelim(Y)&&(n=1,this.next()),Z.call(this,0,Ht),this.tokenEnd-this.tokenStart){case 1:this.next(),r=pe.call(this);break;case 2:Z.call(this,1,_),this.next(),this.skipSC(),pt.call(this,st),r="-"+this.consume(10);break;default:Z.call(this,1,_),Gt.call(this,2,st),this.next(),r=this.substrToCursor(e+n+1)}}else if(this.tokenType===12){let n=this.charCodeAt(this.tokenStart),s=n===Y||n===_,o=this.tokenStart+s;for(;o{t.type==="Declaration"&&this.token(17,";")})}function mr(e){this.token(9,"["),this.children(e),this.token(9,"]")}function dr(){this.token(15,"-->")}function xr(){this.token(14,"\n\n return {\n type: 'CDC',\n loc: this.getLocation(start, this.tokenStart)\n };\n}\n\nexport function generate() {\n this.token(CDC, '-->');\n}\n", "import { CDO } from '../../tokenizer/index.js';\n\nexport const name = 'CDO';\nexport const structure = [];\n\nexport function parse() {\n const start = this.tokenStart;\n\n this.eat(CDO); // \n child = this.CDC();\n break;\n\n // CSS Syntax Module Level 3\n // \u00A72.2 Error handling\n // At the \"top level\" of a stylesheet, an starts an at-rule.\n case AtKeyword:\n child = this.parseWithFallback(this.Atrule, consumeRaw);\n break;\n\n // Anything else starts a qualified rule ...\n default:\n child = this.parseWithFallback(this.Rule, consumeRaw);\n }\n\n children.push(child);\n }\n\n return {\n type: 'StyleSheet',\n loc: this.getLocation(start, this.tokenStart),\n children\n };\n}\n\nexport function generate(node) {\n this.children(node);\n}\n", "import {\n LeftParenthesis,\n RightParenthesis\n} from '../../tokenizer/index.js';\n\nexport const name = 'SupportsDeclaration';\nexport const structure = {\n declaration: 'Declaration'\n};\n\nexport function parse() {\n const start = this.tokenStart;\n\n this.eat(LeftParenthesis);\n this.skipSC();\n\n const declaration = this.Declaration();\n\n if (!this.eof) {\n this.eat(RightParenthesis);\n }\n\n return {\n type: 'SupportsDeclaration',\n loc: this.getLocation(start, this.tokenStart),\n declaration\n };\n}\n\nexport function generate(node) {\n this.token(LeftParenthesis, '(');\n this.node(node.declaration);\n this.token(RightParenthesis, ')');\n}\n", "import { Ident } from '../../tokenizer/index.js';\n\nconst ASTERISK = 0x002A; // U+002A ASTERISK (*)\nconst VERTICALLINE = 0x007C; // U+007C VERTICAL LINE (|)\n\nfunction eatIdentifierOrAsterisk() {\n if (this.tokenType !== Ident &&\n this.isDelim(ASTERISK) === false) {\n this.error('Identifier or asterisk is expected');\n }\n\n this.next();\n}\n\nexport const name = 'TypeSelector';\nexport const structure = {\n name: String\n};\n\n// ident\n// ident|ident\n// ident|*\n// *\n// *|ident\n// *|*\n// |ident\n// |*\nexport function parse() {\n const start = this.tokenStart;\n\n if (this.isDelim(VERTICALLINE)) {\n this.next();\n eatIdentifierOrAsterisk.call(this);\n } else {\n eatIdentifierOrAsterisk.call(this);\n\n if (this.isDelim(VERTICALLINE)) {\n this.next();\n eatIdentifierOrAsterisk.call(this);\n }\n }\n\n return {\n type: 'TypeSelector',\n loc: this.getLocation(start, this.tokenStart),\n name: this.substrToCursor(start)\n };\n}\n\nexport function generate(node) {\n this.tokenize(node.name);\n}\n", "import {\n isHexDigit,\n Ident,\n Number,\n Dimension\n} from '../../tokenizer/index.js';\n\nconst PLUSSIGN = 0x002B; // U+002B PLUS SIGN (+)\nconst HYPHENMINUS = 0x002D; // U+002D HYPHEN-MINUS (-)\nconst QUESTIONMARK = 0x003F; // U+003F QUESTION MARK (?)\n\nfunction eatHexSequence(offset, allowDash) {\n let len = 0;\n\n for (let pos = this.tokenStart + offset; pos < this.tokenEnd; pos++) {\n const code = this.charCodeAt(pos);\n\n if (code === HYPHENMINUS && allowDash && len !== 0) {\n eatHexSequence.call(this, offset + len + 1, false);\n return -1;\n }\n\n if (!isHexDigit(code)) {\n this.error(\n allowDash && len !== 0\n ? 'Hyphen minus' + (len < 6 ? ' or hex digit' : '') + ' is expected'\n : (len < 6 ? 'Hex digit is expected' : 'Unexpected input'),\n pos\n );\n }\n\n if (++len > 6) {\n this.error('Too many hex digits', pos);\n };\n }\n\n this.next();\n return len;\n}\n\nfunction eatQuestionMarkSequence(max) {\n let count = 0;\n\n while (this.isDelim(QUESTIONMARK)) {\n if (++count > max) {\n this.error('Too many question marks');\n }\n\n this.next();\n }\n}\n\nfunction startsWith(code) {\n if (this.charCodeAt(this.tokenStart) !== code) {\n this.error((code === PLUSSIGN ? 'Plus sign' : 'Hyphen minus') + ' is expected');\n }\n}\n\n// https://drafts.csswg.org/css-syntax/#urange\n// Informally, the production has three forms:\n// U+0001\n// Defines a range consisting of a single code point, in this case the code point \"1\".\n// U+0001-00ff\n// Defines a range of codepoints between the first and the second value, in this case\n// the range between \"1\" and \"ff\" (255 in decimal) inclusive.\n// U+00??\n// Defines a range of codepoints where the \"?\" characters range over all hex digits,\n// in this case defining the same as the value U+0000-00ff.\n// In each form, a maximum of 6 digits is allowed for each hexadecimal number (if you treat \"?\" as a hexadecimal digit).\n//\n// =\n// u '+' '?'* |\n// u '?'* |\n// u '?'* |\n// u |\n// u |\n// u '+' '?'+\nfunction scanUnicodeRange() {\n let hexLength = 0;\n\n switch (this.tokenType) {\n case Number:\n // u '?'*\n // u \n // u \n hexLength = eatHexSequence.call(this, 1, true);\n\n if (this.isDelim(QUESTIONMARK)) {\n eatQuestionMarkSequence.call(this, 6 - hexLength);\n break;\n }\n\n if (this.tokenType === Dimension ||\n this.tokenType === Number) {\n startsWith.call(this, HYPHENMINUS);\n eatHexSequence.call(this, 1, false);\n break;\n }\n\n break;\n\n case Dimension:\n // u '?'*\n hexLength = eatHexSequence.call(this, 1, true);\n\n if (hexLength > 0) {\n eatQuestionMarkSequence.call(this, 6 - hexLength);\n }\n\n break;\n\n default:\n // u '+' '?'*\n // u '+' '?'+\n this.eatDelim(PLUSSIGN);\n\n if (this.tokenType === Ident) {\n hexLength = eatHexSequence.call(this, 0, true);\n if (hexLength > 0) {\n eatQuestionMarkSequence.call(this, 6 - hexLength);\n }\n break;\n }\n\n if (this.isDelim(QUESTIONMARK)) {\n this.next();\n eatQuestionMarkSequence.call(this, 5);\n break;\n }\n\n this.error('Hex digit or question mark is expected');\n }\n}\n\nexport const name = 'UnicodeRange';\nexport const structure = {\n value: String\n};\n\nexport function parse() {\n const start = this.tokenStart;\n\n // U or u\n this.eatIdent('u');\n scanUnicodeRange.call(this);\n\n return {\n type: 'UnicodeRange',\n loc: this.getLocation(start, this.tokenStart),\n value: this.substrToCursor(start)\n };\n}\n\nexport function generate(node) {\n this.tokenize(node.value);\n}\n", "import {\n isHexDigit,\n isWhiteSpace,\n isValidEscape,\n consumeEscaped,\n decodeEscaped\n} from '../tokenizer/index.js';\n\nconst SPACE = 0x0020; // U+0020 SPACE\nconst REVERSE_SOLIDUS = 0x005c; // U+005C REVERSE SOLIDUS (\\)\nconst QUOTATION_MARK = 0x0022; // \"\nconst APOSTROPHE = 0x0027; // '\nconst LEFTPARENTHESIS = 0x0028; // U+0028 LEFT PARENTHESIS (()\nconst RIGHTPARENTHESIS = 0x0029; // U+0029 RIGHT PARENTHESIS ())\n\nexport function decode(str) {\n const len = str.length;\n let start = 4; // length of \"url(\"\n let end = str.charCodeAt(len - 1) === RIGHTPARENTHESIS ? len - 2 : len - 1;\n let decoded = '';\n\n while (start < end && isWhiteSpace(str.charCodeAt(start))) {\n start++;\n }\n\n while (start < end && isWhiteSpace(str.charCodeAt(end))) {\n end--;\n }\n\n for (let i = start; i <= end; i++) {\n let code = str.charCodeAt(i);\n\n if (code === REVERSE_SOLIDUS) {\n // special case at the ending\n if (i === end) {\n // if the next input code point is EOF, do nothing\n // otherwise include last left parenthesis as escaped\n if (i !== len - 1) {\n decoded = str.substr(i + 1);\n }\n break;\n }\n\n code = str.charCodeAt(++i);\n\n // consume escaped\n if (isValidEscape(REVERSE_SOLIDUS, code)) {\n const escapeStart = i - 1;\n const escapeEnd = consumeEscaped(str, escapeStart);\n\n i = escapeEnd - 1;\n decoded += decodeEscaped(str.substring(escapeStart + 1, escapeEnd));\n } else {\n // \\r\\n\n if (code === 0x000d && str.charCodeAt(i + 1) === 0x000a) {\n i++;\n }\n }\n } else {\n decoded += str[i];\n }\n }\n\n return decoded;\n}\n\nexport function encode(str) {\n let encoded = '';\n let wsBeforeHexIsNeeded = false;\n\n for (let i = 0; i < str.length; i++) {\n const code = str.charCodeAt(i);\n\n // If the character is NULL (U+0000), then the REPLACEMENT CHARACTER (U+FFFD).\n if (code === 0x0000) {\n encoded += '\\uFFFD';\n continue;\n }\n\n // If the character is in the range [\\1-\\1f] (U+0001 to U+001F) or is U+007F,\n // the character escaped as code point.\n // Note: Do not compare with 0x0001 since 0x0000 is precessed before\n if (code <= 0x001f || code === 0x007F) {\n encoded += '\\\\' + code.toString(16);\n wsBeforeHexIsNeeded = true;\n continue;\n }\n\n if (code === SPACE ||\n code === REVERSE_SOLIDUS ||\n code === QUOTATION_MARK ||\n code === APOSTROPHE ||\n code === LEFTPARENTHESIS ||\n code === RIGHTPARENTHESIS) {\n encoded += '\\\\' + str.charAt(i);\n wsBeforeHexIsNeeded = false;\n } else {\n if (wsBeforeHexIsNeeded && isHexDigit(code)) {\n encoded += ' ';\n }\n\n encoded += str.charAt(i);\n wsBeforeHexIsNeeded = false;\n }\n }\n\n return 'url(' + encoded + ')';\n}\n", "import * as url from '../../utils/url.js';\nimport * as string from '../../utils/string.js';\nimport {\n Function as FunctionToken,\n String as StringToken,\n Url,\n RightParenthesis\n} from '../../tokenizer/index.js';\n\nexport const name = 'Url';\nexport const structure = {\n value: String\n};\n\n// | )\nexport function parse() {\n const start = this.tokenStart;\n let value;\n\n switch (this.tokenType) {\n case Url:\n value = url.decode(this.consume(Url));\n break;\n\n case FunctionToken:\n if (!this.cmpStr(this.tokenStart, this.tokenEnd, 'url(')) {\n this.error('Function name must be `url`');\n }\n\n this.eat(FunctionToken);\n this.skipSC();\n value = string.decode(this.consume(StringToken));\n this.skipSC();\n if (!this.eof) {\n this.eat(RightParenthesis);\n }\n break;\n\n default:\n this.error('Url or Function is expected');\n }\n\n return {\n type: 'Url',\n loc: this.getLocation(start, this.tokenStart),\n value\n };\n}\n\nexport function generate(node) {\n this.token(Url, url.encode(node.value));\n}\n", "export const name = 'Value';\nexport const structure = {\n children: [[]]\n};\n\nexport function parse() {\n const start = this.tokenStart;\n const children = this.readSequence(this.scope.Value);\n\n return {\n type: 'Value',\n loc: this.getLocation(start, this.tokenStart),\n children\n };\n}\n\nexport function generate(node) {\n this.children(node);\n}\n", "import { WhiteSpace } from '../../tokenizer/index.js';\n\nconst SPACE = Object.freeze({\n type: 'WhiteSpace',\n loc: null,\n value: ' '\n});\n\nexport const name = 'WhiteSpace';\nexport const structure = {\n value: String\n};\n\nexport function parse() {\n this.eat(WhiteSpace);\n return SPACE;\n\n // return {\n // type: 'WhiteSpace',\n // loc: this.getLocation(this.tokenStart, this.tokenEnd),\n // value: this.consume(WHITESPACE)\n // };\n}\n\nexport function generate(node) {\n this.token(WhiteSpace, node.value);\n}\n", "import * as node from '../node/index-generate.js';\n\nexport default {\n node\n};\n", "import { createGenerator } from './create.js';\nimport config from '../syntax/config/generator.js';\n\nexport default createGenerator(config);\n", "//\n// list\n// \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n// \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500head \u2502\n// \u2502 \u2502 tail\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n// \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2502\n// \u25BC \u25BC\n// item item item item\n// \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n// null \u25C0\u2500\u2500\u253C\u2500prev \u2502\u25C0\u2500\u2500\u2500\u253C\u2500prev \u2502\u25C0\u2500\u2500\u2500\u253C\u2500prev \u2502\u25C0\u2500\u2500\u2500\u253C\u2500prev \u2502\n// \u2502 next\u2500\u253C\u2500\u2500\u2500\u25B6\u2502 next\u2500\u253C\u2500\u2500\u2500\u25B6\u2502 next\u2500\u253C\u2500\u2500\u2500\u25B6\u2502 next\u2500\u253C\u2500\u2500\u25B6 null\n// \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2524 \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2524 \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2524 \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n// \u2502 data \u2502 \u2502 data \u2502 \u2502 data \u2502 \u2502 data \u2502\n// \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n//\n\nlet releasedCursors = null;\n\nexport class List {\n static createItem(data) {\n return {\n prev: null,\n next: null,\n data\n };\n }\n\n constructor() {\n this.head = null;\n this.tail = null;\n this.cursor = null;\n }\n createItem(data) {\n return List.createItem(data);\n }\n\n // cursor helpers\n allocateCursor(prev, next) {\n let cursor;\n\n if (releasedCursors !== null) {\n cursor = releasedCursors;\n releasedCursors = releasedCursors.cursor;\n cursor.prev = prev;\n cursor.next = next;\n cursor.cursor = this.cursor;\n } else {\n cursor = {\n prev,\n next,\n cursor: this.cursor\n };\n }\n\n this.cursor = cursor;\n\n return cursor;\n }\n releaseCursor() {\n const { cursor } = this;\n\n this.cursor = cursor.cursor;\n cursor.prev = null;\n cursor.next = null;\n cursor.cursor = releasedCursors;\n releasedCursors = cursor;\n }\n updateCursors(prevOld, prevNew, nextOld, nextNew) {\n let { cursor } = this;\n\n while (cursor !== null) {\n if (cursor.prev === prevOld) {\n cursor.prev = prevNew;\n }\n\n if (cursor.next === nextOld) {\n cursor.next = nextNew;\n }\n\n cursor = cursor.cursor;\n }\n }\n *[Symbol.iterator]() {\n for (let cursor = this.head; cursor !== null; cursor = cursor.next) {\n yield cursor.data;\n }\n }\n\n // getters\n get size() {\n let size = 0;\n\n for (let cursor = this.head; cursor !== null; cursor = cursor.next) {\n size++;\n }\n\n return size;\n }\n get isEmpty() {\n return this.head === null;\n }\n get first() {\n return this.head && this.head.data;\n }\n get last() {\n return this.tail && this.tail.data;\n }\n\n // convertors\n fromArray(array) {\n let cursor = null;\n this.head = null;\n\n for (let data of array) {\n const item = List.createItem(data);\n\n if (cursor !== null) {\n cursor.next = item;\n } else {\n this.head = item;\n }\n\n item.prev = cursor;\n cursor = item;\n }\n\n this.tail = cursor;\n return this;\n }\n toArray() {\n return [...this];\n }\n toJSON() {\n return [...this];\n }\n\n // array-like methods\n forEach(fn, thisArg = this) {\n // push cursor\n const cursor = this.allocateCursor(null, this.head);\n\n while (cursor.next !== null) {\n const item = cursor.next;\n cursor.next = item.next;\n fn.call(thisArg, item.data, item, this);\n }\n\n // pop cursor\n this.releaseCursor();\n }\n forEachRight(fn, thisArg = this) {\n // push cursor\n const cursor = this.allocateCursor(this.tail, null);\n\n while (cursor.prev !== null) {\n const item = cursor.prev;\n cursor.prev = item.prev;\n fn.call(thisArg, item.data, item, this);\n }\n\n // pop cursor\n this.releaseCursor();\n }\n reduce(fn, initialValue, thisArg = this) {\n // push cursor\n let cursor = this.allocateCursor(null, this.head);\n let acc = initialValue;\n let item;\n\n while (cursor.next !== null) {\n item = cursor.next;\n cursor.next = item.next;\n\n acc = fn.call(thisArg, acc, item.data, item, this);\n }\n\n // pop cursor\n this.releaseCursor();\n\n return acc;\n }\n reduceRight(fn, initialValue, thisArg = this) {\n // push cursor\n let cursor = this.allocateCursor(this.tail, null);\n let acc = initialValue;\n let item;\n\n while (cursor.prev !== null) {\n item = cursor.prev;\n cursor.prev = item.prev;\n\n acc = fn.call(thisArg, acc, item.data, item, this);\n }\n\n // pop cursor\n this.releaseCursor();\n\n return acc;\n }\n some(fn, thisArg = this) {\n for (let cursor = this.head; cursor !== null; cursor = cursor.next) {\n if (fn.call(thisArg, cursor.data, cursor, this)) {\n return true;\n }\n }\n\n return false;\n }\n map(fn, thisArg = this) {\n const result = new List();\n\n for (let cursor = this.head; cursor !== null; cursor = cursor.next) {\n result.appendData(fn.call(thisArg, cursor.data, cursor, this));\n }\n\n return result;\n }\n filter(fn, thisArg = this) {\n const result = new List();\n\n for (let cursor = this.head; cursor !== null; cursor = cursor.next) {\n if (fn.call(thisArg, cursor.data, cursor, this)) {\n result.appendData(cursor.data);\n }\n }\n\n return result;\n }\n\n nextUntil(start, fn, thisArg = this) {\n if (start === null) {\n return;\n }\n\n // push cursor\n const cursor = this.allocateCursor(null, start);\n\n while (cursor.next !== null) {\n const item = cursor.next;\n cursor.next = item.next;\n if (fn.call(thisArg, item.data, item, this)) {\n break;\n }\n }\n\n // pop cursor\n this.releaseCursor();\n }\n prevUntil(start, fn, thisArg = this) {\n if (start === null) {\n return;\n }\n\n // push cursor\n const cursor = this.allocateCursor(start, null);\n\n while (cursor.prev !== null) {\n const item = cursor.prev;\n cursor.prev = item.prev;\n if (fn.call(thisArg, item.data, item, this)) {\n break;\n }\n }\n\n // pop cursor\n this.releaseCursor();\n }\n\n // mutation\n clear() {\n this.head = null;\n this.tail = null;\n }\n copy() {\n const result = new List();\n\n for (let data of this) {\n result.appendData(data);\n }\n\n return result;\n }\n prepend(item) {\n // head\n // ^\n // item\n this.updateCursors(null, item, this.head, item);\n\n // insert to the beginning of the list\n if (this.head !== null) {\n // new item <- first item\n this.head.prev = item;\n // new item -> first item\n item.next = this.head;\n } else {\n // if list has no head, then it also has no tail\n // in this case tail points to the new item\n this.tail = item;\n }\n\n // head always points to new item\n this.head = item;\n return this;\n }\n prependData(data) {\n return this.prepend(List.createItem(data));\n }\n append(item) {\n return this.insert(item);\n }\n appendData(data) {\n return this.insert(List.createItem(data));\n }\n insert(item, before = null) {\n if (before !== null) {\n // prev before\n // ^\n // item\n this.updateCursors(before.prev, item, before, item);\n\n if (before.prev === null) {\n // insert to the beginning of list\n if (this.head !== before) {\n throw new Error('before doesn\\'t belong to list');\n }\n // since head points to before therefore list doesn't empty\n // no need to check tail\n this.head = item;\n before.prev = item;\n item.next = before;\n this.updateCursors(null, item);\n } else {\n // insert between two items\n before.prev.next = item;\n item.prev = before.prev;\n before.prev = item;\n item.next = before;\n }\n } else {\n // tail\n // ^\n // item\n this.updateCursors(this.tail, item, null, item);\n\n // insert to the ending of the list\n if (this.tail !== null) {\n // last item -> new item\n this.tail.next = item;\n // last item <- new item\n item.prev = this.tail;\n } else {\n // if list has no tail, then it also has no head\n // in this case head points to new item\n this.head = item;\n }\n\n // tail always points to new item\n this.tail = item;\n }\n\n return this;\n }\n insertData(data, before) {\n return this.insert(List.createItem(data), before);\n }\n remove(item) {\n // item\n // ^\n // prev next\n this.updateCursors(item, item.prev, item, item.next);\n\n if (item.prev !== null) {\n item.prev.next = item.next;\n } else {\n if (this.head !== item) {\n throw new Error('item doesn\\'t belong to list');\n }\n\n this.head = item.next;\n }\n\n if (item.next !== null) {\n item.next.prev = item.prev;\n } else {\n if (this.tail !== item) {\n throw new Error('item doesn\\'t belong to list');\n }\n\n this.tail = item.prev;\n }\n\n item.prev = null;\n item.next = null;\n\n return item;\n }\n push(data) {\n this.insert(List.createItem(data));\n }\n pop() {\n return this.tail !== null ? this.remove(this.tail) : null;\n }\n unshift(data) {\n this.prepend(List.createItem(data));\n }\n shift() {\n return this.head !== null ? this.remove(this.head) : null;\n }\n prependList(list) {\n return this.insertList(list, this.head);\n }\n appendList(list) {\n return this.insertList(list);\n }\n insertList(list, before) {\n // ignore empty lists\n if (list.head === null) {\n return this;\n }\n\n if (before !== undefined && before !== null) {\n this.updateCursors(before.prev, list.tail, before, list.head);\n\n // insert in the middle of dist list\n if (before.prev !== null) {\n // before.prev <-> list.head\n before.prev.next = list.head;\n list.head.prev = before.prev;\n } else {\n this.head = list.head;\n }\n\n before.prev = list.tail;\n list.tail.next = before;\n } else {\n this.updateCursors(this.tail, list.tail, null, list.head);\n\n // insert to end of the list\n if (this.tail !== null) {\n // if destination list has a tail, then it also has a head,\n // but head doesn't change\n // dest tail -> source head\n this.tail.next = list.head;\n // dest tail <- source head\n list.head.prev = this.tail;\n } else {\n // if list has no a tail, then it also has no a head\n // in this case points head to new item\n this.head = list.head;\n }\n\n // tail always start point to new item\n this.tail = list.tail;\n }\n\n list.head = null;\n list.tail = null;\n return this;\n }\n replace(oldItem, newItemOrList) {\n if ('head' in newItemOrList) {\n this.insertList(newItemOrList, oldItem);\n } else {\n this.insert(newItemOrList, oldItem);\n }\n\n this.remove(oldItem);\n }\n}\n", "export function createCustomError(name, message) {\n // use Object.create(), because some VMs prevent setting line/column otherwise\n // (iOS Safari 10 even throws an exception)\n const error = Object.create(SyntaxError.prototype);\n const errorStack = new Error();\n\n return Object.assign(error, {\n name,\n message,\n get stack() {\n return (errorStack.stack || '').replace(/^(.+\\n){1,3}/, `${name}: ${message}\\n`);\n }\n });\n};\n", "import { createCustomError } from '../utils/create-custom-error.js';\n\nconst MAX_LINE_LENGTH = 100;\nconst OFFSET_CORRECTION = 60;\nconst TAB_REPLACEMENT = ' ';\n\nfunction sourceFragment({ source, line, column, baseLine, baseColumn }, extraLines) {\n function processLines(start, end) {\n return lines\n .slice(start, end)\n .map((line, idx) =>\n String(start + idx + 1).padStart(maxNumLength) + ' |' + line\n ).join('\\n');\n }\n\n const prelines = '\\n'.repeat(Math.max(baseLine - 1, 0));\n const precolumns = ' '.repeat(Math.max(baseColumn - 1, 0));\n const lines = (prelines + precolumns + source).split(/\\r\\n?|\\n|\\f/);\n const startLine = Math.max(1, line - extraLines) - 1;\n const endLine = Math.min(line + extraLines, lines.length + 1);\n const maxNumLength = Math.max(4, String(endLine).length) + 1;\n let cutLeft = 0;\n\n // column correction according to replaced tab before column\n column += (TAB_REPLACEMENT.length - 1) * (lines[line - 1].substr(0, column - 1).match(/\\t/g) || []).length;\n\n if (column > MAX_LINE_LENGTH) {\n cutLeft = column - OFFSET_CORRECTION + 3;\n column = OFFSET_CORRECTION - 2;\n }\n\n for (let i = startLine; i <= endLine; i++) {\n if (i >= 0 && i < lines.length) {\n lines[i] = lines[i].replace(/\\t/g, TAB_REPLACEMENT);\n lines[i] =\n (cutLeft > 0 && lines[i].length > cutLeft ? '\\u2026' : '') +\n lines[i].substr(cutLeft, MAX_LINE_LENGTH - 2) +\n (lines[i].length > cutLeft + MAX_LINE_LENGTH - 1 ? '\\u2026' : '');\n }\n }\n\n return [\n processLines(startLine, line),\n new Array(column + maxNumLength + 2).join('-') + '^',\n processLines(line, endLine)\n ].filter(Boolean)\n .join('\\n')\n .replace(/^(\\s+\\d+\\s+\\|\\n)+/, '')\n .replace(/\\n(\\s+\\d+\\s+\\|)+$/, '');\n}\n\nexport function SyntaxError(message, source, offset, line, column, baseLine = 1, baseColumn = 1) {\n const error = Object.assign(createCustomError('SyntaxError', message), {\n source,\n offset,\n line,\n column,\n sourceFragment(extraLines) {\n return sourceFragment({ source, line, column, baseLine, baseColumn }, isNaN(extraLines) ? 0 : extraLines);\n },\n get formattedMessage() {\n return (\n `Parse error: ${message}\\n` +\n sourceFragment({ source, line, column, baseLine, baseColumn }, 2)\n );\n }\n });\n\n return error;\n}\n", "import { WhiteSpace, Comment } from '../tokenizer/index.js';\n\nexport function readSequence(recognizer) {\n const children = this.createList();\n let space = false;\n const context = {\n recognizer\n };\n\n while (!this.eof) {\n switch (this.tokenType) {\n case Comment:\n this.next();\n continue;\n\n case WhiteSpace:\n space = true;\n this.next();\n continue;\n }\n\n let child = recognizer.getNode.call(this, context);\n\n if (child === undefined) {\n break;\n }\n\n if (space) {\n if (recognizer.onWhiteSpace) {\n recognizer.onWhiteSpace.call(this, child, children, context);\n }\n space = false;\n }\n\n children.push(child);\n }\n\n if (space && recognizer.onWhiteSpace) {\n recognizer.onWhiteSpace.call(this, null, children, context);\n }\n\n return children;\n};\n", "import { List } from '../utils/List.js';\nimport { SyntaxError } from './SyntaxError.js';\nimport {\n tokenize,\n OffsetToLocation,\n TokenStream,\n tokenNames,\n\n consumeNumber,\n findWhiteSpaceStart,\n cmpChar,\n cmpStr,\n\n WhiteSpace,\n Comment,\n Ident,\n Function as FunctionToken,\n Url,\n Hash,\n Percentage,\n Number as NumberToken\n} from '../tokenizer/index.js';\nimport { readSequence } from './sequence.js';\n\nconst NOOP = () => {};\nconst EXCLAMATIONMARK = 0x0021; // U+0021 EXCLAMATION MARK (!)\nconst NUMBERSIGN = 0x0023; // U+0023 NUMBER SIGN (#)\nconst SEMICOLON = 0x003B; // U+003B SEMICOLON (;)\nconst LEFTCURLYBRACKET = 0x007B; // U+007B LEFT CURLY BRACKET ({)\nconst NULL = 0;\n\nfunction createParseContext(name) {\n return function() {\n return this[name]();\n };\n}\n\nfunction fetchParseValues(dict) {\n const result = Object.create(null);\n\n for (const name of Object.keys(dict)) {\n const item = dict[name];\n const fn = item.parse || item;\n\n if (fn) {\n result[name] = fn;\n }\n }\n\n return result;\n}\n\nfunction processConfig(config) {\n const parseConfig = {\n context: Object.create(null),\n features: Object.assign(Object.create(null), config.features),\n scope: Object.assign(Object.create(null), config.scope),\n atrule: fetchParseValues(config.atrule),\n pseudo: fetchParseValues(config.pseudo),\n node: fetchParseValues(config.node)\n };\n\n for (const [name, context] of Object.entries(config.parseContext)) {\n switch (typeof context) {\n case 'function':\n parseConfig.context[name] = context;\n break;\n\n case 'string':\n parseConfig.context[name] = createParseContext(context);\n break;\n }\n }\n\n return {\n config: parseConfig,\n ...parseConfig,\n ...parseConfig.node\n };\n}\n\nexport function createParser(config) {\n let source = '';\n let filename = '';\n let needPositions = false;\n let onParseError = NOOP;\n let onParseErrorThrow = false;\n\n const locationMap = new OffsetToLocation();\n const parser = Object.assign(new TokenStream(), processConfig(config || {}), {\n parseAtrulePrelude: true,\n parseRulePrelude: true,\n parseValue: true,\n parseCustomProperty: false,\n\n readSequence,\n\n consumeUntilBalanceEnd: () => 0,\n consumeUntilLeftCurlyBracket(code) {\n return code === LEFTCURLYBRACKET ? 1 : 0;\n },\n consumeUntilLeftCurlyBracketOrSemicolon(code) {\n return code === LEFTCURLYBRACKET || code === SEMICOLON ? 1 : 0;\n },\n consumeUntilExclamationMarkOrSemicolon(code) {\n return code === EXCLAMATIONMARK || code === SEMICOLON ? 1 : 0;\n },\n consumeUntilSemicolonIncluded(code) {\n return code === SEMICOLON ? 2 : 0;\n },\n\n createList() {\n return new List();\n },\n createSingleNodeList(node) {\n return new List().appendData(node);\n },\n getFirstListNode(list) {\n return list && list.first;\n },\n getLastListNode(list) {\n return list && list.last;\n },\n\n parseWithFallback(consumer, fallback) {\n const startIndex = this.tokenIndex;\n\n try {\n return consumer.call(this);\n } catch (e) {\n if (onParseErrorThrow) {\n throw e;\n }\n\n this.skip(startIndex - this.tokenIndex);\n const fallbackNode = fallback.call(this);\n\n onParseErrorThrow = true;\n onParseError(e, fallbackNode);\n onParseErrorThrow = false;\n\n return fallbackNode;\n }\n },\n\n lookupNonWSType(offset) {\n let type;\n\n do {\n type = this.lookupType(offset++);\n if (type !== WhiteSpace && type !== Comment) {\n return type;\n }\n } while (type !== NULL);\n\n return NULL;\n },\n\n charCodeAt(offset) {\n return offset >= 0 && offset < source.length ? source.charCodeAt(offset) : 0;\n },\n substring(offsetStart, offsetEnd) {\n return source.substring(offsetStart, offsetEnd);\n },\n substrToCursor(start) {\n return this.source.substring(start, this.tokenStart);\n },\n\n cmpChar(offset, charCode) {\n return cmpChar(source, offset, charCode);\n },\n cmpStr(offsetStart, offsetEnd, str) {\n return cmpStr(source, offsetStart, offsetEnd, str);\n },\n\n consume(tokenType) {\n const start = this.tokenStart;\n\n this.eat(tokenType);\n\n return this.substrToCursor(start);\n },\n consumeFunctionName() {\n const name = source.substring(this.tokenStart, this.tokenEnd - 1);\n\n this.eat(FunctionToken);\n\n return name;\n },\n consumeNumber(type) {\n const number = source.substring(this.tokenStart, consumeNumber(source, this.tokenStart));\n\n this.eat(type);\n\n return number;\n },\n\n eat(tokenType) {\n if (this.tokenType !== tokenType) {\n const tokenName = tokenNames[tokenType].slice(0, -6).replace(/-/g, ' ').replace(/^./, m => m.toUpperCase());\n let message = `${/[[\\](){}]/.test(tokenName) ? `\"${tokenName}\"` : tokenName} is expected`;\n let offset = this.tokenStart;\n\n // tweak message and offset\n switch (tokenType) {\n case Ident:\n // when identifier is expected but there is a function or url\n if (this.tokenType === FunctionToken || this.tokenType === Url) {\n offset = this.tokenEnd - 1;\n message = 'Identifier is expected but function found';\n } else {\n message = 'Identifier is expected';\n }\n break;\n\n case Hash:\n if (this.isDelim(NUMBERSIGN)) {\n this.next();\n offset++;\n message = 'Name is expected';\n }\n break;\n\n case Percentage:\n if (this.tokenType === NumberToken) {\n offset = this.tokenEnd;\n message = 'Percent sign is expected';\n }\n break;\n }\n\n this.error(message, offset);\n }\n\n this.next();\n },\n eatIdent(name) {\n if (this.tokenType !== Ident || this.lookupValue(0, name) === false) {\n this.error(`Identifier \"${name}\" is expected`);\n }\n\n this.next();\n },\n eatDelim(code) {\n if (!this.isDelim(code)) {\n this.error(`Delim \"${String.fromCharCode(code)}\" is expected`);\n }\n\n this.next();\n },\n\n getLocation(start, end) {\n if (needPositions) {\n return locationMap.getLocationRange(\n start,\n end,\n filename\n );\n }\n\n return null;\n },\n getLocationFromList(list) {\n if (needPositions) {\n const head = this.getFirstListNode(list);\n const tail = this.getLastListNode(list);\n return locationMap.getLocationRange(\n head !== null ? head.loc.start.offset - locationMap.startOffset : this.tokenStart,\n tail !== null ? tail.loc.end.offset - locationMap.startOffset : this.tokenStart,\n filename\n );\n }\n\n return null;\n },\n\n error(message, offset) {\n const location = typeof offset !== 'undefined' && offset < source.length\n ? locationMap.getLocation(offset)\n : this.eof\n ? locationMap.getLocation(findWhiteSpaceStart(source, source.length - 1))\n : locationMap.getLocation(this.tokenStart);\n\n throw new SyntaxError(\n message || 'Unexpected input',\n source,\n location.offset,\n location.line,\n location.column,\n locationMap.startLine,\n locationMap.startColumn\n );\n }\n });\n\n const parse = function(source_, options) {\n source = source_;\n options = options || {};\n\n parser.setSource(source, tokenize);\n locationMap.setSource(\n source,\n options.offset,\n options.line,\n options.column\n );\n\n filename = options.filename || '';\n needPositions = Boolean(options.positions);\n onParseError = typeof options.onParseError === 'function' ? options.onParseError : NOOP;\n onParseErrorThrow = false;\n\n parser.parseAtrulePrelude = 'parseAtrulePrelude' in options ? Boolean(options.parseAtrulePrelude) : true;\n parser.parseRulePrelude = 'parseRulePrelude' in options ? Boolean(options.parseRulePrelude) : true;\n parser.parseValue = 'parseValue' in options ? Boolean(options.parseValue) : true;\n parser.parseCustomProperty = 'parseCustomProperty' in options ? Boolean(options.parseCustomProperty) : false;\n\n const { context = 'default', onComment } = options;\n\n if (context in parser.context === false) {\n throw new Error('Unknown context `' + context + '`');\n }\n\n if (typeof onComment === 'function') {\n parser.forEachToken((type, start, end) => {\n if (type === Comment) {\n const loc = parser.getLocation(start, end);\n const value = cmpStr(source, end - 2, end, '*/')\n ? source.slice(start + 2, end - 2)\n : source.slice(start + 2, end);\n\n onComment(value, loc);\n }\n });\n }\n\n const ast = parser.context[context].call(parser, options);\n\n if (!parser.eof) {\n parser.error();\n }\n\n return ast;\n };\n\n return Object.assign(parse, {\n SyntaxError,\n config: parser.config\n });\n};\n", "import {\n Delim,\n Ident,\n Dimension,\n Percentage,\n Number as NumberToken,\n Hash,\n Colon,\n LeftSquareBracket\n} from '../../tokenizer/index.js';\n\nconst NUMBERSIGN = 0x0023; // U+0023 NUMBER SIGN (#)\nconst AMPERSAND = 0x0026; // U+0026 AMPERSAND (&)\nconst ASTERISK = 0x002A; // U+002A ASTERISK (*)\nconst PLUSSIGN = 0x002B; // U+002B PLUS SIGN (+)\nconst SOLIDUS = 0x002F; // U+002F SOLIDUS (/)\nconst FULLSTOP = 0x002E; // U+002E FULL STOP (.)\nconst GREATERTHANSIGN = 0x003E; // U+003E GREATER-THAN SIGN (>)\nconst VERTICALLINE = 0x007C; // U+007C VERTICAL LINE (|)\nconst TILDE = 0x007E; // U+007E TILDE (~)\n\nfunction onWhiteSpace(next, children) {\n if (children.last !== null && children.last.type !== 'Combinator' &&\n next !== null && next.type !== 'Combinator') {\n children.push({ // FIXME: this.Combinator() should be used instead\n type: 'Combinator',\n loc: null,\n name: ' '\n });\n }\n}\n\nfunction getNode() {\n switch (this.tokenType) {\n case LeftSquareBracket:\n return this.AttributeSelector();\n\n case Hash:\n return this.IdSelector();\n\n case Colon:\n if (this.lookupType(1) === Colon) {\n return this.PseudoElementSelector();\n } else {\n return this.PseudoClassSelector();\n }\n\n case Ident:\n return this.TypeSelector();\n\n case NumberToken:\n case Percentage:\n return this.Percentage();\n\n case Dimension:\n // throws when .123ident\n if (this.charCodeAt(this.tokenStart) === FULLSTOP) {\n this.error('Identifier is expected', this.tokenStart + 1);\n }\n break;\n\n case Delim: {\n const code = this.charCodeAt(this.tokenStart);\n\n switch (code) {\n case PLUSSIGN:\n case GREATERTHANSIGN:\n case TILDE:\n case SOLIDUS: // /deep/\n return this.Combinator();\n\n case FULLSTOP:\n return this.ClassSelector();\n\n case ASTERISK:\n case VERTICALLINE:\n return this.TypeSelector();\n\n case NUMBERSIGN:\n return this.IdSelector();\n\n case AMPERSAND:\n return this.NestingSelector();\n }\n\n break;\n }\n }\n};\n\nexport default {\n onWhiteSpace,\n getNode\n};\n", "import { Comma, String as StringToken, Ident, RightParenthesis } from '../../tokenizer/index.js';\n\nexport function parseLanguageRangeList() {\n const children = this.createList();\n\n this.skipSC();\n\n loop: while (!this.eof) {\n switch (this.tokenType) {\n case Ident:\n children.push(this.Identifier());\n break;\n\n case StringToken:\n children.push(this.String());\n break;\n\n case Comma:\n children.push(this.Operator());\n break;\n\n case RightParenthesis:\n break loop;\n\n default:\n this.error('Identifier, string or comma is expected');\n }\n\n this.skipSC();\n }\n\n return children;\n}\n", "import { parseLanguageRangeList } from './lang.js';\n\nconst selectorList = {\n parse() {\n return this.createSingleNodeList(\n this.SelectorList()\n );\n }\n};\n\nconst selector = {\n parse() {\n return this.createSingleNodeList(\n this.Selector()\n );\n }\n};\n\nconst identList = {\n parse() {\n return this.createSingleNodeList(\n this.Identifier()\n );\n }\n};\n\nconst langList = {\n parse: parseLanguageRangeList\n};\n\nconst nth = {\n parse() {\n return this.createSingleNodeList(\n this.Nth()\n );\n }\n};\n\nexport default {\n 'dir': identList,\n 'has': selectorList,\n 'lang': langList,\n 'matches': selectorList,\n 'is': selectorList,\n '-moz-any': selectorList,\n '-webkit-any': selectorList,\n 'where': selectorList,\n 'not': selectorList,\n 'nth-child': nth,\n 'nth-last-child': nth,\n 'nth-last-of-type': nth,\n 'nth-of-type': nth,\n 'slotted': selector,\n 'host': selector,\n 'host-context': selector\n};\n", "export { parse as AnPlusB } from './AnPlusB.js';\nexport { parse as AttributeSelector } from './AttributeSelector.js';\nexport { parse as ClassSelector } from './ClassSelector.js';\nexport { parse as Combinator } from './Combinator.js';\nexport { parse as Identifier } from './Identifier.js';\nexport { parse as IdSelector } from './IdSelector.js';\nexport { parse as NestingSelector } from './NestingSelector.js';\nexport { parse as Nth } from './Nth.js';\nexport { parse as Operator } from './Operator.js';\nexport { parse as Percentage } from './Percentage.js';\nexport { parse as PseudoClassSelector } from './PseudoClassSelector.js';\nexport { parse as PseudoElementSelector } from './PseudoElementSelector.js';\nexport { parse as Raw } from './Raw.js';\nexport { parse as Selector } from './Selector.js';\nexport { parse as SelectorList } from './SelectorList.js';\nexport { parse as String } from './String.js';\nexport { parse as TypeSelector } from './TypeSelector.js';\n", "import { Selector } from '../scope/index.js';\nimport pseudo from '../pseudo/index.js';\nimport * as node from '../node/index-parse-selector.js';\n\nexport default {\n parseContext: {\n default: 'SelectorList',\n selectorList: 'SelectorList',\n selector: 'Selector'\n },\n scope: { Selector },\n atrule: {},\n pseudo,\n node\n};\n", "import { createParser } from './create.js';\nimport config from '../syntax/config/parser-selector.js';\n\nexport default createParser(config);\n", "const compare = (s1, s2) => {\n if (s1.a === s2.a) {\n if (s1.b === s2.b) {\n return s1.c - s2.c;\n }\n return s1.b - s2.b;\n }\n return s1.a - s2.a;\n};\n\nconst equals = (s1, s2) => {\n return compare(s1, s2) === 0;\n};\n\nconst greaterThan = (s1, s2) => {\n return compare(s1, s2) > 0;\n};\n\nconst lessThan = (s1, s2) => {\n return compare(s1, s2) < 0;\n};\n\nexport { compare, equals, greaterThan, lessThan };\n", "import { compare } from './compare.js';\n\nconst sort = (specificities, order = 'ASC') => {\n const sorted = specificities.sort(compare);\n\n if (order === 'DESC') {\n return sorted.reverse();\n }\n\n return sorted;\n};\n\nconst sortAsc = (...specificities) => {\n return sort(specificities, 'ASC');\n};\n\nconst sortDesc = (...specificities) => {\n return sort(specificities, 'DESC');\n};\n\nexport { sortAsc, sortDesc };\n", "import { sortAsc, sortDesc } from './sort.js';\n\nconst max = (...specificities) => {\n const sorted = sortDesc(...specificities);\n return sorted[0];\n};\n\nconst min = (...specificities) => {\n const sorted = sortAsc(...specificities);\n return sorted[0];\n};\n\nexport { max, min };\n", "import parse from 'css-tree/selector-parser';\nimport Specificity from '../index.js';\nimport { max } from './../util/index.js';\n\n/** @param {import('css-tree').Selector} selectorAST */\nconst calculateForAST = (selectorAST) => {\n // Quit while you're ahead\n if (!selectorAST || selectorAST.type !== 'Selector') {\n throw new TypeError(`Passed in source is not a Selector AST`);\n }\n\n // https://www.w3.org/TR/selectors-4/#specificity-rules\n let a = 0; /* ID Selectors */\n let b = 0; /* Class selectors, Attributes selectors, and Pseudo-classes */\n let c = 0; /* Type selectors and Pseudo-elements */\n\n selectorAST.children.forEach((child) => {\n switch (child.type) {\n case 'IdSelector':\n a += 1;\n break;\n\n case 'AttributeSelector':\n case 'ClassSelector':\n b += 1;\n break;\n\n case 'PseudoClassSelector':\n switch (child.name.toLowerCase()) {\n // \u201CThe specificity of a :where() pseudo-class is replaced by zero.\u201D\n case 'where':\n // Noop :)\n break;\n\n case '-webkit-any':\n case 'any':\n if (child.children?.first) {\n b += 1;\n }\n break;\n\n // \u201CThe specificity of an :is(), :not(), or :has() pseudo-class is replaced by the specificity of the most specific complex selector in its selector list argument.\u201C\n case '-moz-any':\n case 'is':\n case 'matches':\n case 'not':\n case 'has':\n if (child.children?.first) {\n // Calculate Specificity from nested SelectorList\n const max1 = max(...calculate(child.children.first));\n\n // Adjust orig specificity\n a += max1.a;\n b += max1.b;\n c += max1.c;\n }\n\n break;\n\n // \u201CThe specificity of an :nth-child() or :nth-last-child() selector is the specificity of the pseudo class itself (counting as one pseudo-class selector) plus the specificity of the most specific complex selector in its selector list argument\u201D\n case 'nth-child':\n case 'nth-last-child':\n b += 1;\n\n if (child.children?.first?.selector) {\n // Calculate Specificity from SelectorList\n const max2 = max(...calculate(child.children.first.selector));\n\n // Adjust orig specificity\n a += max2.a;\n b += max2.b;\n c += max2.c;\n }\n break;\n\n // \u201CThe specificity of :host is that of a pseudo-class. The specificity of :host() is that of a pseudo-class, plus the specificity of its argument.\u201D\n // \u201CThe specificity of :host-context() is that of a pseudo-class, plus the specificity of its argument.\u201D\n case 'host-context':\n case 'host':\n b += 1;\n\n if (child.children?.first?.children) {\n // Workaround to a css-tree bug in which it allows complex selectors instead of only compound selectors\n // We work around it by filtering out any Combinator and successive Selectors\n const childAST = { type: 'Selector', children: [] };\n let foundCombinator = false;\n child.children.first.children.forEach((entry) => {\n if (foundCombinator) return false;\n if (entry.type === 'Combinator') {\n foundCombinator = true;\n return false;\n }\n childAST.children.push(entry);\n });\n\n // Calculate Specificity from Selector\n const childSpecificity = calculate(childAST)[0];\n\n // Adjust orig specificity\n a += childSpecificity.a;\n b += childSpecificity.b;\n c += childSpecificity.c;\n }\n break;\n\n // Improper use of Pseudo-Class Selectors instead of a Pseudo-Element\n // @ref https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-elements#index\n case 'after':\n case 'before':\n case 'first-letter':\n case 'first-line':\n c += 1;\n break;\n\n default:\n b += 1;\n break;\n }\n break;\n\n case 'PseudoElementSelector':\n switch (child.name) {\n // \u201CThe specificity of ::slotted() is that of a pseudo-element, plus the specificity of its argument.\u201D\n case 'slotted':\n c += 1;\n\n if (child.children?.first?.children) {\n // Workaround to a css-tree bug in which it allows complex selectors instead of only compound selectors\n // We work around it by filtering out any Combinator and successive Selectors\n const childAST = { type: 'Selector', children: [] };\n let foundCombinator = false;\n child.children.first.children.forEach((entry) => {\n if (foundCombinator) return false;\n if (entry.type === 'Combinator') {\n foundCombinator = true;\n return false;\n }\n childAST.children.push(entry);\n });\n\n // Calculate Specificity from Selector\n const childSpecificity = calculate(childAST)[0];\n\n // Adjust orig specificity\n a += childSpecificity.a;\n b += childSpecificity.b;\n c += childSpecificity.c;\n }\n break;\n\n case 'view-transition-group':\n case 'view-transition-image-pair':\n case 'view-transition-old':\n case 'view-transition-new':\n // The specificity of a view-transition selector with a * argument is zero.\n if (child.children?.first?.value === '*') {\n break;\n }\n // The specificity of a view-transition selector with an argument is the same\n // as for other pseudo - elements, and is equivalent to a type selector.\n c += 1;\n break;\n\n default:\n c += 1;\n break;\n }\n break;\n\n case 'TypeSelector':\n // Omit namespace\n let typeSelector = child.name;\n if (typeSelector.includes('|')) {\n typeSelector = typeSelector.split('|')[1];\n }\n\n // \u201CIgnore the universal selector\u201D\n if (typeSelector !== '*') {\n c += 1;\n }\n break;\n\n default:\n // NOOP\n break;\n }\n });\n\n return new Specificity({ a, b, c }, selectorAST);\n};\n\nconst convertToAST = (source) => {\n // The passed in argument was a String.\n // ~> Let's try and parse to an AST\n if (typeof source === 'string' || source instanceof String) {\n try {\n return parse(source, {\n context: 'selectorList',\n });\n } catch (e) {\n throw new TypeError(`Could not convert passed in source '${source}' to SelectorList: ${e.message}`);\n }\n }\n\n // The passed in argument was an Object.\n // ~> Let's verify if it's a AST of the type Selector or SelectorList\n if (source instanceof Object) {\n if (source.type && ['Selector', 'SelectorList'].includes(source.type)) {\n return source;\n }\n\n // Manually parsing subtree when the child is of the type Raw, most likely due to https://github.com/csstree/csstree/issues/151\n if (source.type && source.type === 'Raw') {\n try {\n return parse(source.value, {\n context: 'selectorList',\n });\n } catch (e) {\n throw new TypeError(`Could not convert passed in source to SelectorList: ${e.message}`);\n }\n }\n\n throw new TypeError(`Passed in source is an Object but no AST / AST of the type Selector or SelectorList`);\n }\n\n throw new TypeError(`Passed in source is not a String nor an Object. I don't know what to do with it.`);\n};\n\n/**\n * @param {string} selector\n * @returns {Specificity[]}\n */\nconst calculate = (selector) => {\n // Quit while you're ahead\n if (!selector) {\n return [];\n }\n\n // Make sure we have a SelectorList AST\n // If not, an exception will be thrown\n const ast = convertToAST(selector);\n\n // Selector?\n if (ast.type === 'Selector') {\n return [calculateForAST(selector)];\n }\n\n // SelectorList?\n // ~> Calculate Specificity for each contained Selector\n if (ast.type === 'SelectorList') {\n const specificities = [];\n ast.children.forEach((childAST) => {\n const specificity = calculateForAST(childAST);\n specificities.push(specificity);\n });\n return specificities;\n }\n};\n\nexport { calculate, calculateForAST };\n", "import generate from 'css-tree/generator';\n\nimport { calculate, calculateForAST } from './core/index.js';\nimport { compare, equals, greaterThan, lessThan } from './util/compare.js';\nimport { min, max } from './util/filter.js';\nimport { sortAsc, sortDesc } from './util/sort.js';\n\nclass NotAllowedError extends Error {\n constructor() {\n super('Manipulating a Specificity instance is not allowed. Instead, create a new Specificity()');\n }\n}\n\nclass Specificity {\n constructor(value, selector = null) {\n this.value = value;\n this.selector = selector;\n }\n\n get a() {\n return this.value.a;\n }\n\n set a(val) {\n throw new NotAllowedError();\n }\n\n get b() {\n return this.value.b;\n }\n\n set b(val) {\n throw new NotAllowedError();\n }\n\n get c() {\n return this.value.c;\n }\n\n set c(val) {\n throw new NotAllowedError();\n }\n\n selectorString() {\n // this.selector already is a String\n if (typeof this.selector === 'string' || this.selector instanceof String) {\n return this.selector;\n }\n\n // this.selector is a Selector as parsed by CSSTree\n if (this.selector instanceof Object) {\n if (this.selector.type === 'Selector') {\n return generate(this.selector);\n }\n }\n\n // this.selector is something else \u2026\n return '';\n }\n\n toObject() {\n return this.value;\n }\n\n toArray() {\n return [this.value.a, this.value.b, this.value.c];\n }\n\n toString() {\n return `(${this.value.a},${this.value.b},${this.value.c})`;\n }\n\n toJSON() {\n return {\n selector: this.selectorString(),\n asObject: this.toObject(),\n asArray: this.toArray(),\n asString: this.toString(),\n };\n }\n\n isEqualTo(otherSpecificity) {\n return equals(this, otherSpecificity);\n }\n\n isGreaterThan(otherSpecificity) {\n return greaterThan(this, otherSpecificity);\n }\n\n isLessThan(otherSpecificity) {\n return lessThan(this, otherSpecificity);\n }\n\n static calculate(selector) {\n return calculate(selector);\n }\n\n static calculateForAST(selector) {\n return calculateForAST(selector);\n }\n\n static compare(s1, s2) {\n return compare(s1, s2);\n }\n\n static equals(s1, s2) {\n return equals(s1, s2);\n }\n\n static lessThan(s1, s2) {\n return lessThan(s1, s2);\n }\n\n static greaterThan(s1, s2) {\n return greaterThan(s1, s2);\n }\n\n static min(...specificities) {\n return min(...specificities);\n }\n\n static max(...specificities) {\n return max(...specificities);\n }\n\n static sortAsc(...specificities) {\n return sortAsc(...specificities);\n }\n\n static sortDesc(...specificities) {\n return sortDesc(...specificities);\n }\n}\n\nexport default Specificity;\n"], + "mappings": "8pBAAA,eAOA,GAAI,IAAe,mEAAmE,MAAM,IAK5F,GAAQ,OAAS,S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G,SAGX,QAAO,EAAe,CACzB,MAAO,IAAI,GAAG,SAGX,YAAW,EAAe,CAC7B,MAAO,IAAQ,GAAG,SAGf,aAAY,EAAe,CAC9B,MAAO,IAAS,GAAG,KAIpB,GAAQ", + "names": [] +} diff --git a/node_modules/@bramus/specificity/index.d.ts b/node_modules/@bramus/specificity/index.d.ts new file mode 100644 index 00000000..95d477af --- /dev/null +++ b/node_modules/@bramus/specificity/index.d.ts @@ -0,0 +1,59 @@ +// Types & Classes +export type SpecificityArray = [number, number, number]; +export type SpecificityObject = { a: number; b: number; c: number }; + +export default class Specificity { + static calculate(selector: string | CSSTreeAST): Array; + static calculateForAST(selectorAST: CSSTreeAST): Specificity; + static compare(s1: SpecificityInstanceOrObject, s2: SpecificityInstanceOrObject): number; + static equals(s1: SpecificityInstanceOrObject, s2: SpecificityInstanceOrObject): boolean; + static lessThan(s1: SpecificityInstanceOrObject, s2: SpecificityInstanceOrObject): boolean; + static greaterThan(s1: SpecificityInstanceOrObject, s2: SpecificityInstanceOrObject): boolean; + static min(...specificities: SpecificityInstanceOrObject[]): SpecificityInstanceOrObject; + static max(...specificities: SpecificityInstanceOrObject[]): SpecificityInstanceOrObject; + static sortAsc(...specificities: SpecificityInstanceOrObject[]): SpecificityInstanceOrObject; + static sortDesc(...specificities: SpecificityInstanceOrObject[]): SpecificityInstanceOrObject; + constructor(value: SpecificityObject, selector?: any); + value: SpecificityObject; + selector: string | CSSTreeAST; + set a(arg: number); + get a(): number; + set b(arg: number); + get b(): number; + set c(arg: number); + get c(): number; + selectorString(): string; + toObject(): SpecificityObject; + toArray(): SpecificityArray; + toString(): string; + toJSON(): { + selector: string; + asObject: SpecificityObject; + asArray: SpecificityArray; + asString: string; + }; + isEqualTo(otherSpecificity: SpecificityInstanceOrObject): boolean; + isGreaterThan(otherSpecificity: SpecificityInstanceOrObject): boolean; + isLessThan(otherSpecificity: SpecificityInstanceOrObject): boolean; +} + +type SpecificityInstanceOrObject = Specificity | SpecificityObject; +type CSSTreeAST = Object; // @TODO: Define shape + +// CORE +export function calculate(selector: string | CSSTreeAST): Array; +export function calculateForAST(selectorAST: CSSTreeAST): Specificity; + +// UTIL: COMPARE +export function equals(s1: SpecificityInstanceOrObject, s2: SpecificityInstanceOrObject): boolean; +export function greaterThan(s1: SpecificityInstanceOrObject, s2: SpecificityInstanceOrObject): boolean; +export function lessThan(s1: SpecificityInstanceOrObject, s2: SpecificityInstanceOrObject): boolean; +export function compare(s1: SpecificityInstanceOrObject, s2: SpecificityInstanceOrObject): number; + +// UTIL: FILTER +export function min(specificities: SpecificityInstanceOrObject[]): SpecificityInstanceOrObject; +export function max(specificities: SpecificityInstanceOrObject[]): SpecificityInstanceOrObject; + +// UTIL: SORT +export function sortAsc(specificities: SpecificityInstanceOrObject[]): SpecificityInstanceOrObject[]; +export function sortDesc(specificities: SpecificityInstanceOrObject[]): SpecificityInstanceOrObject[]; diff --git a/node_modules/@bramus/specificity/package.json b/node_modules/@bramus/specificity/package.json new file mode 100644 index 00000000..1674a61d --- /dev/null +++ b/node_modules/@bramus/specificity/package.json @@ -0,0 +1,92 @@ +{ + "name": "@bramus/specificity", + "version": "2.4.2", + "description": "Calculate specificity of a CSS Selector", + "type": "module", + "main": "./dist/index.cjs", + "module": "./dist/index.js", + "exports": { + ".": { + "browser": "./dist/index.js", + "import": "./dist/index.js", + "require": "./dist/index.cjs" + }, + "./core": { + "import": "./src/core/index.js" + }, + "./util": { + "import": "./src/util/index.js" + }, + "./compare": { + "import": "./src/util/compare.js" + }, + "./filter": { + "import": "./src/util/filter.js" + }, + "./sort": { + "import": "./src/util/sort.js" + } + }, + "unpkg": "./dist/index.js", + "jsdelivr": "./dist/index.js", + "files": [ + "bin", + "src", + "dist", + "index.d.ts" + ], + "types": "./index.d.ts", + "bin": { + "specificity": "./bin/cli.js" + }, + "scripts": { + "build-esm": "esbuild --bundle ./src/index.js --outfile=./dist/index.js --format=esm --sourcemap --minify", + "build-cjs": "esbuild --bundle ./src/index.js --outfile=./dist/index.cjs --format=cjs --sourcemap --minify", + "lint": "prettier --check '{src,test}/**/*.{ts,tsx,js,jsx}'", + "format": "prettier --write '{src,test}/**/*.{ts,tsx,js,jsx}'", + "build": "npm run build-esm && npm run build-cjs", + "prepack": "npm run prevent-dirty-tree && npm run test", + "prepublish": "npm run build", + "pretest": "npm run build", + "test": "mocha", + "prebenchmark": "npm run build", + "benchmark": "node ./benchmark/bench.cjs", + "beta-version-patch": "npm version $(semver $npm_package_version -i prerelease --preid beta)", + "beta-version-minor": "npm version $(semver $npm_package_version -i preminor --preid beta)", + "beta-version-major": "npm version $(semver $npm_package_version -i premajor --preid beta)", + "rc-version": "npm version $(semver $npm_package_version -i prerelease --preid rc)", + "final-release": "npm version $(semver $npm_package_version -i)", + "preversion": "npm run prevent-dirty-tree && npm run test", + "prevent-dirty-tree": "exit $(git status --porcelain | wc -l)" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/bramus/specificity.git" + }, + "keywords": [ + "css", + "specificity" + ], + "author": { + "name": "Bramus Van Damme", + "email": "bramus@bram.us", + "twitter": "@bramus", + "web": "https://www.bram.us/" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/bramus/specificity/issues" + }, + "homepage": "https://github.com/bramus/specificity#readme", + "devDependencies": { + "benchmark": "^2.1.4", + "esbuild": "^0.25.0", + "microtime": "^3.1.1", + "mocha": "^11.1.0", + "prettier": "^3.5.1", + "semver": "^7.7.1" + }, + "dependencies": { + "css-tree": "^3.0.0" + } +} diff --git a/node_modules/@bramus/specificity/src/core/calculate.js b/node_modules/@bramus/specificity/src/core/calculate.js new file mode 100644 index 00000000..f05b1aed --- /dev/null +++ b/node_modules/@bramus/specificity/src/core/calculate.js @@ -0,0 +1,260 @@ +import parse from 'css-tree/selector-parser'; +import Specificity from '../index.js'; +import { max } from './../util/index.js'; + +/** @param {import('css-tree').Selector} selectorAST */ +const calculateForAST = (selectorAST) => { + // Quit while you're ahead + if (!selectorAST || selectorAST.type !== 'Selector') { + throw new TypeError(`Passed in source is not a Selector AST`); + } + + // https://www.w3.org/TR/selectors-4/#specificity-rules + let a = 0; /* ID Selectors */ + let b = 0; /* Class selectors, Attributes selectors, and Pseudo-classes */ + let c = 0; /* Type selectors and Pseudo-elements */ + + selectorAST.children.forEach((child) => { + switch (child.type) { + case 'IdSelector': + a += 1; + break; + + case 'AttributeSelector': + case 'ClassSelector': + b += 1; + break; + + case 'PseudoClassSelector': + switch (child.name.toLowerCase()) { + // “The specificity of a :where() pseudo-class is replaced by zero.” + case 'where': + // Noop :) + break; + + case '-webkit-any': + case 'any': + if (child.children?.first) { + b += 1; + } + break; + + // “The specificity of an :is(), :not(), or :has() pseudo-class is replaced by the specificity of the most specific complex selector in its selector list argument.“ + case '-moz-any': + case 'is': + case 'matches': + case 'not': + case 'has': + if (child.children?.first) { + // Calculate Specificity from nested SelectorList + const max1 = max(...calculate(child.children.first)); + + // Adjust orig specificity + a += max1.a; + b += max1.b; + c += max1.c; + } + + break; + + // “The specificity of an :nth-child() or :nth-last-child() selector is the specificity of the pseudo class itself (counting as one pseudo-class selector) plus the specificity of the most specific complex selector in its selector list argument” + case 'nth-child': + case 'nth-last-child': + b += 1; + + if (child.children?.first?.selector) { + // Calculate Specificity from SelectorList + const max2 = max(...calculate(child.children.first.selector)); + + // Adjust orig specificity + a += max2.a; + b += max2.b; + c += max2.c; + } + break; + + // “The specificity of :host is that of a pseudo-class. The specificity of :host() is that of a pseudo-class, plus the specificity of its argument.” + // “The specificity of :host-context() is that of a pseudo-class, plus the specificity of its argument.” + case 'host-context': + case 'host': + b += 1; + + if (child.children?.first?.children) { + // Workaround to a css-tree bug in which it allows complex selectors instead of only compound selectors + // We work around it by filtering out any Combinator and successive Selectors + const childAST = { type: 'Selector', children: [] }; + let foundCombinator = false; + child.children.first.children.forEach((entry) => { + if (foundCombinator) return false; + if (entry.type === 'Combinator') { + foundCombinator = true; + return false; + } + childAST.children.push(entry); + }); + + // Calculate Specificity from Selector + const childSpecificity = calculate(childAST)[0]; + + // Adjust orig specificity + a += childSpecificity.a; + b += childSpecificity.b; + c += childSpecificity.c; + } + break; + + // Improper use of Pseudo-Class Selectors instead of a Pseudo-Element + // @ref https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-elements#index + case 'after': + case 'before': + case 'first-letter': + case 'first-line': + c += 1; + break; + + default: + b += 1; + break; + } + break; + + case 'PseudoElementSelector': + switch (child.name) { + // “The specificity of ::slotted() is that of a pseudo-element, plus the specificity of its argument.” + case 'slotted': + c += 1; + + if (child.children?.first?.children) { + // Workaround to a css-tree bug in which it allows complex selectors instead of only compound selectors + // We work around it by filtering out any Combinator and successive Selectors + const childAST = { type: 'Selector', children: [] }; + let foundCombinator = false; + child.children.first.children.forEach((entry) => { + if (foundCombinator) return false; + if (entry.type === 'Combinator') { + foundCombinator = true; + return false; + } + childAST.children.push(entry); + }); + + // Calculate Specificity from Selector + const childSpecificity = calculate(childAST)[0]; + + // Adjust orig specificity + a += childSpecificity.a; + b += childSpecificity.b; + c += childSpecificity.c; + } + break; + + case 'view-transition-group': + case 'view-transition-image-pair': + case 'view-transition-old': + case 'view-transition-new': + // The specificity of a view-transition selector with a * argument is zero. + if (child.children?.first?.value === '*') { + break; + } + // The specificity of a view-transition selector with an argument is the same + // as for other pseudo - elements, and is equivalent to a type selector. + c += 1; + break; + + default: + c += 1; + break; + } + break; + + case 'TypeSelector': + // Omit namespace + let typeSelector = child.name; + if (typeSelector.includes('|')) { + typeSelector = typeSelector.split('|')[1]; + } + + // “Ignore the universal selector” + if (typeSelector !== '*') { + c += 1; + } + break; + + default: + // NOOP + break; + } + }); + + return new Specificity({ a, b, c }, selectorAST); +}; + +const convertToAST = (source) => { + // The passed in argument was a String. + // ~> Let's try and parse to an AST + if (typeof source === 'string' || source instanceof String) { + try { + return parse(source, { + context: 'selectorList', + }); + } catch (e) { + throw new TypeError(`Could not convert passed in source '${source}' to SelectorList: ${e.message}`); + } + } + + // The passed in argument was an Object. + // ~> Let's verify if it's a AST of the type Selector or SelectorList + if (source instanceof Object) { + if (source.type && ['Selector', 'SelectorList'].includes(source.type)) { + return source; + } + + // Manually parsing subtree when the child is of the type Raw, most likely due to https://github.com/csstree/csstree/issues/151 + if (source.type && source.type === 'Raw') { + try { + return parse(source.value, { + context: 'selectorList', + }); + } catch (e) { + throw new TypeError(`Could not convert passed in source to SelectorList: ${e.message}`); + } + } + + throw new TypeError(`Passed in source is an Object but no AST / AST of the type Selector or SelectorList`); + } + + throw new TypeError(`Passed in source is not a String nor an Object. I don't know what to do with it.`); +}; + +/** + * @param {string} selector + * @returns {Specificity[]} + */ +const calculate = (selector) => { + // Quit while you're ahead + if (!selector) { + return []; + } + + // Make sure we have a SelectorList AST + // If not, an exception will be thrown + const ast = convertToAST(selector); + + // Selector? + if (ast.type === 'Selector') { + return [calculateForAST(selector)]; + } + + // SelectorList? + // ~> Calculate Specificity for each contained Selector + if (ast.type === 'SelectorList') { + const specificities = []; + ast.children.forEach((childAST) => { + const specificity = calculateForAST(childAST); + specificities.push(specificity); + }); + return specificities; + } +}; + +export { calculate, calculateForAST }; diff --git a/node_modules/@bramus/specificity/src/core/index.js b/node_modules/@bramus/specificity/src/core/index.js new file mode 100644 index 00000000..0db60bf0 --- /dev/null +++ b/node_modules/@bramus/specificity/src/core/index.js @@ -0,0 +1 @@ +export { calculate, calculateForAST } from './calculate.js'; diff --git a/node_modules/@bramus/specificity/src/index.js b/node_modules/@bramus/specificity/src/index.js new file mode 100644 index 00000000..cfa1932d --- /dev/null +++ b/node_modules/@bramus/specificity/src/index.js @@ -0,0 +1,135 @@ +import generate from 'css-tree/generator'; + +import { calculate, calculateForAST } from './core/index.js'; +import { compare, equals, greaterThan, lessThan } from './util/compare.js'; +import { min, max } from './util/filter.js'; +import { sortAsc, sortDesc } from './util/sort.js'; + +class NotAllowedError extends Error { + constructor() { + super('Manipulating a Specificity instance is not allowed. Instead, create a new Specificity()'); + } +} + +class Specificity { + constructor(value, selector = null) { + this.value = value; + this.selector = selector; + } + + get a() { + return this.value.a; + } + + set a(val) { + throw new NotAllowedError(); + } + + get b() { + return this.value.b; + } + + set b(val) { + throw new NotAllowedError(); + } + + get c() { + return this.value.c; + } + + set c(val) { + throw new NotAllowedError(); + } + + selectorString() { + // this.selector already is a String + if (typeof this.selector === 'string' || this.selector instanceof String) { + return this.selector; + } + + // this.selector is a Selector as parsed by CSSTree + if (this.selector instanceof Object) { + if (this.selector.type === 'Selector') { + return generate(this.selector); + } + } + + // this.selector is something else … + return ''; + } + + toObject() { + return this.value; + } + + toArray() { + return [this.value.a, this.value.b, this.value.c]; + } + + toString() { + return `(${this.value.a},${this.value.b},${this.value.c})`; + } + + toJSON() { + return { + selector: this.selectorString(), + asObject: this.toObject(), + asArray: this.toArray(), + asString: this.toString(), + }; + } + + isEqualTo(otherSpecificity) { + return equals(this, otherSpecificity); + } + + isGreaterThan(otherSpecificity) { + return greaterThan(this, otherSpecificity); + } + + isLessThan(otherSpecificity) { + return lessThan(this, otherSpecificity); + } + + static calculate(selector) { + return calculate(selector); + } + + static calculateForAST(selector) { + return calculateForAST(selector); + } + + static compare(s1, s2) { + return compare(s1, s2); + } + + static equals(s1, s2) { + return equals(s1, s2); + } + + static lessThan(s1, s2) { + return lessThan(s1, s2); + } + + static greaterThan(s1, s2) { + return greaterThan(s1, s2); + } + + static min(...specificities) { + return min(...specificities); + } + + static max(...specificities) { + return max(...specificities); + } + + static sortAsc(...specificities) { + return sortAsc(...specificities); + } + + static sortDesc(...specificities) { + return sortDesc(...specificities); + } +} + +export default Specificity; diff --git a/node_modules/@bramus/specificity/src/util/compare.js b/node_modules/@bramus/specificity/src/util/compare.js new file mode 100644 index 00000000..4e2fcf91 --- /dev/null +++ b/node_modules/@bramus/specificity/src/util/compare.js @@ -0,0 +1,23 @@ +const compare = (s1, s2) => { + if (s1.a === s2.a) { + if (s1.b === s2.b) { + return s1.c - s2.c; + } + return s1.b - s2.b; + } + return s1.a - s2.a; +}; + +const equals = (s1, s2) => { + return compare(s1, s2) === 0; +}; + +const greaterThan = (s1, s2) => { + return compare(s1, s2) > 0; +}; + +const lessThan = (s1, s2) => { + return compare(s1, s2) < 0; +}; + +export { compare, equals, greaterThan, lessThan }; diff --git a/node_modules/@bramus/specificity/src/util/filter.js b/node_modules/@bramus/specificity/src/util/filter.js new file mode 100644 index 00000000..4cf500a4 --- /dev/null +++ b/node_modules/@bramus/specificity/src/util/filter.js @@ -0,0 +1,13 @@ +import { sortAsc, sortDesc } from './sort.js'; + +const max = (...specificities) => { + const sorted = sortDesc(...specificities); + return sorted[0]; +}; + +const min = (...specificities) => { + const sorted = sortAsc(...specificities); + return sorted[0]; +}; + +export { max, min }; diff --git a/node_modules/@bramus/specificity/src/util/index.js b/node_modules/@bramus/specificity/src/util/index.js new file mode 100644 index 00000000..160f3412 --- /dev/null +++ b/node_modules/@bramus/specificity/src/util/index.js @@ -0,0 +1,3 @@ +export * from './compare.js'; +export * from './sort.js'; +export * from './filter.js'; diff --git a/node_modules/@bramus/specificity/src/util/sort.js b/node_modules/@bramus/specificity/src/util/sort.js new file mode 100644 index 00000000..9691c6ee --- /dev/null +++ b/node_modules/@bramus/specificity/src/util/sort.js @@ -0,0 +1,21 @@ +import { compare } from './compare.js'; + +const sort = (specificities, order = 'ASC') => { + const sorted = specificities.sort(compare); + + if (order === 'DESC') { + return sorted.reverse(); + } + + return sorted; +}; + +const sortAsc = (...specificities) => { + return sort(specificities, 'ASC'); +}; + +const sortDesc = (...specificities) => { + return sort(specificities, 'DESC'); +}; + +export { sortAsc, sortDesc }; diff --git a/node_modules/@csstools/color-helpers/CHANGELOG.md b/node_modules/@csstools/color-helpers/CHANGELOG.md new file mode 100644 index 00000000..d99d4c8f --- /dev/null +++ b/node_modules/@csstools/color-helpers/CHANGELOG.md @@ -0,0 +1,9 @@ +# Changes to Color Helpers + +### 6.0.2 + +_February 21, 2026_ + +- Updated: gamut mapping algorithm + +[Full CHANGELOG](https://github.com/csstools/postcss-plugins/tree/main/packages/color-helpers/CHANGELOG.md) diff --git a/node_modules/@csstools/color-helpers/LICENSE.md b/node_modules/@csstools/color-helpers/LICENSE.md new file mode 100644 index 00000000..e8ae93b9 --- /dev/null +++ b/node_modules/@csstools/color-helpers/LICENSE.md @@ -0,0 +1,18 @@ +MIT No Attribution (MIT-0) + +Copyright © CSSTools 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. + +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. diff --git a/node_modules/@csstools/color-helpers/README.md b/node_modules/@csstools/color-helpers/README.md new file mode 100644 index 00000000..97528d0e --- /dev/null +++ b/node_modules/@csstools/color-helpers/README.md @@ -0,0 +1,32 @@ +# Color Helpers for CSS + +[npm version][npm-url] +[Build Status][cli-url] +[Discord][discord] + +## Usage + +Add [Color Helpers] to your project: + +```bash +npm install @csstools/color-helpers --save-dev +``` + +This package exists to join all the different color functions scattered among the Colors 4 and Colors 5 plugins we maintain such as: + +* [PostCSS Color Function] +* [PostCSS Lab Function] +* [PostCSS OKLab Function] + +## Copyright + +This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/tree/main/css-color-4. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). + +[cli-url]: https://github.com/csstools/postcss-plugins/actions/workflows/test.yml?query=workflow/test +[discord]: https://discord.gg/bUadyRwkJS +[npm-url]: https://www.npmjs.com/package/@csstools/color-helpers + +[Color Helpers]: https://github.com/csstools/postcss-plugins/tree/main/packages/color-helpers +[PostCSS Color Function]: https://github.com/csstools/postcss-plugins/tree/main/plugins/postcss-color-function +[PostCSS Lab Function]: https://github.com/csstools/postcss-plugins/tree/main/plugins/postcss-lab-functionw +[PostCSS OKLab Function]: https://github.com/csstools/postcss-plugins/tree/main/plugins/postcss-oklab-function diff --git a/node_modules/@csstools/color-helpers/dist/index.d.ts b/node_modules/@csstools/color-helpers/dist/index.d.ts new file mode 100644 index 00000000..2eb948cf --- /dev/null +++ b/node_modules/@csstools/color-helpers/dist/index.d.ts @@ -0,0 +1,429 @@ +/** + * @param {Color} color [r, g, b] + * - Red as number 0..1; + * - Green as number 0..1; + * - Blue as number 0..1; + * @return {Color} D50 XYZ [x, y, z] + */ +export declare function a98_RGB_to_XYZ_D50(x: Color): Color; + +export declare function clip(color: Color): Color; + +export declare type Color = [number, number, number]; + +/** + * WCAG 2.1 contrast ratio + */ +export declare function contrast_ratio_wcag_2_1(color1: Color, color2: Color): number; + +/** + * Convert an array of linear-light display-p3 RGB in the range 0.0-1.0 + * to gamma corrected form + * + * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). + */ +export declare function gam_P3(RGB: Color): Color; + +/** + * Convert an array of linear-light sRGB values in the range 0.0-1.0 to gamma corrected form + * Extended transfer function: + * For negative values, linear portion extends on reflection + * of axis, then uses reflected pow below that + * + * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). + * @see https://en.wikipedia.org/wiki/SRGB + */ +export declare function gam_sRGB(RGB: Color): Color; + +/** + * @param {Color} color [h, s, l] + * - Hue as degrees 0..360; + * - Saturation as number 0..100; + * - Lightness as number 0..100; + * @return {Color} D50 XYZ [x, y, z] + */ +export declare function HSL_to_XYZ_D50(x: Color): Color; + +/** + * @param {Color} color [h, w, b] + * - Hue as degrees 0..360; + * - Whiteness as number 0..100; + * - Blackness as number 0..100; + * @return {Color} D50 XYZ [x, y, z] + */ +export declare function HWB_to_XYZ_D50(x: Color): Color; + +export declare function inGamut(x: Color): boolean; + +/** + * @param {Color} color [l, a, b] + * - Lightness as number 0..100; + * - a as number -160..160; + * - b as number -160..160; + * @return {Color} D50 XYZ [x, y, z] + */ +export declare function Lab_to_XYZ_D50(x: Color): Color; + +/** + * @param {Color} color [l, c, h] + * - Lightness as number 0..100; + * - Chroma as number 0..230; + * - Hue as degrees 0..360; + * @return {Color} D50 XYZ [x, y, z] + */ +export declare function LCH_to_XYZ_D50(x: Color): Color; + +/** + * Convert an array of display-p3 RGB values in the range 0.0 - 1.0 + * to linear light (un-companded) form. + * + * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). + */ +export declare function lin_P3(RGB: Color): Color; + +/** + * Convert an array of linear-light display-p3 values to CIE XYZ + * using D65 (no chromatic adaptation) + * + * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). + * @see http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html + */ +export declare function lin_P3_to_XYZ(rgb: Color): Color; + +/** + * @param {Color} color [r, g, b] + * - Red as number 0..1; + * - Green as number 0..1; + * - Blue as number 0..1; + * @return {Color} D50 XYZ [x, y, z] + */ +export declare function lin_P3_to_XYZ_D50(x: Color): Color; + +/** + * Convert an array of of sRGB values where in-gamut values are in the range + * [0 - 1] to linear light (un-companded) form. + * Extended transfer function: + * For negative values, linear portion is extended on reflection of axis, + * then reflected power function is used. + * + * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). + * @see https://en.wikipedia.org/wiki/SRGB + */ +export declare function lin_sRGB(RGB: Color): Color; + +/** + * Convert an array of linear-light sRGB values to CIE XYZ + * using sRGB's own white, D65 (no chromatic adaptation) + * + * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). + */ +export declare function lin_sRGB_to_XYZ(rgb: Color): Color; + +/** + * @param {Color} color [r, g, b] + * - Red as number 0..1; + * - Green as number 0..1; + * - Blue as number 0..1; + * @return {Color} D50 XYZ [x, y, z] + */ +export declare function lin_sRGB_to_XYZ_D50(x: Color): Color; + +export declare function mapGamut(startOKLCH: Color, toDestination: (x: Color) => Color, fromDestination: (x: Color) => Color): Color; + +/** + * @license MIT https://github.com/facelessuser/coloraide/blob/main/LICENSE.md + */ +export declare function mapGamutRayTrace(startOKLCH: Color, toLinear: (x: Color) => Color, fromLinear: (x: Color) => Color): Color; + +export declare const namedColors: Record; + +/** + * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). + * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js + */ +export declare function OKLab_to_OKLCH(OKLab: Color): Color; + +/** + * Given OKLab, convert to XYZ relative to D65 + * + * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). + * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js + */ +export declare function OKLab_to_XYZ(OKLab: Color): Color; + +/** + * @param {Color} color [l, a, b] + * - Lightness as number 0..1; + * - a as number 0..0.5; + * - b as number 0..0.5; + * @return {Color} D50 XYZ [x, y, z] + */ +export declare function OKLab_to_XYZ_D50(x: Color): Color; + +/** + * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). + * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js + */ +export declare function OKLCH_to_OKLab(OKLCH: Color): Color; + +/** + * @param {Color} color [l, c, h] + * - Lightness as number 0..1; + * - Chroma as number 0..0.5; + * - Hue as degrees 0..360; + * @return {Color} D50 XYZ [x, y, z] + */ +export declare function OKLCH_to_XYZ_D50(x: Color): Color; + +/** + * @param {Color} color [r, g, b] + * - Red as number 0..1; + * - Green as number 0..1; + * - Blue as number 0..1; + * @return {Color} D50 XYZ [x, y, z] + */ +export declare function P3_to_XYZ_D50(x: Color): Color; + +/** + * @param {Color} color [r, g, b] + * - Red as number 0..1; + * - Green as number 0..1; + * - Blue as number 0..1; + * @return {Color} D50 XYZ [x, y, z] + */ +export declare function ProPhoto_RGB_to_XYZ_D50(x: Color): Color; + +/** + * @param {Color} color [r, g, b] + * - Red as number 0..1; + * - Green as number 0..1; + * - Blue as number 0..1; + * @return {Color} D50 XYZ [x, y, z] + */ +export declare function rec_2020_to_XYZ_D50(x: Color): Color; + +/** + * @param {Color} color [r, g, b] + * - Red as number 0..1; + * - Green as number 0..1; + * - Blue as number 0..1; + * @return {Color} D50 XYZ [x, y, z] + */ +export declare function sRGB_to_XYZ_D50(x: Color): Color; + +/** + * @param {Color} color [x, y, z] + * - X as number 0..1; + * - Y as number 0..1; + * - Z as number 0..1; + * @return {Color} a98 sRGB [r, g, b] + * - Red as number 0..1; + * - Green as number 0..1; + * - Blue as number 0..1; + */ +export declare function XYZ_D50_to_a98_RGB(x: Color): Color; + +/** + * @param {Color} color [x, y, z] + * - X as number 0..1; + * - Y as number 0..1; + * - Z as number 0..1; + * @return {Color} HSL [r, g, b] + * - Hue as degrees 0..360; + * - Saturation as number 0..100; + * - Lightness as number 0..100; + */ +export declare function XYZ_D50_to_HSL(x: Color): Color; + +/** + * @param {Color} color [x, y, z] + * - X as number 0..1; + * - Y as number 0..1; + * - Z as number 0..1; + * @return {Color} HWB [r, g, b] + * - Hue as degrees 0..360; + * - Whiteness as number 0..100; + * - Blackness as number 0..100; + */ +export declare function XYZ_D50_to_HWB(x: Color): Color; + +/** + * @param {Color} color [x, y, z] + * - X as number 0..1; + * - Y as number 0..1; + * - Z as number 0..1; + * @return {Color} Lab [r, g, b] + * - Lightness as number 0..100; + * - a as number -160..160; + * - b as number -160..160; + */ +export declare function XYZ_D50_to_Lab(x: Color): Color; + +/** + * @param {Color} color [x, y, z] + * - X as number 0..1; + * - Y as number 0..1; + * - Z as number 0..1; + * @return {Color} LCH [r, g, b] + * - Lightness as number 0..100; + * - Chroma as number 0..230; + * - Hue as degrees 0..360; + */ +export declare function XYZ_D50_to_LCH(x: Color): Color; + +/** + * @param {Color} color [x, y, z] + * - X as number 0..1; + * - Y as number 0..1; + * - Z as number 0..1; + * @return {Color} P3 [r, g, b] + * - R as number 0..1; + * - G as number 0..1; + * - B as number 0..1; + */ +export declare function XYZ_D50_to_lin_P3(x: Color): Color; + +/** + * @param {Color} color [x, y, z] + * - X as number 0..1; + * - Y as number 0..1; + * - Z as number 0..1; + * @return {Color} linear sRGB [r, g, b] + * - Red as number 0..1; + * - Green as number 0..1; + * - Blue as number 0..1; + */ +export declare function XYZ_D50_to_lin_sRGB(x: Color): Color; + +/** + * @param {Color} color [x, y, z] + * - X as number 0..1; + * - Y as number 0..1; + * - Z as number 0..1; + * @return {Color} OKLab [r, g, b] + * - Lightness as number 0..1; + * - a as number 0..0.5; + * - b as number 0..0.5; + */ +export declare function XYZ_D50_to_OKLab(x: Color): Color; + +/** + * @param {Color} color [x, y, z] + * - X as number 0..1; + * - Y as number 0..1; + * - Z as number 0..1; + * @return {Color} OKLCH [r, g, b] + * - Lightness as number 0..1; + * - Chroma as number 0..0.5; + * - Hue as degrees 0..360; + */ +export declare function XYZ_D50_to_OKLCH(x: Color): Color; + +/** + * @param {Color} color [x, y, z] + * - X as number 0..1; + * - Y as number 0..1; + * - Z as number 0..1; + * @return {Color} P3 [r, g, b] + * - R as number 0..1; + * - G as number 0..1; + * - B as number 0..1; + */ +export declare function XYZ_D50_to_P3(x: Color): Color; + +/** + * @param {Color} color [x, y, z] + * - X as number 0..1; + * - Y as number 0..1; + * - Z as number 0..1; + * @return {Color} ProPhoto [r, g, b] + * - Red as number 0..1; + * - Green as number 0..1; + * - Blue as number 0..1; + */ +export declare function XYZ_D50_to_ProPhoto(x: Color): Color; + +/** + * @param {Color} color [x, y, z] + * - X as number 0..1; + * - Y as number 0..1; + * - Z as number 0..1; + * @return {Color} rec 2020 [r, g, b] + * - Red as number 0..1; + * - Green as number 0..1; + * - Blue as number 0..1; + */ +export declare function XYZ_D50_to_rec_2020(x: Color): Color; + +/** + * @param {Color} color [x, y, z] + * - X as number 0..1; + * - Y as number 0..1; + * - Z as number 0..1; + * @return {Color} sRGB [r, g, b] + * - Red as number 0..1; + * - Green as number 0..1; + * - Blue as number 0..1; + */ +export declare function XYZ_D50_to_sRGB(x: Color): Color; + +/** + * @param {Color} color [x, y, z] + * - X as number 0..1; + * - Y as number 0..1; + * - Z as number 0..1; + * @return {Color} D50 XYZ [x, y, z] + */ +export declare function XYZ_D50_to_XYZ_D50(x: Color): Color; + +/** + * @param {Color} color [x, y, z] + * - X as number 0..1; + * - Y as number 0..1; + * - Z as number 0..1; + * @return {Color} D65 XYZ [x, y, z] + */ +export declare function XYZ_D50_to_XYZ_D65(x: Color): Color; + +/** + * @param {Color} color [x, y, z] + * - X as number 0..1; + * - Y as number 0..1; + * - Z as number 0..1; + * @return {Color} D50 XYZ [x, y, z] + */ +export declare function XYZ_D65_to_XYZ_D50(x: Color): Color; + +/** + * Convert XYZ to linear-light P3 + * + * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). + */ +export declare function XYZ_to_lin_P3(XYZ: Color): Color; + +/** + * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). + */ +export declare function XYZ_to_lin_sRGB(XYZ: Color): Color; + +/** + * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). + * + * XYZ <-> LMS matrices recalculated for consistent reference white + * @see https://github.com/w3c/csswg-drafts/issues/6642#issuecomment-943521484 + */ +export declare function XYZ_to_OKLab(XYZ: Color): Color; + +export { } diff --git a/node_modules/@csstools/color-helpers/dist/index.mjs b/node_modules/@csstools/color-helpers/dist/index.mjs new file mode 100644 index 00000000..6e9f3e65 --- /dev/null +++ b/node_modules/@csstools/color-helpers/dist/index.mjs @@ -0,0 +1,263 @@ +function multiplyMatrices(t,n){return[t[0]*n[0]+t[1]*n[1]+t[2]*n[2],t[3]*n[0]+t[4]*n[1]+t[5]*n[2],t[6]*n[0]+t[7]*n[1]+t[8]*n[2]]}const t=[.955473421488075,-.02309845494876471,.06325924320057072,-.0283697093338637,1.0099953980813041,.021041441191917323,.012314014864481998,-.020507649298898964,1.330365926242124]; +/** + * Bradford chromatic adaptation from D50 to D65 + * + * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). + */function D50_to_D65(n){return multiplyMatrices(t,n)}const n=[1.0479297925449969,.022946870601609652,-.05019226628920524,.02962780877005599,.9904344267538799,-.017073799063418826,-.009243040646204504,.015055191490298152,.7518742814281371]; +/** + * Bradford chromatic adaptation from D65 to D50 + * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). + * @see http://www.brucelindbloom.com/index.html?Eqn_ChromAdapt.html + */function D65_to_D50(t){return multiplyMatrices(n,t)} +/** + * @param {number} hue - Hue as degrees 0..360 + * @param {number} sat - Saturation as percentage 0..100 + * @param {number} light - Lightness as percentage 0..100 + * @return {number[]} Array of sRGB components; in-gamut colors in range [0..1] + * + * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/hslToRgb.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). + * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/hslToRgb.js + */function HSL_to_sRGB(t){let n=t[0]%360;const _=t[1]/100,o=t[2]/100;return n<0&&(n+=360),[HSL_to_sRGB_channel(0,n,_,o),HSL_to_sRGB_channel(8,n,_,o),HSL_to_sRGB_channel(4,n,_,o)]}function HSL_to_sRGB_channel(t,n,_,o){const e=(t+n/30)%12;return o-_*Math.min(o,1-o)*Math.max(-1,Math.min(e-3,9-e,1))} +/** + * @param {number} hue - Hue as degrees 0..360 + * @param {number} white - Whiteness as percentage 0..100 + * @param {number} black - Blackness as percentage 0..100 + * @return {number[]} Array of RGB components 0..1 + * + * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/hwbToRgb.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). + * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/hwbToRgb.js + */function HWB_to_sRGB(t){const n=t[0],_=t[1]/100,o=t[2]/100;if(_+o>=1){const t=_/(_+o);return[t,t,t]}const e=HSL_to_sRGB([n,100,50]),a=1-_-o;return[e[0]*a+_,e[1]*a+_,e[2]*a+_]} +/** + * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). + */function LCH_to_Lab(t){const n=t[2]*Math.PI/180;return[t[0],t[1]*Math.cos(n),t[1]*Math.sin(n)]} +/** + * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). + */function Lab_to_LCH(t){const n=Math.sqrt(Math.pow(t[1],2)+Math.pow(t[2],2));let _=180*Math.atan2(t[2],t[1])/Math.PI;return _<0&&(_+=360),n<=.0015&&(_=NaN),[t[0],n,_]}const _=[.3457/.3585,1,.2958/.3585]; +/** + * Convert Lab to D50-adapted XYZ + * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). + * @see http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html + */function Lab_to_XYZ(t){const n=24389/27,o=216/24389,e=(t[0]+16)/116,a=t[1]/500+e,r=e-t[2]/200;return[(Math.pow(a,3)>o?Math.pow(a,3):(116*a-16)/n)*_[0],(t[0]>8?Math.pow((t[0]+16)/116,3):t[0]/n)*_[1],(Math.pow(r,3)>o?Math.pow(r,3):(116*r-16)/n)*_[2]]} +/** + * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). + * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js + */function OKLCH_to_OKLab(t){const n=t[2]*Math.PI/180;return[t[0],t[1]*Math.cos(n),t[1]*Math.sin(n)]} +/** + * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). + * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js + */function OKLab_to_OKLCH(t){const n=Math.sqrt(t[1]**2+t[2]**2);let _=180*Math.atan2(t[2],t[1])/Math.PI;return _<0&&(_+=360),n<=4e-6&&(_=NaN),[t[0],n,_]}const o=[1.2268798758459243,-.5578149944602171,.2813910456659647,-.0405757452148008,1.112286803280317,-.0717110580655164,-.0763729366746601,-.4214933324022432,1.5869240198367816],e=[1,.3963377773761749,.2158037573099136,1,-.1055613458156586,-.0638541728258133,1,-.0894841775298119,-1.2914855480194092]; +/** + * Given OKLab, convert to XYZ relative to D65 + * + * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). + * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js + */ +function OKLab_to_XYZ(t){const n=multiplyMatrices(e,t);return multiplyMatrices(o,[n[0]**3,n[1]**3,n[2]**3])} +/** + * Assuming XYZ is relative to D50, convert to CIE Lab + * from CIE standard, which now defines these as a rational fraction + * + * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). + */function XYZ_to_Lab(t){const n=compute_f(t[0]/_[0]),o=compute_f(t[1]/_[1]);return[116*o-16,500*(n-o),200*(o-compute_f(t[2]/_[2]))]}const a=216/24389,r=24389/27;function compute_f(t){return t>a?Math.cbrt(t):(r*t+16)/116}const l=[.819022437996703,.3619062600528904,-.1288737815209879,.0329836539323885,.9292868615863434,.0361446663506424,.0481771893596242,.2642395317527308,.6335478284694309],i=[.210454268309314,.7936177747023054,-.0040720430116193,1.9779985324311684,-2.42859224204858,.450593709617411,.0259040424655478,.7827717124575296,-.8086757549230774]; +/** + * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). + * + * XYZ <-> LMS matrices recalculated for consistent reference white + * @see https://github.com/w3c/csswg-drafts/issues/6642#issuecomment-943521484 + */ +function XYZ_to_OKLab(t){const n=multiplyMatrices(l,t);return multiplyMatrices(i,[Math.cbrt(n[0]),Math.cbrt(n[1]),Math.cbrt(n[2])])}const c=[30757411/17917100,-6372589/17917100,-4539589/17917100,-.666684351832489,1.616481236634939,467509/29648200,792561/44930125,-1921689/44930125,.942103121235474]; +/** + * Convert XYZ to linear-light rec2020 + * + * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). + */const u=[446124/178915,-333277/357830,-72051/178915,-14852/17905,63121/35810,423/17905,11844/330415,-50337/660830,316169/330415]; +/** + * Convert XYZ to linear-light P3 + * + * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). + */function XYZ_to_lin_P3(t){return multiplyMatrices(u,t)}const s=[1.3457868816471583,-.25557208737979464,-.05110186497554526,-.5446307051249019,1.5082477428451468,.02052744743642139,0,0,1.2119675456389452]; +/** + * Convert D50 XYZ to linear-light prophoto-rgb + * + * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). + * @see http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html + */const h=[1829569/896150,-506331/896150,-308931/896150,-851781/878810,1648619/878810,36519/878810,16779/1248040,-147721/1248040,1266979/1248040]; +/** + * Convert XYZ to linear-light a98-rgb + * + * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). + */const m=[12831/3959,-329/214,-1974/3959,-851781/878810,1648619/878810,36519/878810,705/12673,-2585/12673,705/667]; +/** + * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). + */function XYZ_to_lin_sRGB(t){return multiplyMatrices(m,t)} +/** + * Convert an array of linear-light rec2020 RGB in the range 0.0-1.0 + * to gamma corrected form ITU-R BT.2020-2 p.4 + * + * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). + */function gam_2020_channel(t){const n=t<0?-1:1,_=Math.abs(t);return n*Math.pow(_,1/2.4)} +/** + * Convert an array of linear-light sRGB values in the range 0.0-1.0 to gamma corrected form + * Extended transfer function: + * For negative values, linear portion extends on reflection + * of axis, then uses reflected pow below that + * + * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). + * @see https://en.wikipedia.org/wiki/SRGB + */function gam_sRGB(t){return[gam_sRGB_channel(t[0]),gam_sRGB_channel(t[1]),gam_sRGB_channel(t[2])]}function gam_sRGB_channel(t){const n=t<0?-1:1,_=Math.abs(t);return _>.0031308?n*(1.055*Math.pow(_,1/2.4)-.055):12.92*t} +/** + * Convert an array of linear-light display-p3 RGB in the range 0.0-1.0 + * to gamma corrected form + * + * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). + */function gam_P3(t){return gam_sRGB(t)} +/** + * Convert an array of linear-light prophoto-rgb in the range 0.0-1.0 + * to gamma corrected form. + * Transfer curve is gamma 1.8 with a small linear portion. + * + * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). + */const D=1/512;function gam_ProPhoto_channel(t){const n=t<0?-1:1,_=Math.abs(t);return _>=D?n*Math.pow(_,1/1.8):16*t} +/** + * Convert an array of linear-light a98-rgb in the range 0.0-1.0 + * to gamma corrected form. Negative values are also now accepted + * + * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). + */function gam_a98rgb_channel(t){const n=t<0?-1:1,_=Math.abs(t);return n*Math.pow(_,256/563)} +/** + * Convert an array of rec2020 RGB values in the range 0.0 - 1.0 + * to linear light (un-companded) form. + * ITU-R BT.2020-2 p.4 + * + * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). + */function lin_2020_channel(t){const n=t<0?-1:1,_=Math.abs(t);return n*Math.pow(_,2.4)}const b=[63426534/99577255,20160776/139408157,47086771/278816314,26158966/99577255,.677998071518871,8267143/139408157,0,19567812/697040785,1.0609850577107909]; +/** + * Convert an array of linear-light rec2020 values to CIE XYZ + * using D65 (no chromatic adaptation) + * + * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). + * @see http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html + */ +/** + * Convert an array of of sRGB values where in-gamut values are in the range + * [0 - 1] to linear light (un-companded) form. + * Extended transfer function: + * For negative values, linear portion is extended on reflection of axis, + * then reflected power function is used. + * + * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). + * @see https://en.wikipedia.org/wiki/SRGB + */ +function lin_sRGB(t){return[lin_sRGB_channel(t[0]),lin_sRGB_channel(t[1]),lin_sRGB_channel(t[2])]}function lin_sRGB_channel(t){const n=t<0?-1:1,_=Math.abs(t);return _<=.04045?t/12.92:n*Math.pow((_+.055)/1.055,2.4)} +/** + * Convert an array of display-p3 RGB values in the range 0.0 - 1.0 + * to linear light (un-companded) form. + * + * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). + */function lin_P3(t){return lin_sRGB(t)}const g=[608311/1250200,189793/714400,198249/1000160,35783/156275,247089/357200,198249/2500400,0,32229/714400,5220557/5000800]; +/** + * Convert an array of linear-light display-p3 values to CIE XYZ + * using D65 (no chromatic adaptation) + * + * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). + * @see http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html + */function lin_P3_to_XYZ(t){return multiplyMatrices(g,t)} +/** + * Convert an array of prophoto-rgb values where in-gamut Colors are in the + * range [0.0 - 1.0] to linear light (un-companded) form. Transfer curve is + * gamma 1.8 with a small linear portion. Extended transfer function + * + * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). + */const X=16/512;function lin_ProPhoto_channel(t){const n=t<0?-1:1,_=Math.abs(t);return _<=X?t/16:n*Math.pow(_,1.8)}const Y=[.7977666449006423,.13518129740053308,.0313477341283922,.2880748288194013,.711835234241873,8993693872564e-17,0,0,.8251046025104602]; +/** + * Convert an array of linear-light prophoto-rgb values to CIE D50 XYZ. + * Matrix cannot be expressed in rational form, but is calculated to 64 bit accuracy. + * + * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). + * @see see https://github.com/w3c/csswg-drafts/issues/7675 + */function lin_a98rgb_channel(t){const n=t<0?-1:1,_=Math.abs(t);return n*Math.pow(_,563/256)}const Z=[573536/994567,263643/1420810,187206/994567,591459/1989134,6239551/9945670,374412/4972835,53769/1989134,351524/4972835,4929758/4972835]; +/** + * Convert an array of linear-light a98-rgb values to CIE XYZ + * http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html + * has greater numerical precision than section 4.3.5.3 of + * https://www.adobe.com/digitalimag/pdfs/AdobeRGB1998.pdf + * but the values below were calculated from first principles + * from the chromaticity coordinates of R G B W + * + * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). + * @see http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html + * @see https://www.adobe.com/digitalimag/pdfs/AdobeRGB1998.pdf + * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/matrixmaker.html + */const f=[506752/1228815,87881/245763,12673/70218,87098/409605,175762/245763,12673/175545,7918/409605,87881/737289,1001167/1053270]; +/** + * Convert an array of linear-light sRGB values to CIE XYZ + * using sRGB's own white, D65 (no chromatic adaptation) + * + * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). + */function lin_sRGB_to_XYZ(t){return multiplyMatrices(f,t)} +/** + * Convert an array of gamma-corrected sRGB values in the 0.0 to 1.0 range to HSL. + * + * @param {Color} RGB [r, g, b] + * - Red component 0..1 + * - Green component 0..1 + * - Blue component 0..1 + * @return {number[]} Array of HSL values: Hue as degrees 0..360, Saturation and Lightness as percentages 0..100 + * + * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/utilities.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). + * + * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/better-rgbToHsl.js + */function sRGB_to_HSL(t){const n=t[0],_=t[1],o=t[2],e=Math.max(n,_,o),a=Math.min(n,_,o),r=(a+e)/2,l=e-a;let i=Number.NaN,c=0;if(0!==Math.round(1e5*l)){const t=Math.round(1e5*r);switch(c=0===t||1e5===t?0:(e-r)/Math.min(r,1-r),e){case n:i=(_-o)/l+(_=360&&(i-=360);return c<=1e-5&&(i=NaN),[i,100*c,100*r]}function sRGB_to_Hue(t){const n=t[0],_=t[1],o=t[2],e=Math.max(n,_,o),a=Math.min(n,_,o);let r=Number.NaN;const l=e-a;if(0!==l){switch(e){case n:r=(_-o)/l+(_=360&&(r-=360),r}function sRGB_to_XYZ_D50(t){let n=t;return n=lin_sRGB(n),n=lin_sRGB_to_XYZ(n),n=D65_to_D50(n),n}function XYZ_D50_to_sRGB(t){let n=t;return n=D50_to_D65(n),n=XYZ_to_lin_sRGB(n),n=gam_sRGB(n),n}function HSL_to_XYZ_D50(t){let n=t;return n=HSL_to_sRGB(n),n=lin_sRGB(n),n=lin_sRGB_to_XYZ(n),n=D65_to_D50(n),n}function XYZ_D50_to_HSL(t){let n=t;return n=D50_to_D65(n),n=XYZ_to_lin_sRGB(n),n=gam_sRGB(n),n=sRGB_to_HSL(n),n}function HWB_to_XYZ_D50(t){let n=t;return n=HWB_to_sRGB(n),n=lin_sRGB(n),n=lin_sRGB_to_XYZ(n),n=D65_to_D50(n),n}function XYZ_D50_to_HWB(t){let n=t;n=D50_to_D65(n),n=XYZ_to_lin_sRGB(n);const _=gam_sRGB(n),o=Math.min(_[0],_[1],_[2]),e=1-Math.max(_[0],_[1],_[2]);let a=sRGB_to_Hue(_);return o+e>=.99999&&(a=NaN),[a,100*o,100*e]}function Lab_to_XYZ_D50(t){let n=t;return n=Lab_to_XYZ(n),n}function XYZ_D50_to_Lab(t){let n=t;return n=XYZ_to_Lab(n),n}function LCH_to_XYZ_D50(t){let n=t;return n=LCH_to_Lab(n),n=Lab_to_XYZ(n),n}function XYZ_D50_to_LCH(t){let n=t;return n=XYZ_to_Lab(n),n=Lab_to_LCH(n),n}function OKLab_to_XYZ_D50(t){let n=t;return n=OKLab_to_XYZ(n),n=D65_to_D50(n),n}function XYZ_D50_to_OKLab(t){let n=t;return n=D50_to_D65(n),n=XYZ_to_OKLab(n),n}function OKLCH_to_XYZ_D50(t){let n=t;return n=OKLCH_to_OKLab(n),n=OKLab_to_XYZ(n),n=D65_to_D50(n),n}function XYZ_D50_to_OKLCH(t){let n=t;return n=D50_to_D65(n),n=XYZ_to_OKLab(n),n=OKLab_to_OKLCH(n),n}function lin_sRGB_to_XYZ_D50(t){let n=t;return n=lin_sRGB_to_XYZ(n),n=D65_to_D50(n),n}function XYZ_D50_to_lin_sRGB(t){let n=t;return n=D50_to_D65(n),n=XYZ_to_lin_sRGB(n),n}function a98_RGB_to_XYZ_D50(t){let n=t; +/** + * Convert an array of a98-rgb values in the range 0.0 - 1.0 + * to linear light (un-companded) form. Negative values are also now accepted + * + * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). + */ +var _;return n=[lin_a98rgb_channel((_=n)[0]),lin_a98rgb_channel(_[1]),lin_a98rgb_channel(_[2])],n=multiplyMatrices(Z,n),n=D65_to_D50(n),n}function XYZ_D50_to_a98_RGB(t){let n=t;var _;return n=D50_to_D65(n),n=multiplyMatrices(h,n),n=[gam_a98rgb_channel((_=n)[0]),gam_a98rgb_channel(_[1]),gam_a98rgb_channel(_[2])],n}function P3_to_XYZ_D50(t){let n=t;return n=lin_P3(n),n=lin_P3_to_XYZ(n),n=D65_to_D50(n),n}function XYZ_D50_to_P3(t){let n=t;return n=D50_to_D65(n),n=XYZ_to_lin_P3(n),n=gam_P3(n),n}function lin_P3_to_XYZ_D50(t){let n=t;return n=lin_P3_to_XYZ(n),n=D65_to_D50(n),n}function XYZ_D50_to_lin_P3(t){let n=t;return n=D50_to_D65(n),n=XYZ_to_lin_P3(n),n}function rec_2020_to_XYZ_D50(t){let n=t;var _;return n=[lin_2020_channel((_=n)[0]),lin_2020_channel(_[1]),lin_2020_channel(_[2])],n=multiplyMatrices(b,n),n=D65_to_D50(n),n}function XYZ_D50_to_rec_2020(t){let n=t;var _;return n=D50_to_D65(n),n=multiplyMatrices(c,n),n=[gam_2020_channel((_=n)[0]),gam_2020_channel(_[1]),gam_2020_channel(_[2])],n}function ProPhoto_RGB_to_XYZ_D50(t){let n=t;var _;return n=[lin_ProPhoto_channel((_=n)[0]),lin_ProPhoto_channel(_[1]),lin_ProPhoto_channel(_[2])],n=multiplyMatrices(Y,n),n}function XYZ_D50_to_ProPhoto(t){let n=t;var _;return n=multiplyMatrices(s,n),n=[gam_ProPhoto_channel((_=n)[0]),gam_ProPhoto_channel(_[1]),gam_ProPhoto_channel(_[2])],n}function XYZ_D65_to_XYZ_D50(t){let n=t;return n=D65_to_D50(n),n}function XYZ_D50_to_XYZ_D65(t){let n=t;return n=D50_to_D65(n),n}function XYZ_D50_to_XYZ_D50(t){return t}function inGamut(t){return t[0]>=-1e-4&&t[0]<=1.0001&&t[1]>=-1e-4&&t[1]<=1.0001&&t[2]>=-1e-4&&t[2]<=1.0001}function clip(t){return[t[0]<0?0:t[0]>1?1:t[0],t[1]<0?0:t[1]>1?1:t[1],t[2]<0?0:t[2]>1?1:t[2]]} +/** + * @description Calculate deltaE OK which is the simple root sum of squares + * @param {number[]} reference - Array of OKLab values: L as 0..1, a and b as -1..1 + * @param {number[]} sample - Array of OKLab values: L as 0..1, a and b as -1..1 + * @return {number} How different a color sample is from reference + * + * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/deltaEOK.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). + * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/deltaEOK.js + */function deltaEOK(t,n){const[_,o,e]=t,[a,r,l]=n,i=_-a,c=o-r,u=e-l;return Math.sqrt(i**2+c**2+u**2)}const M=.02,p=1e-4;function mapGamut(t,n,_){const o=t;let e=clip(n(o)),a=deltaEOK(OKLCH_to_OKLab(_(e)),OKLCH_to_OKLab(o));if(ap;){const t=(r+l)/2;if(o[1]=t,i&&inGamut(n(o)))r=t;else if(e=clip(n(o)),a=deltaEOK(OKLCH_to_OKLab(_(e)),OKLCH_to_OKLab(o)),a0){const t=_(a);t[0]=o,t[2]=e,a=n(t)}const l=rayTraceBox(r,a);if(!l)break;a=l}return clip(a)}function rayTraceBox(t,n){let _=1/0,o=-1/0;const e=[0,0,0];for(let a=0;a<3;a++){const r=t[a],l=n[a]-r;e[a]=l;const i=0,c=1;if(Math.abs(l)>1e-15){const t=1/l,n=(i-r)*t,e=(c-r)*t;o=Math.max(Math.min(n,e),o),_=Math.min(Math.max(n,e),_)}else if(rc)return!1}return!(o>_||_<0)&&(o<0&&(o=_),!!isFinite(o)&&[t[0]+e[0]*o,t[1]+e[1]*o,t[2]+e[2]*o])}const d={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]};function luminance(t){const[n,_,o]=t.map(t=>t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4));return.2126*n+.7152*_+.0722*o}function contrast_ratio_wcag_2_1(t,n){const _=luminance(t),o=luminance(n);return(Math.max(_,o)+.05)/(Math.min(_,o)+.05)}export{HSL_to_XYZ_D50,HWB_to_XYZ_D50,LCH_to_XYZ_D50,Lab_to_XYZ_D50,OKLCH_to_OKLab,OKLCH_to_XYZ_D50,OKLab_to_OKLCH,OKLab_to_XYZ,OKLab_to_XYZ_D50,P3_to_XYZ_D50,ProPhoto_RGB_to_XYZ_D50,XYZ_D50_to_HSL,XYZ_D50_to_HWB,XYZ_D50_to_LCH,XYZ_D50_to_Lab,XYZ_D50_to_OKLCH,XYZ_D50_to_OKLab,XYZ_D50_to_P3,XYZ_D50_to_ProPhoto,XYZ_D50_to_XYZ_D50,XYZ_D50_to_XYZ_D65,XYZ_D50_to_a98_RGB,XYZ_D50_to_lin_P3,XYZ_D50_to_lin_sRGB,XYZ_D50_to_rec_2020,XYZ_D50_to_sRGB,XYZ_D65_to_XYZ_D50,XYZ_to_OKLab,XYZ_to_lin_P3,XYZ_to_lin_sRGB,a98_RGB_to_XYZ_D50,clip,contrast_ratio_wcag_2_1,gam_P3,gam_sRGB,inGamut,lin_P3,lin_P3_to_XYZ,lin_P3_to_XYZ_D50,lin_sRGB,lin_sRGB_to_XYZ,lin_sRGB_to_XYZ_D50,mapGamut,mapGamutRayTrace,d as namedColors,rec_2020_to_XYZ_D50,sRGB_to_XYZ_D50}; diff --git a/node_modules/@csstools/color-helpers/package.json b/node_modules/@csstools/color-helpers/package.json new file mode 100644 index 00000000..1774c011 --- /dev/null +++ b/node_modules/@csstools/color-helpers/package.json @@ -0,0 +1,55 @@ +{ + "name": "@csstools/color-helpers", + "description": "Color helpers to ease transformation between formats, gamut, etc", + "version": "6.0.2", + "contributors": [ + { + "name": "Antonio Laguna", + "email": "antonio@laguna.es", + "url": "https://antonio.laguna.es" + }, + { + "name": "Romain Menke", + "email": "romainmenke@gmail.com" + } + ], + "license": "MIT-0", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "engines": { + "node": ">=20.19.0" + }, + "type": "module", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + } + }, + "files": [ + "CHANGELOG.md", + "LICENSE.md", + "README.md", + "dist" + ], + "scripts": {}, + "homepage": "https://github.com/csstools/postcss-plugins/tree/main/packages/color-helpers#readme", + "repository": { + "type": "git", + "url": "git+https://github.com/csstools/postcss-plugins.git", + "directory": "packages/color-helpers" + }, + "bugs": "https://github.com/csstools/postcss-plugins/issues", + "keywords": [ + "colors", + "css" + ] +} diff --git a/node_modules/@csstools/css-calc/CHANGELOG.md b/node_modules/@csstools/css-calc/CHANGELOG.md new file mode 100644 index 00000000..e0d6799c --- /dev/null +++ b/node_modules/@csstools/css-calc/CHANGELOG.md @@ -0,0 +1,9 @@ +# Changes to CSS Calc + +### 3.1.1 + +_February 13, 2026_ + +- Fix missing whitespace between components after solving calc expressions (e.g. `calc(10px)calc(20px)` now serializes as `10px 20px`) + +[Full CHANGELOG](https://github.com/csstools/postcss-plugins/tree/main/packages/css-calc/CHANGELOG.md) diff --git a/node_modules/@csstools/css-calc/LICENSE.md b/node_modules/@csstools/css-calc/LICENSE.md new file mode 100644 index 00000000..af5411fa --- /dev/null +++ b/node_modules/@csstools/css-calc/LICENSE.md @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright 2022 Romain Menke, Antonio Laguna + +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. diff --git a/node_modules/@csstools/css-calc/README.md b/node_modules/@csstools/css-calc/README.md new file mode 100644 index 00000000..1e20fae7 --- /dev/null +++ b/node_modules/@csstools/css-calc/README.md @@ -0,0 +1,132 @@ +# CSS Calc for CSS + +[npm version][npm-url] +[Build Status][cli-url] +[Discord][discord] + +Implemented from : https://drafts.csswg.org/css-values-4/ on 2023-02-17 + +## Usage + +Add [CSS calc] to your project: + +```bash +npm install @csstools/css-calc @csstools/css-parser-algorithms @csstools/css-tokenizer --save-dev +``` + +### With string values : + +```mjs +import { calc } from '@csstools/css-calc'; + +// '20' +console.log(calc('calc(10 * 2)')); +``` + +### With component values : + +```mjs +import { stringify, tokenizer } from '@csstools/css-tokenizer'; +import { parseCommaSeparatedListOfComponentValues } from '@csstools/css-parser-algorithms'; +import { calcFromComponentValues } from '@csstools/css-calc'; + +const t = tokenizer({ + css: 'calc(10 * 2)', +}); + +const tokens = []; + +{ + while (!t.endOfFile()) { + tokens.push(t.nextToken()); + } + + tokens.push(t.nextToken()); // EOF-token +} + +const result = parseCommaSeparatedListOfComponentValues(tokens, {}); + +// filter or mutate the component values + +const calcResult = calcFromComponentValues(result, { precision: 5, toCanonicalUnits: true }); + +// filter or mutate the component values even further + +const calcResultStr = calcResult.map((componentValues) => { + return componentValues.map((x) => stringify(...x.tokens())).join(''); +}).join(','); + +// '20' +console.log(calcResultStr); +``` + +### Options + +#### `precision` : + +The default precision is fairly high. +It aims to be high enough to make rounding unnoticeable in the browser. + +You can set it to a lower number to suit your needs. + +```mjs +import { calc } from '@csstools/css-calc'; + +// '0.3' +console.log(calc('calc(1 / 3)', { precision: 1 })); +// '0.33' +console.log(calc('calc(1 / 3)', { precision: 2 })); +``` + +#### `globals` : + +Pass global values as a map of key value pairs. + +> Example : Relative color syntax (`lch(from pink calc(l / 2) c h)`) exposes color channel information as ident tokens. +> By passing globals for `l`, `c` and `h` it is possible to solve nested `calc()`'s. + +```mjs +import { calc } from '@csstools/css-calc'; + +const globals = new Map([ + ['a', '10px'], + ['b', '2rem'], +]); + +// '20px' +console.log(calc('calc(a * 2)', { globals: globals })); +// '6rem' +console.log(calc('calc(b * 3)', { globals: globals })); +``` + +#### `toCanonicalUnits` : + +By default this package will try to preserve units. +The heuristic to do this is very simplistic. +We take the first unit we encounter and try to convert other dimensions to that unit. + +This better matches what users expect from a CSS dev tool. + +If you want to have outputs that are closes to CSS serialized values you can pass `toCanonicalUnits: true`. + +```mjs +import { calc } from '@csstools/css-calc'; + +// '20hz' +console.log(calc('calc(0.01khz + 10hz)', { toCanonicalUnits: true })); + +// '20hz' +console.log(calc('calc(10hz + 0.01khz)', { toCanonicalUnits: true })); + +// '0.02khz' !!! +console.log(calc('calc(0.01khz + 10hz)', { toCanonicalUnits: false })); + +// '20hz' +console.log(calc('calc(10hz + 0.01khz)', { toCanonicalUnits: false })); +``` + +[cli-url]: https://github.com/csstools/postcss-plugins/actions/workflows/test.yml?query=workflow/test +[discord]: https://discord.gg/bUadyRwkJS +[npm-url]: https://www.npmjs.com/package/@csstools/css-calc + +[CSS calc]: https://github.com/csstools/postcss-plugins/tree/main/packages/css-calc diff --git a/node_modules/@csstools/css-calc/dist/index.d.ts b/node_modules/@csstools/css-calc/dist/index.d.ts new file mode 100644 index 00000000..28b84815 --- /dev/null +++ b/node_modules/@csstools/css-calc/dist/index.d.ts @@ -0,0 +1,101 @@ +import { ComponentValue } from '@csstools/css-parser-algorithms'; +import type { TokenDimension } from '@csstools/css-tokenizer'; +import type { TokenNumber } from '@csstools/css-tokenizer'; +import type { TokenPercentage } from '@csstools/css-tokenizer'; + +export declare function calc(css: string, options?: conversionOptions): string; + +export declare function calcFromComponentValues(componentValuesList: Array>, options?: conversionOptions): Array>; + +export declare type conversionOptions = { + /** + * If a calc expression can not be solved the parse error might be reported through this callback. + * Not all cases are covered. Open an issue if you need specific errors reported. + * + * Values are recursively visited and at each nesting level an attempt is made to solve the expression. + * Errors can be reported multiple times as a result of this. + */ + onParseError?: (error: ParseError) => void; + /** + * Pass global values as a map of key value pairs. + */ + globals?: GlobalsWithStrings; + /** + * The default precision is fairly high. + * It aims to be high enough to make rounding unnoticeable in the browser. + * You can set it to a lower number to suite your needs. + */ + precision?: number; + /** + * By default this package will try to preserve units. + * The heuristic to do this is very simplistic. + * We take the first unit we encounter and try to convert other dimensions to that unit. + * + * This better matches what users expect from a CSS dev tool. + * + * If you want to have outputs that are closes to CSS serialized values you can set `true`. + */ + toCanonicalUnits?: boolean; + /** + * Convert NaN, Infinity, ... into standard representable values. + */ + censorIntoStandardRepresentableValues?: boolean; + /** + * Some percentages resolve against other values and might be negative or positive depending on context. + * Raw percentages are more likely to be safe to simplify outside of a browser context + * + * @see https://drafts.csswg.org/css-values-4/#calc-simplification + */ + rawPercentages?: boolean; + /** + * The values used to generate random value cache keys. + */ + randomCaching?: { + /** + * The name of the property the random function is used in. + */ + propertyName: string; + /** + * N is the index of the random function among other random functions in the same property value. + */ + propertyN: number; + /** + * An element ID identifying the element the style is being applied to. + * When omitted any `random()` call will not be computed. + */ + elementID: string; + /** + * A document ID identifying the Document the styles are from. + * When omitted any `random()` call will not be computed. + */ + documentID: string; + }; +}; + +export declare type GlobalsWithStrings = Map; + +export declare const mathFunctionNames: Set; + +/** + * Any errors are reported through the `onParseError` callback. + */ +export declare class ParseError extends Error { + /** The index of the start character of the current token. */ + sourceStart: number; + /** The index of the end character of the current token. */ + sourceEnd: number; + constructor(message: string, sourceStart: number, sourceEnd: number); +} + +export declare const ParseErrorMessage: { + UnexpectedAdditionOfDimensionOrPercentageWithNumber: string; + UnexpectedSubtractionOfDimensionOrPercentageWithNumber: string; +}; + +export declare class ParseErrorWithComponentValues extends ParseError { + /** The associated component values. */ + componentValues: Array; + constructor(message: string, componentValues: Array); +} + +export { } diff --git a/node_modules/@csstools/css-calc/dist/index.mjs b/node_modules/@csstools/css-calc/dist/index.mjs new file mode 100644 index 00000000..4471bb9e --- /dev/null +++ b/node_modules/@csstools/css-calc/dist/index.mjs @@ -0,0 +1 @@ +import{sourceIndices as e,TokenNode as n,isTokenNode as t,isWhitespaceNode as r,isCommentNode as a,isWhiteSpaceOrCommentNode as u,isSimpleBlockNode as o,isFunctionNode as i,FunctionNode as l,WhitespaceNode as c,parseCommaSeparatedListOfComponentValues as s,walk as v}from"@csstools/css-parser-algorithms";import{isTokenDimension as f,TokenType as m,NumberType as p,mutateUnit as C,isTokenNumber as d,isTokenPercentage as g,isTokenIdent as D,isTokenNumeric as N,isTokenOpenParen as h,isTokenDelim as B,isTokenComma as A,isToken as b,tokenizer as F,tokenize as w,stringify as E,isTokenColon as S,isTokenSemicolon as I}from"@csstools/css-tokenizer";class ParseError extends Error{sourceStart;sourceEnd;constructor(e,n,t){super(e),this.name="ParseError",this.sourceStart=n,this.sourceEnd=t}}class ParseErrorWithComponentValues extends ParseError{componentValues;constructor(n,t){super(n,...e(t)),this.componentValues=t}}const y={UnexpectedAdditionOfDimensionOrPercentageWithNumber:"Unexpected addition of a dimension or percentage with a number.",UnexpectedSubtractionOfDimensionOrPercentageWithNumber:"Unexpected subtraction of a dimension or percentage with a number."},M=/[A-Z]/g;function toLowerCaseAZ(e){return e.replace(M,e=>String.fromCharCode(e.charCodeAt(0)+32))}const T={cm:"px",in:"px",mm:"px",pc:"px",pt:"px",px:"px",q:"px",deg:"deg",grad:"deg",rad:"deg",turn:"deg",ms:"s",s:"s",hz:"hz",khz:"hz"},x=new Map([["cm",e=>e],["mm",e=>10*e],["q",e=>40*e],["in",e=>e/2.54],["pc",e=>e/2.54*6],["pt",e=>e/2.54*72],["px",e=>e/2.54*96]]),P=new Map([["deg",e=>e],["grad",e=>e/.9],["rad",e=>e/180*Math.PI],["turn",e=>e/360]]),k=new Map([["deg",e=>.9*e],["grad",e=>e],["rad",e=>.9*e/180*Math.PI],["turn",e=>.9*e/360]]),O=new Map([["hz",e=>e],["khz",e=>e/1e3]]),W=new Map([["cm",e=>2.54*e],["mm",e=>25.4*e],["q",e=>25.4*e*4],["in",e=>e],["pc",e=>6*e],["pt",e=>72*e],["px",e=>96*e]]),U=new Map([["hz",e=>1e3*e],["khz",e=>e]]),L=new Map([["cm",e=>e/10],["mm",e=>e],["q",e=>4*e],["in",e=>e/25.4],["pc",e=>e/25.4*6],["pt",e=>e/25.4*72],["px",e=>e/25.4*96]]),V=new Map([["ms",e=>e],["s",e=>e/1e3]]),$=new Map([["cm",e=>e/6*2.54],["mm",e=>e/6*25.4],["q",e=>e/6*25.4*4],["in",e=>e/6],["pc",e=>e],["pt",e=>e/6*72],["px",e=>e/6*96]]),Z=new Map([["cm",e=>e/72*2.54],["mm",e=>e/72*25.4],["q",e=>e/72*25.4*4],["in",e=>e/72],["pc",e=>e/72*6],["pt",e=>e],["px",e=>e/72*96]]),z=new Map([["cm",e=>e/96*2.54],["mm",e=>e/96*25.4],["q",e=>e/96*25.4*4],["in",e=>e/96],["pc",e=>e/96*6],["pt",e=>e/96*72],["px",e=>e]]),q=new Map([["cm",e=>e/4/10],["mm",e=>e/4],["q",e=>e],["in",e=>e/4/25.4],["pc",e=>e/4/25.4*6],["pt",e=>e/4/25.4*72],["px",e=>e/4/25.4*96]]),G=new Map([["deg",e=>180*e/Math.PI],["grad",e=>180*e/Math.PI/.9],["rad",e=>e],["turn",e=>180*e/Math.PI/360]]),R=new Map([["ms",e=>1e3*e],["s",e=>e]]),j=new Map([["deg",e=>360*e],["grad",e=>360*e/.9],["rad",e=>360*e/180*Math.PI],["turn",e=>e]]),Y=new Map([["cm",x],["mm",L],["q",q],["in",W],["pc",$],["pt",Z],["px",z],["ms",V],["s",R],["deg",P],["grad",k],["rad",G],["turn",j],["hz",O],["khz",U]]);function convertUnit(e,n){if(!f(e))return n;if(!f(n))return n;const t=toLowerCaseAZ(e[4].unit),r=toLowerCaseAZ(n[4].unit);if(t===r)return n;const a=Y.get(r);if(!a)return n;const u=a.get(t);if(!u)return n;const o=u(n[4].value),i=[m.Dimension,"",n[2],n[3],{...n[4],signCharacter:o<0?"-":void 0,type:Number.isInteger(o)?p.Integer:p.Number,value:o}];return C(i,e[4].unit),i}function toCanonicalUnit(e){if(!f(e))return e;const n=toLowerCaseAZ(e[4].unit),t=T[n];if(n===t)return e;const r=Y.get(n);if(!r)return e;const a=r.get(t);if(!a)return e;const u=a(e[4].value),o=[m.Dimension,"",e[2],e[3],{...e[4],signCharacter:u<0?"-":void 0,type:Number.isInteger(u)?p.Integer:p.Number,value:u}];return C(o,t),o}function addition(e,t){if(2!==e.length)return-1;const r=e[0].value;let a=e[1].value;if(d(r)&&d(a)){const e=r[4].value+a[4].value;return new n([m.Number,e.toString(),r[2],a[3],{value:e,type:r[4].type===p.Integer&&a[4].type===p.Integer?p.Integer:p.Number}])}if(g(r)&&g(a)){const e=r[4].value+a[4].value;return new n([m.Percentage,e.toString()+"%",r[2],a[3],{value:e}])}if(f(r)&&f(a)&&(a=convertUnit(r,a),toLowerCaseAZ(r[4].unit)===toLowerCaseAZ(a[4].unit))){const e=r[4].value+a[4].value;return new n([m.Dimension,e.toString()+r[4].unit,r[2],a[3],{value:e,type:r[4].type===p.Integer&&a[4].type===p.Integer?p.Integer:p.Number,unit:r[4].unit}])}return(d(r)&&(f(a)||g(a))||d(a)&&(f(r)||g(r)))&&t.onParseError?.(new ParseErrorWithComponentValues(y.UnexpectedAdditionOfDimensionOrPercentageWithNumber,e)),-1}function division(e){if(2!==e.length)return-1;const t=e[0].value,r=e[1].value;if(d(t)&&d(r)){const e=t[4].value/r[4].value;return new n([m.Number,e.toString(),t[2],r[3],{value:e,type:Number.isInteger(e)?p.Integer:p.Number}])}if(g(t)&&d(r)){const e=t[4].value/r[4].value;return new n([m.Percentage,e.toString()+"%",t[2],r[3],{value:e}])}if(f(t)&&d(r)){const e=t[4].value/r[4].value;return new n([m.Dimension,e.toString()+t[4].unit,t[2],r[3],{value:e,type:Number.isInteger(e)?p.Integer:p.Number,unit:t[4].unit}])}return-1}function isCalculation(e){return!!e&&"object"==typeof e&&"inputs"in e&&Array.isArray(e.inputs)&&"operation"in e}function solve(e,n){if(-1===e)return-1;const r=[];for(let a=0;aconvertUnit(a,e.value));if(!arrayOfSameNumeric(u))return-1;const o=u.map(e=>e[4].value),i=Math.hypot(...o);return resultToCalculation(e,a,i)}function solveMax(e,n,r){if(!n.every(t))return-1;const a=n[0].value;if(!N(a))return-1;if(!r.rawPercentages&&g(a))return-1;const u=n.map(e=>convertUnit(a,e.value));if(!arrayOfSameNumeric(u))return-1;const o=u.map(e=>e[4].value),i=Math.max(...o);return resultToCalculation(e,a,i)}function solveMin(e,n,r){if(!n.every(t))return-1;const a=n[0].value;if(!N(a))return-1;if(!r.rawPercentages&&g(a))return-1;const u=n.map(e=>convertUnit(a,e.value));if(!arrayOfSameNumeric(u))return-1;const o=u.map(e=>e[4].value),i=Math.min(...o);return resultToCalculation(e,a,i)}function solveMod(e,n,t){const r=n.value;if(!N(r))return-1;const a=convertUnit(r,t.value);if(!twoOfSameNumeric(r,a))return-1;let u;return u=0===a[4].value?Number.NaN:Number.isFinite(r[4].value)&&(Number.isFinite(a[4].value)||(a[4].value!==Number.POSITIVE_INFINITY||r[4].value!==Number.NEGATIVE_INFINITY&&!Object.is(0*r[4].value,-0))&&(a[4].value!==Number.NEGATIVE_INFINITY||r[4].value!==Number.POSITIVE_INFINITY&&!Object.is(0*r[4].value,0)))?Number.isFinite(a[4].value)?(r[4].value%a[4].value+a[4].value)%a[4].value:r[4].value:Number.NaN,resultToCalculation(e,r,u)}function solvePow(e,n,t){const r=n.value,a=t.value;if(!d(r))return-1;if(!twoOfSameNumeric(r,a))return-1;return numberToCalculation(e,Math.pow(r[4].value,a[4].value))}function solveRem(e,n,t){const r=n.value;if(!N(r))return-1;const a=convertUnit(r,t.value);if(!twoOfSameNumeric(r,a))return-1;let u;return u=0===a[4].value?Number.NaN:Number.isFinite(r[4].value)?Number.isFinite(a[4].value)?r[4].value%a[4].value:r[4].value:Number.NaN,resultToCalculation(e,r,u)}function solveRound(e,n,t,r,a){const u=t.value;if(!N(u))return-1;if(!a.rawPercentages&&g(u))return-1;const o=convertUnit(u,r.value);if(!twoOfSameNumeric(u,o))return-1;let i;if(0===o[4].value)i=Number.NaN;else if(Number.isFinite(u[4].value)||Number.isFinite(o[4].value))if(!Number.isFinite(u[4].value)&&Number.isFinite(o[4].value))i=u[4].value;else if(Number.isFinite(u[4].value)&&!Number.isFinite(o[4].value))switch(n){case"down":i=u[4].value<0?-1/0:Object.is(-0,0*u[4].value)?-0:0;break;case"up":i=u[4].value>0?1/0:Object.is(0,0*u[4].value)?0:-0;break;default:i=Object.is(0,0*u[4].value)?0:-0}else if(Number.isFinite(o[4].value))switch(n){case"down":i=Math.floor(u[4].value/o[4].value)*o[4].value;break;case"up":i=Math.ceil(u[4].value/o[4].value)*o[4].value;break;case"to-zero":i=Math.trunc(u[4].value/o[4].value)*o[4].value;break;default:{let e=Math.floor(u[4].value/o[4].value)*o[4].value,n=Math.ceil(u[4].value/o[4].value)*o[4].value;if(e>n){const t=e;e=n,n=t}const t=Math.abs(u[4].value-e),r=Math.abs(u[4].value-n);i=t===r?n:t0?1/0:-1/0:Math.tan(u),numberToCalculation(e,u)}function subtraction(e,t){if(2!==e.length)return-1;const r=e[0].value;let a=e[1].value;if(d(r)&&d(a)){const e=r[4].value-a[4].value;return new n([m.Number,e.toString(),r[2],a[3],{value:e,type:r[4].type===p.Integer&&a[4].type===p.Integer?p.Integer:p.Number}])}if(g(r)&&g(a)){const e=r[4].value-a[4].value;return new n([m.Percentage,e.toString()+"%",r[2],a[3],{value:e}])}if(f(r)&&f(a)&&(a=convertUnit(r,a),toLowerCaseAZ(r[4].unit)===toLowerCaseAZ(a[4].unit))){const e=r[4].value-a[4].value;return new n([m.Dimension,e.toString()+r[4].unit,r[2],a[3],{value:e,type:r[4].type===p.Integer&&a[4].type===p.Integer?p.Integer:p.Number,unit:r[4].unit}])}return(d(r)&&(f(a)||g(a))||d(a)&&(f(r)||g(r)))&&t.onParseError?.(new ParseErrorWithComponentValues(y.UnexpectedSubtractionOfDimensionOrPercentageWithNumber,e)),-1}function solveLog(e,n){if(1===n.length){const r=n[0];if(!r||!t(r))return-1;const a=r.value;if(!d(a))return-1;return numberToCalculation(e,Math.log(a[4].value))}if(2===n.length){const r=n[0];if(!r||!t(r))return-1;const a=r.value;if(!d(a))return-1;const u=n[1];if(!u||!t(u))return-1;const o=u.value;if(!d(o))return-1;return numberToCalculation(e,Math.log(a[4].value)/Math.log(o[4].value))}return-1}const _=/^none$/i;function isNone(e){if(Array.isArray(e)){const n=e.filter(e=>!(r(e)&&a(e)));return 1===n.length&&isNone(n[0])}if(!t(e))return!1;const n=e.value;return!!D(n)&&_.test(n[4].value)}const H=String.fromCodePoint(0);function solveRandom(e,n,t,r,a,u){if(-1===n.fixed&&!u.randomCaching)return-1;u.randomCaching||(u.randomCaching={propertyName:"",propertyN:0,elementID:"",documentID:""}),u.randomCaching&&!u.randomCaching.propertyN&&(u.randomCaching.propertyN=0);const o=t.value;if(!N(o))return-1;const i=convertUnit(o,r.value);if(!twoOfSameNumeric(o,i))return-1;let l=null;if(a&&(l=convertUnit(o,a.value),!twoOfSameNumeric(o,l)))return-1;if(!Number.isFinite(o[4].value))return resultToCalculation(e,o,Number.NaN);if(!Number.isFinite(i[4].value))return resultToCalculation(e,o,Number.NaN);if(!Number.isFinite(i[4].value-o[4].value))return resultToCalculation(e,o,Number.NaN);if(l&&!Number.isFinite(l[4].value))return resultToCalculation(e,o,o[4].value);const c=-1===n.fixed?sfc32(crc32([n.dashedIdent?n.dashedIdent:`${u.randomCaching?.propertyName} ${u.randomCaching.propertyN++}`,n.elementShared?"":u.randomCaching.elementID,u.randomCaching.documentID].join(H))):()=>n.fixed;let s=o[4].value,v=i[4].value;if(s>v&&([s,v]=[v,s]),l&&(l[4].value<=0||Math.abs(s-v)/l[4].value>1e10)&&(l=null),l){const n=Math.max(l[4].value/1e3,1e-9),t=[s];let r=0;for(;;){r+=l[4].value;const e=s+r;if(!(e+nv)break}const a=c();return resultToCalculation(e,o,Number(t[Math.floor(t.length*a)].toFixed(5)))}const f=c();return resultToCalculation(e,o,Number((f*(v-s)+s).toFixed(5)))}function sfc32(e=.34944106645296036,n=.19228640875738723,t=.8784393832007205,r=.04850964319275053){return()=>{const a=((e|=0)+(n|=0)|0)+(r|=0)|0;return r=r+1|0,e=n^n>>>9,n=(t|=0)+(t<<3)|0,t=(t=t<<21|t>>>11)+a|0,(a>>>0)/4294967296}}function crc32(e){let n=0,t=0,r=0;n^=-1;for(let a=0,u=e.length;a>>8^t;return(-1^n)>>>0}const J=new Map([["abs",function abs(e,n,t){return singleNodeSolver(e,n,t,solveAbs)}],["acos",function acos(e,n,t){return singleNodeSolver(e,n,t,solveACos)}],["asin",function asin(e,n,t){return singleNodeSolver(e,n,t,solveASin)}],["atan",function atan(e,n,t){return singleNodeSolver(e,n,t,solveATan)}],["atan2",function atan2(e,n,t){return twoCommaSeparatedNodesSolver(e,n,t,solveATan2)}],["calc",calc$1],["clamp",function clamp(r,a,o){const i=resolveGlobalsAndConstants([...r.value.filter(e=>!u(e))],a),c=[],s=[],v=[];{let e=c;for(let n=0;n!u(e)),n,t);if(-1===r)return-1;const[a,o]=r,i=variadicArguments(e,o,n,t);if(-1===i)return-1;const[l,c,s]=i;if(!l||!c)return-1;return solveRandom(e,a,l,c,s,t)}],["rem",function rem(e,n,t){return twoCommaSeparatedNodesSolver(e,n,t,solveRem)}],["round",function round(e,r,a){const o=resolveGlobalsAndConstants([...e.value.filter(e=>!u(e))],r);let i="",l=!1;const c=[],s=[];{let e=c;for(let n=0;n!u(e))],n);if(1===a.length&&t(a[0]))return{inputs:[a[0]],operation:unary};let l=0;for(;l!u(e))],n),a=solve(calc$1(calcWrapper(e,r),n,t),t);return-1===a?-1:a}function twoCommaSeparatedNodesSolver(e,n,t,r){const a=twoCommaSeparatedArguments(e,n,t);if(-1===a)return-1;const[u,o]=a;return r(e,u,o,t)}function twoCommaSeparatedArguments(e,n,r){const a=resolveGlobalsAndConstants([...e.value.filter(e=>!u(e))],n),o=[],i=[];{let e=o;for(let n=0;n!u(e))],r),i=[];{const n=[];let u=[];for(let e=0;e1)return-1;u.fixed=Math.max(0,Math.min(i.value[4].value,1-1e-9));continue}if("auto"!==l)if(l.startsWith("--")){if(-1!==u.fixed||u.isAuto)return-1;u.dashedIdent=l}else;else{if(-1!==u.fixed||u.dashedIdent)return-1;u.isAuto=!0}}else{if(-1!==u.fixed)return-1;u.elementShared=!0}}return-1}function calcWrapper(e,n){return new l([m.Function,"calc(",e.name[2],e.name[3],{value:"calc"}],[m.CloseParen,")",e.endToken[2],e.endToken[3],void 0],n)}function maxWrapper(t,r,a){return new l([m.Function,"max(",t.name[2],t.name[3],{value:"max"}],[m.CloseParen,")",t.endToken[2],t.endToken[3],void 0],[r,new n([m.Comma,",",...e(r),void 0]),a])}function patchNaN(e){if(-1===e)return-1;if(i(e))return e;const t=e.value;return N(t)&&Number.isNaN(t[4].value)?d(t)?new l([m.Function,"calc(",t[2],t[3],{value:"calc"}],[m.CloseParen,")",t[2],t[3],void 0],[new n([m.Ident,"NaN",t[2],t[3],{value:"NaN"}])]):f(t)?new l([m.Function,"calc(",t[2],t[3],{value:"calc"}],[m.CloseParen,")",t[2],t[3],void 0],[new n([m.Ident,"NaN",t[2],t[3],{value:"NaN"}]),new c([[m.Whitespace," ",t[2],t[3],void 0]]),new n([m.Delim,"*",t[2],t[3],{value:"*"}]),new c([[m.Whitespace," ",t[2],t[3],void 0]]),new n([m.Dimension,"1"+t[4].unit,t[2],t[3],{value:1,type:p.Integer,unit:t[4].unit}])]):g(t)?new l([m.Function,"calc(",t[2],t[3],{value:"calc"}],[m.CloseParen,")",t[2],t[3],void 0],[new n([m.Ident,"NaN",t[2],t[3],{value:"NaN"}]),new c([[m.Whitespace," ",t[2],t[3],void 0]]),new n([m.Delim,"*",t[2],t[3],{value:"*"}]),new c([[m.Whitespace," ",t[2],t[3],void 0]]),new n([m.Percentage,"1%",t[2],t[3],{value:1}])]):-1:e}function patchInfinity(e){if(-1===e)return-1;if(i(e))return e;const t=e.value;if(!N(t))return e;if(Number.isFinite(t[4].value)||Number.isNaN(t[4].value))return e;let r="";return Number.NEGATIVE_INFINITY===t[4].value&&(r="-"),d(t)?new l([m.Function,"calc(",t[2],t[3],{value:"calc"}],[m.CloseParen,")",t[2],t[3],void 0],[new n([m.Ident,r+"infinity",t[2],t[3],{value:r+"infinity"}])]):f(t)?new l([m.Function,"calc(",t[2],t[3],{value:"calc"}],[m.CloseParen,")",t[2],t[3],void 0],[new n([m.Ident,r+"infinity",t[2],t[3],{value:r+"infinity"}]),new c([[m.Whitespace," ",t[2],t[3],void 0]]),new n([m.Delim,"*",t[2],t[3],{value:"*"}]),new c([[m.Whitespace," ",t[2],t[3],void 0]]),new n([m.Dimension,"1"+t[4].unit,t[2],t[3],{value:1,type:p.Integer,unit:t[4].unit}])]):new l([m.Function,"calc(",t[2],t[3],{value:"calc"}],[m.CloseParen,")",t[2],t[3],void 0],[new n([m.Ident,r+"infinity",t[2],t[3],{value:r+"infinity"}]),new c([[m.Whitespace," ",t[2],t[3],void 0]]),new n([m.Delim,"*",t[2],t[3],{value:"*"}]),new c([[m.Whitespace," ",t[2],t[3],void 0]]),new n([m.Percentage,"1%",t[2],t[3],{value:1}])])}function patchMinusZero(e){if(-1===e)return-1;if(i(e))return e;const n=e.value;return N(n)&&Object.is(-0,n[4].value)?("-0"===n[1]||(g(n)?n[1]="-0%":f(n)?n[1]="-0"+n[4].unit:n[1]="-0"),e):e}function patchPrecision(e,n=13){if(-1===e)return-1;if(n<=0)return e;if(i(e))return e;const t=e.value;if(!N(t))return e;if(Number.isInteger(t[4].value))return e;const r=Number(t[4].value.toFixed(n)).toString();return d(t)?t[1]=r:g(t)?t[1]=r+"%":f(t)&&(t[1]=r+t[4].unit),e}function patchCanonicalUnit(e){return-1===e?-1:i(e)?e:f(e.value)?(e.value=toCanonicalUnit(e.value),e):e}function patchCalcResult(e,n){let t=e;return n?.toCanonicalUnits&&(t=patchCanonicalUnit(t)),t=patchPrecision(t,n?.precision),t=patchMinusZero(t),n?.censorIntoStandardRepresentableValues||(t=patchNaN(t),t=patchInfinity(t)),t}function tokenizeGlobals(e){const n=new Map;if(!e)return n;for(const[t,r]of e)if(b(r))n.set(t,r);else if("string"==typeof r){const e=F({css:r}),a=e.nextToken();if(e.nextToken(),!e.endOfFile())continue;if(!N(a))continue;n.set(t,a);continue}return n}function calc(e,n){return calcFromComponentValues(s(w({css:e}),{}),n).map(e=>e.map(e=>E(...e.tokens())).join("")).join(",")}function calcFromComponentValues(e,n){const t=tokenizeGlobals(n?.globals);return replaceComponentValues(e,e=>{if(!i(e))return;const r=J.get(e.getName().toLowerCase());if(!r)return;const a=patchCalcResult(solve(r(e,t,n??{}),n??{}),n);return-1!==a?a:void 0})}function replaceComponentValues(n,r){for(let a=0;a{if("number"!=typeof a)return;const o=r(n.node);if(!o)return;const i=[o],l=n.parent.value[a-1];t(l)&&B(l.value)&&("-"===l.value[4].value||"+"===l.value[4].value)&&i.splice(0,0,new c([[m.Whitespace," ",...e(n.node),void 0]]));const s=n.parent.value[a+1];!s||u(s)||t(s)&&(A(s.value)||S(s.value)||I(s.value)||B(s.value)&&"-"!==s.value[4].value&&"+"!==s.value[4].value)||i.push(new c([[m.Whitespace," ",...e(n.node),void 0]])),n.parent.value.splice(a,1,...i)})}return n}const Q=new Set(J.keys());export{ParseError,y as ParseErrorMessage,ParseErrorWithComponentValues,calc,calcFromComponentValues,Q as mathFunctionNames}; diff --git a/node_modules/@csstools/css-calc/package.json b/node_modules/@csstools/css-calc/package.json new file mode 100644 index 00000000..8635edef --- /dev/null +++ b/node_modules/@csstools/css-calc/package.json @@ -0,0 +1,59 @@ +{ + "name": "@csstools/css-calc", + "description": "Solve CSS math expressions", + "version": "3.1.1", + "contributors": [ + { + "name": "Antonio Laguna", + "email": "antonio@laguna.es", + "url": "https://antonio.laguna.es" + }, + { + "name": "Romain Menke", + "email": "romainmenke@gmail.com" + } + ], + "license": "MIT", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "engines": { + "node": ">=20.19.0" + }, + "type": "module", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + } + }, + "files": [ + "CHANGELOG.md", + "LICENSE.md", + "README.md", + "dist" + ], + "peerDependencies": { + "@csstools/css-parser-algorithms": "^4.0.0", + "@csstools/css-tokenizer": "^4.0.0" + }, + "scripts": {}, + "homepage": "https://github.com/csstools/postcss-plugins/tree/main/packages/css-calc#readme", + "repository": { + "type": "git", + "url": "git+https://github.com/csstools/postcss-plugins.git", + "directory": "packages/css-calc" + }, + "bugs": "https://github.com/csstools/postcss-plugins/issues", + "keywords": [ + "calc", + "css" + ] +} diff --git a/node_modules/@csstools/css-color-parser/CHANGELOG.md b/node_modules/@csstools/css-color-parser/CHANGELOG.md new file mode 100644 index 00000000..685e4b25 --- /dev/null +++ b/node_modules/@csstools/css-color-parser/CHANGELOG.md @@ -0,0 +1,10 @@ +# Changes to CSS Color Parser + +### 4.0.2 + +_February 21, 2026_ + +- Updated [`@csstools/css-calc`](https://github.com/csstools/postcss-plugins/tree/main/packages/css-calc) to [`3.1.1`](https://github.com/csstools/postcss-plugins/tree/main/packages/css-calc/CHANGELOG.md#311) (minor) +- Updated [`@csstools/color-helpers`](https://github.com/csstools/postcss-plugins/tree/main/packages/color-helpers) to [`6.0.2`](https://github.com/csstools/postcss-plugins/tree/main/packages/color-helpers/CHANGELOG.md#602) (patch) + +[Full CHANGELOG](https://github.com/csstools/postcss-plugins/tree/main/packages/css-color-parser/CHANGELOG.md) diff --git a/node_modules/@csstools/css-color-parser/LICENSE.md b/node_modules/@csstools/css-color-parser/LICENSE.md new file mode 100644 index 00000000..af5411fa --- /dev/null +++ b/node_modules/@csstools/css-color-parser/LICENSE.md @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright 2022 Romain Menke, Antonio Laguna + +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. diff --git a/node_modules/@csstools/css-color-parser/README.md b/node_modules/@csstools/css-color-parser/README.md new file mode 100644 index 00000000..f886fc91 --- /dev/null +++ b/node_modules/@csstools/css-color-parser/README.md @@ -0,0 +1,37 @@ +# CSS Color Parser for CSS + +[npm version][npm-url] +[Build Status][cli-url] +[Discord][discord] + +## Usage + +Add [CSS Color Parser] to your project: + +```bash +npm install @csstools/css-color-parser @csstools/css-parser-algorithms @csstools/css-tokenizer --save-dev +``` + +```ts +import { color } from '@csstools/css-color-parser'; +import { isFunctionNode, parseComponentValue } from '@csstools/css-parser-algorithms'; +import { serializeRGB } from '@csstools/css-color-parser'; +import { tokenize } from '@csstools/css-tokenizer'; + +// color() expects a parsed component value. +const hwbComponentValue = parseComponentValue(tokenize({ css: 'hwb(10deg 10% 20%)' })); +const colorData = color(hwbComponentValue); +if (colorData) { + console.log(colorData); + + // serializeRGB() returns a component value. + const rgbComponentValue = serializeRGB(colorData); + console.log(rgbComponentValue.toString()); +} +``` + +[cli-url]: https://github.com/csstools/postcss-plugins/actions/workflows/test.yml?query=workflow/test +[discord]: https://discord.gg/bUadyRwkJS +[npm-url]: https://www.npmjs.com/package/@csstools/css-color-parser + +[CSS Color Parser]: https://github.com/csstools/postcss-plugins/tree/main/packages/css-color-parser diff --git a/node_modules/@csstools/css-color-parser/dist/index.d.ts b/node_modules/@csstools/css-color-parser/dist/index.d.ts new file mode 100644 index 00000000..e4b8600e --- /dev/null +++ b/node_modules/@csstools/css-color-parser/dist/index.d.ts @@ -0,0 +1,168 @@ +import type { Color } from '@csstools/color-helpers'; +import type { ComponentValue } from '@csstools/css-parser-algorithms'; +import { FunctionNode } from '@csstools/css-parser-algorithms'; + +/** + * Convert a color function to a `ColorData` object. + * + * @param {ComponentValue} colorNode - The color function to be converted. + * @returns {ColorData|false} The color function as a `ColorData` object or `false` if it could not be converted. + */ +export declare function color(colorNode: ComponentValue): ColorData | false; + +/** + * A color data object. + * It contains as much information as possible about the color and the original parsed syntax. + */ +export declare interface ColorData { + /** + * The color notation of the color data. + * + * We use "color notation" and not "color space" because these represent the original notation and not the actual color space. + * The actual color space is however always implied by the color notation. + */ + colorNotation: ColorNotation; + /** + * The color channels. + * This is always an array of three numbers + * but the channels can only be interpreted by looking at the color notation. + */ + channels: Color; + /** + * The alpha channel. + * This is either a number between `0` and `1` or a `ComponentValue` object. + * + * Since most computations are not dependent on the alpha channel, + * we allow things like `var(--some-alpha)` as an alpha channel value for most inputs. + */ + alpha: number | ComponentValue; + /** + * Information about the original syntax. + */ + syntaxFlags: Set; +} + +/** + * Check if a color data object fits the `display-p3` gamut. + * + * @param {ColorData} x - The color data to be checked. + * @returns {boolean} Whether the color data fits the `display-p3` gamut. + */ +export declare function colorDataFitsDisplayP3_Gamut(x: ColorData): boolean; + +/** + * Check if a color data object fits the `sRGB` gamut. + * + * @param {ColorData} x - The color data to be checked. + * @returns {boolean} Whether the color data fits the `sRGB` gamut. + */ +export declare function colorDataFitsRGB_Gamut(x: ColorData): boolean; + +export declare enum ColorNotation { + /** Adobe 1999, expressed through `color(a98-rgb 0 0 0)` */ + A98_RGB = "a98-rgb", + /** Display P3, expressed through `color(display-p3 0 0 0)` */ + Display_P3 = "display-p3", + /** Display P3, expressed through `color(display-p3-linear 0 0 0)` */ + Linear_Display_P3 = "display-p3-linear", + /** Hex, expressed through `#000` */ + HEX = "hex", + /** HSL, expressed through `hsl(0 0% 0%)` */ + HSL = "hsl", + /** HWB, expressed through `hwb(0 0% 0%)` */ + HWB = "hwb", + /** LCH, expressed through `lch(0 0% 0deg)` */ + LCH = "lch", + /** Lab, expressed through `lab(0 0 0)` */ + Lab = "lab", + /** Linear sRGB, expressed through `color(linear-srgb 0 0 0)` */ + Linear_sRGB = "srgb-linear", + /** Oklch, expressed through `oklch(0 0% 0deg)` */ + OKLCH = "oklch", + /** Oklab, expressed through `oklab(0 0 0)` */ + OKLab = "oklab", + /** ProPhoto RGB, expressed through `color(prophoto-rgb 0 0 0)` */ + ProPhoto_RGB = "prophoto-rgb", + /** RGB, expressed through `rgb(0 0 0)` */ + RGB = "rgb", + /** sRGB, expressed through `color(srgb 0 0 0)` */ + sRGB = "srgb", + /** Rec. 2020, expressed through `color(rec2020 0 0 0)` */ + Rec2020 = "rec2020", + /** XYZ, expressed through `color(xyz-d50 0 0 0)` */ + XYZ_D50 = "xyz-d50", + /** XYZ, expressed through `color(xyz-d65 0 0 0)` */ + XYZ_D65 = "xyz-d65" +} + +export declare function serializeHSL(color: ColorData, gamutMapping?: boolean): FunctionNode; + +/** + * Convert color data to component values in the OKLCH color space. + * The return value can be converted to a string by calling `toString()` on it. + * + * @param {ColorData} color - The color data to be serialized. + * @returns {FunctionNode} The serialized color data as a FunctionNode object. + */ +export declare function serializeOKLCH(color: ColorData): FunctionNode; + +/** + * Convert color data to component values in the display-p3 color space. + * The return value can be converted to a string by calling `toString()` on it. + * + * @param {ColorData} color - The color data to be serialized. + * @param {boolean} gamutMapping - Whether to perform gamut mapping, defaults to `true`. + * @returns {FunctionNode} The serialized color data as a FunctionNode object. + */ +export declare function serializeP3(color: ColorData, gamutMapping?: boolean): FunctionNode; + +/** + * Convert color data to component values in the srgb color space. + * The return value can be converted to a string by calling `toString()` on it. + * + * @param {ColorData} color - The color data to be serialized. + * @param {boolean} gamutMapping - Whether to perform gamut mapping, defaults to `true`. + * @returns {FunctionNode} The serialized color data as a FunctionNode object. + */ +export declare function serializeRGB(color: ColorData, gamutMapping?: boolean): FunctionNode; + +export declare enum SyntaxFlag { + /** Is a color keyword, e.g. `transparent`, `currentColor`, ... */ + ColorKeyword = "color-keyword", + /** Has an explicit alpha channel */ + HasAlpha = "has-alpha", + /** Has a channel with a dimension value, e.g. `50deg` */ + HasDimensionValues = "has-dimension-values", + /** Has a channel with the `none` keyword */ + HasNoneKeywords = "has-none-keywords", + /** Has a channel with a number value */ + HasNumberValues = "has-number-values", + /** Has an alpha channel with a percentage value */ + HasPercentageAlpha = "has-percentage-alpha", + /** Has a channel with a percentage value */ + HasPercentageValues = "has-percentage-values", + /** Has an alpha channel with a `var()` function value */ + HasVariableAlpha = "has-variable-alpha", + /** Is Hex notation */ + Hex = "hex", + /** Is legacy HSL, e.g. `hsl(50deg, 0%, 0%)` */ + LegacyHSL = "legacy-hsl", + /** Is legacy RGB, e.g. `rgb(0, 0, 0)` */ + LegacyRGB = "legacy-rgb", + /** Is a named color, e.g. `red`, `blue` */ + NamedColor = "named-color", + /** Is a relative color syntax, e.g. `rgb(from purple r g b)` */ + RelativeColorSyntax = "relative-color-syntax", + /** Is a mixed color, e.g. `color-mix(in oklch, red, blue)` */ + ColorMix = "color-mix", + /** Is a variadic mixed color, e.g. `color-mix(in oklch, red)` `color-mix(in oklch, red, blue, green)` */ + ColorMixVariadic = "color-mix-variadic", + /** Is a contrasting color, e.g. `contrast-color()` */ + ContrastColor = "contrast-color", + /** Is a relative alpha syntax `alpha(from red / 0.5)` */ + RelativeAlphaSyntax = "relative-alpha-syntax", + /** Is an experimental color syntax */ + Experimental = "experimental" +} + +export { } diff --git a/node_modules/@csstools/css-color-parser/dist/index.mjs b/node_modules/@csstools/css-color-parser/dist/index.mjs new file mode 100644 index 00000000..92682a1a --- /dev/null +++ b/node_modules/@csstools/css-color-parser/dist/index.mjs @@ -0,0 +1 @@ +import{TokenType as e,NumberType as a,isTokenIdent as n,isTokenPercentage as r,isTokenNumber as o,isTokenDelim as t,isTokenNumeric as l,isTokenComma as s,isTokenDimension as u,isTokenHash as i}from"@csstools/css-tokenizer";import{XYZ_D50_to_XYZ_D65 as c,XYZ_D50_to_XYZ_D50 as h,XYZ_D50_to_OKLab as m,XYZ_D50_to_OKLCH as p,XYZ_D50_to_LCH as N,XYZ_D50_to_Lab as b,XYZ_D50_to_HWB as v,XYZ_D50_to_HSL as g,XYZ_D50_to_a98_RGB as f,XYZ_D50_to_ProPhoto as d,XYZ_D50_to_rec_2020 as y,XYZ_D50_to_lin_P3 as _,XYZ_D50_to_P3 as C,XYZ_D50_to_lin_sRGB as w,XYZ_D50_to_sRGB as x,XYZ_D65_to_XYZ_D50 as L,OKLCH_to_XYZ_D50 as H,LCH_to_XYZ_D50 as P,OKLab_to_XYZ_D50 as k,Lab_to_XYZ_D50 as S,HWB_to_XYZ_D50 as D,HSL_to_XYZ_D50 as M,ProPhoto_RGB_to_XYZ_D50 as F,a98_RGB_to_XYZ_D50 as z,rec_2020_to_XYZ_D50 as Z,lin_P3_to_XYZ_D50 as R,P3_to_XYZ_D50 as B,lin_sRGB_to_XYZ_D50 as V,sRGB_to_XYZ_D50 as T,namedColors as G,inGamut as A,clip as X,gam_sRGB as K,mapGamutRayTrace as Y,OKLCH_to_OKLab as I,OKLab_to_XYZ as O,XYZ_to_lin_sRGB as W,lin_sRGB_to_XYZ as E,XYZ_to_OKLab as U,OKLab_to_OKLCH as $,contrast_ratio_wcag_2_1 as j,gam_P3 as q,XYZ_to_lin_P3 as J,lin_P3_to_XYZ as Q}from"@csstools/color-helpers";import{isWhitespaceNode as ee,isCommentNode as ae,isTokenNode as ne,isFunctionNode as re,TokenNode as oe,isWhiteSpaceOrCommentNode as te,replaceComponentValues as le,FunctionNode as se,WhitespaceNode as ue}from"@csstools/css-parser-algorithms";import{mathFunctionNames as ie,calcFromComponentValues as ce}from"@csstools/css-calc";var he,me;function convertNaNToZero(e){return[Number.isNaN(e[0])?0:e[0],Number.isNaN(e[1])?0:e[1],Number.isNaN(e[2])?0:e[2]]}function colorData_to_XYZ_D50(e){switch(e.colorNotation){case he.HEX:case he.RGB:case he.sRGB:return{...e,colorNotation:he.XYZ_D50,channels:T(convertNaNToZero(e.channels))};case he.Linear_sRGB:return{...e,colorNotation:he.XYZ_D50,channels:V(convertNaNToZero(e.channels))};case he.Display_P3:return{...e,colorNotation:he.XYZ_D50,channels:B(convertNaNToZero(e.channels))};case he.Linear_Display_P3:return{...e,colorNotation:he.XYZ_D50,channels:R(convertNaNToZero(e.channels))};case he.Rec2020:return{...e,colorNotation:he.XYZ_D50,channels:Z(convertNaNToZero(e.channels))};case he.A98_RGB:return{...e,colorNotation:he.XYZ_D50,channels:z(convertNaNToZero(e.channels))};case he.ProPhoto_RGB:return{...e,colorNotation:he.XYZ_D50,channels:F(convertNaNToZero(e.channels))};case he.HSL:return{...e,colorNotation:he.XYZ_D50,channels:M(convertNaNToZero(e.channels))};case he.HWB:return{...e,colorNotation:he.XYZ_D50,channels:D(convertNaNToZero(e.channels))};case he.Lab:return{...e,colorNotation:he.XYZ_D50,channels:S(convertNaNToZero(e.channels))};case he.OKLab:return{...e,colorNotation:he.XYZ_D50,channels:k(convertNaNToZero(e.channels))};case he.LCH:return{...e,colorNotation:he.XYZ_D50,channels:P(convertNaNToZero(e.channels))};case he.OKLCH:return{...e,colorNotation:he.XYZ_D50,channels:H(convertNaNToZero(e.channels))};case he.XYZ_D50:return{...e,colorNotation:he.XYZ_D50,channels:h(convertNaNToZero(e.channels))};case he.XYZ_D65:return{...e,colorNotation:he.XYZ_D50,channels:L(convertNaNToZero(e.channels))};default:throw new Error("Unsupported color notation")}}!function(e){e.A98_RGB="a98-rgb",e.Display_P3="display-p3",e.Linear_Display_P3="display-p3-linear",e.HEX="hex",e.HSL="hsl",e.HWB="hwb",e.LCH="lch",e.Lab="lab",e.Linear_sRGB="srgb-linear",e.OKLCH="oklch",e.OKLab="oklab",e.ProPhoto_RGB="prophoto-rgb",e.RGB="rgb",e.sRGB="srgb",e.Rec2020="rec2020",e.XYZ_D50="xyz-d50",e.XYZ_D65="xyz-d65"}(he||(he={})),function(e){e.ColorKeyword="color-keyword",e.HasAlpha="has-alpha",e.HasDimensionValues="has-dimension-values",e.HasNoneKeywords="has-none-keywords",e.HasNumberValues="has-number-values",e.HasPercentageAlpha="has-percentage-alpha",e.HasPercentageValues="has-percentage-values",e.HasVariableAlpha="has-variable-alpha",e.Hex="hex",e.LegacyHSL="legacy-hsl",e.LegacyRGB="legacy-rgb",e.NamedColor="named-color",e.RelativeColorSyntax="relative-color-syntax",e.ColorMix="color-mix",e.ColorMixVariadic="color-mix-variadic",e.ContrastColor="contrast-color",e.RelativeAlphaSyntax="relative-alpha-syntax",e.Experimental="experimental"}(me||(me={}));const pe=new Set([he.A98_RGB,he.Display_P3,he.Linear_Display_P3,he.HEX,he.Linear_sRGB,he.ProPhoto_RGB,he.RGB,he.sRGB,he.Rec2020,he.XYZ_D50,he.XYZ_D65]);function colorDataTo(e,a){const n={...e};if(e.colorNotation!==a){const e=colorData_to_XYZ_D50(n);switch(a){case he.HEX:case he.RGB:n.colorNotation=he.RGB,n.channels=x(e.channels);break;case he.sRGB:n.colorNotation=he.sRGB,n.channels=x(e.channels);break;case he.Linear_sRGB:n.colorNotation=he.Linear_sRGB,n.channels=w(e.channels);break;case he.Display_P3:n.colorNotation=he.Display_P3,n.channels=C(e.channels);break;case he.Linear_Display_P3:n.colorNotation=he.Linear_Display_P3,n.channels=_(e.channels);break;case he.Rec2020:n.colorNotation=he.Rec2020,n.channels=y(e.channels);break;case he.ProPhoto_RGB:n.colorNotation=he.ProPhoto_RGB,n.channels=d(e.channels);break;case he.A98_RGB:n.colorNotation=he.A98_RGB,n.channels=f(e.channels);break;case he.HSL:n.colorNotation=he.HSL,n.channels=g(e.channels);break;case he.HWB:n.colorNotation=he.HWB,n.channels=v(e.channels);break;case he.Lab:n.colorNotation=he.Lab,n.channels=b(e.channels);break;case he.LCH:n.colorNotation=he.LCH,n.channels=N(e.channels);break;case he.OKLCH:n.colorNotation=he.OKLCH,n.channels=p(e.channels);break;case he.OKLab:n.colorNotation=he.OKLab,n.channels=m(e.channels);break;case he.XYZ_D50:n.colorNotation=he.XYZ_D50,n.channels=h(e.channels);break;case he.XYZ_D65:n.colorNotation=he.XYZ_D65,n.channels=c(e.channels);break;default:throw new Error("Unsupported color notation")}}else n.channels=convertNaNToZero(e.channels);if(a===e.colorNotation)n.channels=carryForwardMissingComponents(e.channels,[0,1,2],n.channels,[0,1,2]);else if(pe.has(a)&&pe.has(e.colorNotation))n.channels=carryForwardMissingComponents(e.channels,[0,1,2],n.channels,[0,1,2]);else switch(a){case he.HSL:switch(e.colorNotation){case he.HWB:n.channels=carryForwardMissingComponents(e.channels,[0],n.channels,[0]);break;case he.Lab:case he.OKLab:n.channels=carryForwardMissingComponents(e.channels,[2],n.channels,[0]);break;case he.LCH:case he.OKLCH:n.channels=carryForwardMissingComponents(e.channels,[0,1,2],n.channels,[2,1,0])}break;case he.HWB:switch(e.colorNotation){case he.HSL:n.channels=carryForwardMissingComponents(e.channels,[0],n.channels,[0]);break;case he.LCH:case he.OKLCH:n.channels=carryForwardMissingComponents(e.channels,[0],n.channels,[2])}break;case he.Lab:case he.OKLab:switch(e.colorNotation){case he.HSL:n.channels=carryForwardMissingComponents(e.channels,[0],n.channels,[2]);break;case he.Lab:case he.OKLab:n.channels=carryForwardMissingComponents(e.channels,[0,1,2],n.channels,[0,1,2]);break;case he.LCH:case he.OKLCH:n.channels=carryForwardMissingComponents(e.channels,[0],n.channels,[0])}break;case he.LCH:case he.OKLCH:switch(e.colorNotation){case he.HSL:n.channels=carryForwardMissingComponents(e.channels,[0,1,2],n.channels,[2,1,0]);break;case he.HWB:n.channels=carryForwardMissingComponents(e.channels,[0],n.channels,[2]);break;case he.Lab:case he.OKLab:n.channels=carryForwardMissingComponents(e.channels,[0],n.channels,[0]);break;case he.LCH:case he.OKLCH:n.channels=carryForwardMissingComponents(e.channels,[0,1,2],n.channels,[0,1,2])}}return n.channels=convertPowerlessComponentsToMissingComponents(n.channels,a),n}function convertPowerlessComponentsToMissingComponents(e,a){const n=[...e];switch(a){case he.HSL:!Number.isNaN(n[1])&&reducePrecision(n[1],4)<=0&&(n[0]=Number.NaN);break;case he.HWB:Math.max(0,reducePrecision(n[1],4))+Math.max(0,reducePrecision(n[2],4))>=100&&(n[0]=Number.NaN);break;case he.LCH:!Number.isNaN(n[1])&&reducePrecision(n[1],4)<=0&&(n[2]=Number.NaN);break;case he.OKLCH:!Number.isNaN(n[1])&&reducePrecision(n[1],6)<=0&&(n[2]=Number.NaN)}return n}function convertPowerlessComponentsToZeroValuesForDisplay(e,a){const n=[...e];switch(a){case he.HSL:(reducePrecision(n[2])<=0||reducePrecision(n[2])>=100)&&(n[0]=Number.NaN,n[1]=Number.NaN),reducePrecision(n[1])<=0&&(n[0]=Number.NaN);break;case he.HWB:Math.max(0,reducePrecision(n[1]))+Math.max(0,reducePrecision(n[2]))>=100&&(n[0]=Number.NaN);break;case he.Lab:(reducePrecision(n[0])<=0||reducePrecision(n[0])>=100)&&(n[1]=Number.NaN,n[2]=Number.NaN);break;case he.LCH:reducePrecision(n[1])<=0&&(n[2]=Number.NaN),(reducePrecision(n[0])<=0||reducePrecision(n[0])>=100)&&(n[1]=Number.NaN,n[2]=Number.NaN);break;case he.OKLab:(reducePrecision(n[0])<=0||reducePrecision(n[0])>=1)&&(n[1]=Number.NaN,n[2]=Number.NaN);break;case he.OKLCH:reducePrecision(n[1])<=0&&(n[2]=Number.NaN),(reducePrecision(n[0])<=0||reducePrecision(n[0])>=1)&&(n[1]=Number.NaN,n[2]=Number.NaN)}return n}function carryForwardMissingComponents(e,a,n,r){const o=[...n];for(const n of a)Number.isNaN(e[a[n]])&&(o[r[n]]=Number.NaN);return o}function normalizeRelativeColorDataChannels(e){const a=new Map;switch(e.colorNotation){case he.RGB:case he.HEX:a.set("r",dummyNumberToken(255*e.channels[0])),a.set("g",dummyNumberToken(255*e.channels[1])),a.set("b",dummyNumberToken(255*e.channels[2])),"number"==typeof e.alpha&&a.set("alpha",dummyNumberToken(e.alpha));break;case he.HSL:a.set("h",dummyNumberToken(e.channels[0])),a.set("s",dummyNumberToken(e.channels[1])),a.set("l",dummyNumberToken(e.channels[2])),"number"==typeof e.alpha&&a.set("alpha",dummyNumberToken(e.alpha));break;case he.HWB:a.set("h",dummyNumberToken(e.channels[0])),a.set("w",dummyNumberToken(e.channels[1])),a.set("b",dummyNumberToken(e.channels[2])),"number"==typeof e.alpha&&a.set("alpha",dummyNumberToken(e.alpha));break;case he.Lab:case he.OKLab:a.set("l",dummyNumberToken(e.channels[0])),a.set("a",dummyNumberToken(e.channels[1])),a.set("b",dummyNumberToken(e.channels[2])),"number"==typeof e.alpha&&a.set("alpha",dummyNumberToken(e.alpha));break;case he.LCH:case he.OKLCH:a.set("l",dummyNumberToken(e.channels[0])),a.set("c",dummyNumberToken(e.channels[1])),a.set("h",dummyNumberToken(e.channels[2])),"number"==typeof e.alpha&&a.set("alpha",dummyNumberToken(e.alpha));break;case he.sRGB:case he.A98_RGB:case he.Display_P3:case he.Linear_Display_P3:case he.Rec2020:case he.Linear_sRGB:case he.ProPhoto_RGB:a.set("r",dummyNumberToken(e.channels[0])),a.set("g",dummyNumberToken(e.channels[1])),a.set("b",dummyNumberToken(e.channels[2])),"number"==typeof e.alpha&&a.set("alpha",dummyNumberToken(e.alpha));break;case he.XYZ_D50:case he.XYZ_D65:a.set("x",dummyNumberToken(e.channels[0])),a.set("y",dummyNumberToken(e.channels[1])),a.set("z",dummyNumberToken(e.channels[2])),"number"==typeof e.alpha&&a.set("alpha",dummyNumberToken(e.alpha))}return a}function noneToZeroInRelativeColorDataChannels(e){const a=new Map(e);for(const[n,r]of e)Number.isNaN(r[4].value)&&a.set(n,dummyNumberToken(0));return a}function dummyNumberToken(n){return Number.isNaN(n)?[e.Number,"none",-1,-1,{value:Number.NaN,type:a.Number}]:[e.Number,n.toString(),-1,-1,{value:n,type:a.Number}]}function reducePrecision(e,a=7){if(Number.isNaN(e))return 0;const n=Math.pow(10,a);return Math.round(e*n)/n}function colorDataFitsRGB_Gamut(e){const a={...e,channels:[...e.channels]};a.channels=convertPowerlessComponentsToZeroValuesForDisplay(a.channels,a.colorNotation);return!colorDataTo(a,he.RGB).channels.find(e=>e<-1e-5||e>1.00001)}function colorDataFitsDisplayP3_Gamut(e){const a={...e,channels:[...e.channels]};a.channels=convertPowerlessComponentsToZeroValuesForDisplay(a.channels,a.colorNotation);return!colorDataTo(a,he.Display_P3).channels.find(e=>e<-1e-5||e>1.00001)}function normalize(e,a,n,r){return Math.min(Math.max(e/a,n),r)}const Ne=/[A-Z]/g;function toLowerCaseAZ(e){return e.replace(Ne,e=>String.fromCharCode(e.charCodeAt(0)+32))}function normalize_Color_ChannelValues(t,l,s){if(n(t)&&"none"===toLowerCaseAZ(t[4].value))return s.syntaxFlags.add(me.HasNoneKeywords),[e.Number,"none",t[2],t[3],{value:Number.NaN,type:a.Number}];if(r(t)){3!==l&&s.syntaxFlags.add(me.HasPercentageValues);let n=normalize(t[4].value,100,-2147483647,2147483647);return 3===l&&(n=normalize(t[4].value,100,0,1)),[e.Number,n.toString(),t[2],t[3],{value:n,type:a.Number}]}if(o(t)){3!==l&&s.syntaxFlags.add(me.HasNumberValues);let n=normalize(t[4].value,1,-2147483647,2147483647);return 3===l&&(n=normalize(t[4].value,1,0,1)),[e.Number,n.toString(),t[2],t[3],{value:n,type:a.Number}]}return!1}const be=new Set(["srgb","srgb-linear","display-p3","display-p3-linear","a98-rgb","prophoto-rgb","rec2020","xyz","xyz-d50","xyz-d65"]);function color$1(e,a){const r=[],s=[],u=[],i=[];let c,h,m=!1,p=!1;const N={colorNotation:he.sRGB,channels:[0,0,0],alpha:1,syntaxFlags:new Set([])};let b=r;for(let o=0;o=0){u=i.value[4].value;continue}}return!1}if(!t)return!1;n.push({color:t,percentage:u}),t=!1,u=!1}}if(!t)return!1;n.push({color:t,percentage:u});let i=0,c=0;for(let e=0;e100)return!1;i+=a}else c++}const h=Math.max(0,100-i);i=0;for(let e=0;e100)for(let e=0;e=2;){const e=n.pop(),a=n.pop();if(!e||!a)return!1;const o=colorMixRectangularPair(r,e.color,e.percentage,a.color,a.percentage);if(!o)return!1;n.push({color:o,percentage:e.percentage+a.percentage})}const o=n[0]?.color;return!!o&&(a.colors.some(e=>e.color.syntaxFlags.has(me.Experimental))&&o.syntaxFlags.add(me.Experimental),"number"==typeof o.alpha&&(o.alpha=o.alpha*a.alphaMultiplier,2!==a.colors.length&&o.syntaxFlags.add(me.ColorMixVariadic),o))}function colorMixRectangularPair(e,a,n,r,o){const t=n/(n+o);let l=a.alpha;if("number"!=typeof l)return!1;let s=r.alpha;if("number"!=typeof s)return!1;l=Number.isNaN(l)?s:l,s=Number.isNaN(s)?l:s;const u=colorDataTo(a,e).channels,i=colorDataTo(r,e).channels;u[0]=fillInMissingComponent(u[0],i[0]),i[0]=fillInMissingComponent(i[0],u[0]),u[1]=fillInMissingComponent(u[1],i[1]),i[1]=fillInMissingComponent(i[1],u[1]),u[2]=fillInMissingComponent(u[2],i[2]),i[2]=fillInMissingComponent(i[2],u[2]),u[0]=premultiply(u[0],l),u[1]=premultiply(u[1],l),u[2]=premultiply(u[2],l),i[0]=premultiply(i[0],s),i[1]=premultiply(i[1],s),i[2]=premultiply(i[2],s);const c=interpolate(l,s,t);return{colorNotation:e,channels:[un_premultiply(interpolate(u[0],i[0],t),c),un_premultiply(interpolate(u[1],i[1],t),c),un_premultiply(interpolate(u[2],i[2],t),c)],alpha:c,syntaxFlags:new Set([me.ColorMix])}}function colorMixPolar(e,a,n){if(!n||!n.colors.length)return!1;const r=n.colors.slice();let o;switch(r.reverse(),e){case"hsl":o=he.HSL;break;case"hwb":o=he.HWB;break;case"lch":o=he.LCH;break;case"oklch":o=he.OKLCH;break;default:return!1}if(1===r.length){const e=colorDataTo(r[0].color,o);return e.colorNotation=o,e.syntaxFlags.add(me.ColorMixVariadic),"number"!=typeof e.alpha?!1:(e.alpha=e.alpha*n.alphaMultiplier,e)}for(;r.length>=2;){const e=r.pop(),n=r.pop();if(!e||!n)return!1;const t=colorMixPolarPair(o,a,e.color,e.percentage,n.color,n.percentage);if(!t)return!1;r.push({color:t,percentage:e.percentage+n.percentage})}const t=r[0]?.color;return!!t&&(n.colors.some(e=>e.color.syntaxFlags.has(me.Experimental))&&t.syntaxFlags.add(me.Experimental),"number"==typeof t.alpha&&(t.alpha=t.alpha*n.alphaMultiplier,2!==n.colors.length&&t.syntaxFlags.add(me.ColorMixVariadic),t))}function colorMixPolarPair(e,a,n,r,o,t){const l=r/(r+t);let s=0,u=0,i=0,c=0,h=0,m=0,p=n.alpha;if("number"!=typeof p)return!1;let N=o.alpha;if("number"!=typeof N)return!1;p=Number.isNaN(p)?N:p,N=Number.isNaN(N)?p:N;const b=colorDataTo(n,e).channels,v=colorDataTo(o,e).channels;switch(e){case he.HSL:case he.HWB:s=b[0],u=v[0],i=b[1],c=v[1],h=b[2],m=v[2];break;case he.LCH:case he.OKLCH:i=b[0],c=v[0],h=b[1],m=v[1],s=b[2],u=v[2]}s=fillInMissingComponent(s,u),Number.isNaN(s)&&(s=0),u=fillInMissingComponent(u,s),Number.isNaN(u)&&(u=0),i=fillInMissingComponent(i,c),c=fillInMissingComponent(c,i),h=fillInMissingComponent(h,m),m=fillInMissingComponent(m,h);const g=u-s;switch(a){case"shorter":g>180?s+=360:g<-180&&(u+=360);break;case"longer":-1800?s+=360:u+=360);break;case"increasing":g<0&&(u+=360);break;case"decreasing":g>0&&(s+=360);break;default:throw new Error("Unknown hue interpolation method")}i=premultiply(i,p),h=premultiply(h,p),c=premultiply(c,N),m=premultiply(m,N);let f=[0,0,0];const d=interpolate(p,N,l);switch(e){case he.HSL:case he.HWB:f=[interpolate(s,u,l),un_premultiply(interpolate(i,c,l),d),un_premultiply(interpolate(h,m,l),d)];break;case he.LCH:case he.OKLCH:f=[un_premultiply(interpolate(i,c,l),d),un_premultiply(interpolate(h,m,l),d),interpolate(s,u,l)]}return{colorNotation:e,channels:f,alpha:d,syntaxFlags:new Set([me.ColorMix])}}function fillInMissingComponent(e,a){return Number.isNaN(e)?a:e}function interpolate(e,a,n){return e*n+a*(1-n)}function premultiply(e,a){return Number.isNaN(a)?e:Number.isNaN(e)?Number.NaN:e*a}function un_premultiply(e,a){return 0===a||Number.isNaN(a)?e:Number.isNaN(e)?Number.NaN:e/a}function hex(e){const a=toLowerCaseAZ(e[4].value);if(a.match(/[^a-f0-9]/))return!1;const n={colorNotation:he.HEX,channels:[0,0,0],alpha:1,syntaxFlags:new Set([me.Hex])},r=a.length;if(3===r){const e=a[0],r=a[1],o=a[2];return n.channels=[parseInt(e+e,16)/255,parseInt(r+r,16)/255,parseInt(o+o,16)/255],n}if(6===r){const e=a[0]+a[1],r=a[2]+a[3],o=a[4]+a[5];return n.channels=[parseInt(e,16)/255,parseInt(r,16)/255,parseInt(o,16)/255],n}if(4===r){const e=a[0],r=a[1],o=a[2],t=a[3];return n.channels=[parseInt(e+e,16)/255,parseInt(r+r,16)/255,parseInt(o+o,16)/255],n.alpha=parseInt(t+t,16)/255,n.syntaxFlags.add(me.HasAlpha),n}if(8===r){const e=a[0]+a[1],r=a[2]+a[3],o=a[4]+a[5],t=a[6]+a[7];return n.channels=[parseInt(e,16)/255,parseInt(r,16)/255,parseInt(o,16)/255],n.alpha=parseInt(t,16)/255,n.syntaxFlags.add(me.HasAlpha),n}return!1}function normalizeHue(n){if(o(n))return n[4].value=n[4].value%360,n[1]=n[4].value.toString(),n;if(u(n)){let r=n[4].value;switch(toLowerCaseAZ(n[4].unit)){case"deg":break;case"rad":r=180*n[4].value/Math.PI;break;case"grad":r=.9*n[4].value;break;case"turn":r=360*n[4].value;break;default:return!1}return r%=360,[e.Number,r.toString(),n[2],n[3],{value:r,type:a.Number}]}return!1}function normalize_legacy_HSL_ChannelValues(n,t,l){if(0===t){const e=normalizeHue(n);return!1!==e&&(u(n)&&l.syntaxFlags.add(me.HasDimensionValues),e)}if(r(n)){3===t?l.syntaxFlags.add(me.HasPercentageAlpha):l.syntaxFlags.add(me.HasPercentageValues);let r=normalize(n[4].value,1,0,100);return 3===t&&(r=normalize(n[4].value,100,0,1)),[e.Number,r.toString(),n[2],n[3],{value:r,type:a.Number}]}if(o(n)){if(3!==t)return!1;let r=normalize(n[4].value,1,0,100);return 3===t&&(r=normalize(n[4].value,1,0,1)),[e.Number,r.toString(),n[2],n[3],{value:r,type:a.Number}]}return!1}function normalize_modern_HSL_ChannelValues(t,l,s){if(n(t)&&"none"===toLowerCaseAZ(t[4].value))return s.syntaxFlags.add(me.HasNoneKeywords),[e.Number,"none",t[2],t[3],{value:Number.NaN,type:a.Number}];if(0===l){const e=normalizeHue(t);return!1!==e&&(u(t)&&s.syntaxFlags.add(me.HasDimensionValues),e)}if(r(t)){3===l?s.syntaxFlags.add(me.HasPercentageAlpha):s.syntaxFlags.add(me.HasPercentageValues);let n=t[4].value;return 3===l?n=normalize(t[4].value,100,0,1):1===l&&(n=normalize(t[4].value,1,0,2147483647)),[e.Number,n.toString(),t[2],t[3],{value:n,type:a.Number}]}if(o(t)){3!==l&&s.syntaxFlags.add(me.HasNumberValues);let n=t[4].value;return 3===l?n=normalize(t[4].value,1,0,1):1===l&&(n=normalize(t[4].value,1,0,2147483647)),[e.Number,n.toString(),t[2],t[3],{value:n,type:a.Number}]}return!1}function threeChannelLegacySyntax(e,a,n,r){const t=[],u=[],i=[],c=[],h={colorNotation:n,channels:[0,0,0],alpha:1,syntaxFlags:new Set(r)};let m=t;for(let a=0;ane(e)&&s(e.value))){const a=hslCommaSeparated(e);if(!1!==a)return a}{const n=hslSpaceSeparated(e,a);if(!1!==n)return n}return!1}function hslCommaSeparated(e){return threeChannelLegacySyntax(e,normalize_legacy_HSL_ChannelValues,he.HSL,[me.LegacyHSL])}function hslSpaceSeparated(e,a){return threeChannelSpaceSeparated(e,normalize_modern_HSL_ChannelValues,he.HSL,[],a)}function normalize_HWB_ChannelValues(t,l,s){if(n(t)&&"none"===toLowerCaseAZ(t[4].value))return s.syntaxFlags.add(me.HasNoneKeywords),[e.Number,"none",t[2],t[3],{value:Number.NaN,type:a.Number}];if(0===l){const e=normalizeHue(t);return!1!==e&&(u(t)&&s.syntaxFlags.add(me.HasDimensionValues),e)}if(r(t)){3===l?s.syntaxFlags.add(me.HasPercentageAlpha):s.syntaxFlags.add(me.HasPercentageValues);let n=t[4].value;return 3===l&&(n=normalize(t[4].value,100,0,1)),[e.Number,n.toString(),t[2],t[3],{value:n,type:a.Number}]}if(o(t)){3!==l&&s.syntaxFlags.add(me.HasNumberValues);let n=t[4].value;return 3===l&&(n=normalize(t[4].value,1,0,1)),[e.Number,n.toString(),t[2],t[3],{value:n,type:a.Number}]}return!1}function normalize_Lab_ChannelValues(t,l,s){if(n(t)&&"none"===toLowerCaseAZ(t[4].value))return s.syntaxFlags.add(me.HasNoneKeywords),[e.Number,"none",t[2],t[3],{value:Number.NaN,type:a.Number}];if(r(t)){3!==l&&s.syntaxFlags.add(me.HasPercentageValues);let n=normalize(t[4].value,1,0,100);return 1===l||2===l?n=normalize(t[4].value,.8,-2147483647,2147483647):3===l&&(n=normalize(t[4].value,100,0,1)),[e.Number,n.toString(),t[2],t[3],{value:n,type:a.Number}]}if(o(t)){3!==l&&s.syntaxFlags.add(me.HasNumberValues);let n=normalize(t[4].value,1,0,100);return 1===l||2===l?n=normalize(t[4].value,1,-2147483647,2147483647):3===l&&(n=normalize(t[4].value,1,0,1)),[e.Number,n.toString(),t[2],t[3],{value:n,type:a.Number}]}return!1}function lab(e,a){return threeChannelSpaceSeparated(e,normalize_Lab_ChannelValues,he.Lab,[],a)}function normalize_LCH_ChannelValues(t,l,s){if(n(t)&&"none"===toLowerCaseAZ(t[4].value))return s.syntaxFlags.add(me.HasNoneKeywords),[e.Number,"none",t[2],t[3],{value:Number.NaN,type:a.Number}];if(2===l){const e=normalizeHue(t);return!1!==e&&(u(t)&&s.syntaxFlags.add(me.HasDimensionValues),e)}if(r(t)){3!==l&&s.syntaxFlags.add(me.HasPercentageValues);let n=normalize(t[4].value,1,0,100);return 1===l?n=normalize(t[4].value,100/150,0,2147483647):3===l&&(n=normalize(t[4].value,100,0,1)),[e.Number,n.toString(),t[2],t[3],{value:n,type:a.Number}]}if(o(t)){3!==l&&s.syntaxFlags.add(me.HasNumberValues);let n=normalize(t[4].value,1,0,100);return 1===l?n=normalize(t[4].value,1,0,2147483647):3===l&&(n=normalize(t[4].value,1,0,1)),[e.Number,n.toString(),t[2],t[3],{value:n,type:a.Number}]}return!1}function lch(e,a){return threeChannelSpaceSeparated(e,normalize_LCH_ChannelValues,he.LCH,[],a)}const de=new Map;for(const[e,a]of Object.entries(G))de.set(e,a);function namedColor(e){const a=de.get(toLowerCaseAZ(e));return!!a&&{colorNotation:he.RGB,channels:[a[0]/255,a[1]/255,a[2]/255],alpha:1,syntaxFlags:new Set([me.ColorKeyword,me.NamedColor])}}function normalize_OKLab_ChannelValues(t,l,s){if(n(t)&&"none"===toLowerCaseAZ(t[4].value))return s.syntaxFlags.add(me.HasNoneKeywords),[e.Number,"none",t[2],t[3],{value:Number.NaN,type:a.Number}];if(r(t)){3!==l&&s.syntaxFlags.add(me.HasPercentageValues);let n=normalize(t[4].value,100,0,1);return 1===l||2===l?n=normalize(t[4].value,250,-2147483647,2147483647):3===l&&(n=normalize(t[4].value,100,0,1)),[e.Number,n.toString(),t[2],t[3],{value:n,type:a.Number}]}if(o(t)){3!==l&&s.syntaxFlags.add(me.HasNumberValues);let n=normalize(t[4].value,1,0,1);return 1===l||2===l?n=normalize(t[4].value,1,-2147483647,2147483647):3===l&&(n=normalize(t[4].value,1,0,1)),[e.Number,n.toString(),t[2],t[3],{value:n,type:a.Number}]}return!1}function oklab(e,a){return threeChannelSpaceSeparated(e,normalize_OKLab_ChannelValues,he.OKLab,[],a)}function normalize_OKLCH_ChannelValues(t,l,s){if(n(t)&&"none"===toLowerCaseAZ(t[4].value))return s.syntaxFlags.add(me.HasNoneKeywords),[e.Number,"none",t[2],t[3],{value:Number.NaN,type:a.Number}];if(2===l){const e=normalizeHue(t);return!1!==e&&(u(t)&&s.syntaxFlags.add(me.HasDimensionValues),e)}if(r(t)){3!==l&&s.syntaxFlags.add(me.HasPercentageValues);let n=normalize(t[4].value,100,0,1);return 1===l?n=normalize(t[4].value,250,0,2147483647):3===l&&(n=normalize(t[4].value,100,0,1)),[e.Number,n.toString(),t[2],t[3],{value:n,type:a.Number}]}if(o(t)){3!==l&&s.syntaxFlags.add(me.HasNumberValues);let n=normalize(t[4].value,1,0,1);return 1===l?n=normalize(t[4].value,1,0,2147483647):3===l&&(n=normalize(t[4].value,1,0,1)),[e.Number,n.toString(),t[2],t[3],{value:n,type:a.Number}]}return!1}function oklch(e,a){return threeChannelSpaceSeparated(e,normalize_OKLCH_ChannelValues,he.OKLCH,[],a)}function normalize_legacy_sRGB_ChannelValues(n,t,l){if(r(n)){3===t?l.syntaxFlags.add(me.HasPercentageAlpha):l.syntaxFlags.add(me.HasPercentageValues);const r=normalize(n[4].value,100,0,1);return[e.Number,r.toString(),n[2],n[3],{value:r,type:a.Number}]}if(o(n)){3!==t&&l.syntaxFlags.add(me.HasNumberValues);let r=normalize(n[4].value,255,0,1);return 3===t&&(r=normalize(n[4].value,1,0,1)),[e.Number,r.toString(),n[2],n[3],{value:r,type:a.Number}]}return!1}function normalize_modern_sRGB_ChannelValues(t,l,s){if(n(t)&&"none"===t[4].value.toLowerCase())return s.syntaxFlags.add(me.HasNoneKeywords),[e.Number,"none",t[2],t[3],{value:Number.NaN,type:a.Number}];if(r(t)){3!==l&&s.syntaxFlags.add(me.HasPercentageValues);let n=normalize(t[4].value,100,-2147483647,2147483647);return 3===l&&(n=normalize(t[4].value,100,0,1)),[e.Number,n.toString(),t[2],t[3],{value:n,type:a.Number}]}if(o(t)){3!==l&&s.syntaxFlags.add(me.HasNumberValues);let n=normalize(t[4].value,255,-2147483647,2147483647);return 3===l&&(n=normalize(t[4].value,1,0,1)),[e.Number,n.toString(),t[2],t[3],{value:n,type:a.Number}]}return!1}function rgb(e,a){if(e.value.some(e=>ne(e)&&s(e.value))){const a=rgbCommaSeparated(e);if(!1!==a)return(!a.syntaxFlags.has(me.HasNumberValues)||!a.syntaxFlags.has(me.HasPercentageValues))&&a}else{const n=rgbSpaceSeparated(e,a);if(!1!==n)return n}return!1}function rgbCommaSeparated(e){return threeChannelLegacySyntax(e,normalize_legacy_sRGB_ChannelValues,he.RGB,[me.LegacyRGB])}function rgbSpaceSeparated(e,a){return threeChannelSpaceSeparated(e,normalize_modern_sRGB_ChannelValues,he.RGB,[],a)}function XYZ_D50_to_sRGB_Gamut(e){const a=x(e);if(A(a))return X(a);let n=e;return n=p(n),n[0]<1e-6&&(n=[0,0,0]),n[0]>.999999&&(n=[1,0,0]),K(Y(n,oklch_to_lin_srgb,lin_srgb_to_oklch))}function oklch_to_lin_srgb(e){return e=I(e),e=O(e),W(e)}function lin_srgb_to_oklch(e){return e=E(e),e=U(e),$(e)}function contrastColor(e,a){let n=!1;for(let r=0;rt?[1,1,1]:[0,0,0],r}function alpha(e,a){let r,s,u=!1,i=!1,c=!1;const h={colorNotation:he.sRGB,channels:[0,0,0],alpha:1,syntaxFlags:new Set([])};for(let m=0;m{if(ne(e)&&n(e.value)&&"alpha"===toLowerCaseAZ(e.value[4].value)&&r&&r.has("alpha"))return new oe(r.get("alpha"))});h.alpha=e[0][0],i=!0;continue}return!1}if(c)return!1;for(;ee(e.value[m+1])||ae(e.value[m+1]);)m++;if(m++,p=e.value[m],c=a(p),!1===c)return!1;r=normalizeRelativeColorDataChannels(c),s=noneToZeroInRelativeColorDataChannels(r),h.syntaxFlags=new Set(c.syntaxFlags),h.syntaxFlags.add(me.RelativeAlphaSyntax),h.channels=[...c.channels],h.colorNotation=c.colorNotation,h.alpha=c.alpha}}return!!r&&h}function XYZ_D50_to_P3_Gamut(e){const a=C(e);if(A(a))return X(a);let n=e;return n=p(n),n[0]<1e-6&&(n=[0,0,0]),n[0]>.999999&&(n=[1,0,0]),q(Y(n,oklch_to_lin_p3,lin_p3_to_oklch))}function oklch_to_lin_p3(e){return e=I(e),e=O(e),J(e)}function lin_p3_to_oklch(e){return e=Q(e),e=U(e),$(e)}function toPrecision(e,a=7){e=+e,a=+a;const n=(Math.floor(Math.abs(e))+"").length;if(a>n)return+e.toFixed(a-n);{const r=10**(n-a);return Math.round(e/r)*r}}function serializeWithAlpha(n,r,o,t){const l=[e.CloseParen,")",-1,-1,void 0];if("number"==typeof n.alpha){const s=Math.min(1,Math.max(0,toPrecision(Number.isNaN(n.alpha)?0:n.alpha)));return 1===toPrecision(s,4)?new se(r,l,t):new se(r,l,[...t,new ue([o]),new oe([e.Delim,"/",-1,-1,{value:"/"}]),new ue([o]),new oe([e.Number,toPrecision(s,4).toString(),-1,-1,{value:n.alpha,type:a.Integer}])])}return new se(r,l,[...t,new ue([o]),new oe([e.Delim,"/",-1,-1,{value:"/"}]),new ue([o]),n.alpha])}function serializeP3(n,r=!0){n.channels=convertPowerlessComponentsToZeroValuesForDisplay(n.channels,n.colorNotation);let o=n.channels.map(e=>Number.isNaN(e)?0:e);r?o=XYZ_D50_to_P3_Gamut(colorData_to_XYZ_D50(n).channels):n.colorNotation!==he.Display_P3&&(o=C(colorData_to_XYZ_D50(n).channels));const t=r?Math.min(1,Math.max(0,toPrecision(o[0],6))):toPrecision(o[0],6),l=r?Math.min(1,Math.max(0,toPrecision(o[1],6))):toPrecision(o[1],6),s=r?Math.min(1,Math.max(0,toPrecision(o[2],6))):toPrecision(o[2],6),u=[e.Function,"color(",-1,-1,{value:"color"}],i=[e.Whitespace," ",-1,-1,void 0];return serializeWithAlpha(n,u,i,[new oe([e.Ident,"display-p3",-1,-1,{value:"display-p3"}]),new ue([i]),new oe([e.Number,t.toString(),-1,-1,{value:o[0],type:a.Number}]),new ue([i]),new oe([e.Number,l.toString(),-1,-1,{value:o[1],type:a.Number}]),new ue([i]),new oe([e.Number,s.toString(),-1,-1,{value:o[2],type:a.Number}])])}function serializeRGB(n,r=!0){let o;n.channels=convertPowerlessComponentsToZeroValuesForDisplay(n.channels,n.colorNotation),o=r?XYZ_D50_to_sRGB_Gamut(colorData_to_XYZ_D50(n).channels):x(colorData_to_XYZ_D50(n).channels);const t=Math.min(255,Math.max(0,Math.round(255*toPrecision(o[0])))),l=Math.min(255,Math.max(0,Math.round(255*toPrecision(o[1])))),s=Math.min(255,Math.max(0,Math.round(255*toPrecision(o[2])))),u=[e.CloseParen,")",-1,-1,void 0],i=[e.Whitespace," ",-1,-1,void 0],c=[e.Comma,",",-1,-1,void 0],h=[new oe([e.Number,t.toString(),-1,-1,{value:Math.min(255,255*Math.max(0,o[0])),type:a.Integer}]),new oe(c),new ue([i]),new oe([e.Number,l.toString(),-1,-1,{value:Math.min(255,255*Math.max(0,o[1])),type:a.Integer}]),new oe(c),new ue([i]),new oe([e.Number,s.toString(),-1,-1,{value:Math.min(255,255*Math.max(0,o[2])),type:a.Integer}])];if("number"==typeof n.alpha){const r=Math.min(1,Math.max(0,toPrecision(Number.isNaN(n.alpha)?0:n.alpha)));return 1===toPrecision(r,4)?new se([e.Function,"rgb(",-1,-1,{value:"rgb"}],u,h):new se([e.Function,"rgba(",-1,-1,{value:"rgba"}],u,[...h,new oe(c),new ue([i]),new oe([e.Number,toPrecision(r,4).toString(),-1,-1,{value:n.alpha,type:a.Number}])])}return new se([e.Function,"rgba(",-1,-1,{value:"rgba"}],u,[...h,new oe(c),new ue([i]),n.alpha])}function serializeHSL(n,r=!0){let o;n.channels=convertPowerlessComponentsToZeroValuesForDisplay(n.channels,n.colorNotation),o=g(r?T(XYZ_D50_to_sRGB_Gamut(colorData_to_XYZ_D50(n).channels)):colorData_to_XYZ_D50(n).channels),o=o.map(e=>Number.isNaN(e)?0:e);const t=Math.min(360,Math.max(0,Math.round(toPrecision(o[0])))),l=Math.min(100,Math.max(0,Math.round(toPrecision(o[1])))),s=Math.min(100,Math.max(0,Math.round(toPrecision(o[2])))),u=[e.CloseParen,")",-1,-1,void 0],i=[e.Whitespace," ",-1,-1,void 0],c=[e.Comma,",",-1,-1,void 0],h=[new oe([e.Number,t.toString(),-1,-1,{value:o[0],type:a.Integer}]),new oe(c),new ue([i]),new oe([e.Percentage,l.toString()+"%",-1,-1,{value:o[1]}]),new oe(c),new ue([i]),new oe([e.Percentage,s.toString()+"%",-1,-1,{value:o[2]}])];if("number"==typeof n.alpha){const r=Math.min(1,Math.max(0,toPrecision(Number.isNaN(n.alpha)?0:n.alpha)));return 1===toPrecision(r,4)?new se([e.Function,"hsl(",-1,-1,{value:"hsl"}],u,h):new se([e.Function,"hsla(",-1,-1,{value:"hsla"}],u,[...h,new oe(c),new ue([i]),new oe([e.Number,toPrecision(r,4).toString(),-1,-1,{value:n.alpha,type:a.Number}])])}return new se([e.Function,"hsla(",-1,-1,{value:"hsla"}],u,[...h,new oe(c),new ue([i]),n.alpha])}function serializeOKLCH(n){n.channels=convertPowerlessComponentsToZeroValuesForDisplay(n.channels,n.colorNotation);let r=n.channels.map(e=>Number.isNaN(e)?0:e);n.colorNotation!==he.OKLCH&&(r=p(colorData_to_XYZ_D50(n).channels));const o=toPrecision(r[0],6),t=toPrecision(r[1],6),l=toPrecision(r[2],6),s=[e.Function,"oklch(",-1,-1,{value:"oklch"}],u=[e.Whitespace," ",-1,-1,void 0];return serializeWithAlpha(n,s,u,[new oe([e.Number,o.toString(),-1,-1,{value:r[0],type:a.Number}]),new ue([u]),new oe([e.Number,t.toString(),-1,-1,{value:r[1],type:a.Number}]),new ue([u]),new oe([e.Number,l.toString(),-1,-1,{value:r[2],type:a.Number}])])}function color(e){if(re(e)){switch(toLowerCaseAZ(e.getName())){case"rgb":case"rgba":return rgb(e,color);case"hsl":case"hsla":return hsl(e,color);case"hwb":return a=color,threeChannelSpaceSeparated(e,normalize_HWB_ChannelValues,he.HWB,[],a);case"lab":return lab(e,color);case"lch":return lch(e,color);case"oklab":return oklab(e,color);case"oklch":return oklch(e,color);case"color":return color$1(e,color);case"color-mix":return colorMix(e,color);case"contrast-color":return contrastColor(e,color);case"alpha":return alpha(e,color)}}var a;if(ne(e)){if(i(e.value))return hex(e.value);if(n(e.value)){const a=namedColor(e.value[4].value);return!1!==a?a:"transparent"===toLowerCaseAZ(e.value[4].value)&&{colorNotation:he.RGB,channels:[0,0,0],alpha:0,syntaxFlags:new Set([me.ColorKeyword])}}}return!1}export{he as ColorNotation,me as SyntaxFlag,color,colorDataFitsDisplayP3_Gamut,colorDataFitsRGB_Gamut,serializeHSL,serializeOKLCH,serializeP3,serializeRGB}; diff --git a/node_modules/@csstools/css-color-parser/package.json b/node_modules/@csstools/css-color-parser/package.json new file mode 100644 index 00000000..7e5efdff --- /dev/null +++ b/node_modules/@csstools/css-color-parser/package.json @@ -0,0 +1,64 @@ +{ + "name": "@csstools/css-color-parser", + "description": "Parse CSS color values", + "version": "4.0.2", + "contributors": [ + { + "name": "Antonio Laguna", + "email": "antonio@laguna.es", + "url": "https://antonio.laguna.es" + }, + { + "name": "Romain Menke", + "email": "romainmenke@gmail.com" + } + ], + "license": "MIT", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "engines": { + "node": ">=20.19.0" + }, + "type": "module", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + } + }, + "files": [ + "CHANGELOG.md", + "LICENSE.md", + "README.md", + "dist" + ], + "dependencies": { + "@csstools/color-helpers": "^6.0.2", + "@csstools/css-calc": "^3.1.1" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^4.0.0", + "@csstools/css-tokenizer": "^4.0.0" + }, + "scripts": {}, + "homepage": "https://github.com/csstools/postcss-plugins/tree/main/packages/css-color-parser#readme", + "repository": { + "type": "git", + "url": "git+https://github.com/csstools/postcss-plugins.git", + "directory": "packages/css-color-parser" + }, + "bugs": "https://github.com/csstools/postcss-plugins/issues", + "keywords": [ + "color", + "css", + "parser" + ] +} diff --git a/node_modules/@csstools/css-parser-algorithms/CHANGELOG.md b/node_modules/@csstools/css-parser-algorithms/CHANGELOG.md new file mode 100644 index 00000000..5abd5908 --- /dev/null +++ b/node_modules/@csstools/css-parser-algorithms/CHANGELOG.md @@ -0,0 +1,11 @@ +# Changes to CSS Parser Algorithms + +### 4.0.0 + +_January 14, 2026_ + +- Updated: Support for Node `20.19.0` or later (major). +- Removed: `commonjs` API. In supported Node versions `require(esm)` will work without needing to make code changes. +- Updated [`@csstools/css-tokenizer`](https://github.com/csstools/postcss-plugins/tree/main/packages/css-tokenizer) to [`4.0.0`](https://github.com/csstools/postcss-plugins/tree/main/packages/css-tokenizer/CHANGELOG.md#400) (major) + +[Full CHANGELOG](https://github.com/csstools/postcss-plugins/tree/main/packages/css-parser-algorithms/CHANGELOG.md) diff --git a/node_modules/@csstools/css-parser-algorithms/LICENSE.md b/node_modules/@csstools/css-parser-algorithms/LICENSE.md new file mode 100644 index 00000000..af5411fa --- /dev/null +++ b/node_modules/@csstools/css-parser-algorithms/LICENSE.md @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright 2022 Romain Menke, Antonio Laguna + +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. diff --git a/node_modules/@csstools/css-parser-algorithms/README.md b/node_modules/@csstools/css-parser-algorithms/README.md new file mode 100644 index 00000000..a51d6687 --- /dev/null +++ b/node_modules/@csstools/css-parser-algorithms/README.md @@ -0,0 +1,119 @@ +# CSS Parser Algorithms for CSS + +[npm version][npm-url] +[Build Status][cli-url] +[Discord][discord] + +Implemented from : https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/ + +## API + +[Read the API docs](./docs/css-parser-algorithms.md) + +## Usage + +Add [CSS Parser Algorithms] to your project: + +```bash +npm install @csstools/css-parser-algorithms @csstools/css-tokenizer --save-dev +``` + +[CSS Parser Algorithms] only accepts tokenized CSS. +It must be used together with `@csstools/css-tokenizer`. + + +```js +import { tokenizer, TokenType } from '@csstools/css-tokenizer'; +import { parseComponentValue } from '@csstools/css-parser-algorithms'; + +const myCSS = `@media only screen and (min-width: 768rem) { + .foo { + content: 'Some content!' !important; + } +} +`; + +const t = tokenizer({ + css: myCSS, +}); + +const tokens = []; + +{ + while (!t.endOfFile()) { + tokens.push(t.nextToken()); + } + + tokens.push(t.nextToken()); // EOF-token +} + +const options = { + onParseError: ((err) => { + throw err; + }), +}; + +const result = parseComponentValue(tokens, options); + +console.log(result); +``` + +### Available functions + +- [`parseComponentValue`](https://www.w3.org/TR/css-syntax-3/#parse-component-value) +- [`parseListOfComponentValues`](https://www.w3.org/TR/css-syntax-3/#parse-list-of-component-values) +- [`parseCommaSeparatedListOfComponentValues`](https://www.w3.org/TR/css-syntax-3/#parse-comma-separated-list-of-component-values) + +### Utilities + +#### `gatherNodeAncestry` + +The AST does not expose the entire ancestry of each node. +The walker methods do provide access to the current parent, but also not the entire ancestry. + +To gather the entire ancestry for a a given sub tree of the AST you can use `gatherNodeAncestry`. +The result is a `Map` with the child nodes as keys and the parents as values. +This allows you to lookup any ancestor of any node. + +```js +import { parseComponentValue } from '@csstools/css-parser-algorithms'; + +const result = parseComponentValue(tokens, options); +const ancestry = gatherNodeAncestry(result); +``` + +### Options + +```ts +{ + onParseError?: (error: ParseError) => void +} +``` + +#### `onParseError` + +The parser algorithms are forgiving and won't stop when a parse error is encountered. +Parse errors also aren't tokens. + +To receive parsing error information you can set a callback. + +Parser errors will try to inform you about the point in the parsing logic the error happened. +This tells you the kind of error. + +## Goals and non-goals + +Things this package aims to be: +- specification compliant CSS parser +- a reliable low level package to be used in CSS sub-grammars + +What it is not: +- opinionated +- fast +- small +- a replacement for PostCSS (PostCSS is fast and also an ecosystem) + +[cli-url]: https://github.com/csstools/postcss-plugins/actions/workflows/test.yml?query=workflow/test +[discord]: https://discord.gg/bUadyRwkJS +[npm-url]: https://www.npmjs.com/package/@csstools/css-parser-algorithms + +[CSS Parser Algorithms]: https://github.com/csstools/postcss-plugins/tree/main/packages/css-parser-algorithms diff --git a/node_modules/@csstools/css-parser-algorithms/dist/index.d.ts b/node_modules/@csstools/css-parser-algorithms/dist/index.d.ts new file mode 100644 index 00000000..c59d3ddf --- /dev/null +++ b/node_modules/@csstools/css-parser-algorithms/dist/index.d.ts @@ -0,0 +1,604 @@ +/** + * Parse CSS following the {@link https://drafts.csswg.org/css-syntax/#parsing | CSS Syntax Level 3 specification}. + * + * @remarks + * The tokenizing and parsing tools provided by CSS Tools are designed to be low level and generic with strong ties to their respective specifications. + * + * Any analysis or mutation of CSS source code should be done with the least powerful tool that can accomplish the task. + * For many applications it is sufficient to work with tokens. + * For others you might need to use {@link https://github.com/csstools/postcss-plugins/tree/main/packages/css-parser-algorithms | @csstools/css-parser-algorithms} or a more specific parser. + * + * The implementation of the AST nodes is kept lightweight and simple. + * Do not expect magic methods, instead assume that arrays and class instances behave like any other JavaScript. + * + * @example + * Parse a string of CSS into a component value: + * ```js + * import { tokenize } from '@csstools/css-tokenizer'; + * import { parseComponentValue } from '@csstools/css-parser-algorithms'; + * + * const myCSS = `calc(1px * 2)`; + * + * const componentValue = parseComponentValue(tokenize({ + * css: myCSS, + * })); + * + * console.log(componentValue); + * ``` + * + * @example + * Use the right algorithm for the job. + * + * Algorithms that can parse larger structures (comma-separated lists, ...) can also parse smaller structures. + * However, the opposite is not true. + * + * If your context allows a list of component values, use {@link parseListOfComponentValues}: + * ```js + * import { tokenize } from '@csstools/css-tokenizer'; + * import { parseListOfComponentValues } from '@csstools/css-parser-algorithms'; + * + * parseListOfComponentValues(tokenize({ css: `10x 20px` })); + * ``` + * + * If your context allows a comma-separated list of component values, use {@link parseCommaSeparatedListOfComponentValues}: + * ```js + * import { tokenize } from '@csstools/css-tokenizer'; + * import { parseCommaSeparatedListOfComponentValues } from '@csstools/css-parser-algorithms'; + * + * parseCommaSeparatedListOfComponentValues(tokenize({ css: `20deg, 50%, 30%` })); + * ``` + * + * @example + * Use the stateful walkers to keep track of the context of a given component value. + * + * ```js + * import { tokenize } from '@csstools/css-tokenizer'; + * import { parseComponentValue, isSimpleBlockNode } from '@csstools/css-parser-algorithms'; + * + * const myCSS = `calc(1px * (5 / 2))`; + * + * const componentValue = parseComponentValue(tokenize({ css: myCSS })); + * + * let state = { inSimpleBlock: false }; + * componentValue.walk((entry) => { + * if (isSimpleBlockNode(entry)) { + * entry.state.inSimpleBlock = true; + * return; + * } + * + * if (entry.state.inSimpleBlock) { + * console.log(entry.node.toString()); // `5`, ... + * } + * }, state); + * ``` + * + * @packageDocumentation + */ + +import type { CSSToken } from '@csstools/css-tokenizer'; +import { ParseError } from '@csstools/css-tokenizer'; +import type { TokenFunction } from '@csstools/css-tokenizer'; + +export declare class CommentNode { + /** + * The node type, always `ComponentValueType.Comment` + */ + type: ComponentValueType; + /** + * The comment token. + */ + value: CSSToken; + constructor(value: CSSToken); + /** + * Retrieve the tokens for the current comment. + * This is the inverse of parsing from a list of tokens. + */ + tokens(): Array; + /** + * Convert the current comment to a string. + * This is not a true serialization. + * It is purely a concatenation of the string representation of the tokens. + */ + toString(): string; + /** + * @internal + * + * A debug helper to convert the current object to a JSON representation. + * This is useful in asserts and to store large ASTs in files. + */ + toJSON(): Record; + /** + * @internal + */ + isCommentNode(): this is CommentNode; + /** + * @internal + */ + static isCommentNode(x: unknown): x is CommentNode; +} + +export declare type ComponentValue = FunctionNode | SimpleBlockNode | WhitespaceNode | CommentNode | TokenNode; + +export declare enum ComponentValueType { + Function = "function", + SimpleBlock = "simple-block", + Whitespace = "whitespace", + Comment = "comment", + Token = "token" +} + +export declare type ContainerNode = FunctionNode | SimpleBlockNode; + +export declare abstract class ContainerNodeBaseClass { + /** + * The contents of the `Function` or `Simple Block`. + * This is a list of component values. + */ + value: Array; + /** + * Retrieve the index of the given item in the current node. + * For most node types this will be trivially implemented as `this.value.indexOf(item)`. + */ + indexOf(item: ComponentValue): number | string; + /** + * Retrieve the item at the given index in the current node. + * For most node types this will be trivially implemented as `this.value[index]`. + */ + at(index: number | string): ComponentValue | undefined; + /** + * Iterates over each item in the `value` array of the current node. + * + * @param cb - The callback function to execute for each item. + * The function receives an object containing the current node (`node`), its parent (`parent`), + * and an optional `state` object. + * A second parameter is the index of the current node. + * The function can return `false` to stop the iteration. + * + * @param state - An optional state object that can be used to pass additional information to the callback function. + * The state object is cloned for each iteration. This means that changes to the state object are not reflected in the next iteration. + * + * @returns `false` if the iteration was halted, `undefined` otherwise. + */ + forEach, U extends ContainerNode>(this: U, cb: (entry: { + node: ComponentValue; + parent: ContainerNode; + state?: T; + }, index: number | string) => boolean | void, state?: T): false | undefined; + /** + * Walks the current node and all its children. + * + * @param cb - The callback function to execute for each item. + * The function receives an object containing the current node (`node`), its parent (`parent`), + * and an optional `state` object. + * A second parameter is the index of the current node. + * The function can return `false` to stop the iteration. + * + * @param state - An optional state object that can be used to pass additional information to the callback function. + * The state object is cloned for each iteration. This means that changes to the state object are not reflected in the next iteration. + * However changes are passed down to child node iterations. + * + * @returns `false` if the iteration was halted, `undefined` otherwise. + */ + walk, U extends ContainerNode>(this: U, cb: (entry: { + node: ComponentValue; + parent: ContainerNode; + state?: T; + }, index: number | string) => boolean | void, state?: T): false | undefined; +} + +/** + * Iterates over each item in a list of component values. + * + * @param cb - The callback function to execute for each item. + * The function receives an object containing the current node (`node`), its parent (`parent`), + * and an optional `state` object. + * A second parameter is the index of the current node. + * The function can return `false` to stop the iteration. + * + * @param state - An optional state object that can be used to pass additional information to the callback function. + * The state object is cloned for each iteration. This means that changes to the state object are not reflected in the next iteration. + * + * @returns `false` if the iteration was halted, `undefined` otherwise. + */ +export declare function forEach>(componentValues: Array, cb: (entry: { + node: ComponentValue; + parent: ContainerNode | { + value: Array; + }; + state?: T; +}, index: number | string) => boolean | void, state?: T): false | undefined; + +/** + * A function node. + * + * @example + * ```js + * const node = parseComponentValue(tokenize('calc(1 + 1)')); + * + * isFunctionNode(node); // true + * node.getName(); // 'calc' + * ``` + */ +export declare class FunctionNode extends ContainerNodeBaseClass { + /** + * The node type, always `ComponentValueType.Function` + */ + type: ComponentValueType; + /** + * The token for the name of the function. + */ + name: TokenFunction; + /** + * The token for the closing parenthesis of the function. + * If the function is unclosed, this will be an EOF token. + */ + endToken: CSSToken; + constructor(name: TokenFunction, endToken: CSSToken, value: Array); + /** + * Retrieve the name of the current function. + * This is the parsed and unescaped name of the function. + */ + getName(): string; + /** + * Normalize the current function: + * 1. if the "endToken" is EOF, replace with a ")-token" + */ + normalize(): void; + /** + * Retrieve the tokens for the current function. + * This is the inverse of parsing from a list of tokens. + */ + tokens(): Array; + /** + * Convert the current function to a string. + * This is not a true serialization. + * It is purely a concatenation of the string representation of the tokens. + */ + toString(): string; + /** + * @internal + * + * A debug helper to convert the current object to a JSON representation. + * This is useful in asserts and to store large ASTs in files. + */ + toJSON(): unknown; + /** + * @internal + */ + isFunctionNode(): this is FunctionNode; + /** + * @internal + */ + static isFunctionNode(x: unknown): x is FunctionNode; +} + +/** + * AST nodes do not have a `parent` property or method. + * This makes it harder to traverse the AST upwards. + * This function builds a `Map` that can be used to lookup ancestors of a node. + * + * @remarks + * There is no magic behind this or the map it returns. + * Mutating the AST will not update the map. + * + * Types are erased and any content of the map has type `unknown`. + * If someone knows a clever way to type this, please let us know. + * + * @example + * ```js + * const ancestry = gatherNodeAncestry(mediaQuery); + * mediaQuery.walk((entry) => { + * const node = entry.node; // directly exposed + * const parent = entry.parent; // directly exposed + * const grandParent: unknown = ancestry.get(parent); // lookup + * + * console.log('node', node); + * console.log('parent', parent); + * console.log('grandParent', grandParent); + * }); + * ``` + */ +export declare function gatherNodeAncestry(node: { + walk(cb: (entry: { + node: unknown; + parent: unknown; + }, index: number | string) => boolean | void): false | undefined; +}): Map; + +/** + * Check if the current object is a `CommentNode`. + * This is a type guard. + */ +export declare function isCommentNode(x: unknown): x is CommentNode; + +/** + * Check if the current object is a `FunctionNode`. + * This is a type guard. + */ +export declare function isFunctionNode(x: unknown): x is FunctionNode; + +/** + * Check if the current object is a `SimpleBlockNode`. + * This is a type guard. + */ +export declare function isSimpleBlockNode(x: unknown): x is SimpleBlockNode; + +/** + * Check if the current object is a `TokenNode`. + * This is a type guard. + */ +export declare function isTokenNode(x: unknown): x is TokenNode; + +/** + * Check if the current object is a `WhitespaceNode`. + * This is a type guard. + */ +export declare function isWhitespaceNode(x: unknown): x is WhitespaceNode; + +/** + * Check if the current object is a `WhiteSpaceNode` or a `CommentNode`. + * This is a type guard. + */ +export declare function isWhiteSpaceOrCommentNode(x: unknown): x is WhitespaceNode | CommentNode; + +/** + * Parse a comma-separated list of component values. + * + * @example + * ```js + * import { tokenize } from '@csstools/css-tokenizer'; + * import { parseCommaSeparatedListOfComponentValues } from '@csstools/css-parser-algorithms'; + * + * parseCommaSeparatedListOfComponentValues(tokenize({ css: `20deg, 50%, 30%` })); + * ``` + */ +export declare function parseCommaSeparatedListOfComponentValues(tokens: Array, options?: { + onParseError?: (error: ParseError) => void; +}): Array>; + +/** + * Parse a single component value. + * + * @example + * ```js + * import { tokenize } from '@csstools/css-tokenizer'; + * import { parseComponentValue } from '@csstools/css-parser-algorithms'; + * + * parseComponentValue(tokenize({ css: `10px` })); + * parseComponentValue(tokenize({ css: `calc((10px + 1x) * 4)` })); + * ``` + */ +export declare function parseComponentValue(tokens: Array, options?: { + onParseError?: (error: ParseError) => void; +}): ComponentValue | undefined; + +/** + * Parse a list of component values. + * + * @example + * ```js + * import { tokenize } from '@csstools/css-tokenizer'; + * import { parseListOfComponentValues } from '@csstools/css-parser-algorithms'; + * + * parseListOfComponentValues(tokenize({ css: `20deg 30%` })); + * ``` + */ +export declare function parseListOfComponentValues(tokens: Array, options?: { + onParseError?: (error: ParseError) => void; +}): Array; + +/** + * Replace specific component values in a list of component values. + * A helper for the most common and simplistic cases when mutating an AST. + */ +export declare function replaceComponentValues(componentValuesList: Array>, replaceWith: (componentValue: ComponentValue) => Array | ComponentValue | void): Array>; + +/** + * A simple block node. + * + * @example + * ```js + * const node = parseComponentValue(tokenize('[foo=bar]')); + * + * isSimpleBlockNode(node); // true + * node.startToken; // [TokenType.OpenSquare, '[', 0, 0, undefined] + * ``` + */ +export declare class SimpleBlockNode extends ContainerNodeBaseClass { + /** + * The node type, always `ComponentValueType.SimpleBlock` + */ + type: ComponentValueType; + /** + * The token for the opening token of the block. + */ + startToken: CSSToken; + /** + * The token for the closing token of the block. + * If the block is closed it will be the mirror variant of the `startToken`. + * If the block is unclosed, this will be an EOF token. + */ + endToken: CSSToken; + constructor(startToken: CSSToken, endToken: CSSToken, value: Array); + /** + * Normalize the current simple block + * 1. if the "endToken" is EOF, replace with the mirror token of the "startToken" + */ + normalize(): void; + /** + * Retrieve the tokens for the current simple block. + * This is the inverse of parsing from a list of tokens. + */ + tokens(): Array; + /** + * Convert the current simple block to a string. + * This is not a true serialization. + * It is purely a concatenation of the string representation of the tokens. + */ + toString(): string; + /** + * @internal + * + * A debug helper to convert the current object to a JSON representation. + * This is useful in asserts and to store large ASTs in files. + */ + toJSON(): unknown; + /** + * @internal + */ + isSimpleBlockNode(): this is SimpleBlockNode; + /** + * @internal + */ + static isSimpleBlockNode(x: unknown): x is SimpleBlockNode; +} + +/** + * Returns the start and end index of a node in the CSS source string. + */ +export declare function sourceIndices(x: { + tokens(): Array; +} | Array<{ + tokens(): Array; +}>): [number, number]; + +/** + * Concatenate the string representation of a collection of component values. + * This is not a proper serializer that will handle escaping and whitespace. + * It only produces valid CSS for token lists that are also valid. + */ +export declare function stringify(componentValueLists: Array>): string; + +export declare class TokenNode { + /** + * The node type, always `ComponentValueType.Token` + */ + type: ComponentValueType; + /** + * The token. + */ + value: CSSToken; + constructor(value: CSSToken); + /** + * This is the inverse of parsing from a list of tokens. + */ + tokens(): [CSSToken]; + /** + * Convert the current token to a string. + * This is not a true serialization. + * It is purely the string representation of token. + */ + toString(): string; + /** + * @internal + * + * A debug helper to convert the current object to a JSON representation. + * This is useful in asserts and to store large ASTs in files. + */ + toJSON(): Record; + /** + * @internal + */ + isTokenNode(): this is TokenNode; + /** + * @internal + */ + static isTokenNode(x: unknown): x is TokenNode; +} + +/** + * Walks each item in a list of component values all of their children. + * + * @param cb - The callback function to execute for each item. + * The function receives an object containing the current node (`node`), its parent (`parent`), + * and an optional `state` object. + * A second parameter is the index of the current node. + * The function can return `false` to stop the iteration. + * + * @param state - An optional state object that can be used to pass additional information to the callback function. + * The state object is cloned for each iteration. This means that changes to the state object are not reflected in the next iteration. + * However changes are passed down to child node iterations. + * + * @returns `false` if the iteration was halted, `undefined` otherwise. + * + * @example + * ```js + * import { tokenize } from '@csstools/css-tokenizer'; + * import { parseListOfComponentValues, isSimpleBlockNode } from '@csstools/css-parser-algorithms'; + * + * const myCSS = `calc(1px * (5 / 2)) 10px`; + * + * const componentValues = parseListOfComponentValues(tokenize({ css: myCSS })); + * + * let state = { inSimpleBlock: false }; + * walk(componentValues, (entry) => { + * if (isSimpleBlockNode(entry)) { + * entry.state.inSimpleBlock = true; + * return; + * } + * + * if (entry.state.inSimpleBlock) { + * console.log(entry.node.toString()); // `5`, ... + * } + * }, state); + * ``` + */ +export declare function walk>(componentValues: Array, cb: (entry: { + node: ComponentValue; + parent: ContainerNode | { + value: Array; + }; + state?: T; +}, index: number | string) => boolean | void, state?: T): false | undefined; + +/** + * Generate a function that finds the next element that should be visited when walking an AST. + * Rules : + * 1. the previous iteration is used as a reference, so any checks are relative to the start of the current iteration. + * 2. the next element always appears after the current index. + * 3. the next element always exists in the list. + * 4. replacing an element does not cause the replaced element to be visited. + * 5. removing an element does not cause elements to be skipped. + * 6. an element added later in the list will be visited. + */ +export declare function walkerIndexGenerator(initialList: Array): (list: Array, child: T, index: number) => number; + +export declare class WhitespaceNode { + /** + * The node type, always `ComponentValueType.WhiteSpace` + */ + type: ComponentValueType; + /** + * The list of consecutive whitespace tokens. + */ + value: Array; + constructor(value: Array); + /** + * Retrieve the tokens for the current whitespace. + * This is the inverse of parsing from a list of tokens. + */ + tokens(): Array; + /** + * Convert the current whitespace to a string. + * This is not a true serialization. + * It is purely a concatenation of the string representation of the tokens. + */ + toString(): string; + /** + * @internal + * + * A debug helper to convert the current object to a JSON representation. + * This is useful in asserts and to store large ASTs in files. + */ + toJSON(): Record; + /** + * @internal + */ + isWhitespaceNode(): this is WhitespaceNode; + /** + * @internal + */ + static isWhitespaceNode(x: unknown): x is WhitespaceNode; +} + +export { } diff --git a/node_modules/@csstools/css-parser-algorithms/dist/index.mjs b/node_modules/@csstools/css-parser-algorithms/dist/index.mjs new file mode 100644 index 00000000..ca4f76de --- /dev/null +++ b/node_modules/@csstools/css-parser-algorithms/dist/index.mjs @@ -0,0 +1 @@ +import{isTokenEOF as e,TokenType as n,isToken as t,stringify as o,mirrorVariant as s,isTokenOpenParen as i,isTokenOpenCurly as r,isTokenOpenSquare as a,isTokenFunction as c,isTokenWhitespace as u,isTokenComment as l,mirrorVariantType as d,ParseError as h,isTokenWhiteSpaceOrComment as p,isTokenCloseParen as m,isTokenComma as k}from"@csstools/css-tokenizer";var f;function walkerIndexGenerator(e){let n=e.slice();return(e,t,o)=>{let s=-1;for(let i=n.indexOf(t);i=e.length)?-1:(n=e.slice(),s)}}function consumeComponentValue(e,n){const t=n[0];if(i(t)||r(t)||a(t)){const t=consumeSimpleBlock(e,n);return{advance:t.advance,node:t.node}}if(c(t)){const t=consumeFunction(e,n);return{advance:t.advance,node:t.node}}if(u(t)){const t=consumeWhitespace(e,n);return{advance:t.advance,node:t.node}}if(l(t)){const t=consumeComment(e,n);return{advance:t.advance,node:t.node}}return{advance:1,node:new TokenNode(t)}}!function(e){e.Function="function",e.SimpleBlock="simple-block",e.Whitespace="whitespace",e.Comment="comment",e.Token="token"}(f||(f={}));class ContainerNodeBaseClass{value=[];indexOf(e){return this.value.indexOf(e)}at(e){if("number"==typeof e)return e<0&&(e=this.value.length+e),this.value[e]}forEach(e,n){if(0===this.value.length)return;const t=walkerIndexGenerator(this.value);let o=0;for(;o!1!==e(n,t)&&((!("walk"in n.node)||!this.value.includes(n.node)||!1!==n.node.walk(e,n.state))&&void 0),n)}}class FunctionNode extends ContainerNodeBaseClass{type=f.Function;name;endToken;constructor(e,n,t){super(),this.name=e,this.endToken=n,this.value=t}getName(){return this.name[4].value}normalize(){e(this.endToken)&&(this.endToken=[n.CloseParen,")",-1,-1,void 0])}tokens(){return e(this.endToken)?[this.name,...this.value.flatMap(e=>e.tokens())]:[this.name,...this.value.flatMap(e=>e.tokens()),this.endToken]}toString(){const e=this.value.map(e=>t(e)?o(e):e.toString()).join("");return o(this.name)+e+o(this.endToken)}toJSON(){return{type:this.type,name:this.getName(),tokens:this.tokens(),value:this.value.map(e=>e.toJSON())}}isFunctionNode(){return FunctionNode.isFunctionNode(this)}static isFunctionNode(e){return!!e&&(e instanceof FunctionNode&&e.type===f.Function)}}function consumeFunction(n,t){const o=[];let s=1;for(;;){const i=t[s];if(!i||e(i))return n.onParseError(new h("Unexpected EOF while consuming a function.",t[0][2],t[t.length-1][3],["5.4.9. Consume a function","Unexpected EOF"])),{advance:t.length,node:new FunctionNode(t[0],i,o)};if(m(i))return{advance:s+1,node:new FunctionNode(t[0],i,o)};if(p(i)){const e=consumeAllCommentsAndWhitespace(n,t.slice(s));s+=e.advance,o.push(...e.nodes);continue}const r=consumeComponentValue(n,t.slice(s));s+=r.advance,o.push(r.node)}}class SimpleBlockNode extends ContainerNodeBaseClass{type=f.SimpleBlock;startToken;endToken;constructor(e,n,t){super(),this.startToken=e,this.endToken=n,this.value=t}normalize(){if(e(this.endToken)){const e=s(this.startToken);e&&(this.endToken=e)}}tokens(){return e(this.endToken)?[this.startToken,...this.value.flatMap(e=>e.tokens())]:[this.startToken,...this.value.flatMap(e=>e.tokens()),this.endToken]}toString(){const e=this.value.map(e=>t(e)?o(e):e.toString()).join("");return o(this.startToken)+e+o(this.endToken)}toJSON(){return{type:this.type,startToken:this.startToken,tokens:this.tokens(),value:this.value.map(e=>e.toJSON())}}isSimpleBlockNode(){return SimpleBlockNode.isSimpleBlockNode(this)}static isSimpleBlockNode(e){return!!e&&(e instanceof SimpleBlockNode&&e.type===f.SimpleBlock)}}function consumeSimpleBlock(n,t){const o=d(t[0][0]);if(!o)throw new Error("Failed to parse, a mirror variant must exist for all block open tokens.");const s=[];let i=1;for(;;){const r=t[i];if(!r||e(r))return n.onParseError(new h("Unexpected EOF while consuming a simple block.",t[0][2],t[t.length-1][3],["5.4.8. Consume a simple block","Unexpected EOF"])),{advance:t.length,node:new SimpleBlockNode(t[0],r,s)};if(r[0]===o)return{advance:i+1,node:new SimpleBlockNode(t[0],r,s)};if(p(r)){const e=consumeAllCommentsAndWhitespace(n,t.slice(i));i+=e.advance,s.push(...e.nodes);continue}const a=consumeComponentValue(n,t.slice(i));i+=a.advance,s.push(a.node)}}class WhitespaceNode{type=f.Whitespace;value;constructor(e){this.value=e}tokens(){return this.value}toString(){return o(...this.value)}toJSON(){return{type:this.type,tokens:this.tokens()}}isWhitespaceNode(){return WhitespaceNode.isWhitespaceNode(this)}static isWhitespaceNode(e){return!!e&&(e instanceof WhitespaceNode&&e.type===f.Whitespace)}}function consumeWhitespace(e,n){let t=0;for(;;){const e=n[t];if(!u(e))return{advance:t,node:new WhitespaceNode(n.slice(0,t))};t++}}class CommentNode{type=f.Comment;value;constructor(e){this.value=e}tokens(){return[this.value]}toString(){return o(this.value)}toJSON(){return{type:this.type,tokens:this.tokens()}}isCommentNode(){return CommentNode.isCommentNode(this)}static isCommentNode(e){return!!e&&(e instanceof CommentNode&&e.type===f.Comment)}}function consumeComment(e,n){return{advance:1,node:new CommentNode(n[0])}}function consumeAllCommentsAndWhitespace(e,n){const t=[];let o=0;for(;;){if(u(n[o])){const e=consumeWhitespace(0,n.slice(o));o+=e.advance,t.push(e.node);continue}if(!l(n[o]))return{advance:o,nodes:t};t.push(new CommentNode(n[o])),o++}}class TokenNode{type=f.Token;value;constructor(e){this.value=e}tokens(){return[this.value]}toString(){return this.value[1]}toJSON(){return{type:this.type,tokens:this.tokens()}}isTokenNode(){return TokenNode.isTokenNode(this)}static isTokenNode(e){return!!e&&(e instanceof TokenNode&&e.type===f.Token)}}function parseComponentValue(t,o){const s={onParseError:o?.onParseError??(()=>{})},i=[...t];e(i[i.length-1])||i.push([n.EOF,"",i[i.length-1][2],i[i.length-1][3],void 0]);const r=consumeComponentValue(s,i);if(e(i[Math.min(r.advance,i.length-1)]))return r.node;s.onParseError(new h("Expected EOF after parsing a component value.",t[0][2],t[t.length-1][3],["5.3.9. Parse a component value","Expected EOF"]))}function parseListOfComponentValues(t,o){const s={onParseError:o?.onParseError??(()=>{})},i=[...t];e(i[i.length-1])&&i.push([n.EOF,"",i[i.length-1][2],i[i.length-1][3],void 0]);const r=[];let a=0;for(;;){if(!i[a]||e(i[a]))return r;const n=consumeComponentValue(s,i.slice(a));r.push(n.node),a+=n.advance}}function parseCommaSeparatedListOfComponentValues(t,o){const s={onParseError:o?.onParseError??(()=>{})},i=[...t];if(0===t.length)return[];e(i[i.length-1])&&i.push([n.EOF,"",i[i.length-1][2],i[i.length-1][3],void 0]);const r=[];let a=[],c=0;for(;;){if(!i[c]||e(i[c]))return a.length&&r.push(a),r;if(k(i[c])){r.push(a),a=[],c++;continue}const n=consumeComponentValue(s,t.slice(c));a.push(n.node),c+=n.advance}}function gatherNodeAncestry(e){const n=new Map;return e.walk(e=>{Array.isArray(e.node)?e.node.forEach(t=>{n.set(t,e.parent)}):n.set(e.node,e.parent)}),n}function forEach(e,n,t){if(0===e.length)return;const o=walkerIndexGenerator(e);let s=0;for(;s!1!==n(t,o)&&((!("walk"in t.node)||!e.includes(t.node)||!1!==t.node.walk(n,t.state))&&void 0),t)}function replaceComponentValues(e,n){for(let t=0;t{if("number"!=typeof t)return;const o=n(e.node);o&&(Array.isArray(o)?e.parent.value.splice(t,1,...o):e.parent.value.splice(t,1,o))})}return e}function stringify(e){return e.map(e=>e.map(e=>o(...e.tokens())).join("")).join(",")}function isSimpleBlockNode(e){return SimpleBlockNode.isSimpleBlockNode(e)}function isFunctionNode(e){return FunctionNode.isFunctionNode(e)}function isWhitespaceNode(e){return WhitespaceNode.isWhitespaceNode(e)}function isCommentNode(e){return CommentNode.isCommentNode(e)}function isWhiteSpaceOrCommentNode(e){return isWhitespaceNode(e)||isCommentNode(e)}function isTokenNode(e){return TokenNode.isTokenNode(e)}function sourceIndices(e){if(Array.isArray(e)){const n=e[0];if(!n)return[0,0];const t=e[e.length-1]||n;return[sourceIndices(n)[0],sourceIndices(t)[1]]}const n=e.tokens(),t=n[0],o=n[n.length-1];return t&&o?[t[2],o[3]]:[0,0]}export{CommentNode,f as ComponentValueType,ContainerNodeBaseClass,FunctionNode,SimpleBlockNode,TokenNode,WhitespaceNode,forEach,gatherNodeAncestry,isCommentNode,isFunctionNode,isSimpleBlockNode,isTokenNode,isWhiteSpaceOrCommentNode,isWhitespaceNode,parseCommaSeparatedListOfComponentValues,parseComponentValue,parseListOfComponentValues,replaceComponentValues,sourceIndices,stringify,walk,walkerIndexGenerator}; diff --git a/node_modules/@csstools/css-parser-algorithms/package.json b/node_modules/@csstools/css-parser-algorithms/package.json new file mode 100644 index 00000000..5734668f --- /dev/null +++ b/node_modules/@csstools/css-parser-algorithms/package.json @@ -0,0 +1,58 @@ +{ + "name": "@csstools/css-parser-algorithms", + "description": "Algorithms to help you parse CSS from an array of tokens.", + "version": "4.0.0", + "contributors": [ + { + "name": "Antonio Laguna", + "email": "antonio@laguna.es", + "url": "https://antonio.laguna.es" + }, + { + "name": "Romain Menke", + "email": "romainmenke@gmail.com" + } + ], + "license": "MIT", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "engines": { + "node": ">=20.19.0" + }, + "type": "module", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + } + }, + "files": [ + "CHANGELOG.md", + "LICENSE.md", + "README.md", + "dist" + ], + "peerDependencies": { + "@csstools/css-tokenizer": "^4.0.0" + }, + "scripts": {}, + "homepage": "https://github.com/csstools/postcss-plugins/tree/main/packages/css-parser-algorithms#readme", + "repository": { + "type": "git", + "url": "git+https://github.com/csstools/postcss-plugins.git", + "directory": "packages/css-parser-algorithms" + }, + "bugs": "https://github.com/csstools/postcss-plugins/issues", + "keywords": [ + "css", + "parser" + ] +} diff --git a/node_modules/@csstools/css-syntax-patches-for-csstree/CHANGELOG.md b/node_modules/@csstools/css-syntax-patches-for-csstree/CHANGELOG.md new file mode 100644 index 00000000..f04324d5 --- /dev/null +++ b/node_modules/@csstools/css-syntax-patches-for-csstree/CHANGELOG.md @@ -0,0 +1,9 @@ +# Changes to CSS Syntax Patches For CSSTree + +### 1.1.2 + +_March 26, 2026_ + +- Update `@webref/css` to [`v8.5.1`](https://github.com/w3c/webref/releases/tag/%40webref%2Fcss%408.5.1) + +[Full CHANGELOG](https://github.com/csstools/postcss-plugins/tree/main/packages/css-syntax-patches-for-csstree/CHANGELOG.md) diff --git a/node_modules/@csstools/css-syntax-patches-for-csstree/LICENSE.md b/node_modules/@csstools/css-syntax-patches-for-csstree/LICENSE.md new file mode 100644 index 00000000..e8ae93b9 --- /dev/null +++ b/node_modules/@csstools/css-syntax-patches-for-csstree/LICENSE.md @@ -0,0 +1,18 @@ +MIT No Attribution (MIT-0) + +Copyright © CSSTools 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. + +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. diff --git a/node_modules/@csstools/css-syntax-patches-for-csstree/README.md b/node_modules/@csstools/css-syntax-patches-for-csstree/README.md new file mode 100644 index 00000000..00e214f6 --- /dev/null +++ b/node_modules/@csstools/css-syntax-patches-for-csstree/README.md @@ -0,0 +1,43 @@ +# CSS Syntax Patches For CSSTree for CSS + +[npm version][npm-url] +[Build Status][cli-url] + +Patch [csstree](https://github.com/csstree/csstree) syntax definitions with the latest data from CSS specifications. + +## Usage + +```bash +npm install @csstools/css-syntax-patches-for-csstree +``` + +```js +import { fork } from 'css-tree'; +import syntax_patches from '@csstools/css-syntax-patches-for-csstree' with { type: 'json' }; + +const forkedLexer = fork({ + atrules: syntax_patches.next.atrules, + properties: syntax_patches.next.properties, + types: syntax_patches.next.types, +}).lexer; +``` + +## `next` + +```js +import syntax_patches from '@csstools/css-syntax-patches-for-csstree' with { type: 'json' }; + +console.log(syntax_patches.next); +// ^^^^ +``` + +CSS specifications are often still in flux and various parts might change or disappear altogether. +Specifications also contains parts that haven't been implemented yet in a browser. +Only CSS that is widely adopted can be expected to be stable. + +The `next` grouping contains a combination of what is currently valid in browsers and the progress in various specifications. + +_In the future more groupings might be added._ + +[cli-url]: https://github.com/csstools/postcss-plugins/actions/workflows/test.yml?query=workflow/test +[npm-url]: https://www.npmjs.com/package/@csstools/css-syntax-patches-for-csstree diff --git a/node_modules/@csstools/css-syntax-patches-for-csstree/dist/index.d.ts b/node_modules/@csstools/css-syntax-patches-for-csstree/dist/index.d.ts new file mode 100644 index 00000000..05d942a6 --- /dev/null +++ b/node_modules/@csstools/css-syntax-patches-for-csstree/dist/index.d.ts @@ -0,0 +1,5 @@ +export const next: { + atrules: Record }>, + properties: Record, + types: Record, +} diff --git a/node_modules/@csstools/css-syntax-patches-for-csstree/dist/index.json b/node_modules/@csstools/css-syntax-patches-for-csstree/dist/index.json new file mode 100644 index 00000000..68af8df5 --- /dev/null +++ b/node_modules/@csstools/css-syntax-patches-for-csstree/dist/index.json @@ -0,0 +1,748 @@ +{ + "next": { + "atrules": { + "color-profile": { + "descriptors": { + "components": "#", + "rendering-intent": "relative-colorimetric | absolute-colorimetric | perceptual | saturation", + "src": "" + } + }, + "font-face": { + "descriptors": { + "ascent-override": "[ normal | ]{1,2}", + "descent-override": "[ normal | ]{1,2}", + "font-language-override": "normal | ", + "font-named-instance": "auto | ", + "font-size": "auto | [ ]{1,2}", + "font-style": "auto | normal | italic | left | right | oblique [ {1,2} ]?", + "font-weight": "| auto", + "font-width": "auto | <'font-width'>{1,2}", + "line-gap-override": "[ normal | ]{1,2}", + "size-adjust": "", + "src": "", + "subscript-position-override": "[ normal | from-font | ]{1,2}", + "subscript-size-override": "[ normal | from-font | ]{1,2}", + "superscript-position-override": "[ normal | from-font | ]{1,2}", + "superscript-size-override": "[ normal | from-font | ]{1,2}", + "unicode-range": "#" + } + }, + "font-feature-values": { + "descriptors": { + "font-display": "auto | block | swap | fallback | optional" + } + }, + "function": { + "descriptors": { + "result": "?" + } + }, + "page": { + "descriptors": { + "page-margin-safety": "none | clamp | add" + } + } + }, + "properties": { + "align-self": "auto | ? [ normal | ] | stretch | | anchor-center", + "alignment-baseline": "auto | before-edge | text-before-edge | after-edge | text-after-edge | baseline | ", + "all": " | revert-rule", + "anchor-name": "none | #", + "anchor-scope": "none | all | #", + "animation-range-center": "[ normal | [ | ? ] ]#", + "appearance": "none | auto | base | base-select | | | base", + "background-blend-mode": "<'mix-blend-mode'>#", + "background-position-block": "[ center | [ [ start | end ]? ? ]! ]#", + "background-position-inline": "[ center | [ [ start | end ]? ? ]! ]#", + "background-repeat-block": "#", + "background-repeat-inline": "#", + "background-repeat-x": "#", + "background-repeat-y": "#", + "background-tbd": "#", + "baseline-shift": " | sub | super | top | center | bottom", + "block-ellipsis": "no-ellipsis | auto | ", + "block-step": "<'block-step-size'> || <'block-step-insert'> || <'block-step-align'> || <'block-step-round'>", + "block-step-align": "auto | center | start | end", + "block-step-insert": "margin-box | padding-box | content-box", + "block-step-round": "up | down | nearest", + "block-step-size": "none | ", + "bookmark-label": "", + "bookmark-level": "none | ", + "bookmark-state": "open | closed", + "border-block-clip": "<'border-top-clip'>", + "border-block-end": " || || ", + "border-block-end-clip": "none | [ | ]+", + "border-block-end-color": " | ", + "border-block-end-radius": "{1,2} [ / {1,2} ]?", + "border-block-end-style": "", + "border-block-end-width": "", + "border-block-start": " || || ", + "border-block-start-clip": "none | [ | ]+", + "border-block-start-color": " | ", + "border-block-start-radius": "{1,2} [ / {1,2} ]?", + "border-block-start-style": "", + "border-block-start-width": "", + "border-bottom-clip": "none | [ | ]+", + "border-bottom-color": " | ", + "border-bottom-left-radius": "", + "border-bottom-radius": "{1,2} [ / {1,2} ]?", + "border-bottom-right-radius": "", + "border-boundary": "none | parent | display", + "border-clip": "<'border-top-clip'>", + "border-color": "[ | ]{1,4}", + "border-end-end-radius": "", + "border-end-start-radius": "", + "border-inline-clip": "<'border-top-clip'>", + "border-inline-end": " || || ", + "border-inline-end-clip": "none | [ | ]+", + "border-inline-end-color": " | ", + "border-inline-end-radius": "{1,2} [ / {1,2} ]?", + "border-inline-end-style": "", + "border-inline-end-width": "", + "border-inline-start": " || || ", + "border-inline-start-clip": "none | [ | ]+", + "border-inline-start-color": " | ", + "border-inline-start-radius": "{1,2} [ / {1,2} ]?", + "border-inline-start-style": "", + "border-inline-start-width": "", + "border-left-clip": "none | [ | ]+", + "border-left-color": " | ", + "border-left-radius": "{1,2} [ / {1,2} ]?", + "border-limit": "all | [ sides | corners ] ? | [ top | right | bottom | left ] ", + "border-right-clip": "none | [ | ]+", + "border-right-color": " | ", + "border-right-radius": "{1,2} [ / {1,2} ]?", + "border-shape": "none | [ ? ]{1,2}", + "border-start-end-radius": "", + "border-start-start-radius": "", + "border-style": "<'border-top-style'>{1,4}", + "border-top-clip": "none | [ | ]+", + "border-top-color": " | ", + "border-top-left-radius": "", + "border-top-radius": "{1,2} [ / {1,2} ]?", + "border-top-right-radius": "", + "border-width": "<'border-top-width'>{1,4}", + "box-shadow": "#", + "box-shadow-blur": "#", + "box-shadow-color": "#", + "box-shadow-offset": "[ none | {1,2} ]#", + "box-shadow-position": "[ outset | inset ]#", + "box-shadow-spread": "#", + "box-snap": "none | block-start | block-end | center | baseline | last-baseline", + "clear": "| block-start | block-end | top | bottom | both-inline | both-block", + "clip": "rect( , , , ) | rect( ) | auto", + "color-adjust": "<'print-color-adjust'>", + "color-interpolation": "auto | sRGB | linearRGB", + "column-count": "auto | ", + "column-fill": "| balance-all", + "column-gap": "normal | | ", + "column-rule": " | ", + "column-rule-break": "none | normal | intersection", + "column-rule-color": " | ", + "column-rule-edge-inset": " [ ]?", + "column-rule-edge-inset-end": "", + "column-rule-edge-inset-start": "", + "column-rule-inset": "<'column-rule-edge-inset'> [ / <'column-rule-interior-inset'> ]?", + "column-rule-inset-end": "", + "column-rule-inset-start": "", + "column-rule-interior-inset": " [ ]?", + "column-rule-interior-inset-end": "", + "column-rule-interior-inset-start": "", + "column-rule-style": " | ", + "column-rule-visibility-items": "all | around | between", + "column-rule-width": " | ", + "column-span": "| | auto", + "column-width": "auto | | min-content | max-content | fit-content( )", + "contain": "none | strict | content | [ [ size | inline-size ] || layout || style || paint ]", + "contain-intrinsic-block-size": "[ auto | from-element ]? [ none | ]", + "contain-intrinsic-height": "[ auto | from-element ]? [ none | ]", + "contain-intrinsic-inline-size": "[ auto | from-element ]? [ none | ]", + "contain-intrinsic-size": "[ [ auto | from-element ]? [ none | ] ]{1,2}", + "contain-intrinsic-width": "[ auto | from-element ]? [ none | ]", + "container-type": "normal | [ [ size | inline-size ] || scroll-state ]", + "content": "| ", + "continue": "auto | discard | collapse | -webkit-legacy | overflow | paginate | fragments", + "copy-into": "none | [ [ ] [, ]* ]?", + "corner": "<'border-radius'> || <'corner-shape'>", + "corner-block-end": "<'border-top-radius'> || <'corner-top-shape'>", + "corner-block-end-shape": "<'corner-top-left-shape'>{1,2}", + "corner-block-start": "<'border-top-radius'> || <'corner-top-shape'>", + "corner-block-start-shape": "<'corner-top-left-shape'>{1,2}", + "corner-bottom": "<'border-top-radius'> || <'corner-top-shape'>", + "corner-bottom-left": "<'border-top-left-radius'> || <'corner-top-left-shape'>", + "corner-bottom-right": "<'border-top-left-radius'> || <'corner-top-left-shape'>", + "corner-bottom-shape": "<'corner-top-left-shape'>{1,2}", + "corner-end-end": "<'border-top-left-radius'> || <'corner-top-left-shape'>", + "corner-end-start": "<'border-top-left-radius'> || <'corner-top-left-shape'>", + "corner-inline-end": "<'border-top-radius'> || <'corner-top-shape'>", + "corner-inline-end-shape": "<'corner-top-left-shape'>{1,2}", + "corner-inline-start": "<'border-top-radius'> || <'corner-top-shape'>", + "corner-inline-start-shape": "<'corner-top-left-shape'>{1,2}", + "corner-left": "<'border-top-radius'> || <'corner-top-shape'>", + "corner-left-shape": "<'corner-top-left-shape'>{1,2}", + "corner-right": "<'border-top-radius'> || <'corner-top-shape'>", + "corner-right-shape": "<'corner-top-left-shape'>{1,2}", + "corner-shape": "<'corner-top-left-shape'>{1,4}", + "corner-start-end": "<'border-top-left-radius'> || <'corner-top-left-shape'>", + "corner-start-start": "<'border-top-left-radius'> || <'corner-top-left-shape'>", + "corner-top": "<'border-top-radius'> || <'corner-top-shape'>", + "corner-top-left": "<'border-top-left-radius'> || <'corner-top-left-shape'>", + "corner-top-right": "<'border-top-left-radius'> || <'corner-top-left-shape'>", + "corner-top-shape": "<'corner-top-left-shape'>{1,2}", + "cursor": "[ , ]* ", + "cx": "", + "cy": "", + "display": "[ || ] | | | | | grid-lanes | inline-grid-lanes | ruby | ruby-base | ruby-text | ruby-base-container | ruby-text-container | | <-non-standard-display> || [ | math ]", + "dominant-baseline": "use-script | no-change | reset-size | text-after-edge | text-before-edge | auto | ", + "event-trigger": "none | [ <'event-trigger-name'> <'event-trigger-source'> ]#", + "event-trigger-name": "none | #", + "event-trigger-source": "[ none | + [ / + ]? ]#", + "fill-break": "bounding-box | slice | clone", + "fill-color": "", + "fill-image": "#", + "fill-opacity": "<'opacity'>", + "fill-origin": "match-parent | fill-box | stroke-box | content-box | padding-box | border-box", + "fill-position": "#", + "fill-repeat": "#", + "fill-size": "#", + "filter": "none | ", + "flex-grow": "", + "flex-shrink": "", + "float": "| block-start | block-end | snap-block | snap-block( , [ start | end | near ]? ) | snap-inline | snap-inline( , [ left | right | near ]? ) | top | bottom | footnote", + "float-defer": " | last | none", + "float-offset": "", + "float-reference": "inline | column | region | page", + "flow-from": " | none", + "flow-into": "none | [ element | content ]?", + "flow-tolerance": "normal | | infinite", + "font-size-adjust": "none | [ ex-height | cap-height | ch-width | ic-width | ic-height ]? [ from-font | ]", + "font-stretch": "normal | | ultra-condensed | extra-condensed | condensed | semi-condensed | semi-expanded | expanded | extra-expanded | ultra-expanded", + "font-style": "normal | italic | left | right | oblique ?", + "font-synthesis-style": "auto | none | oblique-only", + "font-variant": "normal | none | [ [ || || || ] || [ small-caps | all-small-caps | petite-caps | all-petite-caps | unicase | titling-caps ] || [ stylistic( ) || historical-forms || styleset( # ) || character-variant( # ) || swash( ) || ornaments( ) || annotation( ) ] || [ || || || ordinal || slashed-zero ] || [ || || ruby ] || [ sub | super ] || [ text | emoji | unicode ] ]", + "font-variation-settings": "normal | [ ]#", + "footnote-display": "block | inline | compact", + "footnote-policy": "auto | line | block", + "glyph-orientation-vertical": "auto | 0deg | 90deg | 0 | 90", + "grid-column-gap": "normal | | ", + "grid-gap": "<'row-gap'> <'column-gap'>?", + "grid-row-gap": "normal | | ", + "height": "auto | | min-content | max-content | fit-content( ) | | | stretch | fit-content | contain | <-non-standard-size>", + "hyphenate-limit-last": "none | always | column | page | spread", + "hyphenate-limit-lines": "no-limit | ", + "hyphenate-limit-zone": "", + "image-animation": "normal | paused | stopped | running", + "image-orientation": "from-image | none | [ || flip ]", + "image-rendering": "auto | smooth | high-quality | pixelated | crisp-edges | <-non-standard-image-rendering>", + "initial-letter": "normal | | && [ drop | raise ]?", + "initial-letter-align": "[ border-box? [ alphabetic | ideographic | hanging | leading ]? ]!", + "initial-letter-wrap": "none | first | all | grid | ", + "inline-sizing": "normal | stretch", + "input-security": "auto | none", + "isolation": "", + "justify-self": "auto | ? [ normal | | left | right ] | stretch | | anchor-center", + "line-clamp": "none | [ || <'block-ellipsis'> ] -webkit-legacy?", + "line-fit-edge": "leading | ", + "line-grid": "match-parent | create", + "line-height": "normal | | ", + "line-height-step": "", + "line-padding": "", + "line-snap": "none | baseline | contain", + "link-parameters": "none | #", + "list-style": "<'list-style-position'> || <'list-style-image'> || <'list-style-type'>", + "margin-break": "auto | keep | discard", + "margin-trim": "none | [ block || inline ] | [ block-start || inline-start || block-end || inline-end ]", + "marker": "none | ", + "marker-end": "none | ", + "marker-mid": "none | ", + "marker-side": "match-self | match-parent", + "marker-start": "none | ", + "mask-border-slice": "[ | ]{1,4} fill?", + "max-height": "none | | min-content | max-content | fit-content( ) | | | stretch | fit-content | contain | <-non-standard-size>", + "max-lines": "none | ", + "max-width": "none | | min-content | max-content | fit-content( ) | | | stretch | fit-content | contain | <-non-standard-size>", + "min-height": "auto | | min-content | max-content | fit-content( ) | | | stretch | fit-content | contain | <-non-standard-size>", + "min-intrinsic-sizing": "legacy | zero-if-scroll || zero-if-extrinsic", + "min-width": "auto | | min-content | max-content | fit-content( ) | | | stretch | fit-content | contain | <-non-standard-size>", + "mix-blend-mode": " | plus-lighter", + "object-fit": "fill | none | [ contain | cover ] || scale-down", + "orphans": "", + "outline-color": "auto | <'border-top-color'>", + "overflow": "<'overflow-block'>{1,2} | <-non-standard-overflow>", + "overflow-block": "| <-non-standard-overflow>", + "overflow-clip-margin-block": " || ", + "overflow-clip-margin-block-end": " || ", + "overflow-clip-margin-block-start": " || ", + "overflow-clip-margin-bottom": " || ", + "overflow-clip-margin-inline": " || ", + "overflow-clip-margin-inline-end": " || ", + "overflow-clip-margin-inline-start": " || ", + "overflow-clip-margin-left": " || ", + "overflow-clip-margin-right": " || ", + "overflow-clip-margin-top": " || ", + "overflow-inline": "| <-non-standard-overflow>", + "overflow-x": "| <-non-standard-overflow>", + "overflow-y": "| <-non-standard-overflow>", + "pause-after": "

+ A family of specs for interoperable TypeScript +
+ standardschema.dev +

+
+ + + +The Standard Schema project is a set of interfaces that standardize the provision and consumption of shared functionality in the TypeScript ecosystem. + +Its goal is to allow tools to accept a single input that includes all the types and capabilities they need— no library-specific adapters, no extra dependencies. The result is an ecosystem that's fair for implementers, friendly for consumers, and open for end users. + +## The specifications + +The specifications can be found below in their entirety. Libraries wishing to implement a spec can copy/paste the code block below into their codebase. They're also available at `@standard-schema/spec` on [npm](https://www.npmjs.com/package/@standard-schema/spec) and [JSR](https://jsr.io/@standard-schema/spec). + +```ts +// ######################### +// ### Standard Typed ### +// ######################### + +/** The Standard Typed interface. This is a base type extended by other specs. */ +export interface StandardTypedV1 { + /** The Standard properties. */ + readonly "~standard": StandardTypedV1.Props; +} + +export declare namespace StandardTypedV1 { + /** The Standard Typed properties interface. */ + export interface Props { + /** The version number of the standard. */ + readonly version: 1; + /** The vendor name of the schema library. */ + readonly vendor: string; + /** Inferred types associated with the schema. */ + readonly types?: Types | undefined; + } + + /** The Standard Typed types interface. */ + export interface Types { + /** The input type of the schema. */ + readonly input: Input; + /** The output type of the schema. */ + readonly output: Output; + } + + /** Infers the input type of a Standard Typed. */ + export type InferInput = NonNullable< + Schema["~standard"]["types"] + >["input"]; + + /** Infers the output type of a Standard Typed. */ + export type InferOutput = NonNullable< + Schema["~standard"]["types"] + >["output"]; +} + +// ########################## +// ### Standard Schema ### +// ########################## + +/** The Standard Schema interface. */ +export interface StandardSchemaV1 { + /** The Standard Schema properties. */ + readonly "~standard": StandardSchemaV1.Props; +} + +export declare namespace StandardSchemaV1 { + /** The Standard Schema properties interface. */ + export interface Props + extends StandardTypedV1.Props { + /** Validates unknown input values. */ + readonly validate: ( + value: unknown, + options?: StandardSchemaV1.Options | undefined + ) => Result | Promise>; + } + + /** The result interface of the validate function. */ + export type Result = SuccessResult | FailureResult; + + /** The result interface if validation succeeds. */ + export interface SuccessResult { + /** The typed output value. */ + readonly value: Output; + /** A falsy value for `issues` indicates success. */ + readonly issues?: undefined; + } + + export interface Options { + /** Explicit support for additional vendor-specific parameters, if needed. */ + readonly libraryOptions?: Record | undefined; + } + + /** The result interface if validation fails. */ + export interface FailureResult { + /** The issues of failed validation. */ + readonly issues: ReadonlyArray; + } + + /** The issue interface of the failure output. */ + export interface Issue { + /** The error message of the issue. */ + readonly message: string; + /** The path of the issue, if any. */ + readonly path?: ReadonlyArray | undefined; + } + + /** The path segment interface of the issue. */ + export interface PathSegment { + /** The key representing a path segment. */ + readonly key: PropertyKey; + } + + /** The Standard types interface. */ + export interface Types + extends StandardTypedV1.Types {} + + /** Infers the input type of a Standard. */ + export type InferInput = + StandardTypedV1.InferInput; + + /** Infers the output type of a Standard. */ + export type InferOutput = + StandardTypedV1.InferOutput; +} + +// ############################### +// ### Standard JSON Schema ### +// ############################### + +/** The Standard JSON Schema interface. */ +export interface StandardJSONSchemaV1 { + /** The Standard JSON Schema properties. */ + readonly "~standard": StandardJSONSchemaV1.Props; +} + +export declare namespace StandardJSONSchemaV1 { + /** The Standard JSON Schema properties interface. */ + export interface Props + extends StandardTypedV1.Props { + /** Methods for generating the input/output JSON Schema. */ + readonly jsonSchema: StandardJSONSchemaV1.Converter; + } + + /** The Standard JSON Schema converter interface. */ + export interface Converter { + /** Converts the input type to JSON Schema. May throw if conversion is not supported. */ + readonly input: ( + options: StandardJSONSchemaV1.Options + ) => Record; + /** Converts the output type to JSON Schema. May throw if conversion is not supported. */ + readonly output: ( + options: StandardJSONSchemaV1.Options + ) => Record; + } + + /** + * The target version of the generated JSON Schema. + * + * It is *strongly recommended* that implementers support `"draft-2020-12"` and `"draft-07"`, as they are both in wide use. All other targets can be implemented on a best-effort basis. Libraries should throw if they don't support a specified target. + * + * The `"openapi-3.0"` target is intended as a standardized specifier for OpenAPI 3.0 which is a superset of JSON Schema `"draft-04"`. + */ + export type Target = + | "draft-2020-12" + | "draft-07" + | "openapi-3.0" + // Accepts any string for future targets while preserving autocomplete + | ({} & string); + + /** The options for the input/output methods. */ + export interface Options { + /** Specifies the target version of the generated JSON Schema. Support for all versions is on a best-effort basis. If a given version is not supported, the library should throw. */ + readonly target: Target; + + /** Explicit support for additional vendor-specific parameters, if needed. */ + readonly libraryOptions?: Record | undefined; + } + + /** The Standard types interface. */ + export interface Types + extends StandardTypedV1.Types {} + + /** Infers the input type of a Standard. */ + export type InferInput = + StandardTypedV1.InferInput; + + /** Infers the output type of a Standard. */ + export type InferOutput = + StandardTypedV1.InferOutput; +} +``` diff --git a/node_modules/@standard-schema/spec/dist/index.cjs b/node_modules/@standard-schema/spec/dist/index.cjs new file mode 100644 index 00000000..321666eb --- /dev/null +++ b/node_modules/@standard-schema/spec/dist/index.cjs @@ -0,0 +1,18 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +module.exports = __toCommonJS(src_exports); diff --git a/node_modules/@standard-schema/spec/dist/index.d.cts b/node_modules/@standard-schema/spec/dist/index.d.cts new file mode 100644 index 00000000..5e4acaad --- /dev/null +++ b/node_modules/@standard-schema/spec/dist/index.d.cts @@ -0,0 +1,119 @@ +/** The Standard Typed interface. This is a base type extended by other specs. */ +interface StandardTypedV1 { + /** The Standard properties. */ + readonly "~standard": StandardTypedV1.Props; +} +declare namespace StandardTypedV1 { + /** The Standard Typed properties interface. */ + interface Props { + /** The version number of the standard. */ + readonly version: 1; + /** The vendor name of the schema library. */ + readonly vendor: string; + /** Inferred types associated with the schema. */ + readonly types?: Types | undefined; + } + /** The Standard Typed types interface. */ + interface Types { + /** The input type of the schema. */ + readonly input: Input; + /** The output type of the schema. */ + readonly output: Output; + } + /** Infers the input type of a Standard Typed. */ + type InferInput = NonNullable["input"]; + /** Infers the output type of a Standard Typed. */ + type InferOutput = NonNullable["output"]; +} +/** The Standard Schema interface. */ +interface StandardSchemaV1 { + /** The Standard Schema properties. */ + readonly "~standard": StandardSchemaV1.Props; +} +declare namespace StandardSchemaV1 { + /** The Standard Schema properties interface. */ + interface Props extends StandardTypedV1.Props { + /** Validates unknown input values. */ + readonly validate: (value: unknown, options?: StandardSchemaV1.Options | undefined) => Result | Promise>; + } + /** The result interface of the validate function. */ + type Result = SuccessResult | FailureResult; + /** The result interface if validation succeeds. */ + interface SuccessResult { + /** The typed output value. */ + readonly value: Output; + /** A falsy value for `issues` indicates success. */ + readonly issues?: undefined; + } + interface Options { + /** Explicit support for additional vendor-specific parameters, if needed. */ + readonly libraryOptions?: Record | undefined; + } + /** The result interface if validation fails. */ + interface FailureResult { + /** The issues of failed validation. */ + readonly issues: ReadonlyArray; + } + /** The issue interface of the failure output. */ + interface Issue { + /** The error message of the issue. */ + readonly message: string; + /** The path of the issue, if any. */ + readonly path?: ReadonlyArray | undefined; + } + /** The path segment interface of the issue. */ + interface PathSegment { + /** The key representing a path segment. */ + readonly key: PropertyKey; + } + /** The Standard types interface. */ + interface Types extends StandardTypedV1.Types { + } + /** Infers the input type of a Standard. */ + type InferInput = StandardTypedV1.InferInput; + /** Infers the output type of a Standard. */ + type InferOutput = StandardTypedV1.InferOutput; +} +/** The Standard JSON Schema interface. */ +interface StandardJSONSchemaV1 { + /** The Standard JSON Schema properties. */ + readonly "~standard": StandardJSONSchemaV1.Props; +} +declare namespace StandardJSONSchemaV1 { + /** The Standard JSON Schema properties interface. */ + interface Props extends StandardTypedV1.Props { + /** Methods for generating the input/output JSON Schema. */ + readonly jsonSchema: StandardJSONSchemaV1.Converter; + } + /** The Standard JSON Schema converter interface. */ + interface Converter { + /** Converts the input type to JSON Schema. May throw if conversion is not supported. */ + readonly input: (options: StandardJSONSchemaV1.Options) => Record; + /** Converts the output type to JSON Schema. May throw if conversion is not supported. */ + readonly output: (options: StandardJSONSchemaV1.Options) => Record; + } + /** + * The target version of the generated JSON Schema. + * + * It is *strongly recommended* that implementers support `"draft-2020-12"` and `"draft-07"`, as they are both in wide use. All other targets can be implemented on a best-effort basis. Libraries should throw if they don't support a specified target. + * + * The `"openapi-3.0"` target is intended as a standardized specifier for OpenAPI 3.0 which is a superset of JSON Schema `"draft-04"`. + */ + type Target = "draft-2020-12" | "draft-07" | "openapi-3.0" | ({} & string); + /** The options for the input/output methods. */ + interface Options { + /** Specifies the target version of the generated JSON Schema. Support for all versions is on a best-effort basis. If a given version is not supported, the library should throw. */ + readonly target: Target; + /** Explicit support for additional vendor-specific parameters, if needed. */ + readonly libraryOptions?: Record | undefined; + } + /** The Standard types interface. */ + interface Types extends StandardTypedV1.Types { + } + /** Infers the input type of a Standard. */ + type InferInput = StandardTypedV1.InferInput; + /** Infers the output type of a Standard. */ + type InferOutput = StandardTypedV1.InferOutput; +} + +export { StandardJSONSchemaV1, StandardSchemaV1, StandardTypedV1 }; diff --git a/node_modules/@standard-schema/spec/dist/index.d.ts b/node_modules/@standard-schema/spec/dist/index.d.ts new file mode 100644 index 00000000..5e4acaad --- /dev/null +++ b/node_modules/@standard-schema/spec/dist/index.d.ts @@ -0,0 +1,119 @@ +/** The Standard Typed interface. This is a base type extended by other specs. */ +interface StandardTypedV1 { + /** The Standard properties. */ + readonly "~standard": StandardTypedV1.Props; +} +declare namespace StandardTypedV1 { + /** The Standard Typed properties interface. */ + interface Props { + /** The version number of the standard. */ + readonly version: 1; + /** The vendor name of the schema library. */ + readonly vendor: string; + /** Inferred types associated with the schema. */ + readonly types?: Types | undefined; + } + /** The Standard Typed types interface. */ + interface Types { + /** The input type of the schema. */ + readonly input: Input; + /** The output type of the schema. */ + readonly output: Output; + } + /** Infers the input type of a Standard Typed. */ + type InferInput = NonNullable["input"]; + /** Infers the output type of a Standard Typed. */ + type InferOutput = NonNullable["output"]; +} +/** The Standard Schema interface. */ +interface StandardSchemaV1 { + /** The Standard Schema properties. */ + readonly "~standard": StandardSchemaV1.Props; +} +declare namespace StandardSchemaV1 { + /** The Standard Schema properties interface. */ + interface Props extends StandardTypedV1.Props { + /** Validates unknown input values. */ + readonly validate: (value: unknown, options?: StandardSchemaV1.Options | undefined) => Result | Promise>; + } + /** The result interface of the validate function. */ + type Result = SuccessResult | FailureResult; + /** The result interface if validation succeeds. */ + interface SuccessResult { + /** The typed output value. */ + readonly value: Output; + /** A falsy value for `issues` indicates success. */ + readonly issues?: undefined; + } + interface Options { + /** Explicit support for additional vendor-specific parameters, if needed. */ + readonly libraryOptions?: Record | undefined; + } + /** The result interface if validation fails. */ + interface FailureResult { + /** The issues of failed validation. */ + readonly issues: ReadonlyArray; + } + /** The issue interface of the failure output. */ + interface Issue { + /** The error message of the issue. */ + readonly message: string; + /** The path of the issue, if any. */ + readonly path?: ReadonlyArray | undefined; + } + /** The path segment interface of the issue. */ + interface PathSegment { + /** The key representing a path segment. */ + readonly key: PropertyKey; + } + /** The Standard types interface. */ + interface Types extends StandardTypedV1.Types { + } + /** Infers the input type of a Standard. */ + type InferInput = StandardTypedV1.InferInput; + /** Infers the output type of a Standard. */ + type InferOutput = StandardTypedV1.InferOutput; +} +/** The Standard JSON Schema interface. */ +interface StandardJSONSchemaV1 { + /** The Standard JSON Schema properties. */ + readonly "~standard": StandardJSONSchemaV1.Props; +} +declare namespace StandardJSONSchemaV1 { + /** The Standard JSON Schema properties interface. */ + interface Props extends StandardTypedV1.Props { + /** Methods for generating the input/output JSON Schema. */ + readonly jsonSchema: StandardJSONSchemaV1.Converter; + } + /** The Standard JSON Schema converter interface. */ + interface Converter { + /** Converts the input type to JSON Schema. May throw if conversion is not supported. */ + readonly input: (options: StandardJSONSchemaV1.Options) => Record; + /** Converts the output type to JSON Schema. May throw if conversion is not supported. */ + readonly output: (options: StandardJSONSchemaV1.Options) => Record; + } + /** + * The target version of the generated JSON Schema. + * + * It is *strongly recommended* that implementers support `"draft-2020-12"` and `"draft-07"`, as they are both in wide use. All other targets can be implemented on a best-effort basis. Libraries should throw if they don't support a specified target. + * + * The `"openapi-3.0"` target is intended as a standardized specifier for OpenAPI 3.0 which is a superset of JSON Schema `"draft-04"`. + */ + type Target = "draft-2020-12" | "draft-07" | "openapi-3.0" | ({} & string); + /** The options for the input/output methods. */ + interface Options { + /** Specifies the target version of the generated JSON Schema. Support for all versions is on a best-effort basis. If a given version is not supported, the library should throw. */ + readonly target: Target; + /** Explicit support for additional vendor-specific parameters, if needed. */ + readonly libraryOptions?: Record | undefined; + } + /** The Standard types interface. */ + interface Types extends StandardTypedV1.Types { + } + /** Infers the input type of a Standard. */ + type InferInput = StandardTypedV1.InferInput; + /** Infers the output type of a Standard. */ + type InferOutput = StandardTypedV1.InferOutput; +} + +export { StandardJSONSchemaV1, StandardSchemaV1, StandardTypedV1 }; diff --git a/node_modules/@standard-schema/spec/dist/index.js b/node_modules/@standard-schema/spec/dist/index.js new file mode 100644 index 00000000..e69de29b diff --git a/node_modules/@standard-schema/spec/package.json b/node_modules/@standard-schema/spec/package.json new file mode 100644 index 00000000..62bb5518 --- /dev/null +++ b/node_modules/@standard-schema/spec/package.json @@ -0,0 +1,52 @@ +{ + "name": "@standard-schema/spec", + "description": "A family of specs for interoperable TypeScript", + "version": "1.1.0", + "license": "MIT", + "author": "Colin McDonnell", + "homepage": "https://standardschema.dev", + "repository": { + "type": "git", + "url": "https://github.com/standard-schema/standard-schema" + }, + "keywords": [ + "typescript", + "schema", + "validation", + "standard", + "interface" + ], + "type": "module", + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "exports": { + ".": { + "standard-schema-spec": "./src/index.ts", + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "require": { + "types": "./dist/index.d.cts", + "default": "./dist/index.cjs" + } + } + }, + "sideEffects": false, + "files": [ + "dist" + ], + "publishConfig": { + "access": "public" + }, + "devDependencies": { + "tsup": "^8.3.0", + "typescript": "^5.6.2" + }, + "scripts": { + "lint": "pnpm biome lint ./src", + "format": "pnpm biome format --write ./src", + "check": "pnpm biome check ./src", + "build": "tsup" + } +} \ No newline at end of file diff --git a/node_modules/@testing-library/dom/LICENSE b/node_modules/@testing-library/dom/LICENSE new file mode 100644 index 00000000..4c43675b --- /dev/null +++ b/node_modules/@testing-library/dom/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) +Copyright (c) 2017 Kent C. Dodds + +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. diff --git a/node_modules/@testing-library/dom/README.md b/node_modules/@testing-library/dom/README.md new file mode 100644 index 00000000..2011260a --- /dev/null +++ b/node_modules/@testing-library/dom/README.md @@ -0,0 +1,402 @@ +
+

DOM Testing Library

+ + + octopus + + +

Simple and complete DOM testing utilities that encourage good testing +practices.

+ +[**Read the docs**](https://testing-library.com/dom) | +[Edit the docs](https://github.com/testing-library/testing-library-docs) + +
+ +
+ + +[![Build Status][build-badge]][build] +[![Code Coverage][coverage-badge]][coverage] +[![version][version-badge]][package] +[![downloads][downloads-badge]][npmtrends] +[![MIT License][license-badge]][license] +[![All Contributors][all-contributors-badge]](#contributors) +[![PRs Welcome][prs-badge]][prs] +[![Code of Conduct][coc-badge]][coc] +[![Discord][discord-badge]][discord] + +[![Watch on GitHub][github-watch-badge]][github-watch] +[![Star on GitHub][github-star-badge]][github-star] +[![Tweet][twitter-badge]][twitter] + + + + +## Table of Contents + + + + +- [The Problem](#the-problem) +- [This Solution](#this-solution) +- [Installation](#installation) +- [Documentation](#documentation) +- [Guiding Principles](#guiding-principles) +- [Contributors](#contributors) +- [LICENSE](#license) + + + +## The Problem + +You want to write maintainable tests for your Web UI. As a part of this goal, +you want your tests to avoid including implementation details of your components +and rather focus on making your tests give you the confidence for which they are +intended. As part of this, you want your testbase to be maintainable in the long +run so refactors of your components (changes to implementation but not +functionality) don't break your tests and slow you and your team down. + +## This Solution + +The `DOM Testing Library` is a very light-weight solution for testing DOM nodes +(whether simulated with [`JSDOM`](https://github.com/jsdom/jsdom) as provided by +default with [Jest][] or in the browser). The main utilities it provides involve +querying the DOM for nodes in a way that's similar to how the user finds +elements on the page. In this way, the library helps ensure your tests give you +confidence in your UI code. The `DOM Testing Library`'s primary guiding +principle is: + +> [The more your tests resemble the way your software is used, the more +> confidence they can give you.][guiding-principle] + +## Installation + +This module is distributed via [npm][npm] which is bundled with [node][node] and +should be installed as one of your project's `devDependencies`: + +``` +npm install --save-dev @testing-library/dom +``` + +> [**Docs**](https://testing-library.com/docs/install) + +## Documentation + +Read the docs (and discover framework and tool-specific implementations) at +[testing-library.com](https://testing-library.com/dom) + +## Guiding Principles + +> [The more your tests resemble the way your software is used, the more +> confidence they can give you.][guiding-principle] + +We try to only expose methods and utilities that encourage you to write tests +that closely resemble how your web pages are used. + +Utilities are included in this project based on the following guiding +principles: + +1. If it relates to rendering components, it deals with DOM nodes rather than + component instances, nor should it encourage dealing with component + instances. +2. It should be generally useful for testing the application components in the + way the user would use it. We _are_ making some trade-offs here because + we're using a computer and often a simulated browser environment, but in + general, utilities should encourage tests that use the components the way + they're intended to be used. +3. Utility implementations and APIs should be simple and flexible. + +At the end of the day, what we want is for this library to be pretty +light-weight, simple, and understandable. + +## Contributors + +Thanks goes to these people ([emoji key][emojis]): + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Kent C. Dodds
Kent C. Dodds

💻 📖 🚇 ⚠️
Greg Bergé
Greg Bergé

🤔
Ryan Castner
Ryan Castner

📖
Daniel Sandiego
Daniel Sandiego

💻
Paweł Mikołajczyk
Paweł Mikołajczyk

💻
Alejandro Ñáñez Ortiz
Alejandro Ñáñez Ortiz

📖
Matt Parrish
Matt Parrish

🐛 💻 📖 ⚠️
Justin Hall
Justin Hall

📦
Anto Aravinth
Anto Aravinth

💻 ⚠️ 📖
Jonah Moses
Jonah Moses

📖
Łukasz Gandecki
Łukasz Gandecki

💻 ⚠️ 📖
Ivan Babak
Ivan Babak

🐛 🤔 💻 📖
Jesse Day
Jesse Day

💻
Ernesto García
Ernesto García

💬 💻 📖
Josef Maxx Blake
Josef Maxx Blake

💻 📖 ⚠️
Alex Cook
Alex Cook

📖 💡 👀
Daniel Cook
Daniel Cook

💻 📖 ⚠️
Thomas Chia
Thomas Chia

🐛 💻
Tim Deschryver
Tim Deschryver

💻 ⚠️ 👀
Alex Krolick
Alex Krolick

💻
Maddi Joyce
Maddi Joyce

💻
Peter Kamps
Peter Kamps

🐛 💻 ⚠️
Jonathan Stoye
Jonathan Stoye

📖 💻
Sanghyeon Lee
Sanghyeon Lee

💡
Justice Mba
Justice Mba

💻 📖 🤔
Wayne Crouch
Wayne Crouch

💻
Ben Elliott
Ben Elliott

💻
Ruben Costa
Ruben Costa

💻
Robert Smith
Robert Smith

🐛 🤔 📖
dadamssg
dadamssg

💻
Neil Kistner
Neil Kistner

💻 ⚠️
Ben Chauvette
Ben Chauvette

💻
Jeff Baumgardt
Jeff Baumgardt

💻 📖
Matan Kushner
Matan Kushner

💻 📖 🤔 ⚠️
Alex Wendte
Alex Wendte

💻 📖 ⚠️
Tamas Fodor
Tamas Fodor

📖
Benjamin Eckardt
Benjamin Eckardt

💻
Ryan Campbell
Ryan Campbell

📖
Taylor Briggs
Taylor Briggs

⚠️
John Gozde
John Gozde

💻
C. T. Lin
C. T. Lin

📖
Terrence Wong
Terrence Wong

💻
Soo Jae Hwang
Soo Jae Hwang

💻
Royston Shufflebotham
Royston Shufflebotham

🐛 💻 📖 ⚠️
Vadim Brodsky
Vadim Brodsky

💻
Eunjae Lee
Eunjae Lee

💻
David Peter
David Peter

💻
Shy Alter
Shy Alter

💻 📖
Łukasz Makuch
Łukasz Makuch

📦
Tyler Haas
Tyler Haas

💻 ⚠️
Vesa Laakso
Vesa Laakso

💻 ⚠️
Tulsi Sapkota
Tulsi Sapkota

💻
Tiago Nunes
Tiago Nunes

💻 ⚠️
JaxCavalera
JaxCavalera

💻 👀
bopfer
bopfer

⚠️
Jan Pfitzner
Jan Pfitzner

💻
David
David

💻
Diego Hernandez
Diego Hernandez

💻 ⚠️
Alex Young
Alex Young

💻
Paul Armstrong
Paul Armstrong

💻 ⚠️
Tamás Szabó
Tamás Szabó

💻 ⚠️
Dylan Piercey
Dylan Piercey

💻 ⚠️
Michael Lasky
Michael Lasky

💻 ⚠️ 📖
Sebastian Silbermann
Sebastian Silbermann

💻 ⚠️ 📖 🚇 👀
Dylan Vann
Dylan Vann

💻
Adrià Fontcuberta
Adrià Fontcuberta

💻 ⚠️ 📖
Thomas Lombart
Thomas Lombart

💻
Sam Horton
Sam Horton

💻 ⚠️
Andrew Hill
Andrew Hill

💻
Jan Amann
Jan Amann

💻 ⚠️
Brais Piñeiro
Brais Piñeiro

💻 ⚠️
Dominykas Blyžė
Dominykas Blyžė

💻 ⚠️
Olzhas Askar
Olzhas Askar

💻 ⚠️ 📖
Max Belsky
Max Belsky

💻 ⚠️
Michael Mantel
Michael Mantel

⚠️
Tom Nagle
Tom Nagle

💻
Westbrook Johnson
Westbrook Johnson

💻
Mohammad Aziz
Mohammad Aziz

💻 ⚠️
seetdev
seetdev

⚠️ 💻
Xavier Garcia Buils
Xavier Garcia Buils

💻 ⚠️
aw-davidson
aw-davidson

💻 ⚠️
Michaël De Boey
Michaël De Boey

💻
Minh Nguyen
Minh Nguyen

💻
Egill Sveinbjörnsson
Egill Sveinbjörnsson

💻
Pavel Pustovalov
Pavel Pustovalov

📖
Adam Palaniuk
Adam Palaniuk

💻 ⚠️
Yama-Tomo
Yama-Tomo

💻 ⚠️
Aaron Pettengill
Aaron Pettengill

💻 ⚠️
Kate W. Boyd
Kate W. Boyd

💻
Rahul Suryakanth
Rahul Suryakanth

💻 ⚠️
Jamie
Jamie

💻 ⚠️
Nicolas Stepien
Nicolas Stepien

💻
Ken Powers
Ken Powers

💻
Michał Zdunek
Michał Zdunek

💻
Ali Nasserzadeh
Ali Nasserzadeh

💻
Darek Kay
Darek Kay

📖 💻 ⚠️
Lukas
Lukas

💻 ⚠️
Tom Crockett
Tom Crockett

💻 ⚠️
Kevin Brewer
Kevin Brewer

💻 ⚠️
Ben Monro
Ben Monro

💻 🤔 ⚠️ 📖
Stephan Meijer
Stephan Meijer

🤔 💻 ⚠️
João Forja
João Forja

💻 ⚠️
Nick McCurdy
Nick McCurdy

📖 💻 ⚠️ 👀 🚇
Caleb Meredith
Caleb Meredith

💻
Marco Moretti
Marco Moretti

💻 ⚠️ 👀
Travis Jefferson
Travis Jefferson

💻 ⚠️
Maciej Jastrzebski
Maciej Jastrzebski

🐛
Geoff Harcourt
Geoff Harcourt

💻
Josh Goldberg
Josh Goldberg

💻 ⚠️
Ken Gregory
Ken Gregory

💻 ⚠️
Jacob Paris
Jacob Paris

💻 ⚠️
keiya sasaki
keiya sasaki

📖
Idan Entin
Idan Entin

💻 ⚠️
Deniz Susman
Deniz Susman

💻
Bianca Del Carretto
Bianca Del Carretto

⚠️ 💻
Josh Lalonde
Josh Lalonde

💻 ⚠️
Ioannis Papadopoulos
Ioannis Papadopoulos

💻 ⚠️
Maxwell Newlands
Maxwell Newlands

💻 ⚠️
Jared Luxenberg
Jared Luxenberg

💻 ⚠️
snizhana
snizhana

💻 ⚠️
Michael van Engelshoven
Michael van Engelshoven

👀
Asher Tuggle
Asher Tuggle

🐛
Winter LaMon
Winter LaMon

💻 ⚠️
Victor Cordova
Victor Cordova

💻 ⚠️
slowselfip
slowselfip

🐛
Dmitry Semigradsky
Dmitry Semigradsky

💻
Adam
Adam

💻 ⚠️
balavishnuvj
balavishnuvj

💻
Chris Colborne
Chris Colborne

💻
Romain Trotard
Romain Trotard

💻
Thomas Marshall
Thomas Marshall

💻 ⚠️
johnjessewood
johnjessewood

🐛 💻
Ari Perkkiö
Ari Perkkiö

🐛 💻 📖
Nathan Force
Nathan Force

💻
Philipp Fritsche
Philipp Fritsche

💻
Renato Alencar
Renato Alencar

💻 ⚠️
Simen Bekkhus
Simen Bekkhus

🐛
Dan Abramov
Dan Abramov

🐛 👀
Matan Borenkraout
Matan Borenkraout

💻
simcha90
simcha90

💻
Amit Miran
Amit Miran

🚇
Dominik Lesch
Dominik Lesch

📖
Gareth Jones
Gareth Jones

💻 ⚠️
Rayat Rahman
Rayat Rahman

💻
Nik Savchenko
Nik Savchenko

💻
Kevin Fleischman
Kevin Fleischman

💻 ⚠️
Beth Hitch
Beth Hitch

💻
Jack Laurence
Jack Laurence

💻
SantoJambit
SantoJambit

💻
Yashu Mittal
Yashu Mittal

📖
Ian VanSchooten
Ian VanSchooten

💻
Vanya Prokopovich
Vanya Prokopovich

🐛
James Nail
James Nail

🐛
Rob Caldecott
Rob Caldecott

🐛
Dennis273
Dennis273

💻
Jackson Hardaker
Jackson Hardaker

⚠️
Robin Drexler
Robin Drexler

💻
Omer Dolev
Omer Dolev

💻
Lirlev48
Lirlev48

💻
Tarnay Kálmán
Tarnay Kálmán

💻
Than Hutchins
Than Hutchins

💻
Raphaël LEMIEUX
Raphaël LEMIEUX

💻
Arthur Lauck Vilas Boas
Arthur Lauck Vilas Boas

📖
Daniel Acuña
Daniel Acuña

💻
Craig Morten
Craig Morten

💻 💬
Naor Peled
Naor Peled

💻
Julien Wajsberg
Julien Wajsberg

💻 🐛
Kevin BON
Kevin BON

💻 🐛
sieem
sieem

💻
+ + + + + + +This project follows the [all-contributors][all-contributors] specification. +Contributions of any kind welcome! + +## LICENSE + +[MIT](LICENSE) + + + +[npm]: https://www.npmjs.com/ +[node]: https://nodejs.org +[build-badge]: https://img.shields.io/github/workflow/status/testing-library/dom-testing-library/validate?logo=github&style=flat-square +[build]: https://github.com/testing-library/dom-testing-library/actions?query=workflow%3Avalidate +[coverage-badge]: https://img.shields.io/codecov/c/github/testing-library/dom-testing-library.svg?style=flat-square +[coverage]: https://codecov.io/github/testing-library/dom-testing-library +[version-badge]: https://img.shields.io/npm/v/@testing-library/dom.svg?style=flat-square +[package]: https://www.npmjs.com/package/@testing-library/dom +[downloads-badge]: https://img.shields.io/npm/dm/@testing-library/dom.svg?style=flat-square +[npmtrends]: http://www.npmtrends.com/@testing-library/dom +[license-badge]: https://img.shields.io/npm/l/@testing-library/dom.svg?style=flat-square +[license]: https://github.com/testing-library/dom-testing-library/blob/main/LICENSE +[prs-badge]: https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square +[prs]: http://makeapullrequest.com +[coc-badge]: https://img.shields.io/badge/code%20of-conduct-ff69b4.svg?style=flat-square +[coc]: https://github.com/testing-library/dom-testing-library/blob/main/CODE_OF_CONDUCT.md +[github-watch-badge]: https://img.shields.io/github/watchers/testing-library/dom-testing-library.svg?style=social +[github-watch]: https://github.com/testing-library/dom-testing-library/watchers +[github-star-badge]: https://img.shields.io/github/stars/testing-library/dom-testing-library.svg?style=social +[github-star]: https://github.com/testing-library/dom-testing-library/stargazers +[twitter]: https://twitter.com/intent/tweet?text=Check%20out%20dom-testing-library%20by%20%40testing-library%20https%3A%2F%2Fgithub.com%2Ftesting-library%2Fdom-testing-library%20%F0%9F%91%8D +[twitter-badge]: https://img.shields.io/twitter/url/https/github.com/testing-library/dom-testing-library.svg?style=social +[emojis]: https://github.com/all-contributors/all-contributors#emoji-key +[all-contributors]: https://github.com/all-contributors/all-contributors +[all-contributors-badge]: https://img.shields.io/github/all-contributors/testing-library/dom-testing-library?color=orange&style=flat-square +[set-immediate]: https://developer.mozilla.org/en-US/docs/Web/API/Window/setImmediate +[guiding-principle]: https://twitter.com/kentcdodds/status/977018512689455106 +[jest]: https://facebook.github.io/jest +[discord-badge]: https://img.shields.io/discord/723559267868737556.svg?color=7389D8&labelColor=6A7EC2&logo=discord&logoColor=ffffff&style=flat-square +[discord]: https://discord.gg/testing-library + + diff --git a/node_modules/@testing-library/dom/dist/@testing-library/dom.cjs.js b/node_modules/@testing-library/dom/dist/@testing-library/dom.cjs.js new file mode 100644 index 00000000..d23e7ab1 --- /dev/null +++ b/node_modules/@testing-library/dom/dist/@testing-library/dom.cjs.js @@ -0,0 +1,2951 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var prettyFormat = require('pretty-format'); +var domAccessibilityApi = require('dom-accessibility-api'); +var ariaQuery = require('aria-query'); +var lzString = require('lz-string'); + +function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + +function _interopNamespace(e) { + if (e && e.__esModule) return e; + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n["default"] = e; + return Object.freeze(n); +} + +var prettyFormat__namespace = /*#__PURE__*/_interopNamespace(prettyFormat); +var lzString__default = /*#__PURE__*/_interopDefaultLegacy(lzString); + +/** + * Source: https://github.com/facebook/jest/blob/e7bb6a1e26ffab90611b2593912df15b69315611/packages/pretty-format/src/plugins/DOMElement.ts + */ +/* eslint-disable -- trying to stay as close to the original as possible */ +/* istanbul ignore file */ + +function escapeHTML(str) { + return str.replace(//g, '>'); +} +// Return empty string if keys is empty. +const printProps = (keys, props, config, indentation, depth, refs, printer) => { + const indentationNext = indentation + config.indent; + const colors = config.colors; + return keys.map(key => { + const value = props[key]; + let printed = printer(value, config, indentationNext, depth, refs); + if (typeof value !== 'string') { + if (printed.indexOf('\n') !== -1) { + printed = config.spacingOuter + indentationNext + printed + config.spacingOuter + indentation; + } + printed = '{' + printed + '}'; + } + return config.spacingInner + indentation + colors.prop.open + key + colors.prop.close + '=' + colors.value.open + printed + colors.value.close; + }).join(''); +}; + +// https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType#node_type_constants +const NodeTypeTextNode = 3; + +// Return empty string if children is empty. +const printChildren = (children, config, indentation, depth, refs, printer) => children.map(child => { + const printedChild = typeof child === 'string' ? printText(child, config) : printer(child, config, indentation, depth, refs); + if (printedChild === '' && typeof child === 'object' && child !== null && child.nodeType !== NodeTypeTextNode) { + // A plugin serialized this Node to '' meaning we should ignore it. + return ''; + } + return config.spacingOuter + indentation + printedChild; +}).join(''); +const printText = (text, config) => { + const contentColor = config.colors.content; + return contentColor.open + escapeHTML(text) + contentColor.close; +}; +const printComment = (comment, config) => { + const commentColor = config.colors.comment; + return commentColor.open + '' + commentColor.close; +}; + +// Separate the functions to format props, children, and element, +// so a plugin could override a particular function, if needed. +// Too bad, so sad: the traditional (but unnecessary) space +// in a self-closing tagColor requires a second test of printedProps. +const printElement = (type, printedProps, printedChildren, config, indentation) => { + const tagColor = config.colors.tag; + return tagColor.open + '<' + type + (printedProps && tagColor.close + printedProps + config.spacingOuter + indentation + tagColor.open) + (printedChildren ? '>' + tagColor.close + printedChildren + config.spacingOuter + indentation + tagColor.open + '' + tagColor.close; +}; +const printElementAsLeaf = (type, config) => { + const tagColor = config.colors.tag; + return tagColor.open + '<' + type + tagColor.close + ' …' + tagColor.open + ' />' + tagColor.close; +}; +const ELEMENT_NODE$1 = 1; +const TEXT_NODE$1 = 3; +const COMMENT_NODE$1 = 8; +const FRAGMENT_NODE = 11; +const ELEMENT_REGEXP = /^((HTML|SVG)\w*)?Element$/; +const isCustomElement = val => { + const { + tagName + } = val; + return Boolean(typeof tagName === 'string' && tagName.includes('-') || typeof val.hasAttribute === 'function' && val.hasAttribute('is')); +}; +const testNode = val => { + const constructorName = val.constructor.name; + const { + nodeType + } = val; + return nodeType === ELEMENT_NODE$1 && (ELEMENT_REGEXP.test(constructorName) || isCustomElement(val)) || nodeType === TEXT_NODE$1 && constructorName === 'Text' || nodeType === COMMENT_NODE$1 && constructorName === 'Comment' || nodeType === FRAGMENT_NODE && constructorName === 'DocumentFragment'; +}; +function nodeIsText(node) { + return node.nodeType === TEXT_NODE$1; +} +function nodeIsComment(node) { + return node.nodeType === COMMENT_NODE$1; +} +function nodeIsFragment(node) { + return node.nodeType === FRAGMENT_NODE; +} +function createDOMElementFilter(filterNode) { + return { + test: val => { + var _val$constructor2; + return ((val == null || (_val$constructor2 = val.constructor) == null ? void 0 : _val$constructor2.name) || isCustomElement(val)) && testNode(val); + }, + serialize: (node, config, indentation, depth, refs, printer) => { + if (nodeIsText(node)) { + return printText(node.data, config); + } + if (nodeIsComment(node)) { + return printComment(node.data, config); + } + const type = nodeIsFragment(node) ? "DocumentFragment" : node.tagName.toLowerCase(); + if (++depth > config.maxDepth) { + return printElementAsLeaf(type, config); + } + return printElement(type, printProps(nodeIsFragment(node) ? [] : Array.from(node.attributes).map(attr => attr.name).sort(), nodeIsFragment(node) ? {} : Array.from(node.attributes).reduce((props, attribute) => { + props[attribute.name] = attribute.value; + return props; + }, {}), config, indentation + config.indent, depth, refs, printer), printChildren(Array.prototype.slice.call(node.childNodes || node.children).filter(filterNode), config, indentation + config.indent, depth, refs, printer), config, indentation); + } + }; +} + +// We try to load node dependencies +let picocolors = null; +let readFileSync = null; +let codeFrameColumns = null; +try { + const nodeRequire = module && module.require; + readFileSync = nodeRequire.call(module, 'fs').readFileSync; + codeFrameColumns = nodeRequire.call(module, '@babel/code-frame').codeFrameColumns; + picocolors = nodeRequire.call(module, 'picocolors'); +} catch { + // We're in a browser environment +} + +// frame has the form "at myMethod (location/to/my/file.js:10:2)" +function getCodeFrame(frame) { + const locationStart = frame.indexOf('(') + 1; + const locationEnd = frame.indexOf(')'); + const frameLocation = frame.slice(locationStart, locationEnd); + const frameLocationElements = frameLocation.split(':'); + const [filename, line, column] = [frameLocationElements[0], parseInt(frameLocationElements[1], 10), parseInt(frameLocationElements[2], 10)]; + let rawFileContents = ''; + try { + rawFileContents = readFileSync(filename, 'utf-8'); + } catch { + return ''; + } + const codeFrame = codeFrameColumns(rawFileContents, { + start: { + line, + column + } + }, { + highlightCode: true, + linesBelow: 0 + }); + return picocolors.dim(frameLocation) + "\n" + codeFrame + "\n"; +} +function getUserCodeFrame() { + // If we couldn't load dependencies, we can't generate the user trace + /* istanbul ignore next */ + if (!readFileSync || !codeFrameColumns) { + return ''; + } + const err = new Error(); + const firstClientCodeFrame = err.stack.split('\n').slice(1) // Remove first line which has the form "Error: TypeError" + .find(frame => !frame.includes('node_modules/')); // Ignore frames from 3rd party libraries + + return getCodeFrame(firstClientCodeFrame); +} + +// Constant node.nodeType for text nodes, see: +// https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType#Node_type_constants +const TEXT_NODE = 3; +function jestFakeTimersAreEnabled() { + /* istanbul ignore else */ + // eslint-disable-next-line + if (typeof jest !== 'undefined' && jest !== null) { + return ( + // legacy timers + setTimeout._isMockFunction === true || + // modern timers + // eslint-disable-next-line prefer-object-has-own -- not supported by our support matrix + Object.prototype.hasOwnProperty.call(setTimeout, 'clock') + ); + } + // istanbul ignore next + return false; +} +function getDocument() { + /* istanbul ignore if */ + if (typeof window === 'undefined') { + throw new Error('Could not find default container'); + } + return window.document; +} +function getWindowFromNode(node) { + if (node.defaultView) { + // node is document + return node.defaultView; + } else if (node.ownerDocument && node.ownerDocument.defaultView) { + // node is a DOM node + return node.ownerDocument.defaultView; + } else if (node.window) { + // node is window + return node.window; + } else if (node.ownerDocument && node.ownerDocument.defaultView === null) { + throw new Error("It looks like the window object is not available for the provided node."); + } else if (node.then instanceof Function) { + throw new Error("It looks like you passed a Promise object instead of a DOM node. Did you do something like `fireEvent.click(screen.findBy...` when you meant to use a `getBy` query `fireEvent.click(screen.getBy...`, or await the findBy query `fireEvent.click(await screen.findBy...`?"); + } else if (Array.isArray(node)) { + throw new Error("It looks like you passed an Array instead of a DOM node. Did you do something like `fireEvent.click(screen.getAllBy...` when you meant to use a `getBy` query `fireEvent.click(screen.getBy...`?"); + } else if (typeof node.debug === 'function' && typeof node.logTestingPlaygroundURL === 'function') { + throw new Error("It looks like you passed a `screen` object. Did you do something like `fireEvent.click(screen, ...` when you meant to use a query, e.g. `fireEvent.click(screen.getBy..., `?"); + } else { + // The user passed something unusual to a calling function + throw new Error("The given node is not an Element, the node type is: " + typeof node + "."); + } +} +function checkContainerType(container) { + if (!container || !(typeof container.querySelector === 'function') || !(typeof container.querySelectorAll === 'function')) { + throw new TypeError("Expected container to be an Element, a Document or a DocumentFragment but got " + getTypeName(container) + "."); + } + function getTypeName(object) { + if (typeof object === 'object') { + return object === null ? 'null' : object.constructor.name; + } + return typeof object; + } +} + +const shouldHighlight = () => { + if (typeof process === 'undefined') { + // Don't colorize in non-node environments (e.g. Browsers) + return false; + } + let colors; + // Try to safely parse env COLORS: We will default behavior if any step fails. + try { + var _process$env; + const colorsJSON = (_process$env = process.env) == null ? void 0 : _process$env.COLORS; + if (colorsJSON) { + colors = JSON.parse(colorsJSON); + } + } catch { + // If this throws, process.env?.COLORS wasn't parsable. Since we only + // care about `true` or `false`, we can safely ignore the error. + } + if (typeof colors === 'boolean') { + // If `colors` is set explicitly (both `true` and `false`), use that value. + return colors; + } else { + // If `colors` is not set, colorize if we're in node. + return process.versions !== undefined && process.versions.node !== undefined; + } +}; +const { + DOMCollection +} = prettyFormat__namespace.plugins; + +// https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType#node_type_constants +const ELEMENT_NODE = 1; +const COMMENT_NODE = 8; + +// https://github.com/facebook/jest/blob/615084195ae1ae61ddd56162c62bbdda17587569/packages/pretty-format/src/plugins/DOMElement.ts#L50 +function filterCommentsAndDefaultIgnoreTagsTags(value) { + return value.nodeType !== COMMENT_NODE && (value.nodeType !== ELEMENT_NODE || !value.matches(getConfig().defaultIgnore)); +} +function prettyDOM(dom, maxLength, options) { + if (options === void 0) { + options = {}; + } + if (!dom) { + dom = getDocument().body; + } + if (typeof maxLength !== 'number') { + maxLength = typeof process !== 'undefined' && typeof process.env !== 'undefined' && process.env.DEBUG_PRINT_LIMIT || 7000; + } + if (maxLength === 0) { + return ''; + } + if (dom.documentElement) { + dom = dom.documentElement; + } + let domTypeName = typeof dom; + if (domTypeName === 'object') { + domTypeName = dom.constructor.name; + } else { + // To don't fall with `in` operator + dom = {}; + } + if (!('outerHTML' in dom)) { + throw new TypeError("Expected an element or document but got " + domTypeName); + } + const { + filterNode = filterCommentsAndDefaultIgnoreTagsTags, + ...prettyFormatOptions + } = options; + const debugContent = prettyFormat__namespace.format(dom, { + plugins: [createDOMElementFilter(filterNode), DOMCollection], + printFunctionName: false, + highlight: shouldHighlight(), + ...prettyFormatOptions + }); + return maxLength !== undefined && dom.outerHTML.length > maxLength ? debugContent.slice(0, maxLength) + "..." : debugContent; +} +const logDOM = function () { + const userCodeFrame = getUserCodeFrame(); + if (userCodeFrame) { + console.log(prettyDOM(...arguments) + "\n\n" + userCodeFrame); + } else { + console.log(prettyDOM(...arguments)); + } +}; + +// It would be cleaner for this to live inside './queries', but +// other parts of the code assume that all exports from +// './queries' are query functions. +let config = { + testIdAttribute: 'data-testid', + asyncUtilTimeout: 1000, + // asyncWrapper and advanceTimersWrapper is to support React's async `act` function. + // forcing react-testing-library to wrap all async functions would've been + // a total nightmare (consider wrapping every findBy* query and then also + // updating `within` so those would be wrapped too. Total nightmare). + // so we have this config option that's really only intended for + // react-testing-library to use. For that reason, this feature will remain + // undocumented. + asyncWrapper: cb => cb(), + unstable_advanceTimersWrapper: cb => cb(), + eventWrapper: cb => cb(), + // default value for the `hidden` option in `ByRole` queries + defaultHidden: false, + // default value for the `ignore` option in `ByText` queries + defaultIgnore: 'script, style', + // showOriginalStackTrace flag to show the full error stack traces for async errors + showOriginalStackTrace: false, + // throw errors w/ suggestions for better queries. Opt in so off by default. + throwSuggestions: false, + // called when getBy* queries fail. (message, container) => Error + getElementError(message, container) { + const prettifiedDOM = prettyDOM(container); + const error = new Error([message, "Ignored nodes: comments, " + config.defaultIgnore + "\n" + prettifiedDOM].filter(Boolean).join('\n\n')); + error.name = 'TestingLibraryElementError'; + return error; + }, + _disableExpensiveErrorDiagnostics: false, + computedStyleSupportsPseudoElements: false +}; +function runWithExpensiveErrorDiagnosticsDisabled(callback) { + try { + config._disableExpensiveErrorDiagnostics = true; + return callback(); + } finally { + config._disableExpensiveErrorDiagnostics = false; + } +} +function configure(newConfig) { + if (typeof newConfig === 'function') { + // Pass the existing config out to the provided function + // and accept a delta in return + newConfig = newConfig(config); + } + + // Merge the incoming config delta + config = { + ...config, + ...newConfig + }; +} +function getConfig() { + return config; +} + +const labelledNodeNames = ['button', 'meter', 'output', 'progress', 'select', 'textarea', 'input']; +function getTextContent(node) { + if (labelledNodeNames.includes(node.nodeName.toLowerCase())) { + return ''; + } + if (node.nodeType === TEXT_NODE) return node.textContent; + return Array.from(node.childNodes).map(childNode => getTextContent(childNode)).join(''); +} +function getLabelContent(element) { + let textContent; + if (element.tagName.toLowerCase() === 'label') { + textContent = getTextContent(element); + } else { + textContent = element.value || element.textContent; + } + return textContent; +} + +// Based on https://github.com/eps1lon/dom-accessibility-api/pull/352 +function getRealLabels(element) { + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- types are not aware of older browsers that don't implement `labels` + if (element.labels !== undefined) { + var _labels; + return (_labels = element.labels) != null ? _labels : []; + } + if (!isLabelable(element)) return []; + const labels = element.ownerDocument.querySelectorAll('label'); + return Array.from(labels).filter(label => label.control === element); +} +function isLabelable(element) { + return /BUTTON|METER|OUTPUT|PROGRESS|SELECT|TEXTAREA/.test(element.tagName) || element.tagName === 'INPUT' && element.getAttribute('type') !== 'hidden'; +} +function getLabels(container, element, _temp) { + let { + selector = '*' + } = _temp === void 0 ? {} : _temp; + const ariaLabelledBy = element.getAttribute('aria-labelledby'); + const labelsId = ariaLabelledBy ? ariaLabelledBy.split(' ') : []; + return labelsId.length ? labelsId.map(labelId => { + const labellingElement = container.querySelector("[id=\"" + labelId + "\"]"); + return labellingElement ? { + content: getLabelContent(labellingElement), + formControl: null + } : { + content: '', + formControl: null + }; + }) : Array.from(getRealLabels(element)).map(label => { + const textToMatch = getLabelContent(label); + const formControlSelector = 'button, input, meter, output, progress, select, textarea'; + const labelledFormControl = Array.from(label.querySelectorAll(formControlSelector)).filter(formControlElement => formControlElement.matches(selector))[0]; + return { + content: textToMatch, + formControl: labelledFormControl + }; + }); +} + +function assertNotNullOrUndefined(matcher) { + if (matcher === null || matcher === undefined) { + throw new Error(// eslint-disable-next-line @typescript-eslint/restrict-template-expressions -- implicitly converting `T` to `string` + "It looks like " + matcher + " was passed instead of a matcher. Did you do something like getByText(" + matcher + ")?"); + } +} +function fuzzyMatches(textToMatch, node, matcher, normalizer) { + if (typeof textToMatch !== 'string') { + return false; + } + assertNotNullOrUndefined(matcher); + const normalizedText = normalizer(textToMatch); + if (typeof matcher === 'string' || typeof matcher === 'number') { + return normalizedText.toLowerCase().includes(matcher.toString().toLowerCase()); + } else if (typeof matcher === 'function') { + return matcher(normalizedText, node); + } else { + return matchRegExp(matcher, normalizedText); + } +} +function matches(textToMatch, node, matcher, normalizer) { + if (typeof textToMatch !== 'string') { + return false; + } + assertNotNullOrUndefined(matcher); + const normalizedText = normalizer(textToMatch); + if (matcher instanceof Function) { + return matcher(normalizedText, node); + } else if (matcher instanceof RegExp) { + return matchRegExp(matcher, normalizedText); + } else { + return normalizedText === String(matcher); + } +} +function getDefaultNormalizer(_temp) { + let { + trim = true, + collapseWhitespace = true + } = _temp === void 0 ? {} : _temp; + return text => { + let normalizedText = text; + normalizedText = trim ? normalizedText.trim() : normalizedText; + normalizedText = collapseWhitespace ? normalizedText.replace(/\s+/g, ' ') : normalizedText; + return normalizedText; + }; +} + +/** + * Constructs a normalizer to pass to functions in matches.js + * @param {boolean|undefined} trim The user-specified value for `trim`, without + * any defaulting having been applied + * @param {boolean|undefined} collapseWhitespace The user-specified value for + * `collapseWhitespace`, without any defaulting having been applied + * @param {Function|undefined} normalizer The user-specified normalizer + * @returns {Function} A normalizer + */ + +function makeNormalizer(_ref) { + let { + trim, + collapseWhitespace, + normalizer + } = _ref; + if (!normalizer) { + // No custom normalizer specified. Just use default. + return getDefaultNormalizer({ + trim, + collapseWhitespace + }); + } + if (typeof trim !== 'undefined' || typeof collapseWhitespace !== 'undefined') { + // They've also specified a value for trim or collapseWhitespace + throw new Error('trim and collapseWhitespace are not supported with a normalizer. ' + 'If you want to use the default trim and collapseWhitespace logic in your normalizer, ' + 'use "getDefaultNormalizer({trim, collapseWhitespace})" and compose that into your normalizer'); + } + return normalizer; +} +function matchRegExp(matcher, text) { + const match = matcher.test(text); + if (matcher.global && matcher.lastIndex !== 0) { + console.warn("To match all elements we had to reset the lastIndex of the RegExp because the global flag is enabled. We encourage to remove the global flag from the RegExp."); + matcher.lastIndex = 0; + } + return match; +} + +function getNodeText(node) { + if (node.matches('input[type=submit], input[type=button], input[type=reset]')) { + return node.value; + } + return Array.from(node.childNodes).filter(child => child.nodeType === TEXT_NODE && Boolean(child.textContent)).map(c => c.textContent).join(''); +} + +const elementRoleList = buildElementRoleList(ariaQuery.elementRoles); + +/** + * @param {Element} element - + * @returns {boolean} - `true` if `element` and its subtree are inaccessible + */ +function isSubtreeInaccessible(element) { + if (element.hidden === true) { + return true; + } + if (element.getAttribute('aria-hidden') === 'true') { + return true; + } + const window = element.ownerDocument.defaultView; + if (window.getComputedStyle(element).display === 'none') { + return true; + } + return false; +} + +/** + * Partial implementation https://www.w3.org/TR/wai-aria-1.2/#tree_exclusion + * which should only be used for elements with a non-presentational role i.e. + * `role="none"` and `role="presentation"` will not be excluded. + * + * Implements aria-hidden semantics (i.e. parent overrides child) + * Ignores "Child Presentational: True" characteristics + * + * @param {Element} element - + * @param {object} [options] - + * @param {function (element: Element): boolean} options.isSubtreeInaccessible - + * can be used to return cached results from previous isSubtreeInaccessible calls + * @returns {boolean} true if excluded, otherwise false + */ +function isInaccessible(element, options) { + if (options === void 0) { + options = {}; + } + const { + isSubtreeInaccessible: isSubtreeInaccessibleImpl = isSubtreeInaccessible + } = options; + const window = element.ownerDocument.defaultView; + // since visibility is inherited we can exit early + if (window.getComputedStyle(element).visibility === 'hidden') { + return true; + } + let currentElement = element; + while (currentElement) { + if (isSubtreeInaccessibleImpl(currentElement)) { + return true; + } + currentElement = currentElement.parentElement; + } + return false; +} +function getImplicitAriaRoles(currentNode) { + // eslint bug here: + // eslint-disable-next-line no-unused-vars + for (const { + match, + roles + } of elementRoleList) { + if (match(currentNode)) { + return [...roles]; + } + } + return []; +} +function buildElementRoleList(elementRolesMap) { + function makeElementSelector(_ref) { + let { + name, + attributes + } = _ref; + return "" + name + attributes.map(_ref2 => { + let { + name: attributeName, + value, + constraints = [] + } = _ref2; + const shouldNotExist = constraints.indexOf('undefined') !== -1; + const shouldBeNonEmpty = constraints.indexOf('set') !== -1; + const hasExplicitValue = typeof value !== 'undefined'; + if (hasExplicitValue) { + return "[" + attributeName + "=\"" + value + "\"]"; + } else if (shouldNotExist) { + return ":not([" + attributeName + "])"; + } else if (shouldBeNonEmpty) { + return "[" + attributeName + "]:not([" + attributeName + "=\"\"])"; + } + return "[" + attributeName + "]"; + }).join(''); + } + function getSelectorSpecificity(_ref3) { + let { + attributes = [] + } = _ref3; + return attributes.length; + } + function bySelectorSpecificity(_ref4, _ref5) { + let { + specificity: leftSpecificity + } = _ref4; + let { + specificity: rightSpecificity + } = _ref5; + return rightSpecificity - leftSpecificity; + } + function match(element) { + let { + attributes = [] + } = element; + + // https://github.com/testing-library/dom-testing-library/issues/814 + const typeTextIndex = attributes.findIndex(attribute => attribute.value && attribute.name === 'type' && attribute.value === 'text'); + if (typeTextIndex >= 0) { + // not using splice to not mutate the attributes array + attributes = [...attributes.slice(0, typeTextIndex), ...attributes.slice(typeTextIndex + 1)]; + } + const selector = makeElementSelector({ + ...element, + attributes + }); + return node => { + if (typeTextIndex >= 0 && node.type !== 'text') { + return false; + } + return node.matches(selector); + }; + } + let result = []; + + // eslint bug here: + // eslint-disable-next-line no-unused-vars + for (const [element, roles] of elementRolesMap.entries()) { + result = [...result, { + match: match(element), + roles: Array.from(roles), + specificity: getSelectorSpecificity(element) + }]; + } + return result.sort(bySelectorSpecificity); +} +function getRoles(container, _temp) { + let { + hidden = false + } = _temp === void 0 ? {} : _temp; + function flattenDOM(node) { + return [node, ...Array.from(node.children).reduce((acc, child) => [...acc, ...flattenDOM(child)], [])]; + } + return flattenDOM(container).filter(element => { + return hidden === false ? isInaccessible(element) === false : true; + }).reduce((acc, node) => { + let roles = []; + // TODO: This violates html-aria which does not allow any role on every element + if (node.hasAttribute('role')) { + roles = node.getAttribute('role').split(' ').slice(0, 1); + } else { + roles = getImplicitAriaRoles(node); + } + return roles.reduce((rolesAcc, role) => Array.isArray(rolesAcc[role]) ? { + ...rolesAcc, + [role]: [...rolesAcc[role], node] + } : { + ...rolesAcc, + [role]: [node] + }, acc); + }, {}); +} +function prettyRoles(dom, _ref6) { + let { + hidden, + includeDescription + } = _ref6; + const roles = getRoles(dom, { + hidden + }); + // We prefer to skip generic role, we don't recommend it + return Object.entries(roles).filter(_ref7 => { + let [role] = _ref7; + return role !== 'generic'; + }).map(_ref8 => { + let [role, elements] = _ref8; + const delimiterBar = '-'.repeat(50); + const elementsString = elements.map(el => { + const nameString = "Name \"" + domAccessibilityApi.computeAccessibleName(el, { + computedStyleSupportsPseudoElements: getConfig().computedStyleSupportsPseudoElements + }) + "\":\n"; + const domString = prettyDOM(el.cloneNode(false)); + if (includeDescription) { + const descriptionString = "Description \"" + domAccessibilityApi.computeAccessibleDescription(el, { + computedStyleSupportsPseudoElements: getConfig().computedStyleSupportsPseudoElements + }) + "\":\n"; + return "" + nameString + descriptionString + domString; + } + return "" + nameString + domString; + }).join('\n\n'); + return role + ":\n\n" + elementsString + "\n\n" + delimiterBar; + }).join('\n'); +} +const logRoles = function (dom, _temp2) { + let { + hidden = false + } = _temp2 === void 0 ? {} : _temp2; + return console.log(prettyRoles(dom, { + hidden + })); +}; + +/** + * @param {Element} element - + * @returns {boolean | undefined} - false/true if (not)selected, undefined if not selectable + */ +function computeAriaSelected(element) { + // implicit value from html-aam mappings: https://www.w3.org/TR/html-aam-1.0/#html-attribute-state-and-property-mappings + // https://www.w3.org/TR/html-aam-1.0/#details-id-97 + if (element.tagName === 'OPTION') { + return element.selected; + } + + // explicit value + return checkBooleanAttribute(element, 'aria-selected'); +} + +/** + * @param {Element} element - + * @returns {boolean} - + */ +function computeAriaBusy(element) { + // https://www.w3.org/TR/wai-aria-1.1/#aria-busy + return element.getAttribute('aria-busy') === 'true'; +} + +/** + * @param {Element} element - + * @returns {boolean | undefined} - false/true if (not)checked, undefined if not checked-able + */ +function computeAriaChecked(element) { + // implicit value from html-aam mappings: https://www.w3.org/TR/html-aam-1.0/#html-attribute-state-and-property-mappings + // https://www.w3.org/TR/html-aam-1.0/#details-id-56 + // https://www.w3.org/TR/html-aam-1.0/#details-id-67 + if ('indeterminate' in element && element.indeterminate) { + return undefined; + } + if ('checked' in element) { + return element.checked; + } + + // explicit value + return checkBooleanAttribute(element, 'aria-checked'); +} + +/** + * @param {Element} element - + * @returns {boolean | undefined} - false/true if (not)pressed, undefined if not press-able + */ +function computeAriaPressed(element) { + // https://www.w3.org/TR/wai-aria-1.1/#aria-pressed + return checkBooleanAttribute(element, 'aria-pressed'); +} + +/** + * @param {Element} element - + * @returns {boolean | string | null} - + */ +function computeAriaCurrent(element) { + var _ref9, _checkBooleanAttribut; + // https://www.w3.org/TR/wai-aria-1.1/#aria-current + return (_ref9 = (_checkBooleanAttribut = checkBooleanAttribute(element, 'aria-current')) != null ? _checkBooleanAttribut : element.getAttribute('aria-current')) != null ? _ref9 : false; +} + +/** + * @param {Element} element - + * @returns {boolean | undefined} - false/true if (not)expanded, undefined if not expand-able + */ +function computeAriaExpanded(element) { + // https://www.w3.org/TR/wai-aria-1.1/#aria-expanded + return checkBooleanAttribute(element, 'aria-expanded'); +} +function checkBooleanAttribute(element, attribute) { + const attributeValue = element.getAttribute(attribute); + if (attributeValue === 'true') { + return true; + } + if (attributeValue === 'false') { + return false; + } + return undefined; +} + +/** + * @param {Element} element - + * @returns {number | undefined} - number if implicit heading or aria-level present, otherwise undefined + */ +function computeHeadingLevel(element) { + // https://w3c.github.io/html-aam/#el-h1-h6 + // https://w3c.github.io/html-aam/#el-h1-h6 + const implicitHeadingLevels = { + H1: 1, + H2: 2, + H3: 3, + H4: 4, + H5: 5, + H6: 6 + }; + // explicit aria-level value + // https://www.w3.org/TR/wai-aria-1.2/#aria-level + const ariaLevelAttribute = element.getAttribute('aria-level') && Number(element.getAttribute('aria-level')); + return ariaLevelAttribute || implicitHeadingLevels[element.tagName]; +} + +/** + * @param {Element} element - + * @returns {number | undefined} - + */ +function computeAriaValueNow(element) { + const valueNow = element.getAttribute('aria-valuenow'); + return valueNow === null ? undefined : +valueNow; +} + +/** + * @param {Element} element - + * @returns {number | undefined} - + */ +function computeAriaValueMax(element) { + const valueMax = element.getAttribute('aria-valuemax'); + return valueMax === null ? undefined : +valueMax; +} + +/** + * @param {Element} element - + * @returns {number | undefined} - + */ +function computeAriaValueMin(element) { + const valueMin = element.getAttribute('aria-valuemin'); + return valueMin === null ? undefined : +valueMin; +} + +/** + * @param {Element} element - + * @returns {string | undefined} - + */ +function computeAriaValueText(element) { + const valueText = element.getAttribute('aria-valuetext'); + return valueText === null ? undefined : valueText; +} + +const normalize = getDefaultNormalizer(); +function escapeRegExp(string) { + return string.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string +} +function getRegExpMatcher(string) { + return new RegExp(escapeRegExp(string.toLowerCase()), 'i'); +} +function makeSuggestion(queryName, element, content, _ref) { + let { + variant, + name + } = _ref; + let warning = ''; + const queryOptions = {}; + const queryArgs = [['Role', 'TestId'].includes(queryName) ? content : getRegExpMatcher(content)]; + if (name) { + queryOptions.name = getRegExpMatcher(name); + } + if (queryName === 'Role' && isInaccessible(element)) { + queryOptions.hidden = true; + warning = "Element is inaccessible. This means that the element and all its children are invisible to screen readers.\n If you are using the aria-hidden prop, make sure this is the right choice for your case.\n "; + } + if (Object.keys(queryOptions).length > 0) { + queryArgs.push(queryOptions); + } + const queryMethod = variant + "By" + queryName; + return { + queryName, + queryMethod, + queryArgs, + variant, + warning, + toString() { + if (warning) { + console.warn(warning); + } + let [text, options] = queryArgs; + text = typeof text === 'string' ? "'" + text + "'" : text; + options = options ? ", { " + Object.entries(options).map(_ref2 => { + let [k, v] = _ref2; + return k + ": " + v; + }).join(', ') + " }" : ''; + return queryMethod + "(" + text + options + ")"; + } + }; +} +function canSuggest(currentMethod, requestedMethod, data) { + return data && (!requestedMethod || requestedMethod.toLowerCase() === currentMethod.toLowerCase()); +} +function getSuggestedQuery(element, variant, method) { + var _element$getAttribute, _getImplicitAriaRoles; + if (variant === void 0) { + variant = 'get'; + } + // don't create suggestions for script and style elements + if (element.matches(getConfig().defaultIgnore)) { + return undefined; + } + + //We prefer to suggest something else if the role is generic + const role = (_element$getAttribute = element.getAttribute('role')) != null ? _element$getAttribute : (_getImplicitAriaRoles = getImplicitAriaRoles(element)) == null ? void 0 : _getImplicitAriaRoles[0]; + if (role !== 'generic' && canSuggest('Role', method, role)) { + return makeSuggestion('Role', element, role, { + variant, + name: domAccessibilityApi.computeAccessibleName(element, { + computedStyleSupportsPseudoElements: getConfig().computedStyleSupportsPseudoElements + }) + }); + } + const labelText = getLabels(document, element).map(label => label.content).join(' '); + if (canSuggest('LabelText', method, labelText)) { + return makeSuggestion('LabelText', element, labelText, { + variant + }); + } + const placeholderText = element.getAttribute('placeholder'); + if (canSuggest('PlaceholderText', method, placeholderText)) { + return makeSuggestion('PlaceholderText', element, placeholderText, { + variant + }); + } + const textContent = normalize(getNodeText(element)); + if (canSuggest('Text', method, textContent)) { + return makeSuggestion('Text', element, textContent, { + variant + }); + } + if (canSuggest('DisplayValue', method, element.value)) { + return makeSuggestion('DisplayValue', element, normalize(element.value), { + variant + }); + } + const alt = element.getAttribute('alt'); + if (canSuggest('AltText', method, alt)) { + return makeSuggestion('AltText', element, alt, { + variant + }); + } + const title = element.getAttribute('title'); + if (canSuggest('Title', method, title)) { + return makeSuggestion('Title', element, title, { + variant + }); + } + const testId = element.getAttribute(getConfig().testIdAttribute); + if (canSuggest('TestId', method, testId)) { + return makeSuggestion('TestId', element, testId, { + variant + }); + } + return undefined; +} + +// This is so the stack trace the developer sees is one that's +// closer to their code (because async stack traces are hard to follow). +function copyStackTrace(target, source) { + target.stack = source.stack.replace(source.message, target.message); +} +function waitFor(callback, _ref) { + let { + container = getDocument(), + timeout = getConfig().asyncUtilTimeout, + showOriginalStackTrace = getConfig().showOriginalStackTrace, + stackTraceError, + interval = 50, + onTimeout = error => { + Object.defineProperty(error, 'message', { + value: getConfig().getElementError(error.message, container).message + }); + return error; + }, + mutationObserverOptions = { + subtree: true, + childList: true, + attributes: true, + characterData: true + } + } = _ref; + if (typeof callback !== 'function') { + throw new TypeError('Received `callback` arg must be a function'); + } + return new Promise(async (resolve, reject) => { + let lastError, intervalId, observer; + let finished = false; + let promiseStatus = 'idle'; + const overallTimeoutTimer = setTimeout(handleTimeout, timeout); + const usingJestFakeTimers = jestFakeTimersAreEnabled(); + if (usingJestFakeTimers) { + const { + unstable_advanceTimersWrapper: advanceTimersWrapper + } = getConfig(); + checkCallback(); + // this is a dangerous rule to disable because it could lead to an + // infinite loop. However, eslint isn't smart enough to know that we're + // setting finished inside `onDone` which will be called when we're done + // waiting or when we've timed out. + // eslint-disable-next-line no-unmodified-loop-condition + while (!finished) { + if (!jestFakeTimersAreEnabled()) { + const error = new Error("Changed from using fake timers to real timers while using waitFor. This is not allowed and will result in very strange behavior. Please ensure you're awaiting all async things your test is doing before changing to real timers. For more info, please go to https://github.com/testing-library/dom-testing-library/issues/830"); + if (!showOriginalStackTrace) copyStackTrace(error, stackTraceError); + reject(error); + return; + } + + // In this rare case, we *need* to wait for in-flight promises + // to resolve before continuing. We don't need to take advantage + // of parallelization so we're fine. + // https://stackoverflow.com/a/59243586/971592 + // eslint-disable-next-line no-await-in-loop + await advanceTimersWrapper(async () => { + // we *could* (maybe should?) use `advanceTimersToNextTimer` but it's + // possible that could make this loop go on forever if someone is using + // third party code that's setting up recursive timers so rapidly that + // the user's timer's don't get a chance to resolve. So we'll advance + // by an interval instead. (We have a test for this case). + jest.advanceTimersByTime(interval); + }); + + // Could have timed-out + if (finished) { + break; + } + // It's really important that checkCallback is run *before* we flush + // in-flight promises. To be honest, I'm not sure why, and I can't quite + // think of a way to reproduce the problem in a test, but I spent + // an entire day banging my head against a wall on this. + checkCallback(); + } + } else { + try { + checkContainerType(container); + } catch (e) { + reject(e); + return; + } + intervalId = setInterval(checkRealTimersCallback, interval); + const { + MutationObserver + } = getWindowFromNode(container); + observer = new MutationObserver(checkRealTimersCallback); + observer.observe(container, mutationObserverOptions); + checkCallback(); + } + function onDone(error, result) { + finished = true; + clearTimeout(overallTimeoutTimer); + if (!usingJestFakeTimers) { + clearInterval(intervalId); + observer.disconnect(); + } + if (error) { + reject(error); + } else { + resolve(result); + } + } + function checkRealTimersCallback() { + if (jestFakeTimersAreEnabled()) { + const error = new Error("Changed from using real timers to fake timers while using waitFor. This is not allowed and will result in very strange behavior. Please ensure you're awaiting all async things your test is doing before changing to fake timers. For more info, please go to https://github.com/testing-library/dom-testing-library/issues/830"); + if (!showOriginalStackTrace) copyStackTrace(error, stackTraceError); + return reject(error); + } else { + return checkCallback(); + } + } + function checkCallback() { + if (promiseStatus === 'pending') return; + try { + const result = runWithExpensiveErrorDiagnosticsDisabled(callback); + if (typeof (result == null ? void 0 : result.then) === 'function') { + promiseStatus = 'pending'; + result.then(resolvedValue => { + promiseStatus = 'resolved'; + onDone(null, resolvedValue); + }, rejectedValue => { + promiseStatus = 'rejected'; + lastError = rejectedValue; + }); + } else { + onDone(null, result); + } + // If `callback` throws, wait for the next mutation, interval, or timeout. + } catch (error) { + // Save the most recent callback error to reject the promise with it in the event of a timeout + lastError = error; + } + } + function handleTimeout() { + let error; + if (lastError) { + error = lastError; + if (!showOriginalStackTrace && error.name === 'TestingLibraryElementError') { + copyStackTrace(error, stackTraceError); + } + } else { + error = new Error('Timed out in waitFor.'); + if (!showOriginalStackTrace) { + copyStackTrace(error, stackTraceError); + } + } + onDone(onTimeout(error), null); + } + }); +} +function waitForWrapper(callback, options) { + // create the error here so its stack trace is as close to the + // calling code as possible + const stackTraceError = new Error('STACK_TRACE_MESSAGE'); + return getConfig().asyncWrapper(() => waitFor(callback, { + stackTraceError, + ...options + })); +} + +/* +eslint + max-lines-per-function: ["error", {"max": 200}], +*/ + +function getElementError(message, container) { + return getConfig().getElementError(message, container); +} +function getMultipleElementsFoundError(message, container) { + return getElementError(message + "\n\n(If this is intentional, then use the `*AllBy*` variant of the query (like `queryAllByText`, `getAllByText`, or `findAllByText`)).", container); +} +function queryAllByAttribute(attribute, container, text, _temp) { + let { + exact = true, + collapseWhitespace, + trim, + normalizer + } = _temp === void 0 ? {} : _temp; + const matcher = exact ? matches : fuzzyMatches; + const matchNormalizer = makeNormalizer({ + collapseWhitespace, + trim, + normalizer + }); + return Array.from(container.querySelectorAll("[" + attribute + "]")).filter(node => matcher(node.getAttribute(attribute), node, text, matchNormalizer)); +} +function queryByAttribute(attribute, container, text, options) { + const els = queryAllByAttribute(attribute, container, text, options); + if (els.length > 1) { + throw getMultipleElementsFoundError("Found multiple elements by [" + attribute + "=" + text + "]", container); + } + return els[0] || null; +} + +// this accepts a query function and returns a function which throws an error +// if more than one elements is returned, otherwise it returns the first +// element or null +function makeSingleQuery(allQuery, getMultipleError) { + return function (container) { + for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + const els = allQuery(container, ...args); + if (els.length > 1) { + const elementStrings = els.map(element => getElementError(null, element).message).join('\n\n'); + throw getMultipleElementsFoundError(getMultipleError(container, ...args) + "\n\nHere are the matching elements:\n\n" + elementStrings, container); + } + return els[0] || null; + }; +} +function getSuggestionError(suggestion, container) { + return getConfig().getElementError("A better query is available, try this:\n" + suggestion.toString() + "\n", container); +} + +// this accepts a query function and returns a function which throws an error +// if an empty list of elements is returned +function makeGetAllQuery(allQuery, getMissingError) { + return function (container) { + for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + const els = allQuery(container, ...args); + if (!els.length) { + throw getConfig().getElementError(getMissingError(container, ...args), container); + } + return els; + }; +} + +// this accepts a getter query function and returns a function which calls +// waitFor and passing a function which invokes the getter. +function makeFindQuery(getter) { + return (container, text, options, waitForOptions) => { + return waitForWrapper(() => { + return getter(container, text, options); + }, { + container, + ...waitForOptions + }); + }; +} +const wrapSingleQueryWithSuggestion = (query, queryAllByName, variant) => function (container) { + for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { + args[_key3 - 1] = arguments[_key3]; + } + const element = query(container, ...args); + const [{ + suggest = getConfig().throwSuggestions + } = {}] = args.slice(-1); + if (element && suggest) { + const suggestion = getSuggestedQuery(element, variant); + if (suggestion && !queryAllByName.endsWith(suggestion.queryName)) { + throw getSuggestionError(suggestion.toString(), container); + } + } + return element; +}; +const wrapAllByQueryWithSuggestion = (query, queryAllByName, variant) => function (container) { + for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) { + args[_key4 - 1] = arguments[_key4]; + } + const els = query(container, ...args); + const [{ + suggest = getConfig().throwSuggestions + } = {}] = args.slice(-1); + if (els.length && suggest) { + // get a unique list of all suggestion messages. We are only going to make a suggestion if + // all the suggestions are the same + const uniqueSuggestionMessages = [...new Set(els.map(element => { + var _getSuggestedQuery; + return (_getSuggestedQuery = getSuggestedQuery(element, variant)) == null ? void 0 : _getSuggestedQuery.toString(); + }))]; + if ( + // only want to suggest if all the els have the same suggestion. + uniqueSuggestionMessages.length === 1 && !queryAllByName.endsWith( + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- TODO: Can this be null at runtime? + getSuggestedQuery(els[0], variant).queryName)) { + throw getSuggestionError(uniqueSuggestionMessages[0], container); + } + } + return els; +}; + +// TODO: This deviates from the published declarations +// However, the implementation always required a dyadic (after `container`) not variadic `queryAllBy` considering the implementation of `makeFindQuery` +// This is at least statically true and can be verified by accepting `QueryMethod` +function buildQueries(queryAllBy, getMultipleError, getMissingError) { + const queryBy = wrapSingleQueryWithSuggestion(makeSingleQuery(queryAllBy, getMultipleError), queryAllBy.name, 'query'); + const getAllBy = makeGetAllQuery(queryAllBy, getMissingError); + const getBy = makeSingleQuery(getAllBy, getMultipleError); + const getByWithSuggestions = wrapSingleQueryWithSuggestion(getBy, queryAllBy.name, 'get'); + const getAllWithSuggestions = wrapAllByQueryWithSuggestion(getAllBy, queryAllBy.name.replace('query', 'get'), 'getAll'); + const findAllBy = makeFindQuery(wrapAllByQueryWithSuggestion(getAllBy, queryAllBy.name, 'findAll')); + const findBy = makeFindQuery(wrapSingleQueryWithSuggestion(getBy, queryAllBy.name, 'find')); + return [queryBy, getAllWithSuggestions, getByWithSuggestions, findAllBy, findBy]; +} + +var queryHelpers = /*#__PURE__*/Object.freeze({ + __proto__: null, + getElementError: getElementError, + wrapAllByQueryWithSuggestion: wrapAllByQueryWithSuggestion, + wrapSingleQueryWithSuggestion: wrapSingleQueryWithSuggestion, + getMultipleElementsFoundError: getMultipleElementsFoundError, + queryAllByAttribute: queryAllByAttribute, + queryByAttribute: queryByAttribute, + makeSingleQuery: makeSingleQuery, + makeGetAllQuery: makeGetAllQuery, + makeFindQuery: makeFindQuery, + buildQueries: buildQueries +}); + +function queryAllLabels(container) { + return Array.from(container.querySelectorAll('label,input')).map(node => { + return { + node, + textToMatch: getLabelContent(node) + }; + }).filter(_ref => { + let { + textToMatch + } = _ref; + return textToMatch !== null; + }); +} +const queryAllLabelsByText = function (container, text, _temp) { + let { + exact = true, + trim, + collapseWhitespace, + normalizer + } = _temp === void 0 ? {} : _temp; + const matcher = exact ? matches : fuzzyMatches; + const matchNormalizer = makeNormalizer({ + collapseWhitespace, + trim, + normalizer + }); + const textToMatchByLabels = queryAllLabels(container); + return textToMatchByLabels.filter(_ref2 => { + let { + node, + textToMatch + } = _ref2; + return matcher(textToMatch, node, text, matchNormalizer); + }).map(_ref3 => { + let { + node + } = _ref3; + return node; + }); +}; +const queryAllByLabelText = function (container, text, _temp2) { + let { + selector = '*', + exact = true, + collapseWhitespace, + trim, + normalizer + } = _temp2 === void 0 ? {} : _temp2; + checkContainerType(container); + const matcher = exact ? matches : fuzzyMatches; + const matchNormalizer = makeNormalizer({ + collapseWhitespace, + trim, + normalizer + }); + const matchingLabelledElements = Array.from(container.querySelectorAll('*')).filter(element => { + return getRealLabels(element).length || element.hasAttribute('aria-labelledby'); + }).reduce((labelledElements, labelledElement) => { + const labelList = getLabels(container, labelledElement, { + selector + }); + labelList.filter(label => Boolean(label.formControl)).forEach(label => { + if (matcher(label.content, label.formControl, text, matchNormalizer) && label.formControl) { + labelledElements.push(label.formControl); + } + }); + const labelsValue = labelList.filter(label => Boolean(label.content)).map(label => label.content); + if (matcher(labelsValue.join(' '), labelledElement, text, matchNormalizer)) { + labelledElements.push(labelledElement); + } + if (labelsValue.length > 1) { + labelsValue.forEach((labelValue, index) => { + if (matcher(labelValue, labelledElement, text, matchNormalizer)) { + labelledElements.push(labelledElement); + } + const labelsFiltered = [...labelsValue]; + labelsFiltered.splice(index, 1); + if (labelsFiltered.length > 1) { + if (matcher(labelsFiltered.join(' '), labelledElement, text, matchNormalizer)) { + labelledElements.push(labelledElement); + } + } + }); + } + return labelledElements; + }, []).concat(queryAllByAttribute('aria-label', container, text, { + exact, + normalizer: matchNormalizer + })); + return Array.from(new Set(matchingLabelledElements)).filter(element => element.matches(selector)); +}; + +// the getAll* query would normally look like this: +// const getAllByLabelText = makeGetAllQuery( +// queryAllByLabelText, +// (c, text) => `Unable to find a label with the text of: ${text}`, +// ) +// however, we can give a more helpful error message than the generic one, +// so we're writing this one out by hand. +const getAllByLabelText = function (container, text) { + for (var _len = arguments.length, rest = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { + rest[_key - 2] = arguments[_key]; + } + const els = queryAllByLabelText(container, text, ...rest); + if (!els.length) { + const labels = queryAllLabelsByText(container, text, ...rest); + if (labels.length) { + const tagNames = labels.map(label => getTagNameOfElementAssociatedWithLabelViaFor(container, label)).filter(tagName => !!tagName); + if (tagNames.length) { + throw getConfig().getElementError(tagNames.map(tagName => "Found a label with the text of: " + text + ", however the element associated with this label (<" + tagName + " />) is non-labellable [https://html.spec.whatwg.org/multipage/forms.html#category-label]. If you really need to label a <" + tagName + " />, you can use aria-label or aria-labelledby instead.").join('\n\n'), container); + } else { + throw getConfig().getElementError("Found a label with the text of: " + text + ", however no form control was found associated to that label. Make sure you're using the \"for\" attribute or \"aria-labelledby\" attribute correctly.", container); + } + } else { + throw getConfig().getElementError("Unable to find a label with the text of: " + text, container); + } + } + return els; +}; +function getTagNameOfElementAssociatedWithLabelViaFor(container, label) { + const htmlFor = label.getAttribute('for'); + if (!htmlFor) { + return null; + } + const element = container.querySelector("[id=\"" + htmlFor + "\"]"); + return element ? element.tagName.toLowerCase() : null; +} + +// the reason mentioned above is the same reason we're not using buildQueries +const getMultipleError$7 = (c, text) => "Found multiple elements with the text of: " + text; +const queryByLabelText = wrapSingleQueryWithSuggestion(makeSingleQuery(queryAllByLabelText, getMultipleError$7), queryAllByLabelText.name, 'query'); +const getByLabelText = makeSingleQuery(getAllByLabelText, getMultipleError$7); +const findAllByLabelText = makeFindQuery(wrapAllByQueryWithSuggestion(getAllByLabelText, getAllByLabelText.name, 'findAll')); +const findByLabelText = makeFindQuery(wrapSingleQueryWithSuggestion(getByLabelText, getAllByLabelText.name, 'find')); +const getAllByLabelTextWithSuggestions = wrapAllByQueryWithSuggestion(getAllByLabelText, getAllByLabelText.name, 'getAll'); +const getByLabelTextWithSuggestions = wrapSingleQueryWithSuggestion(getByLabelText, getAllByLabelText.name, 'get'); +const queryAllByLabelTextWithSuggestions = wrapAllByQueryWithSuggestion(queryAllByLabelText, queryAllByLabelText.name, 'queryAll'); + +const queryAllByPlaceholderText = function () { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + checkContainerType(args[0]); + return queryAllByAttribute('placeholder', ...args); +}; +const getMultipleError$6 = (c, text) => "Found multiple elements with the placeholder text of: " + text; +const getMissingError$6 = (c, text) => "Unable to find an element with the placeholder text of: " + text; +const queryAllByPlaceholderTextWithSuggestions = wrapAllByQueryWithSuggestion(queryAllByPlaceholderText, queryAllByPlaceholderText.name, 'queryAll'); +const [queryByPlaceholderText, getAllByPlaceholderText, getByPlaceholderText, findAllByPlaceholderText, findByPlaceholderText] = buildQueries(queryAllByPlaceholderText, getMultipleError$6, getMissingError$6); + +const queryAllByText = function (container, text, _temp) { + let { + selector = '*', + exact = true, + collapseWhitespace, + trim, + ignore = getConfig().defaultIgnore, + normalizer + } = _temp === void 0 ? {} : _temp; + checkContainerType(container); + const matcher = exact ? matches : fuzzyMatches; + const matchNormalizer = makeNormalizer({ + collapseWhitespace, + trim, + normalizer + }); + let baseArray = []; + if (typeof container.matches === 'function' && container.matches(selector)) { + baseArray = [container]; + } + return [...baseArray, ...Array.from(container.querySelectorAll(selector))] + // TODO: `matches` according lib.dom.d.ts can get only `string` but according our code it can handle also boolean :) + .filter(node => !ignore || !node.matches(ignore)).filter(node => matcher(getNodeText(node), node, text, matchNormalizer)); +}; +const getMultipleError$5 = (c, text) => "Found multiple elements with the text: " + text; +const getMissingError$5 = function (c, text, options) { + if (options === void 0) { + options = {}; + } + const { + collapseWhitespace, + trim, + normalizer, + selector + } = options; + const matchNormalizer = makeNormalizer({ + collapseWhitespace, + trim, + normalizer + }); + const normalizedText = matchNormalizer(text.toString()); + const isNormalizedDifferent = normalizedText !== text.toString(); + const isCustomSelector = (selector != null ? selector : '*') !== '*'; + return "Unable to find an element with the text: " + (isNormalizedDifferent ? normalizedText + " (normalized from '" + text + "')" : text) + (isCustomSelector ? ", which matches selector '" + selector + "'" : '') + ". This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible."; +}; +const queryAllByTextWithSuggestions = wrapAllByQueryWithSuggestion(queryAllByText, queryAllByText.name, 'queryAll'); +const [queryByText, getAllByText, getByText, findAllByText, findByText] = buildQueries(queryAllByText, getMultipleError$5, getMissingError$5); + +const queryAllByDisplayValue = function (container, value, _temp) { + let { + exact = true, + collapseWhitespace, + trim, + normalizer + } = _temp === void 0 ? {} : _temp; + checkContainerType(container); + const matcher = exact ? matches : fuzzyMatches; + const matchNormalizer = makeNormalizer({ + collapseWhitespace, + trim, + normalizer + }); + return Array.from(container.querySelectorAll("input,textarea,select")).filter(node => { + if (node.tagName === 'SELECT') { + const selectedOptions = Array.from(node.options).filter(option => option.selected); + return selectedOptions.some(optionNode => matcher(getNodeText(optionNode), optionNode, value, matchNormalizer)); + } else { + return matcher(node.value, node, value, matchNormalizer); + } + }); +}; +const getMultipleError$4 = (c, value) => "Found multiple elements with the display value: " + value + "."; +const getMissingError$4 = (c, value) => "Unable to find an element with the display value: " + value + "."; +const queryAllByDisplayValueWithSuggestions = wrapAllByQueryWithSuggestion(queryAllByDisplayValue, queryAllByDisplayValue.name, 'queryAll'); +const [queryByDisplayValue, getAllByDisplayValue, getByDisplayValue, findAllByDisplayValue, findByDisplayValue] = buildQueries(queryAllByDisplayValue, getMultipleError$4, getMissingError$4); + +// Valid tags are img, input, area and custom elements +const VALID_TAG_REGEXP = /^(img|input|area|.+-.+)$/i; +const queryAllByAltText = function (container, alt, options) { + if (options === void 0) { + options = {}; + } + checkContainerType(container); + return queryAllByAttribute('alt', container, alt, options).filter(node => VALID_TAG_REGEXP.test(node.tagName)); +}; +const getMultipleError$3 = (c, alt) => "Found multiple elements with the alt text: " + alt; +const getMissingError$3 = (c, alt) => "Unable to find an element with the alt text: " + alt; +const queryAllByAltTextWithSuggestions = wrapAllByQueryWithSuggestion(queryAllByAltText, queryAllByAltText.name, 'queryAll'); +const [queryByAltText, getAllByAltText, getByAltText, findAllByAltText, findByAltText] = buildQueries(queryAllByAltText, getMultipleError$3, getMissingError$3); + +const isSvgTitle = node => { + var _node$parentElement; + return node.tagName.toLowerCase() === 'title' && ((_node$parentElement = node.parentElement) == null ? void 0 : _node$parentElement.tagName.toLowerCase()) === 'svg'; +}; +const queryAllByTitle = function (container, text, _temp) { + let { + exact = true, + collapseWhitespace, + trim, + normalizer + } = _temp === void 0 ? {} : _temp; + checkContainerType(container); + const matcher = exact ? matches : fuzzyMatches; + const matchNormalizer = makeNormalizer({ + collapseWhitespace, + trim, + normalizer + }); + return Array.from(container.querySelectorAll('[title], svg > title')).filter(node => matcher(node.getAttribute('title'), node, text, matchNormalizer) || isSvgTitle(node) && matcher(getNodeText(node), node, text, matchNormalizer)); +}; +const getMultipleError$2 = (c, title) => "Found multiple elements with the title: " + title + "."; +const getMissingError$2 = (c, title) => "Unable to find an element with the title: " + title + "."; +const queryAllByTitleWithSuggestions = wrapAllByQueryWithSuggestion(queryAllByTitle, queryAllByTitle.name, 'queryAll'); +const [queryByTitle, getAllByTitle, getByTitle, findAllByTitle, findByTitle] = buildQueries(queryAllByTitle, getMultipleError$2, getMissingError$2); + +/* eslint-disable complexity */ +const queryAllByRole = function (container, role, _temp) { + let { + hidden = getConfig().defaultHidden, + name, + description, + queryFallbacks = false, + selected, + busy, + checked, + pressed, + current, + level, + expanded, + value: { + now: valueNow, + min: valueMin, + max: valueMax, + text: valueText + } = {} + } = _temp === void 0 ? {} : _temp; + checkContainerType(container); + if (selected !== undefined) { + var _allRoles$get; + // guard against unknown roles + if (((_allRoles$get = ariaQuery.roles.get(role)) == null ? void 0 : _allRoles$get.props['aria-selected']) === undefined) { + throw new Error("\"aria-selected\" is not supported on role \"" + role + "\"."); + } + } + if (busy !== undefined) { + var _allRoles$get2; + // guard against unknown roles + if (((_allRoles$get2 = ariaQuery.roles.get(role)) == null ? void 0 : _allRoles$get2.props['aria-busy']) === undefined) { + throw new Error("\"aria-busy\" is not supported on role \"" + role + "\"."); + } + } + if (checked !== undefined) { + var _allRoles$get3; + // guard against unknown roles + if (((_allRoles$get3 = ariaQuery.roles.get(role)) == null ? void 0 : _allRoles$get3.props['aria-checked']) === undefined) { + throw new Error("\"aria-checked\" is not supported on role \"" + role + "\"."); + } + } + if (pressed !== undefined) { + var _allRoles$get4; + // guard against unknown roles + if (((_allRoles$get4 = ariaQuery.roles.get(role)) == null ? void 0 : _allRoles$get4.props['aria-pressed']) === undefined) { + throw new Error("\"aria-pressed\" is not supported on role \"" + role + "\"."); + } + } + if (current !== undefined) { + var _allRoles$get5; + /* istanbul ignore next */ + // guard against unknown roles + // All currently released ARIA versions support `aria-current` on all roles. + // Leaving this for symmetry and forward compatibility + if (((_allRoles$get5 = ariaQuery.roles.get(role)) == null ? void 0 : _allRoles$get5.props['aria-current']) === undefined) { + throw new Error("\"aria-current\" is not supported on role \"" + role + "\"."); + } + } + if (level !== undefined) { + // guard against using `level` option with any role other than `heading` + if (role !== 'heading') { + throw new Error("Role \"" + role + "\" cannot have \"level\" property."); + } + } + if (valueNow !== undefined) { + var _allRoles$get6; + // guard against unknown roles + if (((_allRoles$get6 = ariaQuery.roles.get(role)) == null ? void 0 : _allRoles$get6.props['aria-valuenow']) === undefined) { + throw new Error("\"aria-valuenow\" is not supported on role \"" + role + "\"."); + } + } + if (valueMax !== undefined) { + var _allRoles$get7; + // guard against unknown roles + if (((_allRoles$get7 = ariaQuery.roles.get(role)) == null ? void 0 : _allRoles$get7.props['aria-valuemax']) === undefined) { + throw new Error("\"aria-valuemax\" is not supported on role \"" + role + "\"."); + } + } + if (valueMin !== undefined) { + var _allRoles$get8; + // guard against unknown roles + if (((_allRoles$get8 = ariaQuery.roles.get(role)) == null ? void 0 : _allRoles$get8.props['aria-valuemin']) === undefined) { + throw new Error("\"aria-valuemin\" is not supported on role \"" + role + "\"."); + } + } + if (valueText !== undefined) { + var _allRoles$get9; + // guard against unknown roles + if (((_allRoles$get9 = ariaQuery.roles.get(role)) == null ? void 0 : _allRoles$get9.props['aria-valuetext']) === undefined) { + throw new Error("\"aria-valuetext\" is not supported on role \"" + role + "\"."); + } + } + if (expanded !== undefined) { + var _allRoles$get0; + // guard against unknown roles + if (((_allRoles$get0 = ariaQuery.roles.get(role)) == null ? void 0 : _allRoles$get0.props['aria-expanded']) === undefined) { + throw new Error("\"aria-expanded\" is not supported on role \"" + role + "\"."); + } + } + const subtreeIsInaccessibleCache = new WeakMap(); + function cachedIsSubtreeInaccessible(element) { + if (!subtreeIsInaccessibleCache.has(element)) { + subtreeIsInaccessibleCache.set(element, isSubtreeInaccessible(element)); + } + return subtreeIsInaccessibleCache.get(element); + } + return Array.from(container.querySelectorAll( + // Only query elements that can be matched by the following filters + makeRoleSelector(role))).filter(node => { + const isRoleSpecifiedExplicitly = node.hasAttribute('role'); + if (isRoleSpecifiedExplicitly) { + const roleValue = node.getAttribute('role'); + if (queryFallbacks) { + return roleValue.split(' ').filter(Boolean).some(roleAttributeToken => roleAttributeToken === role); + } + // other wise only send the first token to match + const [firstRoleAttributeToken] = roleValue.split(' '); + return firstRoleAttributeToken === role; + } + const implicitRoles = getImplicitAriaRoles(node); + return implicitRoles.some(implicitRole => { + return implicitRole === role; + }); + }).filter(element => { + if (selected !== undefined) { + return selected === computeAriaSelected(element); + } + if (busy !== undefined) { + return busy === computeAriaBusy(element); + } + if (checked !== undefined) { + return checked === computeAriaChecked(element); + } + if (pressed !== undefined) { + return pressed === computeAriaPressed(element); + } + if (current !== undefined) { + return current === computeAriaCurrent(element); + } + if (expanded !== undefined) { + return expanded === computeAriaExpanded(element); + } + if (level !== undefined) { + return level === computeHeadingLevel(element); + } + if (valueNow !== undefined || valueMax !== undefined || valueMin !== undefined || valueText !== undefined) { + let valueMatches = true; + if (valueNow !== undefined) { + valueMatches && (valueMatches = valueNow === computeAriaValueNow(element)); + } + if (valueMax !== undefined) { + valueMatches && (valueMatches = valueMax === computeAriaValueMax(element)); + } + if (valueMin !== undefined) { + valueMatches && (valueMatches = valueMin === computeAriaValueMin(element)); + } + if (valueText !== undefined) { + var _computeAriaValueText; + valueMatches && (valueMatches = matches((_computeAriaValueText = computeAriaValueText(element)) != null ? _computeAriaValueText : null, element, valueText, text => text)); + } + return valueMatches; + } + // don't care if aria attributes are unspecified + return true; + }).filter(element => { + if (name === undefined) { + // Don't care + return true; + } + return matches(domAccessibilityApi.computeAccessibleName(element, { + computedStyleSupportsPseudoElements: getConfig().computedStyleSupportsPseudoElements + }), element, name, text => text); + }).filter(element => { + if (description === undefined) { + // Don't care + return true; + } + return matches(domAccessibilityApi.computeAccessibleDescription(element, { + computedStyleSupportsPseudoElements: getConfig().computedStyleSupportsPseudoElements + }), element, description, text => text); + }).filter(element => { + return hidden === false ? isInaccessible(element, { + isSubtreeInaccessible: cachedIsSubtreeInaccessible + }) === false : true; + }); +}; +function makeRoleSelector(role) { + var _roleElements$get; + const explicitRoleSelector = "*[role~=\"" + role + "\"]"; + const roleRelations = (_roleElements$get = ariaQuery.roleElements.get(role)) != null ? _roleElements$get : new Set(); + const implicitRoleSelectors = new Set(Array.from(roleRelations).map(_ref => { + let { + name + } = _ref; + return name; + })); + + // Current transpilation config sometimes assumes `...` is always applied to arrays. + // `...` is equivalent to `Array.prototype.concat` for arrays. + // If you replace this code with `[explicitRoleSelector, ...implicitRoleSelectors]`, make sure every transpilation target retains the `...` in favor of `Array.prototype.concat`. + return [explicitRoleSelector].concat(Array.from(implicitRoleSelectors)).join(','); +} +const getNameHint = name => { + let nameHint = ''; + if (name === undefined) { + nameHint = ''; + } else if (typeof name === 'string') { + nameHint = " and name \"" + name + "\""; + } else { + nameHint = " and name `" + name + "`"; + } + return nameHint; +}; +const getMultipleError$1 = function (c, role, _temp2) { + let { + name + } = _temp2 === void 0 ? {} : _temp2; + return "Found multiple elements with the role \"" + role + "\"" + getNameHint(name); +}; +const getMissingError$1 = function (container, role, _temp3) { + let { + hidden = getConfig().defaultHidden, + name, + description + } = _temp3 === void 0 ? {} : _temp3; + if (getConfig()._disableExpensiveErrorDiagnostics) { + return "Unable to find role=\"" + role + "\"" + getNameHint(name); + } + let roles = ''; + Array.from(container.children).forEach(childElement => { + roles += prettyRoles(childElement, { + hidden, + includeDescription: description !== undefined + }); + }); + let roleMessage; + if (roles.length === 0) { + if (hidden === false) { + roleMessage = 'There are no accessible roles. But there might be some inaccessible roles. ' + 'If you wish to access them, then set the `hidden` option to `true`. ' + 'Learn more about this here: https://testing-library.com/docs/dom-testing-library/api-queries#byrole'; + } else { + roleMessage = 'There are no available roles.'; + } + } else { + roleMessage = ("\nHere are the " + (hidden === false ? 'accessible' : 'available') + " roles:\n\n " + roles.replace(/\n/g, '\n ').replace(/\n\s\s\n/g, '\n\n') + "\n").trim(); + } + let nameHint = ''; + if (name === undefined) { + nameHint = ''; + } else if (typeof name === 'string') { + nameHint = " and name \"" + name + "\""; + } else { + nameHint = " and name `" + name + "`"; + } + let descriptionHint = ''; + if (description === undefined) { + descriptionHint = ''; + } else if (typeof description === 'string') { + descriptionHint = " and description \"" + description + "\""; + } else { + descriptionHint = " and description `" + description + "`"; + } + return ("\nUnable to find an " + (hidden === false ? 'accessible ' : '') + "element with the role \"" + role + "\"" + nameHint + descriptionHint + "\n\n" + roleMessage).trim(); +}; +const queryAllByRoleWithSuggestions = wrapAllByQueryWithSuggestion(queryAllByRole, queryAllByRole.name, 'queryAll'); +const [queryByRole, getAllByRole, getByRole, findAllByRole, findByRole] = buildQueries(queryAllByRole, getMultipleError$1, getMissingError$1); + +const getTestIdAttribute = () => getConfig().testIdAttribute; +const queryAllByTestId = function () { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + checkContainerType(args[0]); + return queryAllByAttribute(getTestIdAttribute(), ...args); +}; +const getMultipleError = (c, id) => "Found multiple elements by: [" + getTestIdAttribute() + "=\"" + id + "\"]"; +const getMissingError = (c, id) => "Unable to find an element by: [" + getTestIdAttribute() + "=\"" + id + "\"]"; +const queryAllByTestIdWithSuggestions = wrapAllByQueryWithSuggestion(queryAllByTestId, queryAllByTestId.name, 'queryAll'); +const [queryByTestId, getAllByTestId, getByTestId, findAllByTestId, findByTestId] = buildQueries(queryAllByTestId, getMultipleError, getMissingError); + +var queries = /*#__PURE__*/Object.freeze({ + __proto__: null, + queryAllByLabelText: queryAllByLabelTextWithSuggestions, + queryByLabelText: queryByLabelText, + getAllByLabelText: getAllByLabelTextWithSuggestions, + getByLabelText: getByLabelTextWithSuggestions, + findAllByLabelText: findAllByLabelText, + findByLabelText: findByLabelText, + queryByPlaceholderText: queryByPlaceholderText, + queryAllByPlaceholderText: queryAllByPlaceholderTextWithSuggestions, + getByPlaceholderText: getByPlaceholderText, + getAllByPlaceholderText: getAllByPlaceholderText, + findAllByPlaceholderText: findAllByPlaceholderText, + findByPlaceholderText: findByPlaceholderText, + queryByText: queryByText, + queryAllByText: queryAllByTextWithSuggestions, + getByText: getByText, + getAllByText: getAllByText, + findAllByText: findAllByText, + findByText: findByText, + queryByDisplayValue: queryByDisplayValue, + queryAllByDisplayValue: queryAllByDisplayValueWithSuggestions, + getByDisplayValue: getByDisplayValue, + getAllByDisplayValue: getAllByDisplayValue, + findAllByDisplayValue: findAllByDisplayValue, + findByDisplayValue: findByDisplayValue, + queryByAltText: queryByAltText, + queryAllByAltText: queryAllByAltTextWithSuggestions, + getByAltText: getByAltText, + getAllByAltText: getAllByAltText, + findAllByAltText: findAllByAltText, + findByAltText: findByAltText, + queryByTitle: queryByTitle, + queryAllByTitle: queryAllByTitleWithSuggestions, + getByTitle: getByTitle, + getAllByTitle: getAllByTitle, + findAllByTitle: findAllByTitle, + findByTitle: findByTitle, + queryByRole: queryByRole, + queryAllByRole: queryAllByRoleWithSuggestions, + getAllByRole: getAllByRole, + getByRole: getByRole, + findAllByRole: findAllByRole, + findByRole: findByRole, + queryByTestId: queryByTestId, + queryAllByTestId: queryAllByTestIdWithSuggestions, + getByTestId: getByTestId, + getAllByTestId: getAllByTestId, + findAllByTestId: findAllByTestId, + findByTestId: findByTestId +}); + +/** + * @typedef {{[key: string]: Function}} FuncMap + */ + +/** + * @param {HTMLElement} element container + * @param {FuncMap} queries object of functions + * @param {Object} initialValue for reducer + * @returns {FuncMap} returns object of functions bound to container + */ +function getQueriesForElement(element, queries$1, initialValue) { + if (queries$1 === void 0) { + queries$1 = queries; + } + if (initialValue === void 0) { + initialValue = {}; + } + return Object.keys(queries$1).reduce((helpers, key) => { + const fn = queries$1[key]; + helpers[key] = fn.bind(null, element); + return helpers; + }, initialValue); +} + +const isRemoved = result => !result || Array.isArray(result) && !result.length; + +// Check if the element is not present. +// As the name implies, waitForElementToBeRemoved should check `present` --> `removed` +function initialCheck(elements) { + if (isRemoved(elements)) { + throw new Error('The element(s) given to waitForElementToBeRemoved are already removed. waitForElementToBeRemoved requires that the element(s) exist(s) before waiting for removal.'); + } +} +async function waitForElementToBeRemoved(callback, options) { + // created here so we get a nice stacktrace + const timeoutError = new Error('Timed out in waitForElementToBeRemoved.'); + if (typeof callback !== 'function') { + initialCheck(callback); + const elements = Array.isArray(callback) ? callback : [callback]; + const getRemainingElements = elements.map(element => { + let parent = element.parentElement; + if (parent === null) return () => null; + while (parent.parentElement) parent = parent.parentElement; + return () => parent.contains(element) ? element : null; + }); + callback = () => getRemainingElements.map(c => c()).filter(Boolean); + } + initialCheck(callback()); + return waitForWrapper(() => { + let result; + try { + result = callback(); + } catch (error) { + if (error.name === 'TestingLibraryElementError') { + return undefined; + } + throw error; + } + if (!isRemoved(result)) { + throw timeoutError; + } + return undefined; + }, options); +} + +/* +eslint + require-await: "off" +*/ + +const eventMap = { + // Clipboard Events + copy: { + EventType: 'ClipboardEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + cut: { + EventType: 'ClipboardEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + paste: { + EventType: 'ClipboardEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + // Composition Events + compositionEnd: { + EventType: 'CompositionEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + compositionStart: { + EventType: 'CompositionEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + compositionUpdate: { + EventType: 'CompositionEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + // Keyboard Events + keyDown: { + EventType: 'KeyboardEvent', + defaultInit: { + bubbles: true, + cancelable: true, + charCode: 0, + composed: true + } + }, + keyPress: { + EventType: 'KeyboardEvent', + defaultInit: { + bubbles: true, + cancelable: true, + charCode: 0, + composed: true + } + }, + keyUp: { + EventType: 'KeyboardEvent', + defaultInit: { + bubbles: true, + cancelable: true, + charCode: 0, + composed: true + } + }, + // Focus Events + focus: { + EventType: 'FocusEvent', + defaultInit: { + bubbles: false, + cancelable: false, + composed: true + } + }, + blur: { + EventType: 'FocusEvent', + defaultInit: { + bubbles: false, + cancelable: false, + composed: true + } + }, + focusIn: { + EventType: 'FocusEvent', + defaultInit: { + bubbles: true, + cancelable: false, + composed: true + } + }, + focusOut: { + EventType: 'FocusEvent', + defaultInit: { + bubbles: true, + cancelable: false, + composed: true + } + }, + // Form Events + change: { + EventType: 'Event', + defaultInit: { + bubbles: true, + cancelable: false + } + }, + input: { + EventType: 'InputEvent', + defaultInit: { + bubbles: true, + cancelable: false, + composed: true + } + }, + invalid: { + EventType: 'Event', + defaultInit: { + bubbles: false, + cancelable: true + } + }, + submit: { + EventType: 'Event', + defaultInit: { + bubbles: true, + cancelable: true + } + }, + reset: { + EventType: 'Event', + defaultInit: { + bubbles: true, + cancelable: true + } + }, + // Mouse Events + click: { + EventType: 'MouseEvent', + defaultInit: { + bubbles: true, + cancelable: true, + button: 0, + composed: true + } + }, + contextMenu: { + EventType: 'MouseEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + dblClick: { + EventType: 'MouseEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + drag: { + EventType: 'DragEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + dragEnd: { + EventType: 'DragEvent', + defaultInit: { + bubbles: true, + cancelable: false, + composed: true + } + }, + dragEnter: { + EventType: 'DragEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + dragExit: { + EventType: 'DragEvent', + defaultInit: { + bubbles: true, + cancelable: false, + composed: true + } + }, + dragLeave: { + EventType: 'DragEvent', + defaultInit: { + bubbles: true, + cancelable: false, + composed: true + } + }, + dragOver: { + EventType: 'DragEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + dragStart: { + EventType: 'DragEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + drop: { + EventType: 'DragEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + mouseDown: { + EventType: 'MouseEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + mouseEnter: { + EventType: 'MouseEvent', + defaultInit: { + bubbles: false, + cancelable: false, + composed: true + } + }, + mouseLeave: { + EventType: 'MouseEvent', + defaultInit: { + bubbles: false, + cancelable: false, + composed: true + } + }, + mouseMove: { + EventType: 'MouseEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + mouseOut: { + EventType: 'MouseEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + mouseOver: { + EventType: 'MouseEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + mouseUp: { + EventType: 'MouseEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + // Selection Events + select: { + EventType: 'Event', + defaultInit: { + bubbles: true, + cancelable: false + } + }, + // Touch Events + touchCancel: { + EventType: 'TouchEvent', + defaultInit: { + bubbles: true, + cancelable: false, + composed: true + } + }, + touchEnd: { + EventType: 'TouchEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + touchMove: { + EventType: 'TouchEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + touchStart: { + EventType: 'TouchEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + // UI Events + resize: { + EventType: 'UIEvent', + defaultInit: { + bubbles: false, + cancelable: false + } + }, + scroll: { + EventType: 'UIEvent', + defaultInit: { + bubbles: false, + cancelable: false + } + }, + // Wheel Events + wheel: { + EventType: 'WheelEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + // Media Events + abort: { + EventType: 'Event', + defaultInit: { + bubbles: false, + cancelable: false + } + }, + canPlay: { + EventType: 'Event', + defaultInit: { + bubbles: false, + cancelable: false + } + }, + canPlayThrough: { + EventType: 'Event', + defaultInit: { + bubbles: false, + cancelable: false + } + }, + durationChange: { + EventType: 'Event', + defaultInit: { + bubbles: false, + cancelable: false + } + }, + emptied: { + EventType: 'Event', + defaultInit: { + bubbles: false, + cancelable: false + } + }, + encrypted: { + EventType: 'Event', + defaultInit: { + bubbles: false, + cancelable: false + } + }, + ended: { + EventType: 'Event', + defaultInit: { + bubbles: false, + cancelable: false + } + }, + loadedData: { + EventType: 'Event', + defaultInit: { + bubbles: false, + cancelable: false + } + }, + loadedMetadata: { + EventType: 'Event', + defaultInit: { + bubbles: false, + cancelable: false + } + }, + loadStart: { + EventType: 'ProgressEvent', + defaultInit: { + bubbles: false, + cancelable: false + } + }, + pause: { + EventType: 'Event', + defaultInit: { + bubbles: false, + cancelable: false + } + }, + play: { + EventType: 'Event', + defaultInit: { + bubbles: false, + cancelable: false + } + }, + playing: { + EventType: 'Event', + defaultInit: { + bubbles: false, + cancelable: false + } + }, + progress: { + EventType: 'ProgressEvent', + defaultInit: { + bubbles: false, + cancelable: false + } + }, + rateChange: { + EventType: 'Event', + defaultInit: { + bubbles: false, + cancelable: false + } + }, + seeked: { + EventType: 'Event', + defaultInit: { + bubbles: false, + cancelable: false + } + }, + seeking: { + EventType: 'Event', + defaultInit: { + bubbles: false, + cancelable: false + } + }, + stalled: { + EventType: 'Event', + defaultInit: { + bubbles: false, + cancelable: false + } + }, + suspend: { + EventType: 'Event', + defaultInit: { + bubbles: false, + cancelable: false + } + }, + timeUpdate: { + EventType: 'Event', + defaultInit: { + bubbles: false, + cancelable: false + } + }, + volumeChange: { + EventType: 'Event', + defaultInit: { + bubbles: false, + cancelable: false + } + }, + waiting: { + EventType: 'Event', + defaultInit: { + bubbles: false, + cancelable: false + } + }, + // Events + load: { + // TODO: load events can be UIEvent or Event depending on what generated them + // This is where this abstraction breaks down. + // But the common targets are , +``` + +## Usage + +Import the library in your code, and then pick one of the styles you'd like to use - either `assert`, `expect` or `should`: + +```js +import { assert } from 'chai'; // Using Assert style +import { expect } from 'chai'; // Using Expect style +import { should } from 'chai'; // Using Should style +``` + +### Register the chai testing style globally + +```js +import 'chai/register-assert'; // Using Assert style +import 'chai/register-expect'; // Using Expect style +import 'chai/register-should'; // Using Should style +``` + +### Import assertion styles as local variables + +```js +import { assert } from 'chai'; // Using Assert style +import { expect } from 'chai'; // Using Expect style +import { should } from 'chai'; // Using Should style +should(); // Modifies `Object.prototype` + +import { expect, use } from 'chai'; // Creates local variables `expect` and `use`; useful for plugin use +``` + +### Usage with Mocha + +```bash +mocha spec.js --require chai/register-assert.js # Using Assert style +mocha spec.js --require chai/register-expect.js # Using Expect style +mocha spec.js --require chai/register-should.js # Using Should style +``` + +[Read more about these styles in our docs](http://chaijs.com/guide/styles/). + +## Plugins + +Chai offers a robust Plugin architecture for extending Chai's assertions and interfaces. + +- Need a plugin? View the [official plugin list](http://chaijs.com/plugins). +- Want to build a plugin? Read the [plugin api documentation](http://chaijs.com/guide/plugins/). +- Have a plugin and want it listed? Simply add the following keywords to your package.json: + - `chai-plugin` + - `browser` if your plugin works in the browser as well as Node.js + - `browser-only` if your plugin does not work with Node.js + +### Related Projects + +- [chaijs / chai-docs](https://github.com/chaijs/chai-docs): The chaijs.com website source code. +- [chaijs / assertion-error](https://github.com/chaijs/assertion-error): Custom `Error` constructor thrown upon an assertion failing. +- [chaijs / deep-eql](https://github.com/chaijs/deep-eql): Improved deep equality testing for Node.js and the browser. +- [chaijs / check-error](https://github.com/chaijs/check-error): Error comparison and information related utility for Node.js and the browser. +- [chaijs / loupe](https://github.com/chaijs/loupe): Inspect utility for Node.js and browsers. +- [chaijs / pathval](https://github.com/chaijs/pathval): Object value retrieval given a string path. + +### Contributing + +Thank you very much for considering to contribute! + +Please make sure you follow our [Code Of Conduct](https://github.com/chaijs/chai/blob/master/CODE_OF_CONDUCT.md) and we also strongly recommend reading our [Contributing Guide](https://github.com/chaijs/chai/blob/master/CONTRIBUTING.md). + +Here are a few issues other contributors frequently ran into when opening pull requests: + +- Please do not commit changes to the `chai.js` build. We do it once per release. +- Before pushing your commits, please make sure you [rebase](https://github.com/chaijs/chai/blob/master/CONTRIBUTING.md#pull-requests) them. + +### Contributors + +Please see the full +[Contributors Graph](https://github.com/chaijs/chai/graphs/contributors) for our +list of contributors. + +### Core Contributors + +Feel free to reach out to any of the core contributors with your questions or +concerns. We will do our best to respond in a timely manner. + +[![Keith Cirkel](https://avatars3.githubusercontent.com/u/118266?v=3&s=50)](https://github.com/keithamus) +[![James Garbutt](https://avatars3.githubusercontent.com/u/5677153?v=3&s=50)](https://github.com/43081j) +[![Kristján Oddsson](https://avatars3.githubusercontent.com/u/318208?v=3&s=50)](https://github.com/koddsson) + +### Core Contributor Alumni + +This project would not be what it is without the contributions from our prior +core contributors, for whom we are forever grateful: + +[![Jake Luer](https://avatars3.githubusercontent.com/u/58988?v=3&s=50)](https://github.com/logicalparadox) +[![Veselin Todorov](https://avatars3.githubusercontent.com/u/330048?v=3&s=50)](https://github.com/vesln) +[![Lucas Fernandes da Costa](https://avatars3.githubusercontent.com/u/6868147?v=3&s=50)](https://github.com/lucasfcosta) +[![Grant Snodgrass](https://avatars3.githubusercontent.com/u/17260989?v=3&s=50)](https://github.com/meeber) diff --git a/node_modules/chai/index.js b/node_modules/chai/index.js new file mode 100644 index 00000000..601eb535 --- /dev/null +++ b/node_modules/chai/index.js @@ -0,0 +1,4172 @@ +var __defProp = Object.defineProperty; +var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); + +// lib/chai/utils/index.js +var utils_exports = {}; +__export(utils_exports, { + addChainableMethod: () => addChainableMethod, + addLengthGuard: () => addLengthGuard, + addMethod: () => addMethod, + addProperty: () => addProperty, + checkError: () => check_error_exports, + compareByInspect: () => compareByInspect, + eql: () => deep_eql_default, + events: () => events, + expectTypes: () => expectTypes, + flag: () => flag, + getActual: () => getActual, + getMessage: () => getMessage2, + getName: () => getName, + getOperator: () => getOperator, + getOwnEnumerableProperties: () => getOwnEnumerableProperties, + getOwnEnumerablePropertySymbols: () => getOwnEnumerablePropertySymbols, + getPathInfo: () => getPathInfo, + hasProperty: () => hasProperty, + inspect: () => inspect2, + isNaN: () => isNaN2, + isNumeric: () => isNumeric, + isProxyEnabled: () => isProxyEnabled, + isRegExp: () => isRegExp2, + objDisplay: () => objDisplay, + overwriteChainableMethod: () => overwriteChainableMethod, + overwriteMethod: () => overwriteMethod, + overwriteProperty: () => overwriteProperty, + proxify: () => proxify, + test: () => test, + transferFlags: () => transferFlags, + type: () => type +}); + +// node_modules/check-error/index.js +var check_error_exports = {}; +__export(check_error_exports, { + compatibleConstructor: () => compatibleConstructor, + compatibleInstance: () => compatibleInstance, + compatibleMessage: () => compatibleMessage, + getConstructorName: () => getConstructorName, + getMessage: () => getMessage +}); +function isErrorInstance(obj) { + return obj instanceof Error || Object.prototype.toString.call(obj) === "[object Error]"; +} +__name(isErrorInstance, "isErrorInstance"); +function isRegExp(obj) { + return Object.prototype.toString.call(obj) === "[object RegExp]"; +} +__name(isRegExp, "isRegExp"); +function compatibleInstance(thrown, errorLike) { + return isErrorInstance(errorLike) && thrown === errorLike; +} +__name(compatibleInstance, "compatibleInstance"); +function compatibleConstructor(thrown, errorLike) { + if (isErrorInstance(errorLike)) { + return thrown.constructor === errorLike.constructor || thrown instanceof errorLike.constructor; + } else if ((typeof errorLike === "object" || typeof errorLike === "function") && errorLike.prototype) { + return thrown.constructor === errorLike || thrown instanceof errorLike; + } + return false; +} +__name(compatibleConstructor, "compatibleConstructor"); +function compatibleMessage(thrown, errMatcher) { + const comparisonString = typeof thrown === "string" ? thrown : thrown.message; + if (isRegExp(errMatcher)) { + return errMatcher.test(comparisonString); + } else if (typeof errMatcher === "string") { + return comparisonString.indexOf(errMatcher) !== -1; + } + return false; +} +__name(compatibleMessage, "compatibleMessage"); +function getConstructorName(errorLike) { + let constructorName = errorLike; + if (isErrorInstance(errorLike)) { + constructorName = errorLike.constructor.name; + } else if (typeof errorLike === "function") { + constructorName = errorLike.name; + if (constructorName === "") { + const newConstructorName = new errorLike().name; + constructorName = newConstructorName || constructorName; + } + } + return constructorName; +} +__name(getConstructorName, "getConstructorName"); +function getMessage(errorLike) { + let msg = ""; + if (errorLike && errorLike.message) { + msg = errorLike.message; + } else if (typeof errorLike === "string") { + msg = errorLike; + } + return msg; +} +__name(getMessage, "getMessage"); + +// lib/chai/utils/flag.js +function flag(obj, key, value) { + let flags = obj.__flags || (obj.__flags = /* @__PURE__ */ Object.create(null)); + if (arguments.length === 3) { + flags[key] = value; + } else { + return flags[key]; + } +} +__name(flag, "flag"); + +// lib/chai/utils/test.js +function test(obj, args) { + let negate = flag(obj, "negate"), expr = args[0]; + return negate ? !expr : expr; +} +__name(test, "test"); + +// lib/chai/utils/type-detect.js +function type(obj) { + if (typeof obj === "undefined") { + return "undefined"; + } + if (obj === null) { + return "null"; + } + const stringTag = obj[Symbol.toStringTag]; + if (typeof stringTag === "string") { + return stringTag; + } + const type3 = Object.prototype.toString.call(obj).slice(8, -1); + return type3; +} +__name(type, "type"); + +// node_modules/assertion-error/index.js +var canElideFrames = "captureStackTrace" in Error; +var _AssertionError = class _AssertionError extends Error { + constructor(message = "Unspecified AssertionError", props, ssf) { + super(message); + __publicField(this, "message"); + this.message = message; + if (canElideFrames) { + Error.captureStackTrace(this, ssf || _AssertionError); + } + for (const key in props) { + if (!(key in this)) { + this[key] = props[key]; + } + } + } + get name() { + return "AssertionError"; + } + get ok() { + return false; + } + toJSON(stack) { + return { + ...this, + name: this.name, + message: this.message, + ok: false, + stack: stack !== false ? this.stack : void 0 + }; + } +}; +__name(_AssertionError, "AssertionError"); +var AssertionError = _AssertionError; + +// lib/chai/utils/expectTypes.js +function expectTypes(obj, types) { + let flagMsg = flag(obj, "message"); + let ssfi = flag(obj, "ssfi"); + flagMsg = flagMsg ? flagMsg + ": " : ""; + obj = flag(obj, "object"); + types = types.map(function(t) { + return t.toLowerCase(); + }); + types.sort(); + let str = types.map(function(t, index) { + let art = ~["a", "e", "i", "o", "u"].indexOf(t.charAt(0)) ? "an" : "a"; + let or = types.length > 1 && index === types.length - 1 ? "or " : ""; + return or + art + " " + t; + }).join(", "); + let objType = type(obj).toLowerCase(); + if (!types.some(function(expected) { + return objType === expected; + })) { + throw new AssertionError( + flagMsg + "object tested must be " + str + ", but " + objType + " given", + void 0, + ssfi + ); + } +} +__name(expectTypes, "expectTypes"); + +// lib/chai/utils/getActual.js +function getActual(obj, args) { + return args.length > 4 ? args[4] : obj._obj; +} +__name(getActual, "getActual"); + +// node_modules/loupe/lib/helpers.js +var ansiColors = { + bold: ["1", "22"], + dim: ["2", "22"], + italic: ["3", "23"], + underline: ["4", "24"], + // 5 & 6 are blinking + inverse: ["7", "27"], + hidden: ["8", "28"], + strike: ["9", "29"], + // 10-20 are fonts + // 21-29 are resets for 1-9 + black: ["30", "39"], + red: ["31", "39"], + green: ["32", "39"], + yellow: ["33", "39"], + blue: ["34", "39"], + magenta: ["35", "39"], + cyan: ["36", "39"], + white: ["37", "39"], + brightblack: ["30;1", "39"], + brightred: ["31;1", "39"], + brightgreen: ["32;1", "39"], + brightyellow: ["33;1", "39"], + brightblue: ["34;1", "39"], + brightmagenta: ["35;1", "39"], + brightcyan: ["36;1", "39"], + brightwhite: ["37;1", "39"], + grey: ["90", "39"] +}; +var styles = { + special: "cyan", + number: "yellow", + bigint: "yellow", + boolean: "yellow", + undefined: "grey", + null: "bold", + string: "green", + symbol: "green", + date: "magenta", + regexp: "red" +}; +var truncator = "\u2026"; +function colorise(value, styleType) { + const color = ansiColors[styles[styleType]] || ansiColors[styleType] || ""; + if (!color) { + return String(value); + } + return `\x1B[${color[0]}m${String(value)}\x1B[${color[1]}m`; +} +__name(colorise, "colorise"); +function normaliseOptions({ + showHidden = false, + depth = 2, + colors = false, + customInspect = true, + showProxy = false, + maxArrayLength = Infinity, + breakLength = Infinity, + seen = [], + // eslint-disable-next-line no-shadow + truncate: truncate2 = Infinity, + stylize = String +} = {}, inspect3) { + const options = { + showHidden: Boolean(showHidden), + depth: Number(depth), + colors: Boolean(colors), + customInspect: Boolean(customInspect), + showProxy: Boolean(showProxy), + maxArrayLength: Number(maxArrayLength), + breakLength: Number(breakLength), + truncate: Number(truncate2), + seen, + inspect: inspect3, + stylize + }; + if (options.colors) { + options.stylize = colorise; + } + return options; +} +__name(normaliseOptions, "normaliseOptions"); +function isHighSurrogate(char) { + return char >= "\uD800" && char <= "\uDBFF"; +} +__name(isHighSurrogate, "isHighSurrogate"); +function truncate(string, length, tail = truncator) { + string = String(string); + const tailLength = tail.length; + const stringLength = string.length; + if (tailLength > length && stringLength > tailLength) { + return tail; + } + if (stringLength > length && stringLength > tailLength) { + let end = length - tailLength; + if (end > 0 && isHighSurrogate(string[end - 1])) { + end = end - 1; + } + return `${string.slice(0, end)}${tail}`; + } + return string; +} +__name(truncate, "truncate"); +function inspectList(list, options, inspectItem, separator = ", ") { + inspectItem = inspectItem || options.inspect; + const size = list.length; + if (size === 0) + return ""; + const originalLength = options.truncate; + let output = ""; + let peek = ""; + let truncated = ""; + for (let i = 0; i < size; i += 1) { + const last = i + 1 === list.length; + const secondToLast = i + 2 === list.length; + truncated = `${truncator}(${list.length - i})`; + const value = list[i]; + options.truncate = originalLength - output.length - (last ? 0 : separator.length); + const string = peek || inspectItem(value, options) + (last ? "" : separator); + const nextLength = output.length + string.length; + const truncatedLength = nextLength + truncated.length; + if (last && nextLength > originalLength && output.length + truncated.length <= originalLength) { + break; + } + if (!last && !secondToLast && truncatedLength > originalLength) { + break; + } + peek = last ? "" : inspectItem(list[i + 1], options) + (secondToLast ? "" : separator); + if (!last && secondToLast && truncatedLength > originalLength && nextLength + peek.length > originalLength) { + break; + } + output += string; + if (!last && !secondToLast && nextLength + peek.length >= originalLength) { + truncated = `${truncator}(${list.length - i - 1})`; + break; + } + truncated = ""; + } + return `${output}${truncated}`; +} +__name(inspectList, "inspectList"); +function quoteComplexKey(key) { + if (key.match(/^[a-zA-Z_][a-zA-Z_0-9]*$/)) { + return key; + } + return JSON.stringify(key).replace(/'/g, "\\'").replace(/\\"/g, '"').replace(/(^"|"$)/g, "'"); +} +__name(quoteComplexKey, "quoteComplexKey"); +function inspectProperty([key, value], options) { + options.truncate -= 2; + if (typeof key === "string") { + key = quoteComplexKey(key); + } else if (typeof key !== "number") { + key = `[${options.inspect(key, options)}]`; + } + options.truncate -= key.length; + value = options.inspect(value, options); + return `${key}: ${value}`; +} +__name(inspectProperty, "inspectProperty"); + +// node_modules/loupe/lib/array.js +function inspectArray(array, options) { + const nonIndexProperties = Object.keys(array).slice(array.length); + if (!array.length && !nonIndexProperties.length) + return "[]"; + options.truncate -= 4; + const listContents = inspectList(array, options); + options.truncate -= listContents.length; + let propertyContents = ""; + if (nonIndexProperties.length) { + propertyContents = inspectList(nonIndexProperties.map((key) => [key, array[key]]), options, inspectProperty); + } + return `[ ${listContents}${propertyContents ? `, ${propertyContents}` : ""} ]`; +} +__name(inspectArray, "inspectArray"); + +// node_modules/loupe/lib/typedarray.js +var getArrayName = /* @__PURE__ */ __name((array) => { + if (typeof Buffer === "function" && array instanceof Buffer) { + return "Buffer"; + } + if (array[Symbol.toStringTag]) { + return array[Symbol.toStringTag]; + } + return array.constructor.name; +}, "getArrayName"); +function inspectTypedArray(array, options) { + const name = getArrayName(array); + options.truncate -= name.length + 4; + const nonIndexProperties = Object.keys(array).slice(array.length); + if (!array.length && !nonIndexProperties.length) + return `${name}[]`; + let output = ""; + for (let i = 0; i < array.length; i++) { + const string = `${options.stylize(truncate(array[i], options.truncate), "number")}${i === array.length - 1 ? "" : ", "}`; + options.truncate -= string.length; + if (array[i] !== array.length && options.truncate <= 3) { + output += `${truncator}(${array.length - array[i] + 1})`; + break; + } + output += string; + } + let propertyContents = ""; + if (nonIndexProperties.length) { + propertyContents = inspectList(nonIndexProperties.map((key) => [key, array[key]]), options, inspectProperty); + } + return `${name}[ ${output}${propertyContents ? `, ${propertyContents}` : ""} ]`; +} +__name(inspectTypedArray, "inspectTypedArray"); + +// node_modules/loupe/lib/date.js +function inspectDate(dateObject, options) { + const stringRepresentation = dateObject.toJSON(); + if (stringRepresentation === null) { + return "Invalid Date"; + } + const split = stringRepresentation.split("T"); + const date = split[0]; + return options.stylize(`${date}T${truncate(split[1], options.truncate - date.length - 1)}`, "date"); +} +__name(inspectDate, "inspectDate"); + +// node_modules/loupe/lib/function.js +function inspectFunction(func, options) { + const functionType = func[Symbol.toStringTag] || "Function"; + const name = func.name; + if (!name) { + return options.stylize(`[${functionType}]`, "special"); + } + return options.stylize(`[${functionType} ${truncate(name, options.truncate - 11)}]`, "special"); +} +__name(inspectFunction, "inspectFunction"); + +// node_modules/loupe/lib/map.js +function inspectMapEntry([key, value], options) { + options.truncate -= 4; + key = options.inspect(key, options); + options.truncate -= key.length; + value = options.inspect(value, options); + return `${key} => ${value}`; +} +__name(inspectMapEntry, "inspectMapEntry"); +function mapToEntries(map) { + const entries = []; + map.forEach((value, key) => { + entries.push([key, value]); + }); + return entries; +} +__name(mapToEntries, "mapToEntries"); +function inspectMap(map, options) { + if (map.size === 0) + return "Map{}"; + options.truncate -= 7; + return `Map{ ${inspectList(mapToEntries(map), options, inspectMapEntry)} }`; +} +__name(inspectMap, "inspectMap"); + +// node_modules/loupe/lib/number.js +var isNaN = Number.isNaN || ((i) => i !== i); +function inspectNumber(number, options) { + if (isNaN(number)) { + return options.stylize("NaN", "number"); + } + if (number === Infinity) { + return options.stylize("Infinity", "number"); + } + if (number === -Infinity) { + return options.stylize("-Infinity", "number"); + } + if (number === 0) { + return options.stylize(1 / number === Infinity ? "+0" : "-0", "number"); + } + return options.stylize(truncate(String(number), options.truncate), "number"); +} +__name(inspectNumber, "inspectNumber"); + +// node_modules/loupe/lib/bigint.js +function inspectBigInt(number, options) { + let nums = truncate(number.toString(), options.truncate - 1); + if (nums !== truncator) + nums += "n"; + return options.stylize(nums, "bigint"); +} +__name(inspectBigInt, "inspectBigInt"); + +// node_modules/loupe/lib/regexp.js +function inspectRegExp(value, options) { + const flags = value.toString().split("/")[2]; + const sourceLength = options.truncate - (2 + flags.length); + const source = value.source; + return options.stylize(`/${truncate(source, sourceLength)}/${flags}`, "regexp"); +} +__name(inspectRegExp, "inspectRegExp"); + +// node_modules/loupe/lib/set.js +function arrayFromSet(set2) { + const values = []; + set2.forEach((value) => { + values.push(value); + }); + return values; +} +__name(arrayFromSet, "arrayFromSet"); +function inspectSet(set2, options) { + if (set2.size === 0) + return "Set{}"; + options.truncate -= 7; + return `Set{ ${inspectList(arrayFromSet(set2), options)} }`; +} +__name(inspectSet, "inspectSet"); + +// node_modules/loupe/lib/string.js +var stringEscapeChars = new RegExp("['\\u0000-\\u001f\\u007f-\\u009f\\u00ad\\u0600-\\u0604\\u070f\\u17b4\\u17b5\\u200c-\\u200f\\u2028-\\u202f\\u2060-\\u206f\\ufeff\\ufff0-\\uffff]", "g"); +var escapeCharacters = { + "\b": "\\b", + " ": "\\t", + "\n": "\\n", + "\f": "\\f", + "\r": "\\r", + "'": "\\'", + "\\": "\\\\" +}; +var hex = 16; +var unicodeLength = 4; +function escape(char) { + return escapeCharacters[char] || `\\u${`0000${char.charCodeAt(0).toString(hex)}`.slice(-unicodeLength)}`; +} +__name(escape, "escape"); +function inspectString(string, options) { + if (stringEscapeChars.test(string)) { + string = string.replace(stringEscapeChars, escape); + } + return options.stylize(`'${truncate(string, options.truncate - 2)}'`, "string"); +} +__name(inspectString, "inspectString"); + +// node_modules/loupe/lib/symbol.js +function inspectSymbol(value) { + if ("description" in Symbol.prototype) { + return value.description ? `Symbol(${value.description})` : "Symbol()"; + } + return value.toString(); +} +__name(inspectSymbol, "inspectSymbol"); + +// node_modules/loupe/lib/promise.js +var getPromiseValue = /* @__PURE__ */ __name(() => "Promise{\u2026}", "getPromiseValue"); +var promise_default = getPromiseValue; + +// node_modules/loupe/lib/object.js +function inspectObject(object, options) { + const properties = Object.getOwnPropertyNames(object); + const symbols = Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols(object) : []; + if (properties.length === 0 && symbols.length === 0) { + return "{}"; + } + options.truncate -= 4; + options.seen = options.seen || []; + if (options.seen.includes(object)) { + return "[Circular]"; + } + options.seen.push(object); + const propertyContents = inspectList(properties.map((key) => [key, object[key]]), options, inspectProperty); + const symbolContents = inspectList(symbols.map((key) => [key, object[key]]), options, inspectProperty); + options.seen.pop(); + let sep = ""; + if (propertyContents && symbolContents) { + sep = ", "; + } + return `{ ${propertyContents}${sep}${symbolContents} }`; +} +__name(inspectObject, "inspectObject"); + +// node_modules/loupe/lib/class.js +var toStringTag = typeof Symbol !== "undefined" && Symbol.toStringTag ? Symbol.toStringTag : false; +function inspectClass(value, options) { + let name = ""; + if (toStringTag && toStringTag in value) { + name = value[toStringTag]; + } + name = name || value.constructor.name; + if (!name || name === "_class") { + name = ""; + } + options.truncate -= name.length; + return `${name}${inspectObject(value, options)}`; +} +__name(inspectClass, "inspectClass"); + +// node_modules/loupe/lib/arguments.js +function inspectArguments(args, options) { + if (args.length === 0) + return "Arguments[]"; + options.truncate -= 13; + return `Arguments[ ${inspectList(args, options)} ]`; +} +__name(inspectArguments, "inspectArguments"); + +// node_modules/loupe/lib/error.js +var errorKeys = [ + "stack", + "line", + "column", + "name", + "message", + "fileName", + "lineNumber", + "columnNumber", + "number", + "description", + "cause" +]; +function inspectObject2(error, options) { + const properties = Object.getOwnPropertyNames(error).filter((key) => errorKeys.indexOf(key) === -1); + const name = error.name; + options.truncate -= name.length; + let message = ""; + if (typeof error.message === "string") { + message = truncate(error.message, options.truncate); + } else { + properties.unshift("message"); + } + message = message ? `: ${message}` : ""; + options.truncate -= message.length + 5; + options.seen = options.seen || []; + if (options.seen.includes(error)) { + return "[Circular]"; + } + options.seen.push(error); + const propertyContents = inspectList(properties.map((key) => [key, error[key]]), options, inspectProperty); + return `${name}${message}${propertyContents ? ` { ${propertyContents} }` : ""}`; +} +__name(inspectObject2, "inspectObject"); + +// node_modules/loupe/lib/html.js +function inspectAttribute([key, value], options) { + options.truncate -= 3; + if (!value) { + return `${options.stylize(String(key), "yellow")}`; + } + return `${options.stylize(String(key), "yellow")}=${options.stylize(`"${value}"`, "string")}`; +} +__name(inspectAttribute, "inspectAttribute"); +function inspectNodeCollection(collection, options) { + return inspectList(collection, options, inspectNode, "\n"); +} +__name(inspectNodeCollection, "inspectNodeCollection"); +function inspectNode(node, options) { + switch (node.nodeType) { + case 1: + return inspectHTML(node, options); + case 3: + return options.inspect(node.data, options); + default: + return options.inspect(node, options); + } +} +__name(inspectNode, "inspectNode"); +function inspectHTML(element, options) { + const properties = element.getAttributeNames(); + const name = element.tagName.toLowerCase(); + const head = options.stylize(`<${name}`, "special"); + const headClose = options.stylize(`>`, "special"); + const tail = options.stylize(``, "special"); + options.truncate -= name.length * 2 + 5; + let propertyContents = ""; + if (properties.length > 0) { + propertyContents += " "; + propertyContents += inspectList(properties.map((key) => [key, element.getAttribute(key)]), options, inspectAttribute, " "); + } + options.truncate -= propertyContents.length; + const truncate2 = options.truncate; + let children = inspectNodeCollection(element.children, options); + if (children && children.length > truncate2) { + children = `${truncator}(${element.children.length})`; + } + return `${head}${propertyContents}${headClose}${children}${tail}`; +} +__name(inspectHTML, "inspectHTML"); + +// node_modules/loupe/lib/index.js +var symbolsSupported = typeof Symbol === "function" && typeof Symbol.for === "function"; +var chaiInspect = symbolsSupported ? /* @__PURE__ */ Symbol.for("chai/inspect") : "@@chai/inspect"; +var nodeInspect = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom"); +var constructorMap = /* @__PURE__ */ new WeakMap(); +var stringTagMap = {}; +var baseTypesMap = { + undefined: /* @__PURE__ */ __name((value, options) => options.stylize("undefined", "undefined"), "undefined"), + null: /* @__PURE__ */ __name((value, options) => options.stylize("null", "null"), "null"), + boolean: /* @__PURE__ */ __name((value, options) => options.stylize(String(value), "boolean"), "boolean"), + Boolean: /* @__PURE__ */ __name((value, options) => options.stylize(String(value), "boolean"), "Boolean"), + number: inspectNumber, + Number: inspectNumber, + bigint: inspectBigInt, + BigInt: inspectBigInt, + string: inspectString, + String: inspectString, + function: inspectFunction, + Function: inspectFunction, + symbol: inspectSymbol, + // A Symbol polyfill will return `Symbol` not `symbol` from typedetect + Symbol: inspectSymbol, + Array: inspectArray, + Date: inspectDate, + Map: inspectMap, + Set: inspectSet, + RegExp: inspectRegExp, + Promise: promise_default, + // WeakSet, WeakMap are totally opaque to us + WeakSet: /* @__PURE__ */ __name((value, options) => options.stylize("WeakSet{\u2026}", "special"), "WeakSet"), + WeakMap: /* @__PURE__ */ __name((value, options) => options.stylize("WeakMap{\u2026}", "special"), "WeakMap"), + Arguments: inspectArguments, + Int8Array: inspectTypedArray, + Uint8Array: inspectTypedArray, + Uint8ClampedArray: inspectTypedArray, + Int16Array: inspectTypedArray, + Uint16Array: inspectTypedArray, + Int32Array: inspectTypedArray, + Uint32Array: inspectTypedArray, + Float32Array: inspectTypedArray, + Float64Array: inspectTypedArray, + Generator: /* @__PURE__ */ __name(() => "", "Generator"), + DataView: /* @__PURE__ */ __name(() => "", "DataView"), + ArrayBuffer: /* @__PURE__ */ __name(() => "", "ArrayBuffer"), + Error: inspectObject2, + HTMLCollection: inspectNodeCollection, + NodeList: inspectNodeCollection +}; +var inspectCustom = /* @__PURE__ */ __name((value, options, type3, inspectFn) => { + if (chaiInspect in value && typeof value[chaiInspect] === "function") { + return value[chaiInspect](options); + } + if (nodeInspect in value && typeof value[nodeInspect] === "function") { + return value[nodeInspect](options.depth, options, inspectFn); + } + if ("inspect" in value && typeof value.inspect === "function") { + return value.inspect(options.depth, options); + } + if ("constructor" in value && constructorMap.has(value.constructor)) { + return constructorMap.get(value.constructor)(value, options); + } + if (stringTagMap[type3]) { + return stringTagMap[type3](value, options); + } + return ""; +}, "inspectCustom"); +var toString = Object.prototype.toString; +function inspect(value, opts = {}) { + const options = normaliseOptions(opts, inspect); + const { customInspect } = options; + let type3 = value === null ? "null" : typeof value; + if (type3 === "object") { + type3 = toString.call(value).slice(8, -1); + } + if (type3 in baseTypesMap) { + return baseTypesMap[type3](value, options); + } + if (customInspect && value) { + const output = inspectCustom(value, options, type3, inspect); + if (output) { + if (typeof output === "string") + return output; + return inspect(output, options); + } + } + const proto = value ? Object.getPrototypeOf(value) : false; + if (proto === Object.prototype || proto === null) { + return inspectObject(value, options); + } + if (value && typeof HTMLElement === "function" && value instanceof HTMLElement) { + return inspectHTML(value, options); + } + if ("constructor" in value) { + if (value.constructor !== Object) { + return inspectClass(value, options); + } + return inspectObject(value, options); + } + if (value === Object(value)) { + return inspectObject(value, options); + } + return options.stylize(String(value), type3); +} +__name(inspect, "inspect"); + +// lib/chai/config.js +var config = { + /** + * ### config.includeStack + * + * User configurable property, influences whether stack trace + * is included in Assertion error message. Default of false + * suppresses stack trace in the error message. + * + * chai.config.includeStack = true; // enable stack on error + * + * @param {boolean} + * @public + */ + includeStack: false, + /** + * ### config.showDiff + * + * User configurable property, influences whether or not + * the `showDiff` flag should be included in the thrown + * AssertionErrors. `false` will always be `false`; `true` + * will be true when the assertion has requested a diff + * be shown. + * + * @param {boolean} + * @public + */ + showDiff: true, + /** + * ### config.truncateThreshold + * + * User configurable property, sets length threshold for actual and + * expected values in assertion errors. If this threshold is exceeded, for + * example for large data structures, the value is replaced with something + * like `[ Array(3) ]` or `{ Object (prop1, prop2) }`. + * + * Set it to zero if you want to disable truncating altogether. + * + * This is especially userful when doing assertions on arrays: having this + * set to a reasonable large value makes the failure messages readily + * inspectable. + * + * chai.config.truncateThreshold = 0; // disable truncating + * + * @param {number} + * @public + */ + truncateThreshold: 40, + /** + * ### config.useProxy + * + * User configurable property, defines if chai will use a Proxy to throw + * an error when a non-existent property is read, which protects users + * from typos when using property-based assertions. + * + * Set it to false if you want to disable this feature. + * + * chai.config.useProxy = false; // disable use of Proxy + * + * This feature is automatically disabled regardless of this config value + * in environments that don't support proxies. + * + * @param {boolean} + * @public + */ + useProxy: true, + /** + * ### config.proxyExcludedKeys + * + * User configurable property, defines which properties should be ignored + * instead of throwing an error if they do not exist on the assertion. + * This is only applied if the environment Chai is running in supports proxies and + * if the `useProxy` configuration setting is enabled. + * By default, `then` and `inspect` will not throw an error if they do not exist on the + * assertion object because the `.inspect` property is read by `util.inspect` (for example, when + * using `console.log` on the assertion object) and `.then` is necessary for promise type-checking. + * + * // By default these keys will not throw an error if they do not exist on the assertion object + * chai.config.proxyExcludedKeys = ['then', 'inspect']; + * + * @param {Array} + * @public + */ + proxyExcludedKeys: ["then", "catch", "inspect", "toJSON"], + /** + * ### config.deepEqual + * + * User configurable property, defines which a custom function to use for deepEqual + * comparisons. + * By default, the function used is the one from the `deep-eql` package without custom comparator. + * + * // use a custom comparator + * chai.config.deepEqual = (expected, actual) => { + * return chai.util.eql(expected, actual, { + * comparator: (expected, actual) => { + * // for non number comparison, use the default behavior + * if(typeof expected !== 'number') return null; + * // allow a difference of 10 between compared numbers + * return typeof actual === 'number' && Math.abs(actual - expected) < 10 + * } + * }) + * }; + * + * @param {Function} + * @public + */ + deepEqual: null +}; + +// lib/chai/utils/inspect.js +function inspect2(obj, showHidden, depth, colors) { + let options = { + colors, + depth: typeof depth === "undefined" ? 2 : depth, + showHidden, + truncate: config.truncateThreshold ? config.truncateThreshold : Infinity + }; + return inspect(obj, options); +} +__name(inspect2, "inspect"); + +// lib/chai/utils/objDisplay.js +function objDisplay(obj) { + let str = inspect2(obj), type3 = Object.prototype.toString.call(obj); + if (config.truncateThreshold && str.length >= config.truncateThreshold) { + if (type3 === "[object Function]") { + return !obj.name || obj.name === "" ? "[Function]" : "[Function: " + obj.name + "]"; + } else if (type3 === "[object Array]") { + return "[ Array(" + obj.length + ") ]"; + } else if (type3 === "[object Object]") { + let keys = Object.keys(obj), kstr = keys.length > 2 ? keys.splice(0, 2).join(", ") + ", ..." : keys.join(", "); + return "{ Object (" + kstr + ") }"; + } else { + return str; + } + } else { + return str; + } +} +__name(objDisplay, "objDisplay"); + +// lib/chai/utils/getMessage.js +function getMessage2(obj, args) { + let negate = flag(obj, "negate"); + let val = flag(obj, "object"); + let expected = args[3]; + let actual = getActual(obj, args); + let msg = negate ? args[2] : args[1]; + let flagMsg = flag(obj, "message"); + if (typeof msg === "function") msg = msg(); + msg = msg || ""; + msg = msg.replace(/#\{this\}/g, function() { + return objDisplay(val); + }).replace(/#\{act\}/g, function() { + return objDisplay(actual); + }).replace(/#\{exp\}/g, function() { + return objDisplay(expected); + }); + return flagMsg ? flagMsg + ": " + msg : msg; +} +__name(getMessage2, "getMessage"); + +// lib/chai/utils/transferFlags.js +function transferFlags(assertion, object, includeAll) { + let flags = assertion.__flags || (assertion.__flags = /* @__PURE__ */ Object.create(null)); + if (!object.__flags) { + object.__flags = /* @__PURE__ */ Object.create(null); + } + includeAll = arguments.length === 3 ? includeAll : true; + for (let flag3 in flags) { + if (includeAll || flag3 !== "object" && flag3 !== "ssfi" && flag3 !== "lockSsfi" && flag3 != "message") { + object.__flags[flag3] = flags[flag3]; + } + } +} +__name(transferFlags, "transferFlags"); + +// node_modules/deep-eql/index.js +function type2(obj) { + if (typeof obj === "undefined") { + return "undefined"; + } + if (obj === null) { + return "null"; + } + const stringTag = obj[Symbol.toStringTag]; + if (typeof stringTag === "string") { + return stringTag; + } + const sliceStart = 8; + const sliceEnd = -1; + return Object.prototype.toString.call(obj).slice(sliceStart, sliceEnd); +} +__name(type2, "type"); +function FakeMap() { + this._key = "chai/deep-eql__" + Math.random() + Date.now(); +} +__name(FakeMap, "FakeMap"); +FakeMap.prototype = { + get: /* @__PURE__ */ __name(function get(key) { + return key[this._key]; + }, "get"), + set: /* @__PURE__ */ __name(function set(key, value) { + if (Object.isExtensible(key)) { + Object.defineProperty(key, this._key, { + value, + configurable: true + }); + } + }, "set") +}; +var MemoizeMap = typeof WeakMap === "function" ? WeakMap : FakeMap; +function memoizeCompare(leftHandOperand, rightHandOperand, memoizeMap) { + if (!memoizeMap || isPrimitive(leftHandOperand) || isPrimitive(rightHandOperand)) { + return null; + } + var leftHandMap = memoizeMap.get(leftHandOperand); + if (leftHandMap) { + var result = leftHandMap.get(rightHandOperand); + if (typeof result === "boolean") { + return result; + } + } + return null; +} +__name(memoizeCompare, "memoizeCompare"); +function memoizeSet(leftHandOperand, rightHandOperand, memoizeMap, result) { + if (!memoizeMap || isPrimitive(leftHandOperand) || isPrimitive(rightHandOperand)) { + return; + } + var leftHandMap = memoizeMap.get(leftHandOperand); + if (leftHandMap) { + leftHandMap.set(rightHandOperand, result); + } else { + leftHandMap = new MemoizeMap(); + leftHandMap.set(rightHandOperand, result); + memoizeMap.set(leftHandOperand, leftHandMap); + } +} +__name(memoizeSet, "memoizeSet"); +var deep_eql_default = deepEqual; +function deepEqual(leftHandOperand, rightHandOperand, options) { + if (options && options.comparator) { + return extensiveDeepEqual(leftHandOperand, rightHandOperand, options); + } + var simpleResult = simpleEqual(leftHandOperand, rightHandOperand); + if (simpleResult !== null) { + return simpleResult; + } + return extensiveDeepEqual(leftHandOperand, rightHandOperand, options); +} +__name(deepEqual, "deepEqual"); +function simpleEqual(leftHandOperand, rightHandOperand) { + if (leftHandOperand === rightHandOperand) { + return leftHandOperand !== 0 || 1 / leftHandOperand === 1 / rightHandOperand; + } + if (leftHandOperand !== leftHandOperand && // eslint-disable-line no-self-compare + rightHandOperand !== rightHandOperand) { + return true; + } + if (isPrimitive(leftHandOperand) || isPrimitive(rightHandOperand)) { + return false; + } + return null; +} +__name(simpleEqual, "simpleEqual"); +function extensiveDeepEqual(leftHandOperand, rightHandOperand, options) { + options = options || {}; + options.memoize = options.memoize === false ? false : options.memoize || new MemoizeMap(); + var comparator = options && options.comparator; + var memoizeResultLeft = memoizeCompare(leftHandOperand, rightHandOperand, options.memoize); + if (memoizeResultLeft !== null) { + return memoizeResultLeft; + } + var memoizeResultRight = memoizeCompare(rightHandOperand, leftHandOperand, options.memoize); + if (memoizeResultRight !== null) { + return memoizeResultRight; + } + if (comparator) { + var comparatorResult = comparator(leftHandOperand, rightHandOperand); + if (comparatorResult === false || comparatorResult === true) { + memoizeSet(leftHandOperand, rightHandOperand, options.memoize, comparatorResult); + return comparatorResult; + } + var simpleResult = simpleEqual(leftHandOperand, rightHandOperand); + if (simpleResult !== null) { + return simpleResult; + } + } + var leftHandType = type2(leftHandOperand); + if (leftHandType !== type2(rightHandOperand)) { + memoizeSet(leftHandOperand, rightHandOperand, options.memoize, false); + return false; + } + memoizeSet(leftHandOperand, rightHandOperand, options.memoize, true); + var result = extensiveDeepEqualByType(leftHandOperand, rightHandOperand, leftHandType, options); + memoizeSet(leftHandOperand, rightHandOperand, options.memoize, result); + return result; +} +__name(extensiveDeepEqual, "extensiveDeepEqual"); +function extensiveDeepEqualByType(leftHandOperand, rightHandOperand, leftHandType, options) { + switch (leftHandType) { + case "String": + case "Number": + case "Boolean": + case "Date": + return deepEqual(leftHandOperand.valueOf(), rightHandOperand.valueOf()); + case "Promise": + case "Symbol": + case "function": + case "WeakMap": + case "WeakSet": + return leftHandOperand === rightHandOperand; + case "Error": + return keysEqual(leftHandOperand, rightHandOperand, ["name", "message", "code"], options); + case "Arguments": + case "Int8Array": + case "Uint8Array": + case "Uint8ClampedArray": + case "Int16Array": + case "Uint16Array": + case "Int32Array": + case "Uint32Array": + case "Float32Array": + case "Float64Array": + case "Array": + return iterableEqual(leftHandOperand, rightHandOperand, options); + case "RegExp": + return regexpEqual(leftHandOperand, rightHandOperand); + case "Generator": + return generatorEqual(leftHandOperand, rightHandOperand, options); + case "DataView": + return iterableEqual(new Uint8Array(leftHandOperand.buffer), new Uint8Array(rightHandOperand.buffer), options); + case "ArrayBuffer": + return iterableEqual(new Uint8Array(leftHandOperand), new Uint8Array(rightHandOperand), options); + case "Set": + return entriesEqual(leftHandOperand, rightHandOperand, options); + case "Map": + return entriesEqual(leftHandOperand, rightHandOperand, options); + case "Temporal.PlainDate": + case "Temporal.PlainTime": + case "Temporal.PlainDateTime": + case "Temporal.Instant": + case "Temporal.ZonedDateTime": + case "Temporal.PlainYearMonth": + case "Temporal.PlainMonthDay": + return leftHandOperand.equals(rightHandOperand); + case "Temporal.Duration": + return leftHandOperand.total("nanoseconds") === rightHandOperand.total("nanoseconds"); + case "Temporal.TimeZone": + case "Temporal.Calendar": + return leftHandOperand.toString() === rightHandOperand.toString(); + default: + return objectEqual(leftHandOperand, rightHandOperand, options); + } +} +__name(extensiveDeepEqualByType, "extensiveDeepEqualByType"); +function regexpEqual(leftHandOperand, rightHandOperand) { + return leftHandOperand.toString() === rightHandOperand.toString(); +} +__name(regexpEqual, "regexpEqual"); +function entriesEqual(leftHandOperand, rightHandOperand, options) { + try { + if (leftHandOperand.size !== rightHandOperand.size) { + return false; + } + if (leftHandOperand.size === 0) { + return true; + } + } catch (sizeError) { + return false; + } + var leftHandItems = []; + var rightHandItems = []; + leftHandOperand.forEach(/* @__PURE__ */ __name(function gatherEntries(key, value) { + leftHandItems.push([key, value]); + }, "gatherEntries")); + rightHandOperand.forEach(/* @__PURE__ */ __name(function gatherEntries(key, value) { + rightHandItems.push([key, value]); + }, "gatherEntries")); + return iterableEqual(leftHandItems.sort(), rightHandItems.sort(), options); +} +__name(entriesEqual, "entriesEqual"); +function iterableEqual(leftHandOperand, rightHandOperand, options) { + var length = leftHandOperand.length; + if (length !== rightHandOperand.length) { + return false; + } + if (length === 0) { + return true; + } + var index = -1; + while (++index < length) { + if (deepEqual(leftHandOperand[index], rightHandOperand[index], options) === false) { + return false; + } + } + return true; +} +__name(iterableEqual, "iterableEqual"); +function generatorEqual(leftHandOperand, rightHandOperand, options) { + return iterableEqual(getGeneratorEntries(leftHandOperand), getGeneratorEntries(rightHandOperand), options); +} +__name(generatorEqual, "generatorEqual"); +function hasIteratorFunction(target) { + return typeof Symbol !== "undefined" && typeof target === "object" && typeof Symbol.iterator !== "undefined" && typeof target[Symbol.iterator] === "function"; +} +__name(hasIteratorFunction, "hasIteratorFunction"); +function getIteratorEntries(target) { + if (hasIteratorFunction(target)) { + try { + return getGeneratorEntries(target[Symbol.iterator]()); + } catch (iteratorError) { + return []; + } + } + return []; +} +__name(getIteratorEntries, "getIteratorEntries"); +function getGeneratorEntries(generator) { + var generatorResult = generator.next(); + var accumulator = [generatorResult.value]; + while (generatorResult.done === false) { + generatorResult = generator.next(); + accumulator.push(generatorResult.value); + } + return accumulator; +} +__name(getGeneratorEntries, "getGeneratorEntries"); +function getEnumerableKeys(target) { + var keys = []; + for (var key in target) { + keys.push(key); + } + return keys; +} +__name(getEnumerableKeys, "getEnumerableKeys"); +function getEnumerableSymbols(target) { + var keys = []; + var allKeys = Object.getOwnPropertySymbols(target); + for (var i = 0; i < allKeys.length; i += 1) { + var key = allKeys[i]; + if (Object.getOwnPropertyDescriptor(target, key).enumerable) { + keys.push(key); + } + } + return keys; +} +__name(getEnumerableSymbols, "getEnumerableSymbols"); +function keysEqual(leftHandOperand, rightHandOperand, keys, options) { + var length = keys.length; + if (length === 0) { + return true; + } + for (var i = 0; i < length; i += 1) { + if (deepEqual(leftHandOperand[keys[i]], rightHandOperand[keys[i]], options) === false) { + return false; + } + } + return true; +} +__name(keysEqual, "keysEqual"); +function objectEqual(leftHandOperand, rightHandOperand, options) { + var leftHandKeys = getEnumerableKeys(leftHandOperand); + var rightHandKeys = getEnumerableKeys(rightHandOperand); + var leftHandSymbols = getEnumerableSymbols(leftHandOperand); + var rightHandSymbols = getEnumerableSymbols(rightHandOperand); + leftHandKeys = leftHandKeys.concat(leftHandSymbols); + rightHandKeys = rightHandKeys.concat(rightHandSymbols); + if (leftHandKeys.length && leftHandKeys.length === rightHandKeys.length) { + if (iterableEqual(mapSymbols(leftHandKeys).sort(), mapSymbols(rightHandKeys).sort()) === false) { + return false; + } + return keysEqual(leftHandOperand, rightHandOperand, leftHandKeys, options); + } + var leftHandEntries = getIteratorEntries(leftHandOperand); + var rightHandEntries = getIteratorEntries(rightHandOperand); + if (leftHandEntries.length && leftHandEntries.length === rightHandEntries.length) { + leftHandEntries.sort(); + rightHandEntries.sort(); + return iterableEqual(leftHandEntries, rightHandEntries, options); + } + if (leftHandKeys.length === 0 && leftHandEntries.length === 0 && rightHandKeys.length === 0 && rightHandEntries.length === 0) { + return true; + } + return false; +} +__name(objectEqual, "objectEqual"); +function isPrimitive(value) { + return value === null || typeof value !== "object"; +} +__name(isPrimitive, "isPrimitive"); +function mapSymbols(arr) { + return arr.map(/* @__PURE__ */ __name(function mapSymbol(entry) { + if (typeof entry === "symbol") { + return entry.toString(); + } + return entry; + }, "mapSymbol")); +} +__name(mapSymbols, "mapSymbols"); + +// node_modules/pathval/index.js +function hasProperty(obj, name) { + if (typeof obj === "undefined" || obj === null) { + return false; + } + return name in Object(obj); +} +__name(hasProperty, "hasProperty"); +function parsePath(path) { + const str = path.replace(/([^\\])\[/g, "$1.["); + const parts = str.match(/(\\\.|[^.]+?)+/g); + return parts.map((value) => { + if (value === "constructor" || value === "__proto__" || value === "prototype") { + return {}; + } + const regexp = /^\[(\d+)\]$/; + const mArr = regexp.exec(value); + let parsed = null; + if (mArr) { + parsed = { i: parseFloat(mArr[1]) }; + } else { + parsed = { p: value.replace(/\\([.[\]])/g, "$1") }; + } + return parsed; + }); +} +__name(parsePath, "parsePath"); +function internalGetPathValue(obj, parsed, pathDepth) { + let temporaryValue = obj; + let res = null; + pathDepth = typeof pathDepth === "undefined" ? parsed.length : pathDepth; + for (let i = 0; i < pathDepth; i++) { + const part = parsed[i]; + if (temporaryValue) { + if (typeof part.p === "undefined") { + temporaryValue = temporaryValue[part.i]; + } else { + temporaryValue = temporaryValue[part.p]; + } + if (i === pathDepth - 1) { + res = temporaryValue; + } + } + } + return res; +} +__name(internalGetPathValue, "internalGetPathValue"); +function getPathInfo(obj, path) { + const parsed = parsePath(path); + const last = parsed[parsed.length - 1]; + const info = { + parent: parsed.length > 1 ? internalGetPathValue(obj, parsed, parsed.length - 1) : obj, + name: last.p || last.i, + value: internalGetPathValue(obj, parsed) + }; + info.exists = hasProperty(info.parent, info.name); + return info; +} +__name(getPathInfo, "getPathInfo"); + +// lib/chai/assertion.js +var _Assertion = class _Assertion { + /** + * Creates object for chaining. + * `Assertion` objects contain metadata in the form of flags. Three flags can + * be assigned during instantiation by passing arguments to this constructor: + * + * - `object`: This flag contains the target of the assertion. For example, in + * the assertion `expect(numKittens).to.equal(7);`, the `object` flag will + * contain `numKittens` so that the `equal` assertion can reference it when + * needed. + * + * - `message`: This flag contains an optional custom error message to be + * prepended to the error message that's generated by the assertion when it + * fails. + * + * - `ssfi`: This flag stands for "start stack function indicator". It + * contains a function reference that serves as the starting point for + * removing frames from the stack trace of the error that's created by the + * assertion when it fails. The goal is to provide a cleaner stack trace to + * end users by removing Chai's internal functions. Note that it only works + * in environments that support `Error.captureStackTrace`, and only when + * `Chai.config.includeStack` hasn't been set to `false`. + * + * - `lockSsfi`: This flag controls whether or not the given `ssfi` flag + * should retain its current value, even as assertions are chained off of + * this object. This is usually set to `true` when creating a new assertion + * from within another assertion. It's also temporarily set to `true` before + * an overwritten assertion gets called by the overwriting assertion. + * + * - `eql`: This flag contains the deepEqual function to be used by the assertion. + * + * @param {unknown} obj target of the assertion + * @param {string} [msg] (optional) custom error message + * @param {Function} [ssfi] (optional) starting point for removing stack frames + * @param {boolean} [lockSsfi] (optional) whether or not the ssfi flag is locked + */ + constructor(obj, msg, ssfi, lockSsfi) { + /** @type {{}} */ + __publicField(this, "__flags", {}); + flag(this, "ssfi", ssfi || _Assertion); + flag(this, "lockSsfi", lockSsfi); + flag(this, "object", obj); + flag(this, "message", msg); + flag(this, "eql", config.deepEqual || deep_eql_default); + return proxify(this); + } + /** @returns {boolean} */ + static get includeStack() { + console.warn( + "Assertion.includeStack is deprecated, use chai.config.includeStack instead." + ); + return config.includeStack; + } + /** @param {boolean} value */ + static set includeStack(value) { + console.warn( + "Assertion.includeStack is deprecated, use chai.config.includeStack instead." + ); + config.includeStack = value; + } + /** @returns {boolean} */ + static get showDiff() { + console.warn( + "Assertion.showDiff is deprecated, use chai.config.showDiff instead." + ); + return config.showDiff; + } + /** @param {boolean} value */ + static set showDiff(value) { + console.warn( + "Assertion.showDiff is deprecated, use chai.config.showDiff instead." + ); + config.showDiff = value; + } + /** + * @param {string} name + * @param {Function} fn + */ + static addProperty(name, fn) { + addProperty(this.prototype, name, fn); + } + /** + * @param {string} name + * @param {Function} fn + */ + static addMethod(name, fn) { + addMethod(this.prototype, name, fn); + } + /** + * @param {string} name + * @param {Function} fn + * @param {Function} chainingBehavior + */ + static addChainableMethod(name, fn, chainingBehavior) { + addChainableMethod(this.prototype, name, fn, chainingBehavior); + } + /** + * @param {string} name + * @param {Function} fn + */ + static overwriteProperty(name, fn) { + overwriteProperty(this.prototype, name, fn); + } + /** + * @param {string} name + * @param {Function} fn + */ + static overwriteMethod(name, fn) { + overwriteMethod(this.prototype, name, fn); + } + /** + * @param {string} name + * @param {Function} fn + * @param {Function} chainingBehavior + */ + static overwriteChainableMethod(name, fn, chainingBehavior) { + overwriteChainableMethod(this.prototype, name, fn, chainingBehavior); + } + /** + * ### .assert(expression, message, negateMessage, expected, actual, showDiff) + * + * Executes an expression and check expectations. Throws AssertionError for reporting if test doesn't pass. + * + * @name assert + * @param {unknown} _expr to be tested + * @param {string | Function} msg or function that returns message to display if expression fails + * @param {string | Function} _negateMsg or function that returns negatedMessage to display if negated expression fails + * @param {unknown} expected value (remember to check for negation) + * @param {unknown} _actual (optional) will default to `this.obj` + * @param {boolean} showDiff (optional) when set to `true`, assert will display a diff in addition to the message if expression fails + * @returns {void} + */ + assert(_expr, msg, _negateMsg, expected, _actual, showDiff) { + const ok = test(this, arguments); + if (false !== showDiff) showDiff = true; + if (void 0 === expected && void 0 === _actual) showDiff = false; + if (true !== config.showDiff) showDiff = false; + if (!ok) { + msg = getMessage2(this, arguments); + const actual = getActual(this, arguments); + const assertionErrorObjectProperties = { + actual, + expected, + showDiff + }; + const operator = getOperator(this, arguments); + if (operator) { + assertionErrorObjectProperties.operator = operator; + } + throw new AssertionError( + msg, + assertionErrorObjectProperties, + // @ts-expect-error Not sure what to do about these types yet + config.includeStack ? this.assert : flag(this, "ssfi") + ); + } + } + /** + * Quick reference to stored `actual` value for plugin developers. + * + * @returns {unknown} + */ + get _obj() { + return flag(this, "object"); + } + /** + * Quick reference to stored `actual` value for plugin developers. + * + * @param {unknown} val + */ + set _obj(val) { + flag(this, "object", val); + } +}; +__name(_Assertion, "Assertion"); +var Assertion = _Assertion; + +// lib/chai/utils/events.js +var events = new EventTarget(); +var _PluginEvent = class _PluginEvent extends Event { + constructor(type3, name, fn) { + super(type3); + this.name = String(name); + this.fn = fn; + } +}; +__name(_PluginEvent, "PluginEvent"); +var PluginEvent = _PluginEvent; + +// lib/chai/utils/isProxyEnabled.js +function isProxyEnabled() { + return config.useProxy && typeof Proxy !== "undefined" && typeof Reflect !== "undefined"; +} +__name(isProxyEnabled, "isProxyEnabled"); + +// lib/chai/utils/addProperty.js +function addProperty(ctx, name, getter) { + getter = getter === void 0 ? function() { + } : getter; + Object.defineProperty(ctx, name, { + get: /* @__PURE__ */ __name(function propertyGetter() { + if (!isProxyEnabled() && !flag(this, "lockSsfi")) { + flag(this, "ssfi", propertyGetter); + } + let result = getter.call(this); + if (result !== void 0) return result; + let newAssertion = new Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + }, "propertyGetter"), + configurable: true + }); + events.dispatchEvent(new PluginEvent("addProperty", name, getter)); +} +__name(addProperty, "addProperty"); + +// lib/chai/utils/addLengthGuard.js +var fnLengthDesc = Object.getOwnPropertyDescriptor(function() { +}, "length"); +function addLengthGuard(fn, assertionName, isChainable) { + if (!fnLengthDesc.configurable) return fn; + Object.defineProperty(fn, "length", { + get: /* @__PURE__ */ __name(function() { + if (isChainable) { + throw Error( + "Invalid Chai property: " + assertionName + '.length. Due to a compatibility issue, "length" cannot directly follow "' + assertionName + '". Use "' + assertionName + '.lengthOf" instead.' + ); + } + throw Error( + "Invalid Chai property: " + assertionName + '.length. See docs for proper usage of "' + assertionName + '".' + ); + }, "get") + }); + return fn; +} +__name(addLengthGuard, "addLengthGuard"); + +// lib/chai/utils/getProperties.js +function getProperties(object) { + let result = Object.getOwnPropertyNames(object); + function addProperty2(property) { + if (result.indexOf(property) === -1) { + result.push(property); + } + } + __name(addProperty2, "addProperty"); + let proto = Object.getPrototypeOf(object); + while (proto !== null) { + Object.getOwnPropertyNames(proto).forEach(addProperty2); + proto = Object.getPrototypeOf(proto); + } + return result; +} +__name(getProperties, "getProperties"); + +// lib/chai/utils/proxify.js +var builtins = ["__flags", "__methods", "_obj", "assert"]; +function proxify(obj, nonChainableMethodName) { + if (!isProxyEnabled()) return obj; + return new Proxy(obj, { + get: /* @__PURE__ */ __name(function proxyGetter(target, property) { + if (typeof property === "string" && config.proxyExcludedKeys.indexOf(property) === -1 && !Reflect.has(target, property)) { + if (nonChainableMethodName) { + throw Error( + "Invalid Chai property: " + nonChainableMethodName + "." + property + '. See docs for proper usage of "' + nonChainableMethodName + '".' + ); + } + let suggestion = null; + let suggestionDistance = 4; + getProperties(target).forEach(function(prop) { + if ( + // we actually mean to check `Object.prototype` here + // eslint-disable-next-line no-prototype-builtins + !Object.prototype.hasOwnProperty(prop) && builtins.indexOf(prop) === -1 + ) { + let dist = stringDistanceCapped(property, prop, suggestionDistance); + if (dist < suggestionDistance) { + suggestion = prop; + suggestionDistance = dist; + } + } + }); + if (suggestion !== null) { + throw Error( + "Invalid Chai property: " + property + '. Did you mean "' + suggestion + '"?' + ); + } else { + throw Error("Invalid Chai property: " + property); + } + } + if (builtins.indexOf(property) === -1 && !flag(target, "lockSsfi")) { + flag(target, "ssfi", proxyGetter); + } + return Reflect.get(target, property); + }, "proxyGetter") + }); +} +__name(proxify, "proxify"); +function stringDistanceCapped(strA, strB, cap) { + if (Math.abs(strA.length - strB.length) >= cap) { + return cap; + } + let memo = []; + for (let i = 0; i <= strA.length; i++) { + memo[i] = Array(strB.length + 1).fill(0); + memo[i][0] = i; + } + for (let j = 0; j < strB.length; j++) { + memo[0][j] = j; + } + for (let i = 1; i <= strA.length; i++) { + let ch = strA.charCodeAt(i - 1); + for (let j = 1; j <= strB.length; j++) { + if (Math.abs(i - j) >= cap) { + memo[i][j] = cap; + continue; + } + memo[i][j] = Math.min( + memo[i - 1][j] + 1, + memo[i][j - 1] + 1, + memo[i - 1][j - 1] + (ch === strB.charCodeAt(j - 1) ? 0 : 1) + ); + } + } + return memo[strA.length][strB.length]; +} +__name(stringDistanceCapped, "stringDistanceCapped"); + +// lib/chai/utils/addMethod.js +function addMethod(ctx, name, method) { + let methodWrapper = /* @__PURE__ */ __name(function() { + if (!flag(this, "lockSsfi")) { + flag(this, "ssfi", methodWrapper); + } + let result = method.apply(this, arguments); + if (result !== void 0) return result; + let newAssertion = new Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + }, "methodWrapper"); + addLengthGuard(methodWrapper, name, false); + ctx[name] = proxify(methodWrapper, name); + events.dispatchEvent(new PluginEvent("addMethod", name, method)); +} +__name(addMethod, "addMethod"); + +// lib/chai/utils/overwriteProperty.js +function overwriteProperty(ctx, name, getter) { + let _get = Object.getOwnPropertyDescriptor(ctx, name), _super = /* @__PURE__ */ __name(function() { + }, "_super"); + if (_get && "function" === typeof _get.get) _super = _get.get; + Object.defineProperty(ctx, name, { + get: /* @__PURE__ */ __name(function overwritingPropertyGetter() { + if (!isProxyEnabled() && !flag(this, "lockSsfi")) { + flag(this, "ssfi", overwritingPropertyGetter); + } + let origLockSsfi = flag(this, "lockSsfi"); + flag(this, "lockSsfi", true); + let result = getter(_super).call(this); + flag(this, "lockSsfi", origLockSsfi); + if (result !== void 0) { + return result; + } + let newAssertion = new Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + }, "overwritingPropertyGetter"), + configurable: true + }); +} +__name(overwriteProperty, "overwriteProperty"); + +// lib/chai/utils/overwriteMethod.js +function overwriteMethod(ctx, name, method) { + let _method = ctx[name], _super = /* @__PURE__ */ __name(function() { + throw new Error(name + " is not a function"); + }, "_super"); + if (_method && "function" === typeof _method) _super = _method; + let overwritingMethodWrapper = /* @__PURE__ */ __name(function() { + if (!flag(this, "lockSsfi")) { + flag(this, "ssfi", overwritingMethodWrapper); + } + let origLockSsfi = flag(this, "lockSsfi"); + flag(this, "lockSsfi", true); + let result = method(_super).apply(this, arguments); + flag(this, "lockSsfi", origLockSsfi); + if (result !== void 0) { + return result; + } + let newAssertion = new Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + }, "overwritingMethodWrapper"); + addLengthGuard(overwritingMethodWrapper, name, false); + ctx[name] = proxify(overwritingMethodWrapper, name); +} +__name(overwriteMethod, "overwriteMethod"); + +// lib/chai/utils/addChainableMethod.js +var canSetPrototype = typeof Object.setPrototypeOf === "function"; +var testFn = /* @__PURE__ */ __name(function() { +}, "testFn"); +var excludeNames = Object.getOwnPropertyNames(testFn).filter(function(name) { + let propDesc = Object.getOwnPropertyDescriptor(testFn, name); + if (typeof propDesc !== "object") return true; + return !propDesc.configurable; +}); +var call = Function.prototype.call; +var apply = Function.prototype.apply; +var _PluginAddChainableMethodEvent = class _PluginAddChainableMethodEvent extends PluginEvent { + constructor(type3, name, fn, chainingBehavior) { + super(type3, name, fn); + this.chainingBehavior = chainingBehavior; + } +}; +__name(_PluginAddChainableMethodEvent, "PluginAddChainableMethodEvent"); +var PluginAddChainableMethodEvent = _PluginAddChainableMethodEvent; +function addChainableMethod(ctx, name, method, chainingBehavior) { + if (typeof chainingBehavior !== "function") { + chainingBehavior = /* @__PURE__ */ __name(function() { + }, "chainingBehavior"); + } + let chainableBehavior = { + method, + chainingBehavior + }; + if (!ctx.__methods) { + ctx.__methods = {}; + } + ctx.__methods[name] = chainableBehavior; + Object.defineProperty(ctx, name, { + get: /* @__PURE__ */ __name(function chainableMethodGetter() { + chainableBehavior.chainingBehavior.call(this); + let chainableMethodWrapper = /* @__PURE__ */ __name(function() { + if (!flag(this, "lockSsfi")) { + flag(this, "ssfi", chainableMethodWrapper); + } + let result = chainableBehavior.method.apply(this, arguments); + if (result !== void 0) { + return result; + } + let newAssertion = new Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + }, "chainableMethodWrapper"); + addLengthGuard(chainableMethodWrapper, name, true); + if (canSetPrototype) { + let prototype = Object.create(this); + prototype.call = call; + prototype.apply = apply; + Object.setPrototypeOf(chainableMethodWrapper, prototype); + } else { + let asserterNames = Object.getOwnPropertyNames(ctx); + asserterNames.forEach(function(asserterName) { + if (excludeNames.indexOf(asserterName) !== -1) { + return; + } + let pd = Object.getOwnPropertyDescriptor(ctx, asserterName); + Object.defineProperty(chainableMethodWrapper, asserterName, pd); + }); + } + transferFlags(this, chainableMethodWrapper); + return proxify(chainableMethodWrapper); + }, "chainableMethodGetter"), + configurable: true + }); + events.dispatchEvent( + new PluginAddChainableMethodEvent( + "addChainableMethod", + name, + method, + chainingBehavior + ) + ); +} +__name(addChainableMethod, "addChainableMethod"); + +// lib/chai/utils/overwriteChainableMethod.js +function overwriteChainableMethod(ctx, name, method, chainingBehavior) { + let chainableBehavior = ctx.__methods[name]; + let _chainingBehavior = chainableBehavior.chainingBehavior; + chainableBehavior.chainingBehavior = /* @__PURE__ */ __name(function overwritingChainableMethodGetter() { + let result = chainingBehavior(_chainingBehavior).call(this); + if (result !== void 0) { + return result; + } + let newAssertion = new Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + }, "overwritingChainableMethodGetter"); + let _method = chainableBehavior.method; + chainableBehavior.method = /* @__PURE__ */ __name(function overwritingChainableMethodWrapper() { + let result = method(_method).apply(this, arguments); + if (result !== void 0) { + return result; + } + let newAssertion = new Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + }, "overwritingChainableMethodWrapper"); +} +__name(overwriteChainableMethod, "overwriteChainableMethod"); + +// lib/chai/utils/compareByInspect.js +function compareByInspect(a, b) { + return inspect2(a) < inspect2(b) ? -1 : 1; +} +__name(compareByInspect, "compareByInspect"); + +// lib/chai/utils/getOwnEnumerablePropertySymbols.js +function getOwnEnumerablePropertySymbols(obj) { + if (typeof Object.getOwnPropertySymbols !== "function") return []; + return Object.getOwnPropertySymbols(obj).filter(function(sym) { + return Object.getOwnPropertyDescriptor(obj, sym).enumerable; + }); +} +__name(getOwnEnumerablePropertySymbols, "getOwnEnumerablePropertySymbols"); + +// lib/chai/utils/getOwnEnumerableProperties.js +function getOwnEnumerableProperties(obj) { + return Object.keys(obj).concat(getOwnEnumerablePropertySymbols(obj)); +} +__name(getOwnEnumerableProperties, "getOwnEnumerableProperties"); + +// lib/chai/utils/isNaN.js +var isNaN2 = Number.isNaN; + +// lib/chai/utils/getOperator.js +function isObjectType(obj) { + let objectType = type(obj); + let objectTypes = ["Array", "Object", "Function"]; + return objectTypes.indexOf(objectType) !== -1; +} +__name(isObjectType, "isObjectType"); +function getOperator(obj, args) { + let operator = flag(obj, "operator"); + let negate = flag(obj, "negate"); + let expected = args[3]; + let msg = negate ? args[2] : args[1]; + if (operator) { + return operator; + } + if (typeof msg === "function") msg = msg(); + msg = msg || ""; + if (!msg) { + return void 0; + } + if (/\shave\s/.test(msg)) { + return void 0; + } + let isObject = isObjectType(expected); + if (/\snot\s/.test(msg)) { + return isObject ? "notDeepStrictEqual" : "notStrictEqual"; + } + return isObject ? "deepStrictEqual" : "strictEqual"; +} +__name(getOperator, "getOperator"); + +// lib/chai/utils/index.js +function getName(fn) { + return fn.name; +} +__name(getName, "getName"); +function isRegExp2(obj) { + return Object.prototype.toString.call(obj) === "[object RegExp]"; +} +__name(isRegExp2, "isRegExp"); +function isNumeric(obj) { + return ["Number", "BigInt"].includes(type(obj)); +} +__name(isNumeric, "isNumeric"); + +// lib/chai/core/assertions.js +var { flag: flag2 } = utils_exports; +[ + "to", + "be", + "been", + "is", + "and", + "has", + "have", + "with", + "that", + "which", + "at", + "of", + "same", + "but", + "does", + "still", + "also" +].forEach(function(chain) { + Assertion.addProperty(chain); +}); +Assertion.addProperty("not", function() { + flag2(this, "negate", true); +}); +Assertion.addProperty("deep", function() { + flag2(this, "deep", true); +}); +Assertion.addProperty("nested", function() { + flag2(this, "nested", true); +}); +Assertion.addProperty("own", function() { + flag2(this, "own", true); +}); +Assertion.addProperty("ordered", function() { + flag2(this, "ordered", true); +}); +Assertion.addProperty("any", function() { + flag2(this, "any", true); + flag2(this, "all", false); +}); +Assertion.addProperty("all", function() { + flag2(this, "all", true); + flag2(this, "any", false); +}); +var functionTypes = { + function: [ + "function", + "asyncfunction", + "generatorfunction", + "asyncgeneratorfunction" + ], + asyncfunction: ["asyncfunction", "asyncgeneratorfunction"], + generatorfunction: ["generatorfunction", "asyncgeneratorfunction"], + asyncgeneratorfunction: ["asyncgeneratorfunction"] +}; +function an(type3, msg) { + if (msg) flag2(this, "message", msg); + type3 = type3.toLowerCase(); + let obj = flag2(this, "object"), article = ~["a", "e", "i", "o", "u"].indexOf(type3.charAt(0)) ? "an " : "a "; + const detectedType = type(obj).toLowerCase(); + if (functionTypes["function"].includes(type3)) { + this.assert( + functionTypes[type3].includes(detectedType), + "expected #{this} to be " + article + type3, + "expected #{this} not to be " + article + type3 + ); + } else { + this.assert( + type3 === detectedType, + "expected #{this} to be " + article + type3, + "expected #{this} not to be " + article + type3 + ); + } +} +__name(an, "an"); +Assertion.addChainableMethod("an", an); +Assertion.addChainableMethod("a", an); +function SameValueZero(a, b) { + return isNaN2(a) && isNaN2(b) || a === b; +} +__name(SameValueZero, "SameValueZero"); +function includeChainingBehavior() { + flag2(this, "contains", true); +} +__name(includeChainingBehavior, "includeChainingBehavior"); +function include(val, msg) { + if (msg) flag2(this, "message", msg); + let obj = flag2(this, "object"), objType = type(obj).toLowerCase(), flagMsg = flag2(this, "message"), negate = flag2(this, "negate"), ssfi = flag2(this, "ssfi"), isDeep = flag2(this, "deep"), descriptor = isDeep ? "deep " : "", isEql = isDeep ? flag2(this, "eql") : SameValueZero; + flagMsg = flagMsg ? flagMsg + ": " : ""; + let included = false; + switch (objType) { + case "string": + included = obj.indexOf(val) !== -1; + break; + case "weakset": + if (isDeep) { + throw new AssertionError( + flagMsg + "unable to use .deep.include with WeakSet", + void 0, + ssfi + ); + } + included = obj.has(val); + break; + case "map": + obj.forEach(function(item) { + included = included || isEql(item, val); + }); + break; + case "set": + if (isDeep) { + obj.forEach(function(item) { + included = included || isEql(item, val); + }); + } else { + included = obj.has(val); + } + break; + case "array": + if (isDeep) { + included = obj.some(function(item) { + return isEql(item, val); + }); + } else { + included = obj.indexOf(val) !== -1; + } + break; + default: { + if (val !== Object(val)) { + throw new AssertionError( + flagMsg + "the given combination of arguments (" + objType + " and " + type(val).toLowerCase() + ") is invalid for this assertion. You can use an array, a map, an object, a set, a string, or a weakset instead of a " + type(val).toLowerCase(), + void 0, + ssfi + ); + } + let props = Object.keys(val); + let firstErr = null; + let numErrs = 0; + props.forEach(function(prop) { + let propAssertion = new Assertion(obj); + transferFlags(this, propAssertion, true); + flag2(propAssertion, "lockSsfi", true); + if (!negate || props.length === 1) { + propAssertion.property(prop, val[prop]); + return; + } + try { + propAssertion.property(prop, val[prop]); + } catch (err) { + if (!check_error_exports.compatibleConstructor(err, AssertionError)) { + throw err; + } + if (firstErr === null) firstErr = err; + numErrs++; + } + }, this); + if (negate && props.length > 1 && numErrs === props.length) { + throw firstErr; + } + return; + } + } + this.assert( + included, + "expected #{this} to " + descriptor + "include " + inspect2(val), + "expected #{this} to not " + descriptor + "include " + inspect2(val) + ); +} +__name(include, "include"); +Assertion.addChainableMethod("include", include, includeChainingBehavior); +Assertion.addChainableMethod("contain", include, includeChainingBehavior); +Assertion.addChainableMethod("contains", include, includeChainingBehavior); +Assertion.addChainableMethod("includes", include, includeChainingBehavior); +Assertion.addProperty("ok", function() { + this.assert( + flag2(this, "object"), + "expected #{this} to be truthy", + "expected #{this} to be falsy" + ); +}); +Assertion.addProperty("true", function() { + this.assert( + true === flag2(this, "object"), + "expected #{this} to be true", + "expected #{this} to be false", + flag2(this, "negate") ? false : true + ); +}); +Assertion.addProperty("numeric", function() { + const object = flag2(this, "object"); + this.assert( + ["Number", "BigInt"].includes(type(object)), + "expected #{this} to be numeric", + "expected #{this} to not be numeric", + flag2(this, "negate") ? false : true + ); +}); +Assertion.addProperty("callable", function() { + const val = flag2(this, "object"); + const ssfi = flag2(this, "ssfi"); + const message = flag2(this, "message"); + const msg = message ? `${message}: ` : ""; + const negate = flag2(this, "negate"); + const assertionMessage = negate ? `${msg}expected ${inspect2(val)} not to be a callable function` : `${msg}expected ${inspect2(val)} to be a callable function`; + const isCallable = [ + "Function", + "AsyncFunction", + "GeneratorFunction", + "AsyncGeneratorFunction" + ].includes(type(val)); + if (isCallable && negate || !isCallable && !negate) { + throw new AssertionError(assertionMessage, void 0, ssfi); + } +}); +Assertion.addProperty("false", function() { + this.assert( + false === flag2(this, "object"), + "expected #{this} to be false", + "expected #{this} to be true", + flag2(this, "negate") ? true : false + ); +}); +Assertion.addProperty("null", function() { + this.assert( + null === flag2(this, "object"), + "expected #{this} to be null", + "expected #{this} not to be null" + ); +}); +Assertion.addProperty("undefined", function() { + this.assert( + void 0 === flag2(this, "object"), + "expected #{this} to be undefined", + "expected #{this} not to be undefined" + ); +}); +Assertion.addProperty("NaN", function() { + this.assert( + isNaN2(flag2(this, "object")), + "expected #{this} to be NaN", + "expected #{this} not to be NaN" + ); +}); +function assertExist() { + let val = flag2(this, "object"); + this.assert( + val !== null && val !== void 0, + "expected #{this} to exist", + "expected #{this} to not exist" + ); +} +__name(assertExist, "assertExist"); +Assertion.addProperty("exist", assertExist); +Assertion.addProperty("exists", assertExist); +Assertion.addProperty("empty", function() { + let val = flag2(this, "object"), ssfi = flag2(this, "ssfi"), flagMsg = flag2(this, "message"), itemsCount; + flagMsg = flagMsg ? flagMsg + ": " : ""; + switch (type(val).toLowerCase()) { + case "array": + case "string": + itemsCount = val.length; + break; + case "map": + case "set": + itemsCount = val.size; + break; + case "weakmap": + case "weakset": + throw new AssertionError( + flagMsg + ".empty was passed a weak collection", + void 0, + ssfi + ); + case "function": { + const msg = flagMsg + ".empty was passed a function " + getName(val); + throw new AssertionError(msg.trim(), void 0, ssfi); + } + default: + if (val !== Object(val)) { + throw new AssertionError( + flagMsg + ".empty was passed non-string primitive " + inspect2(val), + void 0, + ssfi + ); + } + itemsCount = Object.keys(val).length; + } + this.assert( + 0 === itemsCount, + "expected #{this} to be empty", + "expected #{this} not to be empty" + ); +}); +function checkArguments() { + let obj = flag2(this, "object"), type3 = type(obj); + this.assert( + "Arguments" === type3, + "expected #{this} to be arguments but got " + type3, + "expected #{this} to not be arguments" + ); +} +__name(checkArguments, "checkArguments"); +Assertion.addProperty("arguments", checkArguments); +Assertion.addProperty("Arguments", checkArguments); +function assertEqual(val, msg) { + if (msg) flag2(this, "message", msg); + let obj = flag2(this, "object"); + if (flag2(this, "deep")) { + let prevLockSsfi = flag2(this, "lockSsfi"); + flag2(this, "lockSsfi", true); + this.eql(val); + flag2(this, "lockSsfi", prevLockSsfi); + } else { + this.assert( + val === obj, + "expected #{this} to equal #{exp}", + "expected #{this} to not equal #{exp}", + val, + this._obj, + true + ); + } +} +__name(assertEqual, "assertEqual"); +Assertion.addMethod("equal", assertEqual); +Assertion.addMethod("equals", assertEqual); +Assertion.addMethod("eq", assertEqual); +function assertEql(obj, msg) { + if (msg) flag2(this, "message", msg); + let eql = flag2(this, "eql"); + this.assert( + eql(obj, flag2(this, "object")), + "expected #{this} to deeply equal #{exp}", + "expected #{this} to not deeply equal #{exp}", + obj, + this._obj, + true + ); +} +__name(assertEql, "assertEql"); +Assertion.addMethod("eql", assertEql); +Assertion.addMethod("eqls", assertEql); +function assertAbove(n, msg) { + if (msg) flag2(this, "message", msg); + let obj = flag2(this, "object"), doLength = flag2(this, "doLength"), flagMsg = flag2(this, "message"), msgPrefix = flagMsg ? flagMsg + ": " : "", ssfi = flag2(this, "ssfi"), objType = type(obj).toLowerCase(), nType = type(n).toLowerCase(); + if (doLength && objType !== "map" && objType !== "set") { + new Assertion(obj, flagMsg, ssfi, true).to.have.property("length"); + } + if (!doLength && objType === "date" && nType !== "date") { + throw new AssertionError( + msgPrefix + "the argument to above must be a date", + void 0, + ssfi + ); + } else if (!isNumeric(n) && (doLength || isNumeric(obj))) { + throw new AssertionError( + msgPrefix + "the argument to above must be a number", + void 0, + ssfi + ); + } else if (!doLength && objType !== "date" && !isNumeric(obj)) { + let printObj = objType === "string" ? "'" + obj + "'" : obj; + throw new AssertionError( + msgPrefix + "expected " + printObj + " to be a number or a date", + void 0, + ssfi + ); + } + if (doLength) { + let descriptor = "length", itemsCount; + if (objType === "map" || objType === "set") { + descriptor = "size"; + itemsCount = obj.size; + } else { + itemsCount = obj.length; + } + this.assert( + itemsCount > n, + "expected #{this} to have a " + descriptor + " above #{exp} but got #{act}", + "expected #{this} to not have a " + descriptor + " above #{exp}", + n, + itemsCount + ); + } else { + this.assert( + obj > n, + "expected #{this} to be above #{exp}", + "expected #{this} to be at most #{exp}", + n + ); + } +} +__name(assertAbove, "assertAbove"); +Assertion.addMethod("above", assertAbove); +Assertion.addMethod("gt", assertAbove); +Assertion.addMethod("greaterThan", assertAbove); +function assertLeast(n, msg) { + if (msg) flag2(this, "message", msg); + let obj = flag2(this, "object"), doLength = flag2(this, "doLength"), flagMsg = flag2(this, "message"), msgPrefix = flagMsg ? flagMsg + ": " : "", ssfi = flag2(this, "ssfi"), objType = type(obj).toLowerCase(), nType = type(n).toLowerCase(), errorMessage, shouldThrow = true; + if (doLength && objType !== "map" && objType !== "set") { + new Assertion(obj, flagMsg, ssfi, true).to.have.property("length"); + } + if (!doLength && objType === "date" && nType !== "date") { + errorMessage = msgPrefix + "the argument to least must be a date"; + } else if (!isNumeric(n) && (doLength || isNumeric(obj))) { + errorMessage = msgPrefix + "the argument to least must be a number"; + } else if (!doLength && objType !== "date" && !isNumeric(obj)) { + let printObj = objType === "string" ? "'" + obj + "'" : obj; + errorMessage = msgPrefix + "expected " + printObj + " to be a number or a date"; + } else { + shouldThrow = false; + } + if (shouldThrow) { + throw new AssertionError(errorMessage, void 0, ssfi); + } + if (doLength) { + let descriptor = "length", itemsCount; + if (objType === "map" || objType === "set") { + descriptor = "size"; + itemsCount = obj.size; + } else { + itemsCount = obj.length; + } + this.assert( + itemsCount >= n, + "expected #{this} to have a " + descriptor + " at least #{exp} but got #{act}", + "expected #{this} to have a " + descriptor + " below #{exp}", + n, + itemsCount + ); + } else { + this.assert( + obj >= n, + "expected #{this} to be at least #{exp}", + "expected #{this} to be below #{exp}", + n + ); + } +} +__name(assertLeast, "assertLeast"); +Assertion.addMethod("least", assertLeast); +Assertion.addMethod("gte", assertLeast); +Assertion.addMethod("greaterThanOrEqual", assertLeast); +function assertBelow(n, msg) { + if (msg) flag2(this, "message", msg); + let obj = flag2(this, "object"), doLength = flag2(this, "doLength"), flagMsg = flag2(this, "message"), msgPrefix = flagMsg ? flagMsg + ": " : "", ssfi = flag2(this, "ssfi"), objType = type(obj).toLowerCase(), nType = type(n).toLowerCase(), errorMessage, shouldThrow = true; + if (doLength && objType !== "map" && objType !== "set") { + new Assertion(obj, flagMsg, ssfi, true).to.have.property("length"); + } + if (!doLength && objType === "date" && nType !== "date") { + errorMessage = msgPrefix + "the argument to below must be a date"; + } else if (!isNumeric(n) && (doLength || isNumeric(obj))) { + errorMessage = msgPrefix + "the argument to below must be a number"; + } else if (!doLength && objType !== "date" && !isNumeric(obj)) { + let printObj = objType === "string" ? "'" + obj + "'" : obj; + errorMessage = msgPrefix + "expected " + printObj + " to be a number or a date"; + } else { + shouldThrow = false; + } + if (shouldThrow) { + throw new AssertionError(errorMessage, void 0, ssfi); + } + if (doLength) { + let descriptor = "length", itemsCount; + if (objType === "map" || objType === "set") { + descriptor = "size"; + itemsCount = obj.size; + } else { + itemsCount = obj.length; + } + this.assert( + itemsCount < n, + "expected #{this} to have a " + descriptor + " below #{exp} but got #{act}", + "expected #{this} to not have a " + descriptor + " below #{exp}", + n, + itemsCount + ); + } else { + this.assert( + obj < n, + "expected #{this} to be below #{exp}", + "expected #{this} to be at least #{exp}", + n + ); + } +} +__name(assertBelow, "assertBelow"); +Assertion.addMethod("below", assertBelow); +Assertion.addMethod("lt", assertBelow); +Assertion.addMethod("lessThan", assertBelow); +function assertMost(n, msg) { + if (msg) flag2(this, "message", msg); + let obj = flag2(this, "object"), doLength = flag2(this, "doLength"), flagMsg = flag2(this, "message"), msgPrefix = flagMsg ? flagMsg + ": " : "", ssfi = flag2(this, "ssfi"), objType = type(obj).toLowerCase(), nType = type(n).toLowerCase(), errorMessage, shouldThrow = true; + if (doLength && objType !== "map" && objType !== "set") { + new Assertion(obj, flagMsg, ssfi, true).to.have.property("length"); + } + if (!doLength && objType === "date" && nType !== "date") { + errorMessage = msgPrefix + "the argument to most must be a date"; + } else if (!isNumeric(n) && (doLength || isNumeric(obj))) { + errorMessage = msgPrefix + "the argument to most must be a number"; + } else if (!doLength && objType !== "date" && !isNumeric(obj)) { + let printObj = objType === "string" ? "'" + obj + "'" : obj; + errorMessage = msgPrefix + "expected " + printObj + " to be a number or a date"; + } else { + shouldThrow = false; + } + if (shouldThrow) { + throw new AssertionError(errorMessage, void 0, ssfi); + } + if (doLength) { + let descriptor = "length", itemsCount; + if (objType === "map" || objType === "set") { + descriptor = "size"; + itemsCount = obj.size; + } else { + itemsCount = obj.length; + } + this.assert( + itemsCount <= n, + "expected #{this} to have a " + descriptor + " at most #{exp} but got #{act}", + "expected #{this} to have a " + descriptor + " above #{exp}", + n, + itemsCount + ); + } else { + this.assert( + obj <= n, + "expected #{this} to be at most #{exp}", + "expected #{this} to be above #{exp}", + n + ); + } +} +__name(assertMost, "assertMost"); +Assertion.addMethod("most", assertMost); +Assertion.addMethod("lte", assertMost); +Assertion.addMethod("lessThanOrEqual", assertMost); +Assertion.addMethod("within", function(start, finish, msg) { + if (msg) flag2(this, "message", msg); + let obj = flag2(this, "object"), doLength = flag2(this, "doLength"), flagMsg = flag2(this, "message"), msgPrefix = flagMsg ? flagMsg + ": " : "", ssfi = flag2(this, "ssfi"), objType = type(obj).toLowerCase(), startType = type(start).toLowerCase(), finishType = type(finish).toLowerCase(), errorMessage, shouldThrow = true, range = startType === "date" && finishType === "date" ? start.toISOString() + ".." + finish.toISOString() : start + ".." + finish; + if (doLength && objType !== "map" && objType !== "set") { + new Assertion(obj, flagMsg, ssfi, true).to.have.property("length"); + } + if (!doLength && objType === "date" && (startType !== "date" || finishType !== "date")) { + errorMessage = msgPrefix + "the arguments to within must be dates"; + } else if ((!isNumeric(start) || !isNumeric(finish)) && (doLength || isNumeric(obj))) { + errorMessage = msgPrefix + "the arguments to within must be numbers"; + } else if (!doLength && objType !== "date" && !isNumeric(obj)) { + let printObj = objType === "string" ? "'" + obj + "'" : obj; + errorMessage = msgPrefix + "expected " + printObj + " to be a number or a date"; + } else { + shouldThrow = false; + } + if (shouldThrow) { + throw new AssertionError(errorMessage, void 0, ssfi); + } + if (doLength) { + let descriptor = "length", itemsCount; + if (objType === "map" || objType === "set") { + descriptor = "size"; + itemsCount = obj.size; + } else { + itemsCount = obj.length; + } + this.assert( + itemsCount >= start && itemsCount <= finish, + "expected #{this} to have a " + descriptor + " within " + range, + "expected #{this} to not have a " + descriptor + " within " + range + ); + } else { + this.assert( + obj >= start && obj <= finish, + "expected #{this} to be within " + range, + "expected #{this} to not be within " + range + ); + } +}); +function assertInstanceOf(constructor, msg) { + if (msg) flag2(this, "message", msg); + let target = flag2(this, "object"); + let ssfi = flag2(this, "ssfi"); + let flagMsg = flag2(this, "message"); + let isInstanceOf; + try { + isInstanceOf = target instanceof constructor; + } catch (err) { + if (err instanceof TypeError) { + flagMsg = flagMsg ? flagMsg + ": " : ""; + throw new AssertionError( + flagMsg + "The instanceof assertion needs a constructor but " + type(constructor) + " was given.", + void 0, + ssfi + ); + } + throw err; + } + let name = getName(constructor); + if (name == null) { + name = "an unnamed constructor"; + } + this.assert( + isInstanceOf, + "expected #{this} to be an instance of " + name, + "expected #{this} to not be an instance of " + name + ); +} +__name(assertInstanceOf, "assertInstanceOf"); +Assertion.addMethod("instanceof", assertInstanceOf); +Assertion.addMethod("instanceOf", assertInstanceOf); +function assertProperty(name, val, msg) { + if (msg) flag2(this, "message", msg); + let isNested = flag2(this, "nested"), isOwn = flag2(this, "own"), flagMsg = flag2(this, "message"), obj = flag2(this, "object"), ssfi = flag2(this, "ssfi"), nameType = typeof name; + flagMsg = flagMsg ? flagMsg + ": " : ""; + if (isNested) { + if (nameType !== "string") { + throw new AssertionError( + flagMsg + "the argument to property must be a string when using nested syntax", + void 0, + ssfi + ); + } + } else { + if (nameType !== "string" && nameType !== "number" && nameType !== "symbol") { + throw new AssertionError( + flagMsg + "the argument to property must be a string, number, or symbol", + void 0, + ssfi + ); + } + } + if (isNested && isOwn) { + throw new AssertionError( + flagMsg + 'The "nested" and "own" flags cannot be combined.', + void 0, + ssfi + ); + } + if (obj === null || obj === void 0) { + throw new AssertionError( + flagMsg + "Target cannot be null or undefined.", + void 0, + ssfi + ); + } + let isDeep = flag2(this, "deep"), negate = flag2(this, "negate"), pathInfo = isNested ? getPathInfo(obj, name) : null, value = isNested ? pathInfo.value : obj[name], isEql = isDeep ? flag2(this, "eql") : (val1, val2) => val1 === val2; + let descriptor = ""; + if (isDeep) descriptor += "deep "; + if (isOwn) descriptor += "own "; + if (isNested) descriptor += "nested "; + descriptor += "property "; + let hasProperty2; + if (isOwn) hasProperty2 = Object.prototype.hasOwnProperty.call(obj, name); + else if (isNested) hasProperty2 = pathInfo.exists; + else hasProperty2 = hasProperty(obj, name); + if (!negate || arguments.length === 1) { + this.assert( + hasProperty2, + "expected #{this} to have " + descriptor + inspect2(name), + "expected #{this} to not have " + descriptor + inspect2(name) + ); + } + if (arguments.length > 1) { + this.assert( + hasProperty2 && isEql(val, value), + "expected #{this} to have " + descriptor + inspect2(name) + " of #{exp}, but got #{act}", + "expected #{this} to not have " + descriptor + inspect2(name) + " of #{act}", + val, + value + ); + } + flag2(this, "object", value); +} +__name(assertProperty, "assertProperty"); +Assertion.addMethod("property", assertProperty); +function assertOwnProperty(_name, _value, _msg) { + flag2(this, "own", true); + assertProperty.apply(this, arguments); +} +__name(assertOwnProperty, "assertOwnProperty"); +Assertion.addMethod("ownProperty", assertOwnProperty); +Assertion.addMethod("haveOwnProperty", assertOwnProperty); +function assertOwnPropertyDescriptor(name, descriptor, msg) { + if (typeof descriptor === "string") { + msg = descriptor; + descriptor = null; + } + if (msg) flag2(this, "message", msg); + let obj = flag2(this, "object"); + let actualDescriptor = Object.getOwnPropertyDescriptor(Object(obj), name); + let eql = flag2(this, "eql"); + if (actualDescriptor && descriptor) { + this.assert( + eql(descriptor, actualDescriptor), + "expected the own property descriptor for " + inspect2(name) + " on #{this} to match " + inspect2(descriptor) + ", got " + inspect2(actualDescriptor), + "expected the own property descriptor for " + inspect2(name) + " on #{this} to not match " + inspect2(descriptor), + descriptor, + actualDescriptor, + true + ); + } else { + this.assert( + actualDescriptor, + "expected #{this} to have an own property descriptor for " + inspect2(name), + "expected #{this} to not have an own property descriptor for " + inspect2(name) + ); + } + flag2(this, "object", actualDescriptor); +} +__name(assertOwnPropertyDescriptor, "assertOwnPropertyDescriptor"); +Assertion.addMethod("ownPropertyDescriptor", assertOwnPropertyDescriptor); +Assertion.addMethod("haveOwnPropertyDescriptor", assertOwnPropertyDescriptor); +function assertLengthChain() { + flag2(this, "doLength", true); +} +__name(assertLengthChain, "assertLengthChain"); +function assertLength(n, msg) { + if (msg) flag2(this, "message", msg); + let obj = flag2(this, "object"), objType = type(obj).toLowerCase(), flagMsg = flag2(this, "message"), ssfi = flag2(this, "ssfi"), descriptor = "length", itemsCount; + switch (objType) { + case "map": + case "set": + descriptor = "size"; + itemsCount = obj.size; + break; + default: + new Assertion(obj, flagMsg, ssfi, true).to.have.property("length"); + itemsCount = obj.length; + } + this.assert( + itemsCount == n, + "expected #{this} to have a " + descriptor + " of #{exp} but got #{act}", + "expected #{this} to not have a " + descriptor + " of #{act}", + n, + itemsCount + ); +} +__name(assertLength, "assertLength"); +Assertion.addChainableMethod("length", assertLength, assertLengthChain); +Assertion.addChainableMethod("lengthOf", assertLength, assertLengthChain); +function assertMatch(re, msg) { + if (msg) flag2(this, "message", msg); + let obj = flag2(this, "object"); + this.assert( + re.exec(obj), + "expected #{this} to match " + re, + "expected #{this} not to match " + re + ); +} +__name(assertMatch, "assertMatch"); +Assertion.addMethod("match", assertMatch); +Assertion.addMethod("matches", assertMatch); +Assertion.addMethod("string", function(str, msg) { + if (msg) flag2(this, "message", msg); + let obj = flag2(this, "object"), flagMsg = flag2(this, "message"), ssfi = flag2(this, "ssfi"); + new Assertion(obj, flagMsg, ssfi, true).is.a("string"); + this.assert( + ~obj.indexOf(str), + "expected #{this} to contain " + inspect2(str), + "expected #{this} to not contain " + inspect2(str) + ); +}); +function assertKeys(keys) { + let obj = flag2(this, "object"), objType = type(obj), keysType = type(keys), ssfi = flag2(this, "ssfi"), isDeep = flag2(this, "deep"), str, deepStr = "", actual, ok = true, flagMsg = flag2(this, "message"); + flagMsg = flagMsg ? flagMsg + ": " : ""; + let mixedArgsMsg = flagMsg + "when testing keys against an object or an array you must give a single Array|Object|String argument or multiple String arguments"; + if (objType === "Map" || objType === "Set") { + deepStr = isDeep ? "deeply " : ""; + actual = []; + obj.forEach(function(val, key) { + actual.push(key); + }); + if (keysType !== "Array") { + keys = Array.prototype.slice.call(arguments); + } + } else { + actual = getOwnEnumerableProperties(obj); + switch (keysType) { + case "Array": + if (arguments.length > 1) { + throw new AssertionError(mixedArgsMsg, void 0, ssfi); + } + break; + case "Object": + if (arguments.length > 1) { + throw new AssertionError(mixedArgsMsg, void 0, ssfi); + } + keys = Object.keys(keys); + break; + default: + keys = Array.prototype.slice.call(arguments); + } + keys = keys.map(function(val) { + return typeof val === "symbol" ? val : String(val); + }); + } + if (!keys.length) { + throw new AssertionError(flagMsg + "keys required", void 0, ssfi); + } + let len = keys.length, any = flag2(this, "any"), all = flag2(this, "all"), expected = keys, isEql = isDeep ? flag2(this, "eql") : (val1, val2) => val1 === val2; + if (!any && !all) { + all = true; + } + if (any) { + ok = expected.some(function(expectedKey) { + return actual.some(function(actualKey) { + return isEql(expectedKey, actualKey); + }); + }); + } + if (all) { + ok = expected.every(function(expectedKey) { + return actual.some(function(actualKey) { + return isEql(expectedKey, actualKey); + }); + }); + if (!flag2(this, "contains")) { + ok = ok && keys.length == actual.length; + } + } + if (len > 1) { + keys = keys.map(function(key) { + return inspect2(key); + }); + let last = keys.pop(); + if (all) { + str = keys.join(", ") + ", and " + last; + } + if (any) { + str = keys.join(", ") + ", or " + last; + } + } else { + str = inspect2(keys[0]); + } + str = (len > 1 ? "keys " : "key ") + str; + str = (flag2(this, "contains") ? "contain " : "have ") + str; + this.assert( + ok, + "expected #{this} to " + deepStr + str, + "expected #{this} to not " + deepStr + str, + expected.slice(0).sort(compareByInspect), + actual.sort(compareByInspect), + true + ); +} +__name(assertKeys, "assertKeys"); +Assertion.addMethod("keys", assertKeys); +Assertion.addMethod("key", assertKeys); +function assertThrows(errorLike, errMsgMatcher, msg) { + if (msg) flag2(this, "message", msg); + let obj = flag2(this, "object"), ssfi = flag2(this, "ssfi"), flagMsg = flag2(this, "message"), negate = flag2(this, "negate") || false; + new Assertion(obj, flagMsg, ssfi, true).is.a("function"); + if (isRegExp2(errorLike) || typeof errorLike === "string") { + errMsgMatcher = errorLike; + errorLike = null; + } + let caughtErr; + let errorWasThrown = false; + try { + obj(); + } catch (err) { + errorWasThrown = true; + caughtErr = err; + } + let everyArgIsUndefined = errorLike === void 0 && errMsgMatcher === void 0; + let everyArgIsDefined = Boolean(errorLike && errMsgMatcher); + let errorLikeFail = false; + let errMsgMatcherFail = false; + if (everyArgIsUndefined || !everyArgIsUndefined && !negate) { + let errorLikeString = "an error"; + if (errorLike instanceof Error) { + errorLikeString = "#{exp}"; + } else if (errorLike) { + errorLikeString = check_error_exports.getConstructorName(errorLike); + } + let actual = caughtErr; + if (caughtErr instanceof Error) { + actual = caughtErr.toString(); + } else if (typeof caughtErr === "string") { + actual = caughtErr; + } else if (caughtErr && (typeof caughtErr === "object" || typeof caughtErr === "function")) { + try { + actual = check_error_exports.getConstructorName(caughtErr); + } catch (_err) { + } + } + this.assert( + errorWasThrown, + "expected #{this} to throw " + errorLikeString, + "expected #{this} to not throw an error but #{act} was thrown", + errorLike && errorLike.toString(), + actual + ); + } + if (errorLike && caughtErr) { + if (errorLike instanceof Error) { + let isCompatibleInstance = check_error_exports.compatibleInstance( + caughtErr, + errorLike + ); + if (isCompatibleInstance === negate) { + if (everyArgIsDefined && negate) { + errorLikeFail = true; + } else { + this.assert( + negate, + "expected #{this} to throw #{exp} but #{act} was thrown", + "expected #{this} to not throw #{exp}" + (caughtErr && !negate ? " but #{act} was thrown" : ""), + errorLike.toString(), + caughtErr.toString() + ); + } + } + } + let isCompatibleConstructor = check_error_exports.compatibleConstructor( + caughtErr, + errorLike + ); + if (isCompatibleConstructor === negate) { + if (everyArgIsDefined && negate) { + errorLikeFail = true; + } else { + this.assert( + negate, + "expected #{this} to throw #{exp} but #{act} was thrown", + "expected #{this} to not throw #{exp}" + (caughtErr ? " but #{act} was thrown" : ""), + errorLike instanceof Error ? errorLike.toString() : errorLike && check_error_exports.getConstructorName(errorLike), + caughtErr instanceof Error ? caughtErr.toString() : caughtErr && check_error_exports.getConstructorName(caughtErr) + ); + } + } + } + if (caughtErr && errMsgMatcher !== void 0 && errMsgMatcher !== null) { + let placeholder = "including"; + if (isRegExp2(errMsgMatcher)) { + placeholder = "matching"; + } + let isCompatibleMessage = check_error_exports.compatibleMessage( + caughtErr, + errMsgMatcher + ); + if (isCompatibleMessage === negate) { + if (everyArgIsDefined && negate) { + errMsgMatcherFail = true; + } else { + this.assert( + negate, + "expected #{this} to throw error " + placeholder + " #{exp} but got #{act}", + "expected #{this} to throw error not " + placeholder + " #{exp}", + errMsgMatcher, + check_error_exports.getMessage(caughtErr) + ); + } + } + } + if (errorLikeFail && errMsgMatcherFail) { + this.assert( + negate, + "expected #{this} to throw #{exp} but #{act} was thrown", + "expected #{this} to not throw #{exp}" + (caughtErr ? " but #{act} was thrown" : ""), + errorLike instanceof Error ? errorLike.toString() : errorLike && check_error_exports.getConstructorName(errorLike), + caughtErr instanceof Error ? caughtErr.toString() : caughtErr && check_error_exports.getConstructorName(caughtErr) + ); + } + flag2(this, "object", caughtErr); +} +__name(assertThrows, "assertThrows"); +Assertion.addMethod("throw", assertThrows); +Assertion.addMethod("throws", assertThrows); +Assertion.addMethod("Throw", assertThrows); +function respondTo(method, msg) { + if (msg) flag2(this, "message", msg); + let obj = flag2(this, "object"), itself = flag2(this, "itself"), context = "function" === typeof obj && !itself ? obj.prototype[method] : obj[method]; + this.assert( + "function" === typeof context, + "expected #{this} to respond to " + inspect2(method), + "expected #{this} to not respond to " + inspect2(method) + ); +} +__name(respondTo, "respondTo"); +Assertion.addMethod("respondTo", respondTo); +Assertion.addMethod("respondsTo", respondTo); +Assertion.addProperty("itself", function() { + flag2(this, "itself", true); +}); +function satisfy(matcher, msg) { + if (msg) flag2(this, "message", msg); + let obj = flag2(this, "object"); + let result = matcher(obj); + this.assert( + result, + "expected #{this} to satisfy " + objDisplay(matcher), + "expected #{this} to not satisfy" + objDisplay(matcher), + flag2(this, "negate") ? false : true, + result + ); +} +__name(satisfy, "satisfy"); +Assertion.addMethod("satisfy", satisfy); +Assertion.addMethod("satisfies", satisfy); +function closeTo(expected, delta, msg) { + if (msg) flag2(this, "message", msg); + let obj = flag2(this, "object"), flagMsg = flag2(this, "message"), ssfi = flag2(this, "ssfi"); + new Assertion(obj, flagMsg, ssfi, true).is.numeric; + let message = "A `delta` value is required for `closeTo`"; + if (delta == void 0) { + throw new AssertionError( + flagMsg ? `${flagMsg}: ${message}` : message, + void 0, + ssfi + ); + } + new Assertion(delta, flagMsg, ssfi, true).is.numeric; + message = "A `expected` value is required for `closeTo`"; + if (expected == void 0) { + throw new AssertionError( + flagMsg ? `${flagMsg}: ${message}` : message, + void 0, + ssfi + ); + } + new Assertion(expected, flagMsg, ssfi, true).is.numeric; + const abs = /* @__PURE__ */ __name((x) => x < 0 ? -x : x, "abs"); + const strip = /* @__PURE__ */ __name((number) => parseFloat(parseFloat(number).toPrecision(12)), "strip"); + this.assert( + strip(abs(obj - expected)) <= delta, + "expected #{this} to be close to " + expected + " +/- " + delta, + "expected #{this} not to be close to " + expected + " +/- " + delta + ); +} +__name(closeTo, "closeTo"); +Assertion.addMethod("closeTo", closeTo); +Assertion.addMethod("approximately", closeTo); +function isSubsetOf(_subset, _superset, cmp, contains, ordered) { + let superset = Array.from(_superset); + let subset = Array.from(_subset); + if (!contains) { + if (subset.length !== superset.length) return false; + superset = superset.slice(); + } + return subset.every(function(elem, idx) { + if (ordered) return cmp ? cmp(elem, superset[idx]) : elem === superset[idx]; + if (!cmp) { + let matchIdx = superset.indexOf(elem); + if (matchIdx === -1) return false; + if (!contains) superset.splice(matchIdx, 1); + return true; + } + return superset.some(function(elem2, matchIdx) { + if (!cmp(elem, elem2)) return false; + if (!contains) superset.splice(matchIdx, 1); + return true; + }); + }); +} +__name(isSubsetOf, "isSubsetOf"); +Assertion.addMethod("members", function(subset, msg) { + if (msg) flag2(this, "message", msg); + let obj = flag2(this, "object"), flagMsg = flag2(this, "message"), ssfi = flag2(this, "ssfi"); + new Assertion(obj, flagMsg, ssfi, true).to.be.iterable; + new Assertion(subset, flagMsg, ssfi, true).to.be.iterable; + let contains = flag2(this, "contains"); + let ordered = flag2(this, "ordered"); + let subject, failMsg, failNegateMsg; + if (contains) { + subject = ordered ? "an ordered superset" : "a superset"; + failMsg = "expected #{this} to be " + subject + " of #{exp}"; + failNegateMsg = "expected #{this} to not be " + subject + " of #{exp}"; + } else { + subject = ordered ? "ordered members" : "members"; + failMsg = "expected #{this} to have the same " + subject + " as #{exp}"; + failNegateMsg = "expected #{this} to not have the same " + subject + " as #{exp}"; + } + let cmp = flag2(this, "deep") ? flag2(this, "eql") : void 0; + this.assert( + isSubsetOf(subset, obj, cmp, contains, ordered), + failMsg, + failNegateMsg, + subset, + obj, + true + ); +}); +Assertion.addProperty("iterable", function(msg) { + if (msg) flag2(this, "message", msg); + let obj = flag2(this, "object"); + this.assert( + obj != void 0 && obj[Symbol.iterator], + "expected #{this} to be an iterable", + "expected #{this} to not be an iterable", + obj + ); +}); +function oneOf(list, msg) { + if (msg) flag2(this, "message", msg); + let expected = flag2(this, "object"), flagMsg = flag2(this, "message"), ssfi = flag2(this, "ssfi"), contains = flag2(this, "contains"), isDeep = flag2(this, "deep"), eql = flag2(this, "eql"); + new Assertion(list, flagMsg, ssfi, true).to.be.an("array"); + if (contains) { + this.assert( + list.some(function(possibility) { + return expected.indexOf(possibility) > -1; + }), + "expected #{this} to contain one of #{exp}", + "expected #{this} to not contain one of #{exp}", + list, + expected + ); + } else { + if (isDeep) { + this.assert( + list.some(function(possibility) { + return eql(expected, possibility); + }), + "expected #{this} to deeply equal one of #{exp}", + "expected #{this} to deeply equal one of #{exp}", + list, + expected + ); + } else { + this.assert( + list.indexOf(expected) > -1, + "expected #{this} to be one of #{exp}", + "expected #{this} to not be one of #{exp}", + list, + expected + ); + } + } +} +__name(oneOf, "oneOf"); +Assertion.addMethod("oneOf", oneOf); +function assertChanges(subject, prop, msg) { + if (msg) flag2(this, "message", msg); + let fn = flag2(this, "object"), flagMsg = flag2(this, "message"), ssfi = flag2(this, "ssfi"); + new Assertion(fn, flagMsg, ssfi, true).is.a("function"); + let initial; + if (!prop) { + new Assertion(subject, flagMsg, ssfi, true).is.a("function"); + initial = subject(); + } else { + new Assertion(subject, flagMsg, ssfi, true).to.have.property(prop); + initial = subject[prop]; + } + fn(); + let final = prop === void 0 || prop === null ? subject() : subject[prop]; + let msgObj = prop === void 0 || prop === null ? initial : "." + prop; + flag2(this, "deltaMsgObj", msgObj); + flag2(this, "initialDeltaValue", initial); + flag2(this, "finalDeltaValue", final); + flag2(this, "deltaBehavior", "change"); + flag2(this, "realDelta", final !== initial); + this.assert( + initial !== final, + "expected " + msgObj + " to change", + "expected " + msgObj + " to not change" + ); +} +__name(assertChanges, "assertChanges"); +Assertion.addMethod("change", assertChanges); +Assertion.addMethod("changes", assertChanges); +function assertIncreases(subject, prop, msg) { + if (msg) flag2(this, "message", msg); + let fn = flag2(this, "object"), flagMsg = flag2(this, "message"), ssfi = flag2(this, "ssfi"); + new Assertion(fn, flagMsg, ssfi, true).is.a("function"); + let initial; + if (!prop) { + new Assertion(subject, flagMsg, ssfi, true).is.a("function"); + initial = subject(); + } else { + new Assertion(subject, flagMsg, ssfi, true).to.have.property(prop); + initial = subject[prop]; + } + new Assertion(initial, flagMsg, ssfi, true).is.a("number"); + fn(); + let final = prop === void 0 || prop === null ? subject() : subject[prop]; + let msgObj = prop === void 0 || prop === null ? initial : "." + prop; + flag2(this, "deltaMsgObj", msgObj); + flag2(this, "initialDeltaValue", initial); + flag2(this, "finalDeltaValue", final); + flag2(this, "deltaBehavior", "increase"); + flag2(this, "realDelta", final - initial); + this.assert( + final - initial > 0, + "expected " + msgObj + " to increase", + "expected " + msgObj + " to not increase" + ); +} +__name(assertIncreases, "assertIncreases"); +Assertion.addMethod("increase", assertIncreases); +Assertion.addMethod("increases", assertIncreases); +function assertDecreases(subject, prop, msg) { + if (msg) flag2(this, "message", msg); + let fn = flag2(this, "object"), flagMsg = flag2(this, "message"), ssfi = flag2(this, "ssfi"); + new Assertion(fn, flagMsg, ssfi, true).is.a("function"); + let initial; + if (!prop) { + new Assertion(subject, flagMsg, ssfi, true).is.a("function"); + initial = subject(); + } else { + new Assertion(subject, flagMsg, ssfi, true).to.have.property(prop); + initial = subject[prop]; + } + new Assertion(initial, flagMsg, ssfi, true).is.a("number"); + fn(); + let final = prop === void 0 || prop === null ? subject() : subject[prop]; + let msgObj = prop === void 0 || prop === null ? initial : "." + prop; + flag2(this, "deltaMsgObj", msgObj); + flag2(this, "initialDeltaValue", initial); + flag2(this, "finalDeltaValue", final); + flag2(this, "deltaBehavior", "decrease"); + flag2(this, "realDelta", initial - final); + this.assert( + final - initial < 0, + "expected " + msgObj + " to decrease", + "expected " + msgObj + " to not decrease" + ); +} +__name(assertDecreases, "assertDecreases"); +Assertion.addMethod("decrease", assertDecreases); +Assertion.addMethod("decreases", assertDecreases); +function assertDelta(delta, msg) { + if (msg) flag2(this, "message", msg); + let msgObj = flag2(this, "deltaMsgObj"); + let initial = flag2(this, "initialDeltaValue"); + let final = flag2(this, "finalDeltaValue"); + let behavior = flag2(this, "deltaBehavior"); + let realDelta = flag2(this, "realDelta"); + let expression; + if (behavior === "change") { + expression = Math.abs(final - initial) === Math.abs(delta); + } else { + expression = realDelta === Math.abs(delta); + } + this.assert( + expression, + "expected " + msgObj + " to " + behavior + " by " + delta, + "expected " + msgObj + " to not " + behavior + " by " + delta + ); +} +__name(assertDelta, "assertDelta"); +Assertion.addMethod("by", assertDelta); +Assertion.addProperty("extensible", function() { + let obj = flag2(this, "object"); + let isExtensible = obj === Object(obj) && Object.isExtensible(obj); + this.assert( + isExtensible, + "expected #{this} to be extensible", + "expected #{this} to not be extensible" + ); +}); +Assertion.addProperty("sealed", function() { + let obj = flag2(this, "object"); + let isSealed = obj === Object(obj) ? Object.isSealed(obj) : true; + this.assert( + isSealed, + "expected #{this} to be sealed", + "expected #{this} to not be sealed" + ); +}); +Assertion.addProperty("frozen", function() { + let obj = flag2(this, "object"); + let isFrozen = obj === Object(obj) ? Object.isFrozen(obj) : true; + this.assert( + isFrozen, + "expected #{this} to be frozen", + "expected #{this} to not be frozen" + ); +}); +Assertion.addProperty("finite", function(_msg) { + let obj = flag2(this, "object"); + this.assert( + typeof obj === "number" && isFinite(obj), + "expected #{this} to be a finite number", + "expected #{this} to not be a finite number" + ); +}); +function compareSubset(expected, actual) { + if (expected === actual) { + return true; + } + if (typeof actual !== typeof expected) { + return false; + } + if (typeof expected !== "object" || expected === null) { + return expected === actual; + } + if (!actual) { + return false; + } + if (Array.isArray(expected)) { + if (!Array.isArray(actual)) { + return false; + } + return expected.every(function(exp) { + return actual.some(function(act) { + return compareSubset(exp, act); + }); + }); + } + if (expected instanceof Date) { + if (actual instanceof Date) { + return expected.getTime() === actual.getTime(); + } else { + return false; + } + } + return Object.keys(expected).every(function(key) { + let expectedValue = expected[key]; + let actualValue = actual[key]; + if (typeof expectedValue === "object" && expectedValue !== null && actualValue !== null) { + return compareSubset(expectedValue, actualValue); + } + if (typeof expectedValue === "function") { + return expectedValue(actualValue); + } + return actualValue === expectedValue; + }); +} +__name(compareSubset, "compareSubset"); +Assertion.addMethod("containSubset", function(expected) { + const actual = flag(this, "object"); + const showDiff = config.showDiff; + this.assert( + compareSubset(expected, actual), + "expected #{act} to contain subset #{exp}", + "expected #{act} to not contain subset #{exp}", + expected, + actual, + showDiff + ); +}); + +// lib/chai/interface/expect.js +function expect(val, message) { + return new Assertion(val, message); +} +__name(expect, "expect"); +expect.fail = function(actual, expected, message, operator) { + if (arguments.length < 2) { + message = actual; + actual = void 0; + } + message = message || "expect.fail()"; + throw new AssertionError( + message, + { + actual, + expected, + operator + }, + expect.fail + ); +}; + +// lib/chai/interface/should.js +var should_exports = {}; +__export(should_exports, { + Should: () => Should, + should: () => should +}); +function loadShould() { + function shouldGetter() { + if (this instanceof String || this instanceof Number || this instanceof Boolean || typeof Symbol === "function" && this instanceof Symbol || typeof BigInt === "function" && this instanceof BigInt) { + return new Assertion(this.valueOf(), null, shouldGetter); + } + return new Assertion(this, null, shouldGetter); + } + __name(shouldGetter, "shouldGetter"); + function shouldSetter(value) { + Object.defineProperty(this, "should", { + value, + enumerable: true, + configurable: true, + writable: true + }); + } + __name(shouldSetter, "shouldSetter"); + Object.defineProperty(Object.prototype, "should", { + set: shouldSetter, + get: shouldGetter, + configurable: true + }); + let should2 = {}; + should2.fail = function(actual, expected, message, operator) { + if (arguments.length < 2) { + message = actual; + actual = void 0; + } + message = message || "should.fail()"; + throw new AssertionError( + message, + { + actual, + expected, + operator + }, + should2.fail + ); + }; + should2.equal = function(actual, expected, message) { + new Assertion(actual, message).to.equal(expected); + }; + should2.Throw = function(fn, errt, errs, msg) { + new Assertion(fn, msg).to.Throw(errt, errs); + }; + should2.exist = function(val, msg) { + new Assertion(val, msg).to.exist; + }; + should2.not = {}; + should2.not.equal = function(actual, expected, msg) { + new Assertion(actual, msg).to.not.equal(expected); + }; + should2.not.Throw = function(fn, errt, errs, msg) { + new Assertion(fn, msg).to.not.Throw(errt, errs); + }; + should2.not.exist = function(val, msg) { + new Assertion(val, msg).to.not.exist; + }; + should2["throw"] = should2["Throw"]; + should2.not["throw"] = should2.not["Throw"]; + return should2; +} +__name(loadShould, "loadShould"); +var should = loadShould; +var Should = loadShould; + +// lib/chai/interface/assert.js +function assert(express, errmsg) { + let test2 = new Assertion(null, null, assert, true); + test2.assert(express, errmsg, "[ negation message unavailable ]"); +} +__name(assert, "assert"); +assert.fail = function(actual, expected, message, operator) { + if (arguments.length < 2) { + message = actual; + actual = void 0; + } + message = message || "assert.fail()"; + throw new AssertionError( + message, + { + actual, + expected, + operator + }, + assert.fail + ); +}; +assert.isOk = function(val, msg) { + new Assertion(val, msg, assert.isOk, true).is.ok; +}; +assert.isNotOk = function(val, msg) { + new Assertion(val, msg, assert.isNotOk, true).is.not.ok; +}; +assert.equal = function(act, exp, msg) { + let test2 = new Assertion(act, msg, assert.equal, true); + test2.assert( + exp == flag(test2, "object"), + "expected #{this} to equal #{exp}", + "expected #{this} to not equal #{act}", + exp, + act, + true + ); +}; +assert.notEqual = function(act, exp, msg) { + let test2 = new Assertion(act, msg, assert.notEqual, true); + test2.assert( + exp != flag(test2, "object"), + "expected #{this} to not equal #{exp}", + "expected #{this} to equal #{act}", + exp, + act, + true + ); +}; +assert.strictEqual = function(act, exp, msg) { + new Assertion(act, msg, assert.strictEqual, true).to.equal(exp); +}; +assert.notStrictEqual = function(act, exp, msg) { + new Assertion(act, msg, assert.notStrictEqual, true).to.not.equal(exp); +}; +assert.deepEqual = assert.deepStrictEqual = function(act, exp, msg) { + new Assertion(act, msg, assert.deepEqual, true).to.eql(exp); +}; +assert.notDeepEqual = function(act, exp, msg) { + new Assertion(act, msg, assert.notDeepEqual, true).to.not.eql(exp); +}; +assert.isAbove = function(val, abv, msg) { + new Assertion(val, msg, assert.isAbove, true).to.be.above(abv); +}; +assert.isAtLeast = function(val, atlst, msg) { + new Assertion(val, msg, assert.isAtLeast, true).to.be.least(atlst); +}; +assert.isBelow = function(val, blw, msg) { + new Assertion(val, msg, assert.isBelow, true).to.be.below(blw); +}; +assert.isAtMost = function(val, atmst, msg) { + new Assertion(val, msg, assert.isAtMost, true).to.be.most(atmst); +}; +assert.isTrue = function(val, msg) { + new Assertion(val, msg, assert.isTrue, true).is["true"]; +}; +assert.isNotTrue = function(val, msg) { + new Assertion(val, msg, assert.isNotTrue, true).to.not.equal(true); +}; +assert.isFalse = function(val, msg) { + new Assertion(val, msg, assert.isFalse, true).is["false"]; +}; +assert.isNotFalse = function(val, msg) { + new Assertion(val, msg, assert.isNotFalse, true).to.not.equal(false); +}; +assert.isNull = function(val, msg) { + new Assertion(val, msg, assert.isNull, true).to.equal(null); +}; +assert.isNotNull = function(val, msg) { + new Assertion(val, msg, assert.isNotNull, true).to.not.equal(null); +}; +assert.isNaN = function(val, msg) { + new Assertion(val, msg, assert.isNaN, true).to.be.NaN; +}; +assert.isNotNaN = function(value, message) { + new Assertion(value, message, assert.isNotNaN, true).not.to.be.NaN; +}; +assert.exists = function(val, msg) { + new Assertion(val, msg, assert.exists, true).to.exist; +}; +assert.notExists = function(val, msg) { + new Assertion(val, msg, assert.notExists, true).to.not.exist; +}; +assert.isUndefined = function(val, msg) { + new Assertion(val, msg, assert.isUndefined, true).to.equal(void 0); +}; +assert.isDefined = function(val, msg) { + new Assertion(val, msg, assert.isDefined, true).to.not.equal(void 0); +}; +assert.isCallable = function(value, message) { + new Assertion(value, message, assert.isCallable, true).is.callable; +}; +assert.isNotCallable = function(value, message) { + new Assertion(value, message, assert.isNotCallable, true).is.not.callable; +}; +assert.isObject = function(val, msg) { + new Assertion(val, msg, assert.isObject, true).to.be.a("object"); +}; +assert.isNotObject = function(val, msg) { + new Assertion(val, msg, assert.isNotObject, true).to.not.be.a("object"); +}; +assert.isArray = function(val, msg) { + new Assertion(val, msg, assert.isArray, true).to.be.an("array"); +}; +assert.isNotArray = function(val, msg) { + new Assertion(val, msg, assert.isNotArray, true).to.not.be.an("array"); +}; +assert.isString = function(val, msg) { + new Assertion(val, msg, assert.isString, true).to.be.a("string"); +}; +assert.isNotString = function(val, msg) { + new Assertion(val, msg, assert.isNotString, true).to.not.be.a("string"); +}; +assert.isNumber = function(val, msg) { + new Assertion(val, msg, assert.isNumber, true).to.be.a("number"); +}; +assert.isNotNumber = function(val, msg) { + new Assertion(val, msg, assert.isNotNumber, true).to.not.be.a("number"); +}; +assert.isNumeric = function(val, msg) { + new Assertion(val, msg, assert.isNumeric, true).is.numeric; +}; +assert.isNotNumeric = function(val, msg) { + new Assertion(val, msg, assert.isNotNumeric, true).is.not.numeric; +}; +assert.isFinite = function(val, msg) { + new Assertion(val, msg, assert.isFinite, true).to.be.finite; +}; +assert.isBoolean = function(val, msg) { + new Assertion(val, msg, assert.isBoolean, true).to.be.a("boolean"); +}; +assert.isNotBoolean = function(val, msg) { + new Assertion(val, msg, assert.isNotBoolean, true).to.not.be.a("boolean"); +}; +assert.typeOf = function(val, type3, msg) { + new Assertion(val, msg, assert.typeOf, true).to.be.a(type3); +}; +assert.notTypeOf = function(value, type3, message) { + new Assertion(value, message, assert.notTypeOf, true).to.not.be.a(type3); +}; +assert.instanceOf = function(val, type3, msg) { + new Assertion(val, msg, assert.instanceOf, true).to.be.instanceOf(type3); +}; +assert.notInstanceOf = function(val, type3, msg) { + new Assertion(val, msg, assert.notInstanceOf, true).to.not.be.instanceOf( + type3 + ); +}; +assert.include = function(exp, inc, msg) { + new Assertion(exp, msg, assert.include, true).include(inc); +}; +assert.notInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.notInclude, true).not.include(inc); +}; +assert.deepInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.deepInclude, true).deep.include(inc); +}; +assert.notDeepInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.notDeepInclude, true).not.deep.include(inc); +}; +assert.nestedInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.nestedInclude, true).nested.include(inc); +}; +assert.notNestedInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.notNestedInclude, true).not.nested.include( + inc + ); +}; +assert.deepNestedInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.deepNestedInclude, true).deep.nested.include( + inc + ); +}; +assert.notDeepNestedInclude = function(exp, inc, msg) { + new Assertion( + exp, + msg, + assert.notDeepNestedInclude, + true + ).not.deep.nested.include(inc); +}; +assert.ownInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.ownInclude, true).own.include(inc); +}; +assert.notOwnInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.notOwnInclude, true).not.own.include(inc); +}; +assert.deepOwnInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.deepOwnInclude, true).deep.own.include(inc); +}; +assert.notDeepOwnInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.notDeepOwnInclude, true).not.deep.own.include( + inc + ); +}; +assert.match = function(exp, re, msg) { + new Assertion(exp, msg, assert.match, true).to.match(re); +}; +assert.notMatch = function(exp, re, msg) { + new Assertion(exp, msg, assert.notMatch, true).to.not.match(re); +}; +assert.property = function(obj, prop, msg) { + new Assertion(obj, msg, assert.property, true).to.have.property(prop); +}; +assert.notProperty = function(obj, prop, msg) { + new Assertion(obj, msg, assert.notProperty, true).to.not.have.property(prop); +}; +assert.propertyVal = function(obj, prop, val, msg) { + new Assertion(obj, msg, assert.propertyVal, true).to.have.property(prop, val); +}; +assert.notPropertyVal = function(obj, prop, val, msg) { + new Assertion(obj, msg, assert.notPropertyVal, true).to.not.have.property( + prop, + val + ); +}; +assert.deepPropertyVal = function(obj, prop, val, msg) { + new Assertion(obj, msg, assert.deepPropertyVal, true).to.have.deep.property( + prop, + val + ); +}; +assert.notDeepPropertyVal = function(obj, prop, val, msg) { + new Assertion( + obj, + msg, + assert.notDeepPropertyVal, + true + ).to.not.have.deep.property(prop, val); +}; +assert.ownProperty = function(obj, prop, msg) { + new Assertion(obj, msg, assert.ownProperty, true).to.have.own.property(prop); +}; +assert.notOwnProperty = function(obj, prop, msg) { + new Assertion(obj, msg, assert.notOwnProperty, true).to.not.have.own.property( + prop + ); +}; +assert.ownPropertyVal = function(obj, prop, value, msg) { + new Assertion(obj, msg, assert.ownPropertyVal, true).to.have.own.property( + prop, + value + ); +}; +assert.notOwnPropertyVal = function(obj, prop, value, msg) { + new Assertion( + obj, + msg, + assert.notOwnPropertyVal, + true + ).to.not.have.own.property(prop, value); +}; +assert.deepOwnPropertyVal = function(obj, prop, value, msg) { + new Assertion( + obj, + msg, + assert.deepOwnPropertyVal, + true + ).to.have.deep.own.property(prop, value); +}; +assert.notDeepOwnPropertyVal = function(obj, prop, value, msg) { + new Assertion( + obj, + msg, + assert.notDeepOwnPropertyVal, + true + ).to.not.have.deep.own.property(prop, value); +}; +assert.nestedProperty = function(obj, prop, msg) { + new Assertion(obj, msg, assert.nestedProperty, true).to.have.nested.property( + prop + ); +}; +assert.notNestedProperty = function(obj, prop, msg) { + new Assertion( + obj, + msg, + assert.notNestedProperty, + true + ).to.not.have.nested.property(prop); +}; +assert.nestedPropertyVal = function(obj, prop, val, msg) { + new Assertion( + obj, + msg, + assert.nestedPropertyVal, + true + ).to.have.nested.property(prop, val); +}; +assert.notNestedPropertyVal = function(obj, prop, val, msg) { + new Assertion( + obj, + msg, + assert.notNestedPropertyVal, + true + ).to.not.have.nested.property(prop, val); +}; +assert.deepNestedPropertyVal = function(obj, prop, val, msg) { + new Assertion( + obj, + msg, + assert.deepNestedPropertyVal, + true + ).to.have.deep.nested.property(prop, val); +}; +assert.notDeepNestedPropertyVal = function(obj, prop, val, msg) { + new Assertion( + obj, + msg, + assert.notDeepNestedPropertyVal, + true + ).to.not.have.deep.nested.property(prop, val); +}; +assert.lengthOf = function(exp, len, msg) { + new Assertion(exp, msg, assert.lengthOf, true).to.have.lengthOf(len); +}; +assert.hasAnyKeys = function(obj, keys, msg) { + new Assertion(obj, msg, assert.hasAnyKeys, true).to.have.any.keys(keys); +}; +assert.hasAllKeys = function(obj, keys, msg) { + new Assertion(obj, msg, assert.hasAllKeys, true).to.have.all.keys(keys); +}; +assert.containsAllKeys = function(obj, keys, msg) { + new Assertion(obj, msg, assert.containsAllKeys, true).to.contain.all.keys( + keys + ); +}; +assert.doesNotHaveAnyKeys = function(obj, keys, msg) { + new Assertion(obj, msg, assert.doesNotHaveAnyKeys, true).to.not.have.any.keys( + keys + ); +}; +assert.doesNotHaveAllKeys = function(obj, keys, msg) { + new Assertion(obj, msg, assert.doesNotHaveAllKeys, true).to.not.have.all.keys( + keys + ); +}; +assert.hasAnyDeepKeys = function(obj, keys, msg) { + new Assertion(obj, msg, assert.hasAnyDeepKeys, true).to.have.any.deep.keys( + keys + ); +}; +assert.hasAllDeepKeys = function(obj, keys, msg) { + new Assertion(obj, msg, assert.hasAllDeepKeys, true).to.have.all.deep.keys( + keys + ); +}; +assert.containsAllDeepKeys = function(obj, keys, msg) { + new Assertion( + obj, + msg, + assert.containsAllDeepKeys, + true + ).to.contain.all.deep.keys(keys); +}; +assert.doesNotHaveAnyDeepKeys = function(obj, keys, msg) { + new Assertion( + obj, + msg, + assert.doesNotHaveAnyDeepKeys, + true + ).to.not.have.any.deep.keys(keys); +}; +assert.doesNotHaveAllDeepKeys = function(obj, keys, msg) { + new Assertion( + obj, + msg, + assert.doesNotHaveAllDeepKeys, + true + ).to.not.have.all.deep.keys(keys); +}; +assert.throws = function(fn, errorLike, errMsgMatcher, msg) { + if ("string" === typeof errorLike || errorLike instanceof RegExp) { + errMsgMatcher = errorLike; + errorLike = null; + } + let assertErr = new Assertion(fn, msg, assert.throws, true).to.throw( + errorLike, + errMsgMatcher + ); + return flag(assertErr, "object"); +}; +assert.doesNotThrow = function(fn, errorLike, errMsgMatcher, message) { + if ("string" === typeof errorLike || errorLike instanceof RegExp) { + errMsgMatcher = errorLike; + errorLike = null; + } + new Assertion(fn, message, assert.doesNotThrow, true).to.not.throw( + errorLike, + errMsgMatcher + ); +}; +assert.operator = function(val, operator, val2, msg) { + let ok; + switch (operator) { + case "==": + ok = val == val2; + break; + case "===": + ok = val === val2; + break; + case ">": + ok = val > val2; + break; + case ">=": + ok = val >= val2; + break; + case "<": + ok = val < val2; + break; + case "<=": + ok = val <= val2; + break; + case "!=": + ok = val != val2; + break; + case "!==": + ok = val !== val2; + break; + default: + msg = msg ? msg + ": " : msg; + throw new AssertionError( + msg + 'Invalid operator "' + operator + '"', + void 0, + assert.operator + ); + } + let test2 = new Assertion(ok, msg, assert.operator, true); + test2.assert( + true === flag(test2, "object"), + "expected " + inspect2(val) + " to be " + operator + " " + inspect2(val2), + "expected " + inspect2(val) + " to not be " + operator + " " + inspect2(val2) + ); +}; +assert.closeTo = function(act, exp, delta, msg) { + new Assertion(act, msg, assert.closeTo, true).to.be.closeTo(exp, delta); +}; +assert.approximately = function(act, exp, delta, msg) { + new Assertion(act, msg, assert.approximately, true).to.be.approximately( + exp, + delta + ); +}; +assert.sameMembers = function(set1, set2, msg) { + new Assertion(set1, msg, assert.sameMembers, true).to.have.same.members(set2); +}; +assert.notSameMembers = function(set1, set2, msg) { + new Assertion( + set1, + msg, + assert.notSameMembers, + true + ).to.not.have.same.members(set2); +}; +assert.sameDeepMembers = function(set1, set2, msg) { + new Assertion( + set1, + msg, + assert.sameDeepMembers, + true + ).to.have.same.deep.members(set2); +}; +assert.notSameDeepMembers = function(set1, set2, msg) { + new Assertion( + set1, + msg, + assert.notSameDeepMembers, + true + ).to.not.have.same.deep.members(set2); +}; +assert.sameOrderedMembers = function(set1, set2, msg) { + new Assertion( + set1, + msg, + assert.sameOrderedMembers, + true + ).to.have.same.ordered.members(set2); +}; +assert.notSameOrderedMembers = function(set1, set2, msg) { + new Assertion( + set1, + msg, + assert.notSameOrderedMembers, + true + ).to.not.have.same.ordered.members(set2); +}; +assert.sameDeepOrderedMembers = function(set1, set2, msg) { + new Assertion( + set1, + msg, + assert.sameDeepOrderedMembers, + true + ).to.have.same.deep.ordered.members(set2); +}; +assert.notSameDeepOrderedMembers = function(set1, set2, msg) { + new Assertion( + set1, + msg, + assert.notSameDeepOrderedMembers, + true + ).to.not.have.same.deep.ordered.members(set2); +}; +assert.includeMembers = function(superset, subset, msg) { + new Assertion(superset, msg, assert.includeMembers, true).to.include.members( + subset + ); +}; +assert.notIncludeMembers = function(superset, subset, msg) { + new Assertion( + superset, + msg, + assert.notIncludeMembers, + true + ).to.not.include.members(subset); +}; +assert.includeDeepMembers = function(superset, subset, msg) { + new Assertion( + superset, + msg, + assert.includeDeepMembers, + true + ).to.include.deep.members(subset); +}; +assert.notIncludeDeepMembers = function(superset, subset, msg) { + new Assertion( + superset, + msg, + assert.notIncludeDeepMembers, + true + ).to.not.include.deep.members(subset); +}; +assert.includeOrderedMembers = function(superset, subset, msg) { + new Assertion( + superset, + msg, + assert.includeOrderedMembers, + true + ).to.include.ordered.members(subset); +}; +assert.notIncludeOrderedMembers = function(superset, subset, msg) { + new Assertion( + superset, + msg, + assert.notIncludeOrderedMembers, + true + ).to.not.include.ordered.members(subset); +}; +assert.includeDeepOrderedMembers = function(superset, subset, msg) { + new Assertion( + superset, + msg, + assert.includeDeepOrderedMembers, + true + ).to.include.deep.ordered.members(subset); +}; +assert.notIncludeDeepOrderedMembers = function(superset, subset, msg) { + new Assertion( + superset, + msg, + assert.notIncludeDeepOrderedMembers, + true + ).to.not.include.deep.ordered.members(subset); +}; +assert.oneOf = function(inList, list, msg) { + new Assertion(inList, msg, assert.oneOf, true).to.be.oneOf(list); +}; +assert.isIterable = function(obj, msg) { + if (obj == void 0 || !obj[Symbol.iterator]) { + msg = msg ? `${msg} expected ${inspect2(obj)} to be an iterable` : `expected ${inspect2(obj)} to be an iterable`; + throw new AssertionError(msg, void 0, assert.isIterable); + } +}; +assert.changes = function(fn, obj, prop, msg) { + if (arguments.length === 3 && typeof obj === "function") { + msg = prop; + prop = null; + } + new Assertion(fn, msg, assert.changes, true).to.change(obj, prop); +}; +assert.changesBy = function(fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === "function") { + let tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + new Assertion(fn, msg, assert.changesBy, true).to.change(obj, prop).by(delta); +}; +assert.doesNotChange = function(fn, obj, prop, msg) { + if (arguments.length === 3 && typeof obj === "function") { + msg = prop; + prop = null; + } + return new Assertion(fn, msg, assert.doesNotChange, true).to.not.change( + obj, + prop + ); +}; +assert.changesButNotBy = function(fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === "function") { + let tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + new Assertion(fn, msg, assert.changesButNotBy, true).to.change(obj, prop).but.not.by(delta); +}; +assert.increases = function(fn, obj, prop, msg) { + if (arguments.length === 3 && typeof obj === "function") { + msg = prop; + prop = null; + } + return new Assertion(fn, msg, assert.increases, true).to.increase(obj, prop); +}; +assert.increasesBy = function(fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === "function") { + let tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + new Assertion(fn, msg, assert.increasesBy, true).to.increase(obj, prop).by(delta); +}; +assert.doesNotIncrease = function(fn, obj, prop, msg) { + if (arguments.length === 3 && typeof obj === "function") { + msg = prop; + prop = null; + } + return new Assertion(fn, msg, assert.doesNotIncrease, true).to.not.increase( + obj, + prop + ); +}; +assert.increasesButNotBy = function(fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === "function") { + let tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + new Assertion(fn, msg, assert.increasesButNotBy, true).to.increase(obj, prop).but.not.by(delta); +}; +assert.decreases = function(fn, obj, prop, msg) { + if (arguments.length === 3 && typeof obj === "function") { + msg = prop; + prop = null; + } + return new Assertion(fn, msg, assert.decreases, true).to.decrease(obj, prop); +}; +assert.decreasesBy = function(fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === "function") { + let tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + new Assertion(fn, msg, assert.decreasesBy, true).to.decrease(obj, prop).by(delta); +}; +assert.doesNotDecrease = function(fn, obj, prop, msg) { + if (arguments.length === 3 && typeof obj === "function") { + msg = prop; + prop = null; + } + return new Assertion(fn, msg, assert.doesNotDecrease, true).to.not.decrease( + obj, + prop + ); +}; +assert.doesNotDecreaseBy = function(fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === "function") { + let tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + return new Assertion(fn, msg, assert.doesNotDecreaseBy, true).to.not.decrease(obj, prop).by(delta); +}; +assert.decreasesButNotBy = function(fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === "function") { + let tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + new Assertion(fn, msg, assert.decreasesButNotBy, true).to.decrease(obj, prop).but.not.by(delta); +}; +assert.ifError = function(val) { + if (val) { + throw val; + } +}; +assert.isExtensible = function(obj, msg) { + new Assertion(obj, msg, assert.isExtensible, true).to.be.extensible; +}; +assert.isNotExtensible = function(obj, msg) { + new Assertion(obj, msg, assert.isNotExtensible, true).to.not.be.extensible; +}; +assert.isSealed = function(obj, msg) { + new Assertion(obj, msg, assert.isSealed, true).to.be.sealed; +}; +assert.isNotSealed = function(obj, msg) { + new Assertion(obj, msg, assert.isNotSealed, true).to.not.be.sealed; +}; +assert.isFrozen = function(obj, msg) { + new Assertion(obj, msg, assert.isFrozen, true).to.be.frozen; +}; +assert.isNotFrozen = function(obj, msg) { + new Assertion(obj, msg, assert.isNotFrozen, true).to.not.be.frozen; +}; +assert.isEmpty = function(val, msg) { + new Assertion(val, msg, assert.isEmpty, true).to.be.empty; +}; +assert.isNotEmpty = function(val, msg) { + new Assertion(val, msg, assert.isNotEmpty, true).to.not.be.empty; +}; +assert.containsSubset = function(val, exp, msg) { + new Assertion(val, msg).to.containSubset(exp); +}; +assert.doesNotContainSubset = function(val, exp, msg) { + new Assertion(val, msg).to.not.containSubset(exp); +}; +var aliases = [ + ["isOk", "ok"], + ["isNotOk", "notOk"], + ["throws", "throw"], + ["throws", "Throw"], + ["isExtensible", "extensible"], + ["isNotExtensible", "notExtensible"], + ["isSealed", "sealed"], + ["isNotSealed", "notSealed"], + ["isFrozen", "frozen"], + ["isNotFrozen", "notFrozen"], + ["isEmpty", "empty"], + ["isNotEmpty", "notEmpty"], + ["isCallable", "isFunction"], + ["isNotCallable", "isNotFunction"], + ["containsSubset", "containSubset"] +]; +for (const [name, as] of aliases) { + assert[as] = assert[name]; +} + +// lib/chai.js +var used = []; +function use(fn) { + const exports = { + use, + AssertionError, + util: utils_exports, + config, + expect, + assert, + Assertion, + ...should_exports + }; + if (!~used.indexOf(fn)) { + fn(exports, utils_exports); + used.push(fn); + } + return exports; +} +__name(use, "use"); +export { + Assertion, + AssertionError, + Should, + assert, + config, + expect, + should, + use, + utils_exports as util +}; diff --git a/node_modules/chai/package.json b/node_modules/chai/package.json new file mode 100644 index 00000000..f2ad34b1 --- /dev/null +++ b/node_modules/chai/package.json @@ -0,0 +1,71 @@ +{ + "author": "Jake Luer ", + "name": "chai", + "type": "module", + "description": "BDD/TDD assertion library for node.js and the browser. Test framework agnostic.", + "keywords": [ + "test", + "assertion", + "assert", + "testing", + "chai" + ], + "files": [ + "index.js", + "register-*.js" + ], + "homepage": "http://chaijs.com", + "license": "MIT", + "contributors": [ + "Jake Luer ", + "Domenic Denicola (http://domenicdenicola.com)", + "Veselin Todorov ", + "John Firebaugh " + ], + "version": "6.2.2", + "repository": { + "type": "git", + "url": "https://github.com/chaijs/chai" + }, + "bugs": { + "url": "https://github.com/chaijs/chai/issues" + }, + "main": "./index.js", + "scripts": { + "build": "esbuild --bundle --format=esm --target=es2021 --keep-names --legal-comments=none --outfile=index.js lib/chai.js", + "prebuild": "npm run clean", + "format": "prettier --write lib", + "pretest": "npm run lint", + "test": "npm run test-node && npm run test-chrome", + "test-node": "c8 --99 --check-coverage mocha --require ./test/bootstrap/index.js test/*.js", + "test-chrome": "web-test-runner --playwright", + "lint": "npm run lint:js && npm run lint:format", + "lint:js": "eslint lib/", + "lint:format": "prettier --check lib", + "lint:types": "tsc", + "clean": "rm -rf index.js coverage/" + }, + "engines": { + "node": ">=18" + }, + "devDependencies": { + "@eslint/js": "^9.17.0", + "@rollup/plugin-commonjs": "^29.0.0", + "@web/dev-server-rollup": "^0.6.1", + "@web/test-runner": "^0.20.0", + "@web/test-runner-playwright": "^0.11.0", + "assertion-error": "^2.0.1", + "c8": "^10.1.3", + "check-error": "^2.1.1", + "deep-eql": "^5.0.1", + "esbuild": "^0.27.0", + "eslint": "^9.0.0", + "eslint-plugin-jsdoc": "^61.0.0", + "globals": "^16.3.0", + "loupe": "^3.1.0", + "mocha": "^11.0.0", + "pathval": "^2.0.0", + "prettier": "^3.4.2", + "typescript": "~5.9.0" + } +} diff --git a/node_modules/chai/register-assert.js b/node_modules/chai/register-assert.js new file mode 100644 index 00000000..f593717e --- /dev/null +++ b/node_modules/chai/register-assert.js @@ -0,0 +1,3 @@ +import {assert} from './index.js'; + +globalThis.assert = assert; diff --git a/node_modules/chai/register-expect.js b/node_modules/chai/register-expect.js new file mode 100644 index 00000000..2807b89b --- /dev/null +++ b/node_modules/chai/register-expect.js @@ -0,0 +1,3 @@ +import {expect} from './index.js'; + +globalThis.expect = expect; diff --git a/node_modules/chai/register-should.js b/node_modules/chai/register-should.js new file mode 100644 index 00000000..1339ee4c --- /dev/null +++ b/node_modules/chai/register-should.js @@ -0,0 +1,3 @@ +import {should} from './index.js'; + +globalThis.should = should(); diff --git a/node_modules/convert-source-map/LICENSE b/node_modules/convert-source-map/LICENSE new file mode 100644 index 00000000..41702c50 --- /dev/null +++ b/node_modules/convert-source-map/LICENSE @@ -0,0 +1,23 @@ +Copyright 2013 Thorsten Lorenz. +All rights reserved. + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/convert-source-map/README.md b/node_modules/convert-source-map/README.md new file mode 100644 index 00000000..aa4d8048 --- /dev/null +++ b/node_modules/convert-source-map/README.md @@ -0,0 +1,206 @@ +# convert-source-map [![Build Status][ci-image]][ci-url] + +Converts a source-map from/to different formats and allows adding/changing properties. + +```js +var convert = require('convert-source-map'); + +var json = convert + .fromComment('//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYnVpbGQvZm9vLm1pbi5qcyIsInNvdXJjZXMiOlsic3JjL2Zvby5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSIsInNvdXJjZVJvb3QiOiIvIn0=') + .toJSON(); + +var modified = convert + .fromComment('//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYnVpbGQvZm9vLm1pbi5qcyIsInNvdXJjZXMiOlsic3JjL2Zvby5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSIsInNvdXJjZVJvb3QiOiIvIn0=') + .setProperty('sources', [ 'SRC/FOO.JS' ]) + .toJSON(); + +console.log(json); +console.log(modified); +``` + +```json +{"version":3,"file":"build/foo.min.js","sources":["src/foo.js"],"names":[],"mappings":"AAAA","sourceRoot":"/"} +{"version":3,"file":"build/foo.min.js","sources":["SRC/FOO.JS"],"names":[],"mappings":"AAAA","sourceRoot":"/"} +``` + +## Upgrading + +Prior to v2.0.0, the `fromMapFileComment` and `fromMapFileSource` functions took a String directory path and used that to resolve & read the source map file from the filesystem. However, this made the library limited to nodejs environments and broke on sources with querystrings. + +In v2.0.0, you now need to pass a function that does the file reading. It will receive the source filename as a String that you can resolve to a filesystem path, URL, or anything else. + +If you are using `convert-source-map` in nodejs and want the previous behavior, you'll use a function like such: + +```diff ++ var fs = require('fs'); // Import the fs module to read a file ++ var path = require('path'); // Import the path module to resolve a path against your directory +- var conv = convert.fromMapFileSource(css, '../my-dir'); ++ var conv = convert.fromMapFileSource(css, function (filename) { ++ return fs.readFileSync(path.resolve('../my-dir', filename), 'utf-8'); ++ }); +``` + +## API + +### fromObject(obj) + +Returns source map converter from given object. + +### fromJSON(json) + +Returns source map converter from given json string. + +### fromURI(uri) + +Returns source map converter from given uri encoded json string. + +### fromBase64(base64) + +Returns source map converter from given base64 encoded json string. + +### fromComment(comment) + +Returns source map converter from given base64 or uri encoded json string prefixed with `//# sourceMappingURL=...`. + +### fromMapFileComment(comment, readMap) + +Returns source map converter from given `filename` by parsing `//# sourceMappingURL=filename`. + +`readMap` must be a function which receives the source map filename and returns either a String or Buffer of the source map (if read synchronously), or a `Promise` containing a String or Buffer of the source map (if read asynchronously). + +If `readMap` doesn't return a `Promise`, `fromMapFileComment` will return a source map converter synchronously. + +If `readMap` returns a `Promise`, `fromMapFileComment` will also return `Promise`. The `Promise` will be either resolved with the source map converter or rejected with an error. + +#### Examples + +**Synchronous read in Node.js:** + +```js +var convert = require('convert-source-map'); +var fs = require('fs'); + +function readMap(filename) { + return fs.readFileSync(filename, 'utf8'); +} + +var json = convert + .fromMapFileComment('//# sourceMappingURL=map-file-comment.css.map', readMap) + .toJSON(); +console.log(json); +``` + + +**Asynchronous read in Node.js:** + +```js +var convert = require('convert-source-map'); +var { promises: fs } = require('fs'); // Notice the `promises` import + +function readMap(filename) { + return fs.readFile(filename, 'utf8'); +} + +var converter = await convert.fromMapFileComment('//# sourceMappingURL=map-file-comment.css.map', readMap) +var json = converter.toJSON(); +console.log(json); +``` + +**Asynchronous read in the browser:** + +```js +var convert = require('convert-source-map'); + +async function readMap(url) { + const res = await fetch(url); + return res.text(); +} + +const converter = await convert.fromMapFileComment('//# sourceMappingURL=map-file-comment.css.map', readMap) +var json = converter.toJSON(); +console.log(json); +``` + +### fromSource(source) + +Finds last sourcemap comment in file and returns source map converter or returns `null` if no source map comment was found. + +### fromMapFileSource(source, readMap) + +Finds last sourcemap comment in file and returns source map converter or returns `null` if no source map comment was found. + +`readMap` must be a function which receives the source map filename and returns either a String or Buffer of the source map (if read synchronously), or a `Promise` containing a String or Buffer of the source map (if read asynchronously). + +If `readMap` doesn't return a `Promise`, `fromMapFileSource` will return a source map converter synchronously. + +If `readMap` returns a `Promise`, `fromMapFileSource` will also return `Promise`. The `Promise` will be either resolved with the source map converter or rejected with an error. + +### toObject() + +Returns a copy of the underlying source map. + +### toJSON([space]) + +Converts source map to json string. If `space` is given (optional), this will be passed to +[JSON.stringify](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringify) when the +JSON string is generated. + +### toURI() + +Converts source map to uri encoded json string. + +### toBase64() + +Converts source map to base64 encoded json string. + +### toComment([options]) + +Converts source map to an inline comment that can be appended to the source-file. + +By default, the comment is formatted like: `//# sourceMappingURL=...`, which you would +normally see in a JS source file. + +When `options.encoding == 'uri'`, the data will be uri encoded, otherwise they will be base64 encoded. + +When `options.multiline == true`, the comment is formatted like: `/*# sourceMappingURL=... */`, which you would find in a CSS source file. + +### addProperty(key, value) + +Adds given property to the source map. Throws an error if property already exists. + +### setProperty(key, value) + +Sets given property to the source map. If property doesn't exist it is added, otherwise its value is updated. + +### getProperty(key) + +Gets given property of the source map. + +### removeComments(src) + +Returns `src` with all source map comments removed + +### removeMapFileComments(src) + +Returns `src` with all source map comments pointing to map files removed. + +### commentRegex + +Provides __a fresh__ RegExp each time it is accessed. Can be used to find source map comments. + +Breaks down a source map comment into groups: Groups: 1: media type, 2: MIME type, 3: charset, 4: encoding, 5: data. + +### mapFileCommentRegex + +Provides __a fresh__ RegExp each time it is accessed. Can be used to find source map comments pointing to map files. + +### generateMapFileComment(file, [options]) + +Returns a comment that links to an external source map via `file`. + +By default, the comment is formatted like: `//# sourceMappingURL=...`, which you would normally see in a JS source file. + +When `options.multiline == true`, the comment is formatted like: `/*# sourceMappingURL=... */`, which you would find in a CSS source file. + +[ci-url]: https://github.com/thlorenz/convert-source-map/actions?query=workflow:ci +[ci-image]: https://img.shields.io/github/workflow/status/thlorenz/convert-source-map/CI?style=flat-square diff --git a/node_modules/convert-source-map/index.js b/node_modules/convert-source-map/index.js new file mode 100644 index 00000000..2e8e916e --- /dev/null +++ b/node_modules/convert-source-map/index.js @@ -0,0 +1,233 @@ +'use strict'; + +Object.defineProperty(exports, 'commentRegex', { + get: function getCommentRegex () { + // Groups: 1: media type, 2: MIME type, 3: charset, 4: encoding, 5: data. + return /^\s*?\/[\/\*][@#]\s+?sourceMappingURL=data:(((?:application|text)\/json)(?:;charset=([^;,]+?)?)?)?(?:;(base64))?,(.*?)$/mg; + } +}); + + +Object.defineProperty(exports, 'mapFileCommentRegex', { + get: function getMapFileCommentRegex () { + // Matches sourceMappingURL in either // or /* comment styles. + return /(?:\/\/[@#][ \t]+?sourceMappingURL=([^\s'"`]+?)[ \t]*?$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^*]+?)[ \t]*?(?:\*\/){1}[ \t]*?$)/mg; + } +}); + +var decodeBase64; +if (typeof Buffer !== 'undefined') { + if (typeof Buffer.from === 'function') { + decodeBase64 = decodeBase64WithBufferFrom; + } else { + decodeBase64 = decodeBase64WithNewBuffer; + } +} else { + decodeBase64 = decodeBase64WithAtob; +} + +function decodeBase64WithBufferFrom(base64) { + return Buffer.from(base64, 'base64').toString(); +} + +function decodeBase64WithNewBuffer(base64) { + if (typeof value === 'number') { + throw new TypeError('The value to decode must not be of type number.'); + } + return new Buffer(base64, 'base64').toString(); +} + +function decodeBase64WithAtob(base64) { + return decodeURIComponent(escape(atob(base64))); +} + +function stripComment(sm) { + return sm.split(',').pop(); +} + +function readFromFileMap(sm, read) { + var r = exports.mapFileCommentRegex.exec(sm); + // for some odd reason //# .. captures in 1 and /* .. */ in 2 + var filename = r[1] || r[2]; + + try { + var sm = read(filename); + if (sm != null && typeof sm.catch === 'function') { + return sm.catch(throwError); + } else { + return sm; + } + } catch (e) { + throwError(e); + } + + function throwError(e) { + throw new Error('An error occurred while trying to read the map file at ' + filename + '\n' + e.stack); + } +} + +function Converter (sm, opts) { + opts = opts || {}; + + if (opts.hasComment) { + sm = stripComment(sm); + } + + if (opts.encoding === 'base64') { + sm = decodeBase64(sm); + } else if (opts.encoding === 'uri') { + sm = decodeURIComponent(sm); + } + + if (opts.isJSON || opts.encoding) { + sm = JSON.parse(sm); + } + + this.sourcemap = sm; +} + +Converter.prototype.toJSON = function (space) { + return JSON.stringify(this.sourcemap, null, space); +}; + +if (typeof Buffer !== 'undefined') { + if (typeof Buffer.from === 'function') { + Converter.prototype.toBase64 = encodeBase64WithBufferFrom; + } else { + Converter.prototype.toBase64 = encodeBase64WithNewBuffer; + } +} else { + Converter.prototype.toBase64 = encodeBase64WithBtoa; +} + +function encodeBase64WithBufferFrom() { + var json = this.toJSON(); + return Buffer.from(json, 'utf8').toString('base64'); +} + +function encodeBase64WithNewBuffer() { + var json = this.toJSON(); + if (typeof json === 'number') { + throw new TypeError('The json to encode must not be of type number.'); + } + return new Buffer(json, 'utf8').toString('base64'); +} + +function encodeBase64WithBtoa() { + var json = this.toJSON(); + return btoa(unescape(encodeURIComponent(json))); +} + +Converter.prototype.toURI = function () { + var json = this.toJSON(); + return encodeURIComponent(json); +}; + +Converter.prototype.toComment = function (options) { + var encoding, content, data; + if (options != null && options.encoding === 'uri') { + encoding = ''; + content = this.toURI(); + } else { + encoding = ';base64'; + content = this.toBase64(); + } + data = 'sourceMappingURL=data:application/json;charset=utf-8' + encoding + ',' + content; + return options != null && options.multiline ? '/*# ' + data + ' */' : '//# ' + data; +}; + +// returns copy instead of original +Converter.prototype.toObject = function () { + return JSON.parse(this.toJSON()); +}; + +Converter.prototype.addProperty = function (key, value) { + if (this.sourcemap.hasOwnProperty(key)) throw new Error('property "' + key + '" already exists on the sourcemap, use set property instead'); + return this.setProperty(key, value); +}; + +Converter.prototype.setProperty = function (key, value) { + this.sourcemap[key] = value; + return this; +}; + +Converter.prototype.getProperty = function (key) { + return this.sourcemap[key]; +}; + +exports.fromObject = function (obj) { + return new Converter(obj); +}; + +exports.fromJSON = function (json) { + return new Converter(json, { isJSON: true }); +}; + +exports.fromURI = function (uri) { + return new Converter(uri, { encoding: 'uri' }); +}; + +exports.fromBase64 = function (base64) { + return new Converter(base64, { encoding: 'base64' }); +}; + +exports.fromComment = function (comment) { + var m, encoding; + comment = comment + .replace(/^\/\*/g, '//') + .replace(/\*\/$/g, ''); + m = exports.commentRegex.exec(comment); + encoding = m && m[4] || 'uri'; + return new Converter(comment, { encoding: encoding, hasComment: true }); +}; + +function makeConverter(sm) { + return new Converter(sm, { isJSON: true }); +} + +exports.fromMapFileComment = function (comment, read) { + if (typeof read === 'string') { + throw new Error( + 'String directory paths are no longer supported with `fromMapFileComment`\n' + + 'Please review the Upgrading documentation at https://github.com/thlorenz/convert-source-map#upgrading' + ) + } + + var sm = readFromFileMap(comment, read); + if (sm != null && typeof sm.then === 'function') { + return sm.then(makeConverter); + } else { + return makeConverter(sm); + } +}; + +// Finds last sourcemap comment in file or returns null if none was found +exports.fromSource = function (content) { + var m = content.match(exports.commentRegex); + return m ? exports.fromComment(m.pop()) : null; +}; + +// Finds last sourcemap comment in file or returns null if none was found +exports.fromMapFileSource = function (content, read) { + if (typeof read === 'string') { + throw new Error( + 'String directory paths are no longer supported with `fromMapFileSource`\n' + + 'Please review the Upgrading documentation at https://github.com/thlorenz/convert-source-map#upgrading' + ) + } + var m = content.match(exports.mapFileCommentRegex); + return m ? exports.fromMapFileComment(m.pop(), read) : null; +}; + +exports.removeComments = function (src) { + return src.replace(exports.commentRegex, ''); +}; + +exports.removeMapFileComments = function (src) { + return src.replace(exports.mapFileCommentRegex, ''); +}; + +exports.generateMapFileComment = function (file, options) { + var data = 'sourceMappingURL=' + file; + return options && options.multiline ? '/*# ' + data + ' */' : '//# ' + data; +}; diff --git a/node_modules/convert-source-map/package.json b/node_modules/convert-source-map/package.json new file mode 100644 index 00000000..c38f29f7 --- /dev/null +++ b/node_modules/convert-source-map/package.json @@ -0,0 +1,38 @@ +{ + "name": "convert-source-map", + "version": "2.0.0", + "description": "Converts a source-map from/to different formats and allows adding/changing properties.", + "main": "index.js", + "scripts": { + "test": "tap test/*.js --color" + }, + "repository": { + "type": "git", + "url": "git://github.com/thlorenz/convert-source-map.git" + }, + "homepage": "https://github.com/thlorenz/convert-source-map", + "devDependencies": { + "inline-source-map": "~0.6.2", + "tap": "~9.0.0" + }, + "keywords": [ + "convert", + "sourcemap", + "source", + "map", + "browser", + "debug" + ], + "author": { + "name": "Thorsten Lorenz", + "email": "thlorenz@gmx.de", + "url": "http://thlorenz.com" + }, + "license": "MIT", + "engine": { + "node": ">=4" + }, + "files": [ + "index.js" + ] +} diff --git a/node_modules/css-tree/LICENSE b/node_modules/css-tree/LICENSE new file mode 100644 index 00000000..f4620933 --- /dev/null +++ b/node_modules/css-tree/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2016-2026 by Roman Dvornov + +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. diff --git a/node_modules/css-tree/README.md b/node_modules/css-tree/README.md new file mode 100644 index 00000000..92e6f15c --- /dev/null +++ b/node_modules/css-tree/README.md @@ -0,0 +1,192 @@ +CSSTree logo + +# CSSTree + +[![NPM version](https://img.shields.io/npm/v/css-tree.svg)](https://www.npmjs.com/package/css-tree) +[![Build Status](https://github.com/csstree/csstree/actions/workflows/build.yml/badge.svg)](https://github.com/csstree/csstree/actions/workflows/build.yml) +[![Coverage Status](https://coveralls.io/repos/github/csstree/csstree/badge.svg?branch=master)](https://coveralls.io/github/csstree/csstree?branch=master) +[![NPM Downloads](https://img.shields.io/npm/dm/css-tree.svg)](https://www.npmjs.com/package/css-tree) +[![Twitter](https://img.shields.io/badge/Twitter-@csstree-blue.svg)](https://twitter.com/csstree) + +CSSTree is a tool set for CSS: [fast](https://github.com/postcss/benchmark) detailed parser (CSS → AST), walker (AST traversal), generator (AST → CSS) and lexer (validation and matching) based on specs and browser implementations. The main goal is to be efficient and W3C spec compliant, with focus on CSS analyzing and source-to-source transforming tasks. + +## Features + +- **Detailed parsing with an adjustable level of detail** + + By default CSSTree parses CSS as detailed as possible, i.e. each single logical part is representing with its own AST node (see [AST format](docs/ast.md) for all possible node types). The parsing detail level can be changed through [parser options](docs/parsing.md#parsesource-options), for example, you can disable parsing of selectors or declaration values for component parts. + +- **Tolerant to errors by design** + + Parser behaves as [spec says](https://www.w3.org/TR/css-syntax-3/#error-handling): "When errors occur in CSS, the parser attempts to recover gracefully, throwing away only the minimum amount of content before returning to parsing as normal". The only thing the parser departs from the specification is that it doesn't throw away bad content, but wraps it in a special node type (`Raw`) that allows processing it later. + +- **Fast and efficient** + + CSSTree is created with focus on performance and effective memory consumption. Therefore it's [one of the fastest CSS parsers](https://github.com/postcss/benchmark) at the moment. + +- **Syntax validation** + + The built-in lexer can test CSS against syntaxes defined by W3C. CSSTree uses [mdn/data](https://github.com/mdn/data/) as a basis for lexer's dictionaries and extends it with vendor specific and legacy syntaxes. Lexer can only check the declaration values and at-rules currently, but this feature will be extended to other parts of the CSS in the future. + +## Projects using CSSTree + +- [Svelte](https://github.com/sveltejs/svelte) – Cybernetically enhanced web apps +- [SVGO](https://github.com/svg/svgo) – Node.js tool for optimizing SVG files +- [CSSO](https://github.com/css/csso) – CSS minifier with structural optimizations +- [NativeScript](https://github.com/NativeScript/NativeScript) – NativeScript empowers you to access native APIs from JavaScript directly +- [react-native-svg](https://github.com/react-native-svg/react-native-svg) – SVG library for React Native, React Native Web, and plain React web projects +- [penthouse](https://github.com/pocketjoso/penthouse) – Critical Path CSS Generator +- [Bit](https://github.com/teambit/bit) – Bit is the platform for collaborating on components +- and more... + +## Documentation + +- [AST format](docs/ast.md) +- [Parsing CSS → AST](docs/parsing.md) + - [parse(source[, options])](docs/parsing.md#parsesource-options) +- [Serialization AST → CSS](docs/generate.md) + - [generate(ast[, options])](docs/generate.md#generateast-options) +- [AST traversal](docs/traversal.md) + - [walk(ast, options)](docs/traversal.md#walkast-options) + - [find(ast, fn)](docs/traversal.md#findast-fn) + - [findLast(ast, fn)](docs/traversal.md#findlastast-fn) + - [findAll(ast, fn)](docs/traversal.md#findallast-fn) +- [Util functions](docs/utils.md) + - Value encoding & decoding + - [property(name)](docs/utils.md#propertyname) + - [keyword(name)](docs/utils.md#keywordname) + - [ident](docs/utils.md#ident) + - [string](docs/utils.md#string) + - [url](docs/utils.md#url) + - [List class](docs/list.md) + - AST transforming + - [clone(ast)](docs/utils.md#cloneast) + - [fromPlainObject(object)](docs/utils.md#fromplainobjectobject) + - [toPlainObject(ast)](docs/utils.md#toplainobjectast) +- [Value Definition Syntax](docs/definition-syntax.md) + - [parse(source)](docs/definition-syntax.md#parsesource) + - [walk(node, options, context)](docs/definition-syntax.md#walknode-options-context) + - [generate(node, options)](docs/definition-syntax.md#generatenode-options) + - [AST format](docs/definition-syntax.md#ast-format) + +## Tools + +* [AST Explorer](https://astexplorer.net/#/gist/244e2fb4da940df52bf0f4b94277db44/e79aff44611020b22cfd9708f3a99ce09b7d67a8) – explore CSSTree AST format with zero setup +* [CSS syntax reference](https://csstree.github.io/docs/syntax.html) +* [CSS syntax validator](https://csstree.github.io/docs/validator.html) + +## Related projects + +* [csstree-validator](https://github.com/csstree/validator) – NPM package to validate CSS +* [stylelint-csstree-validator](https://github.com/csstree/stylelint-validator) – plugin for stylelint to validate CSS +* [Grunt plugin](https://github.com/sergejmueller/grunt-csstree-validator) +* [Gulp plugin](https://github.com/csstree/gulp-csstree) +* [Sublime plugin](https://github.com/csstree/SublimeLinter-contrib-csstree) +* [VS Code plugin](https://github.com/csstree/vscode-plugin) +* [Atom plugin](https://github.com/csstree/atom-plugin) + +## Usage + +Install with npm: + +``` +npm install css-tree +``` + +Basic usage: + +```js +import * as csstree from 'css-tree'; + +// parse CSS to AST +const ast = csstree.parse('.example { world: "!" }'); + +// traverse AST and modify it +csstree.walk(ast, (node) => { + if (node.type === 'ClassSelector' && node.name === 'example') { + node.name = 'hello'; + } +}); + +// generate CSS from AST +console.log(csstree.generate(ast)); +// .hello{world:"!"} +``` + +Syntax matching: + +```js +// parse CSS to AST as a declaration value +const ast = csstree.parse('red 1px solid', { context: 'value' }); + +// match to syntax of `border` property +const matchResult = csstree.lexer.matchProperty('border', ast); + +// check first value node is a +console.log(matchResult.isType(ast.children.first, 'color')); +// true + +// get a type list matched to a node +console.log(matchResult.getTrace(ast.children.first)); +// [ { type: 'Property', name: 'border' }, +// { type: 'Type', name: 'color' }, +// { type: 'Type', name: 'named-color' }, +// { type: 'Keyword', name: 'red' } ] +``` + +### Exports + +Is it possible to import just a needed part of library like a parser or a walker. That's might useful for loading time or bundle size optimisations. + +```js +import * as tokenizer from 'css-tree/tokenizer'; +import * as parser from 'css-tree/parser'; +import * as walker from 'css-tree/walker'; +import * as lexer from 'css-tree/lexer'; +import * as definitionSyntax from 'css-tree/definition-syntax'; +import * as data from 'css-tree/definition-syntax-data'; +import * as dataPatch from 'css-tree/definition-syntax-data-patch'; +import * as utils from 'css-tree/utils'; +``` + +### Using in a browser + +Bundles are available for use in a browser: + +- `dist/csstree.js` – minified IIFE with `csstree` as global +```html + + +``` + +- `dist/csstree.esm.js` – minified ES module +```html + +``` + +One of CDN services like `unpkg` or `jsDelivr` can be used. By default (for short path) a ESM version is exposing. For IIFE version a full path to a bundle should be specified: + +```html + + + + + + +``` + +## Top level API + +![API map](https://cdn.rawgit.com/csstree/csstree/aaf327e/docs/api-map.svg) + +## License + +MIT diff --git a/node_modules/css-tree/cjs/convertor/create.cjs b/node_modules/css-tree/cjs/convertor/create.cjs new file mode 100644 index 00000000..55c655b2 --- /dev/null +++ b/node_modules/css-tree/cjs/convertor/create.cjs @@ -0,0 +1,32 @@ +'use strict'; + +const List = require('../utils/List.cjs'); + +function createConvertor(walk) { + return { + fromPlainObject(ast) { + walk(ast, { + enter(node) { + if (node.children && node.children instanceof List.List === false) { + node.children = new List.List().fromArray(node.children); + } + } + }); + + return ast; + }, + toPlainObject(ast) { + walk(ast, { + leave(node) { + if (node.children && node.children instanceof List.List) { + node.children = node.children.toArray(); + } + } + }); + + return ast; + } + }; +} + +exports.createConvertor = createConvertor; diff --git a/node_modules/css-tree/cjs/convertor/index.cjs b/node_modules/css-tree/cjs/convertor/index.cjs new file mode 100644 index 00000000..66542785 --- /dev/null +++ b/node_modules/css-tree/cjs/convertor/index.cjs @@ -0,0 +1,8 @@ +'use strict'; + +const create = require('./create.cjs'); +const index$1 = require('../walker/index.cjs'); + +const index = create.createConvertor(index$1); + +module.exports = index; diff --git a/node_modules/css-tree/cjs/data-patch.cjs b/node_modules/css-tree/cjs/data-patch.cjs new file mode 100644 index 00000000..9103ea4c --- /dev/null +++ b/node_modules/css-tree/cjs/data-patch.cjs @@ -0,0 +1,7 @@ +'use strict'; + +const patch = require('../data/patch.json'); + +const patch$1 = patch; + +module.exports = patch$1; diff --git a/node_modules/css-tree/cjs/data.cjs b/node_modules/css-tree/cjs/data.cjs new file mode 100644 index 00000000..258ac6a3 --- /dev/null +++ b/node_modules/css-tree/cjs/data.cjs @@ -0,0 +1,120 @@ +'use strict'; + +const dataPatch = require('./data-patch.cjs'); + +const mdnAtrules = require('mdn-data/css/at-rules.json'); +const mdnProperties = require('mdn-data/css/properties.json'); +const mdnSyntaxes = require('mdn-data/css/syntaxes.json'); + +const hasOwn = Object.hasOwn || ((object, property) => Object.prototype.hasOwnProperty.call(object, property)); +const extendSyntax = /^\s*\|\s*/; + +function preprocessAtrules(dict) { + const result = Object.create(null); + + for (const [atruleName, atrule] of Object.entries(dict)) { + let descriptors = null; + + if (atrule.descriptors) { + descriptors = Object.create(null); + + for (const [name, descriptor] of Object.entries(atrule.descriptors)) { + descriptors[name] = descriptor.syntax; + } + } + + result[atruleName.substr(1)] = { + prelude: atrule.syntax.trim().replace(/\{(.|\s)+\}/, '').match(/^@\S+\s+([^;\{]*)/)[1].trim() || null, + descriptors + }; + } + + return result; +} + +function patchDictionary(dict, patchDict) { + const result = Object.create(null); + + // copy all syntaxes for an original dict + for (const [key, value] of Object.entries(dict)) { + if (value) { + result[key] = value.syntax || value; + } + } + + // apply a patch + for (const key of Object.keys(patchDict)) { + if (hasOwn(dict, key)) { + if (patchDict[key].syntax) { + result[key] = extendSyntax.test(patchDict[key].syntax) + ? result[key] + ' ' + patchDict[key].syntax.trim() + : patchDict[key].syntax; + } else { + delete result[key]; + } + } else { + if (patchDict[key].syntax) { + result[key] = patchDict[key].syntax.replace(extendSyntax, ''); + } + } + } + + return result; +} + +function preprocessPatchAtrulesDescritors(declarations) { + const result = {}; + + for (const [key, value] of Object.entries(declarations || {})) { + result[key] = typeof value === 'string' + ? { syntax: value } + : value; + } + + return result; +} + +function patchAtrules(dict, patchDict) { + const result = {}; + + // copy all syntaxes for an original dict + for (const key in dict) { + if (patchDict[key] === null) { + continue; + } + + const atrulePatch = patchDict[key] || {}; + + result[key] = { + prelude: key in patchDict && 'prelude' in atrulePatch + ? atrulePatch.prelude + : dict[key].prelude || null, + descriptors: patchDictionary( + dict[key].descriptors || {}, + preprocessPatchAtrulesDescritors(atrulePatch.descriptors) + ) + }; + } + + // apply a patch + for (const [key, atrulePatch] of Object.entries(patchDict)) { + if (atrulePatch && !hasOwn(dict, key)) { + result[key] = { + prelude: atrulePatch.prelude || null, + descriptors: atrulePatch.descriptors + ? patchDictionary({}, preprocessPatchAtrulesDescritors(atrulePatch.descriptors)) + : null + }; + } + } + + return result; +} + +const definitions = { + types: patchDictionary(mdnSyntaxes, dataPatch.types), + atrules: patchAtrules(preprocessAtrules(mdnAtrules), dataPatch.atrules), + properties: patchDictionary(mdnProperties, dataPatch.properties) +}; + +module.exports = definitions; diff --git a/node_modules/css-tree/cjs/definition-syntax/SyntaxError.cjs b/node_modules/css-tree/cjs/definition-syntax/SyntaxError.cjs new file mode 100644 index 00000000..d24e7ced --- /dev/null +++ b/node_modules/css-tree/cjs/definition-syntax/SyntaxError.cjs @@ -0,0 +1,16 @@ +'use strict'; + +const createCustomError = require('../utils/create-custom-error.cjs'); + +function SyntaxError(message, input, offset) { + return Object.assign(createCustomError.createCustomError('SyntaxError', message), { + input, + offset, + rawMessage: message, + message: message + '\n' + + ' ' + input + '\n' + + '--' + new Array((offset || input.length) + 1).join('-') + '^' + }); +} + +exports.SyntaxError = SyntaxError; diff --git a/node_modules/css-tree/cjs/definition-syntax/generate.cjs b/node_modules/css-tree/cjs/definition-syntax/generate.cjs new file mode 100644 index 00000000..ff9f0ad4 --- /dev/null +++ b/node_modules/css-tree/cjs/definition-syntax/generate.cjs @@ -0,0 +1,139 @@ +'use strict'; + +function noop(value) { + return value; +} + +function generateMultiplier(multiplier) { + const { min, max, comma } = multiplier; + + if (min === 0 && max === 0) { + return comma ? '#?' : '*'; + } + + if (min === 0 && max === 1) { + return '?'; + } + + if (min === 1 && max === 0) { + return comma ? '#' : '+'; + } + + if (min === 1 && max === 1) { + return ''; + } + + return ( + (comma ? '#' : '') + + (min === max + ? '{' + min + '}' + : '{' + min + ',' + (max !== 0 ? max : '') + '}' + ) + ); +} + +function generateTypeOpts(node) { + switch (node.type) { + case 'Range': + return ( + ' [' + + (node.min === null ? '-∞' : node.min) + + ',' + + (node.max === null ? '∞' : node.max) + + ']' + ); + + default: + throw new Error('Unknown node type `' + node.type + '`'); + } +} + +function generateSequence(node, decorate, forceBraces, compact) { + const combinator = node.combinator === ' ' || compact ? node.combinator : ' ' + node.combinator + ' '; + const result = node.terms + .map(term => internalGenerate(term, decorate, forceBraces, compact)) + .join(combinator); + + if (node.explicit || forceBraces) { + return (compact || result[0] === ',' ? '[' : '[ ') + result + (compact ? ']' : ' ]'); + } + + return result; +} + +function internalGenerate(node, decorate, forceBraces, compact) { + let result; + + switch (node.type) { + case 'Group': + result = + generateSequence(node, decorate, forceBraces, compact) + + (node.disallowEmpty ? '!' : ''); + break; + + case 'Multiplier': + // return since node is a composition + return ( + internalGenerate(node.term, decorate, forceBraces, compact) + + decorate(generateMultiplier(node), node) + ); + + case 'Boolean': + result = ''; + break; + + case 'Type': + result = '<' + node.name + (node.opts ? decorate(generateTypeOpts(node.opts), node.opts) : '') + '>'; + break; + + case 'Property': + result = '<\'' + node.name + '\'>'; + break; + + case 'Keyword': + result = node.name; + break; + + case 'AtKeyword': + result = '@' + node.name; + break; + + case 'Function': + result = node.name + '('; + break; + + case 'String': + case 'Token': + result = node.value; + break; + + case 'Comma': + result = ','; + break; + + default: + throw new Error('Unknown node type `' + node.type + '`'); + } + + return decorate(result, node); +} + +function generate(node, options) { + let decorate = noop; + let forceBraces = false; + let compact = false; + + if (typeof options === 'function') { + decorate = options; + } else if (options) { + forceBraces = Boolean(options.forceBraces); + compact = Boolean(options.compact); + if (typeof options.decorate === 'function') { + decorate = options.decorate; + } + } + + return internalGenerate(node, decorate, forceBraces, compact); +} + +exports.generate = generate; diff --git a/node_modules/css-tree/cjs/definition-syntax/index.cjs b/node_modules/css-tree/cjs/definition-syntax/index.cjs new file mode 100644 index 00000000..0afb505c --- /dev/null +++ b/node_modules/css-tree/cjs/definition-syntax/index.cjs @@ -0,0 +1,13 @@ +'use strict'; + +const SyntaxError = require('./SyntaxError.cjs'); +const generate = require('./generate.cjs'); +const parse = require('./parse.cjs'); +const walk = require('./walk.cjs'); + + + +exports.SyntaxError = SyntaxError.SyntaxError; +exports.generate = generate.generate; +exports.parse = parse.parse; +exports.walk = walk.walk; diff --git a/node_modules/css-tree/cjs/definition-syntax/parse.cjs b/node_modules/css-tree/cjs/definition-syntax/parse.cjs new file mode 100644 index 00000000..c978eb15 --- /dev/null +++ b/node_modules/css-tree/cjs/definition-syntax/parse.cjs @@ -0,0 +1,596 @@ +'use strict'; + +const scanner = require('./scanner.cjs'); + +const TAB = 9; +const N = 10; +const F = 12; +const R = 13; +const SPACE = 32; +const EXCLAMATIONMARK = 33; // ! +const NUMBERSIGN = 35; // # +const AMPERSAND = 38; // & +const APOSTROPHE = 39; // ' +const LEFTPARENTHESIS = 40; // ( +const RIGHTPARENTHESIS = 41; // ) +const ASTERISK = 42; // * +const PLUSSIGN = 43; // + +const COMMA = 44; // , +const HYPERMINUS = 45; // - +const LESSTHANSIGN = 60; // < +const GREATERTHANSIGN = 62; // > +const QUESTIONMARK = 63; // ? +const COMMERCIALAT = 64; // @ +const LEFTSQUAREBRACKET = 91; // [ +const RIGHTSQUAREBRACKET = 93; // ] +const LEFTCURLYBRACKET = 123; // { +const VERTICALLINE = 124; // | +const RIGHTCURLYBRACKET = 125; // } +const INFINITY = 8734; // ∞ +const COMBINATOR_PRECEDENCE = { + ' ': 1, + '&&': 2, + '||': 3, + '|': 4 +}; + +function readMultiplierRange(scanner) { + let min = null; + let max = null; + + scanner.eat(LEFTCURLYBRACKET); + scanner.skipWs(); + + min = scanner.scanNumber(scanner); + scanner.skipWs(); + + if (scanner.charCode() === COMMA) { + scanner.pos++; + scanner.skipWs(); + + if (scanner.charCode() !== RIGHTCURLYBRACKET) { + max = scanner.scanNumber(scanner); + scanner.skipWs(); + } + } else { + max = min; + } + + scanner.eat(RIGHTCURLYBRACKET); + + return { + min: Number(min), + max: max ? Number(max) : 0 + }; +} + +function readMultiplier(scanner) { + let range = null; + let comma = false; + + switch (scanner.charCode()) { + case ASTERISK: + scanner.pos++; + + range = { + min: 0, + max: 0 + }; + + break; + + case PLUSSIGN: + scanner.pos++; + + range = { + min: 1, + max: 0 + }; + + break; + + case QUESTIONMARK: + scanner.pos++; + + range = { + min: 0, + max: 1 + }; + + break; + + case NUMBERSIGN: + scanner.pos++; + + comma = true; + + if (scanner.charCode() === LEFTCURLYBRACKET) { + range = readMultiplierRange(scanner); + } else if (scanner.charCode() === QUESTIONMARK) { + // https://www.w3.org/TR/css-values-4/#component-multipliers + // > the # and ? multipliers may be stacked as #? + // In this case just treat "#?" as a single multiplier + // { min: 0, max: 0, comma: true } + scanner.pos++; + range = { + min: 0, + max: 0 + }; + } else { + range = { + min: 1, + max: 0 + }; + } + + break; + + case LEFTCURLYBRACKET: + range = readMultiplierRange(scanner); + break; + + default: + return null; + } + + return { + type: 'Multiplier', + comma, + min: range.min, + max: range.max, + term: null + }; +} + +function maybeMultiplied(scanner, node) { + const multiplier = readMultiplier(scanner); + + if (multiplier !== null) { + multiplier.term = node; + + // https://www.w3.org/TR/css-values-4/#component-multipliers + // > The + and # multipliers may be stacked as +#; + // Represent "+#" as nested multipliers: + // { ..., + // term: { + // ..., + // term: node + // } + // } + if (scanner.charCode() === NUMBERSIGN && + scanner.charCodeAt(scanner.pos - 1) === PLUSSIGN) { + return maybeMultiplied(scanner, multiplier); + } + + // https://www.w3.org/TR/css-values-4/#component-multipliers + // > the # and ? multipliers, {A} and ? multipliers, and {A,B} and ? multipliers + // > may be stacked as #?, {A}?, and {A,B}?, respectively + // Represent "{}?" as nested multipliers as well as "+#". + // The "#?" case is already handled above, in maybeMultiplied() + if (scanner.charCode() === QUESTIONMARK && + scanner.charCodeAt(scanner.pos - 1) === RIGHTCURLYBRACKET) { + return maybeMultiplied(scanner, multiplier); + } + + return multiplier; + } + + return node; +} + +function maybeToken(scanner) { + const ch = scanner.peek(); + + if (ch === '') { + return null; + } + + return maybeMultiplied(scanner, { + type: 'Token', + value: ch + }); +} + +function readProperty(scanner) { + let name; + + scanner.eat(LESSTHANSIGN); + scanner.eat(APOSTROPHE); + + name = scanner.scanWord(); + + scanner.eat(APOSTROPHE); + scanner.eat(GREATERTHANSIGN); + + return maybeMultiplied(scanner, { + type: 'Property', + name + }); +} + +// https://drafts.csswg.org/css-values-3/#numeric-ranges +// 4.1. Range Restrictions and Range Definition Notation +// +// Range restrictions can be annotated in the numeric type notation using CSS bracketed +// range notation—[min,max]—within the angle brackets, after the identifying keyword, +// indicating a closed range between (and including) min and max. +// For example, indicates an integer between 0 and 10, inclusive. +function readTypeRange(scanner) { + // use null for Infinity to make AST format JSON serializable/deserializable + let min = null; // -Infinity + let max = null; // Infinity + let sign = 1; + + scanner.eat(LEFTSQUAREBRACKET); + + if (scanner.charCode() === HYPERMINUS) { + scanner.peek(); + sign = -1; + } + + if (sign == -1 && scanner.charCode() === INFINITY) { + scanner.peek(); + } else { + min = sign * Number(scanner.scanNumber(scanner)); + + if (scanner.isNameCharCode()) { + min += scanner.scanWord(); + } + } + + scanner.skipWs(); + scanner.eat(COMMA); + scanner.skipWs(); + + if (scanner.charCode() === INFINITY) { + scanner.peek(); + } else { + sign = 1; + + if (scanner.charCode() === HYPERMINUS) { + scanner.peek(); + sign = -1; + } + + max = sign * Number(scanner.scanNumber(scanner)); + + if (scanner.isNameCharCode()) { + max += scanner.scanWord(); + } + } + + scanner.eat(RIGHTSQUAREBRACKET); + + return { + type: 'Range', + min, + max + }; +} + +function readType(scanner) { + let name; + let opts = null; + + scanner.eat(LESSTHANSIGN); + name = scanner.scanWord(); + + // https://drafts.csswg.org/css-values-5/#boolean + if (name === 'boolean-expr') { + scanner.eat(LEFTSQUAREBRACKET); + + const implicitGroup = readImplicitGroup(scanner, RIGHTSQUAREBRACKET); + + scanner.eat(RIGHTSQUAREBRACKET); + scanner.eat(GREATERTHANSIGN); + + return maybeMultiplied(scanner, { + type: 'Boolean', + term: implicitGroup.terms.length === 1 + ? implicitGroup.terms[0] + : implicitGroup + }); + } + + if (scanner.charCode() === LEFTPARENTHESIS && + scanner.nextCharCode() === RIGHTPARENTHESIS) { + scanner.pos += 2; + name += '()'; + } + + if (scanner.charCodeAt(scanner.findWsEnd(scanner.pos)) === LEFTSQUAREBRACKET) { + scanner.skipWs(); + opts = readTypeRange(scanner); + } + + scanner.eat(GREATERTHANSIGN); + + return maybeMultiplied(scanner, { + type: 'Type', + name, + opts + }); +} + +function readKeywordOrFunction(scanner) { + const name = scanner.scanWord(); + + if (scanner.charCode() === LEFTPARENTHESIS) { + scanner.pos++; + + return { + type: 'Function', + name + }; + } + + return maybeMultiplied(scanner, { + type: 'Keyword', + name + }); +} + +function regroupTerms(terms, combinators) { + function createGroup(terms, combinator) { + return { + type: 'Group', + terms, + combinator, + disallowEmpty: false, + explicit: false + }; + } + + let combinator; + + combinators = Object.keys(combinators) + .sort((a, b) => COMBINATOR_PRECEDENCE[a] - COMBINATOR_PRECEDENCE[b]); + + while (combinators.length > 0) { + combinator = combinators.shift(); + + let i = 0; + let subgroupStart = 0; + + for (; i < terms.length; i++) { + const term = terms[i]; + + if (term.type === 'Combinator') { + if (term.value === combinator) { + if (subgroupStart === -1) { + subgroupStart = i - 1; + } + terms.splice(i, 1); + i--; + } else { + if (subgroupStart !== -1 && i - subgroupStart > 1) { + terms.splice( + subgroupStart, + i - subgroupStart, + createGroup(terms.slice(subgroupStart, i), combinator) + ); + i = subgroupStart + 1; + } + subgroupStart = -1; + } + } + } + + if (subgroupStart !== -1 && combinators.length) { + terms.splice( + subgroupStart, + i - subgroupStart, + createGroup(terms.slice(subgroupStart, i), combinator) + ); + } + } + + return combinator; +} + +function readImplicitGroup(scanner, stopCharCode = -1) { + const combinators = Object.create(null); + const terms = []; + let prevToken = null; + let prevTokenPos = scanner.pos; + let prevTokenIsFunction = false; + + while (scanner.charCode() !== stopCharCode) { + let token = prevTokenIsFunction + ? readImplicitGroup(scanner, RIGHTPARENTHESIS) + : peek(scanner); + + if (!token) { + break; + } + + if (token.type === 'Spaces') { + continue; + } + + if (prevTokenIsFunction) { + if (token.terms.length === 0) { + prevTokenIsFunction = false; + continue; + } + + if (token.combinator === ' ') { + while (token.terms.length > 1) { + combinators[' '] = true; // a b + terms.push({ + type: 'Combinator', + value: ' ' + }, token.terms.shift()); + } + + token = token.terms[0]; + } + } + + if (token.type === 'Combinator') { + // check for combinator in group beginning and double combinator sequence + if (prevToken === null || prevToken.type === 'Combinator') { + scanner.pos = prevTokenPos; + scanner.error('Unexpected combinator'); + } + + combinators[token.value] = true; + } else if (prevToken !== null && prevToken.type !== 'Combinator') { + combinators[' '] = true; // a b + terms.push({ + type: 'Combinator', + value: ' ' + }); + } + + terms.push(token); + prevToken = token; + prevTokenPos = scanner.pos; + prevTokenIsFunction = token.type === 'Function'; + } + + // check for combinator in group ending + if (prevToken !== null && prevToken.type === 'Combinator') { + scanner.pos -= prevTokenPos; + scanner.error('Unexpected combinator'); + } + + return { + type: 'Group', + terms, + combinator: regroupTerms(terms, combinators) || ' ', + disallowEmpty: false, + explicit: false + }; +} + +function readGroup(scanner) { + let result; + + scanner.eat(LEFTSQUAREBRACKET); + result = readImplicitGroup(scanner, RIGHTSQUAREBRACKET); + scanner.eat(RIGHTSQUAREBRACKET); + + result.explicit = true; + + if (scanner.charCode() === EXCLAMATIONMARK) { + scanner.pos++; + result.disallowEmpty = true; + } + + return result; +} + +function peek(scanner) { + let code = scanner.charCode(); + + switch (code) { + case RIGHTSQUAREBRACKET: + // don't eat, stop scan a group + break; + + case LEFTSQUAREBRACKET: + return maybeMultiplied(scanner, readGroup(scanner)); + + case LESSTHANSIGN: + return scanner.nextCharCode() === APOSTROPHE + ? readProperty(scanner) + : readType(scanner); + + case VERTICALLINE: + return { + type: 'Combinator', + value: scanner.substringToPos( + scanner.pos + (scanner.nextCharCode() === VERTICALLINE ? 2 : 1) + ) + }; + + case AMPERSAND: + scanner.pos++; + scanner.eat(AMPERSAND); + + return { + type: 'Combinator', + value: '&&' + }; + + case COMMA: + scanner.pos++; + return { + type: 'Comma' + }; + + case APOSTROPHE: + return maybeMultiplied(scanner, { + type: 'String', + value: scanner.scanString() + }); + + case SPACE: + case TAB: + case N: + case R: + case F: + return { + type: 'Spaces', + value: scanner.scanSpaces() + }; + + case COMMERCIALAT: + code = scanner.nextCharCode(); + + if (scanner.isNameCharCode(code)) { + scanner.pos++; + return { + type: 'AtKeyword', + name: scanner.scanWord() + }; + } + + return maybeToken(scanner); + + case ASTERISK: + case PLUSSIGN: + case QUESTIONMARK: + case NUMBERSIGN: + case EXCLAMATIONMARK: + // prohibited tokens (used as a multiplier start) + break; + + case LEFTCURLYBRACKET: + // LEFTCURLYBRACKET is allowed since mdn/data uses it w/o quoting + // check next char isn't a number, because it's likely a disjoined multiplier + code = scanner.nextCharCode(); + + if (code < 48 || code > 57) { + return maybeToken(scanner); + } + + break; + + default: + if (scanner.isNameCharCode(code)) { + return readKeywordOrFunction(scanner); + } + + return maybeToken(scanner); + } +} + +function parse(source) { + const scanner$1 = new scanner.Scanner(source); + const result = readImplicitGroup(scanner$1); + + if (scanner$1.pos !== source.length) { + scanner$1.error('Unexpected input'); + } + + // reduce redundant groups with single group term + if (result.terms.length === 1 && result.terms[0].type === 'Group') { + return result.terms[0]; + } + + return result; +} + +exports.parse = parse; diff --git a/node_modules/css-tree/cjs/definition-syntax/scanner.cjs b/node_modules/css-tree/cjs/definition-syntax/scanner.cjs new file mode 100644 index 00000000..0bad36a4 --- /dev/null +++ b/node_modules/css-tree/cjs/definition-syntax/scanner.cjs @@ -0,0 +1,113 @@ +'use strict'; + +const SyntaxError = require('./SyntaxError.cjs'); + +const TAB = 9; +const N = 10; +const F = 12; +const R = 13; +const SPACE = 32; +const NAME_CHAR = new Uint8Array(128).map((_, idx) => + /[a-zA-Z0-9\-]/.test(String.fromCharCode(idx)) ? 1 : 0 +); + +class Scanner { + constructor(str) { + this.str = str; + this.pos = 0; + } + + charCodeAt(pos) { + return pos < this.str.length ? this.str.charCodeAt(pos) : 0; + } + charCode() { + return this.charCodeAt(this.pos); + } + isNameCharCode(code = this.charCode()) { + return code < 128 && NAME_CHAR[code] === 1; + } + nextCharCode() { + return this.charCodeAt(this.pos + 1); + } + nextNonWsCode(pos) { + return this.charCodeAt(this.findWsEnd(pos)); + } + skipWs() { + this.pos = this.findWsEnd(this.pos); + } + findWsEnd(pos) { + for (; pos < this.str.length; pos++) { + const code = this.str.charCodeAt(pos); + if (code !== R && code !== N && code !== F && code !== SPACE && code !== TAB) { + break; + } + } + + return pos; + } + substringToPos(end) { + return this.str.substring(this.pos, this.pos = end); + } + eat(code) { + if (this.charCode() !== code) { + this.error('Expect `' + String.fromCharCode(code) + '`'); + } + + this.pos++; + } + peek() { + return this.pos < this.str.length ? this.str.charAt(this.pos++) : ''; + } + error(message) { + throw new SyntaxError.SyntaxError(message, this.str, this.pos); + } + + scanSpaces() { + return this.substringToPos(this.findWsEnd(this.pos)); + } + scanWord() { + let end = this.pos; + + for (; end < this.str.length; end++) { + const code = this.str.charCodeAt(end); + if (code >= 128 || NAME_CHAR[code] === 0) { + break; + } + } + + if (this.pos === end) { + this.error('Expect a keyword'); + } + + return this.substringToPos(end); + } + scanNumber() { + let end = this.pos; + + for (; end < this.str.length; end++) { + const code = this.str.charCodeAt(end); + + if (code < 48 || code > 57) { + break; + } + } + + if (this.pos === end) { + this.error('Expect a number'); + } + + return this.substringToPos(end); + } + scanString() { + const end = this.str.indexOf('\'', this.pos + 1); + + if (end === -1) { + this.pos = this.str.length; + this.error('Expect an apostrophe'); + } + + return this.substringToPos(end + 1); + } +} + +exports.Scanner = Scanner; diff --git a/node_modules/css-tree/cjs/definition-syntax/walk.cjs b/node_modules/css-tree/cjs/definition-syntax/walk.cjs new file mode 100644 index 00000000..fdba0657 --- /dev/null +++ b/node_modules/css-tree/cjs/definition-syntax/walk.cjs @@ -0,0 +1,57 @@ +'use strict'; + +const noop = function() {}; + +function ensureFunction(value) { + return typeof value === 'function' ? value : noop; +} + +function walk(node, options, context) { + function walk(node) { + enter.call(context, node); + + switch (node.type) { + case 'Group': + node.terms.forEach(walk); + break; + + case 'Multiplier': + case 'Boolean': + walk(node.term); + break; + + case 'Type': + case 'Property': + case 'Keyword': + case 'AtKeyword': + case 'Function': + case 'String': + case 'Token': + case 'Comma': + break; + + default: + throw new Error('Unknown type: ' + node.type); + } + + leave.call(context, node); + } + + let enter = noop; + let leave = noop; + + if (typeof options === 'function') { + enter = options; + } else if (options) { + enter = ensureFunction(options.enter); + leave = ensureFunction(options.leave); + } + + if (enter === noop && leave === noop) { + throw new Error('Neither `enter` nor `leave` walker handler is set or both aren\'t a function'); + } + + walk(node); +} + +exports.walk = walk; diff --git a/node_modules/css-tree/cjs/generator/create.cjs b/node_modules/css-tree/cjs/generator/create.cjs new file mode 100644 index 00000000..147ca553 --- /dev/null +++ b/node_modules/css-tree/cjs/generator/create.cjs @@ -0,0 +1,107 @@ +'use strict'; + +const index = require('../tokenizer/index.cjs'); +const sourceMap = require('./sourceMap.cjs'); +const tokenBefore = require('./token-before.cjs'); +const types = require('../tokenizer/types.cjs'); + +const REVERSESOLIDUS = 0x005c; // U+005C REVERSE SOLIDUS (\) + +function processChildren(node, delimeter) { + if (typeof delimeter === 'function') { + let prev = null; + + node.children.forEach(node => { + if (prev !== null) { + delimeter.call(this, prev); + } + + this.node(node); + prev = node; + }); + + return; + } + + node.children.forEach(this.node, this); +} + +function createGenerator(config) { + const types$1 = new Map(); + + for (let [name, item] of Object.entries(config.node)) { + const fn = item.generate || item; + + if (typeof fn === 'function') { + types$1.set(name, item.generate || item); + } + } + + return function(node, options) { + let buffer = ''; + let prevCode = 0; + let handlers = { + node(node) { + if (types$1.has(node.type)) { + types$1.get(node.type).call(publicApi, node); + } else { + throw new Error('Unknown node type: ' + node.type); + } + }, + tokenBefore: tokenBefore.safe, + token(type, value, suppressAutoWhiteSpace) { + prevCode = this.tokenBefore(prevCode, type, value); + + if (!suppressAutoWhiteSpace && prevCode & 1) { + this.emit(' ', types.WhiteSpace, true); + } + + this.emit(value, type, false); + + if (type === types.Delim && value.charCodeAt(0) === REVERSESOLIDUS) { + this.emit('\n', types.WhiteSpace, true); + } + }, + emit(value) { + buffer += value; + }, + result() { + return buffer; + } + }; + + if (options) { + if (typeof options.decorator === 'function') { + handlers = options.decorator(handlers); + } + + if (options.sourceMap) { + handlers = sourceMap.generateSourceMap(handlers); + } + + if (options.mode in tokenBefore) { + handlers.tokenBefore = tokenBefore[options.mode]; + } + } + + const publicApi = { + node: (node) => handlers.node(node), + children: processChildren, + token: (type, value) => handlers.token(type, value), + tokenize: (raw) => + index.tokenize(raw, (type, start, end) => { + handlers.token( + type, + raw.slice(start, end), + start !== 0 // suppress auto whitespace for internal value tokens + ); + }) + }; + + handlers.node(node); + + return handlers.result(); + }; +} + +exports.createGenerator = createGenerator; diff --git a/node_modules/css-tree/cjs/generator/index.cjs b/node_modules/css-tree/cjs/generator/index.cjs new file mode 100644 index 00000000..5c87cd34 --- /dev/null +++ b/node_modules/css-tree/cjs/generator/index.cjs @@ -0,0 +1,8 @@ +'use strict'; + +const create = require('./create.cjs'); +const generator = require('../syntax/config/generator.cjs'); + +const index = create.createGenerator(generator); + +module.exports = index; diff --git a/node_modules/css-tree/cjs/generator/sourceMap.cjs b/node_modules/css-tree/cjs/generator/sourceMap.cjs new file mode 100644 index 00000000..efbc5b9e --- /dev/null +++ b/node_modules/css-tree/cjs/generator/sourceMap.cjs @@ -0,0 +1,96 @@ +'use strict'; + +const sourceMapGenerator_js = require('source-map-js/lib/source-map-generator.js'); + +const trackNodes = new Set(['Atrule', 'Selector', 'Declaration']); + +function generateSourceMap(handlers) { + const map = new sourceMapGenerator_js.SourceMapGenerator(); + const generated = { + line: 1, + column: 0 + }; + const original = { + line: 0, // should be zero to add first mapping + column: 0 + }; + const activatedGenerated = { + line: 1, + column: 0 + }; + const activatedMapping = { + generated: activatedGenerated + }; + let line = 1; + let column = 0; + let sourceMappingActive = false; + + const origHandlersNode = handlers.node; + handlers.node = function(node) { + if (node.loc && node.loc.start && trackNodes.has(node.type)) { + const nodeLine = node.loc.start.line; + const nodeColumn = node.loc.start.column - 1; + + if (original.line !== nodeLine || + original.column !== nodeColumn) { + original.line = nodeLine; + original.column = nodeColumn; + + generated.line = line; + generated.column = column; + + if (sourceMappingActive) { + sourceMappingActive = false; + if (generated.line !== activatedGenerated.line || + generated.column !== activatedGenerated.column) { + map.addMapping(activatedMapping); + } + } + + sourceMappingActive = true; + map.addMapping({ + source: node.loc.source, + original, + generated + }); + } + } + + origHandlersNode.call(this, node); + + if (sourceMappingActive && trackNodes.has(node.type)) { + activatedGenerated.line = line; + activatedGenerated.column = column; + } + }; + + const origHandlersEmit = handlers.emit; + handlers.emit = function(value, type, auto) { + for (let i = 0; i < value.length; i++) { + if (value.charCodeAt(i) === 10) { // \n + line++; + column = 0; + } else { + column++; + } + } + + origHandlersEmit(value, type, auto); + }; + + const origHandlersResult = handlers.result; + handlers.result = function() { + if (sourceMappingActive) { + map.addMapping(activatedMapping); + } + + return { + css: origHandlersResult(), + map + }; + }; + + return handlers; +} + +exports.generateSourceMap = generateSourceMap; diff --git a/node_modules/css-tree/cjs/generator/token-before.cjs b/node_modules/css-tree/cjs/generator/token-before.cjs new file mode 100644 index 00000000..65739a7e --- /dev/null +++ b/node_modules/css-tree/cjs/generator/token-before.cjs @@ -0,0 +1,169 @@ +'use strict'; + +const types = require('../tokenizer/types.cjs'); + +const PLUSSIGN = 0x002B; // U+002B PLUS SIGN (+) +const HYPHENMINUS = 0x002D; // U+002D HYPHEN-MINUS (-) + +// code: +// 0xxxxxxx x0000000 - char code (0x80 for non-ASCII) or delim value +// 00000000 0xxxxxx0 - token type (0 for delim, 1 for token) +// 00000000 0000000x - reserved for carriage emit flag (0 for no space, 1 for space) +const code = (type, value) => { + if (type === types.Delim) { + type = value; + } + + if (typeof type === 'string') { + type = Math.min(type.charCodeAt(0), 0x80) << 6; // replace non-ASCII with 0x80 + } + + return type << 1; +}; + +// https://www.w3.org/TR/css-syntax-3/#serialization +// The only requirement for serialization is that it must "round-trip" with parsing, +// that is, parsing the stylesheet must produce the same data structures as parsing, +// serializing, and parsing again, except for consecutive s, +// which may be collapsed into a single token. + +const specPairs = [ + [types.Ident, types.Ident], + [types.Ident, types.Function], + [types.Ident, types.Url], + [types.Ident, types.BadUrl], + [types.Ident, '-'], + [types.Ident, types.Number], + [types.Ident, types.Percentage], + [types.Ident, types.Dimension], + [types.Ident, types.CDC], + [types.Ident, types.LeftParenthesis], + + [types.AtKeyword, types.Ident], + [types.AtKeyword, types.Function], + [types.AtKeyword, types.Url], + [types.AtKeyword, types.BadUrl], + [types.AtKeyword, '-'], + [types.AtKeyword, types.Number], + [types.AtKeyword, types.Percentage], + [types.AtKeyword, types.Dimension], + [types.AtKeyword, types.CDC], + + [types.Hash, types.Ident], + [types.Hash, types.Function], + [types.Hash, types.Url], + [types.Hash, types.BadUrl], + [types.Hash, '-'], + [types.Hash, types.Number], + [types.Hash, types.Percentage], + [types.Hash, types.Dimension], + [types.Hash, types.CDC], + + [types.Dimension, types.Ident], + [types.Dimension, types.Function], + [types.Dimension, types.Url], + [types.Dimension, types.BadUrl], + [types.Dimension, '-'], + [types.Dimension, types.Number], + [types.Dimension, types.Percentage], + [types.Dimension, types.Dimension], + [types.Dimension, types.CDC], + + ['#', types.Ident], + ['#', types.Function], + ['#', types.Url], + ['#', types.BadUrl], + ['#', '-'], + ['#', types.Number], + ['#', types.Percentage], + ['#', types.Dimension], + ['#', types.CDC], // https://github.com/w3c/csswg-drafts/pull/6874 + + ['-', types.Ident], + ['-', types.Function], + ['-', types.Url], + ['-', types.BadUrl], + ['-', '-'], + ['-', types.Number], + ['-', types.Percentage], + ['-', types.Dimension], + ['-', types.CDC], // https://github.com/w3c/csswg-drafts/pull/6874 + + [types.Number, types.Ident], + [types.Number, types.Function], + [types.Number, types.Url], + [types.Number, types.BadUrl], + [types.Number, types.Number], + [types.Number, types.Percentage], + [types.Number, types.Dimension], + [types.Number, '%'], + [types.Number, types.CDC], // https://github.com/w3c/csswg-drafts/pull/6874 + + ['@', types.Ident], + ['@', types.Function], + ['@', types.Url], + ['@', types.BadUrl], + ['@', '-'], + ['@', types.CDC], // https://github.com/w3c/csswg-drafts/pull/6874 + + ['.', types.Number], + ['.', types.Percentage], + ['.', types.Dimension], + + ['+', types.Number], + ['+', types.Percentage], + ['+', types.Dimension], + + ['/', '*'] +]; +// validate with scripts/generate-safe +const safePairs = specPairs.concat([ + [types.Ident, types.Hash], + + [types.Dimension, types.Hash], + + [types.Hash, types.Hash], + + [types.AtKeyword, types.LeftParenthesis], + [types.AtKeyword, types.String], + [types.AtKeyword, types.Colon], + + [types.Percentage, types.Percentage], + [types.Percentage, types.Dimension], + [types.Percentage, types.Function], + [types.Percentage, '-'], + + [types.RightParenthesis, types.Ident], + [types.RightParenthesis, types.Function], + [types.RightParenthesis, types.Percentage], + [types.RightParenthesis, types.Dimension], + [types.RightParenthesis, types.Hash], + [types.RightParenthesis, '-'] +]); + +function createMap(pairs) { + const isWhiteSpaceRequired = new Set( + pairs.map(([prev, next]) => (code(prev) << 16 | code(next))) + ); + + return function(prevCode, type, value) { + const nextCode = code(type, value); + const nextCharCode = value.charCodeAt(0); + const emitWs = + (nextCharCode === HYPHENMINUS && + type !== types.Ident && + type !== types.Function && + type !== types.CDC) || + (nextCharCode === PLUSSIGN) + ? isWhiteSpaceRequired.has((prevCode & 0xFFFE) << 16 | nextCharCode << 7) + : isWhiteSpaceRequired.has((prevCode & 0xFFFE) << 16 | nextCode); + + return nextCode | emitWs; + }; +} + +const spec = createMap(specPairs); +const safe = createMap(safePairs); + +exports.safe = safe; +exports.spec = spec; diff --git a/node_modules/css-tree/cjs/index.cjs b/node_modules/css-tree/cjs/index.cjs new file mode 100644 index 00000000..cc611378 --- /dev/null +++ b/node_modules/css-tree/cjs/index.cjs @@ -0,0 +1,65 @@ +'use strict'; + +const index$1 = require('./syntax/index.cjs'); +const version = require('./version.cjs'); +const create = require('./syntax/create.cjs'); +const List = require('./utils/List.cjs'); +const Lexer = require('./lexer/Lexer.cjs'); +const index = require('./definition-syntax/index.cjs'); +const clone = require('./utils/clone.cjs'); +const names$1 = require('./utils/names.cjs'); +const ident = require('./utils/ident.cjs'); +const string = require('./utils/string.cjs'); +const url = require('./utils/url.cjs'); +const types = require('./tokenizer/types.cjs'); +const names = require('./tokenizer/names.cjs'); +const TokenStream = require('./tokenizer/TokenStream.cjs'); +const OffsetToLocation = require('./tokenizer/OffsetToLocation.cjs'); + +const { + tokenize, + parse, + generate, + lexer, + createLexer, + + walk, + find, + findLast, + findAll, + + toPlainObject, + fromPlainObject, + + fork +} = index$1; + +exports.version = version.version; +exports.createSyntax = create; +exports.List = List.List; +exports.Lexer = Lexer.Lexer; +exports.definitionSyntax = index; +exports.clone = clone.clone; +exports.isCustomProperty = names$1.isCustomProperty; +exports.keyword = names$1.keyword; +exports.property = names$1.property; +exports.vendorPrefix = names$1.vendorPrefix; +exports.ident = ident; +exports.string = string; +exports.url = url; +exports.tokenTypes = types; +exports.tokenNames = names; +exports.TokenStream = TokenStream.TokenStream; +exports.OffsetToLocation = OffsetToLocation.OffsetToLocation; +exports.createLexer = createLexer; +exports.find = find; +exports.findAll = findAll; +exports.findLast = findLast; +exports.fork = fork; +exports.fromPlainObject = fromPlainObject; +exports.generate = generate; +exports.lexer = lexer; +exports.parse = parse; +exports.toPlainObject = toPlainObject; +exports.tokenize = tokenize; +exports.walk = walk; diff --git a/node_modules/css-tree/cjs/lexer/Lexer.cjs b/node_modules/css-tree/cjs/lexer/Lexer.cjs new file mode 100644 index 00000000..a6d1fcb6 --- /dev/null +++ b/node_modules/css-tree/cjs/lexer/Lexer.cjs @@ -0,0 +1,517 @@ +'use strict'; + +const error = require('./error.cjs'); +const names = require('../utils/names.cjs'); +const genericConst = require('./generic-const.cjs'); +const generic = require('./generic.cjs'); +const units = require('./units.cjs'); +const prepareTokens = require('./prepare-tokens.cjs'); +const matchGraph = require('./match-graph.cjs'); +const match = require('./match.cjs'); +const trace = require('./trace.cjs'); +const search = require('./search.cjs'); +const structure = require('./structure.cjs'); +const parse = require('../definition-syntax/parse.cjs'); +const generate = require('../definition-syntax/generate.cjs'); +const walk = require('../definition-syntax/walk.cjs'); + +function dumpMapSyntax(map, compact, syntaxAsAst) { + const result = {}; + + for (const name in map) { + if (map[name].syntax) { + result[name] = syntaxAsAst + ? map[name].syntax + : generate.generate(map[name].syntax, { compact }); + } + } + + return result; +} + +function dumpAtruleMapSyntax(map, compact, syntaxAsAst) { + const result = {}; + + for (const [name, atrule] of Object.entries(map)) { + result[name] = { + prelude: atrule.prelude && ( + syntaxAsAst + ? atrule.prelude.syntax + : generate.generate(atrule.prelude.syntax, { compact }) + ), + descriptors: atrule.descriptors && dumpMapSyntax(atrule.descriptors, compact, syntaxAsAst) + }; + } + + return result; +} + +function valueHasVar(tokens) { + for (let i = 0; i < tokens.length; i++) { + if (tokens[i].value.toLowerCase() === 'var(') { + return true; + } + } + + return false; +} + +function syntaxHasTopLevelCommaMultiplier(syntax) { + const singleTerm = syntax.terms[0]; + + return ( + syntax.explicit === false && + syntax.terms.length === 1 && + singleTerm.type === 'Multiplier' && + singleTerm.comma === true + ); +} + +function buildMatchResult(matched, error, iterations) { + return { + matched, + iterations, + error, + ...trace + }; +} + +function matchSyntax(lexer, syntax, value, useCssWideKeywords) { + const tokens = prepareTokens(value, lexer.syntax); + let result; + + if (valueHasVar(tokens)) { + return buildMatchResult(null, new Error('Matching for a tree with var() is not supported')); + } + + if (useCssWideKeywords) { + result = match.matchAsTree(tokens, lexer.cssWideKeywordsSyntax, lexer); + } + + if (!useCssWideKeywords || !result.match) { + result = match.matchAsTree(tokens, syntax.match, lexer); + if (!result.match) { + return buildMatchResult( + null, + new error.SyntaxMatchError(result.reason, syntax.syntax, value, result), + result.iterations + ); + } + } + + return buildMatchResult(result.match, null, result.iterations); +} + +class Lexer { + constructor(config, syntax, structure$1) { + this.cssWideKeywords = genericConst.cssWideKeywords; + this.syntax = syntax; + this.generic = false; + this.units = { ...units }; + this.atrules = Object.create(null); + this.properties = Object.create(null); + this.types = Object.create(null); + this.structure = structure$1 || structure.getStructureFromConfig(config); + + if (config) { + if (config.cssWideKeywords) { + this.cssWideKeywords = config.cssWideKeywords; + } + + if (config.units) { + for (const group of Object.keys(units)) { + if (Array.isArray(config.units[group])) { + this.units[group] = config.units[group]; + } + } + } + + if (config.types) { + for (const [name, type] of Object.entries(config.types)) { + this.addType_(name, type); + } + } + + if (config.generic) { + this.generic = true; + for (const [name, value] of Object.entries(generic.createGenericTypes(this.units))) { + this.addType_(name, value); + } + } + + if (config.atrules) { + for (const [name, atrule] of Object.entries(config.atrules)) { + this.addAtrule_(name, atrule); + } + } + + if (config.properties) { + for (const [name, property] of Object.entries(config.properties)) { + this.addProperty_(name, property); + } + } + } + + this.cssWideKeywordsSyntax = matchGraph.buildMatchGraph(this.cssWideKeywords.join(' | ')); + } + + checkStructure(ast) { + function collectWarning(node, message) { + warns.push({ node, message }); + } + + const structure = this.structure; + const warns = []; + + this.syntax.walk(ast, function(node) { + if (structure.hasOwnProperty(node.type)) { + structure[node.type].check(node, collectWarning); + } else { + collectWarning(node, 'Unknown node type `' + node.type + '`'); + } + }); + + return warns.length ? warns : false; + } + + createDescriptor(syntax, type, name, parent = null) { + const ref = { + type, + name + }; + const descriptor = { + type, + name, + parent, + serializable: typeof syntax === 'string' || (syntax && typeof syntax.type === 'string'), + syntax: null, + match: null, + matchRef: null // used for properties when a syntax referenced as <'property'> in other syntax definitions + }; + + if (typeof syntax === 'function') { + descriptor.match = matchGraph.buildMatchGraph(syntax, ref); + } else { + if (typeof syntax === 'string') { + // lazy parsing on first access + Object.defineProperty(descriptor, 'syntax', { + get() { + Object.defineProperty(descriptor, 'syntax', { + value: parse.parse(syntax) + }); + + return descriptor.syntax; + } + }); + } else { + descriptor.syntax = syntax; + } + + // lazy graph build on first access + Object.defineProperty(descriptor, 'match', { + get() { + Object.defineProperty(descriptor, 'match', { + value: matchGraph.buildMatchGraph(descriptor.syntax, ref) + }); + + return descriptor.match; + } + }); + + if (type === 'Property') { + Object.defineProperty(descriptor, 'matchRef', { + get() { + const syntax = descriptor.syntax; + const value = syntaxHasTopLevelCommaMultiplier(syntax) + ? matchGraph.buildMatchGraph({ + ...syntax, + terms: [syntax.terms[0].term] + }, ref) + : null; + + Object.defineProperty(descriptor, 'matchRef', { + value + }); + + return value; + } + }); + } + } + + return descriptor; + } + addAtrule_(name, syntax) { + if (!syntax) { + return; + } + + this.atrules[name] = { + type: 'Atrule', + name: name, + prelude: syntax.prelude ? this.createDescriptor(syntax.prelude, 'AtrulePrelude', name) : null, + descriptors: syntax.descriptors + ? Object.keys(syntax.descriptors).reduce( + (map, descName) => { + map[descName] = this.createDescriptor(syntax.descriptors[descName], 'AtruleDescriptor', descName, name); + return map; + }, + Object.create(null) + ) + : null + }; + } + addProperty_(name, syntax) { + if (!syntax) { + return; + } + + this.properties[name] = this.createDescriptor(syntax, 'Property', name); + } + addType_(name, syntax) { + if (!syntax) { + return; + } + + this.types[name] = this.createDescriptor(syntax, 'Type', name); + } + + checkAtruleName(atruleName) { + if (!this.getAtrule(atruleName)) { + return new error.SyntaxReferenceError('Unknown at-rule', '@' + atruleName); + } + } + checkAtrulePrelude(atruleName, prelude) { + const error = this.checkAtruleName(atruleName); + + if (error) { + return error; + } + + const atrule = this.getAtrule(atruleName); + + if (!atrule.prelude && prelude) { + return new SyntaxError('At-rule `@' + atruleName + '` should not contain a prelude'); + } + + if (atrule.prelude && !prelude) { + if (!matchSyntax(this, atrule.prelude, '', false).matched) { + return new SyntaxError('At-rule `@' + atruleName + '` should contain a prelude'); + } + } + } + checkAtruleDescriptorName(atruleName, descriptorName) { + const error$1 = this.checkAtruleName(atruleName); + + if (error$1) { + return error$1; + } + + const atrule = this.getAtrule(atruleName); + const descriptor = names.keyword(descriptorName); + + if (!atrule.descriptors) { + return new SyntaxError('At-rule `@' + atruleName + '` has no known descriptors'); + } + + if (!atrule.descriptors[descriptor.name] && + !atrule.descriptors[descriptor.basename]) { + return new error.SyntaxReferenceError('Unknown at-rule descriptor', descriptorName); + } + } + checkPropertyName(propertyName) { + if (!this.getProperty(propertyName)) { + return new error.SyntaxReferenceError('Unknown property', propertyName); + } + } + + matchAtrulePrelude(atruleName, prelude) { + const error = this.checkAtrulePrelude(atruleName, prelude); + + if (error) { + return buildMatchResult(null, error); + } + + const atrule = this.getAtrule(atruleName); + + if (!atrule.prelude) { + return buildMatchResult(null, null); + } + + return matchSyntax(this, atrule.prelude, prelude || '', false); + } + matchAtruleDescriptor(atruleName, descriptorName, value) { + const error = this.checkAtruleDescriptorName(atruleName, descriptorName); + + if (error) { + return buildMatchResult(null, error); + } + + const atrule = this.getAtrule(atruleName); + const descriptor = names.keyword(descriptorName); + + return matchSyntax(this, atrule.descriptors[descriptor.name] || atrule.descriptors[descriptor.basename], value, false); + } + matchDeclaration(node) { + if (node.type !== 'Declaration') { + return buildMatchResult(null, new Error('Not a Declaration node')); + } + + return this.matchProperty(node.property, node.value); + } + matchProperty(propertyName, value) { + // don't match syntax for a custom property at the moment + if (names.property(propertyName).custom) { + return buildMatchResult(null, new Error('Lexer matching doesn\'t applicable for custom properties')); + } + + const error = this.checkPropertyName(propertyName); + + if (error) { + return buildMatchResult(null, error); + } + + return matchSyntax(this, this.getProperty(propertyName), value, true); + } + matchType(typeName, value) { + const typeSyntax = this.getType(typeName); + + if (!typeSyntax) { + return buildMatchResult(null, new error.SyntaxReferenceError('Unknown type', typeName)); + } + + return matchSyntax(this, typeSyntax, value, false); + } + match(syntax, value) { + if (typeof syntax !== 'string' && (!syntax || !syntax.type)) { + return buildMatchResult(null, new error.SyntaxReferenceError('Bad syntax')); + } + + if (typeof syntax === 'string' || !syntax.match) { + syntax = this.createDescriptor(syntax, 'Type', 'anonymous'); + } + + return matchSyntax(this, syntax, value, false); + } + + findValueFragments(propertyName, value, type, name) { + return search.matchFragments(this, value, this.matchProperty(propertyName, value), type, name); + } + findDeclarationValueFragments(declaration, type, name) { + return search.matchFragments(this, declaration.value, this.matchDeclaration(declaration), type, name); + } + findAllFragments(ast, type, name) { + const result = []; + + this.syntax.walk(ast, { + visit: 'Declaration', + enter: (declaration) => { + result.push.apply(result, this.findDeclarationValueFragments(declaration, type, name)); + } + }); + + return result; + } + + getAtrule(atruleName, fallbackBasename = true) { + const atrule = names.keyword(atruleName); + const atruleEntry = atrule.vendor && fallbackBasename + ? this.atrules[atrule.name] || this.atrules[atrule.basename] + : this.atrules[atrule.name]; + + return atruleEntry || null; + } + getAtrulePrelude(atruleName, fallbackBasename = true) { + const atrule = this.getAtrule(atruleName, fallbackBasename); + + return atrule && atrule.prelude || null; + } + getAtruleDescriptor(atruleName, name) { + return this.atrules.hasOwnProperty(atruleName) && this.atrules.declarators + ? this.atrules[atruleName].declarators[name] || null + : null; + } + getProperty(propertyName, fallbackBasename = true) { + const property = names.property(propertyName); + const propertyEntry = property.vendor && fallbackBasename + ? this.properties[property.name] || this.properties[property.basename] + : this.properties[property.name]; + + return propertyEntry || null; + } + getType(name) { + return hasOwnProperty.call(this.types, name) ? this.types[name] : null; + } + + validate() { + function syntaxRef(name, isType) { + return isType ? `<${name}>` : `<'${name}'>`; + } + + function validate(syntax, name, broken, descriptor) { + if (broken.has(name)) { + return broken.get(name); + } + + broken.set(name, false); + if (descriptor.syntax !== null) { + walk.walk(descriptor.syntax, function(node) { + if (node.type !== 'Type' && node.type !== 'Property') { + return; + } + + const map = node.type === 'Type' ? syntax.types : syntax.properties; + const brokenMap = node.type === 'Type' ? brokenTypes : brokenProperties; + + if (!hasOwnProperty.call(map, node.name)) { + errors.push(`${syntaxRef(name, broken === brokenTypes)} used missed syntax definition ${syntaxRef(node.name, node.type === 'Type')}`); + broken.set(name, true); + } else if (validate(syntax, node.name, brokenMap, map[node.name])) { + errors.push(`${syntaxRef(name, broken === brokenTypes)} used broken syntax definition ${syntaxRef(node.name, node.type === 'Type')}`); + broken.set(name, true); + } + }, this); + } + } + + const errors = []; + let brokenTypes = new Map(); + let brokenProperties = new Map(); + + for (const key in this.types) { + validate(this, key, brokenTypes, this.types[key]); + } + + for (const key in this.properties) { + validate(this, key, brokenProperties, this.properties[key]); + } + + const brokenTypesArray = [...brokenTypes.keys()].filter(name => brokenTypes.get(name)); + const brokenPropertiesArray = [...brokenProperties.keys()].filter(name => brokenProperties.get(name)); + + if (brokenTypesArray.length || brokenPropertiesArray.length) { + return { + errors, + types: brokenTypesArray, + properties: brokenPropertiesArray + }; + } + + return null; + } + dump(syntaxAsAst, pretty) { + return { + generic: this.generic, + cssWideKeywords: this.cssWideKeywords, + units: this.units, + types: dumpMapSyntax(this.types, !pretty, syntaxAsAst), + properties: dumpMapSyntax(this.properties, !pretty, syntaxAsAst), + atrules: dumpAtruleMapSyntax(this.atrules, !pretty, syntaxAsAst) + }; + } + toString() { + return JSON.stringify(this.dump()); + } +} + +exports.Lexer = Lexer; diff --git a/node_modules/css-tree/cjs/lexer/error.cjs b/node_modules/css-tree/cjs/lexer/error.cjs new file mode 100644 index 00000000..8d252eeb --- /dev/null +++ b/node_modules/css-tree/cjs/lexer/error.cjs @@ -0,0 +1,128 @@ +'use strict'; + +const createCustomError = require('../utils/create-custom-error.cjs'); +const generate = require('../definition-syntax/generate.cjs'); + +const defaultLoc = { offset: 0, line: 1, column: 1 }; + +function locateMismatch(matchResult, node) { + const tokens = matchResult.tokens; + const longestMatch = matchResult.longestMatch; + const mismatchNode = longestMatch < tokens.length ? tokens[longestMatch].node || null : null; + const badNode = mismatchNode !== node ? mismatchNode : null; + let mismatchOffset = 0; + let mismatchLength = 0; + let entries = 0; + let css = ''; + let start; + let end; + + for (let i = 0; i < tokens.length; i++) { + const token = tokens[i].value; + + if (i === longestMatch) { + mismatchLength = token.length; + mismatchOffset = css.length; + } + + if (badNode !== null && tokens[i].node === badNode) { + if (i <= longestMatch) { + entries++; + } else { + entries = 0; + } + } + + css += token; + } + + if (longestMatch === tokens.length || entries > 1) { // last + start = fromLoc(badNode || node, 'end') || buildLoc(defaultLoc, css); + end = buildLoc(start); + } else { + start = fromLoc(badNode, 'start') || + buildLoc(fromLoc(node, 'start') || defaultLoc, css.slice(0, mismatchOffset)); + end = fromLoc(badNode, 'end') || + buildLoc(start, css.substr(mismatchOffset, mismatchLength)); + } + + return { + css, + mismatchOffset, + mismatchLength, + start, + end + }; +} + +function fromLoc(node, point) { + const value = node && node.loc && node.loc[point]; + + if (value) { + return 'line' in value ? buildLoc(value) : value; + } + + return null; +} + +function buildLoc({ offset, line, column }, extra) { + const loc = { + offset, + line, + column + }; + + if (extra) { + const lines = extra.split(/\n|\r\n?|\f/); + + loc.offset += extra.length; + loc.line += lines.length - 1; + loc.column = lines.length === 1 ? loc.column + extra.length : lines.pop().length + 1; + } + + return loc; +} + +const SyntaxReferenceError = function(type, referenceName) { + const error = createCustomError.createCustomError( + 'SyntaxReferenceError', + type + (referenceName ? ' `' + referenceName + '`' : '') + ); + + error.reference = referenceName; + + return error; +}; + +const SyntaxMatchError = function(message, syntax, node, matchResult) { + const error = createCustomError.createCustomError('SyntaxMatchError', message); + const { + css, + mismatchOffset, + mismatchLength, + start, + end + } = locateMismatch(matchResult, node); + + error.rawMessage = message; + error.syntax = syntax ? generate.generate(syntax) : ''; + error.css = css; + error.mismatchOffset = mismatchOffset; + error.mismatchLength = mismatchLength; + error.message = message + '\n' + + ' syntax: ' + error.syntax + '\n' + + ' value: ' + (css || '') + '\n' + + ' --------' + new Array(error.mismatchOffset + 1).join('-') + '^'; + + Object.assign(error, start); + error.loc = { + source: (node && node.loc && node.loc.source) || '', + start, + end + }; + + return error; +}; + +exports.SyntaxMatchError = SyntaxMatchError; +exports.SyntaxReferenceError = SyntaxReferenceError; diff --git a/node_modules/css-tree/cjs/lexer/generic-an-plus-b.cjs b/node_modules/css-tree/cjs/lexer/generic-an-plus-b.cjs new file mode 100644 index 00000000..a5dfba3e --- /dev/null +++ b/node_modules/css-tree/cjs/lexer/generic-an-plus-b.cjs @@ -0,0 +1,235 @@ +'use strict'; + +const charCodeDefinitions = require('../tokenizer/char-code-definitions.cjs'); +const types = require('../tokenizer/types.cjs'); +const utils = require('../tokenizer/utils.cjs'); + +const PLUSSIGN = 0x002B; // U+002B PLUS SIGN (+) +const HYPHENMINUS = 0x002D; // U+002D HYPHEN-MINUS (-) +const N = 0x006E; // U+006E LATIN SMALL LETTER N (n) +const DISALLOW_SIGN = true; +const ALLOW_SIGN = false; + +function isDelim(token, code) { + return token !== null && token.type === types.Delim && token.value.charCodeAt(0) === code; +} + +function skipSC(token, offset, getNextToken) { + while (token !== null && (token.type === types.WhiteSpace || token.type === types.Comment)) { + token = getNextToken(++offset); + } + + return offset; +} + +function checkInteger(token, valueOffset, disallowSign, offset) { + if (!token) { + return 0; + } + + const code = token.value.charCodeAt(valueOffset); + + if (code === PLUSSIGN || code === HYPHENMINUS) { + if (disallowSign) { + // Number sign is not allowed + return 0; + } + valueOffset++; + } + + for (; valueOffset < token.value.length; valueOffset++) { + if (!charCodeDefinitions.isDigit(token.value.charCodeAt(valueOffset))) { + // Integer is expected + return 0; + } + } + + return offset + 1; +} + +// ... +// ... ['+' | '-'] +function consumeB(token, offset_, getNextToken) { + let sign = false; + let offset = skipSC(token, offset_, getNextToken); + + token = getNextToken(offset); + + if (token === null) { + return offset_; + } + + if (token.type !== types.Number) { + if (isDelim(token, PLUSSIGN) || isDelim(token, HYPHENMINUS)) { + sign = true; + offset = skipSC(getNextToken(++offset), offset, getNextToken); + token = getNextToken(offset); + + if (token === null || token.type !== types.Number) { + return 0; + } + } else { + return offset_; + } + } + + if (!sign) { + const code = token.value.charCodeAt(0); + if (code !== PLUSSIGN && code !== HYPHENMINUS) { + // Number sign is expected + return 0; + } + } + + return checkInteger(token, sign ? 0 : 1, sign, offset); +} + +// An+B microsyntax https://www.w3.org/TR/css-syntax-3/#anb +function anPlusB(token, getNextToken) { + /* eslint-disable brace-style*/ + let offset = 0; + + if (!token) { + return 0; + } + + // + if (token.type === types.Number) { + return checkInteger(token, 0, ALLOW_SIGN, offset); // b + } + + // -n + // -n + // -n ['+' | '-'] + // -n- + // + else if (token.type === types.Ident && token.value.charCodeAt(0) === HYPHENMINUS) { + // expect 1st char is N + if (!utils.cmpChar(token.value, 1, N)) { + return 0; + } + + switch (token.value.length) { + // -n + // -n + // -n ['+' | '-'] + case 2: + return consumeB(getNextToken(++offset), offset, getNextToken); + + // -n- + case 3: + if (token.value.charCodeAt(2) !== HYPHENMINUS) { + return 0; + } + + offset = skipSC(getNextToken(++offset), offset, getNextToken); + token = getNextToken(offset); + + return checkInteger(token, 0, DISALLOW_SIGN, offset); + + // + default: + if (token.value.charCodeAt(2) !== HYPHENMINUS) { + return 0; + } + + return checkInteger(token, 3, DISALLOW_SIGN, offset); + } + } + + // '+'? n + // '+'? n + // '+'? n ['+' | '-'] + // '+'? n- + // '+'? + else if (token.type === types.Ident || (isDelim(token, PLUSSIGN) && getNextToken(offset + 1).type === types.Ident)) { + // just ignore a plus + if (token.type !== types.Ident) { + token = getNextToken(++offset); + } + + if (token === null || !utils.cmpChar(token.value, 0, N)) { + return 0; + } + + switch (token.value.length) { + // '+'? n + // '+'? n + // '+'? n ['+' | '-'] + case 1: + return consumeB(getNextToken(++offset), offset, getNextToken); + + // '+'? n- + case 2: + if (token.value.charCodeAt(1) !== HYPHENMINUS) { + return 0; + } + + offset = skipSC(getNextToken(++offset), offset, getNextToken); + token = getNextToken(offset); + + return checkInteger(token, 0, DISALLOW_SIGN, offset); + + // '+'? + default: + if (token.value.charCodeAt(1) !== HYPHENMINUS) { + return 0; + } + + return checkInteger(token, 2, DISALLOW_SIGN, offset); + } + } + + // + // + // + // + // ['+' | '-'] + else if (token.type === types.Dimension) { + let code = token.value.charCodeAt(0); + let sign = code === PLUSSIGN || code === HYPHENMINUS ? 1 : 0; + let i = sign; + + for (; i < token.value.length; i++) { + if (!charCodeDefinitions.isDigit(token.value.charCodeAt(i))) { + break; + } + } + + if (i === sign) { + // Integer is expected + return 0; + } + + if (!utils.cmpChar(token.value, i, N)) { + return 0; + } + + // + // + // ['+' | '-'] + if (i + 1 === token.value.length) { + return consumeB(getNextToken(++offset), offset, getNextToken); + } else { + if (token.value.charCodeAt(i + 1) !== HYPHENMINUS) { + return 0; + } + + // + if (i + 2 === token.value.length) { + offset = skipSC(getNextToken(++offset), offset, getNextToken); + token = getNextToken(offset); + + return checkInteger(token, 0, DISALLOW_SIGN, offset); + } + // + else { + return checkInteger(token, i + 2, DISALLOW_SIGN, offset); + } + } + } + + return 0; +} + +module.exports = anPlusB; diff --git a/node_modules/css-tree/cjs/lexer/generic-const.cjs b/node_modules/css-tree/cjs/lexer/generic-const.cjs new file mode 100644 index 00000000..9b9f6157 --- /dev/null +++ b/node_modules/css-tree/cjs/lexer/generic-const.cjs @@ -0,0 +1,12 @@ +'use strict'; + +// https://drafts.csswg.org/css-cascade-5/ +const cssWideKeywords = [ + 'initial', + 'inherit', + 'unset', + 'revert', + 'revert-layer' +]; + +exports.cssWideKeywords = cssWideKeywords; diff --git a/node_modules/css-tree/cjs/lexer/generic-urange.cjs b/node_modules/css-tree/cjs/lexer/generic-urange.cjs new file mode 100644 index 00000000..ce167bb1 --- /dev/null +++ b/node_modules/css-tree/cjs/lexer/generic-urange.cjs @@ -0,0 +1,149 @@ +'use strict'; + +const charCodeDefinitions = require('../tokenizer/char-code-definitions.cjs'); +const types = require('../tokenizer/types.cjs'); +const utils = require('../tokenizer/utils.cjs'); + +const PLUSSIGN = 0x002B; // U+002B PLUS SIGN (+) +const HYPHENMINUS = 0x002D; // U+002D HYPHEN-MINUS (-) +const QUESTIONMARK = 0x003F; // U+003F QUESTION MARK (?) +const U = 0x0075; // U+0075 LATIN SMALL LETTER U (u) + +function isDelim(token, code) { + return token !== null && token.type === types.Delim && token.value.charCodeAt(0) === code; +} + +function startsWith(token, code) { + return token.value.charCodeAt(0) === code; +} + +function hexSequence(token, offset, allowDash) { + let hexlen = 0; + + for (let pos = offset; pos < token.value.length; pos++) { + const code = token.value.charCodeAt(pos); + + if (code === HYPHENMINUS && allowDash && hexlen !== 0) { + hexSequence(token, offset + hexlen + 1, false); + return 6; // dissallow following question marks + } + + if (!charCodeDefinitions.isHexDigit(code)) { + return 0; // not a hex digit + } + + if (++hexlen > 6) { + return 0; // too many hex digits + } } + + return hexlen; +} + +function withQuestionMarkSequence(consumed, length, getNextToken) { + if (!consumed) { + return 0; // nothing consumed + } + + while (isDelim(getNextToken(length), QUESTIONMARK)) { + if (++consumed > 6) { + return 0; // too many question marks + } + + length++; + } + + return length; +} + +// https://drafts.csswg.org/css-syntax/#urange +// Informally, the production has three forms: +// U+0001 +// Defines a range consisting of a single code point, in this case the code point "1". +// U+0001-00ff +// Defines a range of codepoints between the first and the second value, in this case +// the range between "1" and "ff" (255 in decimal) inclusive. +// U+00?? +// Defines a range of codepoints where the "?" characters range over all hex digits, +// in this case defining the same as the value U+0000-00ff. +// In each form, a maximum of 6 digits is allowed for each hexadecimal number (if you treat "?" as a hexadecimal digit). +// +// = +// u '+' '?'* | +// u '?'* | +// u '?'* | +// u | +// u | +// u '+' '?'+ +function urange(token, getNextToken) { + let length = 0; + + // should start with `u` or `U` + if (token === null || token.type !== types.Ident || !utils.cmpChar(token.value, 0, U)) { + return 0; + } + + token = getNextToken(++length); + if (token === null) { + return 0; + } + + // u '+' '?'* + // u '+' '?'+ + if (isDelim(token, PLUSSIGN)) { + token = getNextToken(++length); + if (token === null) { + return 0; + } + + if (token.type === types.Ident) { + // u '+' '?'* + return withQuestionMarkSequence(hexSequence(token, 0, true), ++length, getNextToken); + } + + if (isDelim(token, QUESTIONMARK)) { + // u '+' '?'+ + return withQuestionMarkSequence(1, ++length, getNextToken); + } + + // Hex digit or question mark is expected + return 0; + } + + // u '?'* + // u + // u + if (token.type === types.Number) { + const consumedHexLength = hexSequence(token, 1, true); + if (consumedHexLength === 0) { + return 0; + } + + token = getNextToken(++length); + if (token === null) { + // u + return length; + } + + if (token.type === types.Dimension || token.type === types.Number) { + // u + // u + if (!startsWith(token, HYPHENMINUS) || !hexSequence(token, 1, false)) { + return 0; + } + + return length + 1; + } + + // u '?'* + return withQuestionMarkSequence(consumedHexLength, length, getNextToken); + } + + // u '?'* + if (token.type === types.Dimension) { + return withQuestionMarkSequence(hexSequence(token, 1, true), ++length, getNextToken); + } + + return 0; +} + +module.exports = urange; diff --git a/node_modules/css-tree/cjs/lexer/generic.cjs b/node_modules/css-tree/cjs/lexer/generic.cjs new file mode 100644 index 00000000..01230460 --- /dev/null +++ b/node_modules/css-tree/cjs/lexer/generic.cjs @@ -0,0 +1,717 @@ +'use strict'; + +const genericConst = require('./generic-const.cjs'); +const genericAnPlusB = require('./generic-an-plus-b.cjs'); +const genericUrange = require('./generic-urange.cjs'); +const charCodeDefinitions = require('../tokenizer/char-code-definitions.cjs'); +const types = require('../tokenizer/types.cjs'); +const utils = require('../tokenizer/utils.cjs'); + +// CSS mathematical functions categorized by return type behavior +// See: https://www.w3.org/TR/css-values-4/#math + +// Calculation functions that return different types depending on input +const calcFunctionNames = [ + 'calc(', + '-moz-calc(', + '-webkit-calc(' +]; + +// Comparison functions that return different types depending on input +const comparisonFunctionNames = [ + 'min(', + 'max(', + 'clamp(' +]; + +// Functions that return a stepped value, i.e. a value that is rounded to the nearest step +const steppedValueFunctionNames = [ + 'round(', + 'mod(', + 'rem(' +]; + +// Trigonometrical functions that return a +const trigNumberFunctionNames = [ + 'sin(', + 'cos(', + 'tan(' +]; + +// Trigonometrical functions that return a +const trigAngleFunctionNames = [ + 'asin(', + 'acos(', + 'atan(', + 'atan2(' +]; + +// Other functions that return a +const otherNumberFunctionNames = [ + 'pow(', + 'sqrt(', + 'log(', + 'exp(', + 'sign(' +]; + +// Exponential functions that return a or or +const expNumberDimensionPercentageFunctionNames = [ + 'hypot(' +]; + +// Return the same type as the input +const signFunctionNames = [ + 'abs(' +]; + +const numberFunctionNames = [ + ...calcFunctionNames, + ...comparisonFunctionNames, + ...steppedValueFunctionNames, + ...trigNumberFunctionNames, + ...otherNumberFunctionNames, + ...expNumberDimensionPercentageFunctionNames, + ...signFunctionNames +]; + +const percentageFunctionNames = [ + ...calcFunctionNames, + ...comparisonFunctionNames, + ...steppedValueFunctionNames, + ...expNumberDimensionPercentageFunctionNames, + ...signFunctionNames +]; + +const dimensionFunctionNames = [ + ...calcFunctionNames, + ...comparisonFunctionNames, + ...steppedValueFunctionNames, + ...trigAngleFunctionNames, + ...expNumberDimensionPercentageFunctionNames, + ...signFunctionNames +]; + +const balancePair = new Map([ + [types.Function, types.RightParenthesis], + [types.LeftParenthesis, types.RightParenthesis], + [types.LeftSquareBracket, types.RightSquareBracket], + [types.LeftCurlyBracket, types.RightCurlyBracket] +]); + +// safe char code getter +function charCodeAt(str, index) { + return index < str.length ? str.charCodeAt(index) : 0; +} + +function eqStr(actual, expected) { + return utils.cmpStr(actual, 0, actual.length, expected); +} + +function eqStrAny(actual, expected) { + for (let i = 0; i < expected.length; i++) { + if (eqStr(actual, expected[i])) { + return true; + } + } + + return false; +} + +// IE postfix hack, i.e. 123\0 or 123px\9 +function isPostfixIeHack(str, offset) { + if (offset !== str.length - 2) { + return false; + } + + return ( + charCodeAt(str, offset) === 0x005C && // U+005C REVERSE SOLIDUS (\) + charCodeDefinitions.isDigit(charCodeAt(str, offset + 1)) + ); +} + +function outOfRange(opts, value, numEnd) { + if (opts && opts.type === 'Range') { + const num = Number( + numEnd !== undefined && numEnd !== value.length + ? value.substr(0, numEnd) + : value + ); + + if (isNaN(num)) { + return true; + } + + // FIXME: when opts.min is a string it's a dimension, skip a range validation + // for now since it requires a type covertation which is not implmented yet + if (opts.min !== null && num < opts.min && typeof opts.min !== 'string') { + return true; + } + + // FIXME: when opts.max is a string it's a dimension, skip a range validation + // for now since it requires a type covertation which is not implmented yet + if (opts.max !== null && num > opts.max && typeof opts.max !== 'string') { + return true; + } + } + + return false; +} + +function consumeFunction(token, getNextToken) { + let balanceCloseType = 0; + let balanceStash = []; + let length = 0; + + // balanced token consuming + scan: + do { + switch (token.type) { + case types.RightCurlyBracket: + case types.RightParenthesis: + case types.RightSquareBracket: + if (token.type !== balanceCloseType) { + break scan; + } + + balanceCloseType = balanceStash.pop(); + + if (balanceStash.length === 0) { + length++; + break scan; + } + + break; + + case types.Function: + case types.LeftParenthesis: + case types.LeftSquareBracket: + case types.LeftCurlyBracket: + balanceStash.push(balanceCloseType); + balanceCloseType = balancePair.get(token.type); + break; + } + + length++; + } while (token = getNextToken(length)); + + return length; +} + + +// TODO: implement +// can be used wherever , , ,