code:
// Type definitions for Web Bluetooth
// Project: https://webbluetoothcg.github.io/web-bluetooth/
// Definitions by: Uri Shaked <https://github.com/urish>
//                    Xavier Lozinguez <https://github.com/xlozinguez>
//                    Rob Moran <https://github.com/thegecko>
//                    David Bjerremose <https://github.com/DaBs>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

type BluetoothServiceUUID = number | string;
type BluetoothCharacteristicUUID = number | string;
type BluetoothDescriptorUUID = number | string;

type BluetoothManufacturerData = Map<number, DataView>;
type BluetoothServiceData = Map<BluetoothServiceUUID, DataView>;

interface BluetoothDataFilter {
    readonly dataPrefix?: BufferSource | undefined;
    readonly mask?: BufferSource | undefined;
}

interface BluetoothManufacturerDataFilter extends BluetoothDataFilter {
    companyIdentifier: number;
}

interface BluetoothServiceDataFilter extends BluetoothDataFilter {
    service: BluetoothServiceUUID;
}

interface BluetoothLEScanFilter {
    readonly name?: string | undefined;
    readonly namePrefix?: string | undefined;
    readonly services?: BluetoothServiceUUID[] | undefined;
    readonly manufacturerData?: BluetoothManufacturerDataFilter[] | undefined;
    readonly serviceData?: BluetoothServiceDataFilter[] | undefined;
}

interface BluetoothLEScanOptions {
    readonly filters?: BluetoothLEScanFilter[] | undefined;
    readonly keepRepeatedDevices?: boolean | undefined;
    readonly acceptAllAdvertisements?: boolean | undefined;
}

interface BluetoothLEScan extends BluetoothLEScanOptions {
    active: boolean;
    stop: () => void;
}

type RequestDeviceOptions = {
    filters: BluetoothLEScanFilter[];
    optionalServices?: BluetoothServiceUUID[] | undefined;
    optionalManufacturerData?: number[] | undefined;
} | {
    acceptAllDevices: boolean;
    optionalServices?: BluetoothServiceUUID[] | undefined;
    optionalManufacturerData?: number[] | undefined;
};

interface BluetoothAdvertisingEvent extends Event {
    readonly device: BluetoothDevice;
    readonly uuids: BluetoothServiceUUID[];
    readonly manufacturerData: BluetoothManufacturerData;
    readonly serviceData: BluetoothServiceData;
    readonly name?: string | undefined;
    readonly appearance?: number | undefined;
    readonly rssi?: number | undefined;
    readonly txPower?: number | undefined;
}

interface BluetoothRemoteGATTDescriptor {
    readonly characteristic: BluetoothRemoteGATTCharacteristic;
    readonly uuid: string;
    readonly value?: DataView | undefined;
    readValue(): Promise<DataView>;
    writeValue(value: BufferSource): Promise<void>;
}

interface BluetoothCharacteristicProperties {
    readonly broadcast: boolean;
    readonly read: boolean;
    readonly writeWithoutResponse: boolean;
    readonly write: boolean;
    readonly notify: boolean;
    readonly indicate: boolean;
    readonly authenticatedSignedWrites: boolean;
    readonly reliableWrite: boolean;
    readonly writableAuxiliaries: boolean;
}

interface CharacteristicEventHandlers {
    oncharacteristicvaluechanged: (this: this, ev: Event) => any;
}

interface BluetoothRemoteGATTCharacteristic extends EventTarget, CharacteristicEventHandlers {
    readonly service: BluetoothRemoteGATTService;
    readonly uuid: string;
    readonly properties: BluetoothCharacteristicProperties;
    readonly value?: DataView | undefined;
    getDescriptor(descriptor: BluetoothDescriptorUUID): Promise<BluetoothRemoteGATTDescriptor>;
    getDescriptors(descriptor?: BluetoothDescriptorUUID): Promise<BluetoothRemoteGATTDescriptor[]>;
    readValue(): Promise<DataView>;
    writeValue(value: BufferSource): Promise<void>;
    writeValueWithResponse(value: BufferSource): Promise<void>;
    writeValueWithoutResponse(value: BufferSource): Promise<void>;
    startNotifications(): Promise<BluetoothRemoteGATTCharacteristic>;
    stopNotifications(): Promise<BluetoothRemoteGATTCharacteristic>;
    addEventListener(type: "characteristicvaluechanged", listener: (this: this, ev: Event) => any, useCapture?: boolean): void;
    addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}

interface ServiceEventHandlers {
    onserviceadded: (this: this, ev: Event) => any;
    onservicechanged: (this: this, ev: Event) => any;
    onserviceremoved: (this: this, ev: Event) => any;
}

interface BluetoothRemoteGATTService extends EventTarget, CharacteristicEventHandlers, ServiceEventHandlers {
    readonly device: BluetoothDevice;
    readonly uuid: string;
    readonly isPrimary: boolean;
    getCharacteristic(characteristic: BluetoothCharacteristicUUID): Promise<BluetoothRemoteGATTCharacteristic>;
    getCharacteristics(characteristic?: BluetoothCharacteristicUUID): Promise<BluetoothRemoteGATTCharacteristic[]>;
    getIncludedService(service: BluetoothServiceUUID): Promise<BluetoothRemoteGATTService>;
    getIncludedServices(service?: BluetoothServiceUUID): Promise<BluetoothRemoteGATTService[]>;
    addEventListener(type: "serviceadded", listener: (this: this, ev: Event) => any, useCapture?: boolean): void;
    addEventListener(type: "servicechanged", listener: (this: this, ev: Event) => any, useCapture?: boolean): void;
    addEventListener(type: "serviceremoved", listener: (this: this, ev: Event) => any, useCapture?: boolean): void;
    addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}

interface BluetoothRemoteGATTServer {
    readonly device: BluetoothDevice;
    readonly connected: boolean;
    connect(): Promise<BluetoothRemoteGATTServer>;
    disconnect(): void;
    getPrimaryService(service: BluetoothServiceUUID): Promise<BluetoothRemoteGATTService>;
    getPrimaryServices(service?: BluetoothServiceUUID): Promise<BluetoothRemoteGATTService[]>;
}

interface BluetoothDeviceEventHandlers {
    onadvertisementreceived: (this: this, ev: BluetoothAdvertisingEvent) => any;
    ongattserverdisconnected: (this: this, ev: Event) => any;
}

interface WatchAdvertisementsOptions {
    signal?: AbortSignal;
}

interface BluetoothDevice extends EventTarget, BluetoothDeviceEventHandlers, CharacteristicEventHandlers, ServiceEventHandlers {
    readonly id: string;
    readonly name?: string | undefined;
    readonly gatt?: BluetoothRemoteGATTServer | undefined;
    forget(): Promise<void>;
    watchAdvertisements(options?: WatchAdvertisementsOptions): Promise<void>;
    readonly watchingAdvertisements: boolean;
    addEventListener(type: "gattserverdisconnected", listener: (this: this, ev: Event) => any, useCapture?: boolean): void;
    addEventListener(type: "advertisementreceived", listener: (this: this, ev: BluetoothAdvertisingEvent) => any, useCapture?: boolean): void;
    addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}

interface Bluetooth extends EventTarget, BluetoothDeviceEventHandlers, CharacteristicEventHandlers, ServiceEventHandlers {
    getDevices(): Promise<BluetoothDevice[]>;
    getAvailability(): Promise<boolean>;
    onavailabilitychanged: (this: this, ev: Event) => any;
    readonly referringDevice?: BluetoothDevice | undefined;
    requestDevice(options?: RequestDeviceOptions): Promise<BluetoothDevice>;
    requestLEScan(options?: BluetoothLEScanOptions): Promise<BluetoothLEScan>;
    addEventListener(type: "availabilitychanged", listener: (this: this, ev: Event) => any, useCapture?: boolean): void;
    addEventListener(type: "advertisementreceived", listener: (this: this, ev: BluetoothAdvertisingEvent) => any, useCapture?: boolean): void;
    addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}

interface Navigator {
    bluetooth: Bluetooth;
}


@types/web-bluetooth

description: TypeScript definitions for Web Bluetooth

license: MIT

Uri Shaked

githubUsername: urish

Xavier Lozinguez

githubUsername: xlozinguez

Rob Moran

githubUsername: thegecko

David Bjerremose

githubUsername: DaBs

type: git

directory: types/web-bluetooth

license: mit


code:
# Installation
> `npm install --save @types/ws`

# Summary
This package contains type definitions for ws (https://github.com/websockets/ws).

# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/ws.

### Additional Details
 * Last updated: Mon, 20 Nov 2023 23:36:24 GMT
 * Dependencies: [@types/node](https://npmjs.com/package/@types/node)

# Credits
These definitions were written by [Paul Loyd](https://github.com/loyd), [Margus Lamp](https://github.com/mlamp), [Philippe D'Alva](https://github.com/TitaneBoy), [reduckted](https://github.com/reduckted), [teidesu](https://github.com/teidesu), [Bartosz Wojtkowiak](https://github.com/wojtkowiak), [Kyle Hensel](https://github.com/k-yle), and [Samuel Skeen](https://github.com/cwadrupldijjit).


code:
export {
    AddressInfo,
    CertMeta,
    ClientOptions,
    CloseEvent,
    createWebSocketStream,
    Data,
    ErrorEvent,
    Event,
    EventListenerOptions,
    MessageEvent,
    PerMessageDeflateOptions,
    RawData,
    ServerOptions,
    VerifyClientCallbackAsync,
    VerifyClientCallbackSync,
    WebSocket,
    WebSocketServer,
} from "./index.js";
import WebSocket = require("./index.js");
export default WebSocket;


code:
/// <reference types="node" />

import { EventEmitter } from "events";
import {
    Agent,
    ClientRequest,
    ClientRequestArgs,
    IncomingMessage,
    OutgoingHttpHeaders,
    Server as HTTPServer,
} from "http";
import { Server as HTTPSServer } from "https";
import { Duplex, DuplexOptions } from "stream";
import { SecureContextOptions } from "tls";
import { URL } from "url";
import { ZlibOptions } from "zlib";

// can not get all overload of BufferConstructor['from'], need to copy all it's first arguments here
// https://github.com/microsoft/TypeScript/issues/32164
type BufferLike =
    | string
    | Buffer
    | DataView
    | number
    | ArrayBufferView
    | Uint8Array
    | ArrayBuffer
    | SharedArrayBuffer
    | readonly any[]
    | readonly number[]
    | { valueOf(): ArrayBuffer }
    | { valueOf(): SharedArrayBuffer }
    | { valueOf(): Uint8Array }
    | { valueOf(): readonly number[] }
    | { valueOf(): string }
    | { [Symbol.toPrimitive](hint: string): string };

// WebSocket socket.
declare class WebSocket extends EventEmitter {
    /** The connection is not yet open. */
    static readonly CONNECTING: 0;
    /** The connection is open and ready to communicate. */
    static readonly OPEN: 1;
    /** The connection is in the process of closing. */
    static readonly CLOSING: 2;
    /** The connection is closed. */
    static readonly CLOSED: 3;

    binaryType: "nodebuffer" | "arraybuffer" | "fragments";
    readonly bufferedAmount: number;
    readonly extensions: string;
    /** Indicates whether the websocket is paused */
    readonly isPaused: boolean;
    readonly protocol: string;
    /** The current state of the connection */
    readonly readyState:
        | typeof WebSocket.CONNECTING
        | typeof WebSocket.OPEN
        | typeof WebSocket.CLOSING
        | typeof WebSocket.CLOSED;
    readonly url: string;

    /** The connection is not yet open. */
    readonly CONNECTING: 0;
    /** The connection is open and ready to communicate. */
    readonly OPEN: 1;
    /** The connection is in the process of closing. */
    readonly CLOSING: 2;
    /** The connection is closed. */
    readonly CLOSED: 3;

    onopen: ((event: WebSocket.Event) => void) | null;
    onerror: ((event: WebSocket.ErrorEvent) => void) | null;
    onclose: ((event: WebSocket.CloseEvent) => void) | null;
    onmessage: ((event: WebSocket.MessageEvent) => void) | null;

    constructor(address: null);
    constructor(address: string | URL, options?: WebSocket.ClientOptions | ClientRequestArgs);
    constructor(
        address: string | URL,
        protocols?: string | string[],
        options?: WebSocket.ClientOptions | ClientRequestArgs,
    );

    close(code?: number, data?: string | Buffer): void;
    ping(data?: any, mask?: boolean, cb?: (err: Error) => void): void;
    pong(data?: any, mask?: boolean, cb?: (err: Error) => void): void;
    // https://github.com/websockets/ws/issues/2076#issuecomment-1250354722
    send(data: BufferLike, cb?: (err?: Error) => void): void;
    send(
        data: BufferLike,
        options: {
            mask?: boolean | undefined;
            binary?: boolean | undefined;
            compress?: boolean | undefined;
            fin?: boolean | undefined;
        },
        cb?: (err?: Error) => void,
    ): void;
    terminate(): void;

    /**
     * Pause the websocket causing it to stop emitting events. Some events can still be
     * emitted after this is called, until all buffered data is consumed. This method
     * is a noop if the ready state is `CONNECTING` or `CLOSED`.
     */
    pause(): void;
    /**
     * Make a paused socket resume emitting events. This method is a noop if the ready
     * state is `CONNECTING` or `CLOSED`.
     */
    resume(): void;

    // HTML5 WebSocket events
    addEventListener(
        method: "message",
        cb: (event: WebSocket.MessageEvent) => void,
        options?: WebSocket.EventListenerOptions,
    ): void;
    addEventListener(
        method: "close",
        cb: (event: WebSocket.CloseEvent) => void,
        options?: WebSocket.EventListenerOptions,
    ): void;
    addEventListener(
        method: "error",
        cb: (event: WebSocket.ErrorEvent) => void,
        options?: WebSocket.EventListenerOptions,
    ): void;
    addEventListener(
        method: "open",
        cb: (event: WebSocket.Event) => void,
        options?: WebSocket.EventListenerOptions,
    ): void;

    removeEventListener(method: "message", cb: (event: WebSocket.MessageEvent) => void): void;
    removeEventListener(method: "close", cb: (event: WebSocket.CloseEvent) => void): void;
    removeEventListener(method: "error", cb: (event: WebSocket.ErrorEvent) => void): void;
    removeEventListener(method: "open", cb: (event: WebSocket.Event) => void): void;

    // Events
    on(event: "close", listener: (this: WebSocket, code: number, reason: Buffer) => void): this;
    on(event: "error", listener: (this: WebSocket, err: Error) => void): this;
    on(event: "upgrade", listener: (this: WebSocket, request: IncomingMessage) => void): this;
    on(event: "message", listener: (this: WebSocket, data: WebSocket.RawData, isBinary: boolean) => void): this;
    on(event: "open", listener: (this: WebSocket) => void): this;
    on(event: "ping" | "pong", listener: (this: WebSocket, data: Buffer) => void): this;
    on(
        event: "unexpected-response",
        listener: (this: WebSocket, request: ClientRequest, response: IncomingMessage) => void,
    ): this;
    on(event: string | symbol, listener: (this: WebSocket, ...args: any[]) => void): this;

    once(event: "close", listener: (this: WebSocket, code: number, reason: Buffer) => void): this;
    once(event: "error", listener: (this: WebSocket, err: Error) => void): this;
    once(event: "upgrade", listener: (this: WebSocket, request: IncomingMessage) => void): this;
    once(event: "message", listener: (this: WebSocket, data: WebSocket.RawData, isBinary: boolean) => void): this;
    once(event: "open", listener: (this: WebSocket) => void): this;
    once(event: "ping" | "pong", listener: (this: WebSocket, data: Buffer) => void): this;
    once(
        event: "unexpected-response",
        listener: (this: WebSocket, request: ClientRequest, response: IncomingMessage) => void,
    ): this;
    once(event: string | symbol, listener: (this: WebSocket, ...args: any[]) => void): this;

    off(event: "close", listener: (this: WebSocket, code: number, reason: Buffer) => void): this;
    off(event: "error", listener: (this: WebSocket, err: Error) => void): this;
    off(event: "upgrade", listener: (this: WebSocket, request: IncomingMessage) => void): this;
    off(event: "message", listener: (this: WebSocket, data: WebSocket.RawData, isBinary: boolean) => void): this;
    off(event: "open", listener: (this: WebSocket) => void): this;
    off(event: "ping" | "pong", listener: (this: WebSocket, data: Buffer) => void): this;
    off(
        event: "unexpected-response",
        listener: (this: WebSocket, request: ClientRequest, response: IncomingMessage) => void,
    ): this;
    off(event: string | symbol, listener: (this: WebSocket, ...args: any[]) => void): this;

    addListener(event: "close", listener: (code: number, reason: Buffer) => void): this;
    addListener(event: "error", listener: (err: Error) => void): this;
    addListener(event: "upgrade", listener: (request: IncomingMessage) => void): this;
    addListener(event: "message", listener: (data: WebSocket.RawData, isBinary: boolean) => void): this;
    addListener(event: "open", listener: () => void): this;
    addListener(event: "ping" | "pong", listener: (data: Buffer) => void): this;
    addListener(
        event: "unexpected-response",
        listener: (request: ClientRequest, response: IncomingMessage) => void,
    ): this;
    addListener(event: string | symbol, listener: (...args: any[]) => void): this;

    removeListener(event: "close", listener: (code: number, reason: Buffer) => void): this;
    removeListener(event: "error", listener: (err: Error) => void): this;
    removeListener(event: "upgrade", listener: (request: IncomingMessage) => void): this;
    removeListener(event: "message", listener: (data: WebSocket.RawData, isBinary: boolean) => void): this;
    removeListener(event: "open", listener: () => void): this;
    removeListener(event: "ping" | "pong", listener: (data: Buffer) => void): this;
    removeListener(
        event: "unexpected-response",
        listener: (request: ClientRequest, response: IncomingMessage) => void,
    ): this;
    removeListener(event: string | symbol, listener: (...args: any[]) => void): this;
}

declare const WebSocketAlias: typeof WebSocket;
interface WebSocketAlias extends WebSocket {} // eslint-disable-line @typescript-eslint/no-empty-interface

declare namespace WebSocket {
    /**
     * Data represents the raw message payload received over the WebSocket.
     */
    type RawData = Buffer | ArrayBuffer | Buffer[];

    /**
     * Data represents the message payload received over the WebSocket.
     */
    type Data = string | Buffer | ArrayBuffer | Buffer[];

    /**
     * CertMeta represents the accepted types for certificate & key data.
     */
    type CertMeta = string | string[] | Buffer | Buffer[];

    /**
     * VerifyClientCallbackSync is a synchronous callback used to inspect the
     * incoming message. The return value (boolean) of the function determines
     * whether or not to accept the handshake.
     */
    type VerifyClientCallbackSync<Request extends IncomingMessage = IncomingMessage> = (info: {
        origin: string;
        secure: boolean;
        req: Request;
    }) => boolean;

    /**
     * VerifyClientCallbackAsync is an asynchronous callback used to inspect the
     * incoming message. The return value (boolean) of the function determines
     * whether or not to accept the handshake.
     */
    type VerifyClientCallbackAsync<Request extends IncomingMessage = IncomingMessage> = (
        info: { origin: string; secure: boolean; req: Request },
        callback: (res: boolean, code?: number, message?: string, headers?: OutgoingHttpHeaders) => void,
    ) => void;

    interface ClientOptions extends SecureContextOptions {
        protocol?: string | undefined;
        followRedirects?: boolean | undefined;
        generateMask?(mask: Buffer): void;
        handshakeTimeout?: number | undefined;
        maxRedirects?: number | undefined;
        perMessageDeflate?: boolean | PerMessageDeflateOptions | undefined;
        localAddress?: string | undefined;
        protocolVersion?: number | undefined;
        headers?: { [key: string]: string } | undefined;
        origin?: string | undefined;
        agent?: Agent | undefined;
        host?: string | undefined;
        family?: number | undefined;
        checkServerIdentity?(servername: string, cert: CertMeta): boolean;
        rejectUnauthorized?: boolean | undefined;
        maxPayload?: number | undefined;
        skipUTF8Validation?: boolean | undefined;
    }

    interface PerMessageDeflateOptions {
        serverNoContextTakeover?: boolean | undefined;
        clientNoContextTakeover?: boolean | undefined;
        serverMaxWindowBits?: number | undefined;
        clientMaxWindowBits?: number | undefined;
        zlibDeflateOptions?: {
            flush?: number | undefined;
            finishFlush?: number | undefined;
            chunkSize?: number | undefined;
            windowBits?: number | undefined;
            level?: number | undefined;
            memLevel?: number | undefined;
            strategy?: number | undefined;
            dictionary?: Buffer | Buffer[] | DataView | undefined;
            info?: boolean | undefined;
        } | undefined;
        zlibInflateOptions?: ZlibOptions | undefined;
        threshold?: number | undefined;
        concurrencyLimit?: number | undefined;
    }

    interface Event {
        type: string;
        target: WebSocket;
    }

    interface ErrorEvent {
        error: any;
        message: string;
        type: string;
        target: WebSocket;
    }

    interface CloseEvent {
        wasClean: boolean;
        code: number;
        reason: string;
        type: string;
        target: WebSocket;
    }

    interface MessageEvent {
        data: Data;
        type: string;
        target: WebSocket;
    }

    interface EventListenerOptions {
        once?: boolean | undefined;
    }

    interface ServerOptions<
        U extends typeof WebSocket.WebSocket = typeof WebSocket.WebSocket,
        V extends typeof IncomingMessage = typeof IncomingMessage,
    > {
        host?: string | undefined;
        port?: number | undefined;
        backlog?: number | undefined;
        server?: HTTPServer<V> | HTTPSServer<V> | undefined;
        verifyClient?:
            | VerifyClientCallbackAsync<InstanceType<V>>
            | VerifyClientCallbackSync<InstanceType<V>>
            | undefined;
        handleProtocols?: (protocols: Set<string>, request: InstanceType<V>) => string | false;
        path?: string | undefined;
        noServer?: boolean | undefined;
        clientTracking?: boolean | undefined;
        perMessageDeflate?: boolean | PerMessageDeflateOptions | undefined;
        maxPayload?: number | undefined;
        skipUTF8Validation?: boolean | undefined;
        WebSocket?: U | undefined;
    }

    interface AddressInfo {
        address: string;
        family: string;
        port: number;
    }

    // WebSocket Server
    class Server<
        T extends typeof WebSocket.WebSocket = typeof WebSocket.WebSocket,
        U extends typeof IncomingMessage = typeof IncomingMessage,
    > extends EventEmitter {
        options: ServerOptions<T, U>;
        path: string;
        clients: Set<InstanceType<T>>;

        constructor(options?: ServerOptions<T, U>, callback?: () => void);

        address(): AddressInfo | string;
        close(cb?: (err?: Error) => void): void;
        handleUpgrade(
            request: InstanceType<U>,
            socket: Duplex,
            upgradeHead: Buffer,
            callback: (client: InstanceType<T>, request: InstanceType<U>) => void,
        ): void;
        shouldHandle(request: InstanceType<U>): boolean | Promise<boolean>;

        // Events
        on(event: "connection", cb: (this: Server<T>, socket: InstanceType<T>, request: InstanceType<U>) => void): this;
        on(event: "error", cb: (this: Server<T>, error: Error) => void): this;
        on(event: "headers", cb: (this: Server<T>, headers: string[], request: InstanceType<U>) => void): this;
        on(event: "close" | "listening", cb: (this: Server<T>) => void): this;
        on(event: string | symbol, listener: (this: Server<T>, ...args: any[]) => void): this;

        once(
            event: "connection",
            cb: (this: Server<T>, socket: InstanceType<T>, request: InstanceType<U>) => void,
        ): this;
        once(event: "error", cb: (this: Server<T>, error: Error) => void): this;
        once(event: "headers", cb: (this: Server<T>, headers: string[], request: InstanceType<U>) => void): this;
        once(event: "close" | "listening", cb: (this: Server<T>) => void): this;
        once(event: string | symbol, listener: (this: Server<T>, ...args: any[]) => void): this;

        off(
            event: "connection",
            cb: (this: Server<T>, socket: InstanceType<T>, request: InstanceType<U>) => void,
        ): this;
        off(event: "error", cb: (this: Server<T>, error: Error) => void): this;
        off(event: "headers", cb: (this: Server<T>, headers: string[], request: InstanceType<U>) => void): this;
        off(event: "close" | "listening", cb: (this: Server<T>) => void): this;
        off(event: string | symbol, listener: (this: Server<T>, ...args: any[]) => void): this;

        addListener(event: "connection", cb: (client: InstanceType<T>, request: InstanceType<U>) => void): this;
        addListener(event: "error", cb: (err: Error) => void): this;
        addListener(event: "headers", cb: (headers: string[], request: InstanceType<U>) => void): this;
        addListener(event: "close" | "listening", cb: () => void): this;
        addListener(event: string | symbol, listener: (...args: any[]) => void): this;

        removeListener(event: "connection", cb: (client: InstanceType<T>, request: InstanceType<U>) => void): this;
        removeListener(event: "error", cb: (err: Error) => void): this;
        removeListener(event: "headers", cb: (headers: string[], request: InstanceType<U>) => void): this;
        removeListener(event: "close" | "listening", cb: () => void): this;
        removeListener(event: string | symbol, listener: (...args: any[]) => void): this;
    }

    const WebSocketServer: typeof Server;
    interface WebSocketServer extends Server {} // eslint-disable-line @typescript-eslint/no-empty-interface
    const WebSocket: typeof WebSocketAlias;
    interface WebSocket extends WebSocketAlias {} // eslint-disable-line @typescript-eslint/no-empty-interface

    // WebSocket stream
    function createWebSocketStream(websocket: WebSocket, options?: DuplexOptions): Duplex;
}

export = WebSocket;


@types/ws

description: TypeScript definitions for ws

Paul Loyd

githubUsername: loyd

Margus Lamp

githubUsername: mlamp

Philippe D'Alva

githubUsername: TitaneBoy

reduckted

githubUsername: reduckted

teidesu

githubUsername: teidesu

Bartosz Wojtkowiak

githubUsername: wojtkowiak

Kyle Hensel

githubUsername: k-yle

Samuel Skeen

githubUsername: cwadrupldijjit

directory: types/ws


code:
# This workflow will do a clean install of node dependencies, cache/restore them, build the source code and run tests across different versions of node
# For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions

name: build

on: [push, pull_request]

jobs:
  build:

    runs-on: ubuntu-latest

    strategy:
      matrix:
        node-version: [16]

    steps:
    - uses: actions/checkout@v2
    - name: Use Node.js ${{ matrix.node-version }}
      uses: actions/setup-node@v2
      with:
        node-version: ${{ matrix.node-version }}
        cache: 'npm'
    - run: npm ci
    - run: npm run build --if-present
    - run: npm test
    - run: npm run coverage --if-present
    - name: Coveralls
      uses: coverallsapp/github-action@master
      with:
        github-token: ${{ secrets.GITHUB_TOKEN }}


code:
# structuredClone polyfill

[![Downloads](https://img.shields.io/npm/dm/@ungap/structured-clone.svg)](https://www.npmjs.com/package/@ungap/structured-clone) [![build status](https://github.com/ungap/structured-clone/actions/workflows/node.js.yml/badge.svg)](https://github.com/ungap/structured-clone/actions) [![Coverage Status](https://coveralls.io/repos/github/ungap/structured-clone/badge.svg?branch=main)](https://coveralls.io/github/ungap/structured-clone?branch=main)

An env agnostic serializer and deserializer with recursion ability and types beyond *JSON* from the *HTML* standard itself.

  * [Supported Types](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm#supported_types)
    * *not supported yet*: Blob, File, FileList, ImageBitmap, ImageData, and ArrayBuffer, but typed arrays are supported without major issues, but u/int8, u/int16, and u/int32 are the only safely suppored (right now).
    * *not possible to implement*: the `{transfer: []}` option can be passed but it's completely ignored.
  * [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/structuredClone)
  * [Serializer](https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal)
  * [Deserializer](https://html.spec.whatwg.org/multipage/structured-data.html#structureddeserialize)

Serialized values can be safely stringified as *JSON* too, and deserialization resurrect all values, even recursive, or more complex than what *JSON* allows.

### Examples

Check the [100% test coverage](./test/index.js) to know even more.

```js
// as default export
import structuredClone from '@ungap/structured-clone';
const cloned = structuredClone({any: 'serializable'});

// as independent serializer/deserializer
import {serialize, deserialize} from '@ungap/structured-clone';

// the result can be stringified as JSON without issues
// even if there is recursive data, bigint values,
// typed arrays, and so on
const serialized = serialize({any: 'serializable'});

// the result will be a replica of the original object
const deserialized = deserialize(serialized);
```

#### Global Polyfill
Note: Only monkey patch the global if needed. This polyfill works just fine as an explicit import: `import structuredClone from "@ungap/structured-clone"`
```js
// Attach the polyfill as a Global function
import structuredClone from "@ungap/structured-clone";
if (!("structuredClone" in globalThis)) {
  globalThis.structuredClone = structuredClone;
}

// Or don't monkey patch
import structuredClone from "@ungap/structured-clone"
// Just use it in the file
structuredClone()
```

**Note**: Do not attach this module's default export directly to the global scope, whithout a conditional guard to detect a native implementation. In environments where there is a native global implementation of `structuredClone()` already, assignment to the global object will result in an infinite loop when `globalThis.structuredClone()` is called. See the example above for a safe way to provide the polyfill globally in your project.

### Extra Features

There is no middle-ground between the structured clone algorithm and JSON:

  * JSON is more relaxed about incompatible values: it just ignores these
  * Structured clone is inflexible regarding incompatible values, yet it makes specialized instances impossible to reconstruct, plus it doesn't offer any helper, such as `toJSON()`, to make serialization possible, or better, with specific cases

This module specialized `serialize` export offers, within the optional extra argument, a **lossy** property to avoid throwing when incompatible types are found down the road (function, symbol, ...), so that it is possible to send with less worrying about thrown errors.

```js
// as default export
import structuredClone from '@ungap/structured-clone';
const cloned = structuredClone(
  {
    method() {
      // ignored, won't be cloned
    },
    special: Symbol('also ignored')
  },
  {
    // avoid throwing
    lossy: true,
    // avoid throwing *and* looks for toJSON
    json: true
  }
);
```

The behavior is the same found in *JSON* when it comes to *Array*, so that unsupported values will result as `null` placeholders instead.

#### toJSON

If `lossy` option is not enough, `json` will actually enforce `lossy` and also check for `toJSON` method when objects are parsed.

Alternative, the `json` exports combines all features:

```js
import {stringify, parse} from '@ungap/structured-clone/json';

parse(stringify({any: 'serializable'}));
```


code:
'use strict';
const {
  VOID, PRIMITIVE, ARRAY, OBJECT, DATE, REGEXP, MAP, SET, ERROR, BIGINT
} = require('./types.js');

const env = typeof self === 'object' ? self : globalThis;

const deserializer = ($, _) => {
  const as = (out, index) => {
    $.set(index, out);
    return out;
  };

  const unpair = index => {
    if ($.has(index))
      return $.get(index);

    const [type, value] = _[index];
    switch (type) {
      case PRIMITIVE:
      case VOID:
        return as(value, index);
      case ARRAY: {
        const arr = as([], index);
        for (const index of value)
          arr.push(unpair(index));
        return arr;
      }
      case OBJECT: {
        const object = as({}, index);
        for (const [key, index] of value)
          object[unpair(key)] = unpair(index);
        return object;
      }
      case DATE:
        return as(new Date(value), index);
      case REGEXP: {
        const {source, flags} = value;
        return as(new RegExp(source, flags), index);
      }
      case MAP: {
        const map = as(new Map, index);
        for (const [key, index] of value)
          map.set(unpair(key), unpair(index));
        return map;
      }
      case SET: {
        const set = as(new Set, index);
        for (const index of value)
          set.add(unpair(index));
        return set;
      }
      case ERROR: {
        const {name, message} = value;
        return as(new env[name](message), index);
      }
      case BIGINT:
        return as(BigInt(value), index);
      case 'BigInt':
        return as(Object(BigInt(value)), index);
    }
    return as(new env[type](value), index);
  };

  return unpair;
};

/**
 * @typedef {Array<string,any>} Record a type representation
 */

/**
 * Returns a deserialized value from a serialized array of Records.
 * @param {Record[]} serialized a previously serialized value.
 * @returns {any}
 */
const deserialize = serialized => deserializer(new Map, serialized)(0);
exports.deserialize = deserialize;


code:
'use strict';
const {deserialize} = require('./deserialize.js');
const {serialize} = require('./serialize.js');

/**
 * @typedef {Array<string,any>} Record a type representation
 */

/**
 * Returns an array of serialized Records.
 * @param {any} any a serializable value.
 * @param {{transfer?: any[], json?: boolean, lossy?: boolean}?} options an object with
 * a transfer option (ignored when polyfilled) and/or non standard fields that
 * fallback to the polyfill if present.
 * @returns {Record[]}
 */
Object.defineProperty(exports, '__esModule', {value: true}).default = typeof structuredClone === "function" ?
  /* c8 ignore start */
  (any, options) => (
    options && ('json' in options || 'lossy' in options) ?
      deserialize(serialize(any, options)) : structuredClone(any)
  ) :
  (any, options) => deserialize(serialize(any, options));
  /* c8 ignore stop */

exports.deserialize = deserialize;
exports.serialize = serialize;


code:
'use strict';
/*! (c) Andrea Giammarchi - ISC */

const {deserialize} = require('./deserialize.js');
const {serialize} = require('./serialize.js');

const {parse: $parse, stringify: $stringify} = JSON;
const options = {json: true, lossy: true};

/**
 * Revive a previously stringified structured clone.
 * @param {string} str previously stringified data as string.
 * @returns {any} whatever was previously stringified as clone.
 */
const parse = str => deserialize($parse(str));
exports.parse = parse;

/**
 * Represent a structured clone value as string.
 * @param {any} any some clone-able value to stringify.
 * @returns {string} the value stringified.
 */
const stringify = any => $stringify(serialize(any, options));
exports.stringify = stringify;


code:
'use strict';
const {
  VOID, PRIMITIVE, ARRAY, OBJECT, DATE, REGEXP, MAP, SET, ERROR, BIGINT
} = require('./types.js');

const EMPTY = '';

const {toString} = {};
const {keys} = Object;

const typeOf = value => {
  const type = typeof value;
  if (type !== 'object' || !value)
    return [PRIMITIVE, type];

  const asString = toString.call(value).slice(8, -1);
  switch (asString) {
    case 'Array':
      return [ARRAY, EMPTY];
    case 'Object':
      return [OBJECT, EMPTY];
    case 'Date':
      return [DATE, EMPTY];
    case 'RegExp':
      return [REGEXP, EMPTY];
    case 'Map':
      return [MAP, EMPTY];
    case 'Set':
      return [SET, EMPTY];
  }

  if (asString.includes('Array'))
    return [ARRAY, asString];

  if (asString.includes('Error'))
    return [ERROR, asString];

  return [OBJECT, asString];
};

const shouldSkip = ([TYPE, type]) => (
  TYPE === PRIMITIVE &&
  (type === 'function' || type === 'symbol')
);

const serializer = (strict, json, $, _) => {

  const as = (out, value) => {
    const index = _.push(out) - 1;
    $.set(value, index);
    return index;
  };

  const pair = value => {
    if ($.has(value))
      return $.get(value);

    let [TYPE, type] = typeOf(value);
    switch (TYPE) {
      case PRIMITIVE: {
        let entry = value;
        switch (type) {
          case 'bigint':
            TYPE = BIGINT;
            entry = value.toString();
            break;
          case 'function':
          case 'symbol':
            if (strict)
              throw new TypeError('unable to serialize ' + type);
            entry = null;
            break;
          case 'undefined':
            return as([VOID], value);
        }
        return as([TYPE, entry], value);
      }
      case ARRAY: {
        if (type)
          return as([type, [...value]], value);

        const arr = [];
        const index = as([TYPE, arr], value);
        for (const entry of value)
          arr.push(pair(entry));
        return index;
      }
      case OBJECT: {
        if (type) {
          switch (type) {
            case 'BigInt':
              return as([type, value.toString()], value);
            case 'Boolean':
            case 'Number':
            case 'String':
              return as([type, value.valueOf()], value);
          }
        }

        if (json && ('toJSON' in value))
          return pair(value.toJSON());

        const entries = [];
        const index = as([TYPE, entries], value);
        for (const key of keys(value)) {
          if (strict || !shouldSkip(typeOf(value[key])))
            entries.push([pair(key), pair(value[key])]);
        }
        return index;
      }
      case DATE:
        return as([TYPE, value.toISOString()], value);
      case REGEXP: {
        const {source, flags} = value;
        return as([TYPE, {source, flags}], value);
      }
      case MAP: {
        const entries = [];
        const index = as([TYPE, entries], value);
        for (const [key, entry] of value) {
          if (strict || !(shouldSkip(typeOf(key)) || shouldSkip(typeOf(entry))))
            entries.push([pair(key), pair(entry)]);
        }
        return index;
      }
      case SET: {
        const entries = [];
        const index = as([TYPE, entries], value);
        for (const entry of value) {
          if (strict || !shouldSkip(typeOf(entry)))
            entries.push(pair(entry));
        }
        return index;
      }
    }

    const {message} = value;
    return as([TYPE, {name: type, message}], value);
  };

  return pair;
};

/**
 * @typedef {Array<string,any>} Record a type representation
 */

/**
 * Returns an array of serialized Records.
 * @param {any} value a serializable value.
 * @param {{json?: boolean, lossy?: boolean}?} options an object with a `lossy` or `json` property that,
 *  if `true`, will not throw errors on incompatible types, and behave more
 *  like JSON stringify would behave. Symbol and Function will be discarded.
 * @returns {Record[]}
 */
 const serialize = (value, {json, lossy} = {}) => {
  const _ = [];
  return serializer(!(json || lossy), !!json, new Map, _)(value), _;
};
exports.serialize = serialize;


code:
'use strict';
const VOID       = -1;
exports.VOID = VOID;
const PRIMITIVE  = 0;
exports.PRIMITIVE = PRIMITIVE;
const ARRAY      = 1;
exports.ARRAY = ARRAY;
const OBJECT     = 2;
exports.OBJECT = OBJECT;
const DATE       = 3;
exports.DATE = DATE;
const REGEXP     = 4;
exports.REGEXP = REGEXP;
const MAP        = 5;
exports.MAP = MAP;
const SET        = 6;
exports.SET = SET;
const ERROR      = 7;
exports.ERROR = ERROR;
const BIGINT     = 8;
exports.BIGINT = BIGINT;
// export const SYMBOL = 9;


code:
import {
  VOID, PRIMITIVE,
  ARRAY, OBJECT,
  DATE, REGEXP, MAP, SET,
  ERROR, BIGINT
} from './types.js';

const env = typeof self === 'object' ? self : globalThis;

const deserializer = ($, _) => {
  const as = (out, index) => {
    $.set(index, out);
    return out;
  };

  const unpair = index => {
    if ($.has(index))
      return $.get(index);

    const [type, value] = _[index];
    switch (type) {
      case PRIMITIVE:
      case VOID:
        return as(value, index);
      case ARRAY: {
        const arr = as([], index);
        for (const index of value)
          arr.push(unpair(index));
        return arr;
      }
      case OBJECT: {
        const object = as({}, index);
        for (const [key, index] of value)
          object[unpair(key)] = unpair(index);
        return object;
      }
      case DATE:
        return as(new Date(value), index);
      case REGEXP: {
        const {source, flags} = value;
        return as(new RegExp(source, flags), index);
      }
      case MAP: {
        const map = as(new Map, index);
        for (const [key, index] of value)
          map.set(unpair(key), unpair(index));
        return map;
      }
      case SET: {
        const set = as(new Set, index);
        for (const index of value)
          set.add(unpair(index));
        return set;
      }
      case ERROR: {
        const {name, message} = value;
        return as(new env[name](message), index);
      }
      case BIGINT:
        return as(BigInt(value), index);
      case 'BigInt':
        return as(Object(BigInt(value)), index);
    }
    return as(new env[type](value), index);
  };

  return unpair;
};

/**
 * @typedef {Array<string,any>} Record a type representation
 */

/**
 * Returns a deserialized value from a serialized array of Records.
 * @param {Record[]} serialized a previously serialized value.
 * @returns {any}
 */
export const deserialize = serialized => deserializer(new Map, serialized)(0);


code:
import {deserialize} from './deserialize.js';
import {serialize} from './serialize.js';

/**
 * @typedef {Array<string,any>} Record a type representation
 */

/**
 * Returns an array of serialized Records.
 * @param {any} any a serializable value.
 * @param {{transfer?: any[], json?: boolean, lossy?: boolean}?} options an object with
 * a transfer option (ignored when polyfilled) and/or non standard fields that
 * fallback to the polyfill if present.
 * @returns {Record[]}
 */
export default typeof structuredClone === "function" ?
  /* c8 ignore start */
  (any, options) => (
    options && ('json' in options || 'lossy' in options) ?
      deserialize(serialize(any, options)) : structuredClone(any)
  ) :
  (any, options) => deserialize(serialize(any, options));
  /* c8 ignore stop */

export {deserialize, serialize};


code:
/*! (c) Andrea Giammarchi - ISC */

import {deserialize} from './deserialize.js';
import {serialize} from './serialize.js';

const {parse: $parse, stringify: $stringify} = JSON;
const options = {json: true, lossy: true};

/**
 * Revive a previously stringified structured clone.
 * @param {string} str previously stringified data as string.
 * @returns {any} whatever was previously stringified as clone.
 */
export const parse = str => deserialize($parse(str));

/**
 * Represent a structured clone value as string.
 * @param {any} any some clone-able value to stringify.
 * @returns {string} the value stringified.
 */
export const stringify = any => $stringify(serialize(any, options));


code:
import {
  VOID, PRIMITIVE,
  ARRAY, OBJECT,
  DATE, REGEXP, MAP, SET,
  ERROR, BIGINT
} from './types.js';

const EMPTY = '';

const {toString} = {};
const {keys} = Object;

const typeOf = value => {
  const type = typeof value;
  if (type !== 'object' || !value)
    return [PRIMITIVE, type];

  const asString = toString.call(value).slice(8, -1);
  switch (asString) {
    case 'Array':
      return [ARRAY, EMPTY];
    case 'Object':
      return [OBJECT, EMPTY];
    case 'Date':
      return [DATE, EMPTY];
    case 'RegExp':
      return [REGEXP, EMPTY];
    case 'Map':
      return [MAP, EMPTY];
    case 'Set':
      return [SET, EMPTY];
  }

  if (asString.includes('Array'))
    return [ARRAY, asString];

  if (asString.includes('Error'))
    return [ERROR, asString];

  return [OBJECT, asString];
};

const shouldSkip = ([TYPE, type]) => (
  TYPE === PRIMITIVE &&
  (type === 'function' || type === 'symbol')
);

const serializer = (strict, json, $, _) => {

  const as = (out, value) => {
    const index = _.push(out) - 1;
    $.set(value, index);
    return index;
  };

  const pair = value => {
    if ($.has(value))
      return $.get(value);

    let [TYPE, type] = typeOf(value);
    switch (TYPE) {
      case PRIMITIVE: {
        let entry = value;
        switch (type) {
          case 'bigint':
            TYPE = BIGINT;
            entry = value.toString();
            break;
          case 'function':
          case 'symbol':
            if (strict)
              throw new TypeError('unable to serialize ' + type);
            entry = null;
            break;
          case 'undefined':
            return as([VOID], value);
        }
        return as([TYPE, entry], value);
      }
      case ARRAY: {
        if (type)
          return as([type, [...value]], value);

        const arr = [];
        const index = as([TYPE, arr], value);
        for (const entry of value)
          arr.push(pair(entry));
        return index;
      }
      case OBJECT: {
        if (type) {
          switch (type) {
            case 'BigInt':
              return as([type, value.toString()], value);
            case 'Boolean':
            case 'Number':
            case 'String':
              return as([type, value.valueOf()], value);
          }
        }

        if (json && ('toJSON' in value))
          return pair(value.toJSON());

        const entries = [];
        const index = as([TYPE, entries], value);
        for (const key of keys(value)) {
          if (strict || !shouldSkip(typeOf(value[key])))
            entries.push([pair(key), pair(value[key])]);
        }
        return index;
      }
      case DATE:
        return as([TYPE, value.toISOString()], value);
      case REGEXP: {
        const {source, flags} = value;
        return as([TYPE, {source, flags}], value);
      }
      case MAP: {
        const entries = [];
        const index = as([TYPE, entries], value);
        for (const [key, entry] of value) {
          if (strict || !(shouldSkip(typeOf(key)) || shouldSkip(typeOf(entry))))
            entries.push([pair(key), pair(entry)]);
        }
        return index;
      }
      case SET: {
        const entries = [];
        const index = as([TYPE, entries], value);
        for (const entry of value) {
          if (strict || !shouldSkip(typeOf(entry)))
            entries.push(pair(entry));
        }
        return index;
      }
    }

    const {message} = value;
    return as([TYPE, {name: type, message}], value);
  };

  return pair;
};

/**
 * @typedef {Array<string,any>} Record a type representation
 */

/**
 * Returns an array of serialized Records.
 * @param {any} value a serializable value.
 * @param {{json?: boolean, lossy?: boolean}?} options an object with a `lossy` or `json` property that,
 *  if `true`, will not throw errors on incompatible types, and behave more
 *  like JSON stringify would behave. Symbol and Function will be discarded.
 * @returns {Record[]}
 */
 export const serialize = (value, {json, lossy} = {}) => {
  const _ = [];
  return serializer(!(json || lossy), !!json, new Map, _)(value), _;
};


code:
export const VOID       = -1;
export const PRIMITIVE  = 0;
export const ARRAY      = 1;
export const OBJECT     = 2;
export const DATE       = 3;
export const REGEXP     = 4;
export const MAP        = 5;
export const SET        = 6;
export const ERROR      = 7;
export const BIGINT     = 8;
// export const SYMBOL = 9;


@ungap/structured-clone

description: A structuredClone polyfill

build: npm run cjs && npm run rollup:json && npm run test

cjs: ascjs esm cjs

coverage: c8 report --reporter=text-lcov > ./coverage/lcov.info

rollup:json: rollup --config rollup/json.config.js

test: c8 node test/index.js

keywords: recursion structured clone algorithm

author: Andrea Giammarchi

license: ISC

type: module

test: test


code:
## @vue/babel-helper-vue-jsx-merge-props

A package used internally by vue jsx transformer to merge props spread. It is required to merge some prop trees like this:

```js
import mergeProps from '@vue/babel-helper-vue-jsx-merge-props'

const MyComponent = {
  render(h) {
    // original: <button onClick={$event => console.log($event)} {...{ on: { click: $event => doSomething($event) } }} />
    return h(
      'button',
      mergeProps([
        {
          on: {
            click: $event => console.log($event),
          },
        },
        {
          on: {
            click: $event => doSomething($event),
          },
        },
      ]),
    )
  },
}
```

This tool is used internally and there is no reason for you to ever use it.


@vue/babel-helper-vue-jsx-merge-props

description: Babel helper for Vue JSX spread

author: Evan You

access: public

build:testing: rollup -c rollup.config.testing.js

build: rollup -c

pretest: yarn build:testing

test: nyc --reporter=html --reporter=text-summary ava -v test/test.js

prepublish: yarn build

exclude: dist test


code:
# @vue/babel-helper-vue-transform-on

A package used internally by vue jsx transformer to transform events.

on: { click: xx } --> onClick: xx


code:
declare function transformOn(
  obj: Record<string, any>
): Record<`on${string}`, any>;
export = transformOn;


code:
const transformOn = (obj) => {
  const result = {};
  Object.keys(obj).forEach((evt) => {
    result[`on${evt[0].toUpperCase()}${evt.slice(1)}`] = obj[evt];
  });
  return result;
};

module.exports = transformOn;


@vue/babel-helper-vue-transform-on

description: to help transform on

author: Amour1688 <lcz_1996@foxmail.com>


code:
# Babel Plugin JSX for Vue 3

[![npm package](https://img.shields.io/npm/v/@vue/babel-plugin-jsx.svg?style=flat-square)](https://www.npmjs.com/package/@vue/babel-plugin-jsx)
[![issues-helper](https://img.shields.io/badge/Issues%20Manage%20By-issues--helper-blueviolet?style=flat-square)](https://github.com/actions-cool/issues-helper)

To add Vue JSX support.

English | [简体中文](/packages/babel-plugin-jsx/README-zh_CN.md)

## Installation

Install the plugin with:

```bash
npm install @vue/babel-plugin-jsx -D
```

Then add the plugin to your babel config:

```json
{
  "plugins": ["@vue/babel-plugin-jsx"]
}
```

## Usage

### options

#### transformOn

Type: `boolean`

Default: `false`

transform `on: { click: xx }` to `onClick: xxx`

#### optimize

Type: `boolean`

Default: `false`

enable optimization or not. It's not recommended to enable it If you are not familiar with Vue 3.

#### isCustomElement

Type: `(tag: string) => boolean`

Default: `undefined`

configuring custom elements

#### mergeProps

Type: `boolean`

Default: `true`

merge static and dynamic class / style attributes / onXXX handlers

#### enableObjectSlots

Type: `boolean`

Default: `true`

Whether to enable `object slots` (mentioned below the document) syntax". It might be useful in JSX, but it will add a lot of `_isSlot` condition expressions which increase your bundle size. And `v-slots` is still available even if `enableObjectSlots` is turned off.

#### pragma

Type: `string`

Default: `createVNode`

Replace the function used when compiling JSX expressions.

#### resolveType

Type: `boolean`

Default: `false`

(**Experimental**) Infer component metadata from types (e.g. `props`, `emits`, `name`). This is an experimental feature and may not work in all cases.

## Syntax

### Content

functional component

```jsx
const App = () => <div>Vue 3.0</div>;
```

with render

```jsx
const App = {
  render() {
    return <div>Vue 3.0</div>;
  },
};
```

```jsx
import { withModifiers, defineComponent } from 'vue';

const App = defineComponent({
  setup() {
    const count = ref(0);

    const inc = () => {
      count.value++;
    };

    return () => (
      <div onClick={withModifiers(inc, ['self'])}>{count.value}</div>
    );
  },
});
```

Fragment

```jsx
const App = () => (
  <>
    <span>I'm</span>
    <span>Fragment</span>
  </>
);
```

### Attributes / Props

```jsx
const App = () => <input type="email" />;
```

with a dynamic binding:

```jsx
const placeholderText = 'email';
const App = () => <input type="email" placeholder={placeholderText} />;
```

### Directives

#### v-show

```jsx
const App = {
  data() {
    return { visible: true };
  },
  render() {
    return <input v-show={this.visible} />;
  },
};
```

#### v-model

> Note: You should pass the second param as string for using `arg`.

```jsx
<input v-model={val} />
```

```jsx
<input v-model:argument={val} />
```

```jsx
<input v-model={[val, ['modifier']]} />
// Or
<input v-model_modifier={val} />
```

```jsx
<A v-model={[val, 'argument', ['modifier']]} />
// Or
<input v-model:argument_modifier={val} />
```

Will compile to:

```js
h(A, {
  argument: val,
  argumentModifiers: {
    modifier: true,
  },
  'onUpdate:argument': ($event) => (val = $event),
});
```

#### v-models (Not recommended since v1.1.0)

> Note: You should pass a Two-dimensional Arrays to v-models.

```jsx
<A v-models={[[foo], [bar, 'bar']]} />
```

```jsx
<A
  v-models={[
    [foo, 'foo'],
    [bar, 'bar'],
  ]}
/>
```

```jsx
<A
  v-models={[
    [foo, ['modifier']],
    [bar, 'bar', ['modifier']],
  ]}
/>
```

Will compile to:

```js
h(A, {
  modelValue: foo,
  modelModifiers: {
    modifier: true,
  },
  'onUpdate:modelValue': ($event) => (foo = $event),
  bar: bar,
  barModifiers: {
    modifier: true,
  },
  'onUpdate:bar': ($event) => (bar = $event),
});
```

#### custom directive

Recommended when using string arguments

```jsx
const App = {
  directives: { custom: customDirective },
  setup() {
    return () => <a v-custom:arg={val} />;
  },
};
```

```jsx
const App = {
  directives: { custom: customDirective },
  setup() {
    return () => <a v-custom={[val, 'arg', ['a', 'b']]} />;
  },
};
```

### Slot

> Note: In `jsx`, _`v-slot`_ should be replaced with **`v-slots`**

```jsx
const A = (props, { slots }) => (
  <>
    <h1>{slots.default ? slots.default() : 'foo'}</h1>
    <h2>{slots.bar?.()}</h2>
  </>
);

const App = {
  setup() {
    const slots = {
      bar: () => <span>B</span>,
    };
    return () => (
      <A v-slots={slots}>
        <div>A</div>
      </A>
    );
  },
};

// or

const App = {
  setup() {
    const slots = {
      default: () => <div>A</div>,
      bar: () => <span>B</span>,
    };
    return () => <A v-slots={slots} />;
  },
};

// or you can use object slots when `enableObjectSlots` is not false.
const App = {
  setup() {
    return () => (
      <>
        <A>
          {{
            default: () => <div>A</div>,
            bar: () => <span>B</span>,
          }}
        </A>
        <B>{() => 'foo'}</B>
      </>
    );
  },
};
```

### In TypeScript

`tsconfig.json`:

```json
{
  "compilerOptions": {
    "jsx": "preserve"
  }
}
```

## Who is using

          Ant Design Vue

          Vant

          Element Plus

          Vue Json Pretty

## Compatibility

This repo is only compatible with:

- **Babel 7+**
- **Vue 3+**


code:
import * as BabelCore from '@babel/core';
import { Options } from '@vue/babel-plugin-resolve-type';

type State = {
    get: (name: string) => any;
    set: (name: string, value: any) => any;
    opts: VueJSXPluginOptions;
    file: BabelCore.BabelFile;
};
interface VueJSXPluginOptions {
    /** transform `on: { click: xx }` to `onClick: xxx` */
    transformOn?: boolean;
    /** enable optimization or not. */
    optimize?: boolean;
    /** merge static and dynamic class / style attributes / onXXX handlers */
    mergeProps?: boolean;
    /** configuring custom elements */
    isCustomElement?: (tag: string) => boolean;
    /** enable object slots syntax */
    enableObjectSlots?: boolean;
    /** Replace the function used when compiling JSX expressions */
    pragma?: string;
    /**
     * (**Experimental**) Infer component metadata from types (e.g. `props`, `emits`, `name`)
     * @default false
     */
    resolveType?: Options | boolean;
}

declare const _default: (api: object, options: VueJSXPluginOptions | null | undefined, dirname: string) => BabelCore.PluginObj<State>;

export { type VueJSXPluginOptions, _default as default };


code:
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
  for (var prop in b || (b = {}))
    if (__hasOwnProp.call(b, prop))
      __defNormalProp(a, prop, b[prop]);
  if (__getOwnPropSymbols)
    for (var prop of __getOwnPropSymbols(b)) {
      if (__propIsEnum.call(b, prop))
        __defNormalProp(a, prop, b[prop]);
    }
  return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
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 __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/index.ts
var src_exports = {};
__export(src_exports, {
  default: () => src_default
});
module.exports = __toCommonJS(src_exports);
var t5 = __toESM(require("@babel/types"));
var import_template = __toESM(require("@babel/template"));
var import_plugin_syntax_jsx = __toESM(require("@babel/plugin-syntax-jsx"));
var import_helper_module_imports2 = require("@babel/helper-module-imports");
var import_babel_plugin_resolve_type = __toESM(require("@vue/babel-plugin-resolve-type"));
var import_helper_plugin_utils = require("@babel/helper-plugin-utils");

// src/transform-vue-jsx.ts
var t3 = __toESM(require("@babel/types"));
var import_helper_module_imports = require("@babel/helper-module-imports");

// src/utils.ts
var t = __toESM(require("@babel/types"));
var import_html_tags = __toESM(require("html-tags"));
var import_svg_tags = __toESM(require("svg-tags"));

// src/slotFlags.ts
var SlotFlags = /* @__PURE__ */ ((SlotFlags2) => {
  SlotFlags2[SlotFlags2["STABLE"] = 1] = "STABLE";
  SlotFlags2[SlotFlags2["DYNAMIC"] = 2] = "DYNAMIC";
  SlotFlags2[SlotFlags2["FORWARDED"] = 3] = "FORWARDED";
  return SlotFlags2;
})(SlotFlags || {});
var slotFlags_default = SlotFlags;

// src/utils.ts
var FRAGMENT = "Fragment";
var KEEP_ALIVE = "KeepAlive";
var createIdentifier = (state, name) => state.get(name)();
var isDirective = (src) => src.startsWith("v-") || src.startsWith("v") && src.length >= 2 && src[1] >= "A" && src[1] <= "Z";
var shouldTransformedToSlots = (tag) => !(tag.match(RegExp(`^_?${FRAGMENT}\\d*$`)) || tag === KEEP_ALIVE);
var checkIsComponent = (path, state) => {
  var _a, _b;
  const namePath = path.get("name");
  if (namePath.isJSXMemberExpression()) {
    return shouldTransformedToSlots(namePath.node.property.name);
  }
  const tag = namePath.node.name;
  return !((_b = (_a = state.opts).isCustomElement) == null ? void 0 : _b.call(_a, tag)) && shouldTransformedToSlots(tag) && !import_html_tags.default.includes(tag) && !import_svg_tags.default.includes(tag);
};
var transformJSXMemberExpression = (path) => {
  const objectPath = path.node.object;
  const propertyPath = path.node.property;
  const transformedObject = t.isJSXMemberExpression(objectPath) ? transformJSXMemberExpression(
    path.get("object")
  ) : t.isJSXIdentifier(objectPath) ? t.identifier(objectPath.name) : t.nullLiteral();
  const transformedProperty = t.identifier(propertyPath.name);
  return t.memberExpression(transformedObject, transformedProperty);
};
var getTag = (path, state) => {
  var _a, _b;
  const namePath = path.get("openingElement").get("name");
  if (namePath.isJSXIdentifier()) {
    const { name } = namePath.node;
    if (!import_html_tags.default.includes(name) && !import_svg_tags.default.includes(name)) {
      return name === FRAGMENT ? createIdentifier(state, FRAGMENT) : path.scope.hasBinding(name) ? t.identifier(name) : ((_b = (_a = state.opts).isCustomElement) == null ? void 0 : _b.call(_a, name)) ? t.stringLiteral(name) : t.callExpression(createIdentifier(state, "resolveComponent"), [
        t.stringLiteral(name)
      ]);
    }
    return t.stringLiteral(name);
  }
  if (namePath.isJSXMemberExpression()) {
    return transformJSXMemberExpression(namePath);
  }
  throw new Error(`getTag: ${namePath.type} is not supported`);
};
var getJSXAttributeName = (path) => {
  const nameNode = path.node.name;
  if (t.isJSXIdentifier(nameNode)) {
    return nameNode.name;
  }
  return `${nameNode.namespace.name}:${nameNode.name.name}`;
};
var transformJSXText = (path) => {
  const str = transformText(path.node.value);
  return str !== "" ? t.stringLiteral(str) : null;
};
var transformText = (text) => {
  const lines = text.split(/\r\n|\n|\r/);
  let lastNonEmptyLine = 0;
  for (let i = 0; i < lines.length; i++) {
    if (lines[i].match(/[^ \t]/)) {
      lastNonEmptyLine = i;
    }
  }
  let str = "";
  for (let i = 0; i < lines.length; i++) {
    const line = lines[i];
    const isFirstLine = i === 0;
    const isLastLine = i === lines.length - 1;
    const isLastNonEmptyLine = i === lastNonEmptyLine;
    let trimmedLine = line.replace(/\t/g, " ");
    if (!isFirstLine) {
      trimmedLine = trimmedLine.replace(/^[ ]+/, "");
    }
    if (!isLastLine) {
      trimmedLine = trimmedLine.replace(/[ ]+$/, "");
    }
    if (trimmedLine) {
      if (!isLastNonEmptyLine) {
        trimmedLine += " ";
      }
      str += trimmedLine;
    }
  }
  return str;
};
var transformJSXExpressionContainer = (path) => path.get("expression").node;
var transformJSXSpreadChild = (path) => t.spreadElement(path.get("expression").node);
var walksScope = (path, name, slotFlag) => {
  if (path.scope.hasBinding(name) && path.parentPath) {
    if (t.isJSXElement(path.parentPath.node)) {
      path.parentPath.setData("slotFlag", slotFlag);
    }
    walksScope(path.parentPath, name, slotFlag);
  }
};
var buildIIFE = (path, children) => {
  const { parentPath } = path;
  if (parentPath.isAssignmentExpression()) {
    const { left } = parentPath.node;
    if (t.isIdentifier(left)) {
      return children.map((child) => {
        if (t.isIdentifier(child) && child.name === left.name) {
          const insertName = path.scope.generateUidIdentifier(child.name);
          parentPath.insertBefore(
            t.variableDeclaration("const", [
              t.variableDeclarator(
                insertName,
                t.callExpression(
                  t.functionExpression(
                    null,
                    [],
                    t.blockStatement([t.returnStatement(child)])
                  ),
                  []
                )
              )
            ])
          );
          return insertName;
        }
        return child;
      });
    }
  }
  return children;
};
var onRE = /^on[^a-z]/;
var isOn = (key) => onRE.test(key);
var mergeAsArray = (existing, incoming) => {
  if (t.isArrayExpression(existing.value)) {
    existing.value.elements.push(incoming.value);
  } else {
    existing.value = t.arrayExpression([
      existing.value,
      incoming.value
    ]);
  }
};
var dedupeProperties = (properties = [], mergeProps) => {
  if (!mergeProps) {
    return properties;
  }
  const knownProps = /* @__PURE__ */ new Map();
  const deduped = [];
  properties.forEach((prop) => {
    if (t.isStringLiteral(prop.key)) {
      const { value: name } = prop.key;
      const existing = knownProps.get(name);
      if (existing) {
        if (name === "style" || name === "class" || name.startsWith("on")) {
          mergeAsArray(existing, prop);
        }
      } else {
        knownProps.set(name, prop);
        deduped.push(prop);
      }
    } else {
      deduped.push(prop);
    }
  });
  return deduped;
};
var isConstant = (node) => {
  if (t.isIdentifier(node)) {
    return node.name === "undefined";
  }
  if (t.isArrayExpression(node)) {
    const { elements } = node;
    return elements.every((element) => element && isConstant(element));
  }
  if (t.isObjectExpression(node)) {
    return node.properties.every(
      (property) => isConstant(property.value)
    );
  }
  if (t.isLiteral(node)) {
    return true;
  }
  return false;
};
var transformJSXSpreadAttribute = (nodePath, path, mergeProps, args) => {
  const argument = path.get("argument");
  const properties = t.isObjectExpression(argument.node) ? argument.node.properties : void 0;
  if (!properties) {
    if (argument.isIdentifier()) {
      walksScope(
        nodePath,
        argument.node.name,
        slotFlags_default.DYNAMIC
      );
    }
    args.push(mergeProps ? argument.node : t.spreadElement(argument.node));
  } else if (mergeProps) {
    args.push(t.objectExpression(properties));
  } else {
    args.push(...properties);
  }
};

// src/parseDirectives.ts
var t2 = __toESM(require("@babel/types"));
var getType = (path) => {
  const typePath = path.get("attributes").find((attribute) => {
    if (!attribute.isJSXAttribute()) {
      return false;
    }
    return attribute.get("name").isJSXIdentifier() && attribute.get("name").node.name === "type";
  });
  return typePath ? typePath.get("value").node : null;
};
var parseModifiers = (value) => t2.isArrayExpression(value) ? value.elements.map((el) => t2.isStringLiteral(el) ? el.value : "").filter(Boolean) : [];
var parseDirectives = (params) => {
  var _a, _b;
  const { path, value, state, tag, isComponent } = params;
  const args = [];
  const vals = [];
  const modifiersSet = [];
  let directiveName;
  let directiveArgument;
  let directiveModifiers;
  if ("namespace" in path.node.name) {
    [directiveName, directiveArgument] = params.name.split(":");
    directiveName = path.node.name.namespace.name;
    directiveArgument = path.node.name.name.name;
    directiveModifiers = directiveArgument.split("_").slice(1);
  } else {
    const underscoreModifiers = params.name.split("_");
    directiveName = underscoreModifiers.shift() || "";
    directiveModifiers = underscoreModifiers;
  }
  directiveName = directiveName.replace(/^v/, "").replace(/^-/, "").replace(/^\S/, (s) => s.toLowerCase());
  if (directiveArgument) {
    args.push(t2.stringLiteral(directiveArgument.split("_")[0]));
  }
  const isVModels = directiveName === "models";
  const isVModel = directiveName === "model";
  if (isVModel && !path.get("value").isJSXExpressionContainer()) {
    throw new Error("You have to use JSX Expression inside your v-model");
  }
  if (isVModels && !isComponent) {
    throw new Error("v-models can only use in custom components");
  }
  const shouldResolve = !["html", "text", "model", "models"].includes(directiveName) || isVModel && !isComponent;
  let modifiers = directiveModifiers;
  if (t2.isArrayExpression(value)) {
    const elementsList = isVModels ? value.elements : [value];
    elementsList.forEach((element) => {
      if (isVModels && !t2.isArrayExpression(element)) {
        throw new Error("You should pass a Two-dimensional Arrays to v-models");
      }
      const { elements } = element;
      const [first, second, third] = elements;
      if (second && !t2.isArrayExpression(second) && !t2.isSpreadElement(second)) {
        args.push(second);
        modifiers = parseModifiers(third);
      } else if (t2.isArrayExpression(second)) {
        if (!shouldResolve) {
          args.push(t2.nullLiteral());
        }
        modifiers = parseModifiers(second);
      } else if (!shouldResolve) {
        args.push(t2.nullLiteral());
      }
      modifiersSet.push(new Set(modifiers));
      vals.push(first);
    });
  } else if (isVModel && !shouldResolve) {
    args.push(t2.nullLiteral());
    modifiersSet.push(new Set(directiveModifiers));
  } else {
    modifiersSet.push(new Set(directiveModifiers));
  }
  return {
    directiveName,
    modifiers: modifiersSet,
    values: vals.length ? vals : [value],
    args,
    directive: shouldResolve ? [
      resolveDirective(path, state, tag, directiveName),
      vals[0] || value,
      ((_a = modifiersSet[0]) == null ? void 0 : _a.size) ? args[0] || t2.unaryExpression("void", t2.numericLiteral(0), true) : args[0],
      !!((_b = modifiersSet[0]) == null ? void 0 : _b.size) && t2.objectExpression(
        [...modifiersSet[0]].map(
          (modifier) => t2.objectProperty(t2.identifier(modifier), t2.booleanLiteral(true))
        )
      )
    ].filter(Boolean) : void 0
  };
};
var resolveDirective = (path, state, tag, directiveName) => {
  if (directiveName === "show") {
    return createIdentifier(state, "vShow");
  }
  if (directiveName === "model") {
    let modelToUse;
    const type = getType(path.parentPath);
    switch (tag.value) {
      case "select":
        modelToUse = createIdentifier(state, "vModelSelect");
        break;
      case "textarea":
        modelToUse = createIdentifier(state, "vModelText");
        break;
      default:
        if (t2.isStringLiteral(type) || !type) {
          switch (type == null ? void 0 : type.value) {
            case "checkbox":
              modelToUse = createIdentifier(state, "vModelCheckbox");
              break;
            case "radio":
              modelToUse = createIdentifier(state, "vModelRadio");
              break;
            default:
              modelToUse = createIdentifier(state, "vModelText");
          }
        } else {
          modelToUse = createIdentifier(state, "vModelDynamic");
        }
    }
    return modelToUse;
  }
  return t2.callExpression(createIdentifier(state, "resolveDirective"), [
    t2.stringLiteral(directiveName)
  ]);
};
var parseDirectives_default = parseDirectives;

// src/transform-vue-jsx.ts
var xlinkRE = /^xlink([A-Z])/;
var getJSXAttributeValue = (path, state) => {
  const valuePath = path.get("value");
  if (valuePath.isJSXElement()) {
    return transformJSXElement(valuePath, state);
  }
  if (valuePath.isStringLiteral()) {
    return t3.stringLiteral(transformText(valuePath.node.value));
  }
  if (valuePath.isJSXExpressionContainer()) {
    return transformJSXExpressionContainer(valuePath);
  }
  return null;
};
var buildProps = (path, state) => {
  const tag = getTag(path, state);
  const isComponent = checkIsComponent(path.get("openingElement"), state);
  const props = path.get("openingElement").get("attributes");
  const directives = [];
  const dynamicPropNames = /* @__PURE__ */ new Set();
  let slots = null;
  let patchFlag = 0;
  if (props.length === 0) {
    return {
      tag,
      isComponent,
      slots,
      props: t3.nullLiteral(),
      directives,
      patchFlag,
      dynamicPropNames
    };
  }
  let properties = [];
  let hasRef = false;
  let hasClassBinding = false;
  let hasStyleBinding = false;
  let hasHydrationEventBinding = false;
  let hasDynamicKeys = false;
  const mergeArgs = [];
  const { mergeProps = true } = state.opts;
  props.forEach((prop) => {
    if (prop.isJSXAttribute()) {
      let name = getJSXAttributeName(prop);
      const attributeValue = getJSXAttributeValue(prop, state);
      if (!isConstant(attributeValue) || name === "ref") {
        if (!isComponent && isOn(name) && // omit the flag for click handlers becaues hydration gives click
        // dedicated fast path.
        name.toLowerCase() !== "onclick" && // omit v-model handlers
        name !== "onUpdate:modelValue") {
          hasHydrationEventBinding = true;
        }
        if (name === "ref") {
          hasRef = true;
        } else if (name === "class" && !isComponent) {
          hasClassBinding = true;
        } else if (name === "style" && !isComponent) {
          hasStyleBinding = true;
        } else if (name !== "key" && !isDirective(name) && name !== "on") {
          dynamicPropNames.add(name);
        }
      }
      if (state.opts.transformOn && (name === "on" || name === "nativeOn")) {
        if (!state.get("transformOn")) {
          state.set(
            "transformOn",
            (0, import_helper_module_imports.addDefault)(path, "@vue/babel-helper-vue-transform-on", {
              nameHint: "_transformOn"
            })
          );
        }
        mergeArgs.push(
          t3.callExpression(state.get("transformOn"), [
            attributeValue || t3.booleanLiteral(true)
          ])
        );
        return;
      }
      if (isDirective(name)) {
        const { directive, modifiers, values, args, directiveName } = parseDirectives_default({
          tag,
          isComponent,
          name,
          path: prop,
          state,
          value: attributeValue
        });
        if (directiveName === "slots") {
          slots = attributeValue;
          return;
        }
        if (directive) {
          directives.push(t3.arrayExpression(directive));
        } else if (directiveName === "html") {
          properties.push(
            t3.objectProperty(t3.stringLiteral("innerHTML"), values[0])
          );
          dynamicPropNames.add("innerHTML");
        } else if (directiveName === "text") {
          properties.push(
            t3.objectProperty(t3.stringLiteral("textContent"), values[0])
          );
          dynamicPropNames.add("textContent");
        }
        if (["models", "model"].includes(directiveName)) {
          values.forEach((value, index) => {
            var _a;
            const propName = args[index];
            const isDynamic = propName && !t3.isStringLiteral(propName) && !t3.isNullLiteral(propName);
            if (!directive) {
              properties.push(
                t3.objectProperty(
                  t3.isNullLiteral(propName) ? t3.stringLiteral("modelValue") : propName,
                  value,
                  isDynamic
                )
              );
              if (!isDynamic) {
                dynamicPropNames.add(
                  (propName == null ? void 0 : propName.value) || "modelValue"
                );
              }
              if ((_a = modifiers[index]) == null ? void 0 : _a.size) {
                properties.push(
                  t3.objectProperty(
                    isDynamic ? t3.binaryExpression(
                      "+",
                      propName,
                      t3.stringLiteral("Modifiers")
                    ) : t3.stringLiteral(
                      `${(propName == null ? void 0 : propName.value) || "model"}Modifiers`
                    ),
                    t3.objectExpression(
                      [...modifiers[index]].map(
                        (modifier) => t3.objectProperty(
                          t3.stringLiteral(modifier),
                          t3.booleanLiteral(true)
                        )
                      )
                    ),
                    isDynamic
                  )
                );
              }
            }
            const updateName = isDynamic ? t3.binaryExpression("+", t3.stringLiteral("onUpdate"), propName) : t3.stringLiteral(
              `onUpdate:${(propName == null ? void 0 : propName.value) || "modelValue"}`
            );
            properties.push(
              t3.objectProperty(
                updateName,
                t3.arrowFunctionExpression(
                  [t3.identifier("$event")],
                  t3.assignmentExpression(
                    "=",
                    value,
                    t3.identifier("$event")
                  )
                ),
                isDynamic
              )
            );
            if (!isDynamic) {
              dynamicPropNames.add(updateName.value);
            } else {
              hasDynamicKeys = true;
            }
          });
        }
      } else {
        if (name.match(xlinkRE)) {
          name = name.replace(
            xlinkRE,
            (_, firstCharacter) => `xlink:${firstCharacter.toLowerCase()}`
          );
        }
        properties.push(
          t3.objectProperty(
            t3.stringLiteral(name),
            attributeValue || t3.booleanLiteral(true)
          )
        );
      }
    } else {
      if (properties.length && mergeProps) {
        mergeArgs.push(
          t3.objectExpression(dedupeProperties(properties, mergeProps))
        );
        properties = [];
      }
      hasDynamicKeys = true;
      transformJSXSpreadAttribute(
        path,
        prop,
        mergeProps,
        mergeProps ? mergeArgs : properties
      );
    }
  });
  if (hasDynamicKeys) {
    patchFlag |= 16 /* FULL_PROPS */;
  } else {
    if (hasClassBinding) {
      patchFlag |= 2 /* CLASS */;
    }
    if (hasStyleBinding) {
      patchFlag |= 4 /* STYLE */;
    }
    if (dynamicPropNames.size) {
      patchFlag |= 8 /* PROPS */;
    }
    if (hasHydrationEventBinding) {
      patchFlag |= 32 /* HYDRATE_EVENTS */;
    }
  }
  if ((patchFlag === 0 || patchFlag === 32 /* HYDRATE_EVENTS */) && (hasRef || directives.length > 0)) {
    patchFlag |= 512 /* NEED_PATCH */;
  }
  let propsExpression = t3.nullLiteral();
  if (mergeArgs.length) {
    if (properties.length) {
      mergeArgs.push(
        t3.objectExpression(dedupeProperties(properties, mergeProps))
      );
    }
    if (mergeArgs.length > 1) {
      propsExpression = t3.callExpression(
        createIdentifier(state, "mergeProps"),
        mergeArgs
      );
    } else {
      propsExpression = mergeArgs[0];
    }
  } else if (properties.length) {
    if (properties.length === 1 && t3.isSpreadElement(properties[0])) {
      propsExpression = properties[0].argument;
    } else {
      propsExpression = t3.objectExpression(
        dedupeProperties(properties, mergeProps)
      );
    }
  }
  return {
    tag,
    props: propsExpression,
    isComponent,
    slots,
    directives,
    patchFlag,
    dynamicPropNames
  };
};
var getChildren = (paths, state) => paths.map((path) => {
  if (path.isJSXText()) {
    const transformedText = transformJSXText(path);
    if (transformedText) {
      return t3.callExpression(createIdentifier(state, "createTextVNode"), [
        transformedText
      ]);
    }
    return transformedText;
  }
  if (path.isJSXExpressionContainer()) {
    const expression = transformJSXExpressionContainer(path);
    if (t3.isIdentifier(expression)) {
      const { name } = expression;
      const { referencePaths = [] } = path.scope.getBinding(name) || {};
      referencePaths.forEach((referencePath) => {
        walksScope(referencePath, name, slotFlags_default.DYNAMIC);
      });
    }
    return expression;
  }
  if (path.isJSXSpreadChild()) {
    return transformJSXSpreadChild(path);
  }
  if (path.isCallExpression()) {
    return path.node;
  }
  if (path.isJSXElement()) {
    return transformJSXElement(path, state);
  }
  throw new Error(`getChildren: ${path.type} is not supported`);
}).filter(
  (value) => value != null && !t3.isJSXEmptyExpression(value)
);
var transformJSXElement = (path, state) => {
  const children = getChildren(path.get("children"), state);
  const {
    tag,
    props,
    isComponent,
    directives,
    patchFlag,
    dynamicPropNames,
    slots
  } = buildProps(path, state);
  const { optimize = false } = state.opts;
  const slotFlag = path.getData("slotFlag") || slotFlags_default.STABLE;
  let VNodeChild;
  if (children.length > 1 || slots) {
    VNodeChild = isComponent ? children.length ? t3.objectExpression(
      [
        !!children.length && t3.objectProperty(
          t3.identifier("default"),
          t3.arrowFunctionExpression(
            [],
            t3.arrayExpression(buildIIFE(path, children))
          )
        ),
        ...slots ? t3.isObjectExpression(slots) ? slots.properties : [t3.spreadElement(slots)] : [],
        optimize && t3.objectProperty(t3.identifier("_"), t3.numericLiteral(slotFlag))
      ].filter(Boolean)
    ) : slots : t3.arrayExpression(children);
  } else if (children.length === 1) {
    const { enableObjectSlots = true } = state.opts;
    const child = children[0];
    const objectExpression4 = t3.objectExpression(
      [
        t3.objectProperty(
          t3.identifier("default"),
          t3.arrowFunctionExpression(
            [],
            t3.arrayExpression(buildIIFE(path, [child]))
          )
        ),
        optimize && t3.objectProperty(
          t3.identifier("_"),
          t3.numericLiteral(slotFlag)
        )
      ].filter(Boolean)
    );
    if (t3.isIdentifier(child) && isComponent) {
      VNodeChild = enableObjectSlots ? t3.conditionalExpression(
        t3.callExpression(
          state.get("@vue/babel-plugin-jsx/runtimeIsSlot")(),
          [child]
        ),
        child,
        objectExpression4
      ) : objectExpression4;
    } else if (t3.isCallExpression(child) && child.loc && isComponent) {
      if (enableObjectSlots) {
        const { scope } = path;
        const slotId = scope.generateUidIdentifier("slot");
        if (scope) {
          scope.push({
            id: slotId,
            kind: "let"
          });
        }
        const alternate = t3.objectExpression(
          [
            t3.objectProperty(
              t3.identifier("default"),
              t3.arrowFunctionExpression(
                [],
                t3.arrayExpression(buildIIFE(path, [slotId]))
              )
            ),
            optimize && t3.objectProperty(
              t3.identifier("_"),
              t3.numericLiteral(slotFlag)
            )
          ].filter(Boolean)
        );
        const assignment = t3.assignmentExpression("=", slotId, child);
        const condition = t3.callExpression(
          state.get("@vue/babel-plugin-jsx/runtimeIsSlot")(),
          [assignment]
        );
        VNodeChild = t3.conditionalExpression(condition, slotId, alternate);
      } else {
        VNodeChild = objectExpression4;
      }
    } else if (t3.isFunctionExpression(child) || t3.isArrowFunctionExpression(child)) {
      VNodeChild = t3.objectExpression([
        t3.objectProperty(t3.identifier("default"), child)
      ]);
    } else if (t3.isObjectExpression(child)) {
      VNodeChild = t3.objectExpression(
        [
          ...child.properties,
          optimize && t3.objectProperty(t3.identifier("_"), t3.numericLiteral(slotFlag))
        ].filter(Boolean)
      );
    } else {
      VNodeChild = isComponent ? t3.objectExpression([
        t3.objectProperty(
          t3.identifier("default"),
          t3.arrowFunctionExpression([], t3.arrayExpression([child]))
        )
      ]) : t3.arrayExpression([child]);
    }
  }
  const createVNode = t3.callExpression(
    createIdentifier(state, "createVNode"),
    [
      tag,
      props,
      VNodeChild || t3.nullLiteral(),
      !!patchFlag && optimize && t3.numericLiteral(patchFlag),
      !!dynamicPropNames.size && optimize && t3.arrayExpression(
        [...dynamicPropNames.keys()].map((name) => t3.stringLiteral(name))
      )
    ].filter(Boolean)
  );
  if (!directives.length) {
    return createVNode;
  }
  return t3.callExpression(createIdentifier(state, "withDirectives"), [
    createVNode,
    t3.arrayExpression(directives)
  ]);
};
var visitor = {
  JSXElement: {
    exit(path, state) {
      path.replaceWith(transformJSXElement(path, state));
    }
  }
};
var transform_vue_jsx_default = visitor;

// src/sugar-fragment.ts
var t4 = __toESM(require("@babel/types"));
var transformFragment = (path, Fragment) => {
  const children = path.get("children") || [];
  return t4.jsxElement(
    t4.jsxOpeningElement(Fragment, []),
    t4.jsxClosingElement(Fragment),
    children.map(({ node }) => node),
    false
  );
};
var visitor2 = {
  JSXFragment: {
    enter(path, state) {
      const fragmentCallee = createIdentifier(state, FRAGMENT);
      path.replaceWith(
        transformFragment(
          path,
          t4.isIdentifier(fragmentCallee) ? t4.jsxIdentifier(fragmentCallee.name) : t4.jsxMemberExpression(
            t4.jsxIdentifier(fragmentCallee.object.name),
            t4.jsxIdentifier(fragmentCallee.property.name)
          )
        )
      );
    }
  }
};
var sugar_fragment_default = visitor2;

// src/index.ts
var hasJSX = (parentPath) => {
  let fileHasJSX = false;
  parentPath.traverse({
    JSXElement(path) {
      fileHasJSX = true;
      path.stop();
    },
    JSXFragment(path) {
      fileHasJSX = true;
      path.stop();
    }
  });
  return fileHasJSX;
};
var JSX_ANNOTATION_REGEX = /\*?\s*@jsx\s+([^\s]+)/;
// @__NO_SIDE_EFFECTS__
function interopDefault(m) {
  return m.default || m;
}
var syntaxJsx = /* @__PURE__ */ interopDefault(import_plugin_syntax_jsx.default);
var template = /* @__PURE__ */ interopDefault(import_template.default);
var src_default = (0, import_helper_plugin_utils.declare)(
  (api, opt, dirname) => {
    const { types } = api;
    let resolveType;
    if (opt.resolveType) {
      if (typeof opt.resolveType === "boolean")
        opt.resolveType = {};
      resolveType = (0, import_babel_plugin_resolve_type.default)(api, opt.resolveType, dirname);
    }
    return __spreadProps(__spreadValues({}, resolveType || {}), {
      name: "babel-plugin-jsx",
      inherits: /* @__PURE__ */ interopDefault(syntaxJsx),
      visitor: __spreadProps(__spreadValues(__spreadValues(__spreadValues({}, resolveType == null ? void 0 : resolveType.visitor), transform_vue_jsx_default), sugar_fragment_default), {
        Program: {
          enter(path, state) {
            if (hasJSX(path)) {
              const importNames = [
                "createVNode",
                "Fragment",
                "resolveComponent",
                "withDirectives",
                "vShow",
                "vModelSelect",
                "vModelText",
                "vModelCheckbox",
                "vModelRadio",
                "vModelText",
                "vModelDynamic",
                "resolveDirective",
                "mergeProps",
                "createTextVNode",
                "isVNode"
              ];
              if ((0, import_helper_module_imports2.isModule)(path)) {
                const importMap = {};
                importNames.forEach((name) => {
                  state.set(name, () => {
                    if (importMap[name]) {
                      return types.cloneNode(importMap[name]);
                    }
                    const identifier5 = (0, import_helper_module_imports2.addNamed)(path, name, "vue", {
                      ensureLiveReference: true
                    });
                    importMap[name] = identifier5;
                    return identifier5;
                  });
                });
                const { enableObjectSlots = true } = state.opts;
                if (enableObjectSlots) {
                  state.set("@vue/babel-plugin-jsx/runtimeIsSlot", () => {
                    if (importMap.runtimeIsSlot) {
                      return importMap.runtimeIsSlot;
                    }
                    const { name: isVNodeName } = state.get(
                      "isVNode"
                    )();
                    const isSlot = path.scope.generateUidIdentifier("isSlot");
                    const ast = template.ast`
                    function ${isSlot.name}(s) {
                      return typeof s === 'function' || (Object.prototype.toString.call(s) === '[object Object]' && !${isVNodeName}(s));
                    }
                  `;
                    const lastImport = path.get("body").filter((p) => p.isImportDeclaration()).pop();
                    if (lastImport) {
                      lastImport.insertAfter(ast);
                    }
                    importMap.runtimeIsSlot = isSlot;
                    return isSlot;
                  });
                }
              } else {
                let sourceName;
                importNames.forEach((name) => {
                  state.set(name, () => {
                    if (!sourceName) {
                      sourceName = (0, import_helper_module_imports2.addNamespace)(path, "vue", {
                        ensureLiveReference: true
                      });
                    }
                    return t5.memberExpression(sourceName, t5.identifier(name));
                  });
                });
                const helpers = {};
                const { enableObjectSlots = true } = state.opts;
                if (enableObjectSlots) {
                  state.set("@vue/babel-plugin-jsx/runtimeIsSlot", () => {
                    if (helpers.runtimeIsSlot) {
                      return helpers.runtimeIsSlot;
                    }
                    const isSlot = path.scope.generateUidIdentifier("isSlot");
                    const { object: objectName } = state.get(
                      "isVNode"
                    )();
                    const ast = template.ast`
                    function ${isSlot.name}(s) {
                      return typeof s === 'function' || (Object.prototype.toString.call(s) === '[object Object]' && !${objectName.name}.isVNode(s));
                    }
                  `;
                    const nodePaths = path.get("body");
                    const lastImport = nodePaths.filter(
                      (p) => p.isVariableDeclaration() && p.node.declarations.some(
                        (d) => {
                          var _a;
                          return ((_a = d.id) == null ? void 0 : _a.name) === sourceName.name;
                        }
                      )
                    ).pop();
                    if (lastImport) {
                      lastImport.insertAfter(ast);
                    }
                    return isSlot;
                  });
                }
              }
              const {
                opts: { pragma = "" },
                file
              } = state;
              if (pragma) {
                state.set("createVNode", () => t5.identifier(pragma));
              }
              if (file.ast.comments) {
                for (const comment of file.ast.comments) {
                  const jsxMatches = JSX_ANNOTATION_REGEX.exec(comment.value);
                  if (jsxMatches) {
                    state.set("createVNode", () => t5.identifier(jsxMatches[1]));
                  }
                }
              }
            }
          },
          exit(path) {
            const body = path.get("body");
            const specifiersMap = /* @__PURE__ */ new Map();
            body.filter(
              (nodePath) => t5.isImportDeclaration(nodePath.node) && nodePath.node.source.value === "vue"
            ).forEach((nodePath) => {
              const { specifiers: specifiers2 } = nodePath.node;
              let shouldRemove = false;
              specifiers2.forEach((specifier) => {
                if (!specifier.loc && t5.isImportSpecifier(specifier) && t5.isIdentifier(specifier.imported)) {
                  specifiersMap.set(specifier.imported.name, specifier);
                  shouldRemove = true;
                }
              });
              if (shouldRemove) {
                nodePath.remove();
              }
            });
            const specifiers = [...specifiersMap.keys()].map(
              (imported) => specifiersMap.get(imported)
            );
            if (specifiers.length) {
              path.unshiftContainer(
                "body",
                t5.importDeclaration(specifiers, t5.stringLiteral("vue"))
              );
            }
          }
        }
      })
    });
  }
);