docs: 仓库链接指向本镜像仓库
Build NapCat Artifacts / Type Check & Test (push) Waiting to run

This commit is contained in:
TanTan committed 2026-11-13 09:25:58 +08:00
1 parent f954252a34
commit e311ca3275
35554 files changed
+6229626 -4

No files matched your search

@@ -0,0 +1,16 @@
import { ActivationsService, BindingService, DeactivationsService, PlanResultCacheService } from '@inversifyjs/core';
/**
* Manages references to core services used throughout the Container
* This class allows for proper synchronization of services during snapshot/restore operations
*/
export declare class ServiceReferenceManager {
#private;
activationService: ActivationsService;
bindingService: BindingService;
deactivationService: DeactivationsService;
readonly planResultCacheService: PlanResultCacheService;
constructor(activationService: ActivationsService, bindingService: BindingService, deactivationService: DeactivationsService, planResultCacheService: PlanResultCacheService);
reset(activationService: ActivationsService, bindingService: BindingService, deactivationService: DeactivationsService): void;
onReset(listener: () => void): void;
}
//# sourceMappingURL=ServiceReferenceManager.d.ts.map
@@ -0,0 +1,106 @@
var baseSetData = require('./_baseSetData'),
createBind = require('./_createBind'),
createCurry = require('./_createCurry'),
createHybrid = require('./_createHybrid'),
createPartial = require('./_createPartial'),
getData = require('./_getData'),
mergeData = require('./_mergeData'),
setData = require('./_setData'),
setWrapToString = require('./_setWrapToString'),
toInteger = require('./toInteger');
/** Error message constants. */
var FUNC_ERROR_TEXT = 'Expected a function';
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1,
WRAP_BIND_KEY_FLAG = 2,
WRAP_CURRY_FLAG = 8,
WRAP_CURRY_RIGHT_FLAG = 16,
WRAP_PARTIAL_FLAG = 32,
WRAP_PARTIAL_RIGHT_FLAG = 64;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* Creates a function that either curries or invokes `func` with optional
* `this` binding and partially applied arguments.
*
* @private
* @param {Function|string} func The function or method name to wrap.
* @param {number} bitmask The bitmask flags.
* 1 - `_.bind`
* 2 - `_.bindKey`
* 4 - `_.curry` or `_.curryRight` of a bound function
* 8 - `_.curry`
* 16 - `_.curryRight`
* 32 - `_.partial`
* 64 - `_.partialRight`
* 128 - `_.rearg`
* 256 - `_.ary`
* 512 - `_.flip`
* @param {*} [thisArg] The `this` binding of `func`.
* @param {Array} [partials] The arguments to be partially applied.
* @param {Array} [holders] The `partials` placeholder indexes.
* @param {Array} [argPos] The argument positions of the new function.
* @param {number} [ary] The arity cap of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {
var isBindKey = bitmask & WRAP_BIND_KEY_FLAG;
if (!isBindKey && typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
var length = partials ? partials.length : 0;
if (!length) {
bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG);
partials = holders = undefined;
}
ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0);
arity = arity === undefined ? arity : toInteger(arity);
length -= holders ? holders.length : 0;
if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) {
var partialsRight = partials,
holdersRight = holders;
partials = holders = undefined;
}
var data = isBindKey ? undefined : getData(func);
var newData = [
func, bitmask, thisArg, partials, holders, partialsRight, holdersRight,
argPos, ary, arity
];
if (data) {
mergeData(newData, data);
}
func = newData[0];
bitmask = newData[1];
thisArg = newData[2];
partials = newData[3];
holders = newData[4];
arity = newData[9] = newData[9] === undefined
? (isBindKey ? 0 : func.length)
: nativeMax(newData[9] - length, 0);
if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) {
bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG);
}
if (!bitmask || bitmask == WRAP_BIND_FLAG) {
var result = createBind(func, bitmask, thisArg);
} else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) {
result = createCurry(func, bitmask, arity);
} else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) {
result = createPartial(func, bitmask, thisArg, partials);
} else {
result = createHybrid.apply(undefined, newData);
}
var setter = data ? baseSetData : setData;
return setWrapToString(setter(result, newData), func, bitmask);
}
module.exports = createWrap;
@@ -0,0 +1,29 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ExtendsFromMappedKey = ExtendsFromMappedKey;
const index_1 = require("../mapped/index");
const index_2 = require("../literal/index");
const extends_1 = require("./extends");
const value_1 = require("../clone/value");
// prettier-ignore
function FromPropertyKey(K, U, L, R, options) {
return {
[K]: (0, extends_1.Extends)((0, index_2.Literal)(K), U, L, R, (0, value_1.Clone)(options))
};
}
// prettier-ignore
function FromPropertyKeys(K, U, L, R, options) {
return K.reduce((Acc, LK) => {
return { ...Acc, ...FromPropertyKey(LK, U, L, R, options) };
}, {});
}
// prettier-ignore
function FromMappedKey(K, U, L, R, options) {
return FromPropertyKeys(K.keys, U, L, R, options);
}
// prettier-ignore
function ExtendsFromMappedKey(T, U, L, R, options) {
const P = FromMappedKey(T, U, L, R, options);
return (0, index_1.MappedResult)(P);
}
@@ -0,0 +1,522 @@
# React useWebSocket
[Live Demo](https://robtaussig.com/socket/)
Note: `wss://demos.kaazing.com/echo` has been down lately, so the demo will fail to connect when using that as the endpoint. On the plus side, this demonstrates the behavior of a connection failure.
[Test in StackBlitz](https://stackblitz.com/edit/react-otkczd?file=index.js)
React Hook designed to provide robust WebSocket integrations to your React Components. Experimental support for SocketIO (read documentation below for more information)
Pull requests welcomed!
## New in 4.0.0
- `react-use-websocket` now supports (and depends on) React 18. If you are not ready to upgrade to React 18, please install version `3.0.0`:
```
npm install --save react-use-websocket@3.0.0
//or
yarn add react-use-websocket@3.0.0
```
## New in 2.0.0
- `useWebSocket` now returns an object instead of an array. This allows you to pick out specific features/properties to suit your use-case as well as removing mental overhead of keeping track of item order.
- `lastJsonMessage` and `sendJsonMessage` added to return value to reduce need to stringify and parse outgoing and incoming messages at the component level.
- The optional object passed as the second parameter no longer needs to be static.
- Components can close/unsubscribe from a WebSocket by passing `false` as the third parameter. This provides a more explicit solution than the previous method of setting the `socketUrl` to `null`. Both methods work and are supported usage.
## Example Implementation
```js
import React, { useState, useCallback, useEffect } from 'react';
import useWebSocket, { ReadyState } from 'react-use-websocket';
export const WebSocketDemo = () => {
//Public API that will echo messages sent to it back to the client
const [socketUrl, setSocketUrl] = useState('wss://echo.websocket.org');
const [messageHistory, setMessageHistory] =
useState < MessageEvent < any > [] > [];
const { sendMessage, lastMessage, readyState } = useWebSocket(socketUrl);
useEffect(() => {
if (lastMessage !== null) {
setMessageHistory((prev) => prev.concat(lastMessage));
}
}, [lastMessage]);
const handleClickChangeSocketUrl = useCallback(
() => setSocketUrl('wss://demos.kaazing.com/echo'),
[]
);
const handleClickSendMessage = useCallback(() => sendMessage('Hello'), []);
const connectionStatus = {
[ReadyState.CONNECTING]: 'Connecting',
[ReadyState.OPEN]: 'Open',
[ReadyState.CLOSING]: 'Closing',
[ReadyState.CLOSED]: 'Closed',
[ReadyState.UNINSTANTIATED]: 'Uninstantiated',
}[readyState];
return (
<div>
<button onClick={handleClickChangeSocketUrl}>
Click Me to change Socket Url
</button>
<button
onClick={handleClickSendMessage}
disabled={readyState !== ReadyState.OPEN}
>
Click Me to send 'Hello'
</button>
<span>The WebSocket is currently {connectionStatus}</span>
{lastMessage ? <span>Last message: {lastMessage.data}</span> : null}
<ul>
{messageHistory.map((message, idx) => (
<span key={idx}>{message ? message.data : null}</span>
))}
</ul>
</div>
);
};
```
From the example above, the component will rerender every time the `readyState` of the WebSocket changes, as well as when the WebSocket receives a message (which will change `lastMessage`). `sendMessage` is a memoized callback that will pass the message to the current WebSocket (referenced to internally with `useRef`).
A demo of this can be found [here](https://robtaussig.com/socket/). Each component uses its own `useWebSocket` hook. This implementation takes advantage of passing an optional options object (documented below). Among setting event callbacks (for `onmessage`, `onclose`, `onerror`, and `onopen`) that will log to the console, it is using the `share` option -- if multiple components pass the same socketUrl to `useWebSocket` and with `share` set to true, then only a single WebSocket will be created and `useWebSocket` will manage subscriptions/unsubscriptions internally. `useWebSocket` will keep track of how many subscribers any given WebSocket has and will automatically free it from memory once there are no subscribers remaining (a subscriber unsubscribes when it either unmounts or changes its socketUrl). Of course, multiple WebSockets can be created with the same target url, and so components are not required to share the same communication pipeline.
## Features
- Handles reconnect logic
- Multiple components can (optionally) use a single WebSocket, which is closed and cleaned up when all subscribed components have unsubscribed/unmounted
- Written in TypeScript
- Socket.io support
- Heartbeat support
- No more waiting for the WebSocket to open before messages can be sent. Pre-connection messages are queued up and sent on connection
- Provides direct access to unshared WebSockets, while proxying shared WebSockets. Proxied WebSockets provide subscribers controlled access to the underlying (shared) WebSocket, without allowing unsafe behavior
- Seamlessly works with server-sent-events and the [EventSource API](https://developer.mozilla.org/en-US/docs/Web/API/EventSource)
## Getting Started
```sh
npm install react-use-websocket
```
```js
import useWebSocket from 'react-use-websocket';
// In functional React component
// This can also be an async getter function. See notes below on Async Urls.
const socketUrl = 'wss://echo.websocket.org';
const {
sendMessage,
sendJsonMessage,
lastMessage,
lastJsonMessage,
readyState,
getWebSocket,
} = useWebSocket(socketUrl, {
onOpen: () => console.log('opened'),
//Will attempt to reconnect on all close events, such as server shutting down
shouldReconnect: (closeEvent) => true,
});
```
## Interface
```ts
type UseWebSocket<T = unknown> = (
//Url can be return value of a memoized async function.
url: string | () => Promise<string>,
options: {
fromSocketIO?: boolean;
queryParams?: { [field: string]: any };
protocols?: string | string[];
share?: boolean;
onOpen?: (event: WebSocketEventMap['open']) => void;
onClose?: (event: WebSocketEventMap['close']) => void;
onMessage?: (event: WebSocketEventMap['message']) => void;
onError?: (event: WebSocketEventMap['error']) => void;
onReconnectStop?: (numAttempts: number) => void;
shouldReconnect?: (event: WebSocketEventMap['close']) => boolean;
reconnectInterval?: number | ((lastAttemptNumber: number) => number);
reconnectAttempts?: number;
filter?: (message: WebSocketEventMap['message']) => boolean;
disableJson?: boolean;
retryOnError?: boolean;
eventSourceOptions?: EventSourceInit;
heartbeat?: boolean | {
message?: "ping" | "pong" | string | (() => string);
returnMessage?: "ping" | "pong" | string;
timeout?: number;
interval?: number;
};
} = {},
shouldConnect: boolean = true,
): {
sendMessage: (message: string, keep: boolean = true) => void,
//jsonMessage must be JSON-parsable
sendJsonMessage: (jsonMessage: T, keep: boolean = true) => void,
//null before first received message
lastMessage: WebSocketEventMap['message'] | null,
//null before first received message. If message.data is not JSON parsable, then this will be a static empty object
lastJsonMessage: T | null,
// -1 if uninstantiated, otherwise follows WebSocket readyState mapping: 0: 'Connecting', 1 'OPEN', 2: 'CLOSING', 3: 'CLOSED'
readyState: number,
// If using a shared websocket, return value will be a proxy-wrapped websocket, with certain properties/methods protected
getWebSocket: () => (WebSocketLike | null),
}
```
## Requirements
- React 16.8+
- Cannot be used within a class component (must be a functional component that supports React Hooks)
## Async Urls
Instead of passing a string as the first argument to useWebSocket, you can pass a function that returns a string (or a promise that resolves to a string). It's important to note, however, that other rules still apply -- namely, that if the function reference changes, then it will be called again, potentially instantiating a new WebSocket if the returned url changes.
```js
import useWebSocket from 'react-use-websocket';
// In functional React component
const getSocketUrl = useCallback(() => {
return new Promise((resolve) => {
setTimeout(() => {
resolve('wss://echo.websocket.org');
}, 2000);
});
}, []);
const { sendMessage, lastMessage, readyState, getWebSocket } = useWebSocket(
getSocketUrl,
STATIC_OPTIONS
);
```
If `getSocketUrl` throws an error and `Options#retryOnError` is `true`, then `getSocketUrl` will be called at an interval consistent with the retry behavior defined by `Options#reconnectAttempts` and `Options#reconnectInterval`.
## API
### sendMessage
```ts
type sendMessage = (message: string, keep: boolean = true) => void;
```
The argument sent through sendMessage will be passed directly to WebSocket#`send`. `sendMessage` will be static, and thus can be passed down through children components without triggering prop changes. Messages sent before the WebSocket is open will be queued up and sent on connection. If you don't want to use messages queue for a particular message you should use a 'keep' parameter.
### sendJsonMessage
```ts
type sendJsonMessage = (message: any, keep: boolean = true) => void;
```
Message will first be passed through `JSON.stringify`.
### lastMessage
```ts
type lastMessage = WebSocketEventMap['message'];
```
Will be an unparsed `MessageEvent` received from the WebSocket.
### lastJsonMessage
```ts
type lastJsonMessage = any;
```
A `JSON.parse`d object from the `lastMessage`. If `lastMessage` is not a valid JSON string, `lastJsonMessage` will be an empty object. If `Options#disableJson` is `true`, `lastMessage` will not be automatically parsed, and `lastJsonMessage` will always be `null`.
### readyState
```ts
enum ReadyState {
UNINSTANTIATED = -1,
CONNECTING = 0,
OPEN = 1,
CLOSING = 2,
CLOSED = 3,
}
```
Will be an integer representing the `readyState` of the WebSocket. `-1` is not a valid WebSocket `readyState`, but instead indicates that the WebSocket has not been instantiated yet (either because the url is `null` or connect param is `false`)
### getWebSocket
```ts
type getWebSocket = () => WebSocketLike | Proxy<WebSocketLike>;
```
If the WebSocket is shared, calling this function will lazily instantiate a `Proxy` instance that wraps the underlying WebSocket. You can get and set properties on the return value that will directly interact with the WebSocket, however certain properties/methods are protected (cannot invoke `close` or `send`, and cannot redefine any of the event handlers like `onmessage`, `onclose`, `onopen` and `onerror`. An example of using this:
```js
const { sendMessage, lastMessage, readyState, getWebSocket } = useWebSocket(
'wss://echo.websocket.org',
{ share: true }
);
useEffect(() => {
console.log(getWebSocket().binaryType);
//=> 'blob'
//Change binaryType property of WebSocket
getWebSocket().binaryType = 'arraybuffer';
console.log(getWebSocket().binaryType);
//=> 'arraybuffer'
//Attempt to change event handler
getWebSocket().onmessage = console.log;
//=> A warning is logged to console: 'The WebSocket's event handlers should be defined through the options object passed into useWebSocket.'
//Attempt to change an immutable property
getWebSocket().url = 'www.google.com';
console.log(getWebSocket().url);
//=> 'wss://echo.websocket.org'
//Attempt to call webSocket#send
getWebSocket().send('Hello from WebSocket');
//=> No message is sent, and no error thrown (a no-op function was returned), but an error will be logged to console: 'Calling methods directly on the WebSocket is not supported at this moment. You must use the methods returned by useWebSocket.'
}, []);
```
If the WebSocket is not shared (via options), then the return value is the underlying WebSocket, and thus methods such as `close` and `send` can be accessed and used.
## Reconnecting
By default, `useWebSocket` will not attempt to reconnect to a WebSocket. This behavior can be modified through a few options. To attempt to reconnect on error events, set `Options#retryOnError` to `true`. Because `CloseEvent`s are less straight forward (e.g., was it triggered intentionally by the client or by something unexpected by the server restarting?), `Options#shouldReconnect` must be provided as a callback, with the socket `CloseEvent` as the first and only argument, and a return value of either `true` or `false`. If `true`, `useWebSocket` will attempt to reconnect up to a specified number of attempts (with a default of `20`) at a specified interval (with a default of `5000` (ms)). The option properties for attempts is `Options#reconnectAttempts` and the interval is `Options#reconnectInterval`. As an example:
```js
const didUnmount = useRef(false);
const [sendMessage, lastMessage, readyState] = useWebSocket(
'wss://echo.websocket.org',
{
shouldReconnect: (closeEvent) => {
/*
useWebSocket will handle unmounting for you, but this is an example of a
case in which you would not want it to automatically reconnect
*/
return didUnmount.current === false;
},
reconnectAttempts: 10,
reconnectInterval: 3000,
}
);
useEffect(() => {
return () => {
didUnmount.current = true;
};
}, []);
```
Alternatively, you can provide a function for `Options#reconnectInterval` that accepts as a parameter the nth last attempt and returns a number, which represents how long the next interval should be. This should enable a higher degree of control if you wish to employ more advanced reconnect strategies (such as [Exponential Backoff](https://en.wikipedia.org/wiki/Exponential_backoff)):
```js
const [sendMessage, lastMessage, readyState] = useWebSocket(
'wss://echo.websocket.org',
{
shouldReconnect: (closeEvent) => true,
reconnectAttempts: 10,
//attemptNumber will be 0 the first time it attempts to reconnect, so this equation results in a reconnect pattern of 1 second, 2 seconds, 4 seconds, 8 seconds, and then caps at 10 seconds until the maximum number of attempts is reached
reconnectInterval: (attemptNumber) =>
Math.min(Math.pow(2, attemptNumber) * 1000, 10000),
}
);
```
## Options
```ts
interface Options {
share?: boolean;
shouldReconnect?: (event: WebSocketEventMap['close']) => boolean;
reconnectInterval?: number | ((lastAttemptNumber: number) => number);
reconnectAttempts?: number;
filter?: (message: WebSocketEventMap['message']) => boolean;
disableJson?: boolean;
retryOnError?: boolean;
onOpen?: (event: WebSocketEventMap['open']) => void;
onClose?: (event: WebSocketEventMap['close']) => void;
onMessage?: (event: WebSocketEventMap['message']) => void;
onError?: (event: WebSocketEventMap['error']) => void;
onReconnectStop?: (numAttempted: number) => void;
fromSocketIO?: boolean;
queryParams?: {
[key: string]: string | number;
};
protocols?: string | string[];
eventSourceOptions?: EventSourceInit;
heartbeat?:
| boolean
| {
message?: 'ping' | 'pong' | string;
returnMessage?: 'ping' | 'pong' | string;
timeout?: number;
interval?: number;
};
}
```
### shouldReconnect
See section on [Reconnecting](#Reconnecting).
### reconnectInterval
Number of milliseconds to wait until it attempts to reconnect. Default is 5000. Can also be defined as a function that takes the last attemptCount and returns the amount of time for the next interval. See [Reconnecting](#Reconnecting) for an example of this being used.
### Event Handlers: Callback
Each of `Options#onMessage`, `Options#onError`, `Options#onClose`, and `Options#onOpen` will be called on the corresponding WebSocket event, if provided. Each will be passed the same event provided from the WebSocket.
### onReconnectStop
If provided in options, will be called when websocket exceeds reconnect limit, either as provided in the options or the default value of 20.
### share: Boolean
If set to `true`, a new WebSocket will not be instantiated if one for the same url has already been created for another component. Once all subscribing components have either unmounted or changed their target socket url, shared WebSockets will be closed and cleaned up. No other APIs should be affected by this.
### fromSocketIO: Boolean
SocketIO acts as a layer on top of the WebSocket protocol, and the required client-side implementation involves a few peculiarities. If you have a SocketIO back-end, or are converting a client-side application that uses the socketIO library, setting this to `true` might be enough to allow `useWebSocket` to work interchangeably. This is an experimental option as the SocketIO library might change its API at any time. This was tested with Socket IO `2.1.1`.
### queryParams: Object
Pass an object representing an arbitrary number of query parameters, which will be converted into stringified query params and appended to the WebSocket url.
```js
const queryParams = {
user_id: 1,
room_id: 5,
};
//<url>?user_id=1&room_id=5
```
### useSocketIO
SocketIO sends messages in a format that isn't JSON-parsable. One example is:
```
"42["Action",{"key":"value"}]"
```
An extension of this hook is available by importing `useSocketIO`:
```js
import { useSocketIO } from 'react-use-websocket';
//Same API in component
const { sendMessage, lastMessage, readyState } = useSocketIO(
'http://localhost:3000/'
);
```
It is important to note that `lastMessage` will not be a `MessageEvent`, but instead an object with two keys: `type` and `payload`.
### heartbeat
If the `heartbeat` option is set to `true` or has additional options, the library will send a 'ping' message to the server every `interval` milliseconds. If no response is received within `timeout` milliseconds, indicating a potential connection issue, the library will close the connection. You can customize the 'ping' message by changing the `message` property in the `heartbeat` object. If a `returnMessage` is defined, it will be ignored so that it won't be set as the `lastMessage`.
```js
const { sendMessage, lastMessage, readyState } = useWebSocket(
'ws://localhost:3000',
{
heartbeat: {
message: 'ping',
returnMessage: 'pong',
timeout: 60000, // 1 minute, if no response is received, the connection will be closed
interval: 25000, // every 25 seconds, a ping message will be sent
},
}
);
```
### filter: Callback
If a function is provided with the key `filter`, incoming messages will be passed through the function, and only if it returns `true` will the hook pass along the `lastMessage` and update your component.
Example:
```js
filter: (message) => {
// validate your message data
if (isPingMessage(message.data)) {
// do stuff or simply return false
updateHeartbeat()
return false
} else {
return true
}
},
```
The component will rerender every time the WebSocket receives a message that does not match your conditional in this case `isPingMessage`, if the condition is true, you can do some stuff, for this example that is updating the heartbeat time, but you could just avoid unnecessary renders simply returning `false`.
### disableJson: Boolean
If `true`, `lastMessage` will not be automatically parsed and returned as `lastJsonMessage`, in which case `lastJsonMessage` will always be `null`.
## useEventSource
```js
import { useEventSource } from 'react-use-websocket';
//Only the following three properties are provided
const { lastEvent, getEventSource, readyState } = useEventSource(
'http://localhost:3000/',
{
withCredentials: true,
events: {
message: (messageEvent) => {
console.log('This has type "message": ', messageEvent);
},
update: (messageEvent) => {
console.log('This has type "update": ', messageEvent);
},
},
}
);
```
If used, an [EventSource](https://developer.mozilla.org/en-US/docs/Web/API/EventSource) will be instantiated instead of a WebSocket. Although it shares a very similar API with a WebSocket, there are a few differences:
- There is no onclose event, nor is there an event for readyState changes -- as such, this library can only 'track' the first two readyStates: CONNECTING (0) and OPEN (1). The `EventSource` will close when your component unmounts.
- Currently, the library will set the readyState to CLOSED on the underlying `EventSource`'s onerror callback, and will also trigger `Options#onClose`, if provided. In this case, reconnect logic is driven by `Options#retryOnError`, instead of `Options#shouldReconnect`.
- There is no 'CLOSING' readyState for `EventSource`, and as such, the CLOSED readyState is `2` for an `EventSource`, whereas it is `3` for a WebSocket. For purposes of internal consistency, the `readyState` returned by `useWebSocket` will follow the `WebSocket` enumeration and use `3` for the CLOSED event for both instance types.
- `getEventSource` will return the underlying EventSource, even if `Options#share` is used -- as opposed to the `WebSocket` equivalent which returns a `Proxy`.
- There is no concept of sending messages from the client, and as such `sendMessage` will not be provided.
### Reset Global State
There are some cases when the global state of the library won't reset with the page. The main behavior relies on the fact that a single page application operates only in one window, but some scenarios allow us to make a new window via `window.open` and inject code there. In that case, child window will be closed, but the global state of the library remains the same in the main window. This happens because react does not finish components lifecycle on window close.
To avoid troubles with the new initialization of components related to the same URL, you can reset the global state for a specific connection based on your own logic.
```js
import React, { useEffect } from 'react';
import { resetGlobalState } from 'react-use-websocket';
// insside second window opened via window.open
export const ChildWindow = () => {
useEffect(() => {
window.addEventListener('unload', () => {
resetGlobalState('wss://echo.websocket.org');
});
}, []);
};
```
@@ -0,0 +1,7 @@
"use strict";
/**
* Copyright (c) 2017, Daniel Imms (MIT License).
* Copyright (c) 2018, Microsoft Corporation (MIT License).
*/
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=types.js.map
@@ -0,0 +1,3 @@
export { Listeners } from './Listeners';
export { getEventListenerTarget } from './getEventListenerTarget';
export { hasExceededDistance } from './hasExceededDistance';
@@ -0,0 +1,8 @@
/// <reference types="node" />
import type * as scandir from '@nodelib/fs.scandir';
export declare type Entry = scandir.Entry;
export declare type Errno = NodeJS.ErrnoException;
export interface QueueItem {
directory: string;
base?: string;
}
@@ -0,0 +1,3 @@
type MessageIds = 'suggestRemove' | 'suggestSatisfies' | 'unnecessaryTypeConversion';
declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<MessageIds, [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>;
export default _default;
@@ -0,0 +1,5 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.classMetadataReflectKey = void 0;
exports.classMetadataReflectKey = '@inversifyjs/core/classMetadataReflectKey';
//# sourceMappingURL=classMetadataReflectKey.js.map
@@ -0,0 +1,392 @@
var $6E71I$reactariautils = require("@react-aria/utils");
function $parcel$export(e, n, v, s) {
Object.defineProperty(e, n, {get: v, set: s, enumerable: true, configurable: true});
}
$parcel$export(module.exports, "calculatePosition", () => $5935ba4d7da2c103$export$b3ceb0cbf1056d98);
$parcel$export(module.exports, "getRect", () => $5935ba4d7da2c103$export$4b834cebd9e5cebe);
/*
* Copyright 2020 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
const $5935ba4d7da2c103$var$AXIS = {
top: 'top',
bottom: 'top',
left: 'left',
right: 'left'
};
const $5935ba4d7da2c103$var$FLIPPED_DIRECTION = {
top: 'bottom',
bottom: 'top',
left: 'right',
right: 'left'
};
const $5935ba4d7da2c103$var$CROSS_AXIS = {
top: 'left',
left: 'top'
};
const $5935ba4d7da2c103$var$AXIS_SIZE = {
top: 'height',
left: 'width'
};
const $5935ba4d7da2c103$var$TOTAL_SIZE = {
width: 'totalWidth',
height: 'totalHeight'
};
const $5935ba4d7da2c103$var$PARSED_PLACEMENT_CACHE = {};
let $5935ba4d7da2c103$var$visualViewport = typeof document !== 'undefined' ? window.visualViewport : null;
function $5935ba4d7da2c103$var$getContainerDimensions(containerNode) {
let width = 0, height = 0, totalWidth = 0, totalHeight = 0, top = 0, left = 0;
let scroll = {};
var _visualViewport_scale;
let isPinchZoomedIn = ((_visualViewport_scale = $5935ba4d7da2c103$var$visualViewport === null || $5935ba4d7da2c103$var$visualViewport === void 0 ? void 0 : $5935ba4d7da2c103$var$visualViewport.scale) !== null && _visualViewport_scale !== void 0 ? _visualViewport_scale : 1) > 1;
if (containerNode.tagName === 'BODY') {
let documentElement = document.documentElement;
totalWidth = documentElement.clientWidth;
totalHeight = documentElement.clientHeight;
var _visualViewport_width;
width = (_visualViewport_width = $5935ba4d7da2c103$var$visualViewport === null || $5935ba4d7da2c103$var$visualViewport === void 0 ? void 0 : $5935ba4d7da2c103$var$visualViewport.width) !== null && _visualViewport_width !== void 0 ? _visualViewport_width : totalWidth;
var _visualViewport_height;
height = (_visualViewport_height = $5935ba4d7da2c103$var$visualViewport === null || $5935ba4d7da2c103$var$visualViewport === void 0 ? void 0 : $5935ba4d7da2c103$var$visualViewport.height) !== null && _visualViewport_height !== void 0 ? _visualViewport_height : totalHeight;
scroll.top = documentElement.scrollTop || containerNode.scrollTop;
scroll.left = documentElement.scrollLeft || containerNode.scrollLeft;
// The goal of the below is to get a top/left value that represents the top/left of the visual viewport with
// respect to the layout viewport origin. This combined with the scrollTop/scrollLeft will allow us to calculate
// coordinates/values with respect to the visual viewport or with respect to the layout viewport.
if ($5935ba4d7da2c103$var$visualViewport) {
top = $5935ba4d7da2c103$var$visualViewport.offsetTop;
left = $5935ba4d7da2c103$var$visualViewport.offsetLeft;
}
} else {
({ width: width, height: height, top: top, left: left } = $5935ba4d7da2c103$var$getOffset(containerNode, false));
scroll.top = containerNode.scrollTop;
scroll.left = containerNode.scrollLeft;
totalWidth = width;
totalHeight = height;
}
if ((0, $6E71I$reactariautils.isWebKit)() && (containerNode.tagName === 'BODY' || containerNode.tagName === 'HTML') && isPinchZoomedIn) {
// Safari will report a non-zero scrollTop/Left for the non-scrolling body/HTML element when pinch zoomed in unlike other browsers.
// Set to zero for parity calculations so we get consistent positioning of overlays across all browsers.
// Also switch to visualViewport.pageTop/pageLeft so that we still accomodate for scroll positioning for body/HTML elements that are actually scrollable
// before pinch zoom happens
scroll.top = 0;
scroll.left = 0;
var _visualViewport_pageTop;
top = (_visualViewport_pageTop = $5935ba4d7da2c103$var$visualViewport === null || $5935ba4d7da2c103$var$visualViewport === void 0 ? void 0 : $5935ba4d7da2c103$var$visualViewport.pageTop) !== null && _visualViewport_pageTop !== void 0 ? _visualViewport_pageTop : 0;
var _visualViewport_pageLeft;
left = (_visualViewport_pageLeft = $5935ba4d7da2c103$var$visualViewport === null || $5935ba4d7da2c103$var$visualViewport === void 0 ? void 0 : $5935ba4d7da2c103$var$visualViewport.pageLeft) !== null && _visualViewport_pageLeft !== void 0 ? _visualViewport_pageLeft : 0;
}
return {
width: width,
height: height,
totalWidth: totalWidth,
totalHeight: totalHeight,
scroll: scroll,
top: top,
left: left
};
}
function $5935ba4d7da2c103$var$getScroll(node) {
return {
top: node.scrollTop,
left: node.scrollLeft,
width: node.scrollWidth,
height: node.scrollHeight
};
}
// Determines the amount of space required when moving the overlay to ensure it remains in the boundary
function $5935ba4d7da2c103$var$getDelta(axis, offset, size, // The dimensions of the boundary element that the popover is
// positioned within (most of the time this is the <body>).
boundaryDimensions, // The dimensions of the containing block element that the popover is
// positioned relative to (e.g. parent with position: relative).
// Usually this is the same as the boundary element, but if the popover
// is portaled somewhere other than the body and has an ancestor with
// position: relative/absolute, it will be different.
containerDimensions, padding, containerOffsetWithBoundary) {
var _containerDimensions_scroll_axis;
let containerScroll = (_containerDimensions_scroll_axis = containerDimensions.scroll[axis]) !== null && _containerDimensions_scroll_axis !== void 0 ? _containerDimensions_scroll_axis : 0;
// The height/width of the boundary. Matches the axis along which we are adjusting the overlay position
let boundarySize = boundaryDimensions[$5935ba4d7da2c103$var$AXIS_SIZE[axis]];
// Calculate the edges of the boundary (accomodating for the boundary padding) and the edges of the overlay.
// Note that these values are with respect to the visual viewport (aka 0,0 is the top left of the viewport)
let boundaryStartEdge = boundaryDimensions.scroll[$5935ba4d7da2c103$var$AXIS[axis]] + padding;
let boundaryEndEdge = boundarySize + boundaryDimensions.scroll[$5935ba4d7da2c103$var$AXIS[axis]] - padding;
let startEdgeOffset = offset - containerScroll + containerOffsetWithBoundary[axis] - boundaryDimensions[$5935ba4d7da2c103$var$AXIS[axis]];
let endEdgeOffset = offset - containerScroll + size + containerOffsetWithBoundary[axis] - boundaryDimensions[$5935ba4d7da2c103$var$AXIS[axis]];
// If any of the overlay edges falls outside of the boundary, shift the overlay the required amount to align one of the overlay's
// edges with the closest boundary edge.
if (startEdgeOffset < boundaryStartEdge) return boundaryStartEdge - startEdgeOffset;
else if (endEdgeOffset > boundaryEndEdge) return Math.max(boundaryEndEdge - endEdgeOffset, boundaryStartEdge - startEdgeOffset);
else return 0;
}
function $5935ba4d7da2c103$var$getMargins(node) {
let style = window.getComputedStyle(node);
return {
top: parseInt(style.marginTop, 10) || 0,
bottom: parseInt(style.marginBottom, 10) || 0,
left: parseInt(style.marginLeft, 10) || 0,
right: parseInt(style.marginRight, 10) || 0
};
}
function $5935ba4d7da2c103$var$parsePlacement(input) {
if ($5935ba4d7da2c103$var$PARSED_PLACEMENT_CACHE[input]) return $5935ba4d7da2c103$var$PARSED_PLACEMENT_CACHE[input];
let [placement, crossPlacement] = input.split(' ');
let axis = $5935ba4d7da2c103$var$AXIS[placement] || 'right';
let crossAxis = $5935ba4d7da2c103$var$CROSS_AXIS[axis];
if (!$5935ba4d7da2c103$var$AXIS[crossPlacement]) crossPlacement = 'center';
let size = $5935ba4d7da2c103$var$AXIS_SIZE[axis];
let crossSize = $5935ba4d7da2c103$var$AXIS_SIZE[crossAxis];
$5935ba4d7da2c103$var$PARSED_PLACEMENT_CACHE[input] = {
placement: placement,
crossPlacement: crossPlacement,
axis: axis,
crossAxis: crossAxis,
size: size,
crossSize: crossSize
};
return $5935ba4d7da2c103$var$PARSED_PLACEMENT_CACHE[input];
}
function $5935ba4d7da2c103$var$computePosition(childOffset, boundaryDimensions, overlaySize, placementInfo, offset, crossOffset, containerOffsetWithBoundary, isContainerPositioned, arrowSize, arrowBoundaryOffset) {
let { placement: placement, crossPlacement: crossPlacement, axis: axis, crossAxis: crossAxis, size: size, crossSize: crossSize } = placementInfo;
let position = {};
var _childOffset_crossAxis;
// button position
position[crossAxis] = (_childOffset_crossAxis = childOffset[crossAxis]) !== null && _childOffset_crossAxis !== void 0 ? _childOffset_crossAxis : 0;
var _childOffset_crossSize, _overlaySize_crossSize, _childOffset_crossSize1, _overlaySize_crossSize1;
if (crossPlacement === 'center') // + (button size / 2) - (overlay size / 2)
// at this point the overlay center should match the button center
position[crossAxis] += (((_childOffset_crossSize = childOffset[crossSize]) !== null && _childOffset_crossSize !== void 0 ? _childOffset_crossSize : 0) - ((_overlaySize_crossSize = overlaySize[crossSize]) !== null && _overlaySize_crossSize !== void 0 ? _overlaySize_crossSize : 0)) / 2;
else if (crossPlacement !== crossAxis) // + (button size) - (overlay size)
// at this point the overlay bottom should match the button bottom
position[crossAxis] += ((_childOffset_crossSize1 = childOffset[crossSize]) !== null && _childOffset_crossSize1 !== void 0 ? _childOffset_crossSize1 : 0) - ((_overlaySize_crossSize1 = overlaySize[crossSize]) !== null && _overlaySize_crossSize1 !== void 0 ? _overlaySize_crossSize1 : 0);
/* else {
the overlay top should match the button top
} */
position[crossAxis] += crossOffset;
// overlay top overlapping arrow with button bottom
const minPosition = childOffset[crossAxis] - overlaySize[crossSize] + arrowSize + arrowBoundaryOffset;
// overlay bottom overlapping arrow with button top
const maxPosition = childOffset[crossAxis] + childOffset[crossSize] - arrowSize - arrowBoundaryOffset;
position[crossAxis] = (0, $6E71I$reactariautils.clamp)(position[crossAxis], minPosition, maxPosition);
// Floor these so the position isn't placed on a partial pixel, only whole pixels. Shouldn't matter if it was floored or ceiled, so chose one.
if (placement === axis) {
// If the container is positioned (non-static), then we use the container's actual
// height, as `bottom` will be relative to this height. But if the container is static,
// then it can only be the `document.body`, and `bottom` will be relative to _its_
// container, which should be as large as boundaryDimensions.
const containerHeight = isContainerPositioned ? containerOffsetWithBoundary[size] : boundaryDimensions[$5935ba4d7da2c103$var$TOTAL_SIZE[size]];
position[$5935ba4d7da2c103$var$FLIPPED_DIRECTION[axis]] = Math.floor(containerHeight - childOffset[axis] + offset);
} else position[axis] = Math.floor(childOffset[axis] + childOffset[size] + offset);
return position;
}
function $5935ba4d7da2c103$var$getMaxHeight(position, boundaryDimensions, containerOffsetWithBoundary, isContainerPositioned, margins, padding, overlayHeight, heightGrowthDirection) {
const containerHeight = isContainerPositioned ? containerOffsetWithBoundary.height : boundaryDimensions[$5935ba4d7da2c103$var$TOTAL_SIZE.height];
var _position_bottom;
// For cases where position is set via "bottom" instead of "top", we need to calculate the true overlay top with respect to the boundary. Reverse calculate this with the same method
// used in computePosition.
let overlayTop = position.top != null ? containerOffsetWithBoundary.top + position.top : containerOffsetWithBoundary.top + (containerHeight - ((_position_bottom = position.bottom) !== null && _position_bottom !== void 0 ? _position_bottom : 0) - overlayHeight);
var _boundaryDimensions_scroll_top, _margins_top, _margins_bottom, _boundaryDimensions_scroll_top1, _margins_top1, _margins_bottom1;
let maxHeight = heightGrowthDirection !== 'top' ? // We want the distance between the top of the overlay to the bottom of the boundary
Math.max(0, boundaryDimensions.height + boundaryDimensions.top + ((_boundaryDimensions_scroll_top = boundaryDimensions.scroll.top) !== null && _boundaryDimensions_scroll_top !== void 0 ? _boundaryDimensions_scroll_top : 0) - overlayTop // this is the top of the overlay
- (((_margins_top = margins.top) !== null && _margins_top !== void 0 ? _margins_top : 0) + ((_margins_bottom = margins.bottom) !== null && _margins_bottom !== void 0 ? _margins_bottom : 0) + padding // save additional space for margin and padding
)) : Math.max(0, overlayTop + overlayHeight // this is the bottom of the overlay
- (boundaryDimensions.top + ((_boundaryDimensions_scroll_top1 = boundaryDimensions.scroll.top) !== null && _boundaryDimensions_scroll_top1 !== void 0 ? _boundaryDimensions_scroll_top1 : 0) // this is the top of the boundary
) - (((_margins_top1 = margins.top) !== null && _margins_top1 !== void 0 ? _margins_top1 : 0) + ((_margins_bottom1 = margins.bottom) !== null && _margins_bottom1 !== void 0 ? _margins_bottom1 : 0) + padding // save additional space for margin and padding
));
return Math.min(boundaryDimensions.height - padding * 2, maxHeight);
}
function $5935ba4d7da2c103$var$getAvailableSpace(boundaryDimensions, containerOffsetWithBoundary, childOffset, margins, padding, placementInfo) {
let { placement: placement, axis: axis, size: size } = placementInfo;
var _boundaryDimensions_scroll_axis, _margins_axis;
if (placement === axis) return Math.max(0, childOffset[axis] - boundaryDimensions[axis] - ((_boundaryDimensions_scroll_axis = boundaryDimensions.scroll[axis]) !== null && _boundaryDimensions_scroll_axis !== void 0 ? _boundaryDimensions_scroll_axis : 0) + containerOffsetWithBoundary[axis] - ((_margins_axis = margins[axis]) !== null && _margins_axis !== void 0 ? _margins_axis : 0) - margins[$5935ba4d7da2c103$var$FLIPPED_DIRECTION[axis]] - padding);
var _margins_axis1;
return Math.max(0, boundaryDimensions[size] + boundaryDimensions[axis] + boundaryDimensions.scroll[axis] - containerOffsetWithBoundary[axis] - childOffset[axis] - childOffset[size] - ((_margins_axis1 = margins[axis]) !== null && _margins_axis1 !== void 0 ? _margins_axis1 : 0) - margins[$5935ba4d7da2c103$var$FLIPPED_DIRECTION[axis]] - padding);
}
function $5935ba4d7da2c103$export$6839422d1f33cee9(placementInput, childOffset, overlaySize, scrollSize, margins, padding, flip, boundaryDimensions, containerDimensions, containerOffsetWithBoundary, offset, crossOffset, isContainerPositioned, userSetMaxHeight, arrowSize, arrowBoundaryOffset) {
let placementInfo = $5935ba4d7da2c103$var$parsePlacement(placementInput);
let { size: size, crossAxis: crossAxis, crossSize: crossSize, placement: placement, crossPlacement: crossPlacement } = placementInfo;
let position = $5935ba4d7da2c103$var$computePosition(childOffset, boundaryDimensions, overlaySize, placementInfo, offset, crossOffset, containerOffsetWithBoundary, isContainerPositioned, arrowSize, arrowBoundaryOffset);
let normalizedOffset = offset;
let space = $5935ba4d7da2c103$var$getAvailableSpace(boundaryDimensions, containerOffsetWithBoundary, childOffset, margins, padding + offset, placementInfo);
// Check if the scroll size of the overlay is greater than the available space to determine if we need to flip
if (flip && scrollSize[size] > space) {
let flippedPlacementInfo = $5935ba4d7da2c103$var$parsePlacement(`${$5935ba4d7da2c103$var$FLIPPED_DIRECTION[placement]} ${crossPlacement}`);
let flippedPosition = $5935ba4d7da2c103$var$computePosition(childOffset, boundaryDimensions, overlaySize, flippedPlacementInfo, offset, crossOffset, containerOffsetWithBoundary, isContainerPositioned, arrowSize, arrowBoundaryOffset);
let flippedSpace = $5935ba4d7da2c103$var$getAvailableSpace(boundaryDimensions, containerOffsetWithBoundary, childOffset, margins, padding + offset, flippedPlacementInfo);
// If the available space for the flipped position is greater than the original available space, flip.
if (flippedSpace > space) {
placementInfo = flippedPlacementInfo;
position = flippedPosition;
normalizedOffset = offset;
}
}
// Determine the direction the height of the overlay can grow so that we can choose how to calculate the max height
let heightGrowthDirection = 'bottom';
if (placementInfo.axis === 'top') {
if (placementInfo.placement === 'top') heightGrowthDirection = 'top';
else if (placementInfo.placement === 'bottom') heightGrowthDirection = 'bottom';
} else if (placementInfo.crossAxis === 'top') {
if (placementInfo.crossPlacement === 'top') heightGrowthDirection = 'bottom';
else if (placementInfo.crossPlacement === 'bottom') heightGrowthDirection = 'top';
}
let delta = $5935ba4d7da2c103$var$getDelta(crossAxis, position[crossAxis], overlaySize[crossSize], boundaryDimensions, containerDimensions, padding, containerOffsetWithBoundary);
position[crossAxis] += delta;
let maxHeight = $5935ba4d7da2c103$var$getMaxHeight(position, boundaryDimensions, containerOffsetWithBoundary, isContainerPositioned, margins, padding, overlaySize.height, heightGrowthDirection);
if (userSetMaxHeight && userSetMaxHeight < maxHeight) maxHeight = userSetMaxHeight;
overlaySize.height = Math.min(overlaySize.height, maxHeight);
position = $5935ba4d7da2c103$var$computePosition(childOffset, boundaryDimensions, overlaySize, placementInfo, normalizedOffset, crossOffset, containerOffsetWithBoundary, isContainerPositioned, arrowSize, arrowBoundaryOffset);
delta = $5935ba4d7da2c103$var$getDelta(crossAxis, position[crossAxis], overlaySize[crossSize], boundaryDimensions, containerDimensions, padding, containerOffsetWithBoundary);
position[crossAxis] += delta;
let arrowPosition = {};
// All values are transformed so that 0 is at the top/left of the overlay depending on the orientation
// Prefer the arrow being in the center of the trigger/overlay anchor element
// childOffset[crossAxis] + .5 * childOffset[crossSize] = absolute position with respect to the trigger's coordinate system that would place the arrow in the center of the trigger
// position[crossAxis] - margins[AXIS[crossAxis]] = value use to transform the position to a value with respect to the overlay's coordinate system. A child element's (aka arrow) position absolute's "0"
// is positioned after the margin of its parent (aka overlay) so we need to subtract it to get the proper coordinate transform
let origin = childOffset[crossAxis] - position[crossAxis] - margins[$5935ba4d7da2c103$var$AXIS[crossAxis]];
let preferredArrowPosition = origin + .5 * childOffset[crossSize];
// Min/Max position limits for the arrow with respect to the overlay
const arrowMinPosition = arrowSize / 2 + arrowBoundaryOffset;
var _margins_left, _margins_right, _margins_top, _margins_bottom;
// overlaySize[crossSize] - margins = true size of the overlay
const overlayMargin = $5935ba4d7da2c103$var$AXIS[crossAxis] === 'left' ? ((_margins_left = margins.left) !== null && _margins_left !== void 0 ? _margins_left : 0) + ((_margins_right = margins.right) !== null && _margins_right !== void 0 ? _margins_right : 0) : ((_margins_top = margins.top) !== null && _margins_top !== void 0 ? _margins_top : 0) + ((_margins_bottom = margins.bottom) !== null && _margins_bottom !== void 0 ? _margins_bottom : 0);
const arrowMaxPosition = overlaySize[crossSize] - overlayMargin - arrowSize / 2 - arrowBoundaryOffset;
// Min/Max position limits for the arrow with respect to the trigger/overlay anchor element
// Same margin accomodation done here as well as for the preferredArrowPosition
const arrowOverlappingChildMinEdge = childOffset[crossAxis] + arrowSize / 2 - (position[crossAxis] + margins[$5935ba4d7da2c103$var$AXIS[crossAxis]]);
const arrowOverlappingChildMaxEdge = childOffset[crossAxis] + childOffset[crossSize] - arrowSize / 2 - (position[crossAxis] + margins[$5935ba4d7da2c103$var$AXIS[crossAxis]]);
// Clamp the arrow positioning so that it always is within the bounds of the anchor and the overlay
const arrowPositionOverlappingChild = (0, $6E71I$reactariautils.clamp)(preferredArrowPosition, arrowOverlappingChildMinEdge, arrowOverlappingChildMaxEdge);
arrowPosition[crossAxis] = (0, $6E71I$reactariautils.clamp)(arrowPositionOverlappingChild, arrowMinPosition, arrowMaxPosition);
// If there is an arrow, use that as the origin so that animations are smooth.
// Otherwise use the target edge.
({ placement: placement, crossPlacement: crossPlacement } = placementInfo);
if (arrowSize) origin = arrowPosition[crossAxis];
else if (crossPlacement === 'right') origin += childOffset[crossSize];
else if (crossPlacement === 'center') origin += childOffset[crossSize] / 2;
let crossOrigin = placement === 'left' || placement === 'top' ? overlaySize[size] : 0;
let triggerAnchorPoint = {
x: placement === 'top' || placement === 'bottom' ? origin : crossOrigin,
y: placement === 'left' || placement === 'right' ? origin : crossOrigin
};
return {
position: position,
maxHeight: maxHeight,
arrowOffsetLeft: arrowPosition.left,
arrowOffsetTop: arrowPosition.top,
placement: placement,
triggerAnchorPoint: triggerAnchorPoint
};
}
function $5935ba4d7da2c103$export$b3ceb0cbf1056d98(opts) {
let { placement: placement, targetNode: targetNode, overlayNode: overlayNode, scrollNode: scrollNode, padding: padding, shouldFlip: shouldFlip, boundaryElement: boundaryElement, offset: offset, crossOffset: crossOffset, maxHeight: maxHeight, arrowSize: arrowSize = 0, arrowBoundaryOffset: arrowBoundaryOffset = 0 } = opts;
let container = overlayNode instanceof HTMLElement ? $5935ba4d7da2c103$var$getContainingBlock(overlayNode) : document.documentElement;
let isViewportContainer = container === document.documentElement;
const containerPositionStyle = window.getComputedStyle(container).position;
let isContainerPositioned = !!containerPositionStyle && containerPositionStyle !== 'static';
let childOffset = isViewportContainer ? $5935ba4d7da2c103$var$getOffset(targetNode, false) : $5935ba4d7da2c103$var$getPosition(targetNode, container, false);
if (!isViewportContainer) {
let { marginTop: marginTop, marginLeft: marginLeft } = window.getComputedStyle(targetNode);
childOffset.top += parseInt(marginTop, 10) || 0;
childOffset.left += parseInt(marginLeft, 10) || 0;
}
let overlaySize = $5935ba4d7da2c103$var$getOffset(overlayNode, true);
let margins = $5935ba4d7da2c103$var$getMargins(overlayNode);
var _margins_left, _margins_right;
overlaySize.width += ((_margins_left = margins.left) !== null && _margins_left !== void 0 ? _margins_left : 0) + ((_margins_right = margins.right) !== null && _margins_right !== void 0 ? _margins_right : 0);
var _margins_top, _margins_bottom;
overlaySize.height += ((_margins_top = margins.top) !== null && _margins_top !== void 0 ? _margins_top : 0) + ((_margins_bottom = margins.bottom) !== null && _margins_bottom !== void 0 ? _margins_bottom : 0);
let scrollSize = $5935ba4d7da2c103$var$getScroll(scrollNode);
let boundaryDimensions = $5935ba4d7da2c103$var$getContainerDimensions(boundaryElement);
let containerDimensions = $5935ba4d7da2c103$var$getContainerDimensions(container);
// If the container is the HTML element wrapping the body element, the retrieved scrollTop/scrollLeft will be equal to the
// body element's scroll. Set the container's scroll values to 0 since the overlay's edge position value in getDelta don't then need to be further offset
// by the container scroll since they are essentially the same containing element and thus in the same coordinate system
let containerOffsetWithBoundary = boundaryElement.tagName === 'BODY' ? $5935ba4d7da2c103$var$getOffset(container, false) : $5935ba4d7da2c103$var$getPosition(container, boundaryElement, false);
if (container.tagName === 'HTML' && boundaryElement.tagName === 'BODY') {
containerDimensions.scroll.top = 0;
containerDimensions.scroll.left = 0;
}
return $5935ba4d7da2c103$export$6839422d1f33cee9(placement, childOffset, overlaySize, scrollSize, margins, padding, shouldFlip, boundaryDimensions, containerDimensions, containerOffsetWithBoundary, offset, crossOffset, isContainerPositioned, maxHeight, arrowSize, arrowBoundaryOffset);
}
function $5935ba4d7da2c103$export$4b834cebd9e5cebe(node, ignoreScale) {
let { top: top, left: left, width: width, height: height } = node.getBoundingClientRect();
// Use offsetWidth and offsetHeight if this is an HTML element, so that
// the size is not affected by scale transforms.
if (ignoreScale && node instanceof node.ownerDocument.defaultView.HTMLElement) {
width = node.offsetWidth;
height = node.offsetHeight;
}
return {
top: top,
left: left,
width: width,
height: height
};
}
function $5935ba4d7da2c103$var$getOffset(node, ignoreScale) {
let { top: top, left: left, width: width, height: height } = $5935ba4d7da2c103$export$4b834cebd9e5cebe(node, ignoreScale);
let { scrollTop: scrollTop, scrollLeft: scrollLeft, clientTop: clientTop, clientLeft: clientLeft } = document.documentElement;
return {
top: top + scrollTop - clientTop,
left: left + scrollLeft - clientLeft,
width: width,
height: height
};
}
function $5935ba4d7da2c103$var$getPosition(node, parent, ignoreScale) {
let style = window.getComputedStyle(node);
let offset;
if (style.position === 'fixed') offset = $5935ba4d7da2c103$export$4b834cebd9e5cebe(node, ignoreScale);
else {
offset = $5935ba4d7da2c103$var$getOffset(node, ignoreScale);
let parentOffset = $5935ba4d7da2c103$var$getOffset(parent, ignoreScale);
let parentStyle = window.getComputedStyle(parent);
parentOffset.top += (parseInt(parentStyle.borderTopWidth, 10) || 0) - parent.scrollTop;
parentOffset.left += (parseInt(parentStyle.borderLeftWidth, 10) || 0) - parent.scrollLeft;
offset.top -= parentOffset.top;
offset.left -= parentOffset.left;
}
offset.top -= parseInt(style.marginTop, 10) || 0;
offset.left -= parseInt(style.marginLeft, 10) || 0;
return offset;
}
// Returns the containing block of an element, which is the element that
// this element will be positioned relative to.
// https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block
function $5935ba4d7da2c103$var$getContainingBlock(node) {
// The offsetParent of an element in most cases equals the containing block.
// https://w3c.github.io/csswg-drafts/cssom-view/#dom-htmlelement-offsetparent
let offsetParent = node.offsetParent;
// The offsetParent algorithm terminates at the document body,
// even if the body is not a containing block. Double check that
// and use the documentElement if so.
if (offsetParent && offsetParent === document.body && window.getComputedStyle(offsetParent).position === 'static' && !$5935ba4d7da2c103$var$isContainingBlock(offsetParent)) offsetParent = document.documentElement;
// TODO(later): handle table elements?
// The offsetParent can be null if the element has position: fixed, or a few other cases.
// We have to walk up the tree manually in this case because fixed positioned elements
// are still positioned relative to their containing block, which is not always the viewport.
if (offsetParent == null) {
offsetParent = node.parentElement;
while(offsetParent && !$5935ba4d7da2c103$var$isContainingBlock(offsetParent))offsetParent = offsetParent.parentElement;
}
// Fall back to the viewport.
return offsetParent || document.documentElement;
}
// https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block
function $5935ba4d7da2c103$var$isContainingBlock(node) {
let style = window.getComputedStyle(node);
return style.transform !== 'none' || /transform|perspective/.test(style.willChange) || style.filter !== 'none' || style.contain === 'paint' || 'backdropFilter' in style && style.backdropFilter !== 'none' || 'WebkitBackdropFilter' in style && style.WebkitBackdropFilter !== 'none';
}
//# sourceMappingURL=calculatePosition.main.js.map
@@ -0,0 +1,38 @@
import {values} from 'micromark-util-symbol'
/**
* Normalize an identifier (as found in references, definitions).
*
* Collapses markdown whitespace, trim, and then lower- and uppercase.
*
* Some characters are considered “uppercase”, such as U+03F4 (`ϴ`), but if their
* lowercase counterpart (U+03B8 (`θ`)) is uppercased will result in a different
* uppercase character (U+0398 (`Θ`)).
* So, to get a canonical form, we perform both lower- and uppercase.
*
* Using uppercase last makes sure keys will never interact with default
* prototypal values (such as `constructor`): nothing in the prototype of
* `Object` is uppercase.
*
* @param {string} value
* Identifier to normalize.
* @returns {string}
* Normalized identifier.
*/
export function normalizeIdentifier(value) {
return (
value
// Collapse markdown whitespace.
.replace(/[\t\n\r ]+/g, values.space)
// Trim.
.replace(/^ | $/g, '')
// Some characters are considered “uppercase”, but if their lowercase
// counterpart is uppercased will result in a different uppercase
// character.
// Hence, to get that form, we perform both lower- and uppercase.
// Upper case makes sure keys will not interact with default prototypal
// methods: no method is uppercase.
.toLowerCase()
.toUpperCase()
)
}
@@ -0,0 +1,17 @@
import {
useSpacer
} from "./chunk-BRFD4NXM.mjs";
// src/spacer.tsx
import { forwardRef } from "@heroui/system-rsc";
import { jsx } from "react/jsx-runtime";
var Spacer = forwardRef((props, ref) => {
const { Component, getSpacerProps } = useSpacer({ ...props });
return /* @__PURE__ */ jsx(Component, { ref, ...getSpacerProps() });
});
Spacer.displayName = "HeroUI.Spacer";
var spacer_default = Spacer;
export {
spacer_default
};
@@ -0,0 +1,7 @@
import {
getMargin
} from "./chunk-FDFRQJ7U.mjs";
import "./chunk-UYSIEMEK.mjs";
export {
getMargin
};
@@ -0,0 +1,3 @@
declare function hasToStringTagShams(): boolean;
export = hasToStringTagShams;
@@ -0,0 +1,477 @@
// @ts-self-types="./retrier.d.ts"
/**
* @fileoverview A utility for retrying failed async method calls.
*/
/* global setTimeout, clearTimeout */
//-----------------------------------------------------------------------------
// Constants
//-----------------------------------------------------------------------------
const MAX_TASK_TIMEOUT = 60000;
const MAX_TASK_DELAY = 100;
const MAX_CONCURRENCY = 1000;
//-----------------------------------------------------------------------------
// Helpers
//-----------------------------------------------------------------------------
/**
* Logs a message to the console if the DEBUG environment variable is set.
* @param {string} message The message to log.
* @returns {void}
*/
function debug(message) {
if (globalThis?.process?.env.DEBUG === "@hwc/retry") {
console.debug(message);
}
}
/*
* The following logic has been extracted from graceful-fs.
*
* The ISC License
*
* Copyright (c) 2011-2023 Isaac Z. Schlueter, Ben Noordhuis, and Contributors
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
* IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/**
* Checks if it is time to retry a task based on the timestamp and last attempt time.
* @param {RetryTask} task The task to check.
* @param {number} maxDelay The maximum delay for the queue.
* @returns {boolean} true if it is time to retry, false otherwise.
*/
function isTimeToRetry(task, maxDelay) {
const timeSinceLastAttempt = Date.now() - task.lastAttempt;
const timeSinceStart = Math.max(task.lastAttempt - task.timestamp, 1);
const desiredDelay = Math.min(timeSinceStart * 1.2, maxDelay);
return timeSinceLastAttempt >= desiredDelay;
}
/**
* Checks if it is time to bail out based on the given timestamp.
* @param {RetryTask} task The task to check.
* @param {number} timeout The timeout for the queue.
* @returns {boolean} true if it is time to bail, false otherwise.
*/
function isTimeToBail(task, timeout) {
return task.age > timeout;
}
/**
* Creates a new promise with resolve and reject functions.
* @returns {{promise:Promise<any>, resolve:(value:any) => any, reject: (value:any) => any}} A new promise.
*/
function createPromise() {
if (Promise.withResolvers) {
return Promise.withResolvers();
}
let resolve, reject;
const promise = new Promise((res, rej) => {
resolve = res;
reject = rej;
});
if (resolve === undefined || reject === undefined) {
throw new Error("Promise executor did not initialize resolve or reject.");
}
return { promise, resolve, reject };
}
/**
* A class to represent a task in the retry queue.
*/
class RetryTask {
/**
* The unique ID for the task.
* @type {string}
*/
id = Math.random().toString(36).slice(2);
/**
* The function to call.
* @type {Function}
*/
fn;
/**
* The error that was thrown.
* @type {Error}
*/
error;
/**
* The timestamp of the task.
* @type {number}
*/
timestamp = Date.now();
/**
* The timestamp of the last attempt.
* @type {number}
*/
lastAttempt = this.timestamp;
/**
* The resolve function for the promise.
* @type {Function}
*/
resolve;
/**
* The reject function for the promise.
* @type {Function}
*/
reject;
/**
* The AbortSignal to monitor for cancellation.
* @type {AbortSignal|undefined}
*/
signal;
/**
* Creates a new instance.
* @param {Function} fn The function to call.
* @param {Error} error The error that was thrown.
* @param {Function} resolve The resolve function for the promise.
* @param {Function} reject The reject function for the promise.
* @param {AbortSignal|undefined} signal The AbortSignal to monitor for cancellation.
*/
constructor(fn, error, resolve, reject, signal) {
this.fn = fn;
this.error = error;
this.timestamp = Date.now();
this.lastAttempt = Date.now();
this.resolve = resolve;
this.reject = reject;
this.signal = signal;
}
/**
* Gets the age of the task.
* @returns {number} The age of the task in milliseconds.
* @readonly
*/
get age() {
return Date.now() - this.timestamp;
}
}
//-----------------------------------------------------------------------------
// Exports
//-----------------------------------------------------------------------------
/**
* A class that manages a queue of retry jobs.
*/
class Retrier {
/**
* Represents the queue for processing tasks.
* @type {Array<RetryTask>}
*/
#retrying = [];
/**
* Represents the queue for pending tasks.
* @type {Array<Function>}
*/
#pending = [];
/**
* The number of tasks currently being processed.
* @type {number}
*/
#working = 0;
/**
* The timeout for the queue.
* @type {number}
*/
#timeout;
/**
* The maximum delay for the queue.
* @type {number}
*/
#maxDelay;
/**
* The setTimeout() timer ID.
* @type {NodeJS.Timeout|undefined}
*/
#timerId;
/**
* The function to call.
* @type {Function}
*/
#check;
/**
* The maximum number of concurrent tasks.
* @type {number}
*/
#concurrency;
/**
* Creates a new instance.
* @param {Function} check The function to call.
* @param {object} [options] The options for the instance.
* @param {number} [options.timeout] The timeout for the queue.
* @param {number} [options.maxDelay] The maximum delay for the queue.
* @param {number} [options.concurrency] The maximum number of concurrent tasks.
*/
constructor(check, { timeout = MAX_TASK_TIMEOUT, maxDelay = MAX_TASK_DELAY, concurrency = MAX_CONCURRENCY } = {}) {
if (typeof check !== "function") {
throw new Error("Missing function to check errors");
}
this.#check = check;
this.#timeout = timeout;
this.#maxDelay = maxDelay;
this.#concurrency = concurrency;
}
/**
* Gets the number of tasks waiting to be retried.
* @returns {number} The number of tasks in the retry queue.
*/
get retrying() {
return this.#retrying.length;
}
/**
* Gets the number of tasks waiting to be processed in the pending queue.
* @returns {number} The number of tasks in the pending queue.
*/
get pending() {
return this.#pending.length;
}
/**
* Gets the number of tasks currently being processed.
* @returns {number} The number of tasks currently being processed.
*/
get working() {
return this.#working;
}
/**
* Calls the function and retries if it fails.
* @param {Function} fn The function to call.
* @param {Object} options The options for the job.
* @param {AbortSignal} [options.signal] The AbortSignal to monitor for cancellation.
* @param {Promise<any>} options.promise The promise to return when the function settles.
* @param {Function} options.resolve The resolve function for the promise.
* @param {Function} options.reject The reject function for the promise.
* @returns {Promise<any>} A promise that resolves when the function is
* called successfully.
*/
#call(fn, { signal, promise, resolve, reject }) {
let result;
try {
result = fn();
} catch (/** @type {any} */ error) {
reject(new Error(`Synchronous error: ${error.message}`, { cause: error }));
return promise;
}
// if the result is not a promise then reject an error
if (!result || typeof result.then !== "function") {
reject(new Error("Result is not a promise."));
return promise;
}
this.#working++;
promise.finally(() => {
this.#working--;
this.#processPending();
})
// `promise.finally` creates a new promise that may be rejected, so it must be handled.
.catch(() => { });
// call the original function and catch any ENFILE or EMFILE errors
Promise.resolve(result)
.then(value => {
debug("Function called successfully without retry.");
resolve(value);
})
.catch(error => {
if (!this.#check(error)) {
reject(error);
return;
}
const task = new RetryTask(fn, error, resolve, reject, signal);
debug(`Function failed, queuing for retry with task ${task.id}.`);
this.#retrying.push(task);
signal?.addEventListener("abort", () => {
debug(`Task ${task.id} was aborted due to AbortSignal.`);
reject(signal.reason);
});
this.#processQueue();
});
return promise;
}
/**
* Adds a new retry job to the queue.
* @template {(...args: unknown[]) => Promise<unknown>} Func
* @template {Awaited<ReturnType<Func>>} RetVal
* @param {Func} fn The function to call.
* @param {object} [options] The options for the job.
* @param {AbortSignal} [options.signal] The AbortSignal to monitor for cancellation.
* @returns {Promise<RetVal>} A promise that resolves when the queue is processed.
*/
retry(fn, { signal } = {}) {
signal?.throwIfAborted();
const { promise, resolve, reject } = createPromise();
this.#pending.push(() => this.#call(fn, { signal, promise, resolve, reject }));
this.#processPending();
return promise;
}
/**
* Processes the pending queue and the retry queue.
* @returns {void}
*/
#processAll() {
if (this.pending) {
this.#processPending();
}
if (this.retrying) {
this.#processQueue();
}
}
/**
* Processes the pending queue to see which tasks can be started.
* @returns {void}
*/
#processPending() {
debug(`Processing pending tasks: ${this.pending} pending, ${this.working} working.`);
const available = this.#concurrency - this.working;
if (available <= 0) {
return;
}
const count = Math.min(this.pending, available);
for (let i = 0; i < count; i++) {
const task = this.#pending.shift();
task?.();
}
debug(`Processed pending tasks: ${this.pending} pending, ${this.working} working.`);
}
/**
* Processes the queue.
* @returns {void}
*/
#processQueue() {
// clear any timer because we're going to check right now
clearTimeout(this.#timerId);
this.#timerId = undefined;
debug(`Processing retry queue: ${this.retrying} retrying, ${this.working} working.`);
const processAgain = () => {
this.#timerId = setTimeout(() => this.#processAll(), 0);
};
// if there's nothing in the queue, we're done
const task = this.#retrying.shift();
if (!task) {
debug("Queue is empty, exiting.");
if (this.pending) {
processAgain();
}
return;
}
// if it's time to bail, then bail
if (isTimeToBail(task, this.#timeout)) {
debug(`Task ${task.id} was abandoned due to timeout.`);
task.reject(task.error);
processAgain();
return;
}
// if it's not time to retry, then wait and try again
if (!isTimeToRetry(task, this.#maxDelay)) {
debug(`Task ${task.id} is not ready to retry, skipping.`);
this.#retrying.push(task);
processAgain();
return;
}
// otherwise, try again
task.lastAttempt = Date.now();
// Promise.resolve needed in case it's a thenable but not a Promise
Promise.resolve(task.fn())
// @ts-ignore because we know it's any
.then(result => {
debug(`Task ${task.id} succeeded after ${task.age}ms.`);
task.resolve(result);
})
// @ts-ignore because we know it's any
.catch(error => {
if (!this.#check(error)) {
debug(`Task ${task.id} failed with non-retryable error: ${error.message}.`);
task.reject(error);
return;
}
// update the task timestamp and push to back of queue to try again
task.lastAttempt = Date.now();
this.#retrying.push(task);
debug(`Task ${task.id} failed, requeueing to try again.`);
})
.finally(() => {
this.#processAll();
});
}
}
export { Retrier };
@@ -0,0 +1,101 @@
import { Properties as CSSProperties } from 'csstype';
export = goober;
export as namespace goober;
declare namespace goober {
interface DefaultTheme {}
type Theme<T extends object> = keyof T extends never ? T : { theme: T };
interface StyledFunction {
// used when creating a styled component from a native HTML element
<T extends keyof React.JSX.IntrinsicElements, P extends Object = {}>(
tag: T,
forwardRef?: ForwardRefFunction
): Tagged<
React.JSX.LibraryManagedAttributes<T, React.JSX.IntrinsicElements[T]> &
P &
Theme<DefaultTheme>
>;
// used to extend other styled components. Inherits props from the extended component
<PP extends Object = {}, P extends Object = {}>(
tag: StyledVNode<PP>,
forwardRef?: ForwardRefFunction
): Tagged<PP & P & Theme<DefaultTheme>>;
// used when creating a component from a string (html native) but using a non HTML standard
// component, such as when you want to style web components
<P extends Object = {}>(tag: string): Tagged<
P & Partial<React.JSX.ElementChildrenAttribute>
>;
// used to create a styled component from a JSX element (both functional and class-based)
<T extends React.JSX.Element | React.JSX.ElementClass, P extends Object = {}>(
tag: T,
forwardRef?: ForwardRefFunction
): Tagged<P>;
}
// used when creating a styled component from a native HTML element with the babel-plugin-transform-goober parser
type BabelPluginTransformGooberStyledFunction = {
[T in keyof React.JSX.IntrinsicElements]: Tagged<
React.JSX.LibraryManagedAttributes<T, React.JSX.IntrinsicElements[T]> &
Theme<DefaultTheme>
>;
};
type ForwardRefFunction = {
(props: any, ref: any): any;
};
type ForwardPropsFunction = (props: object) => void;
const styled: StyledFunction & BabelPluginTransformGooberStyledFunction;
function setup<T>(
val: T,
prefixer?: (key: string, val: any) => string,
theme?: Function,
forwardProps?: ForwardPropsFunction
): void;
function extractCss(target?: Element): string;
function glob(
tag: CSSAttribute | TemplateStringsArray | string,
...props: Array<string | number>
): void;
function css(
tag: CSSAttribute | TemplateStringsArray | string,
...props: Array<string | number>
): string;
function keyframes(
tag: CSSAttribute | TemplateStringsArray | string,
...props: Array<string | number>
): string;
type StyledVNode<T> = ((props: T, ...args: any[]) => any) & {
defaultProps?: T;
displayName?: string;
};
type StylesGenerator<P extends Object = {}> = (props: P) => CSSAttribute | string;
type Tagged<P extends Object = {}> = <PP extends Object = { as?: any }>(
tag:
| CSSAttribute
| (CSSAttribute | StylesGenerator<P & PP>)[]
| TemplateStringsArray
| string
| StylesGenerator<P & PP>,
...props: Array<
| string
| number
| ((props: P & PP) => CSSAttribute | string | number | false | undefined)
>
) => StyledVNode<Omit<P & PP, keyof Theme<DefaultTheme>>>;
interface CSSAttribute extends CSSProperties {
[key: string]: CSSAttribute | string | number | undefined | null;
}
}
@@ -0,0 +1,590 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
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/components/button.ts
var button_exports = {};
__export(button_exports, {
button: () => button,
buttonGroup: () => buttonGroup
});
module.exports = __toCommonJS(button_exports);
// src/utils/tv.ts
var import_tailwind_variants = require("tailwind-variants");
// src/utils/tw-merge-config.ts
var COMMON_UNITS = ["small", "medium", "large"];
var twMergeConfig = {
theme: {
opacity: ["disabled"],
spacing: ["divider"],
borderWidth: COMMON_UNITS,
borderRadius: COMMON_UNITS
},
classGroups: {
shadow: [{ shadow: COMMON_UNITS }],
"font-size": [{ text: ["tiny", ...COMMON_UNITS] }],
"bg-image": [
"bg-stripe-gradient-default",
"bg-stripe-gradient-primary",
"bg-stripe-gradient-secondary",
"bg-stripe-gradient-success",
"bg-stripe-gradient-warning",
"bg-stripe-gradient-danger"
]
}
};
// src/utils/tv.ts
var tv = (options, config) => {
var _a, _b, _c;
return (0, import_tailwind_variants.tv)(options, {
...config,
twMerge: (_a = config == null ? void 0 : config.twMerge) != null ? _a : true,
twMergeConfig: {
...config == null ? void 0 : config.twMergeConfig,
theme: {
...(_b = config == null ? void 0 : config.twMergeConfig) == null ? void 0 : _b.theme,
...twMergeConfig.theme
},
classGroups: {
...(_c = config == null ? void 0 : config.twMergeConfig) == null ? void 0 : _c.classGroups,
...twMergeConfig.classGroups
}
}
});
};
// src/utils/classes.ts
var dataFocusVisibleClasses = [
"outline-none",
"data-[focus-visible=true]:z-10",
"data-[focus-visible=true]:outline-2",
"data-[focus-visible=true]:outline-focus",
"data-[focus-visible=true]:outline-offset-2"
];
var collapseAdjacentVariantBorders = {
default: ["[&+.border-medium.border-default]:ms-[calc(theme(borderWidth.medium)*-1)]"],
primary: ["[&+.border-medium.border-primary]:ms-[calc(theme(borderWidth.medium)*-1)]"],
secondary: ["[&+.border-medium.border-secondary]:ms-[calc(theme(borderWidth.medium)*-1)]"],
success: ["[&+.border-medium.border-success]:ms-[calc(theme(borderWidth.medium)*-1)]"],
warning: ["[&+.border-medium.border-warning]:ms-[calc(theme(borderWidth.medium)*-1)]"],
danger: ["[&+.border-medium.border-danger]:ms-[calc(theme(borderWidth.medium)*-1)]"]
};
// src/utils/variants.ts
var solid = {
default: "bg-default text-default-foreground",
primary: "bg-primary text-primary-foreground",
secondary: "bg-secondary text-secondary-foreground",
success: "bg-success text-success-foreground",
warning: "bg-warning text-warning-foreground",
danger: "bg-danger text-danger-foreground",
foreground: "bg-foreground text-background"
};
var shadow = {
default: "shadow-lg shadow-default/50 bg-default text-default-foreground",
primary: "shadow-lg shadow-primary/40 bg-primary text-primary-foreground",
secondary: "shadow-lg shadow-secondary/40 bg-secondary text-secondary-foreground",
success: "shadow-lg shadow-success/40 bg-success text-success-foreground",
warning: "shadow-lg shadow-warning/40 bg-warning text-warning-foreground",
danger: "shadow-lg shadow-danger/40 bg-danger text-danger-foreground",
foreground: "shadow-lg shadow-foreground/40 bg-foreground text-background"
};
var bordered = {
default: "bg-transparent border-default text-foreground",
primary: "bg-transparent border-primary text-primary",
secondary: "bg-transparent border-secondary text-secondary",
success: "bg-transparent border-success text-success",
warning: "bg-transparent border-warning text-warning",
danger: "bg-transparent border-danger text-danger",
foreground: "bg-transparent border-foreground text-foreground"
};
var flat = {
default: "bg-default/40 text-default-700",
primary: "bg-primary/20 text-primary-600",
secondary: "bg-secondary/20 text-secondary-600",
success: "bg-success/20 text-success-700 dark:text-success",
warning: "bg-warning/20 text-warning-700 dark:text-warning",
danger: "bg-danger/20 text-danger-600 dark:text-danger-500",
foreground: "bg-foreground/10 text-foreground"
};
var faded = {
default: "border-default bg-default-100 text-default-foreground",
primary: "border-default bg-default-100 text-primary",
secondary: "border-default bg-default-100 text-secondary",
success: "border-default bg-default-100 text-success",
warning: "border-default bg-default-100 text-warning",
danger: "border-default bg-default-100 text-danger",
foreground: "border-default bg-default-100 text-foreground"
};
var light = {
default: "bg-transparent text-default-foreground",
primary: "bg-transparent text-primary",
secondary: "bg-transparent text-secondary",
success: "bg-transparent text-success",
warning: "bg-transparent text-warning",
danger: "bg-transparent text-danger",
foreground: "bg-transparent text-foreground"
};
var ghost = {
default: "border-default text-default-foreground",
primary: "border-primary text-primary",
secondary: "border-secondary text-secondary",
success: "border-success text-success",
warning: "border-warning text-warning",
danger: "border-danger text-danger",
foreground: "border-foreground text-foreground hover:!bg-foreground"
};
var colorVariants = {
solid,
shadow,
bordered,
flat,
faded,
light,
ghost
};
// src/components/button.ts
var button = tv({
base: [
"z-0",
"group",
"relative",
"inline-flex",
"items-center",
"justify-center",
"box-border",
"appearance-none",
"outline-none",
"select-none",
"whitespace-nowrap",
"min-w-max",
"font-normal",
"subpixel-antialiased",
"overflow-hidden",
"tap-highlight-transparent",
"data-[pressed=true]:scale-[0.97]",
...dataFocusVisibleClasses
],
variants: {
variant: {
solid: "",
bordered: "border-medium bg-transparent",
light: "bg-transparent",
flat: "",
faded: "border-medium",
shadow: "",
ghost: "border-medium bg-transparent"
},
size: {
sm: "px-3 min-w-16 h-8 text-tiny gap-2 rounded-small",
md: "px-4 min-w-20 h-10 text-small gap-2 rounded-medium",
lg: "px-6 min-w-24 h-12 text-medium gap-3 rounded-large"
},
color: {
default: "",
primary: "",
secondary: "",
success: "",
warning: "",
danger: ""
},
radius: {
none: "rounded-none",
sm: "rounded-small",
md: "rounded-medium",
lg: "rounded-large",
full: "rounded-full"
},
fullWidth: {
true: "w-full"
},
isDisabled: {
true: "opacity-disabled pointer-events-none"
},
isInGroup: {
true: "[&:not(:first-child):not(:last-child)]:rounded-none"
},
isIconOnly: {
true: "px-0 !gap-0",
false: "[&>svg]:max-w-[theme(spacing.8)]"
},
disableAnimation: {
true: "!transition-none data-[pressed=true]:scale-100",
false: "transition-transform-colors-opacity motion-reduce:transition-none"
}
},
defaultVariants: {
size: "md",
variant: "solid",
color: "default",
fullWidth: false,
isDisabled: false,
isInGroup: false
},
compoundVariants: [
{
variant: "solid",
color: "default",
class: colorVariants.solid.default
},
{
variant: "solid",
color: "primary",
class: colorVariants.solid.primary
},
{
variant: "solid",
color: "secondary",
class: colorVariants.solid.secondary
},
{
variant: "solid",
color: "success",
class: colorVariants.solid.success
},
{
variant: "solid",
color: "warning",
class: colorVariants.solid.warning
},
{
variant: "solid",
color: "danger",
class: colorVariants.solid.danger
},
{
variant: "shadow",
color: "default",
class: colorVariants.shadow.default
},
{
variant: "shadow",
color: "primary",
class: colorVariants.shadow.primary
},
{
variant: "shadow",
color: "secondary",
class: colorVariants.shadow.secondary
},
{
variant: "shadow",
color: "success",
class: colorVariants.shadow.success
},
{
variant: "shadow",
color: "warning",
class: colorVariants.shadow.warning
},
{
variant: "shadow",
color: "danger",
class: colorVariants.shadow.danger
},
{
variant: "bordered",
color: "default",
class: colorVariants.bordered.default
},
{
variant: "bordered",
color: "primary",
class: colorVariants.bordered.primary
},
{
variant: "bordered",
color: "secondary",
class: colorVariants.bordered.secondary
},
{
variant: "bordered",
color: "success",
class: colorVariants.bordered.success
},
{
variant: "bordered",
color: "warning",
class: colorVariants.bordered.warning
},
{
variant: "bordered",
color: "danger",
class: colorVariants.bordered.danger
},
{
variant: "flat",
color: "default",
class: colorVariants.flat.default
},
{
variant: "flat",
color: "primary",
class: colorVariants.flat.primary
},
{
variant: "flat",
color: "secondary",
class: colorVariants.flat.secondary
},
{
variant: "flat",
color: "success",
class: colorVariants.flat.success
},
{
variant: "flat",
color: "warning",
class: colorVariants.flat.warning
},
{
variant: "flat",
color: "danger",
class: colorVariants.flat.danger
},
{
variant: "faded",
color: "default",
class: colorVariants.faded.default
},
{
variant: "faded",
color: "primary",
class: colorVariants.faded.primary
},
{
variant: "faded",
color: "secondary",
class: colorVariants.faded.secondary
},
{
variant: "faded",
color: "success",
class: colorVariants.faded.success
},
{
variant: "faded",
color: "warning",
class: colorVariants.faded.warning
},
{
variant: "faded",
color: "danger",
class: colorVariants.faded.danger
},
{
variant: "light",
color: "default",
class: [colorVariants.light.default, "data-[hover=true]:bg-default/40"]
},
{
variant: "light",
color: "primary",
class: [colorVariants.light.primary, "data-[hover=true]:bg-primary/20"]
},
{
variant: "light",
color: "secondary",
class: [colorVariants.light.secondary, "data-[hover=true]:bg-secondary/20"]
},
{
variant: "light",
color: "success",
class: [colorVariants.light.success, "data-[hover=true]:bg-success/20"]
},
{
variant: "light",
color: "warning",
class: [colorVariants.light.warning, "data-[hover=true]:bg-warning/20"]
},
{
variant: "light",
color: "danger",
class: [colorVariants.light.danger, "data-[hover=true]:bg-danger/20"]
},
{
variant: "ghost",
color: "default",
class: [colorVariants.ghost.default, "data-[hover=true]:!bg-default"]
},
{
variant: "ghost",
color: "primary",
class: [
colorVariants.ghost.primary,
"data-[hover=true]:!bg-primary data-[hover=true]:!text-primary-foreground"
]
},
{
variant: "ghost",
color: "secondary",
class: [
colorVariants.ghost.secondary,
"data-[hover=true]:!bg-secondary data-[hover=true]:!text-secondary-foreground"
]
},
{
variant: "ghost",
color: "success",
class: [
colorVariants.ghost.success,
"data-[hover=true]:!bg-success data-[hover=true]:!text-success-foreground"
]
},
{
variant: "ghost",
color: "warning",
class: [
colorVariants.ghost.warning,
"data-[hover=true]:!bg-warning data-[hover=true]:!text-warning-foreground"
]
},
{
variant: "ghost",
color: "danger",
class: [
colorVariants.ghost.danger,
"data-[hover=true]:!bg-danger data-[hover=true]:!text-danger-foreground"
]
},
{
isInGroup: true,
class: "rounded-none first:rounded-s-medium last:rounded-e-medium"
},
{
isInGroup: true,
size: "sm",
class: "rounded-none first:rounded-s-small last:rounded-e-small"
},
{
isInGroup: true,
size: "md",
class: "rounded-none first:rounded-s-medium last:rounded-e-medium"
},
{
isInGroup: true,
size: "lg",
class: "rounded-none first:rounded-s-large last:rounded-e-large"
},
{
isInGroup: true,
isRounded: true,
class: "rounded-none first:rounded-s-full last:rounded-e-full"
},
{
isInGroup: true,
radius: "none",
class: "rounded-none first:rounded-s-none last:rounded-e-none"
},
{
isInGroup: true,
radius: "sm",
class: "rounded-none first:rounded-s-small last:rounded-e-small"
},
{
isInGroup: true,
radius: "md",
class: "rounded-none first:rounded-s-medium last:rounded-e-medium"
},
{
isInGroup: true,
radius: "lg",
class: "rounded-none first:rounded-s-large last:rounded-e-large"
},
{
isInGroup: true,
radius: "full",
class: "rounded-none first:rounded-s-full last:rounded-e-full"
},
{
isInGroup: true,
variant: ["ghost", "bordered"],
color: "default",
className: collapseAdjacentVariantBorders.default
},
{
isInGroup: true,
variant: ["ghost", "bordered"],
color: "primary",
className: collapseAdjacentVariantBorders.primary
},
{
isInGroup: true,
variant: ["ghost", "bordered"],
color: "secondary",
className: collapseAdjacentVariantBorders.secondary
},
{
isInGroup: true,
variant: ["ghost", "bordered"],
color: "success",
className: collapseAdjacentVariantBorders.success
},
{
isInGroup: true,
variant: ["ghost", "bordered"],
color: "warning",
className: collapseAdjacentVariantBorders.warning
},
{
isInGroup: true,
variant: ["ghost", "bordered"],
color: "danger",
className: collapseAdjacentVariantBorders.danger
},
{
isIconOnly: true,
size: "sm",
class: "min-w-8 w-8 h-8"
},
{
isIconOnly: true,
size: "md",
class: "min-w-10 w-10 h-10"
},
{
isIconOnly: true,
size: "lg",
class: "min-w-12 w-12 h-12"
},
{
variant: ["solid", "faded", "flat", "bordered", "shadow"],
class: "data-[hover=true]:opacity-hover"
}
]
});
var buttonGroup = tv({
base: "inline-flex items-center justify-center h-auto",
variants: {
fullWidth: {
true: "w-full"
}
},
defaultVariants: {
fullWidth: false
}
});
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
button,
buttonGroup
});
@@ -0,0 +1 @@
{"version":3,"file":"escape.js","sourceRoot":"","sources":["../../src/escape.ts"],"names":[],"mappings":";;;AA+BA,8BA0BC;AAzDY,QAAA,WAAW,GAAW,wBAAwB,CAAC;AAE5D,MAAM,UAAU,GAAG,IAAI,GAAG,CAAC;IACvB,CAAC,EAAE,EAAE,QAAQ,CAAC;IACd,CAAC,EAAE,EAAE,OAAO,CAAC;IACb,CAAC,EAAE,EAAE,QAAQ,CAAC;IACd,CAAC,EAAE,EAAE,MAAM,CAAC;IACZ,CAAC,EAAE,EAAE,MAAM,CAAC;CACf,CAAC,CAAC;AAEH,yDAAyD;AAC5C,QAAA,YAAY;AACrB,uEAAuE;AACvE,MAAM,CAAC,SAAS,CAAC,WAAW,IAAI,IAAI;IAChC,CAAC,CAAC,CAAC,CAAS,EAAE,KAAa,EAAU,EAAE,CACjC,CAAC,CAAC,CAAC,UAAU,CAAC,KAAK,CAAC,GAAG,KAAO,CAAC,KAAK,KAAO;QACvC,CAAC,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,KAAK,CAAC,GAAG,KAAO,CAAC,GAAG,IAAM;YACxC,CAAC,CAAC,UAAU,CAAC,KAAK,GAAG,CAAC,CAAC;YACvB,KAAO;YACP,KAAS;QACX,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,KAAK,CAAC;IAC/B,CAAC,CAAC,uEAAuE;QACvE,CAAC,KAAa,EAAE,KAAa,EAAU,EAAE,CAAC,KAAK,CAAC,WAAW,CAAC,KAAK,CAAE,CAAC;AAE9E;;;;;;GAMG;AACH,SAAgB,SAAS,CAAC,KAAa;IACnC,IAAI,WAAW,GAAG,EAAE,CAAC;IACrB,IAAI,SAAS,GAAG,CAAC,CAAC;IAClB,IAAI,KAAK,CAAC;IAEV,OAAO,CAAC,KAAK,GAAG,mBAAW,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,KAAK,IAAI,EAAE,CAAC;QAChD,MAAM,EAAE,KAAK,EAAE,GAAG,KAAK,CAAC;QACxB,MAAM,IAAI,GAAG,KAAK,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC;QACrC,MAAM,IAAI,GAAG,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QAElC,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;YACrB,WAAW,IAAI,GAAG,KAAK,CAAC,SAAS,CAAC,SAAS,EAAE,KAAK,CAAC,MAAM,IAAA,oBAAY,EACjE,KAAK,EACL,KAAK,CACR,CAAC,QAAQ,CAAC,EAAE,CAAC,GAAG,CAAC;YAClB,4CAA4C;YAC5C,SAAS,GAAG,mBAAW,CAAC,SAAS,IAAI,MAAM,CACvC,CAAC,IAAI,GAAG,KAAO,CAAC,KAAK,KAAO,CAC/B,CAAC;QACN,CAAC;aAAM,CAAC;YACJ,WAAW,IAAI,KAAK,CAAC,SAAS,CAAC,SAAS,EAAE,KAAK,CAAC,GAAG,IAAI,CAAC;YACxD,SAAS,GAAG,KAAK,GAAG,CAAC,CAAC;QAC1B,CAAC;IACL,CAAC;IAED,OAAO,WAAW,GAAG,KAAK,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;AACjD,CAAC;AAED;;;;;;;;GAQG;AACU,QAAA,MAAM,GAAqB,SAAS,CAAC;AAElD;;;;;;;;;GASG;AACH,SAAS,UAAU,CACf,KAAa,EACb,GAAwB;IAExB,OAAO,SAAS,MAAM,CAAC,IAAY;QAC/B,IAAI,KAAK,CAAC;QACV,IAAI,SAAS,GAAG,CAAC,CAAC;QAClB,IAAI,MAAM,GAAG,EAAE,CAAC;QAEhB,OAAO,CAAC,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,EAAE,CAAC;YAChC,IAAI,SAAS,KAAK,KAAK,CAAC,KAAK,EAAE,CAAC;gBAC5B,MAAM,IAAI,IAAI,CAAC,SAAS,CAAC,SAAS,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC;YACrD,CAAC;YAED,kDAAkD;YAClD,MAAM,IAAI,GAAG,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAE,CAAC;YAE3C,kCAAkC;YAClC,SAAS,GAAG,KAAK,CAAC,KAAK,GAAG,CAAC,CAAC;QAChC,CAAC;QAED,OAAO,MAAM,GAAG,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC;IAC9C,CAAC,CAAC;AACN,CAAC;AAED;;;;;;GAMG;AACU,QAAA,UAAU,GAA6C,UAAU,CAC1E,UAAU,EACV,UAAU,CACb,CAAC;AAEF;;;;;GAKG;AACU,QAAA,eAAe;AACxB,eAAe,CAAC,UAAU,CACtB,aAAa,EACb,IAAI,GAAG,CAAC;IACJ,CAAC,EAAE,EAAE,QAAQ,CAAC;IACd,CAAC,EAAE,EAAE,OAAO,CAAC;IACb,CAAC,GAAG,EAAE,QAAQ,CAAC;CAClB,CAAC,CACL,CAAC;AAEN;;;;;GAKG;AACU,QAAA,UAAU,GAA6C,UAAU,CAC1E,cAAc,EACd,IAAI,GAAG,CAAC;IACJ,CAAC,EAAE,EAAE,OAAO,CAAC;IACb,CAAC,EAAE,EAAE,MAAM,CAAC;IACZ,CAAC,EAAE,EAAE,MAAM,CAAC;IACZ,CAAC,GAAG,EAAE,QAAQ,CAAC;CAClB,CAAC,CACL,CAAC"}
@@ -0,0 +1 @@
{"version":3,"file":"DecoratorInfo.js","sourceRoot":"","sources":["../../../../src/decorator/models/DecoratorInfo.ts"],"names":[],"mappings":""}
@@ -0,0 +1,148 @@
import * as _react_types_table from '@react-types/table';
import { TableCollection } from '@react-types/table';
import * as _heroui_system from '@heroui/system';
import { HTMLHeroUIProps, PropGetter } from '@heroui/system';
import * as react from 'react';
import { ReactNode, Key } from 'react';
import { SlotsToClasses, TableSlots, TableVariantProps, TableReturnType } from '@heroui/theme';
import { Layout } from '@react-stately/virtualizer';
import { Node, SelectionBehavior, DisabledBehavior } from '@react-types/shared';
import { TableStateProps, TableState } from '@react-stately/table';
import { AriaTableProps } from '@react-aria/table';
import { ReactRef } from '@heroui/react-utils';
import { CheckboxProps } from '@heroui/checkbox';
type TableContentPlacement = "inside" | "outside";
interface Props<T> extends HTMLHeroUIProps<"table"> {
/**
* Ref to the DOM node.
*/
ref?: ReactRef<HTMLElement | null>;
children?: ReactNode;
layoutNode?: Layout<Node<T>>;
/**
* A custom wrapper component for the table.
* @default "div"
*/
BaseComponent?: React.ComponentType<any>;
/**
* Ref to the container element.
*/
baseRef?: ReactRef<HTMLElement | null>;
/**
* Where to place the `topContent` component.
* @default "inside"
*/
topContentPlacement?: TableContentPlacement;
/**
* Provides content to include a component in the top of the table.
*/
topContent?: ReactNode;
/**
* Where to place the `bottomContent` component.
* @default "inside"
*/
bottomContentPlacement?: TableContentPlacement;
/**
* Provides content to include a component in the bottom of the table.
*/
bottomContent?: ReactNode;
/**
* Whether the table base container should not be rendered.
* @default false
*/
removeWrapper?: boolean;
/**
* How multiple selection should behave in the collection.
* The selection behavior for the table. If selectionMode is `"none"`, this will be `null`.
* otherwise, this will be `toggle` or `replace`.
* @default "toggle"
*/
selectionBehavior?: SelectionBehavior | null;
/**
* Whether `disabledKeys` applies to all interactions, or only selection.
* @default "selection"
*/
disabledBehavior?: DisabledBehavior;
/**
* Whether to disable the table and checkbox animations.
* @default false
*/
disableAnimation?: boolean;
/**
* Whether to disable the keyboard navigation functionality.
* @default false
*/
isKeyboardNavigationDisabled?: boolean;
/**
* Props to be passed to the checkboxes.
*/
checkboxesProps?: CheckboxProps;
/**
* Custom Icon to be displayed in the table header - overrides the default chevron one
*/
sortIcon?: ReactNode | ((props: any) => ReactNode);
/** Handler that is called when a user performs an action on the row. */
onRowAction?: (key: Key) => void;
/** Handler that is called when a user performs an action on the cell. */
onCellAction?: (key: Key) => void;
/**
* Classname or List of classes to change the classNames of the element.
* if `className` is passed, it will be added to the base slot.
*
* @example
* ```ts
* <Table classNames={{
* base:"base-classes", // table wrapper
* table: "table-classes",
* thead: "thead-classes",
* tbody: "tbody-classes",
* tr: "tr-classes",
* th: "th-classes",
* td: "td-classes",
* tfoot: "tfoot-classes",
* sortIcon: "sort-icon-classes",
* emptyWrapper: "empty-wrapper-classes",
* }} />
* ```
*/
classNames?: SlotsToClasses<TableSlots>;
}
type UseTableProps<T = object> = Props<T> & TableStateProps<T> & Omit<AriaTableProps, "layout"> & TableVariantProps;
type ValuesType<T = object> = {
state: TableState<T>;
slots: TableReturnType;
collection: TableCollection<T>;
color: TableVariantProps["color"];
isSelectable: boolean;
selectionMode: UseTableProps<T>["selectionMode"];
selectionBehavior: SelectionBehavior | null;
checkboxesProps?: CheckboxProps;
disabledBehavior: UseTableProps<T>["disabledBehavior"];
disableAnimation?: UseTableProps<T>["disableAnimation"];
isHeaderSticky?: UseTableProps<T>["isHeaderSticky"];
showSelectionCheckboxes: UseTableProps<T>["showSelectionCheckboxes"];
classNames?: SlotsToClasses<TableSlots>;
onRowAction?: UseTableProps<T>["onRowAction"];
onCellAction?: UseTableProps<T>["onCellAction"];
};
declare function useTable<T extends object>(originalProps: UseTableProps<T>): {
BaseComponent: string | react.ComponentType<any>;
Component: _heroui_system.As<any>;
children: ((string | number | boolean | react.ReactElement<any, string | react.JSXElementConstructor<any>> | react.ReactFragment | react.ReactPortal | null) & [react.ReactElement<_react_types_table.TableHeaderProps<T>, string | react.JSXElementConstructor<any>>, react.ReactElement<_react_types_table.TableBodyProps<T>, string | react.JSXElementConstructor<any>>]) | undefined;
state: TableState<T>;
collection: TableCollection<T>;
values: ValuesType<T>;
topContent: ReactNode;
bottomContent: ReactNode;
removeWrapper: boolean;
topContentPlacement: TableContentPlacement;
bottomContentPlacement: TableContentPlacement;
sortIcon: ReactNode | ((props: any) => ReactNode);
getBaseProps: PropGetter;
getWrapperProps: PropGetter;
getTableProps: PropGetter;
};
type UseTableReturn = ReturnType<typeof useTable>;
export { type UseTableProps, type UseTableReturn, type ValuesType, useTable };
@@ -0,0 +1,43 @@
import { AnyCnameRecord } from 'node:dns';
import { BizKey, ModifyProfileParams, NodeIKernelProfileListener, ProfileBizType, SimpleInfo, UserDetailInfoByUin, UserDetailInfoListenerArg, UserDetailSource } from '../index';
import { GeneralCallResult } from '../services/common';
export interface NodeIKernelProfileService {
getOtherFlag(callfrom: string, uids: string[]): Promise<Map<string, unknown>>;
getVasInfo(callfrom: string, uids: string[]): Promise<Map<string, unknown>>;
getRelationFlag(callfrom: string, uids: string[]): Promise<Map<string, unknown>>;
getUidByUin(callfrom: string, uin: Array<string>): Map<string, string>;
getUinByUid(callfrom: string, uid: Array<string>): Map<string, string>;
getCoreAndBaseInfo(callfrom: string, uids: string[]): Promise<Map<string, SimpleInfo>>;
fetchUserDetailInfo(trace: string, uids: string[], source: UserDetailSource, bizType: ProfileBizType[]): Promise<GeneralCallResult & {
source: UserDetailSource;
detail: Map<string, UserDetailInfoListenerArg>;
}>;
addKernelProfileListener(listener: NodeIKernelProfileListener): number;
removeKernelProfileListener(listenerId: number): void;
prepareRegionConfig(...args: unknown[]): unknown;
getLocalStrangerRemark(): Promise<AnyCnameRecord>;
enumCountryOptions(): Array<string>;
enumProvinceOptions(country: string): Array<string>;
enumCityOptions(country: string, province: string): unknown;
enumAreaOptions(...args: unknown[]): unknown;
modifySelfProfile(...args: unknown[]): Promise<unknown>;
modifyDesktopMiniProfile(param: ModifyProfileParams): Promise<GeneralCallResult>;
setNickName(nickName: string): Promise<unknown>;
setLongNick(longNick: string): Promise<unknown>;
setBirthday(...args: unknown[]): Promise<unknown>;
setGander(...args: unknown[]): Promise<unknown>;
setHeader(arg: string): Promise<GeneralCallResult>;
setRecommendImgFlag(...args: unknown[]): Promise<unknown>;
getUserSimpleInfo(force: boolean, uids: string[]): Promise<unknown>;
getUserDetailInfo(uid: string): Promise<unknown>;
getUserDetailInfoWithBizInfo(uid: string, Biz: BizKey[]): Promise<GeneralCallResult>;
getUserDetailInfoByUin(uin: string): Promise<UserDetailInfoByUin>;
getZplanAvatarInfos(args: string[]): Promise<unknown>;
getStatus(uid: string): Promise<unknown>;
startStatusPolling(isForceReset: boolean): Promise<unknown>;
getSelfStatus(): Promise<unknown>;
setdisableEmojiShortCuts(...args: unknown[]): unknown;
getProfileQzonePicInfo(uid: string, type: number, force: boolean): Promise<unknown>;
getCoreInfo(sceneId: string, arg: unknown[]): unknown;
isNull(): boolean;
}
@@ -0,0 +1,425 @@
'use strict';
const util = require('./util');
const defaultOptions = {
allowBooleanAttributes: false, //A tag can have attributes without any value
unpairedTags: []
};
//const tagsPattern = new RegExp("<\\/?([\\w:\\-_\.]+)\\s*\/?>","g");
exports.validate = function (xmlData, options) {
options = Object.assign({}, defaultOptions, options);
//xmlData = xmlData.replace(/(\r\n|\n|\r)/gm,"");//make it single line
//xmlData = xmlData.replace(/(^\s*<\?xml.*?\?>)/g,"");//Remove XML starting tag
//xmlData = xmlData.replace(/(<!DOCTYPE[\s\w\"\.\/\-\:]+(\[.*\])*\s*>)/g,"");//Remove DOCTYPE
const tags = [];
let tagFound = false;
//indicates that the root tag has been closed (aka. depth 0 has been reached)
let reachedRoot = false;
if (xmlData[0] === '\ufeff') {
// check for byte order mark (BOM)
xmlData = xmlData.substr(1);
}
for (let i = 0; i < xmlData.length; i++) {
if (xmlData[i] === '<' && xmlData[i+1] === '?') {
i+=2;
i = readPI(xmlData,i);
if (i.err) return i;
}else if (xmlData[i] === '<') {
//starting of tag
//read until you reach to '>' avoiding any '>' in attribute value
let tagStartPos = i;
i++;
if (xmlData[i] === '!') {
i = readCommentAndCDATA(xmlData, i);
continue;
} else {
let closingTag = false;
if (xmlData[i] === '/') {
//closing tag
closingTag = true;
i++;
}
//read tagname
let tagName = '';
for (; i < xmlData.length &&
xmlData[i] !== '>' &&
xmlData[i] !== ' ' &&
xmlData[i] !== '\t' &&
xmlData[i] !== '\n' &&
xmlData[i] !== '\r'; i++
) {
tagName += xmlData[i];
}
tagName = tagName.trim();
//console.log(tagName);
if (tagName[tagName.length - 1] === '/') {
//self closing tag without attributes
tagName = tagName.substring(0, tagName.length - 1);
//continue;
i--;
}
if (!validateTagName(tagName)) {
let msg;
if (tagName.trim().length === 0) {
msg = "Invalid space after '<'.";
} else {
msg = "Tag '"+tagName+"' is an invalid name.";
}
return getErrorObject('InvalidTag', msg, getLineNumberForPosition(xmlData, i));
}
const result = readAttributeStr(xmlData, i);
if (result === false) {
return getErrorObject('InvalidAttr', "Attributes for '"+tagName+"' have open quote.", getLineNumberForPosition(xmlData, i));
}
let attrStr = result.value;
i = result.index;
if (attrStr[attrStr.length - 1] === '/') {
//self closing tag
const attrStrStart = i - attrStr.length;
attrStr = attrStr.substring(0, attrStr.length - 1);
const isValid = validateAttributeString(attrStr, options);
if (isValid === true) {
tagFound = true;
//continue; //text may presents after self closing tag
} else {
//the result from the nested function returns the position of the error within the attribute
//in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute
//this gives us the absolute index in the entire xml, which we can use to find the line at last
return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, attrStrStart + isValid.err.line));
}
} else if (closingTag) {
if (!result.tagClosed) {
return getErrorObject('InvalidTag', "Closing tag '"+tagName+"' doesn't have proper closing.", getLineNumberForPosition(xmlData, i));
} else if (attrStr.trim().length > 0) {
return getErrorObject('InvalidTag', "Closing tag '"+tagName+"' can't have attributes or invalid starting.", getLineNumberForPosition(xmlData, tagStartPos));
} else if (tags.length === 0) {
return getErrorObject('InvalidTag', "Closing tag '"+tagName+"' has not been opened.", getLineNumberForPosition(xmlData, tagStartPos));
} else {
const otg = tags.pop();
if (tagName !== otg.tagName) {
let openPos = getLineNumberForPosition(xmlData, otg.tagStartPos);
return getErrorObject('InvalidTag',
"Expected closing tag '"+otg.tagName+"' (opened in line "+openPos.line+", col "+openPos.col+") instead of closing tag '"+tagName+"'.",
getLineNumberForPosition(xmlData, tagStartPos));
}
//when there are no more tags, we reached the root level.
if (tags.length == 0) {
reachedRoot = true;
}
}
} else {
const isValid = validateAttributeString(attrStr, options);
if (isValid !== true) {
//the result from the nested function returns the position of the error within the attribute
//in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute
//this gives us the absolute index in the entire xml, which we can use to find the line at last
return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, i - attrStr.length + isValid.err.line));
}
//if the root level has been reached before ...
if (reachedRoot === true) {
return getErrorObject('InvalidXml', 'Multiple possible root nodes found.', getLineNumberForPosition(xmlData, i));
} else if(options.unpairedTags.indexOf(tagName) !== -1){
//don't push into stack
} else {
tags.push({tagName, tagStartPos});
}
tagFound = true;
}
//skip tag text value
//It may include comments and CDATA value
for (i++; i < xmlData.length; i++) {
if (xmlData[i] === '<') {
if (xmlData[i + 1] === '!') {
//comment or CADATA
i++;
i = readCommentAndCDATA(xmlData, i);
continue;
} else if (xmlData[i+1] === '?') {
i = readPI(xmlData, ++i);
if (i.err) return i;
} else{
break;
}
} else if (xmlData[i] === '&') {
const afterAmp = validateAmpersand(xmlData, i);
if (afterAmp == -1)
return getErrorObject('InvalidChar', "char '&' is not expected.", getLineNumberForPosition(xmlData, i));
i = afterAmp;
}else{
if (reachedRoot === true && !isWhiteSpace(xmlData[i])) {
return getErrorObject('InvalidXml', "Extra text at the end", getLineNumberForPosition(xmlData, i));
}
}
} //end of reading tag text value
if (xmlData[i] === '<') {
i--;
}
}
} else {
if ( isWhiteSpace(xmlData[i])) {
continue;
}
return getErrorObject('InvalidChar', "char '"+xmlData[i]+"' is not expected.", getLineNumberForPosition(xmlData, i));
}
}
if (!tagFound) {
return getErrorObject('InvalidXml', 'Start tag expected.', 1);
}else if (tags.length == 1) {
return getErrorObject('InvalidTag', "Unclosed tag '"+tags[0].tagName+"'.", getLineNumberForPosition(xmlData, tags[0].tagStartPos));
}else if (tags.length > 0) {
return getErrorObject('InvalidXml', "Invalid '"+
JSON.stringify(tags.map(t => t.tagName), null, 4).replace(/\r?\n/g, '')+
"' found.", {line: 1, col: 1});
}
return true;
};
function isWhiteSpace(char){
return char === ' ' || char === '\t' || char === '\n' || char === '\r';
}
/**
* Read Processing insstructions and skip
* @param {*} xmlData
* @param {*} i
*/
function readPI(xmlData, i) {
const start = i;
for (; i < xmlData.length; i++) {
if (xmlData[i] == '?' || xmlData[i] == ' ') {
//tagname
const tagname = xmlData.substr(start, i - start);
if (i > 5 && tagname === 'xml') {
return getErrorObject('InvalidXml', 'XML declaration allowed only at the start of the document.', getLineNumberForPosition(xmlData, i));
} else if (xmlData[i] == '?' && xmlData[i + 1] == '>') {
//check if valid attribut string
i++;
break;
} else {
continue;
}
}
}
return i;
}
function readCommentAndCDATA(xmlData, i) {
if (xmlData.length > i + 5 && xmlData[i + 1] === '-' && xmlData[i + 2] === '-') {
//comment
for (i += 3; i < xmlData.length; i++) {
if (xmlData[i] === '-' && xmlData[i + 1] === '-' && xmlData[i + 2] === '>') {
i += 2;
break;
}
}
} else if (
xmlData.length > i + 8 &&
xmlData[i + 1] === 'D' &&
xmlData[i + 2] === 'O' &&
xmlData[i + 3] === 'C' &&
xmlData[i + 4] === 'T' &&
xmlData[i + 5] === 'Y' &&
xmlData[i + 6] === 'P' &&
xmlData[i + 7] === 'E'
) {
let angleBracketsCount = 1;
for (i += 8; i < xmlData.length; i++) {
if (xmlData[i] === '<') {
angleBracketsCount++;
} else if (xmlData[i] === '>') {
angleBracketsCount--;
if (angleBracketsCount === 0) {
break;
}
}
}
} else if (
xmlData.length > i + 9 &&
xmlData[i + 1] === '[' &&
xmlData[i + 2] === 'C' &&
xmlData[i + 3] === 'D' &&
xmlData[i + 4] === 'A' &&
xmlData[i + 5] === 'T' &&
xmlData[i + 6] === 'A' &&
xmlData[i + 7] === '['
) {
for (i += 8; i < xmlData.length; i++) {
if (xmlData[i] === ']' && xmlData[i + 1] === ']' && xmlData[i + 2] === '>') {
i += 2;
break;
}
}
}
return i;
}
const doubleQuote = '"';
const singleQuote = "'";
/**
* Keep reading xmlData until '<' is found outside the attribute value.
* @param {string} xmlData
* @param {number} i
*/
function readAttributeStr(xmlData, i) {
let attrStr = '';
let startChar = '';
let tagClosed = false;
for (; i < xmlData.length; i++) {
if (xmlData[i] === doubleQuote || xmlData[i] === singleQuote) {
if (startChar === '') {
startChar = xmlData[i];
} else if (startChar !== xmlData[i]) {
//if vaue is enclosed with double quote then single quotes are allowed inside the value and vice versa
} else {
startChar = '';
}
} else if (xmlData[i] === '>') {
if (startChar === '') {
tagClosed = true;
break;
}
}
attrStr += xmlData[i];
}
if (startChar !== '') {
return false;
}
return {
value: attrStr,
index: i,
tagClosed: tagClosed
};
}
/**
* Select all the attributes whether valid or invalid.
*/
const validAttrStrRegxp = new RegExp('(\\s*)([^\\s=]+)(\\s*=)?(\\s*([\'"])(([\\s\\S])*?)\\5)?', 'g');
//attr, ="sd", a="amit's", a="sd"b="saf", ab cd=""
function validateAttributeString(attrStr, options) {
//console.log("start:"+attrStr+":end");
//if(attrStr.trim().length === 0) return true; //empty string
const matches = util.getAllMatches(attrStr, validAttrStrRegxp);
const attrNames = {};
for (let i = 0; i < matches.length; i++) {
if (matches[i][1].length === 0) {
//nospace before attribute name: a="sd"b="saf"
return getErrorObject('InvalidAttr', "Attribute '"+matches[i][2]+"' has no space in starting.", getPositionFromMatch(matches[i]))
} else if (matches[i][3] !== undefined && matches[i][4] === undefined) {
return getErrorObject('InvalidAttr', "Attribute '"+matches[i][2]+"' is without value.", getPositionFromMatch(matches[i]));
} else if (matches[i][3] === undefined && !options.allowBooleanAttributes) {
//independent attribute: ab
return getErrorObject('InvalidAttr', "boolean attribute '"+matches[i][2]+"' is not allowed.", getPositionFromMatch(matches[i]));
}
/* else if(matches[i][6] === undefined){//attribute without value: ab=
return { err: { code:"InvalidAttr",msg:"attribute " + matches[i][2] + " has no value assigned."}};
} */
const attrName = matches[i][2];
if (!validateAttrName(attrName)) {
return getErrorObject('InvalidAttr', "Attribute '"+attrName+"' is an invalid name.", getPositionFromMatch(matches[i]));
}
if (!attrNames.hasOwnProperty(attrName)) {
//check for duplicate attribute.
attrNames[attrName] = 1;
} else {
return getErrorObject('InvalidAttr', "Attribute '"+attrName+"' is repeated.", getPositionFromMatch(matches[i]));
}
}
return true;
}
function validateNumberAmpersand(xmlData, i) {
let re = /\d/;
if (xmlData[i] === 'x') {
i++;
re = /[\da-fA-F]/;
}
for (; i < xmlData.length; i++) {
if (xmlData[i] === ';')
return i;
if (!xmlData[i].match(re))
break;
}
return -1;
}
function validateAmpersand(xmlData, i) {
// https://www.w3.org/TR/xml/#dt-charref
i++;
if (xmlData[i] === ';')
return -1;
if (xmlData[i] === '#') {
i++;
return validateNumberAmpersand(xmlData, i);
}
let count = 0;
for (; i < xmlData.length; i++, count++) {
if (xmlData[i].match(/\w/) && count < 20)
continue;
if (xmlData[i] === ';')
break;
return -1;
}
return i;
}
function getErrorObject(code, message, lineNumber) {
return {
err: {
code: code,
msg: message,
line: lineNumber.line || lineNumber,
col: lineNumber.col,
},
};
}
function validateAttrName(attrName) {
return util.isName(attrName);
}
// const startsWithXML = /^xml/i;
function validateTagName(tagname) {
return util.isName(tagname) /* && !tagname.match(startsWithXML) */;
}
//this function returns the line number for the character at the given index
function getLineNumberForPosition(xmlData, index) {
const lines = xmlData.substring(0, index).split(/\r?\n/);
return {
line: lines.length,
// column number is last line's length + 1, because column numbering starts at 1:
col: lines[lines.length - 1].length + 1
};
}
//this function returns the position of the first character of match within attrStr
function getPositionFromMatch(match) {
return match.startIndex + match[1].length;
}
@@ -0,0 +1,33 @@
'use strict'
function reusify (Constructor) {
var head = new Constructor()
var tail = head
function get () {
var current = head
if (current.next) {
head = current.next
} else {
head = new Constructor()
tail = head
}
current.next = null
return current
}
function release (obj) {
tail.next = obj
tail = obj
}
return {
get: get,
release: release
}
}
module.exports = reusify
@@ -0,0 +1,6 @@
import type TokenProcessor from "../TokenProcessor";
/**
* Starting at `export {`, look ahead and return `true` if this is an
* `export {...} from` statement and `false` if this is a plain multi-export.
*/
export default function isExportFrom(tokens: TokenProcessor): boolean;
@@ -0,0 +1 @@
{"version":3,"file":"unset.d.ts","sourceRoot":"","sources":["../../src/utils/unset.ts"],"names":[],"mappings":"AA0BA,MAAM,CAAC,OAAO,UAAU,KAAK,CAAC,MAAM,EAAE,GAAG,EAAE,IAAI,EAAE,MAAM,GAAG,CAAC,MAAM,GAAG,MAAM,CAAC,EAAE,OAyB5E"}
@@ -0,0 +1,33 @@
import { PatternNumber, PatternString, PatternBoolean } from '../patterns/index.mjs';
import { Kind } from '../symbols/index.mjs';
import { TypeBoxError } from '../error/index.mjs';
// ------------------------------------------------------------------
// TypeGuard
// ------------------------------------------------------------------
import { IsTemplateLiteral, IsUnion, IsNumber, IsInteger, IsBigInt, IsString, IsLiteral, IsBoolean } from '../guard/kind.mjs';
// ------------------------------------------------------------------
// TemplateLiteralPatternError
// ------------------------------------------------------------------
export class TemplateLiteralPatternError extends TypeBoxError {
}
// ------------------------------------------------------------------
// TemplateLiteralPattern
// ------------------------------------------------------------------
function Escape(value) {
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
// prettier-ignore
function Visit(schema, acc) {
return (IsTemplateLiteral(schema) ? schema.pattern.slice(1, schema.pattern.length - 1) :
IsUnion(schema) ? `(${schema.anyOf.map((schema) => Visit(schema, acc)).join('|')})` :
IsNumber(schema) ? `${acc}${PatternNumber}` :
IsInteger(schema) ? `${acc}${PatternNumber}` :
IsBigInt(schema) ? `${acc}${PatternNumber}` :
IsString(schema) ? `${acc}${PatternString}` :
IsLiteral(schema) ? `${acc}${Escape(schema.const.toString())}` :
IsBoolean(schema) ? `${acc}${PatternBoolean}` :
(() => { throw new TemplateLiteralPatternError(`Unexpected Kind '${schema[Kind]}'`); })());
}
export function TemplateLiteralPattern(kinds) {
return `^${kinds.map((schema) => Visit(schema, '')).join('')}\$`;
}
@@ -0,0 +1,3 @@
declare const _exports: import('eslint').Rule.RuleModule;
export = _exports;
//# sourceMappingURL=jsx-filename-extension.d.ts.map
@@ -0,0 +1,7 @@
function isRefObject(ref) {
return (ref &&
typeof ref === "object" &&
Object.prototype.hasOwnProperty.call(ref, "current"));
}
export { isRefObject };
@@ -0,0 +1,134 @@
import { EditorView } from '@codemirror/view';
import { HighlightStyle, syntaxHighlighting } from '@codemirror/language';
import { tags } from '@lezer/highlight';
// Using https://github.com/one-dark/vscode-one-dark-theme/ as reference for the colors
const chalky = "#e5c07b", coral = "#e06c75", cyan = "#56b6c2", invalid = "#ffffff", ivory = "#abb2bf", stone = "#7d8799", // Brightened compared to original to increase contrast
malibu = "#61afef", sage = "#98c379", whiskey = "#d19a66", violet = "#c678dd", darkBackground = "#21252b", highlightBackground = "#2c313a", background = "#282c34", tooltipBackground = "#353a42", selection = "#3E4451", cursor = "#528bff";
/**
The colors used in the theme, as CSS color strings.
*/
const color = {
chalky,
coral,
cyan,
invalid,
ivory,
stone,
malibu,
sage,
whiskey,
violet,
darkBackground,
highlightBackground,
background,
tooltipBackground,
selection,
cursor
};
/**
The editor theme styles for One Dark.
*/
const oneDarkTheme = /*@__PURE__*/EditorView.theme({
"&": {
color: ivory,
backgroundColor: background
},
".cm-content": {
caretColor: cursor
},
".cm-cursor, .cm-dropCursor": { borderLeftColor: cursor },
"&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection": { backgroundColor: selection },
".cm-panels": { backgroundColor: darkBackground, color: ivory },
".cm-panels.cm-panels-top": { borderBottom: "2px solid black" },
".cm-panels.cm-panels-bottom": { borderTop: "2px solid black" },
".cm-searchMatch": {
backgroundColor: "#72a1ff59",
outline: "1px solid #457dff"
},
".cm-searchMatch.cm-searchMatch-selected": {
backgroundColor: "#6199ff2f"
},
".cm-activeLine": { backgroundColor: "#6699ff0b" },
".cm-selectionMatch": { backgroundColor: "#aafe661a" },
"&.cm-focused .cm-matchingBracket, &.cm-focused .cm-nonmatchingBracket": {
backgroundColor: "#bad0f847"
},
".cm-gutters": {
backgroundColor: background,
color: stone,
border: "none"
},
".cm-activeLineGutter": {
backgroundColor: highlightBackground
},
".cm-foldPlaceholder": {
backgroundColor: "transparent",
border: "none",
color: "#ddd"
},
".cm-tooltip": {
border: "none",
backgroundColor: tooltipBackground
},
".cm-tooltip .cm-tooltip-arrow:before": {
borderTopColor: "transparent",
borderBottomColor: "transparent"
},
".cm-tooltip .cm-tooltip-arrow:after": {
borderTopColor: tooltipBackground,
borderBottomColor: tooltipBackground
},
".cm-tooltip-autocomplete": {
"& > ul > li[aria-selected]": {
backgroundColor: highlightBackground,
color: ivory
}
}
}, { dark: true });
/**
The highlighting style for code in the One Dark theme.
*/
const oneDarkHighlightStyle = /*@__PURE__*/HighlightStyle.define([
{ tag: tags.keyword,
color: violet },
{ tag: [tags.name, tags.deleted, tags.character, tags.propertyName, tags.macroName],
color: coral },
{ tag: [/*@__PURE__*/tags.function(tags.variableName), tags.labelName],
color: malibu },
{ tag: [tags.color, /*@__PURE__*/tags.constant(tags.name), /*@__PURE__*/tags.standard(tags.name)],
color: whiskey },
{ tag: [/*@__PURE__*/tags.definition(tags.name), tags.separator],
color: ivory },
{ tag: [tags.typeName, tags.className, tags.number, tags.changed, tags.annotation, tags.modifier, tags.self, tags.namespace],
color: chalky },
{ tag: [tags.operator, tags.operatorKeyword, tags.url, tags.escape, tags.regexp, tags.link, /*@__PURE__*/tags.special(tags.string)],
color: cyan },
{ tag: [tags.meta, tags.comment],
color: stone },
{ tag: tags.strong,
fontWeight: "bold" },
{ tag: tags.emphasis,
fontStyle: "italic" },
{ tag: tags.strikethrough,
textDecoration: "line-through" },
{ tag: tags.link,
color: stone,
textDecoration: "underline" },
{ tag: tags.heading,
fontWeight: "bold",
color: coral },
{ tag: [tags.atom, tags.bool, /*@__PURE__*/tags.special(tags.variableName)],
color: whiskey },
{ tag: [tags.processingInstruction, tags.string, tags.inserted],
color: sage },
{ tag: tags.invalid,
color: invalid },
]);
/**
Extension to enable the One Dark theme (both the editor theme and
the highlight style).
*/
const oneDark = [oneDarkTheme, /*@__PURE__*/syntaxHighlighting(oneDarkHighlightStyle)];
export { color, oneDark, oneDarkHighlightStyle, oneDarkTheme };
@@ -0,0 +1,12 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var motionDom = require('motion-dom');
Object.defineProperty(exports, "recordStats", {
enumerable: true,
get: function () { return motionDom.recordStats; }
});
@@ -0,0 +1 @@
{"version":3,"file":"cloneBinding.js","sourceRoot":"","sources":["../../../../src/binding/calculations/cloneBinding.ts"],"names":[],"mappings":";;AAoBA,oCAwBC;AA3CD,uDAA0D;AAK1D,2EAAwE;AACxE,yEAAsE;AACtE,+DAA4D;AAC5D,iEAA8D;AAC9D,iEAA8D;AAC9D,2EAAwE;AACxE,qFAAkF;AAElF;;;;;GAKG;AACH,SAAgB,YAAY,CAC1B,OAA4B;IAE5B,uEAAuE;IACvE,QAAQ,OAAO,CAAC,IAAI,EAAE,CAAC;QACrB,KAAK,+BAAiB,CAAC,aAAa;YAClC,OAAO,IAAA,qDAAyB,EAAC,OAAO,CAAC,CAAC;QAC5C,KAAK,+BAAiB,CAAC,YAAY;YACjC,OAAO,IAAA,mDAAwB,EAAC,OAAO,CAAC,CAAC;QAC3C,KAAK,+BAAiB,CAAC,OAAO;YAC5B,OAAO,IAAA,yCAAmB,EACxB,OAAwD,CAClC,CAAC;QAC3B,KAAK,+BAAiB,CAAC,QAAQ;YAC7B,OAAO,IAAA,2CAAoB,EAAC,OAAO,CAAC,CAAC;QACvC,KAAK,+BAAiB,CAAC,QAAQ;YAC7B,OAAO,IAAA,2CAAoB,EACzB,OAA0D,CACpC,CAAC;QAC3B,KAAK,+BAAiB,CAAC,aAAa;YAClC,OAAO,IAAA,qDAAyB,EAAC,OAAO,CAAC,CAAC;QAC5C,KAAK,+BAAiB,CAAC,kBAAkB;YACvC,OAAO,IAAA,+DAA8B,EAAC,OAAO,CAAC,CAAC;IACnD,CAAC;AACH,CAAC"}
@@ -0,0 +1 @@
{"version":3,"file":"parse-args.js","sourceRoot":"","sources":["../../src/parse-args.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,IAAI,MAAM,MAAM,CAAA;AAE5B,MAAM,EAAE,GACN,CACE,OAAO,OAAO,KAAK,QAAQ;IAC3B,CAAC,CAAC,OAAO;IACT,OAAO,OAAO,CAAC,OAAO,KAAK,QAAQ,CACpC,CAAC,CAAC;IACD,OAAO,CAAC,OAAO;IACjB,CAAC,CAAC,QAAQ,CAAA;AACZ,MAAM,GAAG,GAAG,EAAE;KACX,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC;KACjB,KAAK,CAAC,GAAG,CAAC;KACV,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,QAAQ,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAA;AAE5B,qBAAqB;AACrB,MAAM,CAAC,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,CAAC,CAAC,GAAG,GAAG,CAAA;AAClC,oBAAoB;AAEpB,IAAI,EACF,SAAS,EAAE,EAAE,GACd,GAA8D,IAAI,CAAA;AAEnE,wCAAwC;AACxC,IACE,CAAC,EAAE;IACH,KAAK,GAAG,EAAE;IACV,CAAC,KAAK,KAAK,EAAE,IAAI,KAAK,GAAG,EAAE,CAAC;IAC5B,CAAC,KAAK,KAAK,EAAE,IAAI,KAAK,GAAG,EAAE,CAAC,EAC5B,CAAC;IACD,iDAAiD;IACjD,YAAY;IACZ,EAAE,GAAG,CAAC,MAAM,MAAM,CAAC,kBAAkB,CAAC,CAAC,CAAC,SAAS,CAAA;AACnD,CAAC;AACD,oBAAoB;AAEpB,MAAM,CAAC,MAAM,SAAS,GAAG,EAA0C,CAAA","sourcesContent":["import * as util from 'util'\n\nconst pv =\n (\n typeof process === 'object' &&\n !!process &&\n typeof process.version === 'string'\n ) ?\n process.version\n : 'v0.0.0'\nconst pvs = pv\n .replace(/^v/, '')\n .split('.')\n .map(s => parseInt(s, 10))\n\n/* c8 ignore start */\nconst [major = 0, minor = 0] = pvs\n/* c8 ignore stop */\n\nlet {\n parseArgs: pa,\n}: typeof import('util') | typeof import('@pkgjs/parseargs') = util\n\n/* c8 ignore start - version specific */\nif (\n !pa ||\n major < 16 ||\n (major === 18 && minor < 11) ||\n (major === 16 && minor < 19)\n) {\n // Ignore because we will clobber it for commonjs\n //@ts-ignore\n pa = (await import('@pkgjs/parseargs')).parseArgs\n}\n/* c8 ignore stop */\n\nexport const parseArgs = pa as (typeof import('util'))['parseArgs']\n"]}
@@ -0,0 +1,13 @@
import { __rest } from "tslib";
import { instance as globalContainer } from "../dependency-container";
function registry(registrations) {
if (registrations === void 0) { registrations = []; }
return function (target) {
registrations.forEach(function (_a) {
var token = _a.token, options = _a.options, provider = __rest(_a, ["token", "options"]);
return globalContainer.register(token, provider, options);
});
return target;
};
}
export default registry;
@@ -0,0 +1,147 @@
var LazyWrapper = require('./_LazyWrapper'),
LodashWrapper = require('./_LodashWrapper'),
baseLodash = require('./_baseLodash'),
isArray = require('./isArray'),
isObjectLike = require('./isObjectLike'),
wrapperClone = require('./_wrapperClone');
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Creates a `lodash` object which wraps `value` to enable implicit method
* chain sequences. Methods that operate on and return arrays, collections,
* and functions can be chained together. Methods that retrieve a single value
* or may return a primitive value will automatically end the chain sequence
* and return the unwrapped value. Otherwise, the value must be unwrapped
* with `_#value`.
*
* Explicit chain sequences, which must be unwrapped with `_#value`, may be
* enabled using `_.chain`.
*
* The execution of chained methods is lazy, that is, it's deferred until
* `_#value` is implicitly or explicitly called.
*
* Lazy evaluation allows several methods to support shortcut fusion.
* Shortcut fusion is an optimization to merge iteratee calls; this avoids
* the creation of intermediate arrays and can greatly reduce the number of
* iteratee executions. Sections of a chain sequence qualify for shortcut
* fusion if the section is applied to an array and iteratees accept only
* one argument. The heuristic for whether a section qualifies for shortcut
* fusion is subject to change.
*
* Chaining is supported in custom builds as long as the `_#value` method is
* directly or indirectly included in the build.
*
* In addition to lodash methods, wrappers have `Array` and `String` methods.
*
* The wrapper `Array` methods are:
* `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift`
*
* The wrapper `String` methods are:
* `replace` and `split`
*
* The wrapper methods that support shortcut fusion are:
* `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`,
* `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`,
* `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray`
*
* The chainable wrapper methods are:
* `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`,
* `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`,
* `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`,
* `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`,
* `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`,
* `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`,
* `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`,
* `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`,
* `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`,
* `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`,
* `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`,
* `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`,
* `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`,
* `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`,
* `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`,
* `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`,
* `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`,
* `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`,
* `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`,
* `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`,
* `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`,
* `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`,
* `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`,
* `zipObject`, `zipObjectDeep`, and `zipWith`
*
* The wrapper methods that are **not** chainable by default are:
* `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`,
* `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`,
* `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`,
* `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`,
* `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`,
* `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`,
* `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`,
* `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`,
* `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`,
* `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`,
* `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`,
* `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`,
* `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`,
* `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`,
* `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`,
* `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`,
* `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`,
* `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`,
* `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`,
* `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`,
* `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`,
* `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`,
* `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`,
* `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`,
* `upperFirst`, `value`, and `words`
*
* @name _
* @constructor
* @category Seq
* @param {*} value The value to wrap in a `lodash` instance.
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* function square(n) {
* return n * n;
* }
*
* var wrapped = _([1, 2, 3]);
*
* // Returns an unwrapped value.
* wrapped.reduce(_.add);
* // => 6
*
* // Returns a wrapped value.
* var squares = wrapped.map(square);
*
* _.isArray(squares);
* // => false
*
* _.isArray(squares.value());
* // => true
*/
function lodash(value) {
if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) {
if (value instanceof LodashWrapper) {
return value;
}
if (hasOwnProperty.call(value, '__wrapped__')) {
return wrapperClone(value);
}
}
return new LodashWrapper(value);
}
// Ensure wrappers are instances of `baseLodash`.
lodash.prototype = baseLodash.prototype;
lodash.prototype.constructor = lodash;
module.exports = lodash;
@@ -0,0 +1,36 @@
/**
* @file 椭圆转换成轮廓
* @author mengke01(kekee000@gmail.com)
*/
import {computePath} from '../../graphics/computeBoundingBox';
import pathAdjust from '../../graphics/pathAdjust';
import circlePath from '../../graphics/path/circle';
import {clone} from '../../common/lang';
/**
* 椭圆转换成轮廓
*
* @param {number} cx 椭圆中心点x
* @param {number} cy 椭圆中心点y
* @param {number} rx 椭圆x轴半径
* @param {number} ry 椭圆y周半径
* @return {Array} 轮廓数组
*/
export default function oval2contour(cx, cy, rx, ry) {
if (undefined === ry) {
ry = rx;
}
const bound = computePath(circlePath);
const scaleX = (+rx) * 2 / bound.width;
const scaleY = (+ry) * 2 / bound.height;
const centerX = bound.width * scaleX / 2;
const centerY = bound.height * scaleY / 2;
const contour = clone(circlePath);
pathAdjust(contour, scaleX, scaleY);
pathAdjust(contour, 1, 1, +cx - centerX, +cy - centerY);
return contour;
}
@@ -0,0 +1,83 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("@typescript-eslint/utils");
const util_1 = require("../util");
exports.default = (0, util_1.createRule)({
name: 'no-duplicate-enum-values',
meta: {
type: 'problem',
docs: {
description: 'Disallow duplicate enum member values',
recommended: 'recommended',
},
hasSuggestions: false,
messages: {
duplicateValue: 'Duplicate enum member value {{value}}.',
},
schema: [],
},
defaultOptions: [],
create(context) {
function isStringLiteral(node) {
return (node.type === utils_1.AST_NODE_TYPES.Literal && typeof node.value === 'string');
}
function isNumberLiteral(node) {
return (node.type === utils_1.AST_NODE_TYPES.Literal && typeof node.value === 'number');
}
function isSupportedUnary(node) {
return (node.type === utils_1.AST_NODE_TYPES.UnaryExpression &&
['-', '+'].includes(node.operator));
}
function isStaticTemplateLiteral(node) {
return (node.type === utils_1.AST_NODE_TYPES.TemplateLiteral &&
node.expressions.length === 0 &&
node.quasis.length === 1);
}
function getMemberValue(initializer) {
switch (true) {
case isStringLiteral(initializer):
case isNumberLiteral(initializer):
return initializer.value;
case isSupportedUnary(initializer): {
const inner = Number(getMemberValue(initializer.argument));
if (Number.isNaN(inner)) {
return undefined;
}
return initializer.operator === '-' ? -inner : inner;
}
case isStaticTemplateLiteral(initializer):
return initializer.quasis[0].value.cooked;
default:
return undefined;
}
}
return {
TSEnumDeclaration(node) {
const enumMembers = node.body.members;
const seenValues = [];
enumMembers.forEach(member => {
if (member.initializer == null) {
return;
}
const value = getMemberValue(member.initializer);
if (value == null) {
return;
}
const isAlreadyPresent = seenValues.some(seenValue => Object.is(seenValue, value));
if (isAlreadyPresent) {
context.report({
node: member,
messageId: 'duplicateValue',
data: {
value,
},
});
}
else {
seenValues.push(value);
}
});
},
};
},
});
@@ -0,0 +1,92 @@
// Generated by LiveScript 1.6.0
var split, join, lines, unlines, words, unwords, chars, unchars, reverse, repeat, capitalize, camelize, dasherize;
split = curry$(function(sep, str){
return str.split(sep);
});
join = curry$(function(sep, xs){
return xs.join(sep);
});
lines = function(str){
if (!str.length) {
return [];
}
return str.split('\n');
};
unlines = function(it){
return it.join('\n');
};
words = function(str){
if (!str.length) {
return [];
}
return str.split(/[ ]+/);
};
unwords = function(it){
return it.join(' ');
};
chars = function(it){
return it.split('');
};
unchars = function(it){
return it.join('');
};
reverse = function(str){
return str.split('').reverse().join('');
};
repeat = curry$(function(n, str){
var result, i$;
result = '';
for (i$ = 0; i$ < n; ++i$) {
result += str;
}
return result;
});
capitalize = function(str){
return str.charAt(0).toUpperCase() + str.slice(1);
};
camelize = function(it){
return it.replace(/[-_]+(.)?/g, function(arg$, c){
return (c != null ? c : '').toUpperCase();
});
};
dasherize = function(str){
return str.replace(/([^-A-Z])([A-Z]+)/g, function(arg$, lower, upper){
return lower + "-" + (upper.length > 1
? upper
: upper.toLowerCase());
}).replace(/^([A-Z]+)/, function(arg$, upper){
if (upper.length > 1) {
return upper + "-";
} else {
return upper.toLowerCase();
}
});
};
module.exports = {
split: split,
join: join,
lines: lines,
unlines: unlines,
words: words,
unwords: unwords,
chars: chars,
unchars: unchars,
reverse: reverse,
repeat: repeat,
capitalize: capitalize,
camelize: camelize,
dasherize: dasherize
};
function curry$(f, bound){
var context,
_curry = function(args) {
return f.length > 1 ? function(){
var params = args ? args.concat() : [];
context = bound ? context || this : this;
return params.push.apply(params, arguments) <
f.length && arguments.length ?
_curry.call(context, params) : f.apply(context, params);
} : f;
};
return _curry();
}
@@ -0,0 +1,18 @@
# @codemirror/search [![NPM version](https://img.shields.io/npm/v/@codemirror/search.svg)](https://www.npmjs.org/package/@codemirror/search)
[ [**WEBSITE**](https://codemirror.net/) | [**DOCS**](https://codemirror.net/docs/ref/#search) | [**ISSUES**](https://github.com/codemirror/dev/issues) | [**FORUM**](https://discuss.codemirror.net/c/next/) | [**CHANGELOG**](https://github.com/codemirror/search/blob/main/CHANGELOG.md) ]
This package implements search functionality for the
[CodeMirror](https://codemirror.net/) code editor.
The [project page](https://codemirror.net/) has more information, a
number of [examples](https://codemirror.net/examples/) and the
[documentation](https://codemirror.net/docs/).
This code is released under an
[MIT license](https://github.com/codemirror/search/tree/main/LICENSE).
We aim to be an inclusive, welcoming community. To make that explicit,
we have a [code of
conduct](http://contributor-covenant.org/version/1/1/0/) that applies
to communication around the project.
@@ -0,0 +1,23 @@
import type { SourceToken, Token } from '../parse/cst';
import type { ComposeErrorHandler } from './composer';
export interface ResolvePropsArg {
flow?: 'flow map' | 'flow sequence';
indicator: 'doc-start' | 'explicit-key-ind' | 'map-value-ind' | 'seq-item-ind';
next: Token | null | undefined;
offset: number;
onError: ComposeErrorHandler;
parentIndent: number;
startOnNewline: boolean;
}
export declare function resolveProps(tokens: SourceToken[], { flow, indicator, next, offset, onError, parentIndent, startOnNewline }: ResolvePropsArg): {
comma: SourceToken | null;
found: SourceToken | null;
spaceBefore: boolean;
comment: string;
hasNewline: boolean;
anchor: SourceToken | null;
tag: SourceToken | null;
newlineAfterProp: SourceToken | null;
end: number;
start: number;
};
@@ -0,0 +1,10 @@
import { PluginFunc, ConfigType, OpUnitType } from 'dayjs/esm'
declare const plugin: PluginFunc
export = plugin
declare module 'dayjs/esm' {
interface Dayjs {
isSameOrAfter(date?: ConfigType, unit?: OpUnitType): boolean
}
}
@@ -0,0 +1,11 @@
import { TypeBoxError } from '../../type/error/index';
import type { TSchema } from '../../type/schema/index';
import type { Static } from '../../type/static/index';
export declare class ValueCreateError extends TypeBoxError {
readonly schema: TSchema;
constructor(schema: TSchema, message: string);
}
/** Creates a value from the given schema and references */
export declare function Create<T extends TSchema>(schema: T, references: TSchema[]): Static<T>;
/** Creates a value from the given schema */
export declare function Create<T extends TSchema>(schema: T): Static<T>;
@@ -0,0 +1,20 @@
/**
* A specialized version of `matchesProperty` for source values suitable
* for strict equality comparisons, i.e. `===`.
*
* @private
* @param {string} key The key of the property to get.
* @param {*} srcValue The value to match.
* @returns {Function} Returns the new spec function.
*/
function matchesStrictComparable(key, srcValue) {
return function(object) {
if (object == null) {
return false;
}
return object[key] === srcValue &&
(srcValue !== undefined || (key in Object(object)));
};
}
module.exports = matchesStrictComparable;
@@ -0,0 +1,17 @@
"use strict";
// THIS CODE WAS AUTOMATICALLY GENERATED
// DO NOT EDIT THIS CODE BY HAND
// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE:
// npx nx generate-lib repo
Object.defineProperty(exports, "__esModule", { value: true });
exports.dom_asynciterable = void 0;
const base_config_1 = require("./base-config");
exports.dom_asynciterable = {
libs: [],
variables: [
['FileSystemDirectoryHandleAsyncIterator', base_config_1.TYPE],
['FileSystemDirectoryHandle', base_config_1.TYPE],
['ReadableStreamAsyncIterator', base_config_1.TYPE],
['ReadableStream', base_config_1.TYPE],
],
};
@@ -0,0 +1,176 @@
const HELPERS = {
require: `
import {createRequire as CREATE_REQUIRE_NAME} from "module";
const require = CREATE_REQUIRE_NAME(import.meta.url);
`,
interopRequireWildcard: `
function interopRequireWildcard(obj) {
if (obj && obj.__esModule) {
return obj;
} else {
var newObj = {};
if (obj != null) {
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
return newObj;
}
}
`,
interopRequireDefault: `
function interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
`,
createNamedExportFrom: `
function createNamedExportFrom(obj, localName, importedName) {
Object.defineProperty(exports, localName, {enumerable: true, configurable: true, get: () => obj[importedName]});
}
`,
// Note that TypeScript and Babel do this differently; TypeScript does a simple existence
// check in the exports object and does a plain assignment, whereas Babel uses
// defineProperty and builds an object of explicitly-exported names so that star exports can
// always take lower precedence. For now, we do the easier TypeScript thing.
createStarExport: `
function createStarExport(obj) {
Object.keys(obj)
.filter((key) => key !== "default" && key !== "__esModule")
.forEach((key) => {
if (exports.hasOwnProperty(key)) {
return;
}
Object.defineProperty(exports, key, {enumerable: true, configurable: true, get: () => obj[key]});
});
}
`,
nullishCoalesce: `
function nullishCoalesce(lhs, rhsFn) {
if (lhs != null) {
return lhs;
} else {
return rhsFn();
}
}
`,
asyncNullishCoalesce: `
async function asyncNullishCoalesce(lhs, rhsFn) {
if (lhs != null) {
return lhs;
} else {
return await rhsFn();
}
}
`,
optionalChain: `
function optionalChain(ops) {
let lastAccessLHS = undefined;
let value = ops[0];
let i = 1;
while (i < ops.length) {
const op = ops[i];
const fn = ops[i + 1];
i += 2;
if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) {
return undefined;
}
if (op === 'access' || op === 'optionalAccess') {
lastAccessLHS = value;
value = fn(value);
} else if (op === 'call' || op === 'optionalCall') {
value = fn((...args) => value.call(lastAccessLHS, ...args));
lastAccessLHS = undefined;
}
}
return value;
}
`,
asyncOptionalChain: `
async function asyncOptionalChain(ops) {
let lastAccessLHS = undefined;
let value = ops[0];
let i = 1;
while (i < ops.length) {
const op = ops[i];
const fn = ops[i + 1];
i += 2;
if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) {
return undefined;
}
if (op === 'access' || op === 'optionalAccess') {
lastAccessLHS = value;
value = await fn(value);
} else if (op === 'call' || op === 'optionalCall') {
value = await fn((...args) => value.call(lastAccessLHS, ...args));
lastAccessLHS = undefined;
}
}
return value;
}
`,
optionalChainDelete: `
function optionalChainDelete(ops) {
const result = OPTIONAL_CHAIN_NAME(ops);
return result == null ? true : result;
}
`,
asyncOptionalChainDelete: `
async function asyncOptionalChainDelete(ops) {
const result = await ASYNC_OPTIONAL_CHAIN_NAME(ops);
return result == null ? true : result;
}
`,
};
export class HelperManager {
__init() {this.helperNames = {}}
__init2() {this.createRequireName = null}
constructor( nameManager) {;this.nameManager = nameManager;HelperManager.prototype.__init.call(this);HelperManager.prototype.__init2.call(this);}
getHelperName(baseName) {
let helperName = this.helperNames[baseName];
if (helperName) {
return helperName;
}
helperName = this.nameManager.claimFreeName(`_${baseName}`);
this.helperNames[baseName] = helperName;
return helperName;
}
emitHelpers() {
let resultCode = "";
if (this.helperNames.optionalChainDelete) {
this.getHelperName("optionalChain");
}
if (this.helperNames.asyncOptionalChainDelete) {
this.getHelperName("asyncOptionalChain");
}
for (const [baseName, helperCodeTemplate] of Object.entries(HELPERS)) {
const helperName = this.helperNames[baseName];
let helperCode = helperCodeTemplate;
if (baseName === "optionalChainDelete") {
helperCode = helperCode.replace("OPTIONAL_CHAIN_NAME", this.helperNames.optionalChain);
} else if (baseName === "asyncOptionalChainDelete") {
helperCode = helperCode.replace(
"ASYNC_OPTIONAL_CHAIN_NAME",
this.helperNames.asyncOptionalChain,
);
} else if (baseName === "require") {
if (this.createRequireName === null) {
this.createRequireName = this.nameManager.claimFreeName("_createRequire");
}
helperCode = helperCode.replace(/CREATE_REQUIRE_NAME/g, this.createRequireName);
}
if (helperName) {
resultCode += " ";
resultCode += helperCode.replace(baseName, helperName).replace(/\s+/g, " ").trim();
}
}
return resultCode;
}
}
@@ -0,0 +1,17 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var DescriptionListDetailRole = {
relatedConcepts: [{
module: 'HTML',
concept: {
name: 'dd'
}
}],
type: 'structure'
};
var _default = DescriptionListDetailRole;
exports.default = _default;
@@ -0,0 +1,77 @@
import {listData as $b1f0cad8af73213b$export$3585ede4d035bf14} from "./utils.mjs";
import {filterDOMProps as $by1yQ$filterDOMProps, useId as $by1yQ$useId, mergeProps as $by1yQ$mergeProps} from "@react-aria/utils";
import {useFocusWithin as $by1yQ$useFocusWithin} from "@react-aria/interactions";
import {useLabel as $by1yQ$useLabel} from "@react-aria/label";
import {useSelectableList as $by1yQ$useSelectableList} from "@react-aria/selection";
/*
* Copyright 2020 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
function $c132121280ec012d$export$50eacbbf140a3141(props, state, ref) {
let domProps = (0, $by1yQ$filterDOMProps)(props, {
labelable: true
});
// Use props instead of state here. We don't want this to change due to long press.
let selectionBehavior = props.selectionBehavior || 'toggle';
let linkBehavior = props.linkBehavior || (selectionBehavior === 'replace' ? 'action' : 'override');
if (selectionBehavior === 'toggle' && linkBehavior === 'action') // linkBehavior="action" does not work with selectionBehavior="toggle" because there is no way
// to initiate selection (checkboxes are not allowed inside a listbox). Link items will not be
// selectable in this configuration.
linkBehavior = 'override';
let { listProps: listProps } = (0, $by1yQ$useSelectableList)({
...props,
ref: ref,
selectionManager: state.selectionManager,
collection: state.collection,
disabledKeys: state.disabledKeys,
linkBehavior: linkBehavior
});
let { focusWithinProps: focusWithinProps } = (0, $by1yQ$useFocusWithin)({
onFocusWithin: props.onFocus,
onBlurWithin: props.onBlur,
onFocusWithinChange: props.onFocusChange
});
// Share list id and some props with child options.
let id = (0, $by1yQ$useId)(props.id);
(0, $b1f0cad8af73213b$export$3585ede4d035bf14).set(state, {
id: id,
shouldUseVirtualFocus: props.shouldUseVirtualFocus,
shouldSelectOnPressUp: props.shouldSelectOnPressUp,
shouldFocusOnHover: props.shouldFocusOnHover,
isVirtualized: props.isVirtualized,
onAction: props.onAction,
linkBehavior: linkBehavior
});
let { labelProps: labelProps, fieldProps: fieldProps } = (0, $by1yQ$useLabel)({
...props,
id: id,
// listbox is not an HTML input element so it
// shouldn't be labeled by a <label> element.
labelElementType: 'span'
});
return {
labelProps: labelProps,
listBoxProps: (0, $by1yQ$mergeProps)(domProps, focusWithinProps, state.selectionManager.selectionMode === 'multiple' ? {
'aria-multiselectable': 'true'
} : {}, {
role: 'listbox',
...(0, $by1yQ$mergeProps)(fieldProps, listProps)
})
};
}
export {$c132121280ec012d$export$50eacbbf140a3141 as useListBox};
//# sourceMappingURL=useListBox.module.js.map
@@ -0,0 +1,11 @@
export { default as Pagination, PaginationProps } from './pagination.mjs';
export { default as PaginationItem, PaginationItemProps } from './pagination-item.mjs';
export { default as PaginationCursor, PaginationCursorProps } from './pagination-cursor.mjs';
export { PaginationItemRenderProps, usePagination } from './use-pagination.mjs';
export { PaginationItemType, PaginationItemValue } from '@heroui/use-pagination';
export { usePaginationItem } from './use-pagination-item.mjs';
import '@heroui/system';
import 'tailwind-variants';
import '@heroui/theme';
import 'react';
import '@react-types/shared';
@@ -0,0 +1 @@
{"name":"lodash","version":"4.17.21","requiresBuild":false,"files":{"LICENSE":{"checkedAt":1794532111288,"integrity":"sha512-OVKmi0ACReW0qn9lB3gIkwOokjOEH4DTURXOynLKs5Wpgl6nWq/flVnw+Ax/jxxqj+40sAcUtOIZHvz5E4Y0NQ==","mode":420,"size":1952},"fp/__.js":{"checkedAt":1794532111288,"integrity":"sha512-/I/SP7Vgtpf4p/3P6j2mo53lr4opQiM0K8hAmL77VgJGCf/uxiyFcVF0iKmz26QkPYeknDYQvcG4qP0YXffOWQ==","mode":420,"size":43},"_apply.js":{"checkedAt":1794532111289,"integrity":"sha512-bt9f60EtDOa08QjcimY9nTFkN/vabBbKgGn/mEYpIXtuZGtjHsKOrl09hdKtyzKiXRvvx0qgM3yeNgKDOKbsgQ==","mode":420,"size":714},"_arrayAggregator.js":{"checkedAt":1794532111289,"integrity":"sha512-y60kPSqYrpZdzhxNpXfCFPdeUA2y7nfXzHpUugvo36Pjc6Sj5fQlOIwoLBH6DcA3plR1b9+Y5b+ZvKBvYAS44w==","mode":420,"size":684},"_arrayEach.js":{"checkedAt":1794532111289,"integrity":"sha512-bN+806H4trWsdPgKS59x9ABvcHmsKnOZuORJcpgeGPgGTZu1RPh3X7q198i0rcUM4LC7PyGzv5e20s89patyoA==","mode":420,"size":537},"_arrayEachRight.js":{"checkedAt":1794532111289,"integrity":"sha512-dbPCOM0okkf6K+AR883WP7TNHGxfiE1esylLDCA+QUtXgbxNAoRpCLohQsftv966Ql3SXSwM7FdzKJ2qcG09rA==","mode":420,"size":528},"_arrayEvery.js":{"checkedAt":1794532111289,"integrity":"sha512-w0iRa8kORqTqELkEpIlf5q+iy3wB22UlDeMDWcQYkdOgKPfTmhvo5MkIXML30fmRcwTE9iUagbRG17p+YneKiA==","mode":420,"size":597},"_arrayFilter.js":{"checkedAt":1794532111289,"integrity":"sha512-NqyZX4cGL82ZeZqNjm98fufp4cyC6G++lhkNHxhig4nMuXCBZnuIxLPyfXPPeJ+wBM4cGCdzLL5NoY/+HObVNg==","mode":420,"size":632},"_arrayIncludes.js":{"checkedAt":1794532111289,"integrity":"sha512-Ig/mrY2FrJQNfWSnL1i00LOtHouwk2BvFev4WGakD3jntOmaQY52IjY3nMU24hQoyH5kZFBqDSuferwmtrt6QA==","mode":420,"size":526},"_arrayIncludesWith.js":{"checkedAt":1794532111290,"integrity":"sha512-kJkyVpYt1rBYpF/K3WsuK8FXjnwVtrIYaeofsw8u+YL4rCyzsZfn16zxi8qwsgMuBSVYUWs+7sqjGmlwmEtHRA==","mode":420,"size":615},"_arrayLikeKeys.js":{"checkedAt":1794532111290,"integrity":"sha512-YJNM9evbG+6lEEdittUAU/00o7R77OQ5T/QPvpx5ceUJdGWxGbq1j+gocISKI6QpiNjASjIJPNowb7M6uPmmeg==","mode":420,"size":1778},"_arrayMap.js":{"checkedAt":1794532111290,"integrity":"sha512-u18NFQuehFyWhIcnT+MQpqwPgU0nf5aL6OJgL7OLOlX+yUnuAU8UUvEreEGOMj58UfTCXnR9DJyzHrslyGIqUQ==","mode":420,"size":556},"_arrayPush.js":{"checkedAt":1794532111290,"integrity":"sha512-otgPRi4qs2If5CA3Lzh/dWApUYsRwS5Tr/zfhIhQpTb00Dbi//7c+dObcNNZR06e+NJjWzOOW8QbaOm3uc0zzg==","mode":420,"size":437},"_arrayReduce.js":{"checkedAt":1794532111290,"integrity":"sha512-c9LpqjPMDfNQTuEGQ2fwZPgSXgK2O0kdzjH3+LCp/RF6edogTy6XfL032+uy9HuKNYY0Zmti7npLnSCFv1SR9A==","mode":420,"size":787},"_arrayReduceRight.js":{"checkedAt":1794532111290,"integrity":"sha512-ouIUUUSxo6b9L7Rbs1v04PXF2sWbxwk2/W7JymWN5LF7OpellZcJTgpck2pqod+KkkcxRfNlDksFiCmnCo/veA==","mode":420,"size":777},"_arraySample.js":{"checkedAt":1794532111290,"integrity":"sha512-O6sbAVhdzDRgI/MWh6YLt9rXsjf9rVj9bIv7EsJzmrchbzMPsu+GsClfuPqwNZi/BBJW/71k+WXWi3xooeontg==","mode":420,"size":363},"_arraySampleSize.js":{"checkedAt":1794532111291,"integrity":"sha512-EgMC4sey8ahjIizl483zJeHBZKVzN2SuidUSIRN/yFR+Ax2Om9+bgzDG0Aax8pKZgHTJXkBgwkdLh0KQ7Bb97g==","mode":420,"size":500},"_arrayShuffle.js":{"checkedAt":1794532111291,"integrity":"sha512-aLTnVd3SUvpzdDPtk5kVQSPr6WeTPS11757SzQnyM3J/MNkfhSG5UcDM+77rmNS4mt7qU1iTeYCKR5AH0mQYDQ==","mode":420,"size":365},"_arraySome.js":{"checkedAt":1794532111291,"integrity":"sha512-pRj+bz2KkXkMKCTsk1oEMf5mVr6RHaJ5i/M/NHHeNChSbnqChzxSVg+TT8Dyst2qV1HerHyBSjTxPFOVN5bkQw==","mode":420,"size":594},"_asciiSize.js":{"checkedAt":1794532111291,"integrity":"sha512-TMqrveadHW+clY0/t6kOOI/bE93+DzCFJgNZMIFOC42TUVwpit6YplhV/NFsaewzJ7+1bETjIVmSYkARKeo3rQ==","mode":420,"size":271},"_asciiToArray.js":{"checkedAt":1794532111291,"integrity":"sha512-ck3j5d7YhEHe7uccjCyle+vPbsaNrSeWQF5a4b1bTYcg6Q1tDaP04hiwMY4yIe1LZ0OHImuFfQo7j5a6XFgAUA==","mode":420,"size":257},"_asciiWords.js":{"checkedAt":1794532111291,"integrity":"sha512-yZYTIxtj6Z6ZZEbXcTkWvFjgII67ytCBgOZ8s3FPHAmwCx8hGgqwv94GXC7mnAY+C+NwbpqeLhnVSjEZ7jfNmQ==","mode":420,"size":404},"_assignMergeValue.js":{"checkedAt":1794532111291,"integrity":"sha512-NGufZwwqn4XotZ3byKsQzqiMi+nmiZtWgMTS/PLxLYwIIG9gTyI7tpbMgTLiklh8EjG83/ZCw9mk8Cs4Ep5uBg==","mode":420,"size":582},"_assignValue.js":{"checkedAt":1794532111292,"integrity":"sha512-+a+I5doAiut642dgHtBx6gTYpJ4aENIk5vHFgWSkQA77YVWLDKviqgx2+K8GaZIvnWuuCg1vPFvVqH4B6CYu/g==","mode":420,"size":899},"_assocIndexOf.js":{"checkedAt":1794532111292,"integrity":"sha512-31bgdnDWSA6obrk5g8OLYIJKqQHEfq5fzKibJrwjjL5LDQRMH+4Vt+glS8BdFS35uPk2SvETw91ZKpTeVi96eg==","mode":420,"size":487},"_baseAggregator.js":{"checkedAt":1794532111292,"integrity":"sha512-IVXkRGeIth4TioV59wj4cwdO5icXOYmLyipz6C1ISiMLYBpw3eK+m8jgWbh8oA8TMW5Rzocim0aqYvVJBs5VHg==","mode":420,"size":746},"_baseAssign.js":{"checkedAt":1794532111292,"integrity":"sha512-jJ+A3hVi/Yh0jvkzogGYY5QxHdUzvQMsLOZKbdCfh2swkvXkIISILJax+Nm1TnHSH8SdITVBmlNOmU3gkNX56A==","mode":420,"size":470},"_baseAssignIn.js":{"checkedAt":1794532111292,"integrity":"sha512-ca3atUCyjwZiYHETlC8u79tFZANGUKRAwqvgusm/CcXM5NE8DM9TBPcMLine truncated
@@ -0,0 +1 @@
{"name":"@tanstack/virtual-core","version":"3.11.3","requiresBuild":false,"files":{"dist/cjs/index.cjs":{"checkedAt":1794532120287,"integrity":"sha512-mmYm/W6eWdnVuUd3qgo1J0osF22L+bdHEhpYcWST16Jxq2zPHzVyXQ6lNSyK4K+6RrAO8L47zxDbcd0TO1FFKQ==","mode":420,"size":25183},"dist/cjs/utils.cjs":{"checkedAt":1794532108670,"integrity":"sha512-EttFWr3hMXxJoJBG1T7AtQgtNzuhoGF4n9TecR2mr6zSS9Tey/zG0GhTJ7bzhegLNxDseHk9t1CuTAkF/rhiuA==","mode":420,"size":2182},"dist/cjs/index.d.cts":{"checkedAt":1794532108671,"integrity":"sha512-vZ+ItRosnjms8MmtyxkXmKbWpDfw5oZumiALMTXmNVMHmDaOYIkaacp2+wSjgVhwpSc78aIZ+o3y89Q/XkJMAg==","mode":420,"size":6132},"dist/cjs/utils.d.cts":{"checkedAt":1794532108671,"integrity":"sha512-ttvDRC5UADFTLQx0LLVyc3F4Cn2AWit+IqTMkmiA8pN/p3zA1Du4AaPPpJ2dZy7VKFMIrdk7HC1rV1psRizdig==","mode":420,"size":737},"dist/esm/index.js":{"checkedAt":1794532120288,"integrity":"sha512-X6eqgXmW1iidY5rg5Ff2q0OQjLHPAIjO5qL2F+RVbFmXeAYyZYFuPeM86+4DIMxDmsWwc5aeNCnqapQ1RQRTfw==","mode":420,"size":24719},"dist/esm/utils.js":{"checkedAt":1794532108671,"integrity":"sha512-1q/bnA165COX+L6hh4VqLZNnlYmFOVXvGfnxTfrlLjJSdgROeIHpftZEkxwPGgetUmvdzaZuHAAWm47QmvHq1Q==","mode":420,"size":2034},"package.json":{"checkedAt":1794532120288,"integrity":"sha512-Q53zuoWEHbRuw8iNyB14TdNpHad6WRAvSYlbMeZxWhfB3AP4GPDPDvDCeAa0jrmg+jQVb7i16a4pIJMKtWcyHw==","mode":420,"size":1089},"dist/cjs/index.cjs.map":{"checkedAt":1794532120288,"integrity":"sha512-RfEEqBDbobZQ/bbZZOedYoBhXgVz03yTshx4fG9aWwGEK20OJORyi5zUKPPIt6EVOPhh9ZIjELP2lzfBGEzQLQ==","mode":420,"size":45108},"dist/esm/index.js.map":{"checkedAt":1794532120289,"integrity":"sha512-1usUB+3z5sGAFPyO8Uu7dxx0qlvOAILCI9js4uzSt5TI/j+6iwa1JsAT32xl404KDUpkDl5V37VVV8LQJyCFCA==","mode":420,"size":44971},"dist/cjs/utils.cjs.map":{"checkedAt":1794532108672,"integrity":"sha512-cxamP+U1ezB5WNqhGvlhLxmH2ntfla7FzLT54WttDvTLRYzk7DWZnOX957fFfmkBxrIfO4892qASb9DncZ2pZQ==","mode":420,"size":3889},"dist/esm/utils.js.map":{"checkedAt":1794532108672,"integrity":"sha512-FJt6He4/Ki5V0gocpvHQuXghMxl4/XixC8yaiLpR/8NiekT70JJqn6+ug5CyrbM3JnF2J58BdHKqVYzWi/lXbQ==","mode":420,"size":3885},"dist/esm/index.d.ts":{"checkedAt":1794532108672,"integrity":"sha512-EVtuml8iXx4ZUVajoideJg9zrmKK6udu49i7fms7V6REUcHB3mjNLnSg9M9o1PJEGGC408nbMPQo7rHek1/Hbg==","mode":420,"size":6131},"src/index.ts":{"checkedAt":1794532120289,"integrity":"sha512-z/oNnvdAXTu89azXtXY9IbPMHWjm2IRzMjAMY6JR00omSGvUvyd500+lr96w1NfPL29kXgC9vm2KmpoRAEEiyw==","mode":420,"size":28073},"dist/esm/utils.d.ts":{"checkedAt":1794532108671,"integrity":"sha512-ttvDRC5UADFTLQx0LLVyc3F4Cn2AWit+IqTMkmiA8pN/p3zA1Du4AaPPpJ2dZy7VKFMIrdk7HC1rV1psRizdig==","mode":420,"size":737},"src/utils.ts":{"checkedAt":1794532108673,"integrity":"sha512-A+sy8cVVAouqaOXLatCf7HUjHxYRqdKFquBLvnKI3CkNcZyktdrSBf/h/v8xBvLTNHT9YAGyhPtJr5rspZg3lQ==","mode":420,"size":2364},"LICENSE":{"checkedAt":1794532108673,"integrity":"sha512-WxtFIdggoRh30SS8TYSc02iM8s4IjRzRhQrMRS3MpMFMBjXm7XdZynlNto4YSzcwwKwOG8mcHFszSJLjYm0hHg==","mode":420,"size":1079}}}
@@ -0,0 +1,42 @@
"use strict";
// THIS CODE WAS AUTOMATICALLY GENERATED
// DO NOT EDIT THIS CODE BY HAND
// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE:
// npx nx generate-lib repo
Object.defineProperty(exports, "__esModule", { value: true });
exports.webworker_iterable = void 0;
const base_config_1 = require("./base-config");
exports.webworker_iterable = {
libs: [],
variables: [
['CSSNumericArray', base_config_1.TYPE],
['CSSTransformValue', base_config_1.TYPE],
['CSSUnparsedValue', base_config_1.TYPE],
['Cache', base_config_1.TYPE],
['CanvasPath', base_config_1.TYPE],
['CanvasPathDrawingStyles', base_config_1.TYPE],
['CookieStoreManager', base_config_1.TYPE],
['DOMStringList', base_config_1.TYPE],
['FileList', base_config_1.TYPE],
['FontFaceSet', base_config_1.TYPE],
['FormDataIterator', base_config_1.TYPE],
['FormData', base_config_1.TYPE],
['HeadersIterator', base_config_1.TYPE],
['Headers', base_config_1.TYPE],
['IDBDatabase', base_config_1.TYPE],
['IDBObjectStore', base_config_1.TYPE],
['ImageTrackList', base_config_1.TYPE],
['MessageEvent', base_config_1.TYPE],
['StylePropertyMapReadOnlyIterator', base_config_1.TYPE],
['StylePropertyMapReadOnly', base_config_1.TYPE],
['SubtleCrypto', base_config_1.TYPE],
['URLSearchParamsIterator', base_config_1.TYPE],
['URLSearchParams', base_config_1.TYPE],
['WEBGL_draw_buffers', base_config_1.TYPE],
['WEBGL_multi_draw', base_config_1.TYPE],
['WebGL2RenderingContextBase', base_config_1.TYPE],
['WebGL2RenderingContextOverloads', base_config_1.TYPE],
['WebGLRenderingContextBase', base_config_1.TYPE],
['WebGLRenderingContextOverloads', base_config_1.TYPE],
],
};
@@ -0,0 +1,30 @@
"use strict";
const pattern = /-(\w|$)/g;
const callback = (dashChar, char) => char.toUpperCase();
const camelCaseCSS = property =>
{
property = property.toLowerCase();
// NOTE :: IE8's "styleFloat" is intentionally not supported
if (property === "float")
{
return "cssFloat";
}
// Microsoft vendor-prefixes are uniquely cased
else if (property.startsWith("-ms-"))
{
return property.substr(1).replace(pattern, callback);
}
else
{
return property.replace(pattern, callback);
}
};
module.exports = camelCaseCSS;
@@ -0,0 +1,11 @@
const isNotNull = (value) => value !== null;
function getFinalKeyframe(keyframes, { repeat, repeatType = "loop" }, finalKeyframe, speed = 1) {
const resolvedKeyframes = keyframes.filter(isNotNull);
const useFirstKeyframe = speed < 0 || (repeat && repeatType !== "loop" && repeat % 2 === 1);
const index = useFirstKeyframe ? 0 : resolvedKeyframes.length - 1;
return !index || finalKeyframe === undefined
? resolvedKeyframes[index]
: finalKeyframe;
}
export { getFinalKeyframe };
@@ -0,0 +1,108 @@
/**
* @author Toru Nagashima <https://github.com/mysticatea>
* See LICENSE file in root directory for full license.
*/
"use strict"
// https://www-archive.mozilla.org/js/language/E262-3.pdf
const keywords = new Set([
"abstract",
"boolean",
"break",
"byte",
"case",
"catch",
"char",
"class",
"const",
"continue",
"debugger",
"default",
"delete",
"do",
"double",
"else",
"enum",
"export",
"extends",
"false",
"final",
"finally",
"float",
"for",
"function",
"goto",
"if",
"implements",
"import",
"in",
"instanceof",
"int",
"interface",
"long",
"native",
"new",
"null",
"package",
"private",
"protected",
"public",
"return",
"short",
"static",
"super",
"switch",
"synchronized",
"this",
"throw",
"throws",
"transient",
"true",
"try",
"typeof",
"var",
"void",
"volatile",
"while",
"with",
])
module.exports = {
meta: {
docs: {
description: "disallow reserved words as property names.",
category: "ES5",
recommended: false,
url:
"http://mysticatea.github.io/eslint-plugin-es/rules/no-keyword-properties.html",
},
fixable: null,
messages: {
forbidden: "ES5 reserved words as property names are forbidden.",
},
schema: [],
type: "problem",
},
create(context) {
return {
Property(node) {
if (
!node.computed &&
node.key.type === "Identifier" &&
keywords.has(node.key.name)
) {
context.report({ node, messageId: "forbidden" })
}
},
MemberExpression(node) {
if (
!node.computed &&
node.property.type === "Identifier" &&
keywords.has(node.property.name)
) {
context.report({ node, messageId: "forbidden" })
}
},
}
},
}
@@ -0,0 +1,402 @@
gauge
=====
A nearly stateless terminal based horizontal gauge / progress bar.
```javascript
var Gauge = require("gauge")
var gauge = new Gauge()
gauge.show("working…", 0)
setTimeout(() => { gauge.pulse(); gauge.show("working…", 0.25) }, 500)
setTimeout(() => { gauge.pulse(); gauge.show("working…", 0.50) }, 1000)
setTimeout(() => { gauge.pulse(); gauge.show("working…", 0.75) }, 1500)
setTimeout(() => { gauge.pulse(); gauge.show("working…", 0.99) }, 2000)
setTimeout(() => gauge.hide(), 2300)
```
See also the [demos](docs/demo.js):
![](./docs/gauge-demo.gif)
### CHANGES FROM 1.x
Gauge 2.x is breaking release, please see the [changelog] for details on
what's changed if you were previously a user of this module.
[changelog]: CHANGELOG.md
### THE GAUGE CLASS
This is the typical interface to the module– it provides a pretty
fire-and-forget interface to displaying your status information.
```
var Gauge = require("gauge")
var gauge = new Gauge([stream], [options])
```
* **stream** – *(optional, default STDERR)* A stream that progress bar
updates are to be written to. Gauge honors backpressure and will pause
most writing if it is indicated.
* **options** – *(optional)* An option object.
Constructs a new gauge. Gauges are drawn on a single line, and are not drawn
if **stream** isn't a tty and a tty isn't explicitly provided.
If **stream** is a terminal or if you pass in **tty** to **options** then we
will detect terminal resizes and redraw to fit. We do this by watching for
`resize` events on the tty. (To work around a bug in versions of Node prior
to 2.5.0, we watch for them on stdout if the tty is stderr.) Resizes to
larger window sizes will be clean, but shrinking the window will always
result in some cruft.
**IMPORTANT:** If you previously were passing in a non-tty stream but you still
want output (for example, a stream wrapped by the `ansi` module) then you
need to pass in the **tty** option below, as `gauge` needs access to
the underlying tty in order to do things like terminal resizes and terminal
width detection.
The **options** object can have the following properties, all of which are
optional:
* **updateInterval**: How often gauge updates should be drawn, in milliseconds.
* **fixedFramerate**: Defaults to false on node 0.8, true on everything
else. When this is true a timer is created to trigger once every
`updateInterval` ms, when false, updates are printed as soon as they come
in but updates more often than `updateInterval` are ignored. The reason
0.8 doesn't have this set to true is that it can't `unref` its timer and
so it would stop your program from exiting– if you want to use this
feature with 0.8 just make sure you call `gauge.disable()` before you
expect your program to exit.
* **themes**: A themeset to use when selecting the theme to use. Defaults
to `gauge/themes`, see the [themes] documentation for details.
* **theme**: Select a theme for use, it can be a:
* Theme object, in which case the **themes** is not used.
* The name of a theme, which will be looked up in the current *themes*
object.
* A configuration object with any of `hasUnicode`, `hasColor` or
`platform` keys, which if will be used to override our guesses when making
a default theme selection.
If no theme is selected then a default is picked using a combination of our
best guesses at your OS, color support and unicode support.
* **template**: Describes what you want your gauge to look like. The
default is what npm uses. Detailed [documentation] is later in this
document.
* **hideCursor**: Defaults to true. If true, then the cursor will be hidden
while the gauge is displayed.
* **tty**: The tty that you're ultimately writing to. Defaults to the same
as **stream**. This is used for detecting the width of the terminal and
resizes. The width used is `tty.columns - 1`. If no tty is available then
a width of `79` is assumed.
* **enabled**: Defaults to true if `tty` is a TTY, false otherwise. If true
the gauge starts enabled. If disabled then all update commands are
ignored and no gauge will be printed until you call `.enable()`.
* **Plumbing**: The class to use to actually generate the gauge for
printing. This defaults to `require('gauge/plumbing')` and ordinarily you
shouldn't need to override this.
* **cleanupOnExit**: Defaults to true. Ordinarily we register an exit
handler to make sure your cursor is turned back on and the progress bar
erased when your process exits, even if you Ctrl-C out or otherwise exit
unexpectedly. You can disable this and it won't register the exit handler.
[has-unicode]: https://www.npmjs.com/package/has-unicode
[themes]: #themes
[documentation]: #templates
#### `gauge.show(section | status, [completed])`
The first argument is either the section, the name of the current thing
contributing to progress, or an object with keys like **section**,
**subsection** & **completed** (or any others you have types for in a custom
template). If you don't want to update or set any of these you can pass
`null` and it will be ignored.
The second argument is the percent completed as a value between 0 and 1.
Without it, completion is just not updated. You'll also note that completion
can be passed in as part of a status object as the first argument. If both
it and the completed argument are passed in, the completed argument wins.
#### `gauge.hide([cb])`
Removes the gauge from the terminal. Optionally, callback `cb` after IO has
had an opportunity to happen (currently this just means after `setImmediate`
has called back.)
It turns out this is important when you're pausing the progress bar on one
filehandle and printing to another– otherwise (with a big enough print) node
can end up printing the "end progress bar" bits to the progress bar filehandle
while other stuff is printing to another filehandle. These getting interleaved
can cause corruption in some terminals.
#### `gauge.pulse([subsection])`
* **subsection** – *(optional)* The specific thing that triggered this pulse
Spins the spinner in the gauge to show output. If **subsection** is
included then it will be combined with the last name passed to `gauge.show`.
#### `gauge.disable()`
Hides the gauge and ignores further calls to `show` or `pulse`.
#### `gauge.enable()`
Shows the gauge and resumes updating when `show` or `pulse` is called.
#### `gauge.isEnabled()`
Returns true if the gauge is enabled.
#### `gauge.setThemeset(themes)`
Change the themeset to select a theme from. The same as the `themes` option
used in the constructor. The theme will be reselected from this themeset.
#### `gauge.setTheme(theme)`
Change the active theme, will be displayed with the next show or pulse. This can be:
* Theme object, in which case the **themes** is not used.
* The name of a theme, which will be looked up in the current *themes*
object.
* A configuration object with any of `hasUnicode`, `hasColor` or
`platform` keys, which if will be used to override our guesses when making
a default theme selection.
If no theme is selected then a default is picked using a combination of our
best guesses at your OS, color support and unicode support.
#### `gauge.setTemplate(template)`
Change the active template, will be displayed with the next show or pulse
### Tracking Completion
If you have more than one thing going on that you want to track completion
of, you may find the related [are-we-there-yet] helpful. It's `change`
event can be wired up to the `show` method to get a more traditional
progress bar interface.
[are-we-there-yet]: https://www.npmjs.com/package/are-we-there-yet
### THEMES
```
var themes = require('gauge/themes')
// fetch the default color unicode theme for this platform
var ourTheme = themes({hasUnicode: true, hasColor: true})
// fetch the default non-color unicode theme for osx
var ourTheme = themes({hasUnicode: true, hasColor: false, platform: 'darwin'})
// create a new theme based on the color ascii theme for this platform
// that brackets the progress bar with arrows
var ourTheme = themes.newTheme(themes({hasUnicode: false, hasColor: true}), {
preProgressbar: '→',
postProgressbar: '←'
})
```
The object returned by `gauge/themes` is an instance of the `ThemeSet` class.
```
var ThemeSet = require('gauge/theme-set')
var themes = new ThemeSet()
// or
var themes = require('gauge/themes')
var mythemes = themes.newThemeSet() // creates a new themeset based on the default themes
```
#### themes(opts)
#### themes.getDefault(opts)
Theme objects are a function that fetches the default theme based on
platform, unicode and color support.
Options is an object with the following properties:
* **hasUnicode** - If true, fetch a unicode theme, if no unicode theme is
available then a non-unicode theme will be used.
* **hasColor** - If true, fetch a color theme, if no color theme is
available a non-color theme will be used.
* **platform** (optional) - Defaults to `process.platform`. If no
platform match is available then `fallback` is used instead.
If no compatible theme can be found then an error will be thrown with a
`code` of `EMISSINGTHEME`.
#### themes.addTheme(themeName, themeObj)
#### themes.addTheme(themeName, [parentTheme], newTheme)
Adds a named theme to the themeset. You can pass in either a theme object,
as returned by `themes.newTheme` or the arguments you'd pass to
`themes.newTheme`.
#### themes.getThemeNames()
Return a list of all of the names of the themes in this themeset. Suitable
for use in `themes.getTheme(…)`.
#### themes.getTheme(name)
Returns the theme object from this theme set named `name`.
If `name` does not exist in this themeset an error will be thrown with
a `code` of `EMISSINGTHEME`.
#### themes.setDefault([opts], themeName)
`opts` is an object with the following properties.
* **platform** - Defaults to `'fallback'`. If your theme is platform
specific, specify that here with the platform from `process.platform`, eg,
`win32`, `darwin`, etc.
* **hasUnicode** - Defaults to `false`. If your theme uses unicode you
should set this to true.
* **hasColor** - Defaults to `false`. If your theme uses color you should
set this to true.
`themeName` is the name of the theme (as given to `addTheme`) to use for
this set of `opts`.
#### themes.newTheme([parentTheme,] newTheme)
Create a new theme object based on `parentTheme`. If no `parentTheme` is
provided then a minimal parentTheme that defines functions for rendering the
activity indicator (spinner) and progress bar will be defined. (This
fallback parent is defined in `gauge/base-theme`.)
newTheme should be a bare object– we'll start by discussing the properties
defined by the default themes:
* **preProgressbar** - displayed prior to the progress bar, if the progress
bar is displayed.
* **postProgressbar** - displayed after the progress bar, if the progress bar
is displayed.
* **progressBarTheme** - The subtheme passed through to the progress bar
renderer, it's an object with `complete` and `remaining` properties
that are the strings you want repeated for those sections of the progress
bar.
* **activityIndicatorTheme** - The theme for the activity indicator (spinner),
this can either be a string, in which each character is a different step, or
an array of strings.
* **preSubsection** - Displayed as a separator between the `section` and
`subsection` when the latter is printed.
More generally, themes can have any value that would be a valid value when rendering
templates. The properties in the theme are used when their name matches a type in
the template. Their values can be:
* **strings & numbers** - They'll be included as is
* **function (values, theme, width)** - Should return what you want in your output.
*values* is an object with values provided via `gauge.show`,
*theme* is the theme specific to this item (see below) or this theme object,
and *width* is the number of characters wide your result should be.
There are a couple of special prefixes:
* **pre** - Is shown prior to the property, if its displayed.
* **post** - Is shown after the property, if its displayed.
And one special suffix:
* **Theme** - Its value is passed to a function-type item as the theme.
#### themes.addToAllThemes(theme)
This *mixes-in* `theme` into all themes currently defined. It also adds it
to the default parent theme for this themeset, so future themes added to
this themeset will get the values from `theme` by default.
#### themes.newThemeSet()
Copy the current themeset into a new one. This allows you to easily inherit
one themeset from another.
### TEMPLATES
A template is an array of objects and strings that, after being evaluated,
will be turned into the gauge line. The default template is:
```javascript
[
{type: 'progressbar', length: 20},
{type: 'activityIndicator', kerning: 1, length: 1},
{type: 'section', kerning: 1, default: ''},
{type: 'subsection', kerning: 1, default: ''}
]
```
The various template elements can either be **plain strings**, in which case they will
be be included verbatum in the output, or objects with the following properties:
* *type* can be any of the following plus any keys you pass into `gauge.show` plus
any keys you have on a custom theme.
* `section` – What big thing you're working on now.
* `subsection` – What component of that thing is currently working.
* `activityIndicator` – Shows a spinner using the `activityIndicatorTheme`
from your active theme.
* `progressbar` – A progress bar representing your current `completed`
using the `progressbarTheme` from your active theme.
* *kerning* – Number of spaces that must be between this item and other
items, if this item is displayed at all.
* *maxLength* – The maximum length for this element. If its value is longer it
will be truncated.
* *minLength* – The minimum length for this element. If its value is shorter it
will be padded according to the *align* value.
* *align* – (Default: left) Possible values "left", "right" and "center". Works
as you'd expect from word processors.
* *length* – Provides a single value for both *minLength* and *maxLength*. If both
*length* and *minLength or *maxLength* are specified then the latter take precedence.
* *value* – A literal value to use for this template item.
* *default* – A default value to use for this template item if a value
wasn't otherwise passed in.
### PLUMBING
This is the super simple, assume nothing, do no magic internals used by gauge to
implement its ordinary interface.
```
var Plumbing = require('gauge/plumbing')
var gauge = new Plumbing(theme, template, width)
```
* **theme**: The theme to use.
* **template**: The template to use.
* **width**: How wide your gauge should be
#### `gauge.setTheme(theme)`
Change the active theme.
#### `gauge.setTemplate(template)`
Change the active template.
#### `gauge.setWidth(width)`
Change the width to render at.
#### `gauge.hide()`
Return the string necessary to hide the progress bar
#### `gauge.hideCursor()`
Return a string to hide the cursor.
#### `gauge.showCursor()`
Return a string to show the cursor.
#### `gauge.show(status)`
Using `status` for values, render the provided template with the theme and return
a string that is suitable for printing to update the gauge.
@@ -0,0 +1,30 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = unicode2xml;
var _string = _interopRequireDefault(require("../../common/string"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* @file unicode字符转xml字符编码
* @author mengke01(kekee000@gmail.com)
*/
/**
* unicode 转xml编码格式
*
* @param {Array.<number>} unicodeList unicode字符列表
* @return {string} xml编码格式
*/
function unicode2xml(unicodeList) {
if (typeof unicodeList === 'number') {
unicodeList = [unicodeList];
}
return unicodeList.map(function (u) {
if (u < 0x20) {
return '';
}
return u >= 0x20 && u <= 255 ? _string.default.encodeHTML(String.fromCharCode(u)) : '&#x' + u.toString(16) + ';';
}).join('');
}
@@ -0,0 +1,4 @@
type Resolve = (source: string | null) => string;
export default function resolver(mapUrl: string | null | undefined, sourceRoot: string | undefined): Resolve;
export {};
//# sourceMappingURL=resolve.d.ts.map
@@ -0,0 +1,3 @@
declare const _exports: import('eslint').Rule.RuleModule;
export = _exports;
//# sourceMappingURL=static-property-placement.d.ts.map
@@ -0,0 +1,104 @@
/**
* create-logger.js: Logger factory for winston logger instances.
*
* (C) 2010 Charlie Robbins
* MIT LICENCE
*/
'use strict';
const { LEVEL } = require('triple-beam');
const config = require('./config');
const Logger = require('./logger');
const debug = require('@dabh/diagnostics')('winston:create-logger');
function isLevelEnabledFunctionName(level) {
return 'is' + level.charAt(0).toUpperCase() + level.slice(1) + 'Enabled';
}
/**
* Create a new instance of a winston Logger. Creates a new
* prototype for each instance.
* @param {!Object} opts - Options for the created logger.
* @returns {Logger} - A newly created logger instance.
*/
module.exports = function (opts = {}) {
//
// Default levels: npm
//
opts.levels = opts.levels || config.npm.levels;
/**
* DerivedLogger to attach the logs level methods.
* @type {DerivedLogger}
* @extends {Logger}
*/
class DerivedLogger extends Logger {
/**
* Create a new class derived logger for which the levels can be attached to
* the prototype of. This is a V8 optimization that is well know to increase
* performance of prototype functions.
* @param {!Object} options - Options for the created logger.
*/
constructor(options) {
super(options);
}
}
const logger = new DerivedLogger(opts);
//
// Create the log level methods for the derived logger.
//
Object.keys(opts.levels).forEach(function (level) {
debug('Define prototype method for "%s"', level);
if (level === 'log') {
// eslint-disable-next-line no-console
console.warn('Level "log" not defined: conflicts with the method "log". Use a different level name.');
return;
}
//
// Define prototype methods for each log level e.g.:
// logger.log('info', msg) implies these methods are defined:
// - logger.info(msg)
// - logger.isInfoEnabled()
//
// Remark: to support logger.child this **MUST** be a function
// so it'll always be called on the instance instead of a fixed
// place in the prototype chain.
//
DerivedLogger.prototype[level] = function (...args) {
// Prefer any instance scope, but default to "root" logger
const self = this || logger;
// Optimize the hot-path which is the single object.
if (args.length === 1) {
const [msg] = args;
const info = msg && msg.message && msg || { message: msg };
info.level = info[LEVEL] = level;
self._addDefaultMeta(info);
self.write(info);
return (this || logger);
}
// When provided nothing assume the empty string
if (args.length === 0) {
self.log(level, '');
return self;
}
// Otherwise build argument list which could potentially conform to
// either:
// . v3 API: log(obj)
// 2. v1/v2 API: log(level, msg, ... [string interpolate], [{metadata}], [callback])
return self.log(level, ...args);
};
DerivedLogger.prototype[isLevelEnabledFunctionName(level)] = function () {
return (this || logger).isLevelEnabled(level);
};
});
return logger;
};
@@ -0,0 +1,196 @@
# gensync
This module allows for developers to write common code that can share
implementation details, hiding whether an underlying request happens
synchronously or asynchronously. This is in contrast with many current Node
APIs which explicitly implement the same API twice, once with calls to
synchronous functions, and once with asynchronous functions.
Take for example `fs.readFile` and `fs.readFileSync`, if you're writing an API
that loads a file and then performs a synchronous operation on the data, it
can be frustrating to maintain two parallel functions.
## Example
```js
const fs = require("fs");
const gensync = require("gensync");
const readFile = gensync({
sync: fs.readFileSync,
errback: fs.readFile,
});
const myOperation = gensync(function* (filename) {
const code = yield* readFile(filename, "utf8");
return "// some custom prefix\n" + code;
});
// Load and add the prefix synchronously:
const result = myOperation.sync("./some-file.js");
// Load and add the prefix asynchronously with promises:
myOperation.async("./some-file.js").then(result => {
});
// Load and add the prefix asynchronously with promises:
myOperation.errback("./some-file.js", (err, result) => {
});
```
This could even be exposed as your official API by doing
```js
// Using the common 'Sync' suffix for sync functions, and 'Async' suffix for
// promise-returning versions.
exports.myOperationSync = myOperation.sync;
exports.myOperationAsync = myOperation.async;
exports.myOperation = myOperation.errback;
```
or potentially expose one of the async versions as the default, with a
`.sync` property on the function to expose the synchronous version.
```js
module.exports = myOperation.errback;
module.exports.sync = myOperation.sync;
````
## API
### gensync(generatorFnOrOptions)
Returns a function that can be "await"-ed in another `gensync` generator
function, or executed via
* `.sync(...args)` - Returns the computed value, or throws.
* `.async(...args)` - Returns a promise for the computed value.
* `.errback(...args, (err, result) => {})` - Calls the callback with the computed value, or error.
#### Passed a generator
Wraps the generator to populate the `.sync`/`.async`/`.errback` helpers above to
allow for evaluation of the generator for the final value.
##### Example
```js
const readFile = function* () {
return 42;
};
const readFileAndMore = gensync(function* (){
const val = yield* readFile();
return 42 + val;
});
// In general cases
const code = readFileAndMore.sync("./file.js", "utf8");
readFileAndMore.async("./file.js", "utf8").then(code => {})
readFileAndMore.errback("./file.js", "utf8", (err, code) => {});
// In a generator being called indirectly with .sync/.async/.errback
const code = yield* readFileAndMore("./file.js", "utf8");
```
#### Passed an options object
* `opts.sync`
Example: `(...args) => 4`
A function that will be called when `.sync()` is called on the `gensync()`
result, or when the result is passed to `yield*` in another generator that
is being run synchronously.
Also called for `.async()` calls if no async handlers are provided.
* `opts.async`
Example: `async (...args) => 4`
A function that will be called when `.async()` or `.errback()` is called on
the `gensync()` result, or when the result is passed to `yield*` in another
generator that is being run asynchronously.
* `opts.errback`
Example: `(...args, cb) => cb(null, 4)`
A function that will be called when `.async()` or `.errback()` is called on
the `gensync()` result, or when the result is passed to `yield*` in another
generator that is being run asynchronously.
This option allows for simpler compatibility with many existing Node APIs,
and also avoids introducing the extra even loop turns that promises introduce
to access the result value.
* `opts.name`
Example: `"readFile"`
A string name to apply to the returned function. If no value is provided,
the name of `errback`/`async`/`sync` functions will be used, with any
`Sync` or `Async` suffix stripped off. If the callback is simply named
with ES6 inference (same name as the options property), the name is ignored.
* `opts.arity`
Example: `4`
A number for the length to set on the returned function. If no value
is provided, the length will be carried over from the `sync` function's
`length` value.
##### Example
```js
const readFile = gensync({
sync: fs.readFileSync,
errback: fs.readFile,
});
const code = readFile.sync("./file.js", "utf8");
readFile.async("./file.js", "utf8").then(code => {})
readFile.errback("./file.js", "utf8", (err, code) => {});
```
### gensync.all(iterable)
`Promise.all`-like combinator that works with an iterable of generator objects
that could be passed to `yield*` within a gensync generator.
#### Example
```js
const loadFiles = gensync(function* () {
return yield* gensync.all([
readFile("./one.js"),
readFile("./two.js"),
readFile("./three.js"),
]);
});
```
### gensync.race(iterable)
`Promise.race`-like combinator that works with an iterable of generator objects
that could be passed to `yield*` within a gensync generator.
#### Example
```js
const loadFiles = gensync(function* () {
return yield* gensync.race([
readFile("./one.js"),
readFile("./two.js"),
readFile("./three.js"),
]);
});
```
@@ -0,0 +1,61 @@
# 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).
## [v1.2.0](https://github.com/inspect-js/has-proto/compare/v1.1.0...v1.2.0) - 2024-12-06
### Commits
- [Refactor] use `dunder-proto` instead of `call-bind` [`6e5e76c`](https://github.com/inspect-js/has-proto/commit/6e5e76ce3bf4c01ebb99b38dcd61bee1ba35073f)
- [actions] split out node 10-20, and 20+ [`3b8e9e6`](https://github.com/inspect-js/has-proto/commit/3b8e9e651431ef5e9725dae68881b8107e812ee0)
- [Dev Deps] update `@ljharb/tsconfig`, `gopd` [`57bcd00`](https://github.com/inspect-js/has-proto/commit/57bcd000625c7d1e7f41fd10b4a8e1ea380029dd)
- [actions] skip `npm ls` in node &lt; 10 [`ce3a4d7`](https://github.com/inspect-js/has-proto/commit/ce3a4d76d4f15d94540cb5f2ae50967cc6299ee3)
## [v1.1.0](https://github.com/inspect-js/has-proto/compare/v1.0.3...v1.1.0) - 2024-12-01
### Commits
- [New] add `accessor` and `mutator` endpoints [`144f6a9`](https://github.com/inspect-js/has-proto/commit/144f6a9c2a3925f25058d5d5ea7eab3be57767d9)
- [types] use shared config [`8b597cf`](https://github.com/inspect-js/has-proto/commit/8b597cff2b09f0351bc357cac0e0c7b0c8bb7e70)
- [Refactor] cache result at module level [`88418bd`](https://github.com/inspect-js/has-proto/commit/88418bde7e0c37c7d9aa6cc79150e774004c01d8)
- [Dev Deps] update `@ljharb/eslint-config`, `auto-changelog`, `tape` [`d246200`](https://github.com/inspect-js/has-proto/commit/d246200bae6ceceebb495df7f8eb0f27a017b63f)
- [Deps] update `gopd`, `reflect.getprototypeof` [`6f72364`](https://github.com/inspect-js/has-proto/commit/6f723645da9b5bef0aaae4a1aa66c07a1fed179f)
- [Tests] add `@arethetypeswrong/cli` [`8194e1a`](https://github.com/inspect-js/has-proto/commit/8194e1a607233f63c5bd0b91112c0423b3296ac9)
- [Tests] replace `aud` with `npm audit` [`fd7ad11`](https://github.com/inspect-js/has-proto/commit/fd7ad111dc35488b3200a763204dba0f6087defc)
- [Dev Deps] update `@types/tape` [`2695808`](https://github.com/inspect-js/has-proto/commit/26958086aec0b1cbfdddd4f10e54d2de1facf85c)
- [Dev Deps] add missing peer dep [`fa4b2f7`](https://github.com/inspect-js/has-proto/commit/fa4b2f77f7c0071e1c06b5590c9bada8e6b2edce)
## [v1.0.3](https://github.com/inspect-js/has-proto/compare/v1.0.2...v1.0.3) - 2024-02-19
### Commits
- [types] add missing declaration file [`26ecade`](https://github.com/inspect-js/has-proto/commit/26ecade05d253bb5dc376945ee3186d1fbe334f8)
## [v1.0.2](https://github.com/inspect-js/has-proto/compare/v1.0.1...v1.0.2) - 2024-02-19
### Commits
- add types [`6435262`](https://github.com/inspect-js/has-proto/commit/64352626cf511c0276d5f4bb6be770a0bf0f8524)
- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `npmignore`, `tape` [`f16a5e4`](https://github.com/inspect-js/has-proto/commit/f16a5e4121651e551271419f9d60fdd3561fd82c)
- [Refactor] tiny cleanup [`d1f1a4b`](https://github.com/inspect-js/has-proto/commit/d1f1a4bdc135f115a10f148ce302676224534702)
- [meta] add `sideEffects` flag [`e7ab1a6`](https://github.com/inspect-js/has-proto/commit/e7ab1a6f153b3e80dee68d1748b71e46767a0531)
## [v1.0.1](https://github.com/inspect-js/has-proto/compare/v1.0.0...v1.0.1) - 2022-12-21
### Commits
- [meta] correct URLs and description [`ef34483`](https://github.com/inspect-js/has-proto/commit/ef34483ca0d35680f271b6b96e35526151b25dfc)
- [patch] add an additional criteria [`e81959e`](https://github.com/inspect-js/has-proto/commit/e81959ed7c7a77fbf459f00cb4ef824f1099497f)
- [Dev Deps] update `aud` [`2bec2c4`](https://github.com/inspect-js/has-proto/commit/2bec2c47b072b122ff5443fba0263f6dc649531f)
## v1.0.0 - 2022-12-12
### Commits
- Initial implementation, tests, readme [`6886fea`](https://github.com/inspect-js/has-proto/commit/6886fea578f67daf69a7920b2eb7637ea6ebb0bc)
- Initial commit [`99129c8`](https://github.com/inspect-js/has-proto/commit/99129c8f42471ac89cb681ba9cb9d52a583eb94f)
- npm init [`2844ad8`](https://github.com/inspect-js/has-proto/commit/2844ad8e75b84d66a46765b3bab9d2e8ea692e10)
- Only apps should have lockfiles [`c65bc5e`](https://github.com/inspect-js/has-proto/commit/c65bc5e40b9004463f7336d47c67245fb139a36a)
@@ -0,0 +1,29 @@
export declare const OidbSvcTrpcTcp0XE37_1700: {
command: import("napcat-protobuf").ScalarProtoFieldType<ScalarType.UINT32, true, false>;
seq: import("napcat-protobuf").ScalarProtoFieldType<ScalarType.INT32, true, false>;
upload: import("napcat-protobuf").MessageProtoFieldType<() => {
senderUid: import("napcat-protobuf").ScalarProtoFieldType<ScalarType.STRING, true, false>;
receiverUid: import("napcat-protobuf").ScalarProtoFieldType<ScalarType.STRING, true, false>;
fileSize: import("napcat-protobuf").ScalarProtoFieldType<ScalarType.UINT32, true, false>;
fileName: import("napcat-protobuf").ScalarProtoFieldType<ScalarType.STRING, true, false>;
md510MCheckSum: import("napcat-protobuf").ScalarProtoFieldType<ScalarType.BYTES, true, false>;
sha1CheckSum: import("napcat-protobuf").ScalarProtoFieldType<ScalarType.BYTES, true, false>;
localPath: import("napcat-protobuf").ScalarProtoFieldType<ScalarType.STRING, true, false>;
md5CheckSum: import("napcat-protobuf").ScalarProtoFieldType<ScalarType.BYTES, true, false>;
sha3CheckSum: import("napcat-protobuf").ScalarProtoFieldType<ScalarType.BYTES, true, false>;
}, true, false>;
businessId: import("napcat-protobuf").ScalarProtoFieldType<ScalarType.INT32, true, false>;
clientType: import("napcat-protobuf").ScalarProtoFieldType<ScalarType.INT32, true, false>;
flagSupportMediaPlatform: import("napcat-protobuf").ScalarProtoFieldType<ScalarType.INT32, true, false>;
};
export declare const ApplyUploadReqV3: {
senderUid: import("napcat-protobuf").ScalarProtoFieldType<ScalarType.STRING, true, false>;
receiverUid: import("napcat-protobuf").ScalarProtoFieldType<ScalarType.STRING, true, false>;
fileSize: import("napcat-protobuf").ScalarProtoFieldType<ScalarType.UINT32, true, false>;
fileName: import("napcat-protobuf").ScalarProtoFieldType<ScalarType.STRING, true, false>;
md510MCheckSum: import("napcat-protobuf").ScalarProtoFieldType<ScalarType.BYTES, true, false>;
sha1CheckSum: import("napcat-protobuf").ScalarProtoFieldType<ScalarType.BYTES, true, false>;
localPath: import("napcat-protobuf").ScalarProtoFieldType<ScalarType.STRING, true, false>;
md5CheckSum: import("napcat-protobuf").ScalarProtoFieldType<ScalarType.BYTES, true, false>;
sha3CheckSum: import("napcat-protobuf").ScalarProtoFieldType<ScalarType.BYTES, true, false>;
};
@@ -0,0 +1,488 @@
'use strict';
const XHTMLEntities = require('./xhtml');
const hexNumber = /^[\da-fA-F]+$/;
const decimalNumber = /^\d+$/;
// The map to `acorn-jsx` tokens from `acorn` namespace objects.
const acornJsxMap = new WeakMap();
// Get the original tokens for the given `acorn` namespace object.
function getJsxTokens(acorn) {
acorn = acorn.Parser.acorn || acorn;
let acornJsx = acornJsxMap.get(acorn);
if (!acornJsx) {
const tt = acorn.tokTypes;
const TokContext = acorn.TokContext;
const TokenType = acorn.TokenType;
const tc_oTag = new TokContext('<tag', false);
const tc_cTag = new TokContext('</tag', false);
const tc_expr = new TokContext('<tag>...</tag>', true, true);
const tokContexts = {
tc_oTag: tc_oTag,
tc_cTag: tc_cTag,
tc_expr: tc_expr
};
const tokTypes = {
jsxName: new TokenType('jsxName'),
jsxText: new TokenType('jsxText', {beforeExpr: true}),
jsxTagStart: new TokenType('jsxTagStart', {startsExpr: true}),
jsxTagEnd: new TokenType('jsxTagEnd')
};
tokTypes.jsxTagStart.updateContext = function() {
this.context.push(tc_expr); // treat as beginning of JSX expression
this.context.push(tc_oTag); // start opening tag context
this.exprAllowed = false;
};
tokTypes.jsxTagEnd.updateContext = function(prevType) {
let out = this.context.pop();
if (out === tc_oTag && prevType === tt.slash || out === tc_cTag) {
this.context.pop();
this.exprAllowed = this.curContext() === tc_expr;
} else {
this.exprAllowed = true;
}
};
acornJsx = { tokContexts: tokContexts, tokTypes: tokTypes };
acornJsxMap.set(acorn, acornJsx);
}
return acornJsx;
}
// Transforms JSX element name to string.
function getQualifiedJSXName(object) {
if (!object)
return 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);
}
module.exports = function(options) {
options = options || {};
return function(Parser) {
return plugin({
allowNamespaces: options.allowNamespaces !== false,
allowNamespacedObjects: !!options.allowNamespacedObjects
}, Parser);
};
};
// This is `tokTypes` of the peer dep.
// This can be different instances from the actual `tokTypes` this plugin uses.
Object.defineProperty(module.exports, "tokTypes", {
get: function get_tokTypes() {
return getJsxTokens(require("acorn")).tokTypes;
},
configurable: true,
enumerable: true
});
function plugin(options, Parser) {
const acorn = Parser.acorn || require("acorn");
const acornJsx = getJsxTokens(acorn);
const tt = acorn.tokTypes;
const tok = acornJsx.tokTypes;
const tokContexts = acorn.tokContexts;
const tc_oTag = acornJsx.tokContexts.tc_oTag;
const tc_cTag = acornJsx.tokContexts.tc_cTag;
const tc_expr = acornJsx.tokContexts.tc_expr;
const isNewLine = acorn.isNewLine;
const isIdentifierStart = acorn.isIdentifierStart;
const isIdentifierChar = acorn.isIdentifierChar;
return class extends Parser {
// Expose actual `tokTypes` and `tokContexts` to other plugins.
static get acornJsx() {
return acornJsx;
}
// Reads inline JSX contents token.
jsx_readToken() {
let out = '', chunkStart = this.pos;
for (;;) {
if (this.pos >= this.input.length)
this.raise(this.start, 'Unterminated JSX contents');
let ch = this.input.charCodeAt(this.pos);
switch (ch) {
case 60: // '<'
case 123: // '{'
if (this.pos === this.start) {
if (ch === 60 && this.exprAllowed) {
++this.pos;
return this.finishToken(tok.jsxTagStart);
}
return this.getTokenFromCode(ch);
}
out += this.input.slice(chunkStart, this.pos);
return this.finishToken(tok.jsxText, out);
case 38: // '&'
out += this.input.slice(chunkStart, this.pos);
out += this.jsx_readEntity();
chunkStart = this.pos;
break;
case 62: // '>'
case 125: // '}'
this.raise(
this.pos,
"Unexpected token `" + this.input[this.pos] + "`. Did you mean `" +
(ch === 62 ? "&gt;" : "&rbrace;") + "` or " + "`{\"" + this.input[this.pos] + "\"}" + "`?"
);
default:
if (isNewLine(ch)) {
out += this.input.slice(chunkStart, this.pos);
out += this.jsx_readNewLine(true);
chunkStart = this.pos;
} else {
++this.pos;
}
}
}
}
jsx_readNewLine(normalizeCRLF) {
let ch = this.input.charCodeAt(this.pos);
let out;
++this.pos;
if (ch === 13 && this.input.charCodeAt(this.pos) === 10) {
++this.pos;
out = normalizeCRLF ? '\n' : '\r\n';
} else {
out = String.fromCharCode(ch);
}
if (this.options.locations) {
++this.curLine;
this.lineStart = this.pos;
}
return out;
}
jsx_readString(quote) {
let out = '', chunkStart = ++this.pos;
for (;;) {
if (this.pos >= this.input.length)
this.raise(this.start, 'Unterminated string constant');
let ch = this.input.charCodeAt(this.pos);
if (ch === quote) break;
if (ch === 38) { // '&'
out += this.input.slice(chunkStart, this.pos);
out += this.jsx_readEntity();
chunkStart = this.pos;
} else if (isNewLine(ch)) {
out += this.input.slice(chunkStart, this.pos);
out += this.jsx_readNewLine(false);
chunkStart = this.pos;
} else {
++this.pos;
}
}
out += this.input.slice(chunkStart, this.pos++);
return this.finishToken(tt.string, out);
}
jsx_readEntity() {
let str = '', count = 0, entity;
let ch = this.input[this.pos];
if (ch !== '&')
this.raise(this.pos, 'Entity must start with an ampersand');
let startPos = ++this.pos;
while (this.pos < this.input.length && count++ < 10) {
ch = this.input[this.pos++];
if (ch === ';') {
if (str[0] === '#') {
if (str[1] === 'x') {
str = str.substr(2);
if (hexNumber.test(str))
entity = String.fromCharCode(parseInt(str, 16));
} else {
str = str.substr(1);
if (decimalNumber.test(str))
entity = String.fromCharCode(parseInt(str, 10));
}
} else {
entity = XHTMLEntities[str];
}
break;
}
str += ch;
}
if (!entity) {
this.pos = startPos;
return '&';
}
return entity;
}
// Read a JSX identifier (valid tag or attribute name).
//
// Optimized version since JSX identifiers can't contain
// escape characters and so can be read as single slice.
// Also assumes that first character was already checked
// by isIdentifierStart in readToken.
jsx_readWord() {
let ch, start = this.pos;
do {
ch = this.input.charCodeAt(++this.pos);
} while (isIdentifierChar(ch) || ch === 45); // '-'
return this.finishToken(tok.jsxName, this.input.slice(start, this.pos));
}
// Parse next token as JSX identifier
jsx_parseIdentifier() {
let node = this.startNode();
if (this.type === tok.jsxName)
node.name = this.value;
else if (this.type.keyword)
node.name = this.type.keyword;
else
this.unexpected();
this.next();
return this.finishNode(node, 'JSXIdentifier');
}
// Parse namespaced identifier.
jsx_parseNamespacedName() {
let startPos = this.start, startLoc = this.startLoc;
let name = this.jsx_parseIdentifier();
if (!options.allowNamespaces || !this.eat(tt.colon)) return name;
var node = this.startNodeAt(startPos, startLoc);
node.namespace = name;
node.name = this.jsx_parseIdentifier();
return this.finishNode(node, 'JSXNamespacedName');
}
// Parses element name in any form - namespaced, member
// or single identifier.
jsx_parseElementName() {
if (this.type === tok.jsxTagEnd) return '';
let startPos = this.start, startLoc = this.startLoc;
let node = this.jsx_parseNamespacedName();
if (this.type === tt.dot && node.type === 'JSXNamespacedName' && !options.allowNamespacedObjects) {
this.unexpected();
}
while (this.eat(tt.dot)) {
let newNode = this.startNodeAt(startPos, startLoc);
newNode.object = node;
newNode.property = this.jsx_parseIdentifier();
node = this.finishNode(newNode, 'JSXMemberExpression');
}
return node;
}
// Parses any type of JSX attribute value.
jsx_parseAttributeValue() {
switch (this.type) {
case tt.braceL:
let node = this.jsx_parseExpressionContainer();
if (node.expression.type === 'JSXEmptyExpression')
this.raise(node.start, 'JSX attributes must only be assigned a non-empty expression');
return node;
case tok.jsxTagStart:
case tt.string:
return this.parseExprAtom();
default:
this.raise(this.start, 'JSX value should be either an expression or a quoted JSX text');
}
}
// JSXEmptyExpression is unique type since it doesn't actually parse anything,
// and so it should start at the end of last read token (left brace) and finish
// at the beginning of the next one (right brace).
jsx_parseEmptyExpression() {
let node = this.startNodeAt(this.lastTokEnd, this.lastTokEndLoc);
return this.finishNodeAt(node, 'JSXEmptyExpression', this.start, this.startLoc);
}
// Parses JSX expression enclosed into curly brackets.
jsx_parseExpressionContainer() {
let node = this.startNode();
this.next();
node.expression = this.type === tt.braceR
? this.jsx_parseEmptyExpression()
: this.parseExpression();
this.expect(tt.braceR);
return this.finishNode(node, 'JSXExpressionContainer');
}
// Parses following JSX attribute name-value pair.
jsx_parseAttribute() {
let node = this.startNode();
if (this.eat(tt.braceL)) {
this.expect(tt.ellipsis);
node.argument = this.parseMaybeAssign();
this.expect(tt.braceR);
return this.finishNode(node, 'JSXSpreadAttribute');
}
node.name = this.jsx_parseNamespacedName();
node.value = this.eat(tt.eq) ? this.jsx_parseAttributeValue() : null;
return this.finishNode(node, 'JSXAttribute');
}
// Parses JSX opening tag starting after '<'.
jsx_parseOpeningElementAt(startPos, startLoc) {
let node = this.startNodeAt(startPos, startLoc);
node.attributes = [];
let nodeName = this.jsx_parseElementName();
if (nodeName) node.name = nodeName;
while (this.type !== tt.slash && this.type !== tok.jsxTagEnd)
node.attributes.push(this.jsx_parseAttribute());
node.selfClosing = this.eat(tt.slash);
this.expect(tok.jsxTagEnd);
return this.finishNode(node, nodeName ? 'JSXOpeningElement' : 'JSXOpeningFragment');
}
// Parses JSX closing tag starting after '</'.
jsx_parseClosingElementAt(startPos, startLoc) {
let node = this.startNodeAt(startPos, startLoc);
let nodeName = this.jsx_parseElementName();
if (nodeName) node.name = nodeName;
this.expect(tok.jsxTagEnd);
return this.finishNode(node, nodeName ? 'JSXClosingElement' : 'JSXClosingFragment');
}
// Parses entire JSX element, including it's opening tag
// (starting after '<'), attributes, contents and closing tag.
jsx_parseElementAt(startPos, startLoc) {
let node = this.startNodeAt(startPos, startLoc);
let children = [];
let openingElement = this.jsx_parseOpeningElementAt(startPos, startLoc);
let closingElement = null;
if (!openingElement.selfClosing) {
contents: for (;;) {
switch (this.type) {
case tok.jsxTagStart:
startPos = this.start; startLoc = this.startLoc;
this.next();
if (this.eat(tt.slash)) {
closingElement = this.jsx_parseClosingElementAt(startPos, startLoc);
break contents;
}
children.push(this.jsx_parseElementAt(startPos, startLoc));
break;
case tok.jsxText:
children.push(this.parseExprAtom());
break;
case tt.braceL:
children.push(this.jsx_parseExpressionContainer());
break;
default:
this.unexpected();
}
}
if (getQualifiedJSXName(closingElement.name) !== getQualifiedJSXName(openingElement.name)) {
this.raise(
closingElement.start,
'Expected corresponding JSX closing tag for <' + getQualifiedJSXName(openingElement.name) + '>');
}
}
let fragmentOrElement = openingElement.name ? 'Element' : 'Fragment';
node['opening' + fragmentOrElement] = openingElement;
node['closing' + fragmentOrElement] = closingElement;
node.children = children;
if (this.type === tt.relational && this.value === "<") {
this.raise(this.start, "Adjacent JSX elements must be wrapped in an enclosing tag");
}
return this.finishNode(node, 'JSX' + fragmentOrElement);
}
// Parse JSX text
jsx_parseText() {
let node = this.parseLiteral(this.value);
node.type = "JSXText";
return node;
}
// Parses entire JSX element from current position.
jsx_parseElement() {
let startPos = this.start, startLoc = this.startLoc;
this.next();
return this.jsx_parseElementAt(startPos, startLoc);
}
parseExprAtom(refShortHandDefaultPos) {
if (this.type === tok.jsxText)
return this.jsx_parseText();
else if (this.type === tok.jsxTagStart)
return this.jsx_parseElement();
else
return super.parseExprAtom(refShortHandDefaultPos);
}
readToken(code) {
let context = this.curContext();
if (context === tc_expr) return this.jsx_readToken();
if (context === tc_oTag || context === tc_cTag) {
if (isIdentifierStart(code)) return this.jsx_readWord();
if (code == 62) {
++this.pos;
return this.finishToken(tok.jsxTagEnd);
}
if ((code === 34 || code === 39) && context == tc_oTag)
return this.jsx_readString(code);
}
if (code === 60 && this.exprAllowed && this.input.charCodeAt(this.pos + 1) !== 33) {
++this.pos;
return this.finishToken(tok.jsxTagStart);
}
return super.readToken(code);
}
updateContext(prevType) {
if (this.type == tt.braceL) {
var curContext = this.curContext();
if (curContext == tc_oTag) this.context.push(tokContexts.b_expr);
else if (curContext == tc_expr) this.context.push(tokContexts.b_tmpl);
else super.updateContext(prevType);
this.exprAllowed = true;
} else if (this.type === tt.slash && prevType === tok.jsxTagStart) {
this.context.length -= 2; // do not consider JSX expr -> JSX open tag -> ... anymore
this.context.push(tc_cTag); // reconsider as closing tag context
this.exprAllowed = false;
} else {
return super.updateContext(prevType);
}
}
};
}
@@ -0,0 +1,24 @@
var isStrictComparable = require('./_isStrictComparable'),
keys = require('./keys');
/**
* Gets the property names, values, and compare flags of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the match data of `object`.
*/
function getMatchData(object) {
var result = keys(object),
length = result.length;
while (length--) {
var key = result[length],
value = object[key];
result[length] = [key, value, isStrictComparable(value)];
}
return result;
}
module.exports = getMatchData;
@@ -0,0 +1,671 @@
/**
* @fileoverview Prevent usage of unknown DOM property
* @author Yannick Croissant
*/
'use strict';
const has = require('hasown');
const docsUrl = require('../util/docsUrl');
const getText = require('../util/eslint').getText;
const testReactVersion = require('../util/version').testReactVersion;
const report = require('../util/report');
// ------------------------------------------------------------------------------
// Constants
// ------------------------------------------------------------------------------
const DEFAULTS = {
ignore: [],
requireDataLowercase: false,
};
const DOM_ATTRIBUTE_NAMES = {
'accept-charset': 'acceptCharset',
class: 'className',
'http-equiv': 'httpEquiv',
crossorigin: 'crossOrigin',
for: 'htmlFor',
nomodule: 'noModule',
};
const ATTRIBUTE_TAGS_MAP = {
abbr: ['th', 'td'],
charset: ['meta'],
checked: ['input'],
// image is required for SVG support, all other tags are HTML.
crossOrigin: ['script', 'img', 'video', 'audio', 'link', 'image'],
displaystyle: ['math'],
// https://html.spec.whatwg.org/multipage/links.html#downloading-resources
download: ['a', 'area'],
fill: [ // https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/fill
// Fill color
'altGlyph',
'circle',
'ellipse',
'g',
'line',
'marker',
'mask',
'path',
'polygon',
'polyline',
'rect',
'svg',
'symbol',
'text',
'textPath',
'tref',
'tspan',
'use',
// Animation final state
'animate',
'animateColor',
'animateMotion',
'animateTransform',
'set',
],
focusable: ['svg'],
imageSizes: ['link'],
imageSrcSet: ['link'],
property: ['meta'],
viewBox: ['marker', 'pattern', 'svg', 'symbol', 'view'],
as: ['link'],
align: ['applet', 'caption', 'col', 'colgroup', 'hr', 'iframe', 'img', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'tr'], // deprecated, but known
valign: ['tr', 'td', 'th', 'thead', 'tbody', 'tfoot', 'colgroup', 'col'], // deprecated, but known
noModule: ['script'],
// Media events allowed only on audio and video tags, see https://github.com/facebook/react/blob/256aefbea1449869620fb26f6ec695536ab453f5/CHANGELOG.md#notable-enhancements
onAbort: ['audio', 'video'],
onCancel: ['dialog'],
onCanPlay: ['audio', 'video'],
onCanPlayThrough: ['audio', 'video'],
onClose: ['dialog'],
onDurationChange: ['audio', 'video'],
onEmptied: ['audio', 'video'],
onEncrypted: ['audio', 'video'],
onEnded: ['audio', 'video'],
onError: ['audio', 'video', 'img', 'link', 'source', 'script', 'picture', 'iframe'],
onLoad: ['script', 'img', 'link', 'picture', 'iframe', 'object', 'source'],
onLoadedData: ['audio', 'video'],
onLoadedMetadata: ['audio', 'video'],
onLoadStart: ['audio', 'video'],
onPause: ['audio', 'video'],
onPlay: ['audio', 'video'],
onPlaying: ['audio', 'video'],
onProgress: ['audio', 'video'],
onRateChange: ['audio', 'video'],
onResize: ['audio', 'video'],
onSeeked: ['audio', 'video'],
onSeeking: ['audio', 'video'],
onStalled: ['audio', 'video'],
onSuspend: ['audio', 'video'],
onTimeUpdate: ['audio', 'video'],
onVolumeChange: ['audio', 'video'],
onWaiting: ['audio', 'video'],
autoPictureInPicture: ['video'],
controls: ['audio', 'video'],
controlsList: ['audio', 'video'],
disablePictureInPicture: ['video'],
disableRemotePlayback: ['audio', 'video'],
loop: ['audio', 'video'],
muted: ['audio', 'video'],
playsInline: ['video'],
allowFullScreen: ['iframe', 'video'],
webkitAllowFullScreen: ['iframe', 'video'],
mozAllowFullScreen: ['iframe', 'video'],
poster: ['video'],
preload: ['audio', 'video'],
scrolling: ['iframe'],
returnValue: ['dialog'],
webkitDirectory: ['input'],
shadowrootmode: ['template'],
shadowrootclonable: ['template'],
shadowrootdelegatesfocus: ['template'],
shadowrootserializable: ['template'],
'transform-origin': ['rect'],
};
const SVGDOM_ATTRIBUTE_NAMES = {
'accent-height': 'accentHeight',
'alignment-baseline': 'alignmentBaseline',
'arabic-form': 'arabicForm',
'baseline-shift': 'baselineShift',
'cap-height': 'capHeight',
'clip-path': 'clipPath',
'clip-rule': 'clipRule',
'color-interpolation': 'colorInterpolation',
'color-interpolation-filters': 'colorInterpolationFilters',
'color-profile': 'colorProfile',
'color-rendering': 'colorRendering',
'dominant-baseline': 'dominantBaseline',
'enable-background': 'enableBackground',
'fill-opacity': 'fillOpacity',
'fill-rule': 'fillRule',
'flood-color': 'floodColor',
'flood-opacity': 'floodOpacity',
'font-family': 'fontFamily',
'font-size': 'fontSize',
'font-size-adjust': 'fontSizeAdjust',
'font-stretch': 'fontStretch',
'font-style': 'fontStyle',
'font-variant': 'fontVariant',
'font-weight': 'fontWeight',
'glyph-name': 'glyphName',
'glyph-orientation-horizontal': 'glyphOrientationHorizontal',
'glyph-orientation-vertical': 'glyphOrientationVertical',
'horiz-adv-x': 'horizAdvX',
'horiz-origin-x': 'horizOriginX',
'image-rendering': 'imageRendering',
'letter-spacing': 'letterSpacing',
'lighting-color': 'lightingColor',
'marker-end': 'markerEnd',
'marker-mid': 'markerMid',
'marker-start': 'markerStart',
'overline-position': 'overlinePosition',
'overline-thickness': 'overlineThickness',
'paint-order': 'paintOrder',
'panose-1': 'panose1',
'pointer-events': 'pointerEvents',
'rendering-intent': 'renderingIntent',
'shape-rendering': 'shapeRendering',
'stop-color': 'stopColor',
'stop-opacity': 'stopOpacity',
'strikethrough-position': 'strikethroughPosition',
'strikethrough-thickness': 'strikethroughThickness',
'stroke-dasharray': 'strokeDasharray',
'stroke-dashoffset': 'strokeDashoffset',
'stroke-linecap': 'strokeLinecap',
'stroke-linejoin': 'strokeLinejoin',
'stroke-miterlimit': 'strokeMiterlimit',
'stroke-opacity': 'strokeOpacity',
'stroke-width': 'strokeWidth',
'text-anchor': 'textAnchor',
'text-decoration': 'textDecoration',
'text-rendering': 'textRendering',
'underline-position': 'underlinePosition',
'underline-thickness': 'underlineThickness',
'unicode-bidi': 'unicodeBidi',
'unicode-range': 'unicodeRange',
'units-per-em': 'unitsPerEm',
'v-alphabetic': 'vAlphabetic',
'v-hanging': 'vHanging',
'v-ideographic': 'vIdeographic',
'v-mathematical': 'vMathematical',
'vector-effect': 'vectorEffect',
'vert-adv-y': 'vertAdvY',
'vert-origin-x': 'vertOriginX',
'vert-origin-y': 'vertOriginY',
'word-spacing': 'wordSpacing',
'writing-mode': 'writingMode',
'x-height': 'xHeight',
'xlink:actuate': 'xlinkActuate',
'xlink:arcrole': 'xlinkArcrole',
'xlink:href': 'xlinkHref',
'xlink:role': 'xlinkRole',
'xlink:show': 'xlinkShow',
'xlink:title': 'xlinkTitle',
'xlink:type': 'xlinkType',
'xml:base': 'xmlBase',
'xml:lang': 'xmlLang',
'xml:space': 'xmlSpace',
};
const DOM_PROPERTY_NAMES_ONE_WORD = [
// Global attributes - can be used on any HTML/DOM element
// See https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes
'dir', 'draggable', 'hidden', 'id', 'lang', 'nonce', 'part', 'slot', 'style', 'title', 'translate', 'inert',
// Element specific attributes
// See https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes (includes global attributes too)
// To be considered if these should be added also to ATTRIBUTE_TAGS_MAP
'accept', 'action', 'allow', 'alt', 'as', 'async', 'buffered', 'capture', 'challenge', 'cite', 'code', 'cols',
'content', 'coords', 'csp', 'data', 'decoding', 'default', 'defer', 'disabled', 'form',
'headers', 'height', 'high', 'href', 'icon', 'importance', 'integrity', 'kind', 'label',
'language', 'loading', 'list', 'loop', 'low', 'manifest', 'max', 'media', 'method', 'min', 'multiple', 'muted',
'name', 'open', 'optimum', 'pattern', 'ping', 'placeholder', 'poster', 'preload', 'profile',
'rel', 'required', 'reversed', 'role', 'rows', 'sandbox', 'scope', 'seamless', 'selected', 'shape', 'size', 'sizes',
'span', 'src', 'start', 'step', 'summary', 'target', 'type', 'value', 'width', 'wmode', 'wrap',
// SVG attributes
// See https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute
'accumulate', 'additive', 'alphabetic', 'amplitude', 'ascent', 'azimuth', 'bbox', 'begin',
'bias', 'by', 'clip', 'color', 'cursor', 'cx', 'cy', 'd', 'decelerate', 'descent', 'direction',
'display', 'divisor', 'dur', 'dx', 'dy', 'elevation', 'end', 'exponent', 'fill', 'filter',
'format', 'from', 'fr', 'fx', 'fy', 'g1', 'g2', 'hanging', 'height', 'hreflang', 'ideographic',
'in', 'in2', 'intercept', 'k', 'k1', 'k2', 'k3', 'k4', 'kerning', 'local', 'mask', 'mode',
'offset', 'opacity', 'operator', 'order', 'orient', 'orientation', 'origin', 'overflow', 'path',
'ping', 'points', 'r', 'radius', 'rel', 'restart', 'result', 'rotate', 'rx', 'ry', 'scale',
'seed', 'slope', 'spacing', 'speed', 'stemh', 'stemv', 'string', 'stroke', 'to', 'transform',
'u1', 'u2', 'unicode', 'values', 'version', 'visibility', 'widths', 'x', 'x1', 'x2', 'xmlns',
'y', 'y1', 'y2', 'z',
// OpenGraph meta tag attributes
'property',
// React specific attributes
'ref', 'key', 'children',
// Non-standard
'results', 'security',
// Video specific
'controls',
// popovers
'popover', 'popovertarget', 'popovertargetaction',
];
const DOM_PROPERTY_NAMES_TWO_WORDS = [
// Global attributes - can be used on any HTML/DOM element
// See https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes
'accessKey', 'autoCapitalize', 'autoFocus', 'contentEditable', 'enterKeyHint', 'exportParts',
'inputMode', 'itemID', 'itemRef', 'itemProp', 'itemScope', 'itemType', 'spellCheck', 'tabIndex',
// Element specific attributes
// See https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes (includes global attributes too)
// To be considered if these should be added also to ATTRIBUTE_TAGS_MAP
'acceptCharset', 'autoComplete', 'autoPlay', 'border', 'cellPadding', 'cellSpacing', 'classID', 'codeBase',
'colSpan', 'contextMenu', 'dateTime', 'encType', 'formAction', 'formEncType', 'formMethod', 'formNoValidate', 'formTarget',
'frameBorder', 'hrefLang', 'httpEquiv', 'imageSizes', 'imageSrcSet', 'isMap', 'keyParams', 'keyType', 'marginHeight', 'marginWidth',
'maxLength', 'mediaGroup', 'minLength', 'noValidate', 'onAnimationEnd', 'onAnimationIteration', 'onAnimationStart',
'onBlur', 'onChange', 'onClick', 'onContextMenu', 'onCopy', 'onCompositionEnd', 'onCompositionStart',
'onCompositionUpdate', 'onCut', 'onDoubleClick', 'onDrag', 'onDragEnd', 'onDragEnter', 'onDragExit', 'onDragLeave',
'onError', 'onFocus', 'onInput', 'onKeyDown', 'onKeyPress', 'onKeyUp', 'onLoad', 'onWheel', 'onDragOver',
'onDragStart', 'onDrop', 'onMouseDown', 'onMouseEnter', 'onMouseLeave', 'onMouseMove', 'onMouseOut', 'onMouseOver',
'onMouseUp', 'onPaste', 'onScroll', 'onSelect', 'onSubmit', 'onBeforeToggle', 'onToggle', 'onTransitionEnd', 'radioGroup',
'readOnly', 'referrerPolicy', 'rowSpan', 'srcDoc', 'srcLang', 'srcSet', 'useMap', 'fetchPriority',
// SVG attributes
// See https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute
'crossOrigin', 'accentHeight', 'alignmentBaseline', 'arabicForm', 'attributeName',
'attributeType', 'baseFrequency', 'baselineShift', 'baseProfile', 'calcMode', 'capHeight',
'clipPathUnits', 'clipPath', 'clipRule', 'colorInterpolation', 'colorInterpolationFilters',
'colorProfile', 'colorRendering', 'contentScriptType', 'contentStyleType', 'diffuseConstant',
'dominantBaseline', 'edgeMode', 'enableBackground', 'fillOpacity', 'fillRule', 'filterRes',
'filterUnits', 'floodColor', 'floodOpacity', 'fontFamily', 'fontSize', 'fontSizeAdjust',
'fontStretch', 'fontStyle', 'fontVariant', 'fontWeight', 'glyphName',
'glyphOrientationHorizontal', 'glyphOrientationVertical', 'glyphRef', 'gradientTransform',
'gradientUnits', 'horizAdvX', 'horizOriginX', 'imageRendering', 'kernelMatrix',
'kernelUnitLength', 'keyPoints', 'keySplines', 'keyTimes', 'lengthAdjust', 'letterSpacing',
'lightingColor', 'limitingConeAngle', 'markerEnd', 'markerMid', 'markerStart', 'markerHeight',
'markerUnits', 'markerWidth', 'maskContentUnits', 'maskUnits', 'mathematical', 'numOctaves',
'overlinePosition', 'overlineThickness', 'panose1', 'paintOrder', 'pathLength',
'patternContentUnits', 'patternTransform', 'patternUnits', 'pointerEvents', 'pointsAtX',
'pointsAtY', 'pointsAtZ', 'preserveAlpha', 'preserveAspectRatio', 'primitiveUnits',
'referrerPolicy', 'refX', 'refY', 'rendering-intent', 'repeatCount', 'repeatDur',
'requiredExtensions', 'requiredFeatures', 'shapeRendering', 'specularConstant',
'specularExponent', 'spreadMethod', 'startOffset', 'stdDeviation', 'stitchTiles', 'stopColor',
'stopOpacity', 'strikethroughPosition', 'strikethroughThickness', 'strokeDasharray',
'strokeDashoffset', 'strokeLinecap', 'strokeLinejoin', 'strokeMiterlimit', 'strokeOpacity',
'strokeWidth', 'surfaceScale', 'systemLanguage', 'tableValues', 'targetX', 'targetY',
'textAnchor', 'textDecoration', 'textRendering', 'textLength', 'transformOrigin',
'underlinePosition', 'underlineThickness', 'unicodeBidi', 'unicodeRange', 'unitsPerEm',
'vAlphabetic', 'vHanging', 'vIdeographic', 'vMathematical', 'vectorEffect', 'vertAdvY',
'vertOriginX', 'vertOriginY', 'viewBox', 'viewTarget', 'wordSpacing', 'writingMode', 'xHeight',
'xChannelSelector', 'xlinkActuate', 'xlinkArcrole', 'xlinkHref', 'xlinkRole', 'xlinkShow',
'xlinkTitle', 'xlinkType', 'xmlBase', 'xmlLang', 'xmlnsXlink', 'xmlSpace', 'yChannelSelector',
'zoomAndPan',
// Safari/Apple specific, no listing available
'autoCorrect', // https://stackoverflow.com/questions/47985384/html-autocorrect-for-text-input-is-not-working
'autoSave', // https://stackoverflow.com/questions/25456396/what-is-autosave-attribute-supposed-to-do-how-do-i-use-it
// React specific attributes https://reactjs.org/docs/dom-elements.html#differences-in-attributes
'className', 'dangerouslySetInnerHTML', 'defaultValue', 'defaultChecked', 'htmlFor',
// Events' capture events
'onBeforeInput', 'onChange',
'onInvalid', 'onReset', 'onTouchCancel', 'onTouchEnd', 'onTouchMove', 'onTouchStart', 'suppressContentEditableWarning', 'suppressHydrationWarning',
'onAbort', 'onCanPlay', 'onCanPlayThrough', 'onDurationChange', 'onEmptied', 'onEncrypted', 'onEnded',
'onLoadedData', 'onLoadedMetadata', 'onLoadStart', 'onPause', 'onPlay', 'onPlaying', 'onProgress', 'onRateChange', 'onResize',
'onSeeked', 'onSeeking', 'onStalled', 'onSuspend', 'onTimeUpdate', 'onVolumeChange', 'onWaiting',
'onCopyCapture', 'onCutCapture', 'onPasteCapture', 'onCompositionEndCapture', 'onCompositionStartCapture', 'onCompositionUpdateCapture',
'onFocusCapture', 'onBlurCapture', 'onChangeCapture', 'onBeforeInputCapture', 'onInputCapture', 'onResetCapture', 'onSubmitCapture',
'onInvalidCapture', 'onLoadCapture', 'onErrorCapture', 'onKeyDownCapture', 'onKeyPressCapture', 'onKeyUpCapture',
'onAbortCapture', 'onCanPlayCapture', 'onCanPlayThroughCapture', 'onDurationChangeCapture', 'onEmptiedCapture', 'onEncryptedCapture',
'onEndedCapture', 'onLoadedDataCapture', 'onLoadedMetadataCapture', 'onLoadStartCapture', 'onPauseCapture', 'onPlayCapture',
'onPlayingCapture', 'onProgressCapture', 'onRateChangeCapture', 'onSeekedCapture', 'onSeekingCapture', 'onStalledCapture', 'onSuspendCapture',
'onTimeUpdateCapture', 'onVolumeChangeCapture', 'onWaitingCapture', 'onSelectCapture', 'onTouchCancelCapture', 'onTouchEndCapture',
'onTouchMoveCapture', 'onTouchStartCapture', 'onScrollCapture', 'onWheelCapture', 'onAnimationEndCapture', 'onAnimationIteration',
'onAnimationStartCapture', 'onTransitionEndCapture',
'onAuxClick', 'onAuxClickCapture', 'onClickCapture', 'onContextMenuCapture', 'onDoubleClickCapture',
'onDragCapture', 'onDragEndCapture', 'onDragEnterCapture', 'onDragExitCapture', 'onDragLeaveCapture',
'onDragOverCapture', 'onDragStartCapture', 'onDropCapture', 'onMouseDown', 'onMouseDownCapture',
'onMouseMoveCapture', 'onMouseOutCapture', 'onMouseOverCapture', 'onMouseUpCapture',
// Video specific
'autoPictureInPicture', 'controlsList', 'disablePictureInPicture', 'disableRemotePlayback',
// popovers
'popoverTarget', 'popoverTargetAction',
];
const DOM_PROPERTIES_IGNORE_CASE = ['charset', 'allowFullScreen', 'webkitAllowFullScreen', 'mozAllowFullScreen', 'webkitDirectory', 'popoverTarget', 'popoverTargetAction'];
const ARIA_PROPERTIES = [
// See https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes
// Global attributes
'aria-atomic', 'aria-braillelabel', 'aria-brailleroledescription', 'aria-busy', 'aria-controls', 'aria-current',
'aria-describedby', 'aria-description', 'aria-details',
'aria-disabled', 'aria-dropeffect', 'aria-errormessage', 'aria-flowto', 'aria-grabbed', 'aria-haspopup',
'aria-hidden', 'aria-invalid', 'aria-keyshortcuts', 'aria-label', 'aria-labelledby', 'aria-live',
'aria-owns', 'aria-relevant', 'aria-roledescription',
// Widget attributes
'aria-autocomplete', 'aria-checked', 'aria-expanded', 'aria-level', 'aria-modal', 'aria-multiline', 'aria-multiselectable',
'aria-orientation', 'aria-placeholder', 'aria-pressed', 'aria-readonly', 'aria-required', 'aria-selected',
'aria-sort', 'aria-valuemax', 'aria-valuemin', 'aria-valuenow', 'aria-valuetext',
// Relationship attributes
'aria-activedescendant', 'aria-colcount', 'aria-colindex', 'aria-colindextext', 'aria-colspan',
'aria-posinset', 'aria-rowcount', 'aria-rowindex', 'aria-rowindextext', 'aria-rowspan', 'aria-setsize',
];
const REACT_ON_PROPS = [
'onGotPointerCapture',
'onGotPointerCaptureCapture',
'onLostPointerCapture',
'onLostPointerCapture',
'onLostPointerCaptureCapture',
'onPointerCancel',
'onPointerCancelCapture',
'onPointerDown',
'onPointerDownCapture',
'onPointerEnter',
'onPointerEnterCapture',
'onPointerLeave',
'onPointerLeaveCapture',
'onPointerMove',
'onPointerMoveCapture',
'onPointerOut',
'onPointerOutCapture',
'onPointerOver',
'onPointerOverCapture',
'onPointerUp',
'onPointerUpCapture',
];
function getDOMPropertyNames(context) {
return [].concat(
DOM_PROPERTY_NAMES_TWO_WORDS,
DOM_PROPERTY_NAMES_ONE_WORD,
testReactVersion(context, '>= 16.1.0') ? [].concat(
testReactVersion(context, '>= 16.4.0') ? [].concat(
// these were added in React v16.4.0, see https://reactjs.org/blog/2018/05/23/react-v-16-4.html and https://github.com/facebook/react/pull/12507
REACT_ON_PROPS,
testReactVersion(context, '>= 19') ? [
// precedence was added in React v19, see https://react.dev/blog/2024/04/25/react-19#support-for-stylesheets
'precedence',
] : []
) : []
) : [
// this was removed in React v16.1+, see https://github.com/facebook/react/pull/10823
'allowTransparency',
]
);
}
// ------------------------------------------------------------------------------
// Helpers
// ------------------------------------------------------------------------------
/**
* Checks if a node's parent is a JSX tag that is written with lowercase letters,
* and is not a custom web component. Custom web components have a hyphen in tag name,
* or have an `is="some-elem"` attribute.
*
* Note: does not check if a tag's parent against a list of standard HTML/DOM tags. For example,
* a `<fake>`'s child would return `true` because "fake" is written only with lowercase letters
* without a hyphen and does not have a `is="some-elem"` attribute.
*
* @param {Object} childNode - JSX element being tested.
* @returns {boolean} Whether or not the node name match the JSX tag convention.
*/
function isValidHTMLTagInJSX(childNode) {
const tagConvention = /^[a-z][^-]*$/;
if (tagConvention.test(childNode.parent.name.name)) {
return !childNode.parent.attributes.some((attrNode) => (
attrNode.type === 'JSXAttribute'
&& attrNode.name.type === 'JSXIdentifier'
&& attrNode.name.name === 'is'
// To learn more about custom web components and `is` attribute,
// see https://html.spec.whatwg.org/multipage/custom-elements.html#custom-elements-customized-builtin-example
));
}
return false;
}
/**
* Checks if the attribute name is included in the attributes that are excluded
* from the camel casing.
*
* // returns 'charSet'
* @example normalizeAttributeCase('charset')
*
* Note - these exclusions are not made by React core team, but `eslint-plugin-react` community.
*
* @param {string} name - Attribute name to be normalized
* @returns {string} Result
*/
function normalizeAttributeCase(name) {
return DOM_PROPERTIES_IGNORE_CASE.find((element) => element.toLowerCase() === name.toLowerCase()) || name;
}
/**
* Checks if an attribute name is a valid `data-*` attribute:
* if the name starts with "data-" and has alphanumeric words (browsers require lowercase, but React and TS lowercase them),
* not start with any casing of "xml", and separated by hyphens (-) (which is also called "kebab case" or "dash case"),
* then the attribute is a valid data attribute.
*
* @param {string} name - Attribute name to be tested
* @returns {boolean} Result
*/
function isValidDataAttribute(name) {
return !/^data-xml/i.test(name) && /^data-[^:]*$/.test(name);
}
/**
* Checks if an attribute name has at least one uppercase characters
*
* @param {string} name
* @returns {boolean} Result
*/
function hasUpperCaseCharacter(name) {
return name.toLowerCase() !== name;
}
/**
* Checks if an attribute name is a standard aria attribute by compering it to a list
* of standard aria property names
*
* @param {string} name - Attribute name to be tested
* @returns {boolean} Result
*/
function isValidAriaAttribute(name) {
return ARIA_PROPERTIES.some((element) => element === name);
}
/**
* Extracts the tag name for the JSXAttribute
* @param {JSXAttribute} node - JSXAttribute being tested.
* @returns {string | null} tag name
*/
function getTagName(node) {
if (
node
&& node.parent
&& node.parent.name
) {
return node.parent.name.name;
}
return null;
}
/**
* Test wether the tag name for the JSXAttribute is
* something like <Foo.bar />
* @param {JSXAttribute} node - JSXAttribute being tested.
* @returns {boolean} result
*/
function tagNameHasDot(node) {
return !!(
node.parent
&& node.parent.name
&& node.parent.name.type === 'JSXMemberExpression'
);
}
/**
* Get the standard name of the attribute.
* @param {string} name - Name of the attribute.
* @param {object} context - eslint context
* @returns {string | undefined} The standard name of the attribute, or undefined if no standard name was found.
*/
function getStandardName(name, context) {
if (has(DOM_ATTRIBUTE_NAMES, name)) {
return DOM_ATTRIBUTE_NAMES[/** @type {keyof DOM_ATTRIBUTE_NAMES} */ (name)];
}
if (has(SVGDOM_ATTRIBUTE_NAMES, name)) {
return SVGDOM_ATTRIBUTE_NAMES[/** @type {keyof SVGDOM_ATTRIBUTE_NAMES} */ (name)];
}
const names = getDOMPropertyNames(context);
// Let's find a possible attribute match with a case-insensitive search.
return names.find((element) => element.toLowerCase() === name.toLowerCase());
}
// ------------------------------------------------------------------------------
// Rule Definition
// ------------------------------------------------------------------------------
const messages = {
invalidPropOnTag: 'Invalid property \'{{name}}\' found on tag \'{{tagName}}\', but it is only allowed on: {{allowedTags}}',
unknownPropWithStandardName: 'Unknown property \'{{name}}\' found, use \'{{standardName}}\' instead',
unknownProp: 'Unknown property \'{{name}}\' found',
dataLowercaseRequired: 'React does not recognize data-* props with uppercase characters on a DOM element. Found \'{{name}}\', use \'{{lowerCaseName}}\' instead',
};
/** @type {import('eslint').Rule.RuleModule} */
module.exports = {
meta: {
docs: {
description: 'Disallow usage of unknown DOM property',
category: 'Possible Errors',
recommended: true,
url: docsUrl('no-unknown-property'),
},
fixable: 'code',
messages,
schema: [{
type: 'object',
properties: {
ignore: {
type: 'array',
items: {
type: 'string',
},
},
requireDataLowercase: {
type: 'boolean',
default: false,
},
},
additionalProperties: false,
}],
},
create(context) {
function getIgnoreConfig() {
return (context.options[0] && context.options[0].ignore) || DEFAULTS.ignore;
}
function getRequireDataLowercase() {
return (context.options[0] && typeof context.options[0].requireDataLowercase !== 'undefined')
? !!context.options[0].requireDataLowercase
: DEFAULTS.requireDataLowercase;
}
return {
JSXAttribute(node) {
const ignoreNames = getIgnoreConfig();
const actualName = getText(context, node.name);
if (ignoreNames.indexOf(actualName) >= 0) {
return;
}
const name = normalizeAttributeCase(actualName);
// Ignore tags like <Foo.bar />
if (tagNameHasDot(node)) {
return;
}
if (isValidDataAttribute(name)) {
if (getRequireDataLowercase() && hasUpperCaseCharacter(name)) {
report(context, messages.dataLowercaseRequired, 'dataLowercaseRequired', {
node,
data: {
name: actualName,
lowerCaseName: actualName.toLowerCase(),
},
});
}
return;
}
if (isValidAriaAttribute(name)) { return; }
const tagName = getTagName(node);
if (tagName === 'fbt' || tagName === 'fbs') { return; } // fbt/fbs nodes are bonkers, let's not go there
if (!isValidHTMLTagInJSX(node)) { return; }
// Let's dive deeper into tags that are HTML/DOM elements (`<button>`), and not React components (`<Button />`)
// Some attributes are allowed on some tags only
const allowedTags = has(ATTRIBUTE_TAGS_MAP, name)
? ATTRIBUTE_TAGS_MAP[/** @type {keyof ATTRIBUTE_TAGS_MAP} */ (name)]
: null;
if (tagName && allowedTags) {
// Scenario 1A: Allowed attribute found where not supposed to, report it
if (allowedTags.indexOf(tagName) === -1) {
report(context, messages.invalidPropOnTag, 'invalidPropOnTag', {
node,
data: {
name: actualName,
tagName,
allowedTags: allowedTags.join(', '),
},
});
}
// Scenario 1B: There are allowed attributes on allowed tags, no need to report it
return;
}
// Let's see if the attribute is a close version to some standard property name
const standardName = getStandardName(name, context);
const hasStandardNameButIsNotUsed = standardName && standardName !== name;
const usesStandardName = standardName && standardName === name;
if (usesStandardName) {
// Scenario 2A: The attribute name is the standard name, no need to report it
return;
}
if (hasStandardNameButIsNotUsed) {
// Scenario 2B: The name of the attribute is close to a standard one, report it with the standard name
report(context, messages.unknownPropWithStandardName, 'unknownPropWithStandardName', {
node,
data: {
name: actualName,
standardName,
},
fix(fixer) {
return fixer.replaceText(node.name, standardName);
},
});
return;
}
// Scenario 3: We have an attribute that is unknown, report it
report(context, messages.unknownProp, 'unknownProp', {
node,
data: {
name: actualName,
},
});
},
};
},
};
@@ -0,0 +1,65 @@
import {mergeProps as $7JYt2$mergeProps} from "@react-aria/utils";
import $7JYt2$react, {useState as $7JYt2$useState, useMemo as $7JYt2$useMemo} from "react";
import {useFocusWithin as $7JYt2$useFocusWithin} from "@react-aria/interactions";
/*
* Copyright 2020 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
const $5c3e21d68f1c4674$var$styles = {
border: 0,
clip: 'rect(0 0 0 0)',
clipPath: 'inset(50%)',
height: '1px',
margin: '-1px',
overflow: 'hidden',
padding: 0,
position: 'absolute',
width: '1px',
whiteSpace: 'nowrap'
};
function $5c3e21d68f1c4674$export$a966af930f325cab(props = {}) {
let { style: style, isFocusable: isFocusable } = props;
let [isFocused, setFocused] = (0, $7JYt2$useState)(false);
let { focusWithinProps: focusWithinProps } = (0, $7JYt2$useFocusWithin)({
isDisabled: !isFocusable,
onFocusWithinChange: (val)=>setFocused(val)
});
// If focused, don't hide the element.
let combinedStyles = (0, $7JYt2$useMemo)(()=>{
if (isFocused) return style;
else if (style) return {
...$5c3e21d68f1c4674$var$styles,
...style
};
else return $5c3e21d68f1c4674$var$styles;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [
isFocused
]);
return {
visuallyHiddenProps: {
...focusWithinProps,
style: combinedStyles
}
};
}
function $5c3e21d68f1c4674$export$439d29a4e110a164(props) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
let { children: children, elementType: Element = 'div', isFocusable: isFocusable, style: style, ...otherProps } = props;
let { visuallyHiddenProps: visuallyHiddenProps } = $5c3e21d68f1c4674$export$a966af930f325cab(props);
return /*#__PURE__*/ (0, $7JYt2$react).createElement(Element, (0, $7JYt2$mergeProps)(otherProps, visuallyHiddenProps), children);
}
export {$5c3e21d68f1c4674$export$a966af930f325cab as useVisuallyHidden, $5c3e21d68f1c4674$export$439d29a4e110a164 as VisuallyHidden};
//# sourceMappingURL=VisuallyHidden.module.js.map
@@ -0,0 +1,10 @@
"use strict";
function _define_property(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true });
} else obj[key] = value;
return obj;
}
exports._ = _define_property;
@@ -0,0 +1,76 @@
/*
* Copyright 2022 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/ const $5b160d28a433310d$var$localeSymbol = Symbol.for('react-aria.i18n.locale');
const $5b160d28a433310d$var$stringsSymbol = Symbol.for('react-aria.i18n.strings');
let $5b160d28a433310d$var$cachedGlobalStrings = undefined;
class $5b160d28a433310d$export$c17fa47878dc55b6 {
/** Returns a localized string for the given key and locale. */ getStringForLocale(key, locale) {
let strings = this.getStringsForLocale(locale);
let string = strings[key];
if (!string) throw new Error(`Could not find intl message ${key} in ${locale} locale`);
return string;
}
/** Returns all localized strings for the given locale. */ getStringsForLocale(locale) {
let strings = this.strings[locale];
if (!strings) {
strings = $5b160d28a433310d$var$getStringsForLocale(locale, this.strings, this.defaultLocale);
this.strings[locale] = strings;
}
return strings;
}
static getGlobalDictionaryForPackage(packageName) {
if (typeof window === 'undefined') return null;
let locale = window[$5b160d28a433310d$var$localeSymbol];
if ($5b160d28a433310d$var$cachedGlobalStrings === undefined) {
let globalStrings = window[$5b160d28a433310d$var$stringsSymbol];
if (!globalStrings) return null;
$5b160d28a433310d$var$cachedGlobalStrings = {};
for(let pkg in globalStrings)$5b160d28a433310d$var$cachedGlobalStrings[pkg] = new $5b160d28a433310d$export$c17fa47878dc55b6({
[locale]: globalStrings[pkg]
}, locale);
}
let dictionary = $5b160d28a433310d$var$cachedGlobalStrings === null || $5b160d28a433310d$var$cachedGlobalStrings === void 0 ? void 0 : $5b160d28a433310d$var$cachedGlobalStrings[packageName];
if (!dictionary) throw new Error(`Strings for package "${packageName}" were not included by LocalizedStringProvider. Please add it to the list passed to createLocalizedStringDictionary.`);
return dictionary;
}
constructor(messages, defaultLocale = 'en-US'){
// Clone messages so we don't modify the original object.
// Filter out entries with falsy values which may have been caused by applying optimize-locales-plugin.
this.strings = Object.fromEntries(Object.entries(messages).filter(([, v])=>v));
this.defaultLocale = defaultLocale;
}
}
function $5b160d28a433310d$var$getStringsForLocale(locale, strings, defaultLocale = 'en-US') {
// If there is an exact match, use it.
if (strings[locale]) return strings[locale];
// Attempt to find the closest match by language.
// For example, if the locale is fr-CA (French Canadian), but there is only
// an fr-FR (France) set of strings, use that.
// This could be replaced with Intl.LocaleMatcher once it is supported.
// https://github.com/tc39/proposal-intl-localematcher
let language = $5b160d28a433310d$var$getLanguage(locale);
if (strings[language]) return strings[language];
for(let key in strings){
if (key.startsWith(language + '-')) return strings[key];
}
// Nothing close, use english.
return strings[defaultLocale];
}
function $5b160d28a433310d$var$getLanguage(locale) {
// @ts-ignore
if (Intl.Locale) // @ts-ignore
return new Intl.Locale(locale).language;
return locale.split('-')[0];
}
export {$5b160d28a433310d$export$c17fa47878dc55b6 as LocalizedStringDictionary};
//# sourceMappingURL=LocalizedStringDictionary.module.js.map
@@ -0,0 +1,8 @@
'use strict';
var hasSymbols = require('has-symbols/shams');
/** @type {import('.')} */
module.exports = function hasToStringTagShams() {
return hasSymbols() && !!Symbol.toStringTag;
};
@@ -0,0 +1 @@
{"version":3,"file":"request_scope.int.spec.d.ts","sourceRoot":"","sources":["../../../../src/test/features/request_scope.int.spec.ts"],"names":[],"mappings":""}
@@ -0,0 +1,16 @@
/*
* Copyright 2020 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
export type {NumberFormatOptions} from './NumberFormatter';
export {NumberFormatter} from './NumberFormatter';
export {NumberParser} from './NumberParser';
@@ -0,0 +1,5 @@
const isEasingArray = (ease) => {
return Array.isArray(ease) && typeof ease[0] !== "number";
};
export { isEasingArray };
@@ -0,0 +1,689 @@
{
"name": "@swc/helpers",
"packageManager": "yarn@4.0.2",
"version": "0.5.17",
"description": "External helpers for the swc project.",
"module": "esm/index.js",
"main": "cjs/index.cjs",
"sideEffects": false,
"scripts": {
"build": "zx ./scripts/build.js",
"prepack": "zx ./scripts/build.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/swc-project/swc.git"
},
"publishConfig": {
"registry": "https://registry.npmjs.org/",
"access": "public"
},
"keywords": [
"swc",
"helpers"
],
"author": "강동윤 <kdy1997.dev@gmail.com>",
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/swc-project/swc/issues"
},
"homepage": "https://swc.rs",
"type": "module",
"devDependencies": {
"@ast-grep/napi": "^0.3.1",
"dprint": "^0.35.3",
"magic-string": "^0.30.0",
"zx": "^7.2.1"
},
"dependencies": {
"tslib": "^2.8.0"
},
"exports": {
"./package.json": "./package.json",
"./esm/*": "./esm/*",
"./cjs/*": "./cjs/*",
"./src/*": "./src/*",
".": {
"module-sync": "./esm/index.js",
"webpack": "./esm/index.js",
"import": "./esm/index.js",
"default": "./cjs/index.cjs"
},
"./_": {
"module-sync": "./esm/index.js",
"webpack": "./esm/index.js",
"import": "./esm/index.js",
"default": "./cjs/index.cjs"
},
"./_/_apply_decorated_descriptor": {
"module-sync": "./esm/_apply_decorated_descriptor.js",
"webpack": "./esm/_apply_decorated_descriptor.js",
"import": "./esm/_apply_decorated_descriptor.js",
"default": "./cjs/_apply_decorated_descriptor.cjs"
},
"./_/_apply_decs_2203_r": {
"module-sync": "./esm/_apply_decs_2203_r.js",
"webpack": "./esm/_apply_decs_2203_r.js",
"import": "./esm/_apply_decs_2203_r.js",
"default": "./cjs/_apply_decs_2203_r.cjs"
},
"./_/_array_like_to_array": {
"module-sync": "./esm/_array_like_to_array.js",
"webpack": "./esm/_array_like_to_array.js",
"import": "./esm/_array_like_to_array.js",
"default": "./cjs/_array_like_to_array.cjs"
},
"./_/_array_with_holes": {
"module-sync": "./esm/_array_with_holes.js",
"webpack": "./esm/_array_with_holes.js",
"import": "./esm/_array_with_holes.js",
"default": "./cjs/_array_with_holes.cjs"
},
"./_/_array_without_holes": {
"module-sync": "./esm/_array_without_holes.js",
"webpack": "./esm/_array_without_holes.js",
"import": "./esm/_array_without_holes.js",
"default": "./cjs/_array_without_holes.cjs"
},
"./_/_assert_this_initialized": {
"module-sync": "./esm/_assert_this_initialized.js",
"webpack": "./esm/_assert_this_initialized.js",
"import": "./esm/_assert_this_initialized.js",
"default": "./cjs/_assert_this_initialized.cjs"
},
"./_/_async_generator": {
"module-sync": "./esm/_async_generator.js",
"webpack": "./esm/_async_generator.js",
"import": "./esm/_async_generator.js",
"default": "./cjs/_async_generator.cjs"
},
"./_/_async_generator_delegate": {
"module-sync": "./esm/_async_generator_delegate.js",
"webpack": "./esm/_async_generator_delegate.js",
"import": "./esm/_async_generator_delegate.js",
"default": "./cjs/_async_generator_delegate.cjs"
},
"./_/_async_iterator": {
"module-sync": "./esm/_async_iterator.js",
"webpack": "./esm/_async_iterator.js",
"import": "./esm/_async_iterator.js",
"default": "./cjs/_async_iterator.cjs"
},
"./_/_async_to_generator": {
"module-sync": "./esm/_async_to_generator.js",
"webpack": "./esm/_async_to_generator.js",
"import": "./esm/_async_to_generator.js",
"default": "./cjs/_async_to_generator.cjs"
},
"./_/_await_async_generator": {
"module-sync": "./esm/_await_async_generator.js",
"webpack": "./esm/_await_async_generator.js",
"import": "./esm/_await_async_generator.js",
"default": "./cjs/_await_async_generator.cjs"
},
"./_/_await_value": {
"module-sync": "./esm/_await_value.js",
"webpack": "./esm/_await_value.js",
"import": "./esm/_await_value.js",
"default": "./cjs/_await_value.cjs"
},
"./_/_call_super": {
"module-sync": "./esm/_call_super.js",
"webpack": "./esm/_call_super.js",
"import": "./esm/_call_super.js",
"default": "./cjs/_call_super.cjs"
},
"./_/_check_private_redeclaration": {
"module-sync": "./esm/_check_private_redeclaration.js",
"webpack": "./esm/_check_private_redeclaration.js",
"import": "./esm/_check_private_redeclaration.js",
"default": "./cjs/_check_private_redeclaration.cjs"
},
"./_/_class_apply_descriptor_destructure": {
"module-sync": "./esm/_class_apply_descriptor_destructure.js",
"webpack": "./esm/_class_apply_descriptor_destructure.js",
"import": "./esm/_class_apply_descriptor_destructure.js",
"default": "./cjs/_class_apply_descriptor_destructure.cjs"
},
"./_/_class_apply_descriptor_get": {
"module-sync": "./esm/_class_apply_descriptor_get.js",
"webpack": "./esm/_class_apply_descriptor_get.js",
"import": "./esm/_class_apply_descriptor_get.js",
"default": "./cjs/_class_apply_descriptor_get.cjs"
},
"./_/_class_apply_descriptor_set": {
"module-sync": "./esm/_class_apply_descriptor_set.js",
"webpack": "./esm/_class_apply_descriptor_set.js",
"import": "./esm/_class_apply_descriptor_set.js",
"default": "./cjs/_class_apply_descriptor_set.cjs"
},
"./_/_class_apply_descriptor_update": {
"module-sync": "./esm/_class_apply_descriptor_update.js",
"webpack": "./esm/_class_apply_descriptor_update.js",
"import": "./esm/_class_apply_descriptor_update.js",
"default": "./cjs/_class_apply_descriptor_update.cjs"
},
"./_/_class_call_check": {
"module-sync": "./esm/_class_call_check.js",
"webpack": "./esm/_class_call_check.js",
"import": "./esm/_class_call_check.js",
"default": "./cjs/_class_call_check.cjs"
},
"./_/_class_check_private_static_access": {
"module-sync": "./esm/_class_check_private_static_access.js",
"webpack": "./esm/_class_check_private_static_access.js",
"import": "./esm/_class_check_private_static_access.js",
"default": "./cjs/_class_check_private_static_access.cjs"
},
"./_/_class_check_private_static_field_descriptor": {
"module-sync": "./esm/_class_check_private_static_field_descriptor.js",
"webpack": "./esm/_class_check_private_static_field_descriptor.js",
"import": "./esm/_class_check_private_static_field_descriptor.js",
"default": "./cjs/_class_check_private_static_field_descriptor.cjs"
},
"./_/_class_extract_field_descriptor": {
"module-sync": "./esm/_class_extract_field_descriptor.js",
"webpack": "./esm/_class_extract_field_descriptor.js",
"import": "./esm/_class_extract_field_descriptor.js",
"default": "./cjs/_class_extract_field_descriptor.cjs"
},
"./_/_class_name_tdz_error": {
"module-sync": "./esm/_class_name_tdz_error.js",
"webpack": "./esm/_class_name_tdz_error.js",
"import": "./esm/_class_name_tdz_error.js",
"default": "./cjs/_class_name_tdz_error.cjs"
},
"./_/_class_private_field_destructure": {
"module-sync": "./esm/_class_private_field_destructure.js",
"webpack": "./esm/_class_private_field_destructure.js",
"import": "./esm/_class_private_field_destructure.js",
"default": "./cjs/_class_private_field_destructure.cjs"
},
"./_/_class_private_field_get": {
"module-sync": "./esm/_class_private_field_get.js",
"webpack": "./esm/_class_private_field_get.js",
"import": "./esm/_class_private_field_get.js",
"default": "./cjs/_class_private_field_get.cjs"
},
"./_/_class_private_field_init": {
"module-sync": "./esm/_class_private_field_init.js",
"webpack": "./esm/_class_private_field_init.js",
"import": "./esm/_class_private_field_init.js",
"default": "./cjs/_class_private_field_init.cjs"
},
"./_/_class_private_field_loose_base": {
"module-sync": "./esm/_class_private_field_loose_base.js",
"webpack": "./esm/_class_private_field_loose_base.js",
"import": "./esm/_class_private_field_loose_base.js",
"default": "./cjs/_class_private_field_loose_base.cjs"
},
"./_/_class_private_field_loose_key": {
"module-sync": "./esm/_class_private_field_loose_key.js",
"webpack": "./esm/_class_private_field_loose_key.js",
"import": "./esm/_class_private_field_loose_key.js",
"default": "./cjs/_class_private_field_loose_key.cjs"
},
"./_/_class_private_field_set": {
"module-sync": "./esm/_class_private_field_set.js",
"webpack": "./esm/_class_private_field_set.js",
"import": "./esm/_class_private_field_set.js",
"default": "./cjs/_class_private_field_set.cjs"
},
"./_/_class_private_field_update": {
"module-sync": "./esm/_class_private_field_update.js",
"webpack": "./esm/_class_private_field_update.js",
"import": "./esm/_class_private_field_update.js",
"default": "./cjs/_class_private_field_update.cjs"
},
"./_/_class_private_method_get": {
"module-sync": "./esm/_class_private_method_get.js",
"webpack": "./esm/_class_private_method_get.js",
"import": "./esm/_class_private_method_get.js",
"default": "./cjs/_class_private_method_get.cjs"
},
"./_/_class_private_method_init": {
"module-sync": "./esm/_class_private_method_init.js",
"webpack": "./esm/_class_private_method_init.js",
"import": "./esm/_class_private_method_init.js",
"default": "./cjs/_class_private_method_init.cjs"
},
"./_/_class_private_method_set": {
"module-sync": "./esm/_class_private_method_set.js",
"webpack": "./esm/_class_private_method_set.js",
"import": "./esm/_class_private_method_set.js",
"default": "./cjs/_class_private_method_set.cjs"
},
"./_/_class_static_private_field_destructure": {
"module-sync": "./esm/_class_static_private_field_destructure.js",
"webpack": "./esm/_class_static_private_field_destructure.js",
"import": "./esm/_class_static_private_field_destructure.js",
"default": "./cjs/_class_static_private_field_destructure.cjs"
},
"./_/_class_static_private_field_spec_get": {
"module-sync": "./esm/_class_static_private_field_spec_get.js",
"webpack": "./esm/_class_static_private_field_spec_get.js",
"import": "./esm/_class_static_private_field_spec_get.js",
"default": "./cjs/_class_static_private_field_spec_get.cjs"
},
"./_/_class_static_private_field_spec_set": {
"module-sync": "./esm/_class_static_private_field_spec_set.js",
"webpack": "./esm/_class_static_private_field_spec_set.js",
"import": "./esm/_class_static_private_field_spec_set.js",
"default": "./cjs/_class_static_private_field_spec_set.cjs"
},
"./_/_class_static_private_field_update": {
"module-sync": "./esm/_class_static_private_field_update.js",
"webpack": "./esm/_class_static_private_field_update.js",
"import": "./esm/_class_static_private_field_update.js",
"default": "./cjs/_class_static_private_field_update.cjs"
},
"./_/_class_static_private_method_get": {
"module-sync": "./esm/_class_static_private_method_get.js",
"webpack": "./esm/_class_static_private_method_get.js",
"import": "./esm/_class_static_private_method_get.js",
"default": "./cjs/_class_static_private_method_get.cjs"
},
"./_/_construct": {
"module-sync": "./esm/_construct.js",
"webpack": "./esm/_construct.js",
"import": "./esm/_construct.js",
"default": "./cjs/_construct.cjs"
},
"./_/_create_class": {
"module-sync": "./esm/_create_class.js",
"webpack": "./esm/_create_class.js",
"import": "./esm/_create_class.js",
"default": "./cjs/_create_class.cjs"
},
"./_/_create_for_of_iterator_helper_loose": {
"module-sync": "./esm/_create_for_of_iterator_helper_loose.js",
"webpack": "./esm/_create_for_of_iterator_helper_loose.js",
"import": "./esm/_create_for_of_iterator_helper_loose.js",
"default": "./cjs/_create_for_of_iterator_helper_loose.cjs"
},
"./_/_create_super": {
"module-sync": "./esm/_create_super.js",
"webpack": "./esm/_create_super.js",
"import": "./esm/_create_super.js",
"default": "./cjs/_create_super.cjs"
},
"./_/_decorate": {
"module-sync": "./esm/_decorate.js",
"webpack": "./esm/_decorate.js",
"import": "./esm/_decorate.js",
"default": "./cjs/_decorate.cjs"
},
"./_/_defaults": {
"module-sync": "./esm/_defaults.js",
"webpack": "./esm/_defaults.js",
"import": "./esm/_defaults.js",
"default": "./cjs/_defaults.cjs"
},
"./_/_define_enumerable_properties": {
"module-sync": "./esm/_define_enumerable_properties.js",
"webpack": "./esm/_define_enumerable_properties.js",
"import": "./esm/_define_enumerable_properties.js",
"default": "./cjs/_define_enumerable_properties.cjs"
},
"./_/_define_property": {
"module-sync": "./esm/_define_property.js",
"webpack": "./esm/_define_property.js",
"import": "./esm/_define_property.js",
"default": "./cjs/_define_property.cjs"
},
"./_/_dispose": {
"module-sync": "./esm/_dispose.js",
"webpack": "./esm/_dispose.js",
"import": "./esm/_dispose.js",
"default": "./cjs/_dispose.cjs"
},
"./_/_export_star": {
"module-sync": "./esm/_export_star.js",
"webpack": "./esm/_export_star.js",
"import": "./esm/_export_star.js",
"default": "./cjs/_export_star.cjs"
},
"./_/_extends": {
"module-sync": "./esm/_extends.js",
"webpack": "./esm/_extends.js",
"import": "./esm/_extends.js",
"default": "./cjs/_extends.cjs"
},
"./_/_get": {
"module-sync": "./esm/_get.js",
"webpack": "./esm/_get.js",
"import": "./esm/_get.js",
"default": "./cjs/_get.cjs"
},
"./_/_get_prototype_of": {
"module-sync": "./esm/_get_prototype_of.js",
"webpack": "./esm/_get_prototype_of.js",
"import": "./esm/_get_prototype_of.js",
"default": "./cjs/_get_prototype_of.cjs"
},
"./_/_identity": {
"module-sync": "./esm/_identity.js",
"webpack": "./esm/_identity.js",
"import": "./esm/_identity.js",
"default": "./cjs/_identity.cjs"
},
"./_/_inherits": {
"module-sync": "./esm/_inherits.js",
"webpack": "./esm/_inherits.js",
"import": "./esm/_inherits.js",
"default": "./cjs/_inherits.cjs"
},
"./_/_inherits_loose": {
"module-sync": "./esm/_inherits_loose.js",
"webpack": "./esm/_inherits_loose.js",
"import": "./esm/_inherits_loose.js",
"default": "./cjs/_inherits_loose.cjs"
},
"./_/_initializer_define_property": {
"module-sync": "./esm/_initializer_define_property.js",
"webpack": "./esm/_initializer_define_property.js",
"import": "./esm/_initializer_define_property.js",
"default": "./cjs/_initializer_define_property.cjs"
},
"./_/_initializer_warning_helper": {
"module-sync": "./esm/_initializer_warning_helper.js",
"webpack": "./esm/_initializer_warning_helper.js",
"import": "./esm/_initializer_warning_helper.js",
"default": "./cjs/_initializer_warning_helper.cjs"
},
"./_/_instanceof": {
"module-sync": "./esm/_instanceof.js",
"webpack": "./esm/_instanceof.js",
"import": "./esm/_instanceof.js",
"default": "./cjs/_instanceof.cjs"
},
"./_/_interop_require_default": {
"module-sync": "./esm/_interop_require_default.js",
"webpack": "./esm/_interop_require_default.js",
"import": "./esm/_interop_require_default.js",
"default": "./cjs/_interop_require_default.cjs"
},
"./_/_interop_require_wildcard": {
"module-sync": "./esm/_interop_require_wildcard.js",
"webpack": "./esm/_interop_require_wildcard.js",
"import": "./esm/_interop_require_wildcard.js",
"default": "./cjs/_interop_require_wildcard.cjs"
},
"./_/_is_native_function": {
"module-sync": "./esm/_is_native_function.js",
"webpack": "./esm/_is_native_function.js",
"import": "./esm/_is_native_function.js",
"default": "./cjs/_is_native_function.cjs"
},
"./_/_is_native_reflect_construct": {
"module-sync": "./esm/_is_native_reflect_construct.js",
"webpack": "./esm/_is_native_reflect_construct.js",
"import": "./esm/_is_native_reflect_construct.js",
"default": "./cjs/_is_native_reflect_construct.cjs"
},
"./_/_iterable_to_array": {
"module-sync": "./esm/_iterable_to_array.js",
"webpack": "./esm/_iterable_to_array.js",
"import": "./esm/_iterable_to_array.js",
"default": "./cjs/_iterable_to_array.cjs"
},
"./_/_iterable_to_array_limit": {
"module-sync": "./esm/_iterable_to_array_limit.js",
"webpack": "./esm/_iterable_to_array_limit.js",
"import": "./esm/_iterable_to_array_limit.js",
"default": "./cjs/_iterable_to_array_limit.cjs"
},
"./_/_iterable_to_array_limit_loose": {
"module-sync": "./esm/_iterable_to_array_limit_loose.js",
"webpack": "./esm/_iterable_to_array_limit_loose.js",
"import": "./esm/_iterable_to_array_limit_loose.js",
"default": "./cjs/_iterable_to_array_limit_loose.cjs"
},
"./_/_jsx": {
"module-sync": "./esm/_jsx.js",
"webpack": "./esm/_jsx.js",
"import": "./esm/_jsx.js",
"default": "./cjs/_jsx.cjs"
},
"./_/_new_arrow_check": {
"module-sync": "./esm/_new_arrow_check.js",
"webpack": "./esm/_new_arrow_check.js",
"import": "./esm/_new_arrow_check.js",
"default": "./cjs/_new_arrow_check.cjs"
},
"./_/_non_iterable_rest": {
"module-sync": "./esm/_non_iterable_rest.js",
"webpack": "./esm/_non_iterable_rest.js",
"import": "./esm/_non_iterable_rest.js",
"default": "./cjs/_non_iterable_rest.cjs"
},
"./_/_non_iterable_spread": {
"module-sync": "./esm/_non_iterable_spread.js",
"webpack": "./esm/_non_iterable_spread.js",
"import": "./esm/_non_iterable_spread.js",
"default": "./cjs/_non_iterable_spread.cjs"
},
"./_/_object_destructuring_empty": {
"module-sync": "./esm/_object_destructuring_empty.js",
"webpack": "./esm/_object_destructuring_empty.js",
"import": "./esm/_object_destructuring_empty.js",
"default": "./cjs/_object_destructuring_empty.cjs"
},
"./_/_object_spread": {
"module-sync": "./esm/_object_spread.js",
"webpack": "./esm/_object_spread.js",
"import": "./esm/_object_spread.js",
"default": "./cjs/_object_spread.cjs"
},
"./_/_object_spread_props": {
"module-sync": "./esm/_object_spread_props.js",
"webpack": "./esm/_object_spread_props.js",
"import": "./esm/_object_spread_props.js",
"default": "./cjs/_object_spread_props.cjs"
},
"./_/_object_without_properties": {
"module-sync": "./esm/_object_without_properties.js",
"webpack": "./esm/_object_without_properties.js",
"import": "./esm/_object_without_properties.js",
"default": "./cjs/_object_without_properties.cjs"
},
"./_/_object_without_properties_loose": {
"module-sync": "./esm/_object_without_properties_loose.js",
"webpack": "./esm/_object_without_properties_loose.js",
"import": "./esm/_object_without_properties_loose.js",
"default": "./cjs/_object_without_properties_loose.cjs"
},
"./_/_overload_yield": {
"module-sync": "./esm/_overload_yield.js",
"webpack": "./esm/_overload_yield.js",
"import": "./esm/_overload_yield.js",
"default": "./cjs/_overload_yield.cjs"
},
"./_/_possible_constructor_return": {
"module-sync": "./esm/_possible_constructor_return.js",
"webpack": "./esm/_possible_constructor_return.js",
"import": "./esm/_possible_constructor_return.js",
"default": "./cjs/_possible_constructor_return.cjs"
},
"./_/_read_only_error": {
"module-sync": "./esm/_read_only_error.js",
"webpack": "./esm/_read_only_error.js",
"import": "./esm/_read_only_error.js",
"default": "./cjs/_read_only_error.cjs"
},
"./_/_set": {
"module-sync": "./esm/_set.js",
"webpack": "./esm/_set.js",
"import": "./esm/_set.js",
"default": "./cjs/_set.cjs"
},
"./_/_set_prototype_of": {
"module-sync": "./esm/_set_prototype_of.js",
"webpack": "./esm/_set_prototype_of.js",
"import": "./esm/_set_prototype_of.js",
"default": "./cjs/_set_prototype_of.cjs"
},
"./_/_skip_first_generator_next": {
"module-sync": "./esm/_skip_first_generator_next.js",
"webpack": "./esm/_skip_first_generator_next.js",
"import": "./esm/_skip_first_generator_next.js",
"default": "./cjs/_skip_first_generator_next.cjs"
},
"./_/_sliced_to_array": {
"module-sync": "./esm/_sliced_to_array.js",
"webpack": "./esm/_sliced_to_array.js",
"import": "./esm/_sliced_to_array.js",
"default": "./cjs/_sliced_to_array.cjs"
},
"./_/_sliced_to_array_loose": {
"module-sync": "./esm/_sliced_to_array_loose.js",
"webpack": "./esm/_sliced_to_array_loose.js",
"import": "./esm/_sliced_to_array_loose.js",
"default": "./cjs/_sliced_to_array_loose.cjs"
},
"./_/_super_prop_base": {
"module-sync": "./esm/_super_prop_base.js",
"webpack": "./esm/_super_prop_base.js",
"import": "./esm/_super_prop_base.js",
"default": "./cjs/_super_prop_base.cjs"
},
"./_/_tagged_template_literal": {
"module-sync": "./esm/_tagged_template_literal.js",
"webpack": "./esm/_tagged_template_literal.js",
"import": "./esm/_tagged_template_literal.js",
"default": "./cjs/_tagged_template_literal.cjs"
},
"./_/_tagged_template_literal_loose": {
"module-sync": "./esm/_tagged_template_literal_loose.js",
"webpack": "./esm/_tagged_template_literal_loose.js",
"import": "./esm/_tagged_template_literal_loose.js",
"default": "./cjs/_tagged_template_literal_loose.cjs"
},
"./_/_throw": {
"module-sync": "./esm/_throw.js",
"webpack": "./esm/_throw.js",
"import": "./esm/_throw.js",
"default": "./cjs/_throw.cjs"
},
"./_/_to_array": {
"module-sync": "./esm/_to_array.js",
"webpack": "./esm/_to_array.js",
"import": "./esm/_to_array.js",
"default": "./cjs/_to_array.cjs"
},
"./_/_to_consumable_array": {
"module-sync": "./esm/_to_consumable_array.js",
"webpack": "./esm/_to_consumable_array.js",
"import": "./esm/_to_consumable_array.js",
"default": "./cjs/_to_consumable_array.cjs"
},
"./_/_to_primitive": {
"module-sync": "./esm/_to_primitive.js",
"webpack": "./esm/_to_primitive.js",
"import": "./esm/_to_primitive.js",
"default": "./cjs/_to_primitive.cjs"
},
"./_/_to_property_key": {
"module-sync": "./esm/_to_property_key.js",
"webpack": "./esm/_to_property_key.js",
"import": "./esm/_to_property_key.js",
"default": "./cjs/_to_property_key.cjs"
},
"./_/_ts_add_disposable_resource": {
"module-sync": "./esm/_ts_add_disposable_resource.js",
"webpack": "./esm/_ts_add_disposable_resource.js",
"import": "./esm/_ts_add_disposable_resource.js",
"default": "./cjs/_ts_add_disposable_resource.cjs"
},
"./_/_ts_decorate": {
"module-sync": "./esm/_ts_decorate.js",
"webpack": "./esm/_ts_decorate.js",
"import": "./esm/_ts_decorate.js",
"default": "./cjs/_ts_decorate.cjs"
},
"./_/_ts_dispose_resources": {
"module-sync": "./esm/_ts_dispose_resources.js",
"webpack": "./esm/_ts_dispose_resources.js",
"import": "./esm/_ts_dispose_resources.js",
"default": "./cjs/_ts_dispose_resources.cjs"
},
"./_/_ts_generator": {
"module-sync": "./esm/_ts_generator.js",
"webpack": "./esm/_ts_generator.js",
"import": "./esm/_ts_generator.js",
"default": "./cjs/_ts_generator.cjs"
},
"./_/_ts_metadata": {
"module-sync": "./esm/_ts_metadata.js",
"webpack": "./esm/_ts_metadata.js",
"import": "./esm/_ts_metadata.js",
"default": "./cjs/_ts_metadata.cjs"
},
"./_/_ts_param": {
"module-sync": "./esm/_ts_param.js",
"webpack": "./esm/_ts_param.js",
"import": "./esm/_ts_param.js",
"default": "./cjs/_ts_param.cjs"
},
"./_/_ts_values": {
"module-sync": "./esm/_ts_values.js",
"webpack": "./esm/_ts_values.js",
"import": "./esm/_ts_values.js",
"default": "./cjs/_ts_values.cjs"
},
"./_/_type_of": {
"module-sync": "./esm/_type_of.js",
"webpack": "./esm/_type_of.js",
"import": "./esm/_type_of.js",
"default": "./cjs/_type_of.cjs"
},
"./_/_unsupported_iterable_to_array": {
"module-sync": "./esm/_unsupported_iterable_to_array.js",
"webpack": "./esm/_unsupported_iterable_to_array.js",
"import": "./esm/_unsupported_iterable_to_array.js",
"default": "./cjs/_unsupported_iterable_to_array.cjs"
},
"./_/_update": {
"module-sync": "./esm/_update.js",
"webpack": "./esm/_update.js",
"import": "./esm/_update.js",
"default": "./cjs/_update.cjs"
},
"./_/_using": {
"module-sync": "./esm/_using.js",
"webpack": "./esm/_using.js",
"import": "./esm/_using.js",
"default": "./cjs/_using.cjs"
},
"./_/_using_ctx": {
"module-sync": "./esm/_using_ctx.js",
"webpack": "./esm/_using_ctx.js",
"import": "./esm/_using_ctx.js",
"default": "./cjs/_using_ctx.cjs"
},
"./_/_wrap_async_generator": {
"module-sync": "./esm/_wrap_async_generator.js",
"webpack": "./esm/_wrap_async_generator.js",
"import": "./esm/_wrap_async_generator.js",
"default": "./cjs/_wrap_async_generator.cjs"
},
"./_/_wrap_native_super": {
"module-sync": "./esm/_wrap_native_super.js",
"webpack": "./esm/_wrap_native_super.js",
"import": "./esm/_wrap_native_super.js",
"default": "./cjs/_wrap_native_super.cjs"
},
"./_/_write_only_error": {
"module-sync": "./esm/_write_only_error.js",
"webpack": "./esm/_write_only_error.js",
"import": "./esm/_write_only_error.js",
"default": "./cjs/_write_only_error.cjs"
},
"./_/index": {
"module-sync": "./esm/index.js",
"webpack": "./esm/index.js",
"import": "./esm/index.js",
"default": "./cjs/index.cjs"
}
}
}
@@ -0,0 +1,67 @@
declare const colorVariants: {
solid: {
default: string;
primary: string;
secondary: string;
success: string;
warning: string;
danger: string;
foreground: string;
};
shadow: {
default: string;
primary: string;
secondary: string;
success: string;
warning: string;
danger: string;
foreground: string;
};
bordered: {
default: string;
primary: string;
secondary: string;
success: string;
warning: string;
danger: string;
foreground: string;
};
flat: {
default: string;
primary: string;
secondary: string;
success: string;
warning: string;
danger: string;
foreground: string;
};
faded: {
default: string;
primary: string;
secondary: string;
success: string;
warning: string;
danger: string;
foreground: string;
};
light: {
default: string;
primary: string;
secondary: string;
success: string;
warning: string;
danger: string;
foreground: string;
};
ghost: {
default: string;
primary: string;
secondary: string;
success: string;
warning: string;
danger: string;
foreground: string;
};
};
export { colorVariants };
@@ -0,0 +1 @@
{"version":3,"file":"unescape.js","sourceRoot":"","sources":["../../src/unescape.ts"],"names":[],"mappings":";;;AAEA;;;;;;;;;;;;;;;;;;GAkBG;AAEI,MAAM,QAAQ,GAAG,CACtB,CAAS,EACT,EACE,oBAAoB,GAAG,KAAK,EAC5B,aAAa,GAAG,IAAI,MACgD,EAAE,EACxE,EAAE;IACF,IAAI,aAAa,EAAE,CAAC;QAClB,OAAO,oBAAoB;YACzB,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,gBAAgB,EAAE,IAAI,CAAC;YACnC,CAAC,CAAC,CAAC;iBACE,OAAO,CAAC,2BAA2B,EAAE,MAAM,CAAC;iBAC5C,OAAO,CAAC,YAAY,EAAE,IAAI,CAAC,CAAA;IACpC,CAAC;IACD,OAAO,oBAAoB;QACzB,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,kBAAkB,EAAE,IAAI,CAAC;QACrC,CAAC,CAAC,CAAC;aACE,OAAO,CAAC,6BAA6B,EAAE,MAAM,CAAC;aAC9C,OAAO,CAAC,cAAc,EAAE,IAAI,CAAC,CAAA;AACtC,CAAC,CAAA;AAnBY,QAAA,QAAQ,YAmBpB","sourcesContent":["import { MinimatchOptions } from './index.js'\n\n/**\n * Un-escape a string that has been escaped with {@link escape}.\n *\n * If the {@link MinimatchOptions.windowsPathsNoEscape} option is used, then\n * square-bracket escapes are removed, but not backslash escapes.\n *\n * For example, it will turn the string `'[*]'` into `*`, but it will not\n * turn `'\\\\*'` into `'*'`, because `\\` is a path separator in\n * `windowsPathsNoEscape` mode.\n *\n * When `windowsPathsNoEscape` is not set, then both square-bracket escapes and\n * backslash escapes are removed.\n *\n * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped\n * or unescaped.\n *\n * When `magicalBraces` is not set, escapes of braces (`{` and `}`) will not be\n * unescaped.\n */\n\nexport const unescape = (\n s: string,\n {\n windowsPathsNoEscape = false,\n magicalBraces = true,\n }: Pick<MinimatchOptions, 'windowsPathsNoEscape' | 'magicalBraces'> = {},\n) => {\n if (magicalBraces) {\n return windowsPathsNoEscape\n ? s.replace(/\\[([^\\/\\\\])\\]/g, '$1')\n : s\n .replace(/((?!\\\\).|^)\\[([^\\/\\\\])\\]/g, '$1$2')\n .replace(/\\\\([^\\/])/g, '$1')\n }\n return windowsPathsNoEscape\n ? s.replace(/\\[([^\\/\\\\{}])\\]/g, '$1')\n : s\n .replace(/((?!\\\\).|^)\\[([^\\/\\\\{}])\\]/g, '$1$2')\n .replace(/\\\\([^\\/{}])/g, '$1')\n}\n"]}
@@ -0,0 +1,25 @@
import { clamp } from 'motion-utils';
import { number, alpha } from '../numbers/index.mjs';
import { sanitize } from '../utils/sanitize.mjs';
import { isColorString, splitColor } from './utils.mjs';
const clampRgbUnit = (v) => clamp(0, 255, v);
const rgbUnit = {
...number,
transform: (v) => Math.round(clampRgbUnit(v)),
};
const rgba = {
test: /*@__PURE__*/ isColorString("rgb", "red"),
parse: /*@__PURE__*/ splitColor("red", "green", "blue"),
transform: ({ red, green, blue, alpha: alpha$1 = 1 }) => "rgba(" +
rgbUnit.transform(red) +
", " +
rgbUnit.transform(green) +
", " +
rgbUnit.transform(blue) +
", " +
sanitize(alpha.transform(alpha$1)) +
")",
};
export { rgbUnit, rgba };
@@ -0,0 +1,50 @@
import type { Cell } from './autotracking'
import {
getValue as consumeTag,
createCell as createStorage,
setValue
} from './autotracking'
export type Tag = Cell<unknown>
const neverEq = (a: any, b: any): boolean => false
export function createTag(): Tag {
return createStorage(null, neverEq)
}
export { consumeTag }
export function dirtyTag(tag: Tag, value: any): void {
setValue(tag, value)
}
export interface Node<
T extends Array<unknown> | Record<string, unknown> =
| Array<unknown>
| Record<string, unknown>
> {
collectionTag: Tag | null
tag: Tag | null
tags: Record<string, Tag>
children: Record<string, Node>
proxy: T
value: T
id: number
}
export const consumeCollection = (node: Node): void => {
let tag = node.collectionTag
if (tag === null) {
tag = node.collectionTag = createTag()
}
consumeTag(tag)
}
export const dirtyCollection = (node: Node): void => {
const tag = node.collectionTag
if (tag !== null) {
dirtyTag(tag, null)
}
}
@@ -0,0 +1,30 @@
// This file was generated by lezer-generator. You probably shouldn't edit it.
import {LRParser, LocalTokenGroup} from "@lezer/lr"
import {descendant, unitToken, identifiers, queryIdentifiers} from "./tokens"
import {cssHighlighting} from "./highlight"
const spec_callee = {__proto__:null,lang:38, "nth-child":38, "nth-last-child":38, "nth-of-type":38, "nth-last-of-type":38, dir:38, "host-context":38, if:84, url:124, "url-prefix":124, domain:124, regexp:124}
const spec_queryIdentifier = {__proto__:null,or:98, and:98, not:106, only:106, layer:170}
const spec_QueryCallee = {__proto__:null,selector:112, layer:166}
const spec_AtKeyword = {__proto__:null,"@import":162, "@media":174, "@charset":178, "@namespace":182, "@keyframes":188, "@supports":200, "@scope":204}
const spec_identifier = {__proto__:null,to:207}
export const parser = LRParser.deserialize({
version: 14,
states: "EbQYQdOOO#qQdOOP#xO`OOOOQP'#Cf'#CfOOQP'#Ce'#CeO#}QdO'#ChO$nQaO'#CcO$xQdO'#CkO%TQdO'#DpO%YQdO'#DrO%_QdO'#DuO%_QdO'#DxOOQP'#FV'#FVO&eQhO'#EhOOQS'#FU'#FUOOQS'#Ek'#EkQYQdOOO&lQdO'#EOO&PQhO'#EUO&lQdO'#EWO'aQdO'#EYO'lQdO'#E]O'tQhO'#EcO(VQdO'#EeO(bQaO'#CfO)VQ`O'#D{O)[Q`O'#F`O)gQdO'#F`QOQ`OOP)qO&jO'#CaPOOO)C@t)C@tOOQP'#Cj'#CjOOQP,59S,59SO#}QdO,59SO)|QdO,59VO%TQdO,5:[O%YQdO,5:^O%_QdO,5:aO%_QdO,5:cO%_QdO,5:dO%_QdO'#ErO*XQ`O,58}O*aQdO'#DzOOQS,58},58}OOQP'#Cn'#CnOOQO'#Dn'#DnOOQP,59V,59VO*hQ`O,59VO*mQ`O,59VOOQP'#Dq'#DqOOQP,5:[,5:[OOQO'#Ds'#DsO*rQpO,5:^O+]QaO,5:aO+sQaO,5:dOOQW'#DZ'#DZO,ZQhO'#DdO,xQhO'#FaO'tQhO'#DbO-WQ`O'#DhOOQW'#F['#F[O-]Q`O,5;SO-eQ`O'#DeOOQS-E8i-E8iOOQ['#Cs'#CsO-jQdO'#CtO.QQdO'#CzO.hQdO'#C}O/OQ!pO'#DPO1RQ!jO,5:jOOQO'#DU'#DUO*mQ`O'#DTO1cQ!nO'#FXO3`Q`O'#DVO3eQ`O'#DkOOQ['#FX'#FXO-`Q`O,5:pO3jQ!bO,5:rOOQS'#E['#E[O3rQ`O,5:tO3wQdO,5:tOOQO'#E_'#E_O4PQ`O,5:wO4UQhO,5:}O%_QdO'#DgOOQS,5;P,5;PO-eQ`O,5;PO4^QdO,5;PO4fQdO,5:gO4vQdO'#EtO5TQ`O,5;zO5TQ`O,5;zPOOO'#Ej'#EjP5`O&jO,58{POOO,58{,58{OOQP1G.n1G.nOOQP1G.q1G.qO*hQ`O1G.qO*mQ`O1G.qOOQP1G/v1G/vO5kQpO1G/xO5sQaO1G/{O6ZQaO1G/}O6qQaO1G0OO7XQaO,5;^OOQO-E8p-E8pOOQS1G.i1G.iO7cQ`O,5:fO7hQdO'#DoO7oQdO'#CrOOQP1G/x1G/xO&lQdO1G/xO7vQ!jO'#DZO8UQ!bO,59vO8^QhO,5:OOOQO'#F]'#F]O8XQ!bO,59zO'tQhO,59xO8fQhO'#EvO8sQ`O,5;{O9OQhO,59|O9uQhO'#DiOOQW,5:S,5:SOOQS1G0n1G0nOOQW,5:P,5:PO9|Q!fO'#FYOOQS'#FY'#FYOOQS'#Em'#EmO;^QdO,59`OOQ[,59`,59`O;tQdO,59fOOQ[,59f,59fO<[QdO,59iOOQ[,59i,59iOOQ[,59k,59kO&lQdO,59mO<rQhO'#EQOOQW'#EQ'#EQO=WQ`O1G0UO1[QhO1G0UOOQ[,59o,59oO'tQhO'#DXOOQ[,59q,59qO=]Q#tO,5:VOOQS1G0[1G0[OOQS1G0^1G0^OOQS1G0`1G0`O=hQ`O1G0`O=mQdO'#E`OOQS1G0c1G0cOOQS1G0i1G0iO=xQaO,5:RO-`Q`O1G0kOOQS1G0k1G0kO-eQ`O1G0kO>PQ!fO1G0ROOQO1G0R1G0ROOQO,5;`,5;`O>gQdO,5;`OOQO-E8r-E8rO>tQ`O1G1fPOOO-E8h-E8hPOOO1G.g1G.gOOQP7+$]7+$]OOQP7+%d7+%dO&lQdO7+%dOOQS1G0Q1G0QO?PQaO'#F_O?ZQ`O,5:ZO?`Q!fO'#ElO@^QdO'#FWO@hQ`O,59^O@mQ!bO7+%dO&lQdO1G/bO@uQhO1G/fOOQW1G/j1G/jOOQW1G/d1G/dOAWQhO,5;bOOQO-E8t-E8tOAfQhO'#DZOAtQhO'#F^OBPQ`O'#F^OBUQ`O,5:TOOQS-E8k-E8kOOQ[1G.z1G.zOOQ[1G/Q1G/QOOQ[1G/T1G/TOOQ[1G/X1G/XOBZQdO,5:lOOQS7+%p7+%pOB`Q`O7+%pOBeQhO'#DYOBmQ`O,59sO'tQhO,59sOOQ[1G/q1G/qOBuQ`O1G/qOOQS7+%z7+%zOBzQbO'#DPOOQO'#Eb'#EbOCYQ`O'#EaOOQO'#Ea'#EaOCeQ`O'#EwOCmQdO,5:zOOQS,5:z,5:zOOQ[1G/m1G/mOOQS7+&V7+&VO-`Q`O7+&VOCxQ!fO'#EsO&lQdO'#EsOEPQdO7+%mOOQO7+%m7+%mOOQO1G0z1G0zOEdQ!bO<<IOOElQdO'#EqOEvQ`O,5;yOOQP1G/u1G/uOOQS-E8j-E8jOFOQdO'#EpOFYQ`O,5;rOOQ]1G.x1G.xOOQP<<IO<<IOOFbQdO7+$|OOQO'#D]'#D]OFiQ!bO7+%QOFqQhO'#EoOF{Q`O,5;xO&lQdO,5;xOOQW1G/o1G/oOOQO'#ES'#ESOGTQ`O1G0WOOQS<<I[<<I[O&lQdO,59tOGnQhO1G/_OOQ[1G/_1G/_OGuQ`O1G/_OOQW-E8l-E8lOOQ[7+%]7+%]OOQO,5:{,5:{O=pQdO'#ExOCeQ`O,5;cOOQS,5;c,5;cOOQS-E8u-E8uOOQS1G0f1G0fOOQS<<Iq<<IqOG}Q!fO,5;_OOQS-E8q-E8qOOQO<<IX<<IXOOQPAN>jAN>jOIUQaO,5;]OOQO-E8o-E8oOI`QdO,5;[OOQO-E8n-E8nOOQW<<Hh<<HhOOQW<<Hl<<HlOIjQhO<<HlOI{QhO,5;ZOJWQ`O,5;ZOOQO-E8m-E8mOJ]QdO1G1dOBZQdO'#EuOJgQ`O7+%rOOQW7+%r7+%rOJoQ!bO1G/`OOQ[7+$y7+$yOJzQhO7+$yPKRQ`O'#EnOOQO,5;d,5;dOOQO-E8v-E8vOOQS1G0}1G0}OKWQ`OAN>WO&lQdO1G0uOK]Q`O7+'OOOQO,5;a,5;aOOQO-E8s-E8sOOQW<<I^<<I^OOQ[<<He<<HePOQW,5;Y,5;YOOQWG23rG23rOKeQdO7+&a",
stateData: "Kx~O#sOS#tQQ~OW[OZ[O]TO`VOaVOi]OjWOmXO!jYO!mZO!saO!ybO!{cO!}dO#QeO#WfO#YgO#oRO~OQiOW[OZ[O]TO`VOaVOi]OjWOmXO!jYO!mZO!saO!ybO!{cO!}dO#QeO#WfO#YgO#ohO~O#m$SP~P!dO#tmO~O#ooO~O]qO`rOarOjsOmtO!juO!mwO#nvO~OpzO!^xO~P$SOc!QO#o|O#p}O~O#o!RO~O#o!TO~OW[OZ[O]TO`VOaVOjWOmXO!jYO!mZO#oRO~OS!]Oe!YO!V![O!Y!`O#q!XOp$TP~Ok$TP~P&POQ!jOe!cOm!dOp!eOr!mOt!mOz!kO!`!lO#o!bO#p!hO#}!fO~Ot!qO!`!lO#o!pO~Ot!sO#o!sO~OS!]Oe!YO!V![O!Y!`O#q!XO~Oe!vOpzO#Z!xO~O]YX`YX`!pXaYXjYXmYXpYX!^YX!jYX!mYX#nYX~O`!zO~Ok!{O#m$SXo$SX~O#m$SXo$SX~P!dO#u#OO#v#OO#w#QO~Oc#UO#o|O#p}O~OpzO!^xO~Oo$SP~P!dOe#`O~Oe#aO~Ol#bO!h#cO~O]qO`rOarOjsOmtO~Op!ia!^!ia!j!ia!m!ia#n!iad!ia~P*zOp!la!^!la!j!la!m!la#n!lad!la~P*zOR#gOS!]Oe!YOr#gOt#gO!V![O!Y!`O#q#dO#}!fO~O!R#iO!^#jOk$TXp$TX~Oe#mO~Ok#oOpzO~Oe!vO~O]#rO`#rOd#uOi#rOj#rOk#rO~P&lO]#rO`#rOi#rOj#rOk#rOl#wO~P&lO]#rO`#rOi#rOj#rOk#rOo#yO~P&lOP#zOSsXesXksXvsX!VsX!YsX!usX!wsX#qsX!TsXQsX]sX`sXdsXisXjsXmsXpsXrsXtsXzsX!`sX#osX#psX#}sXlsXosX!^sX!qsX#msX~Ov#{O!u#|O!w#}Ok$TP~P'tOe#aOS#{Xk#{Xv#{X!V#{X!Y#{X!u#{X!w#{X#q#{XQ#{X]#{X`#{Xd#{Xi#{Xj#{Xm#{Xp#{Xr#{Xt#{Xz#{X!`#{X#o#{X#p#{X#}#{Xl#{Xo#{X!^#{X!q#{X#m#{X~Oe$RO~Oe$TO~Ok$VOv#{O~Ok$WO~Ot$XO!`!lO~Op$YO~OpzO!R#iO~OpzO#Z$`O~O!q$bOk!oa#m!oao!oa~P&lOk#hX#m#hXo#hX~P!dOk!{O#m$Sao$Sa~O#u#OO#v#OO#w$hO~Ol$jO!h$kO~Op!ii!^!ii!j!ii!m!ii#n!iid!ii~P*zOp!ki!^!ki!j!ki!m!ki#n!kid!ki~P*zOp!li!^!li!j!li!m!li#n!lid!li~P*zOp#fa!^#fa~P$SOo$lO~Od$RP~P%_Od#zP~P&lO`!PXd}X!R}X!T!PX~O`$sO!T$tO~Od$uO!R#iO~Ok#jXp#jX!^#jX~P'tO!^#jOk$Tap$Ta~O!R#iOk!Uap!Ua!^!Uad!Ua`!Ua~OS!]Oe!YO!V![O!Y!`O#q$yO~Od$QP~P9dOv#{OQ#|X]#|X`#|Xd#|Xe#|Xi#|Xj#|Xk#|Xm#|Xp#|Xr#|Xt#|Xz#|X!`#|X#o#|X#p#|X#}#|Xl#|Xo#|X~O]#rO`#rOd%OOi#rOj#rOk#rO~P&lO]#rO`#rOi#rOj#rOk#rOl%PO~P&lO]#rO`#rOi#rOj#rOk#rOo%QO~P&lOe%SOS!tXk!tX!V!tX!Y!tX#q!tX~Ok%TO~Od%YOt%ZO!a%ZO~Ok%[O~Oo%cO#o%^O#}%]O~Od%dO~P$SOv#{O!^%hO!q%jOk!oi#m!oio!oi~P&lOk#ha#m#hao#ha~P!dOk!{O#m$Sio$Si~O!^%mOd$RX~P$SOd%oO~Ov#{OQ#`Xd#`Xe#`Xm#`Xp#`Xr#`Xt#`Xz#`X!^#`X!`#`X#o#`X#p#`X#}#`X~O!^%qOd#zX~P&lOd%sO~Ol%tOv#{O~OR#gOr#gOt#gO#q%vO#}!fO~O!R#iOk#jap#ja!^#ja~O`!PXd}X!R}X!^}X~O!R#iO!^%xOd$QX~O`%zO~Od%{O~O#o%|O~Ok&OO~O`&PO!R#iO~Od&ROk&QO~Od&UO~OP#zOpsX!^sXdsX~O#}%]Op#TX!^#TX~OpzO!^&WO~Oo&[O#o%^O#}%]O~Ov#{OQ#gXe#gXk#gXm#gXp#gXr#gXt#gXz#gX!^#gX!`#gX!q#gX#m#gX#o#gX#p#gX#}#gXo#gX~O!^%hO!q&`Ok!oq#m!oqo!oq~P&lOl&aOv#{O~Od#eX!^#eX~P%_O!^%mOd$Ra~Od#dX!^#dX~P&lO!^%qOd#za~Od&fO~P&lOd&gO!T&hO~Od#cX!^#cX~P9dO!^%xOd$Qa~O]&mOd&oO~OS#bae#ba!V#ba!Y#ba#q#ba~Od&qO~PG]Od&qOk&rO~Ov#{OQ#gae#gak#gam#gap#gar#gat#gaz#ga!^#ga!`#ga!q#ga#m#ga#o#ga#p#ga#}#gao#ga~Od#ea!^#ea~P$SOd#da!^#da~P&lOR#gOr#gOt#gO#q%vO#}%]O~O!R#iOd#ca!^#ca~O`&xO~O!^%xOd$Qi~P&lO]&mOd&|O~Ov#{Od|ik|i~Od&}O~PG]Ok'OO~Od'PO~O!^%xOd$Qq~Od#cq!^#cq~P&lO#s!a#t#}]#}v!m~",
goto: "2h$UPPPPP$VP$YP$c$uP$cP%X$cPP%_PPP%e%o%oPPPPP%oPP%oP&]P%oP%o'W%oP't'w'}'}(^'}P'}P'}P'}'}P(m'}(yP(|PP)p)v$c)|$c*SP$cP$c$cP*Y*{+YP$YP+aP+dP$YP$YP$YP+j$YP+m+p+s+z$YP$YPP$YP,P,V,f,|-[-b-l-r-x.O.U.`.f.l.rPPPPPPPPPPP.x/R/w/z0|P1U1u2O2R2U2[RnQ_^OP`kz!{$dq[OPYZ`kuvwxz!v!{#`$d%mqSOPYZ`kuvwxz!v!{#`$d%mQpTR#RqQ!OVR#SrQ#S!QS$Q!i!jR$i#U!V!mac!c!d!e!z#a#c#t#v#x#{$a$k$p$s%h%i%q%u%z&P&d&l&x'Q!U!mac!c!d!e!z#a#c#t#v#x#{$a$k$p$s%h%i%q%u%z&P&d&l&x'QU#g!Y$t&hU%`$Y%b&WR&V%_!V!iac!c!d!e!z#a#c#t#v#x#{$a$k$p$s%h%i%q%u%z&P&d&l&x'QR$S!kQ%W$RR&S%Xk!^]bf!Y![!g#i#j#m$P$R%X%xQ#e!YQ${#mQ%w$tQ&j%xR&w&hQ!ygQ#p!`Q$^!xR%f$`R#n!]!U!mac!c!d!e!z#a#c#t#v#x#{$a$k$p$s%h%i%q%u%z&P&d&l&x'QQ!qdR$X!rQ!PVR#TrQ#S!PR$i#TQ!SWR#VsQ!UXR#WtQ{UQ!wgQ#^yQ#o!_Q$U!nQ$[!uQ$_!yQ%e$^Q&Y%aQ&]%fR&v&XSjPzQ!}kQ$c!{R%k$dZiPkz!{$dR$P!gQ%}%SR&z&mR!rdR!teR$Z!tS%a$Y%bR&t&WV%_$Y%b&WQ#PmR$g#PQ`OSkPzU!a`k$dR$d!{Q$p#aY%p$p%u&d&l'QQ%u$sQ&d%qQ&l%zR'Q&xQ#t!cQ#v!dQ#x!eV$}#t#v#xQ%X$RR&T%XQ%y$zS&k%y&yR&y&lQ%r$pR&e%rQ%n$mR&c%nQyUR#]yQ%i$aR&_%iQ!|jS$e!|$fR$f!}Q&n%}R&{&nQ#k!ZR$x#kQ%b$YR&Z%bQ&X%aR&u&X__OP`kz!{$d^UOP`kz!{$dQ!VYQ!WZQ#XuQ#YvQ#ZwQ#[xQ$]!vQ$m#`R&b%mR$q#aQ!gaQ!oc[#q!c!d!e#t#v#xQ$a!zd$o#a$p$s%q%u%z&d&l&x'QQ$r#cQ%R#{S%g$a%iQ%l$kQ&^%hR&p&P]#s!c!d!e#t#v#xW!Z]b!g$PQ!ufQ#f!YQ#l![Q$v#iQ$w#jQ$z#mS%V$R%XR&i%xQ#h!YQ%w$tR&w&hR$|#mR$n#`QlPR#_zQ!_]Q!nbQ$O!gR%U$P",
nodeNames: "⚠ Unit VariableName VariableName QueryCallee Comment StyleSheet RuleSet UniversalSelector TagSelector TagName NestingSelector ClassSelector . ClassName PseudoClassSelector : :: PseudoClassName PseudoClassName ) ( ArgList ValueName ParenthesizedValue AtKeyword # ; ] [ BracketedValue } { BracedValue ColorLiteral NumberLiteral StringLiteral BinaryExpression BinOp CallExpression Callee IfExpression if ArgList IfBranch KeywordQuery FeatureQuery FeatureName BinaryQuery LogicOp ComparisonQuery CompareOp UnaryQuery UnaryQueryOp ParenthesizedQuery SelectorQuery selector ParenthesizedSelector CallQuery ArgList , CallLiteral CallTag ParenthesizedContent PseudoClassName ArgList IdSelector IdName AttributeSelector AttributeName MatchOp ChildSelector ChildOp DescendantSelector SiblingSelector SiblingOp Block Declaration PropertyName Important ImportStatement import Layer layer LayerName layer MediaStatement media CharsetStatement charset NamespaceStatement namespace NamespaceName KeyframesStatement keyframes KeyframeName KeyframeList KeyframeSelector KeyframeRangeName SupportsStatement supports ScopeStatement scope to AtRule Styles",
maxTerm: 143,
nodeProps: [
["isolate", -2,5,36,""],
["openedBy", 20,"(",28,"[",31,"{"],
["closedBy", 21,")",29,"]",32,"}"]
],
propSources: [cssHighlighting],
skippedNodes: [0,5,106],
repeatNodeCount: 15,
tokenData: "JQ~R!YOX$qX^%i^p$qpq%iqr({rs-ust/itu6Wuv$qvw7Qwx7cxy9Qyz9cz{9h{|:R|}>t}!O?V!O!P?t!P!Q@]!Q![AU![!]BP!]!^B{!^!_C^!_!`DY!`!aDm!a!b$q!b!cEn!c!}$q!}#OG{#O#P$q#P#QH^#Q#R6W#R#o$q#o#pHo#p#q6W#q#rIQ#r#sIc#s#y$q#y#z%i#z$f$q$f$g%i$g#BY$q#BY#BZ%i#BZ$IS$q$IS$I_%i$I_$I|$q$I|$JO%i$JO$JT$q$JT$JU%i$JU$KV$q$KV$KW%i$KW&FU$q&FU&FV%i&FV;'S$q;'S;=`Iz<%lO$q`$tSOy%Qz;'S%Q;'S;=`%c<%lO%Q`%VS!a`Oy%Qz;'S%Q;'S;=`%c<%lO%Q`%fP;=`<%l%Q~%nh#s~OX%QX^'Y^p%Qpq'Yqy%Qz#y%Q#y#z'Y#z$f%Q$f$g'Y$g#BY%Q#BY#BZ'Y#BZ$IS%Q$IS$I_'Y$I_$I|%Q$I|$JO'Y$JO$JT%Q$JT$JU'Y$JU$KV%Q$KV$KW'Y$KW&FU%Q&FU&FV'Y&FV;'S%Q;'S;=`%c<%lO%Q~'ah#s~!a`OX%QX^'Y^p%Qpq'Yqy%Qz#y%Q#y#z'Y#z$f%Q$f$g'Y$g#BY%Q#BY#BZ'Y#BZ$IS%Q$IS$I_'Y$I_$I|%Q$I|$JO'Y$JO$JT%Q$JT$JU'Y$JU$KV%Q$KV$KW'Y$KW&FU%Q&FU&FV'Y&FV;'S%Q;'S;=`%c<%lO%Qj)OUOy%Qz#]%Q#]#^)b#^;'S%Q;'S;=`%c<%lO%Qj)gU!a`Oy%Qz#a%Q#a#b)y#b;'S%Q;'S;=`%c<%lO%Qj*OU!a`Oy%Qz#d%Q#d#e*b#e;'S%Q;'S;=`%c<%lO%Qj*gU!a`Oy%Qz#c%Q#c#d*y#d;'S%Q;'S;=`%c<%lO%Qj+OU!a`Oy%Qz#f%Q#f#g+b#g;'S%Q;'S;=`%c<%lO%Qj+gU!a`Oy%Qz#h%Q#h#i+y#i;'S%Q;'S;=`%c<%lO%Qj,OU!a`Oy%Qz#T%Q#T#U,b#U;'S%Q;'S;=`%c<%lO%Qj,gU!a`Oy%Qz#b%Q#b#c,y#c;'S%Q;'S;=`%c<%lO%Qj-OU!a`Oy%Qz#h%Q#h#i-b#i;'S%Q;'S;=`%c<%lO%Qj-iS!qY!a`Oy%Qz;'S%Q;'S;=`%c<%lO%Q~-xWOY-uZr-urs.bs#O-u#O#P.g#P;'S-u;'S;=`/c<%lO-u~.gOt~~.jRO;'S-u;'S;=`.s;=`O-u~.vXOY-uZr-urs.bs#O-u#O#P.g#P;'S-u;'S;=`/c;=`<%l-u<%lO-u~/fP;=`<%l-uj/nYjYOy%Qz!Q%Q!Q![0^![!c%Q!c!i0^!i#T%Q#T#Z0^#Z;'S%Q;'S;=`%c<%lO%Qj0cY!a`Oy%Qz!Q%Q!Q![1R![!c%Q!c!i1R!i#T%Q#T#Z1R#Z;'S%Q;'S;=`%c<%lO%Qj1WY!a`Oy%Qz!Q%Q!Q![1v![!c%Q!c!i1v!i#T%Q#T#Z1v#Z;'S%Q;'S;=`%c<%lO%Qj1}YrY!a`Oy%Qz!Q%Q!Q![2m![!c%Q!c!i2m!i#T%Q#T#Z2m#Z;'S%Q;'S;=`%c<%lO%Qj2tYrY!a`Oy%Qz!Q%Q!Q![3d![!c%Q!c!i3d!i#T%Q#T#Z3d#Z;'S%Q;'S;=`%c<%lO%Qj3iY!a`Oy%Qz!Q%Q!Q![4X![!c%Q!c!i4X!i#T%Q#T#Z4X#Z;'S%Q;'S;=`%c<%lO%Qj4`YrY!a`Oy%Qz!Q%Q!Q![5O![!c%Q!c!i5O!i#T%Q#T#Z5O#Z;'S%Q;'S;=`%c<%lO%Qj5TY!a`Oy%Qz!Q%Q!Q![5s![!c%Q!c!i5s!i#T%Q#T#Z5s#Z;'S%Q;'S;=`%c<%lO%Qj5zSrY!a`Oy%Qz;'S%Q;'S;=`%c<%lO%Qd6ZUOy%Qz!_%Q!_!`6m!`;'S%Q;'S;=`%c<%lO%Qd6tS!hS!a`Oy%Qz;'S%Q;'S;=`%c<%lO%Qb7VSZQOy%Qz;'S%Q;'S;=`%c<%lO%Q~7fWOY7cZw7cwx.bx#O7c#O#P8O#P;'S7c;'S;=`8z<%lO7c~8RRO;'S7c;'S;=`8[;=`O7c~8_XOY7cZw7cwx.bx#O7c#O#P8O#P;'S7c;'S;=`8z;=`<%l7c<%lO7c~8}P;=`<%l7cj9VSeYOy%Qz;'S%Q;'S;=`%c<%lO%Q~9hOd~n9oUWQvWOy%Qz!_%Q!_!`6m!`;'S%Q;'S;=`%c<%lO%Qj:YWvW!mQOy%Qz!O%Q!O!P:r!P!Q%Q!Q![=w![;'S%Q;'S;=`%c<%lO%Qj:wU!a`Oy%Qz!Q%Q!Q![;Z![;'S%Q;'S;=`%c<%lO%Qj;bY!a`#}YOy%Qz!Q%Q!Q![;Z![!g%Q!g!h<Q!h#X%Q#X#Y<Q#Y;'S%Q;'S;=`%c<%lO%Qj<VY!a`Oy%Qz{%Q{|<u|}%Q}!O<u!O!Q%Q!Q![=^![;'S%Q;'S;=`%c<%lO%Qj<zU!a`Oy%Qz!Q%Q!Q![=^![;'S%Q;'S;=`%c<%lO%Qj=eU!a`#}YOy%Qz!Q%Q!Q![=^![;'S%Q;'S;=`%c<%lO%Qj>O[!a`#}YOy%Qz!O%Q!O!P;Z!P!Q%Q!Q![=w![!g%Q!g!h<Q!h#X%Q#X#Y<Q#Y;'S%Q;'S;=`%c<%lO%Qj>yS!^YOy%Qz;'S%Q;'S;=`%c<%lO%Qj?[WvWOy%Qz!O%Q!O!P:r!P!Q%Q!Q![=w![;'S%Q;'S;=`%c<%lO%Qj?yU]YOy%Qz!Q%Q!Q![;Z![;'S%Q;'S;=`%c<%lO%Q~@bTvWOy%Qz{@q{;'S%Q;'S;=`%c<%lO%Q~@xS!a`#t~Oy%Qz;'S%Q;'S;=`%c<%lO%QjAZ[#}YOy%Qz!O%Q!O!P;Z!P!Q%Q!Q![=w![!g%Q!g!h<Q!h#X%Q#X#Y<Q#Y;'S%Q;'S;=`%c<%lO%QjBUU`YOy%Qz![%Q![!]Bh!];'S%Q;'S;=`%c<%lO%QbBoSaQ!a`Oy%Qz;'S%Q;'S;=`%c<%lO%QjCQSkYOy%Qz;'S%Q;'S;=`%c<%lO%QhCcU!TWOy%Qz!_%Q!_!`Cu!`;'S%Q;'S;=`%c<%lO%QhC|S!TW!a`Oy%Qz;'S%Q;'S;=`%c<%lO%QlDaS!TW!hSOy%Qz;'S%Q;'S;=`%c<%lO%QjDtV!jQ!TWOy%Qz!_%Q!_!`Cu!`!aEZ!a;'S%Q;'S;=`%c<%lO%QbEbS!jQ!a`Oy%Qz;'S%Q;'S;=`%c<%lO%QjEqYOy%Qz}%Q}!OFa!O!c%Q!c!}GO!}#T%Q#T#oGO#o;'S%Q;'S;=`%c<%lO%QjFfW!a`Oy%Qz!c%Q!c!}GO!}#T%Q#T#oGO#o;'S%Q;'S;=`%c<%lO%QjGV[iY!a`Oy%Qz}%Q}!OGO!O!Q%Q!Q![GO![!c%Q!c!}GO!}#T%Q#T#oGO#o;'S%Q;'S;=`%c<%lO%QjHQSmYOy%Qz;'S%Q;'S;=`%c<%lO%QnHcSl^Oy%Qz;'S%Q;'S;=`%c<%lO%QjHtSpYOy%Qz;'S%Q;'S;=`%c<%lO%QjIVSoYOy%Qz;'S%Q;'S;=`%c<%lO%QfIhU!mQOy%Qz!_%Q!_!`6m!`;'S%Q;'S;=`%c<%lO%Q`I}P;=`<%l$q",
tokenizers: [descendant, unitToken, identifiers, queryIdentifiers, 1, 2, 3, 4, new LocalTokenGroup("m~RRYZ[z{a~~g~aO#v~~dP!P!Qg~lO#w~~", 28, 129)],
topRules: {"StyleSheet":[0,6],"Styles":[1,105]},
specialized: [{term: 124, get: (value) => spec_callee[value] || -1},{term: 125, get: (value) => spec_queryIdentifier[value] || -1},{term: 4, get: (value) => spec_QueryCallee[value] || -1},{term: 25, get: (value) => spec_AtKeyword[value] || -1},{term: 123, get: (value) => spec_identifier[value] || -1}],
tokenPrec: 1963
})
@@ -0,0 +1,53 @@
"use client";
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
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/navbar-brand.tsx
var navbar_brand_exports = {};
__export(navbar_brand_exports, {
default: () => navbar_brand_default
});
module.exports = __toCommonJS(navbar_brand_exports);
var import_system = require("@heroui/system");
var import_react_utils2 = require("@heroui/react-utils");
var import_shared_utils = require("@heroui/shared-utils");
// src/navbar-context.ts
var import_react_utils = require("@heroui/react-utils");
var [NavbarProvider, useNavbarContext] = (0, import_react_utils.createContext)({
name: "NavbarContext",
strict: true,
errorMessage: "useNavbarContext: `context` is undefined. Seems you forgot to wrap component within <Navbar />"
});
// src/navbar-brand.tsx
var import_jsx_runtime = require("react/jsx-runtime");
var NavbarBrand = (0, import_system.forwardRef)((props, ref) => {
var _a;
const { as, className, children, ...otherProps } = props;
const Component = as || "div";
const domRef = (0, import_react_utils2.useDOMRef)(ref);
const { slots, classNames } = useNavbarContext();
const styles = (0, import_shared_utils.clsx)(classNames == null ? void 0 : classNames.brand, className);
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Component, { ref: domRef, className: (_a = slots.brand) == null ? void 0 : _a.call(slots, { class: styles }), ...otherProps, children });
});
NavbarBrand.displayName = "HeroUI.NavbarBrand";
var navbar_brand_default = NavbarBrand;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {});
@@ -0,0 +1 @@
{"version":3,"file":"PluginManager.d.ts","sourceRoot":"","sources":["../../../../src/container/services/PluginManager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAC;AAO9C,OAAO,EAIL,aAAa,EACd,MAAM,qBAAqB,CAAC;AAI7B,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAC7C,OAAO,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AACpE,OAAO,EAAE,wBAAwB,EAAE,MAAM,4BAA4B,CAAC;AAEtE,qBAAa,aAAa;;gBAOtB,SAAS,EAAE,SAAS,EACpB,uBAAuB,EAAE,uBAAuB,EAChD,wBAAwB,EAAE,wBAAwB;IAQ7C,QAAQ,CACb,SAAS,EAAE,SAAS,EACpB,iBAAiB,EAAE,OAAO,CAAC,OAAO,EAAE,CAAC,SAAS,EAAE,aAAa,CAAC,CAAC,GAC9D,IAAI;CA0DR"}
@@ -0,0 +1,38 @@
'use strict';
var parse = require('../');
var test = require('tape');
test('nums', function (t) {
var argv = parse([
'-x', '1234',
'-y', '5.67',
'-z', '1e7',
'-w', '10f',
'--hex', '0xdeadbeef',
'789',
]);
t.deepEqual(argv, {
x: 1234,
y: 5.67,
z: 1e7,
w: '10f',
hex: 0xdeadbeef,
_: [789],
});
t.deepEqual(typeof argv.x, 'number');
t.deepEqual(typeof argv.y, 'number');
t.deepEqual(typeof argv.z, 'number');
t.deepEqual(typeof argv.w, 'string');
t.deepEqual(typeof argv.hex, 'number');
t.deepEqual(typeof argv._[0], 'number');
t.end();
});
test('already a number', function (t) {
var argv = parse(['-x', 1234, 789]);
t.deepEqual(argv, { x: 1234, _: [789] });
t.deepEqual(typeof argv.x, 'number');
t.deepEqual(typeof argv._[0], 'number');
t.end();
});
@@ -0,0 +1,37 @@
var $b6837c2f80a3c32f$exports = require("./useSelectableCollection.main.js");
var $433b1145b0781e10$exports = require("./useSelectableItem.main.js");
var $bd230acee196f50c$exports = require("./useSelectableList.main.js");
var $836f880b12dcae5c$exports = require("./ListKeyboardDelegate.main.js");
var $2ac4508142683dcb$exports = require("./DOMLayoutDelegate.main.js");
var $a1189052f36475e8$exports = require("./useTypeSelect.main.js");
function $parcel$export(e, n, v, s) {
Object.defineProperty(e, n, {get: v, set: s, enumerable: true, configurable: true});
}
$parcel$export(module.exports, "useSelectableCollection", () => $b6837c2f80a3c32f$exports.useSelectableCollection);
$parcel$export(module.exports, "useSelectableItem", () => $433b1145b0781e10$exports.useSelectableItem);
$parcel$export(module.exports, "useSelectableList", () => $bd230acee196f50c$exports.useSelectableList);
$parcel$export(module.exports, "ListKeyboardDelegate", () => $836f880b12dcae5c$exports.ListKeyboardDelegate);
$parcel$export(module.exports, "DOMLayoutDelegate", () => $2ac4508142683dcb$exports.DOMLayoutDelegate);
$parcel$export(module.exports, "useTypeSelect", () => $a1189052f36475e8$exports.useTypeSelect);
/*
* Copyright 2020 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
//# sourceMappingURL=main.js.map
@@ -0,0 +1,152 @@
/**
* @fileoverview Rule to disallow negating the left operand of relational operators
* @author Toru Nagashima
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const astUtils = require("./utils/ast-utils");
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
/**
* Checks whether the given operator is `in` or `instanceof`
* @param {string} op The operator type to check.
* @returns {boolean} `true` if the operator is `in` or `instanceof`
*/
function isInOrInstanceOfOperator(op) {
return op === "in" || op === "instanceof";
}
/**
* Checks whether the given operator is an ordering relational operator or not.
* @param {string} op The operator type to check.
* @returns {boolean} `true` if the operator is an ordering relational operator.
*/
function isOrderingRelationalOperator(op) {
return op === "<" || op === ">" || op === ">=" || op === "<=";
}
/**
* Checks whether the given node is a logical negation expression or not.
* @param {ASTNode} node The node to check.
* @returns {boolean} `true` if the node is a logical negation expression.
*/
function isNegation(node) {
return node.type === "UnaryExpression" && node.operator === "!";
}
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
type: "problem",
defaultOptions: [
{
enforceForOrderingRelations: false,
},
],
docs: {
description:
"Disallow negating the left operand of relational operators",
recommended: true,
url: "https://eslint.org/docs/latest/rules/no-unsafe-negation",
},
hasSuggestions: true,
schema: [
{
type: "object",
properties: {
enforceForOrderingRelations: {
type: "boolean",
},
},
additionalProperties: false,
},
],
fixable: null,
messages: {
unexpected:
"Unexpected negating the left operand of '{{operator}}' operator.",
suggestNegatedExpression:
"Negate '{{operator}}' expression instead of its left operand. This changes the current behavior.",
suggestParenthesisedNegation:
"Wrap negation in '()' to make the intention explicit. This preserves the current behavior.",
},
},
create(context) {
const sourceCode = context.sourceCode;
const [{ enforceForOrderingRelations }] = context.options;
return {
BinaryExpression(node) {
const operator = node.operator;
const orderingRelationRuleApplies =
enforceForOrderingRelations &&
isOrderingRelationalOperator(operator);
if (
(isInOrInstanceOfOperator(operator) ||
orderingRelationRuleApplies) &&
isNegation(node.left) &&
!astUtils.isParenthesised(sourceCode, node.left)
) {
context.report({
node,
loc: node.left.loc,
messageId: "unexpected",
data: { operator },
suggest: [
{
messageId: "suggestNegatedExpression",
data: { operator },
fix(fixer) {
const negationToken =
sourceCode.getFirstToken(node.left);
const fixRange = [
negationToken.range[1],
node.range[1],
];
const text = sourceCode.text.slice(
fixRange[0],
fixRange[1],
);
return fixer.replaceTextRange(
fixRange,
`(${text})`,
);
},
},
{
messageId: "suggestParenthesisedNegation",
fix(fixer) {
return fixer.replaceText(
node.left,
`(${sourceCode.getText(node.left)})`,
);
},
},
],
});
}
},
};
},
};
@@ -0,0 +1,34 @@
let OldValue = require('../old-value')
let Value = require('../value')
class Pixelated extends Value {
/**
* Different name for WebKit and Firefox
*/
old(prefix) {
if (prefix === '-webkit-') {
return new OldValue(this.name, '-webkit-optimize-contrast')
}
if (prefix === '-moz-') {
return new OldValue(this.name, '-moz-crisp-edges')
}
return super.old(prefix)
}
/**
* Use non-standard name for WebKit and Firefox
*/
replace(string, prefix) {
if (prefix === '-webkit-') {
return string.replace(this.regexp(), '$1-webkit-optimize-contrast')
}
if (prefix === '-moz-') {
return string.replace(this.regexp(), '$1-moz-crisp-edges')
}
return super.replace(string, prefix)
}
}
Pixelated.names = ['pixelated']
module.exports = Pixelated
@@ -0,0 +1,7 @@
import addMonths from "./addMonths.mjs";
function addYears(date, years) {
return addMonths(date, years * 12);
}
export {
addYears as default
};
@@ -0,0 +1,753 @@
flf2a$ 4 4 8 0 14 0 8256
Graceful-6x4 by Mikhael Goikhman, http://migo.n3.net/, 20/Jan/2002.
Why did I make this font? Most of the figlet fonts are ugly for my taste.
Chars ".", "'" or "|" are not as graceful as "(", ")", "/", "\" and "_".
Also most of the fonts unlike this one are either small or good, not both.
And finally, I wanted to have a strictly sized font, this one is 6x4.
I intended to create this elegant figlet font in 1996, but only in
January 2002 actually had the time to bring it to the working state. :)
Cyrillic letters are supported, maybe somewhen I will add hebrew latters.
To get a monospaced font 6x4, use "figlet -f graceful -m -1". Enjoy!
Permission is hereby given to modify this font, as long as the
modifier's name is added to this comment.
$$ @
$$ @
$$ @
$$ @@
_ @
/ \ @
\_/ @
(_) @@
_ _ @
(/(/ @
@
@@
_ _ @
/ )( \@
) (@
\_)(_/@@
____ @
/ (__)@
\__ \@
(__)_/@@
_ _ @
(// ) @
/ /_ @
(_/(/ @@
___ @
( _ \@
/ _ /@
\__\_)@@
_ @
(/ @
@
@@
_ @
/ ) @
( ( @
\_) @@
_ @
( \ @
) ) @
(_/ @@
@
(\/\/)@
) ( @
(/\/\)@@
_ @
( ) @
(_ _) @
(_) @@
@
_ @
( ) @
(/ @@
@
___ @
(___) @
@@
@
@
_ @
(_) @@
_ @
/ ) @
/ / @
(_/ @@
__ @
/ \ @
( 0 )@
\__/ @@
__ @
/ \ @
(_/ / @
(__) @@
____ @
(___ \@
/ __/@
(____)@@
____ @
( __ \@
(__ (@
(____/@@
___ @
/ _ \@
(__ (@
(__/@@
___ @
/ __)@
(___ \@
(____/@@
___ @
/ __)@
( _ \@
\___/@@
____ @
(__ )@
/ / @
(_/ @@
____ @
/ _ \@
) _ (@
\____/@@
___ @
/ _ \ @
\__ )@
(___/ @@
_ @
(_) @
_ @
(_) @@
_ @
(_) @
( ) @
(/ @@
__ @
/ / @
( ( @
\_\ @@
___ @
(___) @
___ @
(___) @@
__ @
\ \ @
) ) @
/_/ @@
___ @
(__ \ @
(__/ @
(_) @@
___ @
/ \@
( (__/@
\___)@@
__ @
/ _\ @
/ \@
\_/\_/@@
____ @
( _ \@
) _ (@
(____/@@
___ @
/ __)@
( (__ @
\___)@@
____ @
( \@
) D (@
(____/@@
____ @
( __)@
) _) @
(____)@@
____ @
( __)@
) _) @
(__) @@
___ @
/ __)@
( (_ \@
\___/@@
_ _ @
/ )( \@
) __ (@
\_)(_/@@
__ @
( ) @
)( @
(__) @@
__ @
_( )@
/ \) \@
\____/@@
__ _ @
( / )@
) ( @
(__\_)@@
__ @
( ) @
/ (_/\@
\____/@@
_ _ @
( \/ )@
/ \/ \@
\_)(_/@@
__ _ @
( ( \@
/ /@
\_)__)@@
__ @
/ \ @
( O )@
\__/ @@
____ @
( _ \@
) __/@
(__) @@
__ @
/ \ @
( O )@
\__\)@@
____ @
( _ \@
) /@
(__\_)@@
____ @
/ ___)@
\___ \@
(____/@@
____ @
(_ _)@
)( @
(__) @@
_ _ @
/ )( \@
) \/ (@
\____/@@
_ _ @
/ )( \@
\ \/ /@
\__/ @@
_ _ @
/ )( \@
\ /\ /@
(_/\_)@@
_ _ @
( \/ )@
) ( @
(_/\_)@@
_ _ @
( \/ )@
) / @
(__/ @@
____ @
(__ )@
/ _/ @
(____)@@
___ @
/ _) @
) (_ @
\___) @@
_ @
( \ @
\ \ @
\_) @@
___ @
(_ \@
_) (@
(___/@@
__ @
/ \ @
(_/\_)@
@@
@
@
____ @
(____)@@
_ @
\) @
@
@@
__ @
/ _\ @
/ \@
\_/\_/@@
____ @
( _ \@
) _ (@
(____/@@
___ @
/ __)@
( (__ @
\___)@@
____ @
( \@
) D (@
(____/@@
____ @
( __)@
) _) @
(____)@@
____ @
( __)@
) _) @
(__) @@
___ @
/ __)@
( (_ \@
\___/@@
_ _ @
/ )( \@
) __ (@
\_)(_/@@
__ @
( ) @
)( @
(__) @@
__ @
_( )@
/ \) \@
\____/@@
__ _ @
( / )@
) ( @
(__\_)@@
__ @
( ) @
/ (_/\@
\____/@@
_ _ @
( \/ )@
/ \/ \@
\_)(_/@@
__ _ @
( ( \@
/ /@
\_)__)@@
__ @
/ \ @
( O )@
\__/ @@
____ @
( _ \@
) __/@
(__) @@
__ @
/ \ @
( O )@
\__\)@@
____ @
( _ \@
) /@
(__\_)@@
____ @
/ ___)@
\___ \@
(____/@@
____ @
(_ _)@
)( @
(__) @@
_ _ @
/ )( \@
) \/ (@
\____/@@
_ _ @
/ )( \@
\ \/ /@
\__/ @@
_ _ @
/ )( \@
\ /\ /@
(_/\_)@@
_ _ @
( \/ )@
) ( @
(_/\_)@@
_ _ @
( \/ )@
) / @
(__/ @@
____ @
(__ )@
/ _/ @
(____)@@
___ @
( _)@
(_ (_ @
(___)@@
_ @
( \ @
/ / @
\_) @@
___ @
(_ ) @
_) _)@
(___) @@
__ @
(_ \_ @
\__)@
@@
$ @
$ @
$ @
$ @@
$ @
$ @
$ @
$ @@
$ @
$ @
$ @
$ @@
$ @
$ @
$ @
$ @@
$ @
$ @
$ @
$ @@
$ @
$ @
$ @
$ @@
$ @
$ @
$ @
$ @@
0x0401 CYRILLIC CAPITAL LETTER IO
_--_ @
( __)@
) _) @
(____)@@
0x0410 CYRILLIC CAPITAL LETTER A
__ @
/ _\ @
/ \@
\_/\_/@@
0x0411 CYRILLIC CAPITAL LETTER BE
____ @
( __)@
) _ \@
(____/@@
0x0412 CYRILLIC CAPITAL LETTER VE
____ @
( _ \@
) _ (@
(____/@@
0x0413 CYRILLIC CAPITAL LETTER GHE
____ @
/ __)@
) ( @
\_/ @@
0x0414 CYRILLIC CAPITAL LETTER DE
____ @
/ __ \@
\_ _/@
(_)(_)@@
0x0415 CYRILLIC CAPITAL LETTER IE
____ @
( __)@
) _) @
(____)@@
0x0416 CYRILLIC CAPITAL LETTER ZHE
_ _ @
/( ( \@
) (@
\_)_)/@@
0x0417 CYRILLIC CAPITAL LETTER ZE
____ @
( __ \@
(__ (@
(____/@@
0x0418 CYRILLIC CAPITAL LETTER I
_ __ @
/ ) )@
\ \@
(__(_/@@
0x0419 CYRILLIC CAPITAL LETTER SHORT I
_ u_ @
/ ) )@
\ \@
(__(_/@@
0x041A CYRILLIC CAPITAL LETTER KA
__ _ @
( / )@
) ( @
(__\_)@@
0x041B CYRILLIC CAPITAL LETTER EL
__ @
/ \ @
/ /\ \@
\_)(_/@@
0x041C CYRILLIC CAPITAL LETTER EM
_ _ @
( \/ )@
/ \/ \@
\_)(_/@@
0x041D CYRILLIC CAPITAL LETTER EN
_ _ @
/ )( \@
) __ (@
\_)(_/@@
0x041E CYRILLIC CAPITAL LETTER O
__ @
/ \ @
( O )@
\__/ @@
0x041F CYRILLIC CAPITAL LETTER PE
____ @
/ \@
) /\ (@
\_)(_/@@
0x0420 CYRILLIC CAPITAL LETTER ER
____ @
( _ \@
) __/@
(__) @@
0x0421 CYRILLIC CAPITAL LETTER ES
___ @
/ __)@
( (__ @
\___)@@
0x0422 CYRILLIC CAPITAL LETTER TE
____ @
(_ _)@
)( @
(__) @@
0x0423 CYRILLIC CAPITAL LETTER U
_ _ @
( \/ )@
) / @
(__/ @@
0x0424 CYRILLIC CAPITAL LETTER EF
____ @
/ __ \@
\_ _/@
(__) @@
0x0425 CYRILLIC CAPITAL LETTER HA
_ _ @
( \/ )@
) ( @
(_/\_)@@
0x0426 CYRILLIC CAPITAL LETTER TSE
_ _ @
/ \( \@
) (/ (@
\___\/@@
0x0427 CYRILLIC CAPITAL LETTER CHE
__ _ @
/ (/ \@
\__ (@
(__/@@
0x0428 CYRILLIC CAPITAL LETTER SHA
_ _ @
( ) ))@
/( ( \@
\____/@@
0x0429 CYRILLIC CAPITAL LETTER SHCHA
_ _ @
( ) ))@
/( ( \@
\___\/@@
0x042A CYRILLIC CAPITAL LETTER HARD SIGN
__ @
(_ )_ @
/ _ \@
\___/@@
0x042B CYRILLIC CAPITAL LETTER YERU
_ _ @
( )( )@
/ _ \\@
\___//@@
0x042C CYRILLIC CAPITAL LETTER SOFT SIGN
__ @
( )_ @
) _ \@
(____/@@
0x042D CYRILLIC CAPITAL LETTER E
___ @
(__ \ @
(_ )@
(___/ @@
0x042E CYRILLIC CAPITAL LETTER YU
_ __ @
/ / \@
) O(@
\_\__/@@
0x042F CYRILLIC CAPITAL LETTER YA
____ @
/ _ )@
\ \@
(_/__/@@
0x0430 CYRILLIC SMALL LETTER A
__ @
/ _\ @
/ \@
\_/\_/@@
0x0431 CYRILLIC SMALL LETTER BE
____ @
( __)@
) _ \@
(____/@@
0x0432 CYRILLIC SMALL LETTER VE
____ @
( _ \@
) _ (@
(____/@@
0x0433 CYRILLIC SMALL LETTER GHE
____ @
/ __)@
) ( @
\_/ @@
0x0434 CYRILLIC SMALL LETTER DE
____ @
/ __ \@
\_ _/@
(_)(_)@@
0x0435 CYRILLIC SMALL LETTER IE
____ @
( __)@
) _) @
(____)@@
0x0436 CYRILLIC SMALL LETTER ZHE
_ _ @
/( ( \@
) (@
\_)_)/@@
0x0437 CYRILLIC SMALL LETTER ZE
____ @
( __ \@
(__ (@
(____/@@
0x0438 CYRILLIC SMALL LETTER I
_ __ @
/ ) )@
\ \@
(__(_/@@
0x0439 CYRILLIC SMALL LETTER SHORT I
_ u_ @
/ ) )@
\ \@
(__(_/@@
0x043A CYRILLIC SMALL LETTER KA
__ _ @
( / )@
) ( @
(__\_)@@
0x043B CYRILLIC SMALL LETTER EL
__ @
/ \ @
/ /\ \@
\_)(_/@@
0x043C CYRILLIC SMALL LETTER EM
_ _ @
( \/ )@
/ \/ \@
\_)(_/@@
0x043D CYRILLIC SMALL LETTER EN
_ _ @
/ )( \@
) __ (@
\_)(_/@@
0x043E CYRILLIC SMALL LETTER O
__ @
/ \ @
( O )@
\__/ @@
0x043F CYRILLIC SMALL LETTER PE
____ @
/ \@
) /\ (@
\_)(_/@@
0x0440 CYRILLIC SMALL LETTER ER
____ @
( _ \@
) __/@
(__) @@
0x0441 CYRILLIC SMALL LETTER ES
___ @
/ __)@
( (__ @
\___)@@
0x0442 CYRILLIC SMALL LETTER TE
____ @
(_ _)@
)( @
(__) @@
0x0443 CYRILLIC SMALL LETTER U
_ _ @
( \/ )@
) / @
(__/ @@
0x0444 CYRILLIC SMALL LETTER EF
____ @
/ __ \@
\_ _/@
(__) @@
0x0445 CYRILLIC SMALL LETTER HA
_ _ @
( \/ )@
) ( @
(_/\_)@@
0x0446 CYRILLIC SMALL LETTER TSE
_ _ @
/ \( \@
) (/ (@
\___\/@@
0x0447 CYRILLIC SMALL LETTER CHE
__ _ @
/ (/ \@
\__ (@
(__/@@
0x0448 CYRILLIC SMALL LETTER SHA
_ _ @
( ) ))@
/( ( \@
\____/@@
0x0449 CYRILLIC SMALL LETTER SHCHA
_ _ @
( ) ))@
/( ( \@
\___\/@@
0x044A CYRILLIC SMALL LETTER HARD SIGN
__ @
(_ )_ @
/ _ \@
\___/@@
0x044B CYRILLIC SMALL LETTER YERU
_ _ @
( )( )@
/ _ \\@
\___//@@
0x044C CYRILLIC SMALL LETTER SOFT SIGN
__ @
( )_ @
) _ \@
(____/@@
0x044D CYRILLIC SMALL LETTER E
___ @
(__ \ @
(_ )@
(___/ @@
0x044E CYRILLIC SMALL LETTER YU
_ __ @
/ / \@
) O(@
\_\__/@@
0x044F CYRILLIC SMALL LETTER YA
____ @
/ _ )@
\ \@
(_/__/@@
0x0451 CYRILLIC SMALL LETTER IO
_--_ @
( __)@
) _) @
(____)@@
@@ -0,0 +1,24 @@
var baseSortedUniq = require('./_baseSortedUniq');
/**
* This method is like `_.uniq` except that it's designed and optimized
* for sorted arrays.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @returns {Array} Returns the new duplicate free array.
* @example
*
* _.sortedUniq([1, 1, 2]);
* // => [1, 2]
*/
function sortedUniq(array) {
return (array && array.length)
? baseSortedUniq(array)
: [];
}
module.exports = sortedUniq;
@@ -0,0 +1,24 @@
# @heroui/code
Code is a component used to display inline code.
Please refer to the [documentation](https://heroui.com/docs/components/code) for more information.
## Installation
```sh
yarn add @heroui/code
# or
npm i @heroui/code
```
## Contribution
Yes please! See the
[contributing guidelines](https://github.com/frontio-ai/heroui/blob/master/CONTRIBUTING.md)
for details.
## License
This project is licensed under the terms of the
[MIT license](https://github.com/frontio-ai/heroui/blob/master/LICENSE).
@@ -0,0 +1,103 @@
{
"name": "fdir",
"version": "6.5.0",
"description": "The fastest directory crawler & globbing alternative to glob, fast-glob, & tiny-glob. Crawls 1m files in < 1s",
"main": "./dist/index.cjs",
"types": "./dist/index.d.cts",
"type": "module",
"scripts": {
"prepublishOnly": "npm run test && npm run build",
"build": "tsdown",
"format": "prettier --write src __tests__ benchmarks",
"test": "vitest run __tests__/",
"test:coverage": "vitest run --coverage __tests__/",
"test:watch": "vitest __tests__/",
"bench": "ts-node benchmarks/benchmark.js",
"bench:glob": "ts-node benchmarks/glob-benchmark.ts",
"bench:fdir": "ts-node benchmarks/fdir-benchmark.ts",
"release": "./scripts/release.sh"
},
"engines": {
"node": ">=12.0.0"
},
"repository": {
"type": "git",
"url": "git+https://github.com/thecodrr/fdir.git"
},
"keywords": [
"util",
"os",
"sys",
"fs",
"walk",
"crawler",
"directory",
"files",
"io",
"tiny-glob",
"glob",
"fast-glob",
"speed",
"javascript",
"nodejs"
],
"author": "thecodrr <thecodrr@protonmail.com>",
"license": "MIT",
"bugs": {
"url": "https://github.com/thecodrr/fdir/issues"
},
"homepage": "https://github.com/thecodrr/fdir#readme",
"devDependencies": {
"@types/glob": "^8.1.0",
"@types/mock-fs": "^4.13.4",
"@types/node": "^20.9.4",
"@types/picomatch": "^4.0.0",
"@types/tap": "^15.0.11",
"@vitest/coverage-v8": "^0.34.6",
"all-files-in-tree": "^1.1.2",
"benny": "^3.7.1",
"csv-to-markdown-table": "^1.3.1",
"expect": "^29.7.0",
"fast-glob": "^3.3.2",
"fdir1": "npm:fdir@1.2.0",
"fdir2": "npm:fdir@2.1.0",
"fdir3": "npm:fdir@3.4.2",
"fdir4": "npm:fdir@4.1.0",
"fdir5": "npm:fdir@5.0.0",
"fs-readdir-recursive": "^1.1.0",
"get-all-files": "^4.1.0",
"glob": "^10.3.10",
"klaw-sync": "^6.0.0",
"mock-fs": "^5.2.0",
"picomatch": "^4.0.2",
"prettier": "^3.5.3",
"recur-readdir": "0.0.1",
"recursive-files": "^1.0.2",
"recursive-fs": "^2.1.0",
"recursive-readdir": "^2.2.3",
"rrdir": "^12.1.0",
"systeminformation": "^5.21.17",
"tiny-glob": "^0.2.9",
"ts-node": "^10.9.1",
"tsdown": "^0.12.5",
"typescript": "^5.3.2",
"vitest": "^0.34.6",
"walk-sync": "^3.0.0"
},
"peerDependencies": {
"picomatch": "^3 || ^4"
},
"peerDependenciesMeta": {
"picomatch": {
"optional": true
}
},
"module": "./dist/index.mjs",
"exports": {
".": {
"import": "./dist/index.mjs",
"require": "./dist/index.cjs"
},
"./package.json": "./package.json"
}
}
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2021 Jesse Feng
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.
@@ -0,0 +1,373 @@
"use strict";
// These use the global symbol registry so that multiple copies of this
// library can work together in case they are not deduped.
const GENSYNC_START = Symbol.for("gensync:v1:start");
const GENSYNC_SUSPEND = Symbol.for("gensync:v1:suspend");
const GENSYNC_EXPECTED_START = "GENSYNC_EXPECTED_START";
const GENSYNC_EXPECTED_SUSPEND = "GENSYNC_EXPECTED_SUSPEND";
const GENSYNC_OPTIONS_ERROR = "GENSYNC_OPTIONS_ERROR";
const GENSYNC_RACE_NONEMPTY = "GENSYNC_RACE_NONEMPTY";
const GENSYNC_ERRBACK_NO_CALLBACK = "GENSYNC_ERRBACK_NO_CALLBACK";
module.exports = Object.assign(
function gensync(optsOrFn) {
let genFn = optsOrFn;
if (typeof optsOrFn !== "function") {
genFn = newGenerator(optsOrFn);
} else {
genFn = wrapGenerator(optsOrFn);
}
return Object.assign(genFn, makeFunctionAPI(genFn));
},
{
all: buildOperation({
name: "all",
arity: 1,
sync: function(args) {
const items = Array.from(args[0]);
return items.map(item => evaluateSync(item));
},
async: function(args, resolve, reject) {
const items = Array.from(args[0]);
if (items.length === 0) {
Promise.resolve().then(() => resolve([]));
return;
}
let count = 0;
const results = items.map(() => undefined);
items.forEach((item, i) => {
evaluateAsync(
item,
val => {
results[i] = val;
count += 1;
if (count === results.length) resolve(results);
},
reject
);
});
},
}),
race: buildOperation({
name: "race",
arity: 1,
sync: function(args) {
const items = Array.from(args[0]);
if (items.length === 0) {
throw makeError("Must race at least 1 item", GENSYNC_RACE_NONEMPTY);
}
return evaluateSync(items[0]);
},
async: function(args, resolve, reject) {
const items = Array.from(args[0]);
if (items.length === 0) {
throw makeError("Must race at least 1 item", GENSYNC_RACE_NONEMPTY);
}
for (const item of items) {
evaluateAsync(item, resolve, reject);
}
},
}),
}
);
/**
* Given a generator function, return the standard API object that executes
* the generator and calls the callbacks.
*/
function makeFunctionAPI(genFn) {
const fns = {
sync: function(...args) {
return evaluateSync(genFn.apply(this, args));
},
async: function(...args) {
return new Promise((resolve, reject) => {
evaluateAsync(genFn.apply(this, args), resolve, reject);
});
},
errback: function(...args) {
const cb = args.pop();
if (typeof cb !== "function") {
throw makeError(
"Asynchronous function called without callback",
GENSYNC_ERRBACK_NO_CALLBACK
);
}
let gen;
try {
gen = genFn.apply(this, args);
} catch (err) {
cb(err);
return;
}
evaluateAsync(gen, val => cb(undefined, val), err => cb(err));
},
};
return fns;
}
function assertTypeof(type, name, value, allowUndefined) {
if (
typeof value === type ||
(allowUndefined && typeof value === "undefined")
) {
return;
}
let msg;
if (allowUndefined) {
msg = `Expected opts.${name} to be either a ${type}, or undefined.`;
} else {
msg = `Expected opts.${name} to be a ${type}.`;
}
throw makeError(msg, GENSYNC_OPTIONS_ERROR);
}
function makeError(msg, code) {
return Object.assign(new Error(msg), { code });
}
/**
* Given an options object, return a new generator that dispatches the
* correct handler based on sync or async execution.
*/
function newGenerator({ name, arity, sync, async, errback }) {
assertTypeof("string", "name", name, true /* allowUndefined */);
assertTypeof("number", "arity", arity, true /* allowUndefined */);
assertTypeof("function", "sync", sync);
assertTypeof("function", "async", async, true /* allowUndefined */);
assertTypeof("function", "errback", errback, true /* allowUndefined */);
if (async && errback) {
throw makeError(
"Expected one of either opts.async or opts.errback, but got _both_.",
GENSYNC_OPTIONS_ERROR
);
}
if (typeof name !== "string") {
let fnName;
if (errback && errback.name && errback.name !== "errback") {
fnName = errback.name;
}
if (async && async.name && async.name !== "async") {
fnName = async.name.replace(/Async$/, "");
}
if (sync && sync.name && sync.name !== "sync") {
fnName = sync.name.replace(/Sync$/, "");
}
if (typeof fnName === "string") {
name = fnName;
}
}
if (typeof arity !== "number") {
arity = sync.length;
}
return buildOperation({
name,
arity,
sync: function(args) {
return sync.apply(this, args);
},
async: function(args, resolve, reject) {
if (async) {
async.apply(this, args).then(resolve, reject);
} else if (errback) {
errback.call(this, ...args, (err, value) => {
if (err == null) resolve(value);
else reject(err);
});
} else {
resolve(sync.apply(this, args));
}
},
});
}
function wrapGenerator(genFn) {
return setFunctionMetadata(genFn.name, genFn.length, function(...args) {
return genFn.apply(this, args);
});
}
function buildOperation({ name, arity, sync, async }) {
return setFunctionMetadata(name, arity, function*(...args) {
const resume = yield GENSYNC_START;
if (!resume) {
// Break the tail call to avoid a bug in V8 v6.X with --harmony enabled.
const res = sync.call(this, args);
return res;
}
let result;
try {
async.call(
this,
args,
value => {
if (result) return;
result = { value };
resume();
},
err => {
if (result) return;
result = { err };
resume();
}
);
} catch (err) {
result = { err };
resume();
}
// Suspend until the callbacks run. Will resume synchronously if the
// callback was already called.
yield GENSYNC_SUSPEND;
if (result.hasOwnProperty("err")) {
throw result.err;
}
return result.value;
});
}
function evaluateSync(gen) {
let value;
while (!({ value } = gen.next()).done) {
assertStart(value, gen);
}
return value;
}
function evaluateAsync(gen, resolve, reject) {
(function step() {
try {
let value;
while (!({ value } = gen.next()).done) {
assertStart(value, gen);
// If this throws, it is considered to have broken the contract
// established for async handlers. If these handlers are called
// synchronously, it is also considered bad behavior.
let sync = true;
let didSyncResume = false;
const out = gen.next(() => {
if (sync) {
didSyncResume = true;
} else {
step();
}
});
sync = false;
assertSuspend(out, gen);
if (!didSyncResume) {
// Callback wasn't called synchronously, so break out of the loop
// and let it call 'step' later.
return;
}
}
return resolve(value);
} catch (err) {
return reject(err);
}
})();
}
function assertStart(value, gen) {
if (value === GENSYNC_START) return;
throwError(
gen,
makeError(
`Got unexpected yielded value in gensync generator: ${JSON.stringify(
value
)}. Did you perhaps mean to use 'yield*' instead of 'yield'?`,
GENSYNC_EXPECTED_START
)
);
}
function assertSuspend({ value, done }, gen) {
if (!done && value === GENSYNC_SUSPEND) return;
throwError(
gen,
makeError(
done
? "Unexpected generator completion. If you get this, it is probably a gensync bug."
: `Expected GENSYNC_SUSPEND, got ${JSON.stringify(
value
)}. If you get this, it is probably a gensync bug.`,
GENSYNC_EXPECTED_SUSPEND
)
);
}
function throwError(gen, err) {
// Call `.throw` so that users can step in a debugger to easily see which
// 'yield' passed an unexpected value. If the `.throw` call didn't throw
// back to the generator, we explicitly do it to stop the error
// from being swallowed by user code try/catches.
if (gen.throw) gen.throw(err);
throw err;
}
function isIterable(value) {
return (
!!value &&
(typeof value === "object" || typeof value === "function") &&
!value[Symbol.iterator]
);
}
function setFunctionMetadata(name, arity, fn) {
if (typeof name === "string") {
// This should always work on the supported Node versions, but for the
// sake of users that are compiling to older versions, we check for
// configurability so we don't throw.
const nameDesc = Object.getOwnPropertyDescriptor(fn, "name");
if (!nameDesc || nameDesc.configurable) {
Object.defineProperty(
fn,
"name",
Object.assign(nameDesc || {}, {
configurable: true,
value: name,
})
);
}
}
if (typeof arity === "number") {
const lengthDesc = Object.getOwnPropertyDescriptor(fn, "length");
if (!lengthDesc || lengthDesc.configurable) {
Object.defineProperty(
fn,
"length",
Object.assign(lengthDesc || {}, {
configurable: true,
value: arity,
})
);
}
}
return fn;
}
@@ -0,0 +1,663 @@
import { noop } from '@internal/listenerMiddleware/utils'
import { isNestedFrozen } from '@internal/serializableStateInvariantMiddleware'
import type { Reducer } from '@reduxjs/toolkit'
import {
configureStore,
createNextState,
createSerializableStateInvariantMiddleware,
findNonSerializableValue,
isPlain,
Tuple,
} from '@reduxjs/toolkit'
// Mocking console
const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(noop)
const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(noop)
afterEach(() => {
vi.clearAllMocks()
})
afterAll(() => {
vi.restoreAllMocks()
})
describe('findNonSerializableValue', () => {
it('Should return false if no matching values are found', () => {
const obj = {
a: 42,
b: {
b1: 'test',
},
c: [99, { d: 123 }],
}
const result = findNonSerializableValue(obj)
expect(result).toBe(false)
})
it('Should return a keypath and the value if it finds a non-serializable value', () => {
function testFunction() {}
const obj = {
a: 42,
b: {
b1: testFunction,
},
c: [99, { d: 123 }],
}
const result = findNonSerializableValue(obj)
expect(result).toEqual({ keyPath: 'b.b1', value: testFunction })
})
it('Should return the first non-serializable value it finds', () => {
const map = new Map()
const symbol = Symbol.for('testSymbol')
const obj = {
a: 42,
b: {
b1: 1,
},
c: [99, { d: 123 }, map, symbol, 'test'],
d: symbol,
}
const result = findNonSerializableValue(obj)
expect(result).toEqual({ keyPath: 'c.2', value: map })
})
it('Should return a specific value if the root object is non-serializable', () => {
const value = new Map()
const result = findNonSerializableValue(value)
expect(result).toEqual({ keyPath: '<root>', value })
})
it('Should accept null as a valid value', () => {
const obj = {
a: 42,
b: {
b1: 1,
},
c: null,
}
const result = findNonSerializableValue(obj)
expect(result).toEqual(false)
})
})
describe('serializableStateInvariantMiddleware', () => {
it('Should log an error when a non-serializable action is dispatched', () => {
const reducer: Reducer = (state = 0, _action) => state + 1
const serializableStateInvariantMiddleware =
createSerializableStateInvariantMiddleware()
const store = configureStore({
reducer,
middleware: () => new Tuple(serializableStateInvariantMiddleware),
})
const symbol = Symbol.for('SOME_CONSTANT')
const dispatchedAction = { type: 'an-action', payload: symbol }
store.dispatch(dispatchedAction)
expect(consoleErrorSpy).toHaveBeenCalledOnce()
expect(consoleErrorSpy).toHaveBeenLastCalledWith(
`A non-serializable value was detected in an action, in the path: \`payload\`. Value:`,
symbol,
`\nTake a look at the logic that dispatched this action: `,
dispatchedAction,
`\n(See https://redux.js.org/faq/actions#why-should-type-be-a-string-or-at-least-serializable-why-should-my-action-types-be-constants)`,
`\n(To allow non-serializable values see: https://redux-toolkit.js.org/usage/usage-guide#working-with-non-serializable-data)`,
)
})
it('Should log an error when a non-serializable value is in state', () => {
const ACTION_TYPE = 'TEST_ACTION'
const initialState = {
a: 0,
}
const badValue = new Map()
const reducer: Reducer = (state = initialState, action) => {
switch (action.type) {
case ACTION_TYPE: {
return {
a: badValue,
}
}
default:
return state
}
}
const serializableStateInvariantMiddleware =
createSerializableStateInvariantMiddleware()
const store = configureStore({
reducer: {
testSlice: reducer,
},
middleware: () => new Tuple(serializableStateInvariantMiddleware),
})
store.dispatch({ type: ACTION_TYPE })
expect(consoleErrorSpy).toHaveBeenCalledOnce()
expect(consoleErrorSpy).toHaveBeenLastCalledWith(
`A non-serializable value was detected in the state, in the path: \`testSlice.a\`. Value:`,
badValue,
`\nTake a look at the reducer(s) handling this action type: TEST_ACTION.
(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)`,
)
})
describe('consumer tolerated structures', () => {
const nonSerializableValue = new Map()
const nestedSerializableObjectWithBadValue = {
isSerializable: true,
entries: (): [string, any][] => [
['good-string', 'Good!'],
['good-number', 1337],
['bad-map-instance', nonSerializableValue],
],
}
const serializableObject = {
isSerializable: true,
entries: (): [string, any][] => [
['first', 1],
['second', 'B!'],
['third', nestedSerializableObjectWithBadValue],
],
}
it('Should log an error when a non-serializable value is nested in state', () => {
const ACTION_TYPE = 'TEST_ACTION'
const initialState = {
a: 0,
}
const reducer: Reducer = (state = initialState, action) => {
switch (action.type) {
case ACTION_TYPE: {
return {
a: serializableObject,
}
}
default:
return state
}
}
// use default options
const serializableStateInvariantMiddleware =
createSerializableStateInvariantMiddleware()
const store = configureStore({
reducer: {
testSlice: reducer,
},
middleware: () => new Tuple(serializableStateInvariantMiddleware),
})
store.dispatch({ type: ACTION_TYPE })
expect(consoleErrorSpy).toHaveBeenCalledOnce()
// since default options are used, the `entries` function in `serializableObject` will cause the error
expect(consoleErrorSpy).toHaveBeenLastCalledWith(
`A non-serializable value was detected in the state, in the path: \`testSlice.a.entries\`. Value:`,
serializableObject.entries,
`\nTake a look at the reducer(s) handling this action type: TEST_ACTION.
(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)`,
)
})
it('Should use consumer supplied isSerializable and getEntries options to tolerate certain structures', () => {
const ACTION_TYPE = 'TEST_ACTION'
const initialState = {
a: 0,
}
const isSerializable = (val: any): boolean =>
val.isSerializable || isPlain(val)
const getEntries = (val: any): [string, any][] =>
val.isSerializable ? val.entries() : Object.entries(val)
const reducer: Reducer = (state = initialState, action) => {
switch (action.type) {
case ACTION_TYPE: {
return {
a: serializableObject,
}
}
default:
return state
}
}
const serializableStateInvariantMiddleware =
createSerializableStateInvariantMiddleware({
isSerializable,
getEntries,
})
const store = configureStore({
reducer: {
testSlice: reducer,
},
middleware: () => new Tuple(serializableStateInvariantMiddleware),
})
store.dispatch({ type: ACTION_TYPE })
expect(consoleErrorSpy).toHaveBeenCalledOnce()
// error reported is from a nested class instance, rather than the `entries` function `serializableObject`
expect(consoleErrorSpy).toHaveBeenLastCalledWith(
`A non-serializable value was detected in the state, in the path: \`testSlice.a.third.bad-map-instance\`. Value:`,
nonSerializableValue,
`\nTake a look at the reducer(s) handling this action type: TEST_ACTION.
(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)`,
)
})
})
it('Should use the supplied isSerializable function to determine serializability', () => {
const ACTION_TYPE = 'TEST_ACTION'
const initialState = {
a: 0,
}
const badValue = new Map()
const reducer: Reducer = (state = initialState, action) => {
switch (action.type) {
case ACTION_TYPE: {
return {
a: badValue,
}
}
default:
return state
}
}
const serializableStateInvariantMiddleware =
createSerializableStateInvariantMiddleware({
isSerializable: () => true,
})
const store = configureStore({
reducer: {
testSlice: reducer,
},
middleware: () => new Tuple(serializableStateInvariantMiddleware),
})
store.dispatch({ type: ACTION_TYPE })
// Supplied 'isSerializable' considers all values serializable, hence
// no error logging is expected:
expect(consoleErrorSpy).not.toHaveBeenCalled()
})
it('should not check serializability for ignored action types', () => {
let numTimesCalled = 0
const serializableStateMiddleware =
createSerializableStateInvariantMiddleware({
isSerializable: () => {
numTimesCalled++
return true
},
ignoredActions: ['IGNORE_ME'],
})
const store = configureStore({
reducer: () => ({}),
middleware: () => new Tuple(serializableStateMiddleware),
})
expect(numTimesCalled).toBe(0)
store.dispatch({ type: 'IGNORE_ME' })
// The state check only calls `isSerializable` once
expect(numTimesCalled).toBe(1)
store.dispatch({ type: 'ANY_OTHER_ACTION' })
// Action checks call `isSerializable` 2+ times when enabled
expect(numTimesCalled).toBeGreaterThanOrEqual(3)
})
describe('ignored action paths', () => {
function reducer() {
return 0
}
const nonSerializableValue = new Map()
it('default value: meta.arg', () => {
configureStore({
reducer,
middleware: () =>
new Tuple(createSerializableStateInvariantMiddleware()),
}).dispatch({ type: 'test', meta: { arg: nonSerializableValue } })
expect(consoleErrorSpy).not.toHaveBeenCalled()
})
it('default value can be overridden', () => {
configureStore({
reducer,
middleware: () =>
new Tuple(
createSerializableStateInvariantMiddleware({
ignoredActionPaths: [],
}),
),
}).dispatch({ type: 'test', meta: { arg: nonSerializableValue } })
expect(consoleErrorSpy).toHaveBeenCalledOnce()
expect(consoleErrorSpy).toHaveBeenLastCalledWith(
`A non-serializable value was detected in an action, in the path: \`meta.arg\`. Value:`,
nonSerializableValue,
`\nTake a look at the logic that dispatched this action: `,
{ type: 'test', meta: { arg: nonSerializableValue } },
`\n(See https://redux.js.org/faq/actions#why-should-type-be-a-string-or-at-least-serializable-why-should-my-action-types-be-constants)`,
`\n(To allow non-serializable values see: https://redux-toolkit.js.org/usage/usage-guide#working-with-non-serializable-data)`,
)
})
it('can specify (multiple) different values', () => {
configureStore({
reducer,
middleware: () =>
new Tuple(
createSerializableStateInvariantMiddleware({
ignoredActionPaths: ['payload', 'meta.arg'],
}),
),
}).dispatch({
type: 'test',
payload: { arg: nonSerializableValue },
meta: { arg: nonSerializableValue },
})
expect(consoleErrorSpy).not.toHaveBeenCalled()
})
it('can specify regexp', () => {
configureStore({
reducer,
middleware: () =>
new Tuple(
createSerializableStateInvariantMiddleware({
ignoredActionPaths: [/^payload\..*$/],
}),
),
}).dispatch({
type: 'test',
payload: { arg: nonSerializableValue },
})
expect(consoleErrorSpy).not.toHaveBeenCalled()
})
})
it('allows ignoring actions entirely', () => {
let numTimesCalled = 0
const serializableStateMiddleware =
createSerializableStateInvariantMiddleware({
isSerializable: () => {
numTimesCalled++
return true
},
ignoreActions: true,
})
const store = configureStore({
reducer: () => ({}),
middleware: () => new Tuple(serializableStateMiddleware),
})
expect(numTimesCalled).toBe(0)
store.dispatch({ type: 'THIS_DOESNT_MATTER' })
// `isSerializable` is called once for a state check
expect(numTimesCalled).toBe(1)
store.dispatch({ type: 'THIS_DOESNT_MATTER_AGAIN' })
expect(numTimesCalled).toBe(2)
})
it('should not check serializability for ignored slice names', () => {
const ACTION_TYPE = 'TEST_ACTION'
const initialState = {
a: 0,
}
const badValue = new Map()
const reducer: Reducer = (state = initialState, action) => {
switch (action.type) {
case ACTION_TYPE: {
return {
a: badValue,
b: {
c: badValue,
d: badValue,
},
e: { f: badValue },
g: {
h: badValue,
i: badValue,
},
}
}
default:
return state
}
}
const serializableStateInvariantMiddleware =
createSerializableStateInvariantMiddleware({
ignoredPaths: [
// Test for ignoring a single value
'testSlice.a',
// Test for ignoring a single nested value
'testSlice.b.c',
// Test for ignoring an object and its children
'testSlice.e',
// Test for ignoring based on RegExp
/^testSlice\.g\..*$/,
],
})
const store = configureStore({
reducer: {
testSlice: reducer,
},
middleware: () => new Tuple(serializableStateInvariantMiddleware),
})
store.dispatch({ type: ACTION_TYPE })
expect(consoleErrorSpy).toHaveBeenCalledOnce()
// testSlice.b.d was not covered in ignoredPaths, so will still log the error
expect(consoleErrorSpy).toHaveBeenLastCalledWith(
`A non-serializable value was detected in the state, in the path: \`testSlice.b.d\`. Value:`,
badValue,
`\nTake a look at the reducer(s) handling this action type: TEST_ACTION.
(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)`,
)
})
it('allows ignoring state entirely', () => {
const badValue = new Map()
let numTimesCalled = 0
const reducer = () => badValue
const store = configureStore({
reducer,
middleware: () =>
new Tuple(
createSerializableStateInvariantMiddleware({
isSerializable: () => {
numTimesCalled++
return true
},
ignoreState: true,
}),
),
})
expect(numTimesCalled).toBe(0)
store.dispatch({ type: 'test' })
expect(consoleErrorSpy).not.toHaveBeenCalled()
// Should be called twice for the action - there is an initial check for early returns, then a second and potentially 3rd for nested properties
expect(numTimesCalled).toBe(2)
})
it('never calls isSerializable if both ignoreState and ignoreActions are true', () => {
const badValue = new Map()
let numTimesCalled = 0
const reducer = () => badValue
const store = configureStore({
reducer,
middleware: () =>
new Tuple(
createSerializableStateInvariantMiddleware({
isSerializable: () => {
numTimesCalled++
return true
},
ignoreState: true,
ignoreActions: true,
}),
),
})
expect(numTimesCalled).toBe(0)
store.dispatch({ type: 'TEST', payload: new Date() })
store.dispatch({ type: 'OTHER_THING' })
expect(numTimesCalled).toBe(0)
})
it('Should print a warning if execution takes too long', () => {
const reducer: Reducer = (state = 42, action) => {
return state
}
const serializableStateInvariantMiddleware =
createSerializableStateInvariantMiddleware({ warnAfter: 4 })
const store = configureStore({
reducer: {
testSlice: reducer,
},
middleware: () => new Tuple(serializableStateInvariantMiddleware),
})
store.dispatch({
type: 'SOME_ACTION',
payload: new Array(10_000).fill({ value: 'more' }),
})
expect(consoleWarnSpy).toHaveBeenCalledOnce()
expect(consoleWarnSpy).toHaveBeenLastCalledWith(
expect.stringMatching(
/^SerializableStateInvariantMiddleware took \d*ms, which is more than the warning threshold of 4ms./,
),
)
})
it('Should not print a warning if "reducer" takes too long', () => {
const reducer: Reducer = (state = 42, action) => {
const started = Date.now()
while (Date.now() - started < 8) {}
return state
}
const serializableStateInvariantMiddleware =
createSerializableStateInvariantMiddleware({ warnAfter: 4 })
const store = configureStore({
reducer: {
testSlice: reducer,
},
middleware: () => new Tuple(serializableStateInvariantMiddleware),
})
store.dispatch({ type: 'SOME_ACTION' })
expect(consoleErrorSpy).not.toHaveBeenCalled()
})
it('Should cache its results', () => {
let numPlainChecks = 0
const countPlainChecks = (x: any) => {
numPlainChecks++
return isPlain(x)
}
const serializableStateInvariantMiddleware =
createSerializableStateInvariantMiddleware({
isSerializable: countPlainChecks,
})
const store = configureStore({
reducer: (state = [], action) => {
if (action.type === 'SET_STATE') return action.payload
return state
},
middleware: () => new Tuple(serializableStateInvariantMiddleware),
})
const state = createNextState([], () =>
new Array(50).fill(0).map((x, i) => ({ i })),
)
expect(isNestedFrozen(state)).toBe(true)
store.dispatch({
type: 'SET_STATE',
payload: state,
})
expect(numPlainChecks).toBeGreaterThan(state.length)
numPlainChecks = 0
store.dispatch({ type: 'NOOP' })
expect(numPlainChecks).toBeLessThan(10)
})
})
Loaded 100 of 35554 files, more files were not shown because too many files have changed in this diff. Show more