diff --git a/node_modules/micromark-extension-gfm-task-list-item/package.json b/node_modules/micromark-extension-gfm-task-list-item/package.json new file mode 100644 index 0000000000000000000000000000000000000000..bfc8bd51bfe86bf6ef8f9855e5c236d3dd3d18e9 --- /dev/null +++ b/node_modules/micromark-extension-gfm-task-list-item/package.json @@ -0,0 +1,131 @@ +{ + "name": "micromark-extension-gfm-task-list-item", + "version": "2.1.0", + "description": "micromark extension to support GFM task list items", + "license": "MIT", + "keywords": [ + "micromark", + "micromark-extension", + "task", + "list", + "item", + "check", + "checkbox", + "todo", + "gfm", + "markdown", + "unified" + ], + "repository": "micromark/micromark-extension-gfm-task-list-item", + "bugs": "https://github.com/micromark/micromark-extension-gfm-task-list-item/issues", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + }, + "author": "Titus Wormer (https://wooorm.com)", + "contributors": [ + "Titus Wormer (https://wooorm.com)" + ], + "sideEffects": false, + "type": "module", + "files": [ + "dev/", + "lib/", + "index.d.ts", + "index.js" + ], + "exports": { + "development": "./dev/index.js", + "default": "./index.js" + }, + "dependencies": { + "devlop": "^1.0.0", + "micromark-factory-space": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + }, + "devDependencies": { + "@types/node": "^20.0.0", + "c8": "^10.0.0", + "control-pictures": "^2.0.0", + "create-gfm-fixtures": "^1.0.0", + "micromark": "^4.0.0", + "micromark-build": "^2.0.0", + "prettier": "^3.0.0", + "remark-cli": "^12.0.0", + "remark-preset-wooorm": "^10.0.0", + "type-coverage": "^2.0.0", + "typescript": "^5.0.0", + "xo": "^0.58.0" + }, + "scripts": { + "prepack": "npm run build && npm run format", + "build": "tsc --build --clean && tsc --build && type-coverage && micromark-build", + "format": "remark . -qfo && prettier . -w --log-level warn && xo --fix", + "test-api-prod": "node --conditions production test/index.js", + "test-api-dev": "node --conditions development test/index.js", + "test-api": "npm run test-api-dev && npm run test-api-prod", + "test-coverage": "c8 --100 --reporter lcov npm run test-api", + "test": "npm run build && npm run format && npm run test-coverage" + }, + "prettier": { + "bracketSpacing": false, + "semi": false, + "singleQuote": true, + "tabWidth": 2, + "trailingComma": "none", + "useTabs": false + }, + "remarkConfig": { + "plugins": [ + "remark-preset-wooorm" + ] + }, + "typeCoverage": { + "atLeast": 100, + "detail": true, + "ignoreCatch": true, + "strict": true + }, + "xo": { + "prettier": true, + "rules": { + "unicorn/no-this-assignment": "off", + "unicorn/prefer-string-replace-all": "off" + }, + "overrides": [ + { + "files": [ + "**/*.d.ts" + ], + "rules": { + "@typescript-eslint/array-type": [ + "error", + { + "default": "generic" + } + ], + "@typescript-eslint/ban-types": [ + "error", + { + "extendDefaults": true + } + ], + "@typescript-eslint/consistent-type-definitions": [ + "error", + "interface" + ] + } + }, + { + "files": [ + "test/**/*.js" + ], + "rules": { + "no-await-in-loop": "off" + } + } + ] + } +} diff --git a/node_modules/micromark-extension-gfm-task-list-item/readme.md b/node_modules/micromark-extension-gfm-task-list-item/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..fd8ba964a85fb99ec2d994a1108aab412e2d08f2 --- /dev/null +++ b/node_modules/micromark-extension-gfm-task-list-item/readme.md @@ -0,0 +1,305 @@ +# micromark-extension-gfm-task-list-item + +[![Build][build-badge]][build] +[![Coverage][coverage-badge]][coverage] +[![Downloads][downloads-badge]][downloads] +[![Size][size-badge]][size] +[![Sponsors][sponsors-badge]][collective] +[![Backers][backers-badge]][collective] +[![Chat][chat-badge]][chat] + +[micromark][] extensions to support GFM [task list items][]. + +## Contents + +* [What is this?](#what-is-this) +* [When to use this](#when-to-use-this) +* [Install](#install) +* [Use](#use) +* [API](#api) + * [`gfmTaskListItem()`](#gfmtasklistitem) + * [`gfmTaskListItemHtml()`](#gfmtasklistitemhtml) +* [Authoring](#authoring) +* [HTML](#html) +* [CSS](#css) +* [Syntax](#syntax) +* [Types](#types) +* [Compatibility](#compatibility) +* [Security](#security) +* [Related](#related) +* [Contribute](#contribute) +* [License](#license) + +## What is this? + +This package contains extensions that add support for task lists as enabled by +GFM to [`micromark`][micromark]. +It matches how task list items work on `github.com`. + +## When to use this + +This project is useful when you want to support task lists in markdown. + +You can use these extensions when you are working with [`micromark`][micromark]. +To support all GFM features, use +[`micromark-extension-gfm`][micromark-extension-gfm]. + +When you need a syntax tree, you can combine this package with +[`mdast-util-gfm-task-list-item`][mdast-util-gfm-task-list-item]. + +All these packages are used [`remark-gfm`][remark-gfm], which focusses on making +it easier to transform content by abstracting these internals away. + +## Install + +This package is [ESM only][esm]. +In Node.js (version 16+), install with [npm][]: + +```sh +npm install micromark-extension-gfm-task-list-item +``` + +In Deno with [`esm.sh`][esmsh]: + +```js +import {gfmTaskListItem, gfmTaskListItemHtml} from 'https://esm.sh/micromark-extension-gfm-task-list-item@2' +``` + +In browsers with [`esm.sh`][esmsh]: + +```html + +``` + +## Use + +```js +import {micromark} from 'micromark' +import { + gfmTaskListItem, + gfmTaskListItemHtml +} from 'micromark-extension-gfm-task-list-item' + +const output = micromark('* [x] a\n* [ ] b', { + extensions: [gfmTaskListItem()], + htmlExtensions: [gfmTaskListItemHtml()] +}) + +console.log(output) +``` + +Yields: + +```html + +``` + +## API + +This package exports the identifiers [`gfmTaskListItem`][api-gfm-task-list-item] +and [`gfmTaskListItemHtml`][api-gfm-task-list-item-html]. +There is no default export. + +The export map supports the [`development` condition][development]. +Run `node --conditions development module.js` to get instrumented dev code. +Without this condition, production code is loaded. + +### `gfmTaskListItem()` + +Create an HTML extension for `micromark` to support GFM task list items +syntax. + +###### Returns + +Extension for `micromark` that can be passed in `extensions`, to enable GFM +task list items syntax ([`Extension`][micromark-extension]). + +### `gfmTaskListItemHtml()` + +Create an HTML extension for `micromark` to support GFM task list items when +serializing to HTML. + +###### Returns + +Extension for `micromark` that can be passed in `htmlExtensions` to support GFM +task list items when serializing to HTML +([`HtmlExtension`][micromark-html-extension]). + +## Authoring + +It is recommended to use lowercase `x` (instead of uppercase `X`), because in +markdown, it is more common to use lowercase in places where casing does not +matter. +It is also recommended to use a space (instead of a tab), as there is no benefit +of using tabs in this case. + +## HTML + +Checks relate to the `` element, in the checkbox state (`type=checkbox`), +in HTML. +See [*§ 4.10.5.1.15 Checkbox state (`type=checkbox`)*][html-input-checkbox] +in the HTML spec for more info. + +```html + +
  • foo
  • +
  • bar
  • + +``` + +## CSS + +GitHub itself uses slightly different markup for task list items than they +define in their spec. +When following the spec, as this extension does, only inputs are added. +They can be styled with the following CSS: + +```css +input[type="checkbox"] { + margin: 0 .2em .25em -1.6em; + vertical-align: middle; +} + +input[type="checkbox"]:dir(rtl) { + margin: 0 -1.6em .25em .2em; +} +``` + +For the complete actual CSS see +[`sindresorhus/github-markdown-css`][github-markdown-css]. + +## Syntax + +Checks form with the following BNF: + +```bnf +gfm_task_list_item_check ::= '[' (0x09 | ' ' | 'X' | 'x') ']' +``` + +The check is only allowed at the start of the first paragraph, optionally +following zero or more definitions or a blank line, in a list item. +The check must be followed by whitespace (`[\t\n\r ]*`), which is in turn +followed by non-whitespace. + +## Types + +This package is fully typed with [TypeScript][]. +It exports no additional types. + +## Compatibility + +Projects maintained by the unified collective are compatible with maintained +versions of Node.js. + +When we cut a new major release, we drop support for unmaintained versions of +Node. +This means we try to keep the current release line, +`micromark-extension-gfm-task-list-item@^2`, compatible with Node.js 16. + +This package works with `micromark` version `3` and later. + +## Security + +This package is safe. + +## Related + +* [`micromark-extension-gfm`][micromark-extension-gfm] + — support all of GFM +* [`mdast-util-gfm-task-list-item`][mdast-util-gfm-task-list-item] + — support all of GFM in mdast +* [`mdast-util-gfm`][mdast-util-gfm] + — support all of GFM in mdast +* [`remark-gfm`][remark-gfm] + — support all of GFM in remark + +## Contribute + +See [`contributing.md` in `micromark/.github`][contributing] for ways to get +started. +See [`support.md`][support] for ways to get help. + +This project has a [code of conduct][coc]. +By interacting with this repository, organization, or community you agree to +abide by its terms. + +## License + +[MIT][license] © [Titus Wormer][author] + + + +[build-badge]: https://github.com/micromark/micromark-extension-gfm-task-list-item/workflows/main/badge.svg + +[build]: https://github.com/micromark/micromark-extension-gfm-task-list-item/actions + +[coverage-badge]: https://img.shields.io/codecov/c/github/micromark/micromark-extension-gfm-task-list-item.svg + +[coverage]: https://codecov.io/github/micromark/micromark-extension-gfm-task-list-item + +[downloads-badge]: https://img.shields.io/npm/dm/micromark-extension-gfm-task-list-item.svg + +[downloads]: https://www.npmjs.com/package/micromark-extension-gfm-task-list-item + +[size-badge]: https://img.shields.io/badge/dynamic/json?label=minzipped%20size&query=$.size.compressedSize&url=https://deno.bundlejs.com/?q=micromark-extension-gfm-task-list-item + +[size]: https://bundlejs.com/?q=micromark-extension-gfm-task-list-item + +[sponsors-badge]: https://opencollective.com/unified/sponsors/badge.svg + +[backers-badge]: https://opencollective.com/unified/backers/badge.svg + +[collective]: https://opencollective.com/unified + +[chat-badge]: https://img.shields.io/badge/chat-discussions-success.svg + +[chat]: https://github.com/micromark/micromark/discussions + +[npm]: https://docs.npmjs.com/cli/install + +[esmsh]: https://esm.sh + +[license]: license + +[author]: https://wooorm.com + +[contributing]: https://github.com/micromark/.github/blob/main/contributing.md + +[support]: https://github.com/micromark/.github/blob/main/support.md + +[coc]: https://github.com/micromark/.github/blob/main/code-of-conduct.md + +[esm]: https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c + +[typescript]: https://www.typescriptlang.org + +[development]: https://nodejs.org/api/packages.html#packages_resolving_user_conditions + +[micromark]: https://github.com/micromark/micromark + +[micromark-html-extension]: https://github.com/micromark/micromark#htmlextension + +[micromark-extension]: https://github.com/micromark/micromark#syntaxextension + +[micromark-extension-gfm]: https://github.com/micromark/micromark-extension-gfm + +[mdast-util-gfm-task-list-item]: https://github.com/syntax-tree/mdast-util-gfm-task-list-item + +[mdast-util-gfm]: https://github.com/syntax-tree/mdast-util-gfm + +[remark-gfm]: https://github.com/remarkjs/remark-gfm + +[task list items]: https://github.github.com/gfm/#task-list-items-extension- + +[github-markdown-css]: https://github.com/sindresorhus/github-markdown-css + +[html-input-checkbox]: https://html.spec.whatwg.org/multipage/input.html#checkbox-state-\(type=checkbox\) + +[api-gfm-task-list-item]: #gfmtasklistitem + +[api-gfm-task-list-item-html]: #gfmtasklistitemhtml diff --git a/node_modules/micromark-factory-destination/dev/index.d.ts b/node_modules/micromark-factory-destination/dev/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1d5e02a5d8ed065a2fc82e15e7e16aad882a5cc3 --- /dev/null +++ b/node_modules/micromark-factory-destination/dev/index.d.ts @@ -0,0 +1,42 @@ +/** + * Parse destinations. + * + * ###### Examples + * + * ```markdown + * + * b> + * + * + * a + * a\)b + * a(b)c + * a(b) + * ``` + * + * @param {Effects} effects + * Context. + * @param {State} ok + * State switched to when successful. + * @param {State} nok + * State switched to when unsuccessful. + * @param {TokenType} type + * Type for whole (`` or `b`). + * @param {TokenType} literalType + * Type when enclosed (``). + * @param {TokenType} literalMarkerType + * Type for enclosing (`<` and `>`). + * @param {TokenType} rawType + * Type when not enclosed (`b`). + * @param {TokenType} stringType + * Type for the value (`a` or `b`). + * @param {number | undefined} [max=Infinity] + * Depth of nested parens (inclusive). + * @returns {State} + * Start state. + */ +export function factoryDestination(effects: Effects, ok: State, nok: State, type: TokenType, literalType: TokenType, literalMarkerType: TokenType, rawType: TokenType, stringType: TokenType, max?: number | undefined): State; +import type { Effects } from 'micromark-util-types'; +import type { State } from 'micromark-util-types'; +import type { TokenType } from 'micromark-util-types'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/micromark-factory-destination/dev/index.d.ts.map b/node_modules/micromark-factory-destination/dev/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..84746ee217e2447f8842e07224b3893e657147b5 --- /dev/null +++ b/node_modules/micromark-factory-destination/dev/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.js"],"names":[],"mappings":"AAWA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;AACH,4CArBW,OAAO,MAEP,KAAK,OAEL,KAAK,QAEL,SAAS,eAET,SAAS,qBAET,SAAS,WAET,SAAS,cAET,SAAS,QAET,MAAM,GAAG,SAAS,GAEhB,KAAK,CAiNjB;6BA7P2C,sBAAsB;2BAAtB,sBAAsB;+BAAtB,sBAAsB"} \ No newline at end of file diff --git a/node_modules/micromark-factory-destination/dev/index.js b/node_modules/micromark-factory-destination/dev/index.js new file mode 100644 index 0000000000000000000000000000000000000000..a4816fdc0dd5d7ee19170a8c09acd4ce3d60831e --- /dev/null +++ b/node_modules/micromark-factory-destination/dev/index.js @@ -0,0 +1,255 @@ +/** + * @import {Effects, State, TokenType} from 'micromark-util-types' + */ + +import { + asciiControl, + markdownLineEndingOrSpace, + markdownLineEnding +} from 'micromark-util-character' +import {codes, constants, types} from 'micromark-util-symbol' + +/** + * Parse destinations. + * + * ###### Examples + * + * ```markdown + * + * b> + * + * + * a + * a\)b + * a(b)c + * a(b) + * ``` + * + * @param {Effects} effects + * Context. + * @param {State} ok + * State switched to when successful. + * @param {State} nok + * State switched to when unsuccessful. + * @param {TokenType} type + * Type for whole (`` or `b`). + * @param {TokenType} literalType + * Type when enclosed (``). + * @param {TokenType} literalMarkerType + * Type for enclosing (`<` and `>`). + * @param {TokenType} rawType + * Type when not enclosed (`b`). + * @param {TokenType} stringType + * Type for the value (`a` or `b`). + * @param {number | undefined} [max=Infinity] + * Depth of nested parens (inclusive). + * @returns {State} + * Start state. + */ +export function factoryDestination( + effects, + ok, + nok, + type, + literalType, + literalMarkerType, + rawType, + stringType, + max +) { + const limit = max || Number.POSITIVE_INFINITY + let balance = 0 + + return start + + /** + * Start of destination. + * + * ```markdown + * > | + * ^ + * > | aa + * ^ + * ``` + * + * @type {State} + */ + function start(code) { + if (code === codes.lessThan) { + effects.enter(type) + effects.enter(literalType) + effects.enter(literalMarkerType) + effects.consume(code) + effects.exit(literalMarkerType) + return enclosedBefore + } + + // ASCII control, space, closing paren. + if ( + code === codes.eof || + code === codes.space || + code === codes.rightParenthesis || + asciiControl(code) + ) { + return nok(code) + } + + effects.enter(type) + effects.enter(rawType) + effects.enter(stringType) + effects.enter(types.chunkString, {contentType: constants.contentTypeString}) + return raw(code) + } + + /** + * After `<`, at an enclosed destination. + * + * ```markdown + * > | + * ^ + * ``` + * + * @type {State} + */ + function enclosedBefore(code) { + if (code === codes.greaterThan) { + effects.enter(literalMarkerType) + effects.consume(code) + effects.exit(literalMarkerType) + effects.exit(literalType) + effects.exit(type) + return ok + } + + effects.enter(stringType) + effects.enter(types.chunkString, {contentType: constants.contentTypeString}) + return enclosed(code) + } + + /** + * In enclosed destination. + * + * ```markdown + * > | + * ^ + * ``` + * + * @type {State} + */ + function enclosed(code) { + if (code === codes.greaterThan) { + effects.exit(types.chunkString) + effects.exit(stringType) + return enclosedBefore(code) + } + + if ( + code === codes.eof || + code === codes.lessThan || + markdownLineEnding(code) + ) { + return nok(code) + } + + effects.consume(code) + return code === codes.backslash ? enclosedEscape : enclosed + } + + /** + * After `\`, at a special character. + * + * ```markdown + * > | + * ^ + * ``` + * + * @type {State} + */ + function enclosedEscape(code) { + if ( + code === codes.lessThan || + code === codes.greaterThan || + code === codes.backslash + ) { + effects.consume(code) + return enclosed + } + + return enclosed(code) + } + + /** + * In raw destination. + * + * ```markdown + * > | aa + * ^ + * ``` + * + * @type {State} + */ + function raw(code) { + if ( + !balance && + (code === codes.eof || + code === codes.rightParenthesis || + markdownLineEndingOrSpace(code)) + ) { + effects.exit(types.chunkString) + effects.exit(stringType) + effects.exit(rawType) + effects.exit(type) + return ok(code) + } + + if (balance < limit && code === codes.leftParenthesis) { + effects.consume(code) + balance++ + return raw + } + + if (code === codes.rightParenthesis) { + effects.consume(code) + balance-- + return raw + } + + // ASCII control (but *not* `\0`) and space and `(`. + // Note: in `markdown-rs`, `\0` exists in codes, in `micromark-js` it + // doesn’t. + if ( + code === codes.eof || + code === codes.space || + code === codes.leftParenthesis || + asciiControl(code) + ) { + return nok(code) + } + + effects.consume(code) + return code === codes.backslash ? rawEscape : raw + } + + /** + * After `\`, at special character. + * + * ```markdown + * > | a\*a + * ^ + * ``` + * + * @type {State} + */ + function rawEscape(code) { + if ( + code === codes.leftParenthesis || + code === codes.rightParenthesis || + code === codes.backslash + ) { + effects.consume(code) + return raw + } + + return raw(code) + } +} diff --git a/node_modules/micromark-factory-destination/index.d.ts b/node_modules/micromark-factory-destination/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1d5e02a5d8ed065a2fc82e15e7e16aad882a5cc3 --- /dev/null +++ b/node_modules/micromark-factory-destination/index.d.ts @@ -0,0 +1,42 @@ +/** + * Parse destinations. + * + * ###### Examples + * + * ```markdown + * + * b> + * + * + * a + * a\)b + * a(b)c + * a(b) + * ``` + * + * @param {Effects} effects + * Context. + * @param {State} ok + * State switched to when successful. + * @param {State} nok + * State switched to when unsuccessful. + * @param {TokenType} type + * Type for whole (`` or `b`). + * @param {TokenType} literalType + * Type when enclosed (``). + * @param {TokenType} literalMarkerType + * Type for enclosing (`<` and `>`). + * @param {TokenType} rawType + * Type when not enclosed (`b`). + * @param {TokenType} stringType + * Type for the value (`a` or `b`). + * @param {number | undefined} [max=Infinity] + * Depth of nested parens (inclusive). + * @returns {State} + * Start state. + */ +export function factoryDestination(effects: Effects, ok: State, nok: State, type: TokenType, literalType: TokenType, literalMarkerType: TokenType, rawType: TokenType, stringType: TokenType, max?: number | undefined): State; +import type { Effects } from 'micromark-util-types'; +import type { State } from 'micromark-util-types'; +import type { TokenType } from 'micromark-util-types'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/micromark-factory-destination/index.d.ts.map b/node_modules/micromark-factory-destination/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..84746ee217e2447f8842e07224b3893e657147b5 --- /dev/null +++ b/node_modules/micromark-factory-destination/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.js"],"names":[],"mappings":"AAWA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;AACH,4CArBW,OAAO,MAEP,KAAK,OAEL,KAAK,QAEL,SAAS,eAET,SAAS,qBAET,SAAS,WAET,SAAS,cAET,SAAS,QAET,MAAM,GAAG,SAAS,GAEhB,KAAK,CAiNjB;6BA7P2C,sBAAsB;2BAAtB,sBAAsB;+BAAtB,sBAAsB"} \ No newline at end of file diff --git a/node_modules/micromark-factory-destination/index.js b/node_modules/micromark-factory-destination/index.js new file mode 100644 index 0000000000000000000000000000000000000000..eeb60de6d7fcb60021f6290acc7045854bc04ec7 --- /dev/null +++ b/node_modules/micromark-factory-destination/index.js @@ -0,0 +1,206 @@ +/** + * @import {Effects, State, TokenType} from 'micromark-util-types' + */ + +import { asciiControl, markdownLineEndingOrSpace, markdownLineEnding } from 'micromark-util-character'; +/** + * Parse destinations. + * + * ###### Examples + * + * ```markdown + * + * b> + * + * + * a + * a\)b + * a(b)c + * a(b) + * ``` + * + * @param {Effects} effects + * Context. + * @param {State} ok + * State switched to when successful. + * @param {State} nok + * State switched to when unsuccessful. + * @param {TokenType} type + * Type for whole (`` or `b`). + * @param {TokenType} literalType + * Type when enclosed (``). + * @param {TokenType} literalMarkerType + * Type for enclosing (`<` and `>`). + * @param {TokenType} rawType + * Type when not enclosed (`b`). + * @param {TokenType} stringType + * Type for the value (`a` or `b`). + * @param {number | undefined} [max=Infinity] + * Depth of nested parens (inclusive). + * @returns {State} + * Start state. + */ +export function factoryDestination(effects, ok, nok, type, literalType, literalMarkerType, rawType, stringType, max) { + const limit = max || Number.POSITIVE_INFINITY; + let balance = 0; + return start; + + /** + * Start of destination. + * + * ```markdown + * > | + * ^ + * > | aa + * ^ + * ``` + * + * @type {State} + */ + function start(code) { + if (code === 60) { + effects.enter(type); + effects.enter(literalType); + effects.enter(literalMarkerType); + effects.consume(code); + effects.exit(literalMarkerType); + return enclosedBefore; + } + + // ASCII control, space, closing paren. + if (code === null || code === 32 || code === 41 || asciiControl(code)) { + return nok(code); + } + effects.enter(type); + effects.enter(rawType); + effects.enter(stringType); + effects.enter("chunkString", { + contentType: "string" + }); + return raw(code); + } + + /** + * After `<`, at an enclosed destination. + * + * ```markdown + * > | + * ^ + * ``` + * + * @type {State} + */ + function enclosedBefore(code) { + if (code === 62) { + effects.enter(literalMarkerType); + effects.consume(code); + effects.exit(literalMarkerType); + effects.exit(literalType); + effects.exit(type); + return ok; + } + effects.enter(stringType); + effects.enter("chunkString", { + contentType: "string" + }); + return enclosed(code); + } + + /** + * In enclosed destination. + * + * ```markdown + * > | + * ^ + * ``` + * + * @type {State} + */ + function enclosed(code) { + if (code === 62) { + effects.exit("chunkString"); + effects.exit(stringType); + return enclosedBefore(code); + } + if (code === null || code === 60 || markdownLineEnding(code)) { + return nok(code); + } + effects.consume(code); + return code === 92 ? enclosedEscape : enclosed; + } + + /** + * After `\`, at a special character. + * + * ```markdown + * > | + * ^ + * ``` + * + * @type {State} + */ + function enclosedEscape(code) { + if (code === 60 || code === 62 || code === 92) { + effects.consume(code); + return enclosed; + } + return enclosed(code); + } + + /** + * In raw destination. + * + * ```markdown + * > | aa + * ^ + * ``` + * + * @type {State} + */ + function raw(code) { + if (!balance && (code === null || code === 41 || markdownLineEndingOrSpace(code))) { + effects.exit("chunkString"); + effects.exit(stringType); + effects.exit(rawType); + effects.exit(type); + return ok(code); + } + if (balance < limit && code === 40) { + effects.consume(code); + balance++; + return raw; + } + if (code === 41) { + effects.consume(code); + balance--; + return raw; + } + + // ASCII control (but *not* `\0`) and space and `(`. + // Note: in `markdown-rs`, `\0` exists in codes, in `micromark-js` it + // doesn’t. + if (code === null || code === 32 || code === 40 || asciiControl(code)) { + return nok(code); + } + effects.consume(code); + return code === 92 ? rawEscape : raw; + } + + /** + * After `\`, at special character. + * + * ```markdown + * > | a\*a + * ^ + * ``` + * + * @type {State} + */ + function rawEscape(code) { + if (code === 40 || code === 41 || code === 92) { + effects.consume(code); + return raw; + } + return raw(code); + } +} \ No newline at end of file diff --git a/node_modules/micromark-factory-destination/license b/node_modules/micromark-factory-destination/license new file mode 100644 index 0000000000000000000000000000000000000000..bc8f165a62768a19de38901d81ac662c51ff29db --- /dev/null +++ b/node_modules/micromark-factory-destination/license @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) Titus Wormer + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/micromark-factory-destination/package.json b/node_modules/micromark-factory-destination/package.json new file mode 100644 index 0000000000000000000000000000000000000000..0863cb696dc99a83fdb4bbd95fcc769119f66b0f --- /dev/null +++ b/node_modules/micromark-factory-destination/package.json @@ -0,0 +1,57 @@ +{ + "name": "micromark-factory-destination", + "version": "2.0.1", + "description": "micromark factory to parse destinations (found in resources, definitions)", + "license": "MIT", + "keywords": [ + "micromark", + "factory", + "destination" + ], + "repository": "https://github.com/micromark/micromark/tree/main/packages/micromark-factory-destination", + "bugs": "https://github.com/micromark/micromark/issues", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "author": "Titus Wormer (https://wooorm.com)", + "contributors": [ + "Titus Wormer (https://wooorm.com)" + ], + "sideEffects": false, + "type": "module", + "files": [ + "dev/", + "index.d.ts.map", + "index.d.ts", + "index.js" + ], + "exports": { + "development": "./dev/index.js", + "default": "./index.js" + }, + "dependencies": { + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + }, + "scripts": { + "build": "micromark-build" + }, + "xo": { + "envs": [ + "shared-node-browser" + ], + "prettier": true, + "rules": { + "max-params": "off", + "unicorn/prefer-code-point": "off" + } + } +} diff --git a/node_modules/micromark-factory-destination/readme.md b/node_modules/micromark-factory-destination/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..f4899d74da5534f3467da929dfe1a94414cf2e8f --- /dev/null +++ b/node_modules/micromark-factory-destination/readme.md @@ -0,0 +1,234 @@ +# micromark-factory-destination + +[![Build][build-badge]][build] +[![Coverage][coverage-badge]][coverage] +[![Downloads][downloads-badge]][downloads] +[![Size][bundle-size-badge]][bundle-size] +[![Sponsors][sponsors-badge]][opencollective] +[![Backers][backers-badge]][opencollective] +[![Chat][chat-badge]][chat] + +[micromark][] factory to parse destinations (found in resources, definitions). + +## Contents + +* [What is this?](#what-is-this) +* [When should I use this?](#when-should-i-use-this) +* [Install](#install) +* [Use](#use) +* [API](#api) + * [`factoryDestination(…)`](#factorydestination) +* [Types](#types) +* [Compatibility](#compatibility) +* [Security](#security) +* [Contribute](#contribute) +* [License](#license) + +## What is this? + +This package exposes states to parse destinations. + +## When should I use this? + +This package is useful when you are making your own micromark extensions. + +## Install + +This package is [ESM only][esm]. +In Node.js (version 16+), install with [npm][]: + +```sh +npm install micromark-factory-destination +``` + +In Deno with [`esm.sh`][esmsh]: + +```js +import {factoryDestination} from 'https://esm.sh/micromark-factory-destination@1' +``` + +In browsers with [`esm.sh`][esmsh]: + +```html + +``` + +## Use + +```js +import {factoryDestination} from 'micromark-factory-destination' +import {codes, types} from 'micromark-util-symbol' + +// A micromark tokenizer that uses the factory: +/** + * @this {TokenizeContext} + * Context. + * @type {Tokenizer} + */ +function tokenizeResource(effects, ok, nok) { + return start + + // … + + /** @type {State} */ + function open(code) { + if (code === codes.rightParenthesis) { + return end(code) + } + + return factoryDestination( + effects, + destinationAfter, + nok, + types.resourceDestination, + types.resourceDestinationLiteral, + types.resourceDestinationLiteralMarker, + types.resourceDestinationRaw, + types.resourceDestinationString, + constants.linkResourceDestinationBalanceMax + )(code) + } + + // … +} +``` + +## API + +This module exports the identifier +[`factoryDestination`][api-factory-destination]. +There is no default export. + +### `factoryDestination(…)` + +Parse destinations. + +###### Examples + +```markdown + +b> + + +a +a\)b +a(b)c +a(b) +``` + +###### Parameters + +* `effects` (`Effects`) + — context +* `ok` (`State`) + — state switched to when successful +* `nok` (`State`) + — state switched to when unsuccessful +* `type` (`string`) + — type for whole (`` or `b`) +* `literalType` (`string`) + — type when enclosed (``) +* `literalMarkerType` (`string`) + — type for enclosing (`<` and `>`) +* `rawType` (`string`) + — type when not enclosed (`b`) +* `stringType` (`string`) + — type for the value (`a` or `b`) +* `max` (`number`, default: `Infinity`) + — depth of nested parens (inclusive) + +###### Returns + +Start state (`State`). + +## Types + +This package is fully typed with [TypeScript][]. +It exports no additional types. + +## Compatibility + +Projects maintained by the unified collective are compatible with maintained +versions of Node.js. + +When we cut a new major release, we drop support for unmaintained versions of +Node. +This means we try to keep the current release line, +`micromark-factory-destination@2`, compatible with Node.js 16. +This package works with `micromark@3`. + +## Security + +This package is safe. +See [`security.md`][securitymd] in [`micromark/.github`][health] for how to +submit a security report. + +## Contribute + +See [`contributing.md`][contributing] in [`micromark/.github`][health] for ways +to get started. +See [`support.md`][support] for ways to get help. + +This project has a [code of conduct][coc]. +By interacting with this repository, organisation, or community you agree to +abide by its terms. + +## License + +[MIT][license] © [Titus Wormer][author] + + + +[build-badge]: https://github.com/micromark/micromark/workflows/main/badge.svg + +[build]: https://github.com/micromark/micromark/actions + +[coverage-badge]: https://img.shields.io/codecov/c/github/micromark/micromark.svg + +[coverage]: https://codecov.io/github/micromark/micromark + +[downloads-badge]: https://img.shields.io/npm/dm/micromark-factory-destination.svg + +[downloads]: https://www.npmjs.com/package/micromark-factory-destination + +[bundle-size-badge]: https://img.shields.io/badge/dynamic/json?label=minzipped%20size&query=$.size.compressedSize&url=https://deno.bundlejs.com/?q=micromark-factory-destination + +[bundle-size]: https://bundlejs.com/?q=micromark-factory-destination + +[sponsors-badge]: https://opencollective.com/unified/sponsors/badge.svg + +[backers-badge]: https://opencollective.com/unified/backers/badge.svg + +[opencollective]: https://opencollective.com/unified + +[npm]: https://docs.npmjs.com/cli/install + +[esm]: https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c + +[esmsh]: https://esm.sh + +[chat-badge]: https://img.shields.io/badge/chat-discussions-success.svg + +[chat]: https://github.com/micromark/micromark/discussions + +[license]: https://github.com/micromark/micromark/blob/main/license + +[author]: https://wooorm.com + +[health]: https://github.com/micromark/.github + +[securitymd]: https://github.com/micromark/.github/blob/main/security.md + +[contributing]: https://github.com/micromark/.github/blob/main/contributing.md + +[support]: https://github.com/micromark/.github/blob/main/support.md + +[coc]: https://github.com/micromark/.github/blob/main/code-of-conduct.md + +[typescript]: https://www.typescriptlang.org + +[micromark]: https://github.com/micromark/micromark + +[api-factory-destination]: #factorydestination diff --git a/node_modules/micromark-factory-label/dev/index.d.ts b/node_modules/micromark-factory-label/dev/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..99f5bdad4208705c7d113ed649aadaba5ecec347 --- /dev/null +++ b/node_modules/micromark-factory-label/dev/index.d.ts @@ -0,0 +1,37 @@ +/** + * Parse labels. + * + * > 👉 **Note**: labels in markdown are capped at 999 characters in the string. + * + * ###### Examples + * + * ```markdown + * [a] + * [a + * b] + * [a\]b] + * ``` + * + * @this {TokenizeContext} + * Tokenize context. + * @param {Effects} effects + * Context. + * @param {State} ok + * State switched to when successful. + * @param {State} nok + * State switched to when unsuccessful. + * @param {TokenType} type + * Type of the whole label (`[a]`). + * @param {TokenType} markerType + * Type for the markers (`[` and `]`). + * @param {TokenType} stringType + * Type for the identifier (`a`). + * @returns {State} + * Start state. + */ +export function factoryLabel(this: TokenizeContext, effects: Effects, ok: State, nok: State, type: TokenType, markerType: TokenType, stringType: TokenType): State; +import type { Effects } from 'micromark-util-types'; +import type { State } from 'micromark-util-types'; +import type { TokenType } from 'micromark-util-types'; +import type { TokenizeContext } from 'micromark-util-types'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/micromark-factory-label/dev/index.d.ts.map b/node_modules/micromark-factory-label/dev/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..fe94eeea2d078425e41b8a60785511d169bdae74 --- /dev/null +++ b/node_modules/micromark-factory-label/dev/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.js"],"names":[],"mappings":"AAaA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,6DAfW,OAAO,MAEP,KAAK,OAEL,KAAK,QAEL,SAAS,cAET,SAAS,cAET,SAAS,GAEP,KAAK,CAkIjB;6BArKS,sBAAsB;2BAAtB,sBAAsB;+BAAtB,sBAAsB;qCAAtB,sBAAsB"} \ No newline at end of file diff --git a/node_modules/micromark-factory-label/dev/index.js b/node_modules/micromark-factory-label/dev/index.js new file mode 100644 index 0000000000000000000000000000000000000000..242f0ced9cfbe9a1a24cb5bf0b5c5f6ebd558a66 --- /dev/null +++ b/node_modules/micromark-factory-label/dev/index.js @@ -0,0 +1,172 @@ +/** + * @import { + * Effects, + * State, + * TokenizeContext, + * TokenType + * } from 'micromark-util-types' + */ + +import {ok as assert} from 'devlop' +import {markdownLineEnding, markdownSpace} from 'micromark-util-character' +import {codes, constants, types} from 'micromark-util-symbol' + +/** + * Parse labels. + * + * > 👉 **Note**: labels in markdown are capped at 999 characters in the string. + * + * ###### Examples + * + * ```markdown + * [a] + * [a + * b] + * [a\]b] + * ``` + * + * @this {TokenizeContext} + * Tokenize context. + * @param {Effects} effects + * Context. + * @param {State} ok + * State switched to when successful. + * @param {State} nok + * State switched to when unsuccessful. + * @param {TokenType} type + * Type of the whole label (`[a]`). + * @param {TokenType} markerType + * Type for the markers (`[` and `]`). + * @param {TokenType} stringType + * Type for the identifier (`a`). + * @returns {State} + * Start state. + */ +export function factoryLabel(effects, ok, nok, type, markerType, stringType) { + const self = this + let size = 0 + /** @type {boolean} */ + let seen + + return start + + /** + * Start of label. + * + * ```markdown + * > | [a] + * ^ + * ``` + * + * @type {State} + */ + function start(code) { + assert(code === codes.leftSquareBracket, 'expected `[`') + effects.enter(type) + effects.enter(markerType) + effects.consume(code) + effects.exit(markerType) + effects.enter(stringType) + return atBreak + } + + /** + * In label, at something, before something else. + * + * ```markdown + * > | [a] + * ^ + * ``` + * + * @type {State} + */ + function atBreak(code) { + if ( + size > constants.linkReferenceSizeMax || + code === codes.eof || + code === codes.leftSquareBracket || + (code === codes.rightSquareBracket && !seen) || + // To do: remove in the future once we’ve switched from + // `micromark-extension-footnote` to `micromark-extension-gfm-footnote`, + // which doesn’t need this. + // Hidden footnotes hook. + /* c8 ignore next 3 */ + (code === codes.caret && + !size && + '_hiddenFootnoteSupport' in self.parser.constructs) + ) { + return nok(code) + } + + if (code === codes.rightSquareBracket) { + effects.exit(stringType) + effects.enter(markerType) + effects.consume(code) + effects.exit(markerType) + effects.exit(type) + return ok + } + + // To do: indent? Link chunks and EOLs together? + if (markdownLineEnding(code)) { + effects.enter(types.lineEnding) + effects.consume(code) + effects.exit(types.lineEnding) + return atBreak + } + + effects.enter(types.chunkString, {contentType: constants.contentTypeString}) + return labelInside(code) + } + + /** + * In label, in text. + * + * ```markdown + * > | [a] + * ^ + * ``` + * + * @type {State} + */ + function labelInside(code) { + if ( + code === codes.eof || + code === codes.leftSquareBracket || + code === codes.rightSquareBracket || + markdownLineEnding(code) || + size++ > constants.linkReferenceSizeMax + ) { + effects.exit(types.chunkString) + return atBreak(code) + } + + effects.consume(code) + if (!seen) seen = !markdownSpace(code) + return code === codes.backslash ? labelEscape : labelInside + } + + /** + * After `\`, at a special character. + * + * ```markdown + * > | [a\*a] + * ^ + * ``` + * + * @type {State} + */ + function labelEscape(code) { + if ( + code === codes.leftSquareBracket || + code === codes.backslash || + code === codes.rightSquareBracket + ) { + effects.consume(code) + size++ + return labelInside + } + + return labelInside(code) + } +} diff --git a/node_modules/micromark-factory-label/index.d.ts b/node_modules/micromark-factory-label/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..99f5bdad4208705c7d113ed649aadaba5ecec347 --- /dev/null +++ b/node_modules/micromark-factory-label/index.d.ts @@ -0,0 +1,37 @@ +/** + * Parse labels. + * + * > 👉 **Note**: labels in markdown are capped at 999 characters in the string. + * + * ###### Examples + * + * ```markdown + * [a] + * [a + * b] + * [a\]b] + * ``` + * + * @this {TokenizeContext} + * Tokenize context. + * @param {Effects} effects + * Context. + * @param {State} ok + * State switched to when successful. + * @param {State} nok + * State switched to when unsuccessful. + * @param {TokenType} type + * Type of the whole label (`[a]`). + * @param {TokenType} markerType + * Type for the markers (`[` and `]`). + * @param {TokenType} stringType + * Type for the identifier (`a`). + * @returns {State} + * Start state. + */ +export function factoryLabel(this: TokenizeContext, effects: Effects, ok: State, nok: State, type: TokenType, markerType: TokenType, stringType: TokenType): State; +import type { Effects } from 'micromark-util-types'; +import type { State } from 'micromark-util-types'; +import type { TokenType } from 'micromark-util-types'; +import type { TokenizeContext } from 'micromark-util-types'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/micromark-factory-label/index.d.ts.map b/node_modules/micromark-factory-label/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..fe94eeea2d078425e41b8a60785511d169bdae74 --- /dev/null +++ b/node_modules/micromark-factory-label/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.js"],"names":[],"mappings":"AAaA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,6DAfW,OAAO,MAEP,KAAK,OAEL,KAAK,QAEL,SAAS,cAET,SAAS,cAET,SAAS,GAEP,KAAK,CAkIjB;6BArKS,sBAAsB;2BAAtB,sBAAsB;+BAAtB,sBAAsB;qCAAtB,sBAAsB"} \ No newline at end of file diff --git a/node_modules/micromark-factory-label/index.js b/node_modules/micromark-factory-label/index.js new file mode 100644 index 0000000000000000000000000000000000000000..269340bb85b5ac6297401457b9f6a4a75f13acd1 --- /dev/null +++ b/node_modules/micromark-factory-label/index.js @@ -0,0 +1,148 @@ +/** + * @import { + * Effects, + * State, + * TokenizeContext, + * TokenType + * } from 'micromark-util-types' + */ + +import { markdownLineEnding, markdownSpace } from 'micromark-util-character'; +/** + * Parse labels. + * + * > 👉 **Note**: labels in markdown are capped at 999 characters in the string. + * + * ###### Examples + * + * ```markdown + * [a] + * [a + * b] + * [a\]b] + * ``` + * + * @this {TokenizeContext} + * Tokenize context. + * @param {Effects} effects + * Context. + * @param {State} ok + * State switched to when successful. + * @param {State} nok + * State switched to when unsuccessful. + * @param {TokenType} type + * Type of the whole label (`[a]`). + * @param {TokenType} markerType + * Type for the markers (`[` and `]`). + * @param {TokenType} stringType + * Type for the identifier (`a`). + * @returns {State} + * Start state. + */ +export function factoryLabel(effects, ok, nok, type, markerType, stringType) { + const self = this; + let size = 0; + /** @type {boolean} */ + let seen; + return start; + + /** + * Start of label. + * + * ```markdown + * > | [a] + * ^ + * ``` + * + * @type {State} + */ + function start(code) { + effects.enter(type); + effects.enter(markerType); + effects.consume(code); + effects.exit(markerType); + effects.enter(stringType); + return atBreak; + } + + /** + * In label, at something, before something else. + * + * ```markdown + * > | [a] + * ^ + * ``` + * + * @type {State} + */ + function atBreak(code) { + if (size > 999 || code === null || code === 91 || code === 93 && !seen || + // To do: remove in the future once we’ve switched from + // `micromark-extension-footnote` to `micromark-extension-gfm-footnote`, + // which doesn’t need this. + // Hidden footnotes hook. + /* c8 ignore next 3 */ + code === 94 && !size && '_hiddenFootnoteSupport' in self.parser.constructs) { + return nok(code); + } + if (code === 93) { + effects.exit(stringType); + effects.enter(markerType); + effects.consume(code); + effects.exit(markerType); + effects.exit(type); + return ok; + } + + // To do: indent? Link chunks and EOLs together? + if (markdownLineEnding(code)) { + effects.enter("lineEnding"); + effects.consume(code); + effects.exit("lineEnding"); + return atBreak; + } + effects.enter("chunkString", { + contentType: "string" + }); + return labelInside(code); + } + + /** + * In label, in text. + * + * ```markdown + * > | [a] + * ^ + * ``` + * + * @type {State} + */ + function labelInside(code) { + if (code === null || code === 91 || code === 93 || markdownLineEnding(code) || size++ > 999) { + effects.exit("chunkString"); + return atBreak(code); + } + effects.consume(code); + if (!seen) seen = !markdownSpace(code); + return code === 92 ? labelEscape : labelInside; + } + + /** + * After `\`, at a special character. + * + * ```markdown + * > | [a\*a] + * ^ + * ``` + * + * @type {State} + */ + function labelEscape(code) { + if (code === 91 || code === 92 || code === 93) { + effects.consume(code); + size++; + return labelInside; + } + return labelInside(code); + } +} \ No newline at end of file diff --git a/node_modules/micromark-factory-label/license b/node_modules/micromark-factory-label/license new file mode 100644 index 0000000000000000000000000000000000000000..bc8f165a62768a19de38901d81ac662c51ff29db --- /dev/null +++ b/node_modules/micromark-factory-label/license @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) Titus Wormer + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/micromark-factory-label/package.json b/node_modules/micromark-factory-label/package.json new file mode 100644 index 0000000000000000000000000000000000000000..db6dca2650e71d2306089ba707433989d1fb33c0 --- /dev/null +++ b/node_modules/micromark-factory-label/package.json @@ -0,0 +1,60 @@ +{ + "name": "micromark-factory-label", + "version": "2.0.1", + "description": "micromark factory to parse labels (found in media, definitions)", + "license": "MIT", + "keywords": [ + "micromark", + "factory", + "label" + ], + "repository": "https://github.com/micromark/micromark/tree/main/packages/micromark-factory-label", + "bugs": "https://github.com/micromark/micromark/issues", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "author": "Titus Wormer (https://wooorm.com)", + "contributors": [ + "Titus Wormer (https://wooorm.com)" + ], + "sideEffects": false, + "type": "module", + "files": [ + "dev/", + "index.d.ts.map", + "index.d.ts", + "index.js" + ], + "exports": { + "development": "./dev/index.js", + "default": "./index.js" + }, + "dependencies": { + "devlop": "^1.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + }, + "scripts": { + "build": "micromark-build" + }, + "xo": { + "envs": [ + "shared-node-browser" + ], + "prettier": true, + "rules": { + "logical-assignment-operators": "off", + "max-params": "off", + "unicorn/no-this-assignment": "off", + "unicorn/prefer-code-point": "off" + } + } +} diff --git a/node_modules/micromark-factory-label/readme.md b/node_modules/micromark-factory-label/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..f4b4eab835f0d664296aaa217b4db65202d78c79 --- /dev/null +++ b/node_modules/micromark-factory-label/readme.md @@ -0,0 +1,224 @@ +# micromark-factory-label + +[![Build][build-badge]][build] +[![Coverage][coverage-badge]][coverage] +[![Downloads][downloads-badge]][downloads] +[![Size][bundle-size-badge]][bundle-size] +[![Sponsors][sponsors-badge]][opencollective] +[![Backers][backers-badge]][opencollective] +[![Chat][chat-badge]][chat] + +[micromark][] factory to parse labels (found in media, definitions). + +## Contents + +* [What is this?](#what-is-this) +* [When should I use this?](#when-should-i-use-this) +* [Install](#install) +* [Use](#use) +* [API](#api) + * [`factoryLabel(…)`](#factorylabel) +* [Types](#types) +* [Compatibility](#compatibility) +* [Security](#security) +* [Contribute](#contribute) +* [License](#license) + +## What is this? + +This package exposes states to parse labels. + +## When should I use this? + +This package is useful when you are making your own micromark extensions. + +## Install + +This package is [ESM only][esm]. +In Node.js (version 16+), install with [npm][]: + +```sh +npm install micromark-factory-label +``` + +In Deno with [`esm.sh`][esmsh]: + +```js +import {factoryLabel} from 'https://esm.sh/micromark-factory-label@1' +``` + +In browsers with [`esm.sh`][esmsh]: + +```html + +``` + +## Use + +```js +import {ok as assert} from 'devlop' +import {factoryLabel} from 'micromark-factory-label' +import {codes, types} from 'micromark-util-symbol' + +// A micromark tokenizer that uses the factory: +/** + * @this {TokenizeContext} + * Context. + * @type {Tokenizer} + */ +function tokenizeDefinition(effects, ok, nok) { + return start + + // … + + /** @type {State} */ + function start(code) { + assert(code === codes.leftSquareBracket, 'expected `[`') + effects.enter(types.definition) + return factoryLabel.call( + self, + effects, + labelAfter, + nok, + types.definitionLabel, + types.definitionLabelMarker, + types.definitionLabelString + )(code) + } + + // … +} +``` + +## API + +This module exports the identifier [`factoryLabel`][api-factory-label]. +There is no default export. + +### `factoryLabel(…)` + +Parse labels. + +> 👉 **Note**: labels in markdown are capped at 999 characters in the string. + +###### Examples + +```markdown +[a] +[a +b] +[a\]b] +``` + +###### Parameters + +* `this` (`TokenizeContext`) + — tokenize context +* `effects` (`Effects`) + — context +* `ok` (`State`) + — state switched to when successful +* `nok` (`State`) + — state switched to when unsuccessful +* `type` (`string`) + — type of the whole label (`[a]`) +* `markerType` (`string`) + — type for the markers (`[` and `]`) +* `stringType` (`string`) + — type for the identifier (`a`) + +###### Returns + +Start state (`State`). + +## Types + +This package is fully typed with [TypeScript][]. +It exports no additional types. + +## Compatibility + +Projects maintained by the unified collective are compatible with maintained +versions of Node.js. + +When we cut a new major release, we drop support for unmaintained versions of +Node. +This means we try to keep the current release line, +`micromark-factory-label@2`, compatible with Node.js 16. +This package works with `micromark@3`. + +## Security + +This package is safe. +See [`security.md`][securitymd] in [`micromark/.github`][health] for how to +submit a security report. + +## Contribute + +See [`contributing.md`][contributing] in [`micromark/.github`][health] for ways +to get started. +See [`support.md`][support] for ways to get help. + +This project has a [code of conduct][coc]. +By interacting with this repository, organisation, or community you agree to +abide by its terms. + +## License + +[MIT][license] © [Titus Wormer][author] + + + +[build-badge]: https://github.com/micromark/micromark/workflows/main/badge.svg + +[build]: https://github.com/micromark/micromark/actions + +[coverage-badge]: https://img.shields.io/codecov/c/github/micromark/micromark.svg + +[coverage]: https://codecov.io/github/micromark/micromark + +[downloads-badge]: https://img.shields.io/npm/dm/micromark-factory-label.svg + +[downloads]: https://www.npmjs.com/package/micromark-factory-label + +[bundle-size-badge]: https://img.shields.io/badge/dynamic/json?label=minzipped%20size&query=$.size.compressedSize&url=https://deno.bundlejs.com/?q=micromark-factory-label + +[bundle-size]: https://bundlejs.com/?q=micromark-factory-label + +[sponsors-badge]: https://opencollective.com/unified/sponsors/badge.svg + +[backers-badge]: https://opencollective.com/unified/backers/badge.svg + +[opencollective]: https://opencollective.com/unified + +[npm]: https://docs.npmjs.com/cli/install + +[esm]: https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c + +[esmsh]: https://esm.sh + +[chat-badge]: https://img.shields.io/badge/chat-discussions-success.svg + +[chat]: https://github.com/micromark/micromark/discussions + +[license]: https://github.com/micromark/micromark/blob/main/license + +[author]: https://wooorm.com + +[health]: https://github.com/micromark/.github + +[securitymd]: https://github.com/micromark/.github/blob/main/security.md + +[contributing]: https://github.com/micromark/.github/blob/main/contributing.md + +[support]: https://github.com/micromark/.github/blob/main/support.md + +[coc]: https://github.com/micromark/.github/blob/main/code-of-conduct.md + +[typescript]: https://www.typescriptlang.org + +[micromark]: https://github.com/micromark/micromark + +[api-factory-label]: #factorylabel diff --git a/node_modules/micromark-factory-space/dev/index.d.ts b/node_modules/micromark-factory-space/dev/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d9a30cab17e82ae8c2a761c548161adc2e58d483 --- /dev/null +++ b/node_modules/micromark-factory-space/dev/index.d.ts @@ -0,0 +1,37 @@ +/** + * Parse spaces and tabs. + * + * There is no `nok` parameter: + * + * * spaces in markdown are often optional, in which case this factory can be + * used and `ok` will be switched to whether spaces were found or not + * * one line ending or space can be detected with `markdownSpace(code)` right + * before using `factorySpace` + * + * ###### Examples + * + * Where `␉` represents a tab (plus how much it expands) and `␠` represents a + * single space. + * + * ```markdown + * ␉ + * ␠␠␠␠ + * ␉␠ + * ``` + * + * @param {Effects} effects + * Context. + * @param {State} ok + * State switched to when successful. + * @param {TokenType} type + * Type (`' \t'`). + * @param {number | undefined} [max=Infinity] + * Max (exclusive). + * @returns {State} + * Start state. + */ +export function factorySpace(effects: Effects, ok: State, type: TokenType, max?: number | undefined): State; +import type { Effects } from 'micromark-util-types'; +import type { State } from 'micromark-util-types'; +import type { TokenType } from 'micromark-util-types'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/micromark-factory-space/dev/index.d.ts.map b/node_modules/micromark-factory-space/dev/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..42d12792356cdfe4193022ae9e53775884bea5e5 --- /dev/null +++ b/node_modules/micromark-factory-space/dev/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.js"],"names":[],"mappings":"AAQA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,sCAXW,OAAO,MAEP,KAAK,QAEL,SAAS,QAET,MAAM,GAAG,SAAS,GAEhB,KAAK,CA6BjB;6BAjE2C,sBAAsB;2BAAtB,sBAAsB;+BAAtB,sBAAsB"} \ No newline at end of file diff --git a/node_modules/micromark-factory-space/dev/index.js b/node_modules/micromark-factory-space/dev/index.js new file mode 100644 index 0000000000000000000000000000000000000000..5cead758c12abc6923b79afbe34b68c207fd3b0b --- /dev/null +++ b/node_modules/micromark-factory-space/dev/index.js @@ -0,0 +1,67 @@ +/** + * @import {Effects, State, TokenType} from 'micromark-util-types' + */ + +import {markdownSpace} from 'micromark-util-character' + +// To do: implement `spaceOrTab`, `spaceOrTabMinMax`, `spaceOrTabWithOptions`. + +/** + * Parse spaces and tabs. + * + * There is no `nok` parameter: + * + * * spaces in markdown are often optional, in which case this factory can be + * used and `ok` will be switched to whether spaces were found or not + * * one line ending or space can be detected with `markdownSpace(code)` right + * before using `factorySpace` + * + * ###### Examples + * + * Where `␉` represents a tab (plus how much it expands) and `␠` represents a + * single space. + * + * ```markdown + * ␉ + * ␠␠␠␠ + * ␉␠ + * ``` + * + * @param {Effects} effects + * Context. + * @param {State} ok + * State switched to when successful. + * @param {TokenType} type + * Type (`' \t'`). + * @param {number | undefined} [max=Infinity] + * Max (exclusive). + * @returns {State} + * Start state. + */ +export function factorySpace(effects, ok, type, max) { + const limit = max ? max - 1 : Number.POSITIVE_INFINITY + let size = 0 + + return start + + /** @type {State} */ + function start(code) { + if (markdownSpace(code)) { + effects.enter(type) + return prefix(code) + } + + return ok(code) + } + + /** @type {State} */ + function prefix(code) { + if (markdownSpace(code) && size++ < limit) { + effects.consume(code) + return prefix + } + + effects.exit(type) + return ok(code) + } +} diff --git a/node_modules/micromark-factory-space/index.d.ts b/node_modules/micromark-factory-space/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d9a30cab17e82ae8c2a761c548161adc2e58d483 --- /dev/null +++ b/node_modules/micromark-factory-space/index.d.ts @@ -0,0 +1,37 @@ +/** + * Parse spaces and tabs. + * + * There is no `nok` parameter: + * + * * spaces in markdown are often optional, in which case this factory can be + * used and `ok` will be switched to whether spaces were found or not + * * one line ending or space can be detected with `markdownSpace(code)` right + * before using `factorySpace` + * + * ###### Examples + * + * Where `␉` represents a tab (plus how much it expands) and `␠` represents a + * single space. + * + * ```markdown + * ␉ + * ␠␠␠␠ + * ␉␠ + * ``` + * + * @param {Effects} effects + * Context. + * @param {State} ok + * State switched to when successful. + * @param {TokenType} type + * Type (`' \t'`). + * @param {number | undefined} [max=Infinity] + * Max (exclusive). + * @returns {State} + * Start state. + */ +export function factorySpace(effects: Effects, ok: State, type: TokenType, max?: number | undefined): State; +import type { Effects } from 'micromark-util-types'; +import type { State } from 'micromark-util-types'; +import type { TokenType } from 'micromark-util-types'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/micromark-factory-space/index.d.ts.map b/node_modules/micromark-factory-space/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..42d12792356cdfe4193022ae9e53775884bea5e5 --- /dev/null +++ b/node_modules/micromark-factory-space/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.js"],"names":[],"mappings":"AAQA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,sCAXW,OAAO,MAEP,KAAK,QAEL,SAAS,QAET,MAAM,GAAG,SAAS,GAEhB,KAAK,CA6BjB;6BAjE2C,sBAAsB;2BAAtB,sBAAsB;+BAAtB,sBAAsB"} \ No newline at end of file diff --git a/node_modules/micromark-factory-space/index.js b/node_modules/micromark-factory-space/index.js new file mode 100644 index 0000000000000000000000000000000000000000..646117df2d994bec3c11653c84739afb9c760bd7 --- /dev/null +++ b/node_modules/micromark-factory-space/index.js @@ -0,0 +1,64 @@ +/** + * @import {Effects, State, TokenType} from 'micromark-util-types' + */ + +import { markdownSpace } from 'micromark-util-character'; + +// To do: implement `spaceOrTab`, `spaceOrTabMinMax`, `spaceOrTabWithOptions`. + +/** + * Parse spaces and tabs. + * + * There is no `nok` parameter: + * + * * spaces in markdown are often optional, in which case this factory can be + * used and `ok` will be switched to whether spaces were found or not + * * one line ending or space can be detected with `markdownSpace(code)` right + * before using `factorySpace` + * + * ###### Examples + * + * Where `␉` represents a tab (plus how much it expands) and `␠` represents a + * single space. + * + * ```markdown + * ␉ + * ␠␠␠␠ + * ␉␠ + * ``` + * + * @param {Effects} effects + * Context. + * @param {State} ok + * State switched to when successful. + * @param {TokenType} type + * Type (`' \t'`). + * @param {number | undefined} [max=Infinity] + * Max (exclusive). + * @returns {State} + * Start state. + */ +export function factorySpace(effects, ok, type, max) { + const limit = max ? max - 1 : Number.POSITIVE_INFINITY; + let size = 0; + return start; + + /** @type {State} */ + function start(code) { + if (markdownSpace(code)) { + effects.enter(type); + return prefix(code); + } + return ok(code); + } + + /** @type {State} */ + function prefix(code) { + if (markdownSpace(code) && size++ < limit) { + effects.consume(code); + return prefix; + } + effects.exit(type); + return ok(code); + } +} \ No newline at end of file diff --git a/node_modules/micromark-factory-space/license b/node_modules/micromark-factory-space/license new file mode 100644 index 0000000000000000000000000000000000000000..bc8f165a62768a19de38901d81ac662c51ff29db --- /dev/null +++ b/node_modules/micromark-factory-space/license @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) Titus Wormer + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/micromark-factory-space/package.json b/node_modules/micromark-factory-space/package.json new file mode 100644 index 0000000000000000000000000000000000000000..45828c493e9a6389ba6eda4d6ea900989afbdfae --- /dev/null +++ b/node_modules/micromark-factory-space/package.json @@ -0,0 +1,55 @@ +{ + "name": "micromark-factory-space", + "version": "2.0.1", + "description": "micromark factory to parse markdown space (found in lots of places)", + "license": "MIT", + "keywords": [ + "micromark", + "factory", + "space" + ], + "repository": "https://github.com/micromark/micromark/tree/main/packages/micromark-factory-space", + "bugs": "https://github.com/micromark/micromark/issues", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "author": "Titus Wormer (https://wooorm.com)", + "contributors": [ + "Titus Wormer (https://wooorm.com)" + ], + "sideEffects": false, + "type": "module", + "files": [ + "dev/", + "index.d.ts.map", + "index.d.ts", + "index.js" + ], + "exports": { + "development": "./dev/index.js", + "default": "./index.js" + }, + "dependencies": { + "micromark-util-character": "^2.0.0", + "micromark-util-types": "^2.0.0" + }, + "scripts": { + "build": "micromark-build" + }, + "xo": { + "envs": [ + "shared-node-browser" + ], + "prettier": true, + "rules": { + "unicorn/prefer-code-point": "off" + } + } +} diff --git a/node_modules/micromark-factory-space/readme.md b/node_modules/micromark-factory-space/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..b9c01776d831d0ccb9249f4d4bf310239ab537e8 --- /dev/null +++ b/node_modules/micromark-factory-space/readme.md @@ -0,0 +1,225 @@ +# micromark-factory-space + +[![Build][build-badge]][build] +[![Coverage][coverage-badge]][coverage] +[![Downloads][downloads-badge]][downloads] +[![Size][bundle-size-badge]][bundle-size] +[![Sponsors][sponsors-badge]][opencollective] +[![Backers][backers-badge]][opencollective] +[![Chat][chat-badge]][chat] + +[micromark][] factory to parse [markdown space][markdown-space] (found in lots +of places). + +## Contents + +* [What is this?](#what-is-this) +* [When should I use this?](#when-should-i-use-this) +* [Install](#install) +* [Use](#use) +* [API](#api) + * [`factorySpace(…)`](#factoryspace) +* [Types](#types) +* [Compatibility](#compatibility) +* [Security](#security) +* [Contribute](#contribute) +* [License](#license) + +## What is this? + +This package exposes states to parse spaces and/or tabs. + +## When should I use this? + +This package is useful when you are making your own micromark extensions. + +## Install + +This package is [ESM only][esm]. +In Node.js (version 16+), install with [npm][]: + +```sh +npm install micromark-factory-space +``` + +In Deno with [`esm.sh`][esmsh]: + +```js +import {factorySpace} from 'https://esm.sh/micromark-factory-space@1' +``` + +In browsers with [`esm.sh`][esmsh]: + +```html + +``` + +## Use + +```js +import {factorySpace} from 'micromark-factory-space' +import {codes, types} from 'micromark-util-symbol' + +// A micromark tokenizer that uses the factory: +/** + * @this {TokenizeContext} + * Context. + * @type {Tokenizer} + */ +function tokenizeCodeFenced(effects, ok, nok) { + return start + + // … + + /** @type {State} */ + function info(code) { + if (code === codes.eof || markdownLineEndingOrSpace(code)) { + effects.exit(types.chunkString) + effects.exit(types.codeFencedFenceInfo) + return factorySpace(effects, infoAfter, types.whitespace)(code) + } + + if (code === codes.graveAccent && code === marker) return nok(code) + effects.consume(code) + return info + } + + // … +} +``` + +## API + +This module exports the identifier [`factorySpace`][api-factory-space]. +There is no default export. + +### `factorySpace(…)` + +Parse spaces and tabs. + +There is no `nok` parameter: + +* spaces in markdown are often optional, in which case this factory can be + used and `ok` will be switched to whether spaces were found or not +* one line ending or space can be detected with `markdownSpace(code)` right + before using `factorySpace` + +###### Examples + +Where `␉` represents a tab (plus how much it expands) and `␠` represents a +single space. + +```markdown +␉ +␠␠␠␠ +␉␠ +``` + +###### Parameters + +* `effects` (`Effects`) + — context +* `ok` (`State`) + — state switched to when successful +* `type` (`string`) + — type (`' \t'`) +* `max` (`number`, default: `Infinity`) + — max (exclusive) + +###### Returns + +Start state (`State`). + +## Types + +This package is fully typed with [TypeScript][]. +It exports no additional types. + +## Compatibility + +Projects maintained by the unified collective are compatible with maintained +versions of Node.js. + +When we cut a new major release, we drop support for unmaintained versions of +Node. +This means we try to keep the current release line, +`micromark-factory-space@2`, compatible with Node.js 16. +This package works with `micromark@3`. + +## Security + +This package is safe. +See [`security.md`][securitymd] in [`micromark/.github`][health] for how to +submit a security report. + +## Contribute + +See [`contributing.md`][contributing] in [`micromark/.github`][health] for ways +to get started. +See [`support.md`][support] for ways to get help. + +This project has a [code of conduct][coc]. +By interacting with this repository, organisation, or community you agree to +abide by its terms. + +## License + +[MIT][license] © [Titus Wormer][author] + + + +[build-badge]: https://github.com/micromark/micromark/workflows/main/badge.svg + +[build]: https://github.com/micromark/micromark/actions + +[coverage-badge]: https://img.shields.io/codecov/c/github/micromark/micromark.svg + +[coverage]: https://codecov.io/github/micromark/micromark + +[downloads-badge]: https://img.shields.io/npm/dm/micromark-factory-space.svg + +[downloads]: https://www.npmjs.com/package/micromark-factory-space + +[bundle-size-badge]: https://img.shields.io/badge/dynamic/json?label=minzipped%20size&query=$.size.compressedSize&url=https://deno.bundlejs.com/?q=micromark-factory-space + +[bundle-size]: https://bundlejs.com/?q=micromark-factory-space + +[sponsors-badge]: https://opencollective.com/unified/sponsors/badge.svg + +[backers-badge]: https://opencollective.com/unified/backers/badge.svg + +[opencollective]: https://opencollective.com/unified + +[npm]: https://docs.npmjs.com/cli/install + +[esm]: https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c + +[esmsh]: https://esm.sh + +[chat-badge]: https://img.shields.io/badge/chat-discussions-success.svg + +[chat]: https://github.com/micromark/micromark/discussions + +[license]: https://github.com/micromark/micromark/blob/main/license + +[author]: https://wooorm.com + +[health]: https://github.com/micromark/.github + +[securitymd]: https://github.com/micromark/.github/blob/main/security.md + +[contributing]: https://github.com/micromark/.github/blob/main/contributing.md + +[support]: https://github.com/micromark/.github/blob/main/support.md + +[coc]: https://github.com/micromark/.github/blob/main/code-of-conduct.md + +[markdown-space]: https://github.com/micromark/micromark/tree/main/packages/micromark-util-character#markdownspacecode + +[typescript]: https://www.typescriptlang.org + +[micromark]: https://github.com/micromark/micromark + +[api-factory-space]: #factoryspace diff --git a/node_modules/micromark-factory-title/dev/index.d.ts b/node_modules/micromark-factory-title/dev/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6d4b4be20368f32a092c8dd9d42279610c646119 --- /dev/null +++ b/node_modules/micromark-factory-title/dev/index.d.ts @@ -0,0 +1,36 @@ +/** + * Parse titles. + * + * ###### Examples + * + * ```markdown + * "a" + * 'b' + * (c) + * "a + * b" + * 'a + * b' + * (a\)b) + * ``` + * + * @param {Effects} effects + * Context. + * @param {State} ok + * State switched to when successful. + * @param {State} nok + * State switched to when unsuccessful. + * @param {TokenType} type + * Type of the whole title (`"a"`, `'b'`, `(c)`). + * @param {TokenType} markerType + * Type for the markers (`"`, `'`, `(`, and `)`). + * @param {TokenType} stringType + * Type for the value (`a`). + * @returns {State} + * Start state. + */ +export function factoryTitle(effects: Effects, ok: State, nok: State, type: TokenType, markerType: TokenType, stringType: TokenType): State; +import type { Effects } from 'micromark-util-types'; +import type { State } from 'micromark-util-types'; +import type { TokenType } from 'micromark-util-types'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/micromark-factory-title/dev/index.d.ts.map b/node_modules/micromark-factory-title/dev/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..0108e7c976ae6c5f989ac1d955b39f5d0985aec7 --- /dev/null +++ b/node_modules/micromark-factory-title/dev/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.js"],"names":[],"mappings":"AAaA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,sCAfW,OAAO,MAEP,KAAK,OAEL,KAAK,QAEL,SAAS,cAET,SAAS,cAET,SAAS,GAEP,KAAK,CA+HjB;6BAlKS,sBAAsB;2BAAtB,sBAAsB;+BAAtB,sBAAsB"} \ No newline at end of file diff --git a/node_modules/micromark-factory-title/dev/index.js b/node_modules/micromark-factory-title/dev/index.js new file mode 100644 index 0000000000000000000000000000000000000000..4774214cbb38cfed07e30b5d93ea05a6938ad24d --- /dev/null +++ b/node_modules/micromark-factory-title/dev/index.js @@ -0,0 +1,169 @@ +/** + * @import { + * Code, + * Effects, + * State, + * TokenType + * } from 'micromark-util-types' + */ + +import {factorySpace} from 'micromark-factory-space' +import {markdownLineEnding} from 'micromark-util-character' +import {codes, constants, types} from 'micromark-util-symbol' + +/** + * Parse titles. + * + * ###### Examples + * + * ```markdown + * "a" + * 'b' + * (c) + * "a + * b" + * 'a + * b' + * (a\)b) + * ``` + * + * @param {Effects} effects + * Context. + * @param {State} ok + * State switched to when successful. + * @param {State} nok + * State switched to when unsuccessful. + * @param {TokenType} type + * Type of the whole title (`"a"`, `'b'`, `(c)`). + * @param {TokenType} markerType + * Type for the markers (`"`, `'`, `(`, and `)`). + * @param {TokenType} stringType + * Type for the value (`a`). + * @returns {State} + * Start state. + */ +export function factoryTitle(effects, ok, nok, type, markerType, stringType) { + /** @type {NonNullable} */ + let marker + + return start + + /** + * Start of title. + * + * ```markdown + * > | "a" + * ^ + * ``` + * + * @type {State} + */ + function start(code) { + if ( + code === codes.quotationMark || + code === codes.apostrophe || + code === codes.leftParenthesis + ) { + effects.enter(type) + effects.enter(markerType) + effects.consume(code) + effects.exit(markerType) + marker = code === codes.leftParenthesis ? codes.rightParenthesis : code + return begin + } + + return nok(code) + } + + /** + * After opening marker. + * + * This is also used at the closing marker. + * + * ```markdown + * > | "a" + * ^ + * ``` + * + * @type {State} + */ + function begin(code) { + if (code === marker) { + effects.enter(markerType) + effects.consume(code) + effects.exit(markerType) + effects.exit(type) + return ok + } + + effects.enter(stringType) + return atBreak(code) + } + + /** + * At something, before something else. + * + * ```markdown + * > | "a" + * ^ + * ``` + * + * @type {State} + */ + function atBreak(code) { + if (code === marker) { + effects.exit(stringType) + return begin(marker) + } + + if (code === codes.eof) { + return nok(code) + } + + // Note: blank lines can’t exist in content. + if (markdownLineEnding(code)) { + // To do: use `space_or_tab_eol_with_options`, connect. + effects.enter(types.lineEnding) + effects.consume(code) + effects.exit(types.lineEnding) + return factorySpace(effects, atBreak, types.linePrefix) + } + + effects.enter(types.chunkString, {contentType: constants.contentTypeString}) + return inside(code) + } + + /** + * + * + * @type {State} + */ + function inside(code) { + if (code === marker || code === codes.eof || markdownLineEnding(code)) { + effects.exit(types.chunkString) + return atBreak(code) + } + + effects.consume(code) + return code === codes.backslash ? escape : inside + } + + /** + * After `\`, at a special character. + * + * ```markdown + * > | "a\*b" + * ^ + * ``` + * + * @type {State} + */ + function escape(code) { + if (code === marker || code === codes.backslash) { + effects.consume(code) + return inside + } + + return inside(code) + } +} diff --git a/node_modules/micromark-factory-title/index.d.ts b/node_modules/micromark-factory-title/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6d4b4be20368f32a092c8dd9d42279610c646119 --- /dev/null +++ b/node_modules/micromark-factory-title/index.d.ts @@ -0,0 +1,36 @@ +/** + * Parse titles. + * + * ###### Examples + * + * ```markdown + * "a" + * 'b' + * (c) + * "a + * b" + * 'a + * b' + * (a\)b) + * ``` + * + * @param {Effects} effects + * Context. + * @param {State} ok + * State switched to when successful. + * @param {State} nok + * State switched to when unsuccessful. + * @param {TokenType} type + * Type of the whole title (`"a"`, `'b'`, `(c)`). + * @param {TokenType} markerType + * Type for the markers (`"`, `'`, `(`, and `)`). + * @param {TokenType} stringType + * Type for the value (`a`). + * @returns {State} + * Start state. + */ +export function factoryTitle(effects: Effects, ok: State, nok: State, type: TokenType, markerType: TokenType, stringType: TokenType): State; +import type { Effects } from 'micromark-util-types'; +import type { State } from 'micromark-util-types'; +import type { TokenType } from 'micromark-util-types'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/micromark-factory-title/index.d.ts.map b/node_modules/micromark-factory-title/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..0108e7c976ae6c5f989ac1d955b39f5d0985aec7 --- /dev/null +++ b/node_modules/micromark-factory-title/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.js"],"names":[],"mappings":"AAaA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,sCAfW,OAAO,MAEP,KAAK,OAEL,KAAK,QAEL,SAAS,cAET,SAAS,cAET,SAAS,GAEP,KAAK,CA+HjB;6BAlKS,sBAAsB;2BAAtB,sBAAsB;+BAAtB,sBAAsB"} \ No newline at end of file diff --git a/node_modules/micromark-factory-title/index.js b/node_modules/micromark-factory-title/index.js new file mode 100644 index 0000000000000000000000000000000000000000..02c8026c1e7b4a61d6b3a2aa257d8c3ad17a0232 --- /dev/null +++ b/node_modules/micromark-factory-title/index.js @@ -0,0 +1,158 @@ +/** + * @import { + * Code, + * Effects, + * State, + * TokenType + * } from 'micromark-util-types' + */ + +import { factorySpace } from 'micromark-factory-space'; +import { markdownLineEnding } from 'micromark-util-character'; +/** + * Parse titles. + * + * ###### Examples + * + * ```markdown + * "a" + * 'b' + * (c) + * "a + * b" + * 'a + * b' + * (a\)b) + * ``` + * + * @param {Effects} effects + * Context. + * @param {State} ok + * State switched to when successful. + * @param {State} nok + * State switched to when unsuccessful. + * @param {TokenType} type + * Type of the whole title (`"a"`, `'b'`, `(c)`). + * @param {TokenType} markerType + * Type for the markers (`"`, `'`, `(`, and `)`). + * @param {TokenType} stringType + * Type for the value (`a`). + * @returns {State} + * Start state. + */ +export function factoryTitle(effects, ok, nok, type, markerType, stringType) { + /** @type {NonNullable} */ + let marker; + return start; + + /** + * Start of title. + * + * ```markdown + * > | "a" + * ^ + * ``` + * + * @type {State} + */ + function start(code) { + if (code === 34 || code === 39 || code === 40) { + effects.enter(type); + effects.enter(markerType); + effects.consume(code); + effects.exit(markerType); + marker = code === 40 ? 41 : code; + return begin; + } + return nok(code); + } + + /** + * After opening marker. + * + * This is also used at the closing marker. + * + * ```markdown + * > | "a" + * ^ + * ``` + * + * @type {State} + */ + function begin(code) { + if (code === marker) { + effects.enter(markerType); + effects.consume(code); + effects.exit(markerType); + effects.exit(type); + return ok; + } + effects.enter(stringType); + return atBreak(code); + } + + /** + * At something, before something else. + * + * ```markdown + * > | "a" + * ^ + * ``` + * + * @type {State} + */ + function atBreak(code) { + if (code === marker) { + effects.exit(stringType); + return begin(marker); + } + if (code === null) { + return nok(code); + } + + // Note: blank lines can’t exist in content. + if (markdownLineEnding(code)) { + // To do: use `space_or_tab_eol_with_options`, connect. + effects.enter("lineEnding"); + effects.consume(code); + effects.exit("lineEnding"); + return factorySpace(effects, atBreak, "linePrefix"); + } + effects.enter("chunkString", { + contentType: "string" + }); + return inside(code); + } + + /** + * + * + * @type {State} + */ + function inside(code) { + if (code === marker || code === null || markdownLineEnding(code)) { + effects.exit("chunkString"); + return atBreak(code); + } + effects.consume(code); + return code === 92 ? escape : inside; + } + + /** + * After `\`, at a special character. + * + * ```markdown + * > | "a\*b" + * ^ + * ``` + * + * @type {State} + */ + function escape(code) { + if (code === marker || code === 92) { + effects.consume(code); + return inside; + } + return inside(code); + } +} \ No newline at end of file diff --git a/node_modules/micromark-factory-title/license b/node_modules/micromark-factory-title/license new file mode 100644 index 0000000000000000000000000000000000000000..bc8f165a62768a19de38901d81ac662c51ff29db --- /dev/null +++ b/node_modules/micromark-factory-title/license @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) Titus Wormer + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/micromark-factory-title/package.json b/node_modules/micromark-factory-title/package.json new file mode 100644 index 0000000000000000000000000000000000000000..f643a5dea3fc8a4b213523ec75ece0a261f683f3 --- /dev/null +++ b/node_modules/micromark-factory-title/package.json @@ -0,0 +1,58 @@ +{ + "name": "micromark-factory-title", + "version": "2.0.1", + "description": "micromark factory to parse markdown titles (found in resources, definitions)", + "license": "MIT", + "keywords": [ + "micromark", + "factory", + "title" + ], + "repository": "https://github.com/micromark/micromark/tree/main/packages/micromark-factory-title", + "bugs": "https://github.com/micromark/micromark/issues", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "author": "Titus Wormer (https://wooorm.com)", + "contributors": [ + "Titus Wormer (https://wooorm.com)" + ], + "sideEffects": false, + "type": "module", + "files": [ + "dev/", + "index.d.ts.map", + "index.d.ts", + "index.js" + ], + "exports": { + "development": "./dev/index.js", + "default": "./index.js" + }, + "dependencies": { + "micromark-factory-space": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + }, + "scripts": { + "build": "micromark-build" + }, + "xo": { + "envs": [ + "shared-node-browser" + ], + "prettier": true, + "rules": { + "max-params": "off", + "unicorn/prefer-code-point": "off" + } + } +} diff --git a/node_modules/micromark-factory-title/readme.md b/node_modules/micromark-factory-title/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..ff51cbdebe57cdfc0e1343e12f7402515404e545 --- /dev/null +++ b/node_modules/micromark-factory-title/readme.md @@ -0,0 +1,229 @@ +# micromark-factory-title + +[![Build][build-badge]][build] +[![Coverage][coverage-badge]][coverage] +[![Downloads][downloads-badge]][downloads] +[![Size][bundle-size-badge]][bundle-size] +[![Sponsors][sponsors-badge]][opencollective] +[![Backers][backers-badge]][opencollective] +[![Chat][chat-badge]][chat] + +[micromark][] factory to parse markdown titles (found in resources, +definitions). + +## Contents + +* [What is this?](#what-is-this) +* [When should I use this?](#when-should-i-use-this) +* [Install](#install) +* [Use](#use) +* [API](#api) + * [`factoryTitle(…)`](#factorytitle) +* [Types](#types) +* [Compatibility](#compatibility) +* [Security](#security) +* [Contribute](#contribute) +* [License](#license) + +## What is this? + +This package exposes states to parse titles. + +## When should I use this? + +This package is useful when you are making your own micromark extensions. + +## Install + +This package is [ESM only][esm]. +In Node.js (version 16+), install with [npm][]: + +```sh +npm install micromark-factory-title +``` + +In Deno with [`esm.sh`][esmsh]: + +```js +import {factorySpace} from 'https://esm.sh/micromark-factory-title@1' +``` + +In browsers with [`esm.sh`][esmsh]: + +```html + +``` + +## Use + +```js +import {factoryTitle} from 'micromark-factory-title' +import {codes, types} from 'micromark-util-symbol' + +// A micromark tokenizer that uses the factory: +/** + * @this {TokenizeContext} + * Context. + * @type {Tokenizer} + */ +function tokenizeDefinition(effects, ok, nok) { + return start + + // … + + /** @type {State} */ + function before(code) { + if ( + code === codes.quotationMark || + code === codes.apostrophe || + code === codes.leftParenthesis + ) { + return factoryTitle( + effects, + factorySpace(effects, after, types.whitespace), + nok, + types.definitionTitle, + types.definitionTitleMarker, + types.definitionTitleString + )(code) + } + + return nok(code) + } + + // … +} +``` + +## API + +This module exports the identifier [`factoryTitle`][api-factory-title]. +There is no default export. + +### `factoryTitle(…)` + +Parse titles. + +###### Examples + +```markdown +"a" +'b' +(c) +"a +b" +'a + b' +(a\)b) +``` + +###### Parameters + +* `effects` (`Effects`) + — context +* `ok` (`State`) + — state switched to when successful +* `nok` (`State`) + — state switched to when unsuccessful +* `type` (`string`) + — type of the whole title (`"a"`, `'b'`, `(c)`) +* `markerType` (`string`) + — type for the markers (`"`, `'`, `(`, and `)`) +* `stringType` (`string`) + — type for the value (`a`) + +###### Returns + +Start state (`State`). + +## Types + +This package is fully typed with [TypeScript][]. +It exports no additional types. + +## Compatibility + +Projects maintained by the unified collective are compatible with maintained +versions of Node.js. + +When we cut a new major release, we drop support for unmaintained versions of +Node. +This means we try to keep the current release line, +`micromark-factory-title@2`, compatible with Node.js 16. +This package works with `micromark@3`. + +## Security + +This package is safe. +See [`security.md`][securitymd] in [`micromark/.github`][health] for how to +submit a security report. + +## Contribute + +See [`contributing.md`][contributing] in [`micromark/.github`][health] for ways +to get started. +See [`support.md`][support] for ways to get help. + +This project has a [code of conduct][coc]. +By interacting with this repository, organisation, or community you agree to +abide by its terms. + +## License + +[MIT][license] © [Titus Wormer][author] + + + +[build-badge]: https://github.com/micromark/micromark/workflows/main/badge.svg + +[build]: https://github.com/micromark/micromark/actions + +[coverage-badge]: https://img.shields.io/codecov/c/github/micromark/micromark.svg + +[coverage]: https://codecov.io/github/micromark/micromark + +[downloads-badge]: https://img.shields.io/npm/dm/micromark-factory-title.svg + +[downloads]: https://www.npmjs.com/package/micromark-factory-title + +[bundle-size-badge]: https://img.shields.io/badge/dynamic/json?label=minzipped%20size&query=$.size.compressedSize&url=https://deno.bundlejs.com/?q=micromark-factory-title + +[bundle-size]: https://bundlejs.com/?q=micromark-factory-title + +[sponsors-badge]: https://opencollective.com/unified/sponsors/badge.svg + +[backers-badge]: https://opencollective.com/unified/backers/badge.svg + +[opencollective]: https://opencollective.com/unified + +[npm]: https://docs.npmjs.com/cli/install + +[esm]: https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c + +[esmsh]: https://esm.sh + +[chat-badge]: https://img.shields.io/badge/chat-discussions-success.svg + +[chat]: https://github.com/micromark/micromark/discussions + +[license]: https://github.com/micromark/micromark/blob/main/license + +[author]: https://wooorm.com + +[health]: https://github.com/micromark/.github + +[securitymd]: https://github.com/micromark/.github/blob/main/security.md + +[contributing]: https://github.com/micromark/.github/blob/main/contributing.md + +[support]: https://github.com/micromark/.github/blob/main/support.md + +[coc]: https://github.com/micromark/.github/blob/main/code-of-conduct.md + +[typescript]: https://www.typescriptlang.org + +[micromark]: https://github.com/micromark/micromark + +[api-factory-title]: #factorytitle diff --git a/node_modules/micromark-factory-whitespace/dev/index.d.ts b/node_modules/micromark-factory-whitespace/dev/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..52ca4b85bc46db9d049d0ab7ba9438716952442f --- /dev/null +++ b/node_modules/micromark-factory-whitespace/dev/index.d.ts @@ -0,0 +1,22 @@ +/** + * Parse spaces and tabs. + * + * There is no `nok` parameter: + * + * * line endings or spaces in markdown are often optional, in which case this + * factory can be used and `ok` will be switched to whether spaces were found + * or not + * * one line ending or space can be detected with + * `markdownLineEndingOrSpace(code)` right before using `factoryWhitespace` + * + * @param {Effects} effects + * Context. + * @param {State} ok + * State switched to when successful. + * @returns {State} + * Start state. + */ +export function factoryWhitespace(effects: Effects, ok: State): State; +import type { Effects } from 'micromark-util-types'; +import type { State } from 'micromark-util-types'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/micromark-factory-whitespace/dev/index.d.ts.map b/node_modules/micromark-factory-whitespace/dev/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..5169dc46ad46ea695c469d4dfc7bd808859ed04c --- /dev/null +++ b/node_modules/micromark-factory-whitespace/dev/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.js"],"names":[],"mappings":"AAQA;;;;;;;;;;;;;;;;;GAiBG;AACH,2CAPW,OAAO,MAEP,KAAK,GAEH,KAAK,CA6BjB;6BAnDgC,sBAAsB;2BAAtB,sBAAsB"} \ No newline at end of file diff --git a/node_modules/micromark-factory-whitespace/dev/index.js b/node_modules/micromark-factory-whitespace/dev/index.js new file mode 100644 index 0000000000000000000000000000000000000000..3aa9e37b2dd1b3292df40a63e68c62adb38ff6ea --- /dev/null +++ b/node_modules/micromark-factory-whitespace/dev/index.js @@ -0,0 +1,53 @@ +/** + * @import {Effects, State} from 'micromark-util-types' + */ + +import {factorySpace} from 'micromark-factory-space' +import {markdownLineEnding, markdownSpace} from 'micromark-util-character' +import {types} from 'micromark-util-symbol' + +/** + * Parse spaces and tabs. + * + * There is no `nok` parameter: + * + * * line endings or spaces in markdown are often optional, in which case this + * factory can be used and `ok` will be switched to whether spaces were found + * or not + * * one line ending or space can be detected with + * `markdownLineEndingOrSpace(code)` right before using `factoryWhitespace` + * + * @param {Effects} effects + * Context. + * @param {State} ok + * State switched to when successful. + * @returns {State} + * Start state. + */ +export function factoryWhitespace(effects, ok) { + /** @type {boolean} */ + let seen + + return start + + /** @type {State} */ + function start(code) { + if (markdownLineEnding(code)) { + effects.enter(types.lineEnding) + effects.consume(code) + effects.exit(types.lineEnding) + seen = true + return start + } + + if (markdownSpace(code)) { + return factorySpace( + effects, + start, + seen ? types.linePrefix : types.lineSuffix + )(code) + } + + return ok(code) + } +} diff --git a/node_modules/micromark-factory-whitespace/index.d.ts b/node_modules/micromark-factory-whitespace/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..52ca4b85bc46db9d049d0ab7ba9438716952442f --- /dev/null +++ b/node_modules/micromark-factory-whitespace/index.d.ts @@ -0,0 +1,22 @@ +/** + * Parse spaces and tabs. + * + * There is no `nok` parameter: + * + * * line endings or spaces in markdown are often optional, in which case this + * factory can be used and `ok` will be switched to whether spaces were found + * or not + * * one line ending or space can be detected with + * `markdownLineEndingOrSpace(code)` right before using `factoryWhitespace` + * + * @param {Effects} effects + * Context. + * @param {State} ok + * State switched to when successful. + * @returns {State} + * Start state. + */ +export function factoryWhitespace(effects: Effects, ok: State): State; +import type { Effects } from 'micromark-util-types'; +import type { State } from 'micromark-util-types'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/micromark-factory-whitespace/index.d.ts.map b/node_modules/micromark-factory-whitespace/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..5169dc46ad46ea695c469d4dfc7bd808859ed04c --- /dev/null +++ b/node_modules/micromark-factory-whitespace/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.js"],"names":[],"mappings":"AAQA;;;;;;;;;;;;;;;;;GAiBG;AACH,2CAPW,OAAO,MAEP,KAAK,GAEH,KAAK,CA6BjB;6BAnDgC,sBAAsB;2BAAtB,sBAAsB"} \ No newline at end of file diff --git a/node_modules/micromark-factory-whitespace/index.js b/node_modules/micromark-factory-whitespace/index.js new file mode 100644 index 0000000000000000000000000000000000000000..02243add41e685792bf69165b3c776073049f06b --- /dev/null +++ b/node_modules/micromark-factory-whitespace/index.js @@ -0,0 +1,44 @@ +/** + * @import {Effects, State} from 'micromark-util-types' + */ + +import { factorySpace } from 'micromark-factory-space'; +import { markdownLineEnding, markdownSpace } from 'micromark-util-character'; +/** + * Parse spaces and tabs. + * + * There is no `nok` parameter: + * + * * line endings or spaces in markdown are often optional, in which case this + * factory can be used and `ok` will be switched to whether spaces were found + * or not + * * one line ending or space can be detected with + * `markdownLineEndingOrSpace(code)` right before using `factoryWhitespace` + * + * @param {Effects} effects + * Context. + * @param {State} ok + * State switched to when successful. + * @returns {State} + * Start state. + */ +export function factoryWhitespace(effects, ok) { + /** @type {boolean} */ + let seen; + return start; + + /** @type {State} */ + function start(code) { + if (markdownLineEnding(code)) { + effects.enter("lineEnding"); + effects.consume(code); + effects.exit("lineEnding"); + seen = true; + return start; + } + if (markdownSpace(code)) { + return factorySpace(effects, start, seen ? "linePrefix" : "lineSuffix")(code); + } + return ok(code); + } +} \ No newline at end of file diff --git a/node_modules/micromark-factory-whitespace/license b/node_modules/micromark-factory-whitespace/license new file mode 100644 index 0000000000000000000000000000000000000000..bc8f165a62768a19de38901d81ac662c51ff29db --- /dev/null +++ b/node_modules/micromark-factory-whitespace/license @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) Titus Wormer + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/micromark-factory-whitespace/package.json b/node_modules/micromark-factory-whitespace/package.json new file mode 100644 index 0000000000000000000000000000000000000000..ce733bd06e323c0e3e9b726540b8fc8e7f803c4b --- /dev/null +++ b/node_modules/micromark-factory-whitespace/package.json @@ -0,0 +1,57 @@ +{ + "name": "micromark-factory-whitespace", + "version": "2.0.1", + "description": "micromark factory to parse markdown whitespace (found in lots of places)", + "license": "MIT", + "keywords": [ + "micromark", + "factory", + "whitespace" + ], + "repository": "https://github.com/micromark/micromark/tree/main/packages/micromark-factory-whitespace", + "bugs": "https://github.com/micromark/micromark/issues", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "author": "Titus Wormer (https://wooorm.com)", + "contributors": [ + "Titus Wormer (https://wooorm.com)" + ], + "sideEffects": false, + "type": "module", + "files": [ + "dev/", + "index.d.ts.map", + "index.d.ts", + "index.js" + ], + "exports": { + "development": "./dev/index.js", + "default": "./index.js" + }, + "dependencies": { + "micromark-factory-space": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + }, + "scripts": { + "build": "micromark-build" + }, + "xo": { + "envs": [ + "shared-node-browser" + ], + "prettier": true, + "rules": { + "unicorn/prefer-code-point": "off" + } + } +} diff --git a/node_modules/micromark-factory-whitespace/readme.md b/node_modules/micromark-factory-whitespace/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..a846406a5299badbd3aa92b283a28e9488e49862 --- /dev/null +++ b/node_modules/micromark-factory-whitespace/readme.md @@ -0,0 +1,205 @@ +# micromark-factory-whitespace + +[![Build][build-badge]][build] +[![Coverage][coverage-badge]][coverage] +[![Downloads][downloads-badge]][downloads] +[![Size][bundle-size-badge]][bundle-size] +[![Sponsors][sponsors-badge]][opencollective] +[![Backers][backers-badge]][opencollective] +[![Chat][chat-badge]][chat] + +[micromark][] factory to parse [markdown line endings or spaces][ws] (found in +lots of places). + +## Contents + +* [What is this?](#what-is-this) +* [When should I use this?](#when-should-i-use-this) +* [Install](#install) +* [Use](#use) +* [API](#api) + * [`factoryWhitespace(…)`](#factorywhitespace) +* [Types](#types) +* [Compatibility](#compatibility) +* [Security](#security) +* [Contribute](#contribute) +* [License](#license) + +## What is this? + +This package exposes states to parse whitespace. + +## When should I use this? + +This package is useful when you are making your own micromark extensions. + +## Install + +This package is [ESM only][esm]. +In Node.js (version 16+), install with [npm][]: + +```sh +npm install micromark-factory-whitespace +``` + +In Deno with [`esm.sh`][esmsh]: + +```js +import {factoryWhitespace} from 'https://esm.sh/micromark-factory-whitespace@1' +``` + +In browsers with [`esm.sh`][esmsh]: + +```html + +``` + +## Use + +```js +import {factoryWhitespace} from 'micromark-factory-whitespace' +import {codes, types} from 'micromark-util-symbol' + +// A micromark tokenizer that uses the factory: +/** + * @this {TokenizeContext} + * Context. + * @type {Tokenizer} + */ +function tokenizeTitle(effects, ok, nok) { + return start + + /** @type {State} */ + function start(code) { + return markdownLineEndingOrSpace(code) + ? factoryWhitespace(effects, before)(code) + : nok(code) + } + + // … +} +``` + +## API + +This module exports the identifier +[`factoryWhitespace`][api-factory-whitespace]. +There is no default export. + +### `factoryWhitespace(…)` + +Parse spaces and tabs. + +There is no `nok` parameter: + +* line endings or spaces in markdown are often optional, in which case this + factory can be used and `ok` will be switched to whether spaces were found + or not +* one line ending or space can be detected with + [`markdownLineEndingOrSpace(code)`][ws] right before using + `factoryWhitespace` + +###### Parameters + +* `effects` (`Effects`) + — context +* `ok` (`State`) + — state switched to when successful + +###### Returns + +Start state (`State`). + +## Types + +This package is fully typed with [TypeScript][]. +It exports no additional types. + +## Compatibility + +Projects maintained by the unified collective are compatible with maintained +versions of Node.js. + +When we cut a new major release, we drop support for unmaintained versions of +Node. +This means we try to keep the current release line, +`micromark-factory-whitespace@2`, compatible with Node.js 16. +This package works with `micromark@3`. + +## Security + +This package is safe. +See [`security.md`][securitymd] in [`micromark/.github`][health] for how to +submit a security report. + +## Contribute + +See [`contributing.md`][contributing] in [`micromark/.github`][health] for ways +to get started. +See [`support.md`][support] for ways to get help. + +This project has a [code of conduct][coc]. +By interacting with this repository, organisation, or community you agree to +abide by its terms. + +## License + +[MIT][license] © [Titus Wormer][author] + + + +[build-badge]: https://github.com/micromark/micromark/workflows/main/badge.svg + +[build]: https://github.com/micromark/micromark/actions + +[coverage-badge]: https://img.shields.io/codecov/c/github/micromark/micromark.svg + +[coverage]: https://codecov.io/github/micromark/micromark + +[downloads-badge]: https://img.shields.io/npm/dm/micromark-factory-whitespace.svg + +[downloads]: https://www.npmjs.com/package/micromark-factory-whitespace + +[bundle-size-badge]: https://img.shields.io/badge/dynamic/json?label=minzipped%20size&query=$.size.compressedSize&url=https://deno.bundlejs.com/?q=micromark-factory-whitespace + +[bundle-size]: https://bundlejs.com/?q=micromark-factory-whitespace + +[sponsors-badge]: https://opencollective.com/unified/sponsors/badge.svg + +[backers-badge]: https://opencollective.com/unified/backers/badge.svg + +[opencollective]: https://opencollective.com/unified + +[npm]: https://docs.npmjs.com/cli/install + +[esm]: https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c + +[esmsh]: https://esm.sh + +[chat-badge]: https://img.shields.io/badge/chat-discussions-success.svg + +[chat]: https://github.com/micromark/micromark/discussions + +[license]: https://github.com/micromark/micromark/blob/main/license + +[author]: https://wooorm.com + +[health]: https://github.com/micromark/.github + +[securitymd]: https://github.com/micromark/.github/blob/main/security.md + +[contributing]: https://github.com/micromark/.github/blob/main/contributing.md + +[support]: https://github.com/micromark/.github/blob/main/support.md + +[coc]: https://github.com/micromark/.github/blob/main/code-of-conduct.md + +[ws]: https://github.com/micromark/micromark/tree/main/packages/micromark-util-character#markdownlineendingorspacecode + +[typescript]: https://www.typescriptlang.org + +[micromark]: https://github.com/micromark/micromark + +[api-factory-whitespace]: #factorywhitespace diff --git a/node_modules/micromark-util-character/dev/index.d.ts b/node_modules/micromark-util-character/dev/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fe5289573d03c84b318810d89f5dfbd49702d853 --- /dev/null +++ b/node_modules/micromark-util-character/dev/index.d.ts @@ -0,0 +1,195 @@ +/** + * Check whether a character code is an ASCII control character. + * + * An **ASCII control** is a character in the inclusive range U+0000 NULL (NUL) + * to U+001F (US), or U+007F (DEL). + * + * @param {Code} code + * Code. + * @returns {boolean} + * Whether it matches. + */ +export function asciiControl(code: Code): boolean; +/** + * Check whether a character code is a markdown line ending. + * + * A **markdown line ending** is the virtual characters M-0003 CARRIAGE RETURN + * LINE FEED (CRLF), M-0004 LINE FEED (LF) and M-0005 CARRIAGE RETURN (CR). + * + * In micromark, the actual character U+000A LINE FEED (LF) and U+000D CARRIAGE + * RETURN (CR) are replaced by these virtual characters depending on whether + * they occurred together. + * + * @param {Code} code + * Code. + * @returns {boolean} + * Whether it matches. + */ +export function markdownLineEnding(code: Code): boolean; +/** + * Check whether a character code is a markdown line ending (see + * `markdownLineEnding`) or markdown space (see `markdownSpace`). + * + * @param {Code} code + * Code. + * @returns {boolean} + * Whether it matches. + */ +export function markdownLineEndingOrSpace(code: Code): boolean; +/** + * Check whether a character code is a markdown space. + * + * A **markdown space** is the concrete character U+0020 SPACE (SP) and the + * virtual characters M-0001 VIRTUAL SPACE (VS) and M-0002 HORIZONTAL TAB (HT). + * + * In micromark, the actual character U+0009 CHARACTER TABULATION (HT) is + * replaced by one M-0002 HORIZONTAL TAB (HT) and between 0 and 3 M-0001 VIRTUAL + * SPACE (VS) characters, depending on the column at which the tab occurred. + * + * @param {Code} code + * Code. + * @returns {boolean} + * Whether it matches. + */ +export function markdownSpace(code: Code): boolean; +/** + * Check whether the character code represents an ASCII alpha (`a` through `z`, + * case insensitive). + * + * An **ASCII alpha** is an ASCII upper alpha or ASCII lower alpha. + * + * An **ASCII upper alpha** is a character in the inclusive range U+0041 (`A`) + * to U+005A (`Z`). + * + * An **ASCII lower alpha** is a character in the inclusive range U+0061 (`a`) + * to U+007A (`z`). + * + * @param code + * Code. + * @returns {boolean} + * Whether it matches. + */ +export const asciiAlpha: (code: Code) => boolean; +/** + * Check whether the character code represents an ASCII alphanumeric (`a` + * through `z`, case insensitive, or `0` through `9`). + * + * An **ASCII alphanumeric** is an ASCII digit (see `asciiDigit`) or ASCII alpha + * (see `asciiAlpha`). + * + * @param code + * Code. + * @returns {boolean} + * Whether it matches. + */ +export const asciiAlphanumeric: (code: Code) => boolean; +/** + * Check whether the character code represents an ASCII atext. + * + * atext is an ASCII alphanumeric (see `asciiAlphanumeric`), or a character in + * the inclusive ranges U+0023 NUMBER SIGN (`#`) to U+0027 APOSTROPHE (`'`), + * U+002A ASTERISK (`*`), U+002B PLUS SIGN (`+`), U+002D DASH (`-`), U+002F + * SLASH (`/`), U+003D EQUALS TO (`=`), U+003F QUESTION MARK (`?`), U+005E + * CARET (`^`) to U+0060 GRAVE ACCENT (`` ` ``), or U+007B LEFT CURLY BRACE + * (`{`) to U+007E TILDE (`~`). + * + * See: + * **\[RFC5322]**: + * [Internet Message Format](https://tools.ietf.org/html/rfc5322). + * P. Resnick. + * IETF. + * + * @param code + * Code. + * @returns {boolean} + * Whether it matches. + */ +export const asciiAtext: (code: Code) => boolean; +/** + * Check whether the character code represents an ASCII digit (`0` through `9`). + * + * An **ASCII digit** is a character in the inclusive range U+0030 (`0`) to + * U+0039 (`9`). + * + * @param code + * Code. + * @returns {boolean} + * Whether it matches. + */ +export const asciiDigit: (code: Code) => boolean; +/** + * Check whether the character code represents an ASCII hex digit (`a` through + * `f`, case insensitive, or `0` through `9`). + * + * An **ASCII hex digit** is an ASCII digit (see `asciiDigit`), ASCII upper hex + * digit, or an ASCII lower hex digit. + * + * An **ASCII upper hex digit** is a character in the inclusive range U+0041 + * (`A`) to U+0046 (`F`). + * + * An **ASCII lower hex digit** is a character in the inclusive range U+0061 + * (`a`) to U+0066 (`f`). + * + * @param code + * Code. + * @returns {boolean} + * Whether it matches. + */ +export const asciiHexDigit: (code: Code) => boolean; +/** + * Check whether the character code represents ASCII punctuation. + * + * An **ASCII punctuation** is a character in the inclusive ranges U+0021 + * EXCLAMATION MARK (`!`) to U+002F SLASH (`/`), U+003A COLON (`:`) to U+0040 AT + * SIGN (`@`), U+005B LEFT SQUARE BRACKET (`[`) to U+0060 GRAVE ACCENT + * (`` ` ``), or U+007B LEFT CURLY BRACE (`{`) to U+007E TILDE (`~`). + * + * @param code + * Code. + * @returns {boolean} + * Whether it matches. + */ +export const asciiPunctuation: (code: Code) => boolean; +/** + * Check whether the character code represents Unicode punctuation. + * + * A **Unicode punctuation** is a character in the Unicode `Pc` (Punctuation, + * Connector), `Pd` (Punctuation, Dash), `Pe` (Punctuation, Close), `Pf` + * (Punctuation, Final quote), `Pi` (Punctuation, Initial quote), `Po` + * (Punctuation, Other), or `Ps` (Punctuation, Open) categories, or an ASCII + * punctuation (see `asciiPunctuation`). + * + * See: + * **\[UNICODE]**: + * [The Unicode Standard](https://www.unicode.org/versions/). + * Unicode Consortium. + * + * @param code + * Code. + * @returns + * Whether it matches. + */ +export const unicodePunctuation: (code: Code) => boolean; +/** + * Check whether the character code represents Unicode whitespace. + * + * Note that this does handle micromark specific markdown whitespace characters. + * See `markdownLineEndingOrSpace` to check that. + * + * A **Unicode whitespace** is a character in the Unicode `Zs` (Separator, + * Space) category, or U+0009 CHARACTER TABULATION (HT), U+000A LINE FEED (LF), + * U+000C (FF), or U+000D CARRIAGE RETURN (CR) (**\[UNICODE]**). + * + * See: + * **\[UNICODE]**: + * [The Unicode Standard](https://www.unicode.org/versions/). + * Unicode Consortium. + * + * @param code + * Code. + * @returns + * Whether it matches. + */ +export const unicodeWhitespace: (code: Code) => boolean; +import type { Code } from 'micromark-util-types'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/micromark-util-character/dev/index.d.ts.map b/node_modules/micromark-util-character/dev/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..8ded3c1570e11682a465c097443a291216ea9b1a --- /dev/null +++ b/node_modules/micromark-util-character/dev/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.js"],"names":[],"mappings":"AA8DA;;;;;;;;;;GAUG;AACH,mCALW,IAAI,GAEF,OAAO,CASnB;AAkDD;;;;;;;;;;;;;;GAcG;AACH,yCALW,IAAI,GAEF,OAAO,CAKnB;AAED;;;;;;;;GAQG;AACH,gDALW,IAAI,GAEF,OAAO,CAKnB;AAED;;;;;;;;;;;;;;GAcG;AACH,oCALW,IAAI,GAEF,OAAO,CASnB;AAhLD;;;;;;;;;;;;;;;;GAgBG;AACH,gCAmNoB,IAAI,KAAK,OAAO,CAnNY;AAEhD;;;;;;;;;;;GAWG;AACH,uCAqMoB,IAAI,KAAK,OAAO,CArMqB;AAEzD;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,gCA8KoB,IAAI,KAAK,OAAO,CA9KuB;AAqB3D;;;;;;;;;;GAUG;AACH,gCA8IoB,IAAI,KAAK,OAAO,CA9IM;AAE1C;;;;;;;;;;;;;;;;;GAiBG;AACH,mCA0HoB,IAAI,KAAK,OAAO,CA1HiB;AAErD;;;;;;;;;;;;GAYG;AACH,sCA2GoB,IAAI,KAAK,OAAO,CA3GwB;AA2D5D;;;;;;;;;;;;;;;;;;GAkBG;AACH,wCA6BoB,IAAI,KAAK,OAAO,CA7BwB;AAE5D;;;;;;;;;;;;;;;;;;;GAmBG;AACH,uCAOoB,IAAI,KAAK,OAAO,CAPa;0BAlO1B,sBAAsB"} \ No newline at end of file diff --git a/node_modules/micromark-util-character/dev/index.js b/node_modules/micromark-util-character/dev/index.js new file mode 100644 index 0000000000000000000000000000000000000000..123745e860dd26c0f12b45f79a0a1fb69b45d6f0 --- /dev/null +++ b/node_modules/micromark-util-character/dev/index.js @@ -0,0 +1,252 @@ +/** + * @import {Code} from 'micromark-util-types' + */ + +import {codes} from 'micromark-util-symbol' + +/** + * Check whether the character code represents an ASCII alpha (`a` through `z`, + * case insensitive). + * + * An **ASCII alpha** is an ASCII upper alpha or ASCII lower alpha. + * + * An **ASCII upper alpha** is a character in the inclusive range U+0041 (`A`) + * to U+005A (`Z`). + * + * An **ASCII lower alpha** is a character in the inclusive range U+0061 (`a`) + * to U+007A (`z`). + * + * @param code + * Code. + * @returns {boolean} + * Whether it matches. + */ +export const asciiAlpha = regexCheck(/[A-Za-z]/) + +/** + * Check whether the character code represents an ASCII alphanumeric (`a` + * through `z`, case insensitive, or `0` through `9`). + * + * An **ASCII alphanumeric** is an ASCII digit (see `asciiDigit`) or ASCII alpha + * (see `asciiAlpha`). + * + * @param code + * Code. + * @returns {boolean} + * Whether it matches. + */ +export const asciiAlphanumeric = regexCheck(/[\dA-Za-z]/) + +/** + * Check whether the character code represents an ASCII atext. + * + * atext is an ASCII alphanumeric (see `asciiAlphanumeric`), or a character in + * the inclusive ranges U+0023 NUMBER SIGN (`#`) to U+0027 APOSTROPHE (`'`), + * U+002A ASTERISK (`*`), U+002B PLUS SIGN (`+`), U+002D DASH (`-`), U+002F + * SLASH (`/`), U+003D EQUALS TO (`=`), U+003F QUESTION MARK (`?`), U+005E + * CARET (`^`) to U+0060 GRAVE ACCENT (`` ` ``), or U+007B LEFT CURLY BRACE + * (`{`) to U+007E TILDE (`~`). + * + * See: + * **\[RFC5322]**: + * [Internet Message Format](https://tools.ietf.org/html/rfc5322). + * P. Resnick. + * IETF. + * + * @param code + * Code. + * @returns {boolean} + * Whether it matches. + */ +export const asciiAtext = regexCheck(/[#-'*+\--9=?A-Z^-~]/) + +/** + * Check whether a character code is an ASCII control character. + * + * An **ASCII control** is a character in the inclusive range U+0000 NULL (NUL) + * to U+001F (US), or U+007F (DEL). + * + * @param {Code} code + * Code. + * @returns {boolean} + * Whether it matches. + */ +export function asciiControl(code) { + return ( + // Special whitespace codes (which have negative values), C0 and Control + // character DEL + code !== null && (code < codes.space || code === codes.del) + ) +} + +/** + * Check whether the character code represents an ASCII digit (`0` through `9`). + * + * An **ASCII digit** is a character in the inclusive range U+0030 (`0`) to + * U+0039 (`9`). + * + * @param code + * Code. + * @returns {boolean} + * Whether it matches. + */ +export const asciiDigit = regexCheck(/\d/) + +/** + * Check whether the character code represents an ASCII hex digit (`a` through + * `f`, case insensitive, or `0` through `9`). + * + * An **ASCII hex digit** is an ASCII digit (see `asciiDigit`), ASCII upper hex + * digit, or an ASCII lower hex digit. + * + * An **ASCII upper hex digit** is a character in the inclusive range U+0041 + * (`A`) to U+0046 (`F`). + * + * An **ASCII lower hex digit** is a character in the inclusive range U+0061 + * (`a`) to U+0066 (`f`). + * + * @param code + * Code. + * @returns {boolean} + * Whether it matches. + */ +export const asciiHexDigit = regexCheck(/[\dA-Fa-f]/) + +/** + * Check whether the character code represents ASCII punctuation. + * + * An **ASCII punctuation** is a character in the inclusive ranges U+0021 + * EXCLAMATION MARK (`!`) to U+002F SLASH (`/`), U+003A COLON (`:`) to U+0040 AT + * SIGN (`@`), U+005B LEFT SQUARE BRACKET (`[`) to U+0060 GRAVE ACCENT + * (`` ` ``), or U+007B LEFT CURLY BRACE (`{`) to U+007E TILDE (`~`). + * + * @param code + * Code. + * @returns {boolean} + * Whether it matches. + */ +export const asciiPunctuation = regexCheck(/[!-/:-@[-`{-~]/) + +/** + * Check whether a character code is a markdown line ending. + * + * A **markdown line ending** is the virtual characters M-0003 CARRIAGE RETURN + * LINE FEED (CRLF), M-0004 LINE FEED (LF) and M-0005 CARRIAGE RETURN (CR). + * + * In micromark, the actual character U+000A LINE FEED (LF) and U+000D CARRIAGE + * RETURN (CR) are replaced by these virtual characters depending on whether + * they occurred together. + * + * @param {Code} code + * Code. + * @returns {boolean} + * Whether it matches. + */ +export function markdownLineEnding(code) { + return code !== null && code < codes.horizontalTab +} + +/** + * Check whether a character code is a markdown line ending (see + * `markdownLineEnding`) or markdown space (see `markdownSpace`). + * + * @param {Code} code + * Code. + * @returns {boolean} + * Whether it matches. + */ +export function markdownLineEndingOrSpace(code) { + return code !== null && (code < codes.nul || code === codes.space) +} + +/** + * Check whether a character code is a markdown space. + * + * A **markdown space** is the concrete character U+0020 SPACE (SP) and the + * virtual characters M-0001 VIRTUAL SPACE (VS) and M-0002 HORIZONTAL TAB (HT). + * + * In micromark, the actual character U+0009 CHARACTER TABULATION (HT) is + * replaced by one M-0002 HORIZONTAL TAB (HT) and between 0 and 3 M-0001 VIRTUAL + * SPACE (VS) characters, depending on the column at which the tab occurred. + * + * @param {Code} code + * Code. + * @returns {boolean} + * Whether it matches. + */ +export function markdownSpace(code) { + return ( + code === codes.horizontalTab || + code === codes.virtualSpace || + code === codes.space + ) +} + +// Size note: removing ASCII from the regex and using `asciiPunctuation` here +// In fact adds to the bundle size. +/** + * Check whether the character code represents Unicode punctuation. + * + * A **Unicode punctuation** is a character in the Unicode `Pc` (Punctuation, + * Connector), `Pd` (Punctuation, Dash), `Pe` (Punctuation, Close), `Pf` + * (Punctuation, Final quote), `Pi` (Punctuation, Initial quote), `Po` + * (Punctuation, Other), or `Ps` (Punctuation, Open) categories, or an ASCII + * punctuation (see `asciiPunctuation`). + * + * See: + * **\[UNICODE]**: + * [The Unicode Standard](https://www.unicode.org/versions/). + * Unicode Consortium. + * + * @param code + * Code. + * @returns + * Whether it matches. + */ +export const unicodePunctuation = regexCheck(/\p{P}|\p{S}/u) + +/** + * Check whether the character code represents Unicode whitespace. + * + * Note that this does handle micromark specific markdown whitespace characters. + * See `markdownLineEndingOrSpace` to check that. + * + * A **Unicode whitespace** is a character in the Unicode `Zs` (Separator, + * Space) category, or U+0009 CHARACTER TABULATION (HT), U+000A LINE FEED (LF), + * U+000C (FF), or U+000D CARRIAGE RETURN (CR) (**\[UNICODE]**). + * + * See: + * **\[UNICODE]**: + * [The Unicode Standard](https://www.unicode.org/versions/). + * Unicode Consortium. + * + * @param code + * Code. + * @returns + * Whether it matches. + */ +export const unicodeWhitespace = regexCheck(/\s/) + +/** + * Create a code check from a regex. + * + * @param {RegExp} regex + * Expression. + * @returns {(code: Code) => boolean} + * Check. + */ +function regexCheck(regex) { + return check + + /** + * Check whether a code matches the bound regex. + * + * @param {Code} code + * Character code. + * @returns {boolean} + * Whether the character code matches the bound regex. + */ + function check(code) { + return code !== null && code > -1 && regex.test(String.fromCharCode(code)) + } +} diff --git a/node_modules/micromark-util-character/index.d.ts b/node_modules/micromark-util-character/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fe5289573d03c84b318810d89f5dfbd49702d853 --- /dev/null +++ b/node_modules/micromark-util-character/index.d.ts @@ -0,0 +1,195 @@ +/** + * Check whether a character code is an ASCII control character. + * + * An **ASCII control** is a character in the inclusive range U+0000 NULL (NUL) + * to U+001F (US), or U+007F (DEL). + * + * @param {Code} code + * Code. + * @returns {boolean} + * Whether it matches. + */ +export function asciiControl(code: Code): boolean; +/** + * Check whether a character code is a markdown line ending. + * + * A **markdown line ending** is the virtual characters M-0003 CARRIAGE RETURN + * LINE FEED (CRLF), M-0004 LINE FEED (LF) and M-0005 CARRIAGE RETURN (CR). + * + * In micromark, the actual character U+000A LINE FEED (LF) and U+000D CARRIAGE + * RETURN (CR) are replaced by these virtual characters depending on whether + * they occurred together. + * + * @param {Code} code + * Code. + * @returns {boolean} + * Whether it matches. + */ +export function markdownLineEnding(code: Code): boolean; +/** + * Check whether a character code is a markdown line ending (see + * `markdownLineEnding`) or markdown space (see `markdownSpace`). + * + * @param {Code} code + * Code. + * @returns {boolean} + * Whether it matches. + */ +export function markdownLineEndingOrSpace(code: Code): boolean; +/** + * Check whether a character code is a markdown space. + * + * A **markdown space** is the concrete character U+0020 SPACE (SP) and the + * virtual characters M-0001 VIRTUAL SPACE (VS) and M-0002 HORIZONTAL TAB (HT). + * + * In micromark, the actual character U+0009 CHARACTER TABULATION (HT) is + * replaced by one M-0002 HORIZONTAL TAB (HT) and between 0 and 3 M-0001 VIRTUAL + * SPACE (VS) characters, depending on the column at which the tab occurred. + * + * @param {Code} code + * Code. + * @returns {boolean} + * Whether it matches. + */ +export function markdownSpace(code: Code): boolean; +/** + * Check whether the character code represents an ASCII alpha (`a` through `z`, + * case insensitive). + * + * An **ASCII alpha** is an ASCII upper alpha or ASCII lower alpha. + * + * An **ASCII upper alpha** is a character in the inclusive range U+0041 (`A`) + * to U+005A (`Z`). + * + * An **ASCII lower alpha** is a character in the inclusive range U+0061 (`a`) + * to U+007A (`z`). + * + * @param code + * Code. + * @returns {boolean} + * Whether it matches. + */ +export const asciiAlpha: (code: Code) => boolean; +/** + * Check whether the character code represents an ASCII alphanumeric (`a` + * through `z`, case insensitive, or `0` through `9`). + * + * An **ASCII alphanumeric** is an ASCII digit (see `asciiDigit`) or ASCII alpha + * (see `asciiAlpha`). + * + * @param code + * Code. + * @returns {boolean} + * Whether it matches. + */ +export const asciiAlphanumeric: (code: Code) => boolean; +/** + * Check whether the character code represents an ASCII atext. + * + * atext is an ASCII alphanumeric (see `asciiAlphanumeric`), or a character in + * the inclusive ranges U+0023 NUMBER SIGN (`#`) to U+0027 APOSTROPHE (`'`), + * U+002A ASTERISK (`*`), U+002B PLUS SIGN (`+`), U+002D DASH (`-`), U+002F + * SLASH (`/`), U+003D EQUALS TO (`=`), U+003F QUESTION MARK (`?`), U+005E + * CARET (`^`) to U+0060 GRAVE ACCENT (`` ` ``), or U+007B LEFT CURLY BRACE + * (`{`) to U+007E TILDE (`~`). + * + * See: + * **\[RFC5322]**: + * [Internet Message Format](https://tools.ietf.org/html/rfc5322). + * P. Resnick. + * IETF. + * + * @param code + * Code. + * @returns {boolean} + * Whether it matches. + */ +export const asciiAtext: (code: Code) => boolean; +/** + * Check whether the character code represents an ASCII digit (`0` through `9`). + * + * An **ASCII digit** is a character in the inclusive range U+0030 (`0`) to + * U+0039 (`9`). + * + * @param code + * Code. + * @returns {boolean} + * Whether it matches. + */ +export const asciiDigit: (code: Code) => boolean; +/** + * Check whether the character code represents an ASCII hex digit (`a` through + * `f`, case insensitive, or `0` through `9`). + * + * An **ASCII hex digit** is an ASCII digit (see `asciiDigit`), ASCII upper hex + * digit, or an ASCII lower hex digit. + * + * An **ASCII upper hex digit** is a character in the inclusive range U+0041 + * (`A`) to U+0046 (`F`). + * + * An **ASCII lower hex digit** is a character in the inclusive range U+0061 + * (`a`) to U+0066 (`f`). + * + * @param code + * Code. + * @returns {boolean} + * Whether it matches. + */ +export const asciiHexDigit: (code: Code) => boolean; +/** + * Check whether the character code represents ASCII punctuation. + * + * An **ASCII punctuation** is a character in the inclusive ranges U+0021 + * EXCLAMATION MARK (`!`) to U+002F SLASH (`/`), U+003A COLON (`:`) to U+0040 AT + * SIGN (`@`), U+005B LEFT SQUARE BRACKET (`[`) to U+0060 GRAVE ACCENT + * (`` ` ``), or U+007B LEFT CURLY BRACE (`{`) to U+007E TILDE (`~`). + * + * @param code + * Code. + * @returns {boolean} + * Whether it matches. + */ +export const asciiPunctuation: (code: Code) => boolean; +/** + * Check whether the character code represents Unicode punctuation. + * + * A **Unicode punctuation** is a character in the Unicode `Pc` (Punctuation, + * Connector), `Pd` (Punctuation, Dash), `Pe` (Punctuation, Close), `Pf` + * (Punctuation, Final quote), `Pi` (Punctuation, Initial quote), `Po` + * (Punctuation, Other), or `Ps` (Punctuation, Open) categories, or an ASCII + * punctuation (see `asciiPunctuation`). + * + * See: + * **\[UNICODE]**: + * [The Unicode Standard](https://www.unicode.org/versions/). + * Unicode Consortium. + * + * @param code + * Code. + * @returns + * Whether it matches. + */ +export const unicodePunctuation: (code: Code) => boolean; +/** + * Check whether the character code represents Unicode whitespace. + * + * Note that this does handle micromark specific markdown whitespace characters. + * See `markdownLineEndingOrSpace` to check that. + * + * A **Unicode whitespace** is a character in the Unicode `Zs` (Separator, + * Space) category, or U+0009 CHARACTER TABULATION (HT), U+000A LINE FEED (LF), + * U+000C (FF), or U+000D CARRIAGE RETURN (CR) (**\[UNICODE]**). + * + * See: + * **\[UNICODE]**: + * [The Unicode Standard](https://www.unicode.org/versions/). + * Unicode Consortium. + * + * @param code + * Code. + * @returns + * Whether it matches. + */ +export const unicodeWhitespace: (code: Code) => boolean; +import type { Code } from 'micromark-util-types'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/micromark-util-character/index.d.ts.map b/node_modules/micromark-util-character/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..8ded3c1570e11682a465c097443a291216ea9b1a --- /dev/null +++ b/node_modules/micromark-util-character/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.js"],"names":[],"mappings":"AA8DA;;;;;;;;;;GAUG;AACH,mCALW,IAAI,GAEF,OAAO,CASnB;AAkDD;;;;;;;;;;;;;;GAcG;AACH,yCALW,IAAI,GAEF,OAAO,CAKnB;AAED;;;;;;;;GAQG;AACH,gDALW,IAAI,GAEF,OAAO,CAKnB;AAED;;;;;;;;;;;;;;GAcG;AACH,oCALW,IAAI,GAEF,OAAO,CASnB;AAhLD;;;;;;;;;;;;;;;;GAgBG;AACH,gCAmNoB,IAAI,KAAK,OAAO,CAnNY;AAEhD;;;;;;;;;;;GAWG;AACH,uCAqMoB,IAAI,KAAK,OAAO,CArMqB;AAEzD;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,gCA8KoB,IAAI,KAAK,OAAO,CA9KuB;AAqB3D;;;;;;;;;;GAUG;AACH,gCA8IoB,IAAI,KAAK,OAAO,CA9IM;AAE1C;;;;;;;;;;;;;;;;;GAiBG;AACH,mCA0HoB,IAAI,KAAK,OAAO,CA1HiB;AAErD;;;;;;;;;;;;GAYG;AACH,sCA2GoB,IAAI,KAAK,OAAO,CA3GwB;AA2D5D;;;;;;;;;;;;;;;;;;GAkBG;AACH,wCA6BoB,IAAI,KAAK,OAAO,CA7BwB;AAE5D;;;;;;;;;;;;;;;;;;;GAmBG;AACH,uCAOoB,IAAI,KAAK,OAAO,CAPa;0BAlO1B,sBAAsB"} \ No newline at end of file diff --git a/node_modules/micromark-util-character/index.js b/node_modules/micromark-util-character/index.js new file mode 100644 index 0000000000000000000000000000000000000000..13698f04f2ea3591b7ca012b4270e027fb73e9bf --- /dev/null +++ b/node_modules/micromark-util-character/index.js @@ -0,0 +1,246 @@ +/** + * @import {Code} from 'micromark-util-types' + */ + +/** + * Check whether the character code represents an ASCII alpha (`a` through `z`, + * case insensitive). + * + * An **ASCII alpha** is an ASCII upper alpha or ASCII lower alpha. + * + * An **ASCII upper alpha** is a character in the inclusive range U+0041 (`A`) + * to U+005A (`Z`). + * + * An **ASCII lower alpha** is a character in the inclusive range U+0061 (`a`) + * to U+007A (`z`). + * + * @param code + * Code. + * @returns {boolean} + * Whether it matches. + */ +export const asciiAlpha = regexCheck(/[A-Za-z]/); + +/** + * Check whether the character code represents an ASCII alphanumeric (`a` + * through `z`, case insensitive, or `0` through `9`). + * + * An **ASCII alphanumeric** is an ASCII digit (see `asciiDigit`) or ASCII alpha + * (see `asciiAlpha`). + * + * @param code + * Code. + * @returns {boolean} + * Whether it matches. + */ +export const asciiAlphanumeric = regexCheck(/[\dA-Za-z]/); + +/** + * Check whether the character code represents an ASCII atext. + * + * atext is an ASCII alphanumeric (see `asciiAlphanumeric`), or a character in + * the inclusive ranges U+0023 NUMBER SIGN (`#`) to U+0027 APOSTROPHE (`'`), + * U+002A ASTERISK (`*`), U+002B PLUS SIGN (`+`), U+002D DASH (`-`), U+002F + * SLASH (`/`), U+003D EQUALS TO (`=`), U+003F QUESTION MARK (`?`), U+005E + * CARET (`^`) to U+0060 GRAVE ACCENT (`` ` ``), or U+007B LEFT CURLY BRACE + * (`{`) to U+007E TILDE (`~`). + * + * See: + * **\[RFC5322]**: + * [Internet Message Format](https://tools.ietf.org/html/rfc5322). + * P. Resnick. + * IETF. + * + * @param code + * Code. + * @returns {boolean} + * Whether it matches. + */ +export const asciiAtext = regexCheck(/[#-'*+\--9=?A-Z^-~]/); + +/** + * Check whether a character code is an ASCII control character. + * + * An **ASCII control** is a character in the inclusive range U+0000 NULL (NUL) + * to U+001F (US), or U+007F (DEL). + * + * @param {Code} code + * Code. + * @returns {boolean} + * Whether it matches. + */ +export function asciiControl(code) { + return ( + // Special whitespace codes (which have negative values), C0 and Control + // character DEL + code !== null && (code < 32 || code === 127) + ); +} + +/** + * Check whether the character code represents an ASCII digit (`0` through `9`). + * + * An **ASCII digit** is a character in the inclusive range U+0030 (`0`) to + * U+0039 (`9`). + * + * @param code + * Code. + * @returns {boolean} + * Whether it matches. + */ +export const asciiDigit = regexCheck(/\d/); + +/** + * Check whether the character code represents an ASCII hex digit (`a` through + * `f`, case insensitive, or `0` through `9`). + * + * An **ASCII hex digit** is an ASCII digit (see `asciiDigit`), ASCII upper hex + * digit, or an ASCII lower hex digit. + * + * An **ASCII upper hex digit** is a character in the inclusive range U+0041 + * (`A`) to U+0046 (`F`). + * + * An **ASCII lower hex digit** is a character in the inclusive range U+0061 + * (`a`) to U+0066 (`f`). + * + * @param code + * Code. + * @returns {boolean} + * Whether it matches. + */ +export const asciiHexDigit = regexCheck(/[\dA-Fa-f]/); + +/** + * Check whether the character code represents ASCII punctuation. + * + * An **ASCII punctuation** is a character in the inclusive ranges U+0021 + * EXCLAMATION MARK (`!`) to U+002F SLASH (`/`), U+003A COLON (`:`) to U+0040 AT + * SIGN (`@`), U+005B LEFT SQUARE BRACKET (`[`) to U+0060 GRAVE ACCENT + * (`` ` ``), or U+007B LEFT CURLY BRACE (`{`) to U+007E TILDE (`~`). + * + * @param code + * Code. + * @returns {boolean} + * Whether it matches. + */ +export const asciiPunctuation = regexCheck(/[!-/:-@[-`{-~]/); + +/** + * Check whether a character code is a markdown line ending. + * + * A **markdown line ending** is the virtual characters M-0003 CARRIAGE RETURN + * LINE FEED (CRLF), M-0004 LINE FEED (LF) and M-0005 CARRIAGE RETURN (CR). + * + * In micromark, the actual character U+000A LINE FEED (LF) and U+000D CARRIAGE + * RETURN (CR) are replaced by these virtual characters depending on whether + * they occurred together. + * + * @param {Code} code + * Code. + * @returns {boolean} + * Whether it matches. + */ +export function markdownLineEnding(code) { + return code !== null && code < -2; +} + +/** + * Check whether a character code is a markdown line ending (see + * `markdownLineEnding`) or markdown space (see `markdownSpace`). + * + * @param {Code} code + * Code. + * @returns {boolean} + * Whether it matches. + */ +export function markdownLineEndingOrSpace(code) { + return code !== null && (code < 0 || code === 32); +} + +/** + * Check whether a character code is a markdown space. + * + * A **markdown space** is the concrete character U+0020 SPACE (SP) and the + * virtual characters M-0001 VIRTUAL SPACE (VS) and M-0002 HORIZONTAL TAB (HT). + * + * In micromark, the actual character U+0009 CHARACTER TABULATION (HT) is + * replaced by one M-0002 HORIZONTAL TAB (HT) and between 0 and 3 M-0001 VIRTUAL + * SPACE (VS) characters, depending on the column at which the tab occurred. + * + * @param {Code} code + * Code. + * @returns {boolean} + * Whether it matches. + */ +export function markdownSpace(code) { + return code === -2 || code === -1 || code === 32; +} + +// Size note: removing ASCII from the regex and using `asciiPunctuation` here +// In fact adds to the bundle size. +/** + * Check whether the character code represents Unicode punctuation. + * + * A **Unicode punctuation** is a character in the Unicode `Pc` (Punctuation, + * Connector), `Pd` (Punctuation, Dash), `Pe` (Punctuation, Close), `Pf` + * (Punctuation, Final quote), `Pi` (Punctuation, Initial quote), `Po` + * (Punctuation, Other), or `Ps` (Punctuation, Open) categories, or an ASCII + * punctuation (see `asciiPunctuation`). + * + * See: + * **\[UNICODE]**: + * [The Unicode Standard](https://www.unicode.org/versions/). + * Unicode Consortium. + * + * @param code + * Code. + * @returns + * Whether it matches. + */ +export const unicodePunctuation = regexCheck(/\p{P}|\p{S}/u); + +/** + * Check whether the character code represents Unicode whitespace. + * + * Note that this does handle micromark specific markdown whitespace characters. + * See `markdownLineEndingOrSpace` to check that. + * + * A **Unicode whitespace** is a character in the Unicode `Zs` (Separator, + * Space) category, or U+0009 CHARACTER TABULATION (HT), U+000A LINE FEED (LF), + * U+000C (FF), or U+000D CARRIAGE RETURN (CR) (**\[UNICODE]**). + * + * See: + * **\[UNICODE]**: + * [The Unicode Standard](https://www.unicode.org/versions/). + * Unicode Consortium. + * + * @param code + * Code. + * @returns + * Whether it matches. + */ +export const unicodeWhitespace = regexCheck(/\s/); + +/** + * Create a code check from a regex. + * + * @param {RegExp} regex + * Expression. + * @returns {(code: Code) => boolean} + * Check. + */ +function regexCheck(regex) { + return check; + + /** + * Check whether a code matches the bound regex. + * + * @param {Code} code + * Character code. + * @returns {boolean} + * Whether the character code matches the bound regex. + */ + function check(code) { + return code !== null && code > -1 && regex.test(String.fromCharCode(code)); + } +} \ No newline at end of file diff --git a/node_modules/micromark-util-character/license b/node_modules/micromark-util-character/license new file mode 100644 index 0000000000000000000000000000000000000000..bc8f165a62768a19de38901d81ac662c51ff29db --- /dev/null +++ b/node_modules/micromark-util-character/license @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) Titus Wormer + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/micromark-util-character/package.json b/node_modules/micromark-util-character/package.json new file mode 100644 index 0000000000000000000000000000000000000000..8af57e3999850b9889844fae78f54beff70f6d19 --- /dev/null +++ b/node_modules/micromark-util-character/package.json @@ -0,0 +1,57 @@ +{ + "name": "micromark-util-character", + "version": "2.1.1", + "description": "micromark utility to handle character codes", + "license": "MIT", + "keywords": [ + "micromark", + "util", + "utility", + "character" + ], + "repository": "https://github.com/micromark/micromark/tree/main/packages/micromark-util-character", + "bugs": "https://github.com/micromark/micromark/issues", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "author": "Titus Wormer (https://wooorm.com)", + "contributors": [ + "Titus Wormer (https://wooorm.com)" + ], + "sideEffects": false, + "type": "module", + "files": [ + "dev/", + "lib/", + "index.d.ts.map", + "index.d.ts", + "index.js" + ], + "exports": { + "development": "./dev/index.js", + "default": "./index.js" + }, + "dependencies": { + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + }, + "scripts": { + "build": "micromark-build" + }, + "xo": { + "envs": [ + "shared-node-browser" + ], + "prettier": true, + "rules": { + "unicorn/prefer-code-point": "off" + } + } +} diff --git a/node_modules/micromark-util-character/readme.md b/node_modules/micromark-util-character/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..2356e4720f39bdb46d111732b65f30aa212d7098 --- /dev/null +++ b/node_modules/micromark-util-character/readme.md @@ -0,0 +1,446 @@ +# micromark-util-character + +[![Build][build-badge]][build] +[![Coverage][coverage-badge]][coverage] +[![Downloads][downloads-badge]][downloads] +[![Size][bundle-size-badge]][bundle-size] +[![Sponsors][sponsors-badge]][opencollective] +[![Backers][backers-badge]][opencollective] +[![Chat][chat-badge]][chat] + +[micromark][] utility to handle [character codes][code]. + +## Contents + +* [What is this?](#what-is-this) +* [When should I use this?](#when-should-i-use-this) +* [Install](#install) +* [Use](#use) +* [API](#api) + * [`asciiAlpha(code)`](#asciialphacode) + * [`asciiAlphanumeric(code)`](#asciialphanumericcode) + * [`asciiAtext(code)`](#asciiatextcode) + * [`asciiControl(code)`](#asciicontrolcode) + * [`asciiDigit(code)`](#asciidigitcode) + * [`asciiHexDigit(code)`](#asciihexdigitcode) + * [`asciiPunctuation(code)`](#asciipunctuationcode) + * [`markdownLineEnding(code)`](#markdownlineendingcode) + * [`markdownLineEndingOrSpace(code)`](#markdownlineendingorspacecode) + * [`markdownSpace(code)`](#markdownspacecode) + * [`unicodePunctuation(code)`](#unicodepunctuationcode) + * [`unicodeWhitespace(code)`](#unicodewhitespacecode) +* [Types](#types) +* [Compatibility](#compatibility) +* [Security](#security) +* [Contribute](#contribute) +* [License](#license) + +## What is this? + +This package exposes algorithms to check whether characters match groups. + +## When should I use this? + +This package might be useful when you are making your own micromark extensions. + +## Install + +This package is [ESM only][esm]. +In Node.js (version 16+), install with [npm][]: + +```sh +npm install micromark-util-character +``` + +In Deno with [`esm.sh`][esmsh]: + +```js +import * as character from 'https://esm.sh/micromark-util-character@1' +``` + +In browsers with [`esm.sh`][esmsh]: + +```html + +``` + +## Use + +```js +import {asciiAlpha} from 'micromark-util-character' + +console.log(asciiAlpha(64)) // false +console.log(asciiAlpha(65)) // true +``` + +## API + +This module exports the identifiers +[`asciiAlpha`][api-ascii-alpha], +[`asciiAlphanumeric`][api-ascii-alphanumeric], +[`asciiAtext`][api-ascii-atext], +[`asciiControl`][api-ascii-control], +[`asciiDigit`][api-ascii-digit], +[`asciiHexDigit`][api-ascii-hex-digit], +[`asciiPunctuation`][api-ascii-punctuation], +[`markdownLineEnding`][api-markdown-line-ending], +[`markdownLineEndingOrSpace`][api-markdown-line-ending-or-space], +[`markdownSpace`][api-markdown-space], +[`unicodePunctuation`][api-unicode-punctuation], +[`unicodeWhitespace`][api-unicode-whitespace]. +There is no default export. + +### `asciiAlpha(code)` + +Check whether the [character code][code] represents an ASCII alpha (`a` through +`z`, case insensitive). + +An **ASCII alpha** is an ASCII upper alpha or ASCII lower alpha. + +An **ASCII upper alpha** is a character in the inclusive range U+0041 (`A`) +to U+005A (`Z`). + +An **ASCII lower alpha** is a character in the inclusive range U+0061 (`a`) +to U+007A (`z`). + +###### Parameters + +* `code` (`Code`) + — code + +###### Returns + +Whether it matches (`boolean`). + +### `asciiAlphanumeric(code)` + +Check whether the [character code][code] represents an ASCII alphanumeric (`a` +through `z`, case insensitive, or `0` through `9`). + +An **ASCII alphanumeric** is an ASCII digit (see `asciiDigit`) or ASCII alpha +(see `asciiAlpha`). + +###### Parameters + +* `code` (`Code`) + — code + +###### Returns + +Whether it matches (`boolean`). + +### `asciiAtext(code)` + +Check whether the [character code][code] represents an ASCII atext. + +atext is an ASCII alphanumeric (see `asciiAlphanumeric`), or a character in +the inclusive ranges U+0023 NUMBER SIGN (`#`) to U+0027 APOSTROPHE (`'`), +U+002A ASTERISK (`*`), U+002B PLUS SIGN (`+`), U+002D DASH (`-`), U+002F +SLASH (`/`), U+003D EQUALS TO (`=`), U+003F QUESTION MARK (`?`), U+005E +CARET (`^`) to U+0060 GRAVE ACCENT (`` ` ``), or U+007B LEFT CURLY BRACE +(`{`) to U+007E TILDE (`~`) (**\[RFC5322]**). + +See **\[RFC5322]**:\ +[Internet Message Format](https://tools.ietf.org/html/rfc5322).\ +P. Resnick.\ +IETF. + +###### Parameters + +* `code` (`Code`) + — code + +###### Returns + +Whether it matches (`boolean`). + +### `asciiControl(code)` + +Check whether a [character code][code] is an ASCII control character. + +An **ASCII control** is a character in the inclusive range U+0000 NULL (NUL) +to U+001F (US), or U+007F (DEL). + +###### Parameters + +* `code` (`Code`) + — code + +###### Returns + +Whether it matches (`boolean`). + +### `asciiDigit(code)` + +Check whether the [character code][code] represents an ASCII digit (`0` through +`9`). + +An **ASCII digit** is a character in the inclusive range U+0030 (`0`) to +U+0039 (`9`). + +###### Parameters + +* `code` (`Code`) + — code + +###### Returns + +Whether it matches (`boolean`). + +### `asciiHexDigit(code)` + +Check whether the [character code][code] represents an ASCII hex digit (`a` +through `f`, case insensitive, or `0` through `9`). + +An **ASCII hex digit** is an ASCII digit (see `asciiDigit`), ASCII upper hex +digit, or an ASCII lower hex digit. + +An **ASCII upper hex digit** is a character in the inclusive range U+0041 +(`A`) to U+0046 (`F`). + +An **ASCII lower hex digit** is a character in the inclusive range U+0061 +(`a`) to U+0066 (`f`). + +###### Parameters + +* `code` (`Code`) + — code + +###### Returns + +Whether it matches (`boolean`). + +### `asciiPunctuation(code)` + +Check whether the [character code][code] represents ASCII punctuation. + +An **ASCII punctuation** is a character in the inclusive ranges U+0021 +EXCLAMATION MARK (`!`) to U+002F SLASH (`/`), U+003A COLON (`:`) to U+0040 AT +SIGN (`@`), U+005B LEFT SQUARE BRACKET (`[`) to U+0060 GRAVE ACCENT +(`` ` ``), or U+007B LEFT CURLY BRACE (`{`) to U+007E TILDE (`~`). + +###### Parameters + +* `code` (`Code`) + — code + +###### Returns + +Whether it matches (`boolean`). + +### `markdownLineEnding(code)` + +Check whether a [character code][code] is a markdown line ending. + +A **markdown line ending** is the virtual characters M-0003 CARRIAGE RETURN +LINE FEED (CRLF), M-0004 LINE FEED (LF) and M-0005 CARRIAGE RETURN (CR). + +In micromark, the actual character U+000A LINE FEED (LF) and U+000D CARRIAGE +RETURN (CR) are replaced by these virtual characters depending on whether +they occurred together. + +###### Parameters + +* `code` (`Code`) + — code + +###### Returns + +Whether it matches (`boolean`). + +### `markdownLineEndingOrSpace(code)` + +Check whether a [character code][code] is a markdown line ending (see +`markdownLineEnding`) or markdown space (see `markdownSpace`). + +###### Parameters + +* `code` (`Code`) + — code + +###### Returns + +Whether it matches (`boolean`). + +### `markdownSpace(code)` + +Check whether a [character code][code] is a markdown space. + +A **markdown space** is the concrete character U+0020 SPACE (SP) and the +virtual characters M-0001 VIRTUAL SPACE (VS) and M-0002 HORIZONTAL TAB (HT). + +In micromark, the actual character U+0009 CHARACTER TABULATION (HT) is +replaced by one M-0002 HORIZONTAL TAB (HT) and between 0 and 3 M-0001 VIRTUAL +SPACE (VS) characters, depending on the column at which the tab occurred. + +###### Parameters + +* `code` (`Code`) + — code + +###### Returns + +Whether it matches (`boolean`). + +### `unicodePunctuation(code)` + +Check whether the [character code][code] represents Unicode punctuation. + +A **Unicode punctuation** is a character in the Unicode `Pc` (Punctuation, +Connector), `Pd` (Punctuation, Dash), `Pe` (Punctuation, Close), `Pf` +(Punctuation, Final quote), `Pi` (Punctuation, Initial quote), `Po` +(Punctuation, Other), or `Ps` (Punctuation, Open) categories, or an ASCII +punctuation (see `asciiPunctuation`) (**\[UNICODE]**). + +See **\[UNICODE]**:\ +[The Unicode Standard](https://www.unicode.org/versions/).\ +Unicode Consortium. + +###### Parameters + +* `code` (`Code`) + — code + +###### Returns + +Whether it matches (`boolean`). + +### `unicodeWhitespace(code)` + +Check whether the [character code][code] represents Unicode whitespace. + +Note that this does handle micromark specific markdown whitespace characters. +See `markdownLineEndingOrSpace` to check that. + +A **Unicode whitespace** is a character in the Unicode `Zs` (Separator, +Space) category, or U+0009 CHARACTER TABULATION (HT), U+000A LINE FEED (LF), +U+000C (FF), or U+000D CARRIAGE RETURN (CR) (**\[UNICODE]**). + +See **\[UNICODE]**:\ +[The Unicode Standard](https://www.unicode.org/versions/).\ +Unicode Consortium. + +###### Parameters + +* `code` (`Code`) + — code + +###### Returns + +Whether it matches (`boolean`). + +## Types + +This package is fully typed with [TypeScript][]. +It exports no additional types. + +## Compatibility + +Projects maintained by the unified collective are compatible with maintained +versions of Node.js. + +When we cut a new major release, we drop support for unmaintained versions of +Node. +This means we try to keep the current release line, +`micromark-util-character@2`, compatible with Node.js 16. +This package works with `micromark@3`. + +## Security + +This package is safe. +See [`security.md`][securitymd] in [`micromark/.github`][health] for how to +submit a security report. + +## Contribute + +See [`contributing.md`][contributing] in [`micromark/.github`][health] for ways +to get started. +See [`support.md`][support] for ways to get help. + +This project has a [code of conduct][coc]. +By interacting with this repository, organisation, or community you agree to +abide by its terms. + +## License + +[MIT][license] © [Titus Wormer][author] + + + +[build-badge]: https://github.com/micromark/micromark/workflows/main/badge.svg + +[build]: https://github.com/micromark/micromark/actions + +[coverage-badge]: https://img.shields.io/codecov/c/github/micromark/micromark.svg + +[coverage]: https://codecov.io/github/micromark/micromark + +[downloads-badge]: https://img.shields.io/npm/dm/micromark-util-character.svg + +[downloads]: https://www.npmjs.com/package/micromark-util-character + +[bundle-size-badge]: https://img.shields.io/badge/dynamic/json?label=minzipped%20size&query=$.size.compressedSize&url=https://deno.bundlejs.com/?q=micromark-util-character + +[bundle-size]: https://bundlejs.com/?q=micromark-util-character + +[sponsors-badge]: https://opencollective.com/unified/sponsors/badge.svg + +[backers-badge]: https://opencollective.com/unified/backers/badge.svg + +[opencollective]: https://opencollective.com/unified + +[npm]: https://docs.npmjs.com/cli/install + +[esm]: https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c + +[esmsh]: https://esm.sh + +[chat-badge]: https://img.shields.io/badge/chat-discussions-success.svg + +[chat]: https://github.com/micromark/micromark/discussions + +[license]: https://github.com/micromark/micromark/blob/main/license + +[author]: https://wooorm.com + +[health]: https://github.com/micromark/.github + +[securitymd]: https://github.com/micromark/.github/blob/main/security.md + +[contributing]: https://github.com/micromark/.github/blob/main/contributing.md + +[support]: https://github.com/micromark/.github/blob/main/support.md + +[coc]: https://github.com/micromark/.github/blob/main/code-of-conduct.md + +[typescript]: https://www.typescriptlang.org + +[micromark]: https://github.com/micromark/micromark + +[code]: https://github.com/micromark/micromark#preprocess + +[api-ascii-alpha]: #asciialphacode + +[api-ascii-alphanumeric]: #asciialphanumericcode + +[api-ascii-atext]: #asciiatextcode + +[api-ascii-control]: #asciicontrolcode + +[api-ascii-digit]: #asciidigitcode + +[api-ascii-hex-digit]: #asciihexdigitcode + +[api-ascii-punctuation]: #asciipunctuationcode + +[api-markdown-line-ending]: #markdownlineendingcode + +[api-markdown-line-ending-or-space]: #markdownlineendingorspacecode + +[api-markdown-space]: #markdownspacecode + +[api-unicode-punctuation]: #unicodepunctuationcode + +[api-unicode-whitespace]: #unicodewhitespacecode diff --git a/node_modules/micromark-util-chunked/dev/index.d.ts b/node_modules/micromark-util-chunked/dev/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ed04ba20d0cff35b7d99eb1207a9b90f53c46d38 --- /dev/null +++ b/node_modules/micromark-util-chunked/dev/index.d.ts @@ -0,0 +1,41 @@ +/** + * Like `Array#splice`, but smarter for giant arrays. + * + * `Array#splice` takes all items to be inserted as individual argument which + * causes a stack overflow in V8 when trying to insert 100k items for instance. + * + * Otherwise, this does not return the removed items, and takes `items` as an + * array instead of rest parameters. + * + * @template {unknown} T + * Item type. + * @param {Array} list + * List to operate on. + * @param {number} start + * Index to remove/insert at (can be negative). + * @param {number} remove + * Number of items to remove. + * @param {Array} items + * Items to inject into `list`. + * @returns {undefined} + * Nothing. + */ +export function splice(list: Array, start: number, remove: number, items: Array): undefined; +/** + * Append `items` (an array) at the end of `list` (another array). + * When `list` was empty, returns `items` instead. + * + * This prevents a potentially expensive operation when `list` is empty, + * and adds items in batches to prevent V8 from hanging. + * + * @template {unknown} T + * Item type. + * @param {Array} list + * List to operate on. + * @param {Array} items + * Items to add to `list`. + * @returns {Array} + * Either `list` or `items`. + */ +export function push(list: Array, items: Array): Array; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/micromark-util-chunked/dev/index.d.ts.map b/node_modules/micromark-util-chunked/dev/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..432125397dfaddd1ad0533e9860cabd6ee7187a3 --- /dev/null +++ b/node_modules/micromark-util-chunked/dev/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.js"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,uBAbuB,CAAC,SAAX,OAAS,QAEX,KAAK,CAAC,CAAC,CAAC,SAER,MAAM,UAEN,MAAM,SAEN,KAAK,CAAC,CAAC,CAAC,GAEN,SAAS,CA0CrB;AAED;;;;;;;;;;;;;;;GAeG;AACH,qBATuB,CAAC,SAAX,OAAS,QAEX,KAAK,CAAC,CAAC,CAAC,SAER,KAAK,CAAC,CAAC,CAAC,GAEN,KAAK,CAAC,CAAC,CAAC,CAUpB"} \ No newline at end of file diff --git a/node_modules/micromark-util-chunked/dev/index.js b/node_modules/micromark-util-chunked/dev/index.js new file mode 100644 index 0000000000000000000000000000000000000000..7b6a18f8713efbd01e657c4861fdf9bea2fcc881 --- /dev/null +++ b/node_modules/micromark-util-chunked/dev/index.js @@ -0,0 +1,89 @@ +import {constants} from 'micromark-util-symbol' + +/** + * Like `Array#splice`, but smarter for giant arrays. + * + * `Array#splice` takes all items to be inserted as individual argument which + * causes a stack overflow in V8 when trying to insert 100k items for instance. + * + * Otherwise, this does not return the removed items, and takes `items` as an + * array instead of rest parameters. + * + * @template {unknown} T + * Item type. + * @param {Array} list + * List to operate on. + * @param {number} start + * Index to remove/insert at (can be negative). + * @param {number} remove + * Number of items to remove. + * @param {Array} items + * Items to inject into `list`. + * @returns {undefined} + * Nothing. + */ +export function splice(list, start, remove, items) { + const end = list.length + let chunkStart = 0 + /** @type {Array} */ + let parameters + + // Make start between zero and `end` (included). + if (start < 0) { + start = -start > end ? 0 : end + start + } else { + start = start > end ? end : start + } + + remove = remove > 0 ? remove : 0 + + // No need to chunk the items if there’s only a couple (10k) items. + if (items.length < constants.v8MaxSafeChunkSize) { + parameters = Array.from(items) + parameters.unshift(start, remove) + // @ts-expect-error Hush, it’s fine. + list.splice(...parameters) + } else { + // Delete `remove` items starting from `start` + if (remove) list.splice(start, remove) + + // Insert the items in chunks to not cause stack overflows. + while (chunkStart < items.length) { + parameters = items.slice( + chunkStart, + chunkStart + constants.v8MaxSafeChunkSize + ) + parameters.unshift(start, 0) + // @ts-expect-error Hush, it’s fine. + list.splice(...parameters) + + chunkStart += constants.v8MaxSafeChunkSize + start += constants.v8MaxSafeChunkSize + } + } +} + +/** + * Append `items` (an array) at the end of `list` (another array). + * When `list` was empty, returns `items` instead. + * + * This prevents a potentially expensive operation when `list` is empty, + * and adds items in batches to prevent V8 from hanging. + * + * @template {unknown} T + * Item type. + * @param {Array} list + * List to operate on. + * @param {Array} items + * Items to add to `list`. + * @returns {Array} + * Either `list` or `items`. + */ +export function push(list, items) { + if (list.length > 0) { + splice(list, list.length, 0, items) + return list + } + + return items +} diff --git a/node_modules/micromark-util-chunked/index.d.ts b/node_modules/micromark-util-chunked/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ed04ba20d0cff35b7d99eb1207a9b90f53c46d38 --- /dev/null +++ b/node_modules/micromark-util-chunked/index.d.ts @@ -0,0 +1,41 @@ +/** + * Like `Array#splice`, but smarter for giant arrays. + * + * `Array#splice` takes all items to be inserted as individual argument which + * causes a stack overflow in V8 when trying to insert 100k items for instance. + * + * Otherwise, this does not return the removed items, and takes `items` as an + * array instead of rest parameters. + * + * @template {unknown} T + * Item type. + * @param {Array} list + * List to operate on. + * @param {number} start + * Index to remove/insert at (can be negative). + * @param {number} remove + * Number of items to remove. + * @param {Array} items + * Items to inject into `list`. + * @returns {undefined} + * Nothing. + */ +export function splice(list: Array, start: number, remove: number, items: Array): undefined; +/** + * Append `items` (an array) at the end of `list` (another array). + * When `list` was empty, returns `items` instead. + * + * This prevents a potentially expensive operation when `list` is empty, + * and adds items in batches to prevent V8 from hanging. + * + * @template {unknown} T + * Item type. + * @param {Array} list + * List to operate on. + * @param {Array} items + * Items to add to `list`. + * @returns {Array} + * Either `list` or `items`. + */ +export function push(list: Array, items: Array): Array; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/micromark-util-chunked/index.d.ts.map b/node_modules/micromark-util-chunked/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..432125397dfaddd1ad0533e9860cabd6ee7187a3 --- /dev/null +++ b/node_modules/micromark-util-chunked/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.js"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,uBAbuB,CAAC,SAAX,OAAS,QAEX,KAAK,CAAC,CAAC,CAAC,SAER,MAAM,UAEN,MAAM,SAEN,KAAK,CAAC,CAAC,CAAC,GAEN,SAAS,CA0CrB;AAED;;;;;;;;;;;;;;;GAeG;AACH,qBATuB,CAAC,SAAX,OAAS,QAEX,KAAK,CAAC,CAAC,CAAC,SAER,KAAK,CAAC,CAAC,CAAC,GAEN,KAAK,CAAC,CAAC,CAAC,CAUpB"} \ No newline at end of file diff --git a/node_modules/micromark-util-chunked/index.js b/node_modules/micromark-util-chunked/index.js new file mode 100644 index 0000000000000000000000000000000000000000..3a4b2624004bc591d51773ddebe763db7665cfcc --- /dev/null +++ b/node_modules/micromark-util-chunked/index.js @@ -0,0 +1,81 @@ +/** + * Like `Array#splice`, but smarter for giant arrays. + * + * `Array#splice` takes all items to be inserted as individual argument which + * causes a stack overflow in V8 when trying to insert 100k items for instance. + * + * Otherwise, this does not return the removed items, and takes `items` as an + * array instead of rest parameters. + * + * @template {unknown} T + * Item type. + * @param {Array} list + * List to operate on. + * @param {number} start + * Index to remove/insert at (can be negative). + * @param {number} remove + * Number of items to remove. + * @param {Array} items + * Items to inject into `list`. + * @returns {undefined} + * Nothing. + */ +export function splice(list, start, remove, items) { + const end = list.length; + let chunkStart = 0; + /** @type {Array} */ + let parameters; + + // Make start between zero and `end` (included). + if (start < 0) { + start = -start > end ? 0 : end + start; + } else { + start = start > end ? end : start; + } + remove = remove > 0 ? remove : 0; + + // No need to chunk the items if there’s only a couple (10k) items. + if (items.length < 10000) { + parameters = Array.from(items); + parameters.unshift(start, remove); + // @ts-expect-error Hush, it’s fine. + list.splice(...parameters); + } else { + // Delete `remove` items starting from `start` + if (remove) list.splice(start, remove); + + // Insert the items in chunks to not cause stack overflows. + while (chunkStart < items.length) { + parameters = items.slice(chunkStart, chunkStart + 10000); + parameters.unshift(start, 0); + // @ts-expect-error Hush, it’s fine. + list.splice(...parameters); + chunkStart += 10000; + start += 10000; + } + } +} + +/** + * Append `items` (an array) at the end of `list` (another array). + * When `list` was empty, returns `items` instead. + * + * This prevents a potentially expensive operation when `list` is empty, + * and adds items in batches to prevent V8 from hanging. + * + * @template {unknown} T + * Item type. + * @param {Array} list + * List to operate on. + * @param {Array} items + * Items to add to `list`. + * @returns {Array} + * Either `list` or `items`. + */ +export function push(list, items) { + if (list.length > 0) { + splice(list, list.length, 0, items); + return list; + } + return items; +} \ No newline at end of file diff --git a/node_modules/micromark-util-chunked/license b/node_modules/micromark-util-chunked/license new file mode 100644 index 0000000000000000000000000000000000000000..bc8f165a62768a19de38901d81ac662c51ff29db --- /dev/null +++ b/node_modules/micromark-util-chunked/license @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) Titus Wormer + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/micromark-util-chunked/package.json b/node_modules/micromark-util-chunked/package.json new file mode 100644 index 0000000000000000000000000000000000000000..8a5c91d3955accaeb57cd41ac8e07881c376584d --- /dev/null +++ b/node_modules/micromark-util-chunked/package.json @@ -0,0 +1,57 @@ +{ + "name": "micromark-util-chunked", + "version": "2.0.1", + "description": "micromark utility to splice and push with giant arrays", + "license": "MIT", + "keywords": [ + "micromark", + "util", + "utility", + "chunk", + "splice", + "push" + ], + "repository": "https://github.com/micromark/micromark/tree/main/packages/micromark-util-chunked", + "bugs": "https://github.com/micromark/micromark/issues", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "author": "Titus Wormer (https://wooorm.com)", + "contributors": [ + "Titus Wormer (https://wooorm.com)" + ], + "sideEffects": false, + "type": "module", + "files": [ + "dev/", + "index.d.ts.map", + "index.d.ts", + "index.js" + ], + "exports": { + "development": "./dev/index.js", + "default": "./index.js" + }, + "dependencies": { + "micromark-util-symbol": "^2.0.0" + }, + "scripts": { + "build": "micromark-build" + }, + "xo": { + "envs": [ + "shared-node-browser" + ], + "prettier": true, + "rules": { + "unicorn/prefer-code-point": "off" + } + } +} diff --git a/node_modules/micromark-util-chunked/readme.md b/node_modules/micromark-util-chunked/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..6628fad732331d86454e5cca0c7b88df7230383d --- /dev/null +++ b/node_modules/micromark-util-chunked/readme.md @@ -0,0 +1,219 @@ +# micromark-util-chunked + +[![Build][build-badge]][build] +[![Coverage][coverage-badge]][coverage] +[![Downloads][downloads-badge]][downloads] +[![Size][bundle-size-badge]][bundle-size] +[![Sponsors][sponsors-badge]][opencollective] +[![Backers][backers-badge]][opencollective] +[![Chat][chat-badge]][chat] + +[micromark][] utility to splice and push with giant arrays. + +## Contents + +* [What is this?](#what-is-this) +* [When should I use this?](#when-should-i-use-this) +* [Install](#install) +* [Use](#use) +* [API](#api) + * [`push(list, items)`](#pushlist-items) + * [`splice(list, start, remove, items)`](#splicelist-start-remove-items) +* [Types](#types) +* [Compatibility](#compatibility) +* [Security](#security) +* [Contribute](#contribute) +* [License](#license) + +## What is this? + +This package exposes an algorithm to splice for giant arrays, which V8 bugs +out on. + +## When should I use this? + +This package might be useful when you are making your own micromark extensions. + +## Install + +This package is [ESM only][esm]. +In Node.js (version 16+), install with [npm][]: + +```sh +npm install micromark-util-chunked +``` + +In Deno with [`esm.sh`][esmsh]: + +```js +import {push, splice} from 'https://esm.sh/micromark-util-chunked@1' +``` + +In browsers with [`esm.sh`][esmsh]: + +```html + +``` + +## Use + +```js +import {push, splice} from 'micromark-util-chunked' + +// … + +nextEvents = push(nextEvents, [ + ['enter', events[open][1], context], + ['exit', events[open][1], context] +]) + +// … + +splice(events, open - 1, index - open + 3, nextEvents) + +// … +``` + +## API + +This module exports the identifiers [`push`][api-push] +and [`splice`][api-splice]. +There is no default export. + +### `push(list, items)` + +Append `items` (an array) at the end of `list` (another array). +When `list` was empty, returns `items` instead. + +This prevents a potentially expensive operation when `list` is empty, +and adds items in batches to prevent V8 from hanging. + +###### Parameters + +* `list` (`Array`) + — list to operate on +* `items` (`Array`) + — items to add to `list` + +###### Returns + +Either `list` or `items` (`Array`). + +### `splice(list, start, remove, items)` + +Like `Array#splice`, but smarter for giant arrays. + +`Array#splice` takes all items to be inserted as individual argument which +causes a stack overflow in V8 when trying to insert 100k items for instance. + +Otherwise, this does not return the removed items, and takes `items` as an +array instead of rest parameters. + +###### Parameters + +* `list` (`Array`) + — list to operate on +* `start` (`number`) + — index to remove/insert at (can be negative) +* `remove` (`number`) + — number of items to remove +* `items` (`Array`) + — items to inject into `list` + +###### Returns + +Nothing (`undefined`). + +## Types + +This package is fully typed with [TypeScript][]. +It exports no additional types. + +## Compatibility + +Projects maintained by the unified collective are compatible with maintained +versions of Node.js. + +When we cut a new major release, we drop support for unmaintained versions of +Node. +This means we try to keep the current release line, +`micromark-util-chunked@2`, compatible with Node.js 16. +This package works with `micromark@3`. + +## Security + +This package is safe. +See [`security.md`][securitymd] in [`micromark/.github`][health] for how to +submit a security report. + +## Contribute + +See [`contributing.md`][contributing] in [`micromark/.github`][health] for ways +to get started. +See [`support.md`][support] for ways to get help. + +This project has a [code of conduct][coc]. +By interacting with this repository, organisation, or community you agree to +abide by its terms. + +## License + +[MIT][license] © [Titus Wormer][author] + + + +[build-badge]: https://github.com/micromark/micromark/workflows/main/badge.svg + +[build]: https://github.com/micromark/micromark/actions + +[coverage-badge]: https://img.shields.io/codecov/c/github/micromark/micromark.svg + +[coverage]: https://codecov.io/github/micromark/micromark + +[downloads-badge]: https://img.shields.io/npm/dm/micromark-util-chunked.svg + +[downloads]: https://www.npmjs.com/package/micromark-util-chunked + +[bundle-size-badge]: https://img.shields.io/badge/dynamic/json?label=minzipped%20size&query=$.size.compressedSize&url=https://deno.bundlejs.com/?q=micromark-util-chunked + +[bundle-size]: https://bundlejs.com/?q=micromark-util-chunked + +[sponsors-badge]: https://opencollective.com/unified/sponsors/badge.svg + +[backers-badge]: https://opencollective.com/unified/backers/badge.svg + +[opencollective]: https://opencollective.com/unified + +[npm]: https://docs.npmjs.com/cli/install + +[esm]: https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c + +[esmsh]: https://esm.sh + +[chat-badge]: https://img.shields.io/badge/chat-discussions-success.svg + +[chat]: https://github.com/micromark/micromark/discussions + +[license]: https://github.com/micromark/micromark/blob/main/license + +[author]: https://wooorm.com + +[health]: https://github.com/micromark/.github + +[securitymd]: https://github.com/micromark/.github/blob/main/security.md + +[contributing]: https://github.com/micromark/.github/blob/main/contributing.md + +[support]: https://github.com/micromark/.github/blob/main/support.md + +[coc]: https://github.com/micromark/.github/blob/main/code-of-conduct.md + +[typescript]: https://www.typescriptlang.org + +[micromark]: https://github.com/micromark/micromark + +[api-push]: #pushlist-items + +[api-splice]: #splicelist-start-remove-items diff --git a/node_modules/micromark-util-classify-character/dev/index.d.ts b/node_modules/micromark-util-classify-character/dev/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..db98cd1fe96b08d416945581c6f95e75239e3b05 --- /dev/null +++ b/node_modules/micromark-util-classify-character/dev/index.d.ts @@ -0,0 +1,18 @@ +/** + * Classify whether a code represents whitespace, punctuation, or something + * else. + * + * Used for attention (emphasis, strong), whose sequences can open or close + * based on the class of surrounding characters. + * + * > 👉 **Note**: eof (`null`) is seen as whitespace. + * + * @param {Code} code + * Code. + * @returns {typeof constants.characterGroupWhitespace | typeof constants.characterGroupPunctuation | undefined} + * Group. + */ +export function classifyCharacter(code: Code): typeof constants.characterGroupWhitespace | typeof constants.characterGroupPunctuation | undefined; +import type { Code } from 'micromark-util-types'; +import { constants } from 'micromark-util-symbol'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/micromark-util-classify-character/dev/index.d.ts.map b/node_modules/micromark-util-classify-character/dev/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..9b63a5bedd53e2b54bf7c62fcf2d6aa699267602 --- /dev/null +++ b/node_modules/micromark-util-classify-character/dev/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.js"],"names":[],"mappings":"AAWA;;;;;;;;;;;;;GAaG;AACH,wCALW,IAAI,GAEF,OAAO,SAAS,CAAC,wBAAwB,GAAG,OAAO,SAAS,CAAC,yBAAyB,GAAG,SAAS,CAe9G;0BApCsB,sBAAsB;0BAQd,uBAAuB"} \ No newline at end of file diff --git a/node_modules/micromark-util-classify-character/dev/index.js b/node_modules/micromark-util-classify-character/dev/index.js new file mode 100644 index 0000000000000000000000000000000000000000..0d82474555a898de21122e4538bce32bf4ef97ed --- /dev/null +++ b/node_modules/micromark-util-classify-character/dev/index.js @@ -0,0 +1,38 @@ +/** + * @import {Code} from 'micromark-util-types' + */ + +import { + markdownLineEndingOrSpace, + unicodePunctuation, + unicodeWhitespace +} from 'micromark-util-character' +import {codes, constants} from 'micromark-util-symbol' + +/** + * Classify whether a code represents whitespace, punctuation, or something + * else. + * + * Used for attention (emphasis, strong), whose sequences can open or close + * based on the class of surrounding characters. + * + * > 👉 **Note**: eof (`null`) is seen as whitespace. + * + * @param {Code} code + * Code. + * @returns {typeof constants.characterGroupWhitespace | typeof constants.characterGroupPunctuation | undefined} + * Group. + */ +export function classifyCharacter(code) { + if ( + code === codes.eof || + markdownLineEndingOrSpace(code) || + unicodeWhitespace(code) + ) { + return constants.characterGroupWhitespace + } + + if (unicodePunctuation(code)) { + return constants.characterGroupPunctuation + } +} diff --git a/node_modules/micromark-util-classify-character/index.d.ts b/node_modules/micromark-util-classify-character/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..db98cd1fe96b08d416945581c6f95e75239e3b05 --- /dev/null +++ b/node_modules/micromark-util-classify-character/index.d.ts @@ -0,0 +1,18 @@ +/** + * Classify whether a code represents whitespace, punctuation, or something + * else. + * + * Used for attention (emphasis, strong), whose sequences can open or close + * based on the class of surrounding characters. + * + * > 👉 **Note**: eof (`null`) is seen as whitespace. + * + * @param {Code} code + * Code. + * @returns {typeof constants.characterGroupWhitespace | typeof constants.characterGroupPunctuation | undefined} + * Group. + */ +export function classifyCharacter(code: Code): typeof constants.characterGroupWhitespace | typeof constants.characterGroupPunctuation | undefined; +import type { Code } from 'micromark-util-types'; +import { constants } from 'micromark-util-symbol'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/micromark-util-classify-character/index.d.ts.map b/node_modules/micromark-util-classify-character/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..9b63a5bedd53e2b54bf7c62fcf2d6aa699267602 --- /dev/null +++ b/node_modules/micromark-util-classify-character/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.js"],"names":[],"mappings":"AAWA;;;;;;;;;;;;;GAaG;AACH,wCALW,IAAI,GAEF,OAAO,SAAS,CAAC,wBAAwB,GAAG,OAAO,SAAS,CAAC,yBAAyB,GAAG,SAAS,CAe9G;0BApCsB,sBAAsB;0BAQd,uBAAuB"} \ No newline at end of file diff --git a/node_modules/micromark-util-classify-character/index.js b/node_modules/micromark-util-classify-character/index.js new file mode 100644 index 0000000000000000000000000000000000000000..a9aebc6cb8528f0f415e48ca7c1a2ba62b6f6997 --- /dev/null +++ b/node_modules/micromark-util-classify-character/index.js @@ -0,0 +1,27 @@ +/** + * @import {Code} from 'micromark-util-types' + */ + +import { markdownLineEndingOrSpace, unicodePunctuation, unicodeWhitespace } from 'micromark-util-character'; +/** + * Classify whether a code represents whitespace, punctuation, or something + * else. + * + * Used for attention (emphasis, strong), whose sequences can open or close + * based on the class of surrounding characters. + * + * > 👉 **Note**: eof (`null`) is seen as whitespace. + * + * @param {Code} code + * Code. + * @returns {typeof constants.characterGroupWhitespace | typeof constants.characterGroupPunctuation | undefined} + * Group. + */ +export function classifyCharacter(code) { + if (code === null || markdownLineEndingOrSpace(code) || unicodeWhitespace(code)) { + return 1; + } + if (unicodePunctuation(code)) { + return 2; + } +} \ No newline at end of file diff --git a/node_modules/micromark-util-classify-character/license b/node_modules/micromark-util-classify-character/license new file mode 100644 index 0000000000000000000000000000000000000000..bc8f165a62768a19de38901d81ac662c51ff29db --- /dev/null +++ b/node_modules/micromark-util-classify-character/license @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) Titus Wormer + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/micromark-util-classify-character/package.json b/node_modules/micromark-util-classify-character/package.json new file mode 100644 index 0000000000000000000000000000000000000000..f424ff97e678cbf8e5f5f9c533fa0182599e3dd1 --- /dev/null +++ b/node_modules/micromark-util-classify-character/package.json @@ -0,0 +1,59 @@ +{ + "name": "micromark-util-classify-character", + "version": "2.0.1", + "description": "micromark utility to classify whether a character is whitespace or punctuation", + "license": "MIT", + "keywords": [ + "micromark", + "util", + "utility", + "attention", + "classify", + "character" + ], + "repository": "https://github.com/micromark/micromark/tree/main/packages/micromark-util-classify-character", + "bugs": "https://github.com/micromark/micromark/issues", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "author": "Titus Wormer (https://wooorm.com)", + "contributors": [ + "Titus Wormer (https://wooorm.com)" + ], + "sideEffects": false, + "type": "module", + "files": [ + "dev/", + "index.d.ts.map", + "index.d.ts", + "index.js" + ], + "exports": { + "development": "./dev/index.js", + "default": "./index.js" + }, + "dependencies": { + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + }, + "scripts": { + "build": "micromark-build" + }, + "xo": { + "envs": [ + "shared-node-browser" + ], + "prettier": true, + "rules": { + "unicorn/prefer-code-point": "off" + } + } +} diff --git a/node_modules/micromark-util-classify-character/readme.md b/node_modules/micromark-util-classify-character/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..f0b3ee78dc083f02c980509751babdec753d6298 --- /dev/null +++ b/node_modules/micromark-util-classify-character/readme.md @@ -0,0 +1,205 @@ +# micromark-util-classify-character + +[![Build][build-badge]][build] +[![Coverage][coverage-badge]][coverage] +[![Downloads][downloads-badge]][downloads] +[![Size][bundle-size-badge]][bundle-size] +[![Sponsors][sponsors-badge]][opencollective] +[![Backers][backers-badge]][opencollective] +[![Chat][chat-badge]][chat] + +[micromark][] utility to classify whether a character is whitespace or +punctuation. + +## Contents + +* [What is this?](#what-is-this) +* [When should I use this?](#when-should-i-use-this) +* [Install](#install) +* [Use](#use) +* [API](#api) + * [`classifyCharacter(code)`](#classifycharactercode) +* [Types](#types) +* [Compatibility](#compatibility) +* [Security](#security) +* [Contribute](#contribute) +* [License](#license) + +## What is this? + +This package exposes an algorithm to classify characters into 3 categories. + +## When should I use this? + +This package might be useful when you are making your own micromark extensions. + +## Install + +This package is [ESM only][esm]. +In Node.js (version 16+), install with [npm][]: + +```sh +npm install micromark-util-classify-character +``` + +In Deno with [`esm.sh`][esmsh]: + +```js +import {classifyCharacter} from 'https://esm.sh/micromark-util-classify-character@1' +``` + +In browsers with [`esm.sh`][esmsh]: + +```html + +``` + +## Use + +```js +/** + * @this {TokenizeContext} + * Context. + * @type {Tokenizer} + */ +function tokenizeAttention(effects, ok) { + return start + + // … + + /** @type {State} */ + function sequence(code) { + if (code === marker) { + // … + } + + const token = effects.exit('attentionSequence') + const after = classifyCharacter(code) + const open = + !after || (after === constants.characterGroupPunctuation && before) + const close = + !before || (before === constants.characterGroupPunctuation && after) + // … + } + + // … +} +``` + +## API + +This module exports the identifier +[`classifyCharacter`][api-classify-character]. +There is no default export. + +### `classifyCharacter(code)` + +Classify whether a code represents whitespace, punctuation, or something +else. + +Used for attention (emphasis, strong), whose sequences can open or close +based on the class of surrounding characters. + +> 👉 **Note**: eof (`null`) is seen as whitespace. + +###### Parameters + +* `code` (`Code`) + — code + +###### Returns + +Group (`constants.characterGroupWhitespace`, +`constants.characterGroupPunctuation`, or `undefined`). + +## Types + +This package is fully typed with [TypeScript][]. +It exports no additional types. + +## Compatibility + +Projects maintained by the unified collective are compatible with maintained +versions of Node.js. + +When we cut a new major release, we drop support for unmaintained versions of +Node. +This means we try to keep the current release line, +`micromark-util-classify-character@2`, compatible with Node.js 16. +This package works with `micromark@3`. + +## Security + +This package is safe. +See [`security.md`][securitymd] in [`micromark/.github`][health] for how to +submit a security report. + +## Contribute + +See [`contributing.md`][contributing] in [`micromark/.github`][health] for ways +to get started. +See [`support.md`][support] for ways to get help. + +This project has a [code of conduct][coc]. +By interacting with this repository, organisation, or community you agree to +abide by its terms. + +## License + +[MIT][license] © [Titus Wormer][author] + + + +[build-badge]: https://github.com/micromark/micromark/workflows/main/badge.svg + +[build]: https://github.com/micromark/micromark/actions + +[coverage-badge]: https://img.shields.io/codecov/c/github/micromark/micromark.svg + +[coverage]: https://codecov.io/github/micromark/micromark + +[downloads-badge]: https://img.shields.io/npm/dm/micromark-util-classify-character.svg + +[downloads]: https://www.npmjs.com/package/micromark-util-classify-character + +[bundle-size-badge]: https://img.shields.io/badge/dynamic/json?label=minzipped%20size&query=$.size.compressedSize&url=https://deno.bundlejs.com/?q=micromark-util-classify-character + +[bundle-size]: https://bundlejs.com/?q=micromark-util-classify-character + +[sponsors-badge]: https://opencollective.com/unified/sponsors/badge.svg + +[backers-badge]: https://opencollective.com/unified/backers/badge.svg + +[opencollective]: https://opencollective.com/unified + +[npm]: https://docs.npmjs.com/cli/install + +[esm]: https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c + +[esmsh]: https://esm.sh + +[chat-badge]: https://img.shields.io/badge/chat-discussions-success.svg + +[chat]: https://github.com/micromark/micromark/discussions + +[license]: https://github.com/micromark/micromark/blob/main/license + +[author]: https://wooorm.com + +[health]: https://github.com/micromark/.github + +[securitymd]: https://github.com/micromark/.github/blob/main/security.md + +[contributing]: https://github.com/micromark/.github/blob/main/contributing.md + +[support]: https://github.com/micromark/.github/blob/main/support.md + +[coc]: https://github.com/micromark/.github/blob/main/code-of-conduct.md + +[typescript]: https://www.typescriptlang.org + +[micromark]: https://github.com/micromark/micromark + +[api-classify-character]: #classifycharactercode diff --git a/node_modules/micromark-util-combine-extensions/index.d.ts b/node_modules/micromark-util-combine-extensions/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..dbd674cb8b21a6bb115f9ce162f39f40857df362 --- /dev/null +++ b/node_modules/micromark-util-combine-extensions/index.d.ts @@ -0,0 +1,22 @@ +/** + * Combine multiple syntax extensions into one. + * + * @param {ReadonlyArray} extensions + * List of syntax extensions. + * @returns {NormalizedExtension} + * A single combined extension. + */ +export function combineExtensions(extensions: ReadonlyArray): NormalizedExtension; +/** + * Combine multiple HTML extensions into one. + * + * @param {ReadonlyArray} htmlExtensions + * List of HTML extensions. + * @returns {HtmlExtension} + * Single combined HTML extension. + */ +export function combineHtmlExtensions(htmlExtensions: ReadonlyArray): HtmlExtension; +import type { Extension } from 'micromark-util-types'; +import type { NormalizedExtension } from 'micromark-util-types'; +import type { HtmlExtension } from 'micromark-util-types'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/micromark-util-combine-extensions/index.d.ts.map b/node_modules/micromark-util-combine-extensions/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..e0ea7bf1ee4212d691d3451008021174be568ed0 --- /dev/null +++ b/node_modules/micromark-util-combine-extensions/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.js"],"names":[],"mappings":"AAaA;;;;;;;GAOG;AACH,8CALW,aAAa,CAAC,SAAS,CAAC,GAEtB,mBAAmB,CAa/B;AA+DD;;;;;;;GAOG;AACH,sDALW,aAAa,CAAC,aAAa,CAAC,GAE1B,aAAa,CAazB;+BA1GS,sBAAsB;yCAAtB,sBAAsB;mCAAtB,sBAAsB"} \ No newline at end of file diff --git a/node_modules/micromark-util-combine-extensions/index.js b/node_modules/micromark-util-combine-extensions/index.js new file mode 100644 index 0000000000000000000000000000000000000000..bc28f6d9c3184d9da94423271960560323076909 --- /dev/null +++ b/node_modules/micromark-util-combine-extensions/index.js @@ -0,0 +1,143 @@ +/** + * @import { + * Extension, + * Handles, + * HtmlExtension, + * NormalizedExtension + * } from 'micromark-util-types' + */ + +import {splice} from 'micromark-util-chunked' + +const hasOwnProperty = {}.hasOwnProperty + +/** + * Combine multiple syntax extensions into one. + * + * @param {ReadonlyArray} extensions + * List of syntax extensions. + * @returns {NormalizedExtension} + * A single combined extension. + */ +export function combineExtensions(extensions) { + /** @type {NormalizedExtension} */ + const all = {} + let index = -1 + + while (++index < extensions.length) { + syntaxExtension(all, extensions[index]) + } + + return all +} + +/** + * Merge `extension` into `all`. + * + * @param {NormalizedExtension} all + * Extension to merge into. + * @param {Extension} extension + * Extension to merge. + * @returns {undefined} + * Nothing. + */ +function syntaxExtension(all, extension) { + /** @type {keyof Extension} */ + let hook + + for (hook in extension) { + const maybe = hasOwnProperty.call(all, hook) ? all[hook] : undefined + /** @type {Record} */ + const left = maybe || (all[hook] = {}) + /** @type {Record | undefined} */ + const right = extension[hook] + /** @type {string} */ + let code + + if (right) { + for (code in right) { + if (!hasOwnProperty.call(left, code)) left[code] = [] + const value = right[code] + constructs( + // @ts-expect-error Looks like a list. + left[code], + Array.isArray(value) ? value : value ? [value] : [] + ) + } + } + } +} + +/** + * Merge `list` into `existing` (both lists of constructs). + * Mutates `existing`. + * + * @param {Array} existing + * List of constructs to merge into. + * @param {Array} list + * List of constructs to merge. + * @returns {undefined} + * Nothing. + */ +function constructs(existing, list) { + let index = -1 + /** @type {Array} */ + const before = [] + + while (++index < list.length) { + // @ts-expect-error Looks like an object. + ;(list[index].add === 'after' ? existing : before).push(list[index]) + } + + splice(existing, 0, 0, before) +} + +/** + * Combine multiple HTML extensions into one. + * + * @param {ReadonlyArray} htmlExtensions + * List of HTML extensions. + * @returns {HtmlExtension} + * Single combined HTML extension. + */ +export function combineHtmlExtensions(htmlExtensions) { + /** @type {HtmlExtension} */ + const handlers = {} + let index = -1 + + while (++index < htmlExtensions.length) { + htmlExtension(handlers, htmlExtensions[index]) + } + + return handlers +} + +/** + * Merge `extension` into `all`. + * + * @param {HtmlExtension} all + * Extension to merge into. + * @param {HtmlExtension} extension + * Extension to merge. + * @returns {undefined} + * Nothing. + */ +function htmlExtension(all, extension) { + /** @type {keyof HtmlExtension} */ + let hook + + for (hook in extension) { + const maybe = hasOwnProperty.call(all, hook) ? all[hook] : undefined + const left = maybe || (all[hook] = {}) + const right = extension[hook] + /** @type {keyof Handles} */ + let type + + if (right) { + for (type in right) { + // @ts-expect-error assume document vs regular handler are managed correctly. + left[type] = right[type] + } + } + } +} diff --git a/node_modules/micromark-util-combine-extensions/license b/node_modules/micromark-util-combine-extensions/license new file mode 100644 index 0000000000000000000000000000000000000000..bc8f165a62768a19de38901d81ac662c51ff29db --- /dev/null +++ b/node_modules/micromark-util-combine-extensions/license @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) Titus Wormer + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/micromark-util-combine-extensions/package.json b/node_modules/micromark-util-combine-extensions/package.json new file mode 100644 index 0000000000000000000000000000000000000000..f46ff4099f2a26645e04fb59df07074774cd2e94 --- /dev/null +++ b/node_modules/micromark-util-combine-extensions/package.json @@ -0,0 +1,52 @@ +{ + "name": "micromark-util-combine-extensions", + "version": "2.0.1", + "description": "micromark utility to combine syntax or html extensions", + "license": "MIT", + "keywords": [ + "micromark", + "util", + "utility", + "extension", + "combine", + "merge" + ], + "repository": "https://github.com/micromark/micromark/tree/main/packages/micromark-util-combine-extensions", + "bugs": "https://github.com/micromark/micromark/issues", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "author": "Titus Wormer (https://wooorm.com)", + "contributors": [ + "Titus Wormer (https://wooorm.com)" + ], + "sideEffects": false, + "type": "module", + "files": [ + "index.d.ts.map", + "index.d.ts", + "index.js" + ], + "exports": "./index.js", + "dependencies": { + "micromark-util-chunked": "^2.0.0", + "micromark-util-types": "^2.0.0" + }, + "xo": { + "envs": [ + "shared-node-browser" + ], + "prettier": true, + "rules": { + "guard-for-in": "off", + "unicorn/prefer-code-point": "off" + } + } +} diff --git a/node_modules/micromark-util-combine-extensions/readme.md b/node_modules/micromark-util-combine-extensions/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..b9b6fc13e9a3c7c1647c7ed7509a98a11eef1c7f --- /dev/null +++ b/node_modules/micromark-util-combine-extensions/readme.md @@ -0,0 +1,201 @@ +# micromark-util-combine-extensions + +[![Build][build-badge]][build] +[![Coverage][coverage-badge]][coverage] +[![Downloads][downloads-badge]][downloads] +[![Size][bundle-size-badge]][bundle-size] +[![Sponsors][sponsors-badge]][opencollective] +[![Backers][backers-badge]][opencollective] +[![Chat][chat-badge]][chat] + +[micromark][] utility to combine [syntax][] or [html][] extensions. + +## Contents + +* [What is this?](#what-is-this) +* [When should I use this?](#when-should-i-use-this) +* [Install](#install) +* [Use](#use) +* [API](#api) + * [`combineExtensions(extensions)`](#combineextensionsextensions) + * [`combineHtmlExtensions(htmlExtensions)`](#combinehtmlextensionshtmlextensions) +* [Types](#types) +* [Compatibility](#compatibility) +* [Security](#security) +* [Contribute](#contribute) +* [License](#license) + +## What is this? + +This package can merge multiple extensions into one. + +## When should I use this? + +This package might be useful when you are making “presets”, such as +[`micromark-extension-gfm`][micromark-extension-gfm]. + +## Install + +This package is [ESM only][esm]. +In Node.js (version 16+), install with [npm][]: + +```sh +npm install micromark-util-combine-extensions +``` + +In Deno with [`esm.sh`][esmsh]: + +```js +import {combineExtensions} from 'https://esm.sh/micromark-util-combine-extensions@1' +``` + +In browsers with [`esm.sh`][esmsh]: + +```html + +``` + +## Use + +```js +import {gfmAutolinkLiteral} from 'micromark-extension-gfm-autolink-literal' +import {gfmStrikethrough} from 'micromark-extension-gfm-strikethrough' +import {gfmTable} from 'micromark-extension-gfm-table' +import {gfmTaskListItem} from 'micromark-extension-gfm-task-list-item' +import {combineExtensions} from 'micromark-util-combine-extensions' + +const gfm = combineExtensions([gfmAutolinkLiteral, gfmStrikethrough(), gfmTable, gfmTaskListItem]) +``` + +## API + +This module exports the identifiers +[`combineExtensions`][api-combine-extensions] and +[`combineHtmlExtensions`][api-combine-html-extensions]. +There is no default export. + +### `combineExtensions(extensions)` + +Combine multiple syntax extensions into one. + +###### Parameters + +* `extensions` (`Array`) + — list of syntax extensions + +###### Returns + +A single combined extension (`Extension`). + +### `combineHtmlExtensions(htmlExtensions)` + +Combine multiple html extensions into one. + +###### Parameters + +* `htmlExtensions` (`Array`) + — list of HTML extensions + +###### Returns + +A single combined HTML extension (`HtmlExtension`). + +## Types + +This package is fully typed with [TypeScript][]. +It exports no additional types. + +## Compatibility + +Projects maintained by the unified collective are compatible with maintained +versions of Node.js. + +When we cut a new major release, we drop support for unmaintained versions of +Node. +This means we try to keep the current release line, +`micromark-util-combine-extensions@2`, compatible with Node.js 16. +This package works with `micromark@3`. + +## Security + +This package is safe. +See [`security.md`][securitymd] in [`micromark/.github`][health] for how to +submit a security report. + +## Contribute + +See [`contributing.md`][contributing] in [`micromark/.github`][health] for ways +to get started. +See [`support.md`][support] for ways to get help. + +This project has a [code of conduct][coc]. +By interacting with this repository, organisation, or community you agree to +abide by its terms. + +## License + +[MIT][license] © [Titus Wormer][author] + + + +[build-badge]: https://github.com/micromark/micromark/workflows/main/badge.svg + +[build]: https://github.com/micromark/micromark/actions + +[coverage-badge]: https://img.shields.io/codecov/c/github/micromark/micromark.svg + +[coverage]: https://codecov.io/github/micromark/micromark + +[downloads-badge]: https://img.shields.io/npm/dm/micromark-util-combine-extensions.svg + +[downloads]: https://www.npmjs.com/package/micromark-util-combine-extensions + +[bundle-size-badge]: https://img.shields.io/badge/dynamic/json?label=minzipped%20size&query=$.size.compressedSize&url=https://deno.bundlejs.com/?q=micromark-util-combine-extensions + +[bundle-size]: https://bundlejs.com/?q=micromark-util-combine-extensions + +[sponsors-badge]: https://opencollective.com/unified/sponsors/badge.svg + +[backers-badge]: https://opencollective.com/unified/backers/badge.svg + +[opencollective]: https://opencollective.com/unified + +[npm]: https://docs.npmjs.com/cli/install + +[esm]: https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c + +[esmsh]: https://esm.sh + +[chat-badge]: https://img.shields.io/badge/chat-discussions-success.svg + +[chat]: https://github.com/micromark/micromark/discussions + +[license]: https://github.com/micromark/micromark/blob/main/license + +[author]: https://wooorm.com + +[health]: https://github.com/micromark/.github + +[securitymd]: https://github.com/micromark/.github/blob/main/security.md + +[contributing]: https://github.com/micromark/.github/blob/main/contributing.md + +[support]: https://github.com/micromark/.github/blob/main/support.md + +[coc]: https://github.com/micromark/.github/blob/main/code-of-conduct.md + +[syntax]: https://github.com/micromark/micromark#syntaxextension + +[html]: https://github.com/micromark/micromark#htmlextension + +[typescript]: https://www.typescriptlang.org + +[micromark]: https://github.com/micromark/micromark + +[micromark-extension-gfm]: https://github.com/micromark/micromark-extension-gfm + +[api-combine-extensions]: #combineextensionsextensions + +[api-combine-html-extensions]: #combinehtmlextensionshtmlextensions diff --git a/node_modules/micromark-util-decode-numeric-character-reference/dev/index.d.ts b/node_modules/micromark-util-decode-numeric-character-reference/dev/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..333bdbbd0e6b51f3e9ef939e8821db1e9a0ff644 --- /dev/null +++ b/node_modules/micromark-util-decode-numeric-character-reference/dev/index.d.ts @@ -0,0 +1,16 @@ +/** + * Turn the number (in string form as either hexa- or plain decimal) coming from + * a numeric character reference into a character. + * + * Sort of like `String.fromCodePoint(Number.parseInt(value, base))`, but makes + * non-characters and control characters safe. + * + * @param {string} value + * Value to decode. + * @param {number} base + * Numeric base. + * @returns {string} + * Character. + */ +export function decodeNumericCharacterReference(value: string, base: number): string; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/micromark-util-decode-numeric-character-reference/dev/index.d.ts.map b/node_modules/micromark-util-decode-numeric-character-reference/dev/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..17f668f1040f5182cf4f5a7760060368ca76a905 --- /dev/null +++ b/node_modules/micromark-util-decode-numeric-character-reference/dev/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.js"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;GAaG;AACH,uDAPW,MAAM,QAEN,MAAM,GAEJ,MAAM,CA4BlB"} \ No newline at end of file diff --git a/node_modules/micromark-util-decode-numeric-character-reference/dev/index.js b/node_modules/micromark-util-decode-numeric-character-reference/dev/index.js new file mode 100644 index 0000000000000000000000000000000000000000..a96c423833004a3fa609c647096d357be03e4a5a --- /dev/null +++ b/node_modules/micromark-util-decode-numeric-character-reference/dev/index.js @@ -0,0 +1,42 @@ +import {codes, values} from 'micromark-util-symbol' + +/** + * Turn the number (in string form as either hexa- or plain decimal) coming from + * a numeric character reference into a character. + * + * Sort of like `String.fromCodePoint(Number.parseInt(value, base))`, but makes + * non-characters and control characters safe. + * + * @param {string} value + * Value to decode. + * @param {number} base + * Numeric base. + * @returns {string} + * Character. + */ +export function decodeNumericCharacterReference(value, base) { + const code = Number.parseInt(value, base) + + if ( + // C0 except for HT, LF, FF, CR, space. + code < codes.ht || + code === codes.vt || + (code > codes.cr && code < codes.space) || + // Control character (DEL) of C0, and C1 controls. + (code > codes.tilde && code < 160) || + // Lone high surrogates and low surrogates. + (code > 55_295 && code < 57_344) || + // Noncharacters. + (code > 64_975 && code < 65_008) || + /* eslint-disable no-bitwise */ + (code & 65_535) === 65_535 || + (code & 65_535) === 65_534 || + /* eslint-enable no-bitwise */ + // Out of range + code > 1_114_111 + ) { + return values.replacementCharacter + } + + return String.fromCodePoint(code) +} diff --git a/node_modules/micromark-util-decode-numeric-character-reference/index.d.ts b/node_modules/micromark-util-decode-numeric-character-reference/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..333bdbbd0e6b51f3e9ef939e8821db1e9a0ff644 --- /dev/null +++ b/node_modules/micromark-util-decode-numeric-character-reference/index.d.ts @@ -0,0 +1,16 @@ +/** + * Turn the number (in string form as either hexa- or plain decimal) coming from + * a numeric character reference into a character. + * + * Sort of like `String.fromCodePoint(Number.parseInt(value, base))`, but makes + * non-characters and control characters safe. + * + * @param {string} value + * Value to decode. + * @param {number} base + * Numeric base. + * @returns {string} + * Character. + */ +export function decodeNumericCharacterReference(value: string, base: number): string; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/micromark-util-decode-numeric-character-reference/index.d.ts.map b/node_modules/micromark-util-decode-numeric-character-reference/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..17f668f1040f5182cf4f5a7760060368ca76a905 --- /dev/null +++ b/node_modules/micromark-util-decode-numeric-character-reference/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.js"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;GAaG;AACH,uDAPW,MAAM,QAEN,MAAM,GAEJ,MAAM,CA4BlB"} \ No newline at end of file diff --git a/node_modules/micromark-util-decode-numeric-character-reference/index.js b/node_modules/micromark-util-decode-numeric-character-reference/index.js new file mode 100644 index 0000000000000000000000000000000000000000..1d75d7ba5c88e24ec20f2e9aee3de7c57d233123 --- /dev/null +++ b/node_modules/micromark-util-decode-numeric-character-reference/index.js @@ -0,0 +1,32 @@ +/** + * Turn the number (in string form as either hexa- or plain decimal) coming from + * a numeric character reference into a character. + * + * Sort of like `String.fromCodePoint(Number.parseInt(value, base))`, but makes + * non-characters and control characters safe. + * + * @param {string} value + * Value to decode. + * @param {number} base + * Numeric base. + * @returns {string} + * Character. + */ +export function decodeNumericCharacterReference(value, base) { + const code = Number.parseInt(value, base); + if ( + // C0 except for HT, LF, FF, CR, space. + code < 9 || code === 11 || code > 13 && code < 32 || + // Control character (DEL) of C0, and C1 controls. + code > 126 && code < 160 || + // Lone high surrogates and low surrogates. + code > 55_295 && code < 57_344 || + // Noncharacters. + code > 64_975 && code < 65_008 || /* eslint-disable no-bitwise */ + (code & 65_535) === 65_535 || (code & 65_535) === 65_534 || /* eslint-enable no-bitwise */ + // Out of range + code > 1_114_111) { + return "\uFFFD"; + } + return String.fromCodePoint(code); +} \ No newline at end of file diff --git a/node_modules/micromark-util-decode-numeric-character-reference/license b/node_modules/micromark-util-decode-numeric-character-reference/license new file mode 100644 index 0000000000000000000000000000000000000000..bc8f165a62768a19de38901d81ac662c51ff29db --- /dev/null +++ b/node_modules/micromark-util-decode-numeric-character-reference/license @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) Titus Wormer + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/micromark-util-decode-numeric-character-reference/package.json b/node_modules/micromark-util-decode-numeric-character-reference/package.json new file mode 100644 index 0000000000000000000000000000000000000000..759e989b074066d4ea063eb3f859ae0e7010f47d --- /dev/null +++ b/node_modules/micromark-util-decode-numeric-character-reference/package.json @@ -0,0 +1,59 @@ +{ + "name": "micromark-util-decode-numeric-character-reference", + "version": "2.0.2", + "description": "micromark utility to decode numeric character references", + "license": "MIT", + "keywords": [ + "micromark", + "util", + "utility", + "decode", + "numeric", + "number", + "character", + "reference" + ], + "repository": "https://github.com/micromark/micromark/tree/main/packages/micromark-util-decode-numeric-character-reference", + "bugs": "https://github.com/micromark/micromark/issues", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "author": "Titus Wormer (https://wooorm.com)", + "contributors": [ + "Titus Wormer (https://wooorm.com)" + ], + "sideEffects": false, + "type": "module", + "files": [ + "dev/", + "index.d.ts.map", + "index.d.ts", + "index.js" + ], + "exports": { + "development": "./dev/index.js", + "default": "./index.js" + }, + "dependencies": { + "micromark-util-symbol": "^2.0.0" + }, + "scripts": { + "build": "micromark-build" + }, + "xo": { + "envs": [ + "shared-node-browser" + ], + "prettier": true, + "rules": { + "unicorn/prefer-code-point": "off" + } + } +} diff --git a/node_modules/micromark-util-decode-numeric-character-reference/readme.md b/node_modules/micromark-util-decode-numeric-character-reference/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..4610c59bc957a9c5cc035b53028ac9164efa7e73 --- /dev/null +++ b/node_modules/micromark-util-decode-numeric-character-reference/readme.md @@ -0,0 +1,184 @@ +# micromark-util-decode-numeric-character-reference + +[![Build][build-badge]][build] +[![Coverage][coverage-badge]][coverage] +[![Downloads][downloads-badge]][downloads] +[![Size][bundle-size-badge]][bundle-size] +[![Sponsors][sponsors-badge]][opencollective] +[![Backers][backers-badge]][opencollective] +[![Chat][chat-badge]][chat] + +[micromark][] utility to decode numeric character references. + +## Contents + +* [What is this?](#what-is-this) +* [When should I use this?](#when-should-i-use-this) +* [Install](#install) +* [Use](#use) +* [API](#api) + * [`decodeNumericCharacterReference(value, base)`](#decodenumericcharacterreferencevalue-base) +* [Types](#types) +* [Compatibility](#compatibility) +* [Security](#security) +* [Contribute](#contribute) +* [License](#license) + +## What is this? + +This package exposes an algorithm to decode numeric character references. + +## When should I use this? + +This package might be useful when you are making your own micromark extensions. + +## Install + +This package is [ESM only][esm]. +In Node.js (version 16+), install with [npm][]: + +```sh +npm install micromark-util-decode-numeric-character-reference +``` + +In Deno with [`esm.sh`][esmsh]: + +```js +import {decodeNumericCharacterReference} from 'https://esm.sh/micromark-util-decode-numeric-character-reference@1' +``` + +In browsers with [`esm.sh`][esmsh]: + +```html + +``` + +## Use + +```js +import {decodeNumericCharacterReference} from 'micromark-util-decode-numeric-character-reference' + +decodeNumericCharacterReference('41', 16) // 'A' +decodeNumericCharacterReference('65', 10) // 'A' +decodeNumericCharacterReference('A', 16) // '\n' +decodeNumericCharacterReference('7F', 16) // '�' - Control +decodeNumericCharacterReference('110000', 16) // '�' - Out of range +``` + +## API + +This module exports the identifier: +[`decodeNumericCharacterReference`][api-decode-numeric-character-reference]. +There is no default export. + +### `decodeNumericCharacterReference(value, base)` + +Turn the number (in string form as either hexa- or plain decimal) coming from +a numeric character reference into a character. + +Sort of like `String.fromCodePoint(Number.parseInt(value, base))`, but makes +non-characters and control characters safe. + +###### Parameters + +* `value` (`string`) + — value to decode +* `base` (`number`, probably `10` or `16`) + — numeric base + +###### Returns + +Character (`string`). + +## Types + +This package is fully typed with [TypeScript][]. +It exports no additional types. + +## Compatibility + +Projects maintained by the unified collective are compatible with maintained +versions of Node.js. + +When we cut a new major release, we drop support for unmaintained versions of +Node. +This means we try to keep the current release line, +`micromark-util-decode-numeric-character-reference@2`, compatible with +Node.js 16. +This package works with `micromark@3`. + +## Security + +This package is safe. +See [`security.md`][securitymd] in [`micromark/.github`][health] for how to +submit a security report. + +## Contribute + +See [`contributing.md`][contributing] in [`micromark/.github`][health] for ways +to get started. +See [`support.md`][support] for ways to get help. + +This project has a [code of conduct][coc]. +By interacting with this repository, organisation, or community you agree to +abide by its terms. + +## License + +[MIT][license] © [Titus Wormer][author] + + + +[build-badge]: https://github.com/micromark/micromark/workflows/main/badge.svg + +[build]: https://github.com/micromark/micromark/actions + +[coverage-badge]: https://img.shields.io/codecov/c/github/micromark/micromark.svg + +[coverage]: https://codecov.io/github/micromark/micromark + +[downloads-badge]: https://img.shields.io/npm/dm/micromark-util-normalize-identifier.svg + +[downloads]: https://www.npmjs.com/package/micromark-util-normalize-identifier + +[bundle-size-badge]: https://img.shields.io/badge/dynamic/json?label=minzipped%20size&query=$.size.compressedSize&url=https://deno.bundlejs.com/?q=micromark-util-normalize-identifier + +[bundle-size]: https://bundlejs.com/?q=micromark-util-normalize-identifier + +[sponsors-badge]: https://opencollective.com/unified/sponsors/badge.svg + +[backers-badge]: https://opencollective.com/unified/backers/badge.svg + +[opencollective]: https://opencollective.com/unified + +[npm]: https://docs.npmjs.com/cli/install + +[esm]: https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c + +[esmsh]: https://esm.sh + +[chat-badge]: https://img.shields.io/badge/chat-discussions-success.svg + +[chat]: https://github.com/micromark/micromark/discussions + +[license]: https://github.com/micromark/micromark/blob/main/license + +[author]: https://wooorm.com + +[health]: https://github.com/micromark/.github + +[securitymd]: https://github.com/micromark/.github/blob/main/security.md + +[contributing]: https://github.com/micromark/.github/blob/main/contributing.md + +[support]: https://github.com/micromark/.github/blob/main/support.md + +[coc]: https://github.com/micromark/.github/blob/main/code-of-conduct.md + +[typescript]: https://www.typescriptlang.org + +[micromark]: https://github.com/micromark/micromark + +[api-decode-numeric-character-reference]: #decodenumericcharacterreferencevalue-base diff --git a/node_modules/micromark-util-decode-string/dev/index.d.ts b/node_modules/micromark-util-decode-string/dev/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7395fe0985af77c231a2c719020cb4b91fbb2509 --- /dev/null +++ b/node_modules/micromark-util-decode-string/dev/index.d.ts @@ -0,0 +1,14 @@ +/** + * Decode markdown strings (which occur in places such as fenced code info + * strings, destinations, labels, and titles). + * + * The “string” content type allows character escapes and -references. + * This decodes those. + * + * @param {string} value + * Value to decode. + * @returns {string} + * Decoded value. + */ +export function decodeString(value: string): string; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/micromark-util-decode-string/dev/index.d.ts.map b/node_modules/micromark-util-decode-string/dev/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..773ee9f4bce69742a16ded2f58f67a7a516ebcca --- /dev/null +++ b/node_modules/micromark-util-decode-string/dev/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.js"],"names":[],"mappings":"AAOA;;;;;;;;;;;GAWG;AACH,oCALW,MAAM,GAEJ,MAAM,CAKlB"} \ No newline at end of file diff --git a/node_modules/micromark-util-decode-string/dev/index.js b/node_modules/micromark-util-decode-string/dev/index.js new file mode 100644 index 0000000000000000000000000000000000000000..214ca1663fd8f6a6b50bd99b2004ae3006e7cbec --- /dev/null +++ b/node_modules/micromark-util-decode-string/dev/index.js @@ -0,0 +1,53 @@ +import {decodeNamedCharacterReference} from 'decode-named-character-reference' +import {decodeNumericCharacterReference} from 'micromark-util-decode-numeric-character-reference' +import {codes, constants} from 'micromark-util-symbol' + +const characterEscapeOrReference = + /\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi + +/** + * Decode markdown strings (which occur in places such as fenced code info + * strings, destinations, labels, and titles). + * + * The “string” content type allows character escapes and -references. + * This decodes those. + * + * @param {string} value + * Value to decode. + * @returns {string} + * Decoded value. + */ +export function decodeString(value) { + return value.replace(characterEscapeOrReference, decode) +} + +/** + * @param {string} $0 + * Match. + * @param {string} $1 + * Character escape. + * @param {string} $2 + * Character reference. + * @returns {string} + * Decoded value + */ +function decode($0, $1, $2) { + if ($1) { + // Escape. + return $1 + } + + // Reference. + const head = $2.charCodeAt(0) + + if (head === codes.numberSign) { + const head = $2.charCodeAt(1) + const hex = head === codes.lowercaseX || head === codes.uppercaseX + return decodeNumericCharacterReference( + $2.slice(hex ? 2 : 1), + hex ? constants.numericBaseHexadecimal : constants.numericBaseDecimal + ) + } + + return decodeNamedCharacterReference($2) || $0 +} diff --git a/node_modules/micromark-util-decode-string/index.d.ts b/node_modules/micromark-util-decode-string/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7395fe0985af77c231a2c719020cb4b91fbb2509 --- /dev/null +++ b/node_modules/micromark-util-decode-string/index.d.ts @@ -0,0 +1,14 @@ +/** + * Decode markdown strings (which occur in places such as fenced code info + * strings, destinations, labels, and titles). + * + * The “string” content type allows character escapes and -references. + * This decodes those. + * + * @param {string} value + * Value to decode. + * @returns {string} + * Decoded value. + */ +export function decodeString(value: string): string; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/micromark-util-decode-string/index.d.ts.map b/node_modules/micromark-util-decode-string/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..773ee9f4bce69742a16ded2f58f67a7a516ebcca --- /dev/null +++ b/node_modules/micromark-util-decode-string/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.js"],"names":[],"mappings":"AAOA;;;;;;;;;;;GAWG;AACH,oCALW,MAAM,GAEJ,MAAM,CAKlB"} \ No newline at end of file diff --git a/node_modules/micromark-util-decode-string/index.js b/node_modules/micromark-util-decode-string/index.js new file mode 100644 index 0000000000000000000000000000000000000000..e6f07c8c16bcaed21789001be0de6b52dfff6466 --- /dev/null +++ b/node_modules/micromark-util-decode-string/index.js @@ -0,0 +1,45 @@ +import { decodeNamedCharacterReference } from 'decode-named-character-reference'; +import { decodeNumericCharacterReference } from 'micromark-util-decode-numeric-character-reference'; +const characterEscapeOrReference = /\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi; + +/** + * Decode markdown strings (which occur in places such as fenced code info + * strings, destinations, labels, and titles). + * + * The “string” content type allows character escapes and -references. + * This decodes those. + * + * @param {string} value + * Value to decode. + * @returns {string} + * Decoded value. + */ +export function decodeString(value) { + return value.replace(characterEscapeOrReference, decode); +} + +/** + * @param {string} $0 + * Match. + * @param {string} $1 + * Character escape. + * @param {string} $2 + * Character reference. + * @returns {string} + * Decoded value + */ +function decode($0, $1, $2) { + if ($1) { + // Escape. + return $1; + } + + // Reference. + const head = $2.charCodeAt(0); + if (head === 35) { + const head = $2.charCodeAt(1); + const hex = head === 120 || head === 88; + return decodeNumericCharacterReference($2.slice(hex ? 2 : 1), hex ? 16 : 10); + } + return decodeNamedCharacterReference($2) || $0; +} \ No newline at end of file diff --git a/node_modules/micromark-util-decode-string/license b/node_modules/micromark-util-decode-string/license new file mode 100644 index 0000000000000000000000000000000000000000..bc8f165a62768a19de38901d81ac662c51ff29db --- /dev/null +++ b/node_modules/micromark-util-decode-string/license @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) Titus Wormer + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/micromark-util-decode-string/package.json b/node_modules/micromark-util-decode-string/package.json new file mode 100644 index 0000000000000000000000000000000000000000..e32660a7a1d8cbe63ef44831d9aef4049cb69269 --- /dev/null +++ b/node_modules/micromark-util-decode-string/package.json @@ -0,0 +1,63 @@ +{ + "name": "micromark-util-decode-string", + "version": "2.0.1", + "description": "micromark utility to decode markdown strings", + "license": "MIT", + "keywords": [ + "micromark", + "util", + "utility", + "decode", + "character", + "reference", + "escape", + "string" + ], + "repository": "https://github.com/micromark/micromark/tree/main/packages/micromark-util-decode-string", + "bugs": "https://github.com/micromark/micromark/issues", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "author": "Titus Wormer (https://wooorm.com)", + "contributors": [ + "Titus Wormer (https://wooorm.com)" + ], + "sideEffects": false, + "type": "module", + "files": [ + "dev/", + "index.d.ts.map", + "index.d.ts", + "index.js" + ], + "exports": { + "development": "./dev/index.js", + "default": "./index.js" + }, + "dependencies": { + "micromark-util-character": "^2.0.0", + "micromark-util-decode-numeric-character-reference": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "decode-named-character-reference": "^1.0.0" + }, + "scripts": { + "build": "micromark-build" + }, + "xo": { + "envs": [ + "shared-node-browser" + ], + "prettier": true, + "rules": { + "unicorn/prefer-code-point": "off", + "unicorn/prefer-string-replace-all": "off" + } + } +} diff --git a/node_modules/micromark-util-decode-string/readme.md b/node_modules/micromark-util-decode-string/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..291fe6938ec290a69488bf39709d68ad9790d4df --- /dev/null +++ b/node_modules/micromark-util-decode-string/readme.md @@ -0,0 +1,179 @@ +# micromark-util-decode-string + +[![Build][build-badge]][build] +[![Coverage][coverage-badge]][coverage] +[![Downloads][downloads-badge]][downloads] +[![Size][bundle-size-badge]][bundle-size] +[![Sponsors][sponsors-badge]][opencollective] +[![Backers][backers-badge]][opencollective] +[![Chat][chat-badge]][chat] + +[micromark][] utility to decode markdown strings. + +## Contents + +* [What is this?](#what-is-this) +* [When should I use this?](#when-should-i-use-this) +* [Install](#install) +* [Use](#use) +* [API](#api) + * [`decodeString(value)`](#decodestringvalue) +* [Types](#types) +* [Compatibility](#compatibility) +* [Security](#security) +* [Contribute](#contribute) +* [License](#license) + +## What is this? + +This package exposes an algorithm to parse character escapes and character +references. + +## When should I use this? + +This package might be useful when you are making your own micromark extensions. + +## Install + +This package is [ESM only][esm]. +In Node.js (version 16+), install with [npm][]: + +```sh +npm install micromark-util-decode-string +``` + +In Deno with [`esm.sh`][esmsh]: + +```js +import {decodeString} from 'https://esm.sh/micromark-util-decode-string@1' +``` + +In browsers with [`esm.sh`][esmsh]: + +```html + +``` + +## Use + +```js +import {decodeString} from 'micromark-util-decode-string' + +decodeString('a ; b') // 'a ; b' +decodeString('a \\; b') // 'a ; b' +decodeString('a ; b') // 'a ; b' +``` + +## API + +This module exports the identifier [`decodeString`][api-decode-string]. +There is no default export. + +### `decodeString(value)` + +Decode markdown strings (which occur in places such as fenced code info strings, +destinations, labels, and titles). + +The “string” content type allows character escapes and -references. +This decodes those. + +###### Parameters + +* `value` (`string`) + — value to decode + +###### Returns + +Decoded value (`string`). + +## Types + +This package is fully typed with [TypeScript][]. +It exports no additional types. + +## Compatibility + +Projects maintained by the unified collective are compatible with maintained +versions of Node.js. + +When we cut a new major release, we drop support for unmaintained versions of +Node. +This means we try to keep the current release line, +`micromark-util-decode-string@2`, compatible with Node.js 16. +This package works with `micromark@3`. + +## Security + +This package is safe. +See [`security.md`][securitymd] in [`micromark/.github`][health] for how to +submit a security report. + +## Contribute + +See [`contributing.md`][contributing] in [`micromark/.github`][health] for ways +to get started. +See [`support.md`][support] for ways to get help. + +This project has a [code of conduct][coc]. +By interacting with this repository, organisation, or community you agree to +abide by its terms. + +## License + +[MIT][license] © [Titus Wormer][author] + + + +[build-badge]: https://github.com/micromark/micromark/workflows/main/badge.svg + +[build]: https://github.com/micromark/micromark/actions + +[coverage-badge]: https://img.shields.io/codecov/c/github/micromark/micromark.svg + +[coverage]: https://codecov.io/github/micromark/micromark + +[downloads-badge]: https://img.shields.io/npm/dm/micromark-util-normalize-identifier.svg + +[downloads]: https://www.npmjs.com/package/micromark-util-normalize-identifier + +[bundle-size-badge]: https://img.shields.io/badge/dynamic/json?label=minzipped%20size&query=$.size.compressedSize&url=https://deno.bundlejs.com/?q=micromark-util-normalize-identifier + +[bundle-size]: https://bundlejs.com/?q=micromark-util-normalize-identifier + +[sponsors-badge]: https://opencollective.com/unified/sponsors/badge.svg + +[backers-badge]: https://opencollective.com/unified/backers/badge.svg + +[opencollective]: https://opencollective.com/unified + +[npm]: https://docs.npmjs.com/cli/install + +[esm]: https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c + +[esmsh]: https://esm.sh + +[chat-badge]: https://img.shields.io/badge/chat-discussions-success.svg + +[chat]: https://github.com/micromark/micromark/discussions + +[license]: https://github.com/micromark/micromark/blob/main/license + +[author]: https://wooorm.com + +[health]: https://github.com/micromark/.github + +[securitymd]: https://github.com/micromark/.github/blob/main/security.md + +[contributing]: https://github.com/micromark/.github/blob/main/contributing.md + +[support]: https://github.com/micromark/.github/blob/main/support.md + +[coc]: https://github.com/micromark/.github/blob/main/code-of-conduct.md + +[typescript]: https://www.typescriptlang.org + +[micromark]: https://github.com/micromark/micromark + +[api-decode-string]: #decodestringvalue diff --git a/node_modules/micromark-util-encode/index.d.ts b/node_modules/micromark-util-encode/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..760226f6188af15bbdf4c8238767d7813a6e8ed0 --- /dev/null +++ b/node_modules/micromark-util-encode/index.d.ts @@ -0,0 +1,14 @@ +/** + * Encode only the dangerous HTML characters. + * + * This ensures that certain characters which have special meaning in HTML are + * dealt with. + * Technically, we can skip `>` and `"` in many cases, but CM includes them. + * + * @param {string} value + * Value to encode. + * @returns {string} + * Encoded value. + */ +export function encode(value: string): string; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/micromark-util-encode/index.d.ts.map b/node_modules/micromark-util-encode/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..16eebb1cc4a391c247cb6954a1bcdccee89417cc --- /dev/null +++ b/node_modules/micromark-util-encode/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.js"],"names":[],"mappings":"AAEA;;;;;;;;;;;GAWG;AACH,8BALW,MAAM,GAEJ,MAAM,CAqBlB"} \ No newline at end of file diff --git a/node_modules/micromark-util-encode/index.js b/node_modules/micromark-util-encode/index.js new file mode 100644 index 0000000000000000000000000000000000000000..397f1d4041af0593b79022fa483947534ccb117a --- /dev/null +++ b/node_modules/micromark-util-encode/index.js @@ -0,0 +1,33 @@ +const characterReferences = {'"': 'quot', '&': 'amp', '<': 'lt', '>': 'gt'} + +/** + * Encode only the dangerous HTML characters. + * + * This ensures that certain characters which have special meaning in HTML are + * dealt with. + * Technically, we can skip `>` and `"` in many cases, but CM includes them. + * + * @param {string} value + * Value to encode. + * @returns {string} + * Encoded value. + */ +export function encode(value) { + return value.replace(/["&<>]/g, replace) + + /** + * @param {string} value + * Value to replace. + * @returns {string} + * Encoded value. + */ + function replace(value) { + return ( + '&' + + characterReferences[ + /** @type {keyof typeof characterReferences} */ (value) + ] + + ';' + ) + } +} diff --git a/node_modules/micromark-util-encode/license b/node_modules/micromark-util-encode/license new file mode 100644 index 0000000000000000000000000000000000000000..bc8f165a62768a19de38901d81ac662c51ff29db --- /dev/null +++ b/node_modules/micromark-util-encode/license @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) Titus Wormer + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/micromark-util-encode/package.json b/node_modules/micromark-util-encode/package.json new file mode 100644 index 0000000000000000000000000000000000000000..a56c6b3b04e95af3f3d2282c85eb13294c185ccb --- /dev/null +++ b/node_modules/micromark-util-encode/package.json @@ -0,0 +1,47 @@ +{ + "name": "micromark-util-encode", + "version": "2.0.1", + "description": "micromark utility to encode dangerous html characters", + "license": "MIT", + "keywords": [ + "micromark", + "util", + "utility", + "html", + "encode" + ], + "repository": "https://github.com/micromark/micromark/tree/main/packages/micromark-util-encode", + "bugs": "https://github.com/micromark/micromark/issues", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "author": "Titus Wormer (https://wooorm.com)", + "contributors": [ + "Titus Wormer (https://wooorm.com)" + ], + "sideEffects": false, + "type": "module", + "files": [ + "index.d.ts.map", + "index.d.ts", + "index.js" + ], + "exports": "./index.js", + "xo": { + "envs": [ + "shared-node-browser" + ], + "prettier": true, + "rules": { + "unicorn/prefer-string-replace-all": "off", + "unicorn/prefer-code-point": "off" + } + } +} diff --git a/node_modules/micromark-util-encode/readme.md b/node_modules/micromark-util-encode/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..cd27292fe1223af19890419e545ebd4596fdaf24 --- /dev/null +++ b/node_modules/micromark-util-encode/readme.md @@ -0,0 +1,176 @@ +# micromark-util-encode + +[![Build][build-badge]][build] +[![Coverage][coverage-badge]][coverage] +[![Downloads][downloads-badge]][downloads] +[![Size][bundle-size-badge]][bundle-size] +[![Sponsors][sponsors-badge]][opencollective] +[![Backers][backers-badge]][opencollective] +[![Chat][chat-badge]][chat] + +[micromark][] utility to encode dangerous html characters. + +## Contents + +* [What is this?](#what-is-this) +* [When should I use this?](#when-should-i-use-this) +* [Install](#install) +* [Use](#use) +* [API](#api) + * [`encode(value)`](#encodevalue) +* [Types](#types) +* [Compatibility](#compatibility) +* [Security](#security) +* [Contribute](#contribute) +* [License](#license) + +## What is this? + +This package exposes an algorithm to make text safe for embedding in HTML. + +## When should I use this? + +This package might be useful when you are making your own micromark extensions. + +## Install + +This package is [ESM only][esm]. +In Node.js (version 16+), install with [npm][]: + +```sh +npm install micromark-util-encode +``` + +In Deno with [`esm.sh`][esmsh]: + +```js +import {encode} from 'https://esm.sh/micromark-util-encode@1' +``` + +In browsers with [`esm.sh`][esmsh]: + +```html + +``` + +## Use + +```js +import {encode} from 'micromark-util-encode' + +encode('<3') // '<3' +``` + +## API + +This module exports the identifier [`encode`][api-encode]. +There is no default export. + +### `encode(value)` + +Encode only the dangerous HTML characters. + +This ensures that certain characters which have special meaning in HTML are +dealt with. +Technically, we can skip `>` and `"` in many cases, but CM includes them. + +###### Parameters + +* `value` (`string`) + — value to encode + +###### Returns + +Encoded value (`string`). + +## Types + +This package is fully typed with [TypeScript][]. +It exports no additional types. + +## Compatibility + +Projects maintained by the unified collective are compatible with maintained +versions of Node.js. + +When we cut a new major release, we drop support for unmaintained versions of +Node. +This means we try to keep the current release line, +`micromark-util-encode@2`, compatible with Node.js 16. +This package works with `micromark@3`. + +## Security + +This package is safe. +See [`security.md`][securitymd] in [`micromark/.github`][health] for how to +submit a security report. + +## Contribute + +See [`contributing.md`][contributing] in [`micromark/.github`][health] for ways +to get started. +See [`support.md`][support] for ways to get help. + +This project has a [code of conduct][coc]. +By interacting with this repository, organisation, or community you agree to +abide by its terms. + +## License + +[MIT][license] © [Titus Wormer][author] + + + +[build-badge]: https://github.com/micromark/micromark/workflows/main/badge.svg + +[build]: https://github.com/micromark/micromark/actions + +[coverage-badge]: https://img.shields.io/codecov/c/github/micromark/micromark.svg + +[coverage]: https://codecov.io/github/micromark/micromark + +[downloads-badge]: https://img.shields.io/npm/dm/micromark-util-encode.svg + +[downloads]: https://www.npmjs.com/package/micromark-util-encode + +[bundle-size-badge]: https://img.shields.io/badge/dynamic/json?label=minzipped%20size&query=$.size.compressedSize&url=https://deno.bundlejs.com/?q=micromark-util-encode + +[bundle-size]: https://bundlejs.com/?q=micromark-util-encode + +[sponsors-badge]: https://opencollective.com/unified/sponsors/badge.svg + +[backers-badge]: https://opencollective.com/unified/backers/badge.svg + +[opencollective]: https://opencollective.com/unified + +[npm]: https://docs.npmjs.com/cli/install + +[esm]: https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c + +[esmsh]: https://esm.sh + +[chat-badge]: https://img.shields.io/badge/chat-discussions-success.svg + +[chat]: https://github.com/micromark/micromark/discussions + +[license]: https://github.com/micromark/micromark/blob/main/license + +[author]: https://wooorm.com + +[health]: https://github.com/micromark/.github + +[securitymd]: https://github.com/micromark/.github/blob/main/security.md + +[contributing]: https://github.com/micromark/.github/blob/main/contributing.md + +[support]: https://github.com/micromark/.github/blob/main/support.md + +[coc]: https://github.com/micromark/.github/blob/main/code-of-conduct.md + +[typescript]: https://www.typescriptlang.org + +[micromark]: https://github.com/micromark/micromark + +[api-encode]: #encodevalue diff --git a/node_modules/micromark-util-html-tag-name/index.d.ts b/node_modules/micromark-util-html-tag-name/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cd5ef317cd95d6e4214c34043248faccb545e66a --- /dev/null +++ b/node_modules/micromark-util-html-tag-name/index.d.ts @@ -0,0 +1,30 @@ +/** + * List of lowercase HTML “block” tag names. + * + * The list, when parsing HTML (flow), results in more relaxed rules (condition + * 6). + * Because they are known blocks, the HTML-like syntax doesn’t have to be + * strictly parsed. + * For tag names not in this list, a more strict algorithm (condition 7) is used + * to detect whether the HTML-like syntax is seen as HTML (flow) or not. + * + * This is copied from: + * . + * + * > 👉 **Note**: `search` was added in `CommonMark@0.31`. + */ +export const htmlBlockNames: string[]; +/** + * List of lowercase HTML “raw” tag names. + * + * The list, when parsing HTML (flow), results in HTML that can include lines + * without exiting, until a closing tag also in this list is found (condition + * 1). + * + * This module is copied from: + * . + * + * > 👉 **Note**: `textarea` was added in `CommonMark@0.30`. + */ +export const htmlRawNames: string[]; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/micromark-util-html-tag-name/index.d.ts.map b/node_modules/micromark-util-html-tag-name/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..56f2fc0f2e5943da7e191dd897045427131027ae --- /dev/null +++ b/node_modules/micromark-util-html-tag-name/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.js"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,sCA+DC;AAED;;;;;;;;;;;GAWG;AACH,oCAAkE"} \ No newline at end of file diff --git a/node_modules/micromark-util-html-tag-name/index.js b/node_modules/micromark-util-html-tag-name/index.js new file mode 100644 index 0000000000000000000000000000000000000000..fa0a0fd95004fb549735e5a343e158bcf8145fb5 --- /dev/null +++ b/node_modules/micromark-util-html-tag-name/index.js @@ -0,0 +1,93 @@ +/** + * List of lowercase HTML “block” tag names. + * + * The list, when parsing HTML (flow), results in more relaxed rules (condition + * 6). + * Because they are known blocks, the HTML-like syntax doesn’t have to be + * strictly parsed. + * For tag names not in this list, a more strict algorithm (condition 7) is used + * to detect whether the HTML-like syntax is seen as HTML (flow) or not. + * + * This is copied from: + * . + * + * > 👉 **Note**: `search` was added in `CommonMark@0.31`. + */ +export const htmlBlockNames = [ + 'address', + 'article', + 'aside', + 'base', + 'basefont', + 'blockquote', + 'body', + 'caption', + 'center', + 'col', + 'colgroup', + 'dd', + 'details', + 'dialog', + 'dir', + 'div', + 'dl', + 'dt', + 'fieldset', + 'figcaption', + 'figure', + 'footer', + 'form', + 'frame', + 'frameset', + 'h1', + 'h2', + 'h3', + 'h4', + 'h5', + 'h6', + 'head', + 'header', + 'hr', + 'html', + 'iframe', + 'legend', + 'li', + 'link', + 'main', + 'menu', + 'menuitem', + 'nav', + 'noframes', + 'ol', + 'optgroup', + 'option', + 'p', + 'param', + 'search', + 'section', + 'summary', + 'table', + 'tbody', + 'td', + 'tfoot', + 'th', + 'thead', + 'title', + 'tr', + 'track', + 'ul' +] + +/** + * List of lowercase HTML “raw” tag names. + * + * The list, when parsing HTML (flow), results in HTML that can include lines + * without exiting, until a closing tag also in this list is found (condition + * 1). + * + * This module is copied from: + * . + * + * > 👉 **Note**: `textarea` was added in `CommonMark@0.30`. + */ +export const htmlRawNames = ['pre', 'script', 'style', 'textarea'] diff --git a/node_modules/micromark-util-html-tag-name/license b/node_modules/micromark-util-html-tag-name/license new file mode 100644 index 0000000000000000000000000000000000000000..bc8f165a62768a19de38901d81ac662c51ff29db --- /dev/null +++ b/node_modules/micromark-util-html-tag-name/license @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) Titus Wormer + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/micromark-util-html-tag-name/package.json b/node_modules/micromark-util-html-tag-name/package.json new file mode 100644 index 0000000000000000000000000000000000000000..9015e128c8d0686794806f9ddd1cc9db4f0b2f94 --- /dev/null +++ b/node_modules/micromark-util-html-tag-name/package.json @@ -0,0 +1,47 @@ +{ + "name": "micromark-util-html-tag-name", + "version": "2.0.1", + "description": "micromark utility with list of html tag names", + "license": "MIT", + "keywords": [ + "micromark", + "util", + "utility", + "html", + "tag", + "name" + ], + "repository": "https://github.com/micromark/micromark/tree/main/packages/micromark-util-html-tag-name", + "bugs": "https://github.com/micromark/micromark/issues", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "author": "Titus Wormer (https://wooorm.com)", + "contributors": [ + "Titus Wormer (https://wooorm.com)" + ], + "sideEffects": false, + "type": "module", + "files": [ + "index.d.ts.map", + "index.d.ts", + "index.js" + ], + "exports": "./index.js", + "xo": { + "envs": [ + "shared-node-browser" + ], + "prettier": true, + "rules": { + "unicorn/prefer-code-point": "off" + } + } +} diff --git a/node_modules/micromark-util-html-tag-name/readme.md b/node_modules/micromark-util-html-tag-name/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..ff16f68e742ddf6e4c713b81ea7bc53ebe15df2e --- /dev/null +++ b/node_modules/micromark-util-html-tag-name/readme.md @@ -0,0 +1,193 @@ +# micromark-util-html-tag-name + +[![Build][build-badge]][build] +[![Coverage][coverage-badge]][coverage] +[![Downloads][downloads-badge]][downloads] +[![Size][bundle-size-badge]][bundle-size] +[![Sponsors][sponsors-badge]][opencollective] +[![Backers][backers-badge]][opencollective] +[![Chat][chat-badge]][chat] + +[micromark][] utility with list of html tag names. + +## Contents + +* [What is this?](#what-is-this) +* [When should I use this?](#when-should-i-use-this) +* [Install](#install) +* [Use](#use) +* [API](#api) + * [`htmlBlockNames`](#htmlblocknames) + * [`htmlRawNames`](#htmlrawnames) +* [Types](#types) +* [Compatibility](#compatibility) +* [Security](#security) +* [Contribute](#contribute) +* [License](#license) + +## What is this? + +This package exposes a list of known tag names to markdown. + +## When should I use this? + +This package is only useful if you want to build an alternative to micromark. + +## Install + +This package is [ESM only][esm]. +In Node.js (version 16+), install with [npm][]: + +```sh +npm install micromark-util-html-tag-name +``` + +In Deno with [`esm.sh`][esmsh]: + +```js +import {htmlBlockNames, htmlRawNames} from 'https://esm.sh/micromark-util-html-tag-name@1' +``` + +In browsers with [`esm.sh`][esmsh]: + +```html + +``` + +## Use + +```js +import {htmlBlockNames, htmlRawNames} from 'micromark-util-html-tag-name' + +console.log(htmlBlockNames) // ['address', 'article', …] +console.log(htmlRawNames) // ['pre', 'script', …] +``` + +## API + +This module exports the identifiers [`htmlBlockNames`][api-html-block-names] +and [`htmlRawNames`][api-html-raw-names]. +There is no default export. + +### `htmlBlockNames` + +List of lowercase HTML “block” tag names (`Array`). + +The list, when parsing HTML (flow), results in more relaxed rules (condition +6\). +Because they are known blocks, the HTML-like syntax doesn’t have to be strictly +parsed. +For tag names not in this list, a more strict algorithm (condition 7) is used +to detect whether the HTML-like syntax is seen as HTML (flow) or not. + +This is copied from: +. + +> 👉 **Note**: `search` was added in `CommonMark@0.31`. + +### `htmlRawNames` + +List of lowercase HTML “raw” tag names (`Array`). + +The list, when parsing HTML (flow), results in HTML that can include lines +without exiting, until a closing tag also in this list is found (condition +1\). + +This module is copied from: +. + +> 👉 **Note**: `textarea` was added in `CommonMark@0.30`. + +## Types + +This package is fully typed with [TypeScript][]. +It exports no additional types. + +## Compatibility + +Projects maintained by the unified collective are compatible with maintained +versions of Node.js. + +When we cut a new major release, we drop support for unmaintained versions of +Node. +This means we try to keep the current release line, +`micromark-util-html-tag-name@2`, compatible with Node.js 16. +This package works with `micromark@3`. + +## Security + +This package is safe. +See [`security.md`][securitymd] in [`micromark/.github`][health] for how to +submit a security report. + +## Contribute + +See [`contributing.md`][contributing] in [`micromark/.github`][health] for ways +to get started. +See [`support.md`][support] for ways to get help. + +This project has a [code of conduct][coc]. +By interacting with this repository, organisation, or community you agree to +abide by its terms. + +## License + +[MIT][license] © [Titus Wormer][author] + + + +[build-badge]: https://github.com/micromark/micromark/workflows/main/badge.svg + +[build]: https://github.com/micromark/micromark/actions + +[coverage-badge]: https://img.shields.io/codecov/c/github/micromark/micromark.svg + +[coverage]: https://codecov.io/github/micromark/micromark + +[downloads-badge]: https://img.shields.io/npm/dm/micromark-util-html-tag-name.svg + +[downloads]: https://www.npmjs.com/package/micromark-util-html-tag-name + +[bundle-size-badge]: https://img.shields.io/badge/dynamic/json?label=minzipped%20size&query=$.size.compressedSize&url=https://deno.bundlejs.com/?q=micromark-util-html-tag-name + +[bundle-size]: https://bundlejs.com/?q=micromark-util-html-tag-name + +[sponsors-badge]: https://opencollective.com/unified/sponsors/badge.svg + +[backers-badge]: https://opencollective.com/unified/backers/badge.svg + +[opencollective]: https://opencollective.com/unified + +[npm]: https://docs.npmjs.com/cli/install + +[esm]: https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c + +[esmsh]: https://esm.sh + +[chat-badge]: https://img.shields.io/badge/chat-discussions-success.svg + +[chat]: https://github.com/micromark/micromark/discussions + +[license]: https://github.com/micromark/micromark/blob/main/license + +[author]: https://wooorm.com + +[health]: https://github.com/micromark/.github + +[securitymd]: https://github.com/micromark/.github/blob/main/security.md + +[contributing]: https://github.com/micromark/.github/blob/main/contributing.md + +[support]: https://github.com/micromark/.github/blob/main/support.md + +[coc]: https://github.com/micromark/.github/blob/main/code-of-conduct.md + +[typescript]: https://www.typescriptlang.org + +[micromark]: https://github.com/micromark/micromark + +[api-html-block-names]: #htmlblocknames + +[api-html-raw-names]: #htmlrawnames diff --git a/node_modules/micromark-util-normalize-identifier/dev/index.d.ts b/node_modules/micromark-util-normalize-identifier/dev/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..96074f603183149066a463cc0cf75485528ec819 --- /dev/null +++ b/node_modules/micromark-util-normalize-identifier/dev/index.d.ts @@ -0,0 +1,21 @@ +/** + * Normalize an identifier (as found in references, definitions). + * + * Collapses markdown whitespace, trim, and then lower- and uppercase. + * + * Some characters are considered “uppercase”, such as U+03F4 (`ϴ`), but if their + * lowercase counterpart (U+03B8 (`θ`)) is uppercased will result in a different + * uppercase character (U+0398 (`Θ`)). + * So, to get a canonical form, we perform both lower- and uppercase. + * + * Using uppercase last makes sure keys will never interact with default + * prototypal values (such as `constructor`): nothing in the prototype of + * `Object` is uppercase. + * + * @param {string} value + * Identifier to normalize. + * @returns {string} + * Normalized identifier. + */ +export function normalizeIdentifier(value: string): string; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/micromark-util-normalize-identifier/dev/index.d.ts.map b/node_modules/micromark-util-normalize-identifier/dev/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..684ad8d872b8874ce11ce8a82df3eac05f088dde --- /dev/null +++ b/node_modules/micromark-util-normalize-identifier/dev/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.js"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;GAkBG;AACH,2CALW,MAAM,GAEJ,MAAM,CAmBlB"} \ No newline at end of file diff --git a/node_modules/micromark-util-normalize-identifier/dev/index.js b/node_modules/micromark-util-normalize-identifier/dev/index.js new file mode 100644 index 0000000000000000000000000000000000000000..ce4ce9b61c571e68e4d5208bf00e58d1fa8f8ffc --- /dev/null +++ b/node_modules/micromark-util-normalize-identifier/dev/index.js @@ -0,0 +1,38 @@ +import {values} from 'micromark-util-symbol' + +/** + * Normalize an identifier (as found in references, definitions). + * + * Collapses markdown whitespace, trim, and then lower- and uppercase. + * + * Some characters are considered “uppercase”, such as U+03F4 (`ϴ`), but if their + * lowercase counterpart (U+03B8 (`θ`)) is uppercased will result in a different + * uppercase character (U+0398 (`Θ`)). + * So, to get a canonical form, we perform both lower- and uppercase. + * + * Using uppercase last makes sure keys will never interact with default + * prototypal values (such as `constructor`): nothing in the prototype of + * `Object` is uppercase. + * + * @param {string} value + * Identifier to normalize. + * @returns {string} + * Normalized identifier. + */ +export function normalizeIdentifier(value) { + return ( + value + // Collapse markdown whitespace. + .replace(/[\t\n\r ]+/g, values.space) + // Trim. + .replace(/^ | $/g, '') + // Some characters are considered “uppercase”, but if their lowercase + // counterpart is uppercased will result in a different uppercase + // character. + // Hence, to get that form, we perform both lower- and uppercase. + // Upper case makes sure keys will not interact with default prototypal + // methods: no method is uppercase. + .toLowerCase() + .toUpperCase() + ) +} diff --git a/node_modules/micromark-util-normalize-identifier/index.d.ts b/node_modules/micromark-util-normalize-identifier/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..96074f603183149066a463cc0cf75485528ec819 --- /dev/null +++ b/node_modules/micromark-util-normalize-identifier/index.d.ts @@ -0,0 +1,21 @@ +/** + * Normalize an identifier (as found in references, definitions). + * + * Collapses markdown whitespace, trim, and then lower- and uppercase. + * + * Some characters are considered “uppercase”, such as U+03F4 (`ϴ`), but if their + * lowercase counterpart (U+03B8 (`θ`)) is uppercased will result in a different + * uppercase character (U+0398 (`Θ`)). + * So, to get a canonical form, we perform both lower- and uppercase. + * + * Using uppercase last makes sure keys will never interact with default + * prototypal values (such as `constructor`): nothing in the prototype of + * `Object` is uppercase. + * + * @param {string} value + * Identifier to normalize. + * @returns {string} + * Normalized identifier. + */ +export function normalizeIdentifier(value: string): string; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/micromark-util-normalize-identifier/index.d.ts.map b/node_modules/micromark-util-normalize-identifier/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..684ad8d872b8874ce11ce8a82df3eac05f088dde --- /dev/null +++ b/node_modules/micromark-util-normalize-identifier/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.js"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;GAkBG;AACH,2CALW,MAAM,GAEJ,MAAM,CAmBlB"} \ No newline at end of file diff --git a/node_modules/micromark-util-normalize-identifier/index.js b/node_modules/micromark-util-normalize-identifier/index.js new file mode 100644 index 0000000000000000000000000000000000000000..f2060214270d5f6a72017ab99d05e1325e50db93 --- /dev/null +++ b/node_modules/micromark-util-normalize-identifier/index.js @@ -0,0 +1,33 @@ +/** + * Normalize an identifier (as found in references, definitions). + * + * Collapses markdown whitespace, trim, and then lower- and uppercase. + * + * Some characters are considered “uppercase”, such as U+03F4 (`ϴ`), but if their + * lowercase counterpart (U+03B8 (`θ`)) is uppercased will result in a different + * uppercase character (U+0398 (`Θ`)). + * So, to get a canonical form, we perform both lower- and uppercase. + * + * Using uppercase last makes sure keys will never interact with default + * prototypal values (such as `constructor`): nothing in the prototype of + * `Object` is uppercase. + * + * @param {string} value + * Identifier to normalize. + * @returns {string} + * Normalized identifier. + */ +export function normalizeIdentifier(value) { + return value + // Collapse markdown whitespace. + .replace(/[\t\n\r ]+/g, " ") + // Trim. + .replace(/^ | $/g, '') + // Some characters are considered “uppercase”, but if their lowercase + // counterpart is uppercased will result in a different uppercase + // character. + // Hence, to get that form, we perform both lower- and uppercase. + // Upper case makes sure keys will not interact with default prototypal + // methods: no method is uppercase. + .toLowerCase().toUpperCase(); +} \ No newline at end of file diff --git a/node_modules/micromark-util-normalize-identifier/license b/node_modules/micromark-util-normalize-identifier/license new file mode 100644 index 0000000000000000000000000000000000000000..bc8f165a62768a19de38901d81ac662c51ff29db --- /dev/null +++ b/node_modules/micromark-util-normalize-identifier/license @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) Titus Wormer + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/micromark-util-normalize-identifier/package.json b/node_modules/micromark-util-normalize-identifier/package.json new file mode 100644 index 0000000000000000000000000000000000000000..4fb1982df2962948e555d983da15c78ec16d4170 --- /dev/null +++ b/node_modules/micromark-util-normalize-identifier/package.json @@ -0,0 +1,58 @@ +{ + "name": "micromark-util-normalize-identifier", + "version": "2.0.1", + "description": "micromark utility normalize identifiers (as found in references, definitions)", + "license": "MIT", + "keywords": [ + "micromark", + "util", + "utility", + "normalize", + "id", + "identifier" + ], + "repository": "https://github.com/micromark/micromark/tree/main/packages/micromark-util-normalize-identifier", + "bugs": "https://github.com/micromark/micromark/issues", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "author": "Titus Wormer (https://wooorm.com)", + "contributors": [ + "Titus Wormer (https://wooorm.com)" + ], + "sideEffects": false, + "type": "module", + "files": [ + "dev/", + "index.d.ts.map", + "index.d.ts", + "index.js" + ], + "exports": { + "development": "./dev/index.js", + "default": "./index.js" + }, + "dependencies": { + "micromark-util-symbol": "^2.0.0" + }, + "scripts": { + "build": "micromark-build" + }, + "xo": { + "envs": [ + "shared-node-browser" + ], + "prettier": true, + "rules": { + "unicorn/prefer-code-point": "off", + "unicorn/prefer-string-replace-all": "off" + } + } +} diff --git a/node_modules/micromark-util-normalize-identifier/readme.md b/node_modules/micromark-util-normalize-identifier/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..97e2383a1e1adf0bc595c8ccda2dcb2181f23ef0 --- /dev/null +++ b/node_modules/micromark-util-normalize-identifier/readme.md @@ -0,0 +1,187 @@ +# micromark-util-normalize-identifier + +[![Build][build-badge]][build] +[![Coverage][coverage-badge]][coverage] +[![Downloads][downloads-badge]][downloads] +[![Size][bundle-size-badge]][bundle-size] +[![Sponsors][sponsors-badge]][opencollective] +[![Backers][backers-badge]][opencollective] +[![Chat][chat-badge]][chat] + +[micromark][] utility normalize identifiers. + +## Contents + +* [What is this?](#what-is-this) +* [When should I use this?](#when-should-i-use-this) +* [Install](#install) +* [Use](#use) +* [API](#api) + * [`normalizeIdentifier(value)`](#normalizeidentifiervalue) +* [Types](#types) +* [Compatibility](#compatibility) +* [Security](#security) +* [Contribute](#contribute) +* [License](#license) + +## What is this? + +This package exposes an algorithm to normalize identifiers found in markdown. + +## When should I use this? + +This package might be useful when you are making your own micromark extensions. + +## Install + +This package is [ESM only][esm]. +In Node.js (version 16+), install with [npm][]: + +```sh +npm install micromark-util-normalize-identifier +``` + +In Deno with [`esm.sh`][esmsh]: + +```js +import {normalizeIdentifier} from 'https://esm.sh/micromark-util-normalize-identifier@1' +``` + +In browsers with [`esm.sh`][esmsh]: + +```html + +``` + +## Use + +```js +import {normalizeIdentifier} from 'micromark-util-normalize-identifier' + +normalizeIdentifier(' a ') // 'A' +normalizeIdentifier('a\t\r\nb') // 'A B' +normalizeIdentifier('ТОЛПОЙ') // 'ТОЛПОЙ' +normalizeIdentifier('Толпой') // 'ТОЛПОЙ' +``` + +## API + +This module exports the identifier +[`normalizeIdentifier`][api-normalize-identifier]. +There is no default export. + +### `normalizeIdentifier(value)` + +Normalize an identifier (as found in references, definitions). + +Collapses markdown whitespace, trim, and then lower- and uppercase. + +Some characters are considered “uppercase”, such as U+03F4 (`ϴ`), but if their +lowercase counterpart (U+03B8 (`θ`)) is uppercased will result in a different +uppercase character (U+0398 (`Θ`)). +So, to get a canonical form, we perform both lower- and uppercase. + +Using uppercase last makes sure keys will never interact with default +prototypal values (such as `constructor`): nothing in the prototype of `Object` +is uppercase. + +###### Parameters + +* `value` (`string`) + — identifier to normalize + +###### Returns + +Normalized identifier (`string`). + +## Types + +This package is fully typed with [TypeScript][]. +It exports no additional types. + +## Compatibility + +Projects maintained by the unified collective are compatible with maintained +versions of Node.js. + +When we cut a new major release, we drop support for unmaintained versions of +Node. +This means we try to keep the current release line, +`micromark-util-normalize-identifier@2`, compatible with Node.js 16. +This package works with `micromark@3`. + +## Security + +This package is safe. +See [`security.md`][securitymd] in [`micromark/.github`][health] for how to +submit a security report. + +## Contribute + +See [`contributing.md`][contributing] in [`micromark/.github`][health] for ways +to get started. +See [`support.md`][support] for ways to get help. + +This project has a [code of conduct][coc]. +By interacting with this repository, organisation, or community you agree to +abide by its terms. + +## License + +[MIT][license] © [Titus Wormer][author] + + + +[build-badge]: https://github.com/micromark/micromark/workflows/main/badge.svg + +[build]: https://github.com/micromark/micromark/actions + +[coverage-badge]: https://img.shields.io/codecov/c/github/micromark/micromark.svg + +[coverage]: https://codecov.io/github/micromark/micromark + +[downloads-badge]: https://img.shields.io/npm/dm/micromark-util-normalize-identifier.svg + +[downloads]: https://www.npmjs.com/package/micromark-util-normalize-identifier + +[bundle-size-badge]: https://img.shields.io/badge/dynamic/json?label=minzipped%20size&query=$.size.compressedSize&url=https://deno.bundlejs.com/?q=micromark-util-normalize-identifier + +[bundle-size]: https://bundlejs.com/?q=micromark-util-normalize-identifier + +[sponsors-badge]: https://opencollective.com/unified/sponsors/badge.svg + +[backers-badge]: https://opencollective.com/unified/backers/badge.svg + +[opencollective]: https://opencollective.com/unified + +[npm]: https://docs.npmjs.com/cli/install + +[esm]: https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c + +[esmsh]: https://esm.sh + +[chat-badge]: https://img.shields.io/badge/chat-discussions-success.svg + +[chat]: https://github.com/micromark/micromark/discussions + +[license]: https://github.com/micromark/micromark/blob/main/license + +[author]: https://wooorm.com + +[health]: https://github.com/micromark/.github + +[securitymd]: https://github.com/micromark/.github/blob/main/security.md + +[contributing]: https://github.com/micromark/.github/blob/main/contributing.md + +[support]: https://github.com/micromark/.github/blob/main/support.md + +[coc]: https://github.com/micromark/.github/blob/main/code-of-conduct.md + +[typescript]: https://www.typescriptlang.org + +[micromark]: https://github.com/micromark/micromark + +[api-normalize-identifier]: #normalizeidentifiervalue diff --git a/node_modules/micromark-util-resolve-all/index.d.ts b/node_modules/micromark-util-resolve-all/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c9cbe16b64d9576aae88238769ecd0fe542f698b --- /dev/null +++ b/node_modules/micromark-util-resolve-all/index.d.ts @@ -0,0 +1,22 @@ +/** + * @import {Event, Resolver, TokenizeContext} from 'micromark-util-types' + */ +/** + * Call all `resolveAll`s. + * + * @param {ReadonlyArray<{resolveAll?: Resolver | undefined}>} constructs + * List of constructs, optionally with `resolveAll`s. + * @param {Array} events + * List of events. + * @param {TokenizeContext} context + * Context used by `tokenize`. + * @returns {Array} + * Changed events. + */ +export function resolveAll(constructs: ReadonlyArray<{ + resolveAll?: Resolver | undefined; +}>, events: Array, context: TokenizeContext): Array; +import type { Resolver } from 'micromark-util-types'; +import type { Event } from 'micromark-util-types'; +import type { TokenizeContext } from 'micromark-util-types'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/micromark-util-resolve-all/index.d.ts.map b/node_modules/micromark-util-resolve-all/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..8ba707e732fbd0bbcdf3d37bc8f54c64f27b302e --- /dev/null +++ b/node_modules/micromark-util-resolve-all/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.js"],"names":[],"mappings":"AAAA;;GAEG;AAEH;;;;;;;;;;;GAWG;AACH,uCATW,aAAa,CAAC;IAAC,UAAU,CAAC,EAAE,QAAQ,GAAG,SAAS,CAAA;CAAC,CAAC,UAElD,KAAK,CAAC,KAAK,CAAC,WAEZ,eAAe,GAEb,KAAK,CAAC,KAAK,CAAC,CAkBxB;8BA9BkD,sBAAsB;2BAAtB,sBAAsB;qCAAtB,sBAAsB"} \ No newline at end of file diff --git a/node_modules/micromark-util-resolve-all/index.js b/node_modules/micromark-util-resolve-all/index.js new file mode 100644 index 0000000000000000000000000000000000000000..69eb32b604c6c7a1d87bb664825b9be6876181b2 --- /dev/null +++ b/node_modules/micromark-util-resolve-all/index.js @@ -0,0 +1,32 @@ +/** + * @import {Event, Resolver, TokenizeContext} from 'micromark-util-types' + */ + +/** + * Call all `resolveAll`s. + * + * @param {ReadonlyArray<{resolveAll?: Resolver | undefined}>} constructs + * List of constructs, optionally with `resolveAll`s. + * @param {Array} events + * List of events. + * @param {TokenizeContext} context + * Context used by `tokenize`. + * @returns {Array} + * Changed events. + */ +export function resolveAll(constructs, events, context) { + /** @type {Array} */ + const called = [] + let index = -1 + + while (++index < constructs.length) { + const resolve = constructs[index].resolveAll + + if (resolve && !called.includes(resolve)) { + events = resolve(events, context) + called.push(resolve) + } + } + + return events +} diff --git a/node_modules/micromark-util-resolve-all/license b/node_modules/micromark-util-resolve-all/license new file mode 100644 index 0000000000000000000000000000000000000000..bc8f165a62768a19de38901d81ac662c51ff29db --- /dev/null +++ b/node_modules/micromark-util-resolve-all/license @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) Titus Wormer + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/micromark-util-resolve-all/package.json b/node_modules/micromark-util-resolve-all/package.json new file mode 100644 index 0000000000000000000000000000000000000000..f1d7c2b2af2944f79b771d35f070f76ce1378c80 --- /dev/null +++ b/node_modules/micromark-util-resolve-all/package.json @@ -0,0 +1,48 @@ +{ + "name": "micromark-util-resolve-all", + "version": "2.0.1", + "description": "micromark utility to resolve subtokens", + "license": "MIT", + "keywords": [ + "micromark", + "util", + "utility", + "resolve" + ], + "repository": "https://github.com/micromark/micromark/tree/main/packages/micromark-util-resolve-all", + "bugs": "https://github.com/micromark/micromark/issues", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "author": "Titus Wormer (https://wooorm.com)", + "contributors": [ + "Titus Wormer (https://wooorm.com)" + ], + "sideEffects": false, + "type": "module", + "files": [ + "index.d.ts.map", + "index.d.ts", + "index.js" + ], + "exports": "./index.js", + "dependencies": { + "micromark-util-types": "^2.0.0" + }, + "xo": { + "envs": [ + "shared-node-browser" + ], + "prettier": true, + "rules": { + "unicorn/prefer-code-point": "off" + } + } +} diff --git a/node_modules/micromark-util-resolve-all/readme.md b/node_modules/micromark-util-resolve-all/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..11eefd47aed053752c497307d3df2c5462eb508b --- /dev/null +++ b/node_modules/micromark-util-resolve-all/readme.md @@ -0,0 +1,238 @@ +# micromark-util-resolve-all + +[![Build][build-badge]][build] +[![Coverage][coverage-badge]][coverage] +[![Downloads][downloads-badge]][downloads] +[![Size][bundle-size-badge]][bundle-size] +[![Sponsors][sponsors-badge]][opencollective] +[![Backers][backers-badge]][opencollective] +[![Chat][chat-badge]][chat] + +[micromark][] utility to resolve subtokens. + +[Resolvers][resolver] are functions that take events and manipulate them. +This is needed for example because media (links, images) and attention (strong, +italic) aren’t parsed left-to-right. +Instead, their openings and closings are parsed, and when done, their openings +and closings are matched, and left overs are turned into plain text. +Because media and attention can’t overlap, we need to perform that operation +when one closing matches an opening, too. + +## Contents + +* [What is this?](#what-is-this) +* [When should I use this?](#when-should-i-use-this) +* [Install](#install) +* [Use](#use) +* [API](#api) + * [`resolveAll(constructs, events, context)`](#resolveallconstructs-events-context) +* [Types](#types) +* [Compatibility](#compatibility) +* [Security](#security) +* [Contribute](#contribute) +* [License](#license) + +## What is this? + +This package exposes a micromark internal that you probably don’t need. + +## When should I use this? + +This package might be useful when you are making your own micromark extensions. + +## Install + +This package is [ESM only][esm]. +In Node.js (version 16+), install with [npm][]: + +```sh +npm install micromark-util-resolve-all +``` + +In Deno with [`esm.sh`][esmsh]: + +```js +import {resolveAll} from 'https://esm.sh/micromark-util-resolve-all@1' +``` + +In browsers with [`esm.sh`][esmsh]: + +```html + +``` + +## Use + +```js +import {push} from 'micromark-util-chunked' +import {resolveAll} from 'micromark-util-resolve-all' + +/** + * @type {Resolver} + */ +function resolveAllAttention(events, context) { + // … + + // Walk through all events. + while (++index < events.length) { + // Find a token that can close. + if ( + events[index][0] === 'enter' && + events[index][1].type === 'attentionSequence' && + events[index][1]._close + ) { + open = index + + // Now walk back to find an opener. + while (open--) { + // Find a token that can open the closer. + if ( + // … + ) { + // … + + // Opening. + nextEvents = push(nextEvents, [ + // … + ]) + + // Between. + nextEvents = push( + nextEvents, + resolveAll( + context.parser.constructs.insideSpan.null, + events.slice(open + 1, index), + context + ) + ) + + // Closing. + nextEvents = push(nextEvents, [ + // … + ]) + + // … + } + } + } + } + + // … +} +``` + +## API + +This module exports the identifier [`resolveAll`][api-resolve-all]. +There is no default export. + +### `resolveAll(constructs, events, context)` + +Call all `resolveAll`s in `constructs`. + +###### Parameters + +* `constructs` (`Array`) + — list of constructs, optionally with `resolveAll`s +* `events` (`Array`) + — list of events +* `context` (`TokenizeContext`) + — context used by `tokenize` + +###### Returns + +Changed events (`Array`). + +## Types + +This package is fully typed with [TypeScript][]. +It exports no additional types. + +## Compatibility + +Projects maintained by the unified collective are compatible with maintained +versions of Node.js. + +When we cut a new major release, we drop support for unmaintained versions of +Node. +This means we try to keep the current release line, +`micromark-util-resolve-all@2`, compatible with Node.js 16. +This package works with `micromark@3`. + +## Security + +This package is safe. +See [`security.md`][securitymd] in [`micromark/.github`][health] for how to +submit a security report. + +## Contribute + +See [`contributing.md`][contributing] in [`micromark/.github`][health] for ways +to get started. +See [`support.md`][support] for ways to get help. + +This project has a [code of conduct][coc]. +By interacting with this repository, organisation, or community you agree to +abide by its terms. + +## License + +[MIT][license] © [Titus Wormer][author] + + + +[build-badge]: https://github.com/micromark/micromark/workflows/main/badge.svg + +[build]: https://github.com/micromark/micromark/actions + +[coverage-badge]: https://img.shields.io/codecov/c/github/micromark/micromark.svg + +[coverage]: https://codecov.io/github/micromark/micromark + +[downloads-badge]: https://img.shields.io/npm/dm/micromark-util-resolve-all.svg + +[downloads]: https://www.npmjs.com/package/micromark-util-resolve-all + +[bundle-size-badge]: https://img.shields.io/badge/dynamic/json?label=minzipped%20size&query=$.size.compressedSize&url=https://deno.bundlejs.com/?q=micromark-util-resolve-all + +[bundle-size]: https://bundlejs.com/?q=micromark-util-resolve-all + +[sponsors-badge]: https://opencollective.com/unified/sponsors/badge.svg + +[backers-badge]: https://opencollective.com/unified/backers/badge.svg + +[opencollective]: https://opencollective.com/unified + +[npm]: https://docs.npmjs.com/cli/install + +[esm]: https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c + +[esmsh]: https://esm.sh + +[chat-badge]: https://img.shields.io/badge/chat-discussions-success.svg + +[chat]: https://github.com/micromark/micromark/discussions + +[license]: https://github.com/micromark/micromark/blob/main/license + +[author]: https://wooorm.com + +[health]: https://github.com/micromark/.github + +[securitymd]: https://github.com/micromark/.github/blob/main/security.md + +[contributing]: https://github.com/micromark/.github/blob/main/contributing.md + +[support]: https://github.com/micromark/.github/blob/main/support.md + +[coc]: https://github.com/micromark/.github/blob/main/code-of-conduct.md + +[resolver]: https://github.com/micromark/micromark/blob/a571c09/packages/micromark-util-types/index.js#L219 + +[typescript]: https://www.typescriptlang.org + +[micromark]: https://github.com/micromark/micromark + +[api-resolve-all]: #resolveallconstructs-events-context diff --git a/node_modules/micromark-util-sanitize-uri/dev/index.d.ts b/node_modules/micromark-util-sanitize-uri/dev/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a105f230e852e42911bb97b513b8bc8c76b417e9 --- /dev/null +++ b/node_modules/micromark-util-sanitize-uri/dev/index.d.ts @@ -0,0 +1,36 @@ +/** + * Make a value safe for injection as a URL. + * + * This encodes unsafe characters with percent-encoding and skips already + * encoded sequences (see `normalizeUri`). + * Further unsafe characters are encoded as character references (see + * `micromark-util-encode`). + * + * A regex of allowed protocols can be given, in which case the URL is + * sanitized. + * For example, `/^(https?|ircs?|mailto|xmpp)$/i` can be used for `a[href]`, or + * `/^https?$/i` for `img[src]` (this is what `github.com` allows). + * If the URL includes an unknown protocol (one not matched by `protocol`, such + * as a dangerous example, `javascript:`), the value is ignored. + * + * @param {string | null | undefined} url + * URI to sanitize. + * @param {RegExp | null | undefined} [protocol] + * Allowed protocols. + * @returns {string} + * Sanitized URI. + */ +export function sanitizeUri(url: string | null | undefined, protocol?: RegExp | null | undefined): string; +/** + * Normalize a URL. + * + * Encode unsafe characters with percent-encoding, skipping already encoded + * sequences. + * + * @param {string} value + * URI to normalize. + * @returns {string} + * Normalized URI. + */ +export function normalizeUri(value: string): string; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/micromark-util-sanitize-uri/dev/index.d.ts.map b/node_modules/micromark-util-sanitize-uri/dev/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..cab948352403dc772814bc9245e78a475a8900a6 --- /dev/null +++ b/node_modules/micromark-util-sanitize-uri/dev/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.js"],"names":[],"mappings":"AAIA;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,iCAPW,MAAM,GAAG,IAAI,GAAG,SAAS,aAEzB,MAAM,GAAG,IAAI,GAAG,SAAS,GAEvB,MAAM,CA6BlB;AAED;;;;;;;;;;GAUG;AACH,oCALW,MAAM,GAEJ,MAAM,CA6DlB"} \ No newline at end of file diff --git a/node_modules/micromark-util-sanitize-uri/dev/index.js b/node_modules/micromark-util-sanitize-uri/dev/index.js new file mode 100644 index 0000000000000000000000000000000000000000..cc454b5e02e681a4cf08e1568d52834ad4035e2b --- /dev/null +++ b/node_modules/micromark-util-sanitize-uri/dev/index.js @@ -0,0 +1,124 @@ +import {asciiAlphanumeric} from 'micromark-util-character' +import {encode} from 'micromark-util-encode' +import {codes, values} from 'micromark-util-symbol' + +/** + * Make a value safe for injection as a URL. + * + * This encodes unsafe characters with percent-encoding and skips already + * encoded sequences (see `normalizeUri`). + * Further unsafe characters are encoded as character references (see + * `micromark-util-encode`). + * + * A regex of allowed protocols can be given, in which case the URL is + * sanitized. + * For example, `/^(https?|ircs?|mailto|xmpp)$/i` can be used for `a[href]`, or + * `/^https?$/i` for `img[src]` (this is what `github.com` allows). + * If the URL includes an unknown protocol (one not matched by `protocol`, such + * as a dangerous example, `javascript:`), the value is ignored. + * + * @param {string | null | undefined} url + * URI to sanitize. + * @param {RegExp | null | undefined} [protocol] + * Allowed protocols. + * @returns {string} + * Sanitized URI. + */ +export function sanitizeUri(url, protocol) { + const value = encode(normalizeUri(url || '')) + + if (!protocol) { + return value + } + + const colon = value.indexOf(':') + const questionMark = value.indexOf('?') + const numberSign = value.indexOf('#') + const slash = value.indexOf('/') + + if ( + // If there is no protocol, it’s relative. + colon < 0 || + // If the first colon is after a `?`, `#`, or `/`, it’s not a protocol. + (slash > -1 && colon > slash) || + (questionMark > -1 && colon > questionMark) || + (numberSign > -1 && colon > numberSign) || + // It is a protocol, it should be allowed. + protocol.test(value.slice(0, colon)) + ) { + return value + } + + return '' +} + +/** + * Normalize a URL. + * + * Encode unsafe characters with percent-encoding, skipping already encoded + * sequences. + * + * @param {string} value + * URI to normalize. + * @returns {string} + * Normalized URI. + */ +export function normalizeUri(value) { + /** @type {Array} */ + const result = [] + let index = -1 + let start = 0 + let skip = 0 + + while (++index < value.length) { + const code = value.charCodeAt(index) + /** @type {string} */ + let replace = '' + + // A correct percent encoded value. + if ( + code === codes.percentSign && + asciiAlphanumeric(value.charCodeAt(index + 1)) && + asciiAlphanumeric(value.charCodeAt(index + 2)) + ) { + skip = 2 + } + // ASCII. + else if (code < 128) { + if (!/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(code))) { + replace = String.fromCharCode(code) + } + } + // Astral. + else if (code > 55_295 && code < 57_344) { + const next = value.charCodeAt(index + 1) + + // A correct surrogate pair. + if (code < 56_320 && next > 56_319 && next < 57_344) { + replace = String.fromCharCode(code, next) + skip = 1 + } + // Lone surrogate. + else { + replace = values.replacementCharacter + } + } + // Unicode. + else { + replace = String.fromCharCode(code) + } + + if (replace) { + result.push(value.slice(start, index), encodeURIComponent(replace)) + start = index + skip + 1 + replace = '' + } + + if (skip) { + index += skip + skip = 0 + } + } + + return result.join('') + value.slice(start) +} diff --git a/node_modules/micromark-util-sanitize-uri/index.d.ts b/node_modules/micromark-util-sanitize-uri/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a105f230e852e42911bb97b513b8bc8c76b417e9 --- /dev/null +++ b/node_modules/micromark-util-sanitize-uri/index.d.ts @@ -0,0 +1,36 @@ +/** + * Make a value safe for injection as a URL. + * + * This encodes unsafe characters with percent-encoding and skips already + * encoded sequences (see `normalizeUri`). + * Further unsafe characters are encoded as character references (see + * `micromark-util-encode`). + * + * A regex of allowed protocols can be given, in which case the URL is + * sanitized. + * For example, `/^(https?|ircs?|mailto|xmpp)$/i` can be used for `a[href]`, or + * `/^https?$/i` for `img[src]` (this is what `github.com` allows). + * If the URL includes an unknown protocol (one not matched by `protocol`, such + * as a dangerous example, `javascript:`), the value is ignored. + * + * @param {string | null | undefined} url + * URI to sanitize. + * @param {RegExp | null | undefined} [protocol] + * Allowed protocols. + * @returns {string} + * Sanitized URI. + */ +export function sanitizeUri(url: string | null | undefined, protocol?: RegExp | null | undefined): string; +/** + * Normalize a URL. + * + * Encode unsafe characters with percent-encoding, skipping already encoded + * sequences. + * + * @param {string} value + * URI to normalize. + * @returns {string} + * Normalized URI. + */ +export function normalizeUri(value: string): string; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/micromark-util-sanitize-uri/index.d.ts.map b/node_modules/micromark-util-sanitize-uri/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..cab948352403dc772814bc9245e78a475a8900a6 --- /dev/null +++ b/node_modules/micromark-util-sanitize-uri/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.js"],"names":[],"mappings":"AAIA;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,iCAPW,MAAM,GAAG,IAAI,GAAG,SAAS,aAEzB,MAAM,GAAG,IAAI,GAAG,SAAS,GAEvB,MAAM,CA6BlB;AAED;;;;;;;;;;GAUG;AACH,oCALW,MAAM,GAEJ,MAAM,CA6DlB"} \ No newline at end of file diff --git a/node_modules/micromark-util-sanitize-uri/index.js b/node_modules/micromark-util-sanitize-uri/index.js new file mode 100644 index 0000000000000000000000000000000000000000..fb6fe6fbb8255297c7be9d3850ff945b151a2732 --- /dev/null +++ b/node_modules/micromark-util-sanitize-uri/index.js @@ -0,0 +1,107 @@ +import { asciiAlphanumeric } from 'micromark-util-character'; +import { encode } from 'micromark-util-encode'; +/** + * Make a value safe for injection as a URL. + * + * This encodes unsafe characters with percent-encoding and skips already + * encoded sequences (see `normalizeUri`). + * Further unsafe characters are encoded as character references (see + * `micromark-util-encode`). + * + * A regex of allowed protocols can be given, in which case the URL is + * sanitized. + * For example, `/^(https?|ircs?|mailto|xmpp)$/i` can be used for `a[href]`, or + * `/^https?$/i` for `img[src]` (this is what `github.com` allows). + * If the URL includes an unknown protocol (one not matched by `protocol`, such + * as a dangerous example, `javascript:`), the value is ignored. + * + * @param {string | null | undefined} url + * URI to sanitize. + * @param {RegExp | null | undefined} [protocol] + * Allowed protocols. + * @returns {string} + * Sanitized URI. + */ +export function sanitizeUri(url, protocol) { + const value = encode(normalizeUri(url || '')); + if (!protocol) { + return value; + } + const colon = value.indexOf(':'); + const questionMark = value.indexOf('?'); + const numberSign = value.indexOf('#'); + const slash = value.indexOf('/'); + if ( + // If there is no protocol, it’s relative. + colon < 0 || + // If the first colon is after a `?`, `#`, or `/`, it’s not a protocol. + slash > -1 && colon > slash || questionMark > -1 && colon > questionMark || numberSign > -1 && colon > numberSign || + // It is a protocol, it should be allowed. + protocol.test(value.slice(0, colon))) { + return value; + } + return ''; +} + +/** + * Normalize a URL. + * + * Encode unsafe characters with percent-encoding, skipping already encoded + * sequences. + * + * @param {string} value + * URI to normalize. + * @returns {string} + * Normalized URI. + */ +export function normalizeUri(value) { + /** @type {Array} */ + const result = []; + let index = -1; + let start = 0; + let skip = 0; + while (++index < value.length) { + const code = value.charCodeAt(index); + /** @type {string} */ + let replace = ''; + + // A correct percent encoded value. + if (code === 37 && asciiAlphanumeric(value.charCodeAt(index + 1)) && asciiAlphanumeric(value.charCodeAt(index + 2))) { + skip = 2; + } + // ASCII. + else if (code < 128) { + if (!/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(code))) { + replace = String.fromCharCode(code); + } + } + // Astral. + else if (code > 55_295 && code < 57_344) { + const next = value.charCodeAt(index + 1); + + // A correct surrogate pair. + if (code < 56_320 && next > 56_319 && next < 57_344) { + replace = String.fromCharCode(code, next); + skip = 1; + } + // Lone surrogate. + else { + replace = "\uFFFD"; + } + } + // Unicode. + else { + replace = String.fromCharCode(code); + } + if (replace) { + result.push(value.slice(start, index), encodeURIComponent(replace)); + start = index + skip + 1; + replace = ''; + } + if (skip) { + index += skip; + skip = 0; + } + } + return result.join('') + value.slice(start); +} \ No newline at end of file diff --git a/node_modules/micromark-util-sanitize-uri/license b/node_modules/micromark-util-sanitize-uri/license new file mode 100644 index 0000000000000000000000000000000000000000..bc8f165a62768a19de38901d81ac662c51ff29db --- /dev/null +++ b/node_modules/micromark-util-sanitize-uri/license @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) Titus Wormer + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/micromark-util-sanitize-uri/package.json b/node_modules/micromark-util-sanitize-uri/package.json new file mode 100644 index 0000000000000000000000000000000000000000..068ecbc7a4f7ae06c0f6d1ce78dcdfab1a0a4e99 --- /dev/null +++ b/node_modules/micromark-util-sanitize-uri/package.json @@ -0,0 +1,59 @@ +{ + "name": "micromark-util-sanitize-uri", + "version": "2.0.1", + "description": "micromark utility to sanitize urls", + "license": "MIT", + "keywords": [ + "micromark", + "util", + "utility", + "sanitize", + "clear", + "url" + ], + "repository": "https://github.com/micromark/micromark/tree/main/packages/micromark-util-sanitize-uri", + "bugs": "https://github.com/micromark/micromark/issues", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "author": "Titus Wormer (https://wooorm.com)", + "contributors": [ + "Titus Wormer (https://wooorm.com)" + ], + "sideEffects": false, + "type": "module", + "files": [ + "dev/", + "index.d.ts.map", + "index.d.ts", + "index.js" + ], + "exports": { + "development": "./dev/index.js", + "default": "./index.js" + }, + "dependencies": { + "micromark-util-character": "^2.0.0", + "micromark-util-encode": "^2.0.0", + "micromark-util-symbol": "^2.0.0" + }, + "scripts": { + "build": "micromark-build" + }, + "xo": { + "envs": [ + "shared-node-browser" + ], + "prettier": true, + "rules": { + "unicorn/prefer-code-point": "off" + } + } +} diff --git a/node_modules/micromark-util-sanitize-uri/readme.md b/node_modules/micromark-util-sanitize-uri/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..2d08fc51fbca8f6a9d438c6d25625748b137121d --- /dev/null +++ b/node_modules/micromark-util-sanitize-uri/readme.md @@ -0,0 +1,214 @@ +# micromark-util-sanitize-uri + +[![Build][build-badge]][build] +[![Coverage][coverage-badge]][coverage] +[![Downloads][downloads-badge]][downloads] +[![Size][bundle-size-badge]][bundle-size] +[![Sponsors][sponsors-badge]][opencollective] +[![Backers][backers-badge]][opencollective] +[![Chat][chat-badge]][chat] + +[micromark][] utility to sanitize urls. + +## Contents + +* [What is this?](#what-is-this) +* [When should I use this?](#when-should-i-use-this) +* [Install](#install) +* [Use](#use) +* [API](#api) + * [`normalizeUri(value)`](#normalizeurivalue) + * [`sanitizeUri(url[, pattern])`](#sanitizeuriurl-pattern) +* [Types](#types) +* [Compatibility](#compatibility) +* [Security](#security) +* [Contribute](#contribute) +* [License](#license) + +## What is this? + +This package exposes an algorithm to make URLs safe. + +## When should I use this? + +This package might be useful when you are making your own micromark extensions. + +## Install + +This package is [ESM only][esm]. +In Node.js (version 16+), install with [npm][]: + +```sh +npm install micromark-util-sanitize-uri +``` + +In Deno with [`esm.sh`][esmsh]: + +```js +import {sanitizeUri} from 'https://esm.sh/micromark-util-sanitize-uri@1' +``` + +In browsers with [`esm.sh`][esmsh]: + +```html + +``` + +## Use + +```js +import {sanitizeUri} from 'micromark-util-sanitize-uri' + +sanitizeUri('https://example.com/a&b') // 'https://example.com/a&amp;b' +sanitizeUri('https://example.com/a%b') // 'https://example.com/a%25b' +sanitizeUri('https://example.com/a%20b') // 'https://example.com/a%20b' +sanitizeUri('https://example.com/👍') // 'https://example.com/%F0%9F%91%8D' +sanitizeUri('https://example.com/', /^https?$/i) // 'https://example.com/' +sanitizeUri('javascript:alert(1)', /^https?$/i) // '' +sanitizeUri('./example.jpg', /^https?$/i) // './example.jpg' +sanitizeUri('#a', /^https?$/i) // '#a' +``` + +## API + +This module exports the identifiers [`normalizeUri`][api-normalize-uri] and +[`sanitizeUri`][api-sanitize-uri]. +There is no default export. + +### `normalizeUri(value)` + +Normalize a URL. + +Encode unsafe characters with percent-encoding, skipping already encoded +sequences. + +###### Parameters + +* `value` (`string`) + — URI to normalize + +###### Returns + +Normalized URI (`string`). + +### `sanitizeUri(url[, pattern])` + +Make a value safe for injection as a URL. + +This encodes unsafe characters with percent-encoding and skips already +encoded sequences (see [`normalizeUri`][api-normalize-uri]). +Further unsafe characters are encoded as character references (see +[`micromark-util-encode`][micromark-util-encode]). + +A regex of allowed protocols can be given, in which case the URL is sanitized. +For example, `/^(https?|ircs?|mailto|xmpp)$/i` can be used for `a[href]`, or +`/^https?$/i` for `img[src]` (this is what `github.com` allows). +If the URL includes an unknown protocol (one not matched by `protocol`, such +as a dangerous example, `javascript:`), the value is ignored. + +###### Parameters + +* `url` (`string`) + — URI to sanitize +* `pattern` (`RegExp`, optional) + — allowed protocols + +###### Returns + +Sanitized URI (`string`). + +## Types + +This package is fully typed with [TypeScript][]. +It exports no additional types. + +## Compatibility + +Projects maintained by the unified collective are compatible with maintained +versions of Node.js. + +When we cut a new major release, we drop support for unmaintained versions of +Node. +This means we try to keep the current release line, +`micromark-util-sanitize-uri@2`, compatible with Node.js 16. +This package works with `micromark@3`. + +## Security + +This package is safe. +See [`security.md`][securitymd] in [`micromark/.github`][health] for how to +submit a security report. + +## Contribute + +See [`contributing.md`][contributing] in [`micromark/.github`][health] for ways +to get started. +See [`support.md`][support] for ways to get help. + +This project has a [code of conduct][coc]. +By interacting with this repository, organisation, or community you agree to +abide by its terms. + +## License + +[MIT][license] © [Titus Wormer][author] + + + +[build-badge]: https://github.com/micromark/micromark/workflows/main/badge.svg + +[build]: https://github.com/micromark/micromark/actions + +[coverage-badge]: https://img.shields.io/codecov/c/github/micromark/micromark.svg + +[coverage]: https://codecov.io/github/micromark/micromark + +[downloads-badge]: https://img.shields.io/npm/dm/micromark-util-sanitize-uri.svg + +[downloads]: https://www.npmjs.com/package/micromark-util-sanitize-uri + +[bundle-size-badge]: https://img.shields.io/badge/dynamic/json?label=minzipped%20size&query=$.size.compressedSize&url=https://deno.bundlejs.com/?q=micromark-util-sanitize-uri + +[bundle-size]: https://bundlejs.com/?q=micromark-util-sanitize-uri + +[sponsors-badge]: https://opencollective.com/unified/sponsors/badge.svg + +[backers-badge]: https://opencollective.com/unified/backers/badge.svg + +[opencollective]: https://opencollective.com/unified + +[npm]: https://docs.npmjs.com/cli/install + +[esm]: https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c + +[esmsh]: https://esm.sh + +[chat-badge]: https://img.shields.io/badge/chat-discussions-success.svg + +[chat]: https://github.com/micromark/micromark/discussions + +[license]: https://github.com/micromark/micromark/blob/main/license + +[author]: https://wooorm.com + +[health]: https://github.com/micromark/.github + +[securitymd]: https://github.com/micromark/.github/blob/main/security.md + +[contributing]: https://github.com/micromark/.github/blob/main/contributing.md + +[support]: https://github.com/micromark/.github/blob/main/support.md + +[coc]: https://github.com/micromark/.github/blob/main/code-of-conduct.md + +[typescript]: https://www.typescriptlang.org + +[micromark]: https://github.com/micromark/micromark + +[micromark-util-encode]: https://github.com/micromark/micromark/tree/main/packages/micromark-util-encode + +[api-normalize-uri]: #normalizeurivalue + +[api-sanitize-uri]: #sanitizeuriurl-pattern diff --git a/node_modules/micromark-util-subtokenize/dev/index.d.ts b/node_modules/micromark-util-subtokenize/dev/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b252238a8812436614faf4342253cc45cc7f3c15 --- /dev/null +++ b/node_modules/micromark-util-subtokenize/dev/index.d.ts @@ -0,0 +1,12 @@ +/** + * Tokenize subcontent. + * + * @param {Array} eventsArray + * List of events. + * @returns {boolean} + * Whether subtokens were found. + */ +export function subtokenize(eventsArray: Array): boolean; +export { SpliceBuffer } from "./lib/splice-buffer.js"; +import type { Event } from 'micromark-util-types'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/micromark-util-subtokenize/dev/index.d.ts.map b/node_modules/micromark-util-subtokenize/dev/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..e0a024dcaee6e504fa0922fd6470c26eecf59a75 --- /dev/null +++ b/node_modules/micromark-util-subtokenize/dev/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.js"],"names":[],"mappings":"AAYA;;;;;;;GAOG;AAEH,yCANW,KAAK,CAAC,KAAK,CAAC,GAEV,OAAO,CAuHnB;;2BAvIqC,sBAAsB"} \ No newline at end of file diff --git a/node_modules/micromark-util-subtokenize/dev/index.js b/node_modules/micromark-util-subtokenize/dev/index.js new file mode 100644 index 0000000000000000000000000000000000000000..986ff0a3e493aa0b48b742aa1202499ba2298236 --- /dev/null +++ b/node_modules/micromark-util-subtokenize/dev/index.js @@ -0,0 +1,284 @@ +/** + * @import {Chunk, Event, Token} from 'micromark-util-types' + */ + +import {ok as assert} from 'devlop' +import {splice} from 'micromark-util-chunked' +import {codes, types} from 'micromark-util-symbol' +import {SpliceBuffer} from './lib/splice-buffer.js' + +// Hidden API exposed for testing. +export {SpliceBuffer} from './lib/splice-buffer.js' + +/** + * Tokenize subcontent. + * + * @param {Array} eventsArray + * List of events. + * @returns {boolean} + * Whether subtokens were found. + */ +// eslint-disable-next-line complexity +export function subtokenize(eventsArray) { + /** @type {Record} */ + const jumps = {} + let index = -1 + /** @type {Event} */ + let event + /** @type {number | undefined} */ + let lineIndex + /** @type {number} */ + let otherIndex + /** @type {Event} */ + let otherEvent + /** @type {Array} */ + let parameters + /** @type {Array} */ + let subevents + /** @type {boolean | undefined} */ + let more + const events = new SpliceBuffer(eventsArray) + + while (++index < events.length) { + while (index in jumps) { + index = jumps[index] + } + + event = events.get(index) + + // Add a hook for the GFM tasklist extension, which needs to know if text + // is in the first content of a list item. + if ( + index && + event[1].type === types.chunkFlow && + events.get(index - 1)[1].type === types.listItemPrefix + ) { + assert(event[1]._tokenizer, 'expected `_tokenizer` on subtokens') + subevents = event[1]._tokenizer.events + otherIndex = 0 + + if ( + otherIndex < subevents.length && + subevents[otherIndex][1].type === types.lineEndingBlank + ) { + otherIndex += 2 + } + + if ( + otherIndex < subevents.length && + subevents[otherIndex][1].type === types.content + ) { + while (++otherIndex < subevents.length) { + if (subevents[otherIndex][1].type === types.content) { + break + } + + if (subevents[otherIndex][1].type === types.chunkText) { + subevents[otherIndex][1]._isInFirstContentOfListItem = true + otherIndex++ + } + } + } + } + + // Enter. + if (event[0] === 'enter') { + if (event[1].contentType) { + Object.assign(jumps, subcontent(events, index)) + index = jumps[index] + more = true + } + } + // Exit. + else if (event[1]._container) { + otherIndex = index + lineIndex = undefined + + while (otherIndex--) { + otherEvent = events.get(otherIndex) + + if ( + otherEvent[1].type === types.lineEnding || + otherEvent[1].type === types.lineEndingBlank + ) { + if (otherEvent[0] === 'enter') { + if (lineIndex) { + events.get(lineIndex)[1].type = types.lineEndingBlank + } + + otherEvent[1].type = types.lineEnding + lineIndex = otherIndex + } + } else if ( + otherEvent[1].type === types.linePrefix || + otherEvent[1].type === types.listItemIndent + ) { + // Move past. + } else { + break + } + } + + if (lineIndex) { + // Fix position. + event[1].end = {...events.get(lineIndex)[1].start} + + // Switch container exit w/ line endings. + parameters = events.slice(lineIndex, index) + parameters.unshift(event) + events.splice(lineIndex, index - lineIndex + 1, parameters) + } + } + } + + // The changes to the `events` buffer must be copied back into the eventsArray + splice(eventsArray, 0, Number.POSITIVE_INFINITY, events.slice(0)) + return !more +} + +/** + * Tokenize embedded tokens. + * + * @param {SpliceBuffer} events + * Events. + * @param {number} eventIndex + * Index. + * @returns {Record} + * Gaps. + */ +function subcontent(events, eventIndex) { + const token = events.get(eventIndex)[1] + const context = events.get(eventIndex)[2] + let startPosition = eventIndex - 1 + /** @type {Array} */ + const startPositions = [] + assert(token.contentType, 'expected `contentType` on subtokens') + + let tokenizer = token._tokenizer + + if (!tokenizer) { + tokenizer = context.parser[token.contentType](token.start) + + if (token._contentTypeTextTrailing) { + tokenizer._contentTypeTextTrailing = true + } + } + + const childEvents = tokenizer.events + /** @type {Array<[number, number]>} */ + const jumps = [] + /** @type {Record} */ + const gaps = {} + /** @type {Array} */ + let stream + /** @type {Token | undefined} */ + let previous + let index = -1 + /** @type {Token | undefined} */ + let current = token + let adjust = 0 + let start = 0 + const breaks = [start] + + // Loop forward through the linked tokens to pass them in order to the + // subtokenizer. + while (current) { + // Find the position of the event for this token. + while (events.get(++startPosition)[1] !== current) { + // Empty. + } + + assert( + !previous || current.previous === previous, + 'expected previous to match' + ) + assert(!previous || previous.next === current, 'expected next to match') + + startPositions.push(startPosition) + + if (!current._tokenizer) { + stream = context.sliceStream(current) + + if (!current.next) { + stream.push(codes.eof) + } + + if (previous) { + tokenizer.defineSkip(current.start) + } + + if (current._isInFirstContentOfListItem) { + tokenizer._gfmTasklistFirstContentOfListItem = true + } + + tokenizer.write(stream) + + if (current._isInFirstContentOfListItem) { + tokenizer._gfmTasklistFirstContentOfListItem = undefined + } + } + + // Unravel the next token. + previous = current + current = current.next + } + + // Now, loop back through all events (and linked tokens), to figure out which + // parts belong where. + current = token + + while (++index < childEvents.length) { + if ( + // Find a void token that includes a break. + childEvents[index][0] === 'exit' && + childEvents[index - 1][0] === 'enter' && + childEvents[index][1].type === childEvents[index - 1][1].type && + childEvents[index][1].start.line !== childEvents[index][1].end.line + ) { + assert(current, 'expected a current token') + start = index + 1 + breaks.push(start) + // Help GC. + current._tokenizer = undefined + current.previous = undefined + current = current.next + } + } + + // Help GC. + tokenizer.events = [] + + // If there’s one more token (which is the cases for lines that end in an + // EOF), that’s perfect: the last point we found starts it. + // If there isn’t then make sure any remaining content is added to it. + if (current) { + // Help GC. + current._tokenizer = undefined + current.previous = undefined + assert(!current.next, 'expected no next token') + } else { + breaks.pop() + } + + // Now splice the events from the subtokenizer into the current events, + // moving back to front so that splice indices aren’t affected. + index = breaks.length + + while (index--) { + const slice = childEvents.slice(breaks[index], breaks[index + 1]) + const start = startPositions.pop() + assert(start !== undefined, 'expected a start position when splicing') + jumps.push([start, start + slice.length - 1]) + events.splice(start, 2, slice) + } + + jumps.reverse() + index = -1 + + while (++index < jumps.length) { + gaps[adjust + jumps[index][0]] = adjust + jumps[index][1] + adjust += jumps[index][1] - jumps[index][0] - 1 + } + + return gaps +} diff --git a/node_modules/micromark-util-subtokenize/dev/lib/splice-buffer.d.ts b/node_modules/micromark-util-subtokenize/dev/lib/splice-buffer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6e65b62385ad9dfc053775dd90b593528f017523 --- /dev/null +++ b/node_modules/micromark-util-subtokenize/dev/lib/splice-buffer.d.ts @@ -0,0 +1,161 @@ +/** + * Some of the internal operations of micromark do lots of editing + * operations on very large arrays. This runs into problems with two + * properties of most circa-2020 JavaScript interpreters: + * + * - Array-length modifications at the high end of an array (push/pop) are + * expected to be common and are implemented in (amortized) time + * proportional to the number of elements added or removed, whereas + * other operations (shift/unshift and splice) are much less efficient. + * - Function arguments are passed on the stack, so adding tens of thousands + * of elements to an array with `arr.push(...newElements)` will frequently + * cause stack overflows. (see ) + * + * SpliceBuffers are an implementation of gap buffers, which are a + * generalization of the "queue made of two stacks" idea. The splice buffer + * maintains a cursor, and moving the cursor has cost proportional to the + * distance the cursor moves, but inserting, deleting, or splicing in + * new information at the cursor is as efficient as the push/pop operation. + * This allows for an efficient sequence of splices (or pushes, pops, shifts, + * or unshifts) as long such edits happen at the same part of the array or + * generally sweep through the array from the beginning to the end. + * + * The interface for splice buffers also supports large numbers of inputs by + * passing a single array argument rather passing multiple arguments on the + * function call stack. + * + * @template T + * Item type. + */ +export class SpliceBuffer { + /** + * @param {ReadonlyArray | null | undefined} [initial] + * Initial items (optional). + * @returns + * Splice buffer. + */ + constructor(initial?: ReadonlyArray | null | undefined); + /** @type {Array} */ + left: Array; + /** @type {Array} */ + right: Array; + /** + * Array access; + * does not move the cursor. + * + * @param {number} index + * Index. + * @return {T} + * Item. + */ + get(index: number): T; + /** + * The length of the splice buffer, one greater than the largest index in the + * array. + */ + get length(): number; + /** + * Remove and return `list[0]`; + * moves the cursor to `0`. + * + * @returns {T | undefined} + * Item, optional. + */ + shift(): T | undefined; + /** + * Slice the buffer to get an array; + * does not move the cursor. + * + * @param {number} start + * Start. + * @param {number | null | undefined} [end] + * End (optional). + * @returns {Array} + * Array of items. + */ + slice(start: number, end?: number | null | undefined): Array; + /** + * Mimics the behavior of Array.prototype.splice() except for the change of + * interface necessary to avoid segfaults when patching in very large arrays. + * + * This operation moves cursor is moved to `start` and results in the cursor + * placed after any inserted items. + * + * @param {number} start + * Start; + * zero-based index at which to start changing the array; + * negative numbers count backwards from the end of the array and values + * that are out-of bounds are clamped to the appropriate end of the array. + * @param {number | null | undefined} [deleteCount=0] + * Delete count (default: `0`); + * maximum number of elements to delete, starting from start. + * @param {Array | null | undefined} [items=[]] + * Items to include in place of the deleted items (default: `[]`). + * @return {Array} + * Any removed items. + */ + splice(start: number, deleteCount?: number | null | undefined, items?: Array | null | undefined): Array; + /** + * Remove and return the highest-numbered item in the array, so + * `list[list.length - 1]`; + * Moves the cursor to `length`. + * + * @returns {T | undefined} + * Item, optional. + */ + pop(): T | undefined; + /** + * Inserts a single item to the high-numbered side of the array; + * moves the cursor to `length`. + * + * @param {T} item + * Item. + * @returns {undefined} + * Nothing. + */ + push(item: T): undefined; + /** + * Inserts many items to the high-numbered side of the array. + * Moves the cursor to `length`. + * + * @param {Array} items + * Items. + * @returns {undefined} + * Nothing. + */ + pushMany(items: Array): undefined; + /** + * Inserts a single item to the low-numbered side of the array; + * Moves the cursor to `0`. + * + * @param {T} item + * Item. + * @returns {undefined} + * Nothing. + */ + unshift(item: T): undefined; + /** + * Inserts many items to the low-numbered side of the array; + * moves the cursor to `0`. + * + * @param {Array} items + * Items. + * @returns {undefined} + * Nothing. + */ + unshiftMany(items: Array): undefined; + /** + * Move the cursor to a specific position in the array. Requires + * time proportional to the distance moved. + * + * If `n < 0`, the cursor will end up at the beginning. + * If `n > length`, the cursor will end up at the end. + * + * @param {number} n + * Position. + * @return {undefined} + * Nothing. + */ + setCursor(n: number): undefined; +} +//# sourceMappingURL=splice-buffer.d.ts.map \ No newline at end of file diff --git a/node_modules/micromark-util-subtokenize/dev/lib/splice-buffer.d.ts.map b/node_modules/micromark-util-subtokenize/dev/lib/splice-buffer.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..438ca1c82c6eaa9c7ea78699198d41066fd60c46 --- /dev/null +++ b/node_modules/micromark-util-subtokenize/dev/lib/splice-buffer.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"splice-buffer.d.ts","sourceRoot":"","sources":["splice-buffer.js"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,0BAHa,CAAC;IAIZ;;;;;OAKG;IACH,sBALW,aAAa,CAAC,CAAC,CAAC,GAAG,IAAI,GAAG,SAAS,EAU7C;IAJC,uBAAuB;IACvB,MADW,KAAK,CAAC,CAAC,CAAC,CACoB;IACvC,uBAAuB;IACvB,OADW,KAAK,CAAC,CAAC,CAAC,CACJ;IAGjB;;;;;;;;OAQG;IACH,WALW,MAAM,GAEL,CAAC,CAgBZ;IAED;;;OAGG;IACH,qBAEC;IAED;;;;;;OAMG;IACH,SAHa,CAAC,GAAG,SAAS,CAMzB;IAED;;;;;;;;;;OAUG;IACH,aAPW,MAAM,QAEN,MAAM,GAAG,IAAI,GAAG,SAAS,GAEvB,KAAK,CAAC,CAAC,CAAC,CA0BpB;IAED;;;;;;;;;;;;;;;;;;;OAmBG;IACH,cAbW,MAAM,gBAKN,MAAM,GAAG,IAAI,GAAG,SAAS,UAGzB,KAAK,CAAC,CAAC,CAAC,GAAG,IAAI,GAAG,SAAS,GAE1B,KAAK,CAAC,CAAC,CAAC,CAcnB;IAED;;;;;;;OAOG;IACH,OAHa,CAAC,GAAG,SAAS,CAMzB;IAED;;;;;;;;OAQG;IACH,WALW,CAAC,GAEC,SAAS,CAMrB;IAED;;;;;;;;OAQG;IACH,gBALW,KAAK,CAAC,CAAC,CAAC,GAEN,SAAS,CAMrB;IAED;;;;;;;;OAQG;IACH,cALW,CAAC,GAEC,SAAS,CAMrB;IAED;;;;;;;;OAQG;IACH,mBALW,KAAK,CAAC,CAAC,CAAC,GAEN,SAAS,CAMrB;IAED;;;;;;;;;;;OAWG;IACH,aALW,MAAM,GAEL,SAAS,CAsBpB;CACF"} \ No newline at end of file diff --git a/node_modules/micromark-util-subtokenize/dev/lib/splice-buffer.js b/node_modules/micromark-util-subtokenize/dev/lib/splice-buffer.js new file mode 100644 index 0000000000000000000000000000000000000000..371a9227e22a345a276cd216101bab7b33b416f8 --- /dev/null +++ b/node_modules/micromark-util-subtokenize/dev/lib/splice-buffer.js @@ -0,0 +1,288 @@ +import {constants} from 'micromark-util-symbol' + +/** + * Some of the internal operations of micromark do lots of editing + * operations on very large arrays. This runs into problems with two + * properties of most circa-2020 JavaScript interpreters: + * + * - Array-length modifications at the high end of an array (push/pop) are + * expected to be common and are implemented in (amortized) time + * proportional to the number of elements added or removed, whereas + * other operations (shift/unshift and splice) are much less efficient. + * - Function arguments are passed on the stack, so adding tens of thousands + * of elements to an array with `arr.push(...newElements)` will frequently + * cause stack overflows. (see ) + * + * SpliceBuffers are an implementation of gap buffers, which are a + * generalization of the "queue made of two stacks" idea. The splice buffer + * maintains a cursor, and moving the cursor has cost proportional to the + * distance the cursor moves, but inserting, deleting, or splicing in + * new information at the cursor is as efficient as the push/pop operation. + * This allows for an efficient sequence of splices (or pushes, pops, shifts, + * or unshifts) as long such edits happen at the same part of the array or + * generally sweep through the array from the beginning to the end. + * + * The interface for splice buffers also supports large numbers of inputs by + * passing a single array argument rather passing multiple arguments on the + * function call stack. + * + * @template T + * Item type. + */ +export class SpliceBuffer { + /** + * @param {ReadonlyArray | null | undefined} [initial] + * Initial items (optional). + * @returns + * Splice buffer. + */ + constructor(initial) { + /** @type {Array} */ + this.left = initial ? [...initial] : [] + /** @type {Array} */ + this.right = [] + } + + /** + * Array access; + * does not move the cursor. + * + * @param {number} index + * Index. + * @return {T} + * Item. + */ + get(index) { + if (index < 0 || index >= this.left.length + this.right.length) { + throw new RangeError( + 'Cannot access index `' + + index + + '` in a splice buffer of size `' + + (this.left.length + this.right.length) + + '`' + ) + } + + if (index < this.left.length) return this.left[index] + return this.right[this.right.length - index + this.left.length - 1] + } + + /** + * The length of the splice buffer, one greater than the largest index in the + * array. + */ + get length() { + return this.left.length + this.right.length + } + + /** + * Remove and return `list[0]`; + * moves the cursor to `0`. + * + * @returns {T | undefined} + * Item, optional. + */ + shift() { + this.setCursor(0) + return this.right.pop() + } + + /** + * Slice the buffer to get an array; + * does not move the cursor. + * + * @param {number} start + * Start. + * @param {number | null | undefined} [end] + * End (optional). + * @returns {Array} + * Array of items. + */ + slice(start, end) { + /** @type {number} */ + const stop = + end === null || end === undefined ? Number.POSITIVE_INFINITY : end + + if (stop < this.left.length) { + return this.left.slice(start, stop) + } + + if (start > this.left.length) { + return this.right + .slice( + this.right.length - stop + this.left.length, + this.right.length - start + this.left.length + ) + .reverse() + } + + return this.left + .slice(start) + .concat( + this.right.slice(this.right.length - stop + this.left.length).reverse() + ) + } + + /** + * Mimics the behavior of Array.prototype.splice() except for the change of + * interface necessary to avoid segfaults when patching in very large arrays. + * + * This operation moves cursor is moved to `start` and results in the cursor + * placed after any inserted items. + * + * @param {number} start + * Start; + * zero-based index at which to start changing the array; + * negative numbers count backwards from the end of the array and values + * that are out-of bounds are clamped to the appropriate end of the array. + * @param {number | null | undefined} [deleteCount=0] + * Delete count (default: `0`); + * maximum number of elements to delete, starting from start. + * @param {Array | null | undefined} [items=[]] + * Items to include in place of the deleted items (default: `[]`). + * @return {Array} + * Any removed items. + */ + splice(start, deleteCount, items) { + /** @type {number} */ + const count = deleteCount || 0 + + this.setCursor(Math.trunc(start)) + const removed = this.right.splice( + this.right.length - count, + Number.POSITIVE_INFINITY + ) + if (items) chunkedPush(this.left, items) + return removed.reverse() + } + + /** + * Remove and return the highest-numbered item in the array, so + * `list[list.length - 1]`; + * Moves the cursor to `length`. + * + * @returns {T | undefined} + * Item, optional. + */ + pop() { + this.setCursor(Number.POSITIVE_INFINITY) + return this.left.pop() + } + + /** + * Inserts a single item to the high-numbered side of the array; + * moves the cursor to `length`. + * + * @param {T} item + * Item. + * @returns {undefined} + * Nothing. + */ + push(item) { + this.setCursor(Number.POSITIVE_INFINITY) + this.left.push(item) + } + + /** + * Inserts many items to the high-numbered side of the array. + * Moves the cursor to `length`. + * + * @param {Array} items + * Items. + * @returns {undefined} + * Nothing. + */ + pushMany(items) { + this.setCursor(Number.POSITIVE_INFINITY) + chunkedPush(this.left, items) + } + + /** + * Inserts a single item to the low-numbered side of the array; + * Moves the cursor to `0`. + * + * @param {T} item + * Item. + * @returns {undefined} + * Nothing. + */ + unshift(item) { + this.setCursor(0) + this.right.push(item) + } + + /** + * Inserts many items to the low-numbered side of the array; + * moves the cursor to `0`. + * + * @param {Array} items + * Items. + * @returns {undefined} + * Nothing. + */ + unshiftMany(items) { + this.setCursor(0) + chunkedPush(this.right, items.reverse()) + } + + /** + * Move the cursor to a specific position in the array. Requires + * time proportional to the distance moved. + * + * If `n < 0`, the cursor will end up at the beginning. + * If `n > length`, the cursor will end up at the end. + * + * @param {number} n + * Position. + * @return {undefined} + * Nothing. + */ + setCursor(n) { + if ( + n === this.left.length || + (n > this.left.length && this.right.length === 0) || + (n < 0 && this.left.length === 0) + ) + return + if (n < this.left.length) { + // Move cursor to the this.left + const removed = this.left.splice(n, Number.POSITIVE_INFINITY) + chunkedPush(this.right, removed.reverse()) + } else { + // Move cursor to the this.right + const removed = this.right.splice( + this.left.length + this.right.length - n, + Number.POSITIVE_INFINITY + ) + chunkedPush(this.left, removed.reverse()) + } + } +} + +/** + * Avoid stack overflow by pushing items onto the stack in segments + * + * @template T + * Item type. + * @param {Array} list + * List to inject into. + * @param {ReadonlyArray} right + * Items to inject. + * @return {undefined} + * Nothing. + */ +function chunkedPush(list, right) { + /** @type {number} */ + let chunkStart = 0 + + if (right.length < constants.v8MaxSafeChunkSize) { + list.push(...right) + } else { + while (chunkStart < right.length) { + list.push( + ...right.slice(chunkStart, chunkStart + constants.v8MaxSafeChunkSize) + ) + chunkStart += constants.v8MaxSafeChunkSize + } + } +} diff --git a/node_modules/micromark-util-subtokenize/index.d.ts b/node_modules/micromark-util-subtokenize/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b252238a8812436614faf4342253cc45cc7f3c15 --- /dev/null +++ b/node_modules/micromark-util-subtokenize/index.d.ts @@ -0,0 +1,12 @@ +/** + * Tokenize subcontent. + * + * @param {Array} eventsArray + * List of events. + * @returns {boolean} + * Whether subtokens were found. + */ +export function subtokenize(eventsArray: Array): boolean; +export { SpliceBuffer } from "./lib/splice-buffer.js"; +import type { Event } from 'micromark-util-types'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/micromark-util-subtokenize/index.d.ts.map b/node_modules/micromark-util-subtokenize/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..e0a024dcaee6e504fa0922fd6470c26eecf59a75 --- /dev/null +++ b/node_modules/micromark-util-subtokenize/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.js"],"names":[],"mappings":"AAYA;;;;;;;GAOG;AAEH,yCANW,KAAK,CAAC,KAAK,CAAC,GAEV,OAAO,CAuHnB;;2BAvIqC,sBAAsB"} \ No newline at end of file diff --git a/node_modules/micromark-util-subtokenize/index.js b/node_modules/micromark-util-subtokenize/index.js new file mode 100644 index 0000000000000000000000000000000000000000..f046dc30416d45494071dc5d1a75faa9982e1c58 --- /dev/null +++ b/node_modules/micromark-util-subtokenize/index.js @@ -0,0 +1,228 @@ +/** + * @import {Chunk, Event, Token} from 'micromark-util-types' + */ + +import { splice } from 'micromark-util-chunked'; +import { SpliceBuffer } from './lib/splice-buffer.js'; + +// Hidden API exposed for testing. +export { SpliceBuffer } from './lib/splice-buffer.js'; + +/** + * Tokenize subcontent. + * + * @param {Array} eventsArray + * List of events. + * @returns {boolean} + * Whether subtokens were found. + */ +// eslint-disable-next-line complexity +export function subtokenize(eventsArray) { + /** @type {Record} */ + const jumps = {}; + let index = -1; + /** @type {Event} */ + let event; + /** @type {number | undefined} */ + let lineIndex; + /** @type {number} */ + let otherIndex; + /** @type {Event} */ + let otherEvent; + /** @type {Array} */ + let parameters; + /** @type {Array} */ + let subevents; + /** @type {boolean | undefined} */ + let more; + const events = new SpliceBuffer(eventsArray); + while (++index < events.length) { + while (index in jumps) { + index = jumps[index]; + } + event = events.get(index); + + // Add a hook for the GFM tasklist extension, which needs to know if text + // is in the first content of a list item. + if (index && event[1].type === "chunkFlow" && events.get(index - 1)[1].type === "listItemPrefix") { + subevents = event[1]._tokenizer.events; + otherIndex = 0; + if (otherIndex < subevents.length && subevents[otherIndex][1].type === "lineEndingBlank") { + otherIndex += 2; + } + if (otherIndex < subevents.length && subevents[otherIndex][1].type === "content") { + while (++otherIndex < subevents.length) { + if (subevents[otherIndex][1].type === "content") { + break; + } + if (subevents[otherIndex][1].type === "chunkText") { + subevents[otherIndex][1]._isInFirstContentOfListItem = true; + otherIndex++; + } + } + } + } + + // Enter. + if (event[0] === 'enter') { + if (event[1].contentType) { + Object.assign(jumps, subcontent(events, index)); + index = jumps[index]; + more = true; + } + } + // Exit. + else if (event[1]._container) { + otherIndex = index; + lineIndex = undefined; + while (otherIndex--) { + otherEvent = events.get(otherIndex); + if (otherEvent[1].type === "lineEnding" || otherEvent[1].type === "lineEndingBlank") { + if (otherEvent[0] === 'enter') { + if (lineIndex) { + events.get(lineIndex)[1].type = "lineEndingBlank"; + } + otherEvent[1].type = "lineEnding"; + lineIndex = otherIndex; + } + } else if (otherEvent[1].type === "linePrefix" || otherEvent[1].type === "listItemIndent") { + // Move past. + } else { + break; + } + } + if (lineIndex) { + // Fix position. + event[1].end = { + ...events.get(lineIndex)[1].start + }; + + // Switch container exit w/ line endings. + parameters = events.slice(lineIndex, index); + parameters.unshift(event); + events.splice(lineIndex, index - lineIndex + 1, parameters); + } + } + } + + // The changes to the `events` buffer must be copied back into the eventsArray + splice(eventsArray, 0, Number.POSITIVE_INFINITY, events.slice(0)); + return !more; +} + +/** + * Tokenize embedded tokens. + * + * @param {SpliceBuffer} events + * Events. + * @param {number} eventIndex + * Index. + * @returns {Record} + * Gaps. + */ +function subcontent(events, eventIndex) { + const token = events.get(eventIndex)[1]; + const context = events.get(eventIndex)[2]; + let startPosition = eventIndex - 1; + /** @type {Array} */ + const startPositions = []; + let tokenizer = token._tokenizer; + if (!tokenizer) { + tokenizer = context.parser[token.contentType](token.start); + if (token._contentTypeTextTrailing) { + tokenizer._contentTypeTextTrailing = true; + } + } + const childEvents = tokenizer.events; + /** @type {Array<[number, number]>} */ + const jumps = []; + /** @type {Record} */ + const gaps = {}; + /** @type {Array} */ + let stream; + /** @type {Token | undefined} */ + let previous; + let index = -1; + /** @type {Token | undefined} */ + let current = token; + let adjust = 0; + let start = 0; + const breaks = [start]; + + // Loop forward through the linked tokens to pass them in order to the + // subtokenizer. + while (current) { + // Find the position of the event for this token. + while (events.get(++startPosition)[1] !== current) { + // Empty. + } + startPositions.push(startPosition); + if (!current._tokenizer) { + stream = context.sliceStream(current); + if (!current.next) { + stream.push(null); + } + if (previous) { + tokenizer.defineSkip(current.start); + } + if (current._isInFirstContentOfListItem) { + tokenizer._gfmTasklistFirstContentOfListItem = true; + } + tokenizer.write(stream); + if (current._isInFirstContentOfListItem) { + tokenizer._gfmTasklistFirstContentOfListItem = undefined; + } + } + + // Unravel the next token. + previous = current; + current = current.next; + } + + // Now, loop back through all events (and linked tokens), to figure out which + // parts belong where. + current = token; + while (++index < childEvents.length) { + if ( + // Find a void token that includes a break. + childEvents[index][0] === 'exit' && childEvents[index - 1][0] === 'enter' && childEvents[index][1].type === childEvents[index - 1][1].type && childEvents[index][1].start.line !== childEvents[index][1].end.line) { + start = index + 1; + breaks.push(start); + // Help GC. + current._tokenizer = undefined; + current.previous = undefined; + current = current.next; + } + } + + // Help GC. + tokenizer.events = []; + + // If there’s one more token (which is the cases for lines that end in an + // EOF), that’s perfect: the last point we found starts it. + // If there isn’t then make sure any remaining content is added to it. + if (current) { + // Help GC. + current._tokenizer = undefined; + current.previous = undefined; + } else { + breaks.pop(); + } + + // Now splice the events from the subtokenizer into the current events, + // moving back to front so that splice indices aren’t affected. + index = breaks.length; + while (index--) { + const slice = childEvents.slice(breaks[index], breaks[index + 1]); + const start = startPositions.pop(); + jumps.push([start, start + slice.length - 1]); + events.splice(start, 2, slice); + } + jumps.reverse(); + index = -1; + while (++index < jumps.length) { + gaps[adjust + jumps[index][0]] = adjust + jumps[index][1]; + adjust += jumps[index][1] - jumps[index][0] - 1; + } + return gaps; +} \ No newline at end of file diff --git a/node_modules/micromark-util-subtokenize/lib/splice-buffer.d.ts b/node_modules/micromark-util-subtokenize/lib/splice-buffer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6e65b62385ad9dfc053775dd90b593528f017523 --- /dev/null +++ b/node_modules/micromark-util-subtokenize/lib/splice-buffer.d.ts @@ -0,0 +1,161 @@ +/** + * Some of the internal operations of micromark do lots of editing + * operations on very large arrays. This runs into problems with two + * properties of most circa-2020 JavaScript interpreters: + * + * - Array-length modifications at the high end of an array (push/pop) are + * expected to be common and are implemented in (amortized) time + * proportional to the number of elements added or removed, whereas + * other operations (shift/unshift and splice) are much less efficient. + * - Function arguments are passed on the stack, so adding tens of thousands + * of elements to an array with `arr.push(...newElements)` will frequently + * cause stack overflows. (see ) + * + * SpliceBuffers are an implementation of gap buffers, which are a + * generalization of the "queue made of two stacks" idea. The splice buffer + * maintains a cursor, and moving the cursor has cost proportional to the + * distance the cursor moves, but inserting, deleting, or splicing in + * new information at the cursor is as efficient as the push/pop operation. + * This allows for an efficient sequence of splices (or pushes, pops, shifts, + * or unshifts) as long such edits happen at the same part of the array or + * generally sweep through the array from the beginning to the end. + * + * The interface for splice buffers also supports large numbers of inputs by + * passing a single array argument rather passing multiple arguments on the + * function call stack. + * + * @template T + * Item type. + */ +export class SpliceBuffer { + /** + * @param {ReadonlyArray | null | undefined} [initial] + * Initial items (optional). + * @returns + * Splice buffer. + */ + constructor(initial?: ReadonlyArray | null | undefined); + /** @type {Array} */ + left: Array; + /** @type {Array} */ + right: Array; + /** + * Array access; + * does not move the cursor. + * + * @param {number} index + * Index. + * @return {T} + * Item. + */ + get(index: number): T; + /** + * The length of the splice buffer, one greater than the largest index in the + * array. + */ + get length(): number; + /** + * Remove and return `list[0]`; + * moves the cursor to `0`. + * + * @returns {T | undefined} + * Item, optional. + */ + shift(): T | undefined; + /** + * Slice the buffer to get an array; + * does not move the cursor. + * + * @param {number} start + * Start. + * @param {number | null | undefined} [end] + * End (optional). + * @returns {Array} + * Array of items. + */ + slice(start: number, end?: number | null | undefined): Array; + /** + * Mimics the behavior of Array.prototype.splice() except for the change of + * interface necessary to avoid segfaults when patching in very large arrays. + * + * This operation moves cursor is moved to `start` and results in the cursor + * placed after any inserted items. + * + * @param {number} start + * Start; + * zero-based index at which to start changing the array; + * negative numbers count backwards from the end of the array and values + * that are out-of bounds are clamped to the appropriate end of the array. + * @param {number | null | undefined} [deleteCount=0] + * Delete count (default: `0`); + * maximum number of elements to delete, starting from start. + * @param {Array | null | undefined} [items=[]] + * Items to include in place of the deleted items (default: `[]`). + * @return {Array} + * Any removed items. + */ + splice(start: number, deleteCount?: number | null | undefined, items?: Array | null | undefined): Array; + /** + * Remove and return the highest-numbered item in the array, so + * `list[list.length - 1]`; + * Moves the cursor to `length`. + * + * @returns {T | undefined} + * Item, optional. + */ + pop(): T | undefined; + /** + * Inserts a single item to the high-numbered side of the array; + * moves the cursor to `length`. + * + * @param {T} item + * Item. + * @returns {undefined} + * Nothing. + */ + push(item: T): undefined; + /** + * Inserts many items to the high-numbered side of the array. + * Moves the cursor to `length`. + * + * @param {Array} items + * Items. + * @returns {undefined} + * Nothing. + */ + pushMany(items: Array): undefined; + /** + * Inserts a single item to the low-numbered side of the array; + * Moves the cursor to `0`. + * + * @param {T} item + * Item. + * @returns {undefined} + * Nothing. + */ + unshift(item: T): undefined; + /** + * Inserts many items to the low-numbered side of the array; + * moves the cursor to `0`. + * + * @param {Array} items + * Items. + * @returns {undefined} + * Nothing. + */ + unshiftMany(items: Array): undefined; + /** + * Move the cursor to a specific position in the array. Requires + * time proportional to the distance moved. + * + * If `n < 0`, the cursor will end up at the beginning. + * If `n > length`, the cursor will end up at the end. + * + * @param {number} n + * Position. + * @return {undefined} + * Nothing. + */ + setCursor(n: number): undefined; +} +//# sourceMappingURL=splice-buffer.d.ts.map \ No newline at end of file diff --git a/node_modules/micromark-util-subtokenize/lib/splice-buffer.d.ts.map b/node_modules/micromark-util-subtokenize/lib/splice-buffer.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..438ca1c82c6eaa9c7ea78699198d41066fd60c46 --- /dev/null +++ b/node_modules/micromark-util-subtokenize/lib/splice-buffer.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"splice-buffer.d.ts","sourceRoot":"","sources":["splice-buffer.js"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,0BAHa,CAAC;IAIZ;;;;;OAKG;IACH,sBALW,aAAa,CAAC,CAAC,CAAC,GAAG,IAAI,GAAG,SAAS,EAU7C;IAJC,uBAAuB;IACvB,MADW,KAAK,CAAC,CAAC,CAAC,CACoB;IACvC,uBAAuB;IACvB,OADW,KAAK,CAAC,CAAC,CAAC,CACJ;IAGjB;;;;;;;;OAQG;IACH,WALW,MAAM,GAEL,CAAC,CAgBZ;IAED;;;OAGG;IACH,qBAEC;IAED;;;;;;OAMG;IACH,SAHa,CAAC,GAAG,SAAS,CAMzB;IAED;;;;;;;;;;OAUG;IACH,aAPW,MAAM,QAEN,MAAM,GAAG,IAAI,GAAG,SAAS,GAEvB,KAAK,CAAC,CAAC,CAAC,CA0BpB;IAED;;;;;;;;;;;;;;;;;;;OAmBG;IACH,cAbW,MAAM,gBAKN,MAAM,GAAG,IAAI,GAAG,SAAS,UAGzB,KAAK,CAAC,CAAC,CAAC,GAAG,IAAI,GAAG,SAAS,GAE1B,KAAK,CAAC,CAAC,CAAC,CAcnB;IAED;;;;;;;OAOG;IACH,OAHa,CAAC,GAAG,SAAS,CAMzB;IAED;;;;;;;;OAQG;IACH,WALW,CAAC,GAEC,SAAS,CAMrB;IAED;;;;;;;;OAQG;IACH,gBALW,KAAK,CAAC,CAAC,CAAC,GAEN,SAAS,CAMrB;IAED;;;;;;;;OAQG;IACH,cALW,CAAC,GAEC,SAAS,CAMrB;IAED;;;;;;;;OAQG;IACH,mBALW,KAAK,CAAC,CAAC,CAAC,GAEN,SAAS,CAMrB;IAED;;;;;;;;;;;OAWG;IACH,aALW,MAAM,GAEL,SAAS,CAsBpB;CACF"} \ No newline at end of file diff --git a/node_modules/micromark-util-subtokenize/lib/splice-buffer.js b/node_modules/micromark-util-subtokenize/lib/splice-buffer.js new file mode 100644 index 0000000000000000000000000000000000000000..500e42f63b40d04ca8e5a7a09cb8a5f9e51726ec --- /dev/null +++ b/node_modules/micromark-util-subtokenize/lib/splice-buffer.js @@ -0,0 +1,251 @@ +/** + * Some of the internal operations of micromark do lots of editing + * operations on very large arrays. This runs into problems with two + * properties of most circa-2020 JavaScript interpreters: + * + * - Array-length modifications at the high end of an array (push/pop) are + * expected to be common and are implemented in (amortized) time + * proportional to the number of elements added or removed, whereas + * other operations (shift/unshift and splice) are much less efficient. + * - Function arguments are passed on the stack, so adding tens of thousands + * of elements to an array with `arr.push(...newElements)` will frequently + * cause stack overflows. (see ) + * + * SpliceBuffers are an implementation of gap buffers, which are a + * generalization of the "queue made of two stacks" idea. The splice buffer + * maintains a cursor, and moving the cursor has cost proportional to the + * distance the cursor moves, but inserting, deleting, or splicing in + * new information at the cursor is as efficient as the push/pop operation. + * This allows for an efficient sequence of splices (or pushes, pops, shifts, + * or unshifts) as long such edits happen at the same part of the array or + * generally sweep through the array from the beginning to the end. + * + * The interface for splice buffers also supports large numbers of inputs by + * passing a single array argument rather passing multiple arguments on the + * function call stack. + * + * @template T + * Item type. + */ +export class SpliceBuffer { + /** + * @param {ReadonlyArray | null | undefined} [initial] + * Initial items (optional). + * @returns + * Splice buffer. + */ + constructor(initial) { + /** @type {Array} */ + this.left = initial ? [...initial] : []; + /** @type {Array} */ + this.right = []; + } + + /** + * Array access; + * does not move the cursor. + * + * @param {number} index + * Index. + * @return {T} + * Item. + */ + get(index) { + if (index < 0 || index >= this.left.length + this.right.length) { + throw new RangeError('Cannot access index `' + index + '` in a splice buffer of size `' + (this.left.length + this.right.length) + '`'); + } + if (index < this.left.length) return this.left[index]; + return this.right[this.right.length - index + this.left.length - 1]; + } + + /** + * The length of the splice buffer, one greater than the largest index in the + * array. + */ + get length() { + return this.left.length + this.right.length; + } + + /** + * Remove and return `list[0]`; + * moves the cursor to `0`. + * + * @returns {T | undefined} + * Item, optional. + */ + shift() { + this.setCursor(0); + return this.right.pop(); + } + + /** + * Slice the buffer to get an array; + * does not move the cursor. + * + * @param {number} start + * Start. + * @param {number | null | undefined} [end] + * End (optional). + * @returns {Array} + * Array of items. + */ + slice(start, end) { + /** @type {number} */ + const stop = end === null || end === undefined ? Number.POSITIVE_INFINITY : end; + if (stop < this.left.length) { + return this.left.slice(start, stop); + } + if (start > this.left.length) { + return this.right.slice(this.right.length - stop + this.left.length, this.right.length - start + this.left.length).reverse(); + } + return this.left.slice(start).concat(this.right.slice(this.right.length - stop + this.left.length).reverse()); + } + + /** + * Mimics the behavior of Array.prototype.splice() except for the change of + * interface necessary to avoid segfaults when patching in very large arrays. + * + * This operation moves cursor is moved to `start` and results in the cursor + * placed after any inserted items. + * + * @param {number} start + * Start; + * zero-based index at which to start changing the array; + * negative numbers count backwards from the end of the array and values + * that are out-of bounds are clamped to the appropriate end of the array. + * @param {number | null | undefined} [deleteCount=0] + * Delete count (default: `0`); + * maximum number of elements to delete, starting from start. + * @param {Array | null | undefined} [items=[]] + * Items to include in place of the deleted items (default: `[]`). + * @return {Array} + * Any removed items. + */ + splice(start, deleteCount, items) { + /** @type {number} */ + const count = deleteCount || 0; + this.setCursor(Math.trunc(start)); + const removed = this.right.splice(this.right.length - count, Number.POSITIVE_INFINITY); + if (items) chunkedPush(this.left, items); + return removed.reverse(); + } + + /** + * Remove and return the highest-numbered item in the array, so + * `list[list.length - 1]`; + * Moves the cursor to `length`. + * + * @returns {T | undefined} + * Item, optional. + */ + pop() { + this.setCursor(Number.POSITIVE_INFINITY); + return this.left.pop(); + } + + /** + * Inserts a single item to the high-numbered side of the array; + * moves the cursor to `length`. + * + * @param {T} item + * Item. + * @returns {undefined} + * Nothing. + */ + push(item) { + this.setCursor(Number.POSITIVE_INFINITY); + this.left.push(item); + } + + /** + * Inserts many items to the high-numbered side of the array. + * Moves the cursor to `length`. + * + * @param {Array} items + * Items. + * @returns {undefined} + * Nothing. + */ + pushMany(items) { + this.setCursor(Number.POSITIVE_INFINITY); + chunkedPush(this.left, items); + } + + /** + * Inserts a single item to the low-numbered side of the array; + * Moves the cursor to `0`. + * + * @param {T} item + * Item. + * @returns {undefined} + * Nothing. + */ + unshift(item) { + this.setCursor(0); + this.right.push(item); + } + + /** + * Inserts many items to the low-numbered side of the array; + * moves the cursor to `0`. + * + * @param {Array} items + * Items. + * @returns {undefined} + * Nothing. + */ + unshiftMany(items) { + this.setCursor(0); + chunkedPush(this.right, items.reverse()); + } + + /** + * Move the cursor to a specific position in the array. Requires + * time proportional to the distance moved. + * + * If `n < 0`, the cursor will end up at the beginning. + * If `n > length`, the cursor will end up at the end. + * + * @param {number} n + * Position. + * @return {undefined} + * Nothing. + */ + setCursor(n) { + if (n === this.left.length || n > this.left.length && this.right.length === 0 || n < 0 && this.left.length === 0) return; + if (n < this.left.length) { + // Move cursor to the this.left + const removed = this.left.splice(n, Number.POSITIVE_INFINITY); + chunkedPush(this.right, removed.reverse()); + } else { + // Move cursor to the this.right + const removed = this.right.splice(this.left.length + this.right.length - n, Number.POSITIVE_INFINITY); + chunkedPush(this.left, removed.reverse()); + } + } +} + +/** + * Avoid stack overflow by pushing items onto the stack in segments + * + * @template T + * Item type. + * @param {Array} list + * List to inject into. + * @param {ReadonlyArray} right + * Items to inject. + * @return {undefined} + * Nothing. + */ +function chunkedPush(list, right) { + /** @type {number} */ + let chunkStart = 0; + if (right.length < 10000) { + list.push(...right); + } else { + while (chunkStart < right.length) { + list.push(...right.slice(chunkStart, chunkStart + 10000)); + chunkStart += 10000; + } + } +} \ No newline at end of file diff --git a/node_modules/micromark-util-subtokenize/license b/node_modules/micromark-util-subtokenize/license new file mode 100644 index 0000000000000000000000000000000000000000..bc8f165a62768a19de38901d81ac662c51ff29db --- /dev/null +++ b/node_modules/micromark-util-subtokenize/license @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) Titus Wormer + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/micromark-util-subtokenize/package.json b/node_modules/micromark-util-subtokenize/package.json new file mode 100644 index 0000000000000000000000000000000000000000..e085c487407426447605845092a1eb7a8158fc2d --- /dev/null +++ b/node_modules/micromark-util-subtokenize/package.json @@ -0,0 +1,60 @@ +{ + "name": "micromark-util-subtokenize", + "version": "2.1.0", + "description": "micromark utility to tokenize subtokens", + "license": "MIT", + "keywords": [ + "micromark", + "util", + "utility", + "tokenize" + ], + "repository": "https://github.com/micromark/micromark/tree/main/packages/micromark-util-subtokenize", + "bugs": "https://github.com/micromark/micromark/issues", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "author": "Titus Wormer (https://wooorm.com)", + "contributors": [ + "Titus Wormer (https://wooorm.com)" + ], + "sideEffects": false, + "type": "module", + "files": [ + "dev/", + "lib/", + "index.d.ts.map", + "index.d.ts", + "index.js" + ], + "exports": { + "development": "./dev/index.js", + "default": "./index.js" + }, + "dependencies": { + "devlop": "^1.0.0", + "micromark-util-chunked": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + }, + "scripts": { + "build": "micromark-build" + }, + "xo": { + "envs": [ + "shared-node-browser" + ], + "prettier": true, + "rules": { + "max-depth": "off", + "unicorn/prefer-code-point": "off" + } + } +} diff --git a/node_modules/micromark-util-subtokenize/readme.md b/node_modules/micromark-util-subtokenize/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..75cf59c1343cc0bf906e29014f01fd7992c43604 --- /dev/null +++ b/node_modules/micromark-util-subtokenize/readme.md @@ -0,0 +1,181 @@ +# micromark-util-subtokenize + +[![Build][build-badge]][build] +[![Coverage][coverage-badge]][coverage] +[![Downloads][downloads-badge]][downloads] +[![Size][bundle-size-badge]][bundle-size] +[![Sponsors][sponsors-badge]][opencollective] +[![Backers][backers-badge]][opencollective] +[![Chat][chat-badge]][chat] + +[micromark][] utility to tokenize subtokens. + +## Contents + +* [What is this?](#what-is-this) +* [When should I use this?](#when-should-i-use-this) +* [Install](#install) +* [Use](#use) +* [API](#api) + * [`subtokenize(events)`](#subtokenizeevents) +* [Types](#types) +* [Compatibility](#compatibility) +* [Security](#security) +* [Contribute](#contribute) +* [License](#license) + +## What is this? + +This package exposes a micromark internal that you probably don’t need. + +## When should I use this? + +This package might be useful when you are making your own micromark extensions. + +## Install + +This package is [ESM only][esm]. +In Node.js (version 16+), install with [npm][]: + +```sh +npm install micromark-util-subtokenize +``` + +In Deno with [`esm.sh`][esmsh]: + +```js +import {subtokenize} from 'https://esm.sh/micromark-util-subtokenize@1' +``` + +In browsers with [`esm.sh`][esmsh]: + +```html + +``` + +## Use + +```js +import {subtokenize} from 'micromark-util-subtokenize' + +/** + * Content is transparent: it’s parsed right now. That way, definitions are also + * parsed right now: before text in paragraphs (specifically, media) are parsed. + * + * @type {Resolver} + */ +function resolveContent(events) { + subtokenize(events) + return events +} +``` + +## API + +This module exports the identifiers [`subtokenize`][api-subtokenize]. +There is no default export. + +### `subtokenize(events)` + +Tokenize subcontent. + +###### Parameters + +* `events` (`Array`) + — list of events + +###### Returns + +Whether subtokens were found (`boolean`). + +## Types + +This package is fully typed with [TypeScript][]. +It exports no additional types. + +## Compatibility + +Projects maintained by the unified collective are compatible with maintained +versions of Node.js. + +When we cut a new major release, we drop support for unmaintained versions of +Node. +This means we try to keep the current release line, +`micromark-util-subtokenize@2`, compatible with Node.js 16. +This package works with `micromark@3`. + +## Security + +This package is safe. +See [`security.md`][securitymd] in [`micromark/.github`][health] for how to +submit a security report. + +## Contribute + +See [`contributing.md`][contributing] in [`micromark/.github`][health] for ways +to get started. +See [`support.md`][support] for ways to get help. + +This project has a [code of conduct][coc]. +By interacting with this repository, organisation, or community you agree to +abide by its terms. + +## License + +[MIT][license] © [Titus Wormer][author] + + + +[api-subtokenize]: #subtokenizeevents + +[author]: https://wooorm.com + +[backers-badge]: https://opencollective.com/unified/backers/badge.svg + +[build]: https://github.com/micromark/micromark/actions + +[build-badge]: https://github.com/micromark/micromark/workflows/main/badge.svg + +[bundle-size]: https://bundlejs.com/?q=micromark-util-subtokenize + +[bundle-size-badge]: https://img.shields.io/badge/dynamic/json?label=minzipped%20size&query=$.size.compressedSize&url=https://deno.bundlejs.com/?q=micromark-util-subtokenize + +[chat]: https://github.com/micromark/micromark/discussions + +[chat-badge]: https://img.shields.io/badge/chat-discussions-success.svg + +[coc]: https://github.com/micromark/.github/blob/main/code-of-conduct.md + +[contributing]: https://github.com/micromark/.github/blob/main/contributing.md + +[coverage]: https://codecov.io/github/micromark/micromark + +[coverage-badge]: https://img.shields.io/codecov/c/github/micromark/micromark.svg + +[downloads]: https://www.npmjs.com/package/micromark-util-subtokenize + +[downloads-badge]: https://img.shields.io/npm/dm/micromark-util-subtokenize.svg + +[esm]: https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c + +[esmsh]: https://esm.sh + +[health]: https://github.com/micromark/.github + +[license]: https://github.com/micromark/micromark/blob/main/license + +[micromark]: https://github.com/micromark/micromark + +[npm]: https://docs.npmjs.com/cli/install + +[opencollective]: https://opencollective.com/unified + +[securitymd]: https://github.com/micromark/.github/blob/main/security.md + +[sponsors-badge]: https://opencollective.com/unified/sponsors/badge.svg + +[support]: https://github.com/micromark/.github/blob/main/support.md + +[typescript]: https://www.typescriptlang.org diff --git a/node_modules/micromark-util-symbol/lib/codes.d.ts b/node_modules/micromark-util-symbol/lib/codes.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..879770a4b6de8d0df7ec99bb3a92d821ff9a7995 --- /dev/null +++ b/node_modules/micromark-util-symbol/lib/codes.d.ts @@ -0,0 +1,139 @@ +export namespace codes { + let carriageReturn: -5; + let lineFeed: -4; + let carriageReturnLineFeed: -3; + let horizontalTab: -2; + let virtualSpace: -1; + let eof: null; + let nul: 0; + let soh: 1; + let stx: 2; + let etx: 3; + let eot: 4; + let enq: 5; + let ack: 6; + let bel: 7; + let bs: 8; + let ht: 9; + let lf: 10; + let vt: 11; + let ff: 12; + let cr: 13; + let so: 14; + let si: 15; + let dle: 16; + let dc1: 17; + let dc2: 18; + let dc3: 19; + let dc4: 20; + let nak: 21; + let syn: 22; + let etb: 23; + let can: 24; + let em: 25; + let sub: 26; + let esc: 27; + let fs: 28; + let gs: 29; + let rs: 30; + let us: 31; + let space: 32; + let exclamationMark: 33; + let quotationMark: 34; + let numberSign: 35; + let dollarSign: 36; + let percentSign: 37; + let ampersand: 38; + let apostrophe: 39; + let leftParenthesis: 40; + let rightParenthesis: 41; + let asterisk: 42; + let plusSign: 43; + let comma: 44; + let dash: 45; + let dot: 46; + let slash: 47; + let digit0: 48; + let digit1: 49; + let digit2: 50; + let digit3: 51; + let digit4: 52; + let digit5: 53; + let digit6: 54; + let digit7: 55; + let digit8: 56; + let digit9: 57; + let colon: 58; + let semicolon: 59; + let lessThan: 60; + let equalsTo: 61; + let greaterThan: 62; + let questionMark: 63; + let atSign: 64; + let uppercaseA: 65; + let uppercaseB: 66; + let uppercaseC: 67; + let uppercaseD: 68; + let uppercaseE: 69; + let uppercaseF: 70; + let uppercaseG: 71; + let uppercaseH: 72; + let uppercaseI: 73; + let uppercaseJ: 74; + let uppercaseK: 75; + let uppercaseL: 76; + let uppercaseM: 77; + let uppercaseN: 78; + let uppercaseO: 79; + let uppercaseP: 80; + let uppercaseQ: 81; + let uppercaseR: 82; + let uppercaseS: 83; + let uppercaseT: 84; + let uppercaseU: 85; + let uppercaseV: 86; + let uppercaseW: 87; + let uppercaseX: 88; + let uppercaseY: 89; + let uppercaseZ: 90; + let leftSquareBracket: 91; + let backslash: 92; + let rightSquareBracket: 93; + let caret: 94; + let underscore: 95; + let graveAccent: 96; + let lowercaseA: 97; + let lowercaseB: 98; + let lowercaseC: 99; + let lowercaseD: 100; + let lowercaseE: 101; + let lowercaseF: 102; + let lowercaseG: 103; + let lowercaseH: 104; + let lowercaseI: 105; + let lowercaseJ: 106; + let lowercaseK: 107; + let lowercaseL: 108; + let lowercaseM: 109; + let lowercaseN: 110; + let lowercaseO: 111; + let lowercaseP: 112; + let lowercaseQ: 113; + let lowercaseR: 114; + let lowercaseS: 115; + let lowercaseT: 116; + let lowercaseU: 117; + let lowercaseV: 118; + let lowercaseW: 119; + let lowercaseX: 120; + let lowercaseY: 121; + let lowercaseZ: 122; + let leftCurlyBrace: 123; + let verticalBar: 124; + let rightCurlyBrace: 125; + let tilde: 126; + let del: 127; + let byteOrderMarker: 65279; + let replacementCharacter: 65533; +} +//# sourceMappingURL=codes.d.ts.map \ No newline at end of file diff --git a/node_modules/micromark-util-symbol/lib/codes.d.ts.map b/node_modules/micromark-util-symbol/lib/codes.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..e45ee7b15623f5d5d366ce7a959c10115addb043 --- /dev/null +++ b/node_modules/micromark-util-symbol/lib/codes.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"codes.d.ts","sourceRoot":"","sources":["codes.js"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/micromark-util-symbol/lib/codes.js b/node_modules/micromark-util-symbol/lib/codes.js new file mode 100644 index 0000000000000000000000000000000000000000..62fbfd71a399f1a5f03eceab3047730dadbed03e --- /dev/null +++ b/node_modules/micromark-util-symbol/lib/codes.js @@ -0,0 +1,158 @@ +/** + * Character codes. + * + * This module is compiled away! + * + * micromark works based on character codes. + * This module contains constants for the ASCII block and the replacement + * character. + * A couple of them are handled in a special way, such as the line endings + * (CR, LF, and CR+LF, commonly known as end-of-line: EOLs), the tab (horizontal + * tab) and its expansion based on what column it’s at (virtual space), + * and the end-of-file (eof) character. + * As values are preprocessed before handling them, the actual characters LF, + * CR, HT, and NUL (which is present as the replacement character), are + * guaranteed to not exist. + * + * Unicode basic latin block. + */ +export const codes = /** @type {const} */ ({ + carriageReturn: -5, + lineFeed: -4, + carriageReturnLineFeed: -3, + horizontalTab: -2, + virtualSpace: -1, + eof: null, + nul: 0, + soh: 1, + stx: 2, + etx: 3, + eot: 4, + enq: 5, + ack: 6, + bel: 7, + bs: 8, + ht: 9, // `\t` + lf: 10, // `\n` + vt: 11, // `\v` + ff: 12, // `\f` + cr: 13, // `\r` + so: 14, + si: 15, + dle: 16, + dc1: 17, + dc2: 18, + dc3: 19, + dc4: 20, + nak: 21, + syn: 22, + etb: 23, + can: 24, + em: 25, + sub: 26, + esc: 27, + fs: 28, + gs: 29, + rs: 30, + us: 31, + space: 32, + exclamationMark: 33, // `!` + quotationMark: 34, // `"` + numberSign: 35, // `#` + dollarSign: 36, // `$` + percentSign: 37, // `%` + ampersand: 38, // `&` + apostrophe: 39, // `'` + leftParenthesis: 40, // `(` + rightParenthesis: 41, // `)` + asterisk: 42, // `*` + plusSign: 43, // `+` + comma: 44, // `,` + dash: 45, // `-` + dot: 46, // `.` + slash: 47, // `/` + digit0: 48, // `0` + digit1: 49, // `1` + digit2: 50, // `2` + digit3: 51, // `3` + digit4: 52, // `4` + digit5: 53, // `5` + digit6: 54, // `6` + digit7: 55, // `7` + digit8: 56, // `8` + digit9: 57, // `9` + colon: 58, // `:` + semicolon: 59, // `;` + lessThan: 60, // `<` + equalsTo: 61, // `=` + greaterThan: 62, // `>` + questionMark: 63, // `?` + atSign: 64, // `@` + uppercaseA: 65, // `A` + uppercaseB: 66, // `B` + uppercaseC: 67, // `C` + uppercaseD: 68, // `D` + uppercaseE: 69, // `E` + uppercaseF: 70, // `F` + uppercaseG: 71, // `G` + uppercaseH: 72, // `H` + uppercaseI: 73, // `I` + uppercaseJ: 74, // `J` + uppercaseK: 75, // `K` + uppercaseL: 76, // `L` + uppercaseM: 77, // `M` + uppercaseN: 78, // `N` + uppercaseO: 79, // `O` + uppercaseP: 80, // `P` + uppercaseQ: 81, // `Q` + uppercaseR: 82, // `R` + uppercaseS: 83, // `S` + uppercaseT: 84, // `T` + uppercaseU: 85, // `U` + uppercaseV: 86, // `V` + uppercaseW: 87, // `W` + uppercaseX: 88, // `X` + uppercaseY: 89, // `Y` + uppercaseZ: 90, // `Z` + leftSquareBracket: 91, // `[` + backslash: 92, // `\` + rightSquareBracket: 93, // `]` + caret: 94, // `^` + underscore: 95, // `_` + graveAccent: 96, // `` ` `` + lowercaseA: 97, // `a` + lowercaseB: 98, // `b` + lowercaseC: 99, // `c` + lowercaseD: 100, // `d` + lowercaseE: 101, // `e` + lowercaseF: 102, // `f` + lowercaseG: 103, // `g` + lowercaseH: 104, // `h` + lowercaseI: 105, // `i` + lowercaseJ: 106, // `j` + lowercaseK: 107, // `k` + lowercaseL: 108, // `l` + lowercaseM: 109, // `m` + lowercaseN: 110, // `n` + lowercaseO: 111, // `o` + lowercaseP: 112, // `p` + lowercaseQ: 113, // `q` + lowercaseR: 114, // `r` + lowercaseS: 115, // `s` + lowercaseT: 116, // `t` + lowercaseU: 117, // `u` + lowercaseV: 118, // `v` + lowercaseW: 119, // `w` + lowercaseX: 120, // `x` + lowercaseY: 121, // `y` + lowercaseZ: 122, // `z` + leftCurlyBrace: 123, // `{` + verticalBar: 124, // `|` + rightCurlyBrace: 125, // `}` + tilde: 126, // `~` + del: 127, + // Unicode Specials block. + byteOrderMarker: 65_279, + // Unicode Specials block. + replacementCharacter: 65_533 // `�` +}) diff --git a/node_modules/micromark-util-symbol/lib/constants.d.ts b/node_modules/micromark-util-symbol/lib/constants.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f445b69e4b35b6977b6eb9b3faea39f9a1815b04 --- /dev/null +++ b/node_modules/micromark-util-symbol/lib/constants.d.ts @@ -0,0 +1,37 @@ +export namespace constants { + let attentionSideAfter: 2; + let attentionSideBefore: 1; + let atxHeadingOpeningFenceSizeMax: 6; + let autolinkDomainSizeMax: 63; + let autolinkSchemeSizeMax: 32; + let cdataOpeningString: "CDATA["; + let characterGroupPunctuation: 2; + let characterGroupWhitespace: 1; + let characterReferenceDecimalSizeMax: 7; + let characterReferenceHexadecimalSizeMax: 6; + let characterReferenceNamedSizeMax: 31; + let codeFencedSequenceSizeMin: 3; + let contentTypeContent: "content"; + let contentTypeDocument: "document"; + let contentTypeFlow: "flow"; + let contentTypeString: "string"; + let contentTypeText: "text"; + let hardBreakPrefixSizeMin: 2; + let htmlBasic: 6; + let htmlCdata: 5; + let htmlComment: 2; + let htmlComplete: 7; + let htmlDeclaration: 4; + let htmlInstruction: 3; + let htmlRawSizeMax: 8; + let htmlRaw: 1; + let linkResourceDestinationBalanceMax: 32; + let linkReferenceSizeMax: 999; + let listItemValueSizeMax: 10; + let numericBaseDecimal: 10; + let numericBaseHexadecimal: 16; + let tabSize: 4; + let thematicBreakMarkerCountMin: 3; + let v8MaxSafeChunkSize: 10000; +} +//# sourceMappingURL=constants.d.ts.map \ No newline at end of file diff --git a/node_modules/micromark-util-symbol/lib/constants.d.ts.map b/node_modules/micromark-util-symbol/lib/constants.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..633429e678c2e3b17e67bdf0c744ea1ac4c5227b --- /dev/null +++ b/node_modules/micromark-util-symbol/lib/constants.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["constants.js"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/micromark-util-symbol/lib/constants.js b/node_modules/micromark-util-symbol/lib/constants.js new file mode 100644 index 0000000000000000000000000000000000000000..bbd487d26e3cd27929321c467ffb43ba810db0fd --- /dev/null +++ b/node_modules/micromark-util-symbol/lib/constants.js @@ -0,0 +1,44 @@ +/** + * This module is compiled away! + * + * Parsing markdown comes with a couple of constants, such as minimum or maximum + * sizes of certain sequences. + * Additionally, there are a couple symbols used inside micromark. + * These are all defined here, but compiled away by scripts. + */ +export const constants = /** @type {const} */ ({ + attentionSideAfter: 2, // Symbol to mark an attention sequence as after content: `a*` + attentionSideBefore: 1, // Symbol to mark an attention sequence as before content: `*a` + atxHeadingOpeningFenceSizeMax: 6, // 6 number signs is fine, 7 isn’t. + autolinkDomainSizeMax: 63, // 63 characters is fine, 64 is too many. + autolinkSchemeSizeMax: 32, // 32 characters is fine, 33 is too many. + cdataOpeningString: 'CDATA[', // And preceded by `` + htmlComment: 2, // Symbol for `` + htmlComplete: 7, // Symbol for `` + htmlDeclaration: 4, // Symbol for `` + htmlInstruction: 3, // Symbol for `` + htmlRawSizeMax: 8, // Length of `textarea`. + htmlRaw: 1, // Symbol for ` +``` + +## Use + +```js +import {codes, constants, types, values} from 'micromark-util-symbol' + +console.log(codes.atSign) // 64 +console.log(constants.characterReferenceNamedSizeMax) // 31 +console.log(types.definitionDestinationRaw) // 'definitionDestinationRaw' +console.log(values.atSign) // '@' +``` + +## API + +This package exports the identifiers `codes`, `constants`, `types`, and +`values`. +There is no default export. + +Each identifier is an object mapping strings to values. +See the code for the exposed data. + +## Types + +This package is fully typed with [TypeScript][]. +It exports no additional types. + +## Compatibility + +Projects maintained by the unified collective are compatible with maintained +versions of Node.js. + +When we cut a new major release, we drop support for unmaintained versions of +Node. +This means we try to keep the current release line, +`micromark-util-symbol@2`, compatible with Node.js 16. +This package works with `micromark@3`. + +## Security + +This package is safe. +See [`security.md`][securitymd] in [`micromark/.github`][health] for how to +submit a security report. + +## Contribute + +See [`contributing.md`][contributing] in [`micromark/.github`][health] for ways +to get started. +See [`support.md`][support] for ways to get help. + +This project has a [code of conduct][coc]. +By interacting with this repository, organisation, or community you agree to +abide by its terms. + +## License + +[MIT][license] © [Titus Wormer][author] + + + +[build-badge]: https://github.com/micromark/micromark/workflows/main/badge.svg + +[build]: https://github.com/micromark/micromark/actions + +[coverage-badge]: https://img.shields.io/codecov/c/github/micromark/micromark.svg + +[coverage]: https://codecov.io/github/micromark/micromark + +[downloads-badge]: https://img.shields.io/npm/dm/micromark-util-symbol.svg + +[downloads]: https://www.npmjs.com/package/micromark-util-symbol + +[bundle-size-badge]: https://img.shields.io/badge/dynamic/json?label=minzipped%20size&query=$.size.compressedSize&url=https://deno.bundlejs.com/?q=micromark-util-symbol + +[bundle-size]: https://bundlejs.com/?q=micromark-util-symbol + +[sponsors-badge]: https://opencollective.com/unified/sponsors/badge.svg + +[backers-badge]: https://opencollective.com/unified/backers/badge.svg + +[opencollective]: https://opencollective.com/unified + +[npm]: https://docs.npmjs.com/cli/install + +[esm]: https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c + +[esmsh]: https://esm.sh + +[chat-badge]: https://img.shields.io/badge/chat-discussions-success.svg + +[chat]: https://github.com/micromark/micromark/discussions + +[license]: https://github.com/micromark/micromark/blob/main/license + +[author]: https://wooorm.com + +[health]: https://github.com/micromark/.github + +[securitymd]: https://github.com/micromark/.github/blob/main/security.md + +[contributing]: https://github.com/micromark/.github/blob/main/contributing.md + +[support]: https://github.com/micromark/.github/blob/main/support.md + +[coc]: https://github.com/micromark/.github/blob/main/code-of-conduct.md + +[typescript]: https://www.typescriptlang.org + +[micromark]: https://github.com/micromark/micromark + +[micromark-build]: https://github.com/micromark/micromark/tree/main/packages/micromark-build diff --git a/node_modules/micromark-util-types/index.d.ts b/node_modules/micromark-util-types/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a960aff7e2f19a3f51a7627b82082c51e3b20b6b --- /dev/null +++ b/node_modules/micromark-util-types/index.d.ts @@ -0,0 +1,1312 @@ +// Note: this file is authored manually, not generated from `index.js`. + +/** + * A character code. + * + * This is often the same as what `String#charCodeAt()` yields but micromark + * adds meaning to certain other values. + * + * `null` represents the end of the input stream (called eof). + * Negative integers are used instead of certain sequences of characters (such + * as line endings and tabs). + */ +export type Code = number | null + +/** + * A chunk is either a character code or a slice of a buffer in the form of a + * string. + * + * Chunks are used because strings are more efficient storage that character + * codes, but limited in what they can represent. + */ +export type Chunk = Code | string + +/** + * Enumeration of the content types. + * + * Technically `document` is also a content type, which includes containers + * (lists, block quotes) and flow. + * As `ContentType` is used on tokens to define the type of subcontent but + * `document` is the highest level of content, so it’s not listed here. + * + * Containers in markdown come from the margin and include more constructs + * on the lines that define them. + * Take for example a block quote with a paragraph inside it (such as + * `> asd`). + * + * `flow` represents the sections, such as headings, code, and content, which + * is also parsed per line + * An example is HTML, which has a certain starting condition (such as + * ` +``` + +``` +// "lite" version + +``` + +## Quick Start + +For the full version (800+ MIME types, 1,000+ extensions): + +```javascript +const mime = require('mime'); + +mime.getType('txt'); // ⇨ 'text/plain' +mime.getExtension('text/plain'); // ⇨ 'txt' +``` + +See [Mime API](#mime-api) below for API details. + +## Lite Version + +The "lite" version of this module omits vendor-specific (`*/vnd.*`) and +experimental (`*/x-*`) types. It weighs in at ~2.5KB, compared to 8KB for the +full version. To load the lite version: + +```javascript +const mime = require('mime/lite'); +``` + +## Mime .vs. mime-types .vs. mime-db modules + +For those of you wondering about the difference between these [popular] NPM modules, +here's a brief rundown ... + +[`mime-db`](https://github.com/jshttp/mime-db) is "the source of +truth" for MIME type information. It is not an API. Rather, it is a canonical +dataset of mime type definitions pulled from IANA, Apache, NGINX, and custom mappings +submitted by the Node.js community. + +[`mime-types`](https://github.com/jshttp/mime-types) is a thin +wrapper around mime-db that provides an API drop-in compatible(ish) with `mime @ < v1.3.6` API. + +`mime` is, as of v2, a self-contained module bundled with a pre-optimized version +of the `mime-db` dataset. It provides a simplified API with the following characteristics: + +* Intelligently resolved type conflicts (See [mime-score](https://github.com/broofa/mime-score) for details) +* Method naming consistent with industry best-practices +* Compact footprint. E.g. The minified+compressed sizes of the various modules: + +Module | Size +--- | --- +`mime-db` | 18 KB +`mime-types` | same as mime-db +`mime` | 8 KB +`mime/lite` | 2 KB + +## Mime API + +Both `require('mime')` and `require('mime/lite')` return instances of the MIME +class, documented below. + +Note: Inputs to this API are case-insensitive. Outputs (returned values) will +be lowercase. + +### new Mime(typeMap, ... more maps) + +Most users of this module will not need to create Mime instances directly. +However if you would like to create custom mappings, you may do so as follows +... + +```javascript +// Require Mime class +const Mime = require('mime/Mime'); + +// Define mime type -> extensions map +const typeMap = { + 'text/abc': ['abc', 'alpha', 'bet'], + 'text/def': ['leppard'] +}; + +// Create and use Mime instance +const myMime = new Mime(typeMap); +myMime.getType('abc'); // ⇨ 'text/abc' +myMime.getExtension('text/def'); // ⇨ 'leppard' +``` + +If more than one map argument is provided, each map is `define()`ed (see below), in order. + +### mime.getType(pathOrExtension) + +Get mime type for the given path or extension. E.g. + +```javascript +mime.getType('js'); // ⇨ 'application/javascript' +mime.getType('json'); // ⇨ 'application/json' + +mime.getType('txt'); // ⇨ 'text/plain' +mime.getType('dir/text.txt'); // ⇨ 'text/plain' +mime.getType('dir\\text.txt'); // ⇨ 'text/plain' +mime.getType('.text.txt'); // ⇨ 'text/plain' +mime.getType('.txt'); // ⇨ 'text/plain' +``` + +`null` is returned in cases where an extension is not detected or recognized + +```javascript +mime.getType('foo/txt'); // ⇨ null +mime.getType('bogus_type'); // ⇨ null +``` + +### mime.getExtension(type) +Get extension for the given mime type. Charset options (often included in +Content-Type headers) are ignored. + +```javascript +mime.getExtension('text/plain'); // ⇨ 'txt' +mime.getExtension('application/json'); // ⇨ 'json' +mime.getExtension('text/html; charset=utf8'); // ⇨ 'html' +``` + +### mime.define(typeMap[, force = false]) + +Define [more] type mappings. + +`typeMap` is a map of type -> extensions, as documented in `new Mime`, above. + +By default this method will throw an error if you try to map a type to an +extension that is already assigned to another type. Passing `true` for the +`force` argument will suppress this behavior (overriding any previous mapping). + +```javascript +mime.define({'text/x-abc': ['abc', 'abcd']}); + +mime.getType('abcd'); // ⇨ 'text/x-abc' +mime.getExtension('text/x-abc') // ⇨ 'abc' +``` + +## Command Line + + mime [path_or_extension] + +E.g. + + > mime scripts/jquery.js + application/javascript + +---- +Markdown generated from [src/README_js.md](src/README_js.md) by [![RunMD Logo](http://i.imgur.com/h0FVyzU.png)](https://github.com/broofa/runmd) \ No newline at end of file diff --git a/node_modules/mime/cli.js b/node_modules/mime/cli.js new file mode 100644 index 0000000000000000000000000000000000000000..ab70a49c41aeaee64a44a3667094710dbad2efb0 --- /dev/null +++ b/node_modules/mime/cli.js @@ -0,0 +1,46 @@ +#!/usr/bin/env node + +'use strict'; + +process.title = 'mime'; +let mime = require('.'); +let pkg = require('./package.json'); +let args = process.argv.splice(2); + +if (args.includes('--version') || args.includes('-v') || args.includes('--v')) { + console.log(pkg.version); + process.exit(0); +} else if (args.includes('--name') || args.includes('-n') || args.includes('--n')) { + console.log(pkg.name); + process.exit(0); +} else if (args.includes('--help') || args.includes('-h') || args.includes('--h')) { + console.log(pkg.name + ' - ' + pkg.description + '\n'); + console.log(`Usage: + + mime [flags] [path_or_extension] + + Flags: + --help, -h Show this message + --version, -v Display the version + --name, -n Print the name of the program + + Note: the command will exit after it executes if a command is specified + The path_or_extension is the path to the file or the extension of the file. + + Examples: + mime --help + mime --version + mime --name + mime -v + mime src/log.js + mime new.py + mime foo.sh + `); + process.exit(0); +} + +let file = args[0]; +let type = mime.getType(file); + +process.stdout.write(type + '\n'); + diff --git a/node_modules/mime/index.js b/node_modules/mime/index.js new file mode 100644 index 0000000000000000000000000000000000000000..fadcf8d63cb0b5715ba96973aff5e610d7dd8e43 --- /dev/null +++ b/node_modules/mime/index.js @@ -0,0 +1,4 @@ +'use strict'; + +let Mime = require('./Mime'); +module.exports = new Mime(require('./types/standard'), require('./types/other')); diff --git a/node_modules/mime/lite.js b/node_modules/mime/lite.js new file mode 100644 index 0000000000000000000000000000000000000000..835cffb306af16997634451de30b4fc2c08bca76 --- /dev/null +++ b/node_modules/mime/lite.js @@ -0,0 +1,4 @@ +'use strict'; + +let Mime = require('./Mime'); +module.exports = new Mime(require('./types/standard')); diff --git a/node_modules/mime/package.json b/node_modules/mime/package.json new file mode 100644 index 0000000000000000000000000000000000000000..84f513239acaeb5ded08858675fd5d32f8fb60b8 --- /dev/null +++ b/node_modules/mime/package.json @@ -0,0 +1,52 @@ +{ + "author": { + "name": "Robert Kieffer", + "url": "http://github.com/broofa", + "email": "robert@broofa.com" + }, + "engines": { + "node": ">=10.0.0" + }, + "bin": { + "mime": "cli.js" + }, + "contributors": [], + "description": "A comprehensive library for mime-type mapping", + "license": "MIT", + "dependencies": {}, + "devDependencies": { + "benchmark": "*", + "chalk": "4.1.2", + "eslint": "8.1.0", + "mime-db": "1.50.0", + "mime-score": "1.2.0", + "mime-types": "2.1.33", + "mocha": "9.1.3", + "runmd": "*", + "standard-version": "9.3.2" + }, + "files": [ + "index.js", + "lite.js", + "Mime.js", + "cli.js", + "/types" + ], + "scripts": { + "prepare": "node src/build.js && runmd --output README.md src/README_js.md", + "release": "standard-version", + "benchmark": "node src/benchmark.js", + "md": "runmd --watch --output README.md src/README_js.md", + "test": "mocha src/test.js" + }, + "keywords": [ + "util", + "mime" + ], + "name": "mime", + "repository": { + "url": "https://github.com/broofa/mime", + "type": "git" + }, + "version": "3.0.0" +} diff --git a/node_modules/mime/types/other.js b/node_modules/mime/types/other.js new file mode 100644 index 0000000000000000000000000000000000000000..bb6a03533836c9943d4a438968316ed733b0a43c --- /dev/null +++ b/node_modules/mime/types/other.js @@ -0,0 +1 @@ +module.exports = {"application/prs.cww":["cww"],"application/vnd.1000minds.decision-model+xml":["1km"],"application/vnd.3gpp.pic-bw-large":["plb"],"application/vnd.3gpp.pic-bw-small":["psb"],"application/vnd.3gpp.pic-bw-var":["pvb"],"application/vnd.3gpp2.tcap":["tcap"],"application/vnd.3m.post-it-notes":["pwn"],"application/vnd.accpac.simply.aso":["aso"],"application/vnd.accpac.simply.imp":["imp"],"application/vnd.acucobol":["acu"],"application/vnd.acucorp":["atc","acutc"],"application/vnd.adobe.air-application-installer-package+zip":["air"],"application/vnd.adobe.formscentral.fcdt":["fcdt"],"application/vnd.adobe.fxp":["fxp","fxpl"],"application/vnd.adobe.xdp+xml":["xdp"],"application/vnd.adobe.xfdf":["xfdf"],"application/vnd.ahead.space":["ahead"],"application/vnd.airzip.filesecure.azf":["azf"],"application/vnd.airzip.filesecure.azs":["azs"],"application/vnd.amazon.ebook":["azw"],"application/vnd.americandynamics.acc":["acc"],"application/vnd.amiga.ami":["ami"],"application/vnd.android.package-archive":["apk"],"application/vnd.anser-web-certificate-issue-initiation":["cii"],"application/vnd.anser-web-funds-transfer-initiation":["fti"],"application/vnd.antix.game-component":["atx"],"application/vnd.apple.installer+xml":["mpkg"],"application/vnd.apple.keynote":["key"],"application/vnd.apple.mpegurl":["m3u8"],"application/vnd.apple.numbers":["numbers"],"application/vnd.apple.pages":["pages"],"application/vnd.apple.pkpass":["pkpass"],"application/vnd.aristanetworks.swi":["swi"],"application/vnd.astraea-software.iota":["iota"],"application/vnd.audiograph":["aep"],"application/vnd.balsamiq.bmml+xml":["bmml"],"application/vnd.blueice.multipass":["mpm"],"application/vnd.bmi":["bmi"],"application/vnd.businessobjects":["rep"],"application/vnd.chemdraw+xml":["cdxml"],"application/vnd.chipnuts.karaoke-mmd":["mmd"],"application/vnd.cinderella":["cdy"],"application/vnd.citationstyles.style+xml":["csl"],"application/vnd.claymore":["cla"],"application/vnd.cloanto.rp9":["rp9"],"application/vnd.clonk.c4group":["c4g","c4d","c4f","c4p","c4u"],"application/vnd.cluetrust.cartomobile-config":["c11amc"],"application/vnd.cluetrust.cartomobile-config-pkg":["c11amz"],"application/vnd.commonspace":["csp"],"application/vnd.contact.cmsg":["cdbcmsg"],"application/vnd.cosmocaller":["cmc"],"application/vnd.crick.clicker":["clkx"],"application/vnd.crick.clicker.keyboard":["clkk"],"application/vnd.crick.clicker.palette":["clkp"],"application/vnd.crick.clicker.template":["clkt"],"application/vnd.crick.clicker.wordbank":["clkw"],"application/vnd.criticaltools.wbs+xml":["wbs"],"application/vnd.ctc-posml":["pml"],"application/vnd.cups-ppd":["ppd"],"application/vnd.curl.car":["car"],"application/vnd.curl.pcurl":["pcurl"],"application/vnd.dart":["dart"],"application/vnd.data-vision.rdz":["rdz"],"application/vnd.dbf":["dbf"],"application/vnd.dece.data":["uvf","uvvf","uvd","uvvd"],"application/vnd.dece.ttml+xml":["uvt","uvvt"],"application/vnd.dece.unspecified":["uvx","uvvx"],"application/vnd.dece.zip":["uvz","uvvz"],"application/vnd.denovo.fcselayout-link":["fe_launch"],"application/vnd.dna":["dna"],"application/vnd.dolby.mlp":["mlp"],"application/vnd.dpgraph":["dpg"],"application/vnd.dreamfactory":["dfac"],"application/vnd.ds-keypoint":["kpxx"],"application/vnd.dvb.ait":["ait"],"application/vnd.dvb.service":["svc"],"application/vnd.dynageo":["geo"],"application/vnd.ecowin.chart":["mag"],"application/vnd.enliven":["nml"],"application/vnd.epson.esf":["esf"],"application/vnd.epson.msf":["msf"],"application/vnd.epson.quickanime":["qam"],"application/vnd.epson.salt":["slt"],"application/vnd.epson.ssf":["ssf"],"application/vnd.eszigno3+xml":["es3","et3"],"application/vnd.ezpix-album":["ez2"],"application/vnd.ezpix-package":["ez3"],"application/vnd.fdf":["fdf"],"application/vnd.fdsn.mseed":["mseed"],"application/vnd.fdsn.seed":["seed","dataless"],"application/vnd.flographit":["gph"],"application/vnd.fluxtime.clip":["ftc"],"application/vnd.framemaker":["fm","frame","maker","book"],"application/vnd.frogans.fnc":["fnc"],"application/vnd.frogans.ltf":["ltf"],"application/vnd.fsc.weblaunch":["fsc"],"application/vnd.fujitsu.oasys":["oas"],"application/vnd.fujitsu.oasys2":["oa2"],"application/vnd.fujitsu.oasys3":["oa3"],"application/vnd.fujitsu.oasysgp":["fg5"],"application/vnd.fujitsu.oasysprs":["bh2"],"application/vnd.fujixerox.ddd":["ddd"],"application/vnd.fujixerox.docuworks":["xdw"],"application/vnd.fujixerox.docuworks.binder":["xbd"],"application/vnd.fuzzysheet":["fzs"],"application/vnd.genomatix.tuxedo":["txd"],"application/vnd.geogebra.file":["ggb"],"application/vnd.geogebra.tool":["ggt"],"application/vnd.geometry-explorer":["gex","gre"],"application/vnd.geonext":["gxt"],"application/vnd.geoplan":["g2w"],"application/vnd.geospace":["g3w"],"application/vnd.gmx":["gmx"],"application/vnd.google-apps.document":["gdoc"],"application/vnd.google-apps.presentation":["gslides"],"application/vnd.google-apps.spreadsheet":["gsheet"],"application/vnd.google-earth.kml+xml":["kml"],"application/vnd.google-earth.kmz":["kmz"],"application/vnd.grafeq":["gqf","gqs"],"application/vnd.groove-account":["gac"],"application/vnd.groove-help":["ghf"],"application/vnd.groove-identity-message":["gim"],"application/vnd.groove-injector":["grv"],"application/vnd.groove-tool-message":["gtm"],"application/vnd.groove-tool-template":["tpl"],"application/vnd.groove-vcard":["vcg"],"application/vnd.hal+xml":["hal"],"application/vnd.handheld-entertainment+xml":["zmm"],"application/vnd.hbci":["hbci"],"application/vnd.hhe.lesson-player":["les"],"application/vnd.hp-hpgl":["hpgl"],"application/vnd.hp-hpid":["hpid"],"application/vnd.hp-hps":["hps"],"application/vnd.hp-jlyt":["jlt"],"application/vnd.hp-pcl":["pcl"],"application/vnd.hp-pclxl":["pclxl"],"application/vnd.hydrostatix.sof-data":["sfd-hdstx"],"application/vnd.ibm.minipay":["mpy"],"application/vnd.ibm.modcap":["afp","listafp","list3820"],"application/vnd.ibm.rights-management":["irm"],"application/vnd.ibm.secure-container":["sc"],"application/vnd.iccprofile":["icc","icm"],"application/vnd.igloader":["igl"],"application/vnd.immervision-ivp":["ivp"],"application/vnd.immervision-ivu":["ivu"],"application/vnd.insors.igm":["igm"],"application/vnd.intercon.formnet":["xpw","xpx"],"application/vnd.intergeo":["i2g"],"application/vnd.intu.qbo":["qbo"],"application/vnd.intu.qfx":["qfx"],"application/vnd.ipunplugged.rcprofile":["rcprofile"],"application/vnd.irepository.package+xml":["irp"],"application/vnd.is-xpr":["xpr"],"application/vnd.isac.fcs":["fcs"],"application/vnd.jam":["jam"],"application/vnd.jcp.javame.midlet-rms":["rms"],"application/vnd.jisp":["jisp"],"application/vnd.joost.joda-archive":["joda"],"application/vnd.kahootz":["ktz","ktr"],"application/vnd.kde.karbon":["karbon"],"application/vnd.kde.kchart":["chrt"],"application/vnd.kde.kformula":["kfo"],"application/vnd.kde.kivio":["flw"],"application/vnd.kde.kontour":["kon"],"application/vnd.kde.kpresenter":["kpr","kpt"],"application/vnd.kde.kspread":["ksp"],"application/vnd.kde.kword":["kwd","kwt"],"application/vnd.kenameaapp":["htke"],"application/vnd.kidspiration":["kia"],"application/vnd.kinar":["kne","knp"],"application/vnd.koan":["skp","skd","skt","skm"],"application/vnd.kodak-descriptor":["sse"],"application/vnd.las.las+xml":["lasxml"],"application/vnd.llamagraphics.life-balance.desktop":["lbd"],"application/vnd.llamagraphics.life-balance.exchange+xml":["lbe"],"application/vnd.lotus-1-2-3":["123"],"application/vnd.lotus-approach":["apr"],"application/vnd.lotus-freelance":["pre"],"application/vnd.lotus-notes":["nsf"],"application/vnd.lotus-organizer":["org"],"application/vnd.lotus-screencam":["scm"],"application/vnd.lotus-wordpro":["lwp"],"application/vnd.macports.portpkg":["portpkg"],"application/vnd.mapbox-vector-tile":["mvt"],"application/vnd.mcd":["mcd"],"application/vnd.medcalcdata":["mc1"],"application/vnd.mediastation.cdkey":["cdkey"],"application/vnd.mfer":["mwf"],"application/vnd.mfmp":["mfm"],"application/vnd.micrografx.flo":["flo"],"application/vnd.micrografx.igx":["igx"],"application/vnd.mif":["mif"],"application/vnd.mobius.daf":["daf"],"application/vnd.mobius.dis":["dis"],"application/vnd.mobius.mbk":["mbk"],"application/vnd.mobius.mqy":["mqy"],"application/vnd.mobius.msl":["msl"],"application/vnd.mobius.plc":["plc"],"application/vnd.mobius.txf":["txf"],"application/vnd.mophun.application":["mpn"],"application/vnd.mophun.certificate":["mpc"],"application/vnd.mozilla.xul+xml":["xul"],"application/vnd.ms-artgalry":["cil"],"application/vnd.ms-cab-compressed":["cab"],"application/vnd.ms-excel":["xls","xlm","xla","xlc","xlt","xlw"],"application/vnd.ms-excel.addin.macroenabled.12":["xlam"],"application/vnd.ms-excel.sheet.binary.macroenabled.12":["xlsb"],"application/vnd.ms-excel.sheet.macroenabled.12":["xlsm"],"application/vnd.ms-excel.template.macroenabled.12":["xltm"],"application/vnd.ms-fontobject":["eot"],"application/vnd.ms-htmlhelp":["chm"],"application/vnd.ms-ims":["ims"],"application/vnd.ms-lrm":["lrm"],"application/vnd.ms-officetheme":["thmx"],"application/vnd.ms-outlook":["msg"],"application/vnd.ms-pki.seccat":["cat"],"application/vnd.ms-pki.stl":["*stl"],"application/vnd.ms-powerpoint":["ppt","pps","pot"],"application/vnd.ms-powerpoint.addin.macroenabled.12":["ppam"],"application/vnd.ms-powerpoint.presentation.macroenabled.12":["pptm"],"application/vnd.ms-powerpoint.slide.macroenabled.12":["sldm"],"application/vnd.ms-powerpoint.slideshow.macroenabled.12":["ppsm"],"application/vnd.ms-powerpoint.template.macroenabled.12":["potm"],"application/vnd.ms-project":["mpp","mpt"],"application/vnd.ms-word.document.macroenabled.12":["docm"],"application/vnd.ms-word.template.macroenabled.12":["dotm"],"application/vnd.ms-works":["wps","wks","wcm","wdb"],"application/vnd.ms-wpl":["wpl"],"application/vnd.ms-xpsdocument":["xps"],"application/vnd.mseq":["mseq"],"application/vnd.musician":["mus"],"application/vnd.muvee.style":["msty"],"application/vnd.mynfc":["taglet"],"application/vnd.neurolanguage.nlu":["nlu"],"application/vnd.nitf":["ntf","nitf"],"application/vnd.noblenet-directory":["nnd"],"application/vnd.noblenet-sealer":["nns"],"application/vnd.noblenet-web":["nnw"],"application/vnd.nokia.n-gage.ac+xml":["*ac"],"application/vnd.nokia.n-gage.data":["ngdat"],"application/vnd.nokia.n-gage.symbian.install":["n-gage"],"application/vnd.nokia.radio-preset":["rpst"],"application/vnd.nokia.radio-presets":["rpss"],"application/vnd.novadigm.edm":["edm"],"application/vnd.novadigm.edx":["edx"],"application/vnd.novadigm.ext":["ext"],"application/vnd.oasis.opendocument.chart":["odc"],"application/vnd.oasis.opendocument.chart-template":["otc"],"application/vnd.oasis.opendocument.database":["odb"],"application/vnd.oasis.opendocument.formula":["odf"],"application/vnd.oasis.opendocument.formula-template":["odft"],"application/vnd.oasis.opendocument.graphics":["odg"],"application/vnd.oasis.opendocument.graphics-template":["otg"],"application/vnd.oasis.opendocument.image":["odi"],"application/vnd.oasis.opendocument.image-template":["oti"],"application/vnd.oasis.opendocument.presentation":["odp"],"application/vnd.oasis.opendocument.presentation-template":["otp"],"application/vnd.oasis.opendocument.spreadsheet":["ods"],"application/vnd.oasis.opendocument.spreadsheet-template":["ots"],"application/vnd.oasis.opendocument.text":["odt"],"application/vnd.oasis.opendocument.text-master":["odm"],"application/vnd.oasis.opendocument.text-template":["ott"],"application/vnd.oasis.opendocument.text-web":["oth"],"application/vnd.olpc-sugar":["xo"],"application/vnd.oma.dd2+xml":["dd2"],"application/vnd.openblox.game+xml":["obgx"],"application/vnd.openofficeorg.extension":["oxt"],"application/vnd.openstreetmap.data+xml":["osm"],"application/vnd.openxmlformats-officedocument.presentationml.presentation":["pptx"],"application/vnd.openxmlformats-officedocument.presentationml.slide":["sldx"],"application/vnd.openxmlformats-officedocument.presentationml.slideshow":["ppsx"],"application/vnd.openxmlformats-officedocument.presentationml.template":["potx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":["xlsx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.template":["xltx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.document":["docx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.template":["dotx"],"application/vnd.osgeo.mapguide.package":["mgp"],"application/vnd.osgi.dp":["dp"],"application/vnd.osgi.subsystem":["esa"],"application/vnd.palm":["pdb","pqa","oprc"],"application/vnd.pawaafile":["paw"],"application/vnd.pg.format":["str"],"application/vnd.pg.osasli":["ei6"],"application/vnd.picsel":["efif"],"application/vnd.pmi.widget":["wg"],"application/vnd.pocketlearn":["plf"],"application/vnd.powerbuilder6":["pbd"],"application/vnd.previewsystems.box":["box"],"application/vnd.proteus.magazine":["mgz"],"application/vnd.publishare-delta-tree":["qps"],"application/vnd.pvi.ptid1":["ptid"],"application/vnd.quark.quarkxpress":["qxd","qxt","qwd","qwt","qxl","qxb"],"application/vnd.rar":["rar"],"application/vnd.realvnc.bed":["bed"],"application/vnd.recordare.musicxml":["mxl"],"application/vnd.recordare.musicxml+xml":["musicxml"],"application/vnd.rig.cryptonote":["cryptonote"],"application/vnd.rim.cod":["cod"],"application/vnd.rn-realmedia":["rm"],"application/vnd.rn-realmedia-vbr":["rmvb"],"application/vnd.route66.link66+xml":["link66"],"application/vnd.sailingtracker.track":["st"],"application/vnd.seemail":["see"],"application/vnd.sema":["sema"],"application/vnd.semd":["semd"],"application/vnd.semf":["semf"],"application/vnd.shana.informed.formdata":["ifm"],"application/vnd.shana.informed.formtemplate":["itp"],"application/vnd.shana.informed.interchange":["iif"],"application/vnd.shana.informed.package":["ipk"],"application/vnd.simtech-mindmapper":["twd","twds"],"application/vnd.smaf":["mmf"],"application/vnd.smart.teacher":["teacher"],"application/vnd.software602.filler.form+xml":["fo"],"application/vnd.solent.sdkm+xml":["sdkm","sdkd"],"application/vnd.spotfire.dxp":["dxp"],"application/vnd.spotfire.sfs":["sfs"],"application/vnd.stardivision.calc":["sdc"],"application/vnd.stardivision.draw":["sda"],"application/vnd.stardivision.impress":["sdd"],"application/vnd.stardivision.math":["smf"],"application/vnd.stardivision.writer":["sdw","vor"],"application/vnd.stardivision.writer-global":["sgl"],"application/vnd.stepmania.package":["smzip"],"application/vnd.stepmania.stepchart":["sm"],"application/vnd.sun.wadl+xml":["wadl"],"application/vnd.sun.xml.calc":["sxc"],"application/vnd.sun.xml.calc.template":["stc"],"application/vnd.sun.xml.draw":["sxd"],"application/vnd.sun.xml.draw.template":["std"],"application/vnd.sun.xml.impress":["sxi"],"application/vnd.sun.xml.impress.template":["sti"],"application/vnd.sun.xml.math":["sxm"],"application/vnd.sun.xml.writer":["sxw"],"application/vnd.sun.xml.writer.global":["sxg"],"application/vnd.sun.xml.writer.template":["stw"],"application/vnd.sus-calendar":["sus","susp"],"application/vnd.svd":["svd"],"application/vnd.symbian.install":["sis","sisx"],"application/vnd.syncml+xml":["xsm"],"application/vnd.syncml.dm+wbxml":["bdm"],"application/vnd.syncml.dm+xml":["xdm"],"application/vnd.syncml.dmddf+xml":["ddf"],"application/vnd.tao.intent-module-archive":["tao"],"application/vnd.tcpdump.pcap":["pcap","cap","dmp"],"application/vnd.tmobile-livetv":["tmo"],"application/vnd.trid.tpt":["tpt"],"application/vnd.triscape.mxs":["mxs"],"application/vnd.trueapp":["tra"],"application/vnd.ufdl":["ufd","ufdl"],"application/vnd.uiq.theme":["utz"],"application/vnd.umajin":["umj"],"application/vnd.unity":["unityweb"],"application/vnd.uoml+xml":["uoml"],"application/vnd.vcx":["vcx"],"application/vnd.visio":["vsd","vst","vss","vsw"],"application/vnd.visionary":["vis"],"application/vnd.vsf":["vsf"],"application/vnd.wap.wbxml":["wbxml"],"application/vnd.wap.wmlc":["wmlc"],"application/vnd.wap.wmlscriptc":["wmlsc"],"application/vnd.webturbo":["wtb"],"application/vnd.wolfram.player":["nbp"],"application/vnd.wordperfect":["wpd"],"application/vnd.wqd":["wqd"],"application/vnd.wt.stf":["stf"],"application/vnd.xara":["xar"],"application/vnd.xfdl":["xfdl"],"application/vnd.yamaha.hv-dic":["hvd"],"application/vnd.yamaha.hv-script":["hvs"],"application/vnd.yamaha.hv-voice":["hvp"],"application/vnd.yamaha.openscoreformat":["osf"],"application/vnd.yamaha.openscoreformat.osfpvg+xml":["osfpvg"],"application/vnd.yamaha.smaf-audio":["saf"],"application/vnd.yamaha.smaf-phrase":["spf"],"application/vnd.yellowriver-custom-menu":["cmp"],"application/vnd.zul":["zir","zirz"],"application/vnd.zzazz.deck+xml":["zaz"],"application/x-7z-compressed":["7z"],"application/x-abiword":["abw"],"application/x-ace-compressed":["ace"],"application/x-apple-diskimage":["*dmg"],"application/x-arj":["arj"],"application/x-authorware-bin":["aab","x32","u32","vox"],"application/x-authorware-map":["aam"],"application/x-authorware-seg":["aas"],"application/x-bcpio":["bcpio"],"application/x-bdoc":["*bdoc"],"application/x-bittorrent":["torrent"],"application/x-blorb":["blb","blorb"],"application/x-bzip":["bz"],"application/x-bzip2":["bz2","boz"],"application/x-cbr":["cbr","cba","cbt","cbz","cb7"],"application/x-cdlink":["vcd"],"application/x-cfs-compressed":["cfs"],"application/x-chat":["chat"],"application/x-chess-pgn":["pgn"],"application/x-chrome-extension":["crx"],"application/x-cocoa":["cco"],"application/x-conference":["nsc"],"application/x-cpio":["cpio"],"application/x-csh":["csh"],"application/x-debian-package":["*deb","udeb"],"application/x-dgc-compressed":["dgc"],"application/x-director":["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"],"application/x-doom":["wad"],"application/x-dtbncx+xml":["ncx"],"application/x-dtbook+xml":["dtb"],"application/x-dtbresource+xml":["res"],"application/x-dvi":["dvi"],"application/x-envoy":["evy"],"application/x-eva":["eva"],"application/x-font-bdf":["bdf"],"application/x-font-ghostscript":["gsf"],"application/x-font-linux-psf":["psf"],"application/x-font-pcf":["pcf"],"application/x-font-snf":["snf"],"application/x-font-type1":["pfa","pfb","pfm","afm"],"application/x-freearc":["arc"],"application/x-futuresplash":["spl"],"application/x-gca-compressed":["gca"],"application/x-glulx":["ulx"],"application/x-gnumeric":["gnumeric"],"application/x-gramps-xml":["gramps"],"application/x-gtar":["gtar"],"application/x-hdf":["hdf"],"application/x-httpd-php":["php"],"application/x-install-instructions":["install"],"application/x-iso9660-image":["*iso"],"application/x-iwork-keynote-sffkey":["*key"],"application/x-iwork-numbers-sffnumbers":["*numbers"],"application/x-iwork-pages-sffpages":["*pages"],"application/x-java-archive-diff":["jardiff"],"application/x-java-jnlp-file":["jnlp"],"application/x-keepass2":["kdbx"],"application/x-latex":["latex"],"application/x-lua-bytecode":["luac"],"application/x-lzh-compressed":["lzh","lha"],"application/x-makeself":["run"],"application/x-mie":["mie"],"application/x-mobipocket-ebook":["prc","mobi"],"application/x-ms-application":["application"],"application/x-ms-shortcut":["lnk"],"application/x-ms-wmd":["wmd"],"application/x-ms-wmz":["wmz"],"application/x-ms-xbap":["xbap"],"application/x-msaccess":["mdb"],"application/x-msbinder":["obd"],"application/x-mscardfile":["crd"],"application/x-msclip":["clp"],"application/x-msdos-program":["*exe"],"application/x-msdownload":["*exe","*dll","com","bat","*msi"],"application/x-msmediaview":["mvb","m13","m14"],"application/x-msmetafile":["*wmf","*wmz","*emf","emz"],"application/x-msmoney":["mny"],"application/x-mspublisher":["pub"],"application/x-msschedule":["scd"],"application/x-msterminal":["trm"],"application/x-mswrite":["wri"],"application/x-netcdf":["nc","cdf"],"application/x-ns-proxy-autoconfig":["pac"],"application/x-nzb":["nzb"],"application/x-perl":["pl","pm"],"application/x-pilot":["*prc","*pdb"],"application/x-pkcs12":["p12","pfx"],"application/x-pkcs7-certificates":["p7b","spc"],"application/x-pkcs7-certreqresp":["p7r"],"application/x-rar-compressed":["*rar"],"application/x-redhat-package-manager":["rpm"],"application/x-research-info-systems":["ris"],"application/x-sea":["sea"],"application/x-sh":["sh"],"application/x-shar":["shar"],"application/x-shockwave-flash":["swf"],"application/x-silverlight-app":["xap"],"application/x-sql":["sql"],"application/x-stuffit":["sit"],"application/x-stuffitx":["sitx"],"application/x-subrip":["srt"],"application/x-sv4cpio":["sv4cpio"],"application/x-sv4crc":["sv4crc"],"application/x-t3vm-image":["t3"],"application/x-tads":["gam"],"application/x-tar":["tar"],"application/x-tcl":["tcl","tk"],"application/x-tex":["tex"],"application/x-tex-tfm":["tfm"],"application/x-texinfo":["texinfo","texi"],"application/x-tgif":["*obj"],"application/x-ustar":["ustar"],"application/x-virtualbox-hdd":["hdd"],"application/x-virtualbox-ova":["ova"],"application/x-virtualbox-ovf":["ovf"],"application/x-virtualbox-vbox":["vbox"],"application/x-virtualbox-vbox-extpack":["vbox-extpack"],"application/x-virtualbox-vdi":["vdi"],"application/x-virtualbox-vhd":["vhd"],"application/x-virtualbox-vmdk":["vmdk"],"application/x-wais-source":["src"],"application/x-web-app-manifest+json":["webapp"],"application/x-x509-ca-cert":["der","crt","pem"],"application/x-xfig":["fig"],"application/x-xliff+xml":["*xlf"],"application/x-xpinstall":["xpi"],"application/x-xz":["xz"],"application/x-zmachine":["z1","z2","z3","z4","z5","z6","z7","z8"],"audio/vnd.dece.audio":["uva","uvva"],"audio/vnd.digital-winds":["eol"],"audio/vnd.dra":["dra"],"audio/vnd.dts":["dts"],"audio/vnd.dts.hd":["dtshd"],"audio/vnd.lucent.voice":["lvp"],"audio/vnd.ms-playready.media.pya":["pya"],"audio/vnd.nuera.ecelp4800":["ecelp4800"],"audio/vnd.nuera.ecelp7470":["ecelp7470"],"audio/vnd.nuera.ecelp9600":["ecelp9600"],"audio/vnd.rip":["rip"],"audio/x-aac":["aac"],"audio/x-aiff":["aif","aiff","aifc"],"audio/x-caf":["caf"],"audio/x-flac":["flac"],"audio/x-m4a":["*m4a"],"audio/x-matroska":["mka"],"audio/x-mpegurl":["m3u"],"audio/x-ms-wax":["wax"],"audio/x-ms-wma":["wma"],"audio/x-pn-realaudio":["ram","ra"],"audio/x-pn-realaudio-plugin":["rmp"],"audio/x-realaudio":["*ra"],"audio/x-wav":["*wav"],"chemical/x-cdx":["cdx"],"chemical/x-cif":["cif"],"chemical/x-cmdf":["cmdf"],"chemical/x-cml":["cml"],"chemical/x-csml":["csml"],"chemical/x-xyz":["xyz"],"image/prs.btif":["btif"],"image/prs.pti":["pti"],"image/vnd.adobe.photoshop":["psd"],"image/vnd.airzip.accelerator.azv":["azv"],"image/vnd.dece.graphic":["uvi","uvvi","uvg","uvvg"],"image/vnd.djvu":["djvu","djv"],"image/vnd.dvb.subtitle":["*sub"],"image/vnd.dwg":["dwg"],"image/vnd.dxf":["dxf"],"image/vnd.fastbidsheet":["fbs"],"image/vnd.fpx":["fpx"],"image/vnd.fst":["fst"],"image/vnd.fujixerox.edmics-mmr":["mmr"],"image/vnd.fujixerox.edmics-rlc":["rlc"],"image/vnd.microsoft.icon":["ico"],"image/vnd.ms-dds":["dds"],"image/vnd.ms-modi":["mdi"],"image/vnd.ms-photo":["wdp"],"image/vnd.net-fpx":["npx"],"image/vnd.pco.b16":["b16"],"image/vnd.tencent.tap":["tap"],"image/vnd.valve.source.texture":["vtf"],"image/vnd.wap.wbmp":["wbmp"],"image/vnd.xiff":["xif"],"image/vnd.zbrush.pcx":["pcx"],"image/x-3ds":["3ds"],"image/x-cmu-raster":["ras"],"image/x-cmx":["cmx"],"image/x-freehand":["fh","fhc","fh4","fh5","fh7"],"image/x-icon":["*ico"],"image/x-jng":["jng"],"image/x-mrsid-image":["sid"],"image/x-ms-bmp":["*bmp"],"image/x-pcx":["*pcx"],"image/x-pict":["pic","pct"],"image/x-portable-anymap":["pnm"],"image/x-portable-bitmap":["pbm"],"image/x-portable-graymap":["pgm"],"image/x-portable-pixmap":["ppm"],"image/x-rgb":["rgb"],"image/x-tga":["tga"],"image/x-xbitmap":["xbm"],"image/x-xpixmap":["xpm"],"image/x-xwindowdump":["xwd"],"message/vnd.wfa.wsc":["wsc"],"model/vnd.collada+xml":["dae"],"model/vnd.dwf":["dwf"],"model/vnd.gdl":["gdl"],"model/vnd.gtw":["gtw"],"model/vnd.mts":["mts"],"model/vnd.opengex":["ogex"],"model/vnd.parasolid.transmit.binary":["x_b"],"model/vnd.parasolid.transmit.text":["x_t"],"model/vnd.sap.vds":["vds"],"model/vnd.usdz+zip":["usdz"],"model/vnd.valve.source.compiled-map":["bsp"],"model/vnd.vtu":["vtu"],"text/prs.lines.tag":["dsc"],"text/vnd.curl":["curl"],"text/vnd.curl.dcurl":["dcurl"],"text/vnd.curl.mcurl":["mcurl"],"text/vnd.curl.scurl":["scurl"],"text/vnd.dvb.subtitle":["sub"],"text/vnd.fly":["fly"],"text/vnd.fmi.flexstor":["flx"],"text/vnd.graphviz":["gv"],"text/vnd.in3d.3dml":["3dml"],"text/vnd.in3d.spot":["spot"],"text/vnd.sun.j2me.app-descriptor":["jad"],"text/vnd.wap.wml":["wml"],"text/vnd.wap.wmlscript":["wmls"],"text/x-asm":["s","asm"],"text/x-c":["c","cc","cxx","cpp","h","hh","dic"],"text/x-component":["htc"],"text/x-fortran":["f","for","f77","f90"],"text/x-handlebars-template":["hbs"],"text/x-java-source":["java"],"text/x-lua":["lua"],"text/x-markdown":["mkd"],"text/x-nfo":["nfo"],"text/x-opml":["opml"],"text/x-org":["*org"],"text/x-pascal":["p","pas"],"text/x-processing":["pde"],"text/x-sass":["sass"],"text/x-scss":["scss"],"text/x-setext":["etx"],"text/x-sfv":["sfv"],"text/x-suse-ymp":["ymp"],"text/x-uuencode":["uu"],"text/x-vcalendar":["vcs"],"text/x-vcard":["vcf"],"video/vnd.dece.hd":["uvh","uvvh"],"video/vnd.dece.mobile":["uvm","uvvm"],"video/vnd.dece.pd":["uvp","uvvp"],"video/vnd.dece.sd":["uvs","uvvs"],"video/vnd.dece.video":["uvv","uvvv"],"video/vnd.dvb.file":["dvb"],"video/vnd.fvt":["fvt"],"video/vnd.mpegurl":["mxu","m4u"],"video/vnd.ms-playready.media.pyv":["pyv"],"video/vnd.uvvu.mp4":["uvu","uvvu"],"video/vnd.vivo":["viv"],"video/x-f4v":["f4v"],"video/x-fli":["fli"],"video/x-flv":["flv"],"video/x-m4v":["m4v"],"video/x-matroska":["mkv","mk3d","mks"],"video/x-mng":["mng"],"video/x-ms-asf":["asf","asx"],"video/x-ms-vob":["vob"],"video/x-ms-wm":["wm"],"video/x-ms-wmv":["wmv"],"video/x-ms-wmx":["wmx"],"video/x-ms-wvx":["wvx"],"video/x-msvideo":["avi"],"video/x-sgi-movie":["movie"],"video/x-smv":["smv"],"x-conference/x-cooltalk":["ice"]}; \ No newline at end of file diff --git a/node_modules/mime/types/standard.js b/node_modules/mime/types/standard.js new file mode 100644 index 0000000000000000000000000000000000000000..5ee9937eb07c761e211ce3e96292f51a6132a3b7 --- /dev/null +++ b/node_modules/mime/types/standard.js @@ -0,0 +1 @@ +module.exports = {"application/andrew-inset":["ez"],"application/applixware":["aw"],"application/atom+xml":["atom"],"application/atomcat+xml":["atomcat"],"application/atomdeleted+xml":["atomdeleted"],"application/atomsvc+xml":["atomsvc"],"application/atsc-dwd+xml":["dwd"],"application/atsc-held+xml":["held"],"application/atsc-rsat+xml":["rsat"],"application/bdoc":["bdoc"],"application/calendar+xml":["xcs"],"application/ccxml+xml":["ccxml"],"application/cdfx+xml":["cdfx"],"application/cdmi-capability":["cdmia"],"application/cdmi-container":["cdmic"],"application/cdmi-domain":["cdmid"],"application/cdmi-object":["cdmio"],"application/cdmi-queue":["cdmiq"],"application/cu-seeme":["cu"],"application/dash+xml":["mpd"],"application/davmount+xml":["davmount"],"application/docbook+xml":["dbk"],"application/dssc+der":["dssc"],"application/dssc+xml":["xdssc"],"application/ecmascript":["es","ecma"],"application/emma+xml":["emma"],"application/emotionml+xml":["emotionml"],"application/epub+zip":["epub"],"application/exi":["exi"],"application/express":["exp"],"application/fdt+xml":["fdt"],"application/font-tdpfr":["pfr"],"application/geo+json":["geojson"],"application/gml+xml":["gml"],"application/gpx+xml":["gpx"],"application/gxf":["gxf"],"application/gzip":["gz"],"application/hjson":["hjson"],"application/hyperstudio":["stk"],"application/inkml+xml":["ink","inkml"],"application/ipfix":["ipfix"],"application/its+xml":["its"],"application/java-archive":["jar","war","ear"],"application/java-serialized-object":["ser"],"application/java-vm":["class"],"application/javascript":["js","mjs"],"application/json":["json","map"],"application/json5":["json5"],"application/jsonml+json":["jsonml"],"application/ld+json":["jsonld"],"application/lgr+xml":["lgr"],"application/lost+xml":["lostxml"],"application/mac-binhex40":["hqx"],"application/mac-compactpro":["cpt"],"application/mads+xml":["mads"],"application/manifest+json":["webmanifest"],"application/marc":["mrc"],"application/marcxml+xml":["mrcx"],"application/mathematica":["ma","nb","mb"],"application/mathml+xml":["mathml"],"application/mbox":["mbox"],"application/mediaservercontrol+xml":["mscml"],"application/metalink+xml":["metalink"],"application/metalink4+xml":["meta4"],"application/mets+xml":["mets"],"application/mmt-aei+xml":["maei"],"application/mmt-usd+xml":["musd"],"application/mods+xml":["mods"],"application/mp21":["m21","mp21"],"application/mp4":["mp4s","m4p"],"application/msword":["doc","dot"],"application/mxf":["mxf"],"application/n-quads":["nq"],"application/n-triples":["nt"],"application/node":["cjs"],"application/octet-stream":["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"],"application/oda":["oda"],"application/oebps-package+xml":["opf"],"application/ogg":["ogx"],"application/omdoc+xml":["omdoc"],"application/onenote":["onetoc","onetoc2","onetmp","onepkg"],"application/oxps":["oxps"],"application/p2p-overlay+xml":["relo"],"application/patch-ops-error+xml":["xer"],"application/pdf":["pdf"],"application/pgp-encrypted":["pgp"],"application/pgp-signature":["asc","sig"],"application/pics-rules":["prf"],"application/pkcs10":["p10"],"application/pkcs7-mime":["p7m","p7c"],"application/pkcs7-signature":["p7s"],"application/pkcs8":["p8"],"application/pkix-attr-cert":["ac"],"application/pkix-cert":["cer"],"application/pkix-crl":["crl"],"application/pkix-pkipath":["pkipath"],"application/pkixcmp":["pki"],"application/pls+xml":["pls"],"application/postscript":["ai","eps","ps"],"application/provenance+xml":["provx"],"application/pskc+xml":["pskcxml"],"application/raml+yaml":["raml"],"application/rdf+xml":["rdf","owl"],"application/reginfo+xml":["rif"],"application/relax-ng-compact-syntax":["rnc"],"application/resource-lists+xml":["rl"],"application/resource-lists-diff+xml":["rld"],"application/rls-services+xml":["rs"],"application/route-apd+xml":["rapd"],"application/route-s-tsid+xml":["sls"],"application/route-usd+xml":["rusd"],"application/rpki-ghostbusters":["gbr"],"application/rpki-manifest":["mft"],"application/rpki-roa":["roa"],"application/rsd+xml":["rsd"],"application/rss+xml":["rss"],"application/rtf":["rtf"],"application/sbml+xml":["sbml"],"application/scvp-cv-request":["scq"],"application/scvp-cv-response":["scs"],"application/scvp-vp-request":["spq"],"application/scvp-vp-response":["spp"],"application/sdp":["sdp"],"application/senml+xml":["senmlx"],"application/sensml+xml":["sensmlx"],"application/set-payment-initiation":["setpay"],"application/set-registration-initiation":["setreg"],"application/shf+xml":["shf"],"application/sieve":["siv","sieve"],"application/smil+xml":["smi","smil"],"application/sparql-query":["rq"],"application/sparql-results+xml":["srx"],"application/srgs":["gram"],"application/srgs+xml":["grxml"],"application/sru+xml":["sru"],"application/ssdl+xml":["ssdl"],"application/ssml+xml":["ssml"],"application/swid+xml":["swidtag"],"application/tei+xml":["tei","teicorpus"],"application/thraud+xml":["tfi"],"application/timestamped-data":["tsd"],"application/toml":["toml"],"application/trig":["trig"],"application/ttml+xml":["ttml"],"application/ubjson":["ubj"],"application/urc-ressheet+xml":["rsheet"],"application/urc-targetdesc+xml":["td"],"application/voicexml+xml":["vxml"],"application/wasm":["wasm"],"application/widget":["wgt"],"application/winhlp":["hlp"],"application/wsdl+xml":["wsdl"],"application/wspolicy+xml":["wspolicy"],"application/xaml+xml":["xaml"],"application/xcap-att+xml":["xav"],"application/xcap-caps+xml":["xca"],"application/xcap-diff+xml":["xdf"],"application/xcap-el+xml":["xel"],"application/xcap-ns+xml":["xns"],"application/xenc+xml":["xenc"],"application/xhtml+xml":["xhtml","xht"],"application/xliff+xml":["xlf"],"application/xml":["xml","xsl","xsd","rng"],"application/xml-dtd":["dtd"],"application/xop+xml":["xop"],"application/xproc+xml":["xpl"],"application/xslt+xml":["*xsl","xslt"],"application/xspf+xml":["xspf"],"application/xv+xml":["mxml","xhvml","xvml","xvm"],"application/yang":["yang"],"application/yin+xml":["yin"],"application/zip":["zip"],"audio/3gpp":["*3gpp"],"audio/adpcm":["adp"],"audio/amr":["amr"],"audio/basic":["au","snd"],"audio/midi":["mid","midi","kar","rmi"],"audio/mobile-xmf":["mxmf"],"audio/mp3":["*mp3"],"audio/mp4":["m4a","mp4a"],"audio/mpeg":["mpga","mp2","mp2a","mp3","m2a","m3a"],"audio/ogg":["oga","ogg","spx","opus"],"audio/s3m":["s3m"],"audio/silk":["sil"],"audio/wav":["wav"],"audio/wave":["*wav"],"audio/webm":["weba"],"audio/xm":["xm"],"font/collection":["ttc"],"font/otf":["otf"],"font/ttf":["ttf"],"font/woff":["woff"],"font/woff2":["woff2"],"image/aces":["exr"],"image/apng":["apng"],"image/avif":["avif"],"image/bmp":["bmp"],"image/cgm":["cgm"],"image/dicom-rle":["drle"],"image/emf":["emf"],"image/fits":["fits"],"image/g3fax":["g3"],"image/gif":["gif"],"image/heic":["heic"],"image/heic-sequence":["heics"],"image/heif":["heif"],"image/heif-sequence":["heifs"],"image/hej2k":["hej2"],"image/hsj2":["hsj2"],"image/ief":["ief"],"image/jls":["jls"],"image/jp2":["jp2","jpg2"],"image/jpeg":["jpeg","jpg","jpe"],"image/jph":["jph"],"image/jphc":["jhc"],"image/jpm":["jpm"],"image/jpx":["jpx","jpf"],"image/jxr":["jxr"],"image/jxra":["jxra"],"image/jxrs":["jxrs"],"image/jxs":["jxs"],"image/jxsc":["jxsc"],"image/jxsi":["jxsi"],"image/jxss":["jxss"],"image/ktx":["ktx"],"image/ktx2":["ktx2"],"image/png":["png"],"image/sgi":["sgi"],"image/svg+xml":["svg","svgz"],"image/t38":["t38"],"image/tiff":["tif","tiff"],"image/tiff-fx":["tfx"],"image/webp":["webp"],"image/wmf":["wmf"],"message/disposition-notification":["disposition-notification"],"message/global":["u8msg"],"message/global-delivery-status":["u8dsn"],"message/global-disposition-notification":["u8mdn"],"message/global-headers":["u8hdr"],"message/rfc822":["eml","mime"],"model/3mf":["3mf"],"model/gltf+json":["gltf"],"model/gltf-binary":["glb"],"model/iges":["igs","iges"],"model/mesh":["msh","mesh","silo"],"model/mtl":["mtl"],"model/obj":["obj"],"model/step+xml":["stpx"],"model/step+zip":["stpz"],"model/step-xml+zip":["stpxz"],"model/stl":["stl"],"model/vrml":["wrl","vrml"],"model/x3d+binary":["*x3db","x3dbz"],"model/x3d+fastinfoset":["x3db"],"model/x3d+vrml":["*x3dv","x3dvz"],"model/x3d+xml":["x3d","x3dz"],"model/x3d-vrml":["x3dv"],"text/cache-manifest":["appcache","manifest"],"text/calendar":["ics","ifb"],"text/coffeescript":["coffee","litcoffee"],"text/css":["css"],"text/csv":["csv"],"text/html":["html","htm","shtml"],"text/jade":["jade"],"text/jsx":["jsx"],"text/less":["less"],"text/markdown":["markdown","md"],"text/mathml":["mml"],"text/mdx":["mdx"],"text/n3":["n3"],"text/plain":["txt","text","conf","def","list","log","in","ini"],"text/richtext":["rtx"],"text/rtf":["*rtf"],"text/sgml":["sgml","sgm"],"text/shex":["shex"],"text/slim":["slim","slm"],"text/spdx":["spdx"],"text/stylus":["stylus","styl"],"text/tab-separated-values":["tsv"],"text/troff":["t","tr","roff","man","me","ms"],"text/turtle":["ttl"],"text/uri-list":["uri","uris","urls"],"text/vcard":["vcard"],"text/vtt":["vtt"],"text/xml":["*xml"],"text/yaml":["yaml","yml"],"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/h261":["h261"],"video/h263":["h263"],"video/h264":["h264"],"video/iso.segment":["m4s"],"video/jpeg":["jpgv"],"video/jpm":["*jpm","jpgm"],"video/mj2":["mj2","mjp2"],"video/mp2t":["ts"],"video/mp4":["mp4","mp4v","mpg4"],"video/mpeg":["mpeg","mpg","mpe","m1v","m2v"],"video/ogg":["ogv"],"video/quicktime":["qt","mov"],"video/webm":["webm"]}; \ No newline at end of file diff --git a/node_modules/mimic-response/index.d.ts b/node_modules/mimic-response/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..65a51e988f4d5730b347ac203e68f27c1f1666b3 --- /dev/null +++ b/node_modules/mimic-response/index.d.ts @@ -0,0 +1,17 @@ +import {IncomingMessage} from 'http'; + +/** +Mimic a [Node.js HTTP response stream](https://nodejs.org/api/http.html#http_class_http_incomingmessage) + +Makes `toStream` include the properties from `fromStream`. + +@param fromStream - The stream to copy the properties from. +@param toStream - The stream to copy the properties to. +@return The same object as `toStream`. +*/ +declare function mimicResponse( + fromStream: IncomingMessage, // eslint-disable-line @typescript-eslint/prefer-readonly-parameter-types + toStream: T, +): T & IncomingMessage; + +export = mimicResponse; diff --git a/node_modules/mimic-response/index.js b/node_modules/mimic-response/index.js new file mode 100644 index 0000000000000000000000000000000000000000..404e111139095e5ade1235491c76100bd94a2e14 --- /dev/null +++ b/node_modules/mimic-response/index.js @@ -0,0 +1,77 @@ +'use strict'; + +// We define these manually to ensure they're always copied +// even if they would move up the prototype chain +// https://nodejs.org/api/http.html#http_class_http_incomingmessage +const knownProperties = [ + 'aborted', + 'complete', + 'headers', + 'httpVersion', + 'httpVersionMinor', + 'httpVersionMajor', + 'method', + 'rawHeaders', + 'rawTrailers', + 'setTimeout', + 'socket', + 'statusCode', + 'statusMessage', + 'trailers', + 'url' +]; + +module.exports = (fromStream, toStream) => { + if (toStream._readableState.autoDestroy) { + throw new Error('The second stream must have the `autoDestroy` option set to `false`'); + } + + const fromProperties = new Set(Object.keys(fromStream).concat(knownProperties)); + + const properties = {}; + + for (const property of fromProperties) { + // Don't overwrite existing properties. + if (property in toStream) { + continue; + } + + properties[property] = { + get() { + const value = fromStream[property]; + const isFunction = typeof value === 'function'; + + return isFunction ? value.bind(fromStream) : value; + }, + set(value) { + fromStream[property] = value; + }, + enumerable: true, + configurable: false + }; + } + + Object.defineProperties(toStream, properties); + + fromStream.once('aborted', () => { + toStream.destroy(); + + toStream.emit('aborted'); + }); + + fromStream.once('close', () => { + if (fromStream.complete) { + if (toStream.readable) { + toStream.once('end', () => { + toStream.emit('close'); + }); + } else { + toStream.emit('close'); + } + } else { + toStream.emit('close'); + } + }); + + return toStream; +}; diff --git a/node_modules/mimic-response/license b/node_modules/mimic-response/license new file mode 100644 index 0000000000000000000000000000000000000000..fa7ceba3eb4a9657a9db7f3ffca4e4e97a9019de --- /dev/null +++ b/node_modules/mimic-response/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/mimic-response/package.json b/node_modules/mimic-response/package.json new file mode 100644 index 0000000000000000000000000000000000000000..d478b0f3101dd4ddd514357f9d6e16b3bd6546ff --- /dev/null +++ b/node_modules/mimic-response/package.json @@ -0,0 +1,42 @@ +{ + "name": "mimic-response", + "version": "3.1.0", + "description": "Mimic a Node.js HTTP response stream", + "license": "MIT", + "repository": "sindresorhus/mimic-response", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "engines": { + "node": ">=10" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.d.ts", + "index.js" + ], + "keywords": [ + "mimic", + "response", + "stream", + "http", + "https", + "request", + "get", + "core" + ], + "devDependencies": { + "@types/node": "^14.0.1", + "ava": "^2.4.0", + "create-test-server": "^2.4.0", + "p-event": "^4.1.0", + "pify": "^5.0.0", + "tsd": "^0.11.0", + "xo": "^0.30.0" + } +} diff --git a/node_modules/mimic-response/readme.md b/node_modules/mimic-response/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..e968620a4e02a79b09c5cf3fe0285d82dfdb3e0b --- /dev/null +++ b/node_modules/mimic-response/readme.md @@ -0,0 +1,78 @@ +# mimic-response [![Build Status](https://travis-ci.com/sindresorhus/mimic-response.svg?branch=master)](https://travis-ci.com/sindresorhus/mimic-response) + +> Mimic a [Node.js HTTP response stream](https://nodejs.org/api/http.html#http_class_http_incomingmessage) + +## Install + +``` +$ npm install mimic-response +``` + +## Usage + +```js +const stream = require('stream'); +const mimicResponse = require('mimic-response'); + +const responseStream = getHttpResponseStream(); +const myStream = new stream.PassThrough(); + +mimicResponse(responseStream, myStream); + +console.log(myStream.statusCode); +//=> 200 +``` + +## API + +### mimicResponse(from, to) + +**Note #1:** The `from.destroy(error)` function is not proxied. You have to call it manually: + +```js +const stream = require('stream'); +const mimicResponse = require('mimic-response'); + +const responseStream = getHttpResponseStream(); + +const myStream = new stream.PassThrough({ + destroy(error, callback) { + responseStream.destroy(); + + callback(error); + } +}); + +myStream.destroy(); +``` + +Please note that `myStream` and `responseStream` never throws. The error is passed to the request instead. + +#### from + +Type: `Stream` + +[Node.js HTTP response stream.](https://nodejs.org/api/http.html#http_class_http_incomingmessage) + +#### to + +Type: `Stream` + +Any stream. + +## Related + +- [mimic-fn](https://github.com/sindresorhus/mimic-fn) - Make a function mimic another one +- [clone-response](https://github.com/lukechilds/clone-response) - Clone a Node.js response stream + +--- + + diff --git a/node_modules/min-indent/index.js b/node_modules/min-indent/index.js new file mode 100644 index 0000000000000000000000000000000000000000..77abf19276912fa586a9ac8823e260e3c715dc6d --- /dev/null +++ b/node_modules/min-indent/index.js @@ -0,0 +1,10 @@ +'use strict'; +module.exports = string => { + const match = string.match(/^[ \t]*(?=\S)/gm); + + if (!match) { + return 0; + } + + return match.reduce((r, a) => Math.min(r, a.length), Infinity); +}; diff --git a/node_modules/min-indent/license b/node_modules/min-indent/license new file mode 100644 index 0000000000000000000000000000000000000000..dbe9fdc76405e8bf7d12a6a08776be4441718187 --- /dev/null +++ b/node_modules/min-indent/license @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com), James Kyle (thejameskyle.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/min-indent/package.json b/node_modules/min-indent/package.json new file mode 100644 index 0000000000000000000000000000000000000000..95e5259d90d0ea7d5ff9d131ce4c4176f7eaf2cc --- /dev/null +++ b/node_modules/min-indent/package.json @@ -0,0 +1,38 @@ +{ + "name": "min-indent", + "version": "1.0.1", + "description": "Get the shortest leading whitespace from lines in a string", + "main": "index.js", + "license": "MIT", + "repository": "https://github.com/thejameskyle/min-indent", + "author": { + "name": "James Kyle", + "email": "me@thejameskyle.com", + "url": "thejameskyle.com" + }, + "engines": { + "node": ">=4" + }, + "scripts": { + "test": "xo && ava" + }, + "files": [ + "index.js" + ], + "keywords": [ + "indent", + "indentation", + "normalize", + "whitespace", + "space", + "tab", + "string", + "str", + "min", + "minimum" + ], + "devDependencies": { + "ava": "*", + "xo": "*" + } +} diff --git a/node_modules/min-indent/readme.md b/node_modules/min-indent/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..cf573e5f769f44d255cf4224dc27c5feaebe171e --- /dev/null +++ b/node_modules/min-indent/readme.md @@ -0,0 +1,41 @@ +# min-indent [![Build Status](https://travis-ci.org/thejameskyle/min-indent.svg?branch=master)](https://travis-ci.org/thejameskyle/min-indent) + +> Get the shortest leading whitespace from lines in a string + +The line with the least number of leading whitespace, ignoring empty lines, determines the number. + +Useful for removing redundant indentation. + + +## Install + +``` +$ npm install --save min-indent +``` + + +## Usage + +```js +const minIndent = require('min-indent'); + +const str = '\tunicorn\n\t\tcake'; +/* + unicorn + cake +*/ + +minIndent(str); // 1 +``` + + +## Related + +- [strip-indent](https://github.com/sindresorhus/strip-indent) - Strip leading whitespace from each line in a string +- [strip-indent-cli](https://github.com/sindresorhus/strip-indent-cli) - CLI for this module +- [indent-string](https://github.com/sindresorhus/indent-string) - Indent each line in a string + + +## License + +MIT © [James Kyle](https://thejameskyle.com) diff --git a/node_modules/minimatch/LICENSE b/node_modules/minimatch/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1493534e60dce4a4c73e60e0bb448a0ab2567c9d --- /dev/null +++ b/node_modules/minimatch/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) 2011-2023 Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/minimatch/README.md b/node_modules/minimatch/README.md new file mode 100644 index 0000000000000000000000000000000000000000..5dff0df1c964ddb3fdd4bc1abcb12e9e5310b08d --- /dev/null +++ b/node_modules/minimatch/README.md @@ -0,0 +1,491 @@ +# minimatch + +A minimal matching utility. + +This is the matching library used internally by npm. + +It works by converting glob expressions into JavaScript `RegExp` +objects. + +## Important Security Consideration! + +> [!WARNING] +> This library uses JavaScript regular expressions. Please read +> the following warning carefully, and be thoughtful about what +> you provide to this library in production systems. + +_Any_ library in JavaScript that deals with matching string +patterns using regular expressions will be subject to +[ReDoS](https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS) +if the pattern is generated using untrusted input. + +Efforts have been made to mitigate risk as much as is feasible in +such a library, providing maximum recursion depths and so forth, +but these measures can only ultimately protect against accidents, +not malice. A dedicated attacker can _always_ find patterns that +cannot be defended against by a bash-compatible glob pattern +matching system that uses JavaScript regular expressions. + +To be extremely clear: + +> [!WARNING] +> **If you create a system where you take user input, and use +> that input as the source of a Regular Expression pattern, in +> this or any extant glob matcher in JavaScript, you will be +> pwned.** + +A future version of this library _may_ use a different matching +algorithm which does not exhibit backtracking problems. If and +when that happens, it will likely be a sweeping change, and those +improvements will **not** be backported to legacy versions. + +In the near term, it is not reasonable to continue to play +whack-a-mole with security advisories, and so any future ReDoS +reports will be considered "working as intended", and resolved +entirely by this warning. + +## Usage + +```js +// hybrid module, load with require() or import +import { minimatch } from 'minimatch' +// or: +const { minimatch } = require('minimatch') + +minimatch('bar.foo', '*.foo') // true! +minimatch('bar.foo', '*.bar') // false! +minimatch('bar.foo', '*.+(bar|foo)', { debug: true }) // true, and noisy! +``` + +## Features + +Supports these glob features: + +- Brace Expansion +- Extended glob matching +- "Globstar" `**` matching +- [Posix character + classes](https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html), + like `[[:alpha:]]`, supporting the full range of Unicode + characters. For example, `[[:alpha:]]` will match against + `'é'`, though `[a-zA-Z]` will not. Collating symbol and set + matching is not supported, so `[[=e=]]` will _not_ match `'é'` + and `[[.ch.]]` will not match `'ch'` in locales where `ch` is + considered a single character. + +See: + +- `man sh` +- `man bash` [Pattern + Matching](https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html) +- `man 3 fnmatch` +- `man 5 gitignore` + +## Windows + +**Please only use forward-slashes in glob expressions.** + +Though windows uses either `/` or `\` as its path separator, only `/` +characters are used by this glob implementation. You must use +forward-slashes **only** in glob expressions. Back-slashes in patterns +will always be interpreted as escape characters, not path separators. + +Note that `\` or `/` _will_ be interpreted as path separators in paths on +Windows, and will match against `/` in glob expressions. + +So just always use `/` in patterns. + +### UNC Paths + +On Windows, UNC paths like `//?/c:/...` or +`//ComputerName/Share/...` are handled specially. + +- Patterns starting with a double-slash followed by some + non-slash characters will preserve their double-slash. As a + result, a pattern like `//*` will match `//x`, but not `/x`. +- Patterns staring with `//?/:` will _not_ treat + the `?` as a wildcard character. Instead, it will be treated + as a normal string. +- Patterns starting with `//?/:/...` will match + file paths starting with `:/...`, and vice versa, + as if the `//?/` was not present. This behavior only is + present when the drive letters are a case-insensitive match to + one another. The remaining portions of the path/pattern are + compared case sensitively, unless `nocase:true` is set. + +Note that specifying a UNC path using `\` characters as path +separators is always allowed in the file path argument, but only +allowed in the pattern argument when `windowsPathsNoEscape: true` +is set in the options. + +## Minimatch Class + +Create a minimatch object by instantiating the `minimatch.Minimatch` class. + +```javascript +var Minimatch = require('minimatch').Minimatch +var mm = new Minimatch(pattern, options) +``` + +### Properties + +- `pattern` The original pattern the minimatch object represents. +- `options` The options supplied to the constructor. +- `set` A 2-dimensional array of regexp or string expressions. + Each row in the + array corresponds to a brace-expanded pattern. Each item in the row + corresponds to a single path-part. For example, the pattern + `{a,b/c}/d` would expand to a set of patterns like: + + [ [ a, d ] + , [ b, c, d ] ] + + If a portion of the pattern doesn't have any "magic" in it + (that is, it's something like `"foo"` rather than `fo*o?`), then it + will be left as a string rather than converted to a regular + expression. + +- `regexp` Created by the `makeRe` method. A single regular expression + expressing the entire pattern. This is useful in cases where you wish + to use the pattern somewhat like `fnmatch(3)` with `FNM_PATH` enabled. +- `negate` True if the pattern is negated. +- `comment` True if the pattern is a comment. +- `empty` True if the pattern is `""`. + +### Methods + +- `makeRe()` Generate the `regexp` member if necessary, and return it. + Will return `false` if the pattern is invalid. +- `match(fname)` Return true if the filename matches the pattern, or + false otherwise. +- `matchOne(fileArray, patternArray, partial)` Take a `/`-split + filename, and match it against a single row in the `regExpSet`. This + method is mainly for internal use, but is exposed so that it can be + used by a glob-walker that needs to avoid excessive filesystem calls. +- `hasMagic()` Returns true if the parsed pattern contains any + magic characters. Returns false if all comparator parts are + string literals. If the `magicalBraces` option is set on the + constructor, then it will consider brace expansions which are + not otherwise magical to be magic. If not set, then a pattern + like `a{b,c}d` will return `false`, because neither `abd` nor + `acd` contain any special glob characters. + + This does **not** mean that the pattern string can be used as a + literal filename, as it may contain magic glob characters that + are escaped. For example, the pattern `\\*` or `[*]` would not + be considered to have magic, as the matching portion parses to + the literal string `'*'` and would match a path named `'*'`, + not `'\\*'` or `'[*]'`. The `minimatch.unescape()` method may + be used to remove escape characters. + +All other methods are internal, and will be called as necessary. + +### minimatch(path, pattern, options) + +Main export. Tests a path against the pattern using the options. + +```javascript +var isJS = minimatch(file, '*.js', { matchBase: true }) +``` + +### minimatch.filter(pattern, options) + +Returns a function that tests its +supplied argument, suitable for use with `Array.filter`. Example: + +```javascript +var javascripts = fileList.filter(minimatch.filter('*.js', { matchBase: true })) +``` + +### minimatch.escape(pattern, options = {}) + +Escape all magic characters in a glob pattern, so that it will +only ever match literal strings + +If the `windowsPathsNoEscape` option is used, then characters are +escaped by wrapping in `[]`, because a magic character wrapped in +a character class can only be satisfied by that exact character. + +Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot +be escaped or unescaped. + +### minimatch.unescape(pattern, options = {}) + +Un-escape a glob string that may contain some escaped characters. + +If the `windowsPathsNoEscape` option is used, then square-brace +escapes are removed, but not backslash escapes. For example, it +will turn the string `'[*]'` into `*`, but it will not turn +`'\\*'` into `'*'`, because `\` is a path separator in +`windowsPathsNoEscape` mode. + +When `windowsPathsNoEscape` is not set, then both brace escapes +and backslash escapes are removed. + +Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot +be escaped or unescaped. + +### minimatch.match(list, pattern, options) + +Match against the list of +files, in the style of fnmatch or glob. If nothing is matched, and +options.nonull is set, then return a list containing the pattern itself. + +```javascript +var javascripts = minimatch.match(fileList, '*.js', { matchBase: true }) +``` + +### minimatch.makeRe(pattern, options) + +Make a regular expression object from the pattern. + +## Options + +All options are `false` by default. + +### debug + +Dump a ton of stuff to stderr. + +### nobrace + +Do not expand `{a,b}` and `{1..3}` brace sets. + +### noglobstar + +Disable `**` matching against multiple folder names. + +### dot + +Allow patterns to match filenames starting with a period, even if +the pattern does not explicitly have a period in that spot. + +Note that by default, `a/**/b` will **not** match `a/.d/b`, unless `dot` +is set. + +### noext + +Disable "extglob" style patterns like `+(a|b)`. + +### nocase + +Perform a case-insensitive match. + +### nocaseMagicOnly + +When used with `{nocase: true}`, create regular expressions that +are case-insensitive, but leave string match portions untouched. +Has no effect when used without `{nocase: true}` + +Useful when some other form of case-insensitive matching is used, +or if the original string representation is useful in some other +way. + +### nonull + +When a match is not found by `minimatch.match`, return a list containing +the pattern itself if this option is set. When not set, an empty list +is returned if there are no matches. + +### magicalBraces + +This only affects the results of the `Minimatch.hasMagic` method. + +If the pattern contains brace expansions, such as `a{b,c}d`, but +no other magic characters, then the `Minimatch.hasMagic()` method +will return `false` by default. When this option set, it will +return `true` for brace expansion as well as other magic glob +characters. + +### matchBase + +If set, then patterns without slashes will be matched +against the basename of the path if it contains slashes. For example, +`a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`. + +### nocomment + +Suppress the behavior of treating `#` at the start of a pattern as a +comment. + +### nonegate + +Suppress the behavior of treating a leading `!` character as negation. + +### flipNegate + +Returns from negate expressions the same as if they were not negated. +(Ie, true on a hit, false on a miss.) + +### partial + +Compare a partial path to a pattern. As long as the parts of the path that +are present are not contradicted by the pattern, it will be treated as a +match. This is useful in applications where you're walking through a +folder structure, and don't yet have the full path, but want to ensure that +you do not walk down paths that can never be a match. + +For example, + +```js +minimatch('/a/b', '/a/*/c/d', { partial: true }) // true, might be /a/b/c/d +minimatch('/a/b', '/**/d', { partial: true }) // true, might be /a/b/.../d +minimatch('/x/y/z', '/a/**/z', { partial: true }) // false, because x !== a +``` + +### windowsPathsNoEscape + +Use `\\` as a path separator _only_, and _never_ as an escape +character. If set, all `\\` characters are replaced with `/` in +the pattern. Note that this makes it **impossible** to match +against paths containing literal glob pattern characters, but +allows matching with patterns constructed using `path.join()` and +`path.resolve()` on Windows platforms, mimicking the (buggy!) +behavior of earlier versions on Windows. Please use with +caution, and be mindful of [the caveat about Windows +paths](#windows). + +For legacy reasons, this is also set if +`options.allowWindowsEscape` is set to the exact value `false`. + +### windowsNoMagicRoot + +When a pattern starts with a UNC path or drive letter, and in +`nocase:true` mode, do not convert the root portions of the +pattern into a case-insensitive regular expression, and instead +leave them as strings. + +This is the default when the platform is `win32` and +`nocase:true` is set. + +### preserveMultipleSlashes + +By default, multiple `/` characters (other than the leading `//` +in a UNC path, see "UNC Paths" above) are treated as a single +`/`. + +That is, a pattern like `a///b` will match the file path `a/b`. + +Set `preserveMultipleSlashes: true` to suppress this behavior. + +### optimizationLevel + +A number indicating the level of optimization that should be done +to the pattern prior to parsing and using it for matches. + +Globstar parts `**` are always converted to `*` when `noglobstar` +is set, and multiple adjacent `**` parts are converted into a +single `**` (ie, `a/**/**/b` will be treated as `a/**/b`, as this +is equivalent in all cases). + +- `0` - Make no further changes. In this mode, `.` and `..` are + maintained in the pattern, meaning that they must also appear + in the same position in the test path string. Eg, a pattern + like `a/*/../c` will match the string `a/b/../c` but not the + string `a/c`. +- `1` - (default) Remove cases where a double-dot `..` follows a + pattern portion that is not `**`, `.`, `..`, or empty `''`. For + example, the pattern `./a/b/../*` is converted to `./a/*`, and + so it will match the path string `./a/c`, but not the path + string `./a/b/../c`. Dots and empty path portions in the + pattern are preserved. +- `2` (or higher) - Much more aggressive optimizations, suitable + for use with file-walking cases: + + - Remove cases where a double-dot `..` follows a pattern + portion that is not `**`, `.`, or empty `''`. Remove empty + and `.` portions of the pattern, where safe to do so (ie, + anywhere other than the last position, the first position, or + the second position in a pattern starting with `/`, as this + may indicate a UNC path on Windows). + - Convert patterns containing `
    /**/../

    /` into the + equivalent `

    /{..,**}/

    /`, where `

    ` is a + a pattern portion other than `.`, `..`, `**`, or empty + `''`. + - Dedupe patterns where a `**` portion is present in one and + omitted in another, and it is not the final path portion, and + they are otherwise equivalent. So `{a/**/b,a/b}` becomes + `a/**/b`, because `**` matches against an empty path portion. + - Dedupe patterns where a `*` portion is present in one, and a + non-dot pattern other than `**`, `.`, `..`, or `''` is in the + same position in the other. So `a/{*,x}/b` becomes `a/*/b`, + because `*` can match against `x`. + + While these optimizations improve the performance of + file-walking use cases such as [glob](http://npm.im/glob) (ie, + the reason this module exists), there are cases where it will + fail to match a literal string that would have been matched in + optimization level 1 or 0. + + Specifically, while the `Minimatch.match()` method will + optimize the file path string in the same ways, resulting in + the same matches, it will fail when tested with the regular + expression provided by `Minimatch.makeRe()`, unless the path + string is first processed with + `minimatch.levelTwoFileOptimize()` or similar. + +### platform + +When set to `win32`, this will trigger all windows-specific +behaviors (special handling for UNC paths, and treating `\` as +separators in file paths for comparison.) + +Defaults to the value of `process.platform`. + +## Comparisons to other fnmatch/glob implementations + +While strict compliance with the existing standards is a +worthwhile goal, some discrepancies exist between minimatch and +other implementations. Some are intentional, and some are +unavoidable. + +If the pattern starts with a `!` character, then it is negated. Set the +`nonegate` flag to suppress this behavior, and treat leading `!` +characters normally. This is perhaps relevant if you wish to start the +pattern with a negative extglob pattern like `!(a|B)`. Multiple `!` +characters at the start of a pattern will negate the pattern multiple +times. + +If a pattern starts with `#`, then it is treated as a comment, and +will not match anything. Use `\#` to match a literal `#` at the +start of a line, or set the `nocomment` flag to suppress this behavior. + +The double-star character `**` is supported by default, unless the +`noglobstar` flag is set. This is supported in the manner of bsdglob +and bash 4.1, where `**` only has special significance if it is the only +thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but +`a/**b` will not. + +If an escaped pattern has no matches, and the `nonull` flag is set, +then minimatch.match returns the pattern as-provided, rather than +interpreting the character escapes. For example, +`minimatch.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than +`"*a?"`. This is akin to setting the `nullglob` option in bash, except +that it does not resolve escaped pattern characters. + +If brace expansion is not disabled, then it is performed before any +other interpretation of the glob pattern. Thus, a pattern like +`+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded +**first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are +checked for validity. Since those two are valid, matching proceeds. + +Negated extglob patterns are handled as closely as possible to +Bash semantics, but there are some cases with negative extglobs +which are exceedingly difficult to express in a JavaScript +regular expression. In particular the negated pattern +`!(*|)*` will in bash match anything that does +not start with ``. However, +`!(*)*` _will_ match paths starting with +``, because the empty string can match against +the negated portion. In this library, `!(*|)*` +will _not_ match any pattern starting with ``, due to a +difference in precisely which patterns are considered "greedy" in +Regular Expressions vs bash path expansion. This may be fixable, +but not without incurring some complexity and performance costs, +and the trade-off seems to not be worth pursuing. + +Note that `fnmatch(3)` in libc is an extremely naive string comparison +matcher, which does not do anything special for slashes. This library is +designed to be used in glob searching and file walkers, and so it does do +special things with `/`. Thus, `foo*` will not match `foo/bar` in this +library, even though it would in `fnmatch(3)`. diff --git a/node_modules/minimatch/package.json b/node_modules/minimatch/package.json new file mode 100644 index 0000000000000000000000000000000000000000..3866f1da4fda19fbc1361dae0524457546f799fa --- /dev/null +++ b/node_modules/minimatch/package.json @@ -0,0 +1,82 @@ +{ + "author": "Isaac Z. Schlueter (http://blog.izs.me)", + "name": "minimatch", + "description": "a glob matcher in javascript", + "version": "9.0.9", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/minimatch.git" + }, + "main": "./dist/commonjs/index.js", + "types": "./dist/commonjs/index.d.ts", + "exports": { + "./package.json": "./package.json", + ".": { + "import": { + "types": "./dist/esm/index.d.ts", + "default": "./dist/esm/index.js" + }, + "require": { + "types": "./dist/commonjs/index.d.ts", + "default": "./dist/commonjs/index.js" + } + } + }, + "files": [ + "dist" + ], + "scripts": { + "preversion": "npm test", + "postversion": "npm publish", + "prepublishOnly": "git push origin --follow-tags", + "prepare": "tshy", + "pretest": "npm run prepare", + "presnap": "npm run prepare", + "test": "tap", + "snap": "tap", + "format": "prettier --write . --loglevel warn", + "benchmark": "node benchmark/index.js", + "typedoc": "typedoc --tsconfig tsconfig-esm.json ./src/*.ts" + }, + "prettier": { + "semi": false, + "printWidth": 80, + "tabWidth": 2, + "useTabs": false, + "singleQuote": true, + "jsxSingleQuote": false, + "bracketSameLine": true, + "arrowParens": "avoid", + "endOfLine": "lf" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "dependencies": { + "brace-expansion": "^2.0.2" + }, + "devDependencies": { + "@types/brace-expansion": "^1.1.2", + "@types/node": "^25.3.0", + "mkdirp": "^3.0.1", + "prettier": "^3.8.1", + "tap": "^21.6.1", + "tshy": "^3.3.2", + "typescript": "^5.5.3" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + }, + "license": "ISC", + "tshy": { + "exports": { + "./package.json": "./package.json", + ".": "./src/index.ts" + } + }, + "type": "module", + "publishConfig": { + "tag": "legacy-v9" + }, + "module": "./dist/esm/index.js" +} diff --git a/node_modules/minimist/.eslintrc b/node_modules/minimist/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..bd1a5e046b4148dfc6bfd15c8aa69c81ae809a28 --- /dev/null +++ b/node_modules/minimist/.eslintrc @@ -0,0 +1,29 @@ +{ + "root": true, + + "extends": "@ljharb/eslint-config/node/0.4", + + "rules": { + "array-element-newline": 0, + "complexity": 0, + "func-style": [2, "declaration"], + "max-lines-per-function": 0, + "max-nested-callbacks": 1, + "max-statements-per-line": 1, + "max-statements": 0, + "multiline-comment-style": 0, + "no-continue": 1, + "no-param-reassign": 1, + "no-restricted-syntax": 1, + "object-curly-newline": 0, + }, + + "overrides": [ + { + "files": "test/**", + "rules": { + "camelcase": 0, + }, + }, + ] +} diff --git a/node_modules/minimist/.github/FUNDING.yml b/node_modules/minimist/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..a9366222e92a9f9a7a2a4c4cf7cf0f011510924d --- /dev/null +++ b/node_modules/minimist/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/minimist +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/minimist/.nycrc b/node_modules/minimist/.nycrc new file mode 100644 index 0000000000000000000000000000000000000000..55c3d29367a4216abea3dc5eaa48b59826da355b --- /dev/null +++ b/node_modules/minimist/.nycrc @@ -0,0 +1,14 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "example", + "test" + ] +} diff --git a/node_modules/minimist/CHANGELOG.md b/node_modules/minimist/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..c9a1e15e6c2fe73a0ebf35040fef031b46437ba6 --- /dev/null +++ b/node_modules/minimist/CHANGELOG.md @@ -0,0 +1,298 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.2.8](https://github.com/minimistjs/minimist/compare/v1.2.7...v1.2.8) - 2023-02-09 + +### Merged + +- [Fix] Fix long option followed by single dash [`#17`](https://github.com/minimistjs/minimist/pull/17) +- [Tests] Remove duplicate test [`#12`](https://github.com/minimistjs/minimist/pull/12) +- [Fix] opt.string works with multiple aliases [`#10`](https://github.com/minimistjs/minimist/pull/10) + +### Fixed + +- [Fix] Fix long option followed by single dash (#17) [`#15`](https://github.com/minimistjs/minimist/issues/15) +- [Tests] Remove duplicate test (#12) [`#8`](https://github.com/minimistjs/minimist/issues/8) +- [Fix] Fix long option followed by single dash [`#15`](https://github.com/minimistjs/minimist/issues/15) +- [Fix] opt.string works with multiple aliases (#10) [`#9`](https://github.com/minimistjs/minimist/issues/9) +- [Fix] Fix handling of short option with non-trivial equals [`#5`](https://github.com/minimistjs/minimist/issues/5) +- [Tests] Remove duplicate test [`#8`](https://github.com/minimistjs/minimist/issues/8) +- [Fix] opt.string works with multiple aliases [`#9`](https://github.com/minimistjs/minimist/issues/9) + +### Commits + +- Merge tag 'v0.2.3' [`a026794`](https://github.com/minimistjs/minimist/commit/a0267947c7870fc5847cf2d437fbe33f392767da) +- [eslint] fix indentation and whitespace [`5368ca4`](https://github.com/minimistjs/minimist/commit/5368ca4147e974138a54cc0dc4cea8f756546b70) +- [eslint] fix indentation and whitespace [`e5f5067`](https://github.com/minimistjs/minimist/commit/e5f5067259ceeaf0b098d14bec910f87e58708c7) +- [eslint] more cleanup [`62fde7d`](https://github.com/minimistjs/minimist/commit/62fde7d935f83417fb046741531a9e2346a36976) +- [eslint] more cleanup [`36ac5d0`](https://github.com/minimistjs/minimist/commit/36ac5d0d95e4947d074e5737d94814034ca335d1) +- [meta] add `auto-changelog` [`73923d2`](https://github.com/minimistjs/minimist/commit/73923d223553fca08b1ba77e3fbc2a492862ae4c) +- [actions] add reusable workflows [`d80727d`](https://github.com/minimistjs/minimist/commit/d80727df77bfa9e631044d7f16368d8f09242c91) +- [eslint] add eslint; rules to enable later are warnings [`48bc06a`](https://github.com/minimistjs/minimist/commit/48bc06a1b41f00e9cdf183db34f7a51ba70e98d4) +- [eslint] fix indentation [`34b0f1c`](https://github.com/minimistjs/minimist/commit/34b0f1ccaa45183c3c4f06a91f9b405180a6f982) +- [readme] rename and add badges [`5df0fe4`](https://github.com/minimistjs/minimist/commit/5df0fe49211bd09a3636f8686a7cb3012c3e98f0) +- [Dev Deps] switch from `covert` to `nyc` [`a48b128`](https://github.com/minimistjs/minimist/commit/a48b128fdb8d427dfb20a15273f83e38d97bef07) +- [Dev Deps] update `covert`, `tape`; remove unnecessary `tap` [`f0fb958`](https://github.com/minimistjs/minimist/commit/f0fb958e9a1fe980cdffc436a211b0bda58f621b) +- [meta] create FUNDING.yml; add `funding` in package.json [`3639e0c`](https://github.com/minimistjs/minimist/commit/3639e0c819359a366387e425ab6eabf4c78d3caa) +- [meta] use `npmignore` to autogenerate an npmignore file [`be2e038`](https://github.com/minimistjs/minimist/commit/be2e038c342d8333b32f0fde67a0026b79c8150e) +- Only apps should have lockfiles [`282b570`](https://github.com/minimistjs/minimist/commit/282b570e7489d01b03f2d6d3dabf79cd3e5f84cf) +- isConstructorOrProto adapted from PR [`ef9153f`](https://github.com/minimistjs/minimist/commit/ef9153fc52b6cea0744b2239921c5dcae4697f11) +- [Dev Deps] update `@ljharb/eslint-config`, `aud` [`098873c`](https://github.com/minimistjs/minimist/commit/098873c213cdb7c92e55ae1ef5aa1af3a8192a79) +- [Dev Deps] update `@ljharb/eslint-config`, `aud` [`3124ed3`](https://github.com/minimistjs/minimist/commit/3124ed3e46306301ebb3c834874ce0241555c2c4) +- [meta] add `safe-publish-latest` [`4b927de`](https://github.com/minimistjs/minimist/commit/4b927de696d561c636b4f43bf49d4597cb36d6d6) +- [Tests] add `aud` in `posttest` [`b32d9bd`](https://github.com/minimistjs/minimist/commit/b32d9bd0ab340f4e9f8c3a97ff2a4424f25fab8c) +- [meta] update repo URLs [`f9fdfc0`](https://github.com/minimistjs/minimist/commit/f9fdfc032c54884d9a9996a390c63cd0719bbe1a) +- [actions] Avoid 0.6 tests due to build failures [`ba92fe6`](https://github.com/minimistjs/minimist/commit/ba92fe6ebbdc0431cca9a2ea8f27beb492f5e4ec) +- [Dev Deps] update `tape` [`950eaa7`](https://github.com/minimistjs/minimist/commit/950eaa74f112e04d23e9c606c67472c46739b473) +- [Dev Deps] add missing `npmignore` dev dep [`3226afa`](https://github.com/minimistjs/minimist/commit/3226afaf09e9d127ca369742437fe6e88f752d6b) +- Merge tag 'v0.2.2' [`980d7ac`](https://github.com/minimistjs/minimist/commit/980d7ac61a0b4bd552711251ac107d506b23e41f) + +## [v1.2.7](https://github.com/minimistjs/minimist/compare/v1.2.6...v1.2.7) - 2022-10-10 + +### Commits + +- [meta] add `auto-changelog` [`0ebf4eb`](https://github.com/minimistjs/minimist/commit/0ebf4ebcd5f7787a5524d31a849ef41316b83c3c) +- [actions] add reusable workflows [`e115b63`](https://github.com/minimistjs/minimist/commit/e115b63fa9d3909f33b00a2db647ff79068388de) +- [eslint] add eslint; rules to enable later are warnings [`f58745b`](https://github.com/minimistjs/minimist/commit/f58745b9bb84348e1be72af7dbba5840c7c13013) +- [Dev Deps] switch from `covert` to `nyc` [`ab03356`](https://github.com/minimistjs/minimist/commit/ab033567b9c8b31117cb026dc7f1e592ce455c65) +- [readme] rename and add badges [`236f4a0`](https://github.com/minimistjs/minimist/commit/236f4a07e4ebe5ee44f1496ec6974991ab293ffd) +- [meta] create FUNDING.yml; add `funding` in package.json [`783a49b`](https://github.com/minimistjs/minimist/commit/783a49bfd47e8335d3098a8cac75662cf71eb32a) +- [meta] use `npmignore` to autogenerate an npmignore file [`f81ece6`](https://github.com/minimistjs/minimist/commit/f81ece6aaec2fa14e69ff4f1e0407a8c4e2635a2) +- Only apps should have lockfiles [`56cad44`](https://github.com/minimistjs/minimist/commit/56cad44c7f879b9bb5ec18fcc349308024a89bfc) +- [Dev Deps] update `covert`, `tape`; remove unnecessary `tap` [`49c5f9f`](https://github.com/minimistjs/minimist/commit/49c5f9fb7e6a92db9eb340cc679de92fb3aacded) +- [Tests] add `aud` in `posttest` [`228ae93`](https://github.com/minimistjs/minimist/commit/228ae938f3cd9db9dfd8bd7458b076a7b2aef280) +- [meta] add `safe-publish-latest` [`01fc23f`](https://github.com/minimistjs/minimist/commit/01fc23f5104f85c75059972e01dd33796ab529ff) +- [meta] update repo URLs [`6b164c7`](https://github.com/minimistjs/minimist/commit/6b164c7d68e0b6bf32f894699effdfb7c63041dd) + +## [v1.2.6](https://github.com/minimistjs/minimist/compare/v1.2.5...v1.2.6) - 2022-03-21 + +### Commits + +- test from prototype pollution PR [`bc8ecee`](https://github.com/minimistjs/minimist/commit/bc8ecee43875261f4f17eb20b1243d3ed15e70eb) +- isConstructorOrProto adapted from PR [`c2b9819`](https://github.com/minimistjs/minimist/commit/c2b981977fa834b223b408cfb860f933c9811e4d) +- security notice for additional prototype pollution issue [`ef88b93`](https://github.com/minimistjs/minimist/commit/ef88b9325f77b5ee643ccfc97e2ebda577e4c4e2) + +## [v1.2.5](https://github.com/minimistjs/minimist/compare/v1.2.4...v1.2.5) - 2020-03-12 + +## [v1.2.4](https://github.com/minimistjs/minimist/compare/v1.2.3...v1.2.4) - 2020-03-11 + +### Commits + +- security notice [`4cf1354`](https://github.com/minimistjs/minimist/commit/4cf1354839cb972e38496d35e12f806eea92c11f) +- additional test for constructor prototype pollution [`1043d21`](https://github.com/minimistjs/minimist/commit/1043d212c3caaf871966e710f52cfdf02f9eea4b) + +## [v1.2.3](https://github.com/minimistjs/minimist/compare/v1.2.2...v1.2.3) - 2020-03-10 + +### Commits + +- more failing proto pollution tests [`13c01a5`](https://github.com/minimistjs/minimist/commit/13c01a5327736903704984b7f65616b8476850cc) +- even more aggressive checks for protocol pollution [`38a4d1c`](https://github.com/minimistjs/minimist/commit/38a4d1caead72ef99e824bb420a2528eec03d9ab) + +## [v1.2.2](https://github.com/minimistjs/minimist/compare/v1.2.1...v1.2.2) - 2020-03-10 + +### Commits + +- failing test for protocol pollution [`0efed03`](https://github.com/minimistjs/minimist/commit/0efed0340ec8433638758f7ca0c77cb20a0bfbab) +- cleanup [`67d3722`](https://github.com/minimistjs/minimist/commit/67d3722413448d00a62963d2d30c34656a92d7e2) +- console.dir -> console.log [`47acf72`](https://github.com/minimistjs/minimist/commit/47acf72c715a630bf9ea013867f47f1dd69dfc54) +- don't assign onto __proto__ [`63e7ed0`](https://github.com/minimistjs/minimist/commit/63e7ed05aa4b1889ec2f3b196426db4500cbda94) + +## [v1.2.1](https://github.com/minimistjs/minimist/compare/v1.2.0...v1.2.1) - 2020-03-10 + +### Merged + +- move the `opts['--']` example back where it belongs [`#63`](https://github.com/minimistjs/minimist/pull/63) + +### Commits + +- add test [`6be5dae`](https://github.com/minimistjs/minimist/commit/6be5dae35a32a987bcf4137fcd6c19c5200ee909) +- fix bad boolean regexp [`ac3fc79`](https://github.com/minimistjs/minimist/commit/ac3fc796e63b95128fdbdf67ea7fad71bd59aa76) + +## [v1.2.0](https://github.com/minimistjs/minimist/compare/v1.1.3...v1.2.0) - 2015-08-24 + +### Commits + +- failing -k=v short test [`63416b8`](https://github.com/minimistjs/minimist/commit/63416b8cd1d0d70e4714564cce465a36e4dd26d7) +- kv short fix [`6bbe145`](https://github.com/minimistjs/minimist/commit/6bbe14529166245e86424f220a2321442fe88dc3) +- failing kv short test [`f72ab7f`](https://github.com/minimistjs/minimist/commit/f72ab7f4572adc52902c9b6873cc969192f01b10) +- fixed kv test [`f5a48c3`](https://github.com/minimistjs/minimist/commit/f5a48c3e50e40ca54f00c8e84de4b4d6e9897fa8) +- enforce space between arg key and value [`86b321a`](https://github.com/minimistjs/minimist/commit/86b321affe648a8e016c095a4f0efa9d9074f502) + +## [v1.1.3](https://github.com/minimistjs/minimist/compare/v1.1.2...v1.1.3) - 2015-08-06 + +### Commits + +- add failing test - boolean alias array [`0fa3c5b`](https://github.com/minimistjs/minimist/commit/0fa3c5b3dd98551ddecf5392831b4c21211743fc) +- fix boolean values with multiple aliases [`9c0a6e7`](https://github.com/minimistjs/minimist/commit/9c0a6e7de25a273b11bbf9a7464f0bd833779795) + +## [v1.1.2](https://github.com/minimistjs/minimist/compare/v1.1.1...v1.1.2) - 2015-07-22 + +### Commits + +- Convert boolean arguments to boolean values [`8f3dc27`](https://github.com/minimistjs/minimist/commit/8f3dc27cf833f1d54671b6d0bcb55c2fe19672a9) +- use non-ancient npm, node 0.12 and iojs [`61ed1d0`](https://github.com/minimistjs/minimist/commit/61ed1d034b9ec7282764ce76f3992b1a0b4906ae) +- an older npm for 0.8 [`25cf778`](https://github.com/minimistjs/minimist/commit/25cf778b1220e7838a526832ad6972f75244054f) + +## [v1.1.1](https://github.com/minimistjs/minimist/compare/v1.1.0...v1.1.1) - 2015-03-10 + +### Commits + +- check that they type of a value is a boolean, not just that it is currently set to a boolean [`6863198`](https://github.com/minimistjs/minimist/commit/6863198e36139830ff1f20ffdceaddd93f2c1db9) +- upgrade tape, fix type issues from old tape version [`806712d`](https://github.com/minimistjs/minimist/commit/806712df91604ed02b8e39aa372b84aea659ee34) +- test for setting a boolean to a null default [`8c444fe`](https://github.com/minimistjs/minimist/commit/8c444fe89384ded7d441c120915ea60620b01dd3) +- if the previous value was a boolean, without an default (or with an alias) don't make an array either [`e5f419a`](https://github.com/minimistjs/minimist/commit/e5f419a3b5b3bc3f9e5ac71b7040621af70ed2dd) + +## [v1.1.0](https://github.com/minimistjs/minimist/compare/v1.0.0...v1.1.0) - 2014-08-10 + +### Commits + +- add support for handling "unknown" options not registered with the parser. [`6f3cc5d`](https://github.com/minimistjs/minimist/commit/6f3cc5d4e84524932a6ef2ce3592acc67cdd4383) +- reformat package.json [`02ed371`](https://github.com/minimistjs/minimist/commit/02ed37115194d3697ff358e8e25e5e66bab1d9f8) +- coverage script [`e5531ba`](https://github.com/minimistjs/minimist/commit/e5531ba0479da3b8138d3d8cac545d84ccb1c8df) +- extra fn to get 100% coverage again [`a6972da`](https://github.com/minimistjs/minimist/commit/a6972da89e56bf77642f8ec05a13b6558db93498) + +## [v1.0.0](https://github.com/minimistjs/minimist/compare/v0.2.3...v1.0.0) - 2014-08-10 + +### Commits + +- added stopEarly option [`471c7e4`](https://github.com/minimistjs/minimist/commit/471c7e4a7e910fc7ad8f9df850a186daf32c64e9) +- fix list [`fef6ae7`](https://github.com/minimistjs/minimist/commit/fef6ae79c38b9dc1c49569abb7cd04eb965eac5e) + +## [v0.2.3](https://github.com/minimistjs/minimist/compare/v0.2.2...v0.2.3) - 2023-02-09 + +### Merged + +- [Fix] Fix long option followed by single dash [`#17`](https://github.com/minimistjs/minimist/pull/17) +- [Tests] Remove duplicate test [`#12`](https://github.com/minimistjs/minimist/pull/12) +- [Fix] opt.string works with multiple aliases [`#10`](https://github.com/minimistjs/minimist/pull/10) + +### Fixed + +- [Fix] Fix long option followed by single dash (#17) [`#15`](https://github.com/minimistjs/minimist/issues/15) +- [Tests] Remove duplicate test (#12) [`#8`](https://github.com/minimistjs/minimist/issues/8) +- [Fix] opt.string works with multiple aliases (#10) [`#9`](https://github.com/minimistjs/minimist/issues/9) + +### Commits + +- [eslint] fix indentation and whitespace [`e5f5067`](https://github.com/minimistjs/minimist/commit/e5f5067259ceeaf0b098d14bec910f87e58708c7) +- [eslint] more cleanup [`36ac5d0`](https://github.com/minimistjs/minimist/commit/36ac5d0d95e4947d074e5737d94814034ca335d1) +- [eslint] fix indentation [`34b0f1c`](https://github.com/minimistjs/minimist/commit/34b0f1ccaa45183c3c4f06a91f9b405180a6f982) +- isConstructorOrProto adapted from PR [`ef9153f`](https://github.com/minimistjs/minimist/commit/ef9153fc52b6cea0744b2239921c5dcae4697f11) +- [Dev Deps] update `@ljharb/eslint-config`, `aud` [`098873c`](https://github.com/minimistjs/minimist/commit/098873c213cdb7c92e55ae1ef5aa1af3a8192a79) +- [Dev Deps] add missing `npmignore` dev dep [`3226afa`](https://github.com/minimistjs/minimist/commit/3226afaf09e9d127ca369742437fe6e88f752d6b) + +## [v0.2.2](https://github.com/minimistjs/minimist/compare/v0.2.1...v0.2.2) - 2022-10-10 + +### Commits + +- [meta] add `auto-changelog` [`73923d2`](https://github.com/minimistjs/minimist/commit/73923d223553fca08b1ba77e3fbc2a492862ae4c) +- [actions] add reusable workflows [`d80727d`](https://github.com/minimistjs/minimist/commit/d80727df77bfa9e631044d7f16368d8f09242c91) +- [eslint] add eslint; rules to enable later are warnings [`48bc06a`](https://github.com/minimistjs/minimist/commit/48bc06a1b41f00e9cdf183db34f7a51ba70e98d4) +- [readme] rename and add badges [`5df0fe4`](https://github.com/minimistjs/minimist/commit/5df0fe49211bd09a3636f8686a7cb3012c3e98f0) +- [Dev Deps] switch from `covert` to `nyc` [`a48b128`](https://github.com/minimistjs/minimist/commit/a48b128fdb8d427dfb20a15273f83e38d97bef07) +- [Dev Deps] update `covert`, `tape`; remove unnecessary `tap` [`f0fb958`](https://github.com/minimistjs/minimist/commit/f0fb958e9a1fe980cdffc436a211b0bda58f621b) +- [meta] create FUNDING.yml; add `funding` in package.json [`3639e0c`](https://github.com/minimistjs/minimist/commit/3639e0c819359a366387e425ab6eabf4c78d3caa) +- [meta] use `npmignore` to autogenerate an npmignore file [`be2e038`](https://github.com/minimistjs/minimist/commit/be2e038c342d8333b32f0fde67a0026b79c8150e) +- Only apps should have lockfiles [`282b570`](https://github.com/minimistjs/minimist/commit/282b570e7489d01b03f2d6d3dabf79cd3e5f84cf) +- [meta] add `safe-publish-latest` [`4b927de`](https://github.com/minimistjs/minimist/commit/4b927de696d561c636b4f43bf49d4597cb36d6d6) +- [Tests] add `aud` in `posttest` [`b32d9bd`](https://github.com/minimistjs/minimist/commit/b32d9bd0ab340f4e9f8c3a97ff2a4424f25fab8c) +- [meta] update repo URLs [`f9fdfc0`](https://github.com/minimistjs/minimist/commit/f9fdfc032c54884d9a9996a390c63cd0719bbe1a) + +## [v0.2.1](https://github.com/minimistjs/minimist/compare/v0.2.0...v0.2.1) - 2020-03-12 + +## [v0.2.0](https://github.com/minimistjs/minimist/compare/v0.1.0...v0.2.0) - 2014-06-19 + +### Commits + +- support all-boolean mode [`450a97f`](https://github.com/minimistjs/minimist/commit/450a97f6e2bc85c7a4a13185c19a818d9a5ebe69) + +## [v0.1.0](https://github.com/minimistjs/minimist/compare/v0.0.10...v0.1.0) - 2014-05-12 + +### Commits + +- Provide a mechanism to segregate -- arguments [`ce4a1e6`](https://github.com/minimistjs/minimist/commit/ce4a1e63a7e8d5ab88d2a3768adefa6af98a445a) +- documented argv['--'] [`14db0e6`](https://github.com/minimistjs/minimist/commit/14db0e6dbc6d2b9e472adaa54dad7004b364634f) +- Adding a test-case for notFlags segregation [`715c1e3`](https://github.com/minimistjs/minimist/commit/715c1e3714be223f998f6c537af6b505f0236c16) + +## [v0.0.10](https://github.com/minimistjs/minimist/compare/v0.0.9...v0.0.10) - 2014-05-11 + +### Commits + +- dedicated boolean test [`46e448f`](https://github.com/minimistjs/minimist/commit/46e448f9f513cfeb2bcc8b688b9b47ba1e515c2b) +- dedicated num test [`9bf2d36`](https://github.com/minimistjs/minimist/commit/9bf2d36f1d3b8795be90b8f7de0a937f098aa394) +- aliased values treated as strings [`1ab743b`](https://github.com/minimistjs/minimist/commit/1ab743bad4484d69f1259bed42f9531de01119de) +- cover the case of already numbers, at 100% coverage [`b2bb044`](https://github.com/minimistjs/minimist/commit/b2bb04436599d77a2ce029e8e555e25b3aa55d13) +- another test for higher coverage [`3662624`](https://github.com/minimistjs/minimist/commit/3662624be976d5489d486a856849c048d13be903) + +## [v0.0.9](https://github.com/minimistjs/minimist/compare/v0.0.8...v0.0.9) - 2014-05-08 + +### Commits + +- Eliminate `longest` fn. [`824f642`](https://github.com/minimistjs/minimist/commit/824f642038d1b02ede68b6261d1d65163390929a) + +## [v0.0.8](https://github.com/minimistjs/minimist/compare/v0.0.7...v0.0.8) - 2014-02-20 + +### Commits + +- return '' if flag is string and empty [`fa63ed4`](https://github.com/minimistjs/minimist/commit/fa63ed4651a4ef4eefddce34188e0d98d745a263) +- handle joined single letters [`66c248f`](https://github.com/minimistjs/minimist/commit/66c248f0241d4d421d193b022e9e365f11178534) + +## [v0.0.7](https://github.com/minimistjs/minimist/compare/v0.0.6...v0.0.7) - 2014-02-08 + +### Commits + +- another swap of .test for .match [`d1da408`](https://github.com/minimistjs/minimist/commit/d1da40819acbe846d89a5c02721211e3c1260dde) + +## [v0.0.6](https://github.com/minimistjs/minimist/compare/v0.0.5...v0.0.6) - 2014-02-08 + +### Commits + +- use .test() instead of .match() to not crash on non-string values in the arguments array [`7e0d1ad`](https://github.com/minimistjs/minimist/commit/7e0d1add8c9e5b9b20a4d3d0f9a94d824c578da1) + +## [v0.0.5](https://github.com/minimistjs/minimist/compare/v0.0.4...v0.0.5) - 2013-09-18 + +### Commits + +- Improve '--' handling. [`b11822c`](https://github.com/minimistjs/minimist/commit/b11822c09cc9d2460f30384d12afc0b953c037a4) + +## [v0.0.4](https://github.com/minimistjs/minimist/compare/v0.0.3...v0.0.4) - 2013-09-17 + +## [v0.0.3](https://github.com/minimistjs/minimist/compare/v0.0.2...v0.0.3) - 2013-09-12 + +### Commits + +- failing test for single dash preceeding a double dash [`b465514`](https://github.com/minimistjs/minimist/commit/b465514b82c9ae28972d714facd951deb2ad762b) +- fix for the dot test [`6a095f1`](https://github.com/minimistjs/minimist/commit/6a095f1d364c8fab2d6753d2291a0649315d297a) + +## [v0.0.2](https://github.com/minimistjs/minimist/compare/v0.0.1...v0.0.2) - 2013-08-28 + +### Commits + +- allow dotted aliases & defaults [`321c33e`](https://github.com/minimistjs/minimist/commit/321c33e755485faaeb44eeb1c05d33b2e0a5a7c4) +- use a better version of ff [`e40f611`](https://github.com/minimistjs/minimist/commit/e40f61114cf7be6f7947f7b3eed345853a67dbbb) + +## [v0.0.1](https://github.com/minimistjs/minimist/compare/v0.0.0...v0.0.1) - 2013-06-25 + +### Commits + +- remove trailing commas [`6ff0fa0`](https://github.com/minimistjs/minimist/commit/6ff0fa055064f15dbe06d50b89d5173a6796e1db) + +## v0.0.0 - 2013-06-25 + +### Commits + +- half of the parse test ported [`3079326`](https://github.com/minimistjs/minimist/commit/307932601325087de6cf94188eb798ffc4f3088a) +- stripped down code and a passing test from optimist [`7cced88`](https://github.com/minimistjs/minimist/commit/7cced88d82e399d1a03ed23eb667f04d3f320d10) +- ported parse tests completely over [`9448754`](https://github.com/minimistjs/minimist/commit/944875452e0820df6830b1408c26a0f7d3e1db04) +- docs, package.json [`a5bf46a`](https://github.com/minimistjs/minimist/commit/a5bf46ac9bb3bd114a9c340276c62c1091e538d5) +- move more short tests into short.js [`503edb5`](https://github.com/minimistjs/minimist/commit/503edb5c41d89c0d40831ee517154fc13b0f18b9) +- default bool test was wrong, not the code [`1b9f5db`](https://github.com/minimistjs/minimist/commit/1b9f5db4741b49962846081b68518de824992097) +- passing long tests ripped out of parse.js [`7972c4a`](https://github.com/minimistjs/minimist/commit/7972c4aff1f4803079e1668006658e2a761a0428) +- badges [`84c0370`](https://github.com/minimistjs/minimist/commit/84c037063664d42878aace715fe6572ce01b6f3b) +- all the tests now ported, some failures [`64239ed`](https://github.com/minimistjs/minimist/commit/64239edfe92c711c4eb0da254fcdfad2a5fdb605) +- failing short test [`f8a5341`](https://github.com/minimistjs/minimist/commit/f8a534112dd1138d2fad722def56a848480c446f) +- fixed the numeric test [`6b034f3`](https://github.com/minimistjs/minimist/commit/6b034f37c79342c60083ed97fd222e16928aac51) diff --git a/node_modules/minimist/LICENSE b/node_modules/minimist/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..ee27ba4b4412b0e4a05af5e3d8a005bc6681fdf3 --- /dev/null +++ b/node_modules/minimist/LICENSE @@ -0,0 +1,18 @@ +This software is released under the MIT license: + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/minimist/README.md b/node_modules/minimist/README.md new file mode 100644 index 0000000000000000000000000000000000000000..74da3234b4844a2d381a0c6f29f893beee5591bd --- /dev/null +++ b/node_modules/minimist/README.md @@ -0,0 +1,121 @@ +# minimist [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +parse argument options + +This module is the guts of optimist's argument parser without all the +fanciful decoration. + +# example + +``` js +var argv = require('minimist')(process.argv.slice(2)); +console.log(argv); +``` + +``` +$ node example/parse.js -a beep -b boop +{ _: [], a: 'beep', b: 'boop' } +``` + +``` +$ node example/parse.js -x 3 -y 4 -n5 -abc --beep=boop foo bar baz +{ + _: ['foo', 'bar', 'baz'], + x: 3, + y: 4, + n: 5, + a: true, + b: true, + c: true, + beep: 'boop' +} +``` + +# security + +Previous versions had a prototype pollution bug that could cause privilege +escalation in some circumstances when handling untrusted user input. + +Please use version 1.2.6 or later: + +* https://security.snyk.io/vuln/SNYK-JS-MINIMIST-2429795 (version <=1.2.5) +* https://snyk.io/vuln/SNYK-JS-MINIMIST-559764 (version <=1.2.3) + +# methods + +``` js +var parseArgs = require('minimist') +``` + +## var argv = parseArgs(args, opts={}) + +Return an argument object `argv` populated with the array arguments from `args`. + +`argv._` contains all the arguments that didn't have an option associated with +them. + +Numeric-looking arguments will be returned as numbers unless `opts.string` or +`opts.boolean` is set for that argument name. + +Any arguments after `'--'` will not be parsed and will end up in `argv._`. + +options can be: + +* `opts.string` - a string or array of strings argument names to always treat as +strings +* `opts.boolean` - a boolean, string or array of strings to always treat as +booleans. if `true` will treat all double hyphenated arguments without equal signs +as boolean (e.g. affects `--foo`, not `-f` or `--foo=bar`) +* `opts.alias` - an object mapping string names to strings or arrays of string +argument names to use as aliases +* `opts.default` - an object mapping string argument names to default values +* `opts.stopEarly` - when true, populate `argv._` with everything after the +first non-option +* `opts['--']` - when true, populate `argv._` with everything before the `--` +and `argv['--']` with everything after the `--`. Here's an example: + + ``` + > require('./')('one two three -- four five --six'.split(' '), { '--': true }) + { + _: ['one', 'two', 'three'], + '--': ['four', 'five', '--six'] + } + ``` + + Note that with `opts['--']` set, parsing for arguments still stops after the + `--`. + +* `opts.unknown` - a function which is invoked with a command line parameter not +defined in the `opts` configuration object. If the function returns `false`, the +unknown option is not added to `argv`. + +# install + +With [npm](https://npmjs.org) do: + +``` +npm install minimist +``` + +# license + +MIT + +[package-url]: https://npmjs.org/package/minimist +[npm-version-svg]: https://versionbadg.es/minimistjs/minimist.svg +[npm-badge-png]: https://nodei.co/npm/minimist.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/minimist.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/minimist.svg +[downloads-url]: https://npm-stat.com/charts.html?package=minimist +[codecov-image]: https://codecov.io/gh/minimistjs/minimist/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/minimistjs/minimist/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/minimistjs/minimist +[actions-url]: https://github.com/minimistjs/minimist/actions diff --git a/node_modules/minimist/example/parse.js b/node_modules/minimist/example/parse.js new file mode 100644 index 0000000000000000000000000000000000000000..9d90ffb2642b4caddde1ec6fb0cff2e78192bb09 --- /dev/null +++ b/node_modules/minimist/example/parse.js @@ -0,0 +1,4 @@ +'use strict'; + +var argv = require('../')(process.argv.slice(2)); +console.log(argv); diff --git a/node_modules/minimist/index.js b/node_modules/minimist/index.js new file mode 100644 index 0000000000000000000000000000000000000000..f020f3940e129c361dc89226efaf8775a4af8752 --- /dev/null +++ b/node_modules/minimist/index.js @@ -0,0 +1,263 @@ +'use strict'; + +function hasKey(obj, keys) { + var o = obj; + keys.slice(0, -1).forEach(function (key) { + o = o[key] || {}; + }); + + var key = keys[keys.length - 1]; + return key in o; +} + +function isNumber(x) { + if (typeof x === 'number') { return true; } + if ((/^0x[0-9a-f]+$/i).test(x)) { return true; } + return (/^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/).test(x); +} + +function isConstructorOrProto(obj, key) { + return (key === 'constructor' && typeof obj[key] === 'function') || key === '__proto__'; +} + +module.exports = function (args, opts) { + if (!opts) { opts = {}; } + + var flags = { + bools: {}, + strings: {}, + unknownFn: null, + }; + + if (typeof opts.unknown === 'function') { + flags.unknownFn = opts.unknown; + } + + if (typeof opts.boolean === 'boolean' && opts.boolean) { + flags.allBools = true; + } else { + [].concat(opts.boolean).filter(Boolean).forEach(function (key) { + flags.bools[key] = true; + }); + } + + var aliases = {}; + + function aliasIsBoolean(key) { + return aliases[key].some(function (x) { + return flags.bools[x]; + }); + } + + Object.keys(opts.alias || {}).forEach(function (key) { + aliases[key] = [].concat(opts.alias[key]); + aliases[key].forEach(function (x) { + aliases[x] = [key].concat(aliases[key].filter(function (y) { + return x !== y; + })); + }); + }); + + [].concat(opts.string).filter(Boolean).forEach(function (key) { + flags.strings[key] = true; + if (aliases[key]) { + [].concat(aliases[key]).forEach(function (k) { + flags.strings[k] = true; + }); + } + }); + + var defaults = opts.default || {}; + + var argv = { _: [] }; + + function argDefined(key, arg) { + return (flags.allBools && (/^--[^=]+$/).test(arg)) + || flags.strings[key] + || flags.bools[key] + || aliases[key]; + } + + function setKey(obj, keys, value) { + var o = obj; + for (var i = 0; i < keys.length - 1; i++) { + var key = keys[i]; + if (isConstructorOrProto(o, key)) { return; } + if (o[key] === undefined) { o[key] = {}; } + if ( + o[key] === Object.prototype + || o[key] === Number.prototype + || o[key] === String.prototype + ) { + o[key] = {}; + } + if (o[key] === Array.prototype) { o[key] = []; } + o = o[key]; + } + + var lastKey = keys[keys.length - 1]; + if (isConstructorOrProto(o, lastKey)) { return; } + if ( + o === Object.prototype + || o === Number.prototype + || o === String.prototype + ) { + o = {}; + } + if (o === Array.prototype) { o = []; } + if (o[lastKey] === undefined || flags.bools[lastKey] || typeof o[lastKey] === 'boolean') { + o[lastKey] = value; + } else if (Array.isArray(o[lastKey])) { + o[lastKey].push(value); + } else { + o[lastKey] = [o[lastKey], value]; + } + } + + function setArg(key, val, arg) { + if (arg && flags.unknownFn && !argDefined(key, arg)) { + if (flags.unknownFn(arg) === false) { return; } + } + + var value = !flags.strings[key] && isNumber(val) + ? Number(val) + : val; + setKey(argv, key.split('.'), value); + + (aliases[key] || []).forEach(function (x) { + setKey(argv, x.split('.'), value); + }); + } + + Object.keys(flags.bools).forEach(function (key) { + setArg(key, defaults[key] === undefined ? false : defaults[key]); + }); + + var notFlags = []; + + if (args.indexOf('--') !== -1) { + notFlags = args.slice(args.indexOf('--') + 1); + args = args.slice(0, args.indexOf('--')); + } + + for (var i = 0; i < args.length; i++) { + var arg = args[i]; + var key; + var next; + + if ((/^--.+=/).test(arg)) { + // Using [\s\S] instead of . because js doesn't support the + // 'dotall' regex modifier. See: + // http://stackoverflow.com/a/1068308/13216 + var m = arg.match(/^--([^=]+)=([\s\S]*)$/); + key = m[1]; + var value = m[2]; + if (flags.bools[key]) { + value = value !== 'false'; + } + setArg(key, value, arg); + } else if ((/^--no-.+/).test(arg)) { + key = arg.match(/^--no-(.+)/)[1]; + setArg(key, false, arg); + } else if ((/^--.+/).test(arg)) { + key = arg.match(/^--(.+)/)[1]; + next = args[i + 1]; + if ( + next !== undefined + && !(/^(-|--)[^-]/).test(next) + && !flags.bools[key] + && !flags.allBools + && (aliases[key] ? !aliasIsBoolean(key) : true) + ) { + setArg(key, next, arg); + i += 1; + } else if ((/^(true|false)$/).test(next)) { + setArg(key, next === 'true', arg); + i += 1; + } else { + setArg(key, flags.strings[key] ? '' : true, arg); + } + } else if ((/^-[^-]+/).test(arg)) { + var letters = arg.slice(1, -1).split(''); + + var broken = false; + for (var j = 0; j < letters.length; j++) { + next = arg.slice(j + 2); + + if (next === '-') { + setArg(letters[j], next, arg); + continue; + } + + if ((/[A-Za-z]/).test(letters[j]) && next[0] === '=') { + setArg(letters[j], next.slice(1), arg); + broken = true; + break; + } + + if ( + (/[A-Za-z]/).test(letters[j]) + && (/-?\d+(\.\d*)?(e-?\d+)?$/).test(next) + ) { + setArg(letters[j], next, arg); + broken = true; + break; + } + + if (letters[j + 1] && letters[j + 1].match(/\W/)) { + setArg(letters[j], arg.slice(j + 2), arg); + broken = true; + break; + } else { + setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg); + } + } + + key = arg.slice(-1)[0]; + if (!broken && key !== '-') { + if ( + args[i + 1] + && !(/^(-|--)[^-]/).test(args[i + 1]) + && !flags.bools[key] + && (aliases[key] ? !aliasIsBoolean(key) : true) + ) { + setArg(key, args[i + 1], arg); + i += 1; + } else if (args[i + 1] && (/^(true|false)$/).test(args[i + 1])) { + setArg(key, args[i + 1] === 'true', arg); + i += 1; + } else { + setArg(key, flags.strings[key] ? '' : true, arg); + } + } + } else { + if (!flags.unknownFn || flags.unknownFn(arg) !== false) { + argv._.push(flags.strings._ || !isNumber(arg) ? arg : Number(arg)); + } + if (opts.stopEarly) { + argv._.push.apply(argv._, args.slice(i + 1)); + break; + } + } + } + + Object.keys(defaults).forEach(function (k) { + if (!hasKey(argv, k.split('.'))) { + setKey(argv, k.split('.'), defaults[k]); + + (aliases[k] || []).forEach(function (x) { + setKey(argv, x.split('.'), defaults[k]); + }); + } + }); + + if (opts['--']) { + argv['--'] = notFlags.slice(); + } else { + notFlags.forEach(function (k) { + argv._.push(k); + }); + } + + return argv; +}; diff --git a/node_modules/minimist/package.json b/node_modules/minimist/package.json new file mode 100644 index 0000000000000000000000000000000000000000..c10a3344411197a716883caad07f0319f5d69b89 --- /dev/null +++ b/node_modules/minimist/package.json @@ -0,0 +1,75 @@ +{ + "name": "minimist", + "version": "1.2.8", + "description": "parse argument options", + "main": "index.js", + "devDependencies": { + "@ljharb/eslint-config": "^21.0.1", + "aud": "^2.0.2", + "auto-changelog": "^2.4.0", + "eslint": "=8.8.0", + "in-publish": "^2.0.1", + "npmignore": "^0.3.0", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.6.3" + }, + "scripts": { + "prepack": "npmignore --auto --commentLines=auto", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "lint": "eslint --ext=js,mjs .", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "testling": { + "files": "test/*.js", + "browsers": [ + "ie/6..latest", + "ff/5", + "firefox/latest", + "chrome/10", + "chrome/latest", + "safari/5.1", + "safari/latest", + "opera/12" + ] + }, + "repository": { + "type": "git", + "url": "git://github.com/minimistjs/minimist.git" + }, + "homepage": "https://github.com/minimistjs/minimist", + "keywords": [ + "argv", + "getopt", + "parser", + "optimist" + ], + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + } +} diff --git a/node_modules/minimist/test/all_bool.js b/node_modules/minimist/test/all_bool.js new file mode 100644 index 0000000000000000000000000000000000000000..befa0c99769080972260dac9e4a77630857000f2 --- /dev/null +++ b/node_modules/minimist/test/all_bool.js @@ -0,0 +1,34 @@ +'use strict'; + +var parse = require('../'); +var test = require('tape'); + +test('flag boolean true (default all --args to boolean)', function (t) { + var argv = parse(['moo', '--honk', 'cow'], { + boolean: true, + }); + + t.deepEqual(argv, { + honk: true, + _: ['moo', 'cow'], + }); + + t.deepEqual(typeof argv.honk, 'boolean'); + t.end(); +}); + +test('flag boolean true only affects double hyphen arguments without equals signs', function (t) { + var argv = parse(['moo', '--honk', 'cow', '-p', '55', '--tacos=good'], { + boolean: true, + }); + + t.deepEqual(argv, { + honk: true, + tacos: 'good', + p: 55, + _: ['moo', 'cow'], + }); + + t.deepEqual(typeof argv.honk, 'boolean'); + t.end(); +}); diff --git a/node_modules/minimist/test/bool.js b/node_modules/minimist/test/bool.js new file mode 100644 index 0000000000000000000000000000000000000000..e58d47e442ce127bfe5703b6b64d14c3e4511223 --- /dev/null +++ b/node_modules/minimist/test/bool.js @@ -0,0 +1,177 @@ +'use strict'; + +var parse = require('../'); +var test = require('tape'); + +test('flag boolean default false', function (t) { + var argv = parse(['moo'], { + boolean: ['t', 'verbose'], + default: { verbose: false, t: false }, + }); + + t.deepEqual(argv, { + verbose: false, + t: false, + _: ['moo'], + }); + + t.deepEqual(typeof argv.verbose, 'boolean'); + t.deepEqual(typeof argv.t, 'boolean'); + t.end(); + +}); + +test('boolean groups', function (t) { + var argv = parse(['-x', '-z', 'one', 'two', 'three'], { + boolean: ['x', 'y', 'z'], + }); + + t.deepEqual(argv, { + x: true, + y: false, + z: true, + _: ['one', 'two', 'three'], + }); + + t.deepEqual(typeof argv.x, 'boolean'); + t.deepEqual(typeof argv.y, 'boolean'); + t.deepEqual(typeof argv.z, 'boolean'); + t.end(); +}); +test('boolean and alias with chainable api', function (t) { + var aliased = ['-h', 'derp']; + var regular = ['--herp', 'derp']; + var aliasedArgv = parse(aliased, { + boolean: 'herp', + alias: { h: 'herp' }, + }); + var propertyArgv = parse(regular, { + boolean: 'herp', + alias: { h: 'herp' }, + }); + var expected = { + herp: true, + h: true, + _: ['derp'], + }; + + t.same(aliasedArgv, expected); + t.same(propertyArgv, expected); + t.end(); +}); + +test('boolean and alias with options hash', function (t) { + var aliased = ['-h', 'derp']; + var regular = ['--herp', 'derp']; + var opts = { + alias: { h: 'herp' }, + boolean: 'herp', + }; + var aliasedArgv = parse(aliased, opts); + var propertyArgv = parse(regular, opts); + var expected = { + herp: true, + h: true, + _: ['derp'], + }; + t.same(aliasedArgv, expected); + t.same(propertyArgv, expected); + t.end(); +}); + +test('boolean and alias array with options hash', function (t) { + var aliased = ['-h', 'derp']; + var regular = ['--herp', 'derp']; + var alt = ['--harp', 'derp']; + var opts = { + alias: { h: ['herp', 'harp'] }, + boolean: 'h', + }; + var aliasedArgv = parse(aliased, opts); + var propertyArgv = parse(regular, opts); + var altPropertyArgv = parse(alt, opts); + var expected = { + harp: true, + herp: true, + h: true, + _: ['derp'], + }; + t.same(aliasedArgv, expected); + t.same(propertyArgv, expected); + t.same(altPropertyArgv, expected); + t.end(); +}); + +test('boolean and alias using explicit true', function (t) { + var aliased = ['-h', 'true']; + var regular = ['--herp', 'true']; + var opts = { + alias: { h: 'herp' }, + boolean: 'h', + }; + var aliasedArgv = parse(aliased, opts); + var propertyArgv = parse(regular, opts); + var expected = { + herp: true, + h: true, + _: [], + }; + + t.same(aliasedArgv, expected); + t.same(propertyArgv, expected); + t.end(); +}); + +// regression, see https://github.com/substack/node-optimist/issues/71 +test('boolean and --x=true', function (t) { + var parsed = parse(['--boool', '--other=true'], { + boolean: 'boool', + }); + + t.same(parsed.boool, true); + t.same(parsed.other, 'true'); + + parsed = parse(['--boool', '--other=false'], { + boolean: 'boool', + }); + + t.same(parsed.boool, true); + t.same(parsed.other, 'false'); + t.end(); +}); + +test('boolean --boool=true', function (t) { + var parsed = parse(['--boool=true'], { + default: { + boool: false, + }, + boolean: ['boool'], + }); + + t.same(parsed.boool, true); + t.end(); +}); + +test('boolean --boool=false', function (t) { + var parsed = parse(['--boool=false'], { + default: { + boool: true, + }, + boolean: ['boool'], + }); + + t.same(parsed.boool, false); + t.end(); +}); + +test('boolean using something similar to true', function (t) { + var opts = { boolean: 'h' }; + var result = parse(['-h', 'true.txt'], opts); + var expected = { + h: true, + _: ['true.txt'], + }; + + t.same(result, expected); + t.end(); +}); diff --git a/node_modules/minimist/test/dash.js b/node_modules/minimist/test/dash.js new file mode 100644 index 0000000000000000000000000000000000000000..707881771e275240a0e0d6d4d2fb8d31a564d74f --- /dev/null +++ b/node_modules/minimist/test/dash.js @@ -0,0 +1,43 @@ +'use strict'; + +var parse = require('../'); +var test = require('tape'); + +test('-', function (t) { + t.plan(6); + t.deepEqual(parse(['-n', '-']), { n: '-', _: [] }); + t.deepEqual(parse(['--nnn', '-']), { nnn: '-', _: [] }); + t.deepEqual(parse(['-']), { _: ['-'] }); + t.deepEqual(parse(['-f-']), { f: '-', _: [] }); + t.deepEqual( + parse(['-b', '-'], { boolean: 'b' }), + { b: true, _: ['-'] } + ); + t.deepEqual( + parse(['-s', '-'], { string: 's' }), + { s: '-', _: [] } + ); +}); + +test('-a -- b', function (t) { + t.plan(2); + t.deepEqual(parse(['-a', '--', 'b']), { a: true, _: ['b'] }); + t.deepEqual(parse(['--a', '--', 'b']), { a: true, _: ['b'] }); +}); + +test('move arguments after the -- into their own `--` array', function (t) { + t.plan(1); + t.deepEqual( + parse(['--name', 'John', 'before', '--', 'after'], { '--': true }), + { name: 'John', _: ['before'], '--': ['after'] } + ); +}); + +test('--- option value', function (t) { + // A multi-dash value is largely an edge case, but check the behaviour is as expected, + // and in particular the same for short option and long option (as made consistent in Jan 2023). + t.plan(2); + t.deepEqual(parse(['-n', '---']), { n: '---', _: [] }); + t.deepEqual(parse(['--nnn', '---']), { nnn: '---', _: [] }); +}); + diff --git a/node_modules/minimist/test/default_bool.js b/node_modules/minimist/test/default_bool.js new file mode 100644 index 0000000000000000000000000000000000000000..4e9f6250f08ea8e005b66729630660a3db195566 --- /dev/null +++ b/node_modules/minimist/test/default_bool.js @@ -0,0 +1,37 @@ +'use strict'; + +var test = require('tape'); +var parse = require('../'); + +test('boolean default true', function (t) { + var argv = parse([], { + boolean: 'sometrue', + default: { sometrue: true }, + }); + t.equal(argv.sometrue, true); + t.end(); +}); + +test('boolean default false', function (t) { + var argv = parse([], { + boolean: 'somefalse', + default: { somefalse: false }, + }); + t.equal(argv.somefalse, false); + t.end(); +}); + +test('boolean default to null', function (t) { + var argv = parse([], { + boolean: 'maybe', + default: { maybe: null }, + }); + t.equal(argv.maybe, null); + + var argvLong = parse(['--maybe'], { + boolean: 'maybe', + default: { maybe: null }, + }); + t.equal(argvLong.maybe, true); + t.end(); +}); diff --git a/node_modules/minimist/test/dotted.js b/node_modules/minimist/test/dotted.js new file mode 100644 index 0000000000000000000000000000000000000000..126ff033b4237334be18dafed9f2b4636f684d2d --- /dev/null +++ b/node_modules/minimist/test/dotted.js @@ -0,0 +1,24 @@ +'use strict'; + +var parse = require('../'); +var test = require('tape'); + +test('dotted alias', function (t) { + var argv = parse(['--a.b', '22'], { default: { 'a.b': 11 }, alias: { 'a.b': 'aa.bb' } }); + t.equal(argv.a.b, 22); + t.equal(argv.aa.bb, 22); + t.end(); +}); + +test('dotted default', function (t) { + var argv = parse('', { default: { 'a.b': 11 }, alias: { 'a.b': 'aa.bb' } }); + t.equal(argv.a.b, 11); + t.equal(argv.aa.bb, 11); + t.end(); +}); + +test('dotted default with no alias', function (t) { + var argv = parse('', { default: { 'a.b': 11 } }); + t.equal(argv.a.b, 11); + t.end(); +}); diff --git a/node_modules/minimist/test/kv_short.js b/node_modules/minimist/test/kv_short.js new file mode 100644 index 0000000000000000000000000000000000000000..6d1b53a7a7ee1fcbeb9b12c9804f83ff90f46ccd --- /dev/null +++ b/node_modules/minimist/test/kv_short.js @@ -0,0 +1,32 @@ +'use strict'; + +var parse = require('../'); +var test = require('tape'); + +test('short -k=v', function (t) { + t.plan(1); + + var argv = parse(['-b=123']); + t.deepEqual(argv, { b: 123, _: [] }); +}); + +test('multi short -k=v', function (t) { + t.plan(1); + + var argv = parse(['-a=whatever', '-b=robots']); + t.deepEqual(argv, { a: 'whatever', b: 'robots', _: [] }); +}); + +test('short with embedded equals -k=a=b', function (t) { + t.plan(1); + + var argv = parse(['-k=a=b']); + t.deepEqual(argv, { k: 'a=b', _: [] }); +}); + +test('short with later equals like -ab=c', function (t) { + t.plan(1); + + var argv = parse(['-ab=c']); + t.deepEqual(argv, { a: true, b: 'c', _: [] }); +}); diff --git a/node_modules/minimist/test/long.js b/node_modules/minimist/test/long.js new file mode 100644 index 0000000000000000000000000000000000000000..9fef51f1fa8d9bf8ef9e92ad2ce5742f009ab941 --- /dev/null +++ b/node_modules/minimist/test/long.js @@ -0,0 +1,33 @@ +'use strict'; + +var test = require('tape'); +var parse = require('../'); + +test('long opts', function (t) { + t.deepEqual( + parse(['--bool']), + { bool: true, _: [] }, + 'long boolean' + ); + t.deepEqual( + parse(['--pow', 'xixxle']), + { pow: 'xixxle', _: [] }, + 'long capture sp' + ); + t.deepEqual( + parse(['--pow=xixxle']), + { pow: 'xixxle', _: [] }, + 'long capture eq' + ); + t.deepEqual( + parse(['--host', 'localhost', '--port', '555']), + { host: 'localhost', port: 555, _: [] }, + 'long captures sp' + ); + t.deepEqual( + parse(['--host=localhost', '--port=555']), + { host: 'localhost', port: 555, _: [] }, + 'long captures eq' + ); + t.end(); +}); diff --git a/node_modules/minimist/test/num.js b/node_modules/minimist/test/num.js new file mode 100644 index 0000000000000000000000000000000000000000..074393ecaf1705b9a6170c35ad23d55df943f306 --- /dev/null +++ b/node_modules/minimist/test/num.js @@ -0,0 +1,38 @@ +'use strict'; + +var parse = require('../'); +var test = require('tape'); + +test('nums', function (t) { + var argv = parse([ + '-x', '1234', + '-y', '5.67', + '-z', '1e7', + '-w', '10f', + '--hex', '0xdeadbeef', + '789', + ]); + t.deepEqual(argv, { + x: 1234, + y: 5.67, + z: 1e7, + w: '10f', + hex: 0xdeadbeef, + _: [789], + }); + t.deepEqual(typeof argv.x, 'number'); + t.deepEqual(typeof argv.y, 'number'); + t.deepEqual(typeof argv.z, 'number'); + t.deepEqual(typeof argv.w, 'string'); + t.deepEqual(typeof argv.hex, 'number'); + t.deepEqual(typeof argv._[0], 'number'); + t.end(); +}); + +test('already a number', function (t) { + var argv = parse(['-x', 1234, 789]); + t.deepEqual(argv, { x: 1234, _: [789] }); + t.deepEqual(typeof argv.x, 'number'); + t.deepEqual(typeof argv._[0], 'number'); + t.end(); +}); diff --git a/node_modules/minimist/test/parse.js b/node_modules/minimist/test/parse.js new file mode 100644 index 0000000000000000000000000000000000000000..65d9d90927b91baa152a32e1485479307f1acf44 --- /dev/null +++ b/node_modules/minimist/test/parse.js @@ -0,0 +1,209 @@ +'use strict'; + +var parse = require('../'); +var test = require('tape'); + +test('parse args', function (t) { + t.deepEqual( + parse(['--no-moo']), + { moo: false, _: [] }, + 'no' + ); + t.deepEqual( + parse(['-v', 'a', '-v', 'b', '-v', 'c']), + { v: ['a', 'b', 'c'], _: [] }, + 'multi' + ); + t.end(); +}); + +test('comprehensive', function (t) { + t.deepEqual( + parse([ + '--name=meowmers', 'bare', '-cats', 'woo', + '-h', 'awesome', '--multi=quux', + '--key', 'value', + '-b', '--bool', '--no-meep', '--multi=baz', + '--', '--not-a-flag', 'eek', + ]), + { + c: true, + a: true, + t: true, + s: 'woo', + h: 'awesome', + b: true, + bool: true, + key: 'value', + multi: ['quux', 'baz'], + meep: false, + name: 'meowmers', + _: ['bare', '--not-a-flag', 'eek'], + } + ); + t.end(); +}); + +test('flag boolean', function (t) { + var argv = parse(['-t', 'moo'], { boolean: 't' }); + t.deepEqual(argv, { t: true, _: ['moo'] }); + t.deepEqual(typeof argv.t, 'boolean'); + t.end(); +}); + +test('flag boolean value', function (t) { + var argv = parse(['--verbose', 'false', 'moo', '-t', 'true'], { + boolean: ['t', 'verbose'], + default: { verbose: true }, + }); + + t.deepEqual(argv, { + verbose: false, + t: true, + _: ['moo'], + }); + + t.deepEqual(typeof argv.verbose, 'boolean'); + t.deepEqual(typeof argv.t, 'boolean'); + t.end(); +}); + +test('newlines in params', function (t) { + var args = parse(['-s', 'X\nX']); + t.deepEqual(args, { _: [], s: 'X\nX' }); + + // reproduce in bash: + // VALUE="new + // line" + // node program.js --s="$VALUE" + args = parse(['--s=X\nX']); + t.deepEqual(args, { _: [], s: 'X\nX' }); + t.end(); +}); + +test('strings', function (t) { + var s = parse(['-s', '0001234'], { string: 's' }).s; + t.equal(s, '0001234'); + t.equal(typeof s, 'string'); + + var x = parse(['-x', '56'], { string: 'x' }).x; + t.equal(x, '56'); + t.equal(typeof x, 'string'); + t.end(); +}); + +test('stringArgs', function (t) { + var s = parse([' ', ' '], { string: '_' })._; + t.same(s.length, 2); + t.same(typeof s[0], 'string'); + t.same(s[0], ' '); + t.same(typeof s[1], 'string'); + t.same(s[1], ' '); + t.end(); +}); + +test('empty strings', function (t) { + var s = parse(['-s'], { string: 's' }).s; + t.equal(s, ''); + t.equal(typeof s, 'string'); + + var str = parse(['--str'], { string: 'str' }).str; + t.equal(str, ''); + t.equal(typeof str, 'string'); + + var letters = parse(['-art'], { + string: ['a', 't'], + }); + + t.equal(letters.a, ''); + t.equal(letters.r, true); + t.equal(letters.t, ''); + + t.end(); +}); + +test('string and alias', function (t) { + var x = parse(['--str', '000123'], { + string: 's', + alias: { s: 'str' }, + }); + + t.equal(x.str, '000123'); + t.equal(typeof x.str, 'string'); + t.equal(x.s, '000123'); + t.equal(typeof x.s, 'string'); + + var y = parse(['-s', '000123'], { + string: 'str', + alias: { str: 's' }, + }); + + t.equal(y.str, '000123'); + t.equal(typeof y.str, 'string'); + t.equal(y.s, '000123'); + t.equal(typeof y.s, 'string'); + + var z = parse(['-s123'], { + alias: { str: ['s', 'S'] }, + string: ['str'], + }); + + t.deepEqual( + z, + { _: [], s: '123', S: '123', str: '123' }, + 'opt.string works with multiple aliases' + ); + t.end(); +}); + +test('slashBreak', function (t) { + t.same( + parse(['-I/foo/bar/baz']), + { I: '/foo/bar/baz', _: [] } + ); + t.same( + parse(['-xyz/foo/bar/baz']), + { x: true, y: true, z: '/foo/bar/baz', _: [] } + ); + t.end(); +}); + +test('alias', function (t) { + var argv = parse(['-f', '11', '--zoom', '55'], { + alias: { z: 'zoom' }, + }); + t.equal(argv.zoom, 55); + t.equal(argv.z, argv.zoom); + t.equal(argv.f, 11); + t.end(); +}); + +test('multiAlias', function (t) { + var argv = parse(['-f', '11', '--zoom', '55'], { + alias: { z: ['zm', 'zoom'] }, + }); + t.equal(argv.zoom, 55); + t.equal(argv.z, argv.zoom); + t.equal(argv.z, argv.zm); + t.equal(argv.f, 11); + t.end(); +}); + +test('nested dotted objects', function (t) { + var argv = parse([ + '--foo.bar', '3', '--foo.baz', '4', + '--foo.quux.quibble', '5', '--foo.quux.o_O', + '--beep.boop', + ]); + + t.same(argv.foo, { + bar: 3, + baz: 4, + quux: { + quibble: 5, + o_O: true, + }, + }); + t.same(argv.beep, { boop: true }); + t.end(); +}); diff --git a/node_modules/minimist/test/parse_modified.js b/node_modules/minimist/test/parse_modified.js new file mode 100644 index 0000000000000000000000000000000000000000..32965d130fbd4f59b9a6e12488cf18901004d1f8 --- /dev/null +++ b/node_modules/minimist/test/parse_modified.js @@ -0,0 +1,11 @@ +'use strict'; + +var parse = require('../'); +var test = require('tape'); + +test('parse with modifier functions', function (t) { + t.plan(1); + + var argv = parse(['-b', '123'], { boolean: 'b' }); + t.deepEqual(argv, { b: true, _: [123] }); +}); diff --git a/node_modules/minimist/test/proto.js b/node_modules/minimist/test/proto.js new file mode 100644 index 0000000000000000000000000000000000000000..6e629dd34ef0942c19c4d124542f5f030c228ae4 --- /dev/null +++ b/node_modules/minimist/test/proto.js @@ -0,0 +1,64 @@ +'use strict'; + +/* eslint no-proto: 0 */ + +var parse = require('../'); +var test = require('tape'); + +test('proto pollution', function (t) { + var argv = parse(['--__proto__.x', '123']); + t.equal({}.x, undefined); + t.equal(argv.__proto__.x, undefined); + t.equal(argv.x, undefined); + t.end(); +}); + +test('proto pollution (array)', function (t) { + var argv = parse(['--x', '4', '--x', '5', '--x.__proto__.z', '789']); + t.equal({}.z, undefined); + t.deepEqual(argv.x, [4, 5]); + t.equal(argv.x.z, undefined); + t.equal(argv.x.__proto__.z, undefined); + t.end(); +}); + +test('proto pollution (number)', function (t) { + var argv = parse(['--x', '5', '--x.__proto__.z', '100']); + t.equal({}.z, undefined); + t.equal((4).z, undefined); + t.equal(argv.x, 5); + t.equal(argv.x.z, undefined); + t.end(); +}); + +test('proto pollution (string)', function (t) { + var argv = parse(['--x', 'abc', '--x.__proto__.z', 'def']); + t.equal({}.z, undefined); + t.equal('...'.z, undefined); + t.equal(argv.x, 'abc'); + t.equal(argv.x.z, undefined); + t.end(); +}); + +test('proto pollution (constructor)', function (t) { + var argv = parse(['--constructor.prototype.y', '123']); + t.equal({}.y, undefined); + t.equal(argv.y, undefined); + t.end(); +}); + +test('proto pollution (constructor function)', function (t) { + var argv = parse(['--_.concat.constructor.prototype.y', '123']); + function fnToBeTested() {} + t.equal(fnToBeTested.y, undefined); + t.equal(argv.y, undefined); + t.end(); +}); + +// powered by snyk - https://github.com/backstage/backstage/issues/10343 +test('proto pollution (constructor function) snyk', function (t) { + var argv = parse('--_.constructor.constructor.prototype.foo bar'.split(' ')); + t.equal(function () {}.foo, undefined); + t.equal(argv.y, undefined); + t.end(); +}); diff --git a/node_modules/minimist/test/short.js b/node_modules/minimist/test/short.js new file mode 100644 index 0000000000000000000000000000000000000000..4a7b84385bbfdc74314f5e8f7cc4c36afd52b8bd --- /dev/null +++ b/node_modules/minimist/test/short.js @@ -0,0 +1,69 @@ +'use strict'; + +var parse = require('../'); +var test = require('tape'); + +test('numeric short args', function (t) { + t.plan(2); + t.deepEqual(parse(['-n123']), { n: 123, _: [] }); + t.deepEqual( + parse(['-123', '456']), + { 1: true, 2: true, 3: 456, _: [] } + ); +}); + +test('short', function (t) { + t.deepEqual( + parse(['-b']), + { b: true, _: [] }, + 'short boolean' + ); + t.deepEqual( + parse(['foo', 'bar', 'baz']), + { _: ['foo', 'bar', 'baz'] }, + 'bare' + ); + t.deepEqual( + parse(['-cats']), + { c: true, a: true, t: true, s: true, _: [] }, + 'group' + ); + t.deepEqual( + parse(['-cats', 'meow']), + { c: true, a: true, t: true, s: 'meow', _: [] }, + 'short group next' + ); + t.deepEqual( + parse(['-h', 'localhost']), + { h: 'localhost', _: [] }, + 'short capture' + ); + t.deepEqual( + parse(['-h', 'localhost', '-p', '555']), + { h: 'localhost', p: 555, _: [] }, + 'short captures' + ); + t.end(); +}); + +test('mixed short bool and capture', function (t) { + t.same( + parse(['-h', 'localhost', '-fp', '555', 'script.js']), + { + f: true, p: 555, h: 'localhost', + _: ['script.js'], + } + ); + t.end(); +}); + +test('short and long', function (t) { + t.deepEqual( + parse(['-h', 'localhost', '-fp', '555', 'script.js']), + { + f: true, p: 555, h: 'localhost', + _: ['script.js'], + } + ); + t.end(); +}); diff --git a/node_modules/minimist/test/stop_early.js b/node_modules/minimist/test/stop_early.js new file mode 100644 index 0000000000000000000000000000000000000000..52a6a91903028d5230729df63afcdb80d79b0c68 --- /dev/null +++ b/node_modules/minimist/test/stop_early.js @@ -0,0 +1,17 @@ +'use strict'; + +var parse = require('../'); +var test = require('tape'); + +test('stops parsing on the first non-option when stopEarly is set', function (t) { + var argv = parse(['--aaa', 'bbb', 'ccc', '--ddd'], { + stopEarly: true, + }); + + t.deepEqual(argv, { + aaa: 'bbb', + _: ['ccc', '--ddd'], + }); + + t.end(); +}); diff --git a/node_modules/minimist/test/unknown.js b/node_modules/minimist/test/unknown.js new file mode 100644 index 0000000000000000000000000000000000000000..4f2e0ca447f4ccc2fb7ba4df3876bf45d3f0423a --- /dev/null +++ b/node_modules/minimist/test/unknown.js @@ -0,0 +1,104 @@ +'use strict'; + +var parse = require('../'); +var test = require('tape'); + +test('boolean and alias is not unknown', function (t) { + var unknown = []; + function unknownFn(arg) { + unknown.push(arg); + return false; + } + var aliased = ['-h', 'true', '--derp', 'true']; + var regular = ['--herp', 'true', '-d', 'true']; + var opts = { + alias: { h: 'herp' }, + boolean: 'h', + unknown: unknownFn, + }; + parse(aliased, opts); + parse(regular, opts); + + t.same(unknown, ['--derp', '-d']); + t.end(); +}); + +test('flag boolean true any double hyphen argument is not unknown', function (t) { + var unknown = []; + function unknownFn(arg) { + unknown.push(arg); + return false; + } + var argv = parse(['--honk', '--tacos=good', 'cow', '-p', '55'], { + boolean: true, + unknown: unknownFn, + }); + t.same(unknown, ['--tacos=good', 'cow', '-p']); + t.same(argv, { + honk: true, + _: [], + }); + t.end(); +}); + +test('string and alias is not unknown', function (t) { + var unknown = []; + function unknownFn(arg) { + unknown.push(arg); + return false; + } + var aliased = ['-h', 'hello', '--derp', 'goodbye']; + var regular = ['--herp', 'hello', '-d', 'moon']; + var opts = { + alias: { h: 'herp' }, + string: 'h', + unknown: unknownFn, + }; + parse(aliased, opts); + parse(regular, opts); + + t.same(unknown, ['--derp', '-d']); + t.end(); +}); + +test('default and alias is not unknown', function (t) { + var unknown = []; + function unknownFn(arg) { + unknown.push(arg); + return false; + } + var aliased = ['-h', 'hello']; + var regular = ['--herp', 'hello']; + var opts = { + default: { h: 'bar' }, + alias: { h: 'herp' }, + unknown: unknownFn, + }; + parse(aliased, opts); + parse(regular, opts); + + t.same(unknown, []); + t.end(); + unknownFn(); // exercise fn for 100% coverage +}); + +test('value following -- is not unknown', function (t) { + var unknown = []; + function unknownFn(arg) { + unknown.push(arg); + return false; + } + var aliased = ['--bad', '--', 'good', 'arg']; + var opts = { + '--': true, + unknown: unknownFn, + }; + var argv = parse(aliased, opts); + + t.same(unknown, ['--bad']); + t.same(argv, { + '--': ['good', 'arg'], + _: [], + }); + t.end(); +}); diff --git a/node_modules/minimist/test/whitespace.js b/node_modules/minimist/test/whitespace.js new file mode 100644 index 0000000000000000000000000000000000000000..4fdaf1d3943f5a16b9d76af9cd7bbc82f2f54b54 --- /dev/null +++ b/node_modules/minimist/test/whitespace.js @@ -0,0 +1,10 @@ +'use strict'; + +var parse = require('../'); +var test = require('tape'); + +test('whitespace should be whitespace', function (t) { + t.plan(1); + var x = parse(['-x', '\t']).x; + t.equal(x, '\t'); +}); diff --git a/node_modules/minipass/LICENSE.md b/node_modules/minipass/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..c5402b9577a8cdd966c0974e5b74cc7b85f536c5 --- /dev/null +++ b/node_modules/minipass/LICENSE.md @@ -0,0 +1,55 @@ +# Blue Oak Model License + +Version 1.0.0 + +## Purpose + +This license gives everyone as much permission to work with +this software as possible, while protecting contributors +from liability. + +## Acceptance + +In order to receive this license, you must agree to its +rules. The rules of this license are both obligations +under that agreement and conditions to your license. +You must not do anything with this software that triggers +a rule that you cannot or will not follow. + +## Copyright + +Each contributor licenses you to do everything with this +software that would otherwise infringe that contributor's +copyright in it. + +## Notices + +You must ensure that everyone who gets a copy of +any part of this software from you, with or without +changes, also gets the text of this license or a link to +. + +## Excuse + +If anyone notifies you in writing that you have not +complied with [Notices](#notices), you can keep your +license by taking all practical steps to comply within 30 +days after the notice. If you do not do so, your license +ends immediately. + +## Patent + +Each contributor licenses you to do everything with this +software that would otherwise infringe any patent claims +they can license or become able to license. + +## Reliability + +No contributor can revoke this license. + +## No Liability + +***As far as the law allows, this software comes as is, +without any warranty or condition, and no contributor +will be liable to anyone for any damages related to this +software or this license, under any kind of legal claim.*** diff --git a/node_modules/minipass/README.md b/node_modules/minipass/README.md new file mode 100644 index 0000000000000000000000000000000000000000..1126330582d8ab634134195f893780437760ce59 --- /dev/null +++ b/node_modules/minipass/README.md @@ -0,0 +1,825 @@ +# minipass + +A _very_ minimal implementation of a [PassThrough +stream](https://nodejs.org/api/stream.html#stream_class_stream_passthrough) + +[It's very +fast](https://docs.google.com/spreadsheets/d/1K_HR5oh3r80b8WVMWCPPjfuWXUgfkmhlX7FGI6JJ8tY/edit?usp=sharing) +for objects, strings, and buffers. + +Supports `pipe()`ing (including multi-`pipe()` and backpressure +transmission), buffering data until either a `data` event handler +or `pipe()` is added (so you don't lose the first chunk), and +most other cases where PassThrough is a good idea. + +There is a `read()` method, but it's much more efficient to +consume data from this stream via `'data'` events or by calling +`pipe()` into some other stream. Calling `read()` requires the +buffer to be flattened in some cases, which requires copying +memory. + +If you set `objectMode: true` in the options, then whatever is +written will be emitted. Otherwise, it'll do a minimal amount of +Buffer copying to ensure proper Streams semantics when `read(n)` +is called. + +`objectMode` can only be set at instantiation. Attempting to +write something other than a String or Buffer without having set +`objectMode` in the options will throw an error. + +This is not a `through` or `through2` stream. It doesn't +transform the data, it just passes it right through. If you want +to transform the data, extend the class, and override the +`write()` method. Once you're done transforming the data however +you want, call `super.write()` with the transform output. + +For some examples of streams that extend Minipass in various +ways, check out: + +- [minizlib](http://npm.im/minizlib) +- [fs-minipass](http://npm.im/fs-minipass) +- [tar](http://npm.im/tar) +- [minipass-collect](http://npm.im/minipass-collect) +- [minipass-flush](http://npm.im/minipass-flush) +- [minipass-pipeline](http://npm.im/minipass-pipeline) +- [tap](http://npm.im/tap) +- [tap-parser](http://npm.im/tap-parser) +- [treport](http://npm.im/treport) +- [minipass-fetch](http://npm.im/minipass-fetch) +- [pacote](http://npm.im/pacote) +- [make-fetch-happen](http://npm.im/make-fetch-happen) +- [cacache](http://npm.im/cacache) +- [ssri](http://npm.im/ssri) +- [npm-registry-fetch](http://npm.im/npm-registry-fetch) +- [minipass-json-stream](http://npm.im/minipass-json-stream) +- [minipass-sized](http://npm.im/minipass-sized) + +## Usage in TypeScript + +The `Minipass` class takes three type template definitions: + +- `RType` the type being read, which defaults to `Buffer`. If + `RType` is `string`, then the constructor _must_ get an options + object specifying either an `encoding` or `objectMode: true`. + If it's anything other than `string` or `Buffer`, then it + _must_ get an options object specifying `objectMode: true`. +- `WType` the type being written. If `RType` is `Buffer` or + `string`, then this defaults to `ContiguousData` (Buffer, + string, ArrayBuffer, or ArrayBufferView). Otherwise, it + defaults to `RType`. +- `Events` type mapping event names to the arguments emitted + with that event, which extends `Minipass.Events`. + +To declare types for custom events in subclasses, extend the +third parameter with your own event signatures. For example: + +```js +import { Minipass } from 'minipass' + +// a NDJSON stream that emits 'jsonError' when it can't stringify +export interface Events extends Minipass.Events { + jsonError: [e: Error] +} + +export class NDJSONStream extends Minipass { + constructor() { + super({ objectMode: true }) + } + + // data is type `any` because that's WType + write(data, encoding, cb) { + try { + const json = JSON.stringify(data) + return super.write(json + '\n', encoding, cb) + } catch (er) { + if (!er instanceof Error) { + er = Object.assign(new Error('json stringify failed'), { + cause: er, + }) + } + // trying to emit with something OTHER than an error will + // fail, because we declared the event arguments type. + this.emit('jsonError', er) + } + } +} + +const s = new NDJSONStream() +s.on('jsonError', e => { + // here, TS knows that e is an Error +}) +``` + +Emitting/handling events that aren't declared in this way is +fine, but the arguments will be typed as `unknown`. + +## Differences from Node.js Streams + +There are several things that make Minipass streams different +from (and in some ways superior to) Node.js core streams. + +Please read these caveats if you are familiar with node-core +streams and intend to use Minipass streams in your programs. + +You can avoid most of these differences entirely (for a very +small performance penalty) by setting `{async: true}` in the +constructor options. + +### Timing + +Minipass streams are designed to support synchronous use-cases. +Thus, data is emitted as soon as it is available, always. It is +buffered until read, but no longer. Another way to look at it is +that Minipass streams are exactly as synchronous as the logic +that writes into them. + +This can be surprising if your code relies on +`PassThrough.write()` always providing data on the next tick +rather than the current one, or being able to call `resume()` and +not have the entire buffer disappear immediately. + +However, without this synchronicity guarantee, there would be no +way for Minipass to achieve the speeds it does, or support the +synchronous use cases that it does. Simply put, waiting takes +time. + +This non-deferring approach makes Minipass streams much easier to +reason about, especially in the context of Promises and other +flow-control mechanisms. + +Example: + +```js +// hybrid module, either works +import { Minipass } from 'minipass' +// or: +const { Minipass } = require('minipass') + +const stream = new Minipass() +stream.on('data', () => console.log('data event')) +console.log('before write') +stream.write('hello') +console.log('after write') +// output: +// before write +// data event +// after write +``` + +### Exception: Async Opt-In + +If you wish to have a Minipass stream with behavior that more +closely mimics Node.js core streams, you can set the stream in +async mode either by setting `async: true` in the constructor +options, or by setting `stream.async = true` later on. + +```js +// hybrid module, either works +import { Minipass } from 'minipass' +// or: +const { Minipass } = require('minipass') + +const asyncStream = new Minipass({ async: true }) +asyncStream.on('data', () => console.log('data event')) +console.log('before write') +asyncStream.write('hello') +console.log('after write') +// output: +// before write +// after write +// data event <-- this is deferred until the next tick +``` + +Switching _out_ of async mode is unsafe, as it could cause data +corruption, and so is not enabled. Example: + +```js +import { Minipass } from 'minipass' +const stream = new Minipass({ encoding: 'utf8' }) +stream.on('data', chunk => console.log(chunk)) +stream.async = true +console.log('before writes') +stream.write('hello') +setStreamSyncAgainSomehow(stream) // <-- this doesn't actually exist! +stream.write('world') +console.log('after writes') +// hypothetical output would be: +// before writes +// world +// after writes +// hello +// NOT GOOD! +``` + +To avoid this problem, once set into async mode, any attempt to +make the stream sync again will be ignored. + +```js +const { Minipass } = require('minipass') +const stream = new Minipass({ encoding: 'utf8' }) +stream.on('data', chunk => console.log(chunk)) +stream.async = true +console.log('before writes') +stream.write('hello') +stream.async = false // <-- no-op, stream already async +stream.write('world') +console.log('after writes') +// actual output: +// before writes +// after writes +// hello +// world +``` + +### No High/Low Water Marks + +Node.js core streams will optimistically fill up a buffer, +returning `true` on all writes until the limit is hit, even if +the data has nowhere to go. Then, they will not attempt to draw +more data in until the buffer size dips below a minimum value. + +Minipass streams are much simpler. The `write()` method will +return `true` if the data has somewhere to go (which is to say, +given the timing guarantees, that the data is already there by +the time `write()` returns). + +If the data has nowhere to go, then `write()` returns false, and +the data sits in a buffer, to be drained out immediately as soon +as anyone consumes it. + +Since nothing is ever buffered unnecessarily, there is much less +copying data, and less bookkeeping about buffer capacity levels. + +### Hazards of Buffering (or: Why Minipass Is So Fast) + +Since data written to a Minipass stream is immediately written +all the way through the pipeline, and `write()` always returns +true/false based on whether the data was fully flushed, +backpressure is communicated immediately to the upstream caller. +This minimizes buffering. + +Consider this case: + +```js +const { PassThrough } = require('stream') +const p1 = new PassThrough({ highWaterMark: 1024 }) +const p2 = new PassThrough({ highWaterMark: 1024 }) +const p3 = new PassThrough({ highWaterMark: 1024 }) +const p4 = new PassThrough({ highWaterMark: 1024 }) + +p1.pipe(p2).pipe(p3).pipe(p4) +p4.on('data', () => console.log('made it through')) + +// this returns false and buffers, then writes to p2 on next tick (1) +// p2 returns false and buffers, pausing p1, then writes to p3 on next tick (2) +// p3 returns false and buffers, pausing p2, then writes to p4 on next tick (3) +// p4 returns false and buffers, pausing p3, then emits 'data' and 'drain' +// on next tick (4) +// p3 sees p4's 'drain' event, and calls resume(), emitting 'resume' and +// 'drain' on next tick (5) +// p2 sees p3's 'drain', calls resume(), emits 'resume' and 'drain' on next tick (6) +// p1 sees p2's 'drain', calls resume(), emits 'resume' and 'drain' on next +// tick (7) + +p1.write(Buffer.alloc(2048)) // returns false +``` + +Along the way, the data was buffered and deferred at each stage, +and multiple event deferrals happened, for an unblocked pipeline +where it was perfectly safe to write all the way through! + +Furthermore, setting a `highWaterMark` of `1024` might lead +someone reading the code to think an advisory maximum of 1KiB is +being set for the pipeline. However, the actual advisory +buffering level is the _sum_ of `highWaterMark` values, since +each one has its own bucket. + +Consider the Minipass case: + +```js +const m1 = new Minipass() +const m2 = new Minipass() +const m3 = new Minipass() +const m4 = new Minipass() + +m1.pipe(m2).pipe(m3).pipe(m4) +m4.on('data', () => console.log('made it through')) + +// m1 is flowing, so it writes the data to m2 immediately +// m2 is flowing, so it writes the data to m3 immediately +// m3 is flowing, so it writes the data to m4 immediately +// m4 is flowing, so it fires the 'data' event immediately, returns true +// m4's write returned true, so m3 is still flowing, returns true +// m3's write returned true, so m2 is still flowing, returns true +// m2's write returned true, so m1 is still flowing, returns true +// No event deferrals or buffering along the way! + +m1.write(Buffer.alloc(2048)) // returns true +``` + +It is extremely unlikely that you _don't_ want to buffer any data +written, or _ever_ buffer data that can be flushed all the way +through. Neither node-core streams nor Minipass ever fail to +buffer written data, but node-core streams do a lot of +unnecessary buffering and pausing. + +As always, the faster implementation is the one that does less +stuff and waits less time to do it. + +### Immediately emit `end` for empty streams (when not paused) + +If a stream is not paused, and `end()` is called before writing +any data into it, then it will emit `end` immediately. + +If you have logic that occurs on the `end` event which you don't +want to potentially happen immediately (for example, closing file +descriptors, moving on to the next entry in an archive parse +stream, etc.) then be sure to call `stream.pause()` on creation, +and then `stream.resume()` once you are ready to respond to the +`end` event. + +However, this is _usually_ not a problem because: + +### Emit `end` When Asked + +One hazard of immediately emitting `'end'` is that you may not +yet have had a chance to add a listener. In order to avoid this +hazard, Minipass streams safely re-emit the `'end'` event if a +new listener is added after `'end'` has been emitted. + +Ie, if you do `stream.on('end', someFunction)`, and the stream +has already emitted `end`, then it will call the handler right +away. (You can think of this somewhat like attaching a new +`.then(fn)` to a previously-resolved Promise.) + +To prevent calling handlers multiple times who would not expect +multiple ends to occur, all listeners are removed from the +`'end'` event whenever it is emitted. + +### Emit `error` When Asked + +The most recent error object passed to the `'error'` event is +stored on the stream. If a new `'error'` event handler is added, +and an error was previously emitted, then the event handler will +be called immediately (or on `process.nextTick` in the case of +async streams). + +This makes it much more difficult to end up trying to interact +with a broken stream, if the error handler is added after an +error was previously emitted. + +### Impact of "immediate flow" on Tee-streams + +A "tee stream" is a stream piping to multiple destinations: + +```js +const tee = new Minipass() +t.pipe(dest1) +t.pipe(dest2) +t.write('foo') // goes to both destinations +``` + +Since Minipass streams _immediately_ process any pending data +through the pipeline when a new pipe destination is added, this +can have surprising effects, especially when a stream comes in +from some other function and may or may not have data in its +buffer. + +```js +// WARNING! WILL LOSE DATA! +const src = new Minipass() +src.write('foo') +src.pipe(dest1) // 'foo' chunk flows to dest1 immediately, and is gone +src.pipe(dest2) // gets nothing! +``` + +One solution is to create a dedicated tee-stream junction that +pipes to both locations, and then pipe to _that_ instead. + +```js +// Safe example: tee to both places +const src = new Minipass() +src.write('foo') +const tee = new Minipass() +tee.pipe(dest1) +tee.pipe(dest2) +src.pipe(tee) // tee gets 'foo', pipes to both locations +``` + +The same caveat applies to `on('data')` event listeners. The +first one added will _immediately_ receive all of the data, +leaving nothing for the second: + +```js +// WARNING! WILL LOSE DATA! +const src = new Minipass() +src.write('foo') +src.on('data', handler1) // receives 'foo' right away +src.on('data', handler2) // nothing to see here! +``` + +Using a dedicated tee-stream can be used in this case as well: + +```js +// Safe example: tee to both data handlers +const src = new Minipass() +src.write('foo') +const tee = new Minipass() +tee.on('data', handler1) +tee.on('data', handler2) +src.pipe(tee) +``` + +All of the hazards in this section are avoided by setting `{ +async: true }` in the Minipass constructor, or by setting +`stream.async = true` afterwards. Note that this does add some +overhead, so should only be done in cases where you are willing +to lose a bit of performance in order to avoid having to refactor +program logic. + +## USAGE + +It's a stream! Use it like a stream and it'll most likely do what +you want. + +```js +import { Minipass } from 'minipass' +const mp = new Minipass(options) // options is optional +mp.write('foo') +mp.pipe(someOtherStream) +mp.end('bar') +``` + +### OPTIONS + +- `encoding` How would you like the data coming _out_ of the + stream to be encoded? Accepts any values that can be passed to + `Buffer.toString()`. +- `objectMode` Emit data exactly as it comes in. This will be + flipped on by default if you write() something other than a + string or Buffer at any point. Setting `objectMode: true` will + prevent setting any encoding value. +- `async` Defaults to `false`. Set to `true` to defer data + emission until next tick. This reduces performance slightly, + but makes Minipass streams use timing behavior closer to Node + core streams. See [Timing](#timing) for more details. +- `signal` An `AbortSignal` that will cause the stream to unhook + itself from everything and become as inert as possible. Note + that providing a `signal` parameter will make `'error'` events + no longer throw if they are unhandled, but they will still be + emitted to handlers if any are attached. + +### API + +Implements the user-facing portions of Node.js's `Readable` and +`Writable` streams. + +### Methods + +- `write(chunk, [encoding], [callback])` - Put data in. (Note + that, in the base Minipass class, the same data will come out.) + Returns `false` if the stream will buffer the next write, or + true if it's still in "flowing" mode. +- `end([chunk, [encoding]], [callback])` - Signal that you have + no more data to write. This will queue an `end` event to be + fired when all the data has been consumed. +- `pause()` - No more data for a while, please. This also + prevents `end` from being emitted for empty streams until the + stream is resumed. +- `resume()` - Resume the stream. If there's data in the buffer, + it is all discarded. Any buffered events are immediately + emitted. +- `pipe(dest)` - Send all output to the stream provided. When + data is emitted, it is immediately written to any and all pipe + destinations. (Or written on next tick in `async` mode.) +- `unpipe(dest)` - Stop piping to the destination stream. This is + immediate, meaning that any asynchronously queued data will + _not_ make it to the destination when running in `async` mode. + - `options.end` - Boolean, end the destination stream when the + source stream ends. Default `true`. + - `options.proxyErrors` - Boolean, proxy `error` events from + the source stream to the destination stream. Note that errors + are _not_ proxied after the pipeline terminates, either due + to the source emitting `'end'` or manually unpiping with + `src.unpipe(dest)`. Default `false`. +- `on(ev, fn)`, `emit(ev, fn)` - Minipass streams are + EventEmitters. Some events are given special treatment, + however. (See below under "events".) +- `promise()` - Returns a Promise that resolves when the stream + emits `end`, or rejects if the stream emits `error`. +- `collect()` - Return a Promise that resolves on `end` with an + array containing each chunk of data that was emitted, or + rejects if the stream emits `error`. Note that this consumes + the stream data. +- `concat()` - Same as `collect()`, but concatenates the data + into a single Buffer object. Will reject the returned promise + if the stream is in objectMode, or if it goes into objectMode + by the end of the data. +- `read(n)` - Consume `n` bytes of data out of the buffer. If `n` + is not provided, then consume all of it. If `n` bytes are not + available, then it returns null. **Note** consuming streams in + this way is less efficient, and can lead to unnecessary Buffer + copying. +- `destroy([er])` - Destroy the stream. If an error is provided, + then an `'error'` event is emitted. If the stream has a + `close()` method, and has not emitted a `'close'` event yet, + then `stream.close()` will be called. Any Promises returned by + `.promise()`, `.collect()` or `.concat()` will be rejected. + After being destroyed, writing to the stream will emit an + error. No more data will be emitted if the stream is destroyed, + even if it was previously buffered. + +### Properties + +- `bufferLength` Read-only. Total number of bytes buffered, or in + the case of objectMode, the total number of objects. +- `encoding` Read-only. The encoding that has been set. +- `flowing` Read-only. Boolean indicating whether a chunk written + to the stream will be immediately emitted. +- `emittedEnd` Read-only. Boolean indicating whether the end-ish + events (ie, `end`, `prefinish`, `finish`) have been emitted. + Note that listening on any end-ish event will immediateyl + re-emit it if it has already been emitted. +- `writable` Whether the stream is writable. Default `true`. Set + to `false` when `end()` +- `readable` Whether the stream is readable. Default `true`. +- `pipes` An array of Pipe objects referencing streams that this + stream is piping into. +- `destroyed` A getter that indicates whether the stream was + destroyed. +- `paused` True if the stream has been explicitly paused, + otherwise false. +- `objectMode` Indicates whether the stream is in `objectMode`. +- `aborted` Readonly property set when the `AbortSignal` + dispatches an `abort` event. + +### Events + +- `data` Emitted when there's data to read. Argument is the data + to read. This is never emitted while not flowing. If a listener + is attached, that will resume the stream. +- `end` Emitted when there's no more data to read. This will be + emitted immediately for empty streams when `end()` is called. + If a listener is attached, and `end` was already emitted, then + it will be emitted again. All listeners are removed when `end` + is emitted. +- `prefinish` An end-ish event that follows the same logic as + `end` and is emitted in the same conditions where `end` is + emitted. Emitted after `'end'`. +- `finish` An end-ish event that follows the same logic as `end` + and is emitted in the same conditions where `end` is emitted. + Emitted after `'prefinish'`. +- `close` An indication that an underlying resource has been + released. Minipass does not emit this event, but will defer it + until after `end` has been emitted, since it throws off some + stream libraries otherwise. +- `drain` Emitted when the internal buffer empties, and it is + again suitable to `write()` into the stream. +- `readable` Emitted when data is buffered and ready to be read + by a consumer. +- `resume` Emitted when stream changes state from buffering to + flowing mode. (Ie, when `resume` is called, `pipe` is called, + or a `data` event listener is added.) + +### Static Methods + +- `Minipass.isStream(stream)` Returns `true` if the argument is a + stream, and false otherwise. To be considered a stream, the + object must be either an instance of Minipass, or an + EventEmitter that has either a `pipe()` method, or both + `write()` and `end()` methods. (Pretty much any stream in + node-land will return `true` for this.) + +## EXAMPLES + +Here are some examples of things you can do with Minipass +streams. + +### simple "are you done yet" promise + +```js +mp.promise().then( + () => { + // stream is finished + }, + er => { + // stream emitted an error + } +) +``` + +### collecting + +```js +mp.collect().then(all => { + // all is an array of all the data emitted + // encoding is supported in this case, so + // so the result will be a collection of strings if + // an encoding is specified, or buffers/objects if not. + // + // In an async function, you may do + // const data = await stream.collect() +}) +``` + +### collecting into a single blob + +This is a bit slower because it concatenates the data into one +chunk for you, but if you're going to do it yourself anyway, it's +convenient this way: + +```js +mp.concat().then(onebigchunk => { + // onebigchunk is a string if the stream + // had an encoding set, or a buffer otherwise. +}) +``` + +### iteration + +You can iterate over streams synchronously or asynchronously in +platforms that support it. + +Synchronous iteration will end when the currently available data +is consumed, even if the `end` event has not been reached. In +string and buffer mode, the data is concatenated, so unless +multiple writes are occurring in the same tick as the `read()`, +sync iteration loops will generally only have a single iteration. + +To consume chunks in this way exactly as they have been written, +with no flattening, create the stream with the `{ objectMode: +true }` option. + +```js +const mp = new Minipass({ objectMode: true }) +mp.write('a') +mp.write('b') +for (let letter of mp) { + console.log(letter) // a, b +} +mp.write('c') +mp.write('d') +for (let letter of mp) { + console.log(letter) // c, d +} +mp.write('e') +mp.end() +for (let letter of mp) { + console.log(letter) // e +} +for (let letter of mp) { + console.log(letter) // nothing +} +``` + +Asynchronous iteration will continue until the end event is reached, +consuming all of the data. + +```js +const mp = new Minipass({ encoding: 'utf8' }) + +// some source of some data +let i = 5 +const inter = setInterval(() => { + if (i-- > 0) mp.write(Buffer.from('foo\n', 'utf8')) + else { + mp.end() + clearInterval(inter) + } +}, 100) + +// consume the data with asynchronous iteration +async function consume() { + for await (let chunk of mp) { + console.log(chunk) + } + return 'ok' +} + +consume().then(res => console.log(res)) +// logs `foo\n` 5 times, and then `ok` +``` + +### subclass that `console.log()`s everything written into it + +```js +class Logger extends Minipass { + write(chunk, encoding, callback) { + console.log('WRITE', chunk, encoding) + return super.write(chunk, encoding, callback) + } + end(chunk, encoding, callback) { + console.log('END', chunk, encoding) + return super.end(chunk, encoding, callback) + } +} + +someSource.pipe(new Logger()).pipe(someDest) +``` + +### same thing, but using an inline anonymous class + +```js +// js classes are fun +someSource + .pipe( + new (class extends Minipass { + emit(ev, ...data) { + // let's also log events, because debugging some weird thing + console.log('EMIT', ev) + return super.emit(ev, ...data) + } + write(chunk, encoding, callback) { + console.log('WRITE', chunk, encoding) + return super.write(chunk, encoding, callback) + } + end(chunk, encoding, callback) { + console.log('END', chunk, encoding) + return super.end(chunk, encoding, callback) + } + })() + ) + .pipe(someDest) +``` + +### subclass that defers 'end' for some reason + +```js +class SlowEnd extends Minipass { + emit(ev, ...args) { + if (ev === 'end') { + console.log('going to end, hold on a sec') + setTimeout(() => { + console.log('ok, ready to end now') + super.emit('end', ...args) + }, 100) + return true + } else { + return super.emit(ev, ...args) + } + } +} +``` + +### transform that creates newline-delimited JSON + +```js +class NDJSONEncode extends Minipass { + write(obj, cb) { + try { + // JSON.stringify can throw, emit an error on that + return super.write(JSON.stringify(obj) + '\n', 'utf8', cb) + } catch (er) { + this.emit('error', er) + } + } + end(obj, cb) { + if (typeof obj === 'function') { + cb = obj + obj = undefined + } + if (obj !== undefined) { + this.write(obj) + } + return super.end(cb) + } +} +``` + +### transform that parses newline-delimited JSON + +```js +class NDJSONDecode extends Minipass { + constructor(options) { + // always be in object mode, as far as Minipass is concerned + super({ objectMode: true }) + this._jsonBuffer = '' + } + write(chunk, encoding, cb) { + if ( + typeof chunk === 'string' && + typeof encoding === 'string' && + encoding !== 'utf8' + ) { + chunk = Buffer.from(chunk, encoding).toString() + } else if (Buffer.isBuffer(chunk)) { + chunk = chunk.toString() + } + if (typeof encoding === 'function') { + cb = encoding + } + const jsonData = (this._jsonBuffer + chunk).split('\n') + this._jsonBuffer = jsonData.pop() + for (let i = 0; i < jsonData.length; i++) { + try { + // JSON.parse can throw, emit an error on that + super.write(JSON.parse(jsonData[i])) + } catch (er) { + this.emit('error', er) + continue + } + } + if (cb) cb() + } +} +``` diff --git a/node_modules/minipass/package.json b/node_modules/minipass/package.json new file mode 100644 index 0000000000000000000000000000000000000000..800f215cb02c01bbf5cb206ecfcac6783fbcfd9e --- /dev/null +++ b/node_modules/minipass/package.json @@ -0,0 +1,77 @@ +{ + "name": "minipass", + "version": "7.1.3", + "description": "minimal implementation of a PassThrough stream", + "main": "./dist/commonjs/index.js", + "types": "./dist/commonjs/index.d.ts", + "module": "./dist/esm/index.js", + "type": "module", + "tshy": { + "selfLink": false, + "compiler": "tsgo", + "exports": { + "./package.json": "./package.json", + ".": "./src/index.ts" + } + }, + "exports": { + "./package.json": "./package.json", + ".": { + "import": { + "types": "./dist/esm/index.d.ts", + "default": "./dist/esm/index.js" + }, + "require": { + "types": "./dist/commonjs/index.d.ts", + "default": "./dist/commonjs/index.js" + } + } + }, + "files": [ + "dist" + ], + "scripts": { + "preversion": "npm test", + "postversion": "npm publish", + "prepublishOnly": "git push origin --follow-tags", + "prepare": "tshy", + "pretest": "npm run prepare", + "presnap": "npm run prepare", + "test": "tap", + "snap": "tap", + "format": "prettier --write . --loglevel warn", + "typedoc": "typedoc --tsconfig .tshy/esm.json ./src/*.ts" + }, + "prettier": { + "semi": false, + "printWidth": 75, + "tabWidth": 2, + "useTabs": false, + "singleQuote": true, + "jsxSingleQuote": false, + "bracketSameLine": true, + "arrowParens": "avoid", + "endOfLine": "lf" + }, + "devDependencies": { + "@types/end-of-stream": "^1.4.2", + "@types/node": "^25.2.3", + "end-of-stream": "^1.4.0", + "node-abort-controller": "^3.1.1", + "prettier": "^3.8.1", + "tap": "^21.6.1", + "through2": "^2.0.3", + "tshy": "^3.3.2", + "typedoc": "^0.28.17" + }, + "repository": "https://github.com/isaacs/minipass", + "keywords": [ + "passthrough", + "stream" + ], + "author": "Isaac Z. Schlueter (http://blog.izs.me/)", + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=16 || 14 >=14.17" + } +} diff --git a/node_modules/mkdirp-classic/LICENSE b/node_modules/mkdirp-classic/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f6b3a0d12f55190fbe06bf667c102d5116e5a0bb --- /dev/null +++ b/node_modules/mkdirp-classic/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2020 James Halliday (mail@substack.net) and Mathias Buus + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/mkdirp-classic/README.md b/node_modules/mkdirp-classic/README.md new file mode 100644 index 0000000000000000000000000000000000000000..be5ac938dd9d95969a633b13f9a23808eb6a5583 --- /dev/null +++ b/node_modules/mkdirp-classic/README.md @@ -0,0 +1,18 @@ +# mkdirp-classic + +Just a non-deprecated mirror of [mkdirp 0.5.2](https://github.com/substack/node-mkdirp/tree/0.5.1) +for use in modules where we depend on the non promise interface. + +``` +npm install mkdirp-classic +``` + +## Usage + +``` js +// See the above link +``` + +## License + +MIT diff --git a/node_modules/mkdirp-classic/index.js b/node_modules/mkdirp-classic/index.js new file mode 100644 index 0000000000000000000000000000000000000000..6ce241b58c100f718d59901eac3d4892abb8c360 --- /dev/null +++ b/node_modules/mkdirp-classic/index.js @@ -0,0 +1,98 @@ +var path = require('path'); +var fs = require('fs'); +var _0777 = parseInt('0777', 8); + +module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; + +function mkdirP (p, opts, f, made) { + if (typeof opts === 'function') { + f = opts; + opts = {}; + } + else if (!opts || typeof opts !== 'object') { + opts = { mode: opts }; + } + + var mode = opts.mode; + var xfs = opts.fs || fs; + + if (mode === undefined) { + mode = _0777 & (~process.umask()); + } + if (!made) made = null; + + var cb = f || function () {}; + p = path.resolve(p); + + xfs.mkdir(p, mode, function (er) { + if (!er) { + made = made || p; + return cb(null, made); + } + switch (er.code) { + case 'ENOENT': + mkdirP(path.dirname(p), opts, function (er, made) { + if (er) cb(er, made); + else mkdirP(p, opts, cb, made); + }); + break; + + // In the case of any other error, just see if there's a dir + // there already. If so, then hooray! If not, then something + // is borked. + default: + xfs.stat(p, function (er2, stat) { + // if the stat fails, then that's super weird. + // let the original error be the failure reason. + if (er2 || !stat.isDirectory()) cb(er, made) + else cb(null, made); + }); + break; + } + }); +} + +mkdirP.sync = function sync (p, opts, made) { + if (!opts || typeof opts !== 'object') { + opts = { mode: opts }; + } + + var mode = opts.mode; + var xfs = opts.fs || fs; + + if (mode === undefined) { + mode = _0777 & (~process.umask()); + } + if (!made) made = null; + + p = path.resolve(p); + + try { + xfs.mkdirSync(p, mode); + made = made || p; + } + catch (err0) { + switch (err0.code) { + case 'ENOENT' : + made = sync(path.dirname(p), opts, made); + sync(p, opts, made); + break; + + // In the case of any other error, just see if there's a dir + // there already. If so, then hooray! If not, then something + // is borked. + default: + var stat; + try { + stat = xfs.statSync(p); + } + catch (err1) { + throw err0; + } + if (!stat.isDirectory()) throw err0; + break; + } + } + + return made; +}; diff --git a/node_modules/mkdirp-classic/package.json b/node_modules/mkdirp-classic/package.json new file mode 100644 index 0000000000000000000000000000000000000000..c8b5407b92690d32cdb393f9d82667668b09dcb9 --- /dev/null +++ b/node_modules/mkdirp-classic/package.json @@ -0,0 +1,18 @@ +{ + "name": "mkdirp-classic", + "version": "0.5.3", + "description": "Mirror of mkdirp 0.5.2", + "main": "index.js", + "dependencies": {}, + "devDependencies": {}, + "repository": { + "type": "git", + "url": "https://github.com/mafintosh/mkdirp-classic.git" + }, + "author": "Mathias Buus (@mafintosh)", + "license": "MIT", + "bugs": { + "url": "https://github.com/mafintosh/mkdirp-classic/issues" + }, + "homepage": "https://github.com/mafintosh/mkdirp-classic" +} diff --git a/node_modules/ms/index.js b/node_modules/ms/index.js new file mode 100644 index 0000000000000000000000000000000000000000..ea734fb73820316ed1c0f6a2f6e96dce0e3eb6f0 --- /dev/null +++ b/node_modules/ms/index.js @@ -0,0 +1,162 @@ +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var w = d * 7; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + +module.exports = function (val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'weeks': + case 'week': + case 'w': + return n * w; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + 'd'; + } + if (msAbs >= h) { + return Math.round(ms / h) + 'h'; + } + if (msAbs >= m) { + return Math.round(ms / m) + 'm'; + } + if (msAbs >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, 'day'); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, 'hour'); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, 'minute'); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, 'second'); + } + return ms + ' ms'; +} + +/** + * Pluralization helper. + */ + +function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); +} diff --git a/node_modules/ms/license.md b/node_modules/ms/license.md new file mode 100644 index 0000000000000000000000000000000000000000..fa5d39b6213f8a5e142b643575f99d9149cc71c6 --- /dev/null +++ b/node_modules/ms/license.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2020 Vercel, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/ms/package.json b/node_modules/ms/package.json new file mode 100644 index 0000000000000000000000000000000000000000..49971890df8e2b9a4a5f4909fbd6678b862d8a50 --- /dev/null +++ b/node_modules/ms/package.json @@ -0,0 +1,38 @@ +{ + "name": "ms", + "version": "2.1.3", + "description": "Tiny millisecond conversion utility", + "repository": "vercel/ms", + "main": "./index", + "files": [ + "index.js" + ], + "scripts": { + "precommit": "lint-staged", + "lint": "eslint lib/* bin/*", + "test": "mocha tests.js" + }, + "eslintConfig": { + "extends": "eslint:recommended", + "env": { + "node": true, + "es6": true + } + }, + "lint-staged": { + "*.js": [ + "npm run lint", + "prettier --single-quote --write", + "git add" + ] + }, + "license": "MIT", + "devDependencies": { + "eslint": "4.18.2", + "expect.js": "0.3.1", + "husky": "0.14.3", + "lint-staged": "5.0.0", + "mocha": "4.0.1", + "prettier": "2.0.5" + } +} diff --git a/node_modules/ms/readme.md b/node_modules/ms/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..0fc1abb3b8e30a3ab97023d243127c75b1b3a4d7 --- /dev/null +++ b/node_modules/ms/readme.md @@ -0,0 +1,59 @@ +# ms + +![CI](https://github.com/vercel/ms/workflows/CI/badge.svg) + +Use this package to easily convert various time formats to milliseconds. + +## Examples + +```js +ms('2 days') // 172800000 +ms('1d') // 86400000 +ms('10h') // 36000000 +ms('2.5 hrs') // 9000000 +ms('2h') // 7200000 +ms('1m') // 60000 +ms('5s') // 5000 +ms('1y') // 31557600000 +ms('100') // 100 +ms('-3 days') // -259200000 +ms('-1h') // -3600000 +ms('-200') // -200 +``` + +### Convert from Milliseconds + +```js +ms(60000) // "1m" +ms(2 * 60000) // "2m" +ms(-3 * 60000) // "-3m" +ms(ms('10 hours')) // "10h" +``` + +### Time Format Written-Out + +```js +ms(60000, { long: true }) // "1 minute" +ms(2 * 60000, { long: true }) // "2 minutes" +ms(-3 * 60000, { long: true }) // "-3 minutes" +ms(ms('10 hours'), { long: true }) // "10 hours" +``` + +## Features + +- Works both in [Node.js](https://nodejs.org) and in the browser +- If a number is supplied to `ms`, a string with a unit is returned +- If a string that contains the number is supplied, it returns it as a number (e.g.: it returns `100` for `'100'`) +- If you pass a string with a number and a valid unit, the number of equivalent milliseconds is returned + +## Related Packages + +- [ms.macro](https://github.com/knpwrs/ms.macro) - Run `ms` as a macro at build-time. + +## Caught a Bug? + +1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device +2. Link the package to the global module directory: `npm link` +3. Within the module you want to test your local development instance of ms, just link it to the dependencies: `npm link ms`. Instead of the default one from npm, Node.js will now use your clone of ms! + +As always, you can run the tests using: `npm test` diff --git a/node_modules/msw/LICENSE.md b/node_modules/msw/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..9459df1cbcb24db751944caadf64cfd22a3d470e --- /dev/null +++ b/node_modules/msw/LICENSE.md @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018–present Artem Zakharchenko + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/msw/README.md b/node_modules/msw/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ea4a6ad68ae2b9f76dbc320e381b87589280584c --- /dev/null +++ b/node_modules/msw/README.md @@ -0,0 +1,279 @@ +
    + +

    + The Mock Service Worker logo +

    + +

    Mock Service Worker

    +

    Industry standard API mocking for JavaScript.

    + +

    + Join our Discord server +

    + +
    +
    + +## Features + +- **Seamless**. A dedicated layer of requests interception at your disposal. Keep your application's code and tests unaware of whether something is mocked or not. +- **Deviation-free**. Request the same production resources and test the actual behavior of your app. Augment an existing API, or design it as you go when there is none. +- **Familiar & Powerful**. Use [Express](https://github.com/expressjs/express)-like routing syntax to intercept requests. Use parameters, wildcards, and regular expressions to match requests, and respond with necessary status codes, headers, cookies, delays, or completely custom resolvers. + +--- + +> "_I found MSW and was thrilled that not only could I still see the mocked responses in my DevTools, but that the mocks didn't have to be written in a Service Worker and could instead live alongside the rest of my app. This made it silly easy to adopt. The fact that I can use it for testing as well makes MSW a huge productivity booster._" +> +> — [Kent C. Dodds](https://twitter.com/kentcdodds) + +## Documentation + +This README will give you a brief overview of the library, but there's no better place to start with Mock Service Worker than its official documentation. + +- [Documentation](https://mswjs.io/docs) +- [**Quick start**](https://mswjs.io/docs/quick-start) +- [FAQ](https://mswjs.io/docs/faq) + +## Examples + +- See the list of [**Usage examples**](https://github.com/mswjs/examples) + +## Courses + +We've partnered with Egghead to bring you quality paid materials to learn the best practices of API mocking on the web. Please give them a shot! The royalties earned from them help sustain the project's development. Thank you. + +- 🚀 [**Mocking REST and GraphQL APIs with Mock Service Worker**](https://egghead.io/courses/mock-rest-and-graphql-apis-with-mock-service-worker-8d471ece?af=8mci9b) +- 🔌 [Mocking (and testing) WebSocket APIs with Mock Service Worker](https://egghead.io/courses/mocking-websocket-apis-with-mock-service-worker-9933b7f5) + +## Browser + +- [Learn more about using MSW in a browser](https://mswjs.io/docs/integrations/browser) +- [`setupWorker` API](https://mswjs.io/docs/api/setup-worker) + +### How does it work? + +In-browser usage is what sets Mock Service Worker apart from other tools. Utilizing the [Service Worker API](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API), which can intercept requests for the purpose of caching, Mock Service Worker responds to intercepted requests with your mock definition on the network level. This way your application knows nothing about the mocking. + +**Take a look at this quick presentation on how Mock Service Worker functions in a browser:** + +[![What is Mock Service Worker?](https://raw.githubusercontent.com/mswjs/msw/main/media/msw-video-thumbnail.jpg)](https://youtu.be/HcQCqboatZk) + +### How is it different? + +- This library intercepts requests on the network level, which means _after_ they have been performed and "left" your application. As a result, the entirety of your code runs, giving you more confidence when mocking; +- Imagine your application as a box. Every API mocking library out there opens your box and removes the part that does the request, placing a blackbox in its stead. Mock Service Worker leaves your box intact, 1-1 as it is in production. Instead, MSW lives in a separate box next to yours; +- No more stubbing of `fetch`, `axios`, `react-query`, you-name-it; +- You can reuse the same mock definition for the unit, integration, and E2E testing. Did we mention local development and debugging? Yep. All running against the same network description without the need for adapters or bloated configurations. + +### Usage example + +```js +// 1. Import the library. +import { http, HttpResponse } from 'msw' +import { setupWorker } from 'msw/browser' + +// 2. Describe network behavior with request handlers. +const worker = setupWorker( + http.get('https://github.com/octocat', ({ request, params, cookies }) => { + return HttpResponse.json( + { + message: 'Mocked response', + }, + { + status: 202, + statusText: 'Mocked status', + }, + ) + }), +) + +// 3. Start mocking by starting the Service Worker. +await worker.start() +``` + +Performing a `GET https://github.com/octocat` request in your application will result into a mocked response that you can inspect in your browser's "Network" tab: + +![Chrome DevTools Network screenshot with the request mocked](https://github.com/mswjs/msw/blob/main/media/msw-quick-look-network.png?raw=true) + +> **Tip:** Did you know that although Service Worker runs in a separate thread, your request handlers execute entirely on the client? This way you can use the same languages, like TypeScript, third-party libraries, and internal logic to create the mocks you need. + +## Node.js + +- [Learn more about using MSW in Node.js](https://mswjs.io/docs/integrations/node) +- [`setupServer` API](https://mswjs.io/docs/api/setup-server) + +### How does it work? + +There's no such thing as Service Workers in Node.js. Instead, MSW implements a [low-level interception algorithm](https://github.com/mswjs/interceptors) that can utilize the very same request handlers you have for the browser. This blends the boundary between environments, allowing you to focus on your network behaviors. + +### How is it different? + +- Does not stub `fetch`, `axios`, etc. As a result, your tests know _nothing_ about mocking; +- You can reuse the same request handlers for local development and debugging, as well as for testing. Truly a single source of truth for your network behavior across all environments and all tools. + +### Usage example + +Here's an example of using Mock Service Worker while developing your Express server: + +```js +import express from 'express' +import { http, HttpResponse } from 'msw' +import { setupServer } from 'msw/node' + +const app = express() +const server = setupServer() + +app.get( + '/checkout/session', + server.boundary((req, res) => { + // Describe the network for this Express route. + server.use( + http.get( + 'https://api.stripe.com/v1/checkout/sessions/:id', + ({ params }) => { + return HttpResponse.json({ + id: params.id, + mode: 'payment', + status: 'open', + }) + }, + ), + ) + + // Continue with processing the checkout session. + handleSession(req, res) + }), +) +``` + +> This example showcases [`server.boundary()`](https://mswjs.io/docs/api/setup-server/boundary) to scope request interception to a particular closure, which is extremely handy! + +## Sponsors + +Mock Service Worker is trusted by hundreds of thousands of engineers around the globe. It's used by companies like Google, Microsoft, Spotify, Amazon, Netflix, and countless others. Despite that, it remains a hobby project maintained in a spare time and has no opportunity to financially support even a single full-time contributor. + +**You can change that!** Consider [sponsoring the effort](https://github.com/sponsors/mswjs) behind one of the most innovative approaches around API mocking. Raise a topic of open source sponsorships with your boss and colleagues. Let's build sustainable open source together! + +### Golden sponsors + +> Become our _golden sponsor_ and get featured right here, enjoying other perks like issue prioritization and a personal consulting session with us. +> +> **Learn more on our [GitHub Sponsors profile](https://github.com/sponsors/mswjs)**. + +
    + + + + + + + + + + + +
    + + + + GitHub + + + + + Codacy + + + + Workleap + + + + Chromatic + +
    + + StackBlitz + +
    + +### Silver sponsors + +> Become our _silver sponsor_ and get your profile image and link featured right here. +> +> **Learn more on our [GitHub Sponsors profile](https://github.com/sponsors/mswjs)**. + +
    + + + + + + + +
    + + Replay + + + + Codemod + + + + Ryan Magoon + +
    + +### Bronze sponsors + +> Become our _bronze sponsor_ and get your profile image and link featured in this section. +> +> **Learn more on our [GitHub Sponsors profile](https://github.com/sponsors/mswjs)**. + +
    + + + + + + + +
    + + Materialize + + + + Trigger.dev + + + + Vital + +
    + +## Awards & mentions + +We've been extremely humbled to receive awards and mentions from the community for all the innovation and reach Mock Service Worker brings to the JavaScript ecosystem. + + + + + + + + + + +
    + Technology Radar + +

    Solution Worth Pursuing

    +

    Technology Radar (2020–2021)

    +
    + Open Source Awards 2020 + +

    The Most Exciting Use of Technology

    +

    Open Source Awards (2020)

    +
    diff --git a/node_modules/msw/browser/package.json b/node_modules/msw/browser/package.json new file mode 100644 index 0000000000000000000000000000000000000000..1ac076474ac703542b8a4c96ff9e9510ec806371 --- /dev/null +++ b/node_modules/msw/browser/package.json @@ -0,0 +1,31 @@ +{ + "type": "module", + "main": "../lib/browser/index.js", + "module": "../lib/browser/index.mjs", + "types": "../lib/browser/index.d.ts", + "exports": { + ".": { + "module-sync": { + "types": "./../lib/browser/index.d.mts", + "default": "./../lib/browser/index.mjs" + }, + "module": { + "types": "./../lib/browser/index.d.mts", + "default": "./../lib/browser/index.mjs" + }, + "browser": { + "types": "./../lib/browser/index.d.mts", + "default": "./../lib/browser/index.mjs" + }, + "import": { + "types": "./../lib/browser/index.d.mts", + "default": "./../lib/browser/index.mjs" + }, + "default": { + "types": "./../lib/browser/index.d.ts", + "default": "./../lib/browser/index.js" + } + }, + "./package.json": "./package.json" + } +} diff --git a/node_modules/msw/cli/index.js b/node_modules/msw/cli/index.js new file mode 100644 index 0000000000000000000000000000000000000000..e22bd0e916cb1116c10b5294204bd1350999dc5d --- /dev/null +++ b/node_modules/msw/cli/index.js @@ -0,0 +1,35 @@ +#!/usr/bin/env node +import yargs from 'yargs' +import { init } from './init.js' + +// eslint-disable-next-line @typescript-eslint/no-unused-expressions +yargs(process.argv.slice(2)) + .usage('$0 [args]') + .command( + 'init', + 'Initializes Mock Service Worker at the specified directory', + (yargs) => { + yargs + .positional('publicDir', { + type: 'string', + description: 'Relative path to the public directory', + demandOption: false, + normalize: true, + }) + .option('save', { + type: 'boolean', + description: 'Save the worker directory in your package.json', + }) + .option('cwd', { + type: 'string', + description: 'Custom current worker directory', + normalize: true, + }) + .example('msw init') + .example('msw init ./public') + .example('msw init ./static --save') + }, + init, + ) + .demandCommand() + .help().argv diff --git a/node_modules/msw/cli/init.js b/node_modules/msw/cli/init.js new file mode 100644 index 0000000000000000000000000000000000000000..4c22d11f309d8db8b2075c2dd0d65454cbd43196 --- /dev/null +++ b/node_modules/msw/cli/init.js @@ -0,0 +1,226 @@ +import fs from 'node:fs' +import path from 'node:path' +import colors from 'picocolors' +import confirm from '@inquirer/confirm' +import { invariant } from './invariant.js' +import { SERVICE_WORKER_BUILD_PATH } from '../config/constants.js' + +export async function init(args) { + const CWD = args.cwd || process.cwd() + const publicDir = args._[1] ? normalizePath(args._[1]) : undefined + + const packageJsonPath = path.resolve(CWD, 'package.json') + const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')) + const savedWorkerDirectories = Array.prototype + .concat((packageJson.msw && packageJson.msw.workerDirectory) || []) + .map(normalizePath) + + if (publicDir) { + // If the public directory was provided, copy the worker script + // to that directory only. Even if there are paths stored in "msw.workerDirectory", + // those will not be touched. + await copyWorkerScript(publicDir, CWD) + const relativePublicDir = path.relative(CWD, publicDir) + printSuccessMessage([publicDir]) + + if (args.save) { + // Only save the public path if it's not already saved in "package.json". + if (!savedWorkerDirectories.includes(relativePublicDir)) { + saveWorkerDirectory(packageJsonPath, relativePublicDir) + } + } + // Explicitly check if "save" was not provided (was null). + // You can also provide the "--no-save" option, and then "args.save" + // will equal to false. + else if (args.save == null) { + // eslint-disable-next-line no-console + console.log(`\ + ${colors.cyan( + 'INFO', + )} In order to ease the future updates to the worker script, + we recommend saving the path to the worker directory in your package.json.`) + + // If the "--save" flag was not provided, prompt to save + // the public path. + promptWorkerDirectoryUpdate( + `Do you wish to save "${relativePublicDir}" as the worker directory?`, + packageJsonPath, + relativePublicDir, + ) + } + + return + } + + // Calling "init" without a public directory but with the "--save" flag is a no-op. + invariant( + args.save == null, + 'Failed to copy the worker script: cannot call the "init" command without a public directory but with the "--save" flag. Either drop the "--save" flag to copy the worker script to all paths listed in "msw.workerDirectory", or add an explicit public directory to the command, like "npx msw init ./public".', + ) + + // If the public directory was not provided, check any existing + // paths in "msw.workerDirectory". When called without the public + // directory, the "init" command must copy the worker script + // to all the paths stored in "msw.workerDirectory". + if (savedWorkerDirectories.length > 0) { + const copyResults = await Promise.allSettled( + savedWorkerDirectories.map((destination) => { + return copyWorkerScript(destination, CWD).catch((error) => { + // Inject the absolute destination path onto the copy function rejections + // so it's available in the failed paths array below. + throw [toAbsolutePath(destination, CWD), error] + }) + }), + ) + const successfulPaths = copyResults + .filter((result) => result.status === 'fulfilled') + .map((result) => result.value) + const failedPathsWithErrors = copyResults + .filter((result) => result.status === 'rejected') + .map((result) => result.reason) + + // Notify about failed copies, if any. + if (failedPathsWithErrors.length > 0) { + printFailureMessage(failedPathsWithErrors) + } + + // Notify about successful copies, if any. + if (successfulPaths.length > 0) { + printSuccessMessage(successfulPaths) + } + } +} + +/** + * @param {string} maybeAbsolutePath + * @param {string} cwd + * @returns {string} + */ +function toAbsolutePath(maybeAbsolutePath, cwd) { + return path.isAbsolute(maybeAbsolutePath) + ? maybeAbsolutePath + : path.resolve(cwd, maybeAbsolutePath) +} + +/** + * @param {string} destination + * @param {string} cwd + * @returns {Promise} + */ +async function copyWorkerScript(destination, cwd) { + // When running as a part of "postinstall" script, "cwd" equals the library's directory. + // The "postinstall" script resolves the right absolute public directory path. + const absolutePublicDir = toAbsolutePath(destination, cwd) + + if (!fs.existsSync(absolutePublicDir)) { + await fs.promises + .mkdir(absolutePublicDir, { recursive: true }) + .catch((error) => { + throw new Error( + invariant( + false, + 'Failed to copy the worker script at "%s": directory does not exist and could not be created.\nMake sure to include a relative path to the public directory of your application.\n\nSee the original error below:\n\n%s', + absolutePublicDir, + error, + ), + ) + }) + } + + // eslint-disable-next-line no-console + console.log('Copying the worker script at "%s"...', absolutePublicDir) + + const workerFilename = path.basename(SERVICE_WORKER_BUILD_PATH) + const workerDestinationPath = path.resolve(absolutePublicDir, workerFilename) + + fs.copyFileSync(SERVICE_WORKER_BUILD_PATH, workerDestinationPath) + + return workerDestinationPath +} + +/** + * @param {Array} paths + */ +function printSuccessMessage(paths) { + // eslint-disable-next-line no-console + console.log(` +${colors.green('Worker script successfully copied!')} +${paths.map((path) => colors.gray(` - ${path}\n`))} +Continue by describing the network in your application: + + +${colors.red(colors.bold('https://mswjs.io/docs/quick-start'))} +`) +} + +function printFailureMessage(pathsWithErrors) { + // eslint-disable-next-line no-console + console.error(`\ +${colors.red('Copying the worker script failed at following paths:')} +${pathsWithErrors + .map(([path, error]) => colors.gray(` - ${path}`) + '\n' + ` ${error}`) + .join('\n\n')} + `) +} + +/** + * @param {string} packageJsonPath + * @param {string} publicDir + */ +function saveWorkerDirectory(packageJsonPath, publicDir) { + const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')) + + // eslint-disable-next-line no-console + console.log( + colors.gray('Updating "msw.workerDirectory" at "%s"...'), + packageJsonPath, + ) + + const prevWorkerDirectory = Array.prototype.concat( + (packageJson.msw && packageJson.msw.workerDirectory) || [], + ) + const nextWorkerDirectory = Array.from( + new Set(prevWorkerDirectory).add(publicDir), + ) + + const nextPackageJson = Object.assign({}, packageJson, { + msw: { + workerDirectory: nextWorkerDirectory, + }, + }) + + fs.writeFileSync( + packageJsonPath, + JSON.stringify(nextPackageJson, null, 2), + 'utf8', + ) +} + +/** + * @param {string} message + * @param {string} packageJsonPath + * @param {string} publicDir + * @returns {void} + */ +function promptWorkerDirectoryUpdate(message, packageJsonPath, publicDir) { + return confirm({ + theme: { + prefix: colors.yellowBright('?'), + }, + message, + }).then((answer) => { + if (answer) { + saveWorkerDirectory(packageJsonPath, publicDir) + } + }) +} + +/** + * Normalizes the given path, replacing ambiguous path separators + * with the platform-specific path separator. + * @param {string} input Path to normalize. + * @returns {string} + */ +function normalizePath(input) { + return input.replace(/[\\|/]+/g, path.sep) +} diff --git a/node_modules/msw/cli/invariant.js b/node_modules/msw/cli/invariant.js new file mode 100644 index 0000000000000000000000000000000000000000..6c756ade660139ce309d596d5eae54d1ee411aff --- /dev/null +++ b/node_modules/msw/cli/invariant.js @@ -0,0 +1,9 @@ +import colors from 'picocolors' + +export function invariant(predicate, message, ...args) { + if (!predicate) { + // eslint-disable-next-line no-console + console.error(colors.red(message), ...args) + process.exit(1) + } +} diff --git a/node_modules/msw/cli/package.json b/node_modules/msw/cli/package.json new file mode 100644 index 0000000000000000000000000000000000000000..3dbc1ca591c0557e35b6004aeba250e6a70b56e3 --- /dev/null +++ b/node_modules/msw/cli/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} diff --git a/node_modules/msw/config/constants.js b/node_modules/msw/config/constants.js new file mode 100644 index 0000000000000000000000000000000000000000..7fc606823caa1f49878330e95cdfaf0681ec0dd7 --- /dev/null +++ b/node_modules/msw/config/constants.js @@ -0,0 +1,13 @@ +import url from 'node:url' +import path from 'node:path' + +export const SERVICE_WORKER_SOURCE_PATH = url.fileURLToPath( + new URL('../src/mockServiceWorker.js', import.meta.url), +) + +export const SERVICE_WORKER_BUILD_PATH = url.fileURLToPath( + new URL( + path.join('../lib', path.basename(SERVICE_WORKER_SOURCE_PATH)), + import.meta.url, + ), +) diff --git a/node_modules/msw/config/package.json b/node_modules/msw/config/package.json new file mode 100644 index 0000000000000000000000000000000000000000..3dbc1ca591c0557e35b6004aeba250e6a70b56e3 --- /dev/null +++ b/node_modules/msw/config/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} diff --git a/node_modules/msw/config/scripts/postinstall.js b/node_modules/msw/config/scripts/postinstall.js new file mode 100644 index 0000000000000000000000000000000000000000..7906d93b95b171b3efb0f74da45fe1880a148a7c --- /dev/null +++ b/node_modules/msw/config/scripts/postinstall.js @@ -0,0 +1,36 @@ +import fs from 'node:fs' +import path from 'node:path' +import { execFileSync } from 'node:child_process' + +// When executing the "postinstall" script, the "process.cwd" equals +// the package directory, not the parent project where the package is installed. +// NPM stores the parent project directory in the "INIT_CWD" env variable. +const parentPackageCwd = process.env.INIT_CWD + +function postInstall() { + const packageJson = JSON.parse( + fs.readFileSync(path.resolve(parentPackageCwd, 'package.json'), 'utf8'), + ) + + if (!packageJson.msw || !packageJson.msw.workerDirectory) { + return + } + + const cliExecutable = path.resolve(process.cwd(), 'cli/index.js') + + try { + /** + * @note Call the "init" command directly. It will now copy the worker script + * to all saved paths in "msw.workerDirectory" + */ + execFileSync(process.execPath, [cliExecutable, 'init'], { + cwd: parentPackageCwd, + }) + } catch (error) { + console.error( + `[MSW] Failed to automatically update the worker script.\n\n${error}`, + ) + } +} + +postInstall() diff --git a/node_modules/msw/lib/browser/index.d.mts b/node_modules/msw/lib/browser/index.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..70e5f95a1eec3b3737c663af70fd3e132d5331e7 --- /dev/null +++ b/node_modules/msw/lib/browser/index.d.mts @@ -0,0 +1,112 @@ +import { AnyHandler } from "../core/experimental/handlers-controller.mjs"; +import { SharedOptions, LifeCycleEventEmitter } from "../core/sharedOptions.mjs"; +import { HttpNetworkFrameEventMap } from "../core/experimental/frames/http-frame.mjs"; +import { WebSocketNetworkFrameEventMap } from "../core/experimental/frames/websocket-frame.mjs"; + +type FindWorker = (scriptUrl: string, mockServiceWorkerUrl: string) => boolean; +interface StartOptions extends SharedOptions { + /** + * Service Worker registration options. + */ + serviceWorker?: { + /** + * Custom url to the worker script. + * @default "/mockServiceWorker.js" + */ + url?: string; + options?: RegistrationOptions; + }; + /** + * Disables the logging of the intercepted requests + * into browser's console. + * @default false + */ + quiet?: boolean; + /** + * Defers any network requests until the Service Worker + * instance is activated. + * @default true + * @deprecated + * Please use a proper browser integration instead. + * @see https://mswjs.io/docs/integrations/browser + */ + waitUntilReady?: boolean; + /** + * A custom lookup function to find a Mock Service Worker in the list + * of all registered Service Workers on the page. + */ + findWorker?: FindWorker; +} +type StartReturnType = Promise; +type StopHandler = () => void; +interface SetupWorker { + /** + * Registers and activates the mock Service Worker. + * + * @see {@link https://mswjs.io/docs/api/setup-worker/start `worker.start()` API reference} + */ + start: (options?: StartOptions) => StartReturnType; + /** + * Stops requests interception for the current client. + * + * @see {@link https://mswjs.io/docs/api/setup-worker/stop `worker.stop()` API reference} + */ + stop: StopHandler; + /** + * Prepends given request handlers to the list of existing handlers. + * @param {Array} handlers List of runtime request handlers. + * + * @see {@link https://mswjs.io/docs/api/setup-worker/use `worker.use()` API reference} + */ + use: (...handlers: Array) => void; + /** + * Marks all request handlers that respond using `res.once()` as unused. + * + * @see {@link https://mswjs.io/docs/api/setup-worker/restore-handlers `worker.restoreHandlers()` API reference} + */ + restoreHandlers: () => void; + /** + * Resets request handlers to the initial list given to the `setupWorker` call, or to the explicit next request handlers list, if given. + * @param {Array} nextHandlers List of the new initial request handlers. + * + * @see {@link https://mswjs.io/docs/api/setup-worker/reset-handlers `worker.resetHandlers()` API reference} + */ + resetHandlers: (...nextHandlers: Array) => void; + /** + * Returns a readonly list of currently active request handlers. + * + * @see {@link https://mswjs.io/docs/api/setup-worker/list-handlers `worker.listHandlers()` API reference} + */ + listHandlers: () => ReadonlyArray; + /** + * Life-cycle events. + * Life-cycle events allow you to subscribe to the internal library events occurring during the request/response handling. + * + * @see {@link https://mswjs.io/docs/api/life-cycle-events Life-cycle Events API reference} + */ + events: LifeCycleEventEmitter; +} + +/** + * Sets up a requests interception in the browser with the given request handlers. + * @param {Array} handlers List of request handlers. + * + * @see {@link https://mswjs.io/docs/api/setup-worker `setupWorker()` API reference} + */ +declare function setupWorker(...handlers: Array): SetupWorker; +/** + * @deprecated + * Please use the `defineNetwork` API instead. + */ +declare class SetupWorkerApi implements SetupWorker { + start: (options?: StartOptions) => StartReturnType; + stop: StopHandler; + use: (...handlers: Array) => void; + resetHandlers: (...nextHandlers: Array) => void; + restoreHandlers: () => void; + listHandlers: () => ReadonlyArray; + events: LifeCycleEventEmitter; + constructor(); +} + +export { type SetupWorker, SetupWorkerApi, type StartOptions, setupWorker }; diff --git a/node_modules/msw/lib/browser/index.d.ts b/node_modules/msw/lib/browser/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1a4ea3cfbfeb777763e0155c9f09ac92092cee65 --- /dev/null +++ b/node_modules/msw/lib/browser/index.d.ts @@ -0,0 +1,112 @@ +import { AnyHandler } from "../core/experimental/handlers-controller"; +import { SharedOptions, LifeCycleEventEmitter } from "../core/sharedOptions"; +import { HttpNetworkFrameEventMap } from "../core/experimental/frames/http-frame"; +import { WebSocketNetworkFrameEventMap } from "../core/experimental/frames/websocket-frame"; + +type FindWorker = (scriptUrl: string, mockServiceWorkerUrl: string) => boolean; +interface StartOptions extends SharedOptions { + /** + * Service Worker registration options. + */ + serviceWorker?: { + /** + * Custom url to the worker script. + * @default "/mockServiceWorker.js" + */ + url?: string; + options?: RegistrationOptions; + }; + /** + * Disables the logging of the intercepted requests + * into browser's console. + * @default false + */ + quiet?: boolean; + /** + * Defers any network requests until the Service Worker + * instance is activated. + * @default true + * @deprecated + * Please use a proper browser integration instead. + * @see https://mswjs.io/docs/integrations/browser + */ + waitUntilReady?: boolean; + /** + * A custom lookup function to find a Mock Service Worker in the list + * of all registered Service Workers on the page. + */ + findWorker?: FindWorker; +} +type StartReturnType = Promise; +type StopHandler = () => void; +interface SetupWorker { + /** + * Registers and activates the mock Service Worker. + * + * @see {@link https://mswjs.io/docs/api/setup-worker/start `worker.start()` API reference} + */ + start: (options?: StartOptions) => StartReturnType; + /** + * Stops requests interception for the current client. + * + * @see {@link https://mswjs.io/docs/api/setup-worker/stop `worker.stop()` API reference} + */ + stop: StopHandler; + /** + * Prepends given request handlers to the list of existing handlers. + * @param {Array} handlers List of runtime request handlers. + * + * @see {@link https://mswjs.io/docs/api/setup-worker/use `worker.use()` API reference} + */ + use: (...handlers: Array) => void; + /** + * Marks all request handlers that respond using `res.once()` as unused. + * + * @see {@link https://mswjs.io/docs/api/setup-worker/restore-handlers `worker.restoreHandlers()` API reference} + */ + restoreHandlers: () => void; + /** + * Resets request handlers to the initial list given to the `setupWorker` call, or to the explicit next request handlers list, if given. + * @param {Array} nextHandlers List of the new initial request handlers. + * + * @see {@link https://mswjs.io/docs/api/setup-worker/reset-handlers `worker.resetHandlers()` API reference} + */ + resetHandlers: (...nextHandlers: Array) => void; + /** + * Returns a readonly list of currently active request handlers. + * + * @see {@link https://mswjs.io/docs/api/setup-worker/list-handlers `worker.listHandlers()` API reference} + */ + listHandlers: () => ReadonlyArray; + /** + * Life-cycle events. + * Life-cycle events allow you to subscribe to the internal library events occurring during the request/response handling. + * + * @see {@link https://mswjs.io/docs/api/life-cycle-events Life-cycle Events API reference} + */ + events: LifeCycleEventEmitter; +} + +/** + * Sets up a requests interception in the browser with the given request handlers. + * @param {Array} handlers List of request handlers. + * + * @see {@link https://mswjs.io/docs/api/setup-worker `setupWorker()` API reference} + */ +declare function setupWorker(...handlers: Array): SetupWorker; +/** + * @deprecated + * Please use the `defineNetwork` API instead. + */ +declare class SetupWorkerApi implements SetupWorker { + start: (options?: StartOptions) => StartReturnType; + stop: StopHandler; + use: (...handlers: Array) => void; + resetHandlers: (...nextHandlers: Array) => void; + restoreHandlers: () => void; + listHandlers: () => ReadonlyArray; + events: LifeCycleEventEmitter; + constructor(); +} + +export { type SetupWorker, SetupWorkerApi, type StartOptions, setupWorker }; diff --git a/node_modules/msw/lib/browser/index.js b/node_modules/msw/lib/browser/index.js new file mode 100644 index 0000000000000000000000000000000000000000..4f753610d35eec12d427f6d344bca29ecfa2a469 --- /dev/null +++ b/node_modules/msw/lib/browser/index.js @@ -0,0 +1,3583 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/browser/index.ts +var index_exports = {}; +__export(index_exports, { + SetupWorkerApi: () => SetupWorkerApi, + setupWorker: () => setupWorker +}); +module.exports = __toCommonJS(index_exports); + +// node_modules/.pnpm/outvariant@1.4.3/node_modules/outvariant/lib/index.mjs +var POSITIONALS_EXP = /(%?)(%([sdijo]))/g; +function serializePositional(positional, flag) { + switch (flag) { + case "s": + return positional; + case "d": + case "i": + return Number(positional); + case "j": + return JSON.stringify(positional); + case "o": { + if (typeof positional === "string") { + return positional; + } + const json = JSON.stringify(positional); + if (json === "{}" || json === "[]" || /^\[object .+?\]$/.test(json)) { + return positional; + } + return json; + } + } +} +function format(message, ...positionals) { + if (positionals.length === 0) { + return message; + } + let positionalIndex = 0; + let formattedMessage = message.replace( + POSITIONALS_EXP, + (match, isEscaped, _, flag) => { + const positional = positionals[positionalIndex]; + const value = serializePositional(positional, flag); + if (!isEscaped) { + positionalIndex++; + return value; + } + return match; + } + ); + if (positionalIndex < positionals.length) { + formattedMessage += ` ${positionals.slice(positionalIndex).join(" ")}`; + } + formattedMessage = formattedMessage.replace(/%{2,2}/g, "%"); + return formattedMessage; +} +var STACK_FRAMES_TO_IGNORE = 2; +function cleanErrorStack(error2) { + if (!error2.stack) { + return; + } + const nextStack = error2.stack.split("\n"); + nextStack.splice(1, STACK_FRAMES_TO_IGNORE); + error2.stack = nextStack.join("\n"); +} +var InvariantError = class extends Error { + constructor(message, ...positionals) { + super(message); + this.message = message; + this.name = "Invariant Violation"; + this.message = format(message, ...positionals); + cleanErrorStack(this); + } +}; +var invariant = (predicate, message, ...positionals) => { + if (!predicate) { + throw new InvariantError(message, ...positionals); + } +}; +invariant.as = (ErrorConstructor, predicate, message, ...positionals) => { + if (!predicate) { + const formatMessage = positionals.length === 0 ? message : format(message, ...positionals); + let error2; + try { + error2 = Reflect.construct(ErrorConstructor, [ + formatMessage + ]); + } catch (err) { + error2 = ErrorConstructor(formatMessage); + } + throw error2; + } +}; + +// node_modules/.pnpm/is-node-process@1.2.0/node_modules/is-node-process/lib/index.mjs +function isNodeProcess() { + if (typeof navigator !== "undefined" && navigator.product === "ReactNative") { + return true; + } + if (typeof process !== "undefined") { + const type = process.type; + if (type === "renderer" || type === "worker") { + return false; + } + return !!(process.versions && process.versions.node); + } + return false; +} + +// node_modules/.pnpm/@open-draft+logger@0.3.0/node_modules/@open-draft/logger/lib/index.mjs +var __defProp2 = Object.defineProperty; +var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); +}; +var colors_exports = {}; +__export2(colors_exports, { + blue: () => blue, + gray: () => gray, + green: () => green, + red: () => red, + yellow: () => yellow +}); +function yellow(text) { + return `\x1B[33m${text}\x1B[0m`; +} +function blue(text) { + return `\x1B[34m${text}\x1B[0m`; +} +function gray(text) { + return `\x1B[90m${text}\x1B[0m`; +} +function red(text) { + return `\x1B[31m${text}\x1B[0m`; +} +function green(text) { + return `\x1B[32m${text}\x1B[0m`; +} +var IS_NODE = isNodeProcess(); +var Logger = class { + constructor(name) { + this.name = name; + this.prefix = `[${this.name}]`; + const LOGGER_NAME = getVariable("DEBUG"); + const LOGGER_LEVEL = getVariable("LOG_LEVEL"); + const isLoggingEnabled = LOGGER_NAME === "1" || LOGGER_NAME === "true" || typeof LOGGER_NAME !== "undefined" && this.name.startsWith(LOGGER_NAME); + if (isLoggingEnabled) { + this.debug = isDefinedAndNotEquals(LOGGER_LEVEL, "debug") ? noop : this.debug; + this.info = isDefinedAndNotEquals(LOGGER_LEVEL, "info") ? noop : this.info; + this.success = isDefinedAndNotEquals(LOGGER_LEVEL, "success") ? noop : this.success; + this.warning = isDefinedAndNotEquals(LOGGER_LEVEL, "warning") ? noop : this.warning; + this.error = isDefinedAndNotEquals(LOGGER_LEVEL, "error") ? noop : this.error; + } else { + this.info = noop; + this.success = noop; + this.warning = noop; + this.error = noop; + this.only = noop; + } + } + prefix; + extend(domain) { + return new Logger(`${this.name}:${domain}`); + } + /** + * Print a debug message. + * @example + * logger.debug('no duplicates found, creating a document...') + */ + debug(message, ...positionals) { + this.logEntry({ + level: "debug", + message: gray(message), + positionals, + prefix: this.prefix, + colors: { + prefix: "gray" + } + }); + } + /** + * Print an info message. + * @example + * logger.info('start parsing...') + */ + info(message, ...positionals) { + this.logEntry({ + level: "info", + message, + positionals, + prefix: this.prefix, + colors: { + prefix: "blue" + } + }); + const performance2 = new PerformanceEntry(); + return (message2, ...positionals2) => { + performance2.measure(); + this.logEntry({ + level: "info", + message: `${message2} ${gray(`${performance2.deltaTime}ms`)}`, + positionals: positionals2, + prefix: this.prefix, + colors: { + prefix: "blue" + } + }); + }; + } + /** + * Print a success message. + * @example + * logger.success('successfully created document') + */ + success(message, ...positionals) { + this.logEntry({ + level: "info", + message, + positionals, + prefix: `\u2714 ${this.prefix}`, + colors: { + timestamp: "green", + prefix: "green" + } + }); + } + /** + * Print a warning. + * @example + * logger.warning('found legacy document format') + */ + warning(message, ...positionals) { + this.logEntry({ + level: "warning", + message, + positionals, + prefix: `\u26A0 ${this.prefix}`, + colors: { + timestamp: "yellow", + prefix: "yellow" + } + }); + } + /** + * Print an error message. + * @example + * logger.error('something went wrong') + */ + error(message, ...positionals) { + this.logEntry({ + level: "error", + message, + positionals, + prefix: `\u2716 ${this.prefix}`, + colors: { + timestamp: "red", + prefix: "red" + } + }); + } + /** + * Execute the given callback only when the logging is enabled. + * This is skipped in its entirety and has no runtime cost otherwise. + * This executes regardless of the log level. + * @example + * logger.only(() => { + * logger.info('additional info') + * }) + */ + only(callback) { + callback(); + } + createEntry(level, message) { + return { + timestamp: /* @__PURE__ */ new Date(), + level, + message + }; + } + logEntry(args) { + const { + level, + message, + prefix, + colors: customColors, + positionals = [] + } = args; + const entry = this.createEntry(level, message); + const timestampColor = customColors?.timestamp || "gray"; + const prefixColor = customColors?.prefix || "gray"; + const colorize = { + timestamp: colors_exports[timestampColor], + prefix: colors_exports[prefixColor] + }; + const write = this.getWriter(level); + write( + [colorize.timestamp(this.formatTimestamp(entry.timestamp))].concat(prefix != null ? colorize.prefix(prefix) : []).concat(serializeInput(message)).join(" "), + ...positionals.map(serializeInput) + ); + } + formatTimestamp(timestamp) { + return `${timestamp.toLocaleTimeString( + "en-GB" + )}:${timestamp.getMilliseconds()}`; + } + getWriter(level) { + switch (level) { + case "debug": + case "success": + case "info": { + return log; + } + case "warning": { + return warn; + } + case "error": { + return error; + } + } + } +}; +var PerformanceEntry = class { + startTime; + endTime; + deltaTime; + constructor() { + this.startTime = performance.now(); + } + measure() { + this.endTime = performance.now(); + const deltaTime = this.endTime - this.startTime; + this.deltaTime = deltaTime.toFixed(2); + } +}; +var noop = () => void 0; +function log(message, ...positionals) { + if (IS_NODE) { + process.stdout.write(format(message, ...positionals) + "\n"); + return; + } + console.log(message, ...positionals); +} +function warn(message, ...positionals) { + if (IS_NODE) { + process.stderr.write(format(message, ...positionals) + "\n"); + return; + } + console.warn(message, ...positionals); +} +function error(message, ...positionals) { + if (IS_NODE) { + process.stderr.write(format(message, ...positionals) + "\n"); + return; + } + console.error(message, ...positionals); +} +function getVariable(variableName) { + if (IS_NODE) { + return process.env[variableName]; + } + return globalThis[variableName]?.toString(); +} +function isDefinedAndNotEquals(value, expected) { + return value !== void 0 && value !== expected; +} +function serializeInput(message) { + if (typeof message === "undefined") { + return "undefined"; + } + if (message === null) { + return "null"; + } + if (typeof message === "string") { + return message; + } + if (typeof message === "object") { + return JSON.stringify(message); + } + return message.toString(); +} + +// node_modules/.pnpm/strict-event-emitter@0.5.1/node_modules/strict-event-emitter/lib/index.mjs +var MemoryLeakError = class extends Error { + constructor(emitter, type, count) { + super( + `Possible EventEmitter memory leak detected. ${count} ${type.toString()} listeners added. Use emitter.setMaxListeners() to increase limit` + ); + this.emitter = emitter; + this.type = type; + this.count = count; + this.name = "MaxListenersExceededWarning"; + } +}; +var _Emitter = class { + static listenerCount(emitter, eventName) { + return emitter.listenerCount(eventName); + } + constructor() { + this.events = /* @__PURE__ */ new Map(); + this.maxListeners = _Emitter.defaultMaxListeners; + this.hasWarnedAboutPotentialMemoryLeak = false; + } + _emitInternalEvent(internalEventName, eventName, listener) { + this.emit( + internalEventName, + ...[eventName, listener] + ); + } + _getListeners(eventName) { + return Array.prototype.concat.apply([], this.events.get(eventName)) || []; + } + _removeListener(listeners, listener) { + const index = listeners.indexOf(listener); + if (index > -1) { + listeners.splice(index, 1); + } + return []; + } + _wrapOnceListener(eventName, listener) { + const onceListener = (...data) => { + this.removeListener(eventName, onceListener); + return listener.apply(this, data); + }; + Object.defineProperty(onceListener, "name", { value: listener.name }); + return onceListener; + } + setMaxListeners(maxListeners) { + this.maxListeners = maxListeners; + return this; + } + /** + * Returns the current max listener value for the `Emitter` which is + * either set by `emitter.setMaxListeners(n)` or defaults to + * `Emitter.defaultMaxListeners`. + */ + getMaxListeners() { + return this.maxListeners; + } + /** + * Returns an array listing the events for which the emitter has registered listeners. + * The values in the array will be strings or Symbols. + */ + eventNames() { + return Array.from(this.events.keys()); + } + /** + * Synchronously calls each of the listeners registered for the event named `eventName`, + * in the order they were registered, passing the supplied arguments to each. + * Returns `true` if the event has listeners, `false` otherwise. + * + * @example + * const emitter = new Emitter<{ hello: [string] }>() + * emitter.emit('hello', 'John') + */ + emit(eventName, ...data) { + const listeners = this._getListeners(eventName); + listeners.forEach((listener) => { + listener.apply(this, data); + }); + return listeners.length > 0; + } + addListener(eventName, listener) { + this._emitInternalEvent("newListener", eventName, listener); + const nextListeners = this._getListeners(eventName).concat(listener); + this.events.set(eventName, nextListeners); + if (this.maxListeners > 0 && this.listenerCount(eventName) > this.maxListeners && !this.hasWarnedAboutPotentialMemoryLeak) { + this.hasWarnedAboutPotentialMemoryLeak = true; + const memoryLeakWarning = new MemoryLeakError( + this, + eventName, + this.listenerCount(eventName) + ); + console.warn(memoryLeakWarning); + } + return this; + } + on(eventName, listener) { + return this.addListener(eventName, listener); + } + once(eventName, listener) { + return this.addListener( + eventName, + this._wrapOnceListener(eventName, listener) + ); + } + prependListener(eventName, listener) { + const listeners = this._getListeners(eventName); + if (listeners.length > 0) { + const nextListeners = [listener].concat(listeners); + this.events.set(eventName, nextListeners); + } else { + this.events.set(eventName, listeners.concat(listener)); + } + return this; + } + prependOnceListener(eventName, listener) { + return this.prependListener( + eventName, + this._wrapOnceListener(eventName, listener) + ); + } + removeListener(eventName, listener) { + const listeners = this._getListeners(eventName); + if (listeners.length > 0) { + this._removeListener(listeners, listener); + this.events.set(eventName, listeners); + this._emitInternalEvent("removeListener", eventName, listener); + } + return this; + } + /** + * Alias for `emitter.removeListener()`. + * + * @example + * emitter.off('hello', listener) + */ + off(eventName, listener) { + return this.removeListener(eventName, listener); + } + removeAllListeners(eventName) { + if (eventName) { + this.events.delete(eventName); + } else { + this.events.clear(); + } + return this; + } + /** + * Returns a copy of the array of listeners for the event named `eventName`. + */ + listeners(eventName) { + return Array.from(this._getListeners(eventName)); + } + /** + * Returns the number of listeners listening to the event named `eventName`. + */ + listenerCount(eventName) { + return this._getListeners(eventName).length; + } + rawListeners(eventName) { + return this.listeners(eventName); + } +}; +var Emitter = _Emitter; +Emitter.defaultMaxListeners = 10; + +// node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/lib/browser/createRequestId-DQcIlohW.mjs +var INTERNAL_REQUEST_ID_HEADER_NAME = "x-interceptors-internal-request-id"; +function getGlobalSymbol(symbol) { + return globalThis[symbol] || void 0; +} +function setGlobalSymbol(symbol, value) { + globalThis[symbol] = value; +} +function deleteGlobalSymbol(symbol) { + delete globalThis[symbol]; +} +var InterceptorReadyState = /* @__PURE__ */ (function(InterceptorReadyState$1) { + InterceptorReadyState$1["INACTIVE"] = "INACTIVE"; + InterceptorReadyState$1["APPLYING"] = "APPLYING"; + InterceptorReadyState$1["APPLIED"] = "APPLIED"; + InterceptorReadyState$1["DISPOSING"] = "DISPOSING"; + InterceptorReadyState$1["DISPOSED"] = "DISPOSED"; + return InterceptorReadyState$1; +})({}); +var Interceptor = class { + constructor(symbol) { + this.symbol = symbol; + this.readyState = InterceptorReadyState.INACTIVE; + this.emitter = new Emitter(); + this.subscriptions = []; + this.logger = new Logger(symbol.description); + this.emitter.setMaxListeners(0); + this.logger.info("constructing the interceptor..."); + } + /** + * Determine if this interceptor can be applied + * in the current environment. + */ + checkEnvironment() { + return true; + } + /** + * Apply this interceptor to the current process. + * Returns an already running interceptor instance if it's present. + */ + apply() { + const logger = this.logger.extend("apply"); + logger.info("applying the interceptor..."); + if (this.readyState === InterceptorReadyState.APPLIED) { + logger.info("intercepted already applied!"); + return; + } + if (!this.checkEnvironment()) { + logger.info("the interceptor cannot be applied in this environment!"); + return; + } + this.readyState = InterceptorReadyState.APPLYING; + const runningInstance = this.getInstance(); + if (runningInstance) { + logger.info("found a running instance, reusing..."); + this.on = (event, listener) => { + logger.info('proxying the "%s" listener', event); + runningInstance.emitter.addListener(event, listener); + this.subscriptions.push(() => { + runningInstance.emitter.removeListener(event, listener); + logger.info('removed proxied "%s" listener!', event); + }); + return this; + }; + this.readyState = InterceptorReadyState.APPLIED; + return; + } + logger.info("no running instance found, setting up a new instance..."); + this.setup(); + this.setInstance(); + this.readyState = InterceptorReadyState.APPLIED; + } + /** + * Setup the module augments and stubs necessary for this interceptor. + * This method is not run if there's a running interceptor instance + * to prevent instantiating an interceptor multiple times. + */ + setup() { + } + /** + * Listen to the interceptor's public events. + */ + on(event, listener) { + const logger = this.logger.extend("on"); + if (this.readyState === InterceptorReadyState.DISPOSING || this.readyState === InterceptorReadyState.DISPOSED) { + logger.info("cannot listen to events, already disposed!"); + return this; + } + logger.info('adding "%s" event listener:', event, listener); + this.emitter.on(event, listener); + return this; + } + once(event, listener) { + this.emitter.once(event, listener); + return this; + } + off(event, listener) { + this.emitter.off(event, listener); + return this; + } + removeAllListeners(event) { + this.emitter.removeAllListeners(event); + return this; + } + /** + * Disposes of any side-effects this interceptor has introduced. + */ + dispose() { + const logger = this.logger.extend("dispose"); + if (this.readyState === InterceptorReadyState.DISPOSED) { + logger.info("cannot dispose, already disposed!"); + return; + } + logger.info("disposing the interceptor..."); + this.readyState = InterceptorReadyState.DISPOSING; + if (!this.getInstance()) { + logger.info("no interceptors running, skipping dispose..."); + return; + } + this.clearInstance(); + logger.info("global symbol deleted:", getGlobalSymbol(this.symbol)); + if (this.subscriptions.length > 0) { + logger.info("disposing of %d subscriptions...", this.subscriptions.length); + for (const dispose of this.subscriptions) dispose(); + this.subscriptions = []; + logger.info("disposed of all subscriptions!", this.subscriptions.length); + } + this.emitter.removeAllListeners(); + logger.info("destroyed the listener!"); + this.readyState = InterceptorReadyState.DISPOSED; + } + getInstance() { + const instance = getGlobalSymbol(this.symbol); + this.logger.info("retrieved global instance:", instance?.constructor?.name); + return instance; + } + setInstance() { + setGlobalSymbol(this.symbol, this); + this.logger.info("set global instance!", this.symbol.description); + } + clearInstance() { + deleteGlobalSymbol(this.symbol); + this.logger.info("cleared global instance!", this.symbol.description); + } +}; +function createRequestId() { + return Math.random().toString(16).slice(2); +} + +// node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/lib/browser/resolveWebSocketUrl-C83-x9iE.mjs +function resolveWebSocketUrl(url) { + if (typeof url === "string") return resolveWebSocketUrl(new URL(url, typeof location !== "undefined" ? location.href : void 0)); + if (url.protocol === "http:") url.protocol = "ws:"; + else if (url.protocol === "https:") url.protocol = "wss:"; + if (url.protocol !== "ws:" && url.protocol !== "wss:") + throw new SyntaxError(`Failed to construct 'WebSocket': The URL's scheme must be either 'http', 'https', 'ws', or 'wss'. '${url.protocol}' is not allowed.`); + if (url.hash !== "") throw new SyntaxError(`Failed to construct 'WebSocket': The URL contains a fragment identifier ('${url.hash}'). Fragment identifiers are not allowed in WebSocket URLs.`); + return url.href; +} + +// node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/lib/browser/hasConfigurableGlobal-npXitu1-.mjs +async function emitAsync(emitter, eventName, ...data) { + const listeners = emitter.listeners(eventName); + if (listeners.length === 0) return; + for (const listener of listeners) await listener.apply(emitter, data); +} +function hasConfigurableGlobal(propertyName) { + const descriptor = Object.getOwnPropertyDescriptor(globalThis, propertyName); + if (typeof descriptor === "undefined") return false; + if (typeof descriptor.get === "function" && typeof descriptor.get() === "undefined") return false; + if (typeof descriptor.get === "undefined" && descriptor.value == null) return false; + if (typeof descriptor.set === "undefined" && !descriptor.configurable) { + console.error(`[MSW] Failed to apply interceptor: the global \`${propertyName}\` property is non-configurable. This is likely an issue with your environment. If you are using a framework, please open an issue about this in their repository.`); + return false; + } + return true; +} + +// node_modules/.pnpm/@open-draft+deferred-promise@2.2.0/node_modules/@open-draft/deferred-promise/build/index.mjs +function createDeferredExecutor() { + const executor = (resolve, reject) => { + executor.state = "pending"; + executor.resolve = (data) => { + if (executor.state !== "pending") { + return; + } + executor.result = data; + const onFulfilled = (value) => { + executor.state = "fulfilled"; + return value; + }; + return resolve( + data instanceof Promise ? data : Promise.resolve(data).then(onFulfilled) + ); + }; + executor.reject = (reason) => { + if (executor.state !== "pending") { + return; + } + queueMicrotask(() => { + executor.state = "rejected"; + }); + return reject(executor.rejectionReason = reason); + }; + }; + return executor; +} +var DeferredPromise = class extends Promise { + #executor; + resolve; + reject; + constructor(executor = null) { + const deferredExecutor = createDeferredExecutor(); + super((originalResolve, originalReject) => { + deferredExecutor(originalResolve, originalReject); + executor?.(deferredExecutor.resolve, deferredExecutor.reject); + }); + this.#executor = deferredExecutor; + this.resolve = this.#executor.resolve; + this.reject = this.#executor.reject; + } + get state() { + return this.#executor.state; + } + get rejectionReason() { + return this.#executor.rejectionReason; + } + then(onFulfilled, onRejected) { + return this.#decorate(super.then(onFulfilled, onRejected)); + } + catch(onRejected) { + return this.#decorate(super.catch(onRejected)); + } + finally(onfinally) { + return this.#decorate(super.finally(onfinally)); + } + #decorate(promise) { + return Object.defineProperties(promise, { + resolve: { configurable: true, value: this.resolve }, + reject: { configurable: true, value: this.reject } + }); + } +}; + +// node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/lib/browser/interceptors/WebSocket/index.mjs +function bindEvent(target, event) { + Object.defineProperties(event, { + target: { + value: target, + enumerable: true, + writable: true + }, + currentTarget: { + value: target, + enumerable: true, + writable: true + } + }); + return event; +} +var kCancelable = Symbol("kCancelable"); +var kDefaultPrevented = Symbol("kDefaultPrevented"); +var CancelableMessageEvent = class extends MessageEvent { + constructor(type, init) { + super(type, init); + this[kCancelable] = !!init.cancelable; + this[kDefaultPrevented] = false; + } + get cancelable() { + return this[kCancelable]; + } + set cancelable(nextCancelable) { + this[kCancelable] = nextCancelable; + } + get defaultPrevented() { + return this[kDefaultPrevented]; + } + set defaultPrevented(nextDefaultPrevented) { + this[kDefaultPrevented] = nextDefaultPrevented; + } + preventDefault() { + if (this.cancelable && !this[kDefaultPrevented]) this[kDefaultPrevented] = true; + } +}; +var CloseEvent = class extends Event { + constructor(type, init = {}) { + super(type, init); + this.code = init.code === void 0 ? 0 : init.code; + this.reason = init.reason === void 0 ? "" : init.reason; + this.wasClean = init.wasClean === void 0 ? false : init.wasClean; + } +}; +var CancelableCloseEvent = class extends CloseEvent { + constructor(type, init = {}) { + super(type, init); + this[kCancelable] = !!init.cancelable; + this[kDefaultPrevented] = false; + } + get cancelable() { + return this[kCancelable]; + } + set cancelable(nextCancelable) { + this[kCancelable] = nextCancelable; + } + get defaultPrevented() { + return this[kDefaultPrevented]; + } + set defaultPrevented(nextDefaultPrevented) { + this[kDefaultPrevented] = nextDefaultPrevented; + } + preventDefault() { + if (this.cancelable && !this[kDefaultPrevented]) this[kDefaultPrevented] = true; + } +}; +var kEmitter$1 = Symbol("kEmitter"); +var kBoundListener$1 = Symbol("kBoundListener"); +var WebSocketClientConnection = class { + constructor(socket, transport) { + this.socket = socket; + this.transport = transport; + this.id = createRequestId(); + this.url = new URL(socket.url); + this[kEmitter$1] = new EventTarget(); + this.transport.addEventListener("outgoing", (event) => { + const message = bindEvent(this.socket, new CancelableMessageEvent("message", { + data: event.data, + origin: event.origin, + cancelable: true + })); + this[kEmitter$1].dispatchEvent(message); + if (message.defaultPrevented) event.preventDefault(); + }); + this.transport.addEventListener("close", (event) => { + this[kEmitter$1].dispatchEvent(bindEvent(this.socket, new CloseEvent("close", event))); + }); + } + /** + * Listen for the outgoing events from the connected WebSocket client. + */ + addEventListener(type, listener, options) { + if (!Reflect.has(listener, kBoundListener$1)) { + const boundListener = listener.bind(this.socket); + Object.defineProperty(listener, kBoundListener$1, { + value: boundListener, + enumerable: false, + configurable: false + }); + } + this[kEmitter$1].addEventListener(type, Reflect.get(listener, kBoundListener$1), options); + } + /** + * Removes the listener for the given event. + */ + removeEventListener(event, listener, options) { + this[kEmitter$1].removeEventListener(event, Reflect.get(listener, kBoundListener$1), options); + } + /** + * Send data to the connected client. + */ + send(data) { + this.transport.send(data); + } + /** + * Close the WebSocket connection. + * @param {number} code A status code (see https://www.rfc-editor.org/rfc/rfc6455#section-7.4.1). + * @param {string} reason A custom connection close reason. + */ + close(code, reason) { + this.transport.close(code, reason); + } +}; +var WEBSOCKET_CLOSE_CODE_RANGE_ERROR = "InvalidAccessError: close code out of user configurable range"; +var kPassthroughPromise = Symbol("kPassthroughPromise"); +var kOnSend = Symbol("kOnSend"); +var kClose = Symbol("kClose"); +var WebSocketOverride = class extends EventTarget { + static { + this.CONNECTING = 0; + } + static { + this.OPEN = 1; + } + static { + this.CLOSING = 2; + } + static { + this.CLOSED = 3; + } + constructor(url, protocols) { + super(); + this.CONNECTING = 0; + this.OPEN = 1; + this.CLOSING = 2; + this.CLOSED = 3; + this._onopen = null; + this._onmessage = null; + this._onerror = null; + this._onclose = null; + this.url = resolveWebSocketUrl(url); + this.protocol = ""; + this.extensions = ""; + this.binaryType = "blob"; + this.readyState = this.CONNECTING; + this.bufferedAmount = 0; + this[kPassthroughPromise] = new DeferredPromise(); + queueMicrotask(async () => { + if (await this[kPassthroughPromise]) return; + this.protocol = typeof protocols === "string" ? protocols : Array.isArray(protocols) && protocols.length > 0 ? protocols[0] : ""; + if (this.readyState === this.CONNECTING) { + this.readyState = this.OPEN; + this.dispatchEvent(bindEvent(this, new Event("open"))); + } + }); + } + set onopen(listener) { + this.removeEventListener("open", this._onopen); + this._onopen = listener; + if (listener !== null) this.addEventListener("open", listener); + } + get onopen() { + return this._onopen; + } + set onmessage(listener) { + this.removeEventListener("message", this._onmessage); + this._onmessage = listener; + if (listener !== null) this.addEventListener("message", listener); + } + get onmessage() { + return this._onmessage; + } + set onerror(listener) { + this.removeEventListener("error", this._onerror); + this._onerror = listener; + if (listener !== null) this.addEventListener("error", listener); + } + get onerror() { + return this._onerror; + } + set onclose(listener) { + this.removeEventListener("close", this._onclose); + this._onclose = listener; + if (listener !== null) this.addEventListener("close", listener); + } + get onclose() { + return this._onclose; + } + /** + * @see https://websockets.spec.whatwg.org/#ref-for-dom-websocket-send%E2%91%A0 + */ + send(data) { + if (this.readyState === this.CONNECTING) { + this.close(); + throw new DOMException("InvalidStateError"); + } + if (this.readyState === this.CLOSING || this.readyState === this.CLOSED) return; + this.bufferedAmount += getDataSize(data); + queueMicrotask(() => { + this.bufferedAmount = 0; + this[kOnSend]?.(data); + }); + } + close(code = 1e3, reason) { + invariant(code, WEBSOCKET_CLOSE_CODE_RANGE_ERROR); + invariant(code === 1e3 || code >= 3e3 && code <= 4999, WEBSOCKET_CLOSE_CODE_RANGE_ERROR); + this[kClose](code, reason); + } + [kClose](code = 1e3, reason, wasClean = true) { + if (this.readyState === this.CLOSING || this.readyState === this.CLOSED) return; + this.readyState = this.CLOSING; + queueMicrotask(() => { + this.readyState = this.CLOSED; + this.dispatchEvent(bindEvent(this, new CloseEvent("close", { + code, + reason, + wasClean + }))); + this._onopen = null; + this._onmessage = null; + this._onerror = null; + this._onclose = null; + }); + } + addEventListener(type, listener, options) { + return super.addEventListener(type, listener, options); + } + removeEventListener(type, callback, options) { + return super.removeEventListener(type, callback, options); + } +}; +function getDataSize(data) { + if (typeof data === "string") return data.length; + if (data instanceof Blob) return data.size; + return data.byteLength; +} +var kEmitter = Symbol("kEmitter"); +var kBoundListener = Symbol("kBoundListener"); +var kSend = Symbol("kSend"); +var WebSocketServerConnection = class { + constructor(client, transport, createConnection) { + this.client = client; + this.transport = transport; + this.createConnection = createConnection; + this[kEmitter] = new EventTarget(); + this.mockCloseController = new AbortController(); + this.realCloseController = new AbortController(); + this.transport.addEventListener("outgoing", (event) => { + if (typeof this.realWebSocket === "undefined") return; + queueMicrotask(() => { + if (!event.defaultPrevented) + this[kSend](event.data); + }); + }); + this.transport.addEventListener("incoming", this.handleIncomingMessage.bind(this)); + } + /** + * The `WebSocket` instance connected to the original server. + * Accessing this before calling `server.connect()` will throw. + */ + get socket() { + invariant(this.realWebSocket, 'Cannot access "socket" on the original WebSocket server object: the connection is not open. Did you forget to call `server.connect()`?'); + return this.realWebSocket; + } + /** + * Open connection to the original WebSocket server. + */ + connect() { + invariant(!this.realWebSocket || this.realWebSocket.readyState !== WebSocket.OPEN, 'Failed to call "connect()" on the original WebSocket instance: the connection already open'); + const realWebSocket = this.createConnection(); + realWebSocket.binaryType = this.client.binaryType; + realWebSocket.addEventListener("open", (event) => { + this[kEmitter].dispatchEvent(bindEvent(this.realWebSocket, new Event("open", event))); + }, { once: true }); + realWebSocket.addEventListener("message", (event) => { + this.transport.dispatchEvent(bindEvent(this.realWebSocket, new MessageEvent("incoming", { + data: event.data, + origin: event.origin + }))); + }); + this.client.addEventListener("close", (event) => { + this.handleMockClose(event); + }, { signal: this.mockCloseController.signal }); + realWebSocket.addEventListener("close", (event) => { + this.handleRealClose(event); + }, { signal: this.realCloseController.signal }); + realWebSocket.addEventListener("error", () => { + const errorEvent = bindEvent(realWebSocket, new Event("error", { cancelable: true })); + this[kEmitter].dispatchEvent(errorEvent); + if (!errorEvent.defaultPrevented) this.client.dispatchEvent(bindEvent(this.client, new Event("error"))); + }); + this.realWebSocket = realWebSocket; + } + /** + * Listen for the incoming events from the original WebSocket server. + */ + addEventListener(event, listener, options) { + if (!Reflect.has(listener, kBoundListener)) { + const boundListener = listener.bind(this.client); + Object.defineProperty(listener, kBoundListener, { + value: boundListener, + enumerable: false + }); + } + this[kEmitter].addEventListener(event, Reflect.get(listener, kBoundListener), options); + } + /** + * Remove the listener for the given event. + */ + removeEventListener(event, listener, options) { + this[kEmitter].removeEventListener(event, Reflect.get(listener, kBoundListener), options); + } + /** + * Send data to the original WebSocket server. + * @example + * server.send('hello') + * server.send(new Blob(['hello'])) + * server.send(new TextEncoder().encode('hello')) + */ + send(data) { + this[kSend](data); + } + [kSend](data) { + const { realWebSocket } = this; + invariant(realWebSocket, 'Failed to call "server.send()" for "%s": the connection is not open. Did you forget to call "server.connect()"?', this.client.url); + if (realWebSocket.readyState === WebSocket.CLOSING || realWebSocket.readyState === WebSocket.CLOSED) return; + if (realWebSocket.readyState === WebSocket.CONNECTING) { + realWebSocket.addEventListener("open", () => { + realWebSocket.send(data); + }, { once: true }); + return; + } + realWebSocket.send(data); + } + /** + * Close the actual server connection. + */ + close() { + const { realWebSocket } = this; + invariant(realWebSocket, 'Failed to close server connection for "%s": the connection is not open. Did you forget to call "server.connect()"?', this.client.url); + this.realCloseController.abort(); + if (realWebSocket.readyState === WebSocket.CLOSING || realWebSocket.readyState === WebSocket.CLOSED) return; + realWebSocket.close(); + queueMicrotask(() => { + this[kEmitter].dispatchEvent(bindEvent(this.realWebSocket, new CancelableCloseEvent("close", { + code: 1e3, + cancelable: true + }))); + }); + } + handleIncomingMessage(event) { + const messageEvent = bindEvent(event.target, new CancelableMessageEvent("message", { + data: event.data, + origin: event.origin, + cancelable: true + })); + this[kEmitter].dispatchEvent(messageEvent); + if (!messageEvent.defaultPrevented) this.client.dispatchEvent(bindEvent( + /** + * @note Bind the forwarded original server events + * to the mock WebSocket instance so it would + * dispatch them straight away. + */ + this.client, + new MessageEvent("message", { + data: event.data, + origin: event.origin + }) + )); + } + handleMockClose(_event) { + if (this.realWebSocket) this.realWebSocket.close(); + } + handleRealClose(event) { + this.mockCloseController.abort(); + const closeEvent = bindEvent(this.realWebSocket, new CancelableCloseEvent("close", { + code: event.code, + reason: event.reason, + wasClean: event.wasClean, + cancelable: true + })); + this[kEmitter].dispatchEvent(closeEvent); + if (!closeEvent.defaultPrevented) this.client[kClose](event.code, event.reason); + } +}; +var WebSocketClassTransport = class extends EventTarget { + constructor(socket) { + super(); + this.socket = socket; + this.socket.addEventListener("close", (event) => { + this.dispatchEvent(bindEvent(this.socket, new CloseEvent("close", event))); + }); + this.socket[kOnSend] = (data) => { + this.dispatchEvent(bindEvent(this.socket, new CancelableMessageEvent("outgoing", { + data, + origin: this.socket.url, + cancelable: true + }))); + }; + } + addEventListener(type, callback, options) { + return super.addEventListener(type, callback, options); + } + dispatchEvent(event) { + return super.dispatchEvent(event); + } + send(data) { + queueMicrotask(() => { + if (this.socket.readyState === this.socket.CLOSING || this.socket.readyState === this.socket.CLOSED) return; + const dispatchEvent = () => { + this.socket.dispatchEvent(bindEvent( + /** + * @note Setting this event's "target" to the + * WebSocket override instance is important. + * This way it can tell apart original incoming events + * (must be forwarded to the transport) from the + * mocked message events like the one below + * (must be dispatched on the client instance). + */ + this.socket, + new MessageEvent("message", { + data, + origin: this.socket.url + }) + )); + }; + if (this.socket.readyState === this.socket.CONNECTING) this.socket.addEventListener("open", () => { + dispatchEvent(); + }, { once: true }); + else dispatchEvent(); + }); + } + close(code, reason) { + this.socket[kClose](code, reason); + } +}; +var WebSocketInterceptor = class WebSocketInterceptor2 extends Interceptor { + static { + this.symbol = Symbol("websocket"); + } + constructor() { + super(WebSocketInterceptor2.symbol); + } + checkEnvironment() { + return hasConfigurableGlobal("WebSocket"); + } + setup() { + const originalWebSocketDescriptor = Object.getOwnPropertyDescriptor(globalThis, "WebSocket"); + const WebSocketProxy = new Proxy(globalThis.WebSocket, { construct: (target, args, newTarget) => { + const [url, protocols] = args; + const createConnection = () => { + return Reflect.construct(target, args, newTarget); + }; + const socket = new WebSocketOverride(url, protocols); + const transport = new WebSocketClassTransport(socket); + queueMicrotask(async () => { + try { + const server = new WebSocketServerConnection(socket, transport, createConnection); + const hasConnectionListeners = this.emitter.listenerCount("connection") > 0; + await emitAsync(this.emitter, "connection", { + client: new WebSocketClientConnection(socket, transport), + server, + info: { protocols } + }); + if (hasConnectionListeners) socket[kPassthroughPromise].resolve(false); + else { + socket[kPassthroughPromise].resolve(true); + server.connect(); + server.addEventListener("open", () => { + socket.dispatchEvent(bindEvent(socket, new Event("open"))); + if (server["realWebSocket"]) socket.protocol = server["realWebSocket"].protocol; + }); + } + } catch (error2) { + if (error2 instanceof Error) { + socket.dispatchEvent(new Event("error")); + if (socket.readyState !== WebSocket.CLOSING && socket.readyState !== WebSocket.CLOSED) socket[kClose](1011, error2.message, false); + console.error(error2); + } + } + }); + return socket; + } }); + Object.defineProperty(globalThis, "WebSocket", { + value: WebSocketProxy, + configurable: true + }); + this.subscriptions.push(() => { + Object.defineProperty(globalThis, "WebSocket", originalWebSocketDescriptor); + }); + } +}; + +// src/browser/setup-worker.ts +var import_define_network = require("../core/experimental/define-network"); +var import_interceptor_source2 = require("../core/experimental/sources/interceptor-source"); +var import_compat = require("../core/experimental/compat"); +var import_devUtils5 = require("../core/utils/internal/devUtils"); + +// src/browser/utils/supports.ts +function supportsServiceWorker() { + return typeof navigator !== "undefined" && "serviceWorker" in navigator && typeof location !== "undefined" && location.protocol !== "file:"; +} +function supportsReadableStreamTransfer() { + try { + const stream = new ReadableStream({ + start: (controller) => controller.close() + }); + const message = new MessageChannel(); + message.port1.postMessage(stream, [stream]); + return true; + } catch { + return false; + } +} + +// node_modules/.pnpm/@open-draft+deferred-promise@3.0.0/node_modules/@open-draft/deferred-promise/build/index.mjs +function createDeferredExecutor2() { + const executor = ((resolve, reject) => { + executor.state = "pending"; + executor.resolve = (data) => { + if (executor.state !== "pending") return; + executor.result = data; + const onFulfilled = (value) => { + executor.state = "fulfilled"; + return value; + }; + return resolve(data instanceof Promise ? data : Promise.resolve(data).then(onFulfilled)); + }; + executor.reject = (reason) => { + if (executor.state !== "pending") return; + queueMicrotask(() => { + executor.state = "rejected"; + }); + return reject(executor.rejectionReason = reason); + }; + }); + return executor; +} +var DeferredPromise2 = class extends Promise { + #executor; + resolve; + reject; + constructor(executor = null) { + const deferredExecutor = createDeferredExecutor2(); + super((originalResolve, originalReject) => { + deferredExecutor(originalResolve, originalReject); + executor?.(deferredExecutor.resolve, deferredExecutor.reject); + }); + this.#executor = deferredExecutor; + this.resolve = this.#executor.resolve; + this.reject = this.#executor.reject; + } + get state() { + return this.#executor.state; + } + get rejectionReason() { + return this.#executor.rejectionReason; + } + then(onFulfilled, onRejected) { + return this.#decorate(super.then(onFulfilled, onRejected)); + } + catch(onRejected) { + return this.#decorate(super.catch(onRejected)); + } + finally(onfinally) { + return this.#decorate(super.finally(onfinally)); + } + #decorate(promise) { + return Object.defineProperties(promise, { + resolve: { + configurable: true, + value: this.resolve + }, + reject: { + configurable: true, + value: this.reject + } + }); + } +}; + +// node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/lib/browser/getRawRequest-BTaNLFr0.mjs +var IS_PATCHED_MODULE = Symbol("isPatchedModule"); +var InterceptorError = class InterceptorError2 extends Error { + constructor(message) { + super(message); + this.name = "InterceptorError"; + Object.setPrototypeOf(this, InterceptorError2.prototype); + } +}; +var RequestController = class RequestController2 { + static { + this.PENDING = 0; + } + static { + this.PASSTHROUGH = 1; + } + static { + this.RESPONSE = 2; + } + static { + this.ERROR = 3; + } + constructor(request, source) { + this.request = request; + this.source = source; + this.readyState = RequestController2.PENDING; + this.handled = new DeferredPromise(); + } + get #handled() { + return this.handled; + } + /** + * Perform this request as-is. + */ + async passthrough() { + invariant.as(InterceptorError, this.readyState === RequestController2.PENDING, 'Failed to passthrough the "%s %s" request: the request has already been handled', this.request.method, this.request.url); + this.readyState = RequestController2.PASSTHROUGH; + await this.source.passthrough(); + this.#handled.resolve(); + } + /** + * Respond to this request with the given `Response` instance. + * + * @example + * controller.respondWith(new Response()) + * controller.respondWith(Response.json({ id })) + * controller.respondWith(Response.error()) + */ + respondWith(response) { + invariant.as(InterceptorError, this.readyState === RequestController2.PENDING, 'Failed to respond to the "%s %s" request with "%d %s": the request has already been handled (%d)', this.request.method, this.request.url, response.status, response.statusText || "OK", this.readyState); + this.readyState = RequestController2.RESPONSE; + this.#handled.resolve(); + this.source.respondWith(response); + } + /** + * Error this request with the given reason. + * + * @example + * controller.errorWith() + * controller.errorWith(new Error('Oops!')) + * controller.errorWith({ message: 'Oops!'}) + */ + errorWith(reason) { + invariant.as(InterceptorError, this.readyState === RequestController2.PENDING, 'Failed to error the "%s %s" request with "%s": the request has already been handled (%d)', this.request.method, this.request.url, reason?.toString(), this.readyState); + this.readyState = RequestController2.ERROR; + this.source.errorWith(reason); + this.#handled.resolve(); + } +}; +function canParseUrl(url) { + try { + new URL(url); + return true; + } catch (_error) { + return false; + } +} +function getValueBySymbol(symbolName, source) { + const symbol = Object.getOwnPropertySymbols(source).find((symbol$1) => { + return symbol$1.description === symbolName; + }); + if (symbol) return Reflect.get(source, symbol); +} +var FetchResponse = class FetchResponse2 extends Response { + static { + this.STATUS_CODES_WITHOUT_BODY = [ + 101, + 103, + 204, + 205, + 304 + ]; + } + static { + this.STATUS_CODES_WITH_REDIRECT = [ + 301, + 302, + 303, + 307, + 308 + ]; + } + static isConfigurableStatusCode(status) { + return status >= 200 && status <= 599; + } + static isRedirectResponse(status) { + return FetchResponse2.STATUS_CODES_WITH_REDIRECT.includes(status); + } + /** + * Returns a boolean indicating whether the given response status + * code represents a response that can have a body. + */ + static isResponseWithBody(status) { + return !FetchResponse2.STATUS_CODES_WITHOUT_BODY.includes(status); + } + static setUrl(url, response) { + if (!url || url === "about:" || !canParseUrl(url)) return; + const state = getValueBySymbol("state", response); + if (state) state.urlList.push(new URL(url)); + else Object.defineProperty(response, "url", { + value: url, + enumerable: true, + configurable: true, + writable: false + }); + } + /** + * Parses the given raw HTTP headers into a Fetch API `Headers` instance. + */ + static parseRawHeaders(rawHeaders) { + const headers = new Headers(); + for (let line = 0; line < rawHeaders.length; line += 2) headers.append(rawHeaders[line], rawHeaders[line + 1]); + return headers; + } + constructor(body, init = {}) { + const status = init.status ?? 200; + const safeStatus = FetchResponse2.isConfigurableStatusCode(status) ? status : 200; + const finalBody = FetchResponse2.isResponseWithBody(status) ? body : null; + super(finalBody, { + status: safeStatus, + statusText: init.statusText, + headers: init.headers + }); + if (status !== safeStatus) { + const state = getValueBySymbol("state", this); + if (state) state.status = status; + else Object.defineProperty(this, "status", { + value: status, + enumerable: true, + configurable: true, + writable: false + }); + } + FetchResponse2.setUrl(init.url, this); + } +}; +var kRawRequest = Symbol("kRawRequest"); +function setRawRequest(request, rawRequest) { + Reflect.set(request, kRawRequest, rawRequest); +} + +// node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/lib/browser/bufferUtils-BiiO6HZv.mjs +var encoder = new TextEncoder(); +function encodeBuffer(text) { + return encoder.encode(text); +} +function decodeBuffer(buffer, encoding) { + return new TextDecoder(encoding).decode(buffer); +} +function toArrayBuffer(array) { + return array.buffer.slice(array.byteOffset, array.byteOffset + array.byteLength); +} + +// src/browser/sources/service-worker-source.ts +var import_network_source = require("../core/experimental/sources/network-source"); +var import_RequestHandler = require("../core/handlers/RequestHandler"); +var import_http_frame = require("../core/experimental/frames/http-frame"); +var import_HttpResponse = require("../core/HttpResponse"); +var import_toResponseInit = require("../core/utils/toResponseInit"); +var import_devUtils3 = require("../core/utils/internal/devUtils"); + +// node_modules/.pnpm/until-async@3.0.2/node_modules/until-async/lib/index.js +async function until(callback) { + try { + return [null, await callback().catch((error2) => { + throw error2; + })]; + } catch (error2) { + return [error2, null]; + } +} + +// src/browser/utils/get-worker-instance.ts +var import_devUtils = require("../core/utils/internal/devUtils"); + +// src/browser/utils/getAbsoluteWorkerUrl.ts +function getAbsoluteWorkerUrl(workerUrl) { + return new URL(workerUrl, location.href).href; +} + +// src/browser/utils/get-worker-by-registration.ts +function getWorkerByRegistration(registration, absoluteWorkerUrl, findWorker) { + const allStates = [ + registration.active, + registration.installing, + registration.waiting + ]; + const relevantStates = allStates.filter((state) => { + return state != null; + }); + const worker = relevantStates.find((worker2) => { + return findWorker(worker2.scriptURL, absoluteWorkerUrl); + }); + return worker || null; +} + +// src/browser/utils/get-worker-instance.ts +var getWorkerInstance = async (url, options = {}, findWorker) => { + const absoluteWorkerUrl = getAbsoluteWorkerUrl(url); + const mockRegistrations = await navigator.serviceWorker.getRegistrations().then( + (registrations) => registrations.filter( + (registration) => getWorkerByRegistration(registration, absoluteWorkerUrl, findWorker) + ) + ); + if (!navigator.serviceWorker.controller && mockRegistrations.length > 0) { + location.reload(); + } + const [existingRegistration] = mockRegistrations; + if (existingRegistration) { + existingRegistration.update(); + return [ + getWorkerByRegistration( + existingRegistration, + absoluteWorkerUrl, + findWorker + ), + existingRegistration + ]; + } + const [registrationError, registrationResult] = await until(async () => { + const registration = await navigator.serviceWorker.register(url, options); + return [ + // Compare existing worker registration by its worker URL, + // to prevent irrelevant workers to resolve here (such as Codesandbox worker). + getWorkerByRegistration(registration, absoluteWorkerUrl, findWorker), + registration + ]; + }); + if (registrationError) { + const isWorkerMissing = registrationError.message.includes("(404)"); + if (isWorkerMissing) { + const scopeUrl = new URL(options?.scope || "/", location.href); + throw new Error( + import_devUtils.devUtils.formatMessage(`Failed to register a Service Worker for scope ('${scopeUrl.href}') with script ('${absoluteWorkerUrl}'): Service Worker script does not exist at the given path. + +Did you forget to run "npx msw init "? + +Learn more about creating the Service Worker script: https://mswjs.io/docs/cli/init`) + ); + } + throw new Error( + import_devUtils.devUtils.formatMessage( + "Failed to register the Service Worker:\n\n%s", + registrationError.message + ) + ); + } + return registrationResult; +}; + +// node_modules/.pnpm/rettime@0.11.11/node_modules/rettime/build/lens-list.mjs +var LensList = class { + #list; + #lens; + constructor() { + this.#list = []; + this.#lens = /* @__PURE__ */ new Map(); + } + get [Symbol.iterator]() { + return this.#list[Symbol.iterator].bind(this.#list); + } + entries() { + return this.#lens.entries(); + } + /** + * Return an order-sensitive list of values by the given key. + */ + get(key) { + return this.#lens.get(key) || []; + } + /** + * Return an order-sensitive list of all values. + */ + getAll() { + return this.#list.map(([, value]) => value); + } + /** + * Append a new value to the given key. + */ + append(key, value) { + this.#list.push([key, value]); + this.#openLens(key, (list) => list.push(value)); + } + /** + * Prepend a new value to the given key. + */ + prepend(key, value) { + this.#list.unshift([key, value]); + this.#openLens(key, (list) => list.unshift(value)); + } + /** + * Delete the value belonging to the given key. + * Returns `true` if the value was present and removed, `false` otherwise. + */ + delete(key, value) { + if (this.size === 0) return false; + const values = this.#lens.get(key); + if (!values) return false; + const index = values.indexOf(value); + if (index === -1) return false; + values.splice(index, 1); + this.#list.splice(this.#list.findIndex((item) => item[0] === key && item[1] === value), 1); + return true; + } + /** + * Delete all values belogning to the given key. + */ + deleteAll(key) { + if (this.size === 0) return; + this.#list = this.#list.filter((item) => item[0] !== key); + this.#lens.delete(key); + } + get size() { + return this.#list.length; + } + clear() { + if (this.size === 0) return; + this.#list.length = 0; + this.#lens.clear(); + } + #openLens(key, setter) { + setter(this.#lens.get(key) || this.#lens.set(key, []).get(key)); + } +}; + +// node_modules/.pnpm/rettime@0.11.11/node_modules/rettime/build/index.mjs +var kDefaultPrevented2 = Symbol("kDefaultPrevented"); +var kPropagationStopped = Symbol("kPropagationStopped"); +var kImmediatePropagationStopped = Symbol("kImmediatePropagationStopped"); +var TypedEvent = class extends MessageEvent { + /** + * @note Keep a placeholder property with the return type + * because the type must be set somewhere in order to be + * correctly associated and inferred from the event. + */ + #returnType; + [kDefaultPrevented2]; + [kPropagationStopped]; + [kImmediatePropagationStopped]; + constructor(...args) { + super(args[0], args[1]); + this[kDefaultPrevented2] = false; + } + get defaultPrevented() { + return this[kDefaultPrevented2]; + } + preventDefault() { + super.preventDefault(); + this[kDefaultPrevented2] = true; + } + stopImmediatePropagation() { + super.stopImmediatePropagation(); + this[kImmediatePropagationStopped] = true; + } +}; +var Emitter2 = class { + #listeners; + #listenerOptions; + #listenerAbortCleanups; + #typelessListeners; + #hookListeners; + #hookListenerOptions; + #hookListenerAbortCleanups; + hooks; + constructor() { + this.#listeners = new LensList(); + this.#listenerOptions = /* @__PURE__ */ new WeakMap(); + this.#listenerAbortCleanups = /* @__PURE__ */ new WeakMap(); + this.#typelessListeners = /* @__PURE__ */ new WeakSet(); + this.#hookListeners = new LensList(); + this.#hookListenerOptions = /* @__PURE__ */ new WeakMap(); + this.#hookListenerAbortCleanups = /* @__PURE__ */ new WeakMap(); + this.hooks = { + on: (hook, callback, options) => { + if (options?.signal?.aborted) return; + if (options?.once) { + const original = callback; + const wrapper = ((...args) => { + this.#deleteHookListener(hook, wrapper); + return original(...args); + }); + callback = wrapper; + } + this.#hookListeners.append(hook, callback); + if (options) this.#hookListenerOptions.set(callback, options); + if (options?.signal) { + const { signal } = options; + const onAbort = () => { + this.#deleteHookListener(hook, callback); + }; + signal.addEventListener("abort", onAbort, { once: true }); + this.#hookListenerAbortCleanups.set(callback, () => { + signal.removeEventListener("abort", onAbort); + }); + } + }, + removeListener: (hook, callback) => { + this.#deleteHookListener(hook, callback); + } + }; + } + #deleteHookListener(hook, callback) { + this.#hookListeners.delete(hook, callback); + const cleanup = this.#hookListenerAbortCleanups.get(callback); + if (cleanup) { + cleanup(); + this.#hookListenerAbortCleanups.delete(callback); + } + } + #deleteListener(type, listener) { + const removed = this.#listeners.delete(type, listener); + const cleanup = this.#listenerAbortCleanups.get(listener); + if (cleanup) { + cleanup(); + this.#listenerAbortCleanups.delete(listener); + } + return removed; + } + /** + * Adds a listener for the given event type. + */ + on(type, listener, options) { + this.#addListener(type, listener, options); + return this; + } + /** + * Adds a one-time listener for the given event type. + */ + once(type, listener, options) { + return this.on(type, listener, { + ...options || {}, + once: true + }); + } + /** + * Prepends a listener for the given event type. + */ + earlyOn(type, listener, options) { + this.#addListener(type, listener, options, "prepend"); + return this; + } + /** + * Prepends a one-time listener for the given event type. + */ + earlyOnce(type, listener, options) { + return this.earlyOn(type, listener, { + ...options || {}, + once: true + }); + } + /** + * Emits the given typed event. + * + * @returns {boolean} Returns `true` if the event had any listeners, `false` otherwise. + */ + emit(event) { + if (this.#listeners.size === 0) return false; + const hasListeners = this.listenerCount(event.type) > 0; + const proxiedEvent = this.#proxyEvent(event); + for (const listener of this.#matchListeners(event.type)) { + if (proxiedEvent.event[kPropagationStopped] != null && proxiedEvent.event[kPropagationStopped] !== this) { + proxiedEvent.revoke(); + return false; + } + if (proxiedEvent.event[kImmediatePropagationStopped]) break; + this.#callListener(proxiedEvent.event, listener); + } + proxiedEvent.revoke(); + return hasListeners; + } + /** + * Emits the given typed event and returns a promise that resolves + * when all the listeners for that event have settled. + * + * @returns {Promise>} A promise that resolves + * with the return values of all listeners. + */ + async emitAsPromise(event) { + if (this.#listeners.size === 0) return []; + const pendingListeners = []; + const proxiedEvent = this.#proxyEvent(event); + for (const listener of this.#matchListeners(event.type)) { + if (proxiedEvent.event[kPropagationStopped] != null && proxiedEvent.event[kPropagationStopped] !== this) { + proxiedEvent.revoke(); + return []; + } + if (proxiedEvent.event[kImmediatePropagationStopped]) break; + const returnValue = await Promise.resolve(this.#callListener(proxiedEvent.event, listener)); + if (!this.#isTypelessListener(listener)) pendingListeners.push(returnValue); + } + proxiedEvent.revoke(); + return Promise.allSettled(pendingListeners).then((results) => { + return results.map((result) => result.status === "fulfilled" ? result.value : result.reason); + }); + } + /** + * Emits the given event and returns a generator that yields + * the result of each listener in the order of their registration. + * This way, you stop exhausting the listeners once you get the expected value. + */ + *emitAsGenerator(event) { + if (this.#listeners.size === 0) return; + const proxiedEvent = this.#proxyEvent(event); + for (const listener of this.#matchListeners(event.type)) { + if (proxiedEvent.event[kPropagationStopped] != null && proxiedEvent.event[kPropagationStopped] !== this) { + proxiedEvent.revoke(); + return; + } + if (proxiedEvent.event[kImmediatePropagationStopped]) break; + const returnValue = this.#callListener(proxiedEvent.event, listener); + if (!this.#isTypelessListener(listener)) yield returnValue; + } + proxiedEvent.revoke(); + } + /** + * Removes a listener for the given event type. + */ + removeListener(type, listener) { + const options = this.#listenerOptions.get(listener); + if (!this.#deleteListener(type, listener)) return; + for (const hook of this.#hookListeners.get("removeListener").slice()) hook(type, listener, options); + } + /** + * Removes all listeners for the given event type. + * If no event type is provided, removes all existing listeners. + */ + removeAllListeners(type) { + if (type == null) { + for (const [listenerType, listeners$1] of this.#listeners.entries()) while (listeners$1.length > 0) this.removeListener(listenerType, listeners$1[0]); + for (const [hookType, hookListener] of [...this.#hookListeners]) if (!this.#hookListenerOptions.get(hookListener)?.persist) this.#deleteHookListener(hookType, hookListener); + return; + } + const listeners = this.listeners(type); + while (listeners.length > 0) this.removeListener(type, listeners[0]); + } + /** + * Returns the list of listeners for the given event type. + * If no even type is provided, returns all listeners. + */ + listeners(type) { + if (type == null) return this.#listeners.getAll(); + return this.#listeners.get(type); + } + /** + * Returns the number of listeners for the given event type. + * If no even type is provided, returns the total number of listeners. + */ + listenerCount(type) { + if (type == null) return this.#listeners.size; + return this.listeners(type).length; + } + #addListener(type, listener, options, insertMode = "append") { + if (options?.signal?.aborted) return; + for (const hook of this.#hookListeners.get("newListener").slice()) hook(type, listener, options); + if (type === "*") this.#typelessListeners.add(listener); + if (insertMode === "prepend") this.#listeners.prepend(type, listener); + else this.#listeners.append(type, listener); + if (options) { + this.#listenerOptions.set(listener, options); + if (options.signal) { + const { signal } = options; + const onAbort = () => { + this.removeListener(type, listener); + }; + signal.addEventListener("abort", onAbort, { once: true }); + this.#listenerAbortCleanups.set(listener, () => { + signal.removeEventListener("abort", onAbort); + }); + } + } + } + #proxyEvent(event) { + const { stopPropagation } = event; + event.stopPropagation = () => { + event[kPropagationStopped] = this; + stopPropagation.call(event); + }; + return { + event, + revoke() { + event.stopPropagation = stopPropagation; + } + }; + } + #callListener(event, listener) { + for (const hook of this.#hookListeners.get("beforeEmit").slice()) if (hook(event) === false) return; + const returnValue = listener.call(this, event); + const options = this.#listenerOptions.get(listener); + if (options?.once) { + const type = this.#isTypelessListener(listener) ? "*" : event.type; + if (this.#deleteListener(type, listener)) for (const hook of this.#hookListeners.get("removeListener").slice()) hook(type, listener, options); + } + return returnValue; + } + /** + * Return a list of all event listeners relevant for the given event type. + * This includes the explicit event listeners and also typeless event listeners. + * + * @note Snapshot the matching listeners before yielding. Listeners can add or + * remove other listeners during emission (e.g. `earlyOn` unshifts `#list`), + * which would otherwise shift the live iterator and re-yield prior entries. + */ + *#matchListeners(type) { + const snapshot = []; + for (const [key, listener] of this.#listeners) if (key === "*" || key === type) snapshot.push(listener); + yield* snapshot; + } + #isTypelessListener(listener) { + return this.#typelessListeners.has(listener); + } +}; + +// src/browser/utils/workerChannel.ts +var import_isObject = require("../core/utils/internal/isObject"); +var SUPPORTS_SERVICE_WORKER = supportsServiceWorker(); +var WorkerEvent = class extends TypedEvent { + #workerEvent; + constructor(workerEvent) { + const type = workerEvent.data.type; + const data = workerEvent.data.payload; + super( + // @ts-expect-error Troublesome `TypedEvent` extension. + type, + { data } + ); + this.#workerEvent = workerEvent; + } + get ports() { + return this.#workerEvent.ports; + } + /** + * Reply directly to this event using its `MessagePort`. + */ + postMessage(type, ...rest) { + this.#workerEvent.ports[0].postMessage( + { type, data: rest[0] }, + { transfer: rest[1] } + ); + } +}; +var WorkerChannel = class extends Emitter2 { + #getWorker; + #controller; + constructor(options) { + super(); + invariant( + SUPPORTS_SERVICE_WORKER, + "Failed to open a WorkerChannel: Service Worker is not supported in this environment." + ); + this.#getWorker = options.getWorker; + this.#controller = new AbortController(); + navigator.serviceWorker.addEventListener( + "message", + async (event) => { + const worker = await this.#getWorker(); + if (event.source != null && event.source !== worker) { + return; + } + if (event.data && (0, import_isObject.isObject)(event.data) && "type" in event.data) { + this.emit(new WorkerEvent(event)); + } + }, + { + signal: this.#controller.signal + } + ); + } + /** + * Send data to the Service Worker controlling this client. + * This triggers the `message` event listener on ServiceWorkerGlobalScope. + */ + postMessage(type) { + invariant( + SUPPORTS_SERVICE_WORKER, + "Failed to post message on a WorkerChannel: the Service Worker API is unavailable in this environment. This is likely an issue with MSW. Please report it on GitHub: https://github.com/mswjs/msw/issues" + ); + this.#getWorker().then((worker) => { + worker.postMessage(type); + }); + } + /** + * Terminal teardown. Removes the `navigator.serviceWorker` message listener + * and all emitter subscriptions. The channel is not usable afterwards. + */ + terminate() { + this.#controller.abort(); + this.removeAllListeners(); + } +}; + +// src/browser/utils/pruneGetRequestBody.ts +function pruneGetRequestBody(request) { + if (["HEAD", "GET"].includes(request.method)) { + return void 0; + } + return request.body; +} + +// src/browser/utils/deserializeRequest.ts +function deserializeRequest(serializedRequest) { + return new Request(serializedRequest.url, { + ...serializedRequest, + body: pruneGetRequestBody(serializedRequest) + }); +} + +// src/browser/utils/validate-worker-scope.ts +var import_devUtils2 = require("../core/utils/internal/devUtils"); +function validateWorkerScope(registration) { + if (!location.href.startsWith(registration.scope)) { + import_devUtils2.devUtils.warn( + `Cannot intercept requests on this page because it's outside of the worker's scope ("${registration.scope}"). If you wish to mock API requests on this page, you must resolve this scope issue. + +- (Recommended) Register the worker at the root level ("/") of your application. +- Set the "Service-Worker-Allowed" response header to allow out-of-scope workers.` + ); + } +} + +// src/browser/utils/should-invalidate-worker.ts +function shouldInvalidateWorker(prevOptions, nextOptions) { + return prevOptions.findWorker !== nextOptions.findWorker || prevOptions.serviceWorker.url !== nextOptions.serviceWorker.url || JSON.stringify(prevOptions.serviceWorker.options) !== JSON.stringify(nextOptions.serviceWorker.options); +} + +// src/browser/sources/service-worker-source.ts +var ServiceWorkerSource = class _ServiceWorkerSource extends import_network_source.NetworkSource { + static #current; + /** + * Create a new Service Worker source or reuse an existing one. + * These sources act as a singleton and only get recreated if the options change. + */ + static async from(options) { + if (_ServiceWorkerSource.#current == null) { + _ServiceWorkerSource.#current = new _ServiceWorkerSource(options); + } else if (shouldInvalidateWorker(_ServiceWorkerSource.#current.#options, options)) { + await _ServiceWorkerSource.#current.terminate(); + _ServiceWorkerSource.#current = new _ServiceWorkerSource(options); + } + return _ServiceWorkerSource.#current; + } + #options; + #frames; + #channel; + #listenerController; + #clientPromise; + #keepAliveInterval; + #stoppedAt; + workerPromise; + constructor(options) { + super(); + invariant( + supportsServiceWorker(), + "Failed to use Service Worker as the network source: the Service Worker API is not supported in this environment" + ); + this.#options = options; + this.#frames = /* @__PURE__ */ new Map(); + this.workerPromise = new DeferredPromise2(); + this.#channel = new WorkerChannel({ + getWorker: () => this.workerPromise.then(([worker]) => worker) + }); + } + async enable() { + if (this.workerPromise.state === "fulfilled" && typeof this.#stoppedAt == "undefined") { + import_devUtils3.devUtils.warn( + 'Found a redundant "worker.start()" call. Note that starting the worker while mocking is already enabled will have no effect. Consider removing this "worker.start()" call.' + ); + return this.workerPromise.then(([, registration2]) => registration2); + } + this.#stoppedAt = void 0; + this.#channel.removeAllListeners(); + this.#frames.clear(); + this.#listenerController = new AbortController(); + const [worker, registration] = await this.#startWorker(); + if (worker.state !== "activated") { + const controller = new AbortController(); + const activationPromise = new DeferredPromise2(); + activationPromise.then(() => controller.abort()); + worker.addEventListener( + "statechange", + () => { + if (worker.state === "activated") { + activationPromise.resolve(); + } + }, + { + signal: controller.signal + } + ); + await activationPromise; + } + this.#channel.postMessage("MOCK_ACTIVATE"); + const clientConfirmationPromise = new DeferredPromise2(); + this.#clientPromise = clientConfirmationPromise; + this.#channel.once("MOCKING_ENABLED", (event) => { + clientConfirmationPromise.resolve(event.data.client); + }); + await clientConfirmationPromise; + if (!this.#options.quiet) { + this.#printStartMessage(); + } + return registration; + } + disable() { + if (typeof this.#stoppedAt !== "undefined") { + import_devUtils3.devUtils.warn( + `Found a redundant "worker.stop()" call. Notice that stopping the worker after it has already been stopped has no effect. Consider removing this "worker.stop()" call.` + ); + return; + } + this.#stoppedAt = Date.now(); + this.#listenerController?.abort(); + this.#listenerController = void 0; + this.#channel.postMessage("CLIENT_CLOSED"); + if (!this.#options.quiet) { + this.#printStopMessage(); + } + } + /** + * Terminal teardown. Unregisters the Service Worker, tears down the channel, + * and clears timers. Called when the singleton is being replaced with one + * that has different options. The instance is not usable afterwards. + */ + async terminate() { + if (this.#keepAliveInterval != null) { + clearInterval(this.#keepAliveInterval); + this.#keepAliveInterval = void 0; + } + this.#frames.clear(); + this.#channel.terminate(); + this.#listenerController?.abort(); + this.#listenerController = void 0; + if (this.workerPromise.state === "fulfilled") { + const [, registration] = await this.workerPromise; + await registration.unregister(); + } + if (_ServiceWorkerSource.#current === this) { + _ServiceWorkerSource.#current = void 0; + } + } + async #startWorker() { + if (this.#keepAliveInterval) { + clearInterval(this.#keepAliveInterval); + } + const workerUrl = this.#options.serviceWorker.url; + const [worker, registration] = await getWorkerInstance( + workerUrl, + this.#options.serviceWorker.options, + this.#options.findWorker || this.#defaultFindWorker + ); + if (worker == null) { + const missingWorkerMessage = this.#options?.findWorker ? import_devUtils3.devUtils.formatMessage( + `Failed to locate the Service Worker registration using a custom "findWorker" predicate. + +Please ensure that the custom predicate properly locates the Service Worker registration at "%s". +More details: https://mswjs.io/docs/api/setup-worker/start#findworker + `, + workerUrl + ) : import_devUtils3.devUtils.formatMessage( + `Failed to locate the Service Worker registration. + +This most likely means that the worker script URL "%s" cannot resolve against the actual public hostname (%s). This may happen if your application runs behind a proxy, or has a dynamic hostname. + +Please consider using a custom "serviceWorker.url" option to point to the actual worker script location, or a custom "findWorker" option to resolve the Service Worker registration manually. More details: https://mswjs.io/docs/api/setup-worker/start`, + workerUrl, + location.host + ); + throw new Error(missingWorkerMessage); + } + if (this.workerPromise.state === "pending") { + this.workerPromise.resolve([worker, registration]); + } else { + this.workerPromise = new DeferredPromise2((resolve) => { + resolve([worker, registration]); + }); + } + this.#channel.on("REQUEST", this.#handleRequest.bind(this)); + this.#channel.on("RESPONSE", this.#handleResponse.bind(this)); + window.addEventListener( + "beforeunload", + () => { + if (worker.state !== "redundant") { + this.#channel.postMessage("CLIENT_CLOSED"); + } + clearInterval(this.#keepAliveInterval); + window.postMessage({ type: "msw/worker:stop" }); + }, + { + signal: this.#listenerController?.signal + } + ); + await this.#checkWorkerIntegrity().catch((error2) => { + import_devUtils3.devUtils.error( + "Error while checking the worker script integrity. Please report this on GitHub (https://github.com/mswjs/msw/issues) and include the original error below." + ); + console.error(error2); + }); + this.#keepAliveInterval = window.setInterval(() => { + this.#channel.postMessage("KEEPALIVE_REQUEST"); + }, 5e3); + if (!this.#options.quiet) { + validateWorkerScope(registration); + } + return [worker, registration]; + } + async #handleRequest(event) { + if (this.#stoppedAt && event.data.interceptedAt > this.#stoppedAt) { + return event.postMessage("PASSTHROUGH"); + } + const request = deserializeRequest(event.data); + import_RequestHandler.RequestHandler.cache.set(request, request.clone()); + const frame = new ServiceWorkerHttpNetworkFrame({ + event, + request + }); + this.#frames.set(event.data.id, frame); + await this.queue(frame); + } + async #handleResponse(event) { + const { request, response, isMockedResponse } = event.data; + const frame = this.#frames.get(request.id); + if (response.type?.includes("opaque")) { + this.#frames.delete(request.id); + frame?.events.removeAllListeners(); + return; + } + this.#frames.delete(request.id); + if (frame == null) { + return; + } + const fetchRequest = deserializeRequest(request); + const fetchResponse = response.status === 0 ? Response.error() : new FetchResponse( + /** + * Responses may be streams here, but when we create a response object + * with null-body status codes, like 204, 205, 304 Response will + * throw when passed a non-null body, so ensure it's null here + * for those codes + */ + FetchResponse.isResponseWithBody(response.status) ? response.body : null, + { + ...response, + /** + * Set response URL if it's not set already. + * @see https://github.com/mswjs/msw/issues/2030 + * @see https://developer.mozilla.org/en-US/docs/Web/API/Response/url + */ + url: request.url + } + ); + try { + frame.events.emit( + new import_http_frame.ResponseEvent( + isMockedResponse ? "response:mocked" : "response:bypass", + { + requestId: frame.data.id, + request: fetchRequest, + response: fetchResponse, + isMockedResponse + } + ) + ); + } finally { + frame.events.removeAllListeners(); + } + } + #defaultFindWorker = (workerUrl, mockServiceWorkerUrl) => { + return workerUrl === mockServiceWorkerUrl; + }; + async #checkWorkerIntegrity() { + const integrityCheckPromise = new DeferredPromise2(); + this.#channel.postMessage("INTEGRITY_CHECK_REQUEST"); + this.#channel.once("INTEGRITY_CHECK_RESPONSE", (event) => { + const { checksum, packageVersion } = event.data; + if (checksum !== "4db4a41e972cec1b64cc569c66952d82") { + import_devUtils3.devUtils.warn( + `The currently registered Service Worker has been generated by a different version of MSW (${packageVersion}) and may not be fully compatible with the installed version. + +It's recommended you update your worker script by running this command: + + \u2022 npx msw init + +You can also automate this process and make the worker script update automatically upon the library installations. Read more: https://mswjs.io/docs/cli/init.` + ); + } + integrityCheckPromise.resolve(); + }); + return integrityCheckPromise; + } + async #printStartMessage() { + if (this.workerPromise.state === "rejected") { + return; + } + invariant( + this.#clientPromise != null, + "[ServiceWorkerSource] Failed to print a start message: client confirmation not received" + ); + const client = await this.#clientPromise; + const [worker, registration] = await this.workerPromise; + console.groupCollapsed( + `%c${import_devUtils3.devUtils.formatMessage("Mocking enabled.")}`, + "color:orangered;font-weight:bold;" + ); + console.log( + "%cDocumentation: %chttps://mswjs.io/docs", + "font-weight:bold", + "font-weight:normal" + ); + console.log("Found an issue? https://github.com/mswjs/msw/issues"); + console.log("Worker script URL:", worker.scriptURL); + console.log("Worker scope:", registration.scope); + if (client) { + console.log("Client ID: %s (%s)", client.id, client.frameType); + } + console.groupEnd(); + } + #printStopMessage() { + console.log( + `%c${import_devUtils3.devUtils.formatMessage("Mocking disabled.")}`, + "color:orangered;font-weight:bold;" + ); + } +}; +var ServiceWorkerHttpNetworkFrame = class extends import_http_frame.HttpNetworkFrame { + #event; + constructor(options) { + super({ request: options.request }); + this.#event = options.event; + } + passthrough() { + this.#event.postMessage("PASSTHROUGH"); + } + respondWith(response) { + if (response) { + this.#respondWith(response); + } + } + errorWith(reason) { + if (reason instanceof Response) { + return this.respondWith(reason); + } + import_devUtils3.devUtils.warn( + `Uncaught exception in the request handler for "%s %s". This exception has been gracefully handled as a 500 response, however, it's strongly recommended to resolve this error, as it indicates a mistake in your code. If you wish to mock an error response, please see this guide: https://mswjs.io/docs/http/mocking-responses/error-responses`, + this.data.request.method, + this.data.request.url + ); + const error2 = reason instanceof Error ? reason : new Error(reason?.toString() || "Request failure"); + this.respondWith( + import_HttpResponse.HttpResponse.json( + { + name: error2.name, + message: error2.message, + stack: error2.stack + }, + { + status: 500, + statusText: "Request Handler Error" + } + ) + ); + } + async #respondWith(response) { + let responseBody; + let transfer; + const responseInit = (0, import_toResponseInit.toResponseInit)(response); + if (supportsReadableStreamTransfer()) { + responseBody = response.body; + transfer = response.body == null ? void 0 : [response.body]; + } else { + responseBody = response.body == null ? null : await response.clone().arrayBuffer(); + } + this.#event.postMessage( + "MOCK_RESPONSE", + { + ...responseInit, + body: responseBody + }, + transfer + ); + } +}; + +// node_modules/.pnpm/@open-draft+until@2.1.0/node_modules/@open-draft/until/lib/index.mjs +var until2 = async (promise) => { + try { + const data = await promise().catch((error2) => { + throw error2; + }); + return { error: null, data }; + } catch (error2) { + return { error: error2, data: null }; + } +}; + +// node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/lib/browser/handleRequest-D7kpTI5U.mjs +function isObject2(value, loose = false) { + return loose ? Object.prototype.toString.call(value).startsWith("[object ") : Object.prototype.toString.call(value) === "[object Object]"; +} +function isPropertyAccessible(obj, key) { + try { + obj[key]; + return true; + } catch { + return false; + } +} +function createServerErrorResponse(body) { + return new Response(JSON.stringify(body instanceof Error ? { + name: body.name, + message: body.message, + stack: body.stack + } : body), { + status: 500, + statusText: "Unhandled Exception", + headers: { "Content-Type": "application/json" } + }); +} +function isResponseError(response) { + return response != null && response instanceof Response && isPropertyAccessible(response, "type") && response.type === "error"; +} +function isResponseLike(value) { + return isObject2(value, true) && isPropertyAccessible(value, "status") && isPropertyAccessible(value, "statusText") && isPropertyAccessible(value, "bodyUsed"); +} +function isNodeLikeError(error2) { + if (error2 == null) return false; + if (!(error2 instanceof Error)) return false; + return "code" in error2 && "errno" in error2; +} +async function handleRequest(options) { + const handleResponse = async (response) => { + if (response instanceof Error) { + await options.controller.errorWith(response); + return true; + } + if (isResponseError(response)) { + await options.controller.respondWith(response); + return true; + } + if (isResponseLike(response)) { + await options.controller.respondWith(response); + return true; + } + if (isObject2(response)) { + await options.controller.errorWith(response); + return true; + } + return false; + }; + const handleResponseError = async (error2) => { + if (error2 instanceof InterceptorError) throw result.error; + if (isNodeLikeError(error2)) { + await options.controller.errorWith(error2); + return true; + } + if (error2 instanceof Response) return await handleResponse(error2); + return false; + }; + const requestAbortPromise = new DeferredPromise(); + if (options.request.signal) { + if (options.request.signal.aborted) { + await options.controller.errorWith(options.request.signal.reason); + return; + } + options.request.signal.addEventListener("abort", () => { + requestAbortPromise.reject(options.request.signal.reason); + }, { once: true }); + } + const result = await until2(async () => { + const requestListenersPromise = emitAsync(options.emitter, "request", { + requestId: options.requestId, + request: options.request, + controller: options.controller + }); + await Promise.race([ + requestAbortPromise, + requestListenersPromise, + options.controller.handled + ]); + }); + if (requestAbortPromise.state === "rejected") { + await options.controller.errorWith(requestAbortPromise.rejectionReason); + return; + } + if (result.error) { + if (await handleResponseError(result.error)) return; + if (options.emitter.listenerCount("unhandledException") > 0) { + const unhandledExceptionController = new RequestController(options.request, { + passthrough() { + }, + async respondWith(response) { + await handleResponse(response); + }, + async errorWith(reason) { + await options.controller.errorWith(reason); + } + }); + await emitAsync(options.emitter, "unhandledException", { + error: result.error, + request: options.request, + requestId: options.requestId, + controller: unhandledExceptionController + }); + if (unhandledExceptionController.readyState !== RequestController.PENDING) return; + } + await options.controller.respondWith(createServerErrorResponse(result.error)); + return; + } + if (options.controller.readyState === RequestController.PENDING) return await options.controller.passthrough(); + return options.controller.handled; +} + +// node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/lib/browser/fetch-DdKEdDOR.mjs +function createNetworkError(cause) { + return Object.assign(/* @__PURE__ */ new TypeError("Failed to fetch"), { cause }); +} +var REQUEST_BODY_HEADERS = [ + "content-encoding", + "content-language", + "content-location", + "content-type", + "content-length" +]; +var kRedirectCount = Symbol("kRedirectCount"); +async function followFetchRedirect(request, response) { + if (response.status !== 303 && request.body != null) return Promise.reject(createNetworkError()); + const requestUrl = new URL(request.url); + let locationUrl; + try { + locationUrl = new URL(response.headers.get("location"), request.url); + } catch (error2) { + return Promise.reject(createNetworkError(error2)); + } + if (!(locationUrl.protocol === "http:" || locationUrl.protocol === "https:")) return Promise.reject(createNetworkError("URL scheme must be a HTTP(S) scheme")); + if (Reflect.get(request, kRedirectCount) > 20) return Promise.reject(createNetworkError("redirect count exceeded")); + Object.defineProperty(request, kRedirectCount, { value: (Reflect.get(request, kRedirectCount) || 0) + 1 }); + if (request.mode === "cors" && (locationUrl.username || locationUrl.password) && !sameOrigin(requestUrl, locationUrl)) return Promise.reject(createNetworkError('cross origin not allowed for request mode "cors"')); + const requestInit = {}; + if ([301, 302].includes(response.status) && request.method === "POST" || response.status === 303 && !["HEAD", "GET"].includes(request.method)) { + requestInit.method = "GET"; + requestInit.body = null; + REQUEST_BODY_HEADERS.forEach((headerName) => { + request.headers.delete(headerName); + }); + } + if (!sameOrigin(requestUrl, locationUrl)) { + request.headers.delete("authorization"); + request.headers.delete("proxy-authorization"); + request.headers.delete("cookie"); + request.headers.delete("host"); + } + requestInit.headers = request.headers; + const finalResponse = await fetch(new Request(locationUrl, requestInit)); + Object.defineProperty(finalResponse, "redirected", { + value: true, + configurable: true + }); + return finalResponse; +} +function sameOrigin(left, right) { + if (left.origin === right.origin && left.origin === "null") return true; + if (left.protocol === right.protocol && left.hostname === right.hostname && left.port === right.port) return true; + return false; +} +var BrotliDecompressionStream = class extends TransformStream { + constructor() { + console.warn("[Interceptors]: Brotli decompression of response streams is not supported in the browser"); + super({ transform(chunk, controller) { + controller.enqueue(chunk); + } }); + } +}; +var PipelineStream = class extends TransformStream { + constructor(transformStreams, ...strategies) { + super({}, ...strategies); + const readable = [super.readable, ...transformStreams].reduce((readable$1, transform) => readable$1.pipeThrough(transform)); + Object.defineProperty(this, "readable", { get() { + return readable; + } }); + } +}; +function parseContentEncoding(contentEncoding) { + return contentEncoding.toLowerCase().split(",").map((coding) => coding.trim()); +} +function createDecompressionStream(contentEncoding) { + if (contentEncoding === "") return null; + const codings = parseContentEncoding(contentEncoding); + if (codings.length === 0) return null; + return new PipelineStream(codings.reduceRight((transformers, coding) => { + if (coding === "gzip" || coding === "x-gzip") return transformers.concat(new DecompressionStream("gzip")); + else if (coding === "deflate") return transformers.concat(new DecompressionStream("deflate")); + else if (coding === "br") return transformers.concat(new BrotliDecompressionStream()); + else transformers.length = 0; + return transformers; + }, [])); +} +function decompressResponse(response) { + if (response.body === null) return null; + const decompressionStream = createDecompressionStream(response.headers.get("content-encoding") || ""); + if (!decompressionStream) return null; + response.body.pipeTo(decompressionStream.writable); + return decompressionStream.readable; +} +var FetchInterceptor = class FetchInterceptor2 extends Interceptor { + static { + this.symbol = Symbol("fetch"); + } + constructor() { + super(FetchInterceptor2.symbol); + } + checkEnvironment() { + return hasConfigurableGlobal("fetch"); + } + async setup() { + const pureFetch = globalThis.fetch; + invariant(!pureFetch[IS_PATCHED_MODULE], 'Failed to patch the "fetch" module: already patched.'); + globalThis.fetch = async (input, init) => { + const requestId = createRequestId(); + const resolvedInput = typeof input === "string" && typeof location !== "undefined" && !canParseUrl(input) ? new URL(input, location.href) : input; + const request = new Request(resolvedInput, init); + if (input instanceof Request) setRawRequest(request, input); + const responsePromise = new DeferredPromise(); + const controller = new RequestController(request, { + passthrough: async () => { + this.logger.info("request has not been handled, passthrough..."); + const requestCloneForResponseEvent = request.clone(); + const { error: responseError, data: originalResponse } = await until2(() => pureFetch(request)); + if (responseError) return responsePromise.reject(responseError); + this.logger.info("original fetch performed", originalResponse); + if (this.emitter.listenerCount("response") > 0) { + this.logger.info('emitting the "response" event...'); + const responseClone = originalResponse.clone(); + await emitAsync(this.emitter, "response", { + response: responseClone, + isMockedResponse: false, + request: requestCloneForResponseEvent, + requestId + }); + } + responsePromise.resolve(originalResponse); + }, + respondWith: async (rawResponse) => { + if (isResponseError(rawResponse)) { + this.logger.info("request has errored!", { response: rawResponse }); + responsePromise.reject(createNetworkError(rawResponse)); + return; + } + this.logger.info("received mocked response!", { rawResponse }); + const decompressedStream = decompressResponse(rawResponse); + const response = decompressedStream === null ? rawResponse : new FetchResponse(decompressedStream, rawResponse); + FetchResponse.setUrl(request.url, response); + if (FetchResponse.isRedirectResponse(response.status)) { + if (request.redirect === "error") { + responsePromise.reject(createNetworkError("unexpected redirect")); + return; + } + if (request.redirect === "follow") { + followFetchRedirect(request, response).then((response$1) => { + responsePromise.resolve(response$1); + }, (reason) => { + responsePromise.reject(reason); + }); + return; + } + } + if (this.emitter.listenerCount("response") > 0) { + this.logger.info('emitting the "response" event...'); + await emitAsync(this.emitter, "response", { + response: response.clone(), + isMockedResponse: true, + request, + requestId + }); + } + responsePromise.resolve(response); + }, + errorWith: (reason) => { + this.logger.info("request has been aborted!", { reason }); + responsePromise.reject(reason); + } + }); + this.logger.info("[%s] %s", request.method, request.url); + this.logger.info("awaiting for the mocked response..."); + this.logger.info('emitting the "request" event for %s listener(s)...', this.emitter.listenerCount("request")); + await handleRequest({ + request, + requestId, + emitter: this.emitter, + controller + }); + return responsePromise; + }; + Object.defineProperty(globalThis.fetch, IS_PATCHED_MODULE, { + enumerable: true, + configurable: true, + value: true + }); + this.subscriptions.push(() => { + Object.defineProperty(globalThis.fetch, IS_PATCHED_MODULE, { value: void 0 }); + globalThis.fetch = pureFetch; + this.logger.info('restored native "globalThis.fetch"!', globalThis.fetch.name); + }); + } +}; + +// node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/lib/browser/XMLHttpRequest-BvxZV0WU.mjs +function concatArrayBuffer(left, right) { + const result = new Uint8Array(left.byteLength + right.byteLength); + result.set(left, 0); + result.set(right, left.byteLength); + return result; +} +var EventPolyfill = class { + constructor(type, options) { + this.NONE = 0; + this.CAPTURING_PHASE = 1; + this.AT_TARGET = 2; + this.BUBBLING_PHASE = 3; + this.type = ""; + this.srcElement = null; + this.currentTarget = null; + this.eventPhase = 0; + this.isTrusted = true; + this.composed = false; + this.cancelable = true; + this.defaultPrevented = false; + this.bubbles = true; + this.lengthComputable = true; + this.loaded = 0; + this.total = 0; + this.cancelBubble = false; + this.returnValue = true; + this.type = type; + this.target = options?.target || null; + this.currentTarget = options?.currentTarget || null; + this.timeStamp = Date.now(); + } + composedPath() { + return []; + } + initEvent(type, bubbles, cancelable) { + this.type = type; + this.bubbles = !!bubbles; + this.cancelable = !!cancelable; + } + preventDefault() { + this.defaultPrevented = true; + } + stopPropagation() { + } + stopImmediatePropagation() { + } +}; +var ProgressEventPolyfill = class extends EventPolyfill { + constructor(type, init) { + super(type); + this.lengthComputable = init?.lengthComputable || false; + this.composed = init?.composed || false; + this.loaded = init?.loaded || 0; + this.total = init?.total || 0; + } +}; +var SUPPORTS_PROGRESS_EVENT = typeof ProgressEvent !== "undefined"; +function createEvent(target, type, init) { + const progressEvents = [ + "error", + "progress", + "loadstart", + "loadend", + "load", + "timeout", + "abort" + ]; + const ProgressEventClass = SUPPORTS_PROGRESS_EVENT ? ProgressEvent : ProgressEventPolyfill; + return progressEvents.includes(type) ? new ProgressEventClass(type, { + lengthComputable: true, + loaded: init?.loaded || 0, + total: init?.total || 0 + }) : new EventPolyfill(type, { + target, + currentTarget: target + }); +} +function findPropertySource(target, propertyName) { + if (!(propertyName in target)) return null; + if (Object.prototype.hasOwnProperty.call(target, propertyName)) return target; + const prototype = Reflect.getPrototypeOf(target); + return prototype ? findPropertySource(prototype, propertyName) : null; +} +function createProxy(target, options) { + return new Proxy(target, optionsToProxyHandler(options)); +} +function optionsToProxyHandler(options) { + const { constructorCall, methodCall, getProperty, setProperty } = options; + const handler = {}; + if (typeof constructorCall !== "undefined") handler.construct = function(target, args, newTarget) { + const next = Reflect.construct.bind(null, target, args, newTarget); + return constructorCall.call(newTarget, args, next); + }; + handler.set = function(target, propertyName, nextValue) { + const next = () => { + const propertySource = findPropertySource(target, propertyName) || target; + const ownDescriptors = Reflect.getOwnPropertyDescriptor(propertySource, propertyName); + if (typeof ownDescriptors?.set !== "undefined") { + ownDescriptors.set.apply(target, [nextValue]); + return true; + } + return Reflect.defineProperty(propertySource, propertyName, { + writable: true, + enumerable: true, + configurable: true, + value: nextValue + }); + }; + if (typeof setProperty !== "undefined") return setProperty.call(target, [propertyName, nextValue], next); + return next(); + }; + handler.get = function(target, propertyName, receiver) { + const next = () => target[propertyName]; + const value = typeof getProperty !== "undefined" ? getProperty.call(target, [propertyName, receiver], next) : next(); + if (typeof value === "function") return (...args) => { + const next$1 = value.bind(target, ...args); + if (typeof methodCall !== "undefined") return methodCall.call(target, [propertyName, args], next$1); + return next$1(); + }; + return value; + }; + return handler; +} +function isDomParserSupportedType(type) { + return [ + "application/xhtml+xml", + "application/xml", + "image/svg+xml", + "text/html", + "text/xml" + ].some((supportedType) => { + return type.startsWith(supportedType); + }); +} +function parseJson(data) { + try { + return JSON.parse(data); + } catch (_) { + return null; + } +} +function createResponse(request, body) { + return new FetchResponse(FetchResponse.isResponseWithBody(request.status) ? body : null, { + url: request.responseURL, + status: request.status, + statusText: request.statusText, + headers: createHeadersFromXMLHttpRequestHeaders(request.getAllResponseHeaders()) + }); +} +function createHeadersFromXMLHttpRequestHeaders(headersString) { + const headers = new Headers(); + const lines = headersString.split(/[\r\n]+/); + for (const line of lines) { + if (line.trim() === "") continue; + const [name, ...parts] = line.split(": "); + const value = parts.join(": "); + headers.append(name, value); + } + return headers; +} +async function getBodyByteLength(input) { + const explicitContentLength = input.headers.get("content-length"); + if (explicitContentLength != null && explicitContentLength !== "") return Number(explicitContentLength); + return (await input.arrayBuffer()).byteLength; +} +var kIsRequestHandled = Symbol("kIsRequestHandled"); +var IS_NODE2 = isNodeProcess(); +var kFetchRequest = Symbol("kFetchRequest"); +var XMLHttpRequestController = class { + constructor(initialRequest, logger) { + this.initialRequest = initialRequest; + this.logger = logger; + this.method = "GET"; + this.url = null; + this[kIsRequestHandled] = false; + this.events = /* @__PURE__ */ new Map(); + this.uploadEvents = /* @__PURE__ */ new Map(); + this.requestId = createRequestId(); + this.requestHeaders = new Headers(); + this.responseBuffer = new Uint8Array(); + this.request = createProxy(initialRequest, { + setProperty: ([propertyName, nextValue], invoke) => { + switch (propertyName) { + case "ontimeout": { + const eventName = propertyName.slice(2); + this.request.addEventListener(eventName, nextValue); + return invoke(); + } + default: + return invoke(); + } + }, + methodCall: ([methodName, args], invoke) => { + switch (methodName) { + case "open": { + const [method, url] = args; + if (typeof url === "undefined") { + this.method = "GET"; + this.url = toAbsoluteUrl(method); + } else { + this.method = method; + this.url = toAbsoluteUrl(url); + } + this.logger = this.logger.extend(`${this.method} ${this.url.href}`); + this.logger.info("open", this.method, this.url.href); + return invoke(); + } + case "addEventListener": { + const [eventName, listener] = args; + this.registerEvent(eventName, listener); + this.logger.info("addEventListener", eventName, listener); + return invoke(); + } + case "setRequestHeader": { + const [name, value] = args; + this.requestHeaders.set(name, value); + this.logger.info("setRequestHeader", name, value); + return invoke(); + } + case "send": { + const [body] = args; + this.request.addEventListener("load", () => { + if (typeof this.onResponse !== "undefined") { + const fetchResponse = createResponse( + this.request, + /** + * The `response` property is the right way to read + * the ambiguous response body, as the request's "responseType" may differ. + * @see https://xhr.spec.whatwg.org/#the-response-attribute + */ + this.request.response + ); + this.onResponse.call(this, { + response: fetchResponse, + isMockedResponse: this[kIsRequestHandled], + request: fetchRequest, + requestId: this.requestId + }); + } + }); + const requestBody = typeof body === "string" ? encodeBuffer(body) : body; + const fetchRequest = this.toFetchApiRequest(requestBody); + this[kFetchRequest] = fetchRequest.clone(); + queueMicrotask(() => { + (this.onRequest?.call(this, { + request: fetchRequest, + requestId: this.requestId + }) || Promise.resolve()).finally(() => { + if (!this[kIsRequestHandled]) { + this.logger.info("request callback settled but request has not been handled (readystate %d), performing as-is...", this.request.readyState); + if (IS_NODE2) this.request.setRequestHeader(INTERNAL_REQUEST_ID_HEADER_NAME, this.requestId); + return invoke(); + } + }); + }); + break; + } + default: + return invoke(); + } + } + }); + define(this.request, "upload", createProxy(this.request.upload, { + setProperty: ([propertyName, nextValue], invoke) => { + switch (propertyName) { + case "onloadstart": + case "onprogress": + case "onaboart": + case "onerror": + case "onload": + case "ontimeout": + case "onloadend": { + const eventName = propertyName.slice(2); + this.registerUploadEvent(eventName, nextValue); + } + } + return invoke(); + }, + methodCall: ([methodName, args], invoke) => { + switch (methodName) { + case "addEventListener": { + const [eventName, listener] = args; + this.registerUploadEvent(eventName, listener); + this.logger.info("upload.addEventListener", eventName, listener); + return invoke(); + } + } + } + })); + } + registerEvent(eventName, listener) { + const nextEvents = (this.events.get(eventName) || []).concat(listener); + this.events.set(eventName, nextEvents); + this.logger.info('registered event "%s"', eventName, listener); + } + registerUploadEvent(eventName, listener) { + const nextEvents = (this.uploadEvents.get(eventName) || []).concat(listener); + this.uploadEvents.set(eventName, nextEvents); + this.logger.info('registered upload event "%s"', eventName, listener); + } + /** + * Responds to the current request with the given + * Fetch API `Response` instance. + */ + async respondWith(response) { + this[kIsRequestHandled] = true; + if (this[kFetchRequest]) { + const totalRequestBodyLength = await getBodyByteLength(this[kFetchRequest]); + this.trigger("loadstart", this.request.upload, { + loaded: 0, + total: totalRequestBodyLength + }); + this.trigger("progress", this.request.upload, { + loaded: totalRequestBodyLength, + total: totalRequestBodyLength + }); + this.trigger("load", this.request.upload, { + loaded: totalRequestBodyLength, + total: totalRequestBodyLength + }); + this.trigger("loadend", this.request.upload, { + loaded: totalRequestBodyLength, + total: totalRequestBodyLength + }); + } + this.logger.info("responding with a mocked response: %d %s", response.status, response.statusText); + define(this.request, "status", response.status); + define(this.request, "statusText", response.statusText); + define(this.request, "responseURL", this.url.href); + this.request.getResponseHeader = new Proxy(this.request.getResponseHeader, { apply: (_, __, args) => { + this.logger.info("getResponseHeader", args[0]); + if (this.request.readyState < this.request.HEADERS_RECEIVED) { + this.logger.info("headers not received yet, returning null"); + return null; + } + const headerValue = response.headers.get(args[0]); + this.logger.info('resolved response header "%s" to', args[0], headerValue); + return headerValue; + } }); + this.request.getAllResponseHeaders = new Proxy(this.request.getAllResponseHeaders, { apply: () => { + this.logger.info("getAllResponseHeaders"); + if (this.request.readyState < this.request.HEADERS_RECEIVED) { + this.logger.info("headers not received yet, returning empty string"); + return ""; + } + const allHeaders = Array.from(response.headers.entries()).map(([headerName, headerValue]) => { + return `${headerName}: ${headerValue}`; + }).join("\r\n"); + this.logger.info("resolved all response headers to", allHeaders); + return allHeaders; + } }); + Object.defineProperties(this.request, { + response: { + enumerable: true, + configurable: false, + get: () => this.response + }, + responseText: { + enumerable: true, + configurable: false, + get: () => this.responseText + }, + responseXML: { + enumerable: true, + configurable: false, + get: () => this.responseXML + } + }); + const totalResponseBodyLength = await getBodyByteLength(response.clone()); + this.logger.info("calculated response body length", totalResponseBodyLength); + this.trigger("loadstart", this.request, { + loaded: 0, + total: totalResponseBodyLength + }); + this.setReadyState(this.request.HEADERS_RECEIVED); + this.setReadyState(this.request.LOADING); + const finalizeResponse = () => { + this.logger.info("finalizing the mocked response..."); + this.setReadyState(this.request.DONE); + this.trigger("load", this.request, { + loaded: this.responseBuffer.byteLength, + total: totalResponseBodyLength + }); + this.trigger("loadend", this.request, { + loaded: this.responseBuffer.byteLength, + total: totalResponseBodyLength + }); + }; + if (response.body) { + this.logger.info("mocked response has body, streaming..."); + const reader = response.body.getReader(); + const readNextResponseBodyChunk = async () => { + const { value, done } = await reader.read(); + if (done) { + this.logger.info("response body stream done!"); + finalizeResponse(); + return; + } + if (value) { + this.logger.info("read response body chunk:", value); + this.responseBuffer = concatArrayBuffer(this.responseBuffer, value); + this.trigger("progress", this.request, { + loaded: this.responseBuffer.byteLength, + total: totalResponseBodyLength + }); + } + readNextResponseBodyChunk(); + }; + readNextResponseBodyChunk(); + } else finalizeResponse(); + } + responseBufferToText() { + return decodeBuffer(this.responseBuffer); + } + get response() { + this.logger.info("getResponse (responseType: %s)", this.request.responseType); + if (this.request.readyState !== this.request.DONE) return null; + switch (this.request.responseType) { + case "json": { + const responseJson = parseJson(this.responseBufferToText()); + this.logger.info("resolved response JSON", responseJson); + return responseJson; + } + case "arraybuffer": { + const arrayBuffer = toArrayBuffer(this.responseBuffer); + this.logger.info("resolved response ArrayBuffer", arrayBuffer); + return arrayBuffer; + } + case "blob": { + const mimeType = this.request.getResponseHeader("Content-Type") || "text/plain"; + const responseBlob = new Blob([this.responseBufferToText()], { type: mimeType }); + this.logger.info("resolved response Blob (mime type: %s)", responseBlob, mimeType); + return responseBlob; + } + default: { + const responseText = this.responseBufferToText(); + this.logger.info('resolving "%s" response type as text', this.request.responseType, responseText); + return responseText; + } + } + } + get responseText() { + invariant(this.request.responseType === "" || this.request.responseType === "text", "InvalidStateError: The object is in invalid state."); + if (this.request.readyState !== this.request.LOADING && this.request.readyState !== this.request.DONE) return ""; + const responseText = this.responseBufferToText(); + this.logger.info('getResponseText: "%s"', responseText); + return responseText; + } + get responseXML() { + invariant(this.request.responseType === "" || this.request.responseType === "document", "InvalidStateError: The object is in invalid state."); + if (this.request.readyState !== this.request.DONE) return null; + const contentType = this.request.getResponseHeader("Content-Type") || ""; + if (typeof DOMParser === "undefined") { + console.warn("Cannot retrieve XMLHttpRequest response body as XML: DOMParser is not defined. You are likely using an environment that is not browser or does not polyfill browser globals correctly."); + return null; + } + if (isDomParserSupportedType(contentType)) return new DOMParser().parseFromString(this.responseBufferToText(), contentType); + return null; + } + errorWith(error2) { + this[kIsRequestHandled] = true; + this.logger.info("responding with an error"); + this.setReadyState(this.request.DONE); + this.trigger("error", this.request); + this.trigger("loadend", this.request); + } + /** + * Transitions this request's `readyState` to the given one. + */ + setReadyState(nextReadyState) { + this.logger.info("setReadyState: %d -> %d", this.request.readyState, nextReadyState); + if (this.request.readyState === nextReadyState) { + this.logger.info("ready state identical, skipping transition..."); + return; + } + define(this.request, "readyState", nextReadyState); + this.logger.info("set readyState to: %d", nextReadyState); + if (nextReadyState !== this.request.UNSENT) { + this.logger.info('triggering "readystatechange" event...'); + this.trigger("readystatechange", this.request); + } + } + /** + * Triggers given event on the `XMLHttpRequest` instance. + */ + trigger(eventName, target, options) { + const callback = target[`on${eventName}`]; + const event = createEvent(target, eventName, options); + this.logger.info('trigger "%s"', eventName, options || ""); + if (typeof callback === "function") { + this.logger.info('found a direct "%s" callback, calling...', eventName); + callback.call(target, event); + } + const events = target instanceof XMLHttpRequestUpload ? this.uploadEvents : this.events; + for (const [registeredEventName, listeners] of events) if (registeredEventName === eventName) { + this.logger.info('found %d listener(s) for "%s" event, calling...', listeners.length, eventName); + listeners.forEach((listener) => listener.call(target, event)); + } + } + /** + * Converts this `XMLHttpRequest` instance into a Fetch API `Request` instance. + */ + toFetchApiRequest(body) { + this.logger.info("converting request to a Fetch API Request..."); + const resolvedBody = body instanceof Document ? body.documentElement.innerText : body; + const fetchRequest = new Request(this.url.href, { + method: this.method, + headers: this.requestHeaders, + credentials: this.request.withCredentials ? "include" : "same-origin", + body: ["GET", "HEAD"].includes(this.method.toUpperCase()) ? null : resolvedBody + }); + define(fetchRequest, "headers", createProxy(fetchRequest.headers, { methodCall: ([methodName, args], invoke) => { + switch (methodName) { + case "append": + case "set": { + const [headerName, headerValue] = args; + this.request.setRequestHeader(headerName, headerValue); + break; + } + case "delete": { + const [headerName] = args; + console.warn(`XMLHttpRequest: Cannot remove a "${headerName}" header from the Fetch API representation of the "${fetchRequest.method} ${fetchRequest.url}" request. XMLHttpRequest headers cannot be removed.`); + break; + } + } + return invoke(); + } })); + setRawRequest(fetchRequest, this.request); + this.logger.info("converted request to a Fetch API Request!", fetchRequest); + return fetchRequest; + } +}; +function toAbsoluteUrl(url) { + if (typeof location === "undefined") return new URL(url); + return new URL(url.toString(), location.href); +} +function define(target, property, value) { + Reflect.defineProperty(target, property, { + writable: true, + enumerable: true, + value + }); +} +function createXMLHttpRequestProxy({ emitter, logger }) { + return new Proxy(globalThis.XMLHttpRequest, { construct(target, args, newTarget) { + logger.info("constructed new XMLHttpRequest"); + const originalRequest = Reflect.construct(target, args, newTarget); + const prototypeDescriptors = Object.getOwnPropertyDescriptors(target.prototype); + for (const propertyName in prototypeDescriptors) Reflect.defineProperty(originalRequest, propertyName, prototypeDescriptors[propertyName]); + const xhrRequestController = new XMLHttpRequestController(originalRequest, logger); + xhrRequestController.onRequest = async function({ request, requestId }) { + const controller = new RequestController(request, { + passthrough: () => { + this.logger.info("no mocked response received, performing request as-is..."); + }, + respondWith: async (response) => { + if (isResponseError(response)) { + this.errorWith(/* @__PURE__ */ new TypeError("Network error")); + return; + } + await this.respondWith(response); + }, + errorWith: (reason) => { + this.logger.info("request errored!", { error: reason }); + if (reason instanceof Error) this.errorWith(reason); + } + }); + this.logger.info("awaiting mocked response..."); + this.logger.info('emitting the "request" event for %s listener(s)...', emitter.listenerCount("request")); + await handleRequest({ + request, + requestId, + controller, + emitter + }); + }; + xhrRequestController.onResponse = async function({ response, isMockedResponse, request, requestId }) { + this.logger.info('emitting the "response" event for %s listener(s)...', emitter.listenerCount("response")); + emitter.emit("response", { + response, + isMockedResponse, + request, + requestId + }); + }; + return xhrRequestController.request; + } }); +} +var XMLHttpRequestInterceptor = class XMLHttpRequestInterceptor2 extends Interceptor { + static { + this.interceptorSymbol = Symbol("xhr"); + } + constructor() { + super(XMLHttpRequestInterceptor2.interceptorSymbol); + } + checkEnvironment() { + return hasConfigurableGlobal("XMLHttpRequest"); + } + setup() { + const logger = this.logger.extend("setup"); + logger.info('patching "XMLHttpRequest" module...'); + const PureXMLHttpRequest = globalThis.XMLHttpRequest; + invariant(!PureXMLHttpRequest[IS_PATCHED_MODULE], 'Failed to patch the "XMLHttpRequest" module: already patched.'); + globalThis.XMLHttpRequest = createXMLHttpRequestProxy({ + emitter: this.emitter, + logger: this.logger + }); + logger.info('native "XMLHttpRequest" module patched!', globalThis.XMLHttpRequest.name); + Object.defineProperty(globalThis.XMLHttpRequest, IS_PATCHED_MODULE, { + enumerable: true, + configurable: true, + value: true + }); + this.subscriptions.push(() => { + Object.defineProperty(globalThis.XMLHttpRequest, IS_PATCHED_MODULE, { value: void 0 }); + globalThis.XMLHttpRequest = PureXMLHttpRequest; + logger.info('native "XMLHttpRequest" module restored!', globalThis.XMLHttpRequest.name); + }); + } +}; + +// src/browser/sources/fallback-http-source.ts +var import_interceptor_source = require("../core/experimental/sources/interceptor-source"); +var import_devUtils4 = require("../core/utils/internal/devUtils"); +var FallbackHttpSource = class extends import_interceptor_source.InterceptorSource { + constructor(options) { + super({ + interceptors: [new XMLHttpRequestInterceptor(), new FetchInterceptor()] + }); + this.options = options; + } + enable() { + super.enable(); + if (!this.options.quiet) { + this.#printStartMessage(); + } + } + disable() { + super.disable(); + if (!this.options.quiet) { + this.#printStopMessage(); + } + } + #printStartMessage() { + console.groupCollapsed( + `%c${import_devUtils4.devUtils.formatMessage("Mocking enabled (fallback mode).")}`, + "color:orangered;font-weight:bold;" + ); + console.log( + "%cDocumentation: %chttps://mswjs.io/docs", + "font-weight:bold", + "font-weight:normal" + ); + console.log("Found an issue? https://github.com/mswjs/msw/issues"); + console.groupEnd(); + } + #printStopMessage() { + console.log( + `%c${import_devUtils4.devUtils.formatMessage("Mocking disabled.")}`, + "color:orangered;font-weight:bold;" + ); + } +}; + +// src/browser/setup-worker.ts +var DEFAULT_WORKER_URL = "/mockServiceWorker.js"; +function setupWorker(...handlers) { + invariant( + !isNodeProcess(), + import_devUtils5.devUtils.formatMessage( + "Failed to execute `setupWorker` in a non-browser environment" + ) + ); + const network = (0, import_define_network.defineNetwork)({ + sources: [], + handlers + }); + return { + async start(options) { + if (options?.waitUntilReady != null) { + import_devUtils5.devUtils.warn( + `The "waitUntilReady" option has been deprecated. Please remove it from this "worker.start()" call. Follow the recommended Browser integration (https://mswjs.io/docs/integrations/browser) to eliminate any race conditions between the Service Worker registration and any requests made by your application on initial render.` + ); + } + if (network.readyState === import_define_network.NetworkReadyState.ENABLED) { + import_devUtils5.devUtils.warn( + 'Found a redundant "worker.start()" call. Note that starting the worker while mocking is already enabled will have no effect. Consider removing this "worker.start()" call.' + ); + return; + } + const httpSource = supportsServiceWorker() ? await ServiceWorkerSource.from({ + serviceWorker: { + url: options?.serviceWorker?.url?.toString() || DEFAULT_WORKER_URL, + options: options?.serviceWorker?.options + }, + findWorker: options?.findWorker, + quiet: options?.quiet + }) : new FallbackHttpSource({ + quiet: options?.quiet + }); + network.configure({ + sources: [ + httpSource, + new import_interceptor_source2.InterceptorSource({ + interceptors: [new WebSocketInterceptor()] + }) + ], + onUnhandledFrame: (0, import_compat.fromLegacyOnUnhandledRequest)(() => { + return options?.onUnhandledRequest || "warn"; + }), + context: { + quiet: options?.quiet + } + }); + await network.enable(); + if (httpSource instanceof ServiceWorkerSource) { + const [, registration] = await httpSource.workerPromise; + return registration; + } + }, + stop() { + if (network.readyState === import_define_network.NetworkReadyState.DISABLED) { + import_devUtils5.devUtils.warn( + `Found a redundant "worker.stop()" call. Notice that stopping the worker after it has already been stopped has no effect. Consider removing this "worker.stop()" call.` + ); + return; + } + network.disable(); + window.postMessage({ type: "msw/worker:stop" }); + }, + events: network.events, + use: network.use.bind(network), + resetHandlers: network.resetHandlers.bind(network), + restoreHandlers: network.restoreHandlers.bind(network), + listHandlers: network.listHandlers.bind(network) + }; +} +var SetupWorkerApi = class { + start; + stop; + use; + resetHandlers; + restoreHandlers; + listHandlers; + events; + constructor() { + const worker = setupWorker(); + this.start = worker.start.bind(worker); + this.stop = worker.stop.bind(worker); + this.use = worker.use.bind(worker); + this.resetHandlers = worker.resetHandlers.bind(worker); + this.restoreHandlers = worker.restoreHandlers.bind(worker); + this.listHandlers = worker.listHandlers.bind(worker); + this.events = worker.events; + } +}; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/msw/lib/browser/index.js.map b/node_modules/msw/lib/browser/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..a1222f6cde757b7e8e73aeb473c6bca8b025a278 --- /dev/null +++ b/node_modules/msw/lib/browser/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/browser/index.ts","../../node_modules/.pnpm/outvariant@1.4.3/node_modules/outvariant/src/format.ts","../../node_modules/.pnpm/outvariant@1.4.3/node_modules/outvariant/src/invariant.ts","../../node_modules/.pnpm/is-node-process@1.2.0/node_modules/is-node-process/src/index.ts","../../node_modules/.pnpm/@open-draft+logger@0.3.0/node_modules/@open-draft/logger/lib/index.mjs","../../node_modules/.pnpm/strict-event-emitter@0.5.1/node_modules/strict-event-emitter/src/MemoryLeakError.ts","../../node_modules/.pnpm/strict-event-emitter@0.5.1/node_modules/strict-event-emitter/src/Emitter.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/Interceptor.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/createRequestId.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/utils/resolveWebSocketUrl.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/utils/emitAsync.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/utils/hasConfigurableGlobal.ts","../../node_modules/.pnpm/@open-draft+deferred-promise@2.2.0/node_modules/@open-draft/deferred-promise/src/createDeferredExecutor.ts","../../node_modules/.pnpm/@open-draft+deferred-promise@2.2.0/node_modules/@open-draft/deferred-promise/src/DeferredPromise.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/utils/bindEvent.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/utils/events.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/WebSocketClientConnection.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/WebSocketOverride.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/WebSocketServerConnection.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/WebSocketClassTransport.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/index.ts","../../src/browser/setup-worker.ts","../../src/browser/utils/supports.ts","../../node_modules/.pnpm/@open-draft+deferred-promise@3.0.0/node_modules/@open-draft/deferred-promise/src/create-deferred-executor.ts","../../node_modules/.pnpm/@open-draft+deferred-promise@3.0.0/node_modules/@open-draft/deferred-promise/src/deferred-promise.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/glossary.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/InterceptorError.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/RequestController.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/utils/canParseUrl.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/utils/getValueBySymbol.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/utils/fetchUtils.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/getRawRequest.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/utils/bufferUtils.ts","../../src/browser/sources/service-worker-source.ts","../../node_modules/.pnpm/until-async@3.0.2/node_modules/until-async/src/index.ts","../../src/browser/utils/get-worker-instance.ts","../../src/browser/utils/getAbsoluteWorkerUrl.ts","../../src/browser/utils/get-worker-by-registration.ts","../../node_modules/.pnpm/rettime@0.11.11/node_modules/rettime/src/lens-list.ts","../../node_modules/.pnpm/rettime@0.11.11/node_modules/rettime/src/index.ts","../../src/browser/utils/workerChannel.ts","../../src/browser/utils/pruneGetRequestBody.ts","../../src/browser/utils/deserializeRequest.ts","../../src/browser/utils/validate-worker-scope.ts","../../src/browser/utils/should-invalidate-worker.ts","../../node_modules/.pnpm/@open-draft+until@2.1.0/node_modules/@open-draft/until/src/until.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/utils/isObject.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/utils/isPropertyAccessible.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/utils/responseUtils.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/utils/isNodeLikeError.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/utils/handleRequest.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/interceptors/fetch/utils/createNetworkError.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/interceptors/fetch/utils/followRedirect.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/interceptors/fetch/utils/brotli-decompress.browser.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/interceptors/fetch/utils/decompression.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/interceptors/fetch/index.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/utils/concatArrayBuffer.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/polyfills/EventPolyfill.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/polyfills/ProgressEventPolyfill.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/utils/createEvent.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/utils/findPropertySource.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/utils/createProxy.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/utils/isDomParserSupportedType.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/utils/parseJson.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/utils/createResponse.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/utils/getBodyByteLength.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/XMLHttpRequestController.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/XMLHttpRequestProxy.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/index.ts","../../src/browser/sources/fallback-http-source.ts"],"sourcesContent":["export { setupWorker, SetupWorkerApi } from './setup-worker'\nexport type { SetupWorker, StartOptions } from './glossary'\n","const POSITIONALS_EXP = /(%?)(%([sdijo]))/g\n\nfunction serializePositional(positional: any, flag: string): any {\n switch (flag) {\n // Strings.\n case 's':\n return positional\n\n // Digits.\n case 'd':\n case 'i':\n return Number(positional)\n\n // JSON.\n case 'j':\n return JSON.stringify(positional)\n\n // Objects.\n case 'o': {\n // Preserve stings to prevent extra quotes around them.\n if (typeof positional === 'string') {\n return positional\n }\n\n const json = JSON.stringify(positional)\n\n // If the positional isn't serializable, return it as-is.\n if (json === '{}' || json === '[]' || /^\\[object .+?\\]$/.test(json)) {\n return positional\n }\n\n return json\n }\n }\n}\n\nexport function format(message: string, ...positionals: any[]): string {\n if (positionals.length === 0) {\n return message\n }\n\n let positionalIndex = 0\n let formattedMessage = message.replace(\n POSITIONALS_EXP,\n (match, isEscaped, _, flag) => {\n const positional = positionals[positionalIndex]\n const value = serializePositional(positional, flag)\n\n if (!isEscaped) {\n positionalIndex++\n return value\n }\n\n return match\n }\n )\n\n // Append unresolved positionals to string as-is.\n if (positionalIndex < positionals.length) {\n formattedMessage += ` ${positionals.slice(positionalIndex).join(' ')}`\n }\n\n formattedMessage = formattedMessage.replace(/%{2,2}/g, '%')\n\n return formattedMessage\n}\n","import { format } from './format'\n\nconst STACK_FRAMES_TO_IGNORE = 2\n\n/**\n * Remove the \"outvariant\" package trace from the given error.\n * This scopes down the error stack to the relevant parts\n * when used in other applications.\n */\nfunction cleanErrorStack(error: Error): void {\n if (!error.stack) {\n return\n }\n\n const nextStack = error.stack.split('\\n')\n nextStack.splice(1, STACK_FRAMES_TO_IGNORE)\n error.stack = nextStack.join('\\n')\n}\n\nexport class InvariantError extends Error {\n name = 'Invariant Violation'\n\n constructor(public readonly message: string, ...positionals: any[]) {\n super(message)\n this.message = format(message, ...positionals)\n cleanErrorStack(this)\n }\n}\n\nexport interface CustomErrorConstructor {\n new (message: string): Error\n}\n\nexport interface CustomErrorFactory {\n (message: string): Error\n}\n\nexport type CustomError = CustomErrorConstructor | CustomErrorFactory\n\ntype Invariant = {\n (\n predicate: unknown,\n message: string,\n ...positionals: any[]\n ): asserts predicate\n\n as(\n ErrorConstructor: CustomError,\n predicate: unknown,\n message: string,\n ...positionals: unknown[]\n ): asserts predicate\n}\n\nexport const invariant: Invariant = (\n predicate,\n message,\n ...positionals\n): asserts predicate => {\n if (!predicate) {\n throw new InvariantError(message, ...positionals)\n }\n}\n\ninvariant.as = (ErrorConstructor, predicate, message, ...positionals) => {\n if (!predicate) {\n const formatMessage =\n positionals.length === 0 ? message : format(message, ...positionals)\n let error: Error\n\n try {\n error = Reflect.construct(ErrorConstructor as CustomErrorConstructor, [\n formatMessage,\n ])\n } catch (err) {\n error = (ErrorConstructor as CustomErrorFactory)(formatMessage)\n }\n\n throw error\n }\n}\n","/**\n * Determines if the current process is a Node.js process.\n */\nexport function isNodeProcess(): boolean {\n if (typeof navigator !== 'undefined' && navigator.product === 'ReactNative') {\n return true\n }\n\n if (typeof process !== 'undefined') {\n // Electron (https://www.electronjs.org/docs/latest/api/process#processtype-readonly)\n const type = (process as any).type\n if (type === 'renderer' || type === 'worker') {\n return false\n }\n\n\n return !!(\n process.versions &&\n process.versions.node\n )\n }\n\n return false\n}\n","var __defProp = Object.defineProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\n\n// src/index.ts\nimport { isNodeProcess } from \"is-node-process\";\nimport { format } from \"outvariant\";\n\n// src/colors.ts\nvar colors_exports = {};\n__export(colors_exports, {\n blue: () => blue,\n gray: () => gray,\n green: () => green,\n red: () => red,\n yellow: () => yellow\n});\nfunction yellow(text) {\n return `\\x1B[33m${text}\\x1B[0m`;\n}\nfunction blue(text) {\n return `\\x1B[34m${text}\\x1B[0m`;\n}\nfunction gray(text) {\n return `\\x1B[90m${text}\\x1B[0m`;\n}\nfunction red(text) {\n return `\\x1B[31m${text}\\x1B[0m`;\n}\nfunction green(text) {\n return `\\x1B[32m${text}\\x1B[0m`;\n}\n\n// src/index.ts\nvar IS_NODE = isNodeProcess();\nvar Logger = class {\n constructor(name) {\n this.name = name;\n this.prefix = `[${this.name}]`;\n const LOGGER_NAME = getVariable(\"DEBUG\");\n const LOGGER_LEVEL = getVariable(\"LOG_LEVEL\");\n const isLoggingEnabled = LOGGER_NAME === \"1\" || LOGGER_NAME === \"true\" || typeof LOGGER_NAME !== \"undefined\" && this.name.startsWith(LOGGER_NAME);\n if (isLoggingEnabled) {\n this.debug = isDefinedAndNotEquals(LOGGER_LEVEL, \"debug\") ? noop : this.debug;\n this.info = isDefinedAndNotEquals(LOGGER_LEVEL, \"info\") ? noop : this.info;\n this.success = isDefinedAndNotEquals(LOGGER_LEVEL, \"success\") ? noop : this.success;\n this.warning = isDefinedAndNotEquals(LOGGER_LEVEL, \"warning\") ? noop : this.warning;\n this.error = isDefinedAndNotEquals(LOGGER_LEVEL, \"error\") ? noop : this.error;\n } else {\n this.info = noop;\n this.success = noop;\n this.warning = noop;\n this.error = noop;\n this.only = noop;\n }\n }\n prefix;\n extend(domain) {\n return new Logger(`${this.name}:${domain}`);\n }\n /**\n * Print a debug message.\n * @example\n * logger.debug('no duplicates found, creating a document...')\n */\n debug(message, ...positionals) {\n this.logEntry({\n level: \"debug\",\n message: gray(message),\n positionals,\n prefix: this.prefix,\n colors: {\n prefix: \"gray\"\n }\n });\n }\n /**\n * Print an info message.\n * @example\n * logger.info('start parsing...')\n */\n info(message, ...positionals) {\n this.logEntry({\n level: \"info\",\n message,\n positionals,\n prefix: this.prefix,\n colors: {\n prefix: \"blue\"\n }\n });\n const performance2 = new PerformanceEntry();\n return (message2, ...positionals2) => {\n performance2.measure();\n this.logEntry({\n level: \"info\",\n message: `${message2} ${gray(`${performance2.deltaTime}ms`)}`,\n positionals: positionals2,\n prefix: this.prefix,\n colors: {\n prefix: \"blue\"\n }\n });\n };\n }\n /**\n * Print a success message.\n * @example\n * logger.success('successfully created document')\n */\n success(message, ...positionals) {\n this.logEntry({\n level: \"info\",\n message,\n positionals,\n prefix: `\\u2714 ${this.prefix}`,\n colors: {\n timestamp: \"green\",\n prefix: \"green\"\n }\n });\n }\n /**\n * Print a warning.\n * @example\n * logger.warning('found legacy document format')\n */\n warning(message, ...positionals) {\n this.logEntry({\n level: \"warning\",\n message,\n positionals,\n prefix: `\\u26A0 ${this.prefix}`,\n colors: {\n timestamp: \"yellow\",\n prefix: \"yellow\"\n }\n });\n }\n /**\n * Print an error message.\n * @example\n * logger.error('something went wrong')\n */\n error(message, ...positionals) {\n this.logEntry({\n level: \"error\",\n message,\n positionals,\n prefix: `\\u2716 ${this.prefix}`,\n colors: {\n timestamp: \"red\",\n prefix: \"red\"\n }\n });\n }\n /**\n * Execute the given callback only when the logging is enabled.\n * This is skipped in its entirety and has no runtime cost otherwise.\n * This executes regardless of the log level.\n * @example\n * logger.only(() => {\n * logger.info('additional info')\n * })\n */\n only(callback) {\n callback();\n }\n createEntry(level, message) {\n return {\n timestamp: /* @__PURE__ */ new Date(),\n level,\n message\n };\n }\n logEntry(args) {\n const {\n level,\n message,\n prefix,\n colors: customColors,\n positionals = []\n } = args;\n const entry = this.createEntry(level, message);\n const timestampColor = customColors?.timestamp || \"gray\";\n const prefixColor = customColors?.prefix || \"gray\";\n const colorize = {\n timestamp: colors_exports[timestampColor],\n prefix: colors_exports[prefixColor]\n };\n const write = this.getWriter(level);\n write(\n [colorize.timestamp(this.formatTimestamp(entry.timestamp))].concat(prefix != null ? colorize.prefix(prefix) : []).concat(serializeInput(message)).join(\" \"),\n ...positionals.map(serializeInput)\n );\n }\n formatTimestamp(timestamp) {\n return `${timestamp.toLocaleTimeString(\n \"en-GB\"\n )}:${timestamp.getMilliseconds()}`;\n }\n getWriter(level) {\n switch (level) {\n case \"debug\":\n case \"success\":\n case \"info\": {\n return log;\n }\n case \"warning\": {\n return warn;\n }\n case \"error\": {\n return error;\n }\n }\n }\n};\nvar PerformanceEntry = class {\n startTime;\n endTime;\n deltaTime;\n constructor() {\n this.startTime = performance.now();\n }\n measure() {\n this.endTime = performance.now();\n const deltaTime = this.endTime - this.startTime;\n this.deltaTime = deltaTime.toFixed(2);\n }\n};\nvar noop = () => void 0;\nfunction log(message, ...positionals) {\n if (IS_NODE) {\n process.stdout.write(format(message, ...positionals) + \"\\n\");\n return;\n }\n console.log(message, ...positionals);\n}\nfunction warn(message, ...positionals) {\n if (IS_NODE) {\n process.stderr.write(format(message, ...positionals) + \"\\n\");\n return;\n }\n console.warn(message, ...positionals);\n}\nfunction error(message, ...positionals) {\n if (IS_NODE) {\n process.stderr.write(format(message, ...positionals) + \"\\n\");\n return;\n }\n console.error(message, ...positionals);\n}\nfunction getVariable(variableName) {\n if (IS_NODE) {\n return process.env[variableName];\n }\n return globalThis[variableName]?.toString();\n}\nfunction isDefinedAndNotEquals(value, expected) {\n return value !== void 0 && value !== expected;\n}\nfunction serializeInput(message) {\n if (typeof message === \"undefined\") {\n return \"undefined\";\n }\n if (message === null) {\n return \"null\";\n }\n if (typeof message === \"string\") {\n return message;\n }\n if (typeof message === \"object\") {\n return JSON.stringify(message);\n }\n return message.toString();\n}\nexport {\n Logger\n};\n","import type { Emitter } from './Emitter'\n\nexport class MemoryLeakError extends Error {\n constructor(\n public readonly emitter: Emitter,\n public readonly type: string | number | symbol,\n public readonly count: number\n ) {\n super(\n `Possible EventEmitter memory leak detected. ${count} ${type.toString()} listeners added. Use emitter.setMaxListeners() to increase limit`\n )\n this.name = 'MaxListenersExceededWarning'\n }\n}\n","import { MemoryLeakError } from './MemoryLeakError'\n\nexport type EventMap = {\n [eventName: string]: Array\n}\n\nexport type InternalEventNames = 'newListener' | 'removeListener'\n\nexport type InternalListener = Listener<\n [eventName: keyof Events, listener: Listener>]\n>\n\nexport type Listener> = (...data: Data) => void\n\n/**\n * Node.js-compatible implementation of `EventEmitter`.\n *\n * @example\n * const emitter = new Emitter<{ hello: [string] }>()\n * emitter.on('hello', (name) => console.log(name))\n * emitter.emit('hello', 'John')\n */\nexport class Emitter {\n private events: Map>>\n private maxListeners: number\n private hasWarnedAboutPotentialMemoryLeak: boolean\n\n static defaultMaxListeners = 10\n\n static listenerCount(\n emitter: Emitter,\n eventName: keyof Events\n ): number {\n return emitter.listenerCount(eventName)\n }\n\n constructor() {\n this.events = new Map()\n this.maxListeners = Emitter.defaultMaxListeners\n this.hasWarnedAboutPotentialMemoryLeak = false\n }\n\n private _emitInternalEvent(\n internalEventName: InternalEventNames,\n eventName: keyof Events,\n listener: Listener>\n ): void {\n this.emit(\n internalEventName,\n // Anything to make TypeScript happy.\n ...([eventName, listener] as Events['newListener'] &\n Events['removeListener'])\n )\n }\n\n private _getListeners(\n eventName: EventName\n ): Array>> {\n // Always return a copy of the listeners array\n // so they are fixed at the time of the \"_getListeners\" call.\n return Array.prototype.concat.apply([], this.events.get(eventName)) || []\n }\n\n private _removeListener(\n listeners: Array>,\n listener: Listener\n ): Array> {\n const index = listeners.indexOf(listener)\n\n if (index > -1) {\n listeners.splice(index, 1)\n }\n\n return []\n }\n\n private _wrapOnceListener(\n eventName: EventName,\n listener: Listener\n ): Listener {\n const onceListener = (...data: Events[keyof Events]) => {\n this.removeListener(eventName, onceListener)\n\n /**\n * @note Return the result of the original listener.\n * This way this wrapped preserves listeners that are async.\n */\n return listener.apply(this, data)\n }\n\n // Inherit the name of the original listener.\n Object.defineProperty(onceListener, 'name', { value: listener.name })\n\n return onceListener\n }\n\n public setMaxListeners(maxListeners: number): this {\n this.maxListeners = maxListeners\n return this\n }\n\n /**\n * Returns the current max listener value for the `Emitter` which is\n * either set by `emitter.setMaxListeners(n)` or defaults to\n * `Emitter.defaultMaxListeners`.\n */\n public getMaxListeners(): number {\n return this.maxListeners\n }\n\n /**\n * Returns an array listing the events for which the emitter has registered listeners.\n * The values in the array will be strings or Symbols.\n */\n public eventNames(): Array {\n return Array.from(this.events.keys())\n }\n\n /**\n * Synchronously calls each of the listeners registered for the event named `eventName`,\n * in the order they were registered, passing the supplied arguments to each.\n * Returns `true` if the event has listeners, `false` otherwise.\n *\n * @example\n * const emitter = new Emitter<{ hello: [string] }>()\n * emitter.emit('hello', 'John')\n */\n public emit(\n eventName: EventName,\n ...data: Events[EventName]\n ): boolean {\n const listeners = this._getListeners(eventName)\n listeners.forEach((listener) => {\n listener.apply(this, data)\n })\n\n return listeners.length > 0\n }\n\n public addListener(\n eventName: InternalEventNames,\n listener: InternalListener\n ): this\n public addListener(\n eventName: EventName,\n listener: Listener\n ): this\n public addListener(\n eventName: InternalEventNames | keyof Events,\n listener: InternalListener | Listener\n ): this {\n // Emit the `newListener` event before adding the listener.\n this._emitInternalEvent('newListener', eventName, listener)\n\n const nextListeners = this._getListeners(eventName).concat(listener)\n this.events.set(eventName, nextListeners)\n\n if (\n this.maxListeners > 0 &&\n this.listenerCount(eventName) > this.maxListeners &&\n !this.hasWarnedAboutPotentialMemoryLeak\n ) {\n this.hasWarnedAboutPotentialMemoryLeak = true\n\n const memoryLeakWarning = new MemoryLeakError(\n this,\n eventName,\n this.listenerCount(eventName)\n )\n console.warn(memoryLeakWarning)\n }\n\n return this\n }\n\n public on(\n eventName: InternalEventNames,\n listener: InternalListener\n ): this\n public on(\n eventName: EventName,\n listener: Listener\n ): this\n public on(\n eventName: 'removeListener' | EventName,\n listener: Listener\n ): this {\n return this.addListener(eventName, listener)\n }\n\n public once(\n eventName: InternalEventNames,\n listener: InternalListener\n ): this\n public once(\n eventName: EventName,\n listener: Listener\n ): this\n public once(\n eventName: InternalEventNames | EventName,\n listener: Listener\n ): this {\n return this.addListener(\n eventName,\n this._wrapOnceListener(eventName, listener)\n )\n }\n\n public prependListener(\n eventName: InternalEventNames,\n listener: InternalListener\n ): this\n public prependListener(\n eventName: EventName,\n listener: Listener\n ): this\n public prependListener(\n eventName: InternalEventNames | keyof Events,\n listener: Listener\n ): this {\n const listeners = this._getListeners(eventName)\n\n if (listeners.length > 0) {\n const nextListeners = [listener].concat(listeners)\n this.events.set(eventName, nextListeners)\n } else {\n this.events.set(eventName, listeners.concat(listener))\n }\n\n return this\n }\n\n public prependOnceListener(\n eventName: InternalEventNames,\n listener: InternalListener\n ): this\n public prependOnceListener(\n eventName: EventName,\n listener: Listener\n ): this\n public prependOnceListener(\n eventName: InternalEventNames | keyof Events,\n listener: Listener\n ): this {\n return this.prependListener(\n eventName,\n this._wrapOnceListener(eventName, listener)\n )\n }\n\n public removeListener(\n eventName: InternalEventNames,\n listener: InternalListener\n ): this\n public removeListener(\n eventName: EventName,\n listener: Listener\n ): this\n public removeListener(\n eventName: InternalEventNames | keyof Events,\n listener: Listener\n ): this {\n const listeners = this._getListeners(eventName)\n\n if (listeners.length > 0) {\n this._removeListener(listeners, listener)\n this.events.set(eventName, listeners)\n\n // Emit the `removeListener` event after removing the listener.\n this._emitInternalEvent('removeListener', eventName, listener)\n }\n\n return this\n }\n\n public off(\n eventName: InternalEventNames,\n listener: InternalListener\n ): this\n public off(\n eventName: EventName,\n listener: Listener\n ): this\n /**\n * Alias for `emitter.removeListener()`.\n *\n * @example\n * emitter.off('hello', listener)\n */\n public off(\n eventName: InternalEventNames | keyof Events,\n listener: Listener\n ): this {\n return this.removeListener(eventName, listener)\n }\n\n public removeAllListeners(eventName?: InternalEventNames): this\n public removeAllListeners(\n eventName?: EventName\n ): this\n public removeAllListeners(\n eventName?: InternalEventNames | keyof Events\n ): this {\n if (eventName) {\n this.events.delete(eventName)\n } else {\n this.events.clear()\n }\n\n return this\n }\n\n public listeners(eventName: InternalEventNames): Array>\n public listeners(\n eventName: EventName\n ): Array>\n /**\n * Returns a copy of the array of listeners for the event named `eventName`.\n */\n public listeners(eventName: InternalEventNames | keyof Events) {\n return Array.from(this._getListeners(eventName))\n }\n\n public listenerCount(eventName: InternalEventNames): number\n public listenerCount(\n eventName: EventName\n ): number\n /**\n * Returns the number of listeners listening to the event named `eventName`.\n */\n public listenerCount(eventName: InternalEventNames | keyof Events): number {\n return this._getListeners(eventName).length\n }\n\n public rawListeners(\n eventName: EventName\n ): Array> {\n return this.listeners(eventName)\n }\n}\n","import { Logger } from '@open-draft/logger'\nimport { Emitter, Listener } from 'strict-event-emitter'\n\nexport type InterceptorEventMap = Record\nexport type InterceptorSubscription = () => void\n\n/**\n * Request header name to detect when a single request\n * is being handled by nested interceptors (XHR -> ClientRequest).\n * Obscure by design to prevent collisions with user-defined headers.\n * Ideally, come up with the Interceptor-level mechanism for this.\n * @see https://github.com/mswjs/interceptors/issues/378\n */\nexport const INTERNAL_REQUEST_ID_HEADER_NAME =\n 'x-interceptors-internal-request-id'\n\nexport function getGlobalSymbol(symbol: Symbol): V | undefined {\n return (\n // @ts-ignore https://github.com/Microsoft/TypeScript/issues/24587\n globalThis[symbol] || undefined\n )\n}\n\nfunction setGlobalSymbol(symbol: Symbol, value: any): void {\n // @ts-ignore\n globalThis[symbol] = value\n}\n\nexport function deleteGlobalSymbol(symbol: Symbol): void {\n // @ts-ignore\n delete globalThis[symbol]\n}\n\nexport enum InterceptorReadyState {\n INACTIVE = 'INACTIVE',\n APPLYING = 'APPLYING',\n APPLIED = 'APPLIED',\n DISPOSING = 'DISPOSING',\n DISPOSED = 'DISPOSED',\n}\n\nexport type ExtractEventNames> =\n Events extends Record ? EventName : never\n\nexport class Interceptor {\n protected emitter: Emitter\n protected subscriptions: Array\n protected logger: Logger\n\n public readyState: InterceptorReadyState\n\n constructor(private readonly symbol: symbol) {\n this.readyState = InterceptorReadyState.INACTIVE\n\n this.emitter = new Emitter()\n this.subscriptions = []\n this.logger = new Logger(symbol.description!)\n\n // Do not limit the maximum number of listeners\n // so not to limit the maximum amount of parallel events emitted.\n this.emitter.setMaxListeners(0)\n\n this.logger.info('constructing the interceptor...')\n }\n\n /**\n * Determine if this interceptor can be applied\n * in the current environment.\n */\n protected checkEnvironment(): boolean {\n return true\n }\n\n /**\n * Apply this interceptor to the current process.\n * Returns an already running interceptor instance if it's present.\n */\n public apply(): void {\n const logger = this.logger.extend('apply')\n logger.info('applying the interceptor...')\n\n if (this.readyState === InterceptorReadyState.APPLIED) {\n logger.info('intercepted already applied!')\n return\n }\n\n const shouldApply = this.checkEnvironment()\n\n if (!shouldApply) {\n logger.info('the interceptor cannot be applied in this environment!')\n return\n }\n\n this.readyState = InterceptorReadyState.APPLYING\n\n // Whenever applying a new interceptor, check if it hasn't been applied already.\n // This enables to apply the same interceptor multiple times, for example from a different\n // interceptor, only proxying events but keeping the stubs in a single place.\n const runningInstance = this.getInstance()\n\n if (runningInstance) {\n logger.info('found a running instance, reusing...')\n\n // Proxy any listeners you set on this instance to the running instance.\n this.on = (event, listener) => {\n logger.info('proxying the \"%s\" listener', event)\n\n // Add listeners to the running instance so they appear\n // at the top of the event listeners list and are executed first.\n runningInstance.emitter.addListener(event, listener)\n\n // Ensure that once this interceptor instance is disposed,\n // it removes all listeners it has appended to the running interceptor instance.\n this.subscriptions.push(() => {\n runningInstance.emitter.removeListener(event, listener)\n logger.info('removed proxied \"%s\" listener!', event)\n })\n\n return this\n }\n\n this.readyState = InterceptorReadyState.APPLIED\n\n return\n }\n\n logger.info('no running instance found, setting up a new instance...')\n\n // Setup the interceptor.\n this.setup()\n\n // Store the newly applied interceptor instance globally.\n this.setInstance()\n\n this.readyState = InterceptorReadyState.APPLIED\n }\n\n /**\n * Setup the module augments and stubs necessary for this interceptor.\n * This method is not run if there's a running interceptor instance\n * to prevent instantiating an interceptor multiple times.\n */\n protected setup(): void {}\n\n /**\n * Listen to the interceptor's public events.\n */\n public on>(\n event: EventName,\n listener: Listener\n ): this {\n const logger = this.logger.extend('on')\n\n if (\n this.readyState === InterceptorReadyState.DISPOSING ||\n this.readyState === InterceptorReadyState.DISPOSED\n ) {\n logger.info('cannot listen to events, already disposed!')\n return this\n }\n\n logger.info('adding \"%s\" event listener:', event, listener)\n\n this.emitter.on(event, listener)\n return this\n }\n\n public once>(\n event: EventName,\n listener: Listener\n ): this {\n this.emitter.once(event, listener)\n return this\n }\n\n public off>(\n event: EventName,\n listener: Listener\n ): this {\n this.emitter.off(event, listener)\n return this\n }\n\n public removeAllListeners>(\n event?: EventName\n ): this {\n this.emitter.removeAllListeners(event)\n return this\n }\n\n /**\n * Disposes of any side-effects this interceptor has introduced.\n */\n public dispose(): void {\n const logger = this.logger.extend('dispose')\n\n if (this.readyState === InterceptorReadyState.DISPOSED) {\n logger.info('cannot dispose, already disposed!')\n return\n }\n\n logger.info('disposing the interceptor...')\n this.readyState = InterceptorReadyState.DISPOSING\n\n if (!this.getInstance()) {\n logger.info('no interceptors running, skipping dispose...')\n return\n }\n\n // Delete the global symbol as soon as possible,\n // indicating that the interceptor is no longer running.\n this.clearInstance()\n\n logger.info('global symbol deleted:', getGlobalSymbol(this.symbol))\n\n if (this.subscriptions.length > 0) {\n logger.info('disposing of %d subscriptions...', this.subscriptions.length)\n\n for (const dispose of this.subscriptions) {\n dispose()\n }\n\n this.subscriptions = []\n\n logger.info('disposed of all subscriptions!', this.subscriptions.length)\n }\n\n this.emitter.removeAllListeners()\n logger.info('destroyed the listener!')\n\n this.readyState = InterceptorReadyState.DISPOSED\n }\n\n private getInstance(): this | undefined {\n const instance = getGlobalSymbol(this.symbol)\n this.logger.info('retrieved global instance:', instance?.constructor?.name)\n return instance\n }\n\n private setInstance(): void {\n setGlobalSymbol(this.symbol, this)\n this.logger.info('set global instance!', this.symbol.description)\n }\n\n private clearInstance(): void {\n deleteGlobalSymbol(this.symbol)\n this.logger.info('cleared global instance!', this.symbol.description)\n }\n}\n","/**\n * Generate a random ID string to represent a request.\n * @example\n * createRequestId()\n * // \"f774b6c9c600f\"\n */\nexport function createRequestId(): string {\n return Math.random().toString(16).slice(2)\n}\n","/**\n * Resolve potentially relative WebSocket URLs the same way\n * the browser does (replace the protocol, use the origin, etc).\n *\n * @see https://websockets.spec.whatwg.org//#dom-websocket-websocket\n */\nexport function resolveWebSocketUrl(url: string | URL): string {\n if (typeof url === 'string') {\n /**\n * @note Cast the string to a URL first so the parsing errors\n * are thrown as a part of the WebSocket constructor, not consumers.\n */\n const urlRecord = new URL(\n url,\n typeof location !== 'undefined' ? location.href : undefined\n )\n\n return resolveWebSocketUrl(urlRecord)\n }\n\n if (url.protocol === 'http:') {\n url.protocol = 'ws:'\n } else if (url.protocol === 'https:') {\n url.protocol = 'wss:'\n }\n\n if (url.protocol !== 'ws:' && url.protocol !== 'wss:') {\n /**\n * @note These errors are modeled after the browser errors.\n * The exact error messages aren't provided in the specification.\n * Node.js uses more obscure error messages that I don't wish to replicate.\n */\n throw new SyntaxError(\n `Failed to construct 'WebSocket': The URL's scheme must be either 'http', 'https', 'ws', or 'wss'. '${url.protocol}' is not allowed.`\n )\n }\n\n if (url.hash !== '') {\n throw new SyntaxError(\n `Failed to construct 'WebSocket': The URL contains a fragment identifier ('${url.hash}'). Fragment identifiers are not allowed in WebSocket URLs.`\n )\n }\n\n return url.href\n}\n","import { Emitter, EventMap } from 'strict-event-emitter'\n\n/**\n * Emits an event on the given emitter but executes\n * the listeners sequentially. This accounts for asynchronous\n * listeners (e.g. those having \"sleep\" and handling the request).\n */\nexport async function emitAsync<\n Events extends EventMap,\n EventName extends keyof Events\n>(\n emitter: Emitter,\n eventName: EventName,\n ...data: Events[EventName]\n): Promise {\n const listeners = emitter.listeners(eventName)\n\n if (listeners.length === 0) {\n return\n }\n\n for (const listener of listeners) {\n await listener.apply(emitter, data)\n }\n}\n","/**\n * Returns a boolean indicating whether the given global property\n * is defined and is configurable.\n */\nexport function hasConfigurableGlobal(propertyName: string): boolean {\n const descriptor = Object.getOwnPropertyDescriptor(globalThis, propertyName)\n\n // The property is not set at all.\n if (typeof descriptor === 'undefined') {\n return false\n }\n\n // The property is set to a getter that returns undefined.\n if (\n typeof descriptor.get === 'function' &&\n typeof descriptor.get() === 'undefined'\n ) {\n return false\n }\n\n // The property is set to a value equal to undefined.\n if (typeof descriptor.get === 'undefined' && descriptor.value == null) {\n return false\n }\n\n if (typeof descriptor.set === 'undefined' && !descriptor.configurable) {\n console.error(\n `[MSW] Failed to apply interceptor: the global \\`${propertyName}\\` property is non-configurable. This is likely an issue with your environment. If you are using a framework, please open an issue about this in their repository.`\n )\n return false\n }\n\n return true\n}\n","export type PromiseState = 'pending' | 'fulfilled' | 'rejected'\n\nexport type Executor = ConstructorParameters>[0]\nexport type ResolveFunction = Parameters>[0]\nexport type RejectFunction = Parameters>[1]\n\nexport type DeferredPromiseExecutor = {\n (resolve?: ResolveFunction, reject?: RejectFunction): void\n\n resolve: ResolveFunction\n reject: RejectFunction\n result?: Output\n state: PromiseState\n rejectionReason?: unknown\n}\nexport function createDeferredExecutor<\n Input = never,\n Output = Input\n>(): DeferredPromiseExecutor {\n const executor = >((\n resolve,\n reject\n ) => {\n executor.state = 'pending'\n\n executor.resolve = (data) => {\n if (executor.state !== 'pending') {\n return\n }\n\n executor.result = data as Output\n\n const onFulfilled = (value: Value) => {\n executor.state = 'fulfilled'\n return value\n }\n\n return resolve(\n data instanceof Promise ? data : Promise.resolve(data).then(onFulfilled)\n )\n }\n\n executor.reject = (reason) => {\n if (executor.state !== 'pending') {\n return\n }\n\n queueMicrotask(() => {\n executor.state = 'rejected'\n })\n\n return reject((executor.rejectionReason = reason))\n }\n })\n\n return executor\n}\n","import {\n type Executor,\n type RejectFunction,\n type ResolveFunction,\n type DeferredPromiseExecutor,\n createDeferredExecutor,\n} from './createDeferredExecutor'\n\nexport class DeferredPromise extends Promise {\n #executor: DeferredPromiseExecutor\n\n public resolve: ResolveFunction\n public reject: RejectFunction\n\n constructor(executor: Executor | null = null) {\n const deferredExecutor = createDeferredExecutor()\n super((originalResolve, originalReject) => {\n deferredExecutor(originalResolve, originalReject)\n executor?.(deferredExecutor.resolve, deferredExecutor.reject)\n })\n\n this.#executor = deferredExecutor\n this.resolve = this.#executor.resolve\n this.reject = this.#executor.reject\n }\n\n public get state() {\n return this.#executor.state\n }\n\n public get rejectionReason() {\n return this.#executor.rejectionReason\n }\n\n public then(\n onFulfilled?: (value: Input) => ThenResult | PromiseLike,\n onRejected?: (reason: any) => CatchResult | PromiseLike\n ) {\n return this.#decorate(super.then(onFulfilled, onRejected))\n }\n\n public catch(\n onRejected?: (reason: any) => CatchResult | PromiseLike\n ) {\n return this.#decorate(super.catch(onRejected))\n }\n\n public finally(onfinally?: () => void | Promise) {\n return this.#decorate(super.finally(onfinally))\n }\n\n #decorate(\n promise: Promise\n ): DeferredPromise {\n return Object.defineProperties(promise, {\n resolve: { configurable: true, value: this.resolve },\n reject: { configurable: true, value: this.reject },\n }) as DeferredPromise\n }\n}\n","type EventWithTarget = E & { target: T }\n\nexport function bindEvent(\n target: T,\n event: E\n): EventWithTarget {\n Object.defineProperties(event, {\n target: {\n value: target,\n enumerable: true,\n writable: true,\n },\n currentTarget: {\n value: target,\n enumerable: true,\n writable: true,\n },\n })\n\n return event as EventWithTarget\n}\n","const kCancelable = Symbol('kCancelable')\nconst kDefaultPrevented = Symbol('kDefaultPrevented')\n\n/**\n * A `MessageEvent` superset that supports event cancellation\n * in Node.js. It's rather non-intrusive so it can be safely\n * used in the browser as well.\n *\n * @see https://github.com/nodejs/node/issues/51767\n */\nexport class CancelableMessageEvent extends MessageEvent {\n [kCancelable]: boolean;\n [kDefaultPrevented]: boolean\n\n constructor(type: string, init: MessageEventInit) {\n super(type, init)\n this[kCancelable] = !!init.cancelable\n this[kDefaultPrevented] = false\n }\n\n get cancelable() {\n return this[kCancelable]\n }\n\n set cancelable(nextCancelable) {\n this[kCancelable] = nextCancelable\n }\n\n get defaultPrevented() {\n return this[kDefaultPrevented]\n }\n\n set defaultPrevented(nextDefaultPrevented) {\n this[kDefaultPrevented] = nextDefaultPrevented\n }\n\n public preventDefault(): void {\n if (this.cancelable && !this[kDefaultPrevented]) {\n this[kDefaultPrevented] = true\n }\n }\n}\n\ninterface CloseEventInit extends EventInit {\n code?: number\n reason?: string\n wasClean?: boolean\n}\n\nexport class CloseEvent extends Event {\n public code: number\n public reason: string\n public wasClean: boolean\n\n constructor(type: string, init: CloseEventInit = {}) {\n super(type, init)\n this.code = init.code === undefined ? 0 : init.code\n this.reason = init.reason === undefined ? '' : init.reason\n this.wasClean = init.wasClean === undefined ? false : init.wasClean\n }\n}\n\nexport class CancelableCloseEvent extends CloseEvent {\n [kCancelable]: boolean;\n [kDefaultPrevented]: boolean\n\n constructor(type: string, init: CloseEventInit = {}) {\n super(type, init)\n this[kCancelable] = !!init.cancelable\n this[kDefaultPrevented] = false\n }\n\n get cancelable() {\n return this[kCancelable]\n }\n\n set cancelable(nextCancelable) {\n this[kCancelable] = nextCancelable\n }\n\n get defaultPrevented() {\n return this[kDefaultPrevented]\n }\n\n set defaultPrevented(nextDefaultPrevented) {\n this[kDefaultPrevented] = nextDefaultPrevented\n }\n\n public preventDefault(): void {\n if (this.cancelable && !this[kDefaultPrevented]) {\n this[kDefaultPrevented] = true\n }\n }\n}\n","import type { WebSocketData, WebSocketTransport } from './WebSocketTransport'\nimport type { WebSocketEventListener } from './WebSocketOverride'\nimport { bindEvent } from './utils/bindEvent'\nimport { CancelableMessageEvent, CloseEvent } from './utils/events'\nimport { createRequestId } from '../../createRequestId'\n\nconst kEmitter = Symbol('kEmitter')\nconst kBoundListener = Symbol('kBoundListener')\n\nexport interface WebSocketClientEventMap {\n message: MessageEvent\n close: CloseEvent\n}\n\nexport abstract class WebSocketClientConnectionProtocol {\n abstract id: string\n abstract url: URL\n public abstract send(data: WebSocketData): void\n public abstract close(code?: number, reason?: string): void\n\n public abstract addEventListener<\n EventType extends keyof WebSocketClientEventMap,\n >(\n type: EventType,\n listener: WebSocketEventListener,\n options?: AddEventListenerOptions | boolean\n ): void\n\n public abstract removeEventListener<\n EventType extends keyof WebSocketClientEventMap,\n >(\n event: EventType,\n listener: WebSocketEventListener,\n options?: EventListenerOptions | boolean\n ): void\n}\n\n/**\n * The WebSocket client instance represents an incoming\n * client connection. The user can control the connection,\n * send and receive events.\n */\nexport class WebSocketClientConnection implements WebSocketClientConnectionProtocol {\n public readonly id: string\n public readonly url: URL\n\n private [kEmitter]: EventTarget\n\n constructor(\n public readonly socket: WebSocket,\n private readonly transport: WebSocketTransport\n ) {\n this.id = createRequestId()\n this.url = new URL(socket.url)\n this[kEmitter] = new EventTarget()\n\n // Emit outgoing client data (\"ws.send()\") as \"message\"\n // events on the \"client\" connection.\n this.transport.addEventListener('outgoing', (event) => {\n const message = bindEvent(\n this.socket,\n new CancelableMessageEvent('message', {\n data: event.data,\n origin: event.origin,\n cancelable: true,\n })\n )\n\n this[kEmitter].dispatchEvent(message)\n\n // This is a bit silly but forward the cancellation state\n // of the \"client\" message event to the \"outgoing\" transport event.\n // This way, other agens (like \"server\" connection) can know\n // whether the client listener has pervented the default.\n if (message.defaultPrevented) {\n event.preventDefault()\n }\n })\n\n /**\n * Emit the \"close\" event on the \"client\" connection\n * whenever the underlying transport is closed.\n * @note \"client.close()\" does NOT dispatch the \"close\"\n * event on the WebSocket because it uses non-configurable\n * close status code. Thus, we listen to the transport\n * instead of the WebSocket's \"close\" event.\n */\n this.transport.addEventListener('close', (event) => {\n this[kEmitter].dispatchEvent(\n bindEvent(this.socket, new CloseEvent('close', event))\n )\n })\n }\n\n /**\n * Listen for the outgoing events from the connected WebSocket client.\n */\n public addEventListener(\n type: EventType,\n listener: WebSocketEventListener,\n options?: AddEventListenerOptions | boolean\n ): void {\n if (!Reflect.has(listener, kBoundListener)) {\n const boundListener = listener.bind(this.socket)\n\n // Store the bound listener on the original listener\n // so the exact bound function can be accessed in \"removeEventListener()\".\n Object.defineProperty(listener, kBoundListener, {\n value: boundListener,\n enumerable: false,\n configurable: false,\n })\n }\n\n this[kEmitter].addEventListener(\n type,\n Reflect.get(listener, kBoundListener) as EventListener,\n options\n )\n }\n\n /**\n * Removes the listener for the given event.\n */\n public removeEventListener(\n event: EventType,\n listener: WebSocketEventListener,\n options?: EventListenerOptions | boolean\n ): void {\n this[kEmitter].removeEventListener(\n event,\n Reflect.get(listener, kBoundListener) as EventListener,\n options\n )\n }\n\n /**\n * Send data to the connected client.\n */\n public send(data: WebSocketData): void {\n this.transport.send(data)\n }\n\n /**\n * Close the WebSocket connection.\n * @param {number} code A status code (see https://www.rfc-editor.org/rfc/rfc6455#section-7.4.1).\n * @param {string} reason A custom connection close reason.\n */\n public close(code?: number, reason?: string): void {\n this.transport.close(code, reason)\n }\n}\n","import { invariant } from 'outvariant'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\nimport type { WebSocketData } from './WebSocketTransport'\nimport { bindEvent } from './utils/bindEvent'\nimport { CloseEvent } from './utils/events'\nimport { resolveWebSocketUrl } from '../../utils/resolveWebSocketUrl'\n\nexport type WebSocketEventListener<\n EventType extends WebSocketEventMap[keyof WebSocketEventMap] = Event,\n> = (this: WebSocket, event: EventType) => void\n\nconst WEBSOCKET_CLOSE_CODE_RANGE_ERROR =\n 'InvalidAccessError: close code out of user configurable range'\n\nexport const kPassthroughPromise = Symbol('kPassthroughPromise')\nexport const kOnSend = Symbol('kOnSend')\nexport const kClose = Symbol('kClose')\n\nexport class WebSocketOverride extends EventTarget implements WebSocket {\n static readonly CONNECTING = 0\n static readonly OPEN = 1\n static readonly CLOSING = 2\n static readonly CLOSED = 3\n readonly CONNECTING = 0\n readonly OPEN = 1\n readonly CLOSING = 2\n readonly CLOSED = 3\n\n public url: string\n public protocol: string\n public extensions: string\n public binaryType: BinaryType\n public readyState: WebSocket['readyState']\n public bufferedAmount: number\n\n private _onopen: WebSocketEventListener | null = null\n private _onmessage: WebSocketEventListener<\n MessageEvent\n > | null = null\n private _onerror: WebSocketEventListener | null = null\n private _onclose: WebSocketEventListener | null = null\n\n private [kPassthroughPromise]: DeferredPromise\n private [kOnSend]?: (data: WebSocketData) => void\n\n constructor(url: string | URL, protocols?: string | Array) {\n super()\n this.url = resolveWebSocketUrl(url)\n this.protocol = ''\n this.extensions = ''\n this.binaryType = 'blob'\n this.readyState = this.CONNECTING\n this.bufferedAmount = 0\n\n this[kPassthroughPromise] = new DeferredPromise()\n\n queueMicrotask(async () => {\n if (await this[kPassthroughPromise]) {\n return\n }\n\n this.protocol =\n typeof protocols === 'string'\n ? protocols\n : Array.isArray(protocols) && protocols.length > 0\n ? protocols[0]\n : ''\n\n /**\n * @note Check that nothing has prevented this connection\n * (e.g. called `client.close()` in the connection listener).\n * If the connection has been prevented, never dispatch the open event,.\n */\n if (this.readyState === this.CONNECTING) {\n this.readyState = this.OPEN\n this.dispatchEvent(bindEvent(this, new Event('open')))\n }\n })\n }\n\n set onopen(listener: WebSocketEventListener | null) {\n this.removeEventListener('open', this._onopen)\n this._onopen = listener\n if (listener !== null) {\n this.addEventListener('open', listener)\n }\n }\n get onopen(): WebSocketEventListener | null {\n return this._onopen\n }\n\n set onmessage(\n listener: WebSocketEventListener> | null\n ) {\n this.removeEventListener(\n 'message',\n this._onmessage as WebSocketEventListener\n )\n this._onmessage = listener\n if (listener !== null) {\n this.addEventListener('message', listener)\n }\n }\n get onmessage(): WebSocketEventListener> | null {\n return this._onmessage\n }\n\n set onerror(listener: WebSocketEventListener | null) {\n this.removeEventListener('error', this._onerror)\n this._onerror = listener\n if (listener !== null) {\n this.addEventListener('error', listener)\n }\n }\n get onerror(): WebSocketEventListener | null {\n return this._onerror\n }\n\n set onclose(listener: WebSocketEventListener | null) {\n this.removeEventListener('close', this._onclose as WebSocketEventListener)\n this._onclose = listener\n if (listener !== null) {\n this.addEventListener('close', listener)\n }\n }\n get onclose(): WebSocketEventListener | null {\n return this._onclose\n }\n\n /**\n * @see https://websockets.spec.whatwg.org/#ref-for-dom-websocket-send%E2%91%A0\n */\n public send(data: WebSocketData): void {\n if (this.readyState === this.CONNECTING) {\n this.close()\n throw new DOMException('InvalidStateError')\n }\n\n // Sending when the socket is about to close\n // discards the sent data.\n if (this.readyState === this.CLOSING || this.readyState === this.CLOSED) {\n return\n }\n\n // Buffer the data to send in this even loop\n // but send it in the next.\n this.bufferedAmount += getDataSize(data)\n\n queueMicrotask(() => {\n // This is a bit optimistic but since no actual data transfer\n // is involved, all the data will be \"sent\" on the next tick.\n this.bufferedAmount = 0\n\n /**\n * @note Notify the parent about outgoing data.\n * This notifies the transport and the connection\n * listens to the outgoing data to emit the \"message\" event.\n */\n this[kOnSend]?.(data)\n })\n }\n\n public close(code: number = 1000, reason?: string): void {\n invariant(code, WEBSOCKET_CLOSE_CODE_RANGE_ERROR)\n invariant(\n code === 1000 || (code >= 3000 && code <= 4999),\n WEBSOCKET_CLOSE_CODE_RANGE_ERROR\n )\n\n this[kClose](code, reason)\n }\n\n private [kClose](\n code: number = 1000,\n reason?: string,\n wasClean = true\n ): void {\n /**\n * @note Move this check here so that even internal closures,\n * like those triggered by the `server` connection, are not\n * performed twice.\n */\n if (this.readyState === this.CLOSING || this.readyState === this.CLOSED) {\n return\n }\n\n this.readyState = this.CLOSING\n\n queueMicrotask(() => {\n this.readyState = this.CLOSED\n\n this.dispatchEvent(\n bindEvent(\n this,\n new CloseEvent('close', {\n code,\n reason,\n wasClean,\n })\n )\n )\n\n // Remove all event listeners once the socket is closed.\n this._onopen = null\n this._onmessage = null\n this._onerror = null\n this._onclose = null\n })\n }\n\n public addEventListener(\n type: K,\n listener: (this: WebSocket, event: WebSocketEventMap[K]) => void,\n options?: boolean | AddEventListenerOptions\n ): void\n public addEventListener(\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | AddEventListenerOptions\n ): void\n public addEventListener(\n type: unknown,\n listener: unknown,\n options?: unknown\n ): void {\n return super.addEventListener(\n type as string,\n listener as EventListener,\n options as AddEventListenerOptions\n )\n }\n\n removeEventListener(\n type: K,\n callback: EventListenerOrEventListenerObject | null,\n options?: boolean | EventListenerOptions\n ): void {\n return super.removeEventListener(type, callback, options)\n }\n}\n\nfunction getDataSize(data: WebSocketData): number {\n if (typeof data === 'string') {\n return data.length\n }\n\n if (data instanceof Blob) {\n return data.size\n }\n\n return data.byteLength\n}\n","import { invariant } from 'outvariant'\nimport {\n kClose,\n WebSocketEventListener,\n WebSocketOverride,\n} from './WebSocketOverride'\nimport type { WebSocketData } from './WebSocketTransport'\nimport type { WebSocketClassTransport } from './WebSocketClassTransport'\nimport { bindEvent } from './utils/bindEvent'\nimport {\n CancelableMessageEvent,\n CancelableCloseEvent,\n CloseEvent,\n} from './utils/events'\n\nconst kEmitter = Symbol('kEmitter')\nconst kBoundListener = Symbol('kBoundListener')\nconst kSend = Symbol('kSend')\n\nexport interface WebSocketServerEventMap {\n open: Event\n message: MessageEvent\n error: Event\n close: CloseEvent\n}\n\nexport abstract class WebSocketServerConnectionProtocol {\n public abstract connect(): void\n public abstract send(data: WebSocketData): void\n public abstract close(): void\n\n public abstract addEventListener<\n EventType extends keyof WebSocketServerEventMap,\n >(\n event: EventType,\n listener: WebSocketEventListener,\n options?: AddEventListenerOptions | boolean\n ): void\n\n public abstract removeEventListener<\n EventType extends keyof WebSocketServerEventMap,\n >(\n event: EventType,\n listener: WebSocketEventListener,\n options?: EventListenerOptions | boolean\n ): void\n}\n\n/**\n * The WebSocket server instance represents the actual production\n * WebSocket server connection. It's idle by default but you can\n * establish it by calling `server.connect()`.\n */\nexport class WebSocketServerConnection implements WebSocketServerConnectionProtocol {\n /**\n * A WebSocket instance connected to the original server.\n */\n private realWebSocket?: WebSocket\n private mockCloseController: AbortController\n private realCloseController: AbortController\n private [kEmitter]: EventTarget\n\n constructor(\n private readonly client: WebSocketOverride,\n private readonly transport: WebSocketClassTransport,\n private readonly createConnection: () => WebSocket\n ) {\n this[kEmitter] = new EventTarget()\n this.mockCloseController = new AbortController()\n this.realCloseController = new AbortController()\n\n // Automatically forward outgoing client events\n // to the actual server unless the outgoing message event\n // has been prevented. The \"outgoing\" transport event it\n // dispatched by the \"client\" connection.\n this.transport.addEventListener('outgoing', (event) => {\n // Ignore client messages if the server connection\n // hasn't been established yet. Nowhere to forward.\n if (typeof this.realWebSocket === 'undefined') {\n return\n }\n\n // Every outgoing client message can prevent this forwarding\n // by preventing the default of the outgoing message event.\n // This listener will be added before user-defined listeners,\n // so execute the logic on the next tick.\n queueMicrotask(() => {\n if (!event.defaultPrevented) {\n /**\n * @note Use the internal send mechanism so consumers can tell\n * apart direct user calls to `server.send()` and internal calls.\n * E.g. MSW has to ignore this internal call to log out messages correctly.\n */\n this[kSend](event.data)\n }\n })\n })\n\n this.transport.addEventListener(\n 'incoming',\n this.handleIncomingMessage.bind(this)\n )\n }\n\n /**\n * The `WebSocket` instance connected to the original server.\n * Accessing this before calling `server.connect()` will throw.\n */\n public get socket(): WebSocket {\n invariant(\n this.realWebSocket,\n 'Cannot access \"socket\" on the original WebSocket server object: the connection is not open. Did you forget to call `server.connect()`?'\n )\n\n return this.realWebSocket\n }\n\n /**\n * Open connection to the original WebSocket server.\n */\n public connect(): void {\n invariant(\n !this.realWebSocket || this.realWebSocket.readyState !== WebSocket.OPEN,\n 'Failed to call \"connect()\" on the original WebSocket instance: the connection already open'\n )\n\n const realWebSocket = this.createConnection()\n\n // Inherit the binary type from the mock WebSocket client.\n realWebSocket.binaryType = this.client.binaryType\n\n // Allow the interceptor to listen to when the server connection\n // has been established. This isn't necessary to operate with the connection\n // but may be beneficial in some cases (like conditionally adding logging).\n realWebSocket.addEventListener(\n 'open',\n (event) => {\n this[kEmitter].dispatchEvent(\n bindEvent(this.realWebSocket!, new Event('open', event))\n )\n },\n { once: true }\n )\n\n realWebSocket.addEventListener('message', (event) => {\n // Dispatch the \"incoming\" transport event instead of\n // invoking the internal handler directly. This way,\n // anyone can listen to the \"incoming\" event but this\n // class is the one resulting in it.\n this.transport.dispatchEvent(\n bindEvent(\n this.realWebSocket!,\n new MessageEvent('incoming', {\n data: event.data,\n origin: event.origin,\n })\n )\n )\n })\n\n // Close the original connection when the mock client closes.\n // E.g. \"client.close()\" was called. This is never forwarded anywhere.\n this.client.addEventListener(\n 'close',\n (event) => {\n this.handleMockClose(event)\n },\n {\n signal: this.mockCloseController.signal,\n }\n )\n\n // Forward the \"close\" event to let the interceptor handle\n // closures initiated by the original server.\n realWebSocket.addEventListener(\n 'close',\n (event) => {\n this.handleRealClose(event)\n },\n {\n signal: this.realCloseController.signal,\n }\n )\n\n realWebSocket.addEventListener('error', () => {\n const errorEvent = bindEvent(\n realWebSocket,\n new Event('error', { cancelable: true })\n )\n\n // Emit the \"error\" event on the `server` connection\n // to let the interceptor react to original server errors.\n this[kEmitter].dispatchEvent(errorEvent)\n\n // If the error event from the original server hasn't been prevented,\n // forward it to the underlying client.\n if (!errorEvent.defaultPrevented) {\n this.client.dispatchEvent(bindEvent(this.client, new Event('error')))\n }\n })\n\n this.realWebSocket = realWebSocket\n }\n\n /**\n * Listen for the incoming events from the original WebSocket server.\n */\n public addEventListener(\n event: EventType,\n listener: WebSocketEventListener,\n options?: AddEventListenerOptions | boolean\n ): void {\n if (!Reflect.has(listener, kBoundListener)) {\n const boundListener = listener.bind(this.client)\n\n // Store the bound listener on the original listener\n // so the exact bound function can be accessed in \"removeEventListener()\".\n Object.defineProperty(listener, kBoundListener, {\n value: boundListener,\n enumerable: false,\n })\n }\n\n this[kEmitter].addEventListener(\n event,\n Reflect.get(listener, kBoundListener) as EventListener,\n options\n )\n }\n\n /**\n * Remove the listener for the given event.\n */\n public removeEventListener(\n event: EventType,\n listener: WebSocketEventListener,\n options?: EventListenerOptions | boolean\n ): void {\n this[kEmitter].removeEventListener(\n event,\n Reflect.get(listener, kBoundListener) as EventListener,\n options\n )\n }\n\n /**\n * Send data to the original WebSocket server.\n * @example\n * server.send('hello')\n * server.send(new Blob(['hello']))\n * server.send(new TextEncoder().encode('hello'))\n */\n public send(data: WebSocketData): void {\n this[kSend](data)\n }\n\n private [kSend](data: WebSocketData): void {\n const { realWebSocket } = this\n\n invariant(\n realWebSocket,\n 'Failed to call \"server.send()\" for \"%s\": the connection is not open. Did you forget to call \"server.connect()\"?',\n this.client.url\n )\n\n // Silently ignore writes on the closed original WebSocket.\n if (\n realWebSocket.readyState === WebSocket.CLOSING ||\n realWebSocket.readyState === WebSocket.CLOSED\n ) {\n return\n }\n\n // Delegate the send to when the original connection is open.\n // Unlike the mock, connecting to the original server may take time\n // so we cannot call this on the next tick.\n if (realWebSocket.readyState === WebSocket.CONNECTING) {\n realWebSocket.addEventListener(\n 'open',\n () => {\n realWebSocket.send(data)\n },\n { once: true }\n )\n return\n }\n\n // Send the data to the original WebSocket server.\n realWebSocket.send(data)\n }\n\n /**\n * Close the actual server connection.\n */\n public close(): void {\n const { realWebSocket } = this\n\n invariant(\n realWebSocket,\n 'Failed to close server connection for \"%s\": the connection is not open. Did you forget to call \"server.connect()\"?',\n this.client.url\n )\n\n // Remove the \"close\" event listener from the server\n // so it doesn't close the underlying WebSocket client\n // when you call \"server.close()\". This also prevents the\n // `close` event on the `server` connection from being dispatched twice.\n this.realCloseController.abort()\n\n if (\n realWebSocket.readyState === WebSocket.CLOSING ||\n realWebSocket.readyState === WebSocket.CLOSED\n ) {\n return\n }\n\n // Close the actual client connection.\n realWebSocket.close()\n\n // Dispatch the \"close\" event on the `server` connection.\n queueMicrotask(() => {\n this[kEmitter].dispatchEvent(\n bindEvent(\n this.realWebSocket,\n new CancelableCloseEvent('close', {\n /**\n * @note `server.close()` in the interceptor\n * always results in clean closures.\n */\n code: 1000,\n cancelable: true,\n })\n )\n )\n })\n }\n\n private handleIncomingMessage(event: MessageEvent): void {\n // Clone the event to dispatch it on this class\n // once again and prevent the \"already being dispatched\"\n // exception. Clone it here so we can observe this event\n // being prevented in the \"server.on()\" listeners.\n const messageEvent = bindEvent(\n event.target,\n new CancelableMessageEvent('message', {\n data: event.data,\n origin: event.origin,\n cancelable: true,\n })\n )\n\n /**\n * @note Emit \"message\" event on the server connection\n * instance to let the interceptor know about these\n * incoming events from the original server. In that listener,\n * the interceptor can modify or skip the event forwarding\n * to the mock WebSocket instance.\n */\n this[kEmitter].dispatchEvent(messageEvent)\n\n /**\n * @note Forward the incoming server events to the client.\n * Preventing the default on the message event stops this.\n */\n if (!messageEvent.defaultPrevented) {\n this.client.dispatchEvent(\n bindEvent(\n /**\n * @note Bind the forwarded original server events\n * to the mock WebSocket instance so it would\n * dispatch them straight away.\n */\n this.client,\n // Clone the message event again to prevent\n // the \"already being dispatched\" exception.\n new MessageEvent('message', {\n data: event.data,\n origin: event.origin,\n })\n )\n )\n }\n }\n\n private handleMockClose(_event: Event): void {\n // Close the original connection if the mock client closes.\n if (this.realWebSocket) {\n this.realWebSocket.close()\n }\n }\n\n private handleRealClose(event: CloseEvent): void {\n // For closures originating from the original server,\n // remove the \"close\" listener from the mock client.\n // original close -> (?) client[kClose]() --X--> \"close\" (again).\n this.mockCloseController.abort()\n\n const closeEvent = bindEvent(\n this.realWebSocket,\n new CancelableCloseEvent('close', {\n code: event.code,\n reason: event.reason,\n wasClean: event.wasClean,\n cancelable: true,\n })\n )\n\n this[kEmitter].dispatchEvent(closeEvent)\n\n // If the close event from the server hasn't been prevented,\n // forward the closure to the mock client.\n if (!closeEvent.defaultPrevented) {\n // Close the intercepted client forcefully to\n // allow non-configurable status codes from the server.\n // If the socket has been closed by now, no harm calling\n // this again—it will have no effect.\n this.client[kClose](event.code, event.reason)\n }\n }\n}\n","import { bindEvent } from './utils/bindEvent'\nimport {\n StrictEventListenerOrEventListenerObject,\n WebSocketData,\n WebSocketTransport,\n WebSocketTransportEventMap,\n} from './WebSocketTransport'\nimport { kOnSend, kClose, WebSocketOverride } from './WebSocketOverride'\nimport { CancelableMessageEvent, CloseEvent } from './utils/events'\n\n/**\n * Abstraction over the given mock `WebSocket` instance that allows\n * for controlling that instance (e.g. sending and receiving messages).\n */\nexport class WebSocketClassTransport\n extends EventTarget\n implements WebSocketTransport\n{\n constructor(protected readonly socket: WebSocketOverride) {\n super()\n\n // Emit the \"close\" event on the transport if the close\n // originates from the WebSocket client. E.g. the application\n // calls \"ws.close()\", not the interceptor.\n this.socket.addEventListener('close', (event) => {\n this.dispatchEvent(bindEvent(this.socket, new CloseEvent('close', event)))\n })\n\n /**\n * Emit the \"outgoing\" event on the transport\n * whenever the WebSocket client sends data (\"ws.send()\").\n */\n this.socket[kOnSend] = (data) => {\n this.dispatchEvent(\n bindEvent(\n this.socket,\n // Dispatch this as cancelable because \"client\" connection\n // re-creates this message event (cannot dispatch the same event).\n new CancelableMessageEvent('outgoing', {\n data,\n origin: this.socket.url,\n cancelable: true,\n })\n )\n )\n }\n }\n\n public addEventListener(\n type: EventType,\n callback: StrictEventListenerOrEventListenerObject<\n WebSocketTransportEventMap[EventType]\n > | null,\n options?: boolean | AddEventListenerOptions\n ): void {\n return super.addEventListener(type, callback as EventListener, options)\n }\n\n public dispatchEvent(\n event: WebSocketTransportEventMap[EventType]\n ): boolean {\n return super.dispatchEvent(event)\n }\n\n public send(data: WebSocketData): void {\n queueMicrotask(() => {\n if (\n this.socket.readyState === this.socket.CLOSING ||\n this.socket.readyState === this.socket.CLOSED\n ) {\n return\n }\n\n const dispatchEvent = () => {\n this.socket.dispatchEvent(\n bindEvent(\n /**\n * @note Setting this event's \"target\" to the\n * WebSocket override instance is important.\n * This way it can tell apart original incoming events\n * (must be forwarded to the transport) from the\n * mocked message events like the one below\n * (must be dispatched on the client instance).\n */\n this.socket,\n new MessageEvent('message', {\n data,\n origin: this.socket.url,\n })\n )\n )\n }\n\n if (this.socket.readyState === this.socket.CONNECTING) {\n this.socket.addEventListener(\n 'open',\n () => {\n dispatchEvent()\n },\n { once: true }\n )\n } else {\n dispatchEvent()\n }\n })\n }\n\n public close(code: number, reason?: string): void {\n /**\n * @note Call the internal close method directly\n * to allow closing the connection with the status codes\n * that are non-configurable by the user (> 1000 <= 1015).\n */\n this.socket[kClose](code, reason)\n }\n}\n","import { Interceptor } from '../../Interceptor'\nimport {\n WebSocketClientConnectionProtocol,\n WebSocketClientConnection,\n type WebSocketClientEventMap,\n} from './WebSocketClientConnection'\nimport {\n WebSocketServerConnectionProtocol,\n WebSocketServerConnection,\n type WebSocketServerEventMap,\n} from './WebSocketServerConnection'\nimport { WebSocketClassTransport } from './WebSocketClassTransport'\nimport {\n kClose,\n kPassthroughPromise,\n WebSocketOverride,\n} from './WebSocketOverride'\nimport { bindEvent } from './utils/bindEvent'\nimport { hasConfigurableGlobal } from '../../utils/hasConfigurableGlobal'\nimport { emitAsync } from '../../utils/emitAsync'\n\nexport {\n type WebSocketData,\n type WebSocketTransport,\n} from './WebSocketTransport'\nexport {\n WebSocketClientEventMap,\n WebSocketClientConnectionProtocol,\n WebSocketClientConnection,\n WebSocketServerEventMap,\n WebSocketServerConnectionProtocol,\n WebSocketServerConnection,\n}\n\nexport {\n CloseEvent,\n CancelableCloseEvent,\n CancelableMessageEvent,\n} from './utils/events'\n\nexport type WebSocketEventMap = {\n connection: [args: WebSocketConnectionData]\n}\n\nexport type WebSocketConnectionData = {\n /**\n * The incoming WebSocket client connection.\n */\n client: WebSocketClientConnection\n\n /**\n * The original WebSocket server connection.\n */\n server: WebSocketServerConnection\n\n /**\n * The connection information.\n */\n info: {\n /**\n * The protocols supported by the WebSocket client.\n */\n protocols: string | Array | undefined\n }\n}\n\n/**\n * Intercept the outgoing WebSocket connections created using\n * the global `WebSocket` class.\n */\nexport class WebSocketInterceptor extends Interceptor {\n static symbol = Symbol('websocket')\n\n constructor() {\n super(WebSocketInterceptor.symbol)\n }\n\n protected checkEnvironment(): boolean {\n return hasConfigurableGlobal('WebSocket')\n }\n\n protected setup(): void {\n const originalWebSocketDescriptor = Object.getOwnPropertyDescriptor(\n globalThis,\n 'WebSocket'\n )\n\n const WebSocketProxy = new Proxy(globalThis.WebSocket, {\n construct: (\n target,\n args: ConstructorParameters,\n newTarget\n ) => {\n const [url, protocols] = args\n\n const createConnection = (): WebSocket => {\n return Reflect.construct(target, args, newTarget)\n }\n\n // All WebSocket instances are mocked and don't forward\n // any events to the original server (no connection established).\n // To forward the events, the user must use the \"server.send()\" API.\n const socket = new WebSocketOverride(url, protocols)\n const transport = new WebSocketClassTransport(socket)\n\n // Emit the \"connection\" event to the interceptor on the next tick\n // so the client can modify WebSocket options, like \"binaryType\"\n // while the connection is already pending.\n queueMicrotask(async () => {\n try {\n const server = new WebSocketServerConnection(\n socket,\n transport,\n createConnection\n )\n\n const hasConnectionListeners =\n this.emitter.listenerCount('connection') > 0\n\n // The \"globalThis.WebSocket\" class stands for\n // the client-side connection. Assume it's established\n // as soon as the WebSocket instance is constructed.\n await emitAsync(this.emitter, 'connection', {\n client: new WebSocketClientConnection(socket, transport),\n server,\n info: {\n protocols,\n },\n })\n\n if (hasConnectionListeners) {\n socket[kPassthroughPromise].resolve(false)\n } else {\n socket[kPassthroughPromise].resolve(true)\n\n server.connect()\n\n // Forward the \"open\" event from the original server\n // to the mock WebSocket client in the case of a passthrough connection.\n server.addEventListener('open', () => {\n socket.dispatchEvent(bindEvent(socket, new Event('open')))\n\n // Forward the original connection protocol to the\n // mock WebSocket client.\n if (server['realWebSocket']) {\n socket.protocol = server['realWebSocket'].protocol\n }\n })\n }\n } catch (error) {\n /**\n * @note Translate unhandled exceptions during the connection\n * handling (i.e. interceptor exceptions) as WebSocket connection\n * closures with error. This prevents from the exceptions occurring\n * in `queueMicrotask` from being process-wide and uncatchable.\n */\n if (error instanceof Error) {\n socket.dispatchEvent(new Event('error'))\n\n // No need to close the connection if it's already being closed.\n // E.g. the interceptor called `client.close()` and then threw an error.\n if (\n socket.readyState !== WebSocket.CLOSING &&\n socket.readyState !== WebSocket.CLOSED\n ) {\n socket[kClose](1011, error.message, false)\n }\n\n console.error(error)\n }\n }\n })\n\n return socket\n },\n })\n\n Object.defineProperty(globalThis, 'WebSocket', {\n value: WebSocketProxy,\n configurable: true,\n })\n\n this.subscriptions.push(() => {\n Object.defineProperty(\n globalThis,\n 'WebSocket',\n originalWebSocketDescriptor!\n )\n })\n }\n}\n","import { invariant } from 'outvariant'\nimport { isNodeProcess } from 'is-node-process'\nimport { WebSocketInterceptor } from '@mswjs/interceptors/WebSocket'\nimport {\n defineNetwork,\n NetworkReadyState,\n} from '#core/experimental/define-network'\nimport type { AnyHandler } from '#core/experimental/handlers-controller'\nimport { InterceptorSource } from '#core/experimental/sources/interceptor-source'\nimport { fromLegacyOnUnhandledRequest } from '#core/experimental/compat'\nimport type { LifeCycleEventEmitter } from '#core/sharedOptions'\nimport type { HttpNetworkFrameEventMap } from '#core/experimental/frames/http-frame'\nimport type { WebSocketNetworkFrameEventMap } from '#core/experimental/frames/websocket-frame'\nimport { devUtils } from '#core/utils/internal/devUtils'\nimport { supportsServiceWorker } from './utils/supports'\nimport { ServiceWorkerSource } from './sources/service-worker-source'\nimport { FallbackHttpSource } from './sources/fallback-http-source'\nimport type {\n SetupWorker,\n StartOptions,\n StartReturnType,\n StopHandler,\n} from './glossary'\n\nconst DEFAULT_WORKER_URL = '/mockServiceWorker.js'\n\n/**\n * Sets up a requests interception in the browser with the given request handlers.\n * @param {Array} handlers List of request handlers.\n *\n * @see {@link https://mswjs.io/docs/api/setup-worker `setupWorker()` API reference}\n */\nexport function setupWorker(...handlers: Array): SetupWorker {\n invariant(\n !isNodeProcess(),\n devUtils.formatMessage(\n 'Failed to execute `setupWorker` in a non-browser environment',\n ),\n )\n\n const network = defineNetwork<\n Array\n >({\n sources: [],\n handlers,\n })\n\n return {\n async start(options) {\n if (options?.waitUntilReady != null) {\n devUtils.warn(\n `The \"waitUntilReady\" option has been deprecated. Please remove it from this \"worker.start()\" call. Follow the recommended Browser integration (https://mswjs.io/docs/integrations/browser) to eliminate any race conditions between the Service Worker registration and any requests made by your application on initial render.`,\n )\n }\n\n /**\n * @todo @fixme\n * This is kept for backward-compatibility reasons. We don't really need this check anymore.\n */\n if (network.readyState === NetworkReadyState.ENABLED) {\n devUtils.warn(\n 'Found a redundant \"worker.start()\" call. Note that starting the worker while mocking is already enabled will have no effect. Consider removing this \"worker.start()\" call.',\n )\n return\n }\n\n const httpSource = supportsServiceWorker()\n ? await ServiceWorkerSource.from({\n serviceWorker: {\n url:\n options?.serviceWorker?.url?.toString() || DEFAULT_WORKER_URL,\n options: options?.serviceWorker?.options,\n },\n findWorker: options?.findWorker,\n quiet: options?.quiet,\n })\n : new FallbackHttpSource({\n quiet: options?.quiet,\n })\n\n network.configure({\n sources: [\n httpSource,\n new InterceptorSource({\n interceptors: [new WebSocketInterceptor() as any],\n }),\n ],\n onUnhandledFrame: fromLegacyOnUnhandledRequest(() => {\n return options?.onUnhandledRequest || 'warn'\n }),\n context: {\n quiet: options?.quiet,\n },\n })\n\n await network.enable()\n\n if (httpSource instanceof ServiceWorkerSource) {\n const [, registration] = await httpSource.workerPromise\n return registration\n }\n },\n stop() {\n if (network.readyState === NetworkReadyState.DISABLED) {\n devUtils.warn(\n `Found a redundant \"worker.stop()\" call. Notice that stopping the worker after it has already been stopped has no effect. Consider removing this \"worker.stop()\" call.`,\n )\n return\n }\n\n network.disable()\n window.postMessage({ type: 'msw/worker:stop' })\n },\n events: network.events,\n use: network.use.bind(network),\n resetHandlers: network.resetHandlers.bind(network),\n restoreHandlers: network.restoreHandlers.bind(network),\n listHandlers: network.listHandlers.bind(network),\n }\n}\n\n/**\n * @deprecated\n * Please use the `defineNetwork` API instead.\n */\nexport class SetupWorkerApi implements SetupWorker {\n start: (options?: StartOptions) => StartReturnType\n stop: StopHandler\n use: (...handlers: Array) => void\n resetHandlers: (...nextHandlers: Array) => void\n restoreHandlers: () => void\n listHandlers: () => ReadonlyArray\n events: LifeCycleEventEmitter<\n HttpNetworkFrameEventMap & WebSocketNetworkFrameEventMap\n >\n\n constructor() {\n const worker = setupWorker()\n\n this.start = worker.start.bind(worker)\n this.stop = worker.stop.bind(worker)\n this.use = worker.use.bind(worker)\n this.resetHandlers = worker.resetHandlers.bind(worker)\n this.restoreHandlers = worker.restoreHandlers.bind(worker)\n this.listHandlers = worker.listHandlers.bind(worker)\n this.events = worker.events\n }\n}\n","/**\n * Checks if the Service Worker API is supproted and available\n * in the current browsing context.\n */\nexport function supportsServiceWorker(): boolean {\n return (\n typeof navigator !== 'undefined' &&\n 'serviceWorker' in navigator &&\n typeof location !== 'undefined' &&\n location.protocol !== 'file:'\n )\n}\n\n/**\n * Returns a boolean indicating whether the current browser\n * supports `ReadableStream` as a `Transferable` when posting\n * messages.\n */\nexport function supportsReadableStreamTransfer() {\n try {\n const stream = new ReadableStream({\n start: (controller) => controller.close(),\n })\n const message = new MessageChannel()\n message.port1.postMessage(stream, [stream])\n return true\n } catch {\n return false\n }\n}\n","export type PromiseState = 'pending' | 'fulfilled' | 'rejected'\n\nexport type Executor = ConstructorParameters>[0]\nexport type ResolveFunction = Parameters>[0]\nexport type RejectFunction = Parameters>[1]\n\nexport type DeferredPromiseExecutor = {\n (resolve?: ResolveFunction, reject?: RejectFunction): void\n\n resolve: ResolveFunction\n reject: RejectFunction\n result?: Output\n state: PromiseState\n rejectionReason?: unknown\n}\nexport function createDeferredExecutor<\n Input = never,\n Output = Input\n>(): DeferredPromiseExecutor {\n const executor = >((\n resolve,\n reject\n ) => {\n executor.state = 'pending'\n\n executor.resolve = (data) => {\n if (executor.state !== 'pending') {\n return\n }\n\n executor.result = data as Output\n\n const onFulfilled = (value: Value) => {\n executor.state = 'fulfilled'\n return value\n }\n\n return resolve(\n data instanceof Promise ? data : Promise.resolve(data).then(onFulfilled)\n )\n }\n\n executor.reject = (reason) => {\n if (executor.state !== 'pending') {\n return\n }\n\n queueMicrotask(() => {\n executor.state = 'rejected'\n })\n\n return reject((executor.rejectionReason = reason))\n }\n })\n\n return executor\n}\n","import {\n type Executor,\n type RejectFunction,\n type ResolveFunction,\n type DeferredPromiseExecutor,\n createDeferredExecutor,\n} from './create-deferred-executor'\n\nexport class DeferredPromise extends Promise {\n #executor: DeferredPromiseExecutor\n\n public resolve: ResolveFunction\n public reject: RejectFunction\n\n constructor(executor: Executor | null = null) {\n const deferredExecutor = createDeferredExecutor()\n super((originalResolve, originalReject) => {\n deferredExecutor(originalResolve, originalReject)\n executor?.(deferredExecutor.resolve, deferredExecutor.reject)\n })\n\n this.#executor = deferredExecutor\n this.resolve = this.#executor.resolve\n this.reject = this.#executor.reject\n }\n\n public get state() {\n return this.#executor.state\n }\n\n public get rejectionReason() {\n return this.#executor.rejectionReason\n }\n\n public then(\n onFulfilled?: (value: Input) => ThenResult | PromiseLike,\n onRejected?: (reason: any) => CatchResult | PromiseLike,\n ) {\n return this.#decorate(super.then(onFulfilled, onRejected))\n }\n\n public catch(\n onRejected?: (reason: any) => CatchResult | PromiseLike,\n ) {\n return this.#decorate(super.catch(onRejected))\n }\n\n public finally(onfinally?: () => void | Promise) {\n return this.#decorate(super.finally(onfinally))\n }\n\n #decorate(\n promise: Promise,\n ): DeferredPromise {\n return Object.defineProperties(promise, {\n resolve: { configurable: true, value: this.resolve },\n reject: { configurable: true, value: this.reject },\n }) as DeferredPromise\n }\n}\n","import type { RequestController } from './RequestController'\n\nexport const IS_PATCHED_MODULE: unique symbol = Symbol('isPatchedModule')\n\n/**\n * @note Export `RequestController` as a type only.\n * It's never meant to be created in the userland.\n */\nexport type { RequestController }\n\nexport type RequestCredentials = 'omit' | 'include' | 'same-origin'\n\nexport type HttpRequestEventMap = {\n request: [\n args: {\n request: Request\n requestId: string\n controller: RequestController\n }\n ]\n response: [\n args: {\n response: Response\n isMockedResponse: boolean\n request: Request\n requestId: string\n }\n ]\n unhandledException: [\n args: {\n error: unknown\n request: Request\n requestId: string\n controller: RequestController\n }\n ]\n}\n","export class InterceptorError extends Error {\n constructor(message?: string) {\n super(message)\n this.name = 'InterceptorError'\n Object.setPrototypeOf(this, InterceptorError.prototype)\n }\n}\n","import { DeferredPromise } from '@open-draft/deferred-promise'\nimport { invariant } from 'outvariant'\nimport { InterceptorError } from './InterceptorError'\n\nexport interface RequestControllerSource {\n passthrough(): void\n respondWith(response: Response): void\n errorWith(reason?: unknown): void\n}\n\nexport class RequestController {\n static PENDING = 0 as const\n static PASSTHROUGH = 1 as const\n static RESPONSE = 2 as const\n static ERROR = 3 as const\n\n public readyState: number\n\n /**\n * A Promise that resolves when this controller handles a request.\n * See `controller.readyState` for more information on the handling result.\n */\n public handled: Promise\n\n constructor(\n protected readonly request: Request,\n protected readonly source: RequestControllerSource\n ) {\n this.readyState = RequestController.PENDING\n this.handled = new DeferredPromise()\n }\n\n get #handled() {\n return this.handled as DeferredPromise\n }\n\n /**\n * Perform this request as-is.\n */\n public async passthrough(): Promise {\n invariant.as(\n InterceptorError,\n this.readyState === RequestController.PENDING,\n 'Failed to passthrough the \"%s %s\" request: the request has already been handled',\n this.request.method,\n this.request.url\n )\n\n this.readyState = RequestController.PASSTHROUGH\n await this.source.passthrough()\n this.#handled.resolve()\n }\n\n /**\n * Respond to this request with the given `Response` instance.\n *\n * @example\n * controller.respondWith(new Response())\n * controller.respondWith(Response.json({ id }))\n * controller.respondWith(Response.error())\n */\n public respondWith(response: Response): void {\n invariant.as(\n InterceptorError,\n this.readyState === RequestController.PENDING,\n 'Failed to respond to the \"%s %s\" request with \"%d %s\": the request has already been handled (%d)',\n this.request.method,\n this.request.url,\n response.status,\n response.statusText || 'OK',\n this.readyState\n )\n\n this.readyState = RequestController.RESPONSE\n this.#handled.resolve()\n\n /**\n * @note Although `source.respondWith()` is potentially asynchronous,\n * do NOT await it for backward-compatibility. Awaiting it will short-circuit\n * the request listener invocation as soon as a listener responds to a request.\n * Ideally, that's what we want, but that's not what we promise the user.\n */\n this.source.respondWith(response)\n }\n\n /**\n * Error this request with the given reason.\n *\n * @example\n * controller.errorWith()\n * controller.errorWith(new Error('Oops!'))\n * controller.errorWith({ message: 'Oops!'})\n */\n public errorWith(reason?: unknown): void {\n invariant.as(\n InterceptorError,\n this.readyState === RequestController.PENDING,\n 'Failed to error the \"%s %s\" request with \"%s\": the request has already been handled (%d)',\n this.request.method,\n this.request.url,\n reason?.toString(),\n this.readyState\n )\n\n this.readyState = RequestController.ERROR\n this.source.errorWith(reason)\n this.#handled.resolve()\n }\n}\n","/**\n * Returns a boolean indicating whether the given URL string\n * can be parsed into a `URL` instance.\n * A substitute for `URL.canParse()` for Node.js 18.\n */\nexport function canParseUrl(url: string): boolean {\n try {\n new URL(url)\n return true\n } catch (_error) {\n return false\n }\n}\n","/**\n * Returns the value behind the symbol with the given name.\n */\nexport function getValueBySymbol(\n symbolName: string,\n source: object\n): T | undefined {\n const ownSymbols = Object.getOwnPropertySymbols(source)\n\n const symbol = ownSymbols.find((symbol) => {\n return symbol.description === symbolName\n })\n\n if (symbol) {\n return Reflect.get(source, symbol)\n }\n\n return\n}\n","import { canParseUrl } from './canParseUrl'\nimport { getValueBySymbol } from './getValueBySymbol'\n\nexport interface FetchResponseInit extends ResponseInit {\n url?: string\n}\n\ninterface UndiciFetchInternalState {\n aborted: boolean\n rangeRequested: boolean\n timingAllowPassed: boolean\n requestIncludesCredentials: boolean\n type: ResponseType\n status: number\n statusText: string\n timingInfo: unknown\n cacheState: unknown\n headersList: Record>\n urlList: Array\n body?: {\n stream: ReadableStream\n source: unknown\n length: number\n }\n}\n\nexport class FetchResponse extends Response {\n /**\n * Response status codes for responses that cannot have body.\n * @see https://fetch.spec.whatwg.org/#statuses\n */\n static readonly STATUS_CODES_WITHOUT_BODY = [101, 103, 204, 205, 304]\n\n static readonly STATUS_CODES_WITH_REDIRECT = [301, 302, 303, 307, 308]\n\n static isConfigurableStatusCode(status: number): boolean {\n return status >= 200 && status <= 599\n }\n\n static isRedirectResponse(status: number): boolean {\n return FetchResponse.STATUS_CODES_WITH_REDIRECT.includes(status)\n }\n\n /**\n * Returns a boolean indicating whether the given response status\n * code represents a response that can have a body.\n */\n static isResponseWithBody(status: number): boolean {\n return !FetchResponse.STATUS_CODES_WITHOUT_BODY.includes(status)\n }\n\n static setUrl(url: string | undefined, response: Response): void {\n if (!url || url === 'about:' || !canParseUrl(url)) {\n return\n }\n\n const state = getValueBySymbol('state', response)\n\n if (state) {\n // In Undici, push the URL to the internal list of URLs.\n // This will respect the `response.url` getter logic correctly.\n state.urlList.push(new URL(url))\n } else {\n // In other libraries, redefine the `url` property directly.\n Object.defineProperty(response, 'url', {\n value: url,\n enumerable: true,\n configurable: true,\n writable: false,\n })\n }\n }\n\n /**\n * Parses the given raw HTTP headers into a Fetch API `Headers` instance.\n */\n static parseRawHeaders(rawHeaders: Array): Headers {\n const headers = new Headers()\n for (let line = 0; line < rawHeaders.length; line += 2) {\n headers.append(rawHeaders[line], rawHeaders[line + 1])\n }\n return headers\n }\n\n constructor(body?: BodyInit | null, init: FetchResponseInit = {}) {\n const status = init.status ?? 200\n const safeStatus = FetchResponse.isConfigurableStatusCode(status)\n ? status\n : 200\n const finalBody = FetchResponse.isResponseWithBody(status) ? body : null\n\n super(finalBody, {\n status: safeStatus,\n statusText: init.statusText,\n headers: init.headers,\n })\n\n if (status !== safeStatus) {\n /**\n * @note Undici keeps an internal \"Symbol(state)\" that holds\n * the actual value of response status. Update that in Node.js.\n */\n const state = getValueBySymbol('state', this)\n\n if (state) {\n state.status = status\n } else {\n Object.defineProperty(this, 'status', {\n value: status,\n enumerable: true,\n configurable: true,\n writable: false,\n })\n }\n }\n\n FetchResponse.setUrl(init.url, this)\n }\n}\n","const kRawRequest = Symbol('kRawRequest')\n\n/**\n * Returns a raw request instance associated with this request.\n *\n * @example\n * interceptor.on('request', ({ request }) => {\n * const rawRequest = getRawRequest(request)\n *\n * if (rawRequest instanceof http.ClientRequest) {\n * console.log(rawRequest.rawHeaders)\n * }\n * })\n */\nexport function getRawRequest(request: Request): unknown | undefined {\n return Reflect.get(request, kRawRequest)\n}\n\nexport function setRawRequest(request: Request, rawRequest: unknown): void {\n Reflect.set(request, kRawRequest, rawRequest)\n}\n","const encoder = new TextEncoder()\n\nexport function encodeBuffer(text: string): Uint8Array {\n return encoder.encode(text)\n}\n\nexport function decodeBuffer(buffer: ArrayBuffer, encoding?: string): string {\n const decoder = new TextDecoder(encoding)\n return decoder.decode(buffer)\n}\n\n/**\n * Create an `ArrayBuffer` from the given `Uint8Array`.\n * Takes the byte offset into account to produce the right buffer\n * in the case when the buffer is bigger than the data view.\n */\nexport function toArrayBuffer(array: Uint8Array): ArrayBuffer {\n return array.buffer.slice(\n array.byteOffset,\n array.byteOffset + array.byteLength\n )\n}\n","import { invariant } from 'outvariant'\nimport type { Emitter } from 'rettime'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\nimport { FetchResponse } from '@mswjs/interceptors'\nimport { NetworkSource } from '#core/experimental/sources/network-source'\nimport { RequestHandler } from '#core/handlers/RequestHandler'\nimport {\n HttpNetworkFrame,\n ResponseEvent,\n} from '#core/experimental/frames/http-frame'\nimport { HttpResponse } from '#core/HttpResponse'\nimport { toResponseInit } from '#core/utils/toResponseInit'\nimport { devUtils } from '#core/utils/internal/devUtils'\nimport {\n supportsReadableStreamTransfer,\n supportsServiceWorker,\n} from '../utils/supports'\nimport { getWorkerInstance } from '../utils/get-worker-instance'\nimport type { WorkerChannelEventMap } from '../utils/workerChannel'\nimport { WorkerChannel } from '../utils/workerChannel'\nimport type { FindWorker } from '../glossary'\nimport { deserializeRequest } from '../utils/deserializeRequest'\nimport { validateWorkerScope } from '../utils/validate-worker-scope'\nimport { shouldInvalidateWorker } from '../utils/should-invalidate-worker'\n\nexport interface ServiceWorkerSourceOptions {\n quiet?: boolean\n serviceWorker: {\n url: string\n options?: RegistrationOptions\n }\n findWorker?: FindWorker\n}\n\ntype WorkerChannelRequestEvent = Emitter.Event<\n WorkerChannel,\n 'REQUEST',\n WorkerChannelEventMap\n>\n\ntype WorkerChannelResponseEvent = Emitter.Event<\n WorkerChannel,\n 'RESPONSE',\n WorkerChannelEventMap\n>\n\ntype WorkerChannelClient =\n WorkerChannelEventMap['MOCKING_ENABLED']['data']['client']\n\nexport class ServiceWorkerSource extends NetworkSource {\n static #current?: ServiceWorkerSource\n\n /**\n * Create a new Service Worker source or reuse an existing one.\n * These sources act as a singleton and only get recreated if the options change.\n */\n public static async from(\n options: ServiceWorkerSourceOptions,\n ): Promise {\n if (ServiceWorkerSource.#current == null) {\n ServiceWorkerSource.#current = new ServiceWorkerSource(options)\n } else if (\n shouldInvalidateWorker(ServiceWorkerSource.#current.#options, options)\n ) {\n await ServiceWorkerSource.#current.terminate()\n ServiceWorkerSource.#current = new ServiceWorkerSource(options)\n }\n\n return ServiceWorkerSource.#current\n }\n\n #options: ServiceWorkerSourceOptions\n #frames: Map\n #channel: WorkerChannel\n #listenerController?: AbortController\n #clientPromise?: Promise\n #keepAliveInterval?: number\n #stoppedAt?: number\n\n public workerPromise: DeferredPromise<\n [ServiceWorker, ServiceWorkerRegistration]\n >\n\n constructor(options: ServiceWorkerSourceOptions) {\n super()\n\n invariant(\n supportsServiceWorker(),\n 'Failed to use Service Worker as the network source: the Service Worker API is not supported in this environment',\n )\n\n this.#options = options\n this.#frames = new Map()\n this.workerPromise = new DeferredPromise()\n this.#channel = new WorkerChannel({\n getWorker: () => this.workerPromise.then(([worker]) => worker),\n })\n }\n\n public async enable(): Promise {\n /**\n * @note The source is considered already running if the worker has been\n * resolved AND `stop()` has not been called since. `workerPromise` is NOT\n * reset on `disable()` so that the channel's `getWorker()` can keep\n * resolving to the registered SW for post-stop passthrough replies.\n */\n if (\n this.workerPromise.state === 'fulfilled' &&\n typeof this.#stoppedAt == 'undefined'\n ) {\n devUtils.warn(\n 'Found a redundant \"worker.start()\" call. Note that starting the worker while mocking is already enabled will have no effect. Consider removing this \"worker.start()\" call.',\n )\n\n return this.workerPromise.then(([, registration]) => registration)\n }\n\n this.#stoppedAt = undefined\n this.#channel.removeAllListeners()\n this.#frames.clear()\n\n this.#listenerController = new AbortController()\n const [worker, registration] = await this.#startWorker()\n\n if (worker.state !== 'activated') {\n const controller = new AbortController()\n const activationPromise = new DeferredPromise()\n activationPromise.then(() => controller.abort())\n\n worker.addEventListener(\n 'statechange',\n () => {\n if (worker.state === 'activated') {\n activationPromise.resolve()\n }\n },\n {\n signal: controller.signal,\n },\n )\n\n await activationPromise\n }\n\n this.#channel.postMessage('MOCK_ACTIVATE')\n\n const clientConfirmationPromise = new DeferredPromise()\n this.#clientPromise = clientConfirmationPromise\n\n this.#channel.once('MOCKING_ENABLED', (event) => {\n clientConfirmationPromise.resolve(event.data.client)\n })\n await clientConfirmationPromise\n\n if (!this.#options.quiet) {\n this.#printStartMessage()\n }\n\n return registration\n }\n\n public disable(): void {\n /**\n * @note Do NOT call `super.disable()` because it removes any \"frame\" listeners\n * from this network source, effectively turning it off. The Service Worker source\n * is a bit special since it might process in-flight requests that have been performed\n * after it's been disabled.\n */\n\n if (typeof this.#stoppedAt !== 'undefined') {\n devUtils.warn(\n `Found a redundant \"worker.stop()\" call. Notice that stopping the worker after it has already been stopped has no effect. Consider removing this \"worker.stop()\" call.`,\n )\n\n return\n }\n\n this.#stoppedAt = Date.now()\n\n this.#listenerController?.abort()\n this.#listenerController = undefined\n\n /**\n * @note Tell the Service Worker to drop this client from its active set\n * so it stops forwarding REQUEST events here. `stoppedAt` still guards\n * any requests the SW already forwarded before this message arrived.\n */\n this.#channel.postMessage('CLIENT_CLOSED')\n\n /**\n * @note Do NOT reset `workerPromise` here. The channel must continue to\n * resolve the currently registered SW so that any in-flight requests the\n * worker forwards after `stop()` can be answered with `PASSTHROUGH` by\n * `#handleRequest`. `#startWorker` swaps in a fresh deferred on re-enable.\n */\n\n if (!this.#options.quiet) {\n this.#printStopMessage()\n }\n }\n\n /**\n * Terminal teardown. Unregisters the Service Worker, tears down the channel,\n * and clears timers. Called when the singleton is being replaced with one\n * that has different options. The instance is not usable afterwards.\n */\n public async terminate(): Promise {\n if (this.#keepAliveInterval != null) {\n clearInterval(this.#keepAliveInterval)\n this.#keepAliveInterval = undefined\n }\n\n this.#frames.clear()\n this.#channel.terminate()\n this.#listenerController?.abort()\n this.#listenerController = undefined\n\n if (this.workerPromise.state === 'fulfilled') {\n const [, registration] = await this.workerPromise\n await registration.unregister()\n }\n\n if (ServiceWorkerSource.#current === this) {\n ServiceWorkerSource.#current = undefined\n }\n }\n\n async #startWorker() {\n if (this.#keepAliveInterval) {\n clearInterval(this.#keepAliveInterval)\n }\n\n const workerUrl = this.#options.serviceWorker.url\n\n const [worker, registration] = await getWorkerInstance(\n workerUrl,\n this.#options.serviceWorker.options,\n this.#options.findWorker || this.#defaultFindWorker,\n )\n\n if (worker == null) {\n const missingWorkerMessage = this.#options?.findWorker\n ? devUtils.formatMessage(\n `Failed to locate the Service Worker registration using a custom \"findWorker\" predicate.\n\nPlease ensure that the custom predicate properly locates the Service Worker registration at \"%s\".\nMore details: https://mswjs.io/docs/api/setup-worker/start#findworker\n `,\n workerUrl,\n )\n : devUtils.formatMessage(\n `Failed to locate the Service Worker registration.\n\nThis most likely means that the worker script URL \"%s\" cannot resolve against the actual public hostname (%s). This may happen if your application runs behind a proxy, or has a dynamic hostname.\n\nPlease consider using a custom \"serviceWorker.url\" option to point to the actual worker script location, or a custom \"findWorker\" option to resolve the Service Worker registration manually. More details: https://mswjs.io/docs/api/setup-worker/start`,\n workerUrl,\n location.host,\n )\n\n throw new Error(missingWorkerMessage)\n }\n\n if (this.workerPromise.state === 'pending') {\n this.workerPromise.resolve([worker, registration])\n } else {\n /**\n * @note Re-enable after `stop()`: the previous `workerPromise` is already\n * fulfilled and cannot be resolved again. Swap in a pre-resolved one so\n * `getWorker()` sees the new worker instance immediately.\n */\n this.workerPromise = new DeferredPromise((resolve) => {\n resolve([worker, registration])\n })\n }\n\n this.#channel.on('REQUEST', this.#handleRequest.bind(this))\n this.#channel.on('RESPONSE', this.#handleResponse.bind(this))\n\n window.addEventListener(\n 'beforeunload',\n () => {\n if (worker.state !== 'redundant') {\n this.#channel.postMessage('CLIENT_CLOSED')\n }\n\n clearInterval(this.#keepAliveInterval)\n\n window.postMessage({ type: 'msw/worker:stop' })\n },\n {\n signal: this.#listenerController?.signal,\n },\n )\n\n await this.#checkWorkerIntegrity().catch((error) => {\n devUtils.error(\n 'Error while checking the worker script integrity. Please report this on GitHub (https://github.com/mswjs/msw/issues) and include the original error below.',\n )\n console.error(error)\n })\n\n this.#keepAliveInterval = window.setInterval(() => {\n this.#channel.postMessage('KEEPALIVE_REQUEST')\n }, 5000)\n\n if (!this.#options.quiet) {\n validateWorkerScope(registration)\n }\n\n return [worker, registration] as const\n }\n\n async #handleRequest(event: WorkerChannelRequestEvent): Promise {\n if (this.#stoppedAt && event.data.interceptedAt > this.#stoppedAt) {\n return event.postMessage('PASSTHROUGH')\n }\n\n const request = deserializeRequest(event.data)\n RequestHandler.cache.set(request, request.clone())\n\n const frame = new ServiceWorkerHttpNetworkFrame({\n event,\n request,\n })\n this.#frames.set(event.data.id, frame)\n\n await this.queue(frame)\n }\n\n async #handleResponse(event: WorkerChannelResponseEvent): Promise {\n const { request, response, isMockedResponse } = event.data\n const frame = this.#frames.get(request.id)\n\n /**\n * CORS requests with `mode: \"no-cors\"` result in \"opaque\" responses.\n * That kind of responses cannot be manipulated in JavaScript due\n * to the security considerations.\n * @see https://fetch.spec.whatwg.org/#concept-filtered-response-opaque\n * @see https://github.com/mswjs/msw/issues/529\n */\n if (response.type?.includes('opaque')) {\n this.#frames.delete(request.id)\n frame?.events.removeAllListeners()\n return\n }\n\n this.#frames.delete(request.id)\n\n /**\n * @note A request frame will be missing in case of passthrough after the worker is stopped.\n * Creating a frame is costly so it's better to handle it as an edge case here.\n */\n if (frame == null) {\n return\n }\n\n const fetchRequest = deserializeRequest(request)\n const fetchResponse =\n response.status === 0\n ? Response.error()\n : new FetchResponse(\n /**\n * Responses may be streams here, but when we create a response object\n * with null-body status codes, like 204, 205, 304 Response will\n * throw when passed a non-null body, so ensure it's null here\n * for those codes\n */\n FetchResponse.isResponseWithBody(response.status)\n ? response.body\n : null,\n {\n ...response,\n /**\n * Set response URL if it's not set already.\n * @see https://github.com/mswjs/msw/issues/2030\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Response/url\n */\n url: request.url,\n },\n )\n\n try {\n frame.events.emit(\n new ResponseEvent(\n isMockedResponse ? 'response:mocked' : 'response:bypass',\n {\n requestId: frame.data.id,\n request: fetchRequest,\n response: fetchResponse,\n isMockedResponse,\n },\n ),\n )\n } finally {\n frame.events.removeAllListeners()\n }\n }\n\n #defaultFindWorker: FindWorker = (workerUrl, mockServiceWorkerUrl) => {\n return workerUrl === mockServiceWorkerUrl\n }\n\n async #checkWorkerIntegrity(): Promise {\n const integrityCheckPromise = new DeferredPromise()\n\n this.#channel.postMessage('INTEGRITY_CHECK_REQUEST')\n this.#channel.once('INTEGRITY_CHECK_RESPONSE', (event) => {\n const { checksum, packageVersion } = event.data\n\n // Compare the response from the Service Worker and the\n // global variable set during the build.\n\n // The integrity is validated based on the worker script's checksum\n // that's derived from its minified content during the build.\n // The \"SERVICE_WORKER_CHECKSUM\" global variable is injected by the build.\n if (checksum !== SERVICE_WORKER_CHECKSUM) {\n devUtils.warn(\n `The currently registered Service Worker has been generated by a different version of MSW (${packageVersion}) and may not be fully compatible with the installed version.\n\nIt's recommended you update your worker script by running this command:\n\n \\u2022 npx msw init \n\nYou can also automate this process and make the worker script update automatically upon the library installations. Read more: https://mswjs.io/docs/cli/init.`,\n )\n }\n\n integrityCheckPromise.resolve()\n })\n\n return integrityCheckPromise\n }\n\n async #printStartMessage() {\n if (this.workerPromise.state === 'rejected') {\n return\n }\n\n invariant(\n this.#clientPromise != null,\n '[ServiceWorkerSource] Failed to print a start message: client confirmation not received',\n )\n\n const client = await this.#clientPromise\n const [worker, registration] = await this.workerPromise\n\n console.groupCollapsed(\n `%c${devUtils.formatMessage('Mocking enabled.')}`,\n 'color:orangered;font-weight:bold;',\n )\n // eslint-disable-next-line no-console\n console.log(\n '%cDocumentation: %chttps://mswjs.io/docs',\n 'font-weight:bold',\n 'font-weight:normal',\n )\n // eslint-disable-next-line no-console\n console.log('Found an issue? https://github.com/mswjs/msw/issues')\n\n // eslint-disable-next-line no-console\n console.log('Worker script URL:', worker.scriptURL)\n\n // eslint-disable-next-line no-console\n console.log('Worker scope:', registration.scope)\n\n if (client) {\n // eslint-disable-next-line no-console\n console.log('Client ID: %s (%s)', client.id, client.frameType)\n }\n\n console.groupEnd()\n }\n\n #printStopMessage(): void {\n // eslint-disable-next-line no-console\n console.log(\n `%c${devUtils.formatMessage('Mocking disabled.')}`,\n 'color:orangered;font-weight:bold;',\n )\n }\n}\n\nclass ServiceWorkerHttpNetworkFrame extends HttpNetworkFrame {\n #event: WorkerChannelRequestEvent\n\n constructor(options: { event: WorkerChannelRequestEvent; request: Request }) {\n super({ request: options.request })\n this.#event = options.event\n }\n\n public passthrough(): void {\n this.#event.postMessage('PASSTHROUGH')\n }\n\n public respondWith(response?: Response): void {\n if (response) {\n this.#respondWith(response)\n }\n }\n\n public errorWith(reason?: unknown): void {\n if (reason instanceof Response) {\n return this.respondWith(reason)\n }\n\n devUtils.warn(\n `Uncaught exception in the request handler for \"%s %s\". This exception has been gracefully handled as a 500 response, however, it's strongly recommended to resolve this error, as it indicates a mistake in your code. If you wish to mock an error response, please see this guide: https://mswjs.io/docs/http/mocking-responses/error-responses`,\n this.data.request.method,\n this.data.request.url,\n )\n\n const error =\n reason instanceof Error\n ? reason\n : new Error(reason?.toString() || 'Request failure')\n\n // Treat exceptions during the request handling as 500 responses.\n // This should alert the developer that there's a problem.\n this.respondWith(\n HttpResponse.json(\n {\n name: error.name,\n message: error.message,\n stack: error.stack,\n },\n {\n status: 500,\n statusText: 'Request Handler Error',\n },\n ),\n )\n }\n\n async #respondWith(response: Response): Promise {\n let responseBody: ReadableStream | ArrayBuffer | null\n let transfer: [ReadableStream] | undefined\n const responseInit = toResponseInit(response)\n\n if (supportsReadableStreamTransfer()) {\n responseBody = response.body\n transfer = response.body == null ? undefined : [response.body]\n } else {\n responseBody =\n response.body == null ? null : await response.clone().arrayBuffer()\n }\n\n this.#event.postMessage(\n 'MOCK_RESPONSE',\n {\n ...responseInit,\n body: responseBody,\n },\n transfer,\n )\n }\n}\n","export type UntilResult =\n | [reason: RejectionReason, data: null]\n | [reason: null, data: ResolveData]\n\n/**\n * Gracefully handles a callback that returns a promise.\n *\n * @example\n * await until(() => Promise.resolve(123))\n * // [null, 123]\n *\n * await until(() => Promise.reject(new Error('Oops!')))\n * // [new Error('Oops!'), null]\n */\nexport async function until(\n callback: () => Promise,\n): Promise> {\n try {\n const data = await callback().catch((error) => {\n throw error\n })\n return [null, data]\n } catch (error: any) {\n return [error, null]\n }\n}\n","import { until } from 'until-async'\nimport { devUtils } from '#core/utils/internal/devUtils'\nimport { getAbsoluteWorkerUrl } from './getAbsoluteWorkerUrl'\nimport { getWorkerByRegistration } from './get-worker-by-registration'\nimport type { ServiceWorkerInstanceTuple, FindWorker } from '../glossary'\n\n/**\n * Returns an active Service Worker instance.\n * When not found, registers a new Service Worker.\n */\nexport const getWorkerInstance = async (\n url: string,\n options: RegistrationOptions = {},\n findWorker: FindWorker,\n): Promise => {\n // Resolve the absolute Service Worker URL.\n const absoluteWorkerUrl = getAbsoluteWorkerUrl(url)\n\n const mockRegistrations = await navigator.serviceWorker\n .getRegistrations()\n .then((registrations) =>\n registrations.filter((registration) =>\n getWorkerByRegistration(registration, absoluteWorkerUrl, findWorker),\n ),\n )\n if (!navigator.serviceWorker.controller && mockRegistrations.length > 0) {\n // Reload the page when it has associated workers, but no active controller.\n // The absence of a controller can mean either:\n // - page has no Service Worker associated with it\n // - page has been hard-reloaded and its workers won't be used until the next reload.\n // Since we've checked that there are registrations associated with this page,\n // at this point we are sure it's hard reload that falls into this clause.\n location.reload()\n }\n\n const [existingRegistration] = mockRegistrations\n\n if (existingRegistration) {\n // Schedule the worker update in the background.\n // Update ensures the existing worker is up-to-date.\n existingRegistration.update()\n\n // Return the worker reference immediately.\n return [\n getWorkerByRegistration(\n existingRegistration,\n absoluteWorkerUrl,\n findWorker,\n ),\n existingRegistration,\n ]\n }\n\n // When the Service Worker wasn't found, register it anew and return the reference.\n const [registrationError, registrationResult] = await until<\n Error,\n ServiceWorkerInstanceTuple\n >(async () => {\n const registration = await navigator.serviceWorker.register(url, options)\n return [\n // Compare existing worker registration by its worker URL,\n // to prevent irrelevant workers to resolve here (such as Codesandbox worker).\n getWorkerByRegistration(registration, absoluteWorkerUrl, findWorker),\n registration,\n ]\n })\n\n // Handle Service Worker registration errors.\n if (registrationError) {\n const isWorkerMissing = registrationError.message.includes('(404)')\n\n // Produce a custom error message when given a non-existing Service Worker url.\n // Suggest developers to check their setup.\n if (isWorkerMissing) {\n const scopeUrl = new URL(options?.scope || '/', location.href)\n\n throw new Error(\n devUtils.formatMessage(`\\\nFailed to register a Service Worker for scope ('${scopeUrl.href}') with script ('${absoluteWorkerUrl}'): Service Worker script does not exist at the given path.\n\nDid you forget to run \"npx msw init \"?\n\nLearn more about creating the Service Worker script: https://mswjs.io/docs/cli/init`),\n )\n }\n\n // Fallback error message for any other registration errors.\n throw new Error(\n devUtils.formatMessage(\n 'Failed to register the Service Worker:\\n\\n%s',\n registrationError.message,\n ),\n )\n }\n\n return registrationResult\n}\n","/**\n * Returns an absolute Service Worker URL based on the given\n * relative URL (known during the registration).\n */\nexport function getAbsoluteWorkerUrl(workerUrl: string): string {\n return new URL(workerUrl, location.href).href\n}\n","import type { FindWorker } from '../glossary'\n\n/**\n * Attempts to resolve a Service Worker instance from a given registration,\n * regardless of its state (active, installing, waiting).\n */\nexport function getWorkerByRegistration(\n registration: ServiceWorkerRegistration,\n absoluteWorkerUrl: string,\n findWorker: FindWorker,\n): ServiceWorker | null {\n const allStates = [\n registration.active,\n registration.installing,\n registration.waiting,\n ]\n\n const relevantStates = allStates.filter((state): state is ServiceWorker => {\n return state != null\n })\n\n const worker = relevantStates.find((worker) => {\n return findWorker(worker.scriptURL, absoluteWorkerUrl)\n })\n\n return worker || null\n}\n","type Values = M[keyof M & string]\n\nexport class LensList> {\n #list: Array<[string, Values]>\n #lens: Map>>\n\n constructor() {\n this.#list = []\n this.#lens = new Map()\n }\n\n get [Symbol.iterator]() {\n // Return the list's iterator so iteration is order-sensitive.\n return this.#list[Symbol.iterator].bind(this.#list)\n }\n\n public entries() {\n return this.#lens.entries()\n }\n\n /**\n * Return an order-sensitive list of values by the given key.\n */\n public get(key: K): Array {\n return (this.#lens.get(key) || []) as Array\n }\n\n /**\n * Return an order-sensitive list of all values.\n */\n public getAll(): Array> {\n return this.#list.map(([, value]) => value)\n }\n\n /**\n * Append a new value to the given key.\n */\n public append(\n key: K,\n value: ValueMap[K],\n ): void {\n this.#list.push([key, value])\n this.#openLens(key, (list) => list.push(value))\n }\n\n /**\n * Prepend a new value to the given key.\n */\n public prepend(\n key: K,\n value: ValueMap[K],\n ): void {\n this.#list.unshift([key, value])\n this.#openLens(key, (list) => list.unshift(value))\n }\n\n /**\n * Delete the value belonging to the given key.\n * Returns `true` if the value was present and removed, `false` otherwise.\n */\n public delete(\n key: K,\n value: ValueMap[K],\n ): boolean {\n if (this.size === 0) {\n return false\n }\n\n const values = this.#lens.get(key)\n if (!values) {\n return false\n }\n\n const index = values.indexOf(value)\n if (index === -1) {\n return false\n }\n\n values.splice(index, 1)\n this.#list.splice(\n this.#list.findIndex(\n (item) => item[0] === key && item[1] === value,\n ),\n 1,\n )\n return true\n }\n\n /**\n * Delete all values belogning to the given key.\n */\n public deleteAll(key: K): void {\n if (this.size === 0) {\n return\n }\n\n this.#list = this.#list.filter((item) => item[0] !== key)\n this.#lens.delete(key)\n }\n\n get size(): number {\n return this.#list.length\n }\n\n public clear(): void {\n if (this.size === 0) {\n return\n }\n\n this.#list.length = 0\n this.#lens.clear()\n }\n\n #openLens(\n key: string,\n setter: (target: Array>) => void,\n ): void {\n setter(this.#lens.get(key) || this.#lens.set(key, []).get(key))\n }\n}\n","import { LensList } from './lens-list'\n\nexport type DefaultEventMap = {\n [eventType: string]: TypedEvent\n}\n\n/**\n * Reserved event map containing special event types like '*' for catch-all listeners.\n */\nexport type ReservedEventMap = {\n '*': TypedEvent\n}\n\ntype IsReservedEvent = Type extends keyof ReservedEventMap\n ? true\n : false\n\nexport interface TypedEvent<\n DataType = void,\n ReturnType = void,\n EventType extends string = string,\n> extends Omit, 'type'> {\n type: EventType\n}\n\nconst kDefaultPrevented = Symbol('kDefaultPrevented')\nconst kPropagationStopped = Symbol('kPropagationStopped')\nconst kImmediatePropagationStopped = Symbol('kImmediatePropagationStopped')\n\nexport class TypedEvent<\n DataType = void,\n ReturnType = void,\n EventType extends string = string,\n>\n extends MessageEvent\n implements TypedEvent\n{\n /**\n * @note Keep a placeholder property with the return type\n * because the type must be set somewhere in order to be\n * correctly associated and inferred from the event.\n */\n #returnType: ReturnType;\n\n [kDefaultPrevented]: boolean;\n [kPropagationStopped]?: Emitter;\n [kImmediatePropagationStopped]?: boolean\n\n constructor(\n ...args: [DataType] extends [void]\n ? [type: EventType]\n : [type: EventType, init: { data: DataType }]\n ) {\n super(args[0], args[1])\n this[kDefaultPrevented] = false\n }\n\n get defaultPrevented(): boolean {\n return this[kDefaultPrevented]\n }\n\n public preventDefault(): void {\n super.preventDefault()\n this[kDefaultPrevented] = true\n }\n\n public stopImmediatePropagation(): void {\n /**\n * @note Despite `.stopPropagation()` and `.stopImmediatePropagation()` being defined\n * in Node.js, they do nothing. It is safe to re-define them.\n */\n super.stopImmediatePropagation()\n this[kImmediatePropagationStopped] = true\n }\n}\n\n/**\n * Brands a TypedEvent or its subclass while preserving its (narrower) type.\n */\ntype Brand<\n Event extends TypedEvent,\n EventType extends string,\n Loose extends boolean = false,\n> = Loose extends true\n ? Event extends TypedEvent\n ? /**\n * @note Omit the `ReturnType` so emit methods can accept type events\n * where infering the return type is impossible.\n */\n TypedEvent & {\n type: EventType\n }\n : never\n : Event & { type: EventType }\n\ntype InferEventMap> =\n Target extends Emitter ? WithReservedEvents : never\n\n/**\n * Extracts only user-defined events, excluding reserved event types.\n */\ntype UserEventMap = Omit<\n EventMap,\n keyof ReservedEventMap\n>\n\n/**\n * Decorates the given `EventMap` with the reserved emitter events (e.g. `*`).\n */\nexport type WithReservedEvents = EventMap &\n ReservedEventMap\n\n/**\n * Creates a union of all events in the EventMap with their literal type strings.\n */\ntype AllEvents = {\n [K in keyof EventMap & string]: Brand\n}[keyof EventMap & string]\n\nexport type TypedListenerOptions = {\n once?: boolean\n signal?: AbortSignal\n}\n\nexport interface HookListenerOptions extends TypedListenerOptions {\n persist?: boolean\n}\n\nexport type EmitterHookMap = {\n newListener: (\n type: keyof WithReservedEvents & string,\n listener: {\n [K in keyof WithReservedEvents & string]: Emitter.Listener<\n Emitter,\n K,\n WithReservedEvents\n >\n }[keyof WithReservedEvents & string],\n options: HookListenerOptions | undefined,\n ) => void\n\n removeListener: (\n type: keyof WithReservedEvents & string,\n listener: {\n [K in keyof WithReservedEvents & string]: Emitter.Listener<\n Emitter,\n K,\n WithReservedEvents\n >\n }[keyof WithReservedEvents & string],\n options: HookListenerOptions | undefined,\n ) => void\n\n beforeEmit: (event: EventMap[keyof EventMap & string]) => boolean | void\n}\n\nexport namespace Emitter {\n /**\n * Returns a union of all event types, both public and reserved, for the given emitter.\n *\n * @example\n * const emitter = new Emitter<{ greeting: TypedEvent, handshake: TypedEvent }>()\n * type AllEventTypes = Emitter.AllEventTypes\n * // \"*\" | \"greeting\" | \"handshake\"\n */\n export type AllEventTypes<\n Target extends Emitter,\n EventMap extends DefaultEventMap = InferEventMap,\n > = string extends keyof EventMap ? never : keyof EventMap & string\n\n /**\n * Returns a union of all public event types for the given emitter.\n *\n * @example\n * const emitter = new Emitter<{ greeting: TypedEvent, handshake: TypedEvent }>()\n * type EventTypes = Emitter.EventTypes\n * // \"greeting\" | \"handshake\"\n */\n export type PublicEventTypes<\n Target extends Emitter,\n EventMap extends DefaultEventMap = InferEventMap,\n UserEvents extends UserEventMap = UserEventMap,\n > = string extends keyof UserEvents ? never : keyof UserEvents & string\n\n /**\n * Returns a union of all public event type for the given emitter.\n *\n * @example\n * const emitter = new Emitter<{ greeting: GreetingEvent, handshake: HandshakeEvent }>()\n * type Events = Emitter.Events\n * // GreetingEvent | HandshakeEvent\n */\n export type Events<\n Target extends Emitter,\n EventMap extends DefaultEventMap = InferEventMap,\n > = string extends keyof UserEventMap\n ? never\n : UserEventMap[keyof UserEventMap]\n\n /**\n * Returns an appropriate `Event` type for the given event type.\n *\n * @example\n * const emitter = new Emitter<{ greeting: TypedEvent }>()\n * type GreetingEvent = Emitter.Event\n * // TypedEvent\n */\n export type Event<\n Target extends Emitter,\n EventType extends keyof EventMap & string,\n EventMap extends DefaultEventMap = InferEventMap,\n > =\n IsReservedEvent extends true\n ? AllEvents>\n : Brand\n\n /**\n * Returns an appropriate event data type for the given event type.\n *\n * @example\n * const emitter = new Emitter<{ greeting: TypedEvent<'hello'> }>()\n * type GreetingData = Emitter.EventData\n * // \"hello\"\n */\n export type EventData<\n Target extends Emitter,\n EventType extends keyof EventMap & string,\n EventMap extends DefaultEventMap = InferEventMap,\n > = EventMap[EventType] extends TypedEvent ? DataType : never\n\n /**\n * Returns the listener type for the given event type.\n *\n * @example\n * const emitter = new Emitter<{ getTotalPrice: TypedEvent }>()\n * type Listener = Emitter.ListenerType\n * // (event: TypedEvent) => number\n */\n export type Listener<\n Target extends Emitter,\n EventType extends keyof EventMap & string,\n EventMap extends DefaultEventMap = InferEventMap,\n > =\n IsReservedEvent extends true\n ? (event: Emitter.Event) => void\n : (\n event: Emitter.Event,\n ) => Emitter.ListenerReturnType extends [\n void,\n ]\n ? void\n : Emitter.ListenerReturnType\n\n /**\n * Returns the return type of the listener for the given event type.\n *\n * @example\n * const emitter = new Emitter<{ getTotalPrice: TypedEvent }>()\n * type ListenerReturnType = Emitter.ListenerReturnType\n * // number\n */\n export type ListenerReturnType<\n Target extends Emitter,\n EventType extends keyof EventMap & string,\n EventMap extends DefaultEventMap = InferEventMap,\n > =\n IsReservedEvent extends true\n ? void\n : EventMap[EventType] extends TypedEvent\n ? ReturnType\n : never\n}\n\nexport namespace EventMap {\n /**\n * Returns a union of all public event types from the given event map.\n *\n * @example\n * type MyEventMap = { greeting: TypedEvent, handshake: TypedEvent }\n * type EventTypes = EventMap.EventTypes\n * // \"greeting\" | \"handshake\"\n */\n export type EventTypes =\n Emitter.PublicEventTypes>\n\n /**\n * Returns a union of all public event type from the given event map.\n *\n * @example\n * type MyEventMap = { greeting: GreetingEvent, handshake: HandshakeEvent }\n * type Events = EventMap.Events\n * // GreetingEvent | HandshakeEvent\n */\n export type Events = Emitter.Events>\n\n /**\n * Returns an appropriate `Event` type for the given event type.\n *\n * @example\n * type MyEventMap = { greeting: TypedEvent }\n * type GreetingEvent = EventMap.Event\n * // TypedEvent\n */\n export type Event<\n Map extends DefaultEventMap,\n Type extends keyof WithReservedEvents & string,\n > = Emitter.Event, Type, WithReservedEvents>\n\n /**\n * Returns an appropriate event data type for the given event type.\n *\n * @example\n * type MyEventMap = { greeting: TypedEvent<'hello'> }\n * type GreetingData = EventMap.EventData\n * // \"hello\"\n */\n export type EventData<\n Map extends DefaultEventMap,\n Type extends keyof WithReservedEvents & string,\n > = Emitter.EventData, Type, WithReservedEvents>\n\n /**\n * Returns the listener type for the given event type.\n *\n * @example\n * type MyEventMap = { getTotalPrice: TypedEvent }>\n * type Listener = EventMap.Listener\n * // (event: TypedEvent) => number\n */\n export type Listener<\n Map extends DefaultEventMap,\n Type extends keyof WithReservedEvents & string,\n > = Emitter.Listener, Type, WithReservedEvents>\n\n /**\n * Returns the return type of the listener for the given event type.\n *\n * @example\n * type MyEventMap = { getTotalPrice: TypedEvent }\n * type ListenerReturnType = EventMap.ListenerReturnType\n * // number\n */\n export type ListenerReturnType<\n Map extends DefaultEventMap,\n Type extends keyof WithReservedEvents & string,\n > = Emitter.ListenerReturnType, Type, WithReservedEvents>\n}\n\nexport class Emitter {\n #listeners: LensList<\n Record<\n string,\n Emitter.Listener<\n typeof this,\n keyof WithReservedEvents & string,\n WithReservedEvents\n >\n >\n >\n\n #listenerOptions: WeakMap\n #listenerAbortCleanups: WeakMap void>\n #typelessListeners: WeakSet\n\n #hookListeners: LensList>\n #hookListenerOptions: WeakMap\n #hookListenerAbortCleanups: WeakMap void>\n\n public readonly hooks: {\n on>(\n type: HookType,\n callback: EmitterHookMap[HookType],\n options?: HookListenerOptions,\n ): void\n\n removeListener>(\n type: HookType,\n callback: EmitterHookMap[HookType],\n options?: HookListenerOptions,\n ): void\n }\n\n constructor() {\n this.#listeners = new LensList()\n this.#listenerOptions = new WeakMap()\n this.#listenerAbortCleanups = new WeakMap()\n this.#typelessListeners = new WeakSet()\n this.#hookListeners = new LensList()\n this.#hookListenerOptions = new WeakMap()\n this.#hookListenerAbortCleanups = new WeakMap()\n\n this.hooks = {\n on: (hook, callback, options) => {\n /**\n * @note An already-aborted signal would never fire its 'abort' event,\n * leaving the hook registered indefinitely. Skip registration entirely.\n */\n if (options?.signal?.aborted) {\n return\n }\n\n if (options?.once) {\n const original = callback as (...args: Array) => void\n const wrapper = ((...args: Array) => {\n this.#deleteHookListener(hook, wrapper)\n return original(...args)\n }) as typeof callback\n callback = wrapper\n }\n\n this.#hookListeners.append(hook, callback)\n\n if (options) {\n this.#hookListenerOptions.set(callback, options)\n }\n\n if (options?.signal) {\n const { signal } = options\n const onAbort = () => {\n this.#deleteHookListener(hook, callback)\n }\n signal.addEventListener('abort', onAbort, { once: true })\n this.#hookListenerAbortCleanups.set(callback, () => {\n signal.removeEventListener('abort', onAbort)\n })\n }\n },\n removeListener: (hook, callback) => {\n this.#deleteHookListener(hook, callback)\n },\n }\n }\n\n #deleteHookListener>(\n hook: HookType,\n callback: EmitterHookMap[HookType],\n ): void {\n this.#hookListeners.delete(hook, callback)\n const cleanup = this.#hookListenerAbortCleanups.get(callback)\n if (cleanup) {\n cleanup()\n this.#hookListenerAbortCleanups.delete(callback)\n }\n }\n\n #deleteListener<\n EventType extends keyof WithReservedEvents & string,\n >(\n type: EventType,\n listener: Emitter.Listener<\n typeof this,\n EventType,\n WithReservedEvents\n >,\n ): boolean {\n const removed = this.#listeners.delete(type, listener)\n const cleanup = this.#listenerAbortCleanups.get(listener)\n if (cleanup) {\n cleanup()\n this.#listenerAbortCleanups.delete(listener)\n }\n return removed\n }\n\n /**\n * Adds a listener for the given event type.\n */\n public on & string>(\n type: EventType,\n listener: Emitter.Listener<\n typeof this,\n EventType,\n WithReservedEvents\n >,\n options?: TypedListenerOptions,\n ): typeof this {\n this.#addListener(type, listener, options)\n return this\n }\n\n /**\n * Adds a one-time listener for the given event type.\n */\n public once & string>(\n type: EventType,\n listener: Emitter.Listener<\n typeof this,\n EventType,\n WithReservedEvents\n >,\n options?: Omit,\n ): typeof this {\n return this.on(type, listener, {\n ...(options || {}),\n once: true,\n })\n }\n\n /**\n * Prepends a listener for the given event type.\n */\n public earlyOn & string>(\n type: EventType,\n listener: Emitter.Listener<\n typeof this,\n EventType,\n WithReservedEvents\n >,\n options?: TypedListenerOptions,\n ): typeof this {\n this.#addListener(type, listener, options, 'prepend')\n return this\n }\n\n /**\n * Prepends a one-time listener for the given event type.\n */\n public earlyOnce<\n EventType extends keyof WithReservedEvents & string,\n >(\n type: EventType,\n listener: Emitter.Listener<\n typeof this,\n EventType,\n WithReservedEvents\n >,\n options?: Omit,\n ): typeof this {\n return this.earlyOn(type, listener, {\n ...(options || {}),\n once: true,\n })\n }\n\n /**\n * Emits the given typed event.\n *\n * @returns {boolean} Returns `true` if the event had any listeners, `false` otherwise.\n */\n public emit(\n event: Brand,\n ): boolean {\n if (this.#listeners.size === 0) {\n return false\n }\n\n /**\n * @note Calculate matching listeners before calling them\n * since one-time listeners will self-destruct.\n */\n const hasListeners = this.listenerCount(event.type) > 0\n\n const proxiedEvent = this.#proxyEvent(event)\n\n for (const listener of this.#matchListeners(event.type)) {\n if (\n proxiedEvent.event[kPropagationStopped] != null &&\n proxiedEvent.event[kPropagationStopped] !== this\n ) {\n proxiedEvent.revoke()\n return false\n }\n\n if (proxiedEvent.event[kImmediatePropagationStopped]) {\n break\n }\n\n this.#callListener(proxiedEvent.event, listener)\n }\n\n proxiedEvent.revoke()\n\n return hasListeners\n }\n\n /**\n * Emits the given typed event and returns a promise that resolves\n * when all the listeners for that event have settled.\n *\n * @returns {Promise>} A promise that resolves\n * with the return values of all listeners.\n */\n public async emitAsPromise(\n event: Brand,\n ): Promise<\n Array>\n > {\n if (this.#listeners.size === 0) {\n return []\n }\n\n const pendingListeners: Array<\n Promise>\n > = []\n\n const proxiedEvent = this.#proxyEvent(event)\n\n for (const listener of this.#matchListeners(event.type)) {\n if (\n proxiedEvent.event[kPropagationStopped] != null &&\n proxiedEvent.event[kPropagationStopped] !== this\n ) {\n proxiedEvent.revoke()\n return []\n }\n\n if (proxiedEvent.event[kImmediatePropagationStopped]) {\n break\n }\n\n const listenerPromise = Promise.resolve(\n this.#callListener(proxiedEvent.event, listener),\n )\n\n const returnValue = await listenerPromise\n\n if (!this.#isTypelessListener(listener)) {\n pendingListeners.push(returnValue)\n }\n }\n\n proxiedEvent.revoke()\n\n return Promise.allSettled(pendingListeners).then((results) => {\n return results.map((result) =>\n result.status === 'fulfilled' ? result.value : result.reason,\n )\n })\n }\n\n /**\n * Emits the given event and returns a generator that yields\n * the result of each listener in the order of their registration.\n * This way, you stop exhausting the listeners once you get the expected value.\n */\n public *emitAsGenerator(\n event: Brand,\n ): Generator> {\n if (this.#listeners.size === 0) {\n return\n }\n\n const proxiedEvent = this.#proxyEvent(event)\n\n for (const listener of this.#matchListeners(event.type)) {\n if (\n proxiedEvent.event[kPropagationStopped] != null &&\n proxiedEvent.event[kPropagationStopped] !== this\n ) {\n proxiedEvent.revoke()\n return\n }\n\n if (proxiedEvent.event[kImmediatePropagationStopped]) {\n break\n }\n\n const returnValue = this.#callListener(proxiedEvent.event, listener)\n\n if (!this.#isTypelessListener(listener)) {\n yield returnValue\n }\n }\n\n proxiedEvent.revoke()\n }\n\n /**\n * Removes a listener for the given event type.\n */\n public removeListener<\n EventType extends keyof WithReservedEvents & string,\n >(\n type: EventType,\n listener: Emitter.Listener<\n typeof this,\n EventType,\n WithReservedEvents\n >,\n ): void {\n const options = this.#listenerOptions.get(listener)\n\n if (!this.#deleteListener(type, listener)) {\n return\n }\n\n /**\n * @note Snapshot the hook list before iterating so a hook that removes\n * another `removeListener` hook can't shift the live array mid-iteration.\n */\n for (const hook of this.#hookListeners.get('removeListener').slice()) {\n hook(\n type,\n listener as Parameters['removeListener']>[1],\n options,\n )\n }\n }\n\n /**\n * Removes all listeners for the given event type.\n * If no event type is provided, removes all existing listeners.\n */\n public removeAllListeners<\n EventType extends keyof WithReservedEvents & string,\n >(type?: EventType): void {\n if (type == null) {\n for (const [listenerType, listeners] of this.#listeners.entries()) {\n while (listeners.length > 0) {\n this.removeListener(\n listenerType as keyof WithReservedEvents & string,\n listeners[0],\n )\n }\n }\n\n for (const [hookType, hookListener] of [...this.#hookListeners]) {\n if (!this.#hookListenerOptions.get(hookListener)?.persist) {\n this.#deleteHookListener(\n hookType as keyof EmitterHookMap,\n hookListener as EmitterHookMap[keyof EmitterHookMap],\n )\n }\n }\n\n return\n }\n\n const listeners = this.listeners(type)\n\n while (listeners.length > 0) {\n this.removeListener(type, listeners[0])\n }\n }\n\n /**\n * Returns the list of listeners for the given event type.\n * If no even type is provided, returns all listeners.\n */\n public listeners<\n EventType extends keyof WithReservedEvents & string,\n >(\n type?: EventType,\n ): Array<\n Emitter.Listener>\n > {\n if (type == null) {\n return this.#listeners.getAll()\n }\n\n return this.#listeners.get(type)\n }\n\n /**\n * Returns the number of listeners for the given event type.\n * If no even type is provided, returns the total number of listeners.\n */\n public listenerCount<\n EventType extends keyof WithReservedEvents & string,\n >(type?: EventType): number {\n if (type == null) {\n return this.#listeners.size\n }\n\n return this.listeners(type).length\n }\n\n #addListener & string>(\n type: EventType,\n listener: Emitter.Listener<\n typeof this,\n EventType,\n WithReservedEvents\n >,\n options: TypedListenerOptions | undefined,\n insertMode: 'append' | 'prepend' = 'append',\n ): void {\n /**\n * @note An already-aborted signal would never fire its 'abort' event,\n * leaving the listener registered indefinitely. Skip registration entirely.\n */\n if (options?.signal?.aborted) {\n return\n }\n\n for (const hook of this.#hookListeners.get('newListener').slice()) {\n hook(\n type,\n listener as Parameters['newListener']>[1],\n options,\n )\n }\n\n if (type === '*') {\n this.#typelessListeners.add(listener)\n }\n\n if (insertMode === 'prepend') {\n this.#listeners.prepend(type, listener)\n } else {\n this.#listeners.append(type, listener)\n }\n\n if (options) {\n this.#listenerOptions.set(listener, options)\n\n if (options.signal) {\n const { signal } = options\n const onAbort = () => {\n this.removeListener(type, listener)\n }\n signal.addEventListener('abort', onAbort, { once: true })\n this.#listenerAbortCleanups.set(listener, () => {\n signal.removeEventListener('abort', onAbort)\n })\n }\n }\n }\n\n #proxyEvent(\n event: Event,\n ): { event: Event; revoke: () => void } {\n const { stopPropagation } = event\n\n event.stopPropagation = () => {\n event[kPropagationStopped] = this\n stopPropagation.call(event)\n }\n\n return {\n event,\n revoke() {\n event.stopPropagation = stopPropagation\n },\n }\n }\n\n #callListener(event: Event, listener: (event: any) => any) {\n for (const hook of this.#hookListeners.get('beforeEmit').slice()) {\n if (hook(event as EventMap[keyof EventMap & string]) === false) {\n return\n }\n }\n\n const returnValue = listener.call(this, event)\n\n const options = this.#listenerOptions.get(listener)\n\n if (options?.once) {\n const type = this.#isTypelessListener(listener) ? '*' : event.type\n\n if (this.#deleteListener(type, listener)) {\n for (const hook of this.#hookListeners.get('removeListener').slice()) {\n hook(type, listener, options)\n }\n }\n }\n\n return returnValue\n }\n\n /**\n * Return a list of all event listeners relevant for the given event type.\n * This includes the explicit event listeners and also typeless event listeners.\n *\n * @note Snapshot the matching listeners before yielding. Listeners can add or\n * remove other listeners during emission (e.g. `earlyOn` unshifts `#list`),\n * which would otherwise shift the live iterator and re-yield prior entries.\n */\n *#matchListeners(type: EventType) {\n const snapshot: Array<\n Emitter.Listener<\n typeof this,\n keyof WithReservedEvents & string,\n WithReservedEvents\n >\n > = []\n for (const [key, listener] of this.#listeners) {\n if (key === '*' || key === type) {\n snapshot.push(listener)\n }\n }\n yield* snapshot\n }\n\n #isTypelessListener(listener: any): boolean {\n return this.#typelessListeners.has(listener)\n }\n}\n","import { invariant } from 'outvariant'\nimport { Emitter, TypedEvent } from 'rettime'\nimport { isObject } from '#core/utils/internal/isObject'\nimport type { StringifiedResponse } from '../glossary'\nimport { supportsServiceWorker } from '../utils/supports'\n\nexport type WorkerChannelEventMap = {\n REQUEST: WorkerEvent\n RESPONSE: WorkerEvent\n MOCKING_ENABLED: WorkerEvent<{\n client: {\n id: string\n frameType: string\n }\n }>\n INTEGRITY_CHECK_RESPONSE: WorkerEvent<{\n packageVersion: string\n checksum: string\n }>\n KEEPALIVE_RESPONSE: TypedEvent\n}\n\n/**\n * Request representation received from the worker message event.\n */\nexport interface IncomingWorkerRequest\n extends Omit<\n Request,\n | 'text'\n | 'body'\n | 'json'\n | 'blob'\n | 'arrayBuffer'\n | 'formData'\n | 'clone'\n | 'signal'\n | 'isHistoryNavigation'\n | 'isReloadNavigation'\n > {\n /**\n * Unique ID of the request generated once the request is\n * intercepted by the \"fetch\" event in the Service Worker.\n */\n id: string\n interceptedAt: number\n body?: ArrayBuffer | null\n}\n\ntype IncomingWorkerResponse = {\n isMockedResponse: boolean\n request: IncomingWorkerRequest\n response: Pick<\n Response,\n 'type' | 'ok' | 'status' | 'statusText' | 'body' | 'headers' | 'redirected'\n >\n}\n\nexport type WorkerEventResponse = {\n MOCK_RESPONSE: [\n data: StringifiedResponse,\n transfer?: [ReadableStream],\n ]\n PASSTHROUGH: []\n}\n\nconst SUPPORTS_SERVICE_WORKER = supportsServiceWorker()\n\nexport class WorkerEvent<\n DataType,\n ReturnType = any,\n EventType extends string = string,\n> extends TypedEvent {\n #workerEvent: MessageEvent\n\n constructor(workerEvent: MessageEvent) {\n const type = workerEvent.data.type as EventType\n const data = workerEvent.data.payload as DataType\n\n /**\n * @note This is the only place we're mapping { type, payload }\n * message structure of the worker. The client references the\n * payload via `event.data`.\n */\n super(\n // @ts-expect-error Troublesome `TypedEvent` extension.\n type,\n { data },\n )\n this.#workerEvent = workerEvent\n }\n\n get ports() {\n return this.#workerEvent.ports\n }\n\n /**\n * Reply directly to this event using its `MessagePort`.\n */\n public postMessage(\n type: Type,\n ...rest: WorkerEventResponse[Type]\n ): void {\n this.#workerEvent.ports[0].postMessage(\n { type, data: rest[0] },\n { transfer: rest[1] },\n )\n }\n}\n\n/**\n * Map of the events that can be sent to the Service Worker\n * from any execution context.\n */\ntype OutgoingWorkerEvents =\n | 'MOCK_ACTIVATE'\n | 'INTEGRITY_CHECK_REQUEST'\n | 'KEEPALIVE_REQUEST'\n | 'CLIENT_CLOSED'\n\nexport interface WorkerChannelOptions {\n getWorker: () => Promise\n}\n\nexport class WorkerChannel extends Emitter {\n #getWorker: WorkerChannelOptions['getWorker']\n #controller: AbortController\n\n constructor(options: WorkerChannelOptions) {\n super()\n\n invariant(\n SUPPORTS_SERVICE_WORKER,\n 'Failed to open a WorkerChannel: Service Worker is not supported in this environment.',\n )\n\n this.#getWorker = options.getWorker\n this.#controller = new AbortController()\n\n navigator.serviceWorker.addEventListener(\n 'message',\n async (event) => {\n const worker = await this.#getWorker()\n\n if (event.source != null && event.source !== worker) {\n return\n }\n\n if (event.data && isObject(event.data) && 'type' in event.data) {\n this.emit(new WorkerEvent(event))\n }\n },\n {\n signal: this.#controller.signal,\n },\n )\n }\n\n /**\n * Send data to the Service Worker controlling this client.\n * This triggers the `message` event listener on ServiceWorkerGlobalScope.\n */\n public postMessage(type: OutgoingWorkerEvents): void {\n invariant(\n SUPPORTS_SERVICE_WORKER,\n 'Failed to post message on a WorkerChannel: the Service Worker API is unavailable in this environment. This is likely an issue with MSW. Please report it on GitHub: https://github.com/mswjs/msw/issues',\n )\n\n this.#getWorker().then((worker) => {\n worker.postMessage(type)\n })\n }\n\n /**\n * Terminal teardown. Removes the `navigator.serviceWorker` message listener\n * and all emitter subscriptions. The channel is not usable afterwards.\n */\n public terminate(): void {\n this.#controller.abort()\n this.removeAllListeners()\n }\n}\n","import type { IncomingWorkerRequest } from './workerChannel'\n\ntype Input = Pick\n\n/**\n * Ensures that an empty GET request body is always represented as `undefined`.\n */\nexport function pruneGetRequestBody(\n request: Input,\n): IncomingWorkerRequest['body'] | undefined {\n // Force HEAD/GET request body to always be empty.\n // The worker reads any request's body as ArrayBuffer,\n // and you cannot re-construct a GET/HEAD Request\n // with an ArrayBuffer, even if empty. Also note that\n // \"request.body\" is always undefined in the worker.\n if (['HEAD', 'GET'].includes(request.method)) {\n return undefined\n }\n\n return request.body\n}\n","import { pruneGetRequestBody } from './pruneGetRequestBody'\nimport type { IncomingWorkerRequest } from './workerChannel'\n\n/**\n * Converts a given request received from the Service Worker\n * into a Fetch `Request` instance.\n */\nexport function deserializeRequest(\n serializedRequest: IncomingWorkerRequest,\n): Request {\n return new Request(serializedRequest.url, {\n ...serializedRequest,\n body: pruneGetRequestBody(serializedRequest),\n })\n}\n","import { devUtils } from '#core/utils/internal/devUtils'\n\n/**\n * Print a warning if the given Service Worker registration has a scope\n * outside of the current page's location. That is to help with debugging\n * issues caused by the incorrectly registered Service Worker.\n */\nexport function validateWorkerScope(\n registration: ServiceWorkerRegistration,\n): void {\n if (!location.href.startsWith(registration.scope)) {\n devUtils.warn(\n `Cannot intercept requests on this page because it's outside of the worker's scope (\"${registration.scope}\"). If you wish to mock API requests on this page, you must resolve this scope issue.\n\n- (Recommended) Register the worker at the root level (\"/\") of your application.\n- Set the \"Service-Worker-Allowed\" response header to allow out-of-scope workers.`,\n )\n }\n}\n","import { type ServiceWorkerSourceOptions } from '../sources/service-worker-source'\n\nexport function shouldInvalidateWorker(\n prevOptions: ServiceWorkerSourceOptions,\n nextOptions: ServiceWorkerSourceOptions,\n): boolean {\n return (\n prevOptions.findWorker !== nextOptions.findWorker ||\n prevOptions.serviceWorker.url !== nextOptions.serviceWorker.url ||\n JSON.stringify(prevOptions.serviceWorker.options) !==\n JSON.stringify(nextOptions.serviceWorker.options)\n )\n}\n","export type AsyncTuple<\n ErrorType extends any = Error,\n DataType extends any = unknown,\n> =\n | {\n error: ErrorType\n data: null\n }\n | { error: null; data: DataType }\n\n/**\n * Gracefully handles a given Promise factory.\n * @example\n * const { error, data } = await until(() => asyncAction())\n */\nexport const until = async <\n ErrorType extends any = Error,\n DataType extends any = unknown,\n>(\n promise: () => Promise,\n): Promise> => {\n try {\n const data = await promise().catch((error) => {\n throw error\n })\n return { error: null, data }\n } catch (error) {\n return { error, data: null }\n }\n}\n","/**\n * Determines if a given value is an instance of object.\n */\nexport function isObject(value: any, loose = false): value is T {\n return loose\n ? Object.prototype.toString.call(value).startsWith('[object ')\n : Object.prototype.toString.call(value) === '[object Object]'\n}\n","/**\n * A function that validates if property access is possible on an object\n * without throwing. It returns `true` if the property access is possible\n * and `false` otherwise.\n *\n * Environments like miniflare will throw on property access on certain objects\n * like Request and Response, for unimplemented properties.\n */\nexport function isPropertyAccessible>(\n obj: Obj,\n key: keyof Obj\n) {\n try {\n obj[key]\n return true\n } catch {\n return false\n }\n}\n","import { isObject } from './isObject'\nimport { isPropertyAccessible } from './isPropertyAccessible'\n\n/**\n * Creates a generic 500 Unhandled Exception response.\n */\nexport function createServerErrorResponse(body: unknown): Response {\n return new Response(\n JSON.stringify(\n body instanceof Error\n ? {\n name: body.name,\n message: body.message,\n stack: body.stack,\n }\n : body\n ),\n {\n status: 500,\n statusText: 'Unhandled Exception',\n headers: {\n 'Content-Type': 'application/json',\n },\n }\n )\n}\n\nexport type ResponseError = Response & { type: 'error' }\n\n/**\n * Check if the given response is a `Response.error()`.\n *\n * @note Some environments, like Miniflare (Cloudflare) do not\n * implement the \"Response.type\" property and throw on its access.\n * Safely check if we can access \"type\" on \"Response\" before continuing.\n * @see https://github.com/mswjs/msw/issues/1834\n */\nexport function isResponseError(response: unknown): response is ResponseError {\n return (\n response != null &&\n response instanceof Response &&\n isPropertyAccessible(response, 'type') &&\n response.type === 'error'\n )\n}\n\n/**\n * Check if the given value is a `Response` or a Response-like object.\n * This is different from `value instanceof Response` because it supports\n * custom `Response` constructors, like the one when using Undici directly.\n */\nexport function isResponseLike(value: unknown): value is Response {\n return (\n isObject>(value, true) &&\n isPropertyAccessible(value, 'status') &&\n isPropertyAccessible(value, 'statusText') &&\n isPropertyAccessible(value, 'bodyUsed')\n )\n}\n","export function isNodeLikeError(\n error: unknown\n): error is NodeJS.ErrnoException {\n if (error == null) {\n return false\n }\n\n if (!(error instanceof Error)) {\n return false\n }\n\n return 'code' in error && 'errno' in error\n}\n","import type { Emitter } from 'strict-event-emitter'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\nimport { until } from '@open-draft/until'\nimport type { HttpRequestEventMap } from '../glossary'\nimport { emitAsync } from './emitAsync'\nimport { RequestController } from '../RequestController'\nimport {\n createServerErrorResponse,\n isResponseError,\n isResponseLike,\n} from './responseUtils'\nimport { InterceptorError } from '../InterceptorError'\nimport { isNodeLikeError } from './isNodeLikeError'\nimport { isObject } from './isObject'\n\ninterface HandleRequestOptions {\n requestId: string\n request: Request\n emitter: Emitter\n controller: RequestController\n}\n\nexport async function handleRequest(\n options: HandleRequestOptions\n): Promise {\n const handleResponse = async (\n response: Response | Error | Record\n ) => {\n if (response instanceof Error) {\n await options.controller.errorWith(response)\n return true\n }\n\n // Handle \"Response.error()\" instances.\n if (isResponseError(response)) {\n await options.controller.respondWith(response)\n return true\n }\n\n /**\n * Handle normal responses or response-like objects.\n * @note This must come before the arbitrary object check\n * since Response instances are, in fact, objects.\n */\n if (isResponseLike(response)) {\n await options.controller.respondWith(response)\n return true\n }\n\n // Handle arbitrary objects provided to `.errorWith(reason)`.\n if (isObject(response)) {\n await options.controller.errorWith(response)\n return true\n }\n\n return false\n }\n\n const handleResponseError = async (error: unknown): Promise => {\n // Forward the special interceptor error instances\n // to the developer. These must not be handled in any way.\n if (error instanceof InterceptorError) {\n throw result.error\n }\n\n // Support mocking Node.js-like errors.\n if (isNodeLikeError(error)) {\n await options.controller.errorWith(error)\n return true\n }\n\n // Handle thrown responses.\n if (error instanceof Response) {\n return await handleResponse(error)\n }\n\n return false\n }\n\n // Add the last \"request\" listener to check if the request\n // has been handled in any way. If it hasn't, resolve the\n // response promise with undefined.\n // options.emitter.once('request', async ({ requestId: pendingRequestId }) => {\n // if (\n // pendingRequestId === options.requestId &&\n // options.controller.readyState === RequestController.PENDING\n // ) {\n // await options.controller.passthrough()\n // }\n // })\n\n const requestAbortPromise = new DeferredPromise()\n\n /**\n * @note `signal` is not always defined in React Native.\n */\n if (options.request.signal) {\n if (options.request.signal.aborted) {\n await options.controller.errorWith(options.request.signal.reason)\n return\n }\n\n options.request.signal.addEventListener(\n 'abort',\n () => {\n requestAbortPromise.reject(options.request.signal.reason)\n },\n { once: true }\n )\n }\n\n const result = await until(async () => {\n // Emit the \"request\" event and wait until all the listeners\n // for that event are finished (e.g. async listeners awaited).\n // By the end of this promise, the developer cannot affect the\n // request anymore.\n const requestListenersPromise = emitAsync(options.emitter, 'request', {\n requestId: options.requestId,\n request: options.request,\n controller: options.controller,\n })\n\n await Promise.race([\n // Short-circuit the request handling promise if the request gets aborted.\n requestAbortPromise,\n requestListenersPromise,\n options.controller.handled,\n ])\n })\n\n // Handle the request being aborted while waiting for the request listeners.\n if (requestAbortPromise.state === 'rejected') {\n await options.controller.errorWith(requestAbortPromise.rejectionReason)\n return\n }\n\n if (result.error) {\n // Handle the error during the request listener execution.\n // These can be thrown responses or request errors.\n if (await handleResponseError(result.error)) {\n return\n }\n\n // If the developer has added \"unhandledException\" listeners,\n // allow them to handle the error. They can translate it to a\n // mocked response, network error, or forward it as-is.\n if (options.emitter.listenerCount('unhandledException') > 0) {\n // Create a new request controller just for the unhandled exception case.\n // This is needed because the original controller might have been already\n // interacted with (e.g. \"respondWith\" or \"errorWith\" called on it).\n const unhandledExceptionController = new RequestController(\n options.request,\n {\n /**\n * @note Intentionally empty passthrough handle.\n * This controller is created within another controller and we only need\n * to know if `unhandledException` listeners handled the request.\n */\n passthrough() {},\n async respondWith(response) {\n await handleResponse(response)\n },\n async errorWith(reason) {\n /**\n * @note Handle the result of the unhandled controller\n * in the same way as the original request controller.\n * The exception here is that thrown errors within the\n * \"unhandledException\" event do NOT result in another\n * emit of the same event. They are forwarded as-is.\n */\n await options.controller.errorWith(reason)\n },\n }\n )\n\n await emitAsync(options.emitter, 'unhandledException', {\n error: result.error,\n request: options.request,\n requestId: options.requestId,\n controller: unhandledExceptionController,\n })\n\n // If all the \"unhandledException\" listeners have finished\n // but have not handled the request in any way, passthrough.\n if (\n unhandledExceptionController.readyState !== RequestController.PENDING\n ) {\n return\n }\n }\n\n // Otherwise, coerce unhandled exceptions to a 500 Internal Server Error response.\n await options.controller.respondWith(\n createServerErrorResponse(result.error)\n )\n return\n }\n\n // If the request hasn't been handled by this point, passthrough.\n if (options.controller.readyState === RequestController.PENDING) {\n return await options.controller.passthrough()\n }\n\n return options.controller.handled\n}\n","export function createNetworkError(cause?: unknown) {\n return Object.assign(new TypeError('Failed to fetch'), {\n cause,\n })\n}\n","import { createNetworkError } from './createNetworkError'\n\nconst REQUEST_BODY_HEADERS = [\n 'content-encoding',\n 'content-language',\n 'content-location',\n 'content-type',\n 'content-length',\n]\n\nconst kRedirectCount = Symbol('kRedirectCount')\n\n/**\n * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/index.js#L1210\n */\nexport async function followFetchRedirect(\n request: Request,\n response: Response\n): Promise {\n if (response.status !== 303 && request.body != null) {\n return Promise.reject(createNetworkError())\n }\n\n const requestUrl = new URL(request.url)\n\n let locationUrl: URL\n try {\n // If the location is a relative URL, use the request URL as the base URL.\n locationUrl = new URL(response.headers.get('location')!, request.url) \n } catch (error) {\n return Promise.reject(createNetworkError(error))\n }\n\n if (\n !(locationUrl.protocol === 'http:' || locationUrl.protocol === 'https:')\n ) {\n return Promise.reject(\n createNetworkError('URL scheme must be a HTTP(S) scheme')\n )\n }\n\n if (Reflect.get(request, kRedirectCount) > 20) {\n return Promise.reject(createNetworkError('redirect count exceeded'))\n }\n\n Object.defineProperty(request, kRedirectCount, {\n value: (Reflect.get(request, kRedirectCount) || 0) + 1,\n })\n\n if (\n request.mode === 'cors' &&\n (locationUrl.username || locationUrl.password) &&\n !sameOrigin(requestUrl, locationUrl)\n ) {\n return Promise.reject(\n createNetworkError('cross origin not allowed for request mode \"cors\"')\n )\n }\n\n const requestInit: RequestInit = {}\n\n if (\n ([301, 302].includes(response.status) && request.method === 'POST') ||\n (response.status === 303 && !['HEAD', 'GET'].includes(request.method))\n ) {\n requestInit.method = 'GET'\n requestInit.body = null\n\n REQUEST_BODY_HEADERS.forEach((headerName) => {\n request.headers.delete(headerName)\n })\n }\n\n if (!sameOrigin(requestUrl, locationUrl)) {\n request.headers.delete('authorization')\n request.headers.delete('proxy-authorization')\n request.headers.delete('cookie')\n request.headers.delete('host')\n }\n\n /**\n * @note Undici \"safely\" extracts the request body.\n * I suspect we cannot dispatch this request again\n * since its body has been read and the stream is locked.\n */\n\n requestInit.headers = request.headers\n const finalResponse = await fetch(new Request(locationUrl, requestInit))\n Object.defineProperty(finalResponse, 'redirected', {\n value: true,\n configurable: true,\n })\n\n return finalResponse\n}\n\n/**\n * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/util.js#L761\n */\nfunction sameOrigin(left: URL, right: URL): boolean {\n if (left.origin === right.origin && left.origin === 'null') {\n return true\n }\n\n if (\n left.protocol === right.protocol &&\n left.hostname === right.hostname &&\n left.port === right.port\n ) {\n return true\n }\n\n return false\n}\n","export class BrotliDecompressionStream extends TransformStream {\n constructor() {\n console.warn(\n '[Interceptors]: Brotli decompression of response streams is not supported in the browser'\n )\n\n super({\n transform(chunk, controller) {\n // Keep the stream as passthrough, it does nothing.\n controller.enqueue(chunk)\n },\n })\n }\n}\n","// Import from an internal alias that resolves to different modules\n// depending on the environment. This way, we can keep the fetch interceptor\n// intact while using different strategies for Brotli decompression.\nimport { BrotliDecompressionStream } from 'internal:brotli-decompress'\n\nclass PipelineStream extends TransformStream {\n constructor(\n transformStreams: Array,\n ...strategies: Array\n ) {\n super({}, ...strategies)\n\n const readable = [super.readable as any, ...transformStreams].reduce(\n (readable, transform) => readable.pipeThrough(transform)\n )\n\n Object.defineProperty(this, 'readable', {\n get() {\n return readable\n },\n })\n }\n}\n\nexport function parseContentEncoding(contentEncoding: string): Array {\n return contentEncoding\n .toLowerCase()\n .split(',')\n .map((coding) => coding.trim())\n}\n\nfunction createDecompressionStream(\n contentEncoding: string\n): TransformStream | null {\n if (contentEncoding === '') {\n return null\n }\n\n const codings = parseContentEncoding(contentEncoding)\n\n if (codings.length === 0) {\n return null\n }\n\n const transformers = codings.reduceRight>(\n (transformers, coding) => {\n if (coding === 'gzip' || coding === 'x-gzip') {\n return transformers.concat(new DecompressionStream('gzip'))\n } else if (coding === 'deflate') {\n return transformers.concat(new DecompressionStream('deflate'))\n } else if (coding === 'br') {\n return transformers.concat(new BrotliDecompressionStream())\n } else {\n transformers.length = 0\n }\n\n return transformers\n },\n []\n )\n\n return new PipelineStream(transformers)\n}\n\nexport function decompressResponse(\n response: Response\n): ReadableStream | null {\n if (response.body === null) {\n return null\n }\n\n const decompressionStream = createDecompressionStream(\n response.headers.get('content-encoding') || ''\n )\n\n if (!decompressionStream) {\n return null\n }\n\n // Use `pipeTo` and return the decompression stream's readable\n // instead of `pipeThrough` because that will lock the original\n // response stream, making it unusable as the input to Response.\n response.body.pipeTo(decompressionStream.writable)\n return decompressionStream.readable\n}\n","import { invariant } from 'outvariant'\nimport { until } from '@open-draft/until'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\nimport { HttpRequestEventMap, IS_PATCHED_MODULE } from '../../glossary'\nimport { Interceptor } from '../../Interceptor'\nimport { RequestController } from '../../RequestController'\nimport { emitAsync } from '../../utils/emitAsync'\nimport { handleRequest } from '../../utils/handleRequest'\nimport { canParseUrl } from '../../utils/canParseUrl'\nimport { createRequestId } from '../../createRequestId'\nimport { createNetworkError } from './utils/createNetworkError'\nimport { followFetchRedirect } from './utils/followRedirect'\nimport { decompressResponse } from './utils/decompression'\nimport { hasConfigurableGlobal } from '../../utils/hasConfigurableGlobal'\nimport { FetchResponse } from '../../utils/fetchUtils'\nimport { setRawRequest } from '../../getRawRequest'\nimport { isResponseError } from '../../utils/responseUtils'\n\nexport class FetchInterceptor extends Interceptor {\n static symbol = Symbol('fetch')\n\n constructor() {\n super(FetchInterceptor.symbol)\n }\n\n protected checkEnvironment() {\n return hasConfigurableGlobal('fetch')\n }\n\n protected async setup() {\n const pureFetch = globalThis.fetch\n\n invariant(\n !(pureFetch as any)[IS_PATCHED_MODULE],\n 'Failed to patch the \"fetch\" module: already patched.'\n )\n\n globalThis.fetch = async (input, init) => {\n const requestId = createRequestId()\n\n /**\n * @note Resolve potentially relative request URL\n * against the present `location`. This is mainly\n * for native `fetch` in JSDOM.\n * @see https://github.com/mswjs/msw/issues/1625\n */\n const resolvedInput =\n typeof input === 'string' &&\n typeof location !== 'undefined' &&\n !canParseUrl(input)\n ? new URL(input, location.href)\n : input\n\n const request = new Request(resolvedInput, init)\n\n /**\n * @note Set the raw request only if a Request instance was provided to fetch.\n */\n if (input instanceof Request) {\n setRawRequest(request, input)\n }\n\n const responsePromise = new DeferredPromise()\n\n const controller = new RequestController(request, {\n passthrough: async () => {\n this.logger.info('request has not been handled, passthrough...')\n\n /**\n * @note Clone the request instance right before performing it.\n * This preserves any modifications made to the intercepted request\n * in the \"request\" listener. This also allows the user to read the\n * request body in the \"response\" listener (otherwise \"unusable\").\n */\n const requestCloneForResponseEvent = request.clone()\n\n // Perform the intercepted request as-is.\n const { error: responseError, data: originalResponse } = await until(\n () => pureFetch(request)\n )\n\n if (responseError) {\n return responsePromise.reject(responseError)\n }\n\n this.logger.info('original fetch performed', originalResponse)\n\n if (this.emitter.listenerCount('response') > 0) {\n this.logger.info('emitting the \"response\" event...')\n\n const responseClone = originalResponse.clone()\n await emitAsync(this.emitter, 'response', {\n response: responseClone,\n isMockedResponse: false,\n request: requestCloneForResponseEvent,\n requestId,\n })\n }\n\n // Resolve the response promise with the original response\n // since the `fetch()` return this internal promise.\n responsePromise.resolve(originalResponse)\n },\n respondWith: async (rawResponse) => {\n // Handle mocked `Response.error()` (i.e. request errors).\n if (isResponseError(rawResponse)) {\n this.logger.info('request has errored!', { response: rawResponse })\n responsePromise.reject(createNetworkError(rawResponse))\n return\n }\n\n this.logger.info('received mocked response!', {\n rawResponse,\n })\n\n // Decompress the mocked response body, if applicable.\n const decompressedStream = decompressResponse(rawResponse)\n const response =\n decompressedStream === null\n ? rawResponse\n : new FetchResponse(decompressedStream, rawResponse)\n\n FetchResponse.setUrl(request.url, response)\n\n /**\n * Undici's handling of following redirect responses.\n * Treat the \"manual\" redirect mode as a regular mocked response.\n * This way, the client can manually follow the redirect it receives.\n * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/index.js#L1173\n */\n if (FetchResponse.isRedirectResponse(response.status)) {\n // Reject the request promise if its `redirect` is set to `error`\n // and it receives a mocked redirect response.\n if (request.redirect === 'error') {\n responsePromise.reject(createNetworkError('unexpected redirect'))\n return\n }\n\n if (request.redirect === 'follow') {\n followFetchRedirect(request, response).then(\n (response) => {\n responsePromise.resolve(response)\n },\n (reason) => {\n responsePromise.reject(reason)\n }\n )\n return\n }\n }\n\n if (this.emitter.listenerCount('response') > 0) {\n this.logger.info('emitting the \"response\" event...')\n\n // Await the response listeners to finish before resolving\n // the response promise. This ensures all your logic finishes\n // before the interceptor resolves the pending response.\n await emitAsync(this.emitter, 'response', {\n // Clone the mocked response for the \"response\" event listener.\n // This way, the listener can read the response and not lock its body\n // for the actual fetch consumer.\n response: response.clone(),\n isMockedResponse: true,\n request,\n requestId,\n })\n }\n\n responsePromise.resolve(response)\n },\n errorWith: (reason) => {\n this.logger.info('request has been aborted!', { reason })\n responsePromise.reject(reason)\n },\n })\n\n this.logger.info('[%s] %s', request.method, request.url)\n this.logger.info('awaiting for the mocked response...')\n\n this.logger.info(\n 'emitting the \"request\" event for %s listener(s)...',\n this.emitter.listenerCount('request')\n )\n\n await handleRequest({\n request,\n requestId,\n emitter: this.emitter,\n controller,\n })\n\n return responsePromise\n }\n\n Object.defineProperty(globalThis.fetch, IS_PATCHED_MODULE, {\n enumerable: true,\n configurable: true,\n value: true,\n })\n\n this.subscriptions.push(() => {\n Object.defineProperty(globalThis.fetch, IS_PATCHED_MODULE, {\n value: undefined,\n })\n\n globalThis.fetch = pureFetch\n\n this.logger.info(\n 'restored native \"globalThis.fetch\"!',\n globalThis.fetch.name\n )\n })\n }\n}\n","/**\n * Concatenate two `Uint8Array` buffers.\n */\nexport function concatArrayBuffer(\n left: Uint8Array,\n right: Uint8Array\n): Uint8Array {\n const result = new Uint8Array(left.byteLength + right.byteLength)\n result.set(left, 0)\n result.set(right, left.byteLength)\n return result\n}\n","export class EventPolyfill implements Event {\n readonly NONE = 0\n readonly CAPTURING_PHASE = 1\n readonly AT_TARGET = 2\n readonly BUBBLING_PHASE = 3\n\n public type: string = ''\n public srcElement: EventTarget | null = null\n public target: EventTarget | null\n public currentTarget: EventTarget | null = null\n public eventPhase: number = 0\n public timeStamp: number\n public isTrusted: boolean = true\n public composed: boolean = false\n public cancelable: boolean = true\n public defaultPrevented: boolean = false\n public bubbles: boolean = true\n public lengthComputable: boolean = true\n public loaded: number = 0\n public total: number = 0\n\n cancelBubble: boolean = false\n returnValue: boolean = true\n\n constructor(\n type: string,\n options?: { target: EventTarget; currentTarget: EventTarget }\n ) {\n this.type = type\n this.target = options?.target || null\n this.currentTarget = options?.currentTarget || null\n this.timeStamp = Date.now()\n }\n\n public composedPath(): EventTarget[] {\n return []\n }\n\n public initEvent(type: string, bubbles?: boolean, cancelable?: boolean) {\n this.type = type\n this.bubbles = !!bubbles\n this.cancelable = !!cancelable\n }\n\n public preventDefault() {\n this.defaultPrevented = true\n }\n\n public stopPropagation() {}\n public stopImmediatePropagation() {}\n}\n","import { EventPolyfill } from './EventPolyfill'\n\nexport class ProgressEventPolyfill extends EventPolyfill {\n readonly lengthComputable: boolean\n readonly composed: boolean\n readonly loaded: number\n readonly total: number\n\n constructor(type: string, init?: ProgressEventInit) {\n super(type)\n\n this.lengthComputable = init?.lengthComputable || false\n this.composed = init?.composed || false\n this.loaded = init?.loaded || 0\n this.total = init?.total || 0\n }\n}\n","import { EventPolyfill } from '../polyfills/EventPolyfill'\nimport { ProgressEventPolyfill } from '../polyfills/ProgressEventPolyfill'\n\nconst SUPPORTS_PROGRESS_EVENT = typeof ProgressEvent !== 'undefined'\n\nexport function createEvent(\n target: XMLHttpRequest | XMLHttpRequestUpload,\n type: string,\n init?: ProgressEventInit\n): EventPolyfill | ProgressEvent {\n const progressEvents = [\n 'error',\n 'progress',\n 'loadstart',\n 'loadend',\n 'load',\n 'timeout',\n 'abort',\n ]\n\n /**\n * `ProgressEvent` is not supported in React Native.\n * @see https://github.com/mswjs/interceptors/issues/40\n */\n const ProgressEventClass = SUPPORTS_PROGRESS_EVENT\n ? ProgressEvent\n : ProgressEventPolyfill\n\n const event = progressEvents.includes(type)\n ? new ProgressEventClass(type, {\n lengthComputable: true,\n loaded: init?.loaded || 0,\n total: init?.total || 0,\n })\n : new EventPolyfill(type, {\n target,\n currentTarget: target,\n })\n\n return event\n}\n","/**\n * Returns the source object of the given property on the target object\n * (the target itself, any parent in its prototype, or null).\n */\nexport function findPropertySource(\n target: object,\n propertyName: string | symbol\n): object | null {\n if (!(propertyName in target)) {\n return null\n }\n\n const hasProperty = Object.prototype.hasOwnProperty.call(target, propertyName)\n if (hasProperty) {\n return target\n }\n\n const prototype = Reflect.getPrototypeOf(target)\n return prototype ? findPropertySource(prototype, propertyName) : null\n}\n","import { findPropertySource } from './findPropertySource'\n\nexport interface ProxyOptions> {\n constructorCall?(args: Array, next: NextFunction): Target\n\n methodCall?(\n this: Target,\n data: [methodName: F, args: Array],\n next: NextFunction\n ): void\n\n setProperty?(\n data: [propertyName: string | symbol, nextValue: unknown],\n next: NextFunction\n ): boolean\n\n getProperty?(\n data: [propertyName: string | symbol, receiver: Target],\n next: NextFunction\n ): void\n}\n\nexport type NextFunction = () => ReturnType\n\nexport function createProxy(\n target: Target,\n options: ProxyOptions\n): Target {\n const proxy = new Proxy(target, optionsToProxyHandler(options))\n\n return proxy\n}\n\nfunction optionsToProxyHandler>(\n options: ProxyOptions\n): ProxyHandler {\n const { constructorCall, methodCall, getProperty, setProperty } = options\n const handler: ProxyHandler = {}\n\n if (typeof constructorCall !== 'undefined') {\n handler.construct = function (target, args, newTarget) {\n const next = Reflect.construct.bind(null, target as any, args, newTarget)\n return constructorCall.call(newTarget, args, next)\n }\n }\n\n handler.set = function (target, propertyName, nextValue) {\n const next = () => {\n const propertySource = findPropertySource(target, propertyName) || target\n const ownDescriptors = Reflect.getOwnPropertyDescriptor(\n propertySource,\n propertyName\n )\n\n // Respect any custom setters present for this property.\n if (typeof ownDescriptors?.set !== 'undefined') {\n ownDescriptors.set.apply(target, [nextValue])\n return true\n }\n\n // Otherwise, set the property on the source.\n return Reflect.defineProperty(propertySource, propertyName, {\n writable: true,\n enumerable: true,\n configurable: true,\n value: nextValue,\n })\n }\n\n if (typeof setProperty !== 'undefined') {\n return setProperty.call(target, [propertyName, nextValue], next)\n }\n\n return next()\n }\n\n handler.get = function (target, propertyName, receiver) {\n /**\n * @note Using `Reflect.get()` here causes \"TypeError: Illegal invocation\".\n */\n const next = () => target[propertyName as any]\n\n const value =\n typeof getProperty !== 'undefined'\n ? getProperty.call(target, [propertyName, receiver], next)\n : next()\n\n if (typeof value === 'function') {\n return (...args: Array) => {\n const next = value.bind(target, ...args)\n\n if (typeof methodCall !== 'undefined') {\n return methodCall.call(target, [propertyName as any, args], next)\n }\n\n return next()\n }\n }\n\n return value\n }\n\n return handler\n}\n","export function isDomParserSupportedType(\n type: string\n): type is DOMParserSupportedType {\n const supportedTypes: Array = [\n 'application/xhtml+xml',\n 'application/xml',\n 'image/svg+xml',\n 'text/html',\n 'text/xml',\n ]\n return supportedTypes.some((supportedType) => {\n return type.startsWith(supportedType)\n })\n}\n","/**\n * Parses a given string into JSON.\n * Gracefully handles invalid JSON by returning `null`.\n */\nexport function parseJson(data: string): Record | null {\n try {\n const json = JSON.parse(data)\n return json\n } catch (_) {\n return null\n }\n}\n","import { FetchResponse } from '../../../utils/fetchUtils'\n\n/**\n * Creates a Fetch API `Response` instance from the given\n * `XMLHttpRequest` instance and a response body.\n */\nexport function createResponse(\n request: XMLHttpRequest,\n body: BodyInit | null\n): Response {\n /**\n * Handle XMLHttpRequest responses that must have null as the\n * response body when represented using Fetch API Response.\n * XMLHttpRequest response will always have an empty string\n * as the \"request.response\" in those cases, resulting in an error\n * when constructing a Response instance.\n * @see https://github.com/mswjs/interceptors/issues/379\n */\n const responseBodyOrNull = FetchResponse.isResponseWithBody(request.status)\n ? body\n : null\n\n return new FetchResponse(responseBodyOrNull, {\n url: request.responseURL,\n status: request.status,\n statusText: request.statusText,\n headers: createHeadersFromXMLHttpRequestHeaders(\n request.getAllResponseHeaders()\n ),\n })\n}\n\nfunction createHeadersFromXMLHttpRequestHeaders(headersString: string): Headers {\n const headers = new Headers()\n\n const lines = headersString.split(/[\\r\\n]+/)\n for (const line of lines) {\n if (line.trim() === '') {\n continue\n }\n\n const [name, ...parts] = line.split(': ')\n const value = parts.join(': ')\n\n headers.append(name, value)\n }\n\n return headers\n}\n","/**\n * Return a total byte length of the given request/response body.\n * If the `Content-Length` header is present, it will be used as the byte length.\n */\nexport async function getBodyByteLength(\n input: Request | Response\n): Promise {\n const explicitContentLength = input.headers.get('content-length')\n\n if (explicitContentLength != null && explicitContentLength !== '') {\n return Number(explicitContentLength)\n }\n\n const buffer = await input.arrayBuffer()\n return buffer.byteLength\n}\n","import { invariant } from 'outvariant'\nimport { isNodeProcess } from 'is-node-process'\nimport type { Logger } from '@open-draft/logger'\nimport { concatArrayBuffer } from './utils/concatArrayBuffer'\nimport { createEvent } from './utils/createEvent'\nimport {\n decodeBuffer,\n encodeBuffer,\n toArrayBuffer,\n} from '../../utils/bufferUtils'\nimport { createProxy } from '../../utils/createProxy'\nimport { isDomParserSupportedType } from './utils/isDomParserSupportedType'\nimport { parseJson } from '../../utils/parseJson'\nimport { createResponse } from './utils/createResponse'\nimport { INTERNAL_REQUEST_ID_HEADER_NAME } from '../../Interceptor'\nimport { createRequestId } from '../../createRequestId'\nimport { getBodyByteLength } from './utils/getBodyByteLength'\nimport { setRawRequest } from '../../getRawRequest'\n\nconst kIsRequestHandled = Symbol('kIsRequestHandled')\nconst IS_NODE = isNodeProcess()\nconst kFetchRequest = Symbol('kFetchRequest')\n\n/**\n * An `XMLHttpRequest` instance controller that allows us\n * to handle any given request instance (e.g. responding to it).\n */\nexport class XMLHttpRequestController {\n public request: XMLHttpRequest\n public requestId: string\n public onRequest?: (\n this: XMLHttpRequestController,\n args: {\n request: Request\n requestId: string\n }\n ) => Promise\n public onResponse?: (\n this: XMLHttpRequestController,\n args: {\n response: Response\n isMockedResponse: boolean\n request: Request\n requestId: string\n }\n ) => void;\n\n [kIsRequestHandled]: boolean;\n [kFetchRequest]?: Request\n private method: string = 'GET'\n private url: URL = null as any\n private requestHeaders: Headers\n private responseBuffer: Uint8Array\n private events: Map>\n private uploadEvents: Map<\n keyof XMLHttpRequestEventTargetEventMap,\n Array\n >\n\n constructor(\n readonly initialRequest: XMLHttpRequest,\n public logger: Logger\n ) {\n this[kIsRequestHandled] = false\n\n this.events = new Map()\n this.uploadEvents = new Map()\n this.requestId = createRequestId()\n this.requestHeaders = new Headers()\n this.responseBuffer = new Uint8Array()\n\n this.request = createProxy(initialRequest, {\n setProperty: ([propertyName, nextValue], invoke) => {\n switch (propertyName) {\n case 'ontimeout': {\n const eventName = propertyName.slice(\n 2\n ) as keyof XMLHttpRequestEventTargetEventMap\n\n /**\n * @note Proxy callbacks to event listeners because JSDOM has trouble\n * translating these properties to callbacks. It seemed to be operating\n * on events exclusively.\n */\n this.request.addEventListener(eventName, nextValue as any)\n\n return invoke()\n }\n\n default: {\n return invoke()\n }\n }\n },\n methodCall: ([methodName, args], invoke) => {\n switch (methodName) {\n case 'open': {\n const [method, url] = args as [string, string | undefined]\n\n if (typeof url === 'undefined') {\n this.method = 'GET'\n this.url = toAbsoluteUrl(method)\n } else {\n this.method = method\n this.url = toAbsoluteUrl(url)\n }\n\n this.logger = this.logger.extend(`${this.method} ${this.url.href}`)\n this.logger.info('open', this.method, this.url.href)\n\n return invoke()\n }\n\n case 'addEventListener': {\n const [eventName, listener] = args as [\n keyof XMLHttpRequestEventTargetEventMap,\n Function,\n ]\n\n this.registerEvent(eventName, listener)\n this.logger.info('addEventListener', eventName, listener)\n\n return invoke()\n }\n\n case 'setRequestHeader': {\n const [name, value] = args as [string, string]\n this.requestHeaders.set(name, value)\n\n this.logger.info('setRequestHeader', name, value)\n\n return invoke()\n }\n\n case 'send': {\n const [body] = args as [\n body?: XMLHttpRequestBodyInit | Document | null,\n ]\n\n this.request.addEventListener('load', () => {\n if (typeof this.onResponse !== 'undefined') {\n // Create a Fetch API Response representation of whichever\n // response this XMLHttpRequest received. Note those may\n // be either a mocked and the original response.\n const fetchResponse = createResponse(\n this.request,\n /**\n * The `response` property is the right way to read\n * the ambiguous response body, as the request's \"responseType\" may differ.\n * @see https://xhr.spec.whatwg.org/#the-response-attribute\n */\n this.request.response\n )\n\n // Notify the consumer about the response.\n this.onResponse.call(this, {\n response: fetchResponse,\n isMockedResponse: this[kIsRequestHandled],\n request: fetchRequest,\n requestId: this.requestId!,\n })\n }\n })\n\n const requestBody =\n typeof body === 'string' ? encodeBuffer(body) : body\n\n // Delegate request handling to the consumer.\n const fetchRequest = this.toFetchApiRequest(requestBody)\n this[kFetchRequest] = fetchRequest.clone()\n\n /**\n * @note Start request handling on the next tick so that the user\n * could add event listeners for \"loadend\" before the interceptor fires it.\n */\n queueMicrotask(() => {\n const onceRequestSettled =\n this.onRequest?.call(this, {\n request: fetchRequest,\n requestId: this.requestId!,\n }) || Promise.resolve()\n\n onceRequestSettled.finally(() => {\n // If the consumer didn't handle the request (called `.respondWith()`) perform it as-is.\n if (!this[kIsRequestHandled]) {\n this.logger.info(\n 'request callback settled but request has not been handled (readystate %d), performing as-is...',\n this.request.readyState\n )\n\n /**\n * @note Set the intercepted request ID on the original request in Node.js\n * so that if it triggers any other interceptors, they don't attempt\n * to process it once again.\n *\n * For instance, XMLHttpRequest is often implemented via \"http.ClientRequest\"\n * and we don't want for both XHR and ClientRequest interceptors to\n * handle the same request at the same time (e.g. emit the \"response\" event twice).\n */\n if (IS_NODE) {\n this.request.setRequestHeader(\n INTERNAL_REQUEST_ID_HEADER_NAME,\n this.requestId!\n )\n }\n\n return invoke()\n }\n })\n })\n\n break\n }\n\n default: {\n return invoke()\n }\n }\n },\n })\n\n /**\n * Proxy the `.upload` property to gather the event listeners/callbacks.\n */\n define(\n this.request,\n 'upload',\n createProxy(this.request.upload, {\n setProperty: ([propertyName, nextValue], invoke) => {\n switch (propertyName) {\n case 'onloadstart':\n case 'onprogress':\n case 'onaboart':\n case 'onerror':\n case 'onload':\n case 'ontimeout':\n case 'onloadend': {\n const eventName = propertyName.slice(\n 2\n ) as keyof XMLHttpRequestEventTargetEventMap\n\n this.registerUploadEvent(eventName, nextValue as Function)\n }\n }\n\n return invoke()\n },\n methodCall: ([methodName, args], invoke) => {\n switch (methodName) {\n case 'addEventListener': {\n const [eventName, listener] = args as [\n keyof XMLHttpRequestEventTargetEventMap,\n Function,\n ]\n this.registerUploadEvent(eventName, listener)\n this.logger.info('upload.addEventListener', eventName, listener)\n\n return invoke()\n }\n }\n },\n })\n )\n }\n\n private registerEvent(\n eventName: keyof XMLHttpRequestEventTargetEventMap,\n listener: Function\n ): void {\n const prevEvents = this.events.get(eventName) || []\n const nextEvents = prevEvents.concat(listener)\n this.events.set(eventName, nextEvents)\n\n this.logger.info('registered event \"%s\"', eventName, listener)\n }\n\n private registerUploadEvent(\n eventName: keyof XMLHttpRequestEventTargetEventMap,\n listener: Function\n ): void {\n const prevEvents = this.uploadEvents.get(eventName) || []\n const nextEvents = prevEvents.concat(listener)\n this.uploadEvents.set(eventName, nextEvents)\n\n this.logger.info('registered upload event \"%s\"', eventName, listener)\n }\n\n /**\n * Responds to the current request with the given\n * Fetch API `Response` instance.\n */\n public async respondWith(response: Response): Promise {\n /**\n * @note Since `XMLHttpRequestController` delegates the handling of the responses\n * to the \"load\" event listener that doesn't distinguish between the mocked and original\n * responses, mark the request that had a mocked response with a corresponding symbol.\n *\n * Mark this request as having a mocked response immediately since\n * calculating request/response total body length is asynchronous.\n */\n this[kIsRequestHandled] = true\n\n /**\n * Dispatch request upload events for requests with a body.\n * @see https://github.com/mswjs/interceptors/issues/573\n */\n if (this[kFetchRequest]) {\n const totalRequestBodyLength = await getBodyByteLength(\n this[kFetchRequest]\n )\n\n this.trigger('loadstart', this.request.upload, {\n loaded: 0,\n total: totalRequestBodyLength,\n })\n this.trigger('progress', this.request.upload, {\n loaded: totalRequestBodyLength,\n total: totalRequestBodyLength,\n })\n this.trigger('load', this.request.upload, {\n loaded: totalRequestBodyLength,\n total: totalRequestBodyLength,\n })\n\n this.trigger('loadend', this.request.upload, {\n loaded: totalRequestBodyLength,\n total: totalRequestBodyLength,\n })\n }\n\n this.logger.info(\n 'responding with a mocked response: %d %s',\n response.status,\n response.statusText\n )\n\n define(this.request, 'status', response.status)\n define(this.request, 'statusText', response.statusText)\n define(this.request, 'responseURL', this.url.href)\n\n this.request.getResponseHeader = new Proxy(this.request.getResponseHeader, {\n apply: (_, __, args: [name: string]) => {\n this.logger.info('getResponseHeader', args[0])\n\n if (this.request.readyState < this.request.HEADERS_RECEIVED) {\n this.logger.info('headers not received yet, returning null')\n\n // Headers not received yet, nothing to return.\n return null\n }\n\n const headerValue = response.headers.get(args[0])\n this.logger.info(\n 'resolved response header \"%s\" to',\n args[0],\n headerValue\n )\n\n return headerValue\n },\n })\n\n this.request.getAllResponseHeaders = new Proxy(\n this.request.getAllResponseHeaders,\n {\n apply: () => {\n this.logger.info('getAllResponseHeaders')\n\n if (this.request.readyState < this.request.HEADERS_RECEIVED) {\n this.logger.info('headers not received yet, returning empty string')\n\n // Headers not received yet, nothing to return.\n return ''\n }\n\n const headersList = Array.from(response.headers.entries())\n const allHeaders = headersList\n .map(([headerName, headerValue]) => {\n return `${headerName}: ${headerValue}`\n })\n .join('\\r\\n')\n\n this.logger.info('resolved all response headers to', allHeaders)\n\n return allHeaders\n },\n }\n )\n\n // Update the response getters to resolve against the mocked response.\n Object.defineProperties(this.request, {\n response: {\n enumerable: true,\n configurable: false,\n get: () => this.response,\n },\n responseText: {\n enumerable: true,\n configurable: false,\n get: () => this.responseText,\n },\n responseXML: {\n enumerable: true,\n configurable: false,\n get: () => this.responseXML,\n },\n })\n\n const totalResponseBodyLength = await getBodyByteLength(response.clone())\n\n this.logger.info('calculated response body length', totalResponseBodyLength)\n\n this.trigger('loadstart', this.request, {\n loaded: 0,\n total: totalResponseBodyLength,\n })\n\n this.setReadyState(this.request.HEADERS_RECEIVED)\n this.setReadyState(this.request.LOADING)\n\n const finalizeResponse = () => {\n this.logger.info('finalizing the mocked response...')\n\n this.setReadyState(this.request.DONE)\n\n this.trigger('load', this.request, {\n loaded: this.responseBuffer.byteLength,\n total: totalResponseBodyLength,\n })\n\n this.trigger('loadend', this.request, {\n loaded: this.responseBuffer.byteLength,\n total: totalResponseBodyLength,\n })\n }\n\n if (response.body) {\n this.logger.info('mocked response has body, streaming...')\n\n const reader = response.body.getReader()\n\n const readNextResponseBodyChunk = async () => {\n const { value, done } = await reader.read()\n\n if (done) {\n this.logger.info('response body stream done!')\n finalizeResponse()\n return\n }\n\n if (value) {\n this.logger.info('read response body chunk:', value)\n this.responseBuffer = concatArrayBuffer(this.responseBuffer, value)\n\n this.trigger('progress', this.request, {\n loaded: this.responseBuffer.byteLength,\n total: totalResponseBodyLength,\n })\n }\n\n readNextResponseBodyChunk()\n }\n\n readNextResponseBodyChunk()\n } else {\n finalizeResponse()\n }\n }\n\n private responseBufferToText(): string {\n return decodeBuffer(this.responseBuffer)\n }\n\n get response(): unknown {\n this.logger.info(\n 'getResponse (responseType: %s)',\n this.request.responseType\n )\n\n if (this.request.readyState !== this.request.DONE) {\n return null\n }\n\n switch (this.request.responseType) {\n case 'json': {\n const responseJson = parseJson(this.responseBufferToText())\n this.logger.info('resolved response JSON', responseJson)\n\n return responseJson\n }\n\n case 'arraybuffer': {\n const arrayBuffer = toArrayBuffer(this.responseBuffer)\n this.logger.info('resolved response ArrayBuffer', arrayBuffer)\n\n return arrayBuffer\n }\n\n case 'blob': {\n const mimeType =\n this.request.getResponseHeader('Content-Type') || 'text/plain'\n const responseBlob = new Blob([this.responseBufferToText()], {\n type: mimeType,\n })\n\n this.logger.info(\n 'resolved response Blob (mime type: %s)',\n responseBlob,\n mimeType\n )\n\n return responseBlob\n }\n\n default: {\n const responseText = this.responseBufferToText()\n this.logger.info(\n 'resolving \"%s\" response type as text',\n this.request.responseType,\n responseText\n )\n\n return responseText\n }\n }\n }\n\n get responseText(): string {\n /**\n * Throw when trying to read the response body as text when the\n * \"responseType\" doesn't expect text. This just respects the spec better.\n * @see https://xhr.spec.whatwg.org/#the-responsetext-attribute\n */\n invariant(\n this.request.responseType === '' || this.request.responseType === 'text',\n 'InvalidStateError: The object is in invalid state.'\n )\n\n if (\n this.request.readyState !== this.request.LOADING &&\n this.request.readyState !== this.request.DONE\n ) {\n return ''\n }\n\n const responseText = this.responseBufferToText()\n this.logger.info('getResponseText: \"%s\"', responseText)\n\n return responseText\n }\n\n get responseXML(): Document | null {\n invariant(\n this.request.responseType === '' ||\n this.request.responseType === 'document',\n 'InvalidStateError: The object is in invalid state.'\n )\n\n if (this.request.readyState !== this.request.DONE) {\n return null\n }\n\n const contentType = this.request.getResponseHeader('Content-Type') || ''\n\n if (typeof DOMParser === 'undefined') {\n console.warn(\n 'Cannot retrieve XMLHttpRequest response body as XML: DOMParser is not defined. You are likely using an environment that is not browser or does not polyfill browser globals correctly.'\n )\n return null\n }\n\n if (isDomParserSupportedType(contentType)) {\n return new DOMParser().parseFromString(\n this.responseBufferToText(),\n contentType\n )\n }\n\n return null\n }\n\n public errorWith(error?: Error): void {\n /**\n * @note Mark this request as handled even if it received a mock error.\n * This prevents the controller from trying to perform this request as-is.\n */\n this[kIsRequestHandled] = true\n this.logger.info('responding with an error')\n\n this.setReadyState(this.request.DONE)\n this.trigger('error', this.request)\n this.trigger('loadend', this.request)\n }\n\n /**\n * Transitions this request's `readyState` to the given one.\n */\n private setReadyState(nextReadyState: number): void {\n this.logger.info(\n 'setReadyState: %d -> %d',\n this.request.readyState,\n nextReadyState\n )\n\n if (this.request.readyState === nextReadyState) {\n this.logger.info('ready state identical, skipping transition...')\n return\n }\n\n define(this.request, 'readyState', nextReadyState)\n\n this.logger.info('set readyState to: %d', nextReadyState)\n\n if (nextReadyState !== this.request.UNSENT) {\n this.logger.info('triggering \"readystatechange\" event...')\n\n this.trigger('readystatechange', this.request)\n }\n }\n\n /**\n * Triggers given event on the `XMLHttpRequest` instance.\n */\n private trigger<\n EventName extends keyof (XMLHttpRequestEventTargetEventMap & {\n readystatechange: ProgressEvent\n }),\n >(\n eventName: EventName,\n target: XMLHttpRequest | XMLHttpRequestUpload,\n options?: ProgressEventInit\n ): void {\n const callback = (target as XMLHttpRequest)[`on${eventName}`]\n const event = createEvent(target, eventName, options)\n\n this.logger.info('trigger \"%s\"', eventName, options || '')\n\n // Invoke direct callbacks.\n if (typeof callback === 'function') {\n this.logger.info('found a direct \"%s\" callback, calling...', eventName)\n callback.call(target as XMLHttpRequest, event)\n }\n\n // Invoke event listeners.\n const events =\n target instanceof XMLHttpRequestUpload ? this.uploadEvents : this.events\n\n for (const [registeredEventName, listeners] of events) {\n if (registeredEventName === eventName) {\n this.logger.info(\n 'found %d listener(s) for \"%s\" event, calling...',\n listeners.length,\n eventName\n )\n\n listeners.forEach((listener) => listener.call(target, event))\n }\n }\n }\n\n /**\n * Converts this `XMLHttpRequest` instance into a Fetch API `Request` instance.\n */\n private toFetchApiRequest(\n body: XMLHttpRequestBodyInit | Document | null | undefined\n ): Request {\n this.logger.info('converting request to a Fetch API Request...')\n\n // If the `Document` is used as the body of this XMLHttpRequest,\n // set its inner text as the Fetch API Request body.\n const resolvedBody =\n body instanceof Document ? body.documentElement.innerText : body\n\n const fetchRequest = new Request(this.url.href, {\n method: this.method,\n headers: this.requestHeaders,\n /**\n * @see https://xhr.spec.whatwg.org/#cross-origin-credentials\n */\n credentials: this.request.withCredentials ? 'include' : 'same-origin',\n body: ['GET', 'HEAD'].includes(this.method.toUpperCase())\n ? null\n : resolvedBody,\n })\n\n const proxyHeaders = createProxy(fetchRequest.headers, {\n methodCall: ([methodName, args], invoke) => {\n // Forward the latest state of the internal request headers\n // because the interceptor might have modified them\n // without responding to the request.\n switch (methodName) {\n case 'append':\n case 'set': {\n const [headerName, headerValue] = args as [string, string]\n this.request.setRequestHeader(headerName, headerValue)\n break\n }\n\n case 'delete': {\n const [headerName] = args as [string]\n console.warn(\n `XMLHttpRequest: Cannot remove a \"${headerName}\" header from the Fetch API representation of the \"${fetchRequest.method} ${fetchRequest.url}\" request. XMLHttpRequest headers cannot be removed.`\n )\n break\n }\n }\n\n return invoke()\n },\n })\n define(fetchRequest, 'headers', proxyHeaders)\n setRawRequest(fetchRequest, this.request)\n\n this.logger.info('converted request to a Fetch API Request!', fetchRequest)\n\n return fetchRequest\n }\n}\n\nfunction toAbsoluteUrl(url: string | URL): URL {\n /**\n * @note XMLHttpRequest interceptor may run in environments\n * that implement XMLHttpRequest but don't implement \"location\"\n * (for example, React Native). If that's the case, return the\n * input URL as-is (nothing to be relative to).\n * @see https://github.com/mswjs/msw/issues/1777\n */\n if (typeof location === 'undefined') {\n return new URL(url)\n }\n\n return new URL(url.toString(), location.href)\n}\n\nfunction define(\n target: object,\n property: string | symbol,\n value: unknown\n): void {\n Reflect.defineProperty(target, property, {\n // Ensure writable properties to allow redefining readonly properties.\n writable: true,\n enumerable: true,\n value,\n })\n}\n","import type { Logger } from '@open-draft/logger'\nimport { XMLHttpRequestEmitter } from '.'\nimport { RequestController } from '../../RequestController'\nimport { XMLHttpRequestController } from './XMLHttpRequestController'\nimport { handleRequest } from '../../utils/handleRequest'\nimport { isResponseError } from '../../utils/responseUtils'\n\nexport interface XMLHttpRequestProxyOptions {\n emitter: XMLHttpRequestEmitter\n logger: Logger\n}\n\n/**\n * Create a proxied `XMLHttpRequest` class.\n * The proxied class establishes spies on certain methods,\n * allowing us to intercept requests and respond to them.\n */\nexport function createXMLHttpRequestProxy({\n emitter,\n logger,\n}: XMLHttpRequestProxyOptions) {\n const XMLHttpRequestProxy = new Proxy(globalThis.XMLHttpRequest, {\n construct(target, args, newTarget) {\n logger.info('constructed new XMLHttpRequest')\n\n const originalRequest = Reflect.construct(\n target,\n args,\n newTarget\n ) as XMLHttpRequest\n\n /**\n * @note Forward prototype descriptors onto the proxied object.\n * XMLHttpRequest is implemented in JSDOM in a way that assigns\n * a bunch of descriptors, like \"set responseType()\" on the prototype.\n * With this propagation, we make sure that those descriptors trigger\n * when the user operates with the proxied request instance.\n */\n const prototypeDescriptors = Object.getOwnPropertyDescriptors(\n target.prototype\n )\n for (const propertyName in prototypeDescriptors) {\n Reflect.defineProperty(\n originalRequest,\n propertyName,\n prototypeDescriptors[propertyName]\n )\n }\n\n const xhrRequestController = new XMLHttpRequestController(\n originalRequest,\n logger\n )\n\n xhrRequestController.onRequest = async function ({ request, requestId }) {\n const controller = new RequestController(request, {\n passthrough: () => {\n this.logger.info(\n 'no mocked response received, performing request as-is...'\n )\n },\n respondWith: async (response) => {\n if (isResponseError(response)) {\n this.errorWith(new TypeError('Network error'))\n return\n }\n\n await this.respondWith(response)\n },\n errorWith: (reason) => {\n this.logger.info('request errored!', { error: reason })\n\n if (reason instanceof Error) {\n this.errorWith(reason)\n }\n },\n })\n\n this.logger.info('awaiting mocked response...')\n\n this.logger.info(\n 'emitting the \"request\" event for %s listener(s)...',\n emitter.listenerCount('request')\n )\n\n await handleRequest({\n request,\n requestId,\n controller,\n emitter,\n })\n }\n\n xhrRequestController.onResponse = async function ({\n response,\n isMockedResponse,\n request,\n requestId,\n }) {\n this.logger.info(\n 'emitting the \"response\" event for %s listener(s)...',\n emitter.listenerCount('response')\n )\n\n emitter.emit('response', {\n response,\n isMockedResponse,\n request,\n requestId,\n })\n }\n\n // Return the proxied request from the controller\n // so that the controller can react to the consumer's interactions\n // with this request (opening/sending/etc).\n return xhrRequestController.request\n },\n })\n\n return XMLHttpRequestProxy\n}\n","import { invariant } from 'outvariant'\nimport { Emitter } from 'strict-event-emitter'\nimport { HttpRequestEventMap, IS_PATCHED_MODULE } from '../../glossary'\nimport { Interceptor } from '../../Interceptor'\nimport { createXMLHttpRequestProxy } from './XMLHttpRequestProxy'\nimport { hasConfigurableGlobal } from '../../utils/hasConfigurableGlobal'\n\nexport type XMLHttpRequestEmitter = Emitter\n\nexport class XMLHttpRequestInterceptor extends Interceptor {\n static interceptorSymbol = Symbol('xhr')\n\n constructor() {\n super(XMLHttpRequestInterceptor.interceptorSymbol)\n }\n\n protected checkEnvironment() {\n return hasConfigurableGlobal('XMLHttpRequest')\n }\n\n protected setup() {\n const logger = this.logger.extend('setup')\n\n logger.info('patching \"XMLHttpRequest\" module...')\n\n const PureXMLHttpRequest = globalThis.XMLHttpRequest\n\n invariant(\n !(PureXMLHttpRequest as any)[IS_PATCHED_MODULE],\n 'Failed to patch the \"XMLHttpRequest\" module: already patched.'\n )\n\n globalThis.XMLHttpRequest = createXMLHttpRequestProxy({\n emitter: this.emitter,\n logger: this.logger,\n })\n\n logger.info(\n 'native \"XMLHttpRequest\" module patched!',\n globalThis.XMLHttpRequest.name\n )\n\n Object.defineProperty(globalThis.XMLHttpRequest, IS_PATCHED_MODULE, {\n enumerable: true,\n configurable: true,\n value: true,\n })\n\n this.subscriptions.push(() => {\n Object.defineProperty(globalThis.XMLHttpRequest, IS_PATCHED_MODULE, {\n value: undefined,\n })\n\n globalThis.XMLHttpRequest = PureXMLHttpRequest\n logger.info(\n 'native \"XMLHttpRequest\" module restored!',\n globalThis.XMLHttpRequest.name\n )\n })\n }\n}\n","import { FetchInterceptor } from '@mswjs/interceptors/fetch'\nimport { XMLHttpRequestInterceptor } from '@mswjs/interceptors/XMLHttpRequest'\nimport { InterceptorSource } from '#core/experimental/sources/interceptor-source'\nimport { devUtils } from '#core/utils/internal/devUtils'\n\ninterface FallbackHttpSourceOptions {\n quiet?: boolean\n}\n\nexport class FallbackHttpSource extends InterceptorSource {\n constructor(private readonly options: FallbackHttpSourceOptions) {\n super({\n interceptors: [new XMLHttpRequestInterceptor(), new FetchInterceptor()],\n })\n }\n\n public enable(): void {\n super.enable()\n\n if (!this.options.quiet) {\n this.#printStartMessage()\n }\n }\n\n public disable(): void {\n super.disable()\n\n if (!this.options.quiet) {\n this.#printStopMessage()\n }\n }\n\n #printStartMessage(): void {\n console.groupCollapsed(\n `%c${devUtils.formatMessage('Mocking enabled (fallback mode).')}`,\n 'color:orangered;font-weight:bold;',\n )\n // eslint-disable-next-line no-console\n console.log(\n '%cDocumentation: %chttps://mswjs.io/docs',\n 'font-weight:bold',\n 'font-weight:normal',\n )\n // eslint-disable-next-line no-console\n console.log('Found an issue? https://github.com/mswjs/msw/issues')\n console.groupEnd()\n }\n\n #printStopMessage(): void {\n // eslint-disable-next-line no-console\n console.log(\n `%c${devUtils.formatMessage('Mocking disabled.')}`,\n 'color:orangered;font-weight:bold;',\n )\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAM,kBAAkB;AAExB,SAAS,oBAAoB,YAAiB,MAAmB;AAC/D,UAAQ,MAAM;IAEZ,KAAK;AACH,aAAO;IAGT,KAAK;IACL,KAAK;AACH,aAAO,OAAO,UAAU;IAG1B,KAAK;AACH,aAAO,KAAK,UAAU,UAAU;IAGlC,KAAK,KAAK;AAER,UAAI,OAAO,eAAe,UAAU;AAClC,eAAO;MACT;AAEA,YAAM,OAAO,KAAK,UAAU,UAAU;AAGtC,UAAI,SAAS,QAAQ,SAAS,QAAQ,mBAAmB,KAAK,IAAI,GAAG;AACnE,eAAO;MACT;AAEA,aAAO;IACT;EACF;AACF;AAEO,SAAS,OAAO,YAAoB,aAA4B;AACrE,MAAI,YAAY,WAAW,GAAG;A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M,CAAC,EAAE,YAAY,IAAI,MAAM,WAAW;AAC1C,eAAO;AAAA,MACT;AAAA,IACF;AAAA,IACA,OAAO;AACL,UAAI,QAAQ,eAAe,wCAAkB,UAAU;AACrD,kCAAS;AAAA,UACP;AAAA,QACF;AACA;AAAA,MACF;AAEA,cAAQ,QAAQ;AAChB,aAAO,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAAA,IAChD;AAAA,IACA,QAAQ,QAAQ;AAAA,IAChB,KAAK,QAAQ,IAAI,KAAK,OAAO;AAAA,IAC7B,eAAe,QAAQ,cAAc,KAAK,OAAO;AAAA,IACjD,iBAAiB,QAAQ,gBAAgB,KAAK,OAAO;AAAA,IACrD,cAAc,QAAQ,aAAa,KAAK,OAAO;AAAA,EACjD;AACF;AAMO,IAAM,iBAAN,MAA4C;AAAA,EACjD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAIA,cAAc;AACZ,UAAM,SAAS,YAAY;AAE3B,SAAK,QAAQ,OAAO,MAAM,KAAK,MAAM;AACrC,SAAK,OAAO,OAAO,KAAK,KAAK,MAAM;AACnC,SAAK,MAAM,OAAO,IAAI,KAAK,MAAM;AACjC,SAAK,gBAAgB,OAAO,cAAc,KAAK,MAAM;AACrD,SAAK,kBAAkB,OAAO,gBAAgB,KAAK,MAAM;AACzD,SAAK,eAAe,OAAO,aAAa,KAAK,MAAM;AACnD,SAAK,SAAS,OAAO;AAAA,EACvB;AACF;","names":["error","__defProp","__export","symbol: symbol","kEmitter","kBoundListener","socket: WebSocket","transport: WebSocketTransport","kEmitter","kBoundListener","client: WebSocketOverride","transport: WebSocketClassTransport","createConnection: () => WebSocket","socket: WebSocketOverride","WebSocketInterceptor","error","import_interceptor_source","import_devUtils","createDeferredExecutor","DeferredPromise","IS_PATCHED_MODULE: unique symbol","InterceptorError","RequestController","request: Request","source: RequestControllerSource","symbol","FetchResponse","import_devUtils","error","error: any","worker","#list","kDefaultPrevented","Emitter","listeners","#hookListeners","Emitter","import_devUtils","DeferredPromise","registration","error","until","error","isObject","error","until","locationUrl: URL","error","requestInit: RequestInit","readable","FetchInterceptor","until","response","handler: ProxyHandler","next","IS_NODE","initialRequest: XMLHttpRequest","logger: Logger","error","XMLHttpRequestInterceptor","import_devUtils"]} \ No newline at end of file diff --git a/node_modules/msw/lib/browser/index.mjs b/node_modules/msw/lib/browser/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..15e2b111db2c6206168deae296238b6e0556ae82 --- /dev/null +++ b/node_modules/msw/lib/browser/index.mjs @@ -0,0 +1,3566 @@ +// node_modules/.pnpm/outvariant@1.4.3/node_modules/outvariant/lib/index.mjs +var POSITIONALS_EXP = /(%?)(%([sdijo]))/g; +function serializePositional(positional, flag) { + switch (flag) { + case "s": + return positional; + case "d": + case "i": + return Number(positional); + case "j": + return JSON.stringify(positional); + case "o": { + if (typeof positional === "string") { + return positional; + } + const json = JSON.stringify(positional); + if (json === "{}" || json === "[]" || /^\[object .+?\]$/.test(json)) { + return positional; + } + return json; + } + } +} +function format(message, ...positionals) { + if (positionals.length === 0) { + return message; + } + let positionalIndex = 0; + let formattedMessage = message.replace( + POSITIONALS_EXP, + (match, isEscaped, _, flag) => { + const positional = positionals[positionalIndex]; + const value = serializePositional(positional, flag); + if (!isEscaped) { + positionalIndex++; + return value; + } + return match; + } + ); + if (positionalIndex < positionals.length) { + formattedMessage += ` ${positionals.slice(positionalIndex).join(" ")}`; + } + formattedMessage = formattedMessage.replace(/%{2,2}/g, "%"); + return formattedMessage; +} +var STACK_FRAMES_TO_IGNORE = 2; +function cleanErrorStack(error2) { + if (!error2.stack) { + return; + } + const nextStack = error2.stack.split("\n"); + nextStack.splice(1, STACK_FRAMES_TO_IGNORE); + error2.stack = nextStack.join("\n"); +} +var InvariantError = class extends Error { + constructor(message, ...positionals) { + super(message); + this.message = message; + this.name = "Invariant Violation"; + this.message = format(message, ...positionals); + cleanErrorStack(this); + } +}; +var invariant = (predicate, message, ...positionals) => { + if (!predicate) { + throw new InvariantError(message, ...positionals); + } +}; +invariant.as = (ErrorConstructor, predicate, message, ...positionals) => { + if (!predicate) { + const formatMessage = positionals.length === 0 ? message : format(message, ...positionals); + let error2; + try { + error2 = Reflect.construct(ErrorConstructor, [ + formatMessage + ]); + } catch (err) { + error2 = ErrorConstructor(formatMessage); + } + throw error2; + } +}; + +// node_modules/.pnpm/is-node-process@1.2.0/node_modules/is-node-process/lib/index.mjs +function isNodeProcess() { + if (typeof navigator !== "undefined" && navigator.product === "ReactNative") { + return true; + } + if (typeof process !== "undefined") { + const type = process.type; + if (type === "renderer" || type === "worker") { + return false; + } + return !!(process.versions && process.versions.node); + } + return false; +} + +// node_modules/.pnpm/@open-draft+logger@0.3.0/node_modules/@open-draft/logger/lib/index.mjs +var __defProp = Object.defineProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var colors_exports = {}; +__export(colors_exports, { + blue: () => blue, + gray: () => gray, + green: () => green, + red: () => red, + yellow: () => yellow +}); +function yellow(text) { + return `\x1B[33m${text}\x1B[0m`; +} +function blue(text) { + return `\x1B[34m${text}\x1B[0m`; +} +function gray(text) { + return `\x1B[90m${text}\x1B[0m`; +} +function red(text) { + return `\x1B[31m${text}\x1B[0m`; +} +function green(text) { + return `\x1B[32m${text}\x1B[0m`; +} +var IS_NODE = isNodeProcess(); +var Logger = class { + constructor(name) { + this.name = name; + this.prefix = `[${this.name}]`; + const LOGGER_NAME = getVariable("DEBUG"); + const LOGGER_LEVEL = getVariable("LOG_LEVEL"); + const isLoggingEnabled = LOGGER_NAME === "1" || LOGGER_NAME === "true" || typeof LOGGER_NAME !== "undefined" && this.name.startsWith(LOGGER_NAME); + if (isLoggingEnabled) { + this.debug = isDefinedAndNotEquals(LOGGER_LEVEL, "debug") ? noop : this.debug; + this.info = isDefinedAndNotEquals(LOGGER_LEVEL, "info") ? noop : this.info; + this.success = isDefinedAndNotEquals(LOGGER_LEVEL, "success") ? noop : this.success; + this.warning = isDefinedAndNotEquals(LOGGER_LEVEL, "warning") ? noop : this.warning; + this.error = isDefinedAndNotEquals(LOGGER_LEVEL, "error") ? noop : this.error; + } else { + this.info = noop; + this.success = noop; + this.warning = noop; + this.error = noop; + this.only = noop; + } + } + prefix; + extend(domain) { + return new Logger(`${this.name}:${domain}`); + } + /** + * Print a debug message. + * @example + * logger.debug('no duplicates found, creating a document...') + */ + debug(message, ...positionals) { + this.logEntry({ + level: "debug", + message: gray(message), + positionals, + prefix: this.prefix, + colors: { + prefix: "gray" + } + }); + } + /** + * Print an info message. + * @example + * logger.info('start parsing...') + */ + info(message, ...positionals) { + this.logEntry({ + level: "info", + message, + positionals, + prefix: this.prefix, + colors: { + prefix: "blue" + } + }); + const performance2 = new PerformanceEntry(); + return (message2, ...positionals2) => { + performance2.measure(); + this.logEntry({ + level: "info", + message: `${message2} ${gray(`${performance2.deltaTime}ms`)}`, + positionals: positionals2, + prefix: this.prefix, + colors: { + prefix: "blue" + } + }); + }; + } + /** + * Print a success message. + * @example + * logger.success('successfully created document') + */ + success(message, ...positionals) { + this.logEntry({ + level: "info", + message, + positionals, + prefix: `\u2714 ${this.prefix}`, + colors: { + timestamp: "green", + prefix: "green" + } + }); + } + /** + * Print a warning. + * @example + * logger.warning('found legacy document format') + */ + warning(message, ...positionals) { + this.logEntry({ + level: "warning", + message, + positionals, + prefix: `\u26A0 ${this.prefix}`, + colors: { + timestamp: "yellow", + prefix: "yellow" + } + }); + } + /** + * Print an error message. + * @example + * logger.error('something went wrong') + */ + error(message, ...positionals) { + this.logEntry({ + level: "error", + message, + positionals, + prefix: `\u2716 ${this.prefix}`, + colors: { + timestamp: "red", + prefix: "red" + } + }); + } + /** + * Execute the given callback only when the logging is enabled. + * This is skipped in its entirety and has no runtime cost otherwise. + * This executes regardless of the log level. + * @example + * logger.only(() => { + * logger.info('additional info') + * }) + */ + only(callback) { + callback(); + } + createEntry(level, message) { + return { + timestamp: /* @__PURE__ */ new Date(), + level, + message + }; + } + logEntry(args) { + const { + level, + message, + prefix, + colors: customColors, + positionals = [] + } = args; + const entry = this.createEntry(level, message); + const timestampColor = customColors?.timestamp || "gray"; + const prefixColor = customColors?.prefix || "gray"; + const colorize = { + timestamp: colors_exports[timestampColor], + prefix: colors_exports[prefixColor] + }; + const write = this.getWriter(level); + write( + [colorize.timestamp(this.formatTimestamp(entry.timestamp))].concat(prefix != null ? colorize.prefix(prefix) : []).concat(serializeInput(message)).join(" "), + ...positionals.map(serializeInput) + ); + } + formatTimestamp(timestamp) { + return `${timestamp.toLocaleTimeString( + "en-GB" + )}:${timestamp.getMilliseconds()}`; + } + getWriter(level) { + switch (level) { + case "debug": + case "success": + case "info": { + return log; + } + case "warning": { + return warn; + } + case "error": { + return error; + } + } + } +}; +var PerformanceEntry = class { + startTime; + endTime; + deltaTime; + constructor() { + this.startTime = performance.now(); + } + measure() { + this.endTime = performance.now(); + const deltaTime = this.endTime - this.startTime; + this.deltaTime = deltaTime.toFixed(2); + } +}; +var noop = () => void 0; +function log(message, ...positionals) { + if (IS_NODE) { + process.stdout.write(format(message, ...positionals) + "\n"); + return; + } + console.log(message, ...positionals); +} +function warn(message, ...positionals) { + if (IS_NODE) { + process.stderr.write(format(message, ...positionals) + "\n"); + return; + } + console.warn(message, ...positionals); +} +function error(message, ...positionals) { + if (IS_NODE) { + process.stderr.write(format(message, ...positionals) + "\n"); + return; + } + console.error(message, ...positionals); +} +function getVariable(variableName) { + if (IS_NODE) { + return process.env[variableName]; + } + return globalThis[variableName]?.toString(); +} +function isDefinedAndNotEquals(value, expected) { + return value !== void 0 && value !== expected; +} +function serializeInput(message) { + if (typeof message === "undefined") { + return "undefined"; + } + if (message === null) { + return "null"; + } + if (typeof message === "string") { + return message; + } + if (typeof message === "object") { + return JSON.stringify(message); + } + return message.toString(); +} + +// node_modules/.pnpm/strict-event-emitter@0.5.1/node_modules/strict-event-emitter/lib/index.mjs +var MemoryLeakError = class extends Error { + constructor(emitter, type, count) { + super( + `Possible EventEmitter memory leak detected. ${count} ${type.toString()} listeners added. Use emitter.setMaxListeners() to increase limit` + ); + this.emitter = emitter; + this.type = type; + this.count = count; + this.name = "MaxListenersExceededWarning"; + } +}; +var _Emitter = class { + static listenerCount(emitter, eventName) { + return emitter.listenerCount(eventName); + } + constructor() { + this.events = /* @__PURE__ */ new Map(); + this.maxListeners = _Emitter.defaultMaxListeners; + this.hasWarnedAboutPotentialMemoryLeak = false; + } + _emitInternalEvent(internalEventName, eventName, listener) { + this.emit( + internalEventName, + ...[eventName, listener] + ); + } + _getListeners(eventName) { + return Array.prototype.concat.apply([], this.events.get(eventName)) || []; + } + _removeListener(listeners, listener) { + const index = listeners.indexOf(listener); + if (index > -1) { + listeners.splice(index, 1); + } + return []; + } + _wrapOnceListener(eventName, listener) { + const onceListener = (...data) => { + this.removeListener(eventName, onceListener); + return listener.apply(this, data); + }; + Object.defineProperty(onceListener, "name", { value: listener.name }); + return onceListener; + } + setMaxListeners(maxListeners) { + this.maxListeners = maxListeners; + return this; + } + /** + * Returns the current max listener value for the `Emitter` which is + * either set by `emitter.setMaxListeners(n)` or defaults to + * `Emitter.defaultMaxListeners`. + */ + getMaxListeners() { + return this.maxListeners; + } + /** + * Returns an array listing the events for which the emitter has registered listeners. + * The values in the array will be strings or Symbols. + */ + eventNames() { + return Array.from(this.events.keys()); + } + /** + * Synchronously calls each of the listeners registered for the event named `eventName`, + * in the order they were registered, passing the supplied arguments to each. + * Returns `true` if the event has listeners, `false` otherwise. + * + * @example + * const emitter = new Emitter<{ hello: [string] }>() + * emitter.emit('hello', 'John') + */ + emit(eventName, ...data) { + const listeners = this._getListeners(eventName); + listeners.forEach((listener) => { + listener.apply(this, data); + }); + return listeners.length > 0; + } + addListener(eventName, listener) { + this._emitInternalEvent("newListener", eventName, listener); + const nextListeners = this._getListeners(eventName).concat(listener); + this.events.set(eventName, nextListeners); + if (this.maxListeners > 0 && this.listenerCount(eventName) > this.maxListeners && !this.hasWarnedAboutPotentialMemoryLeak) { + this.hasWarnedAboutPotentialMemoryLeak = true; + const memoryLeakWarning = new MemoryLeakError( + this, + eventName, + this.listenerCount(eventName) + ); + console.warn(memoryLeakWarning); + } + return this; + } + on(eventName, listener) { + return this.addListener(eventName, listener); + } + once(eventName, listener) { + return this.addListener( + eventName, + this._wrapOnceListener(eventName, listener) + ); + } + prependListener(eventName, listener) { + const listeners = this._getListeners(eventName); + if (listeners.length > 0) { + const nextListeners = [listener].concat(listeners); + this.events.set(eventName, nextListeners); + } else { + this.events.set(eventName, listeners.concat(listener)); + } + return this; + } + prependOnceListener(eventName, listener) { + return this.prependListener( + eventName, + this._wrapOnceListener(eventName, listener) + ); + } + removeListener(eventName, listener) { + const listeners = this._getListeners(eventName); + if (listeners.length > 0) { + this._removeListener(listeners, listener); + this.events.set(eventName, listeners); + this._emitInternalEvent("removeListener", eventName, listener); + } + return this; + } + /** + * Alias for `emitter.removeListener()`. + * + * @example + * emitter.off('hello', listener) + */ + off(eventName, listener) { + return this.removeListener(eventName, listener); + } + removeAllListeners(eventName) { + if (eventName) { + this.events.delete(eventName); + } else { + this.events.clear(); + } + return this; + } + /** + * Returns a copy of the array of listeners for the event named `eventName`. + */ + listeners(eventName) { + return Array.from(this._getListeners(eventName)); + } + /** + * Returns the number of listeners listening to the event named `eventName`. + */ + listenerCount(eventName) { + return this._getListeners(eventName).length; + } + rawListeners(eventName) { + return this.listeners(eventName); + } +}; +var Emitter = _Emitter; +Emitter.defaultMaxListeners = 10; + +// node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/lib/browser/createRequestId-DQcIlohW.mjs +var INTERNAL_REQUEST_ID_HEADER_NAME = "x-interceptors-internal-request-id"; +function getGlobalSymbol(symbol) { + return globalThis[symbol] || void 0; +} +function setGlobalSymbol(symbol, value) { + globalThis[symbol] = value; +} +function deleteGlobalSymbol(symbol) { + delete globalThis[symbol]; +} +var InterceptorReadyState = /* @__PURE__ */ (function(InterceptorReadyState$1) { + InterceptorReadyState$1["INACTIVE"] = "INACTIVE"; + InterceptorReadyState$1["APPLYING"] = "APPLYING"; + InterceptorReadyState$1["APPLIED"] = "APPLIED"; + InterceptorReadyState$1["DISPOSING"] = "DISPOSING"; + InterceptorReadyState$1["DISPOSED"] = "DISPOSED"; + return InterceptorReadyState$1; +})({}); +var Interceptor = class { + constructor(symbol) { + this.symbol = symbol; + this.readyState = InterceptorReadyState.INACTIVE; + this.emitter = new Emitter(); + this.subscriptions = []; + this.logger = new Logger(symbol.description); + this.emitter.setMaxListeners(0); + this.logger.info("constructing the interceptor..."); + } + /** + * Determine if this interceptor can be applied + * in the current environment. + */ + checkEnvironment() { + return true; + } + /** + * Apply this interceptor to the current process. + * Returns an already running interceptor instance if it's present. + */ + apply() { + const logger = this.logger.extend("apply"); + logger.info("applying the interceptor..."); + if (this.readyState === InterceptorReadyState.APPLIED) { + logger.info("intercepted already applied!"); + return; + } + if (!this.checkEnvironment()) { + logger.info("the interceptor cannot be applied in this environment!"); + return; + } + this.readyState = InterceptorReadyState.APPLYING; + const runningInstance = this.getInstance(); + if (runningInstance) { + logger.info("found a running instance, reusing..."); + this.on = (event, listener) => { + logger.info('proxying the "%s" listener', event); + runningInstance.emitter.addListener(event, listener); + this.subscriptions.push(() => { + runningInstance.emitter.removeListener(event, listener); + logger.info('removed proxied "%s" listener!', event); + }); + return this; + }; + this.readyState = InterceptorReadyState.APPLIED; + return; + } + logger.info("no running instance found, setting up a new instance..."); + this.setup(); + this.setInstance(); + this.readyState = InterceptorReadyState.APPLIED; + } + /** + * Setup the module augments and stubs necessary for this interceptor. + * This method is not run if there's a running interceptor instance + * to prevent instantiating an interceptor multiple times. + */ + setup() { + } + /** + * Listen to the interceptor's public events. + */ + on(event, listener) { + const logger = this.logger.extend("on"); + if (this.readyState === InterceptorReadyState.DISPOSING || this.readyState === InterceptorReadyState.DISPOSED) { + logger.info("cannot listen to events, already disposed!"); + return this; + } + logger.info('adding "%s" event listener:', event, listener); + this.emitter.on(event, listener); + return this; + } + once(event, listener) { + this.emitter.once(event, listener); + return this; + } + off(event, listener) { + this.emitter.off(event, listener); + return this; + } + removeAllListeners(event) { + this.emitter.removeAllListeners(event); + return this; + } + /** + * Disposes of any side-effects this interceptor has introduced. + */ + dispose() { + const logger = this.logger.extend("dispose"); + if (this.readyState === InterceptorReadyState.DISPOSED) { + logger.info("cannot dispose, already disposed!"); + return; + } + logger.info("disposing the interceptor..."); + this.readyState = InterceptorReadyState.DISPOSING; + if (!this.getInstance()) { + logger.info("no interceptors running, skipping dispose..."); + return; + } + this.clearInstance(); + logger.info("global symbol deleted:", getGlobalSymbol(this.symbol)); + if (this.subscriptions.length > 0) { + logger.info("disposing of %d subscriptions...", this.subscriptions.length); + for (const dispose of this.subscriptions) dispose(); + this.subscriptions = []; + logger.info("disposed of all subscriptions!", this.subscriptions.length); + } + this.emitter.removeAllListeners(); + logger.info("destroyed the listener!"); + this.readyState = InterceptorReadyState.DISPOSED; + } + getInstance() { + const instance = getGlobalSymbol(this.symbol); + this.logger.info("retrieved global instance:", instance?.constructor?.name); + return instance; + } + setInstance() { + setGlobalSymbol(this.symbol, this); + this.logger.info("set global instance!", this.symbol.description); + } + clearInstance() { + deleteGlobalSymbol(this.symbol); + this.logger.info("cleared global instance!", this.symbol.description); + } +}; +function createRequestId() { + return Math.random().toString(16).slice(2); +} + +// node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/lib/browser/resolveWebSocketUrl-C83-x9iE.mjs +function resolveWebSocketUrl(url) { + if (typeof url === "string") return resolveWebSocketUrl(new URL(url, typeof location !== "undefined" ? location.href : void 0)); + if (url.protocol === "http:") url.protocol = "ws:"; + else if (url.protocol === "https:") url.protocol = "wss:"; + if (url.protocol !== "ws:" && url.protocol !== "wss:") + throw new SyntaxError(`Failed to construct 'WebSocket': The URL's scheme must be either 'http', 'https', 'ws', or 'wss'. '${url.protocol}' is not allowed.`); + if (url.hash !== "") throw new SyntaxError(`Failed to construct 'WebSocket': The URL contains a fragment identifier ('${url.hash}'). Fragment identifiers are not allowed in WebSocket URLs.`); + return url.href; +} + +// node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/lib/browser/hasConfigurableGlobal-npXitu1-.mjs +async function emitAsync(emitter, eventName, ...data) { + const listeners = emitter.listeners(eventName); + if (listeners.length === 0) return; + for (const listener of listeners) await listener.apply(emitter, data); +} +function hasConfigurableGlobal(propertyName) { + const descriptor = Object.getOwnPropertyDescriptor(globalThis, propertyName); + if (typeof descriptor === "undefined") return false; + if (typeof descriptor.get === "function" && typeof descriptor.get() === "undefined") return false; + if (typeof descriptor.get === "undefined" && descriptor.value == null) return false; + if (typeof descriptor.set === "undefined" && !descriptor.configurable) { + console.error(`[MSW] Failed to apply interceptor: the global \`${propertyName}\` property is non-configurable. This is likely an issue with your environment. If you are using a framework, please open an issue about this in their repository.`); + return false; + } + return true; +} + +// node_modules/.pnpm/@open-draft+deferred-promise@2.2.0/node_modules/@open-draft/deferred-promise/build/index.mjs +function createDeferredExecutor() { + const executor = (resolve, reject) => { + executor.state = "pending"; + executor.resolve = (data) => { + if (executor.state !== "pending") { + return; + } + executor.result = data; + const onFulfilled = (value) => { + executor.state = "fulfilled"; + return value; + }; + return resolve( + data instanceof Promise ? data : Promise.resolve(data).then(onFulfilled) + ); + }; + executor.reject = (reason) => { + if (executor.state !== "pending") { + return; + } + queueMicrotask(() => { + executor.state = "rejected"; + }); + return reject(executor.rejectionReason = reason); + }; + }; + return executor; +} +var DeferredPromise = class extends Promise { + #executor; + resolve; + reject; + constructor(executor = null) { + const deferredExecutor = createDeferredExecutor(); + super((originalResolve, originalReject) => { + deferredExecutor(originalResolve, originalReject); + executor?.(deferredExecutor.resolve, deferredExecutor.reject); + }); + this.#executor = deferredExecutor; + this.resolve = this.#executor.resolve; + this.reject = this.#executor.reject; + } + get state() { + return this.#executor.state; + } + get rejectionReason() { + return this.#executor.rejectionReason; + } + then(onFulfilled, onRejected) { + return this.#decorate(super.then(onFulfilled, onRejected)); + } + catch(onRejected) { + return this.#decorate(super.catch(onRejected)); + } + finally(onfinally) { + return this.#decorate(super.finally(onfinally)); + } + #decorate(promise) { + return Object.defineProperties(promise, { + resolve: { configurable: true, value: this.resolve }, + reject: { configurable: true, value: this.reject } + }); + } +}; + +// node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/lib/browser/interceptors/WebSocket/index.mjs +function bindEvent(target, event) { + Object.defineProperties(event, { + target: { + value: target, + enumerable: true, + writable: true + }, + currentTarget: { + value: target, + enumerable: true, + writable: true + } + }); + return event; +} +var kCancelable = Symbol("kCancelable"); +var kDefaultPrevented = Symbol("kDefaultPrevented"); +var CancelableMessageEvent = class extends MessageEvent { + constructor(type, init) { + super(type, init); + this[kCancelable] = !!init.cancelable; + this[kDefaultPrevented] = false; + } + get cancelable() { + return this[kCancelable]; + } + set cancelable(nextCancelable) { + this[kCancelable] = nextCancelable; + } + get defaultPrevented() { + return this[kDefaultPrevented]; + } + set defaultPrevented(nextDefaultPrevented) { + this[kDefaultPrevented] = nextDefaultPrevented; + } + preventDefault() { + if (this.cancelable && !this[kDefaultPrevented]) this[kDefaultPrevented] = true; + } +}; +var CloseEvent = class extends Event { + constructor(type, init = {}) { + super(type, init); + this.code = init.code === void 0 ? 0 : init.code; + this.reason = init.reason === void 0 ? "" : init.reason; + this.wasClean = init.wasClean === void 0 ? false : init.wasClean; + } +}; +var CancelableCloseEvent = class extends CloseEvent { + constructor(type, init = {}) { + super(type, init); + this[kCancelable] = !!init.cancelable; + this[kDefaultPrevented] = false; + } + get cancelable() { + return this[kCancelable]; + } + set cancelable(nextCancelable) { + this[kCancelable] = nextCancelable; + } + get defaultPrevented() { + return this[kDefaultPrevented]; + } + set defaultPrevented(nextDefaultPrevented) { + this[kDefaultPrevented] = nextDefaultPrevented; + } + preventDefault() { + if (this.cancelable && !this[kDefaultPrevented]) this[kDefaultPrevented] = true; + } +}; +var kEmitter$1 = Symbol("kEmitter"); +var kBoundListener$1 = Symbol("kBoundListener"); +var WebSocketClientConnection = class { + constructor(socket, transport) { + this.socket = socket; + this.transport = transport; + this.id = createRequestId(); + this.url = new URL(socket.url); + this[kEmitter$1] = new EventTarget(); + this.transport.addEventListener("outgoing", (event) => { + const message = bindEvent(this.socket, new CancelableMessageEvent("message", { + data: event.data, + origin: event.origin, + cancelable: true + })); + this[kEmitter$1].dispatchEvent(message); + if (message.defaultPrevented) event.preventDefault(); + }); + this.transport.addEventListener("close", (event) => { + this[kEmitter$1].dispatchEvent(bindEvent(this.socket, new CloseEvent("close", event))); + }); + } + /** + * Listen for the outgoing events from the connected WebSocket client. + */ + addEventListener(type, listener, options) { + if (!Reflect.has(listener, kBoundListener$1)) { + const boundListener = listener.bind(this.socket); + Object.defineProperty(listener, kBoundListener$1, { + value: boundListener, + enumerable: false, + configurable: false + }); + } + this[kEmitter$1].addEventListener(type, Reflect.get(listener, kBoundListener$1), options); + } + /** + * Removes the listener for the given event. + */ + removeEventListener(event, listener, options) { + this[kEmitter$1].removeEventListener(event, Reflect.get(listener, kBoundListener$1), options); + } + /** + * Send data to the connected client. + */ + send(data) { + this.transport.send(data); + } + /** + * Close the WebSocket connection. + * @param {number} code A status code (see https://www.rfc-editor.org/rfc/rfc6455#section-7.4.1). + * @param {string} reason A custom connection close reason. + */ + close(code, reason) { + this.transport.close(code, reason); + } +}; +var WEBSOCKET_CLOSE_CODE_RANGE_ERROR = "InvalidAccessError: close code out of user configurable range"; +var kPassthroughPromise = Symbol("kPassthroughPromise"); +var kOnSend = Symbol("kOnSend"); +var kClose = Symbol("kClose"); +var WebSocketOverride = class extends EventTarget { + static { + this.CONNECTING = 0; + } + static { + this.OPEN = 1; + } + static { + this.CLOSING = 2; + } + static { + this.CLOSED = 3; + } + constructor(url, protocols) { + super(); + this.CONNECTING = 0; + this.OPEN = 1; + this.CLOSING = 2; + this.CLOSED = 3; + this._onopen = null; + this._onmessage = null; + this._onerror = null; + this._onclose = null; + this.url = resolveWebSocketUrl(url); + this.protocol = ""; + this.extensions = ""; + this.binaryType = "blob"; + this.readyState = this.CONNECTING; + this.bufferedAmount = 0; + this[kPassthroughPromise] = new DeferredPromise(); + queueMicrotask(async () => { + if (await this[kPassthroughPromise]) return; + this.protocol = typeof protocols === "string" ? protocols : Array.isArray(protocols) && protocols.length > 0 ? protocols[0] : ""; + if (this.readyState === this.CONNECTING) { + this.readyState = this.OPEN; + this.dispatchEvent(bindEvent(this, new Event("open"))); + } + }); + } + set onopen(listener) { + this.removeEventListener("open", this._onopen); + this._onopen = listener; + if (listener !== null) this.addEventListener("open", listener); + } + get onopen() { + return this._onopen; + } + set onmessage(listener) { + this.removeEventListener("message", this._onmessage); + this._onmessage = listener; + if (listener !== null) this.addEventListener("message", listener); + } + get onmessage() { + return this._onmessage; + } + set onerror(listener) { + this.removeEventListener("error", this._onerror); + this._onerror = listener; + if (listener !== null) this.addEventListener("error", listener); + } + get onerror() { + return this._onerror; + } + set onclose(listener) { + this.removeEventListener("close", this._onclose); + this._onclose = listener; + if (listener !== null) this.addEventListener("close", listener); + } + get onclose() { + return this._onclose; + } + /** + * @see https://websockets.spec.whatwg.org/#ref-for-dom-websocket-send%E2%91%A0 + */ + send(data) { + if (this.readyState === this.CONNECTING) { + this.close(); + throw new DOMException("InvalidStateError"); + } + if (this.readyState === this.CLOSING || this.readyState === this.CLOSED) return; + this.bufferedAmount += getDataSize(data); + queueMicrotask(() => { + this.bufferedAmount = 0; + this[kOnSend]?.(data); + }); + } + close(code = 1e3, reason) { + invariant(code, WEBSOCKET_CLOSE_CODE_RANGE_ERROR); + invariant(code === 1e3 || code >= 3e3 && code <= 4999, WEBSOCKET_CLOSE_CODE_RANGE_ERROR); + this[kClose](code, reason); + } + [kClose](code = 1e3, reason, wasClean = true) { + if (this.readyState === this.CLOSING || this.readyState === this.CLOSED) return; + this.readyState = this.CLOSING; + queueMicrotask(() => { + this.readyState = this.CLOSED; + this.dispatchEvent(bindEvent(this, new CloseEvent("close", { + code, + reason, + wasClean + }))); + this._onopen = null; + this._onmessage = null; + this._onerror = null; + this._onclose = null; + }); + } + addEventListener(type, listener, options) { + return super.addEventListener(type, listener, options); + } + removeEventListener(type, callback, options) { + return super.removeEventListener(type, callback, options); + } +}; +function getDataSize(data) { + if (typeof data === "string") return data.length; + if (data instanceof Blob) return data.size; + return data.byteLength; +} +var kEmitter = Symbol("kEmitter"); +var kBoundListener = Symbol("kBoundListener"); +var kSend = Symbol("kSend"); +var WebSocketServerConnection = class { + constructor(client, transport, createConnection) { + this.client = client; + this.transport = transport; + this.createConnection = createConnection; + this[kEmitter] = new EventTarget(); + this.mockCloseController = new AbortController(); + this.realCloseController = new AbortController(); + this.transport.addEventListener("outgoing", (event) => { + if (typeof this.realWebSocket === "undefined") return; + queueMicrotask(() => { + if (!event.defaultPrevented) + this[kSend](event.data); + }); + }); + this.transport.addEventListener("incoming", this.handleIncomingMessage.bind(this)); + } + /** + * The `WebSocket` instance connected to the original server. + * Accessing this before calling `server.connect()` will throw. + */ + get socket() { + invariant(this.realWebSocket, 'Cannot access "socket" on the original WebSocket server object: the connection is not open. Did you forget to call `server.connect()`?'); + return this.realWebSocket; + } + /** + * Open connection to the original WebSocket server. + */ + connect() { + invariant(!this.realWebSocket || this.realWebSocket.readyState !== WebSocket.OPEN, 'Failed to call "connect()" on the original WebSocket instance: the connection already open'); + const realWebSocket = this.createConnection(); + realWebSocket.binaryType = this.client.binaryType; + realWebSocket.addEventListener("open", (event) => { + this[kEmitter].dispatchEvent(bindEvent(this.realWebSocket, new Event("open", event))); + }, { once: true }); + realWebSocket.addEventListener("message", (event) => { + this.transport.dispatchEvent(bindEvent(this.realWebSocket, new MessageEvent("incoming", { + data: event.data, + origin: event.origin + }))); + }); + this.client.addEventListener("close", (event) => { + this.handleMockClose(event); + }, { signal: this.mockCloseController.signal }); + realWebSocket.addEventListener("close", (event) => { + this.handleRealClose(event); + }, { signal: this.realCloseController.signal }); + realWebSocket.addEventListener("error", () => { + const errorEvent = bindEvent(realWebSocket, new Event("error", { cancelable: true })); + this[kEmitter].dispatchEvent(errorEvent); + if (!errorEvent.defaultPrevented) this.client.dispatchEvent(bindEvent(this.client, new Event("error"))); + }); + this.realWebSocket = realWebSocket; + } + /** + * Listen for the incoming events from the original WebSocket server. + */ + addEventListener(event, listener, options) { + if (!Reflect.has(listener, kBoundListener)) { + const boundListener = listener.bind(this.client); + Object.defineProperty(listener, kBoundListener, { + value: boundListener, + enumerable: false + }); + } + this[kEmitter].addEventListener(event, Reflect.get(listener, kBoundListener), options); + } + /** + * Remove the listener for the given event. + */ + removeEventListener(event, listener, options) { + this[kEmitter].removeEventListener(event, Reflect.get(listener, kBoundListener), options); + } + /** + * Send data to the original WebSocket server. + * @example + * server.send('hello') + * server.send(new Blob(['hello'])) + * server.send(new TextEncoder().encode('hello')) + */ + send(data) { + this[kSend](data); + } + [kSend](data) { + const { realWebSocket } = this; + invariant(realWebSocket, 'Failed to call "server.send()" for "%s": the connection is not open. Did you forget to call "server.connect()"?', this.client.url); + if (realWebSocket.readyState === WebSocket.CLOSING || realWebSocket.readyState === WebSocket.CLOSED) return; + if (realWebSocket.readyState === WebSocket.CONNECTING) { + realWebSocket.addEventListener("open", () => { + realWebSocket.send(data); + }, { once: true }); + return; + } + realWebSocket.send(data); + } + /** + * Close the actual server connection. + */ + close() { + const { realWebSocket } = this; + invariant(realWebSocket, 'Failed to close server connection for "%s": the connection is not open. Did you forget to call "server.connect()"?', this.client.url); + this.realCloseController.abort(); + if (realWebSocket.readyState === WebSocket.CLOSING || realWebSocket.readyState === WebSocket.CLOSED) return; + realWebSocket.close(); + queueMicrotask(() => { + this[kEmitter].dispatchEvent(bindEvent(this.realWebSocket, new CancelableCloseEvent("close", { + code: 1e3, + cancelable: true + }))); + }); + } + handleIncomingMessage(event) { + const messageEvent = bindEvent(event.target, new CancelableMessageEvent("message", { + data: event.data, + origin: event.origin, + cancelable: true + })); + this[kEmitter].dispatchEvent(messageEvent); + if (!messageEvent.defaultPrevented) this.client.dispatchEvent(bindEvent( + /** + * @note Bind the forwarded original server events + * to the mock WebSocket instance so it would + * dispatch them straight away. + */ + this.client, + new MessageEvent("message", { + data: event.data, + origin: event.origin + }) + )); + } + handleMockClose(_event) { + if (this.realWebSocket) this.realWebSocket.close(); + } + handleRealClose(event) { + this.mockCloseController.abort(); + const closeEvent = bindEvent(this.realWebSocket, new CancelableCloseEvent("close", { + code: event.code, + reason: event.reason, + wasClean: event.wasClean, + cancelable: true + })); + this[kEmitter].dispatchEvent(closeEvent); + if (!closeEvent.defaultPrevented) this.client[kClose](event.code, event.reason); + } +}; +var WebSocketClassTransport = class extends EventTarget { + constructor(socket) { + super(); + this.socket = socket; + this.socket.addEventListener("close", (event) => { + this.dispatchEvent(bindEvent(this.socket, new CloseEvent("close", event))); + }); + this.socket[kOnSend] = (data) => { + this.dispatchEvent(bindEvent(this.socket, new CancelableMessageEvent("outgoing", { + data, + origin: this.socket.url, + cancelable: true + }))); + }; + } + addEventListener(type, callback, options) { + return super.addEventListener(type, callback, options); + } + dispatchEvent(event) { + return super.dispatchEvent(event); + } + send(data) { + queueMicrotask(() => { + if (this.socket.readyState === this.socket.CLOSING || this.socket.readyState === this.socket.CLOSED) return; + const dispatchEvent = () => { + this.socket.dispatchEvent(bindEvent( + /** + * @note Setting this event's "target" to the + * WebSocket override instance is important. + * This way it can tell apart original incoming events + * (must be forwarded to the transport) from the + * mocked message events like the one below + * (must be dispatched on the client instance). + */ + this.socket, + new MessageEvent("message", { + data, + origin: this.socket.url + }) + )); + }; + if (this.socket.readyState === this.socket.CONNECTING) this.socket.addEventListener("open", () => { + dispatchEvent(); + }, { once: true }); + else dispatchEvent(); + }); + } + close(code, reason) { + this.socket[kClose](code, reason); + } +}; +var WebSocketInterceptor = class WebSocketInterceptor2 extends Interceptor { + static { + this.symbol = Symbol("websocket"); + } + constructor() { + super(WebSocketInterceptor2.symbol); + } + checkEnvironment() { + return hasConfigurableGlobal("WebSocket"); + } + setup() { + const originalWebSocketDescriptor = Object.getOwnPropertyDescriptor(globalThis, "WebSocket"); + const WebSocketProxy = new Proxy(globalThis.WebSocket, { construct: (target, args, newTarget) => { + const [url, protocols] = args; + const createConnection = () => { + return Reflect.construct(target, args, newTarget); + }; + const socket = new WebSocketOverride(url, protocols); + const transport = new WebSocketClassTransport(socket); + queueMicrotask(async () => { + try { + const server = new WebSocketServerConnection(socket, transport, createConnection); + const hasConnectionListeners = this.emitter.listenerCount("connection") > 0; + await emitAsync(this.emitter, "connection", { + client: new WebSocketClientConnection(socket, transport), + server, + info: { protocols } + }); + if (hasConnectionListeners) socket[kPassthroughPromise].resolve(false); + else { + socket[kPassthroughPromise].resolve(true); + server.connect(); + server.addEventListener("open", () => { + socket.dispatchEvent(bindEvent(socket, new Event("open"))); + if (server["realWebSocket"]) socket.protocol = server["realWebSocket"].protocol; + }); + } + } catch (error2) { + if (error2 instanceof Error) { + socket.dispatchEvent(new Event("error")); + if (socket.readyState !== WebSocket.CLOSING && socket.readyState !== WebSocket.CLOSED) socket[kClose](1011, error2.message, false); + console.error(error2); + } + } + }); + return socket; + } }); + Object.defineProperty(globalThis, "WebSocket", { + value: WebSocketProxy, + configurable: true + }); + this.subscriptions.push(() => { + Object.defineProperty(globalThis, "WebSocket", originalWebSocketDescriptor); + }); + } +}; + +// src/browser/setup-worker.ts +import { + defineNetwork, + NetworkReadyState +} from '../core/experimental/define-network.mjs'; +import { InterceptorSource as InterceptorSource2 } from '../core/experimental/sources/interceptor-source.mjs'; +import { fromLegacyOnUnhandledRequest } from '../core/experimental/compat.mjs'; +import { devUtils as devUtils5 } from '../core/utils/internal/devUtils.mjs'; + +// src/browser/utils/supports.ts +function supportsServiceWorker() { + return typeof navigator !== "undefined" && "serviceWorker" in navigator && typeof location !== "undefined" && location.protocol !== "file:"; +} +function supportsReadableStreamTransfer() { + try { + const stream = new ReadableStream({ + start: (controller) => controller.close() + }); + const message = new MessageChannel(); + message.port1.postMessage(stream, [stream]); + return true; + } catch { + return false; + } +} + +// node_modules/.pnpm/@open-draft+deferred-promise@3.0.0/node_modules/@open-draft/deferred-promise/build/index.mjs +function createDeferredExecutor2() { + const executor = ((resolve, reject) => { + executor.state = "pending"; + executor.resolve = (data) => { + if (executor.state !== "pending") return; + executor.result = data; + const onFulfilled = (value) => { + executor.state = "fulfilled"; + return value; + }; + return resolve(data instanceof Promise ? data : Promise.resolve(data).then(onFulfilled)); + }; + executor.reject = (reason) => { + if (executor.state !== "pending") return; + queueMicrotask(() => { + executor.state = "rejected"; + }); + return reject(executor.rejectionReason = reason); + }; + }); + return executor; +} +var DeferredPromise2 = class extends Promise { + #executor; + resolve; + reject; + constructor(executor = null) { + const deferredExecutor = createDeferredExecutor2(); + super((originalResolve, originalReject) => { + deferredExecutor(originalResolve, originalReject); + executor?.(deferredExecutor.resolve, deferredExecutor.reject); + }); + this.#executor = deferredExecutor; + this.resolve = this.#executor.resolve; + this.reject = this.#executor.reject; + } + get state() { + return this.#executor.state; + } + get rejectionReason() { + return this.#executor.rejectionReason; + } + then(onFulfilled, onRejected) { + return this.#decorate(super.then(onFulfilled, onRejected)); + } + catch(onRejected) { + return this.#decorate(super.catch(onRejected)); + } + finally(onfinally) { + return this.#decorate(super.finally(onfinally)); + } + #decorate(promise) { + return Object.defineProperties(promise, { + resolve: { + configurable: true, + value: this.resolve + }, + reject: { + configurable: true, + value: this.reject + } + }); + } +}; + +// node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/lib/browser/getRawRequest-BTaNLFr0.mjs +var IS_PATCHED_MODULE = Symbol("isPatchedModule"); +var InterceptorError = class InterceptorError2 extends Error { + constructor(message) { + super(message); + this.name = "InterceptorError"; + Object.setPrototypeOf(this, InterceptorError2.prototype); + } +}; +var RequestController = class RequestController2 { + static { + this.PENDING = 0; + } + static { + this.PASSTHROUGH = 1; + } + static { + this.RESPONSE = 2; + } + static { + this.ERROR = 3; + } + constructor(request, source) { + this.request = request; + this.source = source; + this.readyState = RequestController2.PENDING; + this.handled = new DeferredPromise(); + } + get #handled() { + return this.handled; + } + /** + * Perform this request as-is. + */ + async passthrough() { + invariant.as(InterceptorError, this.readyState === RequestController2.PENDING, 'Failed to passthrough the "%s %s" request: the request has already been handled', this.request.method, this.request.url); + this.readyState = RequestController2.PASSTHROUGH; + await this.source.passthrough(); + this.#handled.resolve(); + } + /** + * Respond to this request with the given `Response` instance. + * + * @example + * controller.respondWith(new Response()) + * controller.respondWith(Response.json({ id })) + * controller.respondWith(Response.error()) + */ + respondWith(response) { + invariant.as(InterceptorError, this.readyState === RequestController2.PENDING, 'Failed to respond to the "%s %s" request with "%d %s": the request has already been handled (%d)', this.request.method, this.request.url, response.status, response.statusText || "OK", this.readyState); + this.readyState = RequestController2.RESPONSE; + this.#handled.resolve(); + this.source.respondWith(response); + } + /** + * Error this request with the given reason. + * + * @example + * controller.errorWith() + * controller.errorWith(new Error('Oops!')) + * controller.errorWith({ message: 'Oops!'}) + */ + errorWith(reason) { + invariant.as(InterceptorError, this.readyState === RequestController2.PENDING, 'Failed to error the "%s %s" request with "%s": the request has already been handled (%d)', this.request.method, this.request.url, reason?.toString(), this.readyState); + this.readyState = RequestController2.ERROR; + this.source.errorWith(reason); + this.#handled.resolve(); + } +}; +function canParseUrl(url) { + try { + new URL(url); + return true; + } catch (_error) { + return false; + } +} +function getValueBySymbol(symbolName, source) { + const symbol = Object.getOwnPropertySymbols(source).find((symbol$1) => { + return symbol$1.description === symbolName; + }); + if (symbol) return Reflect.get(source, symbol); +} +var FetchResponse = class FetchResponse2 extends Response { + static { + this.STATUS_CODES_WITHOUT_BODY = [ + 101, + 103, + 204, + 205, + 304 + ]; + } + static { + this.STATUS_CODES_WITH_REDIRECT = [ + 301, + 302, + 303, + 307, + 308 + ]; + } + static isConfigurableStatusCode(status) { + return status >= 200 && status <= 599; + } + static isRedirectResponse(status) { + return FetchResponse2.STATUS_CODES_WITH_REDIRECT.includes(status); + } + /** + * Returns a boolean indicating whether the given response status + * code represents a response that can have a body. + */ + static isResponseWithBody(status) { + return !FetchResponse2.STATUS_CODES_WITHOUT_BODY.includes(status); + } + static setUrl(url, response) { + if (!url || url === "about:" || !canParseUrl(url)) return; + const state = getValueBySymbol("state", response); + if (state) state.urlList.push(new URL(url)); + else Object.defineProperty(response, "url", { + value: url, + enumerable: true, + configurable: true, + writable: false + }); + } + /** + * Parses the given raw HTTP headers into a Fetch API `Headers` instance. + */ + static parseRawHeaders(rawHeaders) { + const headers = new Headers(); + for (let line = 0; line < rawHeaders.length; line += 2) headers.append(rawHeaders[line], rawHeaders[line + 1]); + return headers; + } + constructor(body, init = {}) { + const status = init.status ?? 200; + const safeStatus = FetchResponse2.isConfigurableStatusCode(status) ? status : 200; + const finalBody = FetchResponse2.isResponseWithBody(status) ? body : null; + super(finalBody, { + status: safeStatus, + statusText: init.statusText, + headers: init.headers + }); + if (status !== safeStatus) { + const state = getValueBySymbol("state", this); + if (state) state.status = status; + else Object.defineProperty(this, "status", { + value: status, + enumerable: true, + configurable: true, + writable: false + }); + } + FetchResponse2.setUrl(init.url, this); + } +}; +var kRawRequest = Symbol("kRawRequest"); +function setRawRequest(request, rawRequest) { + Reflect.set(request, kRawRequest, rawRequest); +} + +// node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/lib/browser/bufferUtils-BiiO6HZv.mjs +var encoder = new TextEncoder(); +function encodeBuffer(text) { + return encoder.encode(text); +} +function decodeBuffer(buffer, encoding) { + return new TextDecoder(encoding).decode(buffer); +} +function toArrayBuffer(array) { + return array.buffer.slice(array.byteOffset, array.byteOffset + array.byteLength); +} + +// src/browser/sources/service-worker-source.ts +import { NetworkSource } from '../core/experimental/sources/network-source.mjs'; +import { RequestHandler } from '../core/handlers/RequestHandler.mjs'; +import { + HttpNetworkFrame, + ResponseEvent +} from '../core/experimental/frames/http-frame.mjs'; +import { HttpResponse } from '../core/HttpResponse.mjs'; +import { toResponseInit } from '../core/utils/toResponseInit.mjs'; +import { devUtils as devUtils3 } from '../core/utils/internal/devUtils.mjs'; + +// node_modules/.pnpm/until-async@3.0.2/node_modules/until-async/lib/index.js +async function until(callback) { + try { + return [null, await callback().catch((error2) => { + throw error2; + })]; + } catch (error2) { + return [error2, null]; + } +} + +// src/browser/utils/get-worker-instance.ts +import { devUtils } from '../core/utils/internal/devUtils.mjs'; + +// src/browser/utils/getAbsoluteWorkerUrl.ts +function getAbsoluteWorkerUrl(workerUrl) { + return new URL(workerUrl, location.href).href; +} + +// src/browser/utils/get-worker-by-registration.ts +function getWorkerByRegistration(registration, absoluteWorkerUrl, findWorker) { + const allStates = [ + registration.active, + registration.installing, + registration.waiting + ]; + const relevantStates = allStates.filter((state) => { + return state != null; + }); + const worker = relevantStates.find((worker2) => { + return findWorker(worker2.scriptURL, absoluteWorkerUrl); + }); + return worker || null; +} + +// src/browser/utils/get-worker-instance.ts +var getWorkerInstance = async (url, options = {}, findWorker) => { + const absoluteWorkerUrl = getAbsoluteWorkerUrl(url); + const mockRegistrations = await navigator.serviceWorker.getRegistrations().then( + (registrations) => registrations.filter( + (registration) => getWorkerByRegistration(registration, absoluteWorkerUrl, findWorker) + ) + ); + if (!navigator.serviceWorker.controller && mockRegistrations.length > 0) { + location.reload(); + } + const [existingRegistration] = mockRegistrations; + if (existingRegistration) { + existingRegistration.update(); + return [ + getWorkerByRegistration( + existingRegistration, + absoluteWorkerUrl, + findWorker + ), + existingRegistration + ]; + } + const [registrationError, registrationResult] = await until(async () => { + const registration = await navigator.serviceWorker.register(url, options); + return [ + // Compare existing worker registration by its worker URL, + // to prevent irrelevant workers to resolve here (such as Codesandbox worker). + getWorkerByRegistration(registration, absoluteWorkerUrl, findWorker), + registration + ]; + }); + if (registrationError) { + const isWorkerMissing = registrationError.message.includes("(404)"); + if (isWorkerMissing) { + const scopeUrl = new URL(options?.scope || "/", location.href); + throw new Error( + devUtils.formatMessage(`Failed to register a Service Worker for scope ('${scopeUrl.href}') with script ('${absoluteWorkerUrl}'): Service Worker script does not exist at the given path. + +Did you forget to run "npx msw init "? + +Learn more about creating the Service Worker script: https://mswjs.io/docs/cli/init`) + ); + } + throw new Error( + devUtils.formatMessage( + "Failed to register the Service Worker:\n\n%s", + registrationError.message + ) + ); + } + return registrationResult; +}; + +// node_modules/.pnpm/rettime@0.11.11/node_modules/rettime/build/lens-list.mjs +var LensList = class { + #list; + #lens; + constructor() { + this.#list = []; + this.#lens = /* @__PURE__ */ new Map(); + } + get [Symbol.iterator]() { + return this.#list[Symbol.iterator].bind(this.#list); + } + entries() { + return this.#lens.entries(); + } + /** + * Return an order-sensitive list of values by the given key. + */ + get(key) { + return this.#lens.get(key) || []; + } + /** + * Return an order-sensitive list of all values. + */ + getAll() { + return this.#list.map(([, value]) => value); + } + /** + * Append a new value to the given key. + */ + append(key, value) { + this.#list.push([key, value]); + this.#openLens(key, (list) => list.push(value)); + } + /** + * Prepend a new value to the given key. + */ + prepend(key, value) { + this.#list.unshift([key, value]); + this.#openLens(key, (list) => list.unshift(value)); + } + /** + * Delete the value belonging to the given key. + * Returns `true` if the value was present and removed, `false` otherwise. + */ + delete(key, value) { + if (this.size === 0) return false; + const values = this.#lens.get(key); + if (!values) return false; + const index = values.indexOf(value); + if (index === -1) return false; + values.splice(index, 1); + this.#list.splice(this.#list.findIndex((item) => item[0] === key && item[1] === value), 1); + return true; + } + /** + * Delete all values belogning to the given key. + */ + deleteAll(key) { + if (this.size === 0) return; + this.#list = this.#list.filter((item) => item[0] !== key); + this.#lens.delete(key); + } + get size() { + return this.#list.length; + } + clear() { + if (this.size === 0) return; + this.#list.length = 0; + this.#lens.clear(); + } + #openLens(key, setter) { + setter(this.#lens.get(key) || this.#lens.set(key, []).get(key)); + } +}; + +// node_modules/.pnpm/rettime@0.11.11/node_modules/rettime/build/index.mjs +var kDefaultPrevented2 = Symbol("kDefaultPrevented"); +var kPropagationStopped = Symbol("kPropagationStopped"); +var kImmediatePropagationStopped = Symbol("kImmediatePropagationStopped"); +var TypedEvent = class extends MessageEvent { + /** + * @note Keep a placeholder property with the return type + * because the type must be set somewhere in order to be + * correctly associated and inferred from the event. + */ + #returnType; + [kDefaultPrevented2]; + [kPropagationStopped]; + [kImmediatePropagationStopped]; + constructor(...args) { + super(args[0], args[1]); + this[kDefaultPrevented2] = false; + } + get defaultPrevented() { + return this[kDefaultPrevented2]; + } + preventDefault() { + super.preventDefault(); + this[kDefaultPrevented2] = true; + } + stopImmediatePropagation() { + super.stopImmediatePropagation(); + this[kImmediatePropagationStopped] = true; + } +}; +var Emitter2 = class { + #listeners; + #listenerOptions; + #listenerAbortCleanups; + #typelessListeners; + #hookListeners; + #hookListenerOptions; + #hookListenerAbortCleanups; + hooks; + constructor() { + this.#listeners = new LensList(); + this.#listenerOptions = /* @__PURE__ */ new WeakMap(); + this.#listenerAbortCleanups = /* @__PURE__ */ new WeakMap(); + this.#typelessListeners = /* @__PURE__ */ new WeakSet(); + this.#hookListeners = new LensList(); + this.#hookListenerOptions = /* @__PURE__ */ new WeakMap(); + this.#hookListenerAbortCleanups = /* @__PURE__ */ new WeakMap(); + this.hooks = { + on: (hook, callback, options) => { + if (options?.signal?.aborted) return; + if (options?.once) { + const original = callback; + const wrapper = ((...args) => { + this.#deleteHookListener(hook, wrapper); + return original(...args); + }); + callback = wrapper; + } + this.#hookListeners.append(hook, callback); + if (options) this.#hookListenerOptions.set(callback, options); + if (options?.signal) { + const { signal } = options; + const onAbort = () => { + this.#deleteHookListener(hook, callback); + }; + signal.addEventListener("abort", onAbort, { once: true }); + this.#hookListenerAbortCleanups.set(callback, () => { + signal.removeEventListener("abort", onAbort); + }); + } + }, + removeListener: (hook, callback) => { + this.#deleteHookListener(hook, callback); + } + }; + } + #deleteHookListener(hook, callback) { + this.#hookListeners.delete(hook, callback); + const cleanup = this.#hookListenerAbortCleanups.get(callback); + if (cleanup) { + cleanup(); + this.#hookListenerAbortCleanups.delete(callback); + } + } + #deleteListener(type, listener) { + const removed = this.#listeners.delete(type, listener); + const cleanup = this.#listenerAbortCleanups.get(listener); + if (cleanup) { + cleanup(); + this.#listenerAbortCleanups.delete(listener); + } + return removed; + } + /** + * Adds a listener for the given event type. + */ + on(type, listener, options) { + this.#addListener(type, listener, options); + return this; + } + /** + * Adds a one-time listener for the given event type. + */ + once(type, listener, options) { + return this.on(type, listener, { + ...options || {}, + once: true + }); + } + /** + * Prepends a listener for the given event type. + */ + earlyOn(type, listener, options) { + this.#addListener(type, listener, options, "prepend"); + return this; + } + /** + * Prepends a one-time listener for the given event type. + */ + earlyOnce(type, listener, options) { + return this.earlyOn(type, listener, { + ...options || {}, + once: true + }); + } + /** + * Emits the given typed event. + * + * @returns {boolean} Returns `true` if the event had any listeners, `false` otherwise. + */ + emit(event) { + if (this.#listeners.size === 0) return false; + const hasListeners = this.listenerCount(event.type) > 0; + const proxiedEvent = this.#proxyEvent(event); + for (const listener of this.#matchListeners(event.type)) { + if (proxiedEvent.event[kPropagationStopped] != null && proxiedEvent.event[kPropagationStopped] !== this) { + proxiedEvent.revoke(); + return false; + } + if (proxiedEvent.event[kImmediatePropagationStopped]) break; + this.#callListener(proxiedEvent.event, listener); + } + proxiedEvent.revoke(); + return hasListeners; + } + /** + * Emits the given typed event and returns a promise that resolves + * when all the listeners for that event have settled. + * + * @returns {Promise>} A promise that resolves + * with the return values of all listeners. + */ + async emitAsPromise(event) { + if (this.#listeners.size === 0) return []; + const pendingListeners = []; + const proxiedEvent = this.#proxyEvent(event); + for (const listener of this.#matchListeners(event.type)) { + if (proxiedEvent.event[kPropagationStopped] != null && proxiedEvent.event[kPropagationStopped] !== this) { + proxiedEvent.revoke(); + return []; + } + if (proxiedEvent.event[kImmediatePropagationStopped]) break; + const returnValue = await Promise.resolve(this.#callListener(proxiedEvent.event, listener)); + if (!this.#isTypelessListener(listener)) pendingListeners.push(returnValue); + } + proxiedEvent.revoke(); + return Promise.allSettled(pendingListeners).then((results) => { + return results.map((result) => result.status === "fulfilled" ? result.value : result.reason); + }); + } + /** + * Emits the given event and returns a generator that yields + * the result of each listener in the order of their registration. + * This way, you stop exhausting the listeners once you get the expected value. + */ + *emitAsGenerator(event) { + if (this.#listeners.size === 0) return; + const proxiedEvent = this.#proxyEvent(event); + for (const listener of this.#matchListeners(event.type)) { + if (proxiedEvent.event[kPropagationStopped] != null && proxiedEvent.event[kPropagationStopped] !== this) { + proxiedEvent.revoke(); + return; + } + if (proxiedEvent.event[kImmediatePropagationStopped]) break; + const returnValue = this.#callListener(proxiedEvent.event, listener); + if (!this.#isTypelessListener(listener)) yield returnValue; + } + proxiedEvent.revoke(); + } + /** + * Removes a listener for the given event type. + */ + removeListener(type, listener) { + const options = this.#listenerOptions.get(listener); + if (!this.#deleteListener(type, listener)) return; + for (const hook of this.#hookListeners.get("removeListener").slice()) hook(type, listener, options); + } + /** + * Removes all listeners for the given event type. + * If no event type is provided, removes all existing listeners. + */ + removeAllListeners(type) { + if (type == null) { + for (const [listenerType, listeners$1] of this.#listeners.entries()) while (listeners$1.length > 0) this.removeListener(listenerType, listeners$1[0]); + for (const [hookType, hookListener] of [...this.#hookListeners]) if (!this.#hookListenerOptions.get(hookListener)?.persist) this.#deleteHookListener(hookType, hookListener); + return; + } + const listeners = this.listeners(type); + while (listeners.length > 0) this.removeListener(type, listeners[0]); + } + /** + * Returns the list of listeners for the given event type. + * If no even type is provided, returns all listeners. + */ + listeners(type) { + if (type == null) return this.#listeners.getAll(); + return this.#listeners.get(type); + } + /** + * Returns the number of listeners for the given event type. + * If no even type is provided, returns the total number of listeners. + */ + listenerCount(type) { + if (type == null) return this.#listeners.size; + return this.listeners(type).length; + } + #addListener(type, listener, options, insertMode = "append") { + if (options?.signal?.aborted) return; + for (const hook of this.#hookListeners.get("newListener").slice()) hook(type, listener, options); + if (type === "*") this.#typelessListeners.add(listener); + if (insertMode === "prepend") this.#listeners.prepend(type, listener); + else this.#listeners.append(type, listener); + if (options) { + this.#listenerOptions.set(listener, options); + if (options.signal) { + const { signal } = options; + const onAbort = () => { + this.removeListener(type, listener); + }; + signal.addEventListener("abort", onAbort, { once: true }); + this.#listenerAbortCleanups.set(listener, () => { + signal.removeEventListener("abort", onAbort); + }); + } + } + } + #proxyEvent(event) { + const { stopPropagation } = event; + event.stopPropagation = () => { + event[kPropagationStopped] = this; + stopPropagation.call(event); + }; + return { + event, + revoke() { + event.stopPropagation = stopPropagation; + } + }; + } + #callListener(event, listener) { + for (const hook of this.#hookListeners.get("beforeEmit").slice()) if (hook(event) === false) return; + const returnValue = listener.call(this, event); + const options = this.#listenerOptions.get(listener); + if (options?.once) { + const type = this.#isTypelessListener(listener) ? "*" : event.type; + if (this.#deleteListener(type, listener)) for (const hook of this.#hookListeners.get("removeListener").slice()) hook(type, listener, options); + } + return returnValue; + } + /** + * Return a list of all event listeners relevant for the given event type. + * This includes the explicit event listeners and also typeless event listeners. + * + * @note Snapshot the matching listeners before yielding. Listeners can add or + * remove other listeners during emission (e.g. `earlyOn` unshifts `#list`), + * which would otherwise shift the live iterator and re-yield prior entries. + */ + *#matchListeners(type) { + const snapshot = []; + for (const [key, listener] of this.#listeners) if (key === "*" || key === type) snapshot.push(listener); + yield* snapshot; + } + #isTypelessListener(listener) { + return this.#typelessListeners.has(listener); + } +}; + +// src/browser/utils/workerChannel.ts +import { isObject } from '../core/utils/internal/isObject.mjs'; +var SUPPORTS_SERVICE_WORKER = supportsServiceWorker(); +var WorkerEvent = class extends TypedEvent { + #workerEvent; + constructor(workerEvent) { + const type = workerEvent.data.type; + const data = workerEvent.data.payload; + super( + // @ts-expect-error Troublesome `TypedEvent` extension. + type, + { data } + ); + this.#workerEvent = workerEvent; + } + get ports() { + return this.#workerEvent.ports; + } + /** + * Reply directly to this event using its `MessagePort`. + */ + postMessage(type, ...rest) { + this.#workerEvent.ports[0].postMessage( + { type, data: rest[0] }, + { transfer: rest[1] } + ); + } +}; +var WorkerChannel = class extends Emitter2 { + #getWorker; + #controller; + constructor(options) { + super(); + invariant( + SUPPORTS_SERVICE_WORKER, + "Failed to open a WorkerChannel: Service Worker is not supported in this environment." + ); + this.#getWorker = options.getWorker; + this.#controller = new AbortController(); + navigator.serviceWorker.addEventListener( + "message", + async (event) => { + const worker = await this.#getWorker(); + if (event.source != null && event.source !== worker) { + return; + } + if (event.data && isObject(event.data) && "type" in event.data) { + this.emit(new WorkerEvent(event)); + } + }, + { + signal: this.#controller.signal + } + ); + } + /** + * Send data to the Service Worker controlling this client. + * This triggers the `message` event listener on ServiceWorkerGlobalScope. + */ + postMessage(type) { + invariant( + SUPPORTS_SERVICE_WORKER, + "Failed to post message on a WorkerChannel: the Service Worker API is unavailable in this environment. This is likely an issue with MSW. Please report it on GitHub: https://github.com/mswjs/msw/issues" + ); + this.#getWorker().then((worker) => { + worker.postMessage(type); + }); + } + /** + * Terminal teardown. Removes the `navigator.serviceWorker` message listener + * and all emitter subscriptions. The channel is not usable afterwards. + */ + terminate() { + this.#controller.abort(); + this.removeAllListeners(); + } +}; + +// src/browser/utils/pruneGetRequestBody.ts +function pruneGetRequestBody(request) { + if (["HEAD", "GET"].includes(request.method)) { + return void 0; + } + return request.body; +} + +// src/browser/utils/deserializeRequest.ts +function deserializeRequest(serializedRequest) { + return new Request(serializedRequest.url, { + ...serializedRequest, + body: pruneGetRequestBody(serializedRequest) + }); +} + +// src/browser/utils/validate-worker-scope.ts +import { devUtils as devUtils2 } from '../core/utils/internal/devUtils.mjs'; +function validateWorkerScope(registration) { + if (!location.href.startsWith(registration.scope)) { + devUtils2.warn( + `Cannot intercept requests on this page because it's outside of the worker's scope ("${registration.scope}"). If you wish to mock API requests on this page, you must resolve this scope issue. + +- (Recommended) Register the worker at the root level ("/") of your application. +- Set the "Service-Worker-Allowed" response header to allow out-of-scope workers.` + ); + } +} + +// src/browser/utils/should-invalidate-worker.ts +function shouldInvalidateWorker(prevOptions, nextOptions) { + return prevOptions.findWorker !== nextOptions.findWorker || prevOptions.serviceWorker.url !== nextOptions.serviceWorker.url || JSON.stringify(prevOptions.serviceWorker.options) !== JSON.stringify(nextOptions.serviceWorker.options); +} + +// src/browser/sources/service-worker-source.ts +var ServiceWorkerSource = class _ServiceWorkerSource extends NetworkSource { + static #current; + /** + * Create a new Service Worker source or reuse an existing one. + * These sources act as a singleton and only get recreated if the options change. + */ + static async from(options) { + if (_ServiceWorkerSource.#current == null) { + _ServiceWorkerSource.#current = new _ServiceWorkerSource(options); + } else if (shouldInvalidateWorker(_ServiceWorkerSource.#current.#options, options)) { + await _ServiceWorkerSource.#current.terminate(); + _ServiceWorkerSource.#current = new _ServiceWorkerSource(options); + } + return _ServiceWorkerSource.#current; + } + #options; + #frames; + #channel; + #listenerController; + #clientPromise; + #keepAliveInterval; + #stoppedAt; + workerPromise; + constructor(options) { + super(); + invariant( + supportsServiceWorker(), + "Failed to use Service Worker as the network source: the Service Worker API is not supported in this environment" + ); + this.#options = options; + this.#frames = /* @__PURE__ */ new Map(); + this.workerPromise = new DeferredPromise2(); + this.#channel = new WorkerChannel({ + getWorker: () => this.workerPromise.then(([worker]) => worker) + }); + } + async enable() { + if (this.workerPromise.state === "fulfilled" && typeof this.#stoppedAt == "undefined") { + devUtils3.warn( + 'Found a redundant "worker.start()" call. Note that starting the worker while mocking is already enabled will have no effect. Consider removing this "worker.start()" call.' + ); + return this.workerPromise.then(([, registration2]) => registration2); + } + this.#stoppedAt = void 0; + this.#channel.removeAllListeners(); + this.#frames.clear(); + this.#listenerController = new AbortController(); + const [worker, registration] = await this.#startWorker(); + if (worker.state !== "activated") { + const controller = new AbortController(); + const activationPromise = new DeferredPromise2(); + activationPromise.then(() => controller.abort()); + worker.addEventListener( + "statechange", + () => { + if (worker.state === "activated") { + activationPromise.resolve(); + } + }, + { + signal: controller.signal + } + ); + await activationPromise; + } + this.#channel.postMessage("MOCK_ACTIVATE"); + const clientConfirmationPromise = new DeferredPromise2(); + this.#clientPromise = clientConfirmationPromise; + this.#channel.once("MOCKING_ENABLED", (event) => { + clientConfirmationPromise.resolve(event.data.client); + }); + await clientConfirmationPromise; + if (!this.#options.quiet) { + this.#printStartMessage(); + } + return registration; + } + disable() { + if (typeof this.#stoppedAt !== "undefined") { + devUtils3.warn( + `Found a redundant "worker.stop()" call. Notice that stopping the worker after it has already been stopped has no effect. Consider removing this "worker.stop()" call.` + ); + return; + } + this.#stoppedAt = Date.now(); + this.#listenerController?.abort(); + this.#listenerController = void 0; + this.#channel.postMessage("CLIENT_CLOSED"); + if (!this.#options.quiet) { + this.#printStopMessage(); + } + } + /** + * Terminal teardown. Unregisters the Service Worker, tears down the channel, + * and clears timers. Called when the singleton is being replaced with one + * that has different options. The instance is not usable afterwards. + */ + async terminate() { + if (this.#keepAliveInterval != null) { + clearInterval(this.#keepAliveInterval); + this.#keepAliveInterval = void 0; + } + this.#frames.clear(); + this.#channel.terminate(); + this.#listenerController?.abort(); + this.#listenerController = void 0; + if (this.workerPromise.state === "fulfilled") { + const [, registration] = await this.workerPromise; + await registration.unregister(); + } + if (_ServiceWorkerSource.#current === this) { + _ServiceWorkerSource.#current = void 0; + } + } + async #startWorker() { + if (this.#keepAliveInterval) { + clearInterval(this.#keepAliveInterval); + } + const workerUrl = this.#options.serviceWorker.url; + const [worker, registration] = await getWorkerInstance( + workerUrl, + this.#options.serviceWorker.options, + this.#options.findWorker || this.#defaultFindWorker + ); + if (worker == null) { + const missingWorkerMessage = this.#options?.findWorker ? devUtils3.formatMessage( + `Failed to locate the Service Worker registration using a custom "findWorker" predicate. + +Please ensure that the custom predicate properly locates the Service Worker registration at "%s". +More details: https://mswjs.io/docs/api/setup-worker/start#findworker + `, + workerUrl + ) : devUtils3.formatMessage( + `Failed to locate the Service Worker registration. + +This most likely means that the worker script URL "%s" cannot resolve against the actual public hostname (%s). This may happen if your application runs behind a proxy, or has a dynamic hostname. + +Please consider using a custom "serviceWorker.url" option to point to the actual worker script location, or a custom "findWorker" option to resolve the Service Worker registration manually. More details: https://mswjs.io/docs/api/setup-worker/start`, + workerUrl, + location.host + ); + throw new Error(missingWorkerMessage); + } + if (this.workerPromise.state === "pending") { + this.workerPromise.resolve([worker, registration]); + } else { + this.workerPromise = new DeferredPromise2((resolve) => { + resolve([worker, registration]); + }); + } + this.#channel.on("REQUEST", this.#handleRequest.bind(this)); + this.#channel.on("RESPONSE", this.#handleResponse.bind(this)); + window.addEventListener( + "beforeunload", + () => { + if (worker.state !== "redundant") { + this.#channel.postMessage("CLIENT_CLOSED"); + } + clearInterval(this.#keepAliveInterval); + window.postMessage({ type: "msw/worker:stop" }); + }, + { + signal: this.#listenerController?.signal + } + ); + await this.#checkWorkerIntegrity().catch((error2) => { + devUtils3.error( + "Error while checking the worker script integrity. Please report this on GitHub (https://github.com/mswjs/msw/issues) and include the original error below." + ); + console.error(error2); + }); + this.#keepAliveInterval = window.setInterval(() => { + this.#channel.postMessage("KEEPALIVE_REQUEST"); + }, 5e3); + if (!this.#options.quiet) { + validateWorkerScope(registration); + } + return [worker, registration]; + } + async #handleRequest(event) { + if (this.#stoppedAt && event.data.interceptedAt > this.#stoppedAt) { + return event.postMessage("PASSTHROUGH"); + } + const request = deserializeRequest(event.data); + RequestHandler.cache.set(request, request.clone()); + const frame = new ServiceWorkerHttpNetworkFrame({ + event, + request + }); + this.#frames.set(event.data.id, frame); + await this.queue(frame); + } + async #handleResponse(event) { + const { request, response, isMockedResponse } = event.data; + const frame = this.#frames.get(request.id); + if (response.type?.includes("opaque")) { + this.#frames.delete(request.id); + frame?.events.removeAllListeners(); + return; + } + this.#frames.delete(request.id); + if (frame == null) { + return; + } + const fetchRequest = deserializeRequest(request); + const fetchResponse = response.status === 0 ? Response.error() : new FetchResponse( + /** + * Responses may be streams here, but when we create a response object + * with null-body status codes, like 204, 205, 304 Response will + * throw when passed a non-null body, so ensure it's null here + * for those codes + */ + FetchResponse.isResponseWithBody(response.status) ? response.body : null, + { + ...response, + /** + * Set response URL if it's not set already. + * @see https://github.com/mswjs/msw/issues/2030 + * @see https://developer.mozilla.org/en-US/docs/Web/API/Response/url + */ + url: request.url + } + ); + try { + frame.events.emit( + new ResponseEvent( + isMockedResponse ? "response:mocked" : "response:bypass", + { + requestId: frame.data.id, + request: fetchRequest, + response: fetchResponse, + isMockedResponse + } + ) + ); + } finally { + frame.events.removeAllListeners(); + } + } + #defaultFindWorker = (workerUrl, mockServiceWorkerUrl) => { + return workerUrl === mockServiceWorkerUrl; + }; + async #checkWorkerIntegrity() { + const integrityCheckPromise = new DeferredPromise2(); + this.#channel.postMessage("INTEGRITY_CHECK_REQUEST"); + this.#channel.once("INTEGRITY_CHECK_RESPONSE", (event) => { + const { checksum, packageVersion } = event.data; + if (checksum !== "4db4a41e972cec1b64cc569c66952d82") { + devUtils3.warn( + `The currently registered Service Worker has been generated by a different version of MSW (${packageVersion}) and may not be fully compatible with the installed version. + +It's recommended you update your worker script by running this command: + + \u2022 npx msw init + +You can also automate this process and make the worker script update automatically upon the library installations. Read more: https://mswjs.io/docs/cli/init.` + ); + } + integrityCheckPromise.resolve(); + }); + return integrityCheckPromise; + } + async #printStartMessage() { + if (this.workerPromise.state === "rejected") { + return; + } + invariant( + this.#clientPromise != null, + "[ServiceWorkerSource] Failed to print a start message: client confirmation not received" + ); + const client = await this.#clientPromise; + const [worker, registration] = await this.workerPromise; + console.groupCollapsed( + `%c${devUtils3.formatMessage("Mocking enabled.")}`, + "color:orangered;font-weight:bold;" + ); + console.log( + "%cDocumentation: %chttps://mswjs.io/docs", + "font-weight:bold", + "font-weight:normal" + ); + console.log("Found an issue? https://github.com/mswjs/msw/issues"); + console.log("Worker script URL:", worker.scriptURL); + console.log("Worker scope:", registration.scope); + if (client) { + console.log("Client ID: %s (%s)", client.id, client.frameType); + } + console.groupEnd(); + } + #printStopMessage() { + console.log( + `%c${devUtils3.formatMessage("Mocking disabled.")}`, + "color:orangered;font-weight:bold;" + ); + } +}; +var ServiceWorkerHttpNetworkFrame = class extends HttpNetworkFrame { + #event; + constructor(options) { + super({ request: options.request }); + this.#event = options.event; + } + passthrough() { + this.#event.postMessage("PASSTHROUGH"); + } + respondWith(response) { + if (response) { + this.#respondWith(response); + } + } + errorWith(reason) { + if (reason instanceof Response) { + return this.respondWith(reason); + } + devUtils3.warn( + `Uncaught exception in the request handler for "%s %s". This exception has been gracefully handled as a 500 response, however, it's strongly recommended to resolve this error, as it indicates a mistake in your code. If you wish to mock an error response, please see this guide: https://mswjs.io/docs/http/mocking-responses/error-responses`, + this.data.request.method, + this.data.request.url + ); + const error2 = reason instanceof Error ? reason : new Error(reason?.toString() || "Request failure"); + this.respondWith( + HttpResponse.json( + { + name: error2.name, + message: error2.message, + stack: error2.stack + }, + { + status: 500, + statusText: "Request Handler Error" + } + ) + ); + } + async #respondWith(response) { + let responseBody; + let transfer; + const responseInit = toResponseInit(response); + if (supportsReadableStreamTransfer()) { + responseBody = response.body; + transfer = response.body == null ? void 0 : [response.body]; + } else { + responseBody = response.body == null ? null : await response.clone().arrayBuffer(); + } + this.#event.postMessage( + "MOCK_RESPONSE", + { + ...responseInit, + body: responseBody + }, + transfer + ); + } +}; + +// node_modules/.pnpm/@open-draft+until@2.1.0/node_modules/@open-draft/until/lib/index.mjs +var until2 = async (promise) => { + try { + const data = await promise().catch((error2) => { + throw error2; + }); + return { error: null, data }; + } catch (error2) { + return { error: error2, data: null }; + } +}; + +// node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/lib/browser/handleRequest-D7kpTI5U.mjs +function isObject2(value, loose = false) { + return loose ? Object.prototype.toString.call(value).startsWith("[object ") : Object.prototype.toString.call(value) === "[object Object]"; +} +function isPropertyAccessible(obj, key) { + try { + obj[key]; + return true; + } catch { + return false; + } +} +function createServerErrorResponse(body) { + return new Response(JSON.stringify(body instanceof Error ? { + name: body.name, + message: body.message, + stack: body.stack + } : body), { + status: 500, + statusText: "Unhandled Exception", + headers: { "Content-Type": "application/json" } + }); +} +function isResponseError(response) { + return response != null && response instanceof Response && isPropertyAccessible(response, "type") && response.type === "error"; +} +function isResponseLike(value) { + return isObject2(value, true) && isPropertyAccessible(value, "status") && isPropertyAccessible(value, "statusText") && isPropertyAccessible(value, "bodyUsed"); +} +function isNodeLikeError(error2) { + if (error2 == null) return false; + if (!(error2 instanceof Error)) return false; + return "code" in error2 && "errno" in error2; +} +async function handleRequest(options) { + const handleResponse = async (response) => { + if (response instanceof Error) { + await options.controller.errorWith(response); + return true; + } + if (isResponseError(response)) { + await options.controller.respondWith(response); + return true; + } + if (isResponseLike(response)) { + await options.controller.respondWith(response); + return true; + } + if (isObject2(response)) { + await options.controller.errorWith(response); + return true; + } + return false; + }; + const handleResponseError = async (error2) => { + if (error2 instanceof InterceptorError) throw result.error; + if (isNodeLikeError(error2)) { + await options.controller.errorWith(error2); + return true; + } + if (error2 instanceof Response) return await handleResponse(error2); + return false; + }; + const requestAbortPromise = new DeferredPromise(); + if (options.request.signal) { + if (options.request.signal.aborted) { + await options.controller.errorWith(options.request.signal.reason); + return; + } + options.request.signal.addEventListener("abort", () => { + requestAbortPromise.reject(options.request.signal.reason); + }, { once: true }); + } + const result = await until2(async () => { + const requestListenersPromise = emitAsync(options.emitter, "request", { + requestId: options.requestId, + request: options.request, + controller: options.controller + }); + await Promise.race([ + requestAbortPromise, + requestListenersPromise, + options.controller.handled + ]); + }); + if (requestAbortPromise.state === "rejected") { + await options.controller.errorWith(requestAbortPromise.rejectionReason); + return; + } + if (result.error) { + if (await handleResponseError(result.error)) return; + if (options.emitter.listenerCount("unhandledException") > 0) { + const unhandledExceptionController = new RequestController(options.request, { + passthrough() { + }, + async respondWith(response) { + await handleResponse(response); + }, + async errorWith(reason) { + await options.controller.errorWith(reason); + } + }); + await emitAsync(options.emitter, "unhandledException", { + error: result.error, + request: options.request, + requestId: options.requestId, + controller: unhandledExceptionController + }); + if (unhandledExceptionController.readyState !== RequestController.PENDING) return; + } + await options.controller.respondWith(createServerErrorResponse(result.error)); + return; + } + if (options.controller.readyState === RequestController.PENDING) return await options.controller.passthrough(); + return options.controller.handled; +} + +// node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/lib/browser/fetch-DdKEdDOR.mjs +function createNetworkError(cause) { + return Object.assign(/* @__PURE__ */ new TypeError("Failed to fetch"), { cause }); +} +var REQUEST_BODY_HEADERS = [ + "content-encoding", + "content-language", + "content-location", + "content-type", + "content-length" +]; +var kRedirectCount = Symbol("kRedirectCount"); +async function followFetchRedirect(request, response) { + if (response.status !== 303 && request.body != null) return Promise.reject(createNetworkError()); + const requestUrl = new URL(request.url); + let locationUrl; + try { + locationUrl = new URL(response.headers.get("location"), request.url); + } catch (error2) { + return Promise.reject(createNetworkError(error2)); + } + if (!(locationUrl.protocol === "http:" || locationUrl.protocol === "https:")) return Promise.reject(createNetworkError("URL scheme must be a HTTP(S) scheme")); + if (Reflect.get(request, kRedirectCount) > 20) return Promise.reject(createNetworkError("redirect count exceeded")); + Object.defineProperty(request, kRedirectCount, { value: (Reflect.get(request, kRedirectCount) || 0) + 1 }); + if (request.mode === "cors" && (locationUrl.username || locationUrl.password) && !sameOrigin(requestUrl, locationUrl)) return Promise.reject(createNetworkError('cross origin not allowed for request mode "cors"')); + const requestInit = {}; + if ([301, 302].includes(response.status) && request.method === "POST" || response.status === 303 && !["HEAD", "GET"].includes(request.method)) { + requestInit.method = "GET"; + requestInit.body = null; + REQUEST_BODY_HEADERS.forEach((headerName) => { + request.headers.delete(headerName); + }); + } + if (!sameOrigin(requestUrl, locationUrl)) { + request.headers.delete("authorization"); + request.headers.delete("proxy-authorization"); + request.headers.delete("cookie"); + request.headers.delete("host"); + } + requestInit.headers = request.headers; + const finalResponse = await fetch(new Request(locationUrl, requestInit)); + Object.defineProperty(finalResponse, "redirected", { + value: true, + configurable: true + }); + return finalResponse; +} +function sameOrigin(left, right) { + if (left.origin === right.origin && left.origin === "null") return true; + if (left.protocol === right.protocol && left.hostname === right.hostname && left.port === right.port) return true; + return false; +} +var BrotliDecompressionStream = class extends TransformStream { + constructor() { + console.warn("[Interceptors]: Brotli decompression of response streams is not supported in the browser"); + super({ transform(chunk, controller) { + controller.enqueue(chunk); + } }); + } +}; +var PipelineStream = class extends TransformStream { + constructor(transformStreams, ...strategies) { + super({}, ...strategies); + const readable = [super.readable, ...transformStreams].reduce((readable$1, transform) => readable$1.pipeThrough(transform)); + Object.defineProperty(this, "readable", { get() { + return readable; + } }); + } +}; +function parseContentEncoding(contentEncoding) { + return contentEncoding.toLowerCase().split(",").map((coding) => coding.trim()); +} +function createDecompressionStream(contentEncoding) { + if (contentEncoding === "") return null; + const codings = parseContentEncoding(contentEncoding); + if (codings.length === 0) return null; + return new PipelineStream(codings.reduceRight((transformers, coding) => { + if (coding === "gzip" || coding === "x-gzip") return transformers.concat(new DecompressionStream("gzip")); + else if (coding === "deflate") return transformers.concat(new DecompressionStream("deflate")); + else if (coding === "br") return transformers.concat(new BrotliDecompressionStream()); + else transformers.length = 0; + return transformers; + }, [])); +} +function decompressResponse(response) { + if (response.body === null) return null; + const decompressionStream = createDecompressionStream(response.headers.get("content-encoding") || ""); + if (!decompressionStream) return null; + response.body.pipeTo(decompressionStream.writable); + return decompressionStream.readable; +} +var FetchInterceptor = class FetchInterceptor2 extends Interceptor { + static { + this.symbol = Symbol("fetch"); + } + constructor() { + super(FetchInterceptor2.symbol); + } + checkEnvironment() { + return hasConfigurableGlobal("fetch"); + } + async setup() { + const pureFetch = globalThis.fetch; + invariant(!pureFetch[IS_PATCHED_MODULE], 'Failed to patch the "fetch" module: already patched.'); + globalThis.fetch = async (input, init) => { + const requestId = createRequestId(); + const resolvedInput = typeof input === "string" && typeof location !== "undefined" && !canParseUrl(input) ? new URL(input, location.href) : input; + const request = new Request(resolvedInput, init); + if (input instanceof Request) setRawRequest(request, input); + const responsePromise = new DeferredPromise(); + const controller = new RequestController(request, { + passthrough: async () => { + this.logger.info("request has not been handled, passthrough..."); + const requestCloneForResponseEvent = request.clone(); + const { error: responseError, data: originalResponse } = await until2(() => pureFetch(request)); + if (responseError) return responsePromise.reject(responseError); + this.logger.info("original fetch performed", originalResponse); + if (this.emitter.listenerCount("response") > 0) { + this.logger.info('emitting the "response" event...'); + const responseClone = originalResponse.clone(); + await emitAsync(this.emitter, "response", { + response: responseClone, + isMockedResponse: false, + request: requestCloneForResponseEvent, + requestId + }); + } + responsePromise.resolve(originalResponse); + }, + respondWith: async (rawResponse) => { + if (isResponseError(rawResponse)) { + this.logger.info("request has errored!", { response: rawResponse }); + responsePromise.reject(createNetworkError(rawResponse)); + return; + } + this.logger.info("received mocked response!", { rawResponse }); + const decompressedStream = decompressResponse(rawResponse); + const response = decompressedStream === null ? rawResponse : new FetchResponse(decompressedStream, rawResponse); + FetchResponse.setUrl(request.url, response); + if (FetchResponse.isRedirectResponse(response.status)) { + if (request.redirect === "error") { + responsePromise.reject(createNetworkError("unexpected redirect")); + return; + } + if (request.redirect === "follow") { + followFetchRedirect(request, response).then((response$1) => { + responsePromise.resolve(response$1); + }, (reason) => { + responsePromise.reject(reason); + }); + return; + } + } + if (this.emitter.listenerCount("response") > 0) { + this.logger.info('emitting the "response" event...'); + await emitAsync(this.emitter, "response", { + response: response.clone(), + isMockedResponse: true, + request, + requestId + }); + } + responsePromise.resolve(response); + }, + errorWith: (reason) => { + this.logger.info("request has been aborted!", { reason }); + responsePromise.reject(reason); + } + }); + this.logger.info("[%s] %s", request.method, request.url); + this.logger.info("awaiting for the mocked response..."); + this.logger.info('emitting the "request" event for %s listener(s)...', this.emitter.listenerCount("request")); + await handleRequest({ + request, + requestId, + emitter: this.emitter, + controller + }); + return responsePromise; + }; + Object.defineProperty(globalThis.fetch, IS_PATCHED_MODULE, { + enumerable: true, + configurable: true, + value: true + }); + this.subscriptions.push(() => { + Object.defineProperty(globalThis.fetch, IS_PATCHED_MODULE, { value: void 0 }); + globalThis.fetch = pureFetch; + this.logger.info('restored native "globalThis.fetch"!', globalThis.fetch.name); + }); + } +}; + +// node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/lib/browser/XMLHttpRequest-BvxZV0WU.mjs +function concatArrayBuffer(left, right) { + const result = new Uint8Array(left.byteLength + right.byteLength); + result.set(left, 0); + result.set(right, left.byteLength); + return result; +} +var EventPolyfill = class { + constructor(type, options) { + this.NONE = 0; + this.CAPTURING_PHASE = 1; + this.AT_TARGET = 2; + this.BUBBLING_PHASE = 3; + this.type = ""; + this.srcElement = null; + this.currentTarget = null; + this.eventPhase = 0; + this.isTrusted = true; + this.composed = false; + this.cancelable = true; + this.defaultPrevented = false; + this.bubbles = true; + this.lengthComputable = true; + this.loaded = 0; + this.total = 0; + this.cancelBubble = false; + this.returnValue = true; + this.type = type; + this.target = options?.target || null; + this.currentTarget = options?.currentTarget || null; + this.timeStamp = Date.now(); + } + composedPath() { + return []; + } + initEvent(type, bubbles, cancelable) { + this.type = type; + this.bubbles = !!bubbles; + this.cancelable = !!cancelable; + } + preventDefault() { + this.defaultPrevented = true; + } + stopPropagation() { + } + stopImmediatePropagation() { + } +}; +var ProgressEventPolyfill = class extends EventPolyfill { + constructor(type, init) { + super(type); + this.lengthComputable = init?.lengthComputable || false; + this.composed = init?.composed || false; + this.loaded = init?.loaded || 0; + this.total = init?.total || 0; + } +}; +var SUPPORTS_PROGRESS_EVENT = typeof ProgressEvent !== "undefined"; +function createEvent(target, type, init) { + const progressEvents = [ + "error", + "progress", + "loadstart", + "loadend", + "load", + "timeout", + "abort" + ]; + const ProgressEventClass = SUPPORTS_PROGRESS_EVENT ? ProgressEvent : ProgressEventPolyfill; + return progressEvents.includes(type) ? new ProgressEventClass(type, { + lengthComputable: true, + loaded: init?.loaded || 0, + total: init?.total || 0 + }) : new EventPolyfill(type, { + target, + currentTarget: target + }); +} +function findPropertySource(target, propertyName) { + if (!(propertyName in target)) return null; + if (Object.prototype.hasOwnProperty.call(target, propertyName)) return target; + const prototype = Reflect.getPrototypeOf(target); + return prototype ? findPropertySource(prototype, propertyName) : null; +} +function createProxy(target, options) { + return new Proxy(target, optionsToProxyHandler(options)); +} +function optionsToProxyHandler(options) { + const { constructorCall, methodCall, getProperty, setProperty } = options; + const handler = {}; + if (typeof constructorCall !== "undefined") handler.construct = function(target, args, newTarget) { + const next = Reflect.construct.bind(null, target, args, newTarget); + return constructorCall.call(newTarget, args, next); + }; + handler.set = function(target, propertyName, nextValue) { + const next = () => { + const propertySource = findPropertySource(target, propertyName) || target; + const ownDescriptors = Reflect.getOwnPropertyDescriptor(propertySource, propertyName); + if (typeof ownDescriptors?.set !== "undefined") { + ownDescriptors.set.apply(target, [nextValue]); + return true; + } + return Reflect.defineProperty(propertySource, propertyName, { + writable: true, + enumerable: true, + configurable: true, + value: nextValue + }); + }; + if (typeof setProperty !== "undefined") return setProperty.call(target, [propertyName, nextValue], next); + return next(); + }; + handler.get = function(target, propertyName, receiver) { + const next = () => target[propertyName]; + const value = typeof getProperty !== "undefined" ? getProperty.call(target, [propertyName, receiver], next) : next(); + if (typeof value === "function") return (...args) => { + const next$1 = value.bind(target, ...args); + if (typeof methodCall !== "undefined") return methodCall.call(target, [propertyName, args], next$1); + return next$1(); + }; + return value; + }; + return handler; +} +function isDomParserSupportedType(type) { + return [ + "application/xhtml+xml", + "application/xml", + "image/svg+xml", + "text/html", + "text/xml" + ].some((supportedType) => { + return type.startsWith(supportedType); + }); +} +function parseJson(data) { + try { + return JSON.parse(data); + } catch (_) { + return null; + } +} +function createResponse(request, body) { + return new FetchResponse(FetchResponse.isResponseWithBody(request.status) ? body : null, { + url: request.responseURL, + status: request.status, + statusText: request.statusText, + headers: createHeadersFromXMLHttpRequestHeaders(request.getAllResponseHeaders()) + }); +} +function createHeadersFromXMLHttpRequestHeaders(headersString) { + const headers = new Headers(); + const lines = headersString.split(/[\r\n]+/); + for (const line of lines) { + if (line.trim() === "") continue; + const [name, ...parts] = line.split(": "); + const value = parts.join(": "); + headers.append(name, value); + } + return headers; +} +async function getBodyByteLength(input) { + const explicitContentLength = input.headers.get("content-length"); + if (explicitContentLength != null && explicitContentLength !== "") return Number(explicitContentLength); + return (await input.arrayBuffer()).byteLength; +} +var kIsRequestHandled = Symbol("kIsRequestHandled"); +var IS_NODE2 = isNodeProcess(); +var kFetchRequest = Symbol("kFetchRequest"); +var XMLHttpRequestController = class { + constructor(initialRequest, logger) { + this.initialRequest = initialRequest; + this.logger = logger; + this.method = "GET"; + this.url = null; + this[kIsRequestHandled] = false; + this.events = /* @__PURE__ */ new Map(); + this.uploadEvents = /* @__PURE__ */ new Map(); + this.requestId = createRequestId(); + this.requestHeaders = new Headers(); + this.responseBuffer = new Uint8Array(); + this.request = createProxy(initialRequest, { + setProperty: ([propertyName, nextValue], invoke) => { + switch (propertyName) { + case "ontimeout": { + const eventName = propertyName.slice(2); + this.request.addEventListener(eventName, nextValue); + return invoke(); + } + default: + return invoke(); + } + }, + methodCall: ([methodName, args], invoke) => { + switch (methodName) { + case "open": { + const [method, url] = args; + if (typeof url === "undefined") { + this.method = "GET"; + this.url = toAbsoluteUrl(method); + } else { + this.method = method; + this.url = toAbsoluteUrl(url); + } + this.logger = this.logger.extend(`${this.method} ${this.url.href}`); + this.logger.info("open", this.method, this.url.href); + return invoke(); + } + case "addEventListener": { + const [eventName, listener] = args; + this.registerEvent(eventName, listener); + this.logger.info("addEventListener", eventName, listener); + return invoke(); + } + case "setRequestHeader": { + const [name, value] = args; + this.requestHeaders.set(name, value); + this.logger.info("setRequestHeader", name, value); + return invoke(); + } + case "send": { + const [body] = args; + this.request.addEventListener("load", () => { + if (typeof this.onResponse !== "undefined") { + const fetchResponse = createResponse( + this.request, + /** + * The `response` property is the right way to read + * the ambiguous response body, as the request's "responseType" may differ. + * @see https://xhr.spec.whatwg.org/#the-response-attribute + */ + this.request.response + ); + this.onResponse.call(this, { + response: fetchResponse, + isMockedResponse: this[kIsRequestHandled], + request: fetchRequest, + requestId: this.requestId + }); + } + }); + const requestBody = typeof body === "string" ? encodeBuffer(body) : body; + const fetchRequest = this.toFetchApiRequest(requestBody); + this[kFetchRequest] = fetchRequest.clone(); + queueMicrotask(() => { + (this.onRequest?.call(this, { + request: fetchRequest, + requestId: this.requestId + }) || Promise.resolve()).finally(() => { + if (!this[kIsRequestHandled]) { + this.logger.info("request callback settled but request has not been handled (readystate %d), performing as-is...", this.request.readyState); + if (IS_NODE2) this.request.setRequestHeader(INTERNAL_REQUEST_ID_HEADER_NAME, this.requestId); + return invoke(); + } + }); + }); + break; + } + default: + return invoke(); + } + } + }); + define(this.request, "upload", createProxy(this.request.upload, { + setProperty: ([propertyName, nextValue], invoke) => { + switch (propertyName) { + case "onloadstart": + case "onprogress": + case "onaboart": + case "onerror": + case "onload": + case "ontimeout": + case "onloadend": { + const eventName = propertyName.slice(2); + this.registerUploadEvent(eventName, nextValue); + } + } + return invoke(); + }, + methodCall: ([methodName, args], invoke) => { + switch (methodName) { + case "addEventListener": { + const [eventName, listener] = args; + this.registerUploadEvent(eventName, listener); + this.logger.info("upload.addEventListener", eventName, listener); + return invoke(); + } + } + } + })); + } + registerEvent(eventName, listener) { + const nextEvents = (this.events.get(eventName) || []).concat(listener); + this.events.set(eventName, nextEvents); + this.logger.info('registered event "%s"', eventName, listener); + } + registerUploadEvent(eventName, listener) { + const nextEvents = (this.uploadEvents.get(eventName) || []).concat(listener); + this.uploadEvents.set(eventName, nextEvents); + this.logger.info('registered upload event "%s"', eventName, listener); + } + /** + * Responds to the current request with the given + * Fetch API `Response` instance. + */ + async respondWith(response) { + this[kIsRequestHandled] = true; + if (this[kFetchRequest]) { + const totalRequestBodyLength = await getBodyByteLength(this[kFetchRequest]); + this.trigger("loadstart", this.request.upload, { + loaded: 0, + total: totalRequestBodyLength + }); + this.trigger("progress", this.request.upload, { + loaded: totalRequestBodyLength, + total: totalRequestBodyLength + }); + this.trigger("load", this.request.upload, { + loaded: totalRequestBodyLength, + total: totalRequestBodyLength + }); + this.trigger("loadend", this.request.upload, { + loaded: totalRequestBodyLength, + total: totalRequestBodyLength + }); + } + this.logger.info("responding with a mocked response: %d %s", response.status, response.statusText); + define(this.request, "status", response.status); + define(this.request, "statusText", response.statusText); + define(this.request, "responseURL", this.url.href); + this.request.getResponseHeader = new Proxy(this.request.getResponseHeader, { apply: (_, __, args) => { + this.logger.info("getResponseHeader", args[0]); + if (this.request.readyState < this.request.HEADERS_RECEIVED) { + this.logger.info("headers not received yet, returning null"); + return null; + } + const headerValue = response.headers.get(args[0]); + this.logger.info('resolved response header "%s" to', args[0], headerValue); + return headerValue; + } }); + this.request.getAllResponseHeaders = new Proxy(this.request.getAllResponseHeaders, { apply: () => { + this.logger.info("getAllResponseHeaders"); + if (this.request.readyState < this.request.HEADERS_RECEIVED) { + this.logger.info("headers not received yet, returning empty string"); + return ""; + } + const allHeaders = Array.from(response.headers.entries()).map(([headerName, headerValue]) => { + return `${headerName}: ${headerValue}`; + }).join("\r\n"); + this.logger.info("resolved all response headers to", allHeaders); + return allHeaders; + } }); + Object.defineProperties(this.request, { + response: { + enumerable: true, + configurable: false, + get: () => this.response + }, + responseText: { + enumerable: true, + configurable: false, + get: () => this.responseText + }, + responseXML: { + enumerable: true, + configurable: false, + get: () => this.responseXML + } + }); + const totalResponseBodyLength = await getBodyByteLength(response.clone()); + this.logger.info("calculated response body length", totalResponseBodyLength); + this.trigger("loadstart", this.request, { + loaded: 0, + total: totalResponseBodyLength + }); + this.setReadyState(this.request.HEADERS_RECEIVED); + this.setReadyState(this.request.LOADING); + const finalizeResponse = () => { + this.logger.info("finalizing the mocked response..."); + this.setReadyState(this.request.DONE); + this.trigger("load", this.request, { + loaded: this.responseBuffer.byteLength, + total: totalResponseBodyLength + }); + this.trigger("loadend", this.request, { + loaded: this.responseBuffer.byteLength, + total: totalResponseBodyLength + }); + }; + if (response.body) { + this.logger.info("mocked response has body, streaming..."); + const reader = response.body.getReader(); + const readNextResponseBodyChunk = async () => { + const { value, done } = await reader.read(); + if (done) { + this.logger.info("response body stream done!"); + finalizeResponse(); + return; + } + if (value) { + this.logger.info("read response body chunk:", value); + this.responseBuffer = concatArrayBuffer(this.responseBuffer, value); + this.trigger("progress", this.request, { + loaded: this.responseBuffer.byteLength, + total: totalResponseBodyLength + }); + } + readNextResponseBodyChunk(); + }; + readNextResponseBodyChunk(); + } else finalizeResponse(); + } + responseBufferToText() { + return decodeBuffer(this.responseBuffer); + } + get response() { + this.logger.info("getResponse (responseType: %s)", this.request.responseType); + if (this.request.readyState !== this.request.DONE) return null; + switch (this.request.responseType) { + case "json": { + const responseJson = parseJson(this.responseBufferToText()); + this.logger.info("resolved response JSON", responseJson); + return responseJson; + } + case "arraybuffer": { + const arrayBuffer = toArrayBuffer(this.responseBuffer); + this.logger.info("resolved response ArrayBuffer", arrayBuffer); + return arrayBuffer; + } + case "blob": { + const mimeType = this.request.getResponseHeader("Content-Type") || "text/plain"; + const responseBlob = new Blob([this.responseBufferToText()], { type: mimeType }); + this.logger.info("resolved response Blob (mime type: %s)", responseBlob, mimeType); + return responseBlob; + } + default: { + const responseText = this.responseBufferToText(); + this.logger.info('resolving "%s" response type as text', this.request.responseType, responseText); + return responseText; + } + } + } + get responseText() { + invariant(this.request.responseType === "" || this.request.responseType === "text", "InvalidStateError: The object is in invalid state."); + if (this.request.readyState !== this.request.LOADING && this.request.readyState !== this.request.DONE) return ""; + const responseText = this.responseBufferToText(); + this.logger.info('getResponseText: "%s"', responseText); + return responseText; + } + get responseXML() { + invariant(this.request.responseType === "" || this.request.responseType === "document", "InvalidStateError: The object is in invalid state."); + if (this.request.readyState !== this.request.DONE) return null; + const contentType = this.request.getResponseHeader("Content-Type") || ""; + if (typeof DOMParser === "undefined") { + console.warn("Cannot retrieve XMLHttpRequest response body as XML: DOMParser is not defined. You are likely using an environment that is not browser or does not polyfill browser globals correctly."); + return null; + } + if (isDomParserSupportedType(contentType)) return new DOMParser().parseFromString(this.responseBufferToText(), contentType); + return null; + } + errorWith(error2) { + this[kIsRequestHandled] = true; + this.logger.info("responding with an error"); + this.setReadyState(this.request.DONE); + this.trigger("error", this.request); + this.trigger("loadend", this.request); + } + /** + * Transitions this request's `readyState` to the given one. + */ + setReadyState(nextReadyState) { + this.logger.info("setReadyState: %d -> %d", this.request.readyState, nextReadyState); + if (this.request.readyState === nextReadyState) { + this.logger.info("ready state identical, skipping transition..."); + return; + } + define(this.request, "readyState", nextReadyState); + this.logger.info("set readyState to: %d", nextReadyState); + if (nextReadyState !== this.request.UNSENT) { + this.logger.info('triggering "readystatechange" event...'); + this.trigger("readystatechange", this.request); + } + } + /** + * Triggers given event on the `XMLHttpRequest` instance. + */ + trigger(eventName, target, options) { + const callback = target[`on${eventName}`]; + const event = createEvent(target, eventName, options); + this.logger.info('trigger "%s"', eventName, options || ""); + if (typeof callback === "function") { + this.logger.info('found a direct "%s" callback, calling...', eventName); + callback.call(target, event); + } + const events = target instanceof XMLHttpRequestUpload ? this.uploadEvents : this.events; + for (const [registeredEventName, listeners] of events) if (registeredEventName === eventName) { + this.logger.info('found %d listener(s) for "%s" event, calling...', listeners.length, eventName); + listeners.forEach((listener) => listener.call(target, event)); + } + } + /** + * Converts this `XMLHttpRequest` instance into a Fetch API `Request` instance. + */ + toFetchApiRequest(body) { + this.logger.info("converting request to a Fetch API Request..."); + const resolvedBody = body instanceof Document ? body.documentElement.innerText : body; + const fetchRequest = new Request(this.url.href, { + method: this.method, + headers: this.requestHeaders, + credentials: this.request.withCredentials ? "include" : "same-origin", + body: ["GET", "HEAD"].includes(this.method.toUpperCase()) ? null : resolvedBody + }); + define(fetchRequest, "headers", createProxy(fetchRequest.headers, { methodCall: ([methodName, args], invoke) => { + switch (methodName) { + case "append": + case "set": { + const [headerName, headerValue] = args; + this.request.setRequestHeader(headerName, headerValue); + break; + } + case "delete": { + const [headerName] = args; + console.warn(`XMLHttpRequest: Cannot remove a "${headerName}" header from the Fetch API representation of the "${fetchRequest.method} ${fetchRequest.url}" request. XMLHttpRequest headers cannot be removed.`); + break; + } + } + return invoke(); + } })); + setRawRequest(fetchRequest, this.request); + this.logger.info("converted request to a Fetch API Request!", fetchRequest); + return fetchRequest; + } +}; +function toAbsoluteUrl(url) { + if (typeof location === "undefined") return new URL(url); + return new URL(url.toString(), location.href); +} +function define(target, property, value) { + Reflect.defineProperty(target, property, { + writable: true, + enumerable: true, + value + }); +} +function createXMLHttpRequestProxy({ emitter, logger }) { + return new Proxy(globalThis.XMLHttpRequest, { construct(target, args, newTarget) { + logger.info("constructed new XMLHttpRequest"); + const originalRequest = Reflect.construct(target, args, newTarget); + const prototypeDescriptors = Object.getOwnPropertyDescriptors(target.prototype); + for (const propertyName in prototypeDescriptors) Reflect.defineProperty(originalRequest, propertyName, prototypeDescriptors[propertyName]); + const xhrRequestController = new XMLHttpRequestController(originalRequest, logger); + xhrRequestController.onRequest = async function({ request, requestId }) { + const controller = new RequestController(request, { + passthrough: () => { + this.logger.info("no mocked response received, performing request as-is..."); + }, + respondWith: async (response) => { + if (isResponseError(response)) { + this.errorWith(/* @__PURE__ */ new TypeError("Network error")); + return; + } + await this.respondWith(response); + }, + errorWith: (reason) => { + this.logger.info("request errored!", { error: reason }); + if (reason instanceof Error) this.errorWith(reason); + } + }); + this.logger.info("awaiting mocked response..."); + this.logger.info('emitting the "request" event for %s listener(s)...', emitter.listenerCount("request")); + await handleRequest({ + request, + requestId, + controller, + emitter + }); + }; + xhrRequestController.onResponse = async function({ response, isMockedResponse, request, requestId }) { + this.logger.info('emitting the "response" event for %s listener(s)...', emitter.listenerCount("response")); + emitter.emit("response", { + response, + isMockedResponse, + request, + requestId + }); + }; + return xhrRequestController.request; + } }); +} +var XMLHttpRequestInterceptor = class XMLHttpRequestInterceptor2 extends Interceptor { + static { + this.interceptorSymbol = Symbol("xhr"); + } + constructor() { + super(XMLHttpRequestInterceptor2.interceptorSymbol); + } + checkEnvironment() { + return hasConfigurableGlobal("XMLHttpRequest"); + } + setup() { + const logger = this.logger.extend("setup"); + logger.info('patching "XMLHttpRequest" module...'); + const PureXMLHttpRequest = globalThis.XMLHttpRequest; + invariant(!PureXMLHttpRequest[IS_PATCHED_MODULE], 'Failed to patch the "XMLHttpRequest" module: already patched.'); + globalThis.XMLHttpRequest = createXMLHttpRequestProxy({ + emitter: this.emitter, + logger: this.logger + }); + logger.info('native "XMLHttpRequest" module patched!', globalThis.XMLHttpRequest.name); + Object.defineProperty(globalThis.XMLHttpRequest, IS_PATCHED_MODULE, { + enumerable: true, + configurable: true, + value: true + }); + this.subscriptions.push(() => { + Object.defineProperty(globalThis.XMLHttpRequest, IS_PATCHED_MODULE, { value: void 0 }); + globalThis.XMLHttpRequest = PureXMLHttpRequest; + logger.info('native "XMLHttpRequest" module restored!', globalThis.XMLHttpRequest.name); + }); + } +}; + +// src/browser/sources/fallback-http-source.ts +import { InterceptorSource } from '../core/experimental/sources/interceptor-source.mjs'; +import { devUtils as devUtils4 } from '../core/utils/internal/devUtils.mjs'; +var FallbackHttpSource = class extends InterceptorSource { + constructor(options) { + super({ + interceptors: [new XMLHttpRequestInterceptor(), new FetchInterceptor()] + }); + this.options = options; + } + enable() { + super.enable(); + if (!this.options.quiet) { + this.#printStartMessage(); + } + } + disable() { + super.disable(); + if (!this.options.quiet) { + this.#printStopMessage(); + } + } + #printStartMessage() { + console.groupCollapsed( + `%c${devUtils4.formatMessage("Mocking enabled (fallback mode).")}`, + "color:orangered;font-weight:bold;" + ); + console.log( + "%cDocumentation: %chttps://mswjs.io/docs", + "font-weight:bold", + "font-weight:normal" + ); + console.log("Found an issue? https://github.com/mswjs/msw/issues"); + console.groupEnd(); + } + #printStopMessage() { + console.log( + `%c${devUtils4.formatMessage("Mocking disabled.")}`, + "color:orangered;font-weight:bold;" + ); + } +}; + +// src/browser/setup-worker.ts +var DEFAULT_WORKER_URL = "/mockServiceWorker.js"; +function setupWorker(...handlers) { + invariant( + !isNodeProcess(), + devUtils5.formatMessage( + "Failed to execute `setupWorker` in a non-browser environment" + ) + ); + const network = defineNetwork({ + sources: [], + handlers + }); + return { + async start(options) { + if (options?.waitUntilReady != null) { + devUtils5.warn( + `The "waitUntilReady" option has been deprecated. Please remove it from this "worker.start()" call. Follow the recommended Browser integration (https://mswjs.io/docs/integrations/browser) to eliminate any race conditions between the Service Worker registration and any requests made by your application on initial render.` + ); + } + if (network.readyState === NetworkReadyState.ENABLED) { + devUtils5.warn( + 'Found a redundant "worker.start()" call. Note that starting the worker while mocking is already enabled will have no effect. Consider removing this "worker.start()" call.' + ); + return; + } + const httpSource = supportsServiceWorker() ? await ServiceWorkerSource.from({ + serviceWorker: { + url: options?.serviceWorker?.url?.toString() || DEFAULT_WORKER_URL, + options: options?.serviceWorker?.options + }, + findWorker: options?.findWorker, + quiet: options?.quiet + }) : new FallbackHttpSource({ + quiet: options?.quiet + }); + network.configure({ + sources: [ + httpSource, + new InterceptorSource2({ + interceptors: [new WebSocketInterceptor()] + }) + ], + onUnhandledFrame: fromLegacyOnUnhandledRequest(() => { + return options?.onUnhandledRequest || "warn"; + }), + context: { + quiet: options?.quiet + } + }); + await network.enable(); + if (httpSource instanceof ServiceWorkerSource) { + const [, registration] = await httpSource.workerPromise; + return registration; + } + }, + stop() { + if (network.readyState === NetworkReadyState.DISABLED) { + devUtils5.warn( + `Found a redundant "worker.stop()" call. Notice that stopping the worker after it has already been stopped has no effect. Consider removing this "worker.stop()" call.` + ); + return; + } + network.disable(); + window.postMessage({ type: "msw/worker:stop" }); + }, + events: network.events, + use: network.use.bind(network), + resetHandlers: network.resetHandlers.bind(network), + restoreHandlers: network.restoreHandlers.bind(network), + listHandlers: network.listHandlers.bind(network) + }; +} +var SetupWorkerApi = class { + start; + stop; + use; + resetHandlers; + restoreHandlers; + listHandlers; + events; + constructor() { + const worker = setupWorker(); + this.start = worker.start.bind(worker); + this.stop = worker.stop.bind(worker); + this.use = worker.use.bind(worker); + this.resetHandlers = worker.resetHandlers.bind(worker); + this.restoreHandlers = worker.restoreHandlers.bind(worker); + this.listHandlers = worker.listHandlers.bind(worker); + this.events = worker.events; + } +}; +export { + SetupWorkerApi, + setupWorker +}; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/node_modules/msw/lib/browser/index.mjs.map b/node_modules/msw/lib/browser/index.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..e7e958cbbd39dadcff23fd8ec8256ac2b503ab92 --- /dev/null +++ b/node_modules/msw/lib/browser/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../node_modules/.pnpm/outvariant@1.4.3/node_modules/outvariant/src/format.ts","../../node_modules/.pnpm/outvariant@1.4.3/node_modules/outvariant/src/invariant.ts","../../node_modules/.pnpm/is-node-process@1.2.0/node_modules/is-node-process/src/index.ts","../../node_modules/.pnpm/@open-draft+logger@0.3.0/node_modules/@open-draft/logger/lib/index.mjs","../../node_modules/.pnpm/strict-event-emitter@0.5.1/node_modules/strict-event-emitter/src/MemoryLeakError.ts","../../node_modules/.pnpm/strict-event-emitter@0.5.1/node_modules/strict-event-emitter/src/Emitter.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/Interceptor.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/createRequestId.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/utils/resolveWebSocketUrl.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/utils/emitAsync.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/utils/hasConfigurableGlobal.ts","../../node_modules/.pnpm/@open-draft+deferred-promise@2.2.0/node_modules/@open-draft/deferred-promise/src/createDeferredExecutor.ts","../../node_modules/.pnpm/@open-draft+deferred-promise@2.2.0/node_modules/@open-draft/deferred-promise/src/DeferredPromise.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/utils/bindEvent.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/utils/events.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/WebSocketClientConnection.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/WebSocketOverride.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/WebSocketServerConnection.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/WebSocketClassTransport.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/index.ts","../../src/browser/setup-worker.ts","../../src/browser/utils/supports.ts","../../node_modules/.pnpm/@open-draft+deferred-promise@3.0.0/node_modules/@open-draft/deferred-promise/src/create-deferred-executor.ts","../../node_modules/.pnpm/@open-draft+deferred-promise@3.0.0/node_modules/@open-draft/deferred-promise/src/deferred-promise.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/glossary.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/InterceptorError.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/RequestController.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/utils/canParseUrl.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/utils/getValueBySymbol.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/utils/fetchUtils.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/getRawRequest.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/utils/bufferUtils.ts","../../src/browser/sources/service-worker-source.ts","../../node_modules/.pnpm/until-async@3.0.2/node_modules/until-async/src/index.ts","../../src/browser/utils/get-worker-instance.ts","../../src/browser/utils/getAbsoluteWorkerUrl.ts","../../src/browser/utils/get-worker-by-registration.ts","../../node_modules/.pnpm/rettime@0.11.11/node_modules/rettime/src/lens-list.ts","../../node_modules/.pnpm/rettime@0.11.11/node_modules/rettime/src/index.ts","../../src/browser/utils/workerChannel.ts","../../src/browser/utils/pruneGetRequestBody.ts","../../src/browser/utils/deserializeRequest.ts","../../src/browser/utils/validate-worker-scope.ts","../../src/browser/utils/should-invalidate-worker.ts","../../node_modules/.pnpm/@open-draft+until@2.1.0/node_modules/@open-draft/until/src/until.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/utils/isObject.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/utils/isPropertyAccessible.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/utils/responseUtils.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/utils/isNodeLikeError.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/utils/handleRequest.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/interceptors/fetch/utils/createNetworkError.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/interceptors/fetch/utils/followRedirect.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/interceptors/fetch/utils/brotli-decompress.browser.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/interceptors/fetch/utils/decompression.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/interceptors/fetch/index.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/utils/concatArrayBuffer.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/polyfills/EventPolyfill.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/polyfills/ProgressEventPolyfill.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/utils/createEvent.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/utils/findPropertySource.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/utils/createProxy.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/utils/isDomParserSupportedType.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/utils/parseJson.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/utils/createResponse.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/utils/getBodyByteLength.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/XMLHttpRequestController.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/XMLHttpRequestProxy.ts","../../node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/index.ts","../../src/browser/sources/fallback-http-source.ts"],"sourcesContent":["const POSITIONALS_EXP = /(%?)(%([sdijo]))/g\n\nfunction serializePositional(positional: any, flag: string): any {\n switch (flag) {\n // Strings.\n case 's':\n return positional\n\n // Digits.\n case 'd':\n case 'i':\n return Number(positional)\n\n // JSON.\n case 'j':\n return JSON.stringify(positional)\n\n // Objects.\n case 'o': {\n // Preserve stings to prevent extra quotes around them.\n if (typeof positional === 'string') {\n return positional\n }\n\n const json = JSON.stringify(positional)\n\n // If the positional isn't serializable, return it as-is.\n if (json === '{}' || json === '[]' || /^\\[object .+?\\]$/.test(json)) {\n return positional\n }\n\n return json\n }\n }\n}\n\nexport function format(message: string, ...positionals: any[]): string {\n if (positionals.length === 0) {\n return message\n }\n\n let positionalIndex = 0\n let formattedMessage = message.replace(\n POSITIONALS_EXP,\n (match, isEscaped, _, flag) => {\n const positional = positionals[positionalIndex]\n const value = serializePositional(positional, flag)\n\n if (!isEscaped) {\n positionalIndex++\n return value\n }\n\n return match\n }\n )\n\n // Append unresolved positionals to string as-is.\n if (positionalIndex < positionals.length) {\n formattedMessage += ` ${positionals.slice(positionalIndex).join(' ')}`\n }\n\n formattedMessage = formattedMessage.replace(/%{2,2}/g, '%')\n\n return formattedMessage\n}\n","import { format } from './format'\n\nconst STACK_FRAMES_TO_IGNORE = 2\n\n/**\n * Remove the \"outvariant\" package trace from the given error.\n * This scopes down the error stack to the relevant parts\n * when used in other applications.\n */\nfunction cleanErrorStack(error: Error): void {\n if (!error.stack) {\n return\n }\n\n const nextStack = error.stack.split('\\n')\n nextStack.splice(1, STACK_FRAMES_TO_IGNORE)\n error.stack = nextStack.join('\\n')\n}\n\nexport class InvariantError extends Error {\n name = 'Invariant Violation'\n\n constructor(public readonly message: string, ...positionals: any[]) {\n super(message)\n this.message = format(message, ...positionals)\n cleanErrorStack(this)\n }\n}\n\nexport interface CustomErrorConstructor {\n new (message: string): Error\n}\n\nexport interface CustomErrorFactory {\n (message: string): Error\n}\n\nexport type CustomError = CustomErrorConstructor | CustomErrorFactory\n\ntype Invariant = {\n (\n predicate: unknown,\n message: string,\n ...positionals: any[]\n ): asserts predicate\n\n as(\n ErrorConstructor: CustomError,\n predicate: unknown,\n message: string,\n ...positionals: unknown[]\n ): asserts predicate\n}\n\nexport const invariant: Invariant = (\n predicate,\n message,\n ...positionals\n): asserts predicate => {\n if (!predicate) {\n throw new InvariantError(message, ...positionals)\n }\n}\n\ninvariant.as = (ErrorConstructor, predicate, message, ...positionals) => {\n if (!predicate) {\n const formatMessage =\n positionals.length === 0 ? message : format(message, ...positionals)\n let error: Error\n\n try {\n error = Reflect.construct(ErrorConstructor as CustomErrorConstructor, [\n formatMessage,\n ])\n } catch (err) {\n error = (ErrorConstructor as CustomErrorFactory)(formatMessage)\n }\n\n throw error\n }\n}\n","/**\n * Determines if the current process is a Node.js process.\n */\nexport function isNodeProcess(): boolean {\n if (typeof navigator !== 'undefined' && navigator.product === 'ReactNative') {\n return true\n }\n\n if (typeof process !== 'undefined') {\n // Electron (https://www.electronjs.org/docs/latest/api/process#processtype-readonly)\n const type = (process as any).type\n if (type === 'renderer' || type === 'worker') {\n return false\n }\n\n\n return !!(\n process.versions &&\n process.versions.node\n )\n }\n\n return false\n}\n","var __defProp = Object.defineProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\n\n// src/index.ts\nimport { isNodeProcess } from \"is-node-process\";\nimport { format } from \"outvariant\";\n\n// src/colors.ts\nvar colors_exports = {};\n__export(colors_exports, {\n blue: () => blue,\n gray: () => gray,\n green: () => green,\n red: () => red,\n yellow: () => yellow\n});\nfunction yellow(text) {\n return `\\x1B[33m${text}\\x1B[0m`;\n}\nfunction blue(text) {\n return `\\x1B[34m${text}\\x1B[0m`;\n}\nfunction gray(text) {\n return `\\x1B[90m${text}\\x1B[0m`;\n}\nfunction red(text) {\n return `\\x1B[31m${text}\\x1B[0m`;\n}\nfunction green(text) {\n return `\\x1B[32m${text}\\x1B[0m`;\n}\n\n// src/index.ts\nvar IS_NODE = isNodeProcess();\nvar Logger = class {\n constructor(name) {\n this.name = name;\n this.prefix = `[${this.name}]`;\n const LOGGER_NAME = getVariable(\"DEBUG\");\n const LOGGER_LEVEL = getVariable(\"LOG_LEVEL\");\n const isLoggingEnabled = LOGGER_NAME === \"1\" || LOGGER_NAME === \"true\" || typeof LOGGER_NAME !== \"undefined\" && this.name.startsWith(LOGGER_NAME);\n if (isLoggingEnabled) {\n this.debug = isDefinedAndNotEquals(LOGGER_LEVEL, \"debug\") ? noop : this.debug;\n this.info = isDefinedAndNotEquals(LOGGER_LEVEL, \"info\") ? noop : this.info;\n this.success = isDefinedAndNotEquals(LOGGER_LEVEL, \"success\") ? noop : this.success;\n this.warning = isDefinedAndNotEquals(LOGGER_LEVEL, \"warning\") ? noop : this.warning;\n this.error = isDefinedAndNotEquals(LOGGER_LEVEL, \"error\") ? noop : this.error;\n } else {\n this.info = noop;\n this.success = noop;\n this.warning = noop;\n this.error = noop;\n this.only = noop;\n }\n }\n prefix;\n extend(domain) {\n return new Logger(`${this.name}:${domain}`);\n }\n /**\n * Print a debug message.\n * @example\n * logger.debug('no duplicates found, creating a document...')\n */\n debug(message, ...positionals) {\n this.logEntry({\n level: \"debug\",\n message: gray(message),\n positionals,\n prefix: this.prefix,\n colors: {\n prefix: \"gray\"\n }\n });\n }\n /**\n * Print an info message.\n * @example\n * logger.info('start parsing...')\n */\n info(message, ...positionals) {\n this.logEntry({\n level: \"info\",\n message,\n positionals,\n prefix: this.prefix,\n colors: {\n prefix: \"blue\"\n }\n });\n const performance2 = new PerformanceEntry();\n return (message2, ...positionals2) => {\n performance2.measure();\n this.logEntry({\n level: \"info\",\n message: `${message2} ${gray(`${performance2.deltaTime}ms`)}`,\n positionals: positionals2,\n prefix: this.prefix,\n colors: {\n prefix: \"blue\"\n }\n });\n };\n }\n /**\n * Print a success message.\n * @example\n * logger.success('successfully created document')\n */\n success(message, ...positionals) {\n this.logEntry({\n level: \"info\",\n message,\n positionals,\n prefix: `\\u2714 ${this.prefix}`,\n colors: {\n timestamp: \"green\",\n prefix: \"green\"\n }\n });\n }\n /**\n * Print a warning.\n * @example\n * logger.warning('found legacy document format')\n */\n warning(message, ...positionals) {\n this.logEntry({\n level: \"warning\",\n message,\n positionals,\n prefix: `\\u26A0 ${this.prefix}`,\n colors: {\n timestamp: \"yellow\",\n prefix: \"yellow\"\n }\n });\n }\n /**\n * Print an error message.\n * @example\n * logger.error('something went wrong')\n */\n error(message, ...positionals) {\n this.logEntry({\n level: \"error\",\n message,\n positionals,\n prefix: `\\u2716 ${this.prefix}`,\n colors: {\n timestamp: \"red\",\n prefix: \"red\"\n }\n });\n }\n /**\n * Execute the given callback only when the logging is enabled.\n * This is skipped in its entirety and has no runtime cost otherwise.\n * This executes regardless of the log level.\n * @example\n * logger.only(() => {\n * logger.info('additional info')\n * })\n */\n only(callback) {\n callback();\n }\n createEntry(level, message) {\n return {\n timestamp: /* @__PURE__ */ new Date(),\n level,\n message\n };\n }\n logEntry(args) {\n const {\n level,\n message,\n prefix,\n colors: customColors,\n positionals = []\n } = args;\n const entry = this.createEntry(level, message);\n const timestampColor = customColors?.timestamp || \"gray\";\n const prefixColor = customColors?.prefix || \"gray\";\n const colorize = {\n timestamp: colors_exports[timestampColor],\n prefix: colors_exports[prefixColor]\n };\n const write = this.getWriter(level);\n write(\n [colorize.timestamp(this.formatTimestamp(entry.timestamp))].concat(prefix != null ? colorize.prefix(prefix) : []).concat(serializeInput(message)).join(\" \"),\n ...positionals.map(serializeInput)\n );\n }\n formatTimestamp(timestamp) {\n return `${timestamp.toLocaleTimeString(\n \"en-GB\"\n )}:${timestamp.getMilliseconds()}`;\n }\n getWriter(level) {\n switch (level) {\n case \"debug\":\n case \"success\":\n case \"info\": {\n return log;\n }\n case \"warning\": {\n return warn;\n }\n case \"error\": {\n return error;\n }\n }\n }\n};\nvar PerformanceEntry = class {\n startTime;\n endTime;\n deltaTime;\n constructor() {\n this.startTime = performance.now();\n }\n measure() {\n this.endTime = performance.now();\n const deltaTime = this.endTime - this.startTime;\n this.deltaTime = deltaTime.toFixed(2);\n }\n};\nvar noop = () => void 0;\nfunction log(message, ...positionals) {\n if (IS_NODE) {\n process.stdout.write(format(message, ...positionals) + \"\\n\");\n return;\n }\n console.log(message, ...positionals);\n}\nfunction warn(message, ...positionals) {\n if (IS_NODE) {\n process.stderr.write(format(message, ...positionals) + \"\\n\");\n return;\n }\n console.warn(message, ...positionals);\n}\nfunction error(message, ...positionals) {\n if (IS_NODE) {\n process.stderr.write(format(message, ...positionals) + \"\\n\");\n return;\n }\n console.error(message, ...positionals);\n}\nfunction getVariable(variableName) {\n if (IS_NODE) {\n return process.env[variableName];\n }\n return globalThis[variableName]?.toString();\n}\nfunction isDefinedAndNotEquals(value, expected) {\n return value !== void 0 && value !== expected;\n}\nfunction serializeInput(message) {\n if (typeof message === \"undefined\") {\n return \"undefined\";\n }\n if (message === null) {\n return \"null\";\n }\n if (typeof message === \"string\") {\n return message;\n }\n if (typeof message === \"object\") {\n return JSON.stringify(message);\n }\n return message.toString();\n}\nexport {\n Logger\n};\n","import type { Emitter } from './Emitter'\n\nexport class MemoryLeakError extends Error {\n constructor(\n public readonly emitter: Emitter,\n public readonly type: string | number | symbol,\n public readonly count: number\n ) {\n super(\n `Possible EventEmitter memory leak detected. ${count} ${type.toString()} listeners added. Use emitter.setMaxListeners() to increase limit`\n )\n this.name = 'MaxListenersExceededWarning'\n }\n}\n","import { MemoryLeakError } from './MemoryLeakError'\n\nexport type EventMap = {\n [eventName: string]: Array\n}\n\nexport type InternalEventNames = 'newListener' | 'removeListener'\n\nexport type InternalListener = Listener<\n [eventName: keyof Events, listener: Listener>]\n>\n\nexport type Listener> = (...data: Data) => void\n\n/**\n * Node.js-compatible implementation of `EventEmitter`.\n *\n * @example\n * const emitter = new Emitter<{ hello: [string] }>()\n * emitter.on('hello', (name) => console.log(name))\n * emitter.emit('hello', 'John')\n */\nexport class Emitter {\n private events: Map>>\n private maxListeners: number\n private hasWarnedAboutPotentialMemoryLeak: boolean\n\n static defaultMaxListeners = 10\n\n static listenerCount(\n emitter: Emitter,\n eventName: keyof Events\n ): number {\n return emitter.listenerCount(eventName)\n }\n\n constructor() {\n this.events = new Map()\n this.maxListeners = Emitter.defaultMaxListeners\n this.hasWarnedAboutPotentialMemoryLeak = false\n }\n\n private _emitInternalEvent(\n internalEventName: InternalEventNames,\n eventName: keyof Events,\n listener: Listener>\n ): void {\n this.emit(\n internalEventName,\n // Anything to make TypeScript happy.\n ...([eventName, listener] as Events['newListener'] &\n Events['removeListener'])\n )\n }\n\n private _getListeners(\n eventName: EventName\n ): Array>> {\n // Always return a copy of the listeners array\n // so they are fixed at the time of the \"_getListeners\" call.\n return Array.prototype.concat.apply([], this.events.get(eventName)) || []\n }\n\n private _removeListener(\n listeners: Array>,\n listener: Listener\n ): Array> {\n const index = listeners.indexOf(listener)\n\n if (index > -1) {\n listeners.splice(index, 1)\n }\n\n return []\n }\n\n private _wrapOnceListener(\n eventName: EventName,\n listener: Listener\n ): Listener {\n const onceListener = (...data: Events[keyof Events]) => {\n this.removeListener(eventName, onceListener)\n\n /**\n * @note Return the result of the original listener.\n * This way this wrapped preserves listeners that are async.\n */\n return listener.apply(this, data)\n }\n\n // Inherit the name of the original listener.\n Object.defineProperty(onceListener, 'name', { value: listener.name })\n\n return onceListener\n }\n\n public setMaxListeners(maxListeners: number): this {\n this.maxListeners = maxListeners\n return this\n }\n\n /**\n * Returns the current max listener value for the `Emitter` which is\n * either set by `emitter.setMaxListeners(n)` or defaults to\n * `Emitter.defaultMaxListeners`.\n */\n public getMaxListeners(): number {\n return this.maxListeners\n }\n\n /**\n * Returns an array listing the events for which the emitter has registered listeners.\n * The values in the array will be strings or Symbols.\n */\n public eventNames(): Array {\n return Array.from(this.events.keys())\n }\n\n /**\n * Synchronously calls each of the listeners registered for the event named `eventName`,\n * in the order they were registered, passing the supplied arguments to each.\n * Returns `true` if the event has listeners, `false` otherwise.\n *\n * @example\n * const emitter = new Emitter<{ hello: [string] }>()\n * emitter.emit('hello', 'John')\n */\n public emit(\n eventName: EventName,\n ...data: Events[EventName]\n ): boolean {\n const listeners = this._getListeners(eventName)\n listeners.forEach((listener) => {\n listener.apply(this, data)\n })\n\n return listeners.length > 0\n }\n\n public addListener(\n eventName: InternalEventNames,\n listener: InternalListener\n ): this\n public addListener(\n eventName: EventName,\n listener: Listener\n ): this\n public addListener(\n eventName: InternalEventNames | keyof Events,\n listener: InternalListener | Listener\n ): this {\n // Emit the `newListener` event before adding the listener.\n this._emitInternalEvent('newListener', eventName, listener)\n\n const nextListeners = this._getListeners(eventName).concat(listener)\n this.events.set(eventName, nextListeners)\n\n if (\n this.maxListeners > 0 &&\n this.listenerCount(eventName) > this.maxListeners &&\n !this.hasWarnedAboutPotentialMemoryLeak\n ) {\n this.hasWarnedAboutPotentialMemoryLeak = true\n\n const memoryLeakWarning = new MemoryLeakError(\n this,\n eventName,\n this.listenerCount(eventName)\n )\n console.warn(memoryLeakWarning)\n }\n\n return this\n }\n\n public on(\n eventName: InternalEventNames,\n listener: InternalListener\n ): this\n public on(\n eventName: EventName,\n listener: Listener\n ): this\n public on(\n eventName: 'removeListener' | EventName,\n listener: Listener\n ): this {\n return this.addListener(eventName, listener)\n }\n\n public once(\n eventName: InternalEventNames,\n listener: InternalListener\n ): this\n public once(\n eventName: EventName,\n listener: Listener\n ): this\n public once(\n eventName: InternalEventNames | EventName,\n listener: Listener\n ): this {\n return this.addListener(\n eventName,\n this._wrapOnceListener(eventName, listener)\n )\n }\n\n public prependListener(\n eventName: InternalEventNames,\n listener: InternalListener\n ): this\n public prependListener(\n eventName: EventName,\n listener: Listener\n ): this\n public prependListener(\n eventName: InternalEventNames | keyof Events,\n listener: Listener\n ): this {\n const listeners = this._getListeners(eventName)\n\n if (listeners.length > 0) {\n const nextListeners = [listener].concat(listeners)\n this.events.set(eventName, nextListeners)\n } else {\n this.events.set(eventName, listeners.concat(listener))\n }\n\n return this\n }\n\n public prependOnceListener(\n eventName: InternalEventNames,\n listener: InternalListener\n ): this\n public prependOnceListener(\n eventName: EventName,\n listener: Listener\n ): this\n public prependOnceListener(\n eventName: InternalEventNames | keyof Events,\n listener: Listener\n ): this {\n return this.prependListener(\n eventName,\n this._wrapOnceListener(eventName, listener)\n )\n }\n\n public removeListener(\n eventName: InternalEventNames,\n listener: InternalListener\n ): this\n public removeListener(\n eventName: EventName,\n listener: Listener\n ): this\n public removeListener(\n eventName: InternalEventNames | keyof Events,\n listener: Listener\n ): this {\n const listeners = this._getListeners(eventName)\n\n if (listeners.length > 0) {\n this._removeListener(listeners, listener)\n this.events.set(eventName, listeners)\n\n // Emit the `removeListener` event after removing the listener.\n this._emitInternalEvent('removeListener', eventName, listener)\n }\n\n return this\n }\n\n public off(\n eventName: InternalEventNames,\n listener: InternalListener\n ): this\n public off(\n eventName: EventName,\n listener: Listener\n ): this\n /**\n * Alias for `emitter.removeListener()`.\n *\n * @example\n * emitter.off('hello', listener)\n */\n public off(\n eventName: InternalEventNames | keyof Events,\n listener: Listener\n ): this {\n return this.removeListener(eventName, listener)\n }\n\n public removeAllListeners(eventName?: InternalEventNames): this\n public removeAllListeners(\n eventName?: EventName\n ): this\n public removeAllListeners(\n eventName?: InternalEventNames | keyof Events\n ): this {\n if (eventName) {\n this.events.delete(eventName)\n } else {\n this.events.clear()\n }\n\n return this\n }\n\n public listeners(eventName: InternalEventNames): Array>\n public listeners(\n eventName: EventName\n ): Array>\n /**\n * Returns a copy of the array of listeners for the event named `eventName`.\n */\n public listeners(eventName: InternalEventNames | keyof Events) {\n return Array.from(this._getListeners(eventName))\n }\n\n public listenerCount(eventName: InternalEventNames): number\n public listenerCount(\n eventName: EventName\n ): number\n /**\n * Returns the number of listeners listening to the event named `eventName`.\n */\n public listenerCount(eventName: InternalEventNames | keyof Events): number {\n return this._getListeners(eventName).length\n }\n\n public rawListeners(\n eventName: EventName\n ): Array> {\n return this.listeners(eventName)\n }\n}\n","import { Logger } from '@open-draft/logger'\nimport { Emitter, Listener } from 'strict-event-emitter'\n\nexport type InterceptorEventMap = Record\nexport type InterceptorSubscription = () => void\n\n/**\n * Request header name to detect when a single request\n * is being handled by nested interceptors (XHR -> ClientRequest).\n * Obscure by design to prevent collisions with user-defined headers.\n * Ideally, come up with the Interceptor-level mechanism for this.\n * @see https://github.com/mswjs/interceptors/issues/378\n */\nexport const INTERNAL_REQUEST_ID_HEADER_NAME =\n 'x-interceptors-internal-request-id'\n\nexport function getGlobalSymbol(symbol: Symbol): V | undefined {\n return (\n // @ts-ignore https://github.com/Microsoft/TypeScript/issues/24587\n globalThis[symbol] || undefined\n )\n}\n\nfunction setGlobalSymbol(symbol: Symbol, value: any): void {\n // @ts-ignore\n globalThis[symbol] = value\n}\n\nexport function deleteGlobalSymbol(symbol: Symbol): void {\n // @ts-ignore\n delete globalThis[symbol]\n}\n\nexport enum InterceptorReadyState {\n INACTIVE = 'INACTIVE',\n APPLYING = 'APPLYING',\n APPLIED = 'APPLIED',\n DISPOSING = 'DISPOSING',\n DISPOSED = 'DISPOSED',\n}\n\nexport type ExtractEventNames> =\n Events extends Record ? EventName : never\n\nexport class Interceptor {\n protected emitter: Emitter\n protected subscriptions: Array\n protected logger: Logger\n\n public readyState: InterceptorReadyState\n\n constructor(private readonly symbol: symbol) {\n this.readyState = InterceptorReadyState.INACTIVE\n\n this.emitter = new Emitter()\n this.subscriptions = []\n this.logger = new Logger(symbol.description!)\n\n // Do not limit the maximum number of listeners\n // so not to limit the maximum amount of parallel events emitted.\n this.emitter.setMaxListeners(0)\n\n this.logger.info('constructing the interceptor...')\n }\n\n /**\n * Determine if this interceptor can be applied\n * in the current environment.\n */\n protected checkEnvironment(): boolean {\n return true\n }\n\n /**\n * Apply this interceptor to the current process.\n * Returns an already running interceptor instance if it's present.\n */\n public apply(): void {\n const logger = this.logger.extend('apply')\n logger.info('applying the interceptor...')\n\n if (this.readyState === InterceptorReadyState.APPLIED) {\n logger.info('intercepted already applied!')\n return\n }\n\n const shouldApply = this.checkEnvironment()\n\n if (!shouldApply) {\n logger.info('the interceptor cannot be applied in this environment!')\n return\n }\n\n this.readyState = InterceptorReadyState.APPLYING\n\n // Whenever applying a new interceptor, check if it hasn't been applied already.\n // This enables to apply the same interceptor multiple times, for example from a different\n // interceptor, only proxying events but keeping the stubs in a single place.\n const runningInstance = this.getInstance()\n\n if (runningInstance) {\n logger.info('found a running instance, reusing...')\n\n // Proxy any listeners you set on this instance to the running instance.\n this.on = (event, listener) => {\n logger.info('proxying the \"%s\" listener', event)\n\n // Add listeners to the running instance so they appear\n // at the top of the event listeners list and are executed first.\n runningInstance.emitter.addListener(event, listener)\n\n // Ensure that once this interceptor instance is disposed,\n // it removes all listeners it has appended to the running interceptor instance.\n this.subscriptions.push(() => {\n runningInstance.emitter.removeListener(event, listener)\n logger.info('removed proxied \"%s\" listener!', event)\n })\n\n return this\n }\n\n this.readyState = InterceptorReadyState.APPLIED\n\n return\n }\n\n logger.info('no running instance found, setting up a new instance...')\n\n // Setup the interceptor.\n this.setup()\n\n // Store the newly applied interceptor instance globally.\n this.setInstance()\n\n this.readyState = InterceptorReadyState.APPLIED\n }\n\n /**\n * Setup the module augments and stubs necessary for this interceptor.\n * This method is not run if there's a running interceptor instance\n * to prevent instantiating an interceptor multiple times.\n */\n protected setup(): void {}\n\n /**\n * Listen to the interceptor's public events.\n */\n public on>(\n event: EventName,\n listener: Listener\n ): this {\n const logger = this.logger.extend('on')\n\n if (\n this.readyState === InterceptorReadyState.DISPOSING ||\n this.readyState === InterceptorReadyState.DISPOSED\n ) {\n logger.info('cannot listen to events, already disposed!')\n return this\n }\n\n logger.info('adding \"%s\" event listener:', event, listener)\n\n this.emitter.on(event, listener)\n return this\n }\n\n public once>(\n event: EventName,\n listener: Listener\n ): this {\n this.emitter.once(event, listener)\n return this\n }\n\n public off>(\n event: EventName,\n listener: Listener\n ): this {\n this.emitter.off(event, listener)\n return this\n }\n\n public removeAllListeners>(\n event?: EventName\n ): this {\n this.emitter.removeAllListeners(event)\n return this\n }\n\n /**\n * Disposes of any side-effects this interceptor has introduced.\n */\n public dispose(): void {\n const logger = this.logger.extend('dispose')\n\n if (this.readyState === InterceptorReadyState.DISPOSED) {\n logger.info('cannot dispose, already disposed!')\n return\n }\n\n logger.info('disposing the interceptor...')\n this.readyState = InterceptorReadyState.DISPOSING\n\n if (!this.getInstance()) {\n logger.info('no interceptors running, skipping dispose...')\n return\n }\n\n // Delete the global symbol as soon as possible,\n // indicating that the interceptor is no longer running.\n this.clearInstance()\n\n logger.info('global symbol deleted:', getGlobalSymbol(this.symbol))\n\n if (this.subscriptions.length > 0) {\n logger.info('disposing of %d subscriptions...', this.subscriptions.length)\n\n for (const dispose of this.subscriptions) {\n dispose()\n }\n\n this.subscriptions = []\n\n logger.info('disposed of all subscriptions!', this.subscriptions.length)\n }\n\n this.emitter.removeAllListeners()\n logger.info('destroyed the listener!')\n\n this.readyState = InterceptorReadyState.DISPOSED\n }\n\n private getInstance(): this | undefined {\n const instance = getGlobalSymbol(this.symbol)\n this.logger.info('retrieved global instance:', instance?.constructor?.name)\n return instance\n }\n\n private setInstance(): void {\n setGlobalSymbol(this.symbol, this)\n this.logger.info('set global instance!', this.symbol.description)\n }\n\n private clearInstance(): void {\n deleteGlobalSymbol(this.symbol)\n this.logger.info('cleared global instance!', this.symbol.description)\n }\n}\n","/**\n * Generate a random ID string to represent a request.\n * @example\n * createRequestId()\n * // \"f774b6c9c600f\"\n */\nexport function createRequestId(): string {\n return Math.random().toString(16).slice(2)\n}\n","/**\n * Resolve potentially relative WebSocket URLs the same way\n * the browser does (replace the protocol, use the origin, etc).\n *\n * @see https://websockets.spec.whatwg.org//#dom-websocket-websocket\n */\nexport function resolveWebSocketUrl(url: string | URL): string {\n if (typeof url === 'string') {\n /**\n * @note Cast the string to a URL first so the parsing errors\n * are thrown as a part of the WebSocket constructor, not consumers.\n */\n const urlRecord = new URL(\n url,\n typeof location !== 'undefined' ? location.href : undefined\n )\n\n return resolveWebSocketUrl(urlRecord)\n }\n\n if (url.protocol === 'http:') {\n url.protocol = 'ws:'\n } else if (url.protocol === 'https:') {\n url.protocol = 'wss:'\n }\n\n if (url.protocol !== 'ws:' && url.protocol !== 'wss:') {\n /**\n * @note These errors are modeled after the browser errors.\n * The exact error messages aren't provided in the specification.\n * Node.js uses more obscure error messages that I don't wish to replicate.\n */\n throw new SyntaxError(\n `Failed to construct 'WebSocket': The URL's scheme must be either 'http', 'https', 'ws', or 'wss'. '${url.protocol}' is not allowed.`\n )\n }\n\n if (url.hash !== '') {\n throw new SyntaxError(\n `Failed to construct 'WebSocket': The URL contains a fragment identifier ('${url.hash}'). Fragment identifiers are not allowed in WebSocket URLs.`\n )\n }\n\n return url.href\n}\n","import { Emitter, EventMap } from 'strict-event-emitter'\n\n/**\n * Emits an event on the given emitter but executes\n * the listeners sequentially. This accounts for asynchronous\n * listeners (e.g. those having \"sleep\" and handling the request).\n */\nexport async function emitAsync<\n Events extends EventMap,\n EventName extends keyof Events\n>(\n emitter: Emitter,\n eventName: EventName,\n ...data: Events[EventName]\n): Promise {\n const listeners = emitter.listeners(eventName)\n\n if (listeners.length === 0) {\n return\n }\n\n for (const listener of listeners) {\n await listener.apply(emitter, data)\n }\n}\n","/**\n * Returns a boolean indicating whether the given global property\n * is defined and is configurable.\n */\nexport function hasConfigurableGlobal(propertyName: string): boolean {\n const descriptor = Object.getOwnPropertyDescriptor(globalThis, propertyName)\n\n // The property is not set at all.\n if (typeof descriptor === 'undefined') {\n return false\n }\n\n // The property is set to a getter that returns undefined.\n if (\n typeof descriptor.get === 'function' &&\n typeof descriptor.get() === 'undefined'\n ) {\n return false\n }\n\n // The property is set to a value equal to undefined.\n if (typeof descriptor.get === 'undefined' && descriptor.value == null) {\n return false\n }\n\n if (typeof descriptor.set === 'undefined' && !descriptor.configurable) {\n console.error(\n `[MSW] Failed to apply interceptor: the global \\`${propertyName}\\` property is non-configurable. This is likely an issue with your environment. If you are using a framework, please open an issue about this in their repository.`\n )\n return false\n }\n\n return true\n}\n","export type PromiseState = 'pending' | 'fulfilled' | 'rejected'\n\nexport type Executor = ConstructorParameters>[0]\nexport type ResolveFunction = Parameters>[0]\nexport type RejectFunction = Parameters>[1]\n\nexport type DeferredPromiseExecutor = {\n (resolve?: ResolveFunction, reject?: RejectFunction): void\n\n resolve: ResolveFunction\n reject: RejectFunction\n result?: Output\n state: PromiseState\n rejectionReason?: unknown\n}\nexport function createDeferredExecutor<\n Input = never,\n Output = Input\n>(): DeferredPromiseExecutor {\n const executor = >((\n resolve,\n reject\n ) => {\n executor.state = 'pending'\n\n executor.resolve = (data) => {\n if (executor.state !== 'pending') {\n return\n }\n\n executor.result = data as Output\n\n const onFulfilled = (value: Value) => {\n executor.state = 'fulfilled'\n return value\n }\n\n return resolve(\n data instanceof Promise ? data : Promise.resolve(data).then(onFulfilled)\n )\n }\n\n executor.reject = (reason) => {\n if (executor.state !== 'pending') {\n return\n }\n\n queueMicrotask(() => {\n executor.state = 'rejected'\n })\n\n return reject((executor.rejectionReason = reason))\n }\n })\n\n return executor\n}\n","import {\n type Executor,\n type RejectFunction,\n type ResolveFunction,\n type DeferredPromiseExecutor,\n createDeferredExecutor,\n} from './createDeferredExecutor'\n\nexport class DeferredPromise extends Promise {\n #executor: DeferredPromiseExecutor\n\n public resolve: ResolveFunction\n public reject: RejectFunction\n\n constructor(executor: Executor | null = null) {\n const deferredExecutor = createDeferredExecutor()\n super((originalResolve, originalReject) => {\n deferredExecutor(originalResolve, originalReject)\n executor?.(deferredExecutor.resolve, deferredExecutor.reject)\n })\n\n this.#executor = deferredExecutor\n this.resolve = this.#executor.resolve\n this.reject = this.#executor.reject\n }\n\n public get state() {\n return this.#executor.state\n }\n\n public get rejectionReason() {\n return this.#executor.rejectionReason\n }\n\n public then(\n onFulfilled?: (value: Input) => ThenResult | PromiseLike,\n onRejected?: (reason: any) => CatchResult | PromiseLike\n ) {\n return this.#decorate(super.then(onFulfilled, onRejected))\n }\n\n public catch(\n onRejected?: (reason: any) => CatchResult | PromiseLike\n ) {\n return this.#decorate(super.catch(onRejected))\n }\n\n public finally(onfinally?: () => void | Promise) {\n return this.#decorate(super.finally(onfinally))\n }\n\n #decorate(\n promise: Promise\n ): DeferredPromise {\n return Object.defineProperties(promise, {\n resolve: { configurable: true, value: this.resolve },\n reject: { configurable: true, value: this.reject },\n }) as DeferredPromise\n }\n}\n","type EventWithTarget = E & { target: T }\n\nexport function bindEvent(\n target: T,\n event: E\n): EventWithTarget {\n Object.defineProperties(event, {\n target: {\n value: target,\n enumerable: true,\n writable: true,\n },\n currentTarget: {\n value: target,\n enumerable: true,\n writable: true,\n },\n })\n\n return event as EventWithTarget\n}\n","const kCancelable = Symbol('kCancelable')\nconst kDefaultPrevented = Symbol('kDefaultPrevented')\n\n/**\n * A `MessageEvent` superset that supports event cancellation\n * in Node.js. It's rather non-intrusive so it can be safely\n * used in the browser as well.\n *\n * @see https://github.com/nodejs/node/issues/51767\n */\nexport class CancelableMessageEvent extends MessageEvent {\n [kCancelable]: boolean;\n [kDefaultPrevented]: boolean\n\n constructor(type: string, init: MessageEventInit) {\n super(type, init)\n this[kCancelable] = !!init.cancelable\n this[kDefaultPrevented] = false\n }\n\n get cancelable() {\n return this[kCancelable]\n }\n\n set cancelable(nextCancelable) {\n this[kCancelable] = nextCancelable\n }\n\n get defaultPrevented() {\n return this[kDefaultPrevented]\n }\n\n set defaultPrevented(nextDefaultPrevented) {\n this[kDefaultPrevented] = nextDefaultPrevented\n }\n\n public preventDefault(): void {\n if (this.cancelable && !this[kDefaultPrevented]) {\n this[kDefaultPrevented] = true\n }\n }\n}\n\ninterface CloseEventInit extends EventInit {\n code?: number\n reason?: string\n wasClean?: boolean\n}\n\nexport class CloseEvent extends Event {\n public code: number\n public reason: string\n public wasClean: boolean\n\n constructor(type: string, init: CloseEventInit = {}) {\n super(type, init)\n this.code = init.code === undefined ? 0 : init.code\n this.reason = init.reason === undefined ? '' : init.reason\n this.wasClean = init.wasClean === undefined ? false : init.wasClean\n }\n}\n\nexport class CancelableCloseEvent extends CloseEvent {\n [kCancelable]: boolean;\n [kDefaultPrevented]: boolean\n\n constructor(type: string, init: CloseEventInit = {}) {\n super(type, init)\n this[kCancelable] = !!init.cancelable\n this[kDefaultPrevented] = false\n }\n\n get cancelable() {\n return this[kCancelable]\n }\n\n set cancelable(nextCancelable) {\n this[kCancelable] = nextCancelable\n }\n\n get defaultPrevented() {\n return this[kDefaultPrevented]\n }\n\n set defaultPrevented(nextDefaultPrevented) {\n this[kDefaultPrevented] = nextDefaultPrevented\n }\n\n public preventDefault(): void {\n if (this.cancelable && !this[kDefaultPrevented]) {\n this[kDefaultPrevented] = true\n }\n }\n}\n","import type { WebSocketData, WebSocketTransport } from './WebSocketTransport'\nimport type { WebSocketEventListener } from './WebSocketOverride'\nimport { bindEvent } from './utils/bindEvent'\nimport { CancelableMessageEvent, CloseEvent } from './utils/events'\nimport { createRequestId } from '../../createRequestId'\n\nconst kEmitter = Symbol('kEmitter')\nconst kBoundListener = Symbol('kBoundListener')\n\nexport interface WebSocketClientEventMap {\n message: MessageEvent\n close: CloseEvent\n}\n\nexport abstract class WebSocketClientConnectionProtocol {\n abstract id: string\n abstract url: URL\n public abstract send(data: WebSocketData): void\n public abstract close(code?: number, reason?: string): void\n\n public abstract addEventListener<\n EventType extends keyof WebSocketClientEventMap,\n >(\n type: EventType,\n listener: WebSocketEventListener,\n options?: AddEventListenerOptions | boolean\n ): void\n\n public abstract removeEventListener<\n EventType extends keyof WebSocketClientEventMap,\n >(\n event: EventType,\n listener: WebSocketEventListener,\n options?: EventListenerOptions | boolean\n ): void\n}\n\n/**\n * The WebSocket client instance represents an incoming\n * client connection. The user can control the connection,\n * send and receive events.\n */\nexport class WebSocketClientConnection implements WebSocketClientConnectionProtocol {\n public readonly id: string\n public readonly url: URL\n\n private [kEmitter]: EventTarget\n\n constructor(\n public readonly socket: WebSocket,\n private readonly transport: WebSocketTransport\n ) {\n this.id = createRequestId()\n this.url = new URL(socket.url)\n this[kEmitter] = new EventTarget()\n\n // Emit outgoing client data (\"ws.send()\") as \"message\"\n // events on the \"client\" connection.\n this.transport.addEventListener('outgoing', (event) => {\n const message = bindEvent(\n this.socket,\n new CancelableMessageEvent('message', {\n data: event.data,\n origin: event.origin,\n cancelable: true,\n })\n )\n\n this[kEmitter].dispatchEvent(message)\n\n // This is a bit silly but forward the cancellation state\n // of the \"client\" message event to the \"outgoing\" transport event.\n // This way, other agens (like \"server\" connection) can know\n // whether the client listener has pervented the default.\n if (message.defaultPrevented) {\n event.preventDefault()\n }\n })\n\n /**\n * Emit the \"close\" event on the \"client\" connection\n * whenever the underlying transport is closed.\n * @note \"client.close()\" does NOT dispatch the \"close\"\n * event on the WebSocket because it uses non-configurable\n * close status code. Thus, we listen to the transport\n * instead of the WebSocket's \"close\" event.\n */\n this.transport.addEventListener('close', (event) => {\n this[kEmitter].dispatchEvent(\n bindEvent(this.socket, new CloseEvent('close', event))\n )\n })\n }\n\n /**\n * Listen for the outgoing events from the connected WebSocket client.\n */\n public addEventListener(\n type: EventType,\n listener: WebSocketEventListener,\n options?: AddEventListenerOptions | boolean\n ): void {\n if (!Reflect.has(listener, kBoundListener)) {\n const boundListener = listener.bind(this.socket)\n\n // Store the bound listener on the original listener\n // so the exact bound function can be accessed in \"removeEventListener()\".\n Object.defineProperty(listener, kBoundListener, {\n value: boundListener,\n enumerable: false,\n configurable: false,\n })\n }\n\n this[kEmitter].addEventListener(\n type,\n Reflect.get(listener, kBoundListener) as EventListener,\n options\n )\n }\n\n /**\n * Removes the listener for the given event.\n */\n public removeEventListener(\n event: EventType,\n listener: WebSocketEventListener,\n options?: EventListenerOptions | boolean\n ): void {\n this[kEmitter].removeEventListener(\n event,\n Reflect.get(listener, kBoundListener) as EventListener,\n options\n )\n }\n\n /**\n * Send data to the connected client.\n */\n public send(data: WebSocketData): void {\n this.transport.send(data)\n }\n\n /**\n * Close the WebSocket connection.\n * @param {number} code A status code (see https://www.rfc-editor.org/rfc/rfc6455#section-7.4.1).\n * @param {string} reason A custom connection close reason.\n */\n public close(code?: number, reason?: string): void {\n this.transport.close(code, reason)\n }\n}\n","import { invariant } from 'outvariant'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\nimport type { WebSocketData } from './WebSocketTransport'\nimport { bindEvent } from './utils/bindEvent'\nimport { CloseEvent } from './utils/events'\nimport { resolveWebSocketUrl } from '../../utils/resolveWebSocketUrl'\n\nexport type WebSocketEventListener<\n EventType extends WebSocketEventMap[keyof WebSocketEventMap] = Event,\n> = (this: WebSocket, event: EventType) => void\n\nconst WEBSOCKET_CLOSE_CODE_RANGE_ERROR =\n 'InvalidAccessError: close code out of user configurable range'\n\nexport const kPassthroughPromise = Symbol('kPassthroughPromise')\nexport const kOnSend = Symbol('kOnSend')\nexport const kClose = Symbol('kClose')\n\nexport class WebSocketOverride extends EventTarget implements WebSocket {\n static readonly CONNECTING = 0\n static readonly OPEN = 1\n static readonly CLOSING = 2\n static readonly CLOSED = 3\n readonly CONNECTING = 0\n readonly OPEN = 1\n readonly CLOSING = 2\n readonly CLOSED = 3\n\n public url: string\n public protocol: string\n public extensions: string\n public binaryType: BinaryType\n public readyState: WebSocket['readyState']\n public bufferedAmount: number\n\n private _onopen: WebSocketEventListener | null = null\n private _onmessage: WebSocketEventListener<\n MessageEvent\n > | null = null\n private _onerror: WebSocketEventListener | null = null\n private _onclose: WebSocketEventListener | null = null\n\n private [kPassthroughPromise]: DeferredPromise\n private [kOnSend]?: (data: WebSocketData) => void\n\n constructor(url: string | URL, protocols?: string | Array) {\n super()\n this.url = resolveWebSocketUrl(url)\n this.protocol = ''\n this.extensions = ''\n this.binaryType = 'blob'\n this.readyState = this.CONNECTING\n this.bufferedAmount = 0\n\n this[kPassthroughPromise] = new DeferredPromise()\n\n queueMicrotask(async () => {\n if (await this[kPassthroughPromise]) {\n return\n }\n\n this.protocol =\n typeof protocols === 'string'\n ? protocols\n : Array.isArray(protocols) && protocols.length > 0\n ? protocols[0]\n : ''\n\n /**\n * @note Check that nothing has prevented this connection\n * (e.g. called `client.close()` in the connection listener).\n * If the connection has been prevented, never dispatch the open event,.\n */\n if (this.readyState === this.CONNECTING) {\n this.readyState = this.OPEN\n this.dispatchEvent(bindEvent(this, new Event('open')))\n }\n })\n }\n\n set onopen(listener: WebSocketEventListener | null) {\n this.removeEventListener('open', this._onopen)\n this._onopen = listener\n if (listener !== null) {\n this.addEventListener('open', listener)\n }\n }\n get onopen(): WebSocketEventListener | null {\n return this._onopen\n }\n\n set onmessage(\n listener: WebSocketEventListener> | null\n ) {\n this.removeEventListener(\n 'message',\n this._onmessage as WebSocketEventListener\n )\n this._onmessage = listener\n if (listener !== null) {\n this.addEventListener('message', listener)\n }\n }\n get onmessage(): WebSocketEventListener> | null {\n return this._onmessage\n }\n\n set onerror(listener: WebSocketEventListener | null) {\n this.removeEventListener('error', this._onerror)\n this._onerror = listener\n if (listener !== null) {\n this.addEventListener('error', listener)\n }\n }\n get onerror(): WebSocketEventListener | null {\n return this._onerror\n }\n\n set onclose(listener: WebSocketEventListener | null) {\n this.removeEventListener('close', this._onclose as WebSocketEventListener)\n this._onclose = listener\n if (listener !== null) {\n this.addEventListener('close', listener)\n }\n }\n get onclose(): WebSocketEventListener | null {\n return this._onclose\n }\n\n /**\n * @see https://websockets.spec.whatwg.org/#ref-for-dom-websocket-send%E2%91%A0\n */\n public send(data: WebSocketData): void {\n if (this.readyState === this.CONNECTING) {\n this.close()\n throw new DOMException('InvalidStateError')\n }\n\n // Sending when the socket is about to close\n // discards the sent data.\n if (this.readyState === this.CLOSING || this.readyState === this.CLOSED) {\n return\n }\n\n // Buffer the data to send in this even loop\n // but send it in the next.\n this.bufferedAmount += getDataSize(data)\n\n queueMicrotask(() => {\n // This is a bit optimistic but since no actual data transfer\n // is involved, all the data will be \"sent\" on the next tick.\n this.bufferedAmount = 0\n\n /**\n * @note Notify the parent about outgoing data.\n * This notifies the transport and the connection\n * listens to the outgoing data to emit the \"message\" event.\n */\n this[kOnSend]?.(data)\n })\n }\n\n public close(code: number = 1000, reason?: string): void {\n invariant(code, WEBSOCKET_CLOSE_CODE_RANGE_ERROR)\n invariant(\n code === 1000 || (code >= 3000 && code <= 4999),\n WEBSOCKET_CLOSE_CODE_RANGE_ERROR\n )\n\n this[kClose](code, reason)\n }\n\n private [kClose](\n code: number = 1000,\n reason?: string,\n wasClean = true\n ): void {\n /**\n * @note Move this check here so that even internal closures,\n * like those triggered by the `server` connection, are not\n * performed twice.\n */\n if (this.readyState === this.CLOSING || this.readyState === this.CLOSED) {\n return\n }\n\n this.readyState = this.CLOSING\n\n queueMicrotask(() => {\n this.readyState = this.CLOSED\n\n this.dispatchEvent(\n bindEvent(\n this,\n new CloseEvent('close', {\n code,\n reason,\n wasClean,\n })\n )\n )\n\n // Remove all event listeners once the socket is closed.\n this._onopen = null\n this._onmessage = null\n this._onerror = null\n this._onclose = null\n })\n }\n\n public addEventListener(\n type: K,\n listener: (this: WebSocket, event: WebSocketEventMap[K]) => void,\n options?: boolean | AddEventListenerOptions\n ): void\n public addEventListener(\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | AddEventListenerOptions\n ): void\n public addEventListener(\n type: unknown,\n listener: unknown,\n options?: unknown\n ): void {\n return super.addEventListener(\n type as string,\n listener as EventListener,\n options as AddEventListenerOptions\n )\n }\n\n removeEventListener(\n type: K,\n callback: EventListenerOrEventListenerObject | null,\n options?: boolean | EventListenerOptions\n ): void {\n return super.removeEventListener(type, callback, options)\n }\n}\n\nfunction getDataSize(data: WebSocketData): number {\n if (typeof data === 'string') {\n return data.length\n }\n\n if (data instanceof Blob) {\n return data.size\n }\n\n return data.byteLength\n}\n","import { invariant } from 'outvariant'\nimport {\n kClose,\n WebSocketEventListener,\n WebSocketOverride,\n} from './WebSocketOverride'\nimport type { WebSocketData } from './WebSocketTransport'\nimport type { WebSocketClassTransport } from './WebSocketClassTransport'\nimport { bindEvent } from './utils/bindEvent'\nimport {\n CancelableMessageEvent,\n CancelableCloseEvent,\n CloseEvent,\n} from './utils/events'\n\nconst kEmitter = Symbol('kEmitter')\nconst kBoundListener = Symbol('kBoundListener')\nconst kSend = Symbol('kSend')\n\nexport interface WebSocketServerEventMap {\n open: Event\n message: MessageEvent\n error: Event\n close: CloseEvent\n}\n\nexport abstract class WebSocketServerConnectionProtocol {\n public abstract connect(): void\n public abstract send(data: WebSocketData): void\n public abstract close(): void\n\n public abstract addEventListener<\n EventType extends keyof WebSocketServerEventMap,\n >(\n event: EventType,\n listener: WebSocketEventListener,\n options?: AddEventListenerOptions | boolean\n ): void\n\n public abstract removeEventListener<\n EventType extends keyof WebSocketServerEventMap,\n >(\n event: EventType,\n listener: WebSocketEventListener,\n options?: EventListenerOptions | boolean\n ): void\n}\n\n/**\n * The WebSocket server instance represents the actual production\n * WebSocket server connection. It's idle by default but you can\n * establish it by calling `server.connect()`.\n */\nexport class WebSocketServerConnection implements WebSocketServerConnectionProtocol {\n /**\n * A WebSocket instance connected to the original server.\n */\n private realWebSocket?: WebSocket\n private mockCloseController: AbortController\n private realCloseController: AbortController\n private [kEmitter]: EventTarget\n\n constructor(\n private readonly client: WebSocketOverride,\n private readonly transport: WebSocketClassTransport,\n private readonly createConnection: () => WebSocket\n ) {\n this[kEmitter] = new EventTarget()\n this.mockCloseController = new AbortController()\n this.realCloseController = new AbortController()\n\n // Automatically forward outgoing client events\n // to the actual server unless the outgoing message event\n // has been prevented. The \"outgoing\" transport event it\n // dispatched by the \"client\" connection.\n this.transport.addEventListener('outgoing', (event) => {\n // Ignore client messages if the server connection\n // hasn't been established yet. Nowhere to forward.\n if (typeof this.realWebSocket === 'undefined') {\n return\n }\n\n // Every outgoing client message can prevent this forwarding\n // by preventing the default of the outgoing message event.\n // This listener will be added before user-defined listeners,\n // so execute the logic on the next tick.\n queueMicrotask(() => {\n if (!event.defaultPrevented) {\n /**\n * @note Use the internal send mechanism so consumers can tell\n * apart direct user calls to `server.send()` and internal calls.\n * E.g. MSW has to ignore this internal call to log out messages correctly.\n */\n this[kSend](event.data)\n }\n })\n })\n\n this.transport.addEventListener(\n 'incoming',\n this.handleIncomingMessage.bind(this)\n )\n }\n\n /**\n * The `WebSocket` instance connected to the original server.\n * Accessing this before calling `server.connect()` will throw.\n */\n public get socket(): WebSocket {\n invariant(\n this.realWebSocket,\n 'Cannot access \"socket\" on the original WebSocket server object: the connection is not open. Did you forget to call `server.connect()`?'\n )\n\n return this.realWebSocket\n }\n\n /**\n * Open connection to the original WebSocket server.\n */\n public connect(): void {\n invariant(\n !this.realWebSocket || this.realWebSocket.readyState !== WebSocket.OPEN,\n 'Failed to call \"connect()\" on the original WebSocket instance: the connection already open'\n )\n\n const realWebSocket = this.createConnection()\n\n // Inherit the binary type from the mock WebSocket client.\n realWebSocket.binaryType = this.client.binaryType\n\n // Allow the interceptor to listen to when the server connection\n // has been established. This isn't necessary to operate with the connection\n // but may be beneficial in some cases (like conditionally adding logging).\n realWebSocket.addEventListener(\n 'open',\n (event) => {\n this[kEmitter].dispatchEvent(\n bindEvent(this.realWebSocket!, new Event('open', event))\n )\n },\n { once: true }\n )\n\n realWebSocket.addEventListener('message', (event) => {\n // Dispatch the \"incoming\" transport event instead of\n // invoking the internal handler directly. This way,\n // anyone can listen to the \"incoming\" event but this\n // class is the one resulting in it.\n this.transport.dispatchEvent(\n bindEvent(\n this.realWebSocket!,\n new MessageEvent('incoming', {\n data: event.data,\n origin: event.origin,\n })\n )\n )\n })\n\n // Close the original connection when the mock client closes.\n // E.g. \"client.close()\" was called. This is never forwarded anywhere.\n this.client.addEventListener(\n 'close',\n (event) => {\n this.handleMockClose(event)\n },\n {\n signal: this.mockCloseController.signal,\n }\n )\n\n // Forward the \"close\" event to let the interceptor handle\n // closures initiated by the original server.\n realWebSocket.addEventListener(\n 'close',\n (event) => {\n this.handleRealClose(event)\n },\n {\n signal: this.realCloseController.signal,\n }\n )\n\n realWebSocket.addEventListener('error', () => {\n const errorEvent = bindEvent(\n realWebSocket,\n new Event('error', { cancelable: true })\n )\n\n // Emit the \"error\" event on the `server` connection\n // to let the interceptor react to original server errors.\n this[kEmitter].dispatchEvent(errorEvent)\n\n // If the error event from the original server hasn't been prevented,\n // forward it to the underlying client.\n if (!errorEvent.defaultPrevented) {\n this.client.dispatchEvent(bindEvent(this.client, new Event('error')))\n }\n })\n\n this.realWebSocket = realWebSocket\n }\n\n /**\n * Listen for the incoming events from the original WebSocket server.\n */\n public addEventListener(\n event: EventType,\n listener: WebSocketEventListener,\n options?: AddEventListenerOptions | boolean\n ): void {\n if (!Reflect.has(listener, kBoundListener)) {\n const boundListener = listener.bind(this.client)\n\n // Store the bound listener on the original listener\n // so the exact bound function can be accessed in \"removeEventListener()\".\n Object.defineProperty(listener, kBoundListener, {\n value: boundListener,\n enumerable: false,\n })\n }\n\n this[kEmitter].addEventListener(\n event,\n Reflect.get(listener, kBoundListener) as EventListener,\n options\n )\n }\n\n /**\n * Remove the listener for the given event.\n */\n public removeEventListener(\n event: EventType,\n listener: WebSocketEventListener,\n options?: EventListenerOptions | boolean\n ): void {\n this[kEmitter].removeEventListener(\n event,\n Reflect.get(listener, kBoundListener) as EventListener,\n options\n )\n }\n\n /**\n * Send data to the original WebSocket server.\n * @example\n * server.send('hello')\n * server.send(new Blob(['hello']))\n * server.send(new TextEncoder().encode('hello'))\n */\n public send(data: WebSocketData): void {\n this[kSend](data)\n }\n\n private [kSend](data: WebSocketData): void {\n const { realWebSocket } = this\n\n invariant(\n realWebSocket,\n 'Failed to call \"server.send()\" for \"%s\": the connection is not open. Did you forget to call \"server.connect()\"?',\n this.client.url\n )\n\n // Silently ignore writes on the closed original WebSocket.\n if (\n realWebSocket.readyState === WebSocket.CLOSING ||\n realWebSocket.readyState === WebSocket.CLOSED\n ) {\n return\n }\n\n // Delegate the send to when the original connection is open.\n // Unlike the mock, connecting to the original server may take time\n // so we cannot call this on the next tick.\n if (realWebSocket.readyState === WebSocket.CONNECTING) {\n realWebSocket.addEventListener(\n 'open',\n () => {\n realWebSocket.send(data)\n },\n { once: true }\n )\n return\n }\n\n // Send the data to the original WebSocket server.\n realWebSocket.send(data)\n }\n\n /**\n * Close the actual server connection.\n */\n public close(): void {\n const { realWebSocket } = this\n\n invariant(\n realWebSocket,\n 'Failed to close server connection for \"%s\": the connection is not open. Did you forget to call \"server.connect()\"?',\n this.client.url\n )\n\n // Remove the \"close\" event listener from the server\n // so it doesn't close the underlying WebSocket client\n // when you call \"server.close()\". This also prevents the\n // `close` event on the `server` connection from being dispatched twice.\n this.realCloseController.abort()\n\n if (\n realWebSocket.readyState === WebSocket.CLOSING ||\n realWebSocket.readyState === WebSocket.CLOSED\n ) {\n return\n }\n\n // Close the actual client connection.\n realWebSocket.close()\n\n // Dispatch the \"close\" event on the `server` connection.\n queueMicrotask(() => {\n this[kEmitter].dispatchEvent(\n bindEvent(\n this.realWebSocket,\n new CancelableCloseEvent('close', {\n /**\n * @note `server.close()` in the interceptor\n * always results in clean closures.\n */\n code: 1000,\n cancelable: true,\n })\n )\n )\n })\n }\n\n private handleIncomingMessage(event: MessageEvent): void {\n // Clone the event to dispatch it on this class\n // once again and prevent the \"already being dispatched\"\n // exception. Clone it here so we can observe this event\n // being prevented in the \"server.on()\" listeners.\n const messageEvent = bindEvent(\n event.target,\n new CancelableMessageEvent('message', {\n data: event.data,\n origin: event.origin,\n cancelable: true,\n })\n )\n\n /**\n * @note Emit \"message\" event on the server connection\n * instance to let the interceptor know about these\n * incoming events from the original server. In that listener,\n * the interceptor can modify or skip the event forwarding\n * to the mock WebSocket instance.\n */\n this[kEmitter].dispatchEvent(messageEvent)\n\n /**\n * @note Forward the incoming server events to the client.\n * Preventing the default on the message event stops this.\n */\n if (!messageEvent.defaultPrevented) {\n this.client.dispatchEvent(\n bindEvent(\n /**\n * @note Bind the forwarded original server events\n * to the mock WebSocket instance so it would\n * dispatch them straight away.\n */\n this.client,\n // Clone the message event again to prevent\n // the \"already being dispatched\" exception.\n new MessageEvent('message', {\n data: event.data,\n origin: event.origin,\n })\n )\n )\n }\n }\n\n private handleMockClose(_event: Event): void {\n // Close the original connection if the mock client closes.\n if (this.realWebSocket) {\n this.realWebSocket.close()\n }\n }\n\n private handleRealClose(event: CloseEvent): void {\n // For closures originating from the original server,\n // remove the \"close\" listener from the mock client.\n // original close -> (?) client[kClose]() --X--> \"close\" (again).\n this.mockCloseController.abort()\n\n const closeEvent = bindEvent(\n this.realWebSocket,\n new CancelableCloseEvent('close', {\n code: event.code,\n reason: event.reason,\n wasClean: event.wasClean,\n cancelable: true,\n })\n )\n\n this[kEmitter].dispatchEvent(closeEvent)\n\n // If the close event from the server hasn't been prevented,\n // forward the closure to the mock client.\n if (!closeEvent.defaultPrevented) {\n // Close the intercepted client forcefully to\n // allow non-configurable status codes from the server.\n // If the socket has been closed by now, no harm calling\n // this again—it will have no effect.\n this.client[kClose](event.code, event.reason)\n }\n }\n}\n","import { bindEvent } from './utils/bindEvent'\nimport {\n StrictEventListenerOrEventListenerObject,\n WebSocketData,\n WebSocketTransport,\n WebSocketTransportEventMap,\n} from './WebSocketTransport'\nimport { kOnSend, kClose, WebSocketOverride } from './WebSocketOverride'\nimport { CancelableMessageEvent, CloseEvent } from './utils/events'\n\n/**\n * Abstraction over the given mock `WebSocket` instance that allows\n * for controlling that instance (e.g. sending and receiving messages).\n */\nexport class WebSocketClassTransport\n extends EventTarget\n implements WebSocketTransport\n{\n constructor(protected readonly socket: WebSocketOverride) {\n super()\n\n // Emit the \"close\" event on the transport if the close\n // originates from the WebSocket client. E.g. the application\n // calls \"ws.close()\", not the interceptor.\n this.socket.addEventListener('close', (event) => {\n this.dispatchEvent(bindEvent(this.socket, new CloseEvent('close', event)))\n })\n\n /**\n * Emit the \"outgoing\" event on the transport\n * whenever the WebSocket client sends data (\"ws.send()\").\n */\n this.socket[kOnSend] = (data) => {\n this.dispatchEvent(\n bindEvent(\n this.socket,\n // Dispatch this as cancelable because \"client\" connection\n // re-creates this message event (cannot dispatch the same event).\n new CancelableMessageEvent('outgoing', {\n data,\n origin: this.socket.url,\n cancelable: true,\n })\n )\n )\n }\n }\n\n public addEventListener(\n type: EventType,\n callback: StrictEventListenerOrEventListenerObject<\n WebSocketTransportEventMap[EventType]\n > | null,\n options?: boolean | AddEventListenerOptions\n ): void {\n return super.addEventListener(type, callback as EventListener, options)\n }\n\n public dispatchEvent(\n event: WebSocketTransportEventMap[EventType]\n ): boolean {\n return super.dispatchEvent(event)\n }\n\n public send(data: WebSocketData): void {\n queueMicrotask(() => {\n if (\n this.socket.readyState === this.socket.CLOSING ||\n this.socket.readyState === this.socket.CLOSED\n ) {\n return\n }\n\n const dispatchEvent = () => {\n this.socket.dispatchEvent(\n bindEvent(\n /**\n * @note Setting this event's \"target\" to the\n * WebSocket override instance is important.\n * This way it can tell apart original incoming events\n * (must be forwarded to the transport) from the\n * mocked message events like the one below\n * (must be dispatched on the client instance).\n */\n this.socket,\n new MessageEvent('message', {\n data,\n origin: this.socket.url,\n })\n )\n )\n }\n\n if (this.socket.readyState === this.socket.CONNECTING) {\n this.socket.addEventListener(\n 'open',\n () => {\n dispatchEvent()\n },\n { once: true }\n )\n } else {\n dispatchEvent()\n }\n })\n }\n\n public close(code: number, reason?: string): void {\n /**\n * @note Call the internal close method directly\n * to allow closing the connection with the status codes\n * that are non-configurable by the user (> 1000 <= 1015).\n */\n this.socket[kClose](code, reason)\n }\n}\n","import { Interceptor } from '../../Interceptor'\nimport {\n WebSocketClientConnectionProtocol,\n WebSocketClientConnection,\n type WebSocketClientEventMap,\n} from './WebSocketClientConnection'\nimport {\n WebSocketServerConnectionProtocol,\n WebSocketServerConnection,\n type WebSocketServerEventMap,\n} from './WebSocketServerConnection'\nimport { WebSocketClassTransport } from './WebSocketClassTransport'\nimport {\n kClose,\n kPassthroughPromise,\n WebSocketOverride,\n} from './WebSocketOverride'\nimport { bindEvent } from './utils/bindEvent'\nimport { hasConfigurableGlobal } from '../../utils/hasConfigurableGlobal'\nimport { emitAsync } from '../../utils/emitAsync'\n\nexport {\n type WebSocketData,\n type WebSocketTransport,\n} from './WebSocketTransport'\nexport {\n WebSocketClientEventMap,\n WebSocketClientConnectionProtocol,\n WebSocketClientConnection,\n WebSocketServerEventMap,\n WebSocketServerConnectionProtocol,\n WebSocketServerConnection,\n}\n\nexport {\n CloseEvent,\n CancelableCloseEvent,\n CancelableMessageEvent,\n} from './utils/events'\n\nexport type WebSocketEventMap = {\n connection: [args: WebSocketConnectionData]\n}\n\nexport type WebSocketConnectionData = {\n /**\n * The incoming WebSocket client connection.\n */\n client: WebSocketClientConnection\n\n /**\n * The original WebSocket server connection.\n */\n server: WebSocketServerConnection\n\n /**\n * The connection information.\n */\n info: {\n /**\n * The protocols supported by the WebSocket client.\n */\n protocols: string | Array | undefined\n }\n}\n\n/**\n * Intercept the outgoing WebSocket connections created using\n * the global `WebSocket` class.\n */\nexport class WebSocketInterceptor extends Interceptor {\n static symbol = Symbol('websocket')\n\n constructor() {\n super(WebSocketInterceptor.symbol)\n }\n\n protected checkEnvironment(): boolean {\n return hasConfigurableGlobal('WebSocket')\n }\n\n protected setup(): void {\n const originalWebSocketDescriptor = Object.getOwnPropertyDescriptor(\n globalThis,\n 'WebSocket'\n )\n\n const WebSocketProxy = new Proxy(globalThis.WebSocket, {\n construct: (\n target,\n args: ConstructorParameters,\n newTarget\n ) => {\n const [url, protocols] = args\n\n const createConnection = (): WebSocket => {\n return Reflect.construct(target, args, newTarget)\n }\n\n // All WebSocket instances are mocked and don't forward\n // any events to the original server (no connection established).\n // To forward the events, the user must use the \"server.send()\" API.\n const socket = new WebSocketOverride(url, protocols)\n const transport = new WebSocketClassTransport(socket)\n\n // Emit the \"connection\" event to the interceptor on the next tick\n // so the client can modify WebSocket options, like \"binaryType\"\n // while the connection is already pending.\n queueMicrotask(async () => {\n try {\n const server = new WebSocketServerConnection(\n socket,\n transport,\n createConnection\n )\n\n const hasConnectionListeners =\n this.emitter.listenerCount('connection') > 0\n\n // The \"globalThis.WebSocket\" class stands for\n // the client-side connection. Assume it's established\n // as soon as the WebSocket instance is constructed.\n await emitAsync(this.emitter, 'connection', {\n client: new WebSocketClientConnection(socket, transport),\n server,\n info: {\n protocols,\n },\n })\n\n if (hasConnectionListeners) {\n socket[kPassthroughPromise].resolve(false)\n } else {\n socket[kPassthroughPromise].resolve(true)\n\n server.connect()\n\n // Forward the \"open\" event from the original server\n // to the mock WebSocket client in the case of a passthrough connection.\n server.addEventListener('open', () => {\n socket.dispatchEvent(bindEvent(socket, new Event('open')))\n\n // Forward the original connection protocol to the\n // mock WebSocket client.\n if (server['realWebSocket']) {\n socket.protocol = server['realWebSocket'].protocol\n }\n })\n }\n } catch (error) {\n /**\n * @note Translate unhandled exceptions during the connection\n * handling (i.e. interceptor exceptions) as WebSocket connection\n * closures with error. This prevents from the exceptions occurring\n * in `queueMicrotask` from being process-wide and uncatchable.\n */\n if (error instanceof Error) {\n socket.dispatchEvent(new Event('error'))\n\n // No need to close the connection if it's already being closed.\n // E.g. the interceptor called `client.close()` and then threw an error.\n if (\n socket.readyState !== WebSocket.CLOSING &&\n socket.readyState !== WebSocket.CLOSED\n ) {\n socket[kClose](1011, error.message, false)\n }\n\n console.error(error)\n }\n }\n })\n\n return socket\n },\n })\n\n Object.defineProperty(globalThis, 'WebSocket', {\n value: WebSocketProxy,\n configurable: true,\n })\n\n this.subscriptions.push(() => {\n Object.defineProperty(\n globalThis,\n 'WebSocket',\n originalWebSocketDescriptor!\n )\n })\n }\n}\n","import { invariant } from 'outvariant'\nimport { isNodeProcess } from 'is-node-process'\nimport { WebSocketInterceptor } from '@mswjs/interceptors/WebSocket'\nimport {\n defineNetwork,\n NetworkReadyState,\n} from '#core/experimental/define-network'\nimport type { AnyHandler } from '#core/experimental/handlers-controller'\nimport { InterceptorSource } from '#core/experimental/sources/interceptor-source'\nimport { fromLegacyOnUnhandledRequest } from '#core/experimental/compat'\nimport type { LifeCycleEventEmitter } from '#core/sharedOptions'\nimport type { HttpNetworkFrameEventMap } from '#core/experimental/frames/http-frame'\nimport type { WebSocketNetworkFrameEventMap } from '#core/experimental/frames/websocket-frame'\nimport { devUtils } from '#core/utils/internal/devUtils'\nimport { supportsServiceWorker } from './utils/supports'\nimport { ServiceWorkerSource } from './sources/service-worker-source'\nimport { FallbackHttpSource } from './sources/fallback-http-source'\nimport type {\n SetupWorker,\n StartOptions,\n StartReturnType,\n StopHandler,\n} from './glossary'\n\nconst DEFAULT_WORKER_URL = '/mockServiceWorker.js'\n\n/**\n * Sets up a requests interception in the browser with the given request handlers.\n * @param {Array} handlers List of request handlers.\n *\n * @see {@link https://mswjs.io/docs/api/setup-worker `setupWorker()` API reference}\n */\nexport function setupWorker(...handlers: Array): SetupWorker {\n invariant(\n !isNodeProcess(),\n devUtils.formatMessage(\n 'Failed to execute `setupWorker` in a non-browser environment',\n ),\n )\n\n const network = defineNetwork<\n Array\n >({\n sources: [],\n handlers,\n })\n\n return {\n async start(options) {\n if (options?.waitUntilReady != null) {\n devUtils.warn(\n `The \"waitUntilReady\" option has been deprecated. Please remove it from this \"worker.start()\" call. Follow the recommended Browser integration (https://mswjs.io/docs/integrations/browser) to eliminate any race conditions between the Service Worker registration and any requests made by your application on initial render.`,\n )\n }\n\n /**\n * @todo @fixme\n * This is kept for backward-compatibility reasons. We don't really need this check anymore.\n */\n if (network.readyState === NetworkReadyState.ENABLED) {\n devUtils.warn(\n 'Found a redundant \"worker.start()\" call. Note that starting the worker while mocking is already enabled will have no effect. Consider removing this \"worker.start()\" call.',\n )\n return\n }\n\n const httpSource = supportsServiceWorker()\n ? await ServiceWorkerSource.from({\n serviceWorker: {\n url:\n options?.serviceWorker?.url?.toString() || DEFAULT_WORKER_URL,\n options: options?.serviceWorker?.options,\n },\n findWorker: options?.findWorker,\n quiet: options?.quiet,\n })\n : new FallbackHttpSource({\n quiet: options?.quiet,\n })\n\n network.configure({\n sources: [\n httpSource,\n new InterceptorSource({\n interceptors: [new WebSocketInterceptor() as any],\n }),\n ],\n onUnhandledFrame: fromLegacyOnUnhandledRequest(() => {\n return options?.onUnhandledRequest || 'warn'\n }),\n context: {\n quiet: options?.quiet,\n },\n })\n\n await network.enable()\n\n if (httpSource instanceof ServiceWorkerSource) {\n const [, registration] = await httpSource.workerPromise\n return registration\n }\n },\n stop() {\n if (network.readyState === NetworkReadyState.DISABLED) {\n devUtils.warn(\n `Found a redundant \"worker.stop()\" call. Notice that stopping the worker after it has already been stopped has no effect. Consider removing this \"worker.stop()\" call.`,\n )\n return\n }\n\n network.disable()\n window.postMessage({ type: 'msw/worker:stop' })\n },\n events: network.events,\n use: network.use.bind(network),\n resetHandlers: network.resetHandlers.bind(network),\n restoreHandlers: network.restoreHandlers.bind(network),\n listHandlers: network.listHandlers.bind(network),\n }\n}\n\n/**\n * @deprecated\n * Please use the `defineNetwork` API instead.\n */\nexport class SetupWorkerApi implements SetupWorker {\n start: (options?: StartOptions) => StartReturnType\n stop: StopHandler\n use: (...handlers: Array) => void\n resetHandlers: (...nextHandlers: Array) => void\n restoreHandlers: () => void\n listHandlers: () => ReadonlyArray\n events: LifeCycleEventEmitter<\n HttpNetworkFrameEventMap & WebSocketNetworkFrameEventMap\n >\n\n constructor() {\n const worker = setupWorker()\n\n this.start = worker.start.bind(worker)\n this.stop = worker.stop.bind(worker)\n this.use = worker.use.bind(worker)\n this.resetHandlers = worker.resetHandlers.bind(worker)\n this.restoreHandlers = worker.restoreHandlers.bind(worker)\n this.listHandlers = worker.listHandlers.bind(worker)\n this.events = worker.events\n }\n}\n","/**\n * Checks if the Service Worker API is supproted and available\n * in the current browsing context.\n */\nexport function supportsServiceWorker(): boolean {\n return (\n typeof navigator !== 'undefined' &&\n 'serviceWorker' in navigator &&\n typeof location !== 'undefined' &&\n location.protocol !== 'file:'\n )\n}\n\n/**\n * Returns a boolean indicating whether the current browser\n * supports `ReadableStream` as a `Transferable` when posting\n * messages.\n */\nexport function supportsReadableStreamTransfer() {\n try {\n const stream = new ReadableStream({\n start: (controller) => controller.close(),\n })\n const message = new MessageChannel()\n message.port1.postMessage(stream, [stream])\n return true\n } catch {\n return false\n }\n}\n","export type PromiseState = 'pending' | 'fulfilled' | 'rejected'\n\nexport type Executor = ConstructorParameters>[0]\nexport type ResolveFunction = Parameters>[0]\nexport type RejectFunction = Parameters>[1]\n\nexport type DeferredPromiseExecutor = {\n (resolve?: ResolveFunction, reject?: RejectFunction): void\n\n resolve: ResolveFunction\n reject: RejectFunction\n result?: Output\n state: PromiseState\n rejectionReason?: unknown\n}\nexport function createDeferredExecutor<\n Input = never,\n Output = Input\n>(): DeferredPromiseExecutor {\n const executor = >((\n resolve,\n reject\n ) => {\n executor.state = 'pending'\n\n executor.resolve = (data) => {\n if (executor.state !== 'pending') {\n return\n }\n\n executor.result = data as Output\n\n const onFulfilled = (value: Value) => {\n executor.state = 'fulfilled'\n return value\n }\n\n return resolve(\n data instanceof Promise ? data : Promise.resolve(data).then(onFulfilled)\n )\n }\n\n executor.reject = (reason) => {\n if (executor.state !== 'pending') {\n return\n }\n\n queueMicrotask(() => {\n executor.state = 'rejected'\n })\n\n return reject((executor.rejectionReason = reason))\n }\n })\n\n return executor\n}\n","import {\n type Executor,\n type RejectFunction,\n type ResolveFunction,\n type DeferredPromiseExecutor,\n createDeferredExecutor,\n} from './create-deferred-executor'\n\nexport class DeferredPromise extends Promise {\n #executor: DeferredPromiseExecutor\n\n public resolve: ResolveFunction\n public reject: RejectFunction\n\n constructor(executor: Executor | null = null) {\n const deferredExecutor = createDeferredExecutor()\n super((originalResolve, originalReject) => {\n deferredExecutor(originalResolve, originalReject)\n executor?.(deferredExecutor.resolve, deferredExecutor.reject)\n })\n\n this.#executor = deferredExecutor\n this.resolve = this.#executor.resolve\n this.reject = this.#executor.reject\n }\n\n public get state() {\n return this.#executor.state\n }\n\n public get rejectionReason() {\n return this.#executor.rejectionReason\n }\n\n public then(\n onFulfilled?: (value: Input) => ThenResult | PromiseLike,\n onRejected?: (reason: any) => CatchResult | PromiseLike,\n ) {\n return this.#decorate(super.then(onFulfilled, onRejected))\n }\n\n public catch(\n onRejected?: (reason: any) => CatchResult | PromiseLike,\n ) {\n return this.#decorate(super.catch(onRejected))\n }\n\n public finally(onfinally?: () => void | Promise) {\n return this.#decorate(super.finally(onfinally))\n }\n\n #decorate(\n promise: Promise,\n ): DeferredPromise {\n return Object.defineProperties(promise, {\n resolve: { configurable: true, value: this.resolve },\n reject: { configurable: true, value: this.reject },\n }) as DeferredPromise\n }\n}\n","import type { RequestController } from './RequestController'\n\nexport const IS_PATCHED_MODULE: unique symbol = Symbol('isPatchedModule')\n\n/**\n * @note Export `RequestController` as a type only.\n * It's never meant to be created in the userland.\n */\nexport type { RequestController }\n\nexport type RequestCredentials = 'omit' | 'include' | 'same-origin'\n\nexport type HttpRequestEventMap = {\n request: [\n args: {\n request: Request\n requestId: string\n controller: RequestController\n }\n ]\n response: [\n args: {\n response: Response\n isMockedResponse: boolean\n request: Request\n requestId: string\n }\n ]\n unhandledException: [\n args: {\n error: unknown\n request: Request\n requestId: string\n controller: RequestController\n }\n ]\n}\n","export class InterceptorError extends Error {\n constructor(message?: string) {\n super(message)\n this.name = 'InterceptorError'\n Object.setPrototypeOf(this, InterceptorError.prototype)\n }\n}\n","import { DeferredPromise } from '@open-draft/deferred-promise'\nimport { invariant } from 'outvariant'\nimport { InterceptorError } from './InterceptorError'\n\nexport interface RequestControllerSource {\n passthrough(): void\n respondWith(response: Response): void\n errorWith(reason?: unknown): void\n}\n\nexport class RequestController {\n static PENDING = 0 as const\n static PASSTHROUGH = 1 as const\n static RESPONSE = 2 as const\n static ERROR = 3 as const\n\n public readyState: number\n\n /**\n * A Promise that resolves when this controller handles a request.\n * See `controller.readyState` for more information on the handling result.\n */\n public handled: Promise\n\n constructor(\n protected readonly request: Request,\n protected readonly source: RequestControllerSource\n ) {\n this.readyState = RequestController.PENDING\n this.handled = new DeferredPromise()\n }\n\n get #handled() {\n return this.handled as DeferredPromise\n }\n\n /**\n * Perform this request as-is.\n */\n public async passthrough(): Promise {\n invariant.as(\n InterceptorError,\n this.readyState === RequestController.PENDING,\n 'Failed to passthrough the \"%s %s\" request: the request has already been handled',\n this.request.method,\n this.request.url\n )\n\n this.readyState = RequestController.PASSTHROUGH\n await this.source.passthrough()\n this.#handled.resolve()\n }\n\n /**\n * Respond to this request with the given `Response` instance.\n *\n * @example\n * controller.respondWith(new Response())\n * controller.respondWith(Response.json({ id }))\n * controller.respondWith(Response.error())\n */\n public respondWith(response: Response): void {\n invariant.as(\n InterceptorError,\n this.readyState === RequestController.PENDING,\n 'Failed to respond to the \"%s %s\" request with \"%d %s\": the request has already been handled (%d)',\n this.request.method,\n this.request.url,\n response.status,\n response.statusText || 'OK',\n this.readyState\n )\n\n this.readyState = RequestController.RESPONSE\n this.#handled.resolve()\n\n /**\n * @note Although `source.respondWith()` is potentially asynchronous,\n * do NOT await it for backward-compatibility. Awaiting it will short-circuit\n * the request listener invocation as soon as a listener responds to a request.\n * Ideally, that's what we want, but that's not what we promise the user.\n */\n this.source.respondWith(response)\n }\n\n /**\n * Error this request with the given reason.\n *\n * @example\n * controller.errorWith()\n * controller.errorWith(new Error('Oops!'))\n * controller.errorWith({ message: 'Oops!'})\n */\n public errorWith(reason?: unknown): void {\n invariant.as(\n InterceptorError,\n this.readyState === RequestController.PENDING,\n 'Failed to error the \"%s %s\" request with \"%s\": the request has already been handled (%d)',\n this.request.method,\n this.request.url,\n reason?.toString(),\n this.readyState\n )\n\n this.readyState = RequestController.ERROR\n this.source.errorWith(reason)\n this.#handled.resolve()\n }\n}\n","/**\n * Returns a boolean indicating whether the given URL string\n * can be parsed into a `URL` instance.\n * A substitute for `URL.canParse()` for Node.js 18.\n */\nexport function canParseUrl(url: string): boolean {\n try {\n new URL(url)\n return true\n } catch (_error) {\n return false\n }\n}\n","/**\n * Returns the value behind the symbol with the given name.\n */\nexport function getValueBySymbol(\n symbolName: string,\n source: object\n): T | undefined {\n const ownSymbols = Object.getOwnPropertySymbols(source)\n\n const symbol = ownSymbols.find((symbol) => {\n return symbol.description === symbolName\n })\n\n if (symbol) {\n return Reflect.get(source, symbol)\n }\n\n return\n}\n","import { canParseUrl } from './canParseUrl'\nimport { getValueBySymbol } from './getValueBySymbol'\n\nexport interface FetchResponseInit extends ResponseInit {\n url?: string\n}\n\ninterface UndiciFetchInternalState {\n aborted: boolean\n rangeRequested: boolean\n timingAllowPassed: boolean\n requestIncludesCredentials: boolean\n type: ResponseType\n status: number\n statusText: string\n timingInfo: unknown\n cacheState: unknown\n headersList: Record>\n urlList: Array\n body?: {\n stream: ReadableStream\n source: unknown\n length: number\n }\n}\n\nexport class FetchResponse extends Response {\n /**\n * Response status codes for responses that cannot have body.\n * @see https://fetch.spec.whatwg.org/#statuses\n */\n static readonly STATUS_CODES_WITHOUT_BODY = [101, 103, 204, 205, 304]\n\n static readonly STATUS_CODES_WITH_REDIRECT = [301, 302, 303, 307, 308]\n\n static isConfigurableStatusCode(status: number): boolean {\n return status >= 200 && status <= 599\n }\n\n static isRedirectResponse(status: number): boolean {\n return FetchResponse.STATUS_CODES_WITH_REDIRECT.includes(status)\n }\n\n /**\n * Returns a boolean indicating whether the given response status\n * code represents a response that can have a body.\n */\n static isResponseWithBody(status: number): boolean {\n return !FetchResponse.STATUS_CODES_WITHOUT_BODY.includes(status)\n }\n\n static setUrl(url: string | undefined, response: Response): void {\n if (!url || url === 'about:' || !canParseUrl(url)) {\n return\n }\n\n const state = getValueBySymbol('state', response)\n\n if (state) {\n // In Undici, push the URL to the internal list of URLs.\n // This will respect the `response.url` getter logic correctly.\n state.urlList.push(new URL(url))\n } else {\n // In other libraries, redefine the `url` property directly.\n Object.defineProperty(response, 'url', {\n value: url,\n enumerable: true,\n configurable: true,\n writable: false,\n })\n }\n }\n\n /**\n * Parses the given raw HTTP headers into a Fetch API `Headers` instance.\n */\n static parseRawHeaders(rawHeaders: Array): Headers {\n const headers = new Headers()\n for (let line = 0; line < rawHeaders.length; line += 2) {\n headers.append(rawHeaders[line], rawHeaders[line + 1])\n }\n return headers\n }\n\n constructor(body?: BodyInit | null, init: FetchResponseInit = {}) {\n const status = init.status ?? 200\n const safeStatus = FetchResponse.isConfigurableStatusCode(status)\n ? status\n : 200\n const finalBody = FetchResponse.isResponseWithBody(status) ? body : null\n\n super(finalBody, {\n status: safeStatus,\n statusText: init.statusText,\n headers: init.headers,\n })\n\n if (status !== safeStatus) {\n /**\n * @note Undici keeps an internal \"Symbol(state)\" that holds\n * the actual value of response status. Update that in Node.js.\n */\n const state = getValueBySymbol('state', this)\n\n if (state) {\n state.status = status\n } else {\n Object.defineProperty(this, 'status', {\n value: status,\n enumerable: true,\n configurable: true,\n writable: false,\n })\n }\n }\n\n FetchResponse.setUrl(init.url, this)\n }\n}\n","const kRawRequest = Symbol('kRawRequest')\n\n/**\n * Returns a raw request instance associated with this request.\n *\n * @example\n * interceptor.on('request', ({ request }) => {\n * const rawRequest = getRawRequest(request)\n *\n * if (rawRequest instanceof http.ClientRequest) {\n * console.log(rawRequest.rawHeaders)\n * }\n * })\n */\nexport function getRawRequest(request: Request): unknown | undefined {\n return Reflect.get(request, kRawRequest)\n}\n\nexport function setRawRequest(request: Request, rawRequest: unknown): void {\n Reflect.set(request, kRawRequest, rawRequest)\n}\n","const encoder = new TextEncoder()\n\nexport function encodeBuffer(text: string): Uint8Array {\n return encoder.encode(text)\n}\n\nexport function decodeBuffer(buffer: ArrayBuffer, encoding?: string): string {\n const decoder = new TextDecoder(encoding)\n return decoder.decode(buffer)\n}\n\n/**\n * Create an `ArrayBuffer` from the given `Uint8Array`.\n * Takes the byte offset into account to produce the right buffer\n * in the case when the buffer is bigger than the data view.\n */\nexport function toArrayBuffer(array: Uint8Array): ArrayBuffer {\n return array.buffer.slice(\n array.byteOffset,\n array.byteOffset + array.byteLength\n )\n}\n","import { invariant } from 'outvariant'\nimport type { Emitter } from 'rettime'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\nimport { FetchResponse } from '@mswjs/interceptors'\nimport { NetworkSource } from '#core/experimental/sources/network-source'\nimport { RequestHandler } from '#core/handlers/RequestHandler'\nimport {\n HttpNetworkFrame,\n ResponseEvent,\n} from '#core/experimental/frames/http-frame'\nimport { HttpResponse } from '#core/HttpResponse'\nimport { toResponseInit } from '#core/utils/toResponseInit'\nimport { devUtils } from '#core/utils/internal/devUtils'\nimport {\n supportsReadableStreamTransfer,\n supportsServiceWorker,\n} from '../utils/supports'\nimport { getWorkerInstance } from '../utils/get-worker-instance'\nimport type { WorkerChannelEventMap } from '../utils/workerChannel'\nimport { WorkerChannel } from '../utils/workerChannel'\nimport type { FindWorker } from '../glossary'\nimport { deserializeRequest } from '../utils/deserializeRequest'\nimport { validateWorkerScope } from '../utils/validate-worker-scope'\nimport { shouldInvalidateWorker } from '../utils/should-invalidate-worker'\n\nexport interface ServiceWorkerSourceOptions {\n quiet?: boolean\n serviceWorker: {\n url: string\n options?: RegistrationOptions\n }\n findWorker?: FindWorker\n}\n\ntype WorkerChannelRequestEvent = Emitter.Event<\n WorkerChannel,\n 'REQUEST',\n WorkerChannelEventMap\n>\n\ntype WorkerChannelResponseEvent = Emitter.Event<\n WorkerChannel,\n 'RESPONSE',\n WorkerChannelEventMap\n>\n\ntype WorkerChannelClient =\n WorkerChannelEventMap['MOCKING_ENABLED']['data']['client']\n\nexport class ServiceWorkerSource extends NetworkSource {\n static #current?: ServiceWorkerSource\n\n /**\n * Create a new Service Worker source or reuse an existing one.\n * These sources act as a singleton and only get recreated if the options change.\n */\n public static async from(\n options: ServiceWorkerSourceOptions,\n ): Promise {\n if (ServiceWorkerSource.#current == null) {\n ServiceWorkerSource.#current = new ServiceWorkerSource(options)\n } else if (\n shouldInvalidateWorker(ServiceWorkerSource.#current.#options, options)\n ) {\n await ServiceWorkerSource.#current.terminate()\n ServiceWorkerSource.#current = new ServiceWorkerSource(options)\n }\n\n return ServiceWorkerSource.#current\n }\n\n #options: ServiceWorkerSourceOptions\n #frames: Map\n #channel: WorkerChannel\n #listenerController?: AbortController\n #clientPromise?: Promise\n #keepAliveInterval?: number\n #stoppedAt?: number\n\n public workerPromise: DeferredPromise<\n [ServiceWorker, ServiceWorkerRegistration]\n >\n\n constructor(options: ServiceWorkerSourceOptions) {\n super()\n\n invariant(\n supportsServiceWorker(),\n 'Failed to use Service Worker as the network source: the Service Worker API is not supported in this environment',\n )\n\n this.#options = options\n this.#frames = new Map()\n this.workerPromise = new DeferredPromise()\n this.#channel = new WorkerChannel({\n getWorker: () => this.workerPromise.then(([worker]) => worker),\n })\n }\n\n public async enable(): Promise {\n /**\n * @note The source is considered already running if the worker has been\n * resolved AND `stop()` has not been called since. `workerPromise` is NOT\n * reset on `disable()` so that the channel's `getWorker()` can keep\n * resolving to the registered SW for post-stop passthrough replies.\n */\n if (\n this.workerPromise.state === 'fulfilled' &&\n typeof this.#stoppedAt == 'undefined'\n ) {\n devUtils.warn(\n 'Found a redundant \"worker.start()\" call. Note that starting the worker while mocking is already enabled will have no effect. Consider removing this \"worker.start()\" call.',\n )\n\n return this.workerPromise.then(([, registration]) => registration)\n }\n\n this.#stoppedAt = undefined\n this.#channel.removeAllListeners()\n this.#frames.clear()\n\n this.#listenerController = new AbortController()\n const [worker, registration] = await this.#startWorker()\n\n if (worker.state !== 'activated') {\n const controller = new AbortController()\n const activationPromise = new DeferredPromise()\n activationPromise.then(() => controller.abort())\n\n worker.addEventListener(\n 'statechange',\n () => {\n if (worker.state === 'activated') {\n activationPromise.resolve()\n }\n },\n {\n signal: controller.signal,\n },\n )\n\n await activationPromise\n }\n\n this.#channel.postMessage('MOCK_ACTIVATE')\n\n const clientConfirmationPromise = new DeferredPromise()\n this.#clientPromise = clientConfirmationPromise\n\n this.#channel.once('MOCKING_ENABLED', (event) => {\n clientConfirmationPromise.resolve(event.data.client)\n })\n await clientConfirmationPromise\n\n if (!this.#options.quiet) {\n this.#printStartMessage()\n }\n\n return registration\n }\n\n public disable(): void {\n /**\n * @note Do NOT call `super.disable()` because it removes any \"frame\" listeners\n * from this network source, effectively turning it off. The Service Worker source\n * is a bit special since it might process in-flight requests that have been performed\n * after it's been disabled.\n */\n\n if (typeof this.#stoppedAt !== 'undefined') {\n devUtils.warn(\n `Found a redundant \"worker.stop()\" call. Notice that stopping the worker after it has already been stopped has no effect. Consider removing this \"worker.stop()\" call.`,\n )\n\n return\n }\n\n this.#stoppedAt = Date.now()\n\n this.#listenerController?.abort()\n this.#listenerController = undefined\n\n /**\n * @note Tell the Service Worker to drop this client from its active set\n * so it stops forwarding REQUEST events here. `stoppedAt` still guards\n * any requests the SW already forwarded before this message arrived.\n */\n this.#channel.postMessage('CLIENT_CLOSED')\n\n /**\n * @note Do NOT reset `workerPromise` here. The channel must continue to\n * resolve the currently registered SW so that any in-flight requests the\n * worker forwards after `stop()` can be answered with `PASSTHROUGH` by\n * `#handleRequest`. `#startWorker` swaps in a fresh deferred on re-enable.\n */\n\n if (!this.#options.quiet) {\n this.#printStopMessage()\n }\n }\n\n /**\n * Terminal teardown. Unregisters the Service Worker, tears down the channel,\n * and clears timers. Called when the singleton is being replaced with one\n * that has different options. The instance is not usable afterwards.\n */\n public async terminate(): Promise {\n if (this.#keepAliveInterval != null) {\n clearInterval(this.#keepAliveInterval)\n this.#keepAliveInterval = undefined\n }\n\n this.#frames.clear()\n this.#channel.terminate()\n this.#listenerController?.abort()\n this.#listenerController = undefined\n\n if (this.workerPromise.state === 'fulfilled') {\n const [, registration] = await this.workerPromise\n await registration.unregister()\n }\n\n if (ServiceWorkerSource.#current === this) {\n ServiceWorkerSource.#current = undefined\n }\n }\n\n async #startWorker() {\n if (this.#keepAliveInterval) {\n clearInterval(this.#keepAliveInterval)\n }\n\n const workerUrl = this.#options.serviceWorker.url\n\n const [worker, registration] = await getWorkerInstance(\n workerUrl,\n this.#options.serviceWorker.options,\n this.#options.findWorker || this.#defaultFindWorker,\n )\n\n if (worker == null) {\n const missingWorkerMessage = this.#options?.findWorker\n ? devUtils.formatMessage(\n `Failed to locate the Service Worker registration using a custom \"findWorker\" predicate.\n\nPlease ensure that the custom predicate properly locates the Service Worker registration at \"%s\".\nMore details: https://mswjs.io/docs/api/setup-worker/start#findworker\n `,\n workerUrl,\n )\n : devUtils.formatMessage(\n `Failed to locate the Service Worker registration.\n\nThis most likely means that the worker script URL \"%s\" cannot resolve against the actual public hostname (%s). This may happen if your application runs behind a proxy, or has a dynamic hostname.\n\nPlease consider using a custom \"serviceWorker.url\" option to point to the actual worker script location, or a custom \"findWorker\" option to resolve the Service Worker registration manually. More details: https://mswjs.io/docs/api/setup-worker/start`,\n workerUrl,\n location.host,\n )\n\n throw new Error(missingWorkerMessage)\n }\n\n if (this.workerPromise.state === 'pending') {\n this.workerPromise.resolve([worker, registration])\n } else {\n /**\n * @note Re-enable after `stop()`: the previous `workerPromise` is already\n * fulfilled and cannot be resolved again. Swap in a pre-resolved one so\n * `getWorker()` sees the new worker instance immediately.\n */\n this.workerPromise = new DeferredPromise((resolve) => {\n resolve([worker, registration])\n })\n }\n\n this.#channel.on('REQUEST', this.#handleRequest.bind(this))\n this.#channel.on('RESPONSE', this.#handleResponse.bind(this))\n\n window.addEventListener(\n 'beforeunload',\n () => {\n if (worker.state !== 'redundant') {\n this.#channel.postMessage('CLIENT_CLOSED')\n }\n\n clearInterval(this.#keepAliveInterval)\n\n window.postMessage({ type: 'msw/worker:stop' })\n },\n {\n signal: this.#listenerController?.signal,\n },\n )\n\n await this.#checkWorkerIntegrity().catch((error) => {\n devUtils.error(\n 'Error while checking the worker script integrity. Please report this on GitHub (https://github.com/mswjs/msw/issues) and include the original error below.',\n )\n console.error(error)\n })\n\n this.#keepAliveInterval = window.setInterval(() => {\n this.#channel.postMessage('KEEPALIVE_REQUEST')\n }, 5000)\n\n if (!this.#options.quiet) {\n validateWorkerScope(registration)\n }\n\n return [worker, registration] as const\n }\n\n async #handleRequest(event: WorkerChannelRequestEvent): Promise {\n if (this.#stoppedAt && event.data.interceptedAt > this.#stoppedAt) {\n return event.postMessage('PASSTHROUGH')\n }\n\n const request = deserializeRequest(event.data)\n RequestHandler.cache.set(request, request.clone())\n\n const frame = new ServiceWorkerHttpNetworkFrame({\n event,\n request,\n })\n this.#frames.set(event.data.id, frame)\n\n await this.queue(frame)\n }\n\n async #handleResponse(event: WorkerChannelResponseEvent): Promise {\n const { request, response, isMockedResponse } = event.data\n const frame = this.#frames.get(request.id)\n\n /**\n * CORS requests with `mode: \"no-cors\"` result in \"opaque\" responses.\n * That kind of responses cannot be manipulated in JavaScript due\n * to the security considerations.\n * @see https://fetch.spec.whatwg.org/#concept-filtered-response-opaque\n * @see https://github.com/mswjs/msw/issues/529\n */\n if (response.type?.includes('opaque')) {\n this.#frames.delete(request.id)\n frame?.events.removeAllListeners()\n return\n }\n\n this.#frames.delete(request.id)\n\n /**\n * @note A request frame will be missing in case of passthrough after the worker is stopped.\n * Creating a frame is costly so it's better to handle it as an edge case here.\n */\n if (frame == null) {\n return\n }\n\n const fetchRequest = deserializeRequest(request)\n const fetchResponse =\n response.status === 0\n ? Response.error()\n : new FetchResponse(\n /**\n * Responses may be streams here, but when we create a response object\n * with null-body status codes, like 204, 205, 304 Response will\n * throw when passed a non-null body, so ensure it's null here\n * for those codes\n */\n FetchResponse.isResponseWithBody(response.status)\n ? response.body\n : null,\n {\n ...response,\n /**\n * Set response URL if it's not set already.\n * @see https://github.com/mswjs/msw/issues/2030\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Response/url\n */\n url: request.url,\n },\n )\n\n try {\n frame.events.emit(\n new ResponseEvent(\n isMockedResponse ? 'response:mocked' : 'response:bypass',\n {\n requestId: frame.data.id,\n request: fetchRequest,\n response: fetchResponse,\n isMockedResponse,\n },\n ),\n )\n } finally {\n frame.events.removeAllListeners()\n }\n }\n\n #defaultFindWorker: FindWorker = (workerUrl, mockServiceWorkerUrl) => {\n return workerUrl === mockServiceWorkerUrl\n }\n\n async #checkWorkerIntegrity(): Promise {\n const integrityCheckPromise = new DeferredPromise()\n\n this.#channel.postMessage('INTEGRITY_CHECK_REQUEST')\n this.#channel.once('INTEGRITY_CHECK_RESPONSE', (event) => {\n const { checksum, packageVersion } = event.data\n\n // Compare the response from the Service Worker and the\n // global variable set during the build.\n\n // The integrity is validated based on the worker script's checksum\n // that's derived from its minified content during the build.\n // The \"SERVICE_WORKER_CHECKSUM\" global variable is injected by the build.\n if (checksum !== SERVICE_WORKER_CHECKSUM) {\n devUtils.warn(\n `The currently registered Service Worker has been generated by a different version of MSW (${packageVersion}) and may not be fully compatible with the installed version.\n\nIt's recommended you update your worker script by running this command:\n\n \\u2022 npx msw init \n\nYou can also automate this process and make the worker script update automatically upon the library installations. Read more: https://mswjs.io/docs/cli/init.`,\n )\n }\n\n integrityCheckPromise.resolve()\n })\n\n return integrityCheckPromise\n }\n\n async #printStartMessage() {\n if (this.workerPromise.state === 'rejected') {\n return\n }\n\n invariant(\n this.#clientPromise != null,\n '[ServiceWorkerSource] Failed to print a start message: client confirmation not received',\n )\n\n const client = await this.#clientPromise\n const [worker, registration] = await this.workerPromise\n\n console.groupCollapsed(\n `%c${devUtils.formatMessage('Mocking enabled.')}`,\n 'color:orangered;font-weight:bold;',\n )\n // eslint-disable-next-line no-console\n console.log(\n '%cDocumentation: %chttps://mswjs.io/docs',\n 'font-weight:bold',\n 'font-weight:normal',\n )\n // eslint-disable-next-line no-console\n console.log('Found an issue? https://github.com/mswjs/msw/issues')\n\n // eslint-disable-next-line no-console\n console.log('Worker script URL:', worker.scriptURL)\n\n // eslint-disable-next-line no-console\n console.log('Worker scope:', registration.scope)\n\n if (client) {\n // eslint-disable-next-line no-console\n console.log('Client ID: %s (%s)', client.id, client.frameType)\n }\n\n console.groupEnd()\n }\n\n #printStopMessage(): void {\n // eslint-disable-next-line no-console\n console.log(\n `%c${devUtils.formatMessage('Mocking disabled.')}`,\n 'color:orangered;font-weight:bold;',\n )\n }\n}\n\nclass ServiceWorkerHttpNetworkFrame extends HttpNetworkFrame {\n #event: WorkerChannelRequestEvent\n\n constructor(options: { event: WorkerChannelRequestEvent; request: Request }) {\n super({ request: options.request })\n this.#event = options.event\n }\n\n public passthrough(): void {\n this.#event.postMessage('PASSTHROUGH')\n }\n\n public respondWith(response?: Response): void {\n if (response) {\n this.#respondWith(response)\n }\n }\n\n public errorWith(reason?: unknown): void {\n if (reason instanceof Response) {\n return this.respondWith(reason)\n }\n\n devUtils.warn(\n `Uncaught exception in the request handler for \"%s %s\". This exception has been gracefully handled as a 500 response, however, it's strongly recommended to resolve this error, as it indicates a mistake in your code. If you wish to mock an error response, please see this guide: https://mswjs.io/docs/http/mocking-responses/error-responses`,\n this.data.request.method,\n this.data.request.url,\n )\n\n const error =\n reason instanceof Error\n ? reason\n : new Error(reason?.toString() || 'Request failure')\n\n // Treat exceptions during the request handling as 500 responses.\n // This should alert the developer that there's a problem.\n this.respondWith(\n HttpResponse.json(\n {\n name: error.name,\n message: error.message,\n stack: error.stack,\n },\n {\n status: 500,\n statusText: 'Request Handler Error',\n },\n ),\n )\n }\n\n async #respondWith(response: Response): Promise {\n let responseBody: ReadableStream | ArrayBuffer | null\n let transfer: [ReadableStream] | undefined\n const responseInit = toResponseInit(response)\n\n if (supportsReadableStreamTransfer()) {\n responseBody = response.body\n transfer = response.body == null ? undefined : [response.body]\n } else {\n responseBody =\n response.body == null ? null : await response.clone().arrayBuffer()\n }\n\n this.#event.postMessage(\n 'MOCK_RESPONSE',\n {\n ...responseInit,\n body: responseBody,\n },\n transfer,\n )\n }\n}\n","export type UntilResult =\n | [reason: RejectionReason, data: null]\n | [reason: null, data: ResolveData]\n\n/**\n * Gracefully handles a callback that returns a promise.\n *\n * @example\n * await until(() => Promise.resolve(123))\n * // [null, 123]\n *\n * await until(() => Promise.reject(new Error('Oops!')))\n * // [new Error('Oops!'), null]\n */\nexport async function until(\n callback: () => Promise,\n): Promise> {\n try {\n const data = await callback().catch((error) => {\n throw error\n })\n return [null, data]\n } catch (error: any) {\n return [error, null]\n }\n}\n","import { until } from 'until-async'\nimport { devUtils } from '#core/utils/internal/devUtils'\nimport { getAbsoluteWorkerUrl } from './getAbsoluteWorkerUrl'\nimport { getWorkerByRegistration } from './get-worker-by-registration'\nimport type { ServiceWorkerInstanceTuple, FindWorker } from '../glossary'\n\n/**\n * Returns an active Service Worker instance.\n * When not found, registers a new Service Worker.\n */\nexport const getWorkerInstance = async (\n url: string,\n options: RegistrationOptions = {},\n findWorker: FindWorker,\n): Promise => {\n // Resolve the absolute Service Worker URL.\n const absoluteWorkerUrl = getAbsoluteWorkerUrl(url)\n\n const mockRegistrations = await navigator.serviceWorker\n .getRegistrations()\n .then((registrations) =>\n registrations.filter((registration) =>\n getWorkerByRegistration(registration, absoluteWorkerUrl, findWorker),\n ),\n )\n if (!navigator.serviceWorker.controller && mockRegistrations.length > 0) {\n // Reload the page when it has associated workers, but no active controller.\n // The absence of a controller can mean either:\n // - page has no Service Worker associated with it\n // - page has been hard-reloaded and its workers won't be used until the next reload.\n // Since we've checked that there are registrations associated with this page,\n // at this point we are sure it's hard reload that falls into this clause.\n location.reload()\n }\n\n const [existingRegistration] = mockRegistrations\n\n if (existingRegistration) {\n // Schedule the worker update in the background.\n // Update ensures the existing worker is up-to-date.\n existingRegistration.update()\n\n // Return the worker reference immediately.\n return [\n getWorkerByRegistration(\n existingRegistration,\n absoluteWorkerUrl,\n findWorker,\n ),\n existingRegistration,\n ]\n }\n\n // When the Service Worker wasn't found, register it anew and return the reference.\n const [registrationError, registrationResult] = await until<\n Error,\n ServiceWorkerInstanceTuple\n >(async () => {\n const registration = await navigator.serviceWorker.register(url, options)\n return [\n // Compare existing worker registration by its worker URL,\n // to prevent irrelevant workers to resolve here (such as Codesandbox worker).\n getWorkerByRegistration(registration, absoluteWorkerUrl, findWorker),\n registration,\n ]\n })\n\n // Handle Service Worker registration errors.\n if (registrationError) {\n const isWorkerMissing = registrationError.message.includes('(404)')\n\n // Produce a custom error message when given a non-existing Service Worker url.\n // Suggest developers to check their setup.\n if (isWorkerMissing) {\n const scopeUrl = new URL(options?.scope || '/', location.href)\n\n throw new Error(\n devUtils.formatMessage(`\\\nFailed to register a Service Worker for scope ('${scopeUrl.href}') with script ('${absoluteWorkerUrl}'): Service Worker script does not exist at the given path.\n\nDid you forget to run \"npx msw init \"?\n\nLearn more about creating the Service Worker script: https://mswjs.io/docs/cli/init`),\n )\n }\n\n // Fallback error message for any other registration errors.\n throw new Error(\n devUtils.formatMessage(\n 'Failed to register the Service Worker:\\n\\n%s',\n registrationError.message,\n ),\n )\n }\n\n return registrationResult\n}\n","/**\n * Returns an absolute Service Worker URL based on the given\n * relative URL (known during the registration).\n */\nexport function getAbsoluteWorkerUrl(workerUrl: string): string {\n return new URL(workerUrl, location.href).href\n}\n","import type { FindWorker } from '../glossary'\n\n/**\n * Attempts to resolve a Service Worker instance from a given registration,\n * regardless of its state (active, installing, waiting).\n */\nexport function getWorkerByRegistration(\n registration: ServiceWorkerRegistration,\n absoluteWorkerUrl: string,\n findWorker: FindWorker,\n): ServiceWorker | null {\n const allStates = [\n registration.active,\n registration.installing,\n registration.waiting,\n ]\n\n const relevantStates = allStates.filter((state): state is ServiceWorker => {\n return state != null\n })\n\n const worker = relevantStates.find((worker) => {\n return findWorker(worker.scriptURL, absoluteWorkerUrl)\n })\n\n return worker || null\n}\n","type Values = M[keyof M & string]\n\nexport class LensList> {\n #list: Array<[string, Values]>\n #lens: Map>>\n\n constructor() {\n this.#list = []\n this.#lens = new Map()\n }\n\n get [Symbol.iterator]() {\n // Return the list's iterator so iteration is order-sensitive.\n return this.#list[Symbol.iterator].bind(this.#list)\n }\n\n public entries() {\n return this.#lens.entries()\n }\n\n /**\n * Return an order-sensitive list of values by the given key.\n */\n public get(key: K): Array {\n return (this.#lens.get(key) || []) as Array\n }\n\n /**\n * Return an order-sensitive list of all values.\n */\n public getAll(): Array> {\n return this.#list.map(([, value]) => value)\n }\n\n /**\n * Append a new value to the given key.\n */\n public append(\n key: K,\n value: ValueMap[K],\n ): void {\n this.#list.push([key, value])\n this.#openLens(key, (list) => list.push(value))\n }\n\n /**\n * Prepend a new value to the given key.\n */\n public prepend(\n key: K,\n value: ValueMap[K],\n ): void {\n this.#list.unshift([key, value])\n this.#openLens(key, (list) => list.unshift(value))\n }\n\n /**\n * Delete the value belonging to the given key.\n * Returns `true` if the value was present and removed, `false` otherwise.\n */\n public delete(\n key: K,\n value: ValueMap[K],\n ): boolean {\n if (this.size === 0) {\n return false\n }\n\n const values = this.#lens.get(key)\n if (!values) {\n return false\n }\n\n const index = values.indexOf(value)\n if (index === -1) {\n return false\n }\n\n values.splice(index, 1)\n this.#list.splice(\n this.#list.findIndex(\n (item) => item[0] === key && item[1] === value,\n ),\n 1,\n )\n return true\n }\n\n /**\n * Delete all values belogning to the given key.\n */\n public deleteAll(key: K): void {\n if (this.size === 0) {\n return\n }\n\n this.#list = this.#list.filter((item) => item[0] !== key)\n this.#lens.delete(key)\n }\n\n get size(): number {\n return this.#list.length\n }\n\n public clear(): void {\n if (this.size === 0) {\n return\n }\n\n this.#list.length = 0\n this.#lens.clear()\n }\n\n #openLens(\n key: string,\n setter: (target: Array>) => void,\n ): void {\n setter(this.#lens.get(key) || this.#lens.set(key, []).get(key))\n }\n}\n","import { LensList } from './lens-list'\n\nexport type DefaultEventMap = {\n [eventType: string]: TypedEvent\n}\n\n/**\n * Reserved event map containing special event types like '*' for catch-all listeners.\n */\nexport type ReservedEventMap = {\n '*': TypedEvent\n}\n\ntype IsReservedEvent = Type extends keyof ReservedEventMap\n ? true\n : false\n\nexport interface TypedEvent<\n DataType = void,\n ReturnType = void,\n EventType extends string = string,\n> extends Omit, 'type'> {\n type: EventType\n}\n\nconst kDefaultPrevented = Symbol('kDefaultPrevented')\nconst kPropagationStopped = Symbol('kPropagationStopped')\nconst kImmediatePropagationStopped = Symbol('kImmediatePropagationStopped')\n\nexport class TypedEvent<\n DataType = void,\n ReturnType = void,\n EventType extends string = string,\n>\n extends MessageEvent\n implements TypedEvent\n{\n /**\n * @note Keep a placeholder property with the return type\n * because the type must be set somewhere in order to be\n * correctly associated and inferred from the event.\n */\n #returnType: ReturnType;\n\n [kDefaultPrevented]: boolean;\n [kPropagationStopped]?: Emitter;\n [kImmediatePropagationStopped]?: boolean\n\n constructor(\n ...args: [DataType] extends [void]\n ? [type: EventType]\n : [type: EventType, init: { data: DataType }]\n ) {\n super(args[0], args[1])\n this[kDefaultPrevented] = false\n }\n\n get defaultPrevented(): boolean {\n return this[kDefaultPrevented]\n }\n\n public preventDefault(): void {\n super.preventDefault()\n this[kDefaultPrevented] = true\n }\n\n public stopImmediatePropagation(): void {\n /**\n * @note Despite `.stopPropagation()` and `.stopImmediatePropagation()` being defined\n * in Node.js, they do nothing. It is safe to re-define them.\n */\n super.stopImmediatePropagation()\n this[kImmediatePropagationStopped] = true\n }\n}\n\n/**\n * Brands a TypedEvent or its subclass while preserving its (narrower) type.\n */\ntype Brand<\n Event extends TypedEvent,\n EventType extends string,\n Loose extends boolean = false,\n> = Loose extends true\n ? Event extends TypedEvent\n ? /**\n * @note Omit the `ReturnType` so emit methods can accept type events\n * where infering the return type is impossible.\n */\n TypedEvent & {\n type: EventType\n }\n : never\n : Event & { type: EventType }\n\ntype InferEventMap> =\n Target extends Emitter ? WithReservedEvents : never\n\n/**\n * Extracts only user-defined events, excluding reserved event types.\n */\ntype UserEventMap = Omit<\n EventMap,\n keyof ReservedEventMap\n>\n\n/**\n * Decorates the given `EventMap` with the reserved emitter events (e.g. `*`).\n */\nexport type WithReservedEvents = EventMap &\n ReservedEventMap\n\n/**\n * Creates a union of all events in the EventMap with their literal type strings.\n */\ntype AllEvents = {\n [K in keyof EventMap & string]: Brand\n}[keyof EventMap & string]\n\nexport type TypedListenerOptions = {\n once?: boolean\n signal?: AbortSignal\n}\n\nexport interface HookListenerOptions extends TypedListenerOptions {\n persist?: boolean\n}\n\nexport type EmitterHookMap = {\n newListener: (\n type: keyof WithReservedEvents & string,\n listener: {\n [K in keyof WithReservedEvents & string]: Emitter.Listener<\n Emitter,\n K,\n WithReservedEvents\n >\n }[keyof WithReservedEvents & string],\n options: HookListenerOptions | undefined,\n ) => void\n\n removeListener: (\n type: keyof WithReservedEvents & string,\n listener: {\n [K in keyof WithReservedEvents & string]: Emitter.Listener<\n Emitter,\n K,\n WithReservedEvents\n >\n }[keyof WithReservedEvents & string],\n options: HookListenerOptions | undefined,\n ) => void\n\n beforeEmit: (event: EventMap[keyof EventMap & string]) => boolean | void\n}\n\nexport namespace Emitter {\n /**\n * Returns a union of all event types, both public and reserved, for the given emitter.\n *\n * @example\n * const emitter = new Emitter<{ greeting: TypedEvent, handshake: TypedEvent }>()\n * type AllEventTypes = Emitter.AllEventTypes\n * // \"*\" | \"greeting\" | \"handshake\"\n */\n export type AllEventTypes<\n Target extends Emitter,\n EventMap extends DefaultEventMap = InferEventMap,\n > = string extends keyof EventMap ? never : keyof EventMap & string\n\n /**\n * Returns a union of all public event types for the given emitter.\n *\n * @example\n * const emitter = new Emitter<{ greeting: TypedEvent, handshake: TypedEvent }>()\n * type EventTypes = Emitter.EventTypes\n * // \"greeting\" | \"handshake\"\n */\n export type PublicEventTypes<\n Target extends Emitter,\n EventMap extends DefaultEventMap = InferEventMap,\n UserEvents extends UserEventMap = UserEventMap,\n > = string extends keyof UserEvents ? never : keyof UserEvents & string\n\n /**\n * Returns a union of all public event type for the given emitter.\n *\n * @example\n * const emitter = new Emitter<{ greeting: GreetingEvent, handshake: HandshakeEvent }>()\n * type Events = Emitter.Events\n * // GreetingEvent | HandshakeEvent\n */\n export type Events<\n Target extends Emitter,\n EventMap extends DefaultEventMap = InferEventMap,\n > = string extends keyof UserEventMap\n ? never\n : UserEventMap[keyof UserEventMap]\n\n /**\n * Returns an appropriate `Event` type for the given event type.\n *\n * @example\n * const emitter = new Emitter<{ greeting: TypedEvent }>()\n * type GreetingEvent = Emitter.Event\n * // TypedEvent\n */\n export type Event<\n Target extends Emitter,\n EventType extends keyof EventMap & string,\n EventMap extends DefaultEventMap = InferEventMap,\n > =\n IsReservedEvent extends true\n ? AllEvents>\n : Brand\n\n /**\n * Returns an appropriate event data type for the given event type.\n *\n * @example\n * const emitter = new Emitter<{ greeting: TypedEvent<'hello'> }>()\n * type GreetingData = Emitter.EventData\n * // \"hello\"\n */\n export type EventData<\n Target extends Emitter,\n EventType extends keyof EventMap & string,\n EventMap extends DefaultEventMap = InferEventMap,\n > = EventMap[EventType] extends TypedEvent ? DataType : never\n\n /**\n * Returns the listener type for the given event type.\n *\n * @example\n * const emitter = new Emitter<{ getTotalPrice: TypedEvent }>()\n * type Listener = Emitter.ListenerType\n * // (event: TypedEvent) => number\n */\n export type Listener<\n Target extends Emitter,\n EventType extends keyof EventMap & string,\n EventMap extends DefaultEventMap = InferEventMap,\n > =\n IsReservedEvent extends true\n ? (event: Emitter.Event) => void\n : (\n event: Emitter.Event,\n ) => Emitter.ListenerReturnType extends [\n void,\n ]\n ? void\n : Emitter.ListenerReturnType\n\n /**\n * Returns the return type of the listener for the given event type.\n *\n * @example\n * const emitter = new Emitter<{ getTotalPrice: TypedEvent }>()\n * type ListenerReturnType = Emitter.ListenerReturnType\n * // number\n */\n export type ListenerReturnType<\n Target extends Emitter,\n EventType extends keyof EventMap & string,\n EventMap extends DefaultEventMap = InferEventMap,\n > =\n IsReservedEvent extends true\n ? void\n : EventMap[EventType] extends TypedEvent\n ? ReturnType\n : never\n}\n\nexport namespace EventMap {\n /**\n * Returns a union of all public event types from the given event map.\n *\n * @example\n * type MyEventMap = { greeting: TypedEvent, handshake: TypedEvent }\n * type EventTypes = EventMap.EventTypes\n * // \"greeting\" | \"handshake\"\n */\n export type EventTypes =\n Emitter.PublicEventTypes>\n\n /**\n * Returns a union of all public event type from the given event map.\n *\n * @example\n * type MyEventMap = { greeting: GreetingEvent, handshake: HandshakeEvent }\n * type Events = EventMap.Events\n * // GreetingEvent | HandshakeEvent\n */\n export type Events = Emitter.Events>\n\n /**\n * Returns an appropriate `Event` type for the given event type.\n *\n * @example\n * type MyEventMap = { greeting: TypedEvent }\n * type GreetingEvent = EventMap.Event\n * // TypedEvent\n */\n export type Event<\n Map extends DefaultEventMap,\n Type extends keyof WithReservedEvents & string,\n > = Emitter.Event, Type, WithReservedEvents>\n\n /**\n * Returns an appropriate event data type for the given event type.\n *\n * @example\n * type MyEventMap = { greeting: TypedEvent<'hello'> }\n * type GreetingData = EventMap.EventData\n * // \"hello\"\n */\n export type EventData<\n Map extends DefaultEventMap,\n Type extends keyof WithReservedEvents & string,\n > = Emitter.EventData, Type, WithReservedEvents>\n\n /**\n * Returns the listener type for the given event type.\n *\n * @example\n * type MyEventMap = { getTotalPrice: TypedEvent }>\n * type Listener = EventMap.Listener\n * // (event: TypedEvent) => number\n */\n export type Listener<\n Map extends DefaultEventMap,\n Type extends keyof WithReservedEvents & string,\n > = Emitter.Listener, Type, WithReservedEvents>\n\n /**\n * Returns the return type of the listener for the given event type.\n *\n * @example\n * type MyEventMap = { getTotalPrice: TypedEvent }\n * type ListenerReturnType = EventMap.ListenerReturnType\n * // number\n */\n export type ListenerReturnType<\n Map extends DefaultEventMap,\n Type extends keyof WithReservedEvents & string,\n > = Emitter.ListenerReturnType, Type, WithReservedEvents>\n}\n\nexport class Emitter {\n #listeners: LensList<\n Record<\n string,\n Emitter.Listener<\n typeof this,\n keyof WithReservedEvents & string,\n WithReservedEvents\n >\n >\n >\n\n #listenerOptions: WeakMap\n #listenerAbortCleanups: WeakMap void>\n #typelessListeners: WeakSet\n\n #hookListeners: LensList>\n #hookListenerOptions: WeakMap\n #hookListenerAbortCleanups: WeakMap void>\n\n public readonly hooks: {\n on>(\n type: HookType,\n callback: EmitterHookMap[HookType],\n options?: HookListenerOptions,\n ): void\n\n removeListener>(\n type: HookType,\n callback: EmitterHookMap[HookType],\n options?: HookListenerOptions,\n ): void\n }\n\n constructor() {\n this.#listeners = new LensList()\n this.#listenerOptions = new WeakMap()\n this.#listenerAbortCleanups = new WeakMap()\n this.#typelessListeners = new WeakSet()\n this.#hookListeners = new LensList()\n this.#hookListenerOptions = new WeakMap()\n this.#hookListenerAbortCleanups = new WeakMap()\n\n this.hooks = {\n on: (hook, callback, options) => {\n /**\n * @note An already-aborted signal would never fire its 'abort' event,\n * leaving the hook registered indefinitely. Skip registration entirely.\n */\n if (options?.signal?.aborted) {\n return\n }\n\n if (options?.once) {\n const original = callback as (...args: Array) => void\n const wrapper = ((...args: Array) => {\n this.#deleteHookListener(hook, wrapper)\n return original(...args)\n }) as typeof callback\n callback = wrapper\n }\n\n this.#hookListeners.append(hook, callback)\n\n if (options) {\n this.#hookListenerOptions.set(callback, options)\n }\n\n if (options?.signal) {\n const { signal } = options\n const onAbort = () => {\n this.#deleteHookListener(hook, callback)\n }\n signal.addEventListener('abort', onAbort, { once: true })\n this.#hookListenerAbortCleanups.set(callback, () => {\n signal.removeEventListener('abort', onAbort)\n })\n }\n },\n removeListener: (hook, callback) => {\n this.#deleteHookListener(hook, callback)\n },\n }\n }\n\n #deleteHookListener>(\n hook: HookType,\n callback: EmitterHookMap[HookType],\n ): void {\n this.#hookListeners.delete(hook, callback)\n const cleanup = this.#hookListenerAbortCleanups.get(callback)\n if (cleanup) {\n cleanup()\n this.#hookListenerAbortCleanups.delete(callback)\n }\n }\n\n #deleteListener<\n EventType extends keyof WithReservedEvents & string,\n >(\n type: EventType,\n listener: Emitter.Listener<\n typeof this,\n EventType,\n WithReservedEvents\n >,\n ): boolean {\n const removed = this.#listeners.delete(type, listener)\n const cleanup = this.#listenerAbortCleanups.get(listener)\n if (cleanup) {\n cleanup()\n this.#listenerAbortCleanups.delete(listener)\n }\n return removed\n }\n\n /**\n * Adds a listener for the given event type.\n */\n public on & string>(\n type: EventType,\n listener: Emitter.Listener<\n typeof this,\n EventType,\n WithReservedEvents\n >,\n options?: TypedListenerOptions,\n ): typeof this {\n this.#addListener(type, listener, options)\n return this\n }\n\n /**\n * Adds a one-time listener for the given event type.\n */\n public once & string>(\n type: EventType,\n listener: Emitter.Listener<\n typeof this,\n EventType,\n WithReservedEvents\n >,\n options?: Omit,\n ): typeof this {\n return this.on(type, listener, {\n ...(options || {}),\n once: true,\n })\n }\n\n /**\n * Prepends a listener for the given event type.\n */\n public earlyOn & string>(\n type: EventType,\n listener: Emitter.Listener<\n typeof this,\n EventType,\n WithReservedEvents\n >,\n options?: TypedListenerOptions,\n ): typeof this {\n this.#addListener(type, listener, options, 'prepend')\n return this\n }\n\n /**\n * Prepends a one-time listener for the given event type.\n */\n public earlyOnce<\n EventType extends keyof WithReservedEvents & string,\n >(\n type: EventType,\n listener: Emitter.Listener<\n typeof this,\n EventType,\n WithReservedEvents\n >,\n options?: Omit,\n ): typeof this {\n return this.earlyOn(type, listener, {\n ...(options || {}),\n once: true,\n })\n }\n\n /**\n * Emits the given typed event.\n *\n * @returns {boolean} Returns `true` if the event had any listeners, `false` otherwise.\n */\n public emit(\n event: Brand,\n ): boolean {\n if (this.#listeners.size === 0) {\n return false\n }\n\n /**\n * @note Calculate matching listeners before calling them\n * since one-time listeners will self-destruct.\n */\n const hasListeners = this.listenerCount(event.type) > 0\n\n const proxiedEvent = this.#proxyEvent(event)\n\n for (const listener of this.#matchListeners(event.type)) {\n if (\n proxiedEvent.event[kPropagationStopped] != null &&\n proxiedEvent.event[kPropagationStopped] !== this\n ) {\n proxiedEvent.revoke()\n return false\n }\n\n if (proxiedEvent.event[kImmediatePropagationStopped]) {\n break\n }\n\n this.#callListener(proxiedEvent.event, listener)\n }\n\n proxiedEvent.revoke()\n\n return hasListeners\n }\n\n /**\n * Emits the given typed event and returns a promise that resolves\n * when all the listeners for that event have settled.\n *\n * @returns {Promise>} A promise that resolves\n * with the return values of all listeners.\n */\n public async emitAsPromise(\n event: Brand,\n ): Promise<\n Array>\n > {\n if (this.#listeners.size === 0) {\n return []\n }\n\n const pendingListeners: Array<\n Promise>\n > = []\n\n const proxiedEvent = this.#proxyEvent(event)\n\n for (const listener of this.#matchListeners(event.type)) {\n if (\n proxiedEvent.event[kPropagationStopped] != null &&\n proxiedEvent.event[kPropagationStopped] !== this\n ) {\n proxiedEvent.revoke()\n return []\n }\n\n if (proxiedEvent.event[kImmediatePropagationStopped]) {\n break\n }\n\n const listenerPromise = Promise.resolve(\n this.#callListener(proxiedEvent.event, listener),\n )\n\n const returnValue = await listenerPromise\n\n if (!this.#isTypelessListener(listener)) {\n pendingListeners.push(returnValue)\n }\n }\n\n proxiedEvent.revoke()\n\n return Promise.allSettled(pendingListeners).then((results) => {\n return results.map((result) =>\n result.status === 'fulfilled' ? result.value : result.reason,\n )\n })\n }\n\n /**\n * Emits the given event and returns a generator that yields\n * the result of each listener in the order of their registration.\n * This way, you stop exhausting the listeners once you get the expected value.\n */\n public *emitAsGenerator(\n event: Brand,\n ): Generator> {\n if (this.#listeners.size === 0) {\n return\n }\n\n const proxiedEvent = this.#proxyEvent(event)\n\n for (const listener of this.#matchListeners(event.type)) {\n if (\n proxiedEvent.event[kPropagationStopped] != null &&\n proxiedEvent.event[kPropagationStopped] !== this\n ) {\n proxiedEvent.revoke()\n return\n }\n\n if (proxiedEvent.event[kImmediatePropagationStopped]) {\n break\n }\n\n const returnValue = this.#callListener(proxiedEvent.event, listener)\n\n if (!this.#isTypelessListener(listener)) {\n yield returnValue\n }\n }\n\n proxiedEvent.revoke()\n }\n\n /**\n * Removes a listener for the given event type.\n */\n public removeListener<\n EventType extends keyof WithReservedEvents & string,\n >(\n type: EventType,\n listener: Emitter.Listener<\n typeof this,\n EventType,\n WithReservedEvents\n >,\n ): void {\n const options = this.#listenerOptions.get(listener)\n\n if (!this.#deleteListener(type, listener)) {\n return\n }\n\n /**\n * @note Snapshot the hook list before iterating so a hook that removes\n * another `removeListener` hook can't shift the live array mid-iteration.\n */\n for (const hook of this.#hookListeners.get('removeListener').slice()) {\n hook(\n type,\n listener as Parameters['removeListener']>[1],\n options,\n )\n }\n }\n\n /**\n * Removes all listeners for the given event type.\n * If no event type is provided, removes all existing listeners.\n */\n public removeAllListeners<\n EventType extends keyof WithReservedEvents & string,\n >(type?: EventType): void {\n if (type == null) {\n for (const [listenerType, listeners] of this.#listeners.entries()) {\n while (listeners.length > 0) {\n this.removeListener(\n listenerType as keyof WithReservedEvents & string,\n listeners[0],\n )\n }\n }\n\n for (const [hookType, hookListener] of [...this.#hookListeners]) {\n if (!this.#hookListenerOptions.get(hookListener)?.persist) {\n this.#deleteHookListener(\n hookType as keyof EmitterHookMap,\n hookListener as EmitterHookMap[keyof EmitterHookMap],\n )\n }\n }\n\n return\n }\n\n const listeners = this.listeners(type)\n\n while (listeners.length > 0) {\n this.removeListener(type, listeners[0])\n }\n }\n\n /**\n * Returns the list of listeners for the given event type.\n * If no even type is provided, returns all listeners.\n */\n public listeners<\n EventType extends keyof WithReservedEvents & string,\n >(\n type?: EventType,\n ): Array<\n Emitter.Listener>\n > {\n if (type == null) {\n return this.#listeners.getAll()\n }\n\n return this.#listeners.get(type)\n }\n\n /**\n * Returns the number of listeners for the given event type.\n * If no even type is provided, returns the total number of listeners.\n */\n public listenerCount<\n EventType extends keyof WithReservedEvents & string,\n >(type?: EventType): number {\n if (type == null) {\n return this.#listeners.size\n }\n\n return this.listeners(type).length\n }\n\n #addListener & string>(\n type: EventType,\n listener: Emitter.Listener<\n typeof this,\n EventType,\n WithReservedEvents\n >,\n options: TypedListenerOptions | undefined,\n insertMode: 'append' | 'prepend' = 'append',\n ): void {\n /**\n * @note An already-aborted signal would never fire its 'abort' event,\n * leaving the listener registered indefinitely. Skip registration entirely.\n */\n if (options?.signal?.aborted) {\n return\n }\n\n for (const hook of this.#hookListeners.get('newListener').slice()) {\n hook(\n type,\n listener as Parameters['newListener']>[1],\n options,\n )\n }\n\n if (type === '*') {\n this.#typelessListeners.add(listener)\n }\n\n if (insertMode === 'prepend') {\n this.#listeners.prepend(type, listener)\n } else {\n this.#listeners.append(type, listener)\n }\n\n if (options) {\n this.#listenerOptions.set(listener, options)\n\n if (options.signal) {\n const { signal } = options\n const onAbort = () => {\n this.removeListener(type, listener)\n }\n signal.addEventListener('abort', onAbort, { once: true })\n this.#listenerAbortCleanups.set(listener, () => {\n signal.removeEventListener('abort', onAbort)\n })\n }\n }\n }\n\n #proxyEvent(\n event: Event,\n ): { event: Event; revoke: () => void } {\n const { stopPropagation } = event\n\n event.stopPropagation = () => {\n event[kPropagationStopped] = this\n stopPropagation.call(event)\n }\n\n return {\n event,\n revoke() {\n event.stopPropagation = stopPropagation\n },\n }\n }\n\n #callListener(event: Event, listener: (event: any) => any) {\n for (const hook of this.#hookListeners.get('beforeEmit').slice()) {\n if (hook(event as EventMap[keyof EventMap & string]) === false) {\n return\n }\n }\n\n const returnValue = listener.call(this, event)\n\n const options = this.#listenerOptions.get(listener)\n\n if (options?.once) {\n const type = this.#isTypelessListener(listener) ? '*' : event.type\n\n if (this.#deleteListener(type, listener)) {\n for (const hook of this.#hookListeners.get('removeListener').slice()) {\n hook(type, listener, options)\n }\n }\n }\n\n return returnValue\n }\n\n /**\n * Return a list of all event listeners relevant for the given event type.\n * This includes the explicit event listeners and also typeless event listeners.\n *\n * @note Snapshot the matching listeners before yielding. Listeners can add or\n * remove other listeners during emission (e.g. `earlyOn` unshifts `#list`),\n * which would otherwise shift the live iterator and re-yield prior entries.\n */\n *#matchListeners(type: EventType) {\n const snapshot: Array<\n Emitter.Listener<\n typeof this,\n keyof WithReservedEvents & string,\n WithReservedEvents\n >\n > = []\n for (const [key, listener] of this.#listeners) {\n if (key === '*' || key === type) {\n snapshot.push(listener)\n }\n }\n yield* snapshot\n }\n\n #isTypelessListener(listener: any): boolean {\n return this.#typelessListeners.has(listener)\n }\n}\n","import { invariant } from 'outvariant'\nimport { Emitter, TypedEvent } from 'rettime'\nimport { isObject } from '#core/utils/internal/isObject'\nimport type { StringifiedResponse } from '../glossary'\nimport { supportsServiceWorker } from '../utils/supports'\n\nexport type WorkerChannelEventMap = {\n REQUEST: WorkerEvent\n RESPONSE: WorkerEvent\n MOCKING_ENABLED: WorkerEvent<{\n client: {\n id: string\n frameType: string\n }\n }>\n INTEGRITY_CHECK_RESPONSE: WorkerEvent<{\n packageVersion: string\n checksum: string\n }>\n KEEPALIVE_RESPONSE: TypedEvent\n}\n\n/**\n * Request representation received from the worker message event.\n */\nexport interface IncomingWorkerRequest\n extends Omit<\n Request,\n | 'text'\n | 'body'\n | 'json'\n | 'blob'\n | 'arrayBuffer'\n | 'formData'\n | 'clone'\n | 'signal'\n | 'isHistoryNavigation'\n | 'isReloadNavigation'\n > {\n /**\n * Unique ID of the request generated once the request is\n * intercepted by the \"fetch\" event in the Service Worker.\n */\n id: string\n interceptedAt: number\n body?: ArrayBuffer | null\n}\n\ntype IncomingWorkerResponse = {\n isMockedResponse: boolean\n request: IncomingWorkerRequest\n response: Pick<\n Response,\n 'type' | 'ok' | 'status' | 'statusText' | 'body' | 'headers' | 'redirected'\n >\n}\n\nexport type WorkerEventResponse = {\n MOCK_RESPONSE: [\n data: StringifiedResponse,\n transfer?: [ReadableStream],\n ]\n PASSTHROUGH: []\n}\n\nconst SUPPORTS_SERVICE_WORKER = supportsServiceWorker()\n\nexport class WorkerEvent<\n DataType,\n ReturnType = any,\n EventType extends string = string,\n> extends TypedEvent {\n #workerEvent: MessageEvent\n\n constructor(workerEvent: MessageEvent) {\n const type = workerEvent.data.type as EventType\n const data = workerEvent.data.payload as DataType\n\n /**\n * @note This is the only place we're mapping { type, payload }\n * message structure of the worker. The client references the\n * payload via `event.data`.\n */\n super(\n // @ts-expect-error Troublesome `TypedEvent` extension.\n type,\n { data },\n )\n this.#workerEvent = workerEvent\n }\n\n get ports() {\n return this.#workerEvent.ports\n }\n\n /**\n * Reply directly to this event using its `MessagePort`.\n */\n public postMessage(\n type: Type,\n ...rest: WorkerEventResponse[Type]\n ): void {\n this.#workerEvent.ports[0].postMessage(\n { type, data: rest[0] },\n { transfer: rest[1] },\n )\n }\n}\n\n/**\n * Map of the events that can be sent to the Service Worker\n * from any execution context.\n */\ntype OutgoingWorkerEvents =\n | 'MOCK_ACTIVATE'\n | 'INTEGRITY_CHECK_REQUEST'\n | 'KEEPALIVE_REQUEST'\n | 'CLIENT_CLOSED'\n\nexport interface WorkerChannelOptions {\n getWorker: () => Promise\n}\n\nexport class WorkerChannel extends Emitter {\n #getWorker: WorkerChannelOptions['getWorker']\n #controller: AbortController\n\n constructor(options: WorkerChannelOptions) {\n super()\n\n invariant(\n SUPPORTS_SERVICE_WORKER,\n 'Failed to open a WorkerChannel: Service Worker is not supported in this environment.',\n )\n\n this.#getWorker = options.getWorker\n this.#controller = new AbortController()\n\n navigator.serviceWorker.addEventListener(\n 'message',\n async (event) => {\n const worker = await this.#getWorker()\n\n if (event.source != null && event.source !== worker) {\n return\n }\n\n if (event.data && isObject(event.data) && 'type' in event.data) {\n this.emit(new WorkerEvent(event))\n }\n },\n {\n signal: this.#controller.signal,\n },\n )\n }\n\n /**\n * Send data to the Service Worker controlling this client.\n * This triggers the `message` event listener on ServiceWorkerGlobalScope.\n */\n public postMessage(type: OutgoingWorkerEvents): void {\n invariant(\n SUPPORTS_SERVICE_WORKER,\n 'Failed to post message on a WorkerChannel: the Service Worker API is unavailable in this environment. This is likely an issue with MSW. Please report it on GitHub: https://github.com/mswjs/msw/issues',\n )\n\n this.#getWorker().then((worker) => {\n worker.postMessage(type)\n })\n }\n\n /**\n * Terminal teardown. Removes the `navigator.serviceWorker` message listener\n * and all emitter subscriptions. The channel is not usable afterwards.\n */\n public terminate(): void {\n this.#controller.abort()\n this.removeAllListeners()\n }\n}\n","import type { IncomingWorkerRequest } from './workerChannel'\n\ntype Input = Pick\n\n/**\n * Ensures that an empty GET request body is always represented as `undefined`.\n */\nexport function pruneGetRequestBody(\n request: Input,\n): IncomingWorkerRequest['body'] | undefined {\n // Force HEAD/GET request body to always be empty.\n // The worker reads any request's body as ArrayBuffer,\n // and you cannot re-construct a GET/HEAD Request\n // with an ArrayBuffer, even if empty. Also note that\n // \"request.body\" is always undefined in the worker.\n if (['HEAD', 'GET'].includes(request.method)) {\n return undefined\n }\n\n return request.body\n}\n","import { pruneGetRequestBody } from './pruneGetRequestBody'\nimport type { IncomingWorkerRequest } from './workerChannel'\n\n/**\n * Converts a given request received from the Service Worker\n * into a Fetch `Request` instance.\n */\nexport function deserializeRequest(\n serializedRequest: IncomingWorkerRequest,\n): Request {\n return new Request(serializedRequest.url, {\n ...serializedRequest,\n body: pruneGetRequestBody(serializedRequest),\n })\n}\n","import { devUtils } from '#core/utils/internal/devUtils'\n\n/**\n * Print a warning if the given Service Worker registration has a scope\n * outside of the current page's location. That is to help with debugging\n * issues caused by the incorrectly registered Service Worker.\n */\nexport function validateWorkerScope(\n registration: ServiceWorkerRegistration,\n): void {\n if (!location.href.startsWith(registration.scope)) {\n devUtils.warn(\n `Cannot intercept requests on this page because it's outside of the worker's scope (\"${registration.scope}\"). If you wish to mock API requests on this page, you must resolve this scope issue.\n\n- (Recommended) Register the worker at the root level (\"/\") of your application.\n- Set the \"Service-Worker-Allowed\" response header to allow out-of-scope workers.`,\n )\n }\n}\n","import { type ServiceWorkerSourceOptions } from '../sources/service-worker-source'\n\nexport function shouldInvalidateWorker(\n prevOptions: ServiceWorkerSourceOptions,\n nextOptions: ServiceWorkerSourceOptions,\n): boolean {\n return (\n prevOptions.findWorker !== nextOptions.findWorker ||\n prevOptions.serviceWorker.url !== nextOptions.serviceWorker.url ||\n JSON.stringify(prevOptions.serviceWorker.options) !==\n JSON.stringify(nextOptions.serviceWorker.options)\n )\n}\n","export type AsyncTuple<\n ErrorType extends any = Error,\n DataType extends any = unknown,\n> =\n | {\n error: ErrorType\n data: null\n }\n | { error: null; data: DataType }\n\n/**\n * Gracefully handles a given Promise factory.\n * @example\n * const { error, data } = await until(() => asyncAction())\n */\nexport const until = async <\n ErrorType extends any = Error,\n DataType extends any = unknown,\n>(\n promise: () => Promise,\n): Promise> => {\n try {\n const data = await promise().catch((error) => {\n throw error\n })\n return { error: null, data }\n } catch (error) {\n return { error, data: null }\n }\n}\n","/**\n * Determines if a given value is an instance of object.\n */\nexport function isObject(value: any, loose = false): value is T {\n return loose\n ? Object.prototype.toString.call(value).startsWith('[object ')\n : Object.prototype.toString.call(value) === '[object Object]'\n}\n","/**\n * A function that validates if property access is possible on an object\n * without throwing. It returns `true` if the property access is possible\n * and `false` otherwise.\n *\n * Environments like miniflare will throw on property access on certain objects\n * like Request and Response, for unimplemented properties.\n */\nexport function isPropertyAccessible>(\n obj: Obj,\n key: keyof Obj\n) {\n try {\n obj[key]\n return true\n } catch {\n return false\n }\n}\n","import { isObject } from './isObject'\nimport { isPropertyAccessible } from './isPropertyAccessible'\n\n/**\n * Creates a generic 500 Unhandled Exception response.\n */\nexport function createServerErrorResponse(body: unknown): Response {\n return new Response(\n JSON.stringify(\n body instanceof Error\n ? {\n name: body.name,\n message: body.message,\n stack: body.stack,\n }\n : body\n ),\n {\n status: 500,\n statusText: 'Unhandled Exception',\n headers: {\n 'Content-Type': 'application/json',\n },\n }\n )\n}\n\nexport type ResponseError = Response & { type: 'error' }\n\n/**\n * Check if the given response is a `Response.error()`.\n *\n * @note Some environments, like Miniflare (Cloudflare) do not\n * implement the \"Response.type\" property and throw on its access.\n * Safely check if we can access \"type\" on \"Response\" before continuing.\n * @see https://github.com/mswjs/msw/issues/1834\n */\nexport function isResponseError(response: unknown): response is ResponseError {\n return (\n response != null &&\n response instanceof Response &&\n isPropertyAccessible(response, 'type') &&\n response.type === 'error'\n )\n}\n\n/**\n * Check if the given value is a `Response` or a Response-like object.\n * This is different from `value instanceof Response` because it supports\n * custom `Response` constructors, like the one when using Undici directly.\n */\nexport function isResponseLike(value: unknown): value is Response {\n return (\n isObject>(value, true) &&\n isPropertyAccessible(value, 'status') &&\n isPropertyAccessible(value, 'statusText') &&\n isPropertyAccessible(value, 'bodyUsed')\n )\n}\n","export function isNodeLikeError(\n error: unknown\n): error is NodeJS.ErrnoException {\n if (error == null) {\n return false\n }\n\n if (!(error instanceof Error)) {\n return false\n }\n\n return 'code' in error && 'errno' in error\n}\n","import type { Emitter } from 'strict-event-emitter'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\nimport { until } from '@open-draft/until'\nimport type { HttpRequestEventMap } from '../glossary'\nimport { emitAsync } from './emitAsync'\nimport { RequestController } from '../RequestController'\nimport {\n createServerErrorResponse,\n isResponseError,\n isResponseLike,\n} from './responseUtils'\nimport { InterceptorError } from '../InterceptorError'\nimport { isNodeLikeError } from './isNodeLikeError'\nimport { isObject } from './isObject'\n\ninterface HandleRequestOptions {\n requestId: string\n request: Request\n emitter: Emitter\n controller: RequestController\n}\n\nexport async function handleRequest(\n options: HandleRequestOptions\n): Promise {\n const handleResponse = async (\n response: Response | Error | Record\n ) => {\n if (response instanceof Error) {\n await options.controller.errorWith(response)\n return true\n }\n\n // Handle \"Response.error()\" instances.\n if (isResponseError(response)) {\n await options.controller.respondWith(response)\n return true\n }\n\n /**\n * Handle normal responses or response-like objects.\n * @note This must come before the arbitrary object check\n * since Response instances are, in fact, objects.\n */\n if (isResponseLike(response)) {\n await options.controller.respondWith(response)\n return true\n }\n\n // Handle arbitrary objects provided to `.errorWith(reason)`.\n if (isObject(response)) {\n await options.controller.errorWith(response)\n return true\n }\n\n return false\n }\n\n const handleResponseError = async (error: unknown): Promise => {\n // Forward the special interceptor error instances\n // to the developer. These must not be handled in any way.\n if (error instanceof InterceptorError) {\n throw result.error\n }\n\n // Support mocking Node.js-like errors.\n if (isNodeLikeError(error)) {\n await options.controller.errorWith(error)\n return true\n }\n\n // Handle thrown responses.\n if (error instanceof Response) {\n return await handleResponse(error)\n }\n\n return false\n }\n\n // Add the last \"request\" listener to check if the request\n // has been handled in any way. If it hasn't, resolve the\n // response promise with undefined.\n // options.emitter.once('request', async ({ requestId: pendingRequestId }) => {\n // if (\n // pendingRequestId === options.requestId &&\n // options.controller.readyState === RequestController.PENDING\n // ) {\n // await options.controller.passthrough()\n // }\n // })\n\n const requestAbortPromise = new DeferredPromise()\n\n /**\n * @note `signal` is not always defined in React Native.\n */\n if (options.request.signal) {\n if (options.request.signal.aborted) {\n await options.controller.errorWith(options.request.signal.reason)\n return\n }\n\n options.request.signal.addEventListener(\n 'abort',\n () => {\n requestAbortPromise.reject(options.request.signal.reason)\n },\n { once: true }\n )\n }\n\n const result = await until(async () => {\n // Emit the \"request\" event and wait until all the listeners\n // for that event are finished (e.g. async listeners awaited).\n // By the end of this promise, the developer cannot affect the\n // request anymore.\n const requestListenersPromise = emitAsync(options.emitter, 'request', {\n requestId: options.requestId,\n request: options.request,\n controller: options.controller,\n })\n\n await Promise.race([\n // Short-circuit the request handling promise if the request gets aborted.\n requestAbortPromise,\n requestListenersPromise,\n options.controller.handled,\n ])\n })\n\n // Handle the request being aborted while waiting for the request listeners.\n if (requestAbortPromise.state === 'rejected') {\n await options.controller.errorWith(requestAbortPromise.rejectionReason)\n return\n }\n\n if (result.error) {\n // Handle the error during the request listener execution.\n // These can be thrown responses or request errors.\n if (await handleResponseError(result.error)) {\n return\n }\n\n // If the developer has added \"unhandledException\" listeners,\n // allow them to handle the error. They can translate it to a\n // mocked response, network error, or forward it as-is.\n if (options.emitter.listenerCount('unhandledException') > 0) {\n // Create a new request controller just for the unhandled exception case.\n // This is needed because the original controller might have been already\n // interacted with (e.g. \"respondWith\" or \"errorWith\" called on it).\n const unhandledExceptionController = new RequestController(\n options.request,\n {\n /**\n * @note Intentionally empty passthrough handle.\n * This controller is created within another controller and we only need\n * to know if `unhandledException` listeners handled the request.\n */\n passthrough() {},\n async respondWith(response) {\n await handleResponse(response)\n },\n async errorWith(reason) {\n /**\n * @note Handle the result of the unhandled controller\n * in the same way as the original request controller.\n * The exception here is that thrown errors within the\n * \"unhandledException\" event do NOT result in another\n * emit of the same event. They are forwarded as-is.\n */\n await options.controller.errorWith(reason)\n },\n }\n )\n\n await emitAsync(options.emitter, 'unhandledException', {\n error: result.error,\n request: options.request,\n requestId: options.requestId,\n controller: unhandledExceptionController,\n })\n\n // If all the \"unhandledException\" listeners have finished\n // but have not handled the request in any way, passthrough.\n if (\n unhandledExceptionController.readyState !== RequestController.PENDING\n ) {\n return\n }\n }\n\n // Otherwise, coerce unhandled exceptions to a 500 Internal Server Error response.\n await options.controller.respondWith(\n createServerErrorResponse(result.error)\n )\n return\n }\n\n // If the request hasn't been handled by this point, passthrough.\n if (options.controller.readyState === RequestController.PENDING) {\n return await options.controller.passthrough()\n }\n\n return options.controller.handled\n}\n","export function createNetworkError(cause?: unknown) {\n return Object.assign(new TypeError('Failed to fetch'), {\n cause,\n })\n}\n","import { createNetworkError } from './createNetworkError'\n\nconst REQUEST_BODY_HEADERS = [\n 'content-encoding',\n 'content-language',\n 'content-location',\n 'content-type',\n 'content-length',\n]\n\nconst kRedirectCount = Symbol('kRedirectCount')\n\n/**\n * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/index.js#L1210\n */\nexport async function followFetchRedirect(\n request: Request,\n response: Response\n): Promise {\n if (response.status !== 303 && request.body != null) {\n return Promise.reject(createNetworkError())\n }\n\n const requestUrl = new URL(request.url)\n\n let locationUrl: URL\n try {\n // If the location is a relative URL, use the request URL as the base URL.\n locationUrl = new URL(response.headers.get('location')!, request.url) \n } catch (error) {\n return Promise.reject(createNetworkError(error))\n }\n\n if (\n !(locationUrl.protocol === 'http:' || locationUrl.protocol === 'https:')\n ) {\n return Promise.reject(\n createNetworkError('URL scheme must be a HTTP(S) scheme')\n )\n }\n\n if (Reflect.get(request, kRedirectCount) > 20) {\n return Promise.reject(createNetworkError('redirect count exceeded'))\n }\n\n Object.defineProperty(request, kRedirectCount, {\n value: (Reflect.get(request, kRedirectCount) || 0) + 1,\n })\n\n if (\n request.mode === 'cors' &&\n (locationUrl.username || locationUrl.password) &&\n !sameOrigin(requestUrl, locationUrl)\n ) {\n return Promise.reject(\n createNetworkError('cross origin not allowed for request mode \"cors\"')\n )\n }\n\n const requestInit: RequestInit = {}\n\n if (\n ([301, 302].includes(response.status) && request.method === 'POST') ||\n (response.status === 303 && !['HEAD', 'GET'].includes(request.method))\n ) {\n requestInit.method = 'GET'\n requestInit.body = null\n\n REQUEST_BODY_HEADERS.forEach((headerName) => {\n request.headers.delete(headerName)\n })\n }\n\n if (!sameOrigin(requestUrl, locationUrl)) {\n request.headers.delete('authorization')\n request.headers.delete('proxy-authorization')\n request.headers.delete('cookie')\n request.headers.delete('host')\n }\n\n /**\n * @note Undici \"safely\" extracts the request body.\n * I suspect we cannot dispatch this request again\n * since its body has been read and the stream is locked.\n */\n\n requestInit.headers = request.headers\n const finalResponse = await fetch(new Request(locationUrl, requestInit))\n Object.defineProperty(finalResponse, 'redirected', {\n value: true,\n configurable: true,\n })\n\n return finalResponse\n}\n\n/**\n * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/util.js#L761\n */\nfunction sameOrigin(left: URL, right: URL): boolean {\n if (left.origin === right.origin && left.origin === 'null') {\n return true\n }\n\n if (\n left.protocol === right.protocol &&\n left.hostname === right.hostname &&\n left.port === right.port\n ) {\n return true\n }\n\n return false\n}\n","export class BrotliDecompressionStream extends TransformStream {\n constructor() {\n console.warn(\n '[Interceptors]: Brotli decompression of response streams is not supported in the browser'\n )\n\n super({\n transform(chunk, controller) {\n // Keep the stream as passthrough, it does nothing.\n controller.enqueue(chunk)\n },\n })\n }\n}\n","// Import from an internal alias that resolves to different modules\n// depending on the environment. This way, we can keep the fetch interceptor\n// intact while using different strategies for Brotli decompression.\nimport { BrotliDecompressionStream } from 'internal:brotli-decompress'\n\nclass PipelineStream extends TransformStream {\n constructor(\n transformStreams: Array,\n ...strategies: Array\n ) {\n super({}, ...strategies)\n\n const readable = [super.readable as any, ...transformStreams].reduce(\n (readable, transform) => readable.pipeThrough(transform)\n )\n\n Object.defineProperty(this, 'readable', {\n get() {\n return readable\n },\n })\n }\n}\n\nexport function parseContentEncoding(contentEncoding: string): Array {\n return contentEncoding\n .toLowerCase()\n .split(',')\n .map((coding) => coding.trim())\n}\n\nfunction createDecompressionStream(\n contentEncoding: string\n): TransformStream | null {\n if (contentEncoding === '') {\n return null\n }\n\n const codings = parseContentEncoding(contentEncoding)\n\n if (codings.length === 0) {\n return null\n }\n\n const transformers = codings.reduceRight>(\n (transformers, coding) => {\n if (coding === 'gzip' || coding === 'x-gzip') {\n return transformers.concat(new DecompressionStream('gzip'))\n } else if (coding === 'deflate') {\n return transformers.concat(new DecompressionStream('deflate'))\n } else if (coding === 'br') {\n return transformers.concat(new BrotliDecompressionStream())\n } else {\n transformers.length = 0\n }\n\n return transformers\n },\n []\n )\n\n return new PipelineStream(transformers)\n}\n\nexport function decompressResponse(\n response: Response\n): ReadableStream | null {\n if (response.body === null) {\n return null\n }\n\n const decompressionStream = createDecompressionStream(\n response.headers.get('content-encoding') || ''\n )\n\n if (!decompressionStream) {\n return null\n }\n\n // Use `pipeTo` and return the decompression stream's readable\n // instead of `pipeThrough` because that will lock the original\n // response stream, making it unusable as the input to Response.\n response.body.pipeTo(decompressionStream.writable)\n return decompressionStream.readable\n}\n","import { invariant } from 'outvariant'\nimport { until } from '@open-draft/until'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\nimport { HttpRequestEventMap, IS_PATCHED_MODULE } from '../../glossary'\nimport { Interceptor } from '../../Interceptor'\nimport { RequestController } from '../../RequestController'\nimport { emitAsync } from '../../utils/emitAsync'\nimport { handleRequest } from '../../utils/handleRequest'\nimport { canParseUrl } from '../../utils/canParseUrl'\nimport { createRequestId } from '../../createRequestId'\nimport { createNetworkError } from './utils/createNetworkError'\nimport { followFetchRedirect } from './utils/followRedirect'\nimport { decompressResponse } from './utils/decompression'\nimport { hasConfigurableGlobal } from '../../utils/hasConfigurableGlobal'\nimport { FetchResponse } from '../../utils/fetchUtils'\nimport { setRawRequest } from '../../getRawRequest'\nimport { isResponseError } from '../../utils/responseUtils'\n\nexport class FetchInterceptor extends Interceptor {\n static symbol = Symbol('fetch')\n\n constructor() {\n super(FetchInterceptor.symbol)\n }\n\n protected checkEnvironment() {\n return hasConfigurableGlobal('fetch')\n }\n\n protected async setup() {\n const pureFetch = globalThis.fetch\n\n invariant(\n !(pureFetch as any)[IS_PATCHED_MODULE],\n 'Failed to patch the \"fetch\" module: already patched.'\n )\n\n globalThis.fetch = async (input, init) => {\n const requestId = createRequestId()\n\n /**\n * @note Resolve potentially relative request URL\n * against the present `location`. This is mainly\n * for native `fetch` in JSDOM.\n * @see https://github.com/mswjs/msw/issues/1625\n */\n const resolvedInput =\n typeof input === 'string' &&\n typeof location !== 'undefined' &&\n !canParseUrl(input)\n ? new URL(input, location.href)\n : input\n\n const request = new Request(resolvedInput, init)\n\n /**\n * @note Set the raw request only if a Request instance was provided to fetch.\n */\n if (input instanceof Request) {\n setRawRequest(request, input)\n }\n\n const responsePromise = new DeferredPromise()\n\n const controller = new RequestController(request, {\n passthrough: async () => {\n this.logger.info('request has not been handled, passthrough...')\n\n /**\n * @note Clone the request instance right before performing it.\n * This preserves any modifications made to the intercepted request\n * in the \"request\" listener. This also allows the user to read the\n * request body in the \"response\" listener (otherwise \"unusable\").\n */\n const requestCloneForResponseEvent = request.clone()\n\n // Perform the intercepted request as-is.\n const { error: responseError, data: originalResponse } = await until(\n () => pureFetch(request)\n )\n\n if (responseError) {\n return responsePromise.reject(responseError)\n }\n\n this.logger.info('original fetch performed', originalResponse)\n\n if (this.emitter.listenerCount('response') > 0) {\n this.logger.info('emitting the \"response\" event...')\n\n const responseClone = originalResponse.clone()\n await emitAsync(this.emitter, 'response', {\n response: responseClone,\n isMockedResponse: false,\n request: requestCloneForResponseEvent,\n requestId,\n })\n }\n\n // Resolve the response promise with the original response\n // since the `fetch()` return this internal promise.\n responsePromise.resolve(originalResponse)\n },\n respondWith: async (rawResponse) => {\n // Handle mocked `Response.error()` (i.e. request errors).\n if (isResponseError(rawResponse)) {\n this.logger.info('request has errored!', { response: rawResponse })\n responsePromise.reject(createNetworkError(rawResponse))\n return\n }\n\n this.logger.info('received mocked response!', {\n rawResponse,\n })\n\n // Decompress the mocked response body, if applicable.\n const decompressedStream = decompressResponse(rawResponse)\n const response =\n decompressedStream === null\n ? rawResponse\n : new FetchResponse(decompressedStream, rawResponse)\n\n FetchResponse.setUrl(request.url, response)\n\n /**\n * Undici's handling of following redirect responses.\n * Treat the \"manual\" redirect mode as a regular mocked response.\n * This way, the client can manually follow the redirect it receives.\n * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/index.js#L1173\n */\n if (FetchResponse.isRedirectResponse(response.status)) {\n // Reject the request promise if its `redirect` is set to `error`\n // and it receives a mocked redirect response.\n if (request.redirect === 'error') {\n responsePromise.reject(createNetworkError('unexpected redirect'))\n return\n }\n\n if (request.redirect === 'follow') {\n followFetchRedirect(request, response).then(\n (response) => {\n responsePromise.resolve(response)\n },\n (reason) => {\n responsePromise.reject(reason)\n }\n )\n return\n }\n }\n\n if (this.emitter.listenerCount('response') > 0) {\n this.logger.info('emitting the \"response\" event...')\n\n // Await the response listeners to finish before resolving\n // the response promise. This ensures all your logic finishes\n // before the interceptor resolves the pending response.\n await emitAsync(this.emitter, 'response', {\n // Clone the mocked response for the \"response\" event listener.\n // This way, the listener can read the response and not lock its body\n // for the actual fetch consumer.\n response: response.clone(),\n isMockedResponse: true,\n request,\n requestId,\n })\n }\n\n responsePromise.resolve(response)\n },\n errorWith: (reason) => {\n this.logger.info('request has been aborted!', { reason })\n responsePromise.reject(reason)\n },\n })\n\n this.logger.info('[%s] %s', request.method, request.url)\n this.logger.info('awaiting for the mocked response...')\n\n this.logger.info(\n 'emitting the \"request\" event for %s listener(s)...',\n this.emitter.listenerCount('request')\n )\n\n await handleRequest({\n request,\n requestId,\n emitter: this.emitter,\n controller,\n })\n\n return responsePromise\n }\n\n Object.defineProperty(globalThis.fetch, IS_PATCHED_MODULE, {\n enumerable: true,\n configurable: true,\n value: true,\n })\n\n this.subscriptions.push(() => {\n Object.defineProperty(globalThis.fetch, IS_PATCHED_MODULE, {\n value: undefined,\n })\n\n globalThis.fetch = pureFetch\n\n this.logger.info(\n 'restored native \"globalThis.fetch\"!',\n globalThis.fetch.name\n )\n })\n }\n}\n","/**\n * Concatenate two `Uint8Array` buffers.\n */\nexport function concatArrayBuffer(\n left: Uint8Array,\n right: Uint8Array\n): Uint8Array {\n const result = new Uint8Array(left.byteLength + right.byteLength)\n result.set(left, 0)\n result.set(right, left.byteLength)\n return result\n}\n","export class EventPolyfill implements Event {\n readonly NONE = 0\n readonly CAPTURING_PHASE = 1\n readonly AT_TARGET = 2\n readonly BUBBLING_PHASE = 3\n\n public type: string = ''\n public srcElement: EventTarget | null = null\n public target: EventTarget | null\n public currentTarget: EventTarget | null = null\n public eventPhase: number = 0\n public timeStamp: number\n public isTrusted: boolean = true\n public composed: boolean = false\n public cancelable: boolean = true\n public defaultPrevented: boolean = false\n public bubbles: boolean = true\n public lengthComputable: boolean = true\n public loaded: number = 0\n public total: number = 0\n\n cancelBubble: boolean = false\n returnValue: boolean = true\n\n constructor(\n type: string,\n options?: { target: EventTarget; currentTarget: EventTarget }\n ) {\n this.type = type\n this.target = options?.target || null\n this.currentTarget = options?.currentTarget || null\n this.timeStamp = Date.now()\n }\n\n public composedPath(): EventTarget[] {\n return []\n }\n\n public initEvent(type: string, bubbles?: boolean, cancelable?: boolean) {\n this.type = type\n this.bubbles = !!bubbles\n this.cancelable = !!cancelable\n }\n\n public preventDefault() {\n this.defaultPrevented = true\n }\n\n public stopPropagation() {}\n public stopImmediatePropagation() {}\n}\n","import { EventPolyfill } from './EventPolyfill'\n\nexport class ProgressEventPolyfill extends EventPolyfill {\n readonly lengthComputable: boolean\n readonly composed: boolean\n readonly loaded: number\n readonly total: number\n\n constructor(type: string, init?: ProgressEventInit) {\n super(type)\n\n this.lengthComputable = init?.lengthComputable || false\n this.composed = init?.composed || false\n this.loaded = init?.loaded || 0\n this.total = init?.total || 0\n }\n}\n","import { EventPolyfill } from '../polyfills/EventPolyfill'\nimport { ProgressEventPolyfill } from '../polyfills/ProgressEventPolyfill'\n\nconst SUPPORTS_PROGRESS_EVENT = typeof ProgressEvent !== 'undefined'\n\nexport function createEvent(\n target: XMLHttpRequest | XMLHttpRequestUpload,\n type: string,\n init?: ProgressEventInit\n): EventPolyfill | ProgressEvent {\n const progressEvents = [\n 'error',\n 'progress',\n 'loadstart',\n 'loadend',\n 'load',\n 'timeout',\n 'abort',\n ]\n\n /**\n * `ProgressEvent` is not supported in React Native.\n * @see https://github.com/mswjs/interceptors/issues/40\n */\n const ProgressEventClass = SUPPORTS_PROGRESS_EVENT\n ? ProgressEvent\n : ProgressEventPolyfill\n\n const event = progressEvents.includes(type)\n ? new ProgressEventClass(type, {\n lengthComputable: true,\n loaded: init?.loaded || 0,\n total: init?.total || 0,\n })\n : new EventPolyfill(type, {\n target,\n currentTarget: target,\n })\n\n return event\n}\n","/**\n * Returns the source object of the given property on the target object\n * (the target itself, any parent in its prototype, or null).\n */\nexport function findPropertySource(\n target: object,\n propertyName: string | symbol\n): object | null {\n if (!(propertyName in target)) {\n return null\n }\n\n const hasProperty = Object.prototype.hasOwnProperty.call(target, propertyName)\n if (hasProperty) {\n return target\n }\n\n const prototype = Reflect.getPrototypeOf(target)\n return prototype ? findPropertySource(prototype, propertyName) : null\n}\n","import { findPropertySource } from './findPropertySource'\n\nexport interface ProxyOptions> {\n constructorCall?(args: Array, next: NextFunction): Target\n\n methodCall?(\n this: Target,\n data: [methodName: F, args: Array],\n next: NextFunction\n ): void\n\n setProperty?(\n data: [propertyName: string | symbol, nextValue: unknown],\n next: NextFunction\n ): boolean\n\n getProperty?(\n data: [propertyName: string | symbol, receiver: Target],\n next: NextFunction\n ): void\n}\n\nexport type NextFunction = () => ReturnType\n\nexport function createProxy(\n target: Target,\n options: ProxyOptions\n): Target {\n const proxy = new Proxy(target, optionsToProxyHandler(options))\n\n return proxy\n}\n\nfunction optionsToProxyHandler>(\n options: ProxyOptions\n): ProxyHandler {\n const { constructorCall, methodCall, getProperty, setProperty } = options\n const handler: ProxyHandler = {}\n\n if (typeof constructorCall !== 'undefined') {\n handler.construct = function (target, args, newTarget) {\n const next = Reflect.construct.bind(null, target as any, args, newTarget)\n return constructorCall.call(newTarget, args, next)\n }\n }\n\n handler.set = function (target, propertyName, nextValue) {\n const next = () => {\n const propertySource = findPropertySource(target, propertyName) || target\n const ownDescriptors = Reflect.getOwnPropertyDescriptor(\n propertySource,\n propertyName\n )\n\n // Respect any custom setters present for this property.\n if (typeof ownDescriptors?.set !== 'undefined') {\n ownDescriptors.set.apply(target, [nextValue])\n return true\n }\n\n // Otherwise, set the property on the source.\n return Reflect.defineProperty(propertySource, propertyName, {\n writable: true,\n enumerable: true,\n configurable: true,\n value: nextValue,\n })\n }\n\n if (typeof setProperty !== 'undefined') {\n return setProperty.call(target, [propertyName, nextValue], next)\n }\n\n return next()\n }\n\n handler.get = function (target, propertyName, receiver) {\n /**\n * @note Using `Reflect.get()` here causes \"TypeError: Illegal invocation\".\n */\n const next = () => target[propertyName as any]\n\n const value =\n typeof getProperty !== 'undefined'\n ? getProperty.call(target, [propertyName, receiver], next)\n : next()\n\n if (typeof value === 'function') {\n return (...args: Array) => {\n const next = value.bind(target, ...args)\n\n if (typeof methodCall !== 'undefined') {\n return methodCall.call(target, [propertyName as any, args], next)\n }\n\n return next()\n }\n }\n\n return value\n }\n\n return handler\n}\n","export function isDomParserSupportedType(\n type: string\n): type is DOMParserSupportedType {\n const supportedTypes: Array = [\n 'application/xhtml+xml',\n 'application/xml',\n 'image/svg+xml',\n 'text/html',\n 'text/xml',\n ]\n return supportedTypes.some((supportedType) => {\n return type.startsWith(supportedType)\n })\n}\n","/**\n * Parses a given string into JSON.\n * Gracefully handles invalid JSON by returning `null`.\n */\nexport function parseJson(data: string): Record | null {\n try {\n const json = JSON.parse(data)\n return json\n } catch (_) {\n return null\n }\n}\n","import { FetchResponse } from '../../../utils/fetchUtils'\n\n/**\n * Creates a Fetch API `Response` instance from the given\n * `XMLHttpRequest` instance and a response body.\n */\nexport function createResponse(\n request: XMLHttpRequest,\n body: BodyInit | null\n): Response {\n /**\n * Handle XMLHttpRequest responses that must have null as the\n * response body when represented using Fetch API Response.\n * XMLHttpRequest response will always have an empty string\n * as the \"request.response\" in those cases, resulting in an error\n * when constructing a Response instance.\n * @see https://github.com/mswjs/interceptors/issues/379\n */\n const responseBodyOrNull = FetchResponse.isResponseWithBody(request.status)\n ? body\n : null\n\n return new FetchResponse(responseBodyOrNull, {\n url: request.responseURL,\n status: request.status,\n statusText: request.statusText,\n headers: createHeadersFromXMLHttpRequestHeaders(\n request.getAllResponseHeaders()\n ),\n })\n}\n\nfunction createHeadersFromXMLHttpRequestHeaders(headersString: string): Headers {\n const headers = new Headers()\n\n const lines = headersString.split(/[\\r\\n]+/)\n for (const line of lines) {\n if (line.trim() === '') {\n continue\n }\n\n const [name, ...parts] = line.split(': ')\n const value = parts.join(': ')\n\n headers.append(name, value)\n }\n\n return headers\n}\n","/**\n * Return a total byte length of the given request/response body.\n * If the `Content-Length` header is present, it will be used as the byte length.\n */\nexport async function getBodyByteLength(\n input: Request | Response\n): Promise {\n const explicitContentLength = input.headers.get('content-length')\n\n if (explicitContentLength != null && explicitContentLength !== '') {\n return Number(explicitContentLength)\n }\n\n const buffer = await input.arrayBuffer()\n return buffer.byteLength\n}\n","import { invariant } from 'outvariant'\nimport { isNodeProcess } from 'is-node-process'\nimport type { Logger } from '@open-draft/logger'\nimport { concatArrayBuffer } from './utils/concatArrayBuffer'\nimport { createEvent } from './utils/createEvent'\nimport {\n decodeBuffer,\n encodeBuffer,\n toArrayBuffer,\n} from '../../utils/bufferUtils'\nimport { createProxy } from '../../utils/createProxy'\nimport { isDomParserSupportedType } from './utils/isDomParserSupportedType'\nimport { parseJson } from '../../utils/parseJson'\nimport { createResponse } from './utils/createResponse'\nimport { INTERNAL_REQUEST_ID_HEADER_NAME } from '../../Interceptor'\nimport { createRequestId } from '../../createRequestId'\nimport { getBodyByteLength } from './utils/getBodyByteLength'\nimport { setRawRequest } from '../../getRawRequest'\n\nconst kIsRequestHandled = Symbol('kIsRequestHandled')\nconst IS_NODE = isNodeProcess()\nconst kFetchRequest = Symbol('kFetchRequest')\n\n/**\n * An `XMLHttpRequest` instance controller that allows us\n * to handle any given request instance (e.g. responding to it).\n */\nexport class XMLHttpRequestController {\n public request: XMLHttpRequest\n public requestId: string\n public onRequest?: (\n this: XMLHttpRequestController,\n args: {\n request: Request\n requestId: string\n }\n ) => Promise\n public onResponse?: (\n this: XMLHttpRequestController,\n args: {\n response: Response\n isMockedResponse: boolean\n request: Request\n requestId: string\n }\n ) => void;\n\n [kIsRequestHandled]: boolean;\n [kFetchRequest]?: Request\n private method: string = 'GET'\n private url: URL = null as any\n private requestHeaders: Headers\n private responseBuffer: Uint8Array\n private events: Map>\n private uploadEvents: Map<\n keyof XMLHttpRequestEventTargetEventMap,\n Array\n >\n\n constructor(\n readonly initialRequest: XMLHttpRequest,\n public logger: Logger\n ) {\n this[kIsRequestHandled] = false\n\n this.events = new Map()\n this.uploadEvents = new Map()\n this.requestId = createRequestId()\n this.requestHeaders = new Headers()\n this.responseBuffer = new Uint8Array()\n\n this.request = createProxy(initialRequest, {\n setProperty: ([propertyName, nextValue], invoke) => {\n switch (propertyName) {\n case 'ontimeout': {\n const eventName = propertyName.slice(\n 2\n ) as keyof XMLHttpRequestEventTargetEventMap\n\n /**\n * @note Proxy callbacks to event listeners because JSDOM has trouble\n * translating these properties to callbacks. It seemed to be operating\n * on events exclusively.\n */\n this.request.addEventListener(eventName, nextValue as any)\n\n return invoke()\n }\n\n default: {\n return invoke()\n }\n }\n },\n methodCall: ([methodName, args], invoke) => {\n switch (methodName) {\n case 'open': {\n const [method, url] = args as [string, string | undefined]\n\n if (typeof url === 'undefined') {\n this.method = 'GET'\n this.url = toAbsoluteUrl(method)\n } else {\n this.method = method\n this.url = toAbsoluteUrl(url)\n }\n\n this.logger = this.logger.extend(`${this.method} ${this.url.href}`)\n this.logger.info('open', this.method, this.url.href)\n\n return invoke()\n }\n\n case 'addEventListener': {\n const [eventName, listener] = args as [\n keyof XMLHttpRequestEventTargetEventMap,\n Function,\n ]\n\n this.registerEvent(eventName, listener)\n this.logger.info('addEventListener', eventName, listener)\n\n return invoke()\n }\n\n case 'setRequestHeader': {\n const [name, value] = args as [string, string]\n this.requestHeaders.set(name, value)\n\n this.logger.info('setRequestHeader', name, value)\n\n return invoke()\n }\n\n case 'send': {\n const [body] = args as [\n body?: XMLHttpRequestBodyInit | Document | null,\n ]\n\n this.request.addEventListener('load', () => {\n if (typeof this.onResponse !== 'undefined') {\n // Create a Fetch API Response representation of whichever\n // response this XMLHttpRequest received. Note those may\n // be either a mocked and the original response.\n const fetchResponse = createResponse(\n this.request,\n /**\n * The `response` property is the right way to read\n * the ambiguous response body, as the request's \"responseType\" may differ.\n * @see https://xhr.spec.whatwg.org/#the-response-attribute\n */\n this.request.response\n )\n\n // Notify the consumer about the response.\n this.onResponse.call(this, {\n response: fetchResponse,\n isMockedResponse: this[kIsRequestHandled],\n request: fetchRequest,\n requestId: this.requestId!,\n })\n }\n })\n\n const requestBody =\n typeof body === 'string' ? encodeBuffer(body) : body\n\n // Delegate request handling to the consumer.\n const fetchRequest = this.toFetchApiRequest(requestBody)\n this[kFetchRequest] = fetchRequest.clone()\n\n /**\n * @note Start request handling on the next tick so that the user\n * could add event listeners for \"loadend\" before the interceptor fires it.\n */\n queueMicrotask(() => {\n const onceRequestSettled =\n this.onRequest?.call(this, {\n request: fetchRequest,\n requestId: this.requestId!,\n }) || Promise.resolve()\n\n onceRequestSettled.finally(() => {\n // If the consumer didn't handle the request (called `.respondWith()`) perform it as-is.\n if (!this[kIsRequestHandled]) {\n this.logger.info(\n 'request callback settled but request has not been handled (readystate %d), performing as-is...',\n this.request.readyState\n )\n\n /**\n * @note Set the intercepted request ID on the original request in Node.js\n * so that if it triggers any other interceptors, they don't attempt\n * to process it once again.\n *\n * For instance, XMLHttpRequest is often implemented via \"http.ClientRequest\"\n * and we don't want for both XHR and ClientRequest interceptors to\n * handle the same request at the same time (e.g. emit the \"response\" event twice).\n */\n if (IS_NODE) {\n this.request.setRequestHeader(\n INTERNAL_REQUEST_ID_HEADER_NAME,\n this.requestId!\n )\n }\n\n return invoke()\n }\n })\n })\n\n break\n }\n\n default: {\n return invoke()\n }\n }\n },\n })\n\n /**\n * Proxy the `.upload` property to gather the event listeners/callbacks.\n */\n define(\n this.request,\n 'upload',\n createProxy(this.request.upload, {\n setProperty: ([propertyName, nextValue], invoke) => {\n switch (propertyName) {\n case 'onloadstart':\n case 'onprogress':\n case 'onaboart':\n case 'onerror':\n case 'onload':\n case 'ontimeout':\n case 'onloadend': {\n const eventName = propertyName.slice(\n 2\n ) as keyof XMLHttpRequestEventTargetEventMap\n\n this.registerUploadEvent(eventName, nextValue as Function)\n }\n }\n\n return invoke()\n },\n methodCall: ([methodName, args], invoke) => {\n switch (methodName) {\n case 'addEventListener': {\n const [eventName, listener] = args as [\n keyof XMLHttpRequestEventTargetEventMap,\n Function,\n ]\n this.registerUploadEvent(eventName, listener)\n this.logger.info('upload.addEventListener', eventName, listener)\n\n return invoke()\n }\n }\n },\n })\n )\n }\n\n private registerEvent(\n eventName: keyof XMLHttpRequestEventTargetEventMap,\n listener: Function\n ): void {\n const prevEvents = this.events.get(eventName) || []\n const nextEvents = prevEvents.concat(listener)\n this.events.set(eventName, nextEvents)\n\n this.logger.info('registered event \"%s\"', eventName, listener)\n }\n\n private registerUploadEvent(\n eventName: keyof XMLHttpRequestEventTargetEventMap,\n listener: Function\n ): void {\n const prevEvents = this.uploadEvents.get(eventName) || []\n const nextEvents = prevEvents.concat(listener)\n this.uploadEvents.set(eventName, nextEvents)\n\n this.logger.info('registered upload event \"%s\"', eventName, listener)\n }\n\n /**\n * Responds to the current request with the given\n * Fetch API `Response` instance.\n */\n public async respondWith(response: Response): Promise {\n /**\n * @note Since `XMLHttpRequestController` delegates the handling of the responses\n * to the \"load\" event listener that doesn't distinguish between the mocked and original\n * responses, mark the request that had a mocked response with a corresponding symbol.\n *\n * Mark this request as having a mocked response immediately since\n * calculating request/response total body length is asynchronous.\n */\n this[kIsRequestHandled] = true\n\n /**\n * Dispatch request upload events for requests with a body.\n * @see https://github.com/mswjs/interceptors/issues/573\n */\n if (this[kFetchRequest]) {\n const totalRequestBodyLength = await getBodyByteLength(\n this[kFetchRequest]\n )\n\n this.trigger('loadstart', this.request.upload, {\n loaded: 0,\n total: totalRequestBodyLength,\n })\n this.trigger('progress', this.request.upload, {\n loaded: totalRequestBodyLength,\n total: totalRequestBodyLength,\n })\n this.trigger('load', this.request.upload, {\n loaded: totalRequestBodyLength,\n total: totalRequestBodyLength,\n })\n\n this.trigger('loadend', this.request.upload, {\n loaded: totalRequestBodyLength,\n total: totalRequestBodyLength,\n })\n }\n\n this.logger.info(\n 'responding with a mocked response: %d %s',\n response.status,\n response.statusText\n )\n\n define(this.request, 'status', response.status)\n define(this.request, 'statusText', response.statusText)\n define(this.request, 'responseURL', this.url.href)\n\n this.request.getResponseHeader = new Proxy(this.request.getResponseHeader, {\n apply: (_, __, args: [name: string]) => {\n this.logger.info('getResponseHeader', args[0])\n\n if (this.request.readyState < this.request.HEADERS_RECEIVED) {\n this.logger.info('headers not received yet, returning null')\n\n // Headers not received yet, nothing to return.\n return null\n }\n\n const headerValue = response.headers.get(args[0])\n this.logger.info(\n 'resolved response header \"%s\" to',\n args[0],\n headerValue\n )\n\n return headerValue\n },\n })\n\n this.request.getAllResponseHeaders = new Proxy(\n this.request.getAllResponseHeaders,\n {\n apply: () => {\n this.logger.info('getAllResponseHeaders')\n\n if (this.request.readyState < this.request.HEADERS_RECEIVED) {\n this.logger.info('headers not received yet, returning empty string')\n\n // Headers not received yet, nothing to return.\n return ''\n }\n\n const headersList = Array.from(response.headers.entries())\n const allHeaders = headersList\n .map(([headerName, headerValue]) => {\n return `${headerName}: ${headerValue}`\n })\n .join('\\r\\n')\n\n this.logger.info('resolved all response headers to', allHeaders)\n\n return allHeaders\n },\n }\n )\n\n // Update the response getters to resolve against the mocked response.\n Object.defineProperties(this.request, {\n response: {\n enumerable: true,\n configurable: false,\n get: () => this.response,\n },\n responseText: {\n enumerable: true,\n configurable: false,\n get: () => this.responseText,\n },\n responseXML: {\n enumerable: true,\n configurable: false,\n get: () => this.responseXML,\n },\n })\n\n const totalResponseBodyLength = await getBodyByteLength(response.clone())\n\n this.logger.info('calculated response body length', totalResponseBodyLength)\n\n this.trigger('loadstart', this.request, {\n loaded: 0,\n total: totalResponseBodyLength,\n })\n\n this.setReadyState(this.request.HEADERS_RECEIVED)\n this.setReadyState(this.request.LOADING)\n\n const finalizeResponse = () => {\n this.logger.info('finalizing the mocked response...')\n\n this.setReadyState(this.request.DONE)\n\n this.trigger('load', this.request, {\n loaded: this.responseBuffer.byteLength,\n total: totalResponseBodyLength,\n })\n\n this.trigger('loadend', this.request, {\n loaded: this.responseBuffer.byteLength,\n total: totalResponseBodyLength,\n })\n }\n\n if (response.body) {\n this.logger.info('mocked response has body, streaming...')\n\n const reader = response.body.getReader()\n\n const readNextResponseBodyChunk = async () => {\n const { value, done } = await reader.read()\n\n if (done) {\n this.logger.info('response body stream done!')\n finalizeResponse()\n return\n }\n\n if (value) {\n this.logger.info('read response body chunk:', value)\n this.responseBuffer = concatArrayBuffer(this.responseBuffer, value)\n\n this.trigger('progress', this.request, {\n loaded: this.responseBuffer.byteLength,\n total: totalResponseBodyLength,\n })\n }\n\n readNextResponseBodyChunk()\n }\n\n readNextResponseBodyChunk()\n } else {\n finalizeResponse()\n }\n }\n\n private responseBufferToText(): string {\n return decodeBuffer(this.responseBuffer)\n }\n\n get response(): unknown {\n this.logger.info(\n 'getResponse (responseType: %s)',\n this.request.responseType\n )\n\n if (this.request.readyState !== this.request.DONE) {\n return null\n }\n\n switch (this.request.responseType) {\n case 'json': {\n const responseJson = parseJson(this.responseBufferToText())\n this.logger.info('resolved response JSON', responseJson)\n\n return responseJson\n }\n\n case 'arraybuffer': {\n const arrayBuffer = toArrayBuffer(this.responseBuffer)\n this.logger.info('resolved response ArrayBuffer', arrayBuffer)\n\n return arrayBuffer\n }\n\n case 'blob': {\n const mimeType =\n this.request.getResponseHeader('Content-Type') || 'text/plain'\n const responseBlob = new Blob([this.responseBufferToText()], {\n type: mimeType,\n })\n\n this.logger.info(\n 'resolved response Blob (mime type: %s)',\n responseBlob,\n mimeType\n )\n\n return responseBlob\n }\n\n default: {\n const responseText = this.responseBufferToText()\n this.logger.info(\n 'resolving \"%s\" response type as text',\n this.request.responseType,\n responseText\n )\n\n return responseText\n }\n }\n }\n\n get responseText(): string {\n /**\n * Throw when trying to read the response body as text when the\n * \"responseType\" doesn't expect text. This just respects the spec better.\n * @see https://xhr.spec.whatwg.org/#the-responsetext-attribute\n */\n invariant(\n this.request.responseType === '' || this.request.responseType === 'text',\n 'InvalidStateError: The object is in invalid state.'\n )\n\n if (\n this.request.readyState !== this.request.LOADING &&\n this.request.readyState !== this.request.DONE\n ) {\n return ''\n }\n\n const responseText = this.responseBufferToText()\n this.logger.info('getResponseText: \"%s\"', responseText)\n\n return responseText\n }\n\n get responseXML(): Document | null {\n invariant(\n this.request.responseType === '' ||\n this.request.responseType === 'document',\n 'InvalidStateError: The object is in invalid state.'\n )\n\n if (this.request.readyState !== this.request.DONE) {\n return null\n }\n\n const contentType = this.request.getResponseHeader('Content-Type') || ''\n\n if (typeof DOMParser === 'undefined') {\n console.warn(\n 'Cannot retrieve XMLHttpRequest response body as XML: DOMParser is not defined. You are likely using an environment that is not browser or does not polyfill browser globals correctly.'\n )\n return null\n }\n\n if (isDomParserSupportedType(contentType)) {\n return new DOMParser().parseFromString(\n this.responseBufferToText(),\n contentType\n )\n }\n\n return null\n }\n\n public errorWith(error?: Error): void {\n /**\n * @note Mark this request as handled even if it received a mock error.\n * This prevents the controller from trying to perform this request as-is.\n */\n this[kIsRequestHandled] = true\n this.logger.info('responding with an error')\n\n this.setReadyState(this.request.DONE)\n this.trigger('error', this.request)\n this.trigger('loadend', this.request)\n }\n\n /**\n * Transitions this request's `readyState` to the given one.\n */\n private setReadyState(nextReadyState: number): void {\n this.logger.info(\n 'setReadyState: %d -> %d',\n this.request.readyState,\n nextReadyState\n )\n\n if (this.request.readyState === nextReadyState) {\n this.logger.info('ready state identical, skipping transition...')\n return\n }\n\n define(this.request, 'readyState', nextReadyState)\n\n this.logger.info('set readyState to: %d', nextReadyState)\n\n if (nextReadyState !== this.request.UNSENT) {\n this.logger.info('triggering \"readystatechange\" event...')\n\n this.trigger('readystatechange', this.request)\n }\n }\n\n /**\n * Triggers given event on the `XMLHttpRequest` instance.\n */\n private trigger<\n EventName extends keyof (XMLHttpRequestEventTargetEventMap & {\n readystatechange: ProgressEvent\n }),\n >(\n eventName: EventName,\n target: XMLHttpRequest | XMLHttpRequestUpload,\n options?: ProgressEventInit\n ): void {\n const callback = (target as XMLHttpRequest)[`on${eventName}`]\n const event = createEvent(target, eventName, options)\n\n this.logger.info('trigger \"%s\"', eventName, options || '')\n\n // Invoke direct callbacks.\n if (typeof callback === 'function') {\n this.logger.info('found a direct \"%s\" callback, calling...', eventName)\n callback.call(target as XMLHttpRequest, event)\n }\n\n // Invoke event listeners.\n const events =\n target instanceof XMLHttpRequestUpload ? this.uploadEvents : this.events\n\n for (const [registeredEventName, listeners] of events) {\n if (registeredEventName === eventName) {\n this.logger.info(\n 'found %d listener(s) for \"%s\" event, calling...',\n listeners.length,\n eventName\n )\n\n listeners.forEach((listener) => listener.call(target, event))\n }\n }\n }\n\n /**\n * Converts this `XMLHttpRequest` instance into a Fetch API `Request` instance.\n */\n private toFetchApiRequest(\n body: XMLHttpRequestBodyInit | Document | null | undefined\n ): Request {\n this.logger.info('converting request to a Fetch API Request...')\n\n // If the `Document` is used as the body of this XMLHttpRequest,\n // set its inner text as the Fetch API Request body.\n const resolvedBody =\n body instanceof Document ? body.documentElement.innerText : body\n\n const fetchRequest = new Request(this.url.href, {\n method: this.method,\n headers: this.requestHeaders,\n /**\n * @see https://xhr.spec.whatwg.org/#cross-origin-credentials\n */\n credentials: this.request.withCredentials ? 'include' : 'same-origin',\n body: ['GET', 'HEAD'].includes(this.method.toUpperCase())\n ? null\n : resolvedBody,\n })\n\n const proxyHeaders = createProxy(fetchRequest.headers, {\n methodCall: ([methodName, args], invoke) => {\n // Forward the latest state of the internal request headers\n // because the interceptor might have modified them\n // without responding to the request.\n switch (methodName) {\n case 'append':\n case 'set': {\n const [headerName, headerValue] = args as [string, string]\n this.request.setRequestHeader(headerName, headerValue)\n break\n }\n\n case 'delete': {\n const [headerName] = args as [string]\n console.warn(\n `XMLHttpRequest: Cannot remove a \"${headerName}\" header from the Fetch API representation of the \"${fetchRequest.method} ${fetchRequest.url}\" request. XMLHttpRequest headers cannot be removed.`\n )\n break\n }\n }\n\n return invoke()\n },\n })\n define(fetchRequest, 'headers', proxyHeaders)\n setRawRequest(fetchRequest, this.request)\n\n this.logger.info('converted request to a Fetch API Request!', fetchRequest)\n\n return fetchRequest\n }\n}\n\nfunction toAbsoluteUrl(url: string | URL): URL {\n /**\n * @note XMLHttpRequest interceptor may run in environments\n * that implement XMLHttpRequest but don't implement \"location\"\n * (for example, React Native). If that's the case, return the\n * input URL as-is (nothing to be relative to).\n * @see https://github.com/mswjs/msw/issues/1777\n */\n if (typeof location === 'undefined') {\n return new URL(url)\n }\n\n return new URL(url.toString(), location.href)\n}\n\nfunction define(\n target: object,\n property: string | symbol,\n value: unknown\n): void {\n Reflect.defineProperty(target, property, {\n // Ensure writable properties to allow redefining readonly properties.\n writable: true,\n enumerable: true,\n value,\n })\n}\n","import type { Logger } from '@open-draft/logger'\nimport { XMLHttpRequestEmitter } from '.'\nimport { RequestController } from '../../RequestController'\nimport { XMLHttpRequestController } from './XMLHttpRequestController'\nimport { handleRequest } from '../../utils/handleRequest'\nimport { isResponseError } from '../../utils/responseUtils'\n\nexport interface XMLHttpRequestProxyOptions {\n emitter: XMLHttpRequestEmitter\n logger: Logger\n}\n\n/**\n * Create a proxied `XMLHttpRequest` class.\n * The proxied class establishes spies on certain methods,\n * allowing us to intercept requests and respond to them.\n */\nexport function createXMLHttpRequestProxy({\n emitter,\n logger,\n}: XMLHttpRequestProxyOptions) {\n const XMLHttpRequestProxy = new Proxy(globalThis.XMLHttpRequest, {\n construct(target, args, newTarget) {\n logger.info('constructed new XMLHttpRequest')\n\n const originalRequest = Reflect.construct(\n target,\n args,\n newTarget\n ) as XMLHttpRequest\n\n /**\n * @note Forward prototype descriptors onto the proxied object.\n * XMLHttpRequest is implemented in JSDOM in a way that assigns\n * a bunch of descriptors, like \"set responseType()\" on the prototype.\n * With this propagation, we make sure that those descriptors trigger\n * when the user operates with the proxied request instance.\n */\n const prototypeDescriptors = Object.getOwnPropertyDescriptors(\n target.prototype\n )\n for (const propertyName in prototypeDescriptors) {\n Reflect.defineProperty(\n originalRequest,\n propertyName,\n prototypeDescriptors[propertyName]\n )\n }\n\n const xhrRequestController = new XMLHttpRequestController(\n originalRequest,\n logger\n )\n\n xhrRequestController.onRequest = async function ({ request, requestId }) {\n const controller = new RequestController(request, {\n passthrough: () => {\n this.logger.info(\n 'no mocked response received, performing request as-is...'\n )\n },\n respondWith: async (response) => {\n if (isResponseError(response)) {\n this.errorWith(new TypeError('Network error'))\n return\n }\n\n await this.respondWith(response)\n },\n errorWith: (reason) => {\n this.logger.info('request errored!', { error: reason })\n\n if (reason instanceof Error) {\n this.errorWith(reason)\n }\n },\n })\n\n this.logger.info('awaiting mocked response...')\n\n this.logger.info(\n 'emitting the \"request\" event for %s listener(s)...',\n emitter.listenerCount('request')\n )\n\n await handleRequest({\n request,\n requestId,\n controller,\n emitter,\n })\n }\n\n xhrRequestController.onResponse = async function ({\n response,\n isMockedResponse,\n request,\n requestId,\n }) {\n this.logger.info(\n 'emitting the \"response\" event for %s listener(s)...',\n emitter.listenerCount('response')\n )\n\n emitter.emit('response', {\n response,\n isMockedResponse,\n request,\n requestId,\n })\n }\n\n // Return the proxied request from the controller\n // so that the controller can react to the consumer's interactions\n // with this request (opening/sending/etc).\n return xhrRequestController.request\n },\n })\n\n return XMLHttpRequestProxy\n}\n","import { invariant } from 'outvariant'\nimport { Emitter } from 'strict-event-emitter'\nimport { HttpRequestEventMap, IS_PATCHED_MODULE } from '../../glossary'\nimport { Interceptor } from '../../Interceptor'\nimport { createXMLHttpRequestProxy } from './XMLHttpRequestProxy'\nimport { hasConfigurableGlobal } from '../../utils/hasConfigurableGlobal'\n\nexport type XMLHttpRequestEmitter = Emitter\n\nexport class XMLHttpRequestInterceptor extends Interceptor {\n static interceptorSymbol = Symbol('xhr')\n\n constructor() {\n super(XMLHttpRequestInterceptor.interceptorSymbol)\n }\n\n protected checkEnvironment() {\n return hasConfigurableGlobal('XMLHttpRequest')\n }\n\n protected setup() {\n const logger = this.logger.extend('setup')\n\n logger.info('patching \"XMLHttpRequest\" module...')\n\n const PureXMLHttpRequest = globalThis.XMLHttpRequest\n\n invariant(\n !(PureXMLHttpRequest as any)[IS_PATCHED_MODULE],\n 'Failed to patch the \"XMLHttpRequest\" module: already patched.'\n )\n\n globalThis.XMLHttpRequest = createXMLHttpRequestProxy({\n emitter: this.emitter,\n logger: this.logger,\n })\n\n logger.info(\n 'native \"XMLHttpRequest\" module patched!',\n globalThis.XMLHttpRequest.name\n )\n\n Object.defineProperty(globalThis.XMLHttpRequest, IS_PATCHED_MODULE, {\n enumerable: true,\n configurable: true,\n value: true,\n })\n\n this.subscriptions.push(() => {\n Object.defineProperty(globalThis.XMLHttpRequest, IS_PATCHED_MODULE, {\n value: undefined,\n })\n\n globalThis.XMLHttpRequest = PureXMLHttpRequest\n logger.info(\n 'native \"XMLHttpRequest\" module restored!',\n globalThis.XMLHttpRequest.name\n )\n })\n }\n}\n","import { FetchInterceptor } from '@mswjs/interceptors/fetch'\nimport { XMLHttpRequestInterceptor } from '@mswjs/interceptors/XMLHttpRequest'\nimport { InterceptorSource } from '#core/experimental/sources/interceptor-source'\nimport { devUtils } from '#core/utils/internal/devUtils'\n\ninterface FallbackHttpSourceOptions {\n quiet?: boolean\n}\n\nexport class FallbackHttpSource extends InterceptorSource {\n constructor(private readonly options: FallbackHttpSourceOptions) {\n super({\n interceptors: [new XMLHttpRequestInterceptor(), new FetchInterceptor()],\n })\n }\n\n public enable(): void {\n super.enable()\n\n if (!this.options.quiet) {\n this.#printStartMessage()\n }\n }\n\n public disable(): void {\n super.disable()\n\n if (!this.options.quiet) {\n this.#printStopMessage()\n }\n }\n\n #printStartMessage(): void {\n console.groupCollapsed(\n `%c${devUtils.formatMessage('Mocking enabled (fallback mode).')}`,\n 'color:orangered;font-weight:bold;',\n )\n // eslint-disable-next-line no-console\n console.log(\n '%cDocumentation: %chttps://mswjs.io/docs',\n 'font-weight:bold',\n 'font-weight:normal',\n )\n // eslint-disable-next-line no-console\n console.log('Found an issue? https://github.com/mswjs/msw/issues')\n console.groupEnd()\n }\n\n #printStopMessage(): void {\n // eslint-disable-next-line no-console\n console.log(\n `%c${devUtils.formatMessage('Mocking disabled.')}`,\n 'color:orangered;font-weight:bold;',\n )\n }\n}\n"],"mappings":";AAAA,IAAM,kBAAkB;AAExB,SAAS,oBAAoB,YAAiB,MAAmB;AAC/D,UAAQ,MAAM;IAEZ,KAAK;AACH,aAAO;IAGT,KAAK;IACL,KAAK;AAC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O,IAAI,KAAK,MAAM;AACjC,SAAK,gBAAgB,OAAO,cAAc,KAAK,MAAM;AACrD,SAAK,kBAAkB,OAAO,gBAAgB,KAAK,MAAM;AACzD,SAAK,eAAe,OAAO,aAAa,KAAK,MAAM;AACnD,SAAK,SAAS,OAAO;AAAA,EACvB;AACF;","names":["error","symbol: symbol","kEmitter","kBoundListener","socket: WebSocket","transport: WebSocketTransport","kEmitter","kBoundListener","client: WebSocketOverride","transport: WebSocketClassTransport","createConnection: () => WebSocket","socket: WebSocketOverride","WebSocketInterceptor","error","InterceptorSource","devUtils","createDeferredExecutor","DeferredPromise","IS_PATCHED_MODULE: unique symbol","InterceptorError","RequestController","request: Request","source: RequestControllerSource","symbol","FetchResponse","devUtils","error","error: any","worker","#list","kDefaultPrevented","Emitter","listeners","#hookListeners","Emitter","devUtils","DeferredPromise","devUtils","registration","error","until","error","isObject","error","until","locationUrl: URL","error","requestInit: RequestInit","readable","FetchInterceptor","until","response","handler: ProxyHandler","next","IS_NODE","initialRequest: XMLHttpRequest","logger: Logger","error","XMLHttpRequestInterceptor","devUtils","devUtils","InterceptorSource"]} \ No newline at end of file diff --git a/node_modules/msw/lib/core/HttpResponse-BFS34nkx.d.ts b/node_modules/msw/lib/core/HttpResponse-BFS34nkx.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6a6d0e026011402b15d56cd7058a409e6435b0b8 --- /dev/null +++ b/node_modules/msw/lib/core/HttpResponse-BFS34nkx.d.ts @@ -0,0 +1,371 @@ +import { FetchResponse } from '@mswjs/interceptors'; +import { Iterable, AsyncIterable } from './utils/internal/isIterable.js'; +import { MaybePromise, NoInfer } from './typeUtils.js'; +import { OperationTypeNode, DocumentNode, GraphQLError } from 'graphql'; +import { Match, Path } from './utils/matching/matchRequestUrl.js'; + +interface HandlersExecutionResult { + handler: RequestHandler; + parsedResult?: any; + response?: Response; +} +interface ResponseResolutionContext { + /** + * A base url to use when resolving relative urls. + * @note This is primarily used by the `@mswjs/http-middleware` + * to resolve relative urls in the context of the running server + */ + baseUrl?: string; + quiet?: boolean; +} +/** + * Executes the list of request handlers against the given request. + * Returns the execution result object containing any matching request + * handler and any mocked response it returned. + */ +declare const executeHandlers: >({ request, requestId, handlers, resolutionContext, }: { + request: Request; + requestId: string; + handlers: Handlers; + resolutionContext?: ResponseResolutionContext; +}) => Promise; + +interface ParsedGraphQLQuery { + operationType: OperationTypeNode; + operationName?: string; +} +type ParsedGraphQLRequest = (ParsedGraphQLQuery & { + query: string; + variables?: VariablesType; +}) | undefined; +declare function parseDocumentNode(node: DocumentNode): ParsedGraphQLQuery; +type GraphQLParsedOperationsMap = Record; +type GraphQLMultipartRequestBody = { + operations: string; + map?: string; +} & { + [fileName: string]: File; +}; +/** + * Determines if a given request can be considered a GraphQL request. + * Does not parse the query and does not guarantee its validity. + */ +declare function parseGraphQLRequest(request: Request): Promise; + +interface DocumentTypeDecoration { + __apiType?: (variables: Variables) => Result; + __resultType?: Result; + __variablesType?: Variables; +} +type GraphQLOperationType = OperationTypeNode | 'all'; +type GraphQLHandlerNameSelector = DocumentNode | RegExp | string; +type GraphQLQuery = Record | null; +type GraphQLVariables = Record; +interface GraphQLHandlerInfo extends RequestHandlerDefaultInfo { + operationType: GraphQLOperationType; + operationName: GraphQLHandlerNameSelector | GraphQLCustomPredicate; +} +type GraphQLRequestParsedResult = { + match: Match; + cookies: Record; +} & (ParsedGraphQLRequest +/** + * An empty version of the ParsedGraphQLRequest + * which simplifies the return type of the resolver + * when the request is to a non-matching endpoint + */ + | { + operationType?: undefined; + operationName?: undefined; + query?: undefined; + variables?: undefined; +}); +type GraphQLResolverExtras = { + query: string; + operationName: string; + variables: Variables; + cookies: Record; +}; +type GraphQLRequestBody = GraphQLJsonRequestBody | GraphQLMultipartRequestBody | Record | undefined; +interface GraphQLJsonRequestBody { + query: string; + variables?: Variables; +} +type GraphQLResponseBody = { + data?: BodyType | null; + errors?: readonly Partial[] | null; + extensions?: Record; +} | null | undefined; +type GraphQLCustomPredicate = (args: { + request: Request; + query: string; + operationType: GraphQLOperationType; + operationName: string; + variables: GraphQLVariables; + cookies: Record; +}) => GraphQLCustomPredicateResult | Promise; +type GraphQLCustomPredicateResult = boolean | { + matches: boolean; +}; +type GraphQLPredicate = GraphQLHandlerNameSelector | DocumentTypeDecoration | GraphQLCustomPredicate; +declare function isDocumentNode(value: DocumentNode | any): value is DocumentNode; +declare class GraphQLHandler extends RequestHandler> { + #private; + private endpoint; + static parsedRequestCache: WeakMap>; + constructor(operationType: GraphQLOperationType, predicate: GraphQLPredicate, endpoint: Path, resolver: ResponseResolver, any, any>, options?: RequestHandlerOptions); + /** + * Parses the request body, once per request, cached across all + * GraphQL handlers. This is done to avoid multiple parsing of the + * request body, which each requires a clone of the request. + */ + parseGraphQLRequestOrGetFromCache(request: Request): Promise>; + parse(args: { + request: Request; + }): Promise; + predicate(args: { + request: Request; + parsedResult: GraphQLRequestParsedResult; + }): Promise; + run(args: { + request: StrictRequest; + requestId: string; + resolutionContext?: ResponseResolutionContext; + }): Promise | null>; + private matchOperationName; + protected extendResolverArgs(args: { + request: Request; + parsedResult: GraphQLRequestParsedResult; + }): { + query: string; + operationType: OperationTypeNode; + operationName: string; + variables: GraphQLVariables; + cookies: Record; + }; + log(args: { + request: Request; + response: Response; + parsedResult: GraphQLRequestParsedResult; + }): Promise; +} + +type DefaultRequestMultipartBody = Record>; +type DefaultBodyType = Record | DefaultRequestMultipartBody | string | number | boolean | null | undefined; +type JsonBodyType = Record | string | number | boolean | null | undefined; +interface RequestHandlerDefaultInfo { + header: string; +} +interface RequestHandlerInternalInfo { + callFrame?: string; +} +type ResponseResolverReturnType = ([ResponseBodyType] extends [undefined] ? Response : ResponseBodyType extends GraphQLRequestBody ? HttpResponse | DefaultUnsafeFetchResponse : HttpResponse) | undefined | void; +type MaybeAsyncResponseResolverReturnType = MaybePromise>; +type AsyncResponseResolverReturnType = MaybePromise | Iterable, MaybeAsyncResponseResolverReturnType, MaybeAsyncResponseResolverReturnType> | AsyncIterable, MaybeAsyncResponseResolverReturnType, MaybeAsyncResponseResolverReturnType>>; +type ResponseResolverInfo, RequestBodyType extends DefaultBodyType = DefaultBodyType> = { + request: StrictRequest; + requestId: string; + /** + * Schedule a callback to run after this response resolver completes. + * Handy for cleaning up the side effects introduced in the resolver. + * @example + * sse('/', ({ client, finalize }) => { + * const interval = setInterval(() => client.send({ data: 'ping' })) + * finalize(() => clearInterval(interval)) + * }) + */ + finalize: ResponseResolverFinalizeFunction; +} & ResolverExtraInfo; +type ResponseResolverFinalizeFunction = (callback: () => MaybePromise) => void; +type ResponseResolver = Record, RequestBodyType extends DefaultBodyType = DefaultBodyType, ResponseBodyType extends DefaultBodyType = undefined> = (info: ResponseResolverInfo) => AsyncResponseResolverReturnType; +interface RequestHandlerArgs { + info: HandlerInfo; + resolver: ResponseResolver; + options?: HandlerOptions; +} +interface RequestHandlerOptions { + once?: boolean; +} +interface RequestHandlerExecutionResult { + handler: RequestHandler; + parsedResult?: ParsedResult; + request: Request; + requestId: string; + response?: Response; +} +declare abstract class RequestHandler | undefined = any, ResolverExtras extends Record = any, HandlerOptions extends RequestHandlerOptions = RequestHandlerOptions> { + static cache: WeakMap, StrictRequest>; + readonly kind: "request"; + protected resolver: ResponseResolver; + private resolverIterator?; + private resolverIteratorResult?; + private resolverIteratorCleanups?; + private options?; + private scheduledCleanups; + info: HandlerInfo & RequestHandlerInternalInfo; + /** + * Indicates whether this request handler has been used + * (its resolver has successfully executed). + */ + isUsed: boolean; + constructor(args: RequestHandlerArgs); + /** + * Reset the runtime state accumulated during response resolution, + * such as generator iterator progress. Called when this handler is + * removed from the active handlers list so re-adding it later starts + * from a clean state. + */ + protected reset(): void; + /** + * Restore this handler so it can match requests again after being + * exhausted (e.g. via `{ once: true }`). Also clears any accumulated + * resolution state. + */ + protected restore(): void; + /** + * Determine if the intercepted request should be mocked. + */ + abstract predicate(args: { + request: Request; + parsedResult: ParsedResult; + resolutionContext?: ResponseResolutionContext; + }): boolean | Promise; + /** + * Print out the successfully handled request. + */ + abstract log(args: { + request: Request; + response: Response; + parsedResult: ParsedResult; + }): void; + /** + * Parse the intercepted request to extract additional information from it. + * Parsed result is then exposed to other methods of this request handler. + */ + parse(_args: { + request: Request; + resolutionContext?: ResponseResolutionContext; + }): Promise; + /** + * Test if this handler matches the given request. + * + * This method is not used internally but is exposed + * as a convenience method for consumers writing custom + * handlers. + */ + test(args: { + request: Request; + resolutionContext?: ResponseResolutionContext; + }): Promise; + protected extendResolverArgs(_args: { + request: Request; + parsedResult: ParsedResult; + }): ResolverExtras; + private cloneRequestOrGetFromCache; + /** + * Execute this request handler and produce a mocked response + * using the given resolver function. + */ + run(args: { + request: StrictRequest; + requestId: string; + resolutionContext?: ResponseResolutionContext; + }): Promise | null>; + private wrapResolver; + private createExecutionResult; + private scheduleCleanup; + private exhaustCleanups; + private runScheduledCleanups; +} +/** + * Forwards the cookies from the given response to `document.cookie`. + */ +declare function forwardResponseCookies(response: Response): void; + +interface HttpResponseInit extends ResponseInit { + type?: ResponseType; +} +declare const bodyType: unique symbol; +type DefaultUnsafeFetchResponse = Response & { + [bodyType]?: never; +}; +interface StrictRequest extends Request { + json(): Promise; + clone(): StrictRequest; +} +/** + * Opaque `Response` type that supports strict body type. + * + * @deprecated Please use {@link HttpResponse} instead. + */ +type StrictResponse = HttpResponse; +declare const kDefaultContentType: unique symbol; +/** + * A drop-in replacement for the standard `Response` class + * to allow additional features, like mocking the response `Set-Cookie` header. + * + * @example + * new HttpResponse('Hello world', { status: 201 }) + * HttpResponse.json({ name: 'John' }) + * HttpResponse.formData(form) + * + * @see {@link https://mswjs.io/docs/api/http-response `HttpResponse` API reference} + */ +declare class HttpResponse extends FetchResponse { + readonly [bodyType]: BodyType; + constructor(body?: NoInfer | null, init?: HttpResponseInit); + static error(): HttpResponse; + /** + * Create a `Response` with a `Content-Type: "text/plain"` body. + * @example + * HttpResponse.text('hello world') + * HttpResponse.text('Error', { status: 500 }) + */ + static text(body?: NoInfer | null, init?: HttpResponseInit): HttpResponse; + /** + * Create a `Response` with a `Content-Type: "application/json"` body. + * @example + * HttpResponse.json({ firstName: 'John' }) + * HttpResponse.json({ error: 'Not Authorized' }, { status: 401 }) + */ + static json(body?: NoInfer | null | undefined, init?: HttpResponseInit): HttpResponse; + /** + * Create a `Response` with a `Content-Type: "application/xml"` body. + * @example + * HttpResponse.xml(``) + * HttpResponse.xml(`
    `, { status: 201 }) + */ + static xml(body?: BodyType | null, init?: HttpResponseInit): HttpResponse; + /** + * Create a `Response` with a `Content-Type: "text/html"` body. + * @example + * HttpResponse.html(`

    Jane Doe

    `) + * HttpResponse.html(`
    Main text
    `, { status: 201 }) + */ + static html(body?: BodyType | null, init?: HttpResponseInit): HttpResponse; + /** + * Create a `Response` with an `ArrayBuffer` body. + * @example + * const buffer = new ArrayBuffer(3) + * const view = new Uint8Array(buffer) + * view.set([1, 2, 3]) + * + * HttpResponse.arrayBuffer(buffer) + */ + static arrayBuffer(body?: BodyType, init?: HttpResponseInit): HttpResponse; + /** + * Create a `Response` with a `FormData` body. + * @example + * const data = new FormData() + * data.set('name', 'Alice') + * + * HttpResponse.formData(data) + */ + static formData(body?: FormData, init?: HttpResponseInit): HttpResponse; +} + +export { type AsyncResponseResolverReturnType as A, type GraphQLHandlerNameSelector as B, type GraphQLHandlerInfo as C, type DefaultBodyType as D, type GraphQLRequestParsedResult as E, type GraphQLCustomPredicateResult as F, GraphQLHandler as G, HttpResponse as H, isDocumentNode as I, type JsonBodyType as J, type RequestHandlerInternalInfo as K, type RequestHandlerArgs as L, type MaybeAsyncResponseResolverReturnType as M, type RequestHandlerExecutionResult as N, forwardResponseCookies as O, type ParsedGraphQLRequest as P, bodyType as Q, RequestHandler as R, type StrictRequest as S, type DefaultUnsafeFetchResponse as T, kDefaultContentType as U, type ResponseResolver as a, type ResponseResolverReturnType as b, type RequestHandlerOptions as c, type DefaultRequestMultipartBody as d, type ResponseResolverInfo as e, type GraphQLQuery as f, type GraphQLVariables as g, type GraphQLRequestBody as h, type GraphQLResponseBody as i, type GraphQLJsonRequestBody as j, type GraphQLOperationType as k, type GraphQLCustomPredicate as l, type ResponseResolutionContext as m, type HttpResponseInit as n, type StrictResponse as o, type GraphQLPredicate as p, type GraphQLResolverExtras as q, type RequestHandlerDefaultInfo as r, type HandlersExecutionResult as s, executeHandlers as t, type ParsedGraphQLQuery as u, parseDocumentNode as v, type GraphQLParsedOperationsMap as w, type GraphQLMultipartRequestBody as x, parseGraphQLRequest as y, type DocumentTypeDecoration as z }; diff --git a/node_modules/msw/lib/core/HttpResponse-CQwYpuKo.d.mts b/node_modules/msw/lib/core/HttpResponse-CQwYpuKo.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..6ca4878ed936f0614e3f255af834ef7cfc28a43c --- /dev/null +++ b/node_modules/msw/lib/core/HttpResponse-CQwYpuKo.d.mts @@ -0,0 +1,371 @@ +import { FetchResponse } from '@mswjs/interceptors'; +import { Iterable, AsyncIterable } from './utils/internal/isIterable.mjs'; +import { MaybePromise, NoInfer } from './typeUtils.mjs'; +import { OperationTypeNode, DocumentNode, GraphQLError } from 'graphql'; +import { Match, Path } from './utils/matching/matchRequestUrl.mjs'; + +interface HandlersExecutionResult { + handler: RequestHandler; + parsedResult?: any; + response?: Response; +} +interface ResponseResolutionContext { + /** + * A base url to use when resolving relative urls. + * @note This is primarily used by the `@mswjs/http-middleware` + * to resolve relative urls in the context of the running server + */ + baseUrl?: string; + quiet?: boolean; +} +/** + * Executes the list of request handlers against the given request. + * Returns the execution result object containing any matching request + * handler and any mocked response it returned. + */ +declare const executeHandlers: >({ request, requestId, handlers, resolutionContext, }: { + request: Request; + requestId: string; + handlers: Handlers; + resolutionContext?: ResponseResolutionContext; +}) => Promise; + +interface ParsedGraphQLQuery { + operationType: OperationTypeNode; + operationName?: string; +} +type ParsedGraphQLRequest = (ParsedGraphQLQuery & { + query: string; + variables?: VariablesType; +}) | undefined; +declare function parseDocumentNode(node: DocumentNode): ParsedGraphQLQuery; +type GraphQLParsedOperationsMap = Record; +type GraphQLMultipartRequestBody = { + operations: string; + map?: string; +} & { + [fileName: string]: File; +}; +/** + * Determines if a given request can be considered a GraphQL request. + * Does not parse the query and does not guarantee its validity. + */ +declare function parseGraphQLRequest(request: Request): Promise; + +interface DocumentTypeDecoration { + __apiType?: (variables: Variables) => Result; + __resultType?: Result; + __variablesType?: Variables; +} +type GraphQLOperationType = OperationTypeNode | 'all'; +type GraphQLHandlerNameSelector = DocumentNode | RegExp | string; +type GraphQLQuery = Record | null; +type GraphQLVariables = Record; +interface GraphQLHandlerInfo extends RequestHandlerDefaultInfo { + operationType: GraphQLOperationType; + operationName: GraphQLHandlerNameSelector | GraphQLCustomPredicate; +} +type GraphQLRequestParsedResult = { + match: Match; + cookies: Record; +} & (ParsedGraphQLRequest +/** + * An empty version of the ParsedGraphQLRequest + * which simplifies the return type of the resolver + * when the request is to a non-matching endpoint + */ + | { + operationType?: undefined; + operationName?: undefined; + query?: undefined; + variables?: undefined; +}); +type GraphQLResolverExtras = { + query: string; + operationName: string; + variables: Variables; + cookies: Record; +}; +type GraphQLRequestBody = GraphQLJsonRequestBody | GraphQLMultipartRequestBody | Record | undefined; +interface GraphQLJsonRequestBody { + query: string; + variables?: Variables; +} +type GraphQLResponseBody = { + data?: BodyType | null; + errors?: readonly Partial[] | null; + extensions?: Record; +} | null | undefined; +type GraphQLCustomPredicate = (args: { + request: Request; + query: string; + operationType: GraphQLOperationType; + operationName: string; + variables: GraphQLVariables; + cookies: Record; +}) => GraphQLCustomPredicateResult | Promise; +type GraphQLCustomPredicateResult = boolean | { + matches: boolean; +}; +type GraphQLPredicate = GraphQLHandlerNameSelector | DocumentTypeDecoration | GraphQLCustomPredicate; +declare function isDocumentNode(value: DocumentNode | any): value is DocumentNode; +declare class GraphQLHandler extends RequestHandler> { + #private; + private endpoint; + static parsedRequestCache: WeakMap>; + constructor(operationType: GraphQLOperationType, predicate: GraphQLPredicate, endpoint: Path, resolver: ResponseResolver, any, any>, options?: RequestHandlerOptions); + /** + * Parses the request body, once per request, cached across all + * GraphQL handlers. This is done to avoid multiple parsing of the + * request body, which each requires a clone of the request. + */ + parseGraphQLRequestOrGetFromCache(request: Request): Promise>; + parse(args: { + request: Request; + }): Promise; + predicate(args: { + request: Request; + parsedResult: GraphQLRequestParsedResult; + }): Promise; + run(args: { + request: StrictRequest; + requestId: string; + resolutionContext?: ResponseResolutionContext; + }): Promise | null>; + private matchOperationName; + protected extendResolverArgs(args: { + request: Request; + parsedResult: GraphQLRequestParsedResult; + }): { + query: string; + operationType: OperationTypeNode; + operationName: string; + variables: GraphQLVariables; + cookies: Record; + }; + log(args: { + request: Request; + response: Response; + parsedResult: GraphQLRequestParsedResult; + }): Promise; +} + +type DefaultRequestMultipartBody = Record>; +type DefaultBodyType = Record | DefaultRequestMultipartBody | string | number | boolean | null | undefined; +type JsonBodyType = Record | string | number | boolean | null | undefined; +interface RequestHandlerDefaultInfo { + header: string; +} +interface RequestHandlerInternalInfo { + callFrame?: string; +} +type ResponseResolverReturnType = ([ResponseBodyType] extends [undefined] ? Response : ResponseBodyType extends GraphQLRequestBody ? HttpResponse | DefaultUnsafeFetchResponse : HttpResponse) | undefined | void; +type MaybeAsyncResponseResolverReturnType = MaybePromise>; +type AsyncResponseResolverReturnType = MaybePromise | Iterable, MaybeAsyncResponseResolverReturnType, MaybeAsyncResponseResolverReturnType> | AsyncIterable, MaybeAsyncResponseResolverReturnType, MaybeAsyncResponseResolverReturnType>>; +type ResponseResolverInfo, RequestBodyType extends DefaultBodyType = DefaultBodyType> = { + request: StrictRequest; + requestId: string; + /** + * Schedule a callback to run after this response resolver completes. + * Handy for cleaning up the side effects introduced in the resolver. + * @example + * sse('/', ({ client, finalize }) => { + * const interval = setInterval(() => client.send({ data: 'ping' })) + * finalize(() => clearInterval(interval)) + * }) + */ + finalize: ResponseResolverFinalizeFunction; +} & ResolverExtraInfo; +type ResponseResolverFinalizeFunction = (callback: () => MaybePromise) => void; +type ResponseResolver = Record, RequestBodyType extends DefaultBodyType = DefaultBodyType, ResponseBodyType extends DefaultBodyType = undefined> = (info: ResponseResolverInfo) => AsyncResponseResolverReturnType; +interface RequestHandlerArgs { + info: HandlerInfo; + resolver: ResponseResolver; + options?: HandlerOptions; +} +interface RequestHandlerOptions { + once?: boolean; +} +interface RequestHandlerExecutionResult { + handler: RequestHandler; + parsedResult?: ParsedResult; + request: Request; + requestId: string; + response?: Response; +} +declare abstract class RequestHandler | undefined = any, ResolverExtras extends Record = any, HandlerOptions extends RequestHandlerOptions = RequestHandlerOptions> { + static cache: WeakMap, StrictRequest>; + readonly kind: "request"; + protected resolver: ResponseResolver; + private resolverIterator?; + private resolverIteratorResult?; + private resolverIteratorCleanups?; + private options?; + private scheduledCleanups; + info: HandlerInfo & RequestHandlerInternalInfo; + /** + * Indicates whether this request handler has been used + * (its resolver has successfully executed). + */ + isUsed: boolean; + constructor(args: RequestHandlerArgs); + /** + * Reset the runtime state accumulated during response resolution, + * such as generator iterator progress. Called when this handler is + * removed from the active handlers list so re-adding it later starts + * from a clean state. + */ + protected reset(): void; + /** + * Restore this handler so it can match requests again after being + * exhausted (e.g. via `{ once: true }`). Also clears any accumulated + * resolution state. + */ + protected restore(): void; + /** + * Determine if the intercepted request should be mocked. + */ + abstract predicate(args: { + request: Request; + parsedResult: ParsedResult; + resolutionContext?: ResponseResolutionContext; + }): boolean | Promise; + /** + * Print out the successfully handled request. + */ + abstract log(args: { + request: Request; + response: Response; + parsedResult: ParsedResult; + }): void; + /** + * Parse the intercepted request to extract additional information from it. + * Parsed result is then exposed to other methods of this request handler. + */ + parse(_args: { + request: Request; + resolutionContext?: ResponseResolutionContext; + }): Promise; + /** + * Test if this handler matches the given request. + * + * This method is not used internally but is exposed + * as a convenience method for consumers writing custom + * handlers. + */ + test(args: { + request: Request; + resolutionContext?: ResponseResolutionContext; + }): Promise; + protected extendResolverArgs(_args: { + request: Request; + parsedResult: ParsedResult; + }): ResolverExtras; + private cloneRequestOrGetFromCache; + /** + * Execute this request handler and produce a mocked response + * using the given resolver function. + */ + run(args: { + request: StrictRequest; + requestId: string; + resolutionContext?: ResponseResolutionContext; + }): Promise | null>; + private wrapResolver; + private createExecutionResult; + private scheduleCleanup; + private exhaustCleanups; + private runScheduledCleanups; +} +/** + * Forwards the cookies from the given response to `document.cookie`. + */ +declare function forwardResponseCookies(response: Response): void; + +interface HttpResponseInit extends ResponseInit { + type?: ResponseType; +} +declare const bodyType: unique symbol; +type DefaultUnsafeFetchResponse = Response & { + [bodyType]?: never; +}; +interface StrictRequest extends Request { + json(): Promise; + clone(): StrictRequest; +} +/** + * Opaque `Response` type that supports strict body type. + * + * @deprecated Please use {@link HttpResponse} instead. + */ +type StrictResponse = HttpResponse; +declare const kDefaultContentType: unique symbol; +/** + * A drop-in replacement for the standard `Response` class + * to allow additional features, like mocking the response `Set-Cookie` header. + * + * @example + * new HttpResponse('Hello world', { status: 201 }) + * HttpResponse.json({ name: 'John' }) + * HttpResponse.formData(form) + * + * @see {@link https://mswjs.io/docs/api/http-response `HttpResponse` API reference} + */ +declare class HttpResponse extends FetchResponse { + readonly [bodyType]: BodyType; + constructor(body?: NoInfer | null, init?: HttpResponseInit); + static error(): HttpResponse; + /** + * Create a `Response` with a `Content-Type: "text/plain"` body. + * @example + * HttpResponse.text('hello world') + * HttpResponse.text('Error', { status: 500 }) + */ + static text(body?: NoInfer | null, init?: HttpResponseInit): HttpResponse; + /** + * Create a `Response` with a `Content-Type: "application/json"` body. + * @example + * HttpResponse.json({ firstName: 'John' }) + * HttpResponse.json({ error: 'Not Authorized' }, { status: 401 }) + */ + static json(body?: NoInfer | null | undefined, init?: HttpResponseInit): HttpResponse; + /** + * Create a `Response` with a `Content-Type: "application/xml"` body. + * @example + * HttpResponse.xml(``) + * HttpResponse.xml(`
    `, { status: 201 }) + */ + static xml(body?: BodyType | null, init?: HttpResponseInit): HttpResponse; + /** + * Create a `Response` with a `Content-Type: "text/html"` body. + * @example + * HttpResponse.html(`

    Jane Doe

    `) + * HttpResponse.html(`
    Main text
    `, { status: 201 }) + */ + static html(body?: BodyType | null, init?: HttpResponseInit): HttpResponse; + /** + * Create a `Response` with an `ArrayBuffer` body. + * @example + * const buffer = new ArrayBuffer(3) + * const view = new Uint8Array(buffer) + * view.set([1, 2, 3]) + * + * HttpResponse.arrayBuffer(buffer) + */ + static arrayBuffer(body?: BodyType, init?: HttpResponseInit): HttpResponse; + /** + * Create a `Response` with a `FormData` body. + * @example + * const data = new FormData() + * data.set('name', 'Alice') + * + * HttpResponse.formData(data) + */ + static formData(body?: FormData, init?: HttpResponseInit): HttpResponse; +} + +export { type AsyncResponseResolverReturnType as A, type GraphQLHandlerNameSelector as B, type GraphQLHandlerInfo as C, type DefaultBodyType as D, type GraphQLRequestParsedResult as E, type GraphQLCustomPredicateResult as F, GraphQLHandler as G, HttpResponse as H, isDocumentNode as I, type JsonBodyType as J, type RequestHandlerInternalInfo as K, type RequestHandlerArgs as L, type MaybeAsyncResponseResolverReturnType as M, type RequestHandlerExecutionResult as N, forwardResponseCookies as O, type ParsedGraphQLRequest as P, bodyType as Q, RequestHandler as R, type StrictRequest as S, type DefaultUnsafeFetchResponse as T, kDefaultContentType as U, type ResponseResolver as a, type ResponseResolverReturnType as b, type RequestHandlerOptions as c, type DefaultRequestMultipartBody as d, type ResponseResolverInfo as e, type GraphQLQuery as f, type GraphQLVariables as g, type GraphQLRequestBody as h, type GraphQLResponseBody as i, type GraphQLJsonRequestBody as j, type GraphQLOperationType as k, type GraphQLCustomPredicate as l, type ResponseResolutionContext as m, type HttpResponseInit as n, type StrictResponse as o, type GraphQLPredicate as p, type GraphQLResolverExtras as q, type RequestHandlerDefaultInfo as r, type HandlersExecutionResult as s, executeHandlers as t, type ParsedGraphQLQuery as u, parseDocumentNode as v, type GraphQLParsedOperationsMap as w, type GraphQLMultipartRequestBody as x, parseGraphQLRequest as y, type DocumentTypeDecoration as z }; diff --git a/node_modules/msw/lib/core/HttpResponse.d.mts b/node_modules/msw/lib/core/HttpResponse.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..1fdd6437d3295f88394b46e78c534c36d9dcf732 --- /dev/null +++ b/node_modules/msw/lib/core/HttpResponse.d.mts @@ -0,0 +1,6 @@ +import '@mswjs/interceptors'; +export { T as DefaultUnsafeFetchResponse, H as HttpResponse, n as HttpResponseInit, S as StrictRequest, o as StrictResponse, Q as bodyType, U as kDefaultContentType } from './HttpResponse-CQwYpuKo.mjs'; +import './typeUtils.mjs'; +import './utils/internal/isIterable.mjs'; +import 'graphql'; +import './utils/matching/matchRequestUrl.mjs'; diff --git a/node_modules/msw/lib/core/HttpResponse.d.ts b/node_modules/msw/lib/core/HttpResponse.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f67906f21c61cef33ccdf710f710b29b9c2d0aea --- /dev/null +++ b/node_modules/msw/lib/core/HttpResponse.d.ts @@ -0,0 +1,6 @@ +import '@mswjs/interceptors'; +export { T as DefaultUnsafeFetchResponse, H as HttpResponse, n as HttpResponseInit, S as StrictRequest, o as StrictResponse, Q as bodyType, U as kDefaultContentType } from './HttpResponse-BFS34nkx.js'; +import './typeUtils.js'; +import './utils/internal/isIterable.js'; +import 'graphql'; +import './utils/matching/matchRequestUrl.js'; diff --git a/node_modules/msw/lib/core/HttpResponse.js b/node_modules/msw/lib/core/HttpResponse.js new file mode 100644 index 0000000000000000000000000000000000000000..345569dbdc0653d3e0dcd94b952be5651a7b5804 --- /dev/null +++ b/node_modules/msw/lib/core/HttpResponse.js @@ -0,0 +1,176 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var HttpResponse_exports = {}; +__export(HttpResponse_exports, { + HttpResponse: () => HttpResponse, + bodyType: () => bodyType, + kDefaultContentType: () => kDefaultContentType +}); +module.exports = __toCommonJS(HttpResponse_exports); +var import_interceptors = require("@mswjs/interceptors"); +var import_decorators = require("./utils/HttpResponse/decorators"); +const bodyType = Symbol("bodyType"); +const kDefaultContentType = Symbol.for("kDefaultContentType"); +class HttpResponse extends import_interceptors.FetchResponse { + [bodyType] = null; + constructor(body, init) { + const responseInit = (0, import_decorators.normalizeResponseInit)(init); + super(body, responseInit); + (0, import_decorators.decorateResponse)(this, responseInit); + } + static error() { + return super.error(); + } + /** + * Create a `Response` with a `Content-Type: "text/plain"` body. + * @example + * HttpResponse.text('hello world') + * HttpResponse.text('Error', { status: 500 }) + */ + static text(body, init) { + const responseInit = (0, import_decorators.normalizeResponseInit)(init); + const hasExplicitContentType = responseInit.headers.has("Content-Type"); + if (!hasExplicitContentType) { + responseInit.headers.set("Content-Type", "text/plain"); + } + if (!responseInit.headers.has("Content-Length")) { + responseInit.headers.set( + "Content-Length", + body ? new Blob([body]).size.toString() : "0" + ); + } + const response = new HttpResponse(body, responseInit); + if (!hasExplicitContentType) { + Object.defineProperty(response, kDefaultContentType, { + value: true, + enumerable: false + }); + } + return response; + } + /** + * Create a `Response` with a `Content-Type: "application/json"` body. + * @example + * HttpResponse.json({ firstName: 'John' }) + * HttpResponse.json({ error: 'Not Authorized' }, { status: 401 }) + */ + static json(body, init) { + const responseInit = (0, import_decorators.normalizeResponseInit)(init); + const hasExplicitContentType = responseInit.headers.has("Content-Type"); + if (!hasExplicitContentType) { + responseInit.headers.set("Content-Type", "application/json"); + } + const responseText = JSON.stringify(body); + if (!responseInit.headers.has("Content-Length")) { + responseInit.headers.set( + "Content-Length", + responseText ? new Blob([responseText]).size.toString() : "0" + ); + } + const response = new HttpResponse(responseText, responseInit); + if (!hasExplicitContentType) { + Object.defineProperty(response, kDefaultContentType, { + value: true, + enumerable: false + }); + } + return response; + } + /** + * Create a `Response` with a `Content-Type: "application/xml"` body. + * @example + * HttpResponse.xml(``) + * HttpResponse.xml(`
    `, { status: 201 }) + */ + static xml(body, init) { + const responseInit = (0, import_decorators.normalizeResponseInit)(init); + const hasExplicitContentType = responseInit.headers.has("Content-Type"); + if (!hasExplicitContentType) { + responseInit.headers.set("Content-Type", "text/xml"); + } + const response = new HttpResponse(body, responseInit); + if (!hasExplicitContentType) { + Object.defineProperty(response, kDefaultContentType, { + value: true, + enumerable: false + }); + } + return response; + } + /** + * Create a `Response` with a `Content-Type: "text/html"` body. + * @example + * HttpResponse.html(`

    Jane Doe

    `) + * HttpResponse.html(`
    Main text
    `, { status: 201 }) + */ + static html(body, init) { + const responseInit = (0, import_decorators.normalizeResponseInit)(init); + const hasExplicitContentType = responseInit.headers.has("Content-Type"); + if (!hasExplicitContentType) { + responseInit.headers.set("Content-Type", "text/html"); + } + const response = new HttpResponse(body, responseInit); + if (!hasExplicitContentType) { + Object.defineProperty(response, kDefaultContentType, { + value: true, + enumerable: false + }); + } + return response; + } + /** + * Create a `Response` with an `ArrayBuffer` body. + * @example + * const buffer = new ArrayBuffer(3) + * const view = new Uint8Array(buffer) + * view.set([1, 2, 3]) + * + * HttpResponse.arrayBuffer(buffer) + */ + static arrayBuffer(body, init) { + const responseInit = (0, import_decorators.normalizeResponseInit)(init); + const hasExplicitContentType = responseInit.headers.has("Content-Type"); + if (!hasExplicitContentType) { + responseInit.headers.set("Content-Type", "application/octet-stream"); + } + if (body && !responseInit.headers.has("Content-Length")) { + responseInit.headers.set("Content-Length", body.byteLength.toString()); + } + const response = new HttpResponse(body, responseInit); + if (!hasExplicitContentType) { + Object.defineProperty(response, kDefaultContentType, { + value: true, + enumerable: false + }); + } + return response; + } + /** + * Create a `Response` with a `FormData` body. + * @example + * const data = new FormData() + * data.set('name', 'Alice') + * + * HttpResponse.formData(data) + */ + static formData(body, init) { + return new HttpResponse(body, (0, import_decorators.normalizeResponseInit)(init)); + } +} +//# sourceMappingURL=HttpResponse.js.map \ No newline at end of file diff --git a/node_modules/msw/lib/core/HttpResponse.js.map b/node_modules/msw/lib/core/HttpResponse.js.map new file mode 100644 index 0000000000000000000000000000000000000000..31688925868635c7e5edfb178413ea0953199ff0 --- /dev/null +++ b/node_modules/msw/lib/core/HttpResponse.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/core/HttpResponse.ts"],"sourcesContent":["import { FetchResponse } from '@mswjs/interceptors'\nimport type { DefaultBodyType, JsonBodyType } from './handlers/RequestHandler'\nimport type { NoInfer } from './typeUtils'\nimport {\n decorateResponse,\n normalizeResponseInit,\n} from './utils/HttpResponse/decorators'\n\nexport interface HttpResponseInit extends ResponseInit {\n type?: ResponseType\n}\n\nexport const bodyType: unique symbol = Symbol('bodyType')\nexport type DefaultUnsafeFetchResponse = Response & {\n [bodyType]?: never\n}\n\nexport interface StrictRequest extends Request {\n json(): Promise\n clone(): StrictRequest\n}\n\n/**\n * Opaque `Response` type that supports strict body type.\n *\n * @deprecated Please use {@link HttpResponse} instead.\n */\nexport type StrictResponse =\n HttpResponse\n\nexport const kDefaultContentType = Symbol.for('kDefaultContentType')\n\n/**\n * A drop-in replacement for the standard `Response` class\n * to allow additional features, like mocking the response `Set-Cookie` header.\n *\n * @example\n * new HttpResponse('Hello world', { status: 201 })\n * HttpResponse.json({ name: 'John' })\n * HttpResponse.formData(form)\n *\n * @see {@link https://mswjs.io/docs/api/http-response `HttpResponse` API reference}\n */\nexport class HttpResponse<\n BodyType extends DefaultBodyType,\n> extends FetchResponse {\n readonly [bodyType]: BodyType = null as any\n\n constructor(body?: NoInfer | null, init?: HttpResponseInit) {\n const responseInit = normalizeResponseInit(init)\n super(body as BodyInit, responseInit)\n decorateResponse(this, responseInit)\n }\n\n static error(): HttpResponse {\n return super.error() as HttpResponse\n }\n\n /**\n * Create a `Response` with a `Content-Type: \"text/plain\"` body.\n * @example\n * HttpResponse.text('hello world')\n * HttpResponse.text('Error', { status: 500 })\n */\n static text(\n body?: NoInfer | null,\n init?: HttpResponseInit,\n ): HttpResponse {\n const responseInit = normalizeResponseInit(init)\n const hasExplicitContentType = responseInit.headers.has('Content-Type')\n\n if (!hasExplicitContentType) {\n responseInit.headers.set('Content-Type', 'text/plain')\n }\n\n // Automatically set the \"Content-Length\" response header\n // for non-empty text responses. This enforces consistency and\n // brings mocked responses closer to production.\n if (!responseInit.headers.has('Content-Length')) {\n responseInit.headers.set(\n 'Content-Length',\n body ? new Blob([body]).size.toString() : '0',\n )\n }\n\n const response = new HttpResponse(body, responseInit)\n\n if (!hasExplicitContentType) {\n Object.defineProperty(response, kDefaultContentType, {\n value: true,\n enumerable: false,\n })\n }\n\n return response\n }\n\n /**\n * Create a `Response` with a `Content-Type: \"application/json\"` body.\n * @example\n * HttpResponse.json({ firstName: 'John' })\n * HttpResponse.json({ error: 'Not Authorized' }, { status: 401 })\n */\n static json(\n body?: NoInfer | null | undefined,\n init?: HttpResponseInit,\n ): HttpResponse {\n const responseInit = normalizeResponseInit(init)\n const hasExplicitContentType = responseInit.headers.has('Content-Type')\n\n if (!hasExplicitContentType) {\n responseInit.headers.set('Content-Type', 'application/json')\n }\n\n /**\n * @note TypeScript is incorrect here.\n * Stringifying undefined will return undefined.\n */\n const responseText = JSON.stringify(body) as string | undefined\n\n if (!responseInit.headers.has('Content-Length')) {\n responseInit.headers.set(\n 'Content-Length',\n responseText ? new Blob([responseText]).size.toString() : '0',\n )\n }\n\n const response = new HttpResponse(responseText, responseInit)\n\n if (!hasExplicitContentType) {\n Object.defineProperty(response, kDefaultContentType, {\n value: true,\n enumerable: false,\n })\n }\n\n return response as HttpResponse\n }\n\n /**\n * Create a `Response` with a `Content-Type: \"application/xml\"` body.\n * @example\n * HttpResponse.xml(``)\n * HttpResponse.xml(`
    `, { status: 201 })\n */\n static xml(\n body?: BodyType | null,\n init?: HttpResponseInit,\n ): HttpResponse {\n const responseInit = normalizeResponseInit(init)\n const hasExplicitContentType = responseInit.headers.has('Content-Type')\n\n if (!hasExplicitContentType) {\n responseInit.headers.set('Content-Type', 'text/xml')\n }\n\n const response = new HttpResponse(body, responseInit)\n\n if (!hasExplicitContentType) {\n Object.defineProperty(response, kDefaultContentType, {\n value: true,\n enumerable: false,\n })\n }\n\n return response as HttpResponse\n }\n\n /**\n * Create a `Response` with a `Content-Type: \"text/html\"` body.\n * @example\n * HttpResponse.html(`

    Jane Doe

    `)\n * HttpResponse.html(`
    Main text
    `, { status: 201 })\n */\n static html(\n body?: BodyType | null,\n init?: HttpResponseInit,\n ): HttpResponse {\n const responseInit = normalizeResponseInit(init)\n const hasExplicitContentType = responseInit.headers.has('Content-Type')\n\n if (!hasExplicitContentType) {\n responseInit.headers.set('Content-Type', 'text/html')\n }\n\n const response = new HttpResponse(body, responseInit)\n\n if (!hasExplicitContentType) {\n Object.defineProperty(response, kDefaultContentType, {\n value: true,\n enumerable: false,\n })\n }\n\n return response as HttpResponse\n }\n\n /**\n * Create a `Response` with an `ArrayBuffer` body.\n * @example\n * const buffer = new ArrayBuffer(3)\n * const view = new Uint8Array(buffer)\n * view.set([1, 2, 3])\n *\n * HttpResponse.arrayBuffer(buffer)\n */\n static arrayBuffer(\n body?: BodyType,\n init?: HttpResponseInit,\n ): HttpResponse {\n const responseInit = normalizeResponseInit(init)\n const hasExplicitContentType = responseInit.headers.has('Content-Type')\n\n if (!hasExplicitContentType) {\n responseInit.headers.set('Content-Type', 'application/octet-stream')\n }\n\n if (body && !responseInit.headers.has('Content-Length')) {\n responseInit.headers.set('Content-Length', body.byteLength.toString())\n }\n\n const response = new HttpResponse(body, responseInit)\n\n if (!hasExplicitContentType) {\n Object.defineProperty(response, kDefaultContentType, {\n value: true,\n enumerable: false,\n })\n }\n\n return response as HttpResponse\n }\n\n /**\n * Create a `Response` with a `FormData` body.\n * @example\n * const data = new FormData()\n * data.set('name', 'Alice')\n *\n * HttpResponse.formData(data)\n */\n static formData(\n body?: FormData,\n init?: HttpResponseInit,\n ): HttpResponse {\n return new HttpResponse(body, normalizeResponseInit(init))\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,0BAA8B;AAG9B,wBAGO;AAMA,MAAM,WAA0B,OAAO,UAAU;AAkBjD,MAAM,sBAAsB,OAAO,IAAI,qBAAqB;AAa5D,MAAM,qBAEH,kCAAc;AAAA,EACtB,CAAU,QAAQ,IAAc;AAAA,EAEhC,YAAY,MAAiC,MAAyB;AACpE,UAAM,mBAAe,yCAAsB,IAAI;AAC/C,UAAM,MAAkB,YAAY;AACpC,4CAAiB,MAAM,YAAY;AAAA,EACrC;AAAA,EAEA,OAAO,QAA2B;AAChC,WAAO,MAAM,MAAM;AAAA,EACrB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,OAAO,KACL,MACA,MACwB;AACxB,UAAM,mBAAe,yCAAsB,IAAI;AAC/C,UAAM,yBAAyB,aAAa,QAAQ,IAAI,cAAc;AAEtE,QAAI,CAAC,wBAAwB;AAC3B,mBAAa,QAAQ,IAAI,gBAAgB,YAAY;AAAA,IACvD;AAKA,QAAI,CAAC,aAAa,QAAQ,IAAI,gBAAgB,GAAG;AAC/C,mBAAa,QAAQ;AAAA,QACnB;AAAA,QACA,OAAO,IAAI,KAAK,CAAC,IAAI,CAAC,EAAE,KAAK,SAAS,IAAI;AAAA,MAC5C;AAAA,IACF;AAEA,UAAM,WAAW,IAAI,aAAa,MAAM,YAAY;AAEpD,QAAI,CAAC,wBAAwB;AAC3B,aAAO,eAAe,UAAU,qBAAqB;AAAA,QACnD,OAAO;AAAA,QACP,YAAY;AAAA,MACd,CAAC;AAAA,IACH;AAEA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,OAAO,KACL,MACA,MACwB;AACxB,UAAM,mBAAe,yCAAsB,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,YAAY;AAEpD,QAAI,CAAC,wBAAwB;AAC3B,aAAO,eAAe,UAAU,qBAAqB;AAAA,QACnD,OAAO;AAAA,QACP,YAAY;AAAA,MACd,CAAC;AAAA,IACH;AAEA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWA,OAAO,YACL,MACA,MACwB;AACxB,UAAM,mBAAe,yCAAsB,IAAI;AAC/C,UAAM,yBAAyB,aAAa,QAAQ,IAAI,cAAc;AAEtE,QAAI,CAAC,wBAAwB;AAC3B,mBAAa,QAAQ,IAAI,gBAAgB,0BAA0B;AAAA,IACrE;AAEA,QAAI,QAAQ,CAAC,aAAa,QAAQ,IAAI,gBAAgB,GAAG;AACvD,mBAAa,QAAQ,IAAI,kBAAkB,KAAK,WAAW,SAAS,CAAC;AAAA,IACvE;AAEA,UAAM,WAAW,IAAI,aAAa,MAAM,YAAY;AAEpD,QAAI,CAAC,wBAAwB;AAC3B,aAAO,eAAe,UAAU,qBAAqB;AAAA,QACnD,OAAO;AAAA,QACP,YAAY;AAAA,MACd,CAAC;AAAA,IACH;AAEA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,OAAO,SACL,MACA,MACwB;AACxB,WAAO,IAAI,aAAa,UAAM,yCAAsB,IAAI,CAAC;AAAA,EAC3D;AACF;","names":[]} \ No newline at end of file diff --git a/node_modules/msw/lib/core/HttpResponse.mjs b/node_modules/msw/lib/core/HttpResponse.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ee0d866192e164423eab185145e52c131ad70340 --- /dev/null +++ b/node_modules/msw/lib/core/HttpResponse.mjs @@ -0,0 +1,159 @@ +import { FetchResponse } from "@mswjs/interceptors"; +import { + decorateResponse, + normalizeResponseInit +} from './utils/HttpResponse/decorators.mjs'; +const bodyType = Symbol("bodyType"); +const kDefaultContentType = Symbol.for("kDefaultContentType"); +class HttpResponse extends FetchResponse { + [bodyType] = null; + constructor(body, init) { + const responseInit = normalizeResponseInit(init); + super(body, responseInit); + decorateResponse(this, responseInit); + } + static error() { + return super.error(); + } + /** + * Create a `Response` with a `Content-Type: "text/plain"` body. + * @example + * HttpResponse.text('hello world') + * HttpResponse.text('Error', { status: 500 }) + */ + static text(body, init) { + const responseInit = normalizeResponseInit(init); + const hasExplicitContentType = responseInit.headers.has("Content-Type"); + if (!hasExplicitContentType) { + responseInit.headers.set("Content-Type", "text/plain"); + } + if (!responseInit.headers.has("Content-Length")) { + responseInit.headers.set( + "Content-Length", + body ? new Blob([body]).size.toString() : "0" + ); + } + const response = new HttpResponse(body, responseInit); + if (!hasExplicitContentType) { + Object.defineProperty(response, kDefaultContentType, { + value: true, + enumerable: false + }); + } + return response; + } + /** + * Create a `Response` with a `Content-Type: "application/json"` body. + * @example + * HttpResponse.json({ firstName: 'John' }) + * HttpResponse.json({ error: 'Not Authorized' }, { status: 401 }) + */ + static json(body, init) { + const responseInit = normalizeResponseInit(init); + const hasExplicitContentType = responseInit.headers.has("Content-Type"); + if (!hasExplicitContentType) { + responseInit.headers.set("Content-Type", "application/json"); + } + const responseText = JSON.stringify(body); + if (!responseInit.headers.has("Content-Length")) { + responseInit.headers.set( + "Content-Length", + responseText ? new Blob([responseText]).size.toString() : "0" + ); + } + const response = new HttpResponse(responseText, responseInit); + if (!hasExplicitContentType) { + Object.defineProperty(response, kDefaultContentType, { + value: true, + enumerable: false + }); + } + return response; + } + /** + * Create a `Response` with a `Content-Type: "application/xml"` body. + * @example + * HttpResponse.xml(``) + * HttpResponse.xml(`
    `, { status: 201 }) + */ + static xml(body, init) { + const responseInit = normalizeResponseInit(init); + const hasExplicitContentType = responseInit.headers.has("Content-Type"); + if (!hasExplicitContentType) { + responseInit.headers.set("Content-Type", "text/xml"); + } + const response = new HttpResponse(body, responseInit); + if (!hasExplicitContentType) { + Object.defineProperty(response, kDefaultContentType, { + value: true, + enumerable: false + }); + } + return response; + } + /** + * Create a `Response` with a `Content-Type: "text/html"` body. + * @example + * HttpResponse.html(`

    Jane Doe

    `) + * HttpResponse.html(`
    Main text
    `, { status: 201 }) + */ + static html(body, init) { + const responseInit = normalizeResponseInit(init); + const hasExplicitContentType = responseInit.headers.has("Content-Type"); + if (!hasExplicitContentType) { + responseInit.headers.set("Content-Type", "text/html"); + } + const response = new HttpResponse(body, responseInit); + if (!hasExplicitContentType) { + Object.defineProperty(response, kDefaultContentType, { + value: true, + enumerable: false + }); + } + return response; + } + /** + * Create a `Response` with an `ArrayBuffer` body. + * @example + * const buffer = new ArrayBuffer(3) + * const view = new Uint8Array(buffer) + * view.set([1, 2, 3]) + * + * HttpResponse.arrayBuffer(buffer) + */ + static arrayBuffer(body, init) { + const responseInit = normalizeResponseInit(init); + const hasExplicitContentType = responseInit.headers.has("Content-Type"); + if (!hasExplicitContentType) { + responseInit.headers.set("Content-Type", "application/octet-stream"); + } + if (body && !responseInit.headers.has("Content-Length")) { + responseInit.headers.set("Content-Length", body.byteLength.toString()); + } + const response = new HttpResponse(body, responseInit); + if (!hasExplicitContentType) { + Object.defineProperty(response, kDefaultContentType, { + value: true, + enumerable: false + }); + } + return response; + } + /** + * Create a `Response` with a `FormData` body. + * @example + * const data = new FormData() + * data.set('name', 'Alice') + * + * HttpResponse.formData(data) + */ + static formData(body, init) { + return new HttpResponse(body, normalizeResponseInit(init)); + } +} +export { + HttpResponse, + bodyType, + kDefaultContentType +}; +//# sourceMappingURL=HttpResponse.mjs.map \ No newline at end of file diff --git a/node_modules/msw/lib/core/HttpResponse.mjs.map b/node_modules/msw/lib/core/HttpResponse.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..e16ed445576255eeb0f51bed170f3319a21a2006 --- /dev/null +++ b/node_modules/msw/lib/core/HttpResponse.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/core/HttpResponse.ts"],"sourcesContent":["import { FetchResponse } from '@mswjs/interceptors'\nimport type { DefaultBodyType, JsonBodyType } from './handlers/RequestHandler'\nimport type { NoInfer } from './typeUtils'\nimport {\n decorateResponse,\n normalizeResponseInit,\n} from './utils/HttpResponse/decorators'\n\nexport interface HttpResponseInit extends ResponseInit {\n type?: ResponseType\n}\n\nexport const bodyType: unique symbol = Symbol('bodyType')\nexport type DefaultUnsafeFetchResponse = Response & {\n [bodyType]?: never\n}\n\nexport interface StrictRequest extends Request {\n json(): Promise\n clone(): StrictRequest\n}\n\n/**\n * Opaque `Response` type that supports strict body type.\n *\n * @deprecated Please use {@link HttpResponse} instead.\n */\nexport type StrictResponse =\n HttpResponse\n\nexport const kDefaultContentType = Symbol.for('kDefaultContentType')\n\n/**\n * A drop-in replacement for the standard `Response` class\n * to allow additional features, like mocking the response `Set-Cookie` header.\n *\n * @example\n * new HttpResponse('Hello world', { status: 201 })\n * HttpResponse.json({ name: 'John' })\n * HttpResponse.formData(form)\n *\n * @see {@link https://mswjs.io/docs/api/http-response `HttpResponse` API reference}\n */\nexport class HttpResponse<\n BodyType extends DefaultBodyType,\n> extends FetchResponse {\n readonly [bodyType]: BodyType = null as any\n\n constructor(body?: NoInfer | null, init?: HttpResponseInit) {\n const responseInit = normalizeResponseInit(init)\n super(body as BodyInit, responseInit)\n decorateResponse(this, responseInit)\n }\n\n static error(): HttpResponse {\n return super.error() as HttpResponse\n }\n\n /**\n * Create a `Response` with a `Content-Type: \"text/plain\"` body.\n * @example\n * HttpResponse.text('hello world')\n * HttpResponse.text('Error', { status: 500 })\n */\n static text(\n body?: NoInfer | null,\n init?: HttpResponseInit,\n ): HttpResponse {\n const responseInit = normalizeResponseInit(init)\n const hasExplicitContentType = responseInit.headers.has('Content-Type')\n\n if (!hasExplicitContentType) {\n responseInit.headers.set('Content-Type', 'text/plain')\n }\n\n // Automatically set the \"Content-Length\" response header\n // for non-empty text responses. This enforces consistency and\n // brings mocked responses closer to production.\n if (!responseInit.headers.has('Content-Length')) {\n responseInit.headers.set(\n 'Content-Length',\n body ? new Blob([body]).size.toString() : '0',\n )\n }\n\n const response = new HttpResponse(body, responseInit)\n\n if (!hasExplicitContentType) {\n Object.defineProperty(response, kDefaultContentType, {\n value: true,\n enumerable: false,\n })\n }\n\n return response\n }\n\n /**\n * Create a `Response` with a `Content-Type: \"application/json\"` body.\n * @example\n * HttpResponse.json({ firstName: 'John' })\n * HttpResponse.json({ error: 'Not Authorized' }, { status: 401 })\n */\n static json(\n body?: NoInfer | null | undefined,\n init?: HttpResponseInit,\n ): HttpResponse {\n const responseInit = normalizeResponseInit(init)\n const hasExplicitContentType = responseInit.headers.has('Content-Type')\n\n if (!hasExplicitContentType) {\n responseInit.headers.set('Content-Type', 'application/json')\n }\n\n /**\n * @note TypeScript is incorrect here.\n * Stringifying undefined will return undefined.\n */\n const responseText = JSON.stringify(body) as string | undefined\n\n if (!responseInit.headers.has('Content-Length')) {\n responseInit.headers.set(\n 'Content-Length',\n responseText ? new Blob([responseText]).size.toString() : '0',\n )\n }\n\n const response = new HttpResponse(responseText, responseInit)\n\n if (!hasExplicitContentType) {\n Object.defineProperty(response, kDefaultContentType, {\n value: true,\n enumerable: false,\n })\n }\n\n return response as HttpResponse\n }\n\n /**\n * Create a `Response` with a `Content-Type: \"application/xml\"` body.\n * @example\n * HttpResponse.xml(``)\n * HttpResponse.xml(`
    `, { status: 201 })\n */\n static xml(\n body?: BodyType | null,\n init?: HttpResponseInit,\n ): HttpResponse {\n const responseInit = normalizeResponseInit(init)\n const hasExplicitContentType = responseInit.headers.has('Content-Type')\n\n if (!hasExplicitContentType) {\n responseInit.headers.set('Content-Type', 'text/xml')\n }\n\n const response = new HttpResponse(body, responseInit)\n\n if (!hasExplicitContentType) {\n Object.defineProperty(response, kDefaultContentType, {\n value: true,\n enumerable: false,\n })\n }\n\n return response as HttpResponse\n }\n\n /**\n * Create a `Response` with a `Content-Type: \"text/html\"` body.\n * @example\n * HttpResponse.html(`

    Jane Doe

    `)\n * HttpResponse.html(`
    Main text
    `, { status: 201 })\n */\n static html(\n body?: BodyType | null,\n init?: HttpResponseInit,\n ): HttpResponse {\n const responseInit = normalizeResponseInit(init)\n const hasExplicitContentType = responseInit.headers.has('Content-Type')\n\n if (!hasExplicitContentType) {\n responseInit.headers.set('Content-Type', 'text/html')\n }\n\n const response = new HttpResponse(body, responseInit)\n\n if (!hasExplicitContentType) {\n Object.defineProperty(response, kDefaultContentType, {\n value: true,\n enumerable: false,\n })\n }\n\n return response as HttpResponse\n }\n\n /**\n * Create a `Response` with an `ArrayBuffer` body.\n * @example\n * const buffer = new ArrayBuffer(3)\n * const view = new Uint8Array(buffer)\n * view.set([1, 2, 3])\n *\n * HttpResponse.arrayBuffer(buffer)\n */\n static arrayBuffer(\n body?: BodyType,\n init?: HttpResponseInit,\n ): HttpResponse {\n const responseInit = normalizeResponseInit(init)\n const hasExplicitContentType = responseInit.headers.has('Content-Type')\n\n if (!hasExplicitContentType) {\n responseInit.headers.set('Content-Type', 'application/octet-stream')\n }\n\n if (body && !responseInit.headers.has('Content-Length')) {\n responseInit.headers.set('Content-Length', body.byteLength.toString())\n }\n\n const response = new HttpResponse(body, responseInit)\n\n if (!hasExplicitContentType) {\n Object.defineProperty(response, kDefaultContentType, {\n value: true,\n enumerable: false,\n })\n }\n\n return response as HttpResponse\n }\n\n /**\n * Create a `Response` with a `FormData` body.\n * @example\n * const data = new FormData()\n * data.set('name', 'Alice')\n *\n * HttpResponse.formData(data)\n */\n static formData(\n body?: FormData,\n init?: HttpResponseInit,\n ): HttpResponse {\n return new HttpResponse(body, normalizeResponseInit(init))\n }\n}\n"],"mappings":"AAAA,SAAS,qBAAqB;AAG9B;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAMA,MAAM,WAA0B,OAAO,UAAU;AAkBjD,MAAM,sBAAsB,OAAO,IAAI,qBAAqB;AAa5D,MAAM,qBAEH,cAAc;AAAA,EACtB,CAAU,QAAQ,IAAc;AAAA,EAEhC,YAAY,MAAiC,MAAyB;AACpE,UAAM,eAAe,sBAAsB,IAAI;AAC/C,UAAM,MAAkB,YAAY;AACpC,qBAAiB,MA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gB,GAAG;AACvD,mBAAa,QAAQ,IAAI,kBAAkB,KAAK,WAAW,SAAS,CAAC;AAAA,IACvE;AAEA,UAAM,WAAW,IAAI,aAAa,MAAM,YAAY;AAEpD,QAAI,CAAC,wBAAwB;AAC3B,aAAO,eAAe,UAAU,qBAAqB;AAAA,QACnD,OAAO;AAAA,QACP,YAAY;AAAA,MACd,CAAC;AAAA,IACH;AAEA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,OAAO,SACL,MACA,MACwB;AACxB,WAAO,IAAI,aAAa,MAAM,sBAAsB,IAAI,CAAC;AAAA,EAC3D;AACF;","names":[]} \ No newline at end of file diff --git a/node_modules/msw/lib/core/bypass.d.mts b/node_modules/msw/lib/core/bypass.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..0481787acd77be5a3f688b063291699a6c8f2c95 --- /dev/null +++ b/node_modules/msw/lib/core/bypass.d.mts @@ -0,0 +1,16 @@ +type BypassRequestInput = string | URL | Request; +/** + * Creates a `Request` instance that will always be ignored by MSW. + * + * @example + * import { bypass } from 'msw' + * + * fetch(bypass('/resource')) + * fetch(bypass(new URL('/resource', 'https://example.com))) + * fetch(bypass(new Request('https://example.com/resource'))) + * + * @see {@link https://mswjs.io/docs/api/bypass `bypass()` API reference} + */ +declare function bypass(input: BypassRequestInput, init?: RequestInit): Request; + +export { type BypassRequestInput, bypass }; diff --git a/node_modules/msw/lib/core/bypass.d.ts b/node_modules/msw/lib/core/bypass.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0481787acd77be5a3f688b063291699a6c8f2c95 --- /dev/null +++ b/node_modules/msw/lib/core/bypass.d.ts @@ -0,0 +1,16 @@ +type BypassRequestInput = string | URL | Request; +/** + * Creates a `Request` instance that will always be ignored by MSW. + * + * @example + * import { bypass } from 'msw' + * + * fetch(bypass('/resource')) + * fetch(bypass(new URL('/resource', 'https://example.com))) + * fetch(bypass(new Request('https://example.com/resource'))) + * + * @see {@link https://mswjs.io/docs/api/bypass `bypass()` API reference} + */ +declare function bypass(input: BypassRequestInput, init?: RequestInit): Request; + +export { type BypassRequestInput, bypass }; diff --git a/node_modules/msw/lib/core/bypass.js b/node_modules/msw/lib/core/bypass.js new file mode 100644 index 0000000000000000000000000000000000000000..42c8f9630af6586784ad54bd5f27161f7e07612a --- /dev/null +++ b/node_modules/msw/lib/core/bypass.js @@ -0,0 +1,42 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var bypass_exports = {}; +__export(bypass_exports, { + bypass: () => bypass +}); +module.exports = __toCommonJS(bypass_exports); +var import_outvariant = require("outvariant"); +function bypass(input, init) { + const request = new Request( + // If given a Request instance, clone it not to exhaust + // the original request's body. + input instanceof Request ? input.clone() : input, + init + ); + (0, import_outvariant.invariant)( + !request.bodyUsed, + 'Failed to create a bypassed request to "%s %s": given request instance already has its body read. Make sure to clone the intercepted request if you wish to read its body before bypassing it.', + request.method, + request.url + ); + const requestClone = request.clone(); + requestClone.headers.append("accept", "msw/passthrough"); + return requestClone; +} +//# sourceMappingURL=bypass.js.map \ No newline at end of file diff --git a/node_modules/msw/lib/core/bypass.js.map b/node_modules/msw/lib/core/bypass.js.map new file mode 100644 index 0000000000000000000000000000000000000000..3559bb55d093acbc97e59e3c9769036ca55a2cf6 --- /dev/null +++ b/node_modules/msw/lib/core/bypass.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/core/bypass.ts"],"sourcesContent":["import { invariant } from 'outvariant'\n\nexport type BypassRequestInput = string | URL | Request\n\n/**\n * Creates a `Request` instance that will always be ignored by MSW.\n *\n * @example\n * import { bypass } from 'msw'\n *\n * fetch(bypass('/resource'))\n * fetch(bypass(new URL('/resource', 'https://example.com)))\n * fetch(bypass(new Request('https://example.com/resource')))\n *\n * @see {@link https://mswjs.io/docs/api/bypass `bypass()` API reference}\n */\nexport function bypass(input: BypassRequestInput, init?: RequestInit): Request {\n // Always create a new Request instance.\n // This way, the \"init\" modifications will propagate\n // to the bypass request instance automatically.\n const request = new Request(\n // If given a Request instance, clone it not to exhaust\n // the original request's body.\n input instanceof Request ? input.clone() : input,\n init,\n )\n\n invariant(\n !request.bodyUsed,\n 'Failed to create a bypassed request to \"%s %s\": given request instance already has its body read. Make sure to clone the intercepted request if you wish to read its body before bypassing it.',\n request.method,\n request.url,\n )\n\n const requestClone = request.clone()\n\n /**\n * Send the internal request header that would instruct MSW\n * to perform this request as-is, ignoring any matching handlers.\n * @note Use the `accept` header to support scenarios when the\n * request cannot have headers (e.g. `sendBeacon` requests).\n */\n requestClone.headers.append('accept', 'msw/passthrough')\n\n return requestClone\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,wBAA0B;AAgBnB,SAAS,OAAO,OAA2B,MAA6B;AAI7E,QAAM,UAAU,IAAI;AAAA;AAAA;AAAA,IAGlB,iBAAiB,UAAU,MAAM,MAAM,IAAI;AAAA,IAC3C;AAAA,EACF;AAEA;AAAA,IACE,CAAC,QAAQ;AAAA,IACT;AAAA,IACA,QAAQ;AAAA,IACR,QAAQ;AAAA,EACV;AAEA,QAAM,eAAe,QAAQ,MAAM;AAQnC,eAAa,QAAQ,OAAO,UAAU,iBAAiB;AAEvD,SAAO;AACT;","names":[]} \ No newline at end of file diff --git a/node_modules/msw/lib/core/bypass.mjs b/node_modules/msw/lib/core/bypass.mjs new file mode 100644 index 0000000000000000000000000000000000000000..08248acf0400ca778ea31cc1721a0a407a40009e --- /dev/null +++ b/node_modules/msw/lib/core/bypass.mjs @@ -0,0 +1,22 @@ +import { invariant } from "outvariant"; +function bypass(input, init) { + const request = new Request( + // If given a Request instance, clone it not to exhaust + // the original request's body. + input instanceof Request ? input.clone() : input, + init + ); + invariant( + !request.bodyUsed, + 'Failed to create a bypassed request to "%s %s": given request instance already has its body read. Make sure to clone the intercepted request if you wish to read its body before bypassing it.', + request.method, + request.url + ); + const requestClone = request.clone(); + requestClone.headers.append("accept", "msw/passthrough"); + return requestClone; +} +export { + bypass +}; +//# sourceMappingURL=bypass.mjs.map \ No newline at end of file diff --git a/node_modules/msw/lib/core/bypass.mjs.map b/node_modules/msw/lib/core/bypass.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..dc3607aea75ece782914e3ba87b472c3acfd118b --- /dev/null +++ b/node_modules/msw/lib/core/bypass.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/core/bypass.ts"],"sourcesContent":["import { invariant } from 'outvariant'\n\nexport type BypassRequestInput = string | URL | Request\n\n/**\n * Creates a `Request` instance that will always be ignored by MSW.\n *\n * @example\n * import { bypass } from 'msw'\n *\n * fetch(bypass('/resource'))\n * fetch(bypass(new URL('/resource', 'https://example.com)))\n * fetch(bypass(new Request('https://example.com/resource')))\n *\n * @see {@link https://mswjs.io/docs/api/bypass `bypass()` API reference}\n */\nexport function bypass(input: BypassRequestInput, init?: RequestInit): Request {\n // Always create a new Request instance.\n // This way, the \"init\" modifications will propagate\n // to the bypass request instance automatically.\n const request = new Request(\n // If given a Request instance, clone it not to exhaust\n // the original request's body.\n input instanceof Request ? input.clone() : input,\n init,\n )\n\n invariant(\n !request.bodyUsed,\n 'Failed to create a bypassed request to \"%s %s\": given request instance already has its body read. Make sure to clone the intercepted request if you wish to read its body before bypassing it.',\n request.method,\n request.url,\n )\n\n const requestClone = request.clone()\n\n /**\n * Send the internal request header that would instruct MSW\n * to perform this request as-is, ignoring any matching handlers.\n * @note Use the `accept` header to support scenarios when the\n * request cannot have headers (e.g. `sendBeacon` requests).\n */\n requestClone.headers.append('accept', 'msw/passthrough')\n\n return requestClone\n}\n"],"mappings":"AAAA,SAAS,iBAAiB;AAgBnB,SAAS,OAAO,OAA2B,MAA6B;AAI7E,QAAM,UAAU,IAAI;AAAA;AAAA;AAAA,IAGlB,iBAAiB,UAAU,MAAM,MAAM,IAAI;AAAA,IAC3C;AAAA,EACF;AAEA;AAAA,IACE,CAAC,QAAQ;AAAA,IACT;AAAA,IACA,QAAQ;AAAA,IACR,QAAQ;AAAA,EACV;AAEA,QAAM,eAAe,QAAQ,MAAM;AAQnC,eAAa,QAAQ,OAAO,UAAU,iBAAiB;AAEvD,SAAO;AACT;","names":[]} \ No newline at end of file diff --git a/node_modules/msw/lib/core/delay.d.mts b/node_modules/msw/lib/core/delay.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..02882824609dd74959b9ece23b548a1f4bddea69 --- /dev/null +++ b/node_modules/msw/lib/core/delay.d.mts @@ -0,0 +1,18 @@ +declare const SET_TIMEOUT_MAX_ALLOWED_INT = 2147483647; +declare const MIN_SERVER_RESPONSE_TIME = 100; +declare const MAX_SERVER_RESPONSE_TIME = 400; +declare const NODE_SERVER_RESPONSE_TIME = 5; +type DelayMode = 'real' | 'infinite'; +/** + * Delays the response by the given duration (ms). + * + * @example + * await delay() // emulate realistic server response time + * await delay(1200) // delay response by 1200ms + * await delay('infinite') // delay response infinitely + * + * @see {@link https://mswjs.io/docs/api/delay `delay()` API reference} + */ +declare function delay(durationOrMode?: DelayMode | number): Promise; + +export { type DelayMode, MAX_SERVER_RESPONSE_TIME, MIN_SERVER_RESPONSE_TIME, NODE_SERVER_RESPONSE_TIME, SET_TIMEOUT_MAX_ALLOWED_INT, delay }; diff --git a/node_modules/msw/lib/core/delay.d.ts b/node_modules/msw/lib/core/delay.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..02882824609dd74959b9ece23b548a1f4bddea69 --- /dev/null +++ b/node_modules/msw/lib/core/delay.d.ts @@ -0,0 +1,18 @@ +declare const SET_TIMEOUT_MAX_ALLOWED_INT = 2147483647; +declare const MIN_SERVER_RESPONSE_TIME = 100; +declare const MAX_SERVER_RESPONSE_TIME = 400; +declare const NODE_SERVER_RESPONSE_TIME = 5; +type DelayMode = 'real' | 'infinite'; +/** + * Delays the response by the given duration (ms). + * + * @example + * await delay() // emulate realistic server response time + * await delay(1200) // delay response by 1200ms + * await delay('infinite') // delay response infinitely + * + * @see {@link https://mswjs.io/docs/api/delay `delay()` API reference} + */ +declare function delay(durationOrMode?: DelayMode | number): Promise; + +export { type DelayMode, MAX_SERVER_RESPONSE_TIME, MIN_SERVER_RESPONSE_TIME, NODE_SERVER_RESPONSE_TIME, SET_TIMEOUT_MAX_ALLOWED_INT, delay }; diff --git a/node_modules/msw/lib/core/delay.js b/node_modules/msw/lib/core/delay.js new file mode 100644 index 0000000000000000000000000000000000000000..ab3ebb2b55cf3a7042f4418b3a79be8b590e8e73 --- /dev/null +++ b/node_modules/msw/lib/core/delay.js @@ -0,0 +1,77 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var delay_exports = {}; +__export(delay_exports, { + MAX_SERVER_RESPONSE_TIME: () => MAX_SERVER_RESPONSE_TIME, + MIN_SERVER_RESPONSE_TIME: () => MIN_SERVER_RESPONSE_TIME, + NODE_SERVER_RESPONSE_TIME: () => NODE_SERVER_RESPONSE_TIME, + SET_TIMEOUT_MAX_ALLOWED_INT: () => SET_TIMEOUT_MAX_ALLOWED_INT, + delay: () => delay +}); +module.exports = __toCommonJS(delay_exports); +var import_is_node_process = require("is-node-process"); +var import_hasRefCounted = require("./utils/internal/hasRefCounted"); +const SET_TIMEOUT_MAX_ALLOWED_INT = 2147483647; +const MIN_SERVER_RESPONSE_TIME = 100; +const MAX_SERVER_RESPONSE_TIME = 400; +const NODE_SERVER_RESPONSE_TIME = 5; +function getRealisticResponseTime() { + if ((0, import_is_node_process.isNodeProcess)()) { + return NODE_SERVER_RESPONSE_TIME; + } + return Math.floor( + Math.random() * (MAX_SERVER_RESPONSE_TIME - MIN_SERVER_RESPONSE_TIME) + MIN_SERVER_RESPONSE_TIME + ); +} +async function delay(durationOrMode) { + let delayTime; + if (typeof durationOrMode === "string") { + switch (durationOrMode) { + case "infinite": { + delayTime = SET_TIMEOUT_MAX_ALLOWED_INT; + break; + } + case "real": { + delayTime = getRealisticResponseTime(); + break; + } + default: { + throw new Error( + `Failed to delay a response: unknown delay mode "${durationOrMode}". Please make sure you provide one of the supported modes ("real", "infinite") or a number.` + ); + } + } + } else if (typeof durationOrMode === "undefined") { + delayTime = getRealisticResponseTime(); + } else { + if (durationOrMode > SET_TIMEOUT_MAX_ALLOWED_INT) { + throw new Error( + `Failed to delay a response: provided delay duration (${durationOrMode}) exceeds the maximum allowed duration for "setTimeout" (${SET_TIMEOUT_MAX_ALLOWED_INT}). This will cause the response to be returned immediately. Please use a number within the allowed range to delay the response by exact duration, or consider the "infinite" delay mode to delay the response indefinitely.` + ); + } + delayTime = durationOrMode; + } + return new Promise((resolve) => { + const timeoutId = setTimeout(resolve, delayTime); + if (delayTime === SET_TIMEOUT_MAX_ALLOWED_INT && (0, import_is_node_process.isNodeProcess)() && (0, import_hasRefCounted.hasRefCounted)(timeoutId)) { + timeoutId.unref(); + } + }); +} +//# sourceMappingURL=delay.js.map \ No newline at end of file diff --git a/node_modules/msw/lib/core/delay.js.map b/node_modules/msw/lib/core/delay.js.map new file mode 100644 index 0000000000000000000000000000000000000000..24bd91e147c6b77293b9774afe072402a40a23fd --- /dev/null +++ b/node_modules/msw/lib/core/delay.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/core/delay.ts"],"sourcesContent":["import { isNodeProcess } from 'is-node-process'\nimport { hasRefCounted } from './utils/internal/hasRefCounted'\n\nexport const SET_TIMEOUT_MAX_ALLOWED_INT = 2147483647\nexport const MIN_SERVER_RESPONSE_TIME = 100\nexport const MAX_SERVER_RESPONSE_TIME = 400\nexport const NODE_SERVER_RESPONSE_TIME = 5\n\nfunction getRealisticResponseTime(): number {\n if (isNodeProcess()) {\n return NODE_SERVER_RESPONSE_TIME\n }\n\n return Math.floor(\n Math.random() * (MAX_SERVER_RESPONSE_TIME - MIN_SERVER_RESPONSE_TIME) +\n MIN_SERVER_RESPONSE_TIME,\n )\n}\n\nexport type DelayMode = 'real' | 'infinite'\n\n/**\n * Delays the response by the given duration (ms).\n *\n * @example\n * await delay() // emulate realistic server response time\n * await delay(1200) // delay response by 1200ms\n * await delay('infinite') // delay response infinitely\n *\n * @see {@link https://mswjs.io/docs/api/delay `delay()` API reference}\n */\nexport async function delay(\n durationOrMode?: DelayMode | number,\n): Promise {\n let delayTime: number\n\n if (typeof durationOrMode === 'string') {\n switch (durationOrMode) {\n case 'infinite': {\n // Using `Infinity` as a delay value executes the response timeout immediately.\n // Instead, use the maximum allowed integer for `setTimeout`.\n delayTime = SET_TIMEOUT_MAX_ALLOWED_INT\n break\n }\n case 'real': {\n delayTime = getRealisticResponseTime()\n break\n }\n default: {\n throw new Error(\n `Failed to delay a response: unknown delay mode \"${durationOrMode}\". Please make sure you provide one of the supported modes (\"real\", \"infinite\") or a number.`,\n )\n }\n }\n } else if (typeof durationOrMode === 'undefined') {\n // Use random realistic server response time when no explicit delay duration was provided.\n delayTime = getRealisticResponseTime()\n } else {\n // Guard against passing values like `Infinity` or `Number.MAX_VALUE`\n // as the response delay duration. They don't produce the result you may expect.\n if (durationOrMode > SET_TIMEOUT_MAX_ALLOWED_INT) {\n throw new Error(\n `Failed to delay a response: provided delay duration (${durationOrMode}) exceeds the maximum allowed duration for \"setTimeout\" (${SET_TIMEOUT_MAX_ALLOWED_INT}). This will cause the response to be returned immediately. Please use a number within the allowed range to delay the response by exact duration, or consider the \"infinite\" delay mode to delay the response indefinitely.`,\n )\n }\n\n delayTime = durationOrMode\n }\n\n return new Promise((resolve) => {\n const timeoutId = setTimeout(resolve, delayTime)\n\n if (\n delayTime === SET_TIMEOUT_MAX_ALLOWED_INT &&\n isNodeProcess() &&\n hasRefCounted(timeoutId)\n ) {\n // Prevent the process from hanging if this is the only active ref.\n timeoutId.unref()\n }\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,6BAA8B;AAC9B,2BAA8B;AAEvB,MAAM,8BAA8B;AACpC,MAAM,2BAA2B;AACjC,MAAM,2BAA2B;AACjC,MAAM,4BAA4B;AAEzC,SAAS,2BAAmC;AAC1C,UAAI,sCAAc,GAAG;AACnB,WAAO;AAAA,EACT;AAEA,SAAO,KAAK;AAAA,IACV,KAAK,OAAO,KAAK,2BAA2B,4BAC1C;AAAA,EACJ;AACF;AAcA,eAAsB,MACpB,gBACe;AACf,MAAI;AAEJ,MAAI,OAAO,mBAAmB,UAAU;AACtC,YAAQ,gBAAgB;AAAA,MACtB,KAAK,YAAY;AAGf,oBAAY;AACZ;AAAA,MACF;AAAA,MACA,KAAK,QAAQ;AACX,oBAAY,yBAAyB;AACrC;AAAA,MACF;AAAA,MACA,SAAS;AACP,cAAM,IAAI;AAAA,UACR,mDAAmD,cAAc;AAAA,QACnE;AAAA,MACF;AAAA,IACF;AAAA,EACF,WAAW,OAAO,mBAAmB,aAAa;AAEhD,gBAAY,yBAAyB;AAAA,EACvC,OAAO;AAGL,QAAI,iBAAiB,6BAA6B;AAChD,YAAM,IAAI;AAAA,QACR,wDAAwD,cAAc,4DAA4D,2BAA2B;AAAA,MAC/J;AAAA,IACF;AAEA,gBAAY;AAAA,EACd;AAEA,SAAO,IAAI,QAAQ,CAAC,YAAY;AAC9B,UAAM,YAAY,WAAW,SAAS,SAAS;AAE/C,QACE,cAAc,mCACd,sCAAc,SACd,oCAAc,SAAS,GACvB;AAEA,gBAAU,MAAM;AAAA,IAClB;AAAA,EACF,CAAC;AACH;","names":[]} \ No newline at end of file diff --git a/node_modules/msw/lib/core/delay.mjs b/node_modules/msw/lib/core/delay.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c978abc58d5a3effef6acf733d45414aa837cd4c --- /dev/null +++ b/node_modules/msw/lib/core/delay.mjs @@ -0,0 +1,57 @@ +import { isNodeProcess } from "is-node-process"; +import { hasRefCounted } from './utils/internal/hasRefCounted.mjs'; +const SET_TIMEOUT_MAX_ALLOWED_INT = 2147483647; +const MIN_SERVER_RESPONSE_TIME = 100; +const MAX_SERVER_RESPONSE_TIME = 400; +const NODE_SERVER_RESPONSE_TIME = 5; +function getRealisticResponseTime() { + if (isNodeProcess()) { + return NODE_SERVER_RESPONSE_TIME; + } + return Math.floor( + Math.random() * (MAX_SERVER_RESPONSE_TIME - MIN_SERVER_RESPONSE_TIME) + MIN_SERVER_RESPONSE_TIME + ); +} +async function delay(durationOrMode) { + let delayTime; + if (typeof durationOrMode === "string") { + switch (durationOrMode) { + case "infinite": { + delayTime = SET_TIMEOUT_MAX_ALLOWED_INT; + break; + } + case "real": { + delayTime = getRealisticResponseTime(); + break; + } + default: { + throw new Error( + `Failed to delay a response: unknown delay mode "${durationOrMode}". Please make sure you provide one of the supported modes ("real", "infinite") or a number.` + ); + } + } + } else if (typeof durationOrMode === "undefined") { + delayTime = getRealisticResponseTime(); + } else { + if (durationOrMode > SET_TIMEOUT_MAX_ALLOWED_INT) { + throw new Error( + `Failed to delay a response: provided delay duration (${durationOrMode}) exceeds the maximum allowed duration for "setTimeout" (${SET_TIMEOUT_MAX_ALLOWED_INT}). This will cause the response to be returned immediately. Please use a number within the allowed range to delay the response by exact duration, or consider the "infinite" delay mode to delay the response indefinitely.` + ); + } + delayTime = durationOrMode; + } + return new Promise((resolve) => { + const timeoutId = setTimeout(resolve, delayTime); + if (delayTime === SET_TIMEOUT_MAX_ALLOWED_INT && isNodeProcess() && hasRefCounted(timeoutId)) { + timeoutId.unref(); + } + }); +} +export { + MAX_SERVER_RESPONSE_TIME, + MIN_SERVER_RESPONSE_TIME, + NODE_SERVER_RESPONSE_TIME, + SET_TIMEOUT_MAX_ALLOWED_INT, + delay +}; +//# sourceMappingURL=delay.mjs.map \ No newline at end of file diff --git a/node_modules/msw/lib/core/delay.mjs.map b/node_modules/msw/lib/core/delay.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..9625442936cd6322765f0819be7c4d3102c5756f --- /dev/null +++ b/node_modules/msw/lib/core/delay.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/core/delay.ts"],"sourcesContent":["import { isNodeProcess } from 'is-node-process'\nimport { hasRefCounted } from './utils/internal/hasRefCounted'\n\nexport const SET_TIMEOUT_MAX_ALLOWED_INT = 2147483647\nexport const MIN_SERVER_RESPONSE_TIME = 100\nexport const MAX_SERVER_RESPONSE_TIME = 400\nexport const NODE_SERVER_RESPONSE_TIME = 5\n\nfunction getRealisticResponseTime(): number {\n if (isNodeProcess()) {\n return NODE_SERVER_RESPONSE_TIME\n }\n\n return Math.floor(\n Math.random() * (MAX_SERVER_RESPONSE_TIME - MIN_SERVER_RESPONSE_TIME) +\n MIN_SERVER_RESPONSE_TIME,\n )\n}\n\nexport type DelayMode = 'real' | 'infinite'\n\n/**\n * Delays the response by the given duration (ms).\n *\n * @example\n * await delay() // emulate realistic server response time\n * await delay(1200) // delay response by 1200ms\n * await delay('infinite') // delay response infinitely\n *\n * @see {@link https://mswjs.io/docs/api/delay `delay()` API reference}\n */\nexport async function delay(\n durationOrMode?: DelayMode | number,\n): Promise {\n let delayTime: number\n\n if (typeof durationOrMode === 'string') {\n switch (durationOrMode) {\n case 'infinite': {\n // Using `Infinity` as a delay value executes the response timeout immediately.\n // Instead, use the maximum allowed integer for `setTimeout`.\n delayTime = SET_TIMEOUT_MAX_ALLOWED_INT\n break\n }\n case 'real': {\n delayTime = getRealisticResponseTime()\n break\n }\n default: {\n throw new Error(\n `Failed to delay a response: unknown delay mode \"${durationOrMode}\". Please make sure you provide one of the supported modes (\"real\", \"infinite\") or a number.`,\n )\n }\n }\n } else if (typeof durationOrMode === 'undefined') {\n // Use random realistic server response time when no explicit delay duration was provided.\n delayTime = getRealisticResponseTime()\n } else {\n // Guard against passing values like `Infinity` or `Number.MAX_VALUE`\n // as the response delay duration. They don't produce the result you may expect.\n if (durationOrMode > SET_TIMEOUT_MAX_ALLOWED_INT) {\n throw new Error(\n `Failed to delay a response: provided delay duration (${durationOrMode}) exceeds the maximum allowed duration for \"setTimeout\" (${SET_TIMEOUT_MAX_ALLOWED_INT}). This will cause the response to be returned immediately. Please use a number within the allowed range to delay the response by exact duration, or consider the \"infinite\" delay mode to delay the response indefinitely.`,\n )\n }\n\n delayTime = durationOrMode\n }\n\n return new Promise((resolve) => {\n const timeoutId = setTimeout(resolve, delayTime)\n\n if (\n delayTime === SET_TIMEOUT_MAX_ALLOWED_INT &&\n isNodeProcess() &&\n hasRefCounted(timeoutId)\n ) {\n // Prevent the process from hanging if this is the only active ref.\n timeoutId.unref()\n }\n })\n}\n"],"mappings":"AAAA,SAAS,qBAAqB;AAC9B,SAAS,qBAAqB;AAEvB,MAAM,8BAA8B;AACpC,MAAM,2BAA2B;AACjC,MAAM,2BAA2B;AACjC,MAAM,4BAA4B;AAEzC,SAAS,2BAAmC;AAC1C,MAAI,cAAc,GAAG;AACnB,WAAO;AAAA,EACT;AAEA,SAAO,KAAK;AAAA,IACV,KAAK,OAAO,KAAK,2BAA2B,4BAC1C;AAAA,EACJ;AACF;AAcA,eAAsB,MACpB,gBACe;AACf,MAAI;AAEJ,MAAI,OAAO,mBAAmB,UAAU;AACtC,YAAQ,gBAAgB;AAAA,MACtB,KAAK,YAAY;AAGf,oBAAY;AACZ;AAAA,MACF;AAAA,MACA,KAAK,QAAQ;AACX,oBAAY,yBAAyB;AACrC;AAAA,MACF;AAAA,MACA,SAAS;AACP,cAAM,IAAI;AAAA,UACR,mDAAmD,cAAc;AAAA,QACnE;AAAA,MACF;AAAA,IACF;AAAA,EACF,WAAW,OAAO,mBAAmB,aAAa;AAEhD,gBAAY,yBAAyB;AAAA,EACvC,OAAO;AAGL,QAAI,iBAAiB,6BAA6B;AAChD,YAAM,IAAI;AAAA,QACR,wDAAwD,cAAc,4DAA4D,2BAA2B;AAAA,MAC/J;AAAA,IACF;AAEA,gBAAY;AAAA,EACd;AAEA,SAAO,IAAI,QAAQ,CAAC,YAAY;AAC9B,UAAM,YAAY,WAAW,SAAS,SAAS;AAE/C,QACE,cAAc,+BACd,cAAc,KACd,cAAc,SAAS,GACvB;AAEA,gBAAU,MAAM;AAAA,IAClB;AAAA,EACF,CAAC;AACH;","names":[]} \ No newline at end of file diff --git a/node_modules/msw/lib/core/experimental/compat.d.mts b/node_modules/msw/lib/core/experimental/compat.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..601a381f3350d4397e557620a004dc2344e59019 --- /dev/null +++ b/node_modules/msw/lib/core/experimental/compat.d.mts @@ -0,0 +1,17 @@ +import { UnhandledRequestStrategy } from '../utils/request/onUnhandledRequest.mjs'; +import { U as UnhandledFrameCallback } from '../on-unhandled-frame-Cr1KOZ0I.mjs'; +import 'rettime'; +import './handlers-controller.mjs'; +import '../HttpResponse-CQwYpuKo.mjs'; +import '@mswjs/interceptors'; +import '../utils/internal/isIterable.mjs'; +import '../typeUtils.mjs'; +import 'graphql'; +import '../utils/matching/matchRequestUrl.mjs'; +import '../handlers/WebSocketHandler.mjs'; +import 'strict-event-emitter'; +import '@mswjs/interceptors/WebSocket'; + +declare function fromLegacyOnUnhandledRequest(getLegacyValue: () => UnhandledRequestStrategy | undefined): UnhandledFrameCallback; + +export { fromLegacyOnUnhandledRequest }; diff --git a/node_modules/msw/lib/core/experimental/compat.d.ts b/node_modules/msw/lib/core/experimental/compat.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..414bce4b1378de0e1f452f4eae5258cc47f518c5 --- /dev/null +++ b/node_modules/msw/lib/core/experimental/compat.d.ts @@ -0,0 +1,17 @@ +import { UnhandledRequestStrategy } from '../utils/request/onUnhandledRequest.js'; +import { U as UnhandledFrameCallback } from '../on-unhandled-frame-BBR-P3kV.js'; +import 'rettime'; +import './handlers-controller.js'; +import '../HttpResponse-BFS34nkx.js'; +import '@mswjs/interceptors'; +import '../utils/internal/isIterable.js'; +import '../typeUtils.js'; +import 'graphql'; +import '../utils/matching/matchRequestUrl.js'; +import '../handlers/WebSocketHandler.js'; +import 'strict-event-emitter'; +import '@mswjs/interceptors/WebSocket'; + +declare function fromLegacyOnUnhandledRequest(getLegacyValue: () => UnhandledRequestStrategy | undefined): UnhandledFrameCallback; + +export { fromLegacyOnUnhandledRequest }; diff --git a/node_modules/msw/lib/core/experimental/compat.js b/node_modules/msw/lib/core/experimental/compat.js new file mode 100644 index 0000000000000000000000000000000000000000..2c17e9276347515e1d92df289bb499217db2bcff --- /dev/null +++ b/node_modules/msw/lib/core/experimental/compat.js @@ -0,0 +1,55 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var compat_exports = {}; +__export(compat_exports, { + fromLegacyOnUnhandledRequest: () => fromLegacyOnUnhandledRequest +}); +module.exports = __toCommonJS(compat_exports); +var import_outvariant = require("outvariant"); +var import_onUnhandledRequest = require("../utils/request/onUnhandledRequest"); +var import_on_unhandled_frame = require("./on-unhandled-frame"); +var import_http_frame = require("./frames/http-frame"); +var import_websocket_frame = require("./frames/websocket-frame"); +function fromLegacyOnUnhandledRequest(getLegacyValue) { + return ({ frame, defaults }) => { + const legacyOnUnhandledRequestStrategy = getLegacyValue(); + if (legacyOnUnhandledRequestStrategy == null) { + return; + } + if (typeof legacyOnUnhandledRequestStrategy === "function") { + const request = frame instanceof import_http_frame.HttpNetworkFrame ? frame.data.request : frame instanceof import_websocket_frame.WebSocketNetworkFrame ? new Request(frame.data.connection.client.url, { + headers: { + connection: "upgrade", + upgrade: "websocket" + } + }) : null; + (0, import_outvariant.invariant)( + request != null, + 'Failed to coerce a network frame to a legacy `onUnhandledRequest` strategy: unknown frame protocol "%s"', + frame.protocol + ); + return legacyOnUnhandledRequestStrategy(request, { + warning: defaults.warn, + error: defaults.error + }); + } + return (0, import_on_unhandled_frame.executeUnhandledFrameHandle)(frame, legacyOnUnhandledRequestStrategy); + }; +} +//# sourceMappingURL=compat.js.map \ No newline at end of file diff --git a/node_modules/msw/lib/core/experimental/compat.js.map b/node_modules/msw/lib/core/experimental/compat.js.map new file mode 100644 index 0000000000000000000000000000000000000000..7e7dab54fa8e73d3087f353cbdf6755dabf3e26e --- /dev/null +++ b/node_modules/msw/lib/core/experimental/compat.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/core/experimental/compat.ts"],"sourcesContent":["/**\n * Collection of helpers for bridging the compatibility between the old and the new APIs.\n */\nimport { invariant } from 'outvariant'\nimport { type UnhandledRequestStrategy } from '../utils/request/onUnhandledRequest'\nimport {\n executeUnhandledFrameHandle,\n type UnhandledFrameCallback,\n} from './on-unhandled-frame'\nimport { HttpNetworkFrame } from './frames/http-frame'\nimport { WebSocketNetworkFrame } from './frames/websocket-frame'\n\nexport function fromLegacyOnUnhandledRequest(\n getLegacyValue: () => UnhandledRequestStrategy | undefined,\n): UnhandledFrameCallback {\n return ({ frame, defaults }) => {\n const legacyOnUnhandledRequestStrategy = getLegacyValue()\n\n if (legacyOnUnhandledRequestStrategy == null) {\n return\n }\n\n if (typeof legacyOnUnhandledRequestStrategy === 'function') {\n const request =\n frame instanceof HttpNetworkFrame\n ? frame.data.request\n : frame instanceof WebSocketNetworkFrame\n ? new Request(frame.data.connection.client.url, {\n headers: {\n connection: 'upgrade',\n upgrade: 'websocket',\n },\n })\n : null\n\n invariant(\n request != null,\n 'Failed to coerce a network frame to a legacy `onUnhandledRequest` strategy: unknown frame protocol \"%s\"',\n frame.protocol,\n )\n\n return legacyOnUnhandledRequestStrategy(request, {\n warning: defaults.warn,\n error: defaults.error,\n })\n }\n\n return executeUnhandledFrameHandle(frame, legacyOnUnhandledRequestStrategy)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,wBAA0B;AAC1B,gCAA8C;AAC9C,gCAGO;AACP,wBAAiC;AACjC,6BAAsC;AAE/B,SAAS,6BACd,gBACwB;AACxB,SAAO,CAAC,EAAE,OAAO,SAAS,MAAM;AAC9B,UAAM,mCAAmC,eAAe;AAExD,QAAI,oCAAoC,MAAM;AAC5C;AAAA,IACF;AAEA,QAAI,OAAO,qCAAqC,YAAY;AAC1D,YAAM,UACJ,iBAAiB,qCACb,MAAM,KAAK,UACX,iBAAiB,+CACf,IAAI,QAAQ,MAAM,KAAK,WAAW,OAAO,KAAK;AAAA,QAC5C,SAAS;AAAA,UACP,YAAY;AAAA,UACZ,SAAS;AAAA,QACX;AAAA,MACF,CAAC,IACD;AAER;AAAA,QACE,WAAW;AAAA,QACX;AAAA,QACA,MAAM;AAAA,MACR;AAEA,aAAO,iCAAiC,SAAS;AAAA,QAC/C,SAAS,SAAS;AAAA,QAClB,OAAO,SAAS;AAAA,MAClB,CAAC;AAAA,IACH;AAEA,eAAO,uDAA4B,OAAO,gCAAgC;AAAA,EAC5E;AACF;","names":[]} \ No newline at end of file diff --git a/node_modules/msw/lib/core/experimental/compat.mjs b/node_modules/msw/lib/core/experimental/compat.mjs new file mode 100644 index 0000000000000000000000000000000000000000..837b93331ed639399e2f3bce287a0f364b22db8f --- /dev/null +++ b/node_modules/msw/lib/core/experimental/compat.mjs @@ -0,0 +1,37 @@ +import { invariant } from "outvariant"; +import {} from '../utils/request/onUnhandledRequest.mjs'; +import { + executeUnhandledFrameHandle +} from './on-unhandled-frame.mjs'; +import { HttpNetworkFrame } from './frames/http-frame.mjs'; +import { WebSocketNetworkFrame } from './frames/websocket-frame.mjs'; +function fromLegacyOnUnhandledRequest(getLegacyValue) { + return ({ frame, defaults }) => { + const legacyOnUnhandledRequestStrategy = getLegacyValue(); + if (legacyOnUnhandledRequestStrategy == null) { + return; + } + if (typeof legacyOnUnhandledRequestStrategy === "function") { + const request = frame instanceof HttpNetworkFrame ? frame.data.request : frame instanceof WebSocketNetworkFrame ? new Request(frame.data.connection.client.url, { + headers: { + connection: "upgrade", + upgrade: "websocket" + } + }) : null; + invariant( + request != null, + 'Failed to coerce a network frame to a legacy `onUnhandledRequest` strategy: unknown frame protocol "%s"', + frame.protocol + ); + return legacyOnUnhandledRequestStrategy(request, { + warning: defaults.warn, + error: defaults.error + }); + } + return executeUnhandledFrameHandle(frame, legacyOnUnhandledRequestStrategy); + }; +} +export { + fromLegacyOnUnhandledRequest +}; +//# sourceMappingURL=compat.mjs.map \ No newline at end of file diff --git a/node_modules/msw/lib/core/experimental/compat.mjs.map b/node_modules/msw/lib/core/experimental/compat.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..b4cef66b30fde33339d47abd64a17d0fc2dde978 --- /dev/null +++ b/node_modules/msw/lib/core/experimental/compat.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/core/experimental/compat.ts"],"sourcesContent":["/**\n * Collection of helpers for bridging the compatibility between the old and the new APIs.\n */\nimport { invariant } from 'outvariant'\nimport { type UnhandledRequestStrategy } from '../utils/request/onUnhandledRequest'\nimport {\n executeUnhandledFrameHandle,\n type UnhandledFrameCallback,\n} from './on-unhandled-frame'\nimport { HttpNetworkFrame } from './frames/http-frame'\nimport { WebSocketNetworkFrame } from './frames/websocket-frame'\n\nexport function fromLegacyOnUnhandledRequest(\n getLegacyValue: () => UnhandledRequestStrategy | undefined,\n): UnhandledFrameCallback {\n return ({ frame, defaults }) => {\n const legacyOnUnhandledRequestStrategy = getLegacyValue()\n\n if (legacyOnUnhandledRequestStrategy == null) {\n return\n }\n\n if (typeof legacyOnUnhandledRequestStrategy === 'function') {\n const request =\n frame instanceof HttpNetworkFrame\n ? frame.data.request\n : frame instanceof WebSocketNetworkFrame\n ? new Request(frame.data.connection.client.url, {\n headers: {\n connection: 'upgrade',\n upgrade: 'websocket',\n },\n })\n : null\n\n invariant(\n request != null,\n 'Failed to coerce a network frame to a legacy `onUnhandledRequest` strategy: unknown frame protocol \"%s\"',\n frame.protocol,\n )\n\n return legacyOnUnhandledRequestStrategy(request, {\n warning: defaults.warn,\n error: defaults.error,\n })\n }\n\n return executeUnhandledFrameHandle(frame, legacyOnUnhandledRequestStrategy)\n }\n}\n"],"mappings":"AAGA,SAAS,iBAAiB;AAC1B,eAA8C;AAC9C;AAAA,EACE;AAAA,OAEK;AACP,SAAS,wBAAwB;AACjC,SAAS,6BAA6B;AAE/B,SAAS,6BACd,gBACwB;AACxB,SAAO,CAAC,EAAE,OAAO,SAAS,MAAM;AAC9B,UAAM,mCAAmC,eAAe;AAExD,QAAI,oCAAoC,MAAM;AAC5C;AAAA,IACF;AAEA,QAAI,OAAO,qCAAqC,YAAY;AAC1D,YAAM,UACJ,iBAAiB,mBACb,MAAM,KAAK,UACX,iBAAiB,wBACf,IAAI,QAAQ,MAAM,KAAK,WAAW,OAAO,KAAK;AAAA,QAC5C,SAAS;AAAA,UACP,YAAY;AAAA,UACZ,SAAS;AAAA,QACX;AAAA,MACF,CAAC,IACD;AAER;AAAA,QACE,WAAW;AAAA,QACX;AAAA,QACA,MAAM;AAAA,MACR;AAEA,aAAO,iCAAiC,SAAS;AAAA,QAC/C,SAAS,SAAS;AAAA,QAClB,OAAO,SAAS;AAAA,MAClB,CAAC;AAAA,IACH;AAEA,WAAO,4BAA4B,OAAO,gCAAgC;AAAA,EAC5E;AACF;","names":[]} \ No newline at end of file diff --git a/node_modules/msw/lib/core/experimental/define-network.d.mts b/node_modules/msw/lib/core/experimental/define-network.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..8cc48f75a31efcece87c7506a0dda059fb1a8d92 --- /dev/null +++ b/node_modules/msw/lib/core/experimental/define-network.d.mts @@ -0,0 +1,75 @@ +import { Emitter, DefaultEventMap } from 'rettime'; +import { NetworkSource, ExtractSourceEvents } from './sources/network-source.mjs'; +import { a as NetworkFrameResolutionContext, b as UnhandledFrameHandle } from '../on-unhandled-frame-Cr1KOZ0I.mjs'; +import { AnyHandler, HandlersController } from './handlers-controller.mjs'; +import '../HttpResponse-CQwYpuKo.mjs'; +import '@mswjs/interceptors'; +import '../utils/internal/isIterable.mjs'; +import '../typeUtils.mjs'; +import 'graphql'; +import '../utils/matching/matchRequestUrl.mjs'; +import '../handlers/WebSocketHandler.mjs'; +import 'strict-event-emitter'; +import '@mswjs/interceptors/WebSocket'; + +type UnionToIntersection = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never; +type MergeEventMaps>> = UnionToIntersection> extends infer R ? R extends Record ? R : DefaultEventMap : DefaultEventMap; +type MaybePromise = Extract> extends never ? void : Promise; +interface DefineNetworkOptions>> { + /** + * List of the network sources. + * Every network source emits frames, and every frame describes how + * to handle the various network scenarios, like mocking a response, + * erroring the request, or performing it as-is. + */ + sources: Sources; + /** + * List of handlers to describe the network. + */ + handlers?: Array | HandlersController; + context?: NetworkFrameResolutionContext; + onUnhandledFrame?: UnhandledFrameHandle; +} +interface NetworkApi>> extends NetworkHandlersApi { + readyState: NetworkReadyState; + /** + * Enable the network interception and handling. + */ + enable: () => MaybePromise>; + /** + * Disable the network interception and handling. + */ + disable: () => MaybePromise>; + /** + * Configure the network instance with additional options. + * The options provided in the `.configure()` call will override the same + * options in the `defineNetwork()` call. + */ + configure: (options: Partial>) => void; + events: Emitter>; +} +interface NetworkHandlersApi { + use: (...handlers: Array) => void; + resetHandlers: (...handlers: Array) => void; + restoreHandlers: () => void; + listHandlers: () => ReadonlyArray; +} +declare enum NetworkReadyState { + DISABLED = 0, + ENABLED = 1 +} +/** + * Define a network instance with the given configuration. + * @example + * import { InterceptorSource } from 'msw/experimental' + * import { handlers } from './handlers' + * + * const network = defineNetwork({ + * sources: [new InterceptorSource({ interceptors })], + * handlers, + * }) + * await network.enable() + */ +declare function defineNetwork>>(options: DefineNetworkOptions): NetworkApi; + +export { type DefineNetworkOptions, type NetworkApi, type NetworkHandlersApi, NetworkReadyState, defineNetwork }; diff --git a/node_modules/msw/lib/core/experimental/define-network.d.ts b/node_modules/msw/lib/core/experimental/define-network.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7d5f58bb9aa2e4c64a80d73095c1ac04442988c3 --- /dev/null +++ b/node_modules/msw/lib/core/experimental/define-network.d.ts @@ -0,0 +1,75 @@ +import { Emitter, DefaultEventMap } from 'rettime'; +import { NetworkSource, ExtractSourceEvents } from './sources/network-source.js'; +import { a as NetworkFrameResolutionContext, b as UnhandledFrameHandle } from '../on-unhandled-frame-BBR-P3kV.js'; +import { AnyHandler, HandlersController } from './handlers-controller.js'; +import '../HttpResponse-BFS34nkx.js'; +import '@mswjs/interceptors'; +import '../utils/internal/isIterable.js'; +import '../typeUtils.js'; +import 'graphql'; +import '../utils/matching/matchRequestUrl.js'; +import '../handlers/WebSocketHandler.js'; +import 'strict-event-emitter'; +import '@mswjs/interceptors/WebSocket'; + +type UnionToIntersection = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never; +type MergeEventMaps>> = UnionToIntersection> extends infer R ? R extends Record ? R : DefaultEventMap : DefaultEventMap; +type MaybePromise = Extract> extends never ? void : Promise; +interface DefineNetworkOptions>> { + /** + * List of the network sources. + * Every network source emits frames, and every frame describes how + * to handle the various network scenarios, like mocking a response, + * erroring the request, or performing it as-is. + */ + sources: Sources; + /** + * List of handlers to describe the network. + */ + handlers?: Array | HandlersController; + context?: NetworkFrameResolutionContext; + onUnhandledFrame?: UnhandledFrameHandle; +} +interface NetworkApi>> extends NetworkHandlersApi { + readyState: NetworkReadyState; + /** + * Enable the network interception and handling. + */ + enable: () => MaybePromise>; + /** + * Disable the network interception and handling. + */ + disable: () => MaybePromise>; + /** + * Configure the network instance with additional options. + * The options provided in the `.configure()` call will override the same + * options in the `defineNetwork()` call. + */ + configure: (options: Partial>) => void; + events: Emitter>; +} +interface NetworkHandlersApi { + use: (...handlers: Array) => void; + resetHandlers: (...handlers: Array) => void; + restoreHandlers: () => void; + listHandlers: () => ReadonlyArray; +} +declare enum NetworkReadyState { + DISABLED = 0, + ENABLED = 1 +} +/** + * Define a network instance with the given configuration. + * @example + * import { InterceptorSource } from 'msw/experimental' + * import { handlers } from './handlers' + * + * const network = defineNetwork({ + * sources: [new InterceptorSource({ interceptors })], + * handlers, + * }) + * await network.enable() + */ +declare function defineNetwork>>(options: DefineNetworkOptions): NetworkApi; + +export { type DefineNetworkOptions, type NetworkApi, type NetworkHandlersApi, NetworkReadyState, defineNetwork }; diff --git a/node_modules/msw/lib/core/experimental/define-network.js b/node_modules/msw/lib/core/experimental/define-network.js new file mode 100644 index 0000000000000000000000000000000000000000..fb025f2546d9cf88cd4968e283ef3878fff9afb3 --- /dev/null +++ b/node_modules/msw/lib/core/experimental/define-network.js @@ -0,0 +1,134 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var define_network_exports = {}; +__export(define_network_exports, { + NetworkReadyState: () => NetworkReadyState, + defineNetwork: () => defineNetwork +}); +module.exports = __toCommonJS(define_network_exports); +var import_outvariant = require("outvariant"); +var import_rettime = require("rettime"); +var import_network_source = require("./sources/network-source"); +var import_network_frame = require("./frames/network-frame"); +var import_on_unhandled_frame = require("./on-unhandled-frame"); +var import_handlers_controller = require("./handlers-controller"); +var import_toReadonlyArray = require("../utils/internal/toReadonlyArray"); +var import_Disposable = require("../utils/internal/Disposable"); +function colorlessPromiseAll(values) { + const promises = []; + for (const value of values) { + if (value instanceof Promise) { + promises.push(value); + } + } + if (promises.length > 0) { + return Promise.all(promises).then(() => { + }); + } +} +var NetworkReadyState = /* @__PURE__ */ ((NetworkReadyState2) => { + NetworkReadyState2[NetworkReadyState2["DISABLED"] = 0] = "DISABLED"; + NetworkReadyState2[NetworkReadyState2["ENABLED"] = 1] = "ENABLED"; + return NetworkReadyState2; +})(NetworkReadyState || {}); +function defineNetwork(options) { + let readyState = 0 /* DISABLED */; + const events = new import_rettime.Emitter(); + const disposable = new import_Disposable.Disposable(); + const deriveHandlersController = (handlers) => { + return handlers instanceof import_handlers_controller.HandlersController ? handlers : new import_handlers_controller.InMemoryHandlersController(handlers || []); + }; + let resolvedOptions = { + ...options + }; + let handlersController = deriveHandlersController(resolvedOptions.handlers); + return { + get readyState() { + return readyState; + }, + events, + configure(options2) { + (0, import_outvariant.invariant)( + readyState === 0 /* DISABLED */, + 'Failed to call "configure()" on the network: cannot configure an already enabled network.' + ); + if (options2.handlers && !Object.is(options2.handlers, resolvedOptions.handlers)) { + handlersController = deriveHandlersController(options2.handlers); + } + resolvedOptions = { + ...resolvedOptions, + ...options2 + }; + }, + enable() { + (0, import_outvariant.invariant)( + readyState === 0 /* DISABLED */, + 'Failed to call "enable" on the network: already enabled' + ); + readyState = 1 /* ENABLED */; + const session = { active: true }; + disposable["subscriptions"].push(() => { + session.active = false; + }); + const result = resolvedOptions.sources.map((source) => { + import_network_source.NetworkSource.prototype.disable.call(source); + source.on("frame", async ({ frame }) => { + frame.events.on("*", (event) => { + if (!session.active) { + return; + } + events.emit(event); + }); + const handlers = frame.getHandlers(handlersController); + await frame.resolve( + handlers, + resolvedOptions.onUnhandledFrame || "warn", + resolvedOptions.context + ); + }); + return source.enable(); + }); + return colorlessPromiseAll(result); + }, + disable() { + (0, import_outvariant.invariant)( + readyState === 1 /* ENABLED */, + 'Failed to call "disable" on the network: already disabled' + ); + readyState = 0 /* DISABLED */; + disposable.dispose(); + return colorlessPromiseAll( + resolvedOptions.sources.map((source) => source.disable()) + ); + }, + use(...handlers) { + handlersController.use(handlers); + }, + resetHandlers(...handlers) { + handlersController.reset(handlers); + }, + restoreHandlers() { + handlersController.restore(); + }, + listHandlers() { + return (0, import_toReadonlyArray.toReadonlyArray)(handlersController.currentHandlers()); + } + }; +} +//# sourceMappingURL=define-network.js.map \ No newline at end of file diff --git a/node_modules/msw/lib/core/experimental/define-network.js.map b/node_modules/msw/lib/core/experimental/define-network.js.map new file mode 100644 index 0000000000000000000000000000000000000000..1081c5e67c3c615a60ab08a945a87ade0b068d91 --- /dev/null +++ b/node_modules/msw/lib/core/experimental/define-network.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/core/experimental/define-network.ts"],"sourcesContent":["import { invariant } from 'outvariant'\nimport { Emitter, type DefaultEventMap } from 'rettime'\nimport {\n NetworkSource,\n type ExtractSourceEvents,\n} from './sources/network-source'\nimport { type NetworkFrameResolutionContext } from './frames/network-frame'\nimport { type UnhandledFrameHandle } from './on-unhandled-frame'\nimport {\n HandlersController,\n InMemoryHandlersController,\n type AnyHandler,\n} from './handlers-controller'\nimport { toReadonlyArray } from '../utils/internal/toReadonlyArray'\nimport { Disposable } from '../utils/internal/Disposable'\n\ntype UnionToIntersection = (U extends any ? (k: U) => void : never) extends (\n k: infer I,\n) => void\n ? I\n : never\n\ntype MergeEventMaps>> =\n UnionToIntersection> extends infer R\n ? R extends Record\n ? R\n : DefaultEventMap\n : DefaultEventMap\n\ntype MaybePromise =\n Extract> extends never ? void : Promise\n\nexport interface DefineNetworkOptions<\n Sources extends Array>,\n> {\n /**\n * List of the network sources.\n * Every network source emits frames, and every frame describes how\n * to handle the various network scenarios, like mocking a response,\n * erroring the request, or performing it as-is.\n */\n sources: Sources\n /**\n * List of handlers to describe the network.\n */\n handlers?: Array | HandlersController\n context?: NetworkFrameResolutionContext\n onUnhandledFrame?: UnhandledFrameHandle\n}\n\nexport interface NetworkApi<\n Sources extends Array>,\n> extends NetworkHandlersApi {\n readyState: NetworkReadyState\n /**\n * Enable the network interception and handling.\n */\n enable: () => MaybePromise>\n /**\n * Disable the network interception and handling.\n */\n disable: () => MaybePromise>\n /**\n * Configure the network instance with additional options.\n * The options provided in the `.configure()` call will override the same\n * options in the `defineNetwork()` call.\n */\n configure: (options: Partial>) => void\n events: Emitter>\n}\n\nexport interface NetworkHandlersApi {\n use: (...handlers: Array) => void\n resetHandlers: (...handlers: Array) => void\n restoreHandlers: () => void\n listHandlers: () => ReadonlyArray\n}\n\nfunction colorlessPromiseAll(values: Array): MaybePromise\nfunction colorlessPromiseAll(values: Array): Promise | void {\n const promises: Array> = []\n\n for (const value of values) {\n if (value instanceof Promise) {\n promises.push(value)\n }\n }\n\n if (promises.length > 0) {\n return Promise.all(promises).then(() => {})\n }\n}\n\nexport enum NetworkReadyState {\n DISABLED,\n ENABLED,\n}\n\n/**\n * Define a network instance with the given configuration.\n * @example\n * import { InterceptorSource } from 'msw/experimental'\n * import { handlers } from './handlers'\n *\n * const network = defineNetwork({\n * sources: [new InterceptorSource({ interceptors })],\n * handlers,\n * })\n * await network.enable()\n */\nexport function defineNetwork>>(\n options: DefineNetworkOptions,\n): NetworkApi {\n let readyState: NetworkReadyState = NetworkReadyState.DISABLED\n const events = new Emitter>()\n const disposable = new Disposable()\n\n const deriveHandlersController = (\n handlers: DefineNetworkOptions['handlers'],\n ) => {\n return handlers instanceof HandlersController\n ? handlers\n : new InMemoryHandlersController(handlers || [])\n }\n\n let resolvedOptions: DefineNetworkOptions = {\n ...options,\n }\n\n /**\n * @note Create the handlers controller immediately because\n * certain setup APIs, like `setupServer`, don't await `.enable` (`.listen`).\n */\n let handlersController = deriveHandlersController(resolvedOptions.handlers)\n\n return {\n get readyState() {\n return readyState\n },\n events,\n configure(options) {\n invariant(\n readyState === NetworkReadyState.DISABLED,\n 'Failed to call \"configure()\" on the network: cannot configure an already enabled network.',\n )\n\n if (\n options.handlers &&\n !Object.is(options.handlers, resolvedOptions.handlers)\n ) {\n handlersController = deriveHandlersController(options.handlers)\n }\n\n resolvedOptions = {\n ...resolvedOptions,\n ...options,\n }\n },\n enable() {\n invariant(\n readyState === NetworkReadyState.DISABLED,\n 'Failed to call \"enable\" on the network: already enabled',\n )\n\n readyState = NetworkReadyState.ENABLED\n\n /**\n * @note Use a session object scoped to the current \"enable()\"\n * to prevent \"frame.events\" listeners from surviving across enable/disable cycles.\n * @see The note about `AbortController` below.\n */\n const session = { active: true }\n disposable['subscriptions'].push(() => {\n session.active = false\n })\n\n const result = resolvedOptions.sources.map((source) => {\n /**\n * @note Preemptively disable the network source before enabling.\n * This intentionally calls only the prototype method that clears the\n * event listeners and nothing else. This prevents the \"frame\" listeners\n * from accumulating across enable/disable in case the source is a singleton.\n */\n NetworkSource.prototype.disable.call(source)\n\n source.on('frame', async ({ frame }) => {\n frame.events.on('*', (event) => {\n /**\n * @note Prevent event forwarding manually and not via an AbortController\n * because certain runtimes, like Cloudflare, throw when referencing an\n * AbortController created in a different context. Bear in mind that the frame\n * events run in the patched request client context while the AbortController\n * is created outside, in the \"defineNetwork\" closure, which is a test context.\n */\n if (!session.active) {\n return\n }\n\n events.emit(event)\n })\n\n const handlers = frame.getHandlers(handlersController)\n\n await frame.resolve(\n handlers,\n resolvedOptions.onUnhandledFrame || 'warn',\n resolvedOptions.context,\n )\n })\n\n return source.enable()\n })\n\n return colorlessPromiseAll(result) as MaybePromise<\n ReturnType\n >\n },\n disable() {\n invariant(\n readyState === NetworkReadyState.ENABLED,\n 'Failed to call \"disable\" on the network: already disabled',\n )\n\n readyState = NetworkReadyState.DISABLED\n disposable.dispose()\n\n return colorlessPromiseAll(\n resolvedOptions.sources.map((source) => source.disable()),\n ) as MaybePromise>\n },\n use(...handlers) {\n handlersController.use(handlers)\n },\n resetHandlers(...handlers) {\n handlersController.reset(handlers)\n },\n restoreHandlers() {\n handlersController.restore()\n },\n listHandlers() {\n return toReadonlyArray(handlersController.currentHandlers())\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,wBAA0B;AAC1B,qBAA8C;AAC9C,4BAGO;AACP,2BAAmD;AACnD,gCAA0C;AAC1C,iCAIO;AACP,6BAAgC;AAChC,wBAA2B;AAiE3B,SAAS,oBAAoB,QAA8C;AACzE,QAAM,WAAiC,CAAC;AAExC,aAAW,SAAS,QAAQ;AAC1B,QAAI,iBAAiB,SAAS;AAC5B,eAAS,KAAK,KAAK;AAAA,IACrB;AAAA,EACF;AAEA,MAAI,SAAS,SAAS,GAAG;AACvB,WAAO,QAAQ,IAAI,QAAQ,EAAE,KAAK,MAAM;AAAA,IAAC,CAAC;AAAA,EAC5C;AACF;AAEO,IAAK,oBAAL,kBAAKA,uBAAL;AACL,EAAAA,sCAAA;AACA,EAAAA,sCAAA;AAFU,SAAAA;AAAA,GAAA;AAiBL,SAAS,cACd,SACqB;AACrB,MAA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AO,OAAO,OAAO;AAAA,MACvB,CAAC;AAED,aAAO,oBAAoB,MAAM;AAAA,IAGnC;AAAA,IACA,UAAU;AACR;AAAA,QACE,eAAe;AAAA,QACf;AAAA,MACF;AAEA,mBAAa;AACb,iBAAW,QAAQ;AAEnB,aAAO;AAAA,QACL,gBAAgB,QAAQ,IAAI,CAAC,WAAW,OAAO,QAAQ,CAAC;AAAA,MAC1D;AAAA,IACF;AAAA,IACA,OAAO,UAAU;AACf,yBAAmB,IAAI,QAAQ;AAAA,IACjC;AAAA,IACA,iBAAiB,UAAU;AACzB,yBAAmB,MAAM,QAAQ;AAAA,IACnC;AAAA,IACA,kBAAkB;AAChB,yBAAmB,QAAQ;AAAA,IAC7B;AAAA,IACA,eAAe;AACb,iBAAO,wCAAgB,mBAAmB,gBAAgB,CAAC;AAAA,IAC7D;AAAA,EACF;AACF;","names":["NetworkReadyState","options"]} \ No newline at end of file diff --git a/node_modules/msw/lib/core/experimental/define-network.mjs b/node_modules/msw/lib/core/experimental/define-network.mjs new file mode 100644 index 0000000000000000000000000000000000000000..df57b392e4f963e493be89af6b66c214912d0cb3 --- /dev/null +++ b/node_modules/msw/lib/core/experimental/define-network.mjs @@ -0,0 +1,119 @@ +import { invariant } from "outvariant"; +import { Emitter } from "rettime"; +import { + NetworkSource +} from './sources/network-source.mjs'; +import {} from './frames/network-frame.mjs'; +import {} from './on-unhandled-frame.mjs'; +import { + HandlersController, + InMemoryHandlersController +} from './handlers-controller.mjs'; +import { toReadonlyArray } from '../utils/internal/toReadonlyArray.mjs'; +import { Disposable } from '../utils/internal/Disposable.mjs'; +function colorlessPromiseAll(values) { + const promises = []; + for (const value of values) { + if (value instanceof Promise) { + promises.push(value); + } + } + if (promises.length > 0) { + return Promise.all(promises).then(() => { + }); + } +} +var NetworkReadyState = /* @__PURE__ */ ((NetworkReadyState2) => { + NetworkReadyState2[NetworkReadyState2["DISABLED"] = 0] = "DISABLED"; + NetworkReadyState2[NetworkReadyState2["ENABLED"] = 1] = "ENABLED"; + return NetworkReadyState2; +})(NetworkReadyState || {}); +function defineNetwork(options) { + let readyState = 0 /* DISABLED */; + const events = new Emitter(); + const disposable = new Disposable(); + const deriveHandlersController = (handlers) => { + return handlers instanceof HandlersController ? handlers : new InMemoryHandlersController(handlers || []); + }; + let resolvedOptions = { + ...options + }; + let handlersController = deriveHandlersController(resolvedOptions.handlers); + return { + get readyState() { + return readyState; + }, + events, + configure(options2) { + invariant( + readyState === 0 /* DISABLED */, + 'Failed to call "configure()" on the network: cannot configure an already enabled network.' + ); + if (options2.handlers && !Object.is(options2.handlers, resolvedOptions.handlers)) { + handlersController = deriveHandlersController(options2.handlers); + } + resolvedOptions = { + ...resolvedOptions, + ...options2 + }; + }, + enable() { + invariant( + readyState === 0 /* DISABLED */, + 'Failed to call "enable" on the network: already enabled' + ); + readyState = 1 /* ENABLED */; + const session = { active: true }; + disposable["subscriptions"].push(() => { + session.active = false; + }); + const result = resolvedOptions.sources.map((source) => { + NetworkSource.prototype.disable.call(source); + source.on("frame", async ({ frame }) => { + frame.events.on("*", (event) => { + if (!session.active) { + return; + } + events.emit(event); + }); + const handlers = frame.getHandlers(handlersController); + await frame.resolve( + handlers, + resolvedOptions.onUnhandledFrame || "warn", + resolvedOptions.context + ); + }); + return source.enable(); + }); + return colorlessPromiseAll(result); + }, + disable() { + invariant( + readyState === 1 /* ENABLED */, + 'Failed to call "disable" on the network: already disabled' + ); + readyState = 0 /* DISABLED */; + disposable.dispose(); + return colorlessPromiseAll( + resolvedOptions.sources.map((source) => source.disable()) + ); + }, + use(...handlers) { + handlersController.use(handlers); + }, + resetHandlers(...handlers) { + handlersController.reset(handlers); + }, + restoreHandlers() { + handlersController.restore(); + }, + listHandlers() { + return toReadonlyArray(handlersController.currentHandlers()); + } + }; +} +export { + NetworkReadyState, + defineNetwork +}; +//# sourceMappingURL=define-network.mjs.map \ No newline at end of file diff --git a/node_modules/msw/lib/core/experimental/define-network.mjs.map b/node_modules/msw/lib/core/experimental/define-network.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..1d4d10e0b4053ef73f7f4752b527ae11e3130abd --- /dev/null +++ b/node_modules/msw/lib/core/experimental/define-network.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/core/experimental/define-network.ts"],"sourcesContent":["import { invariant } from 'outvariant'\nimport { Emitter, type DefaultEventMap } from 'rettime'\nimport {\n NetworkSource,\n type ExtractSourceEvents,\n} from './sources/network-source'\nimport { type NetworkFrameResolutionContext } from './frames/network-frame'\nimport { type UnhandledFrameHandle } from './on-unhandled-frame'\nimport {\n HandlersController,\n InMemoryHandlersController,\n type AnyHandler,\n} from './handlers-controller'\nimport { toReadonlyArray } from '../utils/internal/toReadonlyArray'\nimport { Disposable } from '../utils/internal/Disposable'\n\ntype UnionToIntersection = (U extends any ? (k: U) => void : never) extends (\n k: infer I,\n) => void\n ? I\n : never\n\ntype MergeEventMaps>> =\n UnionToIntersection> extends infer R\n ? R extends Record\n ? R\n : DefaultEventMap\n : DefaultEventMap\n\ntype MaybePromise =\n Extract> extends never ? void : Promise\n\nexport interface DefineNetworkOptions<\n Sources extends Array>,\n> {\n /**\n * List of the network sources.\n * Every network source emits frames, and every frame describes how\n * to handle the various network scenarios, like mocking a response,\n * erroring the request, or performing it as-is.\n */\n sources: Sources\n /**\n * List of handlers to describe the network.\n */\n handlers?: Array | HandlersController\n context?: NetworkFrameResolutionContext\n onUnhandledFrame?: UnhandledFrameHandle\n}\n\nexport interface NetworkApi<\n Sources extends Array>,\n> extends NetworkHandlersApi {\n readyState: NetworkReadyState\n /**\n * Enable the network interception and handling.\n */\n enable: () => MaybePromise>\n /**\n * Disable the network interception and handling.\n */\n disable: () => MaybePromise>\n /**\n * Configure the network instance with additional options.\n * The options provided in the `.configure()` call will override the same\n * options in the `defineNetwork()` call.\n */\n configure: (options: Partial>) => void\n events: Emitter>\n}\n\nexport interface NetworkHandlersApi {\n use: (...handlers: Array) => void\n resetHandlers: (...handlers: Array) => void\n restoreHandlers: () => void\n listHandlers: () => ReadonlyArray\n}\n\nfunction colorlessPromiseAll(values: Array): MaybePromise\nfunction colorlessPromiseAll(values: Array): Promise | void {\n const promises: Array> = []\n\n for (const value of values) {\n if (value instanceof Promise) {\n promises.push(value)\n }\n }\n\n if (promises.length > 0) {\n return Promise.all(promises).then(() => {})\n }\n}\n\nexport enum NetworkReadyState {\n DISABLED,\n ENABLED,\n}\n\n/**\n * Define a network instance with the given configuration.\n * @example\n * import { InterceptorSource } from 'msw/experimental'\n * import { handlers } from './handlers'\n *\n * const network = defineNetwork({\n * sources: [new InterceptorSource({ interceptors })],\n * handlers,\n * })\n * await network.enable()\n */\nexport function defineNetwork>>(\n options: DefineNetworkOptions,\n): NetworkApi {\n let readyState: NetworkReadyState = NetworkReadyState.DISABLED\n const events = new Emitter>()\n const disposable = new Disposable()\n\n const deriveHandlersController = (\n handlers: DefineNetworkOptions['handlers'],\n ) => {\n return handlers instanceof HandlersController\n ? handlers\n : new InMemoryHandlersController(handlers || [])\n }\n\n let resolvedOptions: DefineNetworkOptions = {\n ...options,\n }\n\n /**\n * @note Create the handlers controller immediately because\n * certain setup APIs, like `setupServer`, don't await `.enable` (`.listen`).\n */\n let handlersController = deriveHandlersController(resolvedOptions.handlers)\n\n return {\n get readyState() {\n return readyState\n },\n events,\n configure(options) {\n invariant(\n readyState === NetworkReadyState.DISABLED,\n 'Failed to call \"configure()\" on the network: cannot configure an already enabled network.',\n )\n\n if (\n options.handlers &&\n !Object.is(options.handlers, resolvedOptions.handlers)\n ) {\n handlersController = deriveHandlersController(options.handlers)\n }\n\n resolvedOptions = {\n ...resolvedOptions,\n ...options,\n }\n },\n enable() {\n invariant(\n readyState === NetworkReadyState.DISABLED,\n 'Failed to call \"enable\" on the network: already enabled',\n )\n\n readyState = NetworkReadyState.ENABLED\n\n /**\n * @note Use a session object scoped to the current \"enable()\"\n * to prevent \"frame.events\" listeners from surviving across enable/disable cycles.\n * @see The note about `AbortController` below.\n */\n const session = { active: true }\n disposable['subscriptions'].push(() => {\n session.active = false\n })\n\n const result = resolvedOptions.sources.map((source) => {\n /**\n * @note Preemptively disable the network source before enabling.\n * This intentionally calls only the prototype method that clears the\n * event listeners and nothing else. This prevents the \"frame\" listeners\n * from accumulating across enable/disable in case the source is a singleton.\n */\n NetworkSource.prototype.disable.call(source)\n\n source.on('frame', async ({ frame }) => {\n frame.events.on('*', (event) => {\n /**\n * @note Prevent event forwarding manually and not via an AbortController\n * because certain runtimes, like Cloudflare, throw when referencing an\n * AbortController created in a different context. Bear in mind that the frame\n * events run in the patched request client context while the AbortController\n * is created outside, in the \"defineNetwork\" closure, which is a test context.\n */\n if (!session.active) {\n return\n }\n\n events.emit(event)\n })\n\n const handlers = frame.getHandlers(handlersController)\n\n await frame.resolve(\n handlers,\n resolvedOptions.onUnhandledFrame || 'warn',\n resolvedOptions.context,\n )\n })\n\n return source.enable()\n })\n\n return colorlessPromiseAll(result) as MaybePromise<\n ReturnType\n >\n },\n disable() {\n invariant(\n readyState === NetworkReadyState.ENABLED,\n 'Failed to call \"disable\" on the network: already disabled',\n )\n\n readyState = NetworkReadyState.DISABLED\n disposable.dispose()\n\n return colorlessPromiseAll(\n resolvedOptions.sources.map((source) => source.disable()),\n ) as MaybePromise>\n },\n use(...handlers) {\n handlersController.use(handlers)\n },\n resetHandlers(...handlers) {\n handlersController.reset(handlers)\n },\n restoreHandlers() {\n handlersController.restore()\n },\n listHandlers() {\n return toReadonlyArray(handlersController.currentHandlers())\n },\n }\n}\n"],"mappings":"AAAA,SAAS,iBAAiB;AAC1B,SAAS,eAAqC;AAC9C;AAAA,EACE;AAAA,OAEK;AACP,eAAmD;AACnD,eAA0C;AAC1C;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP,SAAS,uBAAuB;AAChC,SAAS,kBAAkB;AAiE3B,SAAS,oBAAoB,QAA8C;AACzE,QAAM,WAAiC,CAAC;AAExC,aAAW,SAAS,QAAQ;AAC1B,QAAI,iBAAiB,SAAS;AAC5B,eAAS,KA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OAAO,GAAG,KAAK,CAAC,UAAU;AAQ9B,gBAAI,CAAC,QAAQ,QAAQ;AACnB;AAAA,YACF;AAEA,mBAAO,KAAK,KAAK;AAAA,UACnB,CAAC;AAED,gBAAM,WAAW,MAAM,YAAY,kBAAkB;AAErD,gBAAM,MAAM;AAAA,YACV;AAAA,YACA,gBAAgB,oBAAoB;AAAA,YACpC,gBAAgB;AAAA,UAClB;AAAA,QACF,CAAC;AAED,eAAO,OAAO,OAAO;AAAA,MACvB,CAAC;AAED,aAAO,oBAAoB,MAAM;AAAA,IAGnC;AAAA,IACA,UAAU;AACR;AAAA,QACE,eAAe;AAAA,QACf;AAAA,MACF;AAEA,mBAAa;AACb,iBAAW,QAAQ;AAEnB,aAAO;AAAA,QACL,gBAAgB,QAAQ,IAAI,CAAC,WAAW,OAAO,QAAQ,CAAC;AAAA,MAC1D;AAAA,IACF;AAAA,IACA,OAAO,UAAU;AACf,yBAAmB,IAAI,QAAQ;AAAA,IACjC;AAAA,IACA,iBAAiB,UAAU;AACzB,yBAAmB,MAAM,QAAQ;AAAA,IACnC;AAAA,IACA,kBAAkB;AAChB,yBAAmB,QAAQ;AAAA,IAC7B;AAAA,IACA,eAAe;AACb,aAAO,gBAAgB,mBAAmB,gBAAgB,CAAC;AAAA,IAC7D;AAAA,EACF;AACF;","names":["NetworkReadyState","options"]} \ No newline at end of file diff --git a/node_modules/msw/lib/core/experimental/frames/http-frame.d.mts b/node_modules/msw/lib/core/experimental/frames/http-frame.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..92bd5a91ba90e0329922107170aaed64b222db72 --- /dev/null +++ b/node_modules/msw/lib/core/experimental/frames/http-frame.d.mts @@ -0,0 +1,77 @@ +import { TypedEvent } from 'rettime'; +import { N as NetworkFrame, b as UnhandledFrameHandle, a as NetworkFrameResolutionContext } from '../../on-unhandled-frame-Cr1KOZ0I.mjs'; +import { HandlersController, AnyHandler } from '../handlers-controller.mjs'; +import { R as RequestHandler } from '../../HttpResponse-CQwYpuKo.mjs'; +import '../../handlers/WebSocketHandler.mjs'; +import 'strict-event-emitter'; +import '@mswjs/interceptors/WebSocket'; +import '../../utils/matching/matchRequestUrl.mjs'; +import '@mswjs/interceptors'; +import '../../utils/internal/isIterable.mjs'; +import '../../typeUtils.mjs'; +import 'graphql'; + +interface HttpNetworkFrameOptions { + id?: string; + request: Request; +} +declare class RequestEvent extends TypedEvent { + readonly requestId: string; + readonly request: Request; + constructor(type: EventType, data: DataType); +} +declare class ResponseEvent extends TypedEvent { + readonly requestId: string; + readonly request: Request; + readonly response: Response; + constructor(type: EventType, data: DataType); +} +declare class UnhandledExceptionEvent extends TypedEvent { + readonly error: Error; + readonly requestId: string; + readonly request: Request; + constructor(type: EventType, data: DataType); +} +type HttpNetworkFrameEventMap = { + 'request:start': RequestEvent; + 'request:match': RequestEvent; + 'request:unhandled': RequestEvent; + 'request:end': RequestEvent; + 'response:mocked': ResponseEvent; + 'response:bypass': ResponseEvent; + unhandledException: UnhandledExceptionEvent; +}; +declare abstract class HttpNetworkFrame extends NetworkFrame<'http', { + id: string; + request: Request; +}, HttpNetworkFrameEventMap> { + constructor(options: HttpNetworkFrameOptions); + getHandlers(controller: HandlersController): Array; + abstract respondWith(response?: Response): void; + getUnhandledMessage(): Promise; + resolve(handlers: Array, onUnhandledFrame: UnhandledFrameHandle, resolutionContext?: NetworkFrameResolutionContext): Promise; +} + +export { HttpNetworkFrame, type HttpNetworkFrameEventMap, RequestEvent, ResponseEvent, UnhandledExceptionEvent }; diff --git a/node_modules/msw/lib/core/experimental/frames/http-frame.d.ts b/node_modules/msw/lib/core/experimental/frames/http-frame.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6ffc20c026b5723f9ce526913045f555f13bfadc --- /dev/null +++ b/node_modules/msw/lib/core/experimental/frames/http-frame.d.ts @@ -0,0 +1,77 @@ +import { TypedEvent } from 'rettime'; +import { N as NetworkFrame, b as UnhandledFrameHandle, a as NetworkFrameResolutionContext } from '../../on-unhandled-frame-BBR-P3kV.js'; +import { HandlersController, AnyHandler } from '../handlers-controller.js'; +import { R as RequestHandler } from '../../HttpResponse-BFS34nkx.js'; +import '../../handlers/WebSocketHandler.js'; +import 'strict-event-emitter'; +import '@mswjs/interceptors/WebSocket'; +import '../../utils/matching/matchRequestUrl.js'; +import '@mswjs/interceptors'; +import '../../utils/internal/isIterable.js'; +import '../../typeUtils.js'; +import 'graphql'; + +interface HttpNetworkFrameOptions { + id?: string; + request: Request; +} +declare class RequestEvent extends TypedEvent { + readonly requestId: string; + readonly request: Request; + constructor(type: EventType, data: DataType); +} +declare class ResponseEvent extends TypedEvent { + readonly requestId: string; + readonly request: Request; + readonly response: Response; + constructor(type: EventType, data: DataType); +} +declare class UnhandledExceptionEvent extends TypedEvent { + readonly error: Error; + readonly requestId: string; + readonly request: Request; + constructor(type: EventType, data: DataType); +} +type HttpNetworkFrameEventMap = { + 'request:start': RequestEvent; + 'request:match': RequestEvent; + 'request:unhandled': RequestEvent; + 'request:end': RequestEvent; + 'response:mocked': ResponseEvent; + 'response:bypass': ResponseEvent; + unhandledException: UnhandledExceptionEvent; +}; +declare abstract class HttpNetworkFrame extends NetworkFrame<'http', { + id: string; + request: Request; +}, HttpNetworkFrameEventMap> { + constructor(options: HttpNetworkFrameOptions); + getHandlers(controller: HandlersController): Array; + abstract respondWith(response?: Response): void; + getUnhandledMessage(): Promise; + resolve(handlers: Array, onUnhandledFrame: UnhandledFrameHandle, resolutionContext?: NetworkFrameResolutionContext): Promise; +} + +export { HttpNetworkFrame, type HttpNetworkFrameEventMap, RequestEvent, ResponseEvent, UnhandledExceptionEvent }; diff --git a/node_modules/msw/lib/core/experimental/frames/http-frame.js b/node_modules/msw/lib/core/experimental/frames/http-frame.js new file mode 100644 index 0000000000000000000000000000000000000000..8ea2a86b59b7f7d705053241533c8159ca40b630 --- /dev/null +++ b/node_modules/msw/lib/core/experimental/frames/http-frame.js @@ -0,0 +1,197 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var http_frame_exports = {}; +__export(http_frame_exports, { + HttpNetworkFrame: () => HttpNetworkFrame, + RequestEvent: () => RequestEvent, + ResponseEvent: () => ResponseEvent, + UnhandledExceptionEvent: () => UnhandledExceptionEvent +}); +module.exports = __toCommonJS(http_frame_exports); +var import_rettime = require("rettime"); +var import_until_async = require("until-async"); +var import_interceptors = require("@mswjs/interceptors"); +var import_network_frame = require("./network-frame"); +var import_toPublicUrl = require("../../utils/request/toPublicUrl"); +var import_executeHandlers = require("../../utils/executeHandlers"); +var import_storeResponseCookies = require("../../utils/request/storeResponseCookies"); +var import_request_utils = require("../request-utils"); +var import_devUtils = require("../../utils/internal/devUtils"); +var import_on_unhandled_frame = require("../on-unhandled-frame"); +var import_handlers_controller = require("../handlers-controller"); +var import_RequestHandler = require("../../handlers/RequestHandler"); +class RequestEvent extends import_rettime.TypedEvent { + requestId; + request; + constructor(type, data) { + super(...[type, {}]); + this.requestId = data.requestId; + this.request = data.request; + } +} +class ResponseEvent extends import_rettime.TypedEvent { + requestId; + request; + response; + constructor(type, data) { + super(...[type, {}]); + this.requestId = data.requestId; + this.request = data.request; + this.response = data.response; + } +} +class UnhandledExceptionEvent extends import_rettime.TypedEvent { + error; + requestId; + request; + constructor(type, data) { + super(...[type, {}]); + this.error = data.error; + this.requestId = data.requestId; + this.request = data.request; + } +} +class HttpNetworkFrame extends import_network_frame.NetworkFrame { + constructor(options) { + const id = options.id || (0, import_interceptors.createRequestId)(); + super("http", { id, request: options.request }); + } + getHandlers(controller) { + return controller.getHandlersByKind("request"); + } + async getUnhandledMessage() { + const { request } = this.data; + const url = new URL(request.url); + const publicUrl = (0, import_toPublicUrl.toPublicUrl)(url) + url.search; + const requestBody = request.body == null ? null : await request.clone().text(); + const details = ` + + \u2022 ${request.method} ${publicUrl} + +${requestBody ? ` \u2022 Request body: ${requestBody} + +` : ""}`; + const message = `intercepted a request without a matching request handler:${details}If you still wish to intercept this unhandled request, please create a request handler for it. +Read more: https://mswjs.io/docs/http/intercepting-requests`; + return message; + } + async resolve(handlers, onUnhandledFrame, resolutionContext) { + const { id: requestId, request } = this.data; + const requestCloneForLogs = resolutionContext?.quiet ? null : request.clone(); + this.events.emit(new RequestEvent("request:start", { requestId, request })); + if ((0, import_request_utils.shouldBypassRequest)(request)) { + this.events.emit(new RequestEvent("request:end", { requestId, request })); + this.passthrough(); + return null; + } + const [lookupError, lookupResult] = await (0, import_until_async.until)(() => { + return (0, import_executeHandlers.executeHandlers)({ + requestId, + request, + handlers, + resolutionContext: { + baseUrl: resolutionContext?.baseUrl?.toString(), + quiet: resolutionContext?.quiet + } + }); + }); + if (lookupError != null) { + if (!this.events.emit( + new UnhandledExceptionEvent("unhandledException", { + error: lookupError, + requestId, + request + }) + )) { + console.error(lookupError); + import_devUtils.devUtils.error( + 'Encountered an unhandled exception during the handler lookup for "%s %s". Please see the original error above.', + request.method, + request.url + ); + } + this.errorWith(lookupError); + return null; + } + if (lookupResult == null) { + this.events.emit( + new RequestEvent("request:unhandled", { + requestId, + request + }) + ); + await (0, import_on_unhandled_frame.executeUnhandledFrameHandle)(this, onUnhandledFrame).then( + () => this.passthrough(), + (error) => this.errorWith(error) + ); + this.events.emit( + new RequestEvent("request:end", { + requestId, + request + }) + ); + return false; + } + const { response, handler, parsedResult } = lookupResult; + this.events.emit( + new RequestEvent("request:match", { + requestId, + request + }) + ); + if (response == null) { + this.events.emit( + new RequestEvent("request:end", { + requestId, + request + }) + ); + this.passthrough(); + return null; + } + if ((0, import_request_utils.isPassthroughResponse)(response)) { + this.events.emit( + new RequestEvent("request:end", { + requestId, + request + }) + ); + this.passthrough(); + return null; + } + const responseCloneForLogs = resolutionContext?.quiet ? null : response.clone(); + await (0, import_storeResponseCookies.storeResponseCookies)(request, response); + this.respondWith(response); + this.events.emit( + new RequestEvent("request:end", { + requestId, + request + }) + ); + if (!resolutionContext?.quiet) { + handler.log({ + request: requestCloneForLogs, + response: responseCloneForLogs, + parsedResult + }); + } + return true; + } +} +//# sourceMappingURL=http-frame.js.map \ No newline at end of file diff --git a/node_modules/msw/lib/core/experimental/frames/http-frame.js.map b/node_modules/msw/lib/core/experimental/frames/http-frame.js.map new file mode 100644 index 0000000000000000000000000000000000000000..2df77c33cf16c096eaef822974460b8fe595cb5c --- /dev/null +++ b/node_modules/msw/lib/core/experimental/frames/http-frame.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/core/experimental/frames/http-frame.ts"],"sourcesContent":["import { TypedEvent } from 'rettime'\nimport { until } from 'until-async'\nimport { createRequestId } from '@mswjs/interceptors'\nimport {\n NetworkFrame,\n type NetworkFrameResolutionContext,\n} from './network-frame'\nimport { toPublicUrl } from '../../utils/request/toPublicUrl'\nimport { executeHandlers } from '../../utils/executeHandlers'\nimport { storeResponseCookies } from '../../utils/request/storeResponseCookies'\nimport { isPassthroughResponse, shouldBypassRequest } from '../request-utils'\nimport { devUtils } from '../../utils/internal/devUtils'\nimport {\n executeUnhandledFrameHandle,\n type UnhandledFrameHandle,\n} from '../on-unhandled-frame'\nimport type { HandlersController } from '../handlers-controller'\nimport { type AnyHandler } from '../handlers-controller'\nimport { type RequestHandler } from '../../handlers/RequestHandler'\n\ninterface HttpNetworkFrameOptions {\n id?: string\n request: Request\n}\n\nexport class RequestEvent<\n DataType extends { requestId: string; request: Request } = {\n requestId: string\n request: Request\n },\n ReturnType = void,\n EventType extends string = string,\n> extends TypedEvent {\n public readonly requestId: string\n public readonly request: Request\n\n constructor(type: EventType, data: DataType) {\n super(...([type, {}] as any))\n this.requestId = data.requestId\n this.request = data.request\n }\n}\n\nexport class ResponseEvent<\n DataType extends {\n requestId: string\n request: Request\n response: Response\n } = {\n requestId: string\n request: Request\n response: Response\n },\n ReturnType = void,\n EventType extends string = string,\n> extends TypedEvent {\n public readonly requestId: string\n public readonly request: Request\n public readonly response: Response\n\n constructor(type: EventType, data: DataType) {\n super(...([type, {}] as any))\n this.requestId = data.requestId\n this.request = data.request\n this.response = data.response\n }\n}\n\nexport class UnhandledExceptionEvent<\n DataType extends {\n error: Error\n requestId: string\n request: Request\n } = {\n error: Error\n requestId: string\n request: Request\n },\n ReturnType = void,\n EventType extends string = string,\n> extends TypedEvent {\n public readonly error: Error\n public readonly requestId: string\n public readonly request: Request\n\n constructor(type: EventType, data: DataType) {\n super(...([type, {}] as any))\n this.error = data.error\n this.requestId = data.requestId\n this.request = data.request\n }\n}\n\nexport type HttpNetworkFrameEventMap = {\n 'request:start': RequestEvent\n 'request:match': RequestEvent\n 'request:unhandled': RequestEvent\n 'request:end': RequestEvent\n 'response:mocked': ResponseEvent\n 'response:bypass': ResponseEvent\n unhandledException: UnhandledExceptionEvent\n}\n\nexport abstract class HttpNetworkFrame extends NetworkFrame<\n 'http',\n {\n id: string\n request: Request\n },\n HttpNetworkFrameEventMap\n> {\n constructor(options: HttpNetworkFrameOptions) {\n const id = options.id || createRequestId()\n super('http', { id, request: options.request })\n }\n\n public getHandlers(controller: HandlersController): Array {\n return controller.getHandlersByKind('request')\n }\n\n public abstract respondWith(response?: Response): void\n\n public async getUnhandledMessage(): Promise {\n const { request } = this.data\n\n const url = new URL(request.url)\n const publicUrl = toPublicUrl(url) + url.search\n const requestBody =\n request.body == null ? null : await request.clone().text()\n\n const details = `\\n\\n \\u2022 ${request.method} ${publicUrl}\\n\\n${requestBody ? ` \\u2022 Request body: ${requestBody}\\n\\n` : ''}`\n const message = `intercepted a request without a matching request handler:${details}If you still wish to intercept this unhandled request, please create a request handler for it.\\nRead more: https://mswjs.io/docs/http/intercepting-requests`\n\n return message\n }\n\n public async resolve(\n handlers: Array,\n onUnhandledFrame: UnhandledFrameHandle,\n resolutionContext?: NetworkFrameResolutionContext,\n ): Promise {\n const { id: requestId, request } = this.data\n const requestCloneForLogs = resolutionContext?.quiet\n ? null\n : request.clone()\n\n this.events.emit(new RequestEvent('request:start', { requestId, request }))\n\n // Requests wrapped in explicit \"bypass(request)\".\n if (shouldBypassRequest(request)) {\n this.events.emit(new RequestEvent('request:end', { requestId, request }))\n this.passthrough()\n return null\n }\n\n const [lookupError, lookupResult] = await until(() => {\n return executeHandlers({\n requestId,\n request,\n handlers,\n resolutionContext: {\n baseUrl: resolutionContext?.baseUrl?.toString(),\n quiet: resolutionContext?.quiet,\n },\n })\n })\n\n if (lookupError != null) {\n if (\n !this.events.emit(\n new UnhandledExceptionEvent('unhandledException', {\n error: lookupError,\n requestId,\n request,\n }),\n )\n ) {\n // Surface the error to the developer since they haven't handled it.\n console.error(lookupError)\n devUtils.error(\n 'Encountered an unhandled exception during the handler lookup for \"%s %s\". Please see the original error above.',\n request.method,\n request.url,\n )\n }\n\n this.errorWith(lookupError)\n return null\n }\n\n // No matching handlers.\n if (lookupResult == null) {\n this.events.emit(\n new RequestEvent('request:unhandled', {\n requestId,\n request,\n }),\n )\n\n /**\n * @note The unhandled frame handle must be executed during the request resolution\n * since it can influence it (e.g. error the request if the \"error\" startegy was used).\n */\n await executeUnhandledFrameHandle(this, onUnhandledFrame).then(\n () => this.passthrough(),\n (error) => this.errorWith(error),\n )\n\n this.events.emit(\n new RequestEvent('request:end', {\n requestId,\n request,\n }),\n )\n\n return false\n }\n\n const { response, handler, parsedResult } = lookupResult\n\n this.events.emit(\n new RequestEvent('request:match', {\n requestId,\n request,\n }),\n )\n\n // Handlers that returned no mocked response.\n if (response == null) {\n this.events.emit(\n new RequestEvent('request:end', {\n requestId,\n request,\n }),\n )\n\n this.passthrough()\n return null\n }\n\n // Handlers that returned explicit `passthrough()`.\n if (isPassthroughResponse(response)) {\n this.events.emit(\n new RequestEvent('request:end', {\n requestId,\n request,\n }),\n )\n\n this.passthrough()\n return null\n }\n\n const responseCloneForLogs = resolutionContext?.quiet\n ? null\n : response.clone()\n\n await storeResponseCookies(request, response)\n\n this.respondWith(response)\n\n this.events.emit(\n new RequestEvent('request:end', {\n requestId,\n request,\n }),\n )\n\n if (!resolutionContext?.quiet) {\n handler.log({\n request: requestCloneForLogs!,\n response: responseCloneForLogs!,\n parsedResult,\n })\n }\n\n return true\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,qBAA2B;AAC3B,yBAAsB;AACtB,0BAAgC;AAChC,2BAGO;AACP,yBAA4B;AAC5B,6BAAgC;AAChC,kCAAqC;AACrC,2BAA2D;AAC3D,sBAAyB;AACzB,gCAGO;AAEP,iCAAgC;AAChC,4BAAoC;AAO7B,MAAM,qBAOH,0BAA4C;AAAA,EACpC;AAAA,EACA;AAAA,EAEhB,YAAY,MAAiB,MAAgB;AAC3C,UAAM,GAAI,CAAC,MAAM,CAAC,CAAC,CAAS;AAC5B,SAAK,YAAY,KAAK;AACtB,SAAK,UAAU,KAAK;AAAA,EACtB;AACF;AAEO,MAAM,sBAYH,0BAA4C;AAAA,EACpC;AAAA,EACA;AAAA,EACA;AAAA,EAEhB,YAAY,MAAiB,MAAgB;AAC3C,UAAM,GAAI,CAAC,MAAM,CAAC,CAAC,CAAS;AAC5B,SAAK,YAAY,KAAK;AACtB,SAAK,UAAU,KAAK;AACpB,SAAK,WAAW,KAAK;AAAA,EACvB;AACF;AAEO,MAAM,gCAYH,0BAA4C;AAAA,EACpC;AAAA,EACA;AAAA,EACA;AAAA,EAEhB,YAAY,MAAiB,MAAgB;AAC3C,UAAM,GAAI,CAAC,MAAM,CAAC,CAAC,CAAS;AAC5B,SAAK,QAAQ,KAAK;AAClB,S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AY;AACjB,aAAO;AAAA,IACT;AAEA,UAAM,uBAAuB,mBAAmB,QAC5C,OACA,SAAS,MAAM;AAEnB,cAAM,kDAAqB,SAAS,QAAQ;AAE5C,SAAK,YAAY,QAAQ;AAEzB,SAAK,OAAO;AAAA,MACV,IAAI,aAAa,eAAe;AAAA,QAC9B;AAAA,QACA;AAAA,MACF,CAAC;AAAA,IACH;AAEA,QAAI,CAAC,mBAAmB,OAAO;AAC7B,cAAQ,IAAI;AAAA,QACV,SAAS;AAAA,QACT,UAAU;AAAA,QACV;AAAA,MACF,CAAC;AAAA,IACH;AAEA,WAAO;AAAA,EACT;AACF;","names":[]} \ No newline at end of file diff --git a/node_modules/msw/lib/core/experimental/frames/http-frame.mjs b/node_modules/msw/lib/core/experimental/frames/http-frame.mjs new file mode 100644 index 0000000000000000000000000000000000000000..157076cec0ac897c4c0f2861ded0a26e421aad37 --- /dev/null +++ b/node_modules/msw/lib/core/experimental/frames/http-frame.mjs @@ -0,0 +1,181 @@ +import { TypedEvent } from "rettime"; +import { until } from "until-async"; +import { createRequestId } from "@mswjs/interceptors"; +import { + NetworkFrame +} from './network-frame.mjs'; +import { toPublicUrl } from '../../utils/request/toPublicUrl.mjs'; +import { executeHandlers } from '../../utils/executeHandlers.mjs'; +import { storeResponseCookies } from '../../utils/request/storeResponseCookies.mjs'; +import { isPassthroughResponse, shouldBypassRequest } from '../request-utils.mjs'; +import { devUtils } from '../../utils/internal/devUtils.mjs'; +import { + executeUnhandledFrameHandle +} from '../on-unhandled-frame.mjs'; +import {} from '../handlers-controller.mjs'; +import {} from '../../handlers/RequestHandler.mjs'; +class RequestEvent extends TypedEvent { + requestId; + request; + constructor(type, data) { + super(...[type, {}]); + this.requestId = data.requestId; + this.request = data.request; + } +} +class ResponseEvent extends TypedEvent { + requestId; + request; + response; + constructor(type, data) { + super(...[type, {}]); + this.requestId = data.requestId; + this.request = data.request; + this.response = data.response; + } +} +class UnhandledExceptionEvent extends TypedEvent { + error; + requestId; + request; + constructor(type, data) { + super(...[type, {}]); + this.error = data.error; + this.requestId = data.requestId; + this.request = data.request; + } +} +class HttpNetworkFrame extends NetworkFrame { + constructor(options) { + const id = options.id || createRequestId(); + super("http", { id, request: options.request }); + } + getHandlers(controller) { + return controller.getHandlersByKind("request"); + } + async getUnhandledMessage() { + const { request } = this.data; + const url = new URL(request.url); + const publicUrl = toPublicUrl(url) + url.search; + const requestBody = request.body == null ? null : await request.clone().text(); + const details = ` + + \u2022 ${request.method} ${publicUrl} + +${requestBody ? ` \u2022 Request body: ${requestBody} + +` : ""}`; + const message = `intercepted a request without a matching request handler:${details}If you still wish to intercept this unhandled request, please create a request handler for it. +Read more: https://mswjs.io/docs/http/intercepting-requests`; + return message; + } + async resolve(handlers, onUnhandledFrame, resolutionContext) { + const { id: requestId, request } = this.data; + const requestCloneForLogs = resolutionContext?.quiet ? null : request.clone(); + this.events.emit(new RequestEvent("request:start", { requestId, request })); + if (shouldBypassRequest(request)) { + this.events.emit(new RequestEvent("request:end", { requestId, request })); + this.passthrough(); + return null; + } + const [lookupError, lookupResult] = await until(() => { + return executeHandlers({ + requestId, + request, + handlers, + resolutionContext: { + baseUrl: resolutionContext?.baseUrl?.toString(), + quiet: resolutionContext?.quiet + } + }); + }); + if (lookupError != null) { + if (!this.events.emit( + new UnhandledExceptionEvent("unhandledException", { + error: lookupError, + requestId, + request + }) + )) { + console.error(lookupError); + devUtils.error( + 'Encountered an unhandled exception during the handler lookup for "%s %s". Please see the original error above.', + request.method, + request.url + ); + } + this.errorWith(lookupError); + return null; + } + if (lookupResult == null) { + this.events.emit( + new RequestEvent("request:unhandled", { + requestId, + request + }) + ); + await executeUnhandledFrameHandle(this, onUnhandledFrame).then( + () => this.passthrough(), + (error) => this.errorWith(error) + ); + this.events.emit( + new RequestEvent("request:end", { + requestId, + request + }) + ); + return false; + } + const { response, handler, parsedResult } = lookupResult; + this.events.emit( + new RequestEvent("request:match", { + requestId, + request + }) + ); + if (response == null) { + this.events.emit( + new RequestEvent("request:end", { + requestId, + request + }) + ); + this.passthrough(); + return null; + } + if (isPassthroughResponse(response)) { + this.events.emit( + new RequestEvent("request:end", { + requestId, + request + }) + ); + this.passthrough(); + return null; + } + const responseCloneForLogs = resolutionContext?.quiet ? null : response.clone(); + await storeResponseCookies(request, response); + this.respondWith(response); + this.events.emit( + new RequestEvent("request:end", { + requestId, + request + }) + ); + if (!resolutionContext?.quiet) { + handler.log({ + request: requestCloneForLogs, + response: responseCloneForLogs, + parsedResult + }); + } + return true; + } +} +export { + HttpNetworkFrame, + RequestEvent, + ResponseEvent, + UnhandledExceptionEvent +}; +//# sourceMappingURL=http-frame.mjs.map \ No newline at end of file diff --git a/node_modules/msw/lib/core/experimental/frames/http-frame.mjs.map b/node_modules/msw/lib/core/experimental/frames/http-frame.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..145811576b10dc1646042b2960187e1fb3538884 --- /dev/null +++ b/node_modules/msw/lib/core/experimental/frames/http-frame.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/core/experimental/frames/http-frame.ts"],"sourcesContent":["import { TypedEvent } from 'rettime'\nimport { until } from 'until-async'\nimport { createRequestId } from '@mswjs/interceptors'\nimport {\n NetworkFrame,\n type NetworkFrameResolutionContext,\n} from './network-frame'\nimport { toPublicUrl } from '../../utils/request/toPublicUrl'\nimport { executeHandlers } from '../../utils/executeHandlers'\nimport { storeResponseCookies } from '../../utils/request/storeResponseCookies'\nimport { isPassthroughResponse, shouldBypassRequest } from '../request-utils'\nimport { devUtils } from '../../utils/internal/devUtils'\nimport {\n executeUnhandledFrameHandle,\n type UnhandledFrameHandle,\n} from '../on-unhandled-frame'\nimport type { HandlersController } from '../handlers-controller'\nimport { type AnyHandler } from '../handlers-controller'\nimport { type RequestHandler } from '../../handlers/RequestHandler'\n\ninterface HttpNetworkFrameOptions {\n id?: string\n request: Request\n}\n\nexport class RequestEvent<\n DataType extends { requestId: string; request: Request } = {\n requestId: string\n request: Request\n },\n ReturnType = void,\n EventType extends string = string,\n> extends TypedEvent {\n public readonly requestId: string\n public readonly request: Request\n\n constructor(type: EventType, data: DataType) {\n super(...([type, {}] as any))\n this.requestId = data.requestId\n this.request = data.request\n }\n}\n\nexport class ResponseEvent<\n DataType extends {\n requestId: string\n request: Request\n response: Response\n } = {\n requestId: string\n request: Request\n response: Response\n },\n ReturnType = void,\n EventType extends string = string,\n> extends TypedEvent {\n public readonly requestId: string\n public readonly request: Request\n public readonly response: Response\n\n constructor(type: EventType, data: DataType) {\n super(...([type, {}] as any))\n this.requestId = data.requestId\n this.request = data.request\n this.response = data.response\n }\n}\n\nexport class UnhandledExceptionEvent<\n DataType extends {\n error: Error\n requestId: string\n request: Request\n } = {\n error: Error\n requestId: string\n request: Request\n },\n ReturnType = void,\n EventType extends string = string,\n> extends TypedEvent {\n public readonly error: Error\n public readonly requestId: string\n public readonly request: Request\n\n constructor(type: EventType, data: DataType) {\n super(...([type, {}] as any))\n this.error = data.error\n this.requestId = data.requestId\n this.request = data.request\n }\n}\n\nexport type HttpNetworkFrameEventMap = {\n 'request:start': RequestEvent\n 'request:match': RequestEvent\n 'request:unhandled': RequestEvent\n 'request:end': RequestEvent\n 'response:mocked': ResponseEvent\n 'response:bypass': ResponseEvent\n unhandledException: UnhandledExceptionEvent\n}\n\nexport abstract class HttpNetworkFrame extends NetworkFrame<\n 'http',\n {\n id: string\n request: Request\n },\n HttpNetworkFrameEventMap\n> {\n constructor(options: HttpNetworkFrameOptions) {\n const id = options.id || createRequestId()\n super('http', { id, request: options.request })\n }\n\n public getHandlers(controller: HandlersController): Array {\n return controller.getHandlersByKind('request')\n }\n\n public abstract respondWith(response?: Response): void\n\n public async getUnhandledMessage(): Promise {\n const { request } = this.data\n\n const url = new URL(request.url)\n const publicUrl = toPublicUrl(url) + url.search\n const requestBody =\n request.body == null ? null : await request.clone().text()\n\n const details = `\\n\\n \\u2022 ${request.method} ${publicUrl}\\n\\n${requestBody ? ` \\u2022 Request body: ${requestBody}\\n\\n` : ''}`\n const message = `intercepted a request without a matching request handler:${details}If you still wish to intercept this unhandled request, please create a request handler for it.\\nRead more: https://mswjs.io/docs/http/intercepting-requests`\n\n return message\n }\n\n public async resolve(\n handlers: Array,\n onUnhandledFrame: UnhandledFrameHandle,\n resolutionContext?: NetworkFrameResolutionContext,\n ): Promise {\n const { id: requestId, request } = this.data\n const requestCloneForLogs = resolutionContext?.quiet\n ? null\n : request.clone()\n\n this.events.emit(new RequestEvent('request:start', { requestId, request }))\n\n // Requests wrapped in explicit \"bypass(request)\".\n if (shouldBypassRequest(request)) {\n this.events.emit(new RequestEvent('request:end', { requestId, request }))\n this.passthrough()\n return null\n }\n\n const [lookupError, lookupResult] = await until(() => {\n return executeHandlers({\n requestId,\n request,\n handlers,\n resolutionContext: {\n baseUrl: resolutionContext?.baseUrl?.toString(),\n quiet: resolutionContext?.quiet,\n },\n })\n })\n\n if (lookupError != null) {\n if (\n !this.events.emit(\n new UnhandledExceptionEvent('unhandledException', {\n error: lookupError,\n requestId,\n request,\n }),\n )\n ) {\n // Surface the error to the developer since they haven't handled it.\n console.error(lookupError)\n devUtils.error(\n 'Encountered an unhandled exception during the handler lookup for \"%s %s\". Please see the original error above.',\n request.method,\n request.url,\n )\n }\n\n this.errorWith(lookupError)\n return null\n }\n\n // No matching handlers.\n if (lookupResult == null) {\n this.events.emit(\n new RequestEvent('request:unhandled', {\n requestId,\n request,\n }),\n )\n\n /**\n * @note The unhandled frame handle must be executed during the request resolution\n * since it can influence it (e.g. error the request if the \"error\" startegy was used).\n */\n await executeUnhandledFrameHandle(this, onUnhandledFrame).then(\n () => this.passthrough(),\n (error) => this.errorWith(error),\n )\n\n this.events.emit(\n new RequestEvent('request:end', {\n requestId,\n request,\n }),\n )\n\n return false\n }\n\n const { response, handler, parsedResult } = lookupResult\n\n this.events.emit(\n new RequestEvent('request:match', {\n requestId,\n request,\n }),\n )\n\n // Handlers that returned no mocked response.\n if (response == null) {\n this.events.emit(\n new RequestEvent('request:end', {\n requestId,\n request,\n }),\n )\n\n this.passthrough()\n return null\n }\n\n // Handlers that returned explicit `passthrough()`.\n if (isPassthroughResponse(response)) {\n this.events.emit(\n new RequestEvent('request:end', {\n requestId,\n request,\n }),\n )\n\n this.passthrough()\n return null\n }\n\n const responseCloneForLogs = resolutionContext?.quiet\n ? null\n : response.clone()\n\n await storeResponseCookies(request, response)\n\n this.respondWith(response)\n\n this.events.emit(\n new RequestEvent('request:end', {\n requestId,\n request,\n }),\n )\n\n if (!resolutionContext?.quiet) {\n handler.log({\n request: requestCloneForLogs!,\n response: responseCloneForLogs!,\n parsedResult,\n })\n }\n\n return true\n }\n}\n"],"mappings":"AAAA,SAAS,kBAAkB;AAC3B,SAAS,aAAa;AACtB,SAAS,uBAAuB;AAChC;AAAA,EACE;AAAA,OAEK;AACP,SAAS,mBAAmB;AAC5B,SAAS,uBAAuB;AAChC,SAAS,4BAA4B;AACrC,SAAS,uBAAuB,2BAA2B;AAC3D,SAAS,gBAAgB;AACzB;AAAA,EACE;AAAA,OAEK;AAEP,eAAgC;AAChC,eAAoC;AAO7B,MAAM,qBAOH,WAA4C;AAAA,EACpC;AAAA,EACA;AAAA,EAEhB,YAAY,MAAiB,MAAgB;AAC3C,UAAM,GAAI,CAAC,MAAM,CAAC,CAAC,CAAS;AAC5B,SAAK,YAAY,KAAK;AACtB,SAAK,UAAU,KAAK;AAAA,EACtB;AACF;AAEO,MAAM,sBAYH,WAA4C;AAAA,EACpC;AAAA,EACA;AAAA,EACA;AAAA,EAEhB,YAAY,MAAiB,MAAgB;AAC3C,UAAM,GAAI,CAAC,MAAM,CAAC,CAAC,CAAS;AAC5B,SAAK,YAAY,KAAK;AACtB,SAAK,UAAU,KAAK;AACpB,SAAK,WAAW,KAAK;AAAA,EACvB;AACF;AAEO,MAAM,gCAYH,WAA4C;AAAA,EACpC;AAAA,EACA;AAAA,EACA;AAAA,EAEhB,YAAY,MAAiB,MAAgB;AAC3C,UAAM,GAAI,CAAC,MAAM,CAAC,CAAC,CAAS;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;AAAA,MACH;AAEA,WAAK,YAAY;AACjB,aAAO;AAAA,IACT;AAEA,UAAM,uBAAuB,mBAAmB,QAC5C,OACA,SAAS,MAAM;AAEnB,UAAM,qBAAqB,SAAS,QAAQ;AAE5C,SAAK,YAAY,QAAQ;AAEzB,SAAK,OAAO;AAAA,MACV,IAAI,aAAa,eAAe;AAAA,QAC9B;AAAA,QACA;AAAA,MACF,CAAC;AAAA,IACH;AAEA,QAAI,CAAC,mBAAmB,OAAO;AAC7B,cAAQ,IAAI;AAAA,QACV,SAAS;AAAA,QACT,UAAU;AAAA,QACV;AAAA,MACF,CAAC;AAAA,IACH;AAEA,WAAO;AAAA,EACT;AACF;","names":[]} \ No newline at end of file diff --git a/node_modules/msw/lib/core/experimental/frames/network-frame.d.mts b/node_modules/msw/lib/core/experimental/frames/network-frame.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..a81874383d171f72b5b43bd1f07539e1182140c4 --- /dev/null +++ b/node_modules/msw/lib/core/experimental/frames/network-frame.d.mts @@ -0,0 +1,12 @@ +import 'rettime'; +import '../handlers-controller.mjs'; +export { A as AnyNetworkFrame, E as ExtractFrameEvents, N as NetworkFrame, a as NetworkFrameResolutionContext } from '../../on-unhandled-frame-Cr1KOZ0I.mjs'; +import '../../HttpResponse-CQwYpuKo.mjs'; +import '@mswjs/interceptors'; +import '../../utils/internal/isIterable.mjs'; +import '../../typeUtils.mjs'; +import 'graphql'; +import '../../utils/matching/matchRequestUrl.mjs'; +import '../../handlers/WebSocketHandler.mjs'; +import 'strict-event-emitter'; +import '@mswjs/interceptors/WebSocket'; diff --git a/node_modules/msw/lib/core/experimental/frames/network-frame.d.ts b/node_modules/msw/lib/core/experimental/frames/network-frame.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6ce48c124ad621f7cb0606fe23e120e1a6e7bfcd --- /dev/null +++ b/node_modules/msw/lib/core/experimental/frames/network-frame.d.ts @@ -0,0 +1,12 @@ +import 'rettime'; +import '../handlers-controller.js'; +export { A as AnyNetworkFrame, E as ExtractFrameEvents, N as NetworkFrame, a as NetworkFrameResolutionContext } from '../../on-unhandled-frame-BBR-P3kV.js'; +import '../../HttpResponse-BFS34nkx.js'; +import '@mswjs/interceptors'; +import '../../utils/internal/isIterable.js'; +import '../../typeUtils.js'; +import 'graphql'; +import '../../utils/matching/matchRequestUrl.js'; +import '../../handlers/WebSocketHandler.js'; +import 'strict-event-emitter'; +import '@mswjs/interceptors/WebSocket'; diff --git a/node_modules/msw/lib/core/experimental/frames/network-frame.js b/node_modules/msw/lib/core/experimental/frames/network-frame.js new file mode 100644 index 0000000000000000000000000000000000000000..cfe32afe9f4802e273fcac0bc2eff13c145765dd --- /dev/null +++ b/node_modules/msw/lib/core/experimental/frames/network-frame.js @@ -0,0 +1,33 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var network_frame_exports = {}; +__export(network_frame_exports, { + NetworkFrame: () => NetworkFrame +}); +module.exports = __toCommonJS(network_frame_exports); +var import_rettime = require("rettime"); +class NetworkFrame { + constructor(protocol, data) { + this.protocol = protocol; + this.data = data; + this.events = new import_rettime.Emitter(); + } + events; +} +//# sourceMappingURL=network-frame.js.map \ No newline at end of file diff --git a/node_modules/msw/lib/core/experimental/frames/network-frame.js.map b/node_modules/msw/lib/core/experimental/frames/network-frame.js.map new file mode 100644 index 0000000000000000000000000000000000000000..28bf5b5a5495b9fc0a36d57ad9aa3a2b0c2430b4 --- /dev/null +++ b/node_modules/msw/lib/core/experimental/frames/network-frame.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/core/experimental/frames/network-frame.ts"],"sourcesContent":["import { Emitter, type DefaultEventMap } from 'rettime'\nimport type { AnyHandler, HandlersController } from '../handlers-controller'\nimport type { UnhandledFrameHandle } from '../on-unhandled-frame'\n\nexport type AnyNetworkFrame = NetworkFrame\n\nexport type ExtractFrameEvents =\n Frame extends NetworkFrame ? Events : never\n\nexport interface NetworkFrameResolutionContext {\n baseUrl?: string | URL\n quiet?: boolean\n}\n\n/**\n * The base for the network frames. Extend this abstract class\n * to implement custom network frames.\n */\nexport abstract class NetworkFrame<\n Protocol extends string,\n Data,\n Events extends DefaultEventMap,\n> {\n public events: Emitter\n\n constructor(\n public readonly protocol: Protocol,\n public readonly data: Data,\n ) {\n this.events = new Emitter()\n }\n\n public abstract getHandlers(controller: HandlersController): Array\n\n /**\n * Resolve the current frame against the given list of handlers.\n * Optionally, use a custom resolution context to control behaviors\n * like `baseUrl`.\n *\n * Returns `true` if the frame was handled, `false` if it wasn't, and `null`\n * if its handling was skipped (e.g. the frame was bypassed).\n */\n public abstract resolve(\n handlers: Array,\n onUnhandledFrame: UnhandledFrameHandle,\n resolutionContext?: NetworkFrameResolutionContext,\n ): Promise\n\n /**\n * Perform this network frame as-is.\n */\n public abstract passthrough(): void\n\n /**\n * Error the underling network frame.\n * @param reason The reason for the error.\n */\n public abstract errorWith(reason?: unknown): void\n\n /**\n * Get a message to be used when this frame is unhandled.\n */\n public abstract getUnhandledMessage(): Promise\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,qBAA8C;AAkBvC,MAAe,aAIpB;AAAA,EAGA,YACkB,UACA,MAChB;AAFgB;AACA;AAEhB,SAAK,SAAS,IAAI,uBAAQ;AAAA,EAC5B;AAAA,EAPO;AAwCT;","names":[]} \ No newline at end of file diff --git a/node_modules/msw/lib/core/experimental/frames/network-frame.mjs b/node_modules/msw/lib/core/experimental/frames/network-frame.mjs new file mode 100644 index 0000000000000000000000000000000000000000..e57bd0045c984b4b9cd74fe84f29d63a67252977 --- /dev/null +++ b/node_modules/msw/lib/core/experimental/frames/network-frame.mjs @@ -0,0 +1,13 @@ +import { Emitter } from "rettime"; +class NetworkFrame { + constructor(protocol, data) { + this.protocol = protocol; + this.data = data; + this.events = new Emitter(); + } + events; +} +export { + NetworkFrame +}; +//# sourceMappingURL=network-frame.mjs.map \ No newline at end of file diff --git a/node_modules/msw/lib/core/experimental/frames/network-frame.mjs.map b/node_modules/msw/lib/core/experimental/frames/network-frame.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..75e37c06e893c3dce7179898c67ebfb0c35988d7 --- /dev/null +++ b/node_modules/msw/lib/core/experimental/frames/network-frame.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/core/experimental/frames/network-frame.ts"],"sourcesContent":["import { Emitter, type DefaultEventMap } from 'rettime'\nimport type { AnyHandler, HandlersController } from '../handlers-controller'\nimport type { UnhandledFrameHandle } from '../on-unhandled-frame'\n\nexport type AnyNetworkFrame = NetworkFrame\n\nexport type ExtractFrameEvents =\n Frame extends NetworkFrame ? Events : never\n\nexport interface NetworkFrameResolutionContext {\n baseUrl?: string | URL\n quiet?: boolean\n}\n\n/**\n * The base for the network frames. Extend this abstract class\n * to implement custom network frames.\n */\nexport abstract class NetworkFrame<\n Protocol extends string,\n Data,\n Events extends DefaultEventMap,\n> {\n public events: Emitter\n\n constructor(\n public readonly protocol: Protocol,\n public readonly data: Data,\n ) {\n this.events = new Emitter()\n }\n\n public abstract getHandlers(controller: HandlersController): Array\n\n /**\n * Resolve the current frame against the given list of handlers.\n * Optionally, use a custom resolution context to control behaviors\n * like `baseUrl`.\n *\n * Returns `true` if the frame was handled, `false` if it wasn't, and `null`\n * if its handling was skipped (e.g. the frame was bypassed).\n */\n public abstract resolve(\n handlers: Array,\n onUnhandledFrame: UnhandledFrameHandle,\n resolutionContext?: NetworkFrameResolutionContext,\n ): Promise\n\n /**\n * Perform this network frame as-is.\n */\n public abstract passthrough(): void\n\n /**\n * Error the underling network frame.\n * @param reason The reason for the error.\n */\n public abstract errorWith(reason?: unknown): void\n\n /**\n * Get a message to be used when this frame is unhandled.\n */\n public abstract getUnhandledMessage(): Promise\n}\n"],"mappings":"AAAA,SAAS,eAAqC;AAkBvC,MAAe,aAIpB;AAAA,EAGA,YACkB,UACA,MAChB;AAFgB;AACA;AAEhB,SAAK,SAAS,IAAI,QAAQ;AAAA,EAC5B;AAAA,EAPO;AAwCT;","names":[]} \ No newline at end of file diff --git a/node_modules/msw/lib/core/experimental/frames/websocket-frame.d.mts b/node_modules/msw/lib/core/experimental/frames/websocket-frame.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..418965bd722843f97abd310e4221729b74b28095 --- /dev/null +++ b/node_modules/msw/lib/core/experimental/frames/websocket-frame.d.mts @@ -0,0 +1,55 @@ +import { TypedEvent } from 'rettime'; +import { WebSocketConnectionData } from '@mswjs/interceptors/WebSocket'; +import { WebSocketHandler } from '../../handlers/WebSocketHandler.mjs'; +import { N as NetworkFrame, b as UnhandledFrameHandle, a as NetworkFrameResolutionContext } from '../../on-unhandled-frame-Cr1KOZ0I.mjs'; +import { HandlersController, AnyHandler } from '../handlers-controller.mjs'; +import 'strict-event-emitter'; +import '../../utils/matching/matchRequestUrl.mjs'; +import '../../HttpResponse-CQwYpuKo.mjs'; +import '@mswjs/interceptors'; +import '../../utils/internal/isIterable.mjs'; +import '../../typeUtils.mjs'; +import 'graphql'; + +interface WebSocketNetworkFrameOptions { + connection: WebSocketConnectionData; +} +type WebSocketNetworkFrameEventMap = { + connection: WebSocketConnectionEvent; + unhandledException: UnhandledWebSocketExceptionEvent; +}; +declare class WebSocketConnectionEvent | undefined; +} = { + url: URL; + protocols: string | Array | undefined; +}, ReturnType = void, EventType extends string = string> extends TypedEvent { + readonly url: URL; + readonly protocols: string | Array | undefined; + constructor(type: EventType, data: DataType); +} +declare class UnhandledWebSocketExceptionEvent | undefined; + error: unknown; +} = { + url: URL; + protocols: string | Array | undefined; + error: unknown; +}, ReturnType = void, EventType extends string = string> extends TypedEvent { + readonly url: URL; + readonly protocols: string | Array | undefined; + readonly error: unknown; + constructor(type: EventType, data: DataType); +} +declare abstract class WebSocketNetworkFrame extends NetworkFrame<'ws', { + connection: WebSocketConnectionData; +}, WebSocketNetworkFrameEventMap> { + constructor(options: WebSocketNetworkFrameOptions); + getHandlers(controller: HandlersController): Array; + resolve(handlers: Array, onUnhandledFrame: UnhandledFrameHandle, resolutionContext?: NetworkFrameResolutionContext): Promise; + getUnhandledMessage(): Promise; +} + +export { WebSocketNetworkFrame, type WebSocketNetworkFrameEventMap, type WebSocketNetworkFrameOptions }; diff --git a/node_modules/msw/lib/core/experimental/frames/websocket-frame.d.ts b/node_modules/msw/lib/core/experimental/frames/websocket-frame.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..68fc8f76497fd9ae7674a85c0ece53a097f7a0d3 --- /dev/null +++ b/node_modules/msw/lib/core/experimental/frames/websocket-frame.d.ts @@ -0,0 +1,55 @@ +import { TypedEvent } from 'rettime'; +import { WebSocketConnectionData } from '@mswjs/interceptors/WebSocket'; +import { WebSocketHandler } from '../../handlers/WebSocketHandler.js'; +import { N as NetworkFrame, b as UnhandledFrameHandle, a as NetworkFrameResolutionContext } from '../../on-unhandled-frame-BBR-P3kV.js'; +import { HandlersController, AnyHandler } from '../handlers-controller.js'; +import 'strict-event-emitter'; +import '../../utils/matching/matchRequestUrl.js'; +import '../../HttpResponse-BFS34nkx.js'; +import '@mswjs/interceptors'; +import '../../utils/internal/isIterable.js'; +import '../../typeUtils.js'; +import 'graphql'; + +interface WebSocketNetworkFrameOptions { + connection: WebSocketConnectionData; +} +type WebSocketNetworkFrameEventMap = { + connection: WebSocketConnectionEvent; + unhandledException: UnhandledWebSocketExceptionEvent; +}; +declare class WebSocketConnectionEvent | undefined; +} = { + url: URL; + protocols: string | Array | undefined; +}, ReturnType = void, EventType extends string = string> extends TypedEvent { + readonly url: URL; + readonly protocols: string | Array | undefined; + constructor(type: EventType, data: DataType); +} +declare class UnhandledWebSocketExceptionEvent | undefined; + error: unknown; +} = { + url: URL; + protocols: string | Array | undefined; + error: unknown; +}, ReturnType = void, EventType extends string = string> extends TypedEvent { + readonly url: URL; + readonly protocols: string | Array | undefined; + readonly error: unknown; + constructor(type: EventType, data: DataType); +} +declare abstract class WebSocketNetworkFrame extends NetworkFrame<'ws', { + connection: WebSocketConnectionData; +}, WebSocketNetworkFrameEventMap> { + constructor(options: WebSocketNetworkFrameOptions); + getHandlers(controller: HandlersController): Array; + resolve(handlers: Array, onUnhandledFrame: UnhandledFrameHandle, resolutionContext?: NetworkFrameResolutionContext): Promise; + getUnhandledMessage(): Promise; +} + +export { WebSocketNetworkFrame, type WebSocketNetworkFrameEventMap, type WebSocketNetworkFrameOptions }; diff --git a/node_modules/msw/lib/core/experimental/frames/websocket-frame.js b/node_modules/msw/lib/core/experimental/frames/websocket-frame.js new file mode 100644 index 0000000000000000000000000000000000000000..19e69436c6cf0fc4fcbca2dadf360a9b37d20d5c --- /dev/null +++ b/node_modules/msw/lib/core/experimental/frames/websocket-frame.js @@ -0,0 +1,131 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var websocket_frame_exports = {}; +__export(websocket_frame_exports, { + WebSocketNetworkFrame: () => WebSocketNetworkFrame +}); +module.exports = __toCommonJS(websocket_frame_exports); +var import_rettime = require("rettime"); +var import_WebSocket = require("@mswjs/interceptors/WebSocket"); +var import_WebSocketHandler = require("../../handlers/WebSocketHandler"); +var import_network_frame = require("./network-frame"); +var import_on_unhandled_frame = require("../on-unhandled-frame"); +var import_devUtils = require("../../utils/internal/devUtils"); +var import_handlers_controller = require("../handlers-controller"); +class WebSocketConnectionEvent extends import_rettime.TypedEvent { + url; + protocols; + constructor(type, data) { + super(...[type, {}]); + this.url = data.url; + this.protocols = data.protocols; + } +} +class UnhandledWebSocketExceptionEvent extends import_rettime.TypedEvent { + url; + protocols; + error; + constructor(type, data) { + super(...[type, {}]); + this.url = data.url; + this.protocols = data.protocols; + this.error = data.error; + } +} +class WebSocketNetworkFrame extends import_network_frame.NetworkFrame { + constructor(options) { + super("ws", { + connection: options.connection + }); + } + getHandlers(controller) { + return controller.getHandlersByKind("websocket"); + } + async resolve(handlers, onUnhandledFrame, resolutionContext) { + const { connection } = this.data; + this.events.emit( + new WebSocketConnectionEvent("connection", { + url: connection.client.url, + protocols: connection.info.protocols + }) + ); + if (handlers.length === 0) { + await (0, import_on_unhandled_frame.executeUnhandledFrameHandle)(this, onUnhandledFrame).then( + () => this.passthrough(), + (error) => this.errorWith(error) + ); + return false; + } + let hasMatchingHandlers = false; + for (const handler of handlers) { + const handlerConnection = await handler.run(connection, { + baseUrl: resolutionContext?.baseUrl?.toString(), + /** + * @note Do not emit the "connection" event when running the handler. + * Use the run only to get the resolved connection object. + */ + [import_WebSocketHandler.kAutoConnect]: false + }); + if (!handlerConnection) { + continue; + } + hasMatchingHandlers = true; + const removeLogger = !resolutionContext?.quiet ? handler.log(connection) : void 0; + try { + if (!handler[import_WebSocketHandler.kConnect](handlerConnection)) { + removeLogger?.(); + } + } catch (error) { + if (!this.events.emit( + new UnhandledWebSocketExceptionEvent("unhandledException", { + error, + url: connection.client.url, + protocols: connection.info.protocols + }) + )) { + console.error(error); + import_devUtils.devUtils.error( + 'Encountered an unhandled exception during the handler lookup for "%s". Please see the original error above.', + connection.client.url + ); + } + throw error; + } + } + if (!hasMatchingHandlers) { + await (0, import_on_unhandled_frame.executeUnhandledFrameHandle)(this, onUnhandledFrame).then( + () => this.passthrough(), + (error) => this.errorWith(error) + ); + return false; + } + return true; + } + async getUnhandledMessage() { + const { connection } = this.data; + const details = ` + + \u2022 ${connection.client.url} + +`; + return `intercepted a WebSocket connection without a matching event handler:${details}If you still wish to intercept this unhandled connection, please create an event handler for it. +Read more: https://mswjs.io/docs/websocket`; + } +} +//# sourceMappingURL=websocket-frame.js.map \ No newline at end of file diff --git a/node_modules/msw/lib/core/experimental/frames/websocket-frame.js.map b/node_modules/msw/lib/core/experimental/frames/websocket-frame.js.map new file mode 100644 index 0000000000000000000000000000000000000000..991807d1551f8f95d110ceb5054dce0d18401720 --- /dev/null +++ b/node_modules/msw/lib/core/experimental/frames/websocket-frame.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/core/experimental/frames/websocket-frame.ts"],"sourcesContent":["import { TypedEvent } from 'rettime'\nimport { type WebSocketConnectionData } from '@mswjs/interceptors/WebSocket'\nimport {\n kConnect,\n kAutoConnect,\n type WebSocketHandler,\n} from '../../handlers/WebSocketHandler'\nimport {\n NetworkFrame,\n type NetworkFrameResolutionContext,\n} from './network-frame'\nimport {\n executeUnhandledFrameHandle,\n type UnhandledFrameHandle,\n} from '../on-unhandled-frame'\nimport { devUtils } from '../../utils/internal/devUtils'\nimport type { HandlersController } from '../handlers-controller'\nimport { type AnyHandler } from '../handlers-controller'\n\nexport interface WebSocketNetworkFrameOptions {\n connection: WebSocketConnectionData\n}\n\nexport type WebSocketNetworkFrameEventMap = {\n connection: WebSocketConnectionEvent\n unhandledException: UnhandledWebSocketExceptionEvent\n}\n\nclass WebSocketConnectionEvent<\n DataType extends {\n url: URL\n protocols: string | Array | undefined\n } = { url: URL; protocols: string | Array | undefined },\n ReturnType = void,\n EventType extends string = string,\n> extends TypedEvent {\n public readonly url: URL\n public readonly protocols: string | Array | undefined\n\n constructor(type: EventType, data: DataType) {\n super(...([type, {}] as any))\n this.url = data.url\n this.protocols = data.protocols\n }\n}\n\nclass UnhandledWebSocketExceptionEvent<\n DataType extends {\n url: URL\n protocols: string | Array | undefined\n error: unknown\n } = {\n url: URL\n protocols: string | Array | undefined\n error: unknown\n },\n ReturnType = void,\n EventType extends string = string,\n> extends TypedEvent {\n public readonly url: URL\n public readonly protocols: string | Array | undefined\n public readonly error: unknown\n\n constructor(type: EventType, data: DataType) {\n super(...([type, {}] as any))\n this.url = data.url\n this.protocols = data.protocols\n this.error = data.error\n }\n}\n\nexport abstract class WebSocketNetworkFrame extends NetworkFrame<\n 'ws',\n {\n connection: WebSocketConnectionData\n },\n WebSocketNetworkFrameEventMap\n> {\n constructor(options: WebSocketNetworkFrameOptions) {\n super('ws', {\n connection: options.connection,\n })\n }\n\n public getHandlers(controller: HandlersController): Array {\n return controller.getHandlersByKind('websocket')\n }\n\n public async resolve(\n handlers: Array,\n onUnhandledFrame: UnhandledFrameHandle,\n resolutionContext?: NetworkFrameResolutionContext,\n ): Promise {\n const { connection } = this.data\n\n this.events.emit(\n new WebSocketConnectionEvent('connection', {\n url: connection.client.url,\n protocols: connection.info.protocols,\n }),\n )\n\n // No WebSocket handlers defined.\n if (handlers.length === 0) {\n await executeUnhandledFrameHandle(this, onUnhandledFrame).then(\n () => this.passthrough(),\n (error) => this.errorWith(error),\n )\n\n return false\n }\n\n let hasMatchingHandlers = false\n\n for (const handler of handlers) {\n const handlerConnection = await handler.run(connection, {\n baseUrl: resolutionContext?.baseUrl?.toString(),\n /**\n * @note Do not emit the \"connection\" event when running the handler.\n * Use the run only to get the resolved connection object.\n */\n [kAutoConnect]: false,\n })\n\n if (!handlerConnection) {\n continue\n }\n\n hasMatchingHandlers = true\n\n /**\n * @note Attach the WebSocket logger *before* emitting the \"connection\" event.\n * Connection event listeners may perform actions that should be reflected in the logs\n * (e.g. closing the connection immediately). If the logger is attached after the connection,\n * those actions cannot be properly logged.\n */\n const removeLogger = !resolutionContext?.quiet\n ? handler.log(connection)\n : undefined\n\n try {\n if (!handler[kConnect](handlerConnection)) {\n removeLogger?.()\n }\n } catch (error) {\n if (\n !this.events.emit(\n new UnhandledWebSocketExceptionEvent('unhandledException', {\n error,\n url: connection.client.url,\n protocols: connection.info.protocols,\n }),\n )\n ) {\n console.error(error)\n devUtils.error(\n 'Encountered an unhandled exception during the handler lookup for \"%s\". Please see the original error above.',\n connection.client.url,\n )\n }\n\n /**\n * @note Throw the caught error so it gets picked up by WebSocketInterceptor.\n * It's the interceptor who translates handler errors to WebSocket closures.\n */\n throw error\n }\n }\n\n // No matching WebSocket handlers found.\n if (!hasMatchingHandlers) {\n await executeUnhandledFrameHandle(this, onUnhandledFrame).then(\n () => this.passthrough(),\n (error) => this.errorWith(error),\n )\n\n return false\n }\n\n return true\n }\n\n public async getUnhandledMessage(): Promise {\n const { connection } = this.data\n const details = `\\n\\n \\u2022 ${connection.client.url}\\n\\n`\n\n return `intercepted a WebSocket connection without a matching event handler:${details}If you still wish to intercept this unhandled connection, please create an event handler for it.\\nRead more: https://mswjs.io/docs/websocket`\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,qBAA2B;AAC3B,uBAA6C;AAC7C,8BAIO;AACP,2BAGO;AACP,gCAGO;AACP,sBAAyB;AAEzB,iCAAgC;AAWhC,MAAM,iCAOI,0BAA4C;AAAA,EACpC;AAAA,EACA;AAAA,EAEhB,YAAY,MAAiB,MAAgB;AAC3C,UAAM,GAAI,CAAC,MAAM,CAAC,CAAC,CAAS;AAC5B,SAAK,MAAM,KAAK;AAChB,SAAK,YAAY,KAAK;AAAA,EACxB;AACF;AAEA,MAAM,yCAYI,0BAA4C;AAAA,EACpC;AAAA,EACA;AAAA,EACA;AAAA,EAEhB,YAAY,MAAiB,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,sBAAsB;AAAA,YACzD;AAAA,YACA,KAAK,WAAW,OAAO;AAAA,YACvB,WAAW,WAAW,KAAK;AAAA,UAC7B,CAAC;AAAA,QACH,GACA;AACA,kBAAQ,MAAM,KAAK;AACnB,mCAAS;AAAA,YACP;AAAA,YACA,WAAW,OAAO;AAAA,UACpB;AAAA,QACF;AAMA,cAAM;AAAA,MACR;AAAA,IACF;AAGA,QAAI,CAAC,qBAAqB;AACxB,gBAAM,uDAA4B,MAAM,gBAAgB,EAAE;AAAA,QACxD,MAAM,KAAK,YAAY;AAAA,QACvB,CAAC,UAAU,KAAK,UAAU,KAAK;AAAA,MACjC;AAEA,aAAO;AAAA,IACT;AAEA,WAAO;AAAA,EACT;AAAA,EAEA,MAAa,sBAAuC;AAClD,UAAM,EAAE,WAAW,IAAI,KAAK;AAC5B,UAAM,UAAU;AAAA;AAAA,WAAgB,WAAW,OAAO,GAAG;AAAA;AAAA;AAErD,WAAO,uEAAuE,OAAO;AAAA;AAAA,EACvF;AACF;","names":[]} \ No newline at end of file diff --git a/node_modules/msw/lib/core/experimental/frames/websocket-frame.mjs b/node_modules/msw/lib/core/experimental/frames/websocket-frame.mjs new file mode 100644 index 0000000000000000000000000000000000000000..3afc6c5c8f5c501618aab1d7ef92d209a18ca2cb --- /dev/null +++ b/node_modules/msw/lib/core/experimental/frames/websocket-frame.mjs @@ -0,0 +1,118 @@ +import { TypedEvent } from "rettime"; +import {} from "@mswjs/interceptors/WebSocket"; +import { + kConnect, + kAutoConnect +} from '../../handlers/WebSocketHandler.mjs'; +import { + NetworkFrame +} from './network-frame.mjs'; +import { + executeUnhandledFrameHandle +} from '../on-unhandled-frame.mjs'; +import { devUtils } from '../../utils/internal/devUtils.mjs'; +import {} from '../handlers-controller.mjs'; +class WebSocketConnectionEvent extends TypedEvent { + url; + protocols; + constructor(type, data) { + super(...[type, {}]); + this.url = data.url; + this.protocols = data.protocols; + } +} +class UnhandledWebSocketExceptionEvent extends TypedEvent { + url; + protocols; + error; + constructor(type, data) { + super(...[type, {}]); + this.url = data.url; + this.protocols = data.protocols; + this.error = data.error; + } +} +class WebSocketNetworkFrame extends NetworkFrame { + constructor(options) { + super("ws", { + connection: options.connection + }); + } + getHandlers(controller) { + return controller.getHandlersByKind("websocket"); + } + async resolve(handlers, onUnhandledFrame, resolutionContext) { + const { connection } = this.data; + this.events.emit( + new WebSocketConnectionEvent("connection", { + url: connection.client.url, + protocols: connection.info.protocols + }) + ); + if (handlers.length === 0) { + await executeUnhandledFrameHandle(this, onUnhandledFrame).then( + () => this.passthrough(), + (error) => this.errorWith(error) + ); + return false; + } + let hasMatchingHandlers = false; + for (const handler of handlers) { + const handlerConnection = await handler.run(connection, { + baseUrl: resolutionContext?.baseUrl?.toString(), + /** + * @note Do not emit the "connection" event when running the handler. + * Use the run only to get the resolved connection object. + */ + [kAutoConnect]: false + }); + if (!handlerConnection) { + continue; + } + hasMatchingHandlers = true; + const removeLogger = !resolutionContext?.quiet ? handler.log(connection) : void 0; + try { + if (!handler[kConnect](handlerConnection)) { + removeLogger?.(); + } + } catch (error) { + if (!this.events.emit( + new UnhandledWebSocketExceptionEvent("unhandledException", { + error, + url: connection.client.url, + protocols: connection.info.protocols + }) + )) { + console.error(error); + devUtils.error( + 'Encountered an unhandled exception during the handler lookup for "%s". Please see the original error above.', + connection.client.url + ); + } + throw error; + } + } + if (!hasMatchingHandlers) { + await executeUnhandledFrameHandle(this, onUnhandledFrame).then( + () => this.passthrough(), + (error) => this.errorWith(error) + ); + return false; + } + return true; + } + async getUnhandledMessage() { + const { connection } = this.data; + const details = ` + + \u2022 ${connection.client.url} + +`; + return `intercepted a WebSocket connection without a matching event handler:${details}If you still wish to intercept this unhandled connection, please create an event handler for it. +Read more: https://mswjs.io/docs/websocket`; + } +} +export { + WebSocketNetworkFrame +}; +//# sourceMappingURL=websocket-frame.mjs.map \ No newline at end of file diff --git a/node_modules/msw/lib/core/experimental/frames/websocket-frame.mjs.map b/node_modules/msw/lib/core/experimental/frames/websocket-frame.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..8e532f48e172f21a35443255900d1ab1bd75581c --- /dev/null +++ b/node_modules/msw/lib/core/experimental/frames/websocket-frame.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/core/experimental/frames/websocket-frame.ts"],"sourcesContent":["import { TypedEvent } from 'rettime'\nimport { type WebSocketConnectionData } from '@mswjs/interceptors/WebSocket'\nimport {\n kConnect,\n kAutoConnect,\n type WebSocketHandler,\n} from '../../handlers/WebSocketHandler'\nimport {\n NetworkFrame,\n type NetworkFrameResolutionContext,\n} from './network-frame'\nimport {\n executeUnhandledFrameHandle,\n type UnhandledFrameHandle,\n} from '../on-unhandled-frame'\nimport { devUtils } from '../../utils/internal/devUtils'\nimport type { HandlersController } from '../handlers-controller'\nimport { type AnyHandler } from '../handlers-controller'\n\nexport interface WebSocketNetworkFrameOptions {\n connection: WebSocketConnectionData\n}\n\nexport type WebSocketNetworkFrameEventMap = {\n connection: WebSocketConnectionEvent\n unhandledException: UnhandledWebSocketExceptionEvent\n}\n\nclass WebSocketConnectionEvent<\n DataType extends {\n url: URL\n protocols: string | Array | undefined\n } = { url: URL; protocols: string | Array | undefined },\n ReturnType = void,\n EventType extends string = string,\n> extends TypedEvent {\n public readonly url: URL\n public readonly protocols: string | Array | undefined\n\n constructor(type: EventType, data: DataType) {\n super(...([type, {}] as any))\n this.url = data.url\n this.protocols = data.protocols\n }\n}\n\nclass UnhandledWebSocketExceptionEvent<\n DataType extends {\n url: URL\n protocols: string | Array | undefined\n error: unknown\n } = {\n url: URL\n protocols: string | Array | undefined\n error: unknown\n },\n ReturnType = void,\n EventType extends string = string,\n> extends TypedEvent {\n public readonly url: URL\n public readonly protocols: string | Array | undefined\n public readonly error: unknown\n\n constructor(type: EventType, data: DataType) {\n super(...([type, {}] as any))\n this.url = data.url\n this.protocols = data.protocols\n this.error = data.error\n }\n}\n\nexport abstract class WebSocketNetworkFrame extends NetworkFrame<\n 'ws',\n {\n connection: WebSocketConnectionData\n },\n WebSocketNetworkFrameEventMap\n> {\n constructor(options: WebSocketNetworkFrameOptions) {\n super('ws', {\n connection: options.connection,\n })\n }\n\n public getHandlers(controller: HandlersController): Array {\n return controller.getHandlersByKind('websocket')\n }\n\n public async resolve(\n handlers: Array,\n onUnhandledFrame: UnhandledFrameHandle,\n resolutionContext?: NetworkFrameResolutionContext,\n ): Promise {\n const { connection } = this.data\n\n this.events.emit(\n new WebSocketConnectionEvent('connection', {\n url: connection.client.url,\n protocols: connection.info.protocols,\n }),\n )\n\n // No WebSocket handlers defined.\n if (handlers.length === 0) {\n await executeUnhandledFrameHandle(this, onUnhandledFrame).then(\n () => this.passthrough(),\n (error) => this.errorWith(error),\n )\n\n return false\n }\n\n let hasMatchingHandlers = false\n\n for (const handler of handlers) {\n const handlerConnection = await handler.run(connection, {\n baseUrl: resolutionContext?.baseUrl?.toString(),\n /**\n * @note Do not emit the \"connection\" event when running the handler.\n * Use the run only to get the resolved connection object.\n */\n [kAutoConnect]: false,\n })\n\n if (!handlerConnection) {\n continue\n }\n\n hasMatchingHandlers = true\n\n /**\n * @note Attach the WebSocket logger *before* emitting the \"connection\" event.\n * Connection event listeners may perform actions that should be reflected in the logs\n * (e.g. closing the connection immediately). If the logger is attached after the connection,\n * those actions cannot be properly logged.\n */\n const removeLogger = !resolutionContext?.quiet\n ? handler.log(connection)\n : undefined\n\n try {\n if (!handler[kConnect](handlerConnection)) {\n removeLogger?.()\n }\n } catch (error) {\n if (\n !this.events.emit(\n new UnhandledWebSocketExceptionEvent('unhandledException', {\n error,\n url: connection.client.url,\n protocols: connection.info.protocols,\n }),\n )\n ) {\n console.error(error)\n devUtils.error(\n 'Encountered an unhandled exception during the handler lookup for \"%s\". Please see the original error above.',\n connection.client.url,\n )\n }\n\n /**\n * @note Throw the caught error so it gets picked up by WebSocketInterceptor.\n * It's the interceptor who translates handler errors to WebSocket closures.\n */\n throw error\n }\n }\n\n // No matching WebSocket handlers found.\n if (!hasMatchingHandlers) {\n await executeUnhandledFrameHandle(this, onUnhandledFrame).then(\n () => this.passthrough(),\n (error) => this.errorWith(error),\n )\n\n return false\n }\n\n return true\n }\n\n public async getUnhandledMessage(): Promise {\n const { connection } = this.data\n const details = `\\n\\n \\u2022 ${connection.client.url}\\n\\n`\n\n return `intercepted a WebSocket connection without a matching event handler:${details}If you still wish to intercept this unhandled connection, please create an event handler for it.\\nRead more: https://mswjs.io/docs/websocket`\n }\n}\n"],"mappings":"AAAA,SAAS,kBAAkB;AAC3B,eAA6C;AAC7C;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP;AAAA,EACE;AAAA,OAEK;AACP;AAAA,EACE;AAAA,OAEK;AACP,SAAS,gBAAgB;AAEzB,eAAgC;AAWhC,MAAM,iCAOI,WAA4C;AAAA,EACpC;AAAA,EACA;AAAA,EAEhB,YAAY,MAAiB,MAAgB;AAC3C,UAAM,GAAI,CAAC,MAAM,CAAC,CAAC,CAAS;AAC5B,SAAK,MAAM,KAAK;AAChB,SAAK,YAAY,KAAK;AAAA,EACxB;AACF;AAEA,MAAM,yCAYI,WAA4C;AAAA,EACpC;AAAA,EACA;AAAA,EACA;AAAA,EAEhB,YAAY,MAAiB,MAAgB;AAC3C,UAAM,GAAI,CAAC,MAAM,CAAC,CAAC,CAAS;AAC5B,SAAK,MAAM,KAAK;AAChB,SAAK,YAAY,KAAK;AACtB,SAAK,QAAQ,KAAK;AAAA,EACpB;AACF;AAEO,MAAe,8BAA8B,aAMlD;AAAA,EACA,YAAY,SAAuC;AACjD,UAAM,MAAM;AAAA,MACV,YAAY,QAAQ;AAAA,IACtB,CAAC;AAAA,EACH;AAAA,EAEO,YAAY,YAAmD;AACpE,WAAO,WAAW,kBAAkB,WAAW;AAAA,EACjD;AAAA,EAEA,MAAa,QACX,UACA,kBACA,mBACyB;AACzB,UAAM,EAAE,WAAW,IAAI,KAAK;AAE5B,SAAK,OAAO;AAAA,MACV,IAAI,yBAAyB,cAAc;AAAA,QACzC,KAAK,WAAW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I,KAAK;AAC5B,UAAM,UAAU;AAAA;AAAA,WAAgB,WAAW,OAAO,GAAG;AAAA;AAAA;AAErD,WAAO,uEAAuE,OAAO;AAAA;AAAA,EACvF;AACF;","names":[]} \ No newline at end of file diff --git a/node_modules/msw/lib/core/experimental/handlers-controller.d.mts b/node_modules/msw/lib/core/experimental/handlers-controller.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..2938cc6df9644ce1dce81eed25a69d9111e83dcb --- /dev/null +++ b/node_modules/msw/lib/core/experimental/handlers-controller.d.mts @@ -0,0 +1,36 @@ +import { R as RequestHandler } from '../HttpResponse-CQwYpuKo.mjs'; +import { WebSocketHandler } from '../handlers/WebSocketHandler.mjs'; +import '@mswjs/interceptors'; +import '../utils/internal/isIterable.mjs'; +import '../typeUtils.mjs'; +import 'graphql'; +import '../utils/matching/matchRequestUrl.mjs'; +import 'strict-event-emitter'; +import '@mswjs/interceptors/WebSocket'; + +type AnyHandler = RequestHandler | WebSocketHandler; +type HandlersMap = Partial>>; +declare function groupHandlersByKind(handlers: Array): HandlersMap; +interface HandlersControllerState { + initialHandlers: HandlersMap; + handlers: HandlersMap; +} +declare abstract class HandlersController { + #private; + protected getInitialState(initialHandlers: Array): HandlersControllerState; + protected abstract getState(): HandlersControllerState; + protected abstract setState(nextState: Partial): void; + currentHandlers(): Array; + getHandlersByKind(kind: AnyHandler['kind']): Array; + use(nextHandlers: Array): void; + reset(nextHandlers: Array): void; + restore(): void; +} +declare class InMemoryHandlersController extends HandlersController { + #private; + constructor(initialHandlers: Array); + protected getState(): HandlersControllerState; + protected setState(nextState: Partial): void; +} + +export { type AnyHandler, HandlersController, type HandlersControllerState, type HandlersMap, InMemoryHandlersController, groupHandlersByKind }; diff --git a/node_modules/msw/lib/core/experimental/handlers-controller.d.ts b/node_modules/msw/lib/core/experimental/handlers-controller.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1bd41ce69e19b2ffb2ff2ef1bab5115ec6530b22 --- /dev/null +++ b/node_modules/msw/lib/core/experimental/handlers-controller.d.ts @@ -0,0 +1,36 @@ +import { R as RequestHandler } from '../HttpResponse-BFS34nkx.js'; +import { WebSocketHandler } from '../handlers/WebSocketHandler.js'; +import '@mswjs/interceptors'; +import '../utils/internal/isIterable.js'; +import '../typeUtils.js'; +import 'graphql'; +import '../utils/matching/matchRequestUrl.js'; +import 'strict-event-emitter'; +import '@mswjs/interceptors/WebSocket'; + +type AnyHandler = RequestHandler | WebSocketHandler; +type HandlersMap = Partial>>; +declare function groupHandlersByKind(handlers: Array): HandlersMap; +interface HandlersControllerState { + initialHandlers: HandlersMap; + handlers: HandlersMap; +} +declare abstract class HandlersController { + #private; + protected getInitialState(initialHandlers: Array): HandlersControllerState; + protected abstract getState(): HandlersControllerState; + protected abstract setState(nextState: Partial): void; + currentHandlers(): Array; + getHandlersByKind(kind: AnyHandler['kind']): Array; + use(nextHandlers: Array): void; + reset(nextHandlers: Array): void; + restore(): void; +} +declare class InMemoryHandlersController extends HandlersController { + #private; + constructor(initialHandlers: Array); + protected getState(): HandlersControllerState; + protected setState(nextState: Partial): void; +} + +export { type AnyHandler, HandlersController, type HandlersControllerState, type HandlersMap, InMemoryHandlersController, groupHandlersByKind }; diff --git a/node_modules/msw/lib/core/experimental/handlers-controller.js b/node_modules/msw/lib/core/experimental/handlers-controller.js new file mode 100644 index 0000000000000000000000000000000000000000..6fe62d7839cadb017e5e01d02daef1db4d8d20b6 --- /dev/null +++ b/node_modules/msw/lib/core/experimental/handlers-controller.js @@ -0,0 +1,146 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var handlers_controller_exports = {}; +__export(handlers_controller_exports, { + HandlersController: () => HandlersController, + InMemoryHandlersController: () => InMemoryHandlersController, + groupHandlersByKind: () => groupHandlersByKind +}); +module.exports = __toCommonJS(handlers_controller_exports); +var import_outvariant = require("outvariant"); +var import_RequestHandler = require("../handlers/RequestHandler"); +var import_WebSocketHandler = require("../handlers/WebSocketHandler"); +var import_devUtils = require("../utils/internal/devUtils"); +var import_attachSiblingHandlers = require("../utils/internal/attachSiblingHandlers"); +function groupHandlersByKind(handlers) { + const groups = {}; + const pushUnique = (kind, handler) => { + const bucket = groups[kind] ||= []; + if (!bucket.includes(handler)) { + bucket.push(handler); + } + }; + for (const handler of handlers) { + pushUnique(handler.kind, handler); + for (const sibling of (0, import_attachSiblingHandlers.getSiblingHandlers)(handler)) { + pushUnique(sibling.kind, sibling); + } + } + return groups; +} +class HandlersController { + getInitialState(initialHandlers) { + (0, import_outvariant.invariant)( + this.#validateHandlers(initialHandlers), + import_devUtils.devUtils.formatMessage( + "Failed to apply given request handlers: invalid input. Did you forget to spread the request handlers Array?" + ) + ); + const normalizedInitialHandlers = groupHandlersByKind(initialHandlers); + return { + initialHandlers: normalizedInitialHandlers, + handlers: { ...normalizedInitialHandlers } + }; + } + currentHandlers() { + return Object.values(this.getState().handlers).flat().filter((handler) => handler != null); + } + getHandlersByKind(kind) { + return this.getState().handlers[kind] || []; + } + use(nextHandlers) { + (0, import_outvariant.invariant)( + this.#validateHandlers(nextHandlers), + import_devUtils.devUtils.formatMessage( + '[MSW] Failed to call "use()" with the given request handlers: invalid input. Did you forget to spread the array of request handlers?' + ) + ); + if (nextHandlers.length === 0) { + return; + } + const { handlers } = this.getState(); + const overrides = groupHandlersByKind(nextHandlers); + for (const kind in overrides) { + const overridesForKind = overrides[kind]; + const existingForKind = handlers[kind]; + handlers[kind] = existingForKind ? [...overridesForKind, ...existingForKind] : overridesForKind; + } + this.setState({ handlers }); + } + reset(nextHandlers) { + (0, import_outvariant.invariant)( + nextHandlers.length > 0 ? this.#validateHandlers(nextHandlers) : true, + import_devUtils.devUtils.formatMessage( + "Failed to replace initial handlers during reset: invalid handlers. Did you forget to spread the handlers array?" + ) + ); + for (const handler of this.currentHandlers()) { + if ("reset" in handler) { + handler["reset"](); + } + } + const { initialHandlers } = this.getState(); + if (nextHandlers.length === 0) { + this.setState({ + handlers: { ...initialHandlers } + }); + return; + } + const normalizedNextHandlers = groupHandlersByKind(nextHandlers); + this.setState({ + initialHandlers: normalizedNextHandlers, + handlers: { ...normalizedNextHandlers } + }); + } + restore() { + for (const handler of this.currentHandlers()) { + if ("restore" in handler) { + handler["restore"](); + } + } + } + #validateHandlers(handlers) { + return handlers.every((handler) => !Array.isArray(handler)); + } +} +class InMemoryHandlersController extends HandlersController { + #handlers; + #initialHandlers; + constructor(initialHandlers) { + super(); + const initialState = this.getInitialState(initialHandlers); + this.#initialHandlers = initialState.initialHandlers; + this.#handlers = initialState.handlers; + } + getState() { + return { + initialHandlers: this.#initialHandlers, + handlers: this.#handlers + }; + } + setState(nextState) { + if (nextState.initialHandlers) { + this.#initialHandlers = nextState.initialHandlers; + } + if (nextState.handlers) { + this.#handlers = nextState.handlers; + } + } +} +//# sourceMappingURL=handlers-controller.js.map \ No newline at end of file diff --git a/node_modules/msw/lib/core/experimental/handlers-controller.js.map b/node_modules/msw/lib/core/experimental/handlers-controller.js.map new file mode 100644 index 0000000000000000000000000000000000000000..3b67b9e0291c98d4a260441ddcf63c410d465112 --- /dev/null +++ b/node_modules/msw/lib/core/experimental/handlers-controller.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/core/experimental/handlers-controller.ts"],"sourcesContent":["import { invariant } from 'outvariant'\nimport { type RequestHandler } from '../handlers/RequestHandler'\nimport { type WebSocketHandler } from '../handlers/WebSocketHandler'\nimport { devUtils } from '../utils/internal/devUtils'\nimport { getSiblingHandlers } from '../utils/internal/attachSiblingHandlers'\n\nexport type AnyHandler = RequestHandler | WebSocketHandler\nexport type HandlersMap = Partial>>\n\nexport function groupHandlersByKind(handlers: Array): HandlersMap {\n const groups: HandlersMap = {}\n\n const pushUnique = (kind: AnyHandler['kind'], handler: AnyHandler) => {\n const bucket = (groups[kind] ||= [])\n\n if (!bucket.includes(handler)) {\n bucket.push(handler)\n }\n }\n\n /**\n * @note `Object.groupBy` is not implemented in Node.js v20.\n */\n for (const handler of handlers) {\n pushUnique(handler.kind, handler)\n\n for (const sibling of getSiblingHandlers(handler)) {\n pushUnique(sibling.kind, sibling)\n }\n }\n\n return groups\n}\n\nexport interface HandlersControllerState {\n initialHandlers: HandlersMap\n handlers: HandlersMap\n}\n\nexport abstract class HandlersController {\n protected getInitialState(\n initialHandlers: Array,\n ): HandlersControllerState {\n invariant(\n this.#validateHandlers(initialHandlers),\n devUtils.formatMessage(\n 'Failed to apply given request handlers: invalid input. Did you forget to spread the request handlers Array?',\n ),\n )\n\n const normalizedInitialHandlers = groupHandlersByKind(initialHandlers)\n\n return {\n initialHandlers: normalizedInitialHandlers,\n handlers: { ...normalizedInitialHandlers },\n }\n }\n\n protected abstract getState(): HandlersControllerState\n protected abstract setState(nextState: Partial): void\n\n public currentHandlers(): Array {\n return Object.values(this.getState().handlers)\n .flat()\n .filter((handler) => handler != null)\n }\n\n public getHandlersByKind(kind: AnyHandler['kind']): Array {\n return this.getState().handlers[kind] || []\n }\n\n public use(nextHandlers: Array): void {\n invariant(\n this.#validateHandlers(nextHandlers),\n devUtils.formatMessage(\n '[MSW] Failed to call \"use()\" with the given request handlers: invalid input. Did you forget to spread the array of request handlers?',\n ),\n )\n\n if (nextHandlers.length === 0) {\n return\n }\n\n const { handlers } = this.getState()\n const overrides = groupHandlersByKind(nextHandlers)\n\n // Prepend overrides to their respective kind buckets so they take\n // priority over existing handlers while preserving input order.\n for (const kind in overrides) {\n const overridesForKind = overrides[kind as AnyHandler['kind']]!\n const existingForKind = handlers[kind as AnyHandler['kind']]\n handlers[kind as AnyHandler['kind']] = existingForKind\n ? [...overridesForKind, ...existingForKind]\n : overridesForKind\n }\n\n this.setState({ handlers })\n }\n\n public reset(nextHandlers: Array): void {\n invariant(\n nextHandlers.length > 0 ? this.#validateHandlers(nextHandlers) : true,\n devUtils.formatMessage(\n 'Failed to replace initial handlers during reset: invalid handlers. Did you forget to spread the handlers array?',\n ),\n )\n\n for (const handler of this.currentHandlers()) {\n if ('reset' in handler) {\n handler['reset']()\n }\n }\n\n const { initialHandlers } = this.getState()\n\n if (nextHandlers.length === 0) {\n this.setState({\n handlers: { ...initialHandlers },\n })\n\n return\n }\n\n const normalizedNextHandlers = groupHandlersByKind(nextHandlers)\n\n this.setState({\n initialHandlers: normalizedNextHandlers,\n handlers: { ...normalizedNextHandlers },\n })\n }\n\n public restore(): void {\n for (const handler of this.currentHandlers()) {\n if ('restore' in handler) {\n handler['restore']()\n }\n }\n }\n\n #validateHandlers(handlers: Array): boolean {\n return handlers.every((handler) => !Array.isArray(handler))\n }\n}\n\nexport class InMemoryHandlersController extends HandlersController {\n #handlers: HandlersMap\n #initialHandlers: HandlersMap\n\n constructor(initialHandlers: Array) {\n super()\n\n const initialState = this.getInitialState(initialHandlers)\n\n this.#initialHandlers = initialState.initialHandlers\n this.#handlers = initialState.handlers\n }\n\n protected getState(): HandlersControllerState {\n return {\n initialHandlers: this.#initialHandlers,\n handlers: this.#handlers,\n }\n }\n\n protected setState(nextState: Partial): void {\n if (nextState.initialHandlers) {\n this.#initialHandlers = nextState.initialHandlers\n }\n\n if (nextState.handlers) {\n this.#handlers = nextState.handlers\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,wBAA0B;AAC1B,4BAAoC;AACpC,8BAAsC;AACtC,sBAAyB;AACzB,mCAAmC;AAK5B,SAAS,oBAAoB,UAA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mD;AACpE,QAAI,UAAU,iBAAiB;AAC7B,WAAK,mBAAmB,UAAU;AAAA,IACpC;AAEA,QAAI,UAAU,UAAU;AACtB,WAAK,YAAY,UAAU;AAAA,IAC7B;AAAA,EACF;AACF;","names":[]} \ No newline at end of file diff --git a/node_modules/msw/lib/core/experimental/handlers-controller.mjs b/node_modules/msw/lib/core/experimental/handlers-controller.mjs new file mode 100644 index 0000000000000000000000000000000000000000..7cc6b7b16b975a3a215efd07ddcfe197e3a4154f --- /dev/null +++ b/node_modules/msw/lib/core/experimental/handlers-controller.mjs @@ -0,0 +1,126 @@ +import { invariant } from "outvariant"; +import {} from '../handlers/RequestHandler.mjs'; +import {} from '../handlers/WebSocketHandler.mjs'; +import { devUtils } from '../utils/internal/devUtils.mjs'; +import { getSiblingHandlers } from '../utils/internal/attachSiblingHandlers.mjs'; +function groupHandlersByKind(handlers) { + const groups = {}; + const pushUnique = (kind, handler) => { + const bucket = groups[kind] ||= []; + if (!bucket.includes(handler)) { + bucket.push(handler); + } + }; + for (const handler of handlers) { + pushUnique(handler.kind, handler); + for (const sibling of getSiblingHandlers(handler)) { + pushUnique(sibling.kind, sibling); + } + } + return groups; +} +class HandlersController { + getInitialState(initialHandlers) { + invariant( + this.#validateHandlers(initialHandlers), + devUtils.formatMessage( + "Failed to apply given request handlers: invalid input. Did you forget to spread the request handlers Array?" + ) + ); + const normalizedInitialHandlers = groupHandlersByKind(initialHandlers); + return { + initialHandlers: normalizedInitialHandlers, + handlers: { ...normalizedInitialHandlers } + }; + } + currentHandlers() { + return Object.values(this.getState().handlers).flat().filter((handler) => handler != null); + } + getHandlersByKind(kind) { + return this.getState().handlers[kind] || []; + } + use(nextHandlers) { + invariant( + this.#validateHandlers(nextHandlers), + devUtils.formatMessage( + '[MSW] Failed to call "use()" with the given request handlers: invalid input. Did you forget to spread the array of request handlers?' + ) + ); + if (nextHandlers.length === 0) { + return; + } + const { handlers } = this.getState(); + const overrides = groupHandlersByKind(nextHandlers); + for (const kind in overrides) { + const overridesForKind = overrides[kind]; + const existingForKind = handlers[kind]; + handlers[kind] = existingForKind ? [...overridesForKind, ...existingForKind] : overridesForKind; + } + this.setState({ handlers }); + } + reset(nextHandlers) { + invariant( + nextHandlers.length > 0 ? this.#validateHandlers(nextHandlers) : true, + devUtils.formatMessage( + "Failed to replace initial handlers during reset: invalid handlers. Did you forget to spread the handlers array?" + ) + ); + for (const handler of this.currentHandlers()) { + if ("reset" in handler) { + handler["reset"](); + } + } + const { initialHandlers } = this.getState(); + if (nextHandlers.length === 0) { + this.setState({ + handlers: { ...initialHandlers } + }); + return; + } + const normalizedNextHandlers = groupHandlersByKind(nextHandlers); + this.setState({ + initialHandlers: normalizedNextHandlers, + handlers: { ...normalizedNextHandlers } + }); + } + restore() { + for (const handler of this.currentHandlers()) { + if ("restore" in handler) { + handler["restore"](); + } + } + } + #validateHandlers(handlers) { + return handlers.every((handler) => !Array.isArray(handler)); + } +} +class InMemoryHandlersController extends HandlersController { + #handlers; + #initialHandlers; + constructor(initialHandlers) { + super(); + const initialState = this.getInitialState(initialHandlers); + this.#initialHandlers = initialState.initialHandlers; + this.#handlers = initialState.handlers; + } + getState() { + return { + initialHandlers: this.#initialHandlers, + handlers: this.#handlers + }; + } + setState(nextState) { + if (nextState.initialHandlers) { + this.#initialHandlers = nextState.initialHandlers; + } + if (nextState.handlers) { + this.#handlers = nextState.handlers; + } + } +} +export { + HandlersController, + InMemoryHandlersController, + groupHandlersByKind +}; +//# sourceMappingURL=handlers-controller.mjs.map \ No newline at end of file diff --git a/node_modules/msw/lib/core/experimental/handlers-controller.mjs.map b/node_modules/msw/lib/core/experimental/handlers-controller.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..93e40a58f3db36f2b36d0048e3083c58aba2ce0f --- /dev/null +++ b/node_modules/msw/lib/core/experimental/handlers-controller.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/core/experimental/handlers-controller.ts"],"sourcesContent":["import { invariant } from 'outvariant'\nimport { type RequestHandler } from '../handlers/RequestHandler'\nimport { type WebSocketHandler } from '../handlers/WebSocketHandler'\nimport { devUtils } from '../utils/internal/devUtils'\nimport { getSiblingHandlers } from '../utils/internal/attachSiblingHandlers'\n\nexport type AnyHandler = RequestHandler | WebSocketHandler\nexport type HandlersMap = Partial>>\n\nexport function groupHandlersByKind(handlers: Array): HandlersMap {\n const groups: HandlersMap = {}\n\n const pushUnique = (kind: AnyHandler['kind'], handler: AnyHandler) => {\n const bucket = (groups[kind] ||= [])\n\n if (!bucket.includes(handler)) {\n bucket.push(handler)\n }\n }\n\n /**\n * @note `Object.groupBy` is not implemented in Node.js v20.\n */\n for (const handler of handlers) {\n pushUnique(handler.kind, handler)\n\n for (const sibling of getSiblingHandlers(handler)) {\n pushUnique(sibling.kind, sibling)\n }\n }\n\n return groups\n}\n\nexport interface HandlersControllerState {\n initialHandlers: HandlersMap\n handlers: HandlersMap\n}\n\nexport abstract class HandlersController {\n protected getInitialState(\n initialHandlers: Array,\n ): HandlersControllerState {\n invariant(\n this.#validateHandlers(initialHandlers),\n devUtils.formatMessage(\n 'Failed to apply given request handlers: invalid input. Did you forget to spread the request handlers Array?',\n ),\n )\n\n const normalizedInitialHandlers = groupHandlersByKind(initialHandlers)\n\n return {\n initialHandlers: normalizedInitialHandlers,\n handlers: { ...normalizedInitialHandlers },\n }\n }\n\n protected abstract getState(): HandlersControllerState\n protected abstract setState(nextState: Partial): void\n\n public currentHandlers(): Array {\n return Object.values(this.getState().handlers)\n .flat()\n .filter((handler) => handler != null)\n }\n\n public getHandlersByKind(kind: AnyHandler['kind']): Array {\n return this.getState().handlers[kind] || []\n }\n\n public use(nextHandlers: Array): void {\n invariant(\n this.#validateHandlers(nextHandlers),\n devUtils.formatMessage(\n '[MSW] Failed to call \"use()\" with the given request handlers: invalid input. Did you forget to spread the array of request handlers?',\n ),\n )\n\n if (nextHandlers.length === 0) {\n return\n }\n\n const { handlers } = this.getState()\n const overrides = groupHandlersByKind(nextHandlers)\n\n // Prepend overrides to their respective kind buckets so they take\n // priority over existing handlers while preserving input order.\n for (const kind in overrides) {\n const overridesForKind = overrides[kind as AnyHandler['kind']]!\n const existingForKind = handlers[kind as AnyHandler['kind']]\n handlers[kind as AnyHandler['kind']] = existingForKind\n ? [...overridesForKind, ...existingForKind]\n : overridesForKind\n }\n\n this.setState({ handlers })\n }\n\n public reset(nextHandlers: Array): void {\n invariant(\n nextHandlers.length > 0 ? this.#validateHandlers(nextHandlers) : true,\n devUtils.formatMessage(\n 'Failed to replace initial handlers during reset: invalid handlers. Did you forget to spread the handlers array?',\n ),\n )\n\n for (const handler of this.currentHandlers()) {\n if ('reset' in handler) {\n handler['reset']()\n }\n }\n\n const { initialHandlers } = this.getState()\n\n if (nextHandlers.length === 0) {\n this.setState({\n handlers: { ...initialHandlers },\n })\n\n return\n }\n\n const normalizedNextHandlers = groupHandlersByKind(nextHandlers)\n\n this.setState({\n initialHandlers: normalizedNextHandlers,\n handlers: { ...normalizedNextHandlers },\n })\n }\n\n public restore(): void {\n for (const handler of this.currentHandlers()) {\n if ('restore' in handler) {\n handler['restore']()\n }\n }\n }\n\n #validateHandlers(handlers: Array): boolean {\n return handlers.every((handler) => !Array.isArray(handler))\n }\n}\n\nexport class InMemoryHandlersController extends HandlersController {\n #handlers: HandlersMap\n #initialHandlers: HandlersMap\n\n constructor(initialHandlers: Array) {\n super()\n\n const initialState = this.getInitialState(initialHandlers)\n\n this.#initialHandlers = initialState.initialHandlers\n this.#handlers = initialState.handlers\n }\n\n protected getState(): HandlersControllerState {\n return {\n initialHandlers: this.#initialHandlers,\n handlers: this.#handlers,\n }\n }\n\n protected setState(nextState: Partial): void {\n if (nextState.initialHandlers) {\n this.#initialHandlers = nextState.initialHandlers\n }\n\n if (nextState.handlers) {\n this.#handlers = nextState.handlers\n }\n }\n}\n"],"mappings":"AAAA,SAAS,iBAAiB;AAC1B,eAAoC;AACpC,eAAsC;AACtC,SAAS,gBAAgB;AACzB,SAAS,0BAA0B;AAK5B,SAA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,SAAS,WAAmD;AACpE,QAAI,UAAU,iBAAiB;AAC7B,WAAK,mBAAmB,UAAU;AAAA,IACpC;AAEA,QAAI,UAAU,UAAU;AACtB,WAAK,YAAY,UAAU;AAAA,IAC7B;AAAA,EACF;AACF;","names":[]} \ No newline at end of file diff --git a/node_modules/msw/lib/core/experimental/index.d.mts b/node_modules/msw/lib/core/experimental/index.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..1493cfdfcf836b9aed6af2ce942c26a19f04ed59 --- /dev/null +++ b/node_modules/msw/lib/core/experimental/index.d.mts @@ -0,0 +1,17 @@ +export { DefineNetworkOptions, NetworkApi, defineNetwork } from './define-network.mjs'; +export { NetworkSource } from './sources/network-source.mjs'; +export { InterceptorSource } from './sources/interceptor-source.mjs'; +export { N as NetworkFrame } from '../on-unhandled-frame-Cr1KOZ0I.mjs'; +export { HttpNetworkFrame, HttpNetworkFrameEventMap } from './frames/http-frame.mjs'; +export { WebSocketNetworkFrame, WebSocketNetworkFrameEventMap } from './frames/websocket-frame.mjs'; +export { HandlersController, InMemoryHandlersController } from './handlers-controller.mjs'; +import 'rettime'; +import '@mswjs/interceptors'; +import '@mswjs/interceptors/WebSocket'; +import '../HttpResponse-CQwYpuKo.mjs'; +import '../utils/internal/isIterable.mjs'; +import '../typeUtils.mjs'; +import 'graphql'; +import '../utils/matching/matchRequestUrl.mjs'; +import '../handlers/WebSocketHandler.mjs'; +import 'strict-event-emitter'; diff --git a/node_modules/msw/lib/core/experimental/index.d.ts b/node_modules/msw/lib/core/experimental/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9bc9e17a3a6c54bc2c0882377229c6518d8d6517 --- /dev/null +++ b/node_modules/msw/lib/core/experimental/index.d.ts @@ -0,0 +1,17 @@ +export { DefineNetworkOptions, NetworkApi, defineNetwork } from './define-network.js'; +export { NetworkSource } from './sources/network-source.js'; +export { InterceptorSource } from './sources/interceptor-source.js'; +export { N as NetworkFrame } from '../on-unhandled-frame-BBR-P3kV.js'; +export { HttpNetworkFrame, HttpNetworkFrameEventMap } from './frames/http-frame.js'; +export { WebSocketNetworkFrame, WebSocketNetworkFrameEventMap } from './frames/websocket-frame.js'; +export { HandlersController, InMemoryHandlersController } from './handlers-controller.js'; +import 'rettime'; +import '@mswjs/interceptors'; +import '@mswjs/interceptors/WebSocket'; +import '../HttpResponse-BFS34nkx.js'; +import '../utils/internal/isIterable.js'; +import '../typeUtils.js'; +import 'graphql'; +import '../utils/matching/matchRequestUrl.js'; +import '../handlers/WebSocketHandler.js'; +import 'strict-event-emitter'; diff --git a/node_modules/msw/lib/core/experimental/index.js b/node_modules/msw/lib/core/experimental/index.js new file mode 100644 index 0000000000000000000000000000000000000000..78095a4b45e7ac7e95a95383d31508b0ca0724f6 --- /dev/null +++ b/node_modules/msw/lib/core/experimental/index.js @@ -0,0 +1,38 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var experimental_exports = {}; +__export(experimental_exports, { + HandlersController: () => import_handlers_controller.HandlersController, + HttpNetworkFrame: () => import_http_frame.HttpNetworkFrame, + InMemoryHandlersController: () => import_handlers_controller.InMemoryHandlersController, + InterceptorSource: () => import_interceptor_source.InterceptorSource, + NetworkFrame: () => import_network_frame.NetworkFrame, + NetworkSource: () => import_network_source.NetworkSource, + WebSocketNetworkFrame: () => import_websocket_frame.WebSocketNetworkFrame, + defineNetwork: () => import_define_network.defineNetwork +}); +module.exports = __toCommonJS(experimental_exports); +var import_define_network = require("./define-network"); +var import_network_source = require("./sources/network-source"); +var import_interceptor_source = require("./sources/interceptor-source"); +var import_network_frame = require("./frames/network-frame"); +var import_http_frame = require("./frames/http-frame"); +var import_websocket_frame = require("./frames/websocket-frame"); +var import_handlers_controller = require("./handlers-controller"); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/msw/lib/core/experimental/index.js.map b/node_modules/msw/lib/core/experimental/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..e7cfe094de3f6120102e8986ea0806ac936e77d5 --- /dev/null +++ b/node_modules/msw/lib/core/experimental/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/core/experimental/index.ts"],"sourcesContent":["export {\n defineNetwork,\n type DefineNetworkOptions,\n type NetworkApi,\n} from './define-network'\n\n/* Network sources */\nexport { NetworkSource } from './sources/network-source'\nexport { InterceptorSource } from './sources/interceptor-source'\n\n/* Frames */\nexport { NetworkFrame } from './frames/network-frame'\nexport {\n HttpNetworkFrame,\n type HttpNetworkFrameEventMap,\n} from './frames/http-frame'\nexport {\n WebSocketNetworkFrame,\n type WebSocketNetworkFrameEventMap,\n} from './frames/websocket-frame'\n\n/* Handler controllers */\nexport {\n HandlersController,\n InMemoryHandlersController,\n} from './handlers-controller'\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,4BAIO;AAGP,4BAA8B;AAC9B,gCAAkC;AAGlC,2BAA6B;AAC7B,wBAGO;AACP,6BAGO;AAGP,iCAGO;","names":[]} \ No newline at end of file diff --git a/node_modules/msw/lib/core/experimental/index.mjs b/node_modules/msw/lib/core/experimental/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..eb527cb668618abead10fdfaf9154ed60e736ac3 --- /dev/null +++ b/node_modules/msw/lib/core/experimental/index.mjs @@ -0,0 +1,27 @@ +import { + defineNetwork +} from './define-network.mjs'; +import { NetworkSource } from './sources/network-source.mjs'; +import { InterceptorSource } from './sources/interceptor-source.mjs'; +import { NetworkFrame } from './frames/network-frame.mjs'; +import { + HttpNetworkFrame +} from './frames/http-frame.mjs'; +import { + WebSocketNetworkFrame +} from './frames/websocket-frame.mjs'; +import { + HandlersController, + InMemoryHandlersController +} from './handlers-controller.mjs'; +export { + HandlersController, + HttpNetworkFrame, + InMemoryHandlersController, + InterceptorSource, + NetworkFrame, + NetworkSource, + WebSocketNetworkFrame, + defineNetwork +}; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/node_modules/msw/lib/core/experimental/index.mjs.map b/node_modules/msw/lib/core/experimental/index.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..5a674ba874bb333157620e21f4555f58e5b73bbf --- /dev/null +++ b/node_modules/msw/lib/core/experimental/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/core/experimental/index.ts"],"sourcesContent":["export {\n defineNetwork,\n type DefineNetworkOptions,\n type NetworkApi,\n} from './define-network'\n\n/* Network sources */\nexport { NetworkSource } from './sources/network-source'\nexport { InterceptorSource } from './sources/interceptor-source'\n\n/* Frames */\nexport { NetworkFrame } from './frames/network-frame'\nexport {\n HttpNetworkFrame,\n type HttpNetworkFrameEventMap,\n} from './frames/http-frame'\nexport {\n WebSocketNetworkFrame,\n type WebSocketNetworkFrameEventMap,\n} from './frames/websocket-frame'\n\n/* Handler controllers */\nexport {\n HandlersController,\n InMemoryHandlersController,\n} from './handlers-controller'\n"],"mappings":"AAAA;AAAA,EACE;AAAA,OAGK;AAGP,SAAS,qBAAqB;AAC9B,SAAS,yBAAyB;AAGlC,SAAS,oBAAoB;AAC7B;AAAA,EACE;AAAA,OAEK;AACP;AAAA,EACE;AAAA,OAEK;AAGP;AAAA,EACE;AAAA,EACA;AAAA,OACK;","names":[]} \ No newline at end of file diff --git a/node_modules/msw/lib/core/experimental/on-unhandled-frame.d.mts b/node_modules/msw/lib/core/experimental/on-unhandled-frame.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..3614da9a81122c6329c1d7ba7e43201a586e70dd --- /dev/null +++ b/node_modules/msw/lib/core/experimental/on-unhandled-frame.d.mts @@ -0,0 +1,12 @@ +export { U as UnhandledFrameCallback, d as UnhandledFrameDefaults, b as UnhandledFrameHandle, c as UnhandledFrameStrategy, e as executeUnhandledFrameHandle } from '../on-unhandled-frame-Cr1KOZ0I.mjs'; +import 'rettime'; +import './handlers-controller.mjs'; +import '../HttpResponse-CQwYpuKo.mjs'; +import '@mswjs/interceptors'; +import '../utils/internal/isIterable.mjs'; +import '../typeUtils.mjs'; +import 'graphql'; +import '../utils/matching/matchRequestUrl.mjs'; +import '../handlers/WebSocketHandler.mjs'; +import 'strict-event-emitter'; +import '@mswjs/interceptors/WebSocket'; diff --git a/node_modules/msw/lib/core/experimental/on-unhandled-frame.d.ts b/node_modules/msw/lib/core/experimental/on-unhandled-frame.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..65606e4fff5412f7cbc2696d162223ecdbd0d47b --- /dev/null +++ b/node_modules/msw/lib/core/experimental/on-unhandled-frame.d.ts @@ -0,0 +1,12 @@ +export { U as UnhandledFrameCallback, d as UnhandledFrameDefaults, b as UnhandledFrameHandle, c as UnhandledFrameStrategy, e as executeUnhandledFrameHandle } from '../on-unhandled-frame-BBR-P3kV.js'; +import 'rettime'; +import './handlers-controller.js'; +import '../HttpResponse-BFS34nkx.js'; +import '@mswjs/interceptors'; +import '../utils/internal/isIterable.js'; +import '../typeUtils.js'; +import 'graphql'; +import '../utils/matching/matchRequestUrl.js'; +import '../handlers/WebSocketHandler.js'; +import 'strict-event-emitter'; +import '@mswjs/interceptors/WebSocket'; diff --git a/node_modules/msw/lib/core/experimental/on-unhandled-frame.js b/node_modules/msw/lib/core/experimental/on-unhandled-frame.js new file mode 100644 index 0000000000000000000000000000000000000000..528d3d5f393acb0cacc87d274a055e1d648443f3 --- /dev/null +++ b/node_modules/msw/lib/core/experimental/on-unhandled-frame.js @@ -0,0 +1,91 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var on_unhandled_frame_exports = {}; +__export(on_unhandled_frame_exports, { + executeUnhandledFrameHandle: () => executeUnhandledFrameHandle +}); +module.exports = __toCommonJS(on_unhandled_frame_exports); +var import_outvariant = require("outvariant"); +var import_isCommonAssetRequest = require("../isCommonAssetRequest"); +var import_devUtils = require("../utils/internal/devUtils"); +var import_http_frame = require("./frames/http-frame"); +var import_network_frame = require("./frames/network-frame"); +async function executeUnhandledFrameHandle(frame, handle) { + const printStrategyMessage = async (strategy) => { + if (strategy === "bypass") { + return; + } + const message = await frame.getUnhandledMessage(); + switch (strategy) { + case "warn": { + return import_devUtils.devUtils.warn("Warning: %s", message); + } + case "error": { + return import_devUtils.devUtils.error("Error: %s", message); + } + } + }; + const applyStrategy = async (strategy) => { + import_outvariant.invariant.as( + import_devUtils.InternalError, + strategy === "bypass" || strategy === "warn" || strategy === "error", + /** + * @fixme Rename "onUnhandledRequest" to "onUnhandledFrame" in the error message + * with the next major release. + */ + import_devUtils.devUtils.formatMessage( + 'Failed to react to an unhandled network frame: unknown strategy "%s". Please provide one of the supported strategies ("bypass", "warn", "error") or a custom callback function as the value of the "onUnhandledRequest" option.', + strategy + ) + ); + if (strategy === "bypass") { + return; + } + await printStrategyMessage(strategy); + if (strategy === "error") { + return Promise.reject( + new import_devUtils.InternalError( + import_devUtils.devUtils.formatMessage( + 'Cannot bypass a request when using the "error" strategy for the "onUnhandledRequest" option.' + ) + ) + ); + } + }; + if (typeof handle === "function") { + return handle({ + frame, + defaults: { + warn: printStrategyMessage.bind(null, "warn"), + /** + * @note The defaults only print the corresponding messages now. + * They do not affect the frame resolution (e.g. do not error the frame). + * That is only for backward compatibility reasons. In the future, these should + * be an alias to `applyStrategy.bind(null, 'error')` instead. + */ + error: printStrategyMessage.bind(null, "error") + } + }); + } + if (frame instanceof import_http_frame.HttpNetworkFrame && (0, import_isCommonAssetRequest.isCommonAssetRequest)(frame.data.request)) { + return; + } + return applyStrategy(handle); +} +//# sourceMappingURL=on-unhandled-frame.js.map \ No newline at end of file diff --git a/node_modules/msw/lib/core/experimental/on-unhandled-frame.js.map b/node_modules/msw/lib/core/experimental/on-unhandled-frame.js.map new file mode 100644 index 0000000000000000000000000000000000000000..51a2eabd650b0d879159530adf650bcac9498396 --- /dev/null +++ b/node_modules/msw/lib/core/experimental/on-unhandled-frame.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/core/experimental/on-unhandled-frame.ts"],"sourcesContent":["import { invariant } from 'outvariant'\nimport { isCommonAssetRequest } from '../isCommonAssetRequest'\nimport { devUtils, InternalError } from '../utils/internal/devUtils'\nimport { HttpNetworkFrame } from './frames/http-frame'\nimport { type AnyNetworkFrame } from './frames/network-frame'\n\nexport type UnhandledFrameHandle =\n | UnhandledFrameStrategy\n | UnhandledFrameCallback\n\nexport type UnhandledFrameStrategy = 'bypass' | 'warn' | 'error'\n\nexport type UnhandledFrameCallback = (args: {\n frame: AnyNetworkFrame\n defaults: UnhandledFrameDefaults\n}) => Promise | void\n\nexport type UnhandledFrameDefaults = {\n warn: () => void\n error: () => void\n}\n\nexport async function executeUnhandledFrameHandle(\n frame: AnyNetworkFrame,\n handle: UnhandledFrameHandle,\n): Promise {\n const printStrategyMessage = async (\n strategy: UnhandledFrameStrategy,\n ): Promise => {\n if (strategy === 'bypass') {\n return\n }\n\n const message = await frame.getUnhandledMessage()\n\n switch (strategy) {\n case 'warn': {\n return devUtils.warn('Warning: %s', message)\n }\n\n case 'error': {\n return devUtils.error('Error: %s', message)\n }\n }\n }\n\n const applyStrategy = async (\n strategy: UnhandledFrameStrategy,\n ): Promise => {\n invariant.as(\n InternalError,\n strategy === 'bypass' || strategy === 'warn' || strategy === 'error',\n /**\n * @fixme Rename \"onUnhandledRequest\" to \"onUnhandledFrame\" in the error message\n * with the next major release.\n */\n devUtils.formatMessage(\n 'Failed to react to an unhandled network frame: unknown strategy \"%s\". Please provide one of the supported strategies (\"bypass\", \"warn\", \"error\") or a custom callback function as the value of the \"onUnhandledRequest\" option.',\n strategy,\n ),\n )\n\n if (strategy === 'bypass') {\n return\n }\n\n await printStrategyMessage(strategy)\n\n if (strategy === 'error') {\n return Promise.reject(\n new InternalError(\n devUtils.formatMessage(\n 'Cannot bypass a request when using the \"error\" strategy for the \"onUnhandledRequest\" option.',\n ),\n ),\n )\n }\n }\n\n if (typeof handle === 'function') {\n return handle({\n frame,\n defaults: {\n warn: printStrategyMessage.bind(null, 'warn'),\n /**\n * @note The defaults only print the corresponding messages now.\n * They do not affect the frame resolution (e.g. do not error the frame).\n * That is only for backward compatibility reasons. In the future, these should\n * be an alias to `applyStrategy.bind(null, 'error')` instead.\n */\n error: printStrategyMessage.bind(null, 'error'),\n },\n })\n }\n\n /**\n * Ignore unhandled common HTTP assets.\n * @note Calling this here applies the common assets check\n * only to the scenarios when `onUnhandledFrame` was set to a predefined strategy.\n * When using a custom function, you need to check for common assets manually.\n */\n if (\n frame instanceof HttpNetworkFrame &&\n isCommonAssetRequest(frame.data.request)\n ) {\n return\n }\n\n return applyStrategy(handle)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,wBAA0B;AAC1B,kCAAqC;AACrC,sBAAwC;AACxC,wBAAiC;AACjC,2BAAqC;AAkBrC,eAAsB,4BACpB,OACA,QACe;AACf,QAAM,uBAAuB,OAC3B,aACkB;AAClB,QAAI,aAAa,UAAU;AACzB;AAAA,IACF;AAEA,UAAM,UAAU,MAAM,MAAM,oBAAoB;AAEhD,YAAQ,UAAU;AAAA,MAChB,KAAK,QAAQ;AACX,eAAO,yBAAS,KAAK,eAAe,OAAO;AAAA,MAC7C;AAAA,MAEA,KAAK,SAAS;AACZ,eAAO,yBAAS,MAAM,aAAa,OAAO;AAAA,MAC5C;AAAA,IACF;AAAA,EACF;AAEA,QAAM,gBAAgB,OACpB,aACkB;AAClB,gCAAU;AAAA,MACR;AAAA,MACA,aAAa,YAAY,aAAa,UAAU,aAAa;AAAA;AAAA;AAAA;AAAA;AAAA,MAK7D,yBAAS;AAAA,QACP;AAAA,QACA;AAAA,MACF;AAAA,IACF;AAEA,QAAI,aAAa,UAAU;AACzB;AAAA,IACF;AAEA,UAAM,qBAAqB,QAAQ;AAEnC,QAAI,aAAa,SAAS;AACxB,aAAO,QAAQ;AAAA,QACb,IAAI;AAAA,UACF,yBAAS;AAAA,YACP;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,MAAI,OAAO,WAAW,YAAY;AAChC,WAAO,OAAO;AAAA,MACZ;AAAA,MACA,UAAU;AAAA,QACR,MAAM,qBAAqB,KAAK,MAAM,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,QAO5C,OAAO,qBAAqB,KAAK,MAAM,OAAO;AAAA,MAChD;AAAA,IACF,CAAC;AAAA,EACH;AAQA,MACE,iBAAiB,0CACjB,kDAAqB,MAAM,KAAK,OAAO,GACvC;AACA;AAAA,EACF;AAEA,SAAO,cAAc,MAAM;AAC7B;","names":[]} \ No newline at end of file diff --git a/node_modules/msw/lib/core/experimental/on-unhandled-frame.mjs b/node_modules/msw/lib/core/experimental/on-unhandled-frame.mjs new file mode 100644 index 0000000000000000000000000000000000000000..7ac03a3e6edac5baa0e8fa19d99af722b11ccfa5 --- /dev/null +++ b/node_modules/msw/lib/core/experimental/on-unhandled-frame.mjs @@ -0,0 +1,71 @@ +import { invariant } from "outvariant"; +import { isCommonAssetRequest } from '../isCommonAssetRequest.mjs'; +import { devUtils, InternalError } from '../utils/internal/devUtils.mjs'; +import { HttpNetworkFrame } from './frames/http-frame.mjs'; +import {} from './frames/network-frame.mjs'; +async function executeUnhandledFrameHandle(frame, handle) { + const printStrategyMessage = async (strategy) => { + if (strategy === "bypass") { + return; + } + const message = await frame.getUnhandledMessage(); + switch (strategy) { + case "warn": { + return devUtils.warn("Warning: %s", message); + } + case "error": { + return devUtils.error("Error: %s", message); + } + } + }; + const applyStrategy = async (strategy) => { + invariant.as( + InternalError, + strategy === "bypass" || strategy === "warn" || strategy === "error", + /** + * @fixme Rename "onUnhandledRequest" to "onUnhandledFrame" in the error message + * with the next major release. + */ + devUtils.formatMessage( + 'Failed to react to an unhandled network frame: unknown strategy "%s". Please provide one of the supported strategies ("bypass", "warn", "error") or a custom callback function as the value of the "onUnhandledRequest" option.', + strategy + ) + ); + if (strategy === "bypass") { + return; + } + await printStrategyMessage(strategy); + if (strategy === "error") { + return Promise.reject( + new InternalError( + devUtils.formatMessage( + 'Cannot bypass a request when using the "error" strategy for the "onUnhandledRequest" option.' + ) + ) + ); + } + }; + if (typeof handle === "function") { + return handle({ + frame, + defaults: { + warn: printStrategyMessage.bind(null, "warn"), + /** + * @note The defaults only print the corresponding messages now. + * They do not affect the frame resolution (e.g. do not error the frame). + * That is only for backward compatibility reasons. In the future, these should + * be an alias to `applyStrategy.bind(null, 'error')` instead. + */ + error: printStrategyMessage.bind(null, "error") + } + }); + } + if (frame instanceof HttpNetworkFrame && isCommonAssetRequest(frame.data.request)) { + return; + } + return applyStrategy(handle); +} +export { + executeUnhandledFrameHandle +}; +//# sourceMappingURL=on-unhandled-frame.mjs.map \ No newline at end of file diff --git a/node_modules/msw/lib/core/experimental/on-unhandled-frame.mjs.map b/node_modules/msw/lib/core/experimental/on-unhandled-frame.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..8920a537ed6a2719a8cac173b7d26724dfc5ba95 --- /dev/null +++ b/node_modules/msw/lib/core/experimental/on-unhandled-frame.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/core/experimental/on-unhandled-frame.ts"],"sourcesContent":["import { invariant } from 'outvariant'\nimport { isCommonAssetRequest } from '../isCommonAssetRequest'\nimport { devUtils, InternalError } from '../utils/internal/devUtils'\nimport { HttpNetworkFrame } from './frames/http-frame'\nimport { type AnyNetworkFrame } from './frames/network-frame'\n\nexport type UnhandledFrameHandle =\n | UnhandledFrameStrategy\n | UnhandledFrameCallback\n\nexport type UnhandledFrameStrategy = 'bypass' | 'warn' | 'error'\n\nexport type UnhandledFrameCallback = (args: {\n frame: AnyNetworkFrame\n defaults: UnhandledFrameDefaults\n}) => Promise | void\n\nexport type UnhandledFrameDefaults = {\n warn: () => void\n error: () => void\n}\n\nexport async function executeUnhandledFrameHandle(\n frame: AnyNetworkFrame,\n handle: UnhandledFrameHandle,\n): Promise {\n const printStrategyMessage = async (\n strategy: UnhandledFrameStrategy,\n ): Promise => {\n if (strategy === 'bypass') {\n return\n }\n\n const message = await frame.getUnhandledMessage()\n\n switch (strategy) {\n case 'warn': {\n return devUtils.warn('Warning: %s', message)\n }\n\n case 'error': {\n return devUtils.error('Error: %s', message)\n }\n }\n }\n\n const applyStrategy = async (\n strategy: UnhandledFrameStrategy,\n ): Promise => {\n invariant.as(\n InternalError,\n strategy === 'bypass' || strategy === 'warn' || strategy === 'error',\n /**\n * @fixme Rename \"onUnhandledRequest\" to \"onUnhandledFrame\" in the error message\n * with the next major release.\n */\n devUtils.formatMessage(\n 'Failed to react to an unhandled network frame: unknown strategy \"%s\". Please provide one of the supported strategies (\"bypass\", \"warn\", \"error\") or a custom callback function as the value of the \"onUnhandledRequest\" option.',\n strategy,\n ),\n )\n\n if (strategy === 'bypass') {\n return\n }\n\n await printStrategyMessage(strategy)\n\n if (strategy === 'error') {\n return Promise.reject(\n new InternalError(\n devUtils.formatMessage(\n 'Cannot bypass a request when using the \"error\" strategy for the \"onUnhandledRequest\" option.',\n ),\n ),\n )\n }\n }\n\n if (typeof handle === 'function') {\n return handle({\n frame,\n defaults: {\n warn: printStrategyMessage.bind(null, 'warn'),\n /**\n * @note The defaults only print the corresponding messages now.\n * They do not affect the frame resolution (e.g. do not error the frame).\n * That is only for backward compatibility reasons. In the future, these should\n * be an alias to `applyStrategy.bind(null, 'error')` instead.\n */\n error: printStrategyMessage.bind(null, 'error'),\n },\n })\n }\n\n /**\n * Ignore unhandled common HTTP assets.\n * @note Calling this here applies the common assets check\n * only to the scenarios when `onUnhandledFrame` was set to a predefined strategy.\n * When using a custom function, you need to check for common assets manually.\n */\n if (\n frame instanceof HttpNetworkFrame &&\n isCommonAssetRequest(frame.data.request)\n ) {\n return\n }\n\n return applyStrategy(handle)\n}\n"],"mappings":"AAAA,SAAS,iBAAiB;AAC1B,SAAS,4BAA4B;AACrC,SAAS,UAAU,qBAAqB;AACxC,SAAS,wBAAwB;AACjC,eAAqC;AAkBrC,eAAsB,4BACpB,OACA,QACe;AACf,QAAM,uBAAuB,OAC3B,aACkB;AAClB,QAAI,aAAa,UAAU;AACzB;AAAA,IACF;AAEA,UAAM,UAAU,MAAM,MAAM,oBAAoB;AAEhD,YAAQ,UAAU;AAAA,MAChB,KAAK,QAAQ;AACX,eAAO,SAAS,KAAK,eAAe,OAAO;AAAA,MAC7C;AAAA,MAEA,KAAK,SAAS;AACZ,eAAO,SAAS,MAAM,aAAa,OAAO;AAAA,MAC5C;AAAA,IACF;AAAA,EACF;AAEA,QAAM,gBAAgB,OACpB,aACkB;AAClB,cAAU;AAAA,MACR;AAAA,MACA,aAAa,YAAY,aAAa,UAAU,aAAa;AAAA;AAAA;AAAA;AAAA;AAAA,MAK7D,SAAS;AAAA,QACP;AAAA,QACA;AAAA,MACF;AAAA,IACF;AAEA,QAAI,aAAa,UAAU;AACzB;AAAA,IACF;AAEA,UAAM,qBAAqB,QAAQ;AAEnC,QAAI,aAAa,SAAS;AACxB,aAAO,QAAQ;AAAA,QACb,IAAI;AAAA,UACF,SAAS;AAAA,YACP;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,MAAI,OAAO,WAAW,YAAY;AAChC,WAAO,OAAO;AAAA,MACZ;AAAA,MACA,UAAU;AAAA,QACR,MAAM,qBAAqB,KAAK,MAAM,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,QAO5C,OAAO,qBAAqB,KAAK,MAAM,OAAO;AAAA,MAChD;AAAA,IACF,CAAC;AAAA,EACH;AAQA,MACE,iBAAiB,oBACjB,qBAAqB,MAAM,KAAK,OAAO,GACvC;AACA;AAAA,EACF;AAEA,SAAO,cAAc,MAAM;AAC7B;","names":[]} \ No newline at end of file diff --git a/node_modules/msw/lib/core/experimental/request-utils.d.mts b/node_modules/msw/lib/core/experimental/request-utils.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..c435c1bdf2e7c2c333f49154ebe64bf2a89573b3 --- /dev/null +++ b/node_modules/msw/lib/core/experimental/request-utils.d.mts @@ -0,0 +1,12 @@ +declare const REQUEST_INTENTION_HEADER_NAME = "x-msw-intention"; +declare enum RequestIntention { + passthrough = "passthrough" +} +declare function shouldBypassRequest(request: Request): boolean; +declare function isPassthroughResponse(response: Response): boolean; +/** + * Remove the internal passthrough instruction from the request's `Accept` header. + */ +declare function deleteRequestPassthroughHeader(request: Request): void; + +export { REQUEST_INTENTION_HEADER_NAME, RequestIntention, deleteRequestPassthroughHeader, isPassthroughResponse, shouldBypassRequest }; diff --git a/node_modules/msw/lib/core/experimental/request-utils.d.ts b/node_modules/msw/lib/core/experimental/request-utils.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c435c1bdf2e7c2c333f49154ebe64bf2a89573b3 --- /dev/null +++ b/node_modules/msw/lib/core/experimental/request-utils.d.ts @@ -0,0 +1,12 @@ +declare const REQUEST_INTENTION_HEADER_NAME = "x-msw-intention"; +declare enum RequestIntention { + passthrough = "passthrough" +} +declare function shouldBypassRequest(request: Request): boolean; +declare function isPassthroughResponse(response: Response): boolean; +/** + * Remove the internal passthrough instruction from the request's `Accept` header. + */ +declare function deleteRequestPassthroughHeader(request: Request): void; + +export { REQUEST_INTENTION_HEADER_NAME, RequestIntention, deleteRequestPassthroughHeader, isPassthroughResponse, shouldBypassRequest }; diff --git a/node_modules/msw/lib/core/experimental/request-utils.js b/node_modules/msw/lib/core/experimental/request-utils.js new file mode 100644 index 0000000000000000000000000000000000000000..2af14129e886ee0ffc637b27add01914162bab4f --- /dev/null +++ b/node_modules/msw/lib/core/experimental/request-utils.js @@ -0,0 +1,50 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var request_utils_exports = {}; +__export(request_utils_exports, { + REQUEST_INTENTION_HEADER_NAME: () => REQUEST_INTENTION_HEADER_NAME, + RequestIntention: () => RequestIntention, + deleteRequestPassthroughHeader: () => deleteRequestPassthroughHeader, + isPassthroughResponse: () => isPassthroughResponse, + shouldBypassRequest: () => shouldBypassRequest +}); +module.exports = __toCommonJS(request_utils_exports); +const REQUEST_INTENTION_HEADER_NAME = "x-msw-intention"; +var RequestIntention = /* @__PURE__ */ ((RequestIntention2) => { + RequestIntention2["passthrough"] = "passthrough"; + return RequestIntention2; +})(RequestIntention || {}); +function shouldBypassRequest(request) { + return !!request.headers.get("accept")?.includes("msw/passthrough"); +} +function isPassthroughResponse(response) { + return response.status === 302 && response.headers.get(REQUEST_INTENTION_HEADER_NAME) === "passthrough" /* passthrough */; +} +function deleteRequestPassthroughHeader(request) { + const acceptHeader = request.headers.get("accept"); + if (acceptHeader) { + const nextAcceptHeader = acceptHeader.replace(/(,\s+)?msw\/passthrough/, ""); + if (nextAcceptHeader) { + request.headers.set("accept", nextAcceptHeader); + } else { + request.headers.delete("accept"); + } + } +} +//# sourceMappingURL=request-utils.js.map \ No newline at end of file diff --git a/node_modules/msw/lib/core/experimental/request-utils.js.map b/node_modules/msw/lib/core/experimental/request-utils.js.map new file mode 100644 index 0000000000000000000000000000000000000000..26212ecb21b33b84d1a9e1b5fce401308a74ab65 --- /dev/null +++ b/node_modules/msw/lib/core/experimental/request-utils.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/core/experimental/request-utils.ts"],"sourcesContent":["export const REQUEST_INTENTION_HEADER_NAME = 'x-msw-intention'\n\nexport enum RequestIntention {\n passthrough = 'passthrough',\n}\n\nexport function shouldBypassRequest(request: Request): boolean {\n return !!request.headers.get('accept')?.includes('msw/passthrough')\n}\n\nexport function isPassthroughResponse(response: Response): boolean {\n return (\n response.status === 302 &&\n response.headers.get(REQUEST_INTENTION_HEADER_NAME) ===\n RequestIntention.passthrough\n )\n}\n\n/**\n * Remove the internal passthrough instruction from the request's `Accept` header.\n */\nexport function deleteRequestPassthroughHeader(request: Request): void {\n const acceptHeader = request.headers.get('accept')\n\n /**\n * @note Remove the internal bypass request header.\n * In the browser, this is done by the worker script.\n * In Node.js, it has to be done here.\n */\n if (acceptHeader) {\n const nextAcceptHeader = acceptHeader.replace(/(,\\s+)?msw\\/passthrough/, '')\n\n if (nextAcceptHeader) {\n request.headers.set('accept', nextAcceptHeader)\n } else {\n request.headers.delete('accept')\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAO,MAAM,gCAAgC;AAEtC,IAAK,mBAAL,kBAAKA,sBAAL;AACL,EAAAA,kBAAA,iBAAc;AADJ,SAAAA;AAAA,GAAA;AAIL,SAAS,oBAAoB,SAA2B;AAC7D,SAAO,CAAC,CAAC,QAAQ,QAAQ,IAAI,QAAQ,GAAG,SAAS,iBAAiB;AACpE;AAEO,SAAS,sBAAsB,UAA6B;AACjE,SACE,SAAS,WAAW,OACpB,SAAS,QAAQ,IAAI,6BAA6B,MAChD;AAEN;AAKO,SAAS,+BAA+B,SAAwB;AACrE,QAAM,eAAe,QAAQ,QAAQ,IAAI,QAAQ;AAOjD,MAAI,cAAc;AAChB,UAAM,mBAAmB,aAAa,QAAQ,2BAA2B,EAAE;AAE3E,QAAI,kBAAkB;AACpB,cAAQ,QAAQ,IAAI,UAAU,gBAAgB;AAAA,IAChD,OAAO;AACL,cAAQ,QAAQ,OAAO,QAAQ;AAAA,IACjC;AAAA,EACF;AACF;","names":["RequestIntention"]} \ No newline at end of file diff --git a/node_modules/msw/lib/core/experimental/request-utils.mjs b/node_modules/msw/lib/core/experimental/request-utils.mjs new file mode 100644 index 0000000000000000000000000000000000000000..141497b34d8fdd7fb5054adc274f51bf6b8a2748 --- /dev/null +++ b/node_modules/msw/lib/core/experimental/request-utils.mjs @@ -0,0 +1,30 @@ +const REQUEST_INTENTION_HEADER_NAME = "x-msw-intention"; +var RequestIntention = /* @__PURE__ */ ((RequestIntention2) => { + RequestIntention2["passthrough"] = "passthrough"; + return RequestIntention2; +})(RequestIntention || {}); +function shouldBypassRequest(request) { + return !!request.headers.get("accept")?.includes("msw/passthrough"); +} +function isPassthroughResponse(response) { + return response.status === 302 && response.headers.get(REQUEST_INTENTION_HEADER_NAME) === "passthrough" /* passthrough */; +} +function deleteRequestPassthroughHeader(request) { + const acceptHeader = request.headers.get("accept"); + if (acceptHeader) { + const nextAcceptHeader = acceptHeader.replace(/(,\s+)?msw\/passthrough/, ""); + if (nextAcceptHeader) { + request.headers.set("accept", nextAcceptHeader); + } else { + request.headers.delete("accept"); + } + } +} +export { + REQUEST_INTENTION_HEADER_NAME, + RequestIntention, + deleteRequestPassthroughHeader, + isPassthroughResponse, + shouldBypassRequest +}; +//# sourceMappingURL=request-utils.mjs.map \ No newline at end of file diff --git a/node_modules/msw/lib/core/experimental/request-utils.mjs.map b/node_modules/msw/lib/core/experimental/request-utils.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..c37f3b800d000ec567a45a922698c70d25dd9b05 --- /dev/null +++ b/node_modules/msw/lib/core/experimental/request-utils.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/core/experimental/request-utils.ts"],"sourcesContent":["export const REQUEST_INTENTION_HEADER_NAME = 'x-msw-intention'\n\nexport enum RequestIntention {\n passthrough = 'passthrough',\n}\n\nexport function shouldBypassRequest(request: Request): boolean {\n return !!request.headers.get('accept')?.includes('msw/passthrough')\n}\n\nexport function isPassthroughResponse(response: Response): boolean {\n return (\n response.status === 302 &&\n response.headers.get(REQUEST_INTENTION_HEADER_NAME) ===\n RequestIntention.passthrough\n )\n}\n\n/**\n * Remove the internal passthrough instruction from the request's `Accept` header.\n */\nexport function deleteRequestPassthroughHeader(request: Request): void {\n const acceptHeader = request.headers.get('accept')\n\n /**\n * @note Remove the internal bypass request header.\n * In the browser, this is done by the worker script.\n * In Node.js, it has to be done here.\n */\n if (acceptHeader) {\n const nextAcceptHeader = acceptHeader.replace(/(,\\s+)?msw\\/passthrough/, '')\n\n if (nextAcceptHeader) {\n request.headers.set('accept', nextAcceptHeader)\n } else {\n request.headers.delete('accept')\n }\n }\n}\n"],"mappings":"AAAO,MAAM,gCAAgC;AAEtC,IAAK,mBAAL,kBAAKA,sBAAL;AACL,EAAAA,kBAAA,iBAAc;AADJ,SAAAA;AAAA,GAAA;AAIL,SAAS,oBAAoB,SAA2B;AAC7D,SAAO,CAAC,CAAC,QAAQ,QAAQ,IAAI,QAAQ,GAAG,SAAS,iBAAiB;AACpE;AAEO,SAAS,sBAAsB,UAA6B;AACjE,SACE,SAAS,WAAW,OACpB,SAAS,QAAQ,IAAI,6BAA6B,MAChD;AAEN;AAKO,SAAS,+BAA+B,SAAwB;AACrE,QAAM,eAAe,QAAQ,QAAQ,IAAI,QAAQ;AAOjD,MAAI,cAAc;AAChB,UAAM,mBAAmB,aAAa,QAAQ,2BAA2B,EAAE;AAE3E,QAAI,kBAAkB;AACpB,cAAQ,QAAQ,IAAI,UAAU,gBAAgB;AAAA,IAChD,OAAO;AACL,cAAQ,QAAQ,OAAO,QAAQ;AAAA,IACjC;AAAA,EACF;AACF;","names":["RequestIntention"]} \ No newline at end of file diff --git a/node_modules/msw/lib/core/experimental/setup-api.d.mts b/node_modules/msw/lib/core/experimental/setup-api.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..1610d9a47146423ecb54261b4624b5703917e586 --- /dev/null +++ b/node_modules/msw/lib/core/experimental/setup-api.d.mts @@ -0,0 +1,33 @@ +import { DefaultEventMap, Emitter } from 'rettime'; +import { LifeCycleEventEmitter } from '../sharedOptions.mjs'; +import { HandlersController, AnyHandler } from './handlers-controller.mjs'; +import { Disposable } from '../utils/internal/Disposable.mjs'; +import '../utils/request/onUnhandledRequest.mjs'; +import '../HttpResponse-CQwYpuKo.mjs'; +import '@mswjs/interceptors'; +import '../utils/internal/isIterable.mjs'; +import '../typeUtils.mjs'; +import 'graphql'; +import '../utils/matching/matchRequestUrl.mjs'; +import '../handlers/WebSocketHandler.mjs'; +import 'strict-event-emitter'; +import '@mswjs/interceptors/WebSocket'; + +/** + * Generic class for the mock API setup. + * Preserved only for backward compatibility. + * @deprecated + */ +declare abstract class SetupApi extends Disposable { + protected handlersController: HandlersController; + protected emitter: Emitter; + protected publicEmitter: Emitter; + readonly events: LifeCycleEventEmitter; + constructor(...initialHandlers: Array); + use(...runtimeHandlers: Array): void; + restoreHandlers(): void; + resetHandlers(...nextHandlers: Array): void; + listHandlers(): ReadonlyArray; +} + +export { SetupApi }; diff --git a/node_modules/msw/lib/core/experimental/setup-api.d.ts b/node_modules/msw/lib/core/experimental/setup-api.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4b3efa08639efb9cf6d4da7790dd5910b473c88b --- /dev/null +++ b/node_modules/msw/lib/core/experimental/setup-api.d.ts @@ -0,0 +1,33 @@ +import { DefaultEventMap, Emitter } from 'rettime'; +import { LifeCycleEventEmitter } from '../sharedOptions.js'; +import { HandlersController, AnyHandler } from './handlers-controller.js'; +import { Disposable } from '../utils/internal/Disposable.js'; +import '../utils/request/onUnhandledRequest.js'; +import '../HttpResponse-BFS34nkx.js'; +import '@mswjs/interceptors'; +import '../utils/internal/isIterable.js'; +import '../typeUtils.js'; +import 'graphql'; +import '../utils/matching/matchRequestUrl.js'; +import '../handlers/WebSocketHandler.js'; +import 'strict-event-emitter'; +import '@mswjs/interceptors/WebSocket'; + +/** + * Generic class for the mock API setup. + * Preserved only for backward compatibility. + * @deprecated + */ +declare abstract class SetupApi extends Disposable { + protected handlersController: HandlersController; + protected emitter: Emitter; + protected publicEmitter: Emitter; + readonly events: LifeCycleEventEmitter; + constructor(...initialHandlers: Array); + use(...runtimeHandlers: Array): void; + restoreHandlers(): void; + resetHandlers(...nextHandlers: Array): void; + listHandlers(): ReadonlyArray; +} + +export { SetupApi }; diff --git a/node_modules/msw/lib/core/experimental/setup-api.js b/node_modules/msw/lib/core/experimental/setup-api.js new file mode 100644 index 0000000000000000000000000000000000000000..cb284ef6404e3fd8ade437fb3b2be2c0f1c45b4d --- /dev/null +++ b/node_modules/msw/lib/core/experimental/setup-api.js @@ -0,0 +1,58 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var setup_api_exports = {}; +__export(setup_api_exports, { + SetupApi: () => SetupApi +}); +module.exports = __toCommonJS(setup_api_exports); +var import_rettime = require("rettime"); +var import_sharedOptions = require("../sharedOptions"); +var import_handlers_controller = require("./handlers-controller"); +var import_Disposable = require("../utils/internal/Disposable"); +var import_toReadonlyArray = require("../utils/internal/toReadonlyArray"); +class SetupApi extends import_Disposable.Disposable { + handlersController; + emitter; + publicEmitter; + events; + constructor(...initialHandlers) { + super(); + this.handlersController = new import_handlers_controller.InMemoryHandlersController(initialHandlers); + this.emitter = new import_rettime.Emitter(); + this.publicEmitter = new import_rettime.Emitter(); + this.events = this.emitter; + this.subscriptions.push(() => { + this.emitter.removeAllListeners(); + this.publicEmitter.removeAllListeners(); + }); + } + use(...runtimeHandlers) { + this.handlersController.use(runtimeHandlers); + } + restoreHandlers() { + this.handlersController.restore(); + } + resetHandlers(...nextHandlers) { + this.handlersController.reset(nextHandlers); + } + listHandlers() { + return (0, import_toReadonlyArray.toReadonlyArray)(this.handlersController.currentHandlers()); + } +} +//# sourceMappingURL=setup-api.js.map \ No newline at end of file diff --git a/node_modules/msw/lib/core/experimental/setup-api.js.map b/node_modules/msw/lib/core/experimental/setup-api.js.map new file mode 100644 index 0000000000000000000000000000000000000000..8822515ef21f65e151afae4f6f3010d94817f7fa --- /dev/null +++ b/node_modules/msw/lib/core/experimental/setup-api.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/core/experimental/setup-api.ts"],"sourcesContent":["import { type DefaultEventMap, Emitter } from 'rettime'\nimport { type LifeCycleEventEmitter } from '../sharedOptions'\nimport type { HandlersController } from './handlers-controller'\nimport {\n InMemoryHandlersController,\n type AnyHandler,\n} from './handlers-controller'\nimport { Disposable } from '../utils/internal/Disposable'\nimport { toReadonlyArray } from '../utils/internal/toReadonlyArray'\n\n/**\n * Generic class for the mock API setup.\n * Preserved only for backward compatibility.\n * @deprecated\n */\nexport abstract class SetupApi<\n EventMap extends DefaultEventMap,\n> extends Disposable {\n protected handlersController: HandlersController\n protected emitter: Emitter\n protected publicEmitter: Emitter\n\n public readonly events: LifeCycleEventEmitter\n\n constructor(...initialHandlers: Array) {\n super()\n\n this.handlersController = new InMemoryHandlersController(initialHandlers)\n\n this.emitter = new Emitter()\n this.publicEmitter = new Emitter()\n this.events = this.emitter\n\n this.subscriptions.push(() => {\n this.emitter.removeAllListeners()\n this.publicEmitter.removeAllListeners()\n })\n }\n\n public use(...runtimeHandlers: Array): void {\n this.handlersController.use(runtimeHandlers)\n }\n\n public restoreHandlers(): void {\n this.handlersController.restore()\n }\n\n public resetHandlers(...nextHandlers: Array): void {\n this.handlersController.reset(nextHandlers)\n }\n\n public listHandlers(): ReadonlyArray {\n return toReadonlyArray(this.handlersController.currentHandlers())\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,qBAA8C;AAC9C,2BAA2C;AAE3C,iCAGO;AACP,wBAA2B;AAC3B,6BAAgC;AAOzB,MAAe,iBAEZ,6BAAW;AAAA,EACT;AAAA,EACA;AAAA,EACA;AAAA,EAEM;AAAA,EAEhB,eAAe,iBAAoC;AACjD,UAAM;AAEN,SAAK,qBAAqB,IAAI,sDAA2B,eAAe;AAExE,SAAK,UAAU,IAAI,uBAAQ;AAC3B,SAAK,gBAAgB,IAAI,uBAAQ;AACjC,SAAK,SAAS,KAAK;AAEnB,SAAK,cAAc,KAAK,MAAM;AAC5B,WAAK,QAAQ,mBAAmB;AAChC,WAAK,cAAc,mBAAmB;AAAA,IACxC,CAAC;AAAA,EACH;AAAA,EAEO,OAAO,iBAA0C;AACtD,SAAK,mBAAmB,IAAI,eAAe;AAAA,EAC7C;AAAA,EAEO,kBAAwB;AAC7B,SAAK,mBAAmB,QAAQ;AAAA,EAClC;AAAA,EAEO,iBAAiB,cAAuC;AAC7D,SAAK,mBAAmB,MAAM,YAAY;AAAA,EAC5C;AAAA,EAEO,eAA0C;AAC/C,eAAO,wCAAgB,KAAK,mBAAmB,gBAAgB,CAAC;AAAA,EAClE;AACF;","names":[]} \ No newline at end of file diff --git a/node_modules/msw/lib/core/experimental/setup-api.mjs b/node_modules/msw/lib/core/experimental/setup-api.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c88b1aea5c0cacd9280727f3cca7dc3f985a5b48 --- /dev/null +++ b/node_modules/msw/lib/core/experimental/setup-api.mjs @@ -0,0 +1,40 @@ +import { Emitter } from "rettime"; +import {} from '../sharedOptions.mjs'; +import { + InMemoryHandlersController +} from './handlers-controller.mjs'; +import { Disposable } from '../utils/internal/Disposable.mjs'; +import { toReadonlyArray } from '../utils/internal/toReadonlyArray.mjs'; +class SetupApi extends Disposable { + handlersController; + emitter; + publicEmitter; + events; + constructor(...initialHandlers) { + super(); + this.handlersController = new InMemoryHandlersController(initialHandlers); + this.emitter = new Emitter(); + this.publicEmitter = new Emitter(); + this.events = this.emitter; + this.subscriptions.push(() => { + this.emitter.removeAllListeners(); + this.publicEmitter.removeAllListeners(); + }); + } + use(...runtimeHandlers) { + this.handlersController.use(runtimeHandlers); + } + restoreHandlers() { + this.handlersController.restore(); + } + resetHandlers(...nextHandlers) { + this.handlersController.reset(nextHandlers); + } + listHandlers() { + return toReadonlyArray(this.handlersController.currentHandlers()); + } +} +export { + SetupApi +}; +//# sourceMappingURL=setup-api.mjs.map \ No newline at end of file diff --git a/node_modules/msw/lib/core/experimental/setup-api.mjs.map b/node_modules/msw/lib/core/experimental/setup-api.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..e27f6624074b5367c9f459ea168fff64e0347070 --- /dev/null +++ b/node_modules/msw/lib/core/experimental/setup-api.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/core/experimental/setup-api.ts"],"sourcesContent":["import { type DefaultEventMap, Emitter } from 'rettime'\nimport { type LifeCycleEventEmitter } from '../sharedOptions'\nimport type { HandlersController } from './handlers-controller'\nimport {\n InMemoryHandlersController,\n type AnyHandler,\n} from './handlers-controller'\nimport { Disposable } from '../utils/internal/Disposable'\nimport { toReadonlyArray } from '../utils/internal/toReadonlyArray'\n\n/**\n * Generic class for the mock API setup.\n * Preserved only for backward compatibility.\n * @deprecated\n */\nexport abstract class SetupApi<\n EventMap extends DefaultEventMap,\n> extends Disposable {\n protected handlersController: HandlersController\n protected emitter: Emitter\n protected publicEmitter: Emitter\n\n public readonly events: LifeCycleEventEmitter\n\n constructor(...initialHandlers: Array) {\n super()\n\n this.handlersController = new InMemoryHandlersController(initialHandlers)\n\n this.emitter = new Emitter()\n this.publicEmitter = new Emitter()\n this.events = this.emitter\n\n this.subscriptions.push(() => {\n this.emitter.removeAllListeners()\n this.publicEmitter.removeAllListeners()\n })\n }\n\n public use(...runtimeHandlers: Array): void {\n this.handlersController.use(runtimeHandlers)\n }\n\n public restoreHandlers(): void {\n this.handlersController.restore()\n }\n\n public resetHandlers(...nextHandlers: Array): void {\n this.handlersController.reset(nextHandlers)\n }\n\n public listHandlers(): ReadonlyArray {\n return toReadonlyArray(this.handlersController.currentHandlers())\n }\n}\n"],"mappings":"AAAA,SAA+B,eAAe;AAC9C,eAA2C;AAE3C;AAAA,EACE;AAAA,OAEK;AACP,SAAS,kBAAkB;AAC3B,SAAS,uBAAuB;AAOzB,MAAe,iBAEZ,WAAW;AAAA,EACT;AAAA,EACA;AAAA,EACA;AAAA,EAEM;AAAA,EAEhB,eAAe,iBAAoC;AACjD,UAAM;AAEN,SAAK,qBAAqB,IAAI,2BAA2B,eAAe;AAExE,SAAK,UAAU,IAAI,QAAQ;AAC3B,SAAK,gBAAgB,IAAI,QAAQ;AACjC,SAAK,SAAS,KAAK;AAEnB,SAAK,cAAc,KAAK,MAAM;AAC5B,WAAK,QAAQ,mBAAmB;AAChC,WAAK,cAAc,mBAAmB;AAAA,IACxC,CAAC;AAAA,EACH;AAAA,EAEO,OAAO,iBAA0C;AACtD,SAAK,mBAAmB,IAAI,eAAe;AAAA,EAC7C;AAAA,EAEO,kBAAwB;AAC7B,SAAK,mBAAmB,QAAQ;AAAA,EAClC;AAAA,EAEO,iBAAiB,cAAuC;AAC7D,SAAK,mBAAmB,MAAM,YAAY;AAAA,EAC5C;AAAA,EAEO,eAA0C;AAC/C,WAAO,gBAAgB,KAAK,mBAAmB,gBAAgB,CAAC;AAAA,EAClE;AACF;","names":[]} \ No newline at end of file diff --git a/node_modules/msw/lib/core/experimental/sources/interceptor-source.d.mts b/node_modules/msw/lib/core/experimental/sources/interceptor-source.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..427bd1ae7ebf2ed6f458299583f842012822eb9f --- /dev/null +++ b/node_modules/msw/lib/core/experimental/sources/interceptor-source.d.mts @@ -0,0 +1,28 @@ +import { Interceptor, HttpRequestEventMap } from '@mswjs/interceptors'; +import { WebSocketEventMap } from '@mswjs/interceptors/WebSocket'; +import { NetworkSource } from './network-source.mjs'; +import 'rettime'; +import '../../on-unhandled-frame-Cr1KOZ0I.mjs'; +import '../handlers-controller.mjs'; +import '../../HttpResponse-CQwYpuKo.mjs'; +import '../../utils/internal/isIterable.mjs'; +import '../../typeUtils.mjs'; +import 'graphql'; +import '../../utils/matching/matchRequestUrl.mjs'; +import '../../handlers/WebSocketHandler.mjs'; +import 'strict-event-emitter'; + +interface InterceptorSourceOptions { + interceptors: Array>; +} +/** + * Create a network source from the given list of interceptors. + */ +declare class InterceptorSource extends NetworkSource { + #private; + constructor(options: InterceptorSourceOptions); + enable(): void; + disable(): void; +} + +export { InterceptorSource, type InterceptorSourceOptions }; diff --git a/node_modules/msw/lib/core/experimental/sources/interceptor-source.d.ts b/node_modules/msw/lib/core/experimental/sources/interceptor-source.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3d46ea6f2df19c97c3bb3e173df94d066327c652 --- /dev/null +++ b/node_modules/msw/lib/core/experimental/sources/interceptor-source.d.ts @@ -0,0 +1,28 @@ +import { Interceptor, HttpRequestEventMap } from '@mswjs/interceptors'; +import { WebSocketEventMap } from '@mswjs/interceptors/WebSocket'; +import { NetworkSource } from './network-source.js'; +import 'rettime'; +import '../../on-unhandled-frame-BBR-P3kV.js'; +import '../handlers-controller.js'; +import '../../HttpResponse-BFS34nkx.js'; +import '../../utils/internal/isIterable.js'; +import '../../typeUtils.js'; +import 'graphql'; +import '../../utils/matching/matchRequestUrl.js'; +import '../../handlers/WebSocketHandler.js'; +import 'strict-event-emitter'; + +interface InterceptorSourceOptions { + interceptors: Array>; +} +/** + * Create a network source from the given list of interceptors. + */ +declare class InterceptorSource extends NetworkSource { + #private; + constructor(options: InterceptorSourceOptions); + enable(): void; + disable(): void; +} + +export { InterceptorSource, type InterceptorSourceOptions }; diff --git a/node_modules/msw/lib/core/experimental/sources/interceptor-source.js b/node_modules/msw/lib/core/experimental/sources/interceptor-source.js new file mode 100644 index 0000000000000000000000000000000000000000..26c43326c93a4357173b1e58379cb59e53ad41ce --- /dev/null +++ b/node_modules/msw/lib/core/experimental/sources/interceptor-source.js @@ -0,0 +1,155 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var interceptor_source_exports = {}; +__export(interceptor_source_exports, { + InterceptorSource: () => InterceptorSource +}); +module.exports = __toCommonJS(interceptor_source_exports); +var import_interceptors = require("@mswjs/interceptors"); +var import_network_source = require("./network-source"); +var import_devUtils = require("../../utils/internal/devUtils"); +var import_http_frame = require("../frames/http-frame"); +var import_websocket_frame = require("../frames/websocket-frame"); +var import_request_utils = require("../request-utils"); +class InterceptorSource extends import_network_source.NetworkSource { + #interceptor; + #frames; + constructor(options) { + super(); + this.#interceptor = new import_interceptors.BatchInterceptor({ + name: "interceptor-source", + interceptors: options.interceptors + }); + this.#frames = /* @__PURE__ */ new Map(); + } + enable() { + this.#interceptor.apply(); + this.#interceptor.on("request", this.#handleRequest.bind(this)).on("response", this.#handleResponse.bind(this)).on("connection", this.#handleWebSocketConnection.bind(this)); + } + disable() { + super.disable(); + this.#interceptor.dispose(); + this.#frames.clear(); + } + async #handleRequest({ + requestId, + request, + controller + }) { + const httpFrame = new InterceptorHttpNetworkFrame({ + id: requestId, + request, + controller + }); + this.#frames.set(requestId, httpFrame); + await this.queue(httpFrame); + } + async #handleResponse({ + requestId, + request, + response, + isMockedResponse + }) { + const httpFrame = this.#frames.get(requestId); + this.#frames.delete(requestId); + if (httpFrame == null) { + return; + } + queueMicrotask(() => { + try { + httpFrame.events.emit( + new import_http_frame.ResponseEvent( + isMockedResponse ? "response:mocked" : "response:bypass", + { + requestId, + request, + response + } + ) + ); + } finally { + httpFrame.events.removeAllListeners(); + } + }); + } + async #handleWebSocketConnection(connection) { + await this.queue( + new InterceptorWebSocketNetworkFrame({ + connection + }) + ); + } +} +class InterceptorHttpNetworkFrame extends import_http_frame.HttpNetworkFrame { + #controller; + constructor(options) { + super({ + id: options.id, + request: options.request + }); + this.#controller = options.controller; + } + passthrough() { + (0, import_request_utils.deleteRequestPassthroughHeader)(this.data.request); + } + respondWith(response) { + if (response) { + this.#controller.respondWith(response); + } + } + errorWith(reason) { + if (reason instanceof Response) { + return this.respondWith(reason); + } + if (reason instanceof import_devUtils.InternalError) { + this.#controller.errorWith(reason); + } + throw reason; + } +} +class InterceptorWebSocketNetworkFrame extends import_websocket_frame.WebSocketNetworkFrame { + constructor(args) { + super({ connection: args.connection }); + args.connection.client.addEventListener( + "close", + () => { + this.events.removeAllListeners(); + }, + { + once: true + } + ); + } + errorWith(reason) { + if (reason instanceof Error) { + const { client } = this.data.connection; + const errorEvent = new Event("error"); + Object.defineProperty(errorEvent, "cause", { + enumerable: true, + configurable: false, + value: reason + }); + client.socket.dispatchEvent(errorEvent); + } + } + passthrough() { + this.data.connection.server.connect(); + } +} +//# sourceMappingURL=interceptor-source.js.map \ No newline at end of file diff --git a/node_modules/msw/lib/core/experimental/sources/interceptor-source.js.map b/node_modules/msw/lib/core/experimental/sources/interceptor-source.js.map new file mode 100644 index 0000000000000000000000000000000000000000..4e4aba5e97c2096b805943205a082e61353dd34f --- /dev/null +++ b/node_modules/msw/lib/core/experimental/sources/interceptor-source.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/core/experimental/sources/interceptor-source.ts"],"sourcesContent":["import type { Interceptor, RequestController } from '@mswjs/interceptors'\nimport { BatchInterceptor, type HttpRequestEventMap } from '@mswjs/interceptors'\nimport type {\n WebSocketConnectionData,\n WebSocketEventMap,\n} from '@mswjs/interceptors/WebSocket'\nimport { NetworkSource } from './network-source'\nimport { InternalError } from '../../utils/internal/devUtils'\nimport { HttpNetworkFrame, ResponseEvent } from '../frames/http-frame'\nimport { WebSocketNetworkFrame } from '../frames/websocket-frame'\nimport { deleteRequestPassthroughHeader } from '../request-utils'\n\nexport interface InterceptorSourceOptions {\n interceptors: Array>\n}\n\n/**\n * Create a network source from the given list of interceptors.\n */\nexport class InterceptorSource extends NetworkSource {\n #interceptor: BatchInterceptor<\n InterceptorSourceOptions['interceptors'],\n HttpRequestEventMap | WebSocketEventMap\n >\n\n #frames: Map\n\n constructor(options: InterceptorSourceOptions) {\n super()\n\n this.#interceptor = new BatchInterceptor({\n name: 'interceptor-source',\n interceptors: options.interceptors,\n })\n this.#frames = new Map()\n }\n\n public enable(): void {\n this.#interceptor.apply()\n\n /**\n * @todo @fixme BatchInterceptor infers event types but not listener types.\n */\n this.#interceptor\n .on('request', this.#handleRequest.bind(this) as any)\n .on('response', this.#handleResponse.bind(this) as any)\n .on('connection', this.#handleWebSocketConnection.bind(this) as any)\n }\n\n public disable(): void {\n super.disable()\n this.#interceptor.dispose()\n\n /**\n * @todo We can also abort any pending frames here, given we implement\n * the `NetworkFrame.abort()` method.\n */\n this.#frames.clear()\n }\n\n async #handleRequest({\n requestId,\n request,\n controller,\n }: HttpRequestEventMap['request'][0]): Promise {\n const httpFrame = new InterceptorHttpNetworkFrame({\n id: requestId,\n request,\n controller,\n })\n\n this.#frames.set(requestId, httpFrame)\n await this.queue(httpFrame)\n }\n\n async #handleResponse({\n requestId,\n request,\n response,\n isMockedResponse,\n }: HttpRequestEventMap['response'][0]): Promise {\n const httpFrame = this.#frames.get(requestId)\n this.#frames.delete(requestId)\n\n if (httpFrame == null) {\n return\n }\n\n queueMicrotask(() => {\n try {\n httpFrame.events.emit(\n new ResponseEvent(\n isMockedResponse ? 'response:mocked' : 'response:bypass',\n {\n requestId,\n request,\n response,\n },\n ),\n )\n } finally {\n /**\n * @note Remove any listeners from this frame.\n * Past this point, it won't emit anything. The removal is crucial\n * to prevent \"rettime\" from keeping the abort cleanup listeners internally.\n * @see https://github.com/mswjs/msw/issues/2735\n */\n httpFrame.events.removeAllListeners()\n }\n })\n }\n\n async #handleWebSocketConnection(\n connection: WebSocketEventMap['connection'][0],\n ): Promise {\n await this.queue(\n new InterceptorWebSocketNetworkFrame({\n connection,\n }),\n )\n }\n}\n\nclass InterceptorHttpNetworkFrame extends HttpNetworkFrame {\n #controller: RequestController\n\n constructor(options: {\n id: string\n request: Request\n controller: RequestController\n }) {\n super({\n id: options.id,\n request: options.request,\n })\n\n this.#controller = options.controller\n }\n\n public passthrough(): void {\n deleteRequestPassthroughHeader(this.data.request)\n }\n\n public respondWith(response?: Response): void {\n if (response) {\n this.#controller.respondWith(response)\n }\n }\n\n public errorWith(reason?: unknown): void {\n if (reason instanceof Response) {\n return this.respondWith(reason)\n }\n\n if (reason instanceof InternalError) {\n this.#controller.errorWith(reason)\n }\n\n throw reason\n }\n}\n\nclass InterceptorWebSocketNetworkFrame extends WebSocketNetworkFrame {\n constructor(args: { connection: WebSocketConnectionData }) {\n super({ connection: args.connection })\n\n /**\n * @note Provide a similar frame listener cleanup as for HTTP.\n * When the client connection closes, the handler can no longer be used.\n */\n args.connection.client.addEventListener(\n 'close',\n () => {\n this.events.removeAllListeners()\n },\n {\n once: true,\n },\n )\n }\n\n public errorWith(reason?: unknown): void {\n if (reason instanceof Error) {\n const { client } = this.data.connection\n\n /**\n * Use `client.errorWith(reason)` in the future.\n * @see https://github.com/mswjs/interceptors/issues/747\n */\n const errorEvent = new Event('error')\n\n Object.defineProperty(errorEvent, 'cause', {\n enumerable: true,\n configurable: false,\n value: reason,\n })\n\n client.socket.dispatchEvent(errorEvent)\n }\n }\n\n public passthrough() {\n this.data.connection.server.connect()\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,0BAA2D;AAK3D,4BAA8B;AAC9B,sBAA8B;AAC9B,wBAAgD;AAChD,6BAAsC;AACtC,2BAA+C;AASxC,MAAM,0BAA0B,oCAAc;AAAA,EACnD;AAAA,EAKA;AAAA,EAEA,YAAY,SAAmC;AAC7C,UAAM;AAEN,SAAK,eAAe,IAAI,qCAAiB;AAAA,MACvC,MAAM;AAAA,MACN,cAAc,QAAQ;AAAA,IACxB,CAAC;AACD,SAAK,UAAU,oBAAI,IAAI;AAAA,EACzB;AAAA,EAEO,SAAe;AACpB,SAAK,aAAa,MAAM;AAKxB,SAAK,aACF,GAAG,WAAW,KAAK,eAAe,KAAK,IAAI,CAAQ,EACnD,GAAG,YAAY,KAAK,gBAAgB,KAAK,IAAI,CAAQ,EACrD,GAAG,cAAc,KAAK,2BAA2B,KAAK,IAAI,CAAQ;AAAA,EACvE;A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AAK,YAAY,YAAY,QAAQ;AAAA,IACvC;AAAA,EACF;AAAA,EAEO,UAAU,QAAwB;AACvC,QAAI,kBAAkB,UAAU;AAC9B,aAAO,KAAK,YAAY,MAAM;AAAA,IAChC;AAEA,QAAI,kBAAkB,+BAAe;AACnC,WAAK,YAAY,UAAU,MAAM;AAAA,IACnC;AAEA,UAAM;AAAA,EACR;AACF;AAEA,MAAM,yCAAyC,6CAAsB;AAAA,EACnE,YAAY,MAA+C;AACzD,UAAM,EAAE,YAAY,KAAK,WAAW,CAAC;AAMrC,SAAK,WAAW,OAAO;AAAA,MACrB;AAAA,MACA,MAAM;AACJ,aAAK,OAAO,mBAAmB;AAAA,MACjC;AAAA,MACA;AAAA,QACE,MAAM;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAAA,EAEO,UAAU,QAAwB;AACvC,QAAI,kBAAkB,OAAO;AAC3B,YAAM,EAAE,OAAO,IAAI,KAAK,KAAK;AAM7B,YAAM,aAAa,IAAI,MAAM,OAAO;AAEpC,aAAO,eAAe,YAAY,SAAS;AAAA,QACzC,YAAY;AAAA,QACZ,cAAc;AAAA,QACd,OAAO;AAAA,MACT,CAAC;AAED,aAAO,OAAO,cAAc,UAAU;AAAA,IACxC;AAAA,EACF;AAAA,EAEO,cAAc;AACnB,SAAK,KAAK,WAAW,OAAO,QAAQ;AAAA,EACtC;AACF;","names":[]} \ No newline at end of file diff --git a/node_modules/msw/lib/core/experimental/sources/interceptor-source.mjs b/node_modules/msw/lib/core/experimental/sources/interceptor-source.mjs new file mode 100644 index 0000000000000000000000000000000000000000..f44fa2e7619e9003bda0a55ebaf856aea09ddb06 --- /dev/null +++ b/node_modules/msw/lib/core/experimental/sources/interceptor-source.mjs @@ -0,0 +1,135 @@ +import { BatchInterceptor } from "@mswjs/interceptors"; +import { NetworkSource } from './network-source.mjs'; +import { InternalError } from '../../utils/internal/devUtils.mjs'; +import { HttpNetworkFrame, ResponseEvent } from '../frames/http-frame.mjs'; +import { WebSocketNetworkFrame } from '../frames/websocket-frame.mjs'; +import { deleteRequestPassthroughHeader } from '../request-utils.mjs'; +class InterceptorSource extends NetworkSource { + #interceptor; + #frames; + constructor(options) { + super(); + this.#interceptor = new BatchInterceptor({ + name: "interceptor-source", + interceptors: options.interceptors + }); + this.#frames = /* @__PURE__ */ new Map(); + } + enable() { + this.#interceptor.apply(); + this.#interceptor.on("request", this.#handleRequest.bind(this)).on("response", this.#handleResponse.bind(this)).on("connection", this.#handleWebSocketConnection.bind(this)); + } + disable() { + super.disable(); + this.#interceptor.dispose(); + this.#frames.clear(); + } + async #handleRequest({ + requestId, + request, + controller + }) { + const httpFrame = new InterceptorHttpNetworkFrame({ + id: requestId, + request, + controller + }); + this.#frames.set(requestId, httpFrame); + await this.queue(httpFrame); + } + async #handleResponse({ + requestId, + request, + response, + isMockedResponse + }) { + const httpFrame = this.#frames.get(requestId); + this.#frames.delete(requestId); + if (httpFrame == null) { + return; + } + queueMicrotask(() => { + try { + httpFrame.events.emit( + new ResponseEvent( + isMockedResponse ? "response:mocked" : "response:bypass", + { + requestId, + request, + response + } + ) + ); + } finally { + httpFrame.events.removeAllListeners(); + } + }); + } + async #handleWebSocketConnection(connection) { + await this.queue( + new InterceptorWebSocketNetworkFrame({ + connection + }) + ); + } +} +class InterceptorHttpNetworkFrame extends HttpNetworkFrame { + #controller; + constructor(options) { + super({ + id: options.id, + request: options.request + }); + this.#controller = options.controller; + } + passthrough() { + deleteRequestPassthroughHeader(this.data.request); + } + respondWith(response) { + if (response) { + this.#controller.respondWith(response); + } + } + errorWith(reason) { + if (reason instanceof Response) { + return this.respondWith(reason); + } + if (reason instanceof InternalError) { + this.#controller.errorWith(reason); + } + throw reason; + } +} +class InterceptorWebSocketNetworkFrame extends WebSocketNetworkFrame { + constructor(args) { + super({ connection: args.connection }); + args.connection.client.addEventListener( + "close", + () => { + this.events.removeAllListeners(); + }, + { + once: true + } + ); + } + errorWith(reason) { + if (reason instanceof Error) { + const { client } = this.data.connection; + const errorEvent = new Event("error"); + Object.defineProperty(errorEvent, "cause", { + enumerable: true, + configurable: false, + value: reason + }); + client.socket.dispatchEvent(errorEvent); + } + } + passthrough() { + this.data.connection.server.connect(); + } +} +export { + InterceptorSource +}; +//# sourceMappingURL=interceptor-source.mjs.map \ No newline at end of file diff --git a/node_modules/msw/lib/core/experimental/sources/interceptor-source.mjs.map b/node_modules/msw/lib/core/experimental/sources/interceptor-source.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..048a86ce9032db5192ffc4b146d47f9c7064bd84 --- /dev/null +++ b/node_modules/msw/lib/core/experimental/sources/interceptor-source.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/core/experimental/sources/interceptor-source.ts"],"sourcesContent":["import type { Interceptor, RequestController } from '@mswjs/interceptors'\nimport { BatchInterceptor, type HttpRequestEventMap } from '@mswjs/interceptors'\nimport type {\n WebSocketConnectionData,\n WebSocketEventMap,\n} from '@mswjs/interceptors/WebSocket'\nimport { NetworkSource } from './network-source'\nimport { InternalError } from '../../utils/internal/devUtils'\nimport { HttpNetworkFrame, ResponseEvent } from '../frames/http-frame'\nimport { WebSocketNetworkFrame } from '../frames/websocket-frame'\nimport { deleteRequestPassthroughHeader } from '../request-utils'\n\nexport interface InterceptorSourceOptions {\n interceptors: Array>\n}\n\n/**\n * Create a network source from the given list of interceptors.\n */\nexport class InterceptorSource extends NetworkSource {\n #interceptor: BatchInterceptor<\n InterceptorSourceOptions['interceptors'],\n HttpRequestEventMap | WebSocketEventMap\n >\n\n #frames: Map\n\n constructor(options: InterceptorSourceOptions) {\n super()\n\n this.#interceptor = new BatchInterceptor({\n name: 'interceptor-source',\n interceptors: options.interceptors,\n })\n this.#frames = new Map()\n }\n\n public enable(): void {\n this.#interceptor.apply()\n\n /**\n * @todo @fixme BatchInterceptor infers event types but not listener types.\n */\n this.#interceptor\n .on('request', this.#handleRequest.bind(this) as any)\n .on('response', this.#handleResponse.bind(this) as any)\n .on('connection', this.#handleWebSocketConnection.bind(this) as any)\n }\n\n public disable(): void {\n super.disable()\n this.#interceptor.dispose()\n\n /**\n * @todo We can also abort any pending frames here, given we implement\n * the `NetworkFrame.abort()` method.\n */\n this.#frames.clear()\n }\n\n async #handleRequest({\n requestId,\n request,\n controller,\n }: HttpRequestEventMap['request'][0]): Promise {\n const httpFrame = new InterceptorHttpNetworkFrame({\n id: requestId,\n request,\n controller,\n })\n\n this.#frames.set(requestId, httpFrame)\n await this.queue(httpFrame)\n }\n\n async #handleResponse({\n requestId,\n request,\n response,\n isMockedResponse,\n }: HttpRequestEventMap['response'][0]): Promise {\n const httpFrame = this.#frames.get(requestId)\n this.#frames.delete(requestId)\n\n if (httpFrame == null) {\n return\n }\n\n queueMicrotask(() => {\n try {\n httpFrame.events.emit(\n new ResponseEvent(\n isMockedResponse ? 'response:mocked' : 'response:bypass',\n {\n requestId,\n request,\n response,\n },\n ),\n )\n } finally {\n /**\n * @note Remove any listeners from this frame.\n * Past this point, it won't emit anything. The removal is crucial\n * to prevent \"rettime\" from keeping the abort cleanup listeners internally.\n * @see https://github.com/mswjs/msw/issues/2735\n */\n httpFrame.events.removeAllListeners()\n }\n })\n }\n\n async #handleWebSocketConnection(\n connection: WebSocketEventMap['connection'][0],\n ): Promise {\n await this.queue(\n new InterceptorWebSocketNetworkFrame({\n connection,\n }),\n )\n }\n}\n\nclass InterceptorHttpNetworkFrame extends HttpNetworkFrame {\n #controller: RequestController\n\n constructor(options: {\n id: string\n request: Request\n controller: RequestController\n }) {\n super({\n id: options.id,\n request: options.request,\n })\n\n this.#controller = options.controller\n }\n\n public passthrough(): void {\n deleteRequestPassthroughHeader(this.data.request)\n }\n\n public respondWith(response?: Response): void {\n if (response) {\n this.#controller.respondWith(response)\n }\n }\n\n public errorWith(reason?: unknown): void {\n if (reason instanceof Response) {\n return this.respondWith(reason)\n }\n\n if (reason instanceof InternalError) {\n this.#controller.errorWith(reason)\n }\n\n throw reason\n }\n}\n\nclass InterceptorWebSocketNetworkFrame extends WebSocketNetworkFrame {\n constructor(args: { connection: WebSocketConnectionData }) {\n super({ connection: args.connection })\n\n /**\n * @note Provide a similar frame listener cleanup as for HTTP.\n * When the client connection closes, the handler can no longer be used.\n */\n args.connection.client.addEventListener(\n 'close',\n () => {\n this.events.removeAllListeners()\n },\n {\n once: true,\n },\n )\n }\n\n public errorWith(reason?: unknown): void {\n if (reason instanceof Error) {\n const { client } = this.data.connection\n\n /**\n * Use `client.errorWith(reason)` in the future.\n * @see https://github.com/mswjs/interceptors/issues/747\n */\n const errorEvent = new Event('error')\n\n Object.defineProperty(errorEvent, 'cause', {\n enumerable: true,\n configurable: false,\n value: reason,\n })\n\n client.socket.dispatchEvent(errorEvent)\n }\n }\n\n public passthrough() {\n this.data.connection.server.connect()\n }\n}\n"],"mappings":"AACA,SAAS,wBAAkD;AAK3D,SAAS,qBAAqB;AAC9B,SAAS,qBAAqB;AAC9B,SAAS,kBAAkB,qBAAqB;AAChD,SAAS,6BAA6B;AACtC,SAAS,sCAAsC;AASxC,MAAM,0BAA0B,cAAc;AAAA,EACnD;AAAA,EAKA;AAAA,EAEA,YAAY,SAAmC;AAC7C,UAAM;AAEN,SAAK,eAAe,IAAI,iBAAiB;AAAA,MACvC,MAAM;AAAA,MACN,cAAc,QAAQ;AAAA,IACxB,CAAC;AACD,SAAK,UAAU,oBAAI,IAAI;AAAA,EACzB;AAAA,EAEO,SAAe;AACpB,SAAK,aAAa,MAAM;AAKxB,SAAK,aACF,GAAG,WAAW,KAAK,eAAe,KAAK,IAAI,CAAQ,EACnD,GAAG,YAAY,KAAK,gBAAgB,KAAK,IAAI,CAAQ,EACrD,GAAG,cAAc,KAAK,2BAA2B,KAAK,IAAI,CAAQ;AAAA,EACvE;AAAA,EAEO,UAAgB;AACrB,UAAM,QAAQ;AACd,SAAK,aAAa,QAAQ;AAM1B,SAAK,QAAQ,MAAM;AAAA,EACrB;AAAA,EAEA,MAAM,eAAe;AAAA,IACnB;AAAA,IACA;AAAA,IACA;AAAA,EACF,GAAqD;AAC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K,YAAY,UAAU,MAAM;AAAA,IACnC;AAEA,UAAM;AAAA,EACR;AACF;AAEA,MAAM,yCAAyC,sBAAsB;AAAA,EACnE,YAAY,MAA+C;AACzD,UAAM,EAAE,YAAY,KAAK,WAAW,CAAC;AAMrC,SAAK,WAAW,OAAO;AAAA,MACrB;AAAA,MACA,MAAM;AACJ,aAAK,OAAO,mBAAmB;AAAA,MACjC;AAAA,MACA;AAAA,QACE,MAAM;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAAA,EAEO,UAAU,QAAwB;AACvC,QAAI,kBAAkB,OAAO;AAC3B,YAAM,EAAE,OAAO,IAAI,KAAK,KAAK;AAM7B,YAAM,aAAa,IAAI,MAAM,OAAO;AAEpC,aAAO,eAAe,YAAY,SAAS;AAAA,QACzC,YAAY;AAAA,QACZ,cAAc;AAAA,QACd,OAAO;AAAA,MACT,CAAC;AAED,aAAO,OAAO,cAAc,UAAU;AAAA,IACxC;AAAA,EACF;AAAA,EAEO,cAAc;AACnB,SAAK,KAAK,WAAW,OAAO,QAAQ;AAAA,EACtC;AACF;","names":[]} \ No newline at end of file diff --git a/node_modules/msw/lib/core/experimental/sources/network-source.d.mts b/node_modules/msw/lib/core/experimental/sources/network-source.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..199046d56330ff5f41cfb7dee293a71a038d6419 --- /dev/null +++ b/node_modules/msw/lib/core/experimental/sources/network-source.d.mts @@ -0,0 +1,31 @@ +import { Emitter, TypedEvent, TypedListenerOptions } from 'rettime'; +import { A as AnyNetworkFrame, E as ExtractFrameEvents } from '../../on-unhandled-frame-Cr1KOZ0I.mjs'; +import '../handlers-controller.mjs'; +import '../../HttpResponse-CQwYpuKo.mjs'; +import '@mswjs/interceptors'; +import '../../utils/internal/isIterable.mjs'; +import '../../typeUtils.mjs'; +import 'graphql'; +import '../../utils/matching/matchRequestUrl.mjs'; +import '../../handlers/WebSocketHandler.mjs'; +import 'strict-event-emitter'; +import '@mswjs/interceptors/WebSocket'; + +declare class NetworkFrameEvent extends TypedEvent { + frame: AnyNetworkFrame; + constructor(type: string, frame: AnyNetworkFrame); +} +type NetworkSourceEventMap = { + frame: NetworkFrameEvent; +}; +type ExtractSourceEvents = Source extends NetworkSource ? ExtractFrameEvents : never; +declare abstract class NetworkSource { + protected emitter: Emitter>; + constructor(); + abstract enable(): unknown | Promise; + queue(frame: Frame): Promise; + on>(type: Type, listener: Emitter.Listener, options?: TypedListenerOptions): void; + disable(): void | Promise; +} + +export { type ExtractSourceEvents, NetworkSource }; diff --git a/node_modules/msw/lib/core/experimental/sources/network-source.d.ts b/node_modules/msw/lib/core/experimental/sources/network-source.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..350bfcc282e8dbacf6548405643f24fa1bfff576 --- /dev/null +++ b/node_modules/msw/lib/core/experimental/sources/network-source.d.ts @@ -0,0 +1,31 @@ +import { Emitter, TypedEvent, TypedListenerOptions } from 'rettime'; +import { A as AnyNetworkFrame, E as ExtractFrameEvents } from '../../on-unhandled-frame-BBR-P3kV.js'; +import '../handlers-controller.js'; +import '../../HttpResponse-BFS34nkx.js'; +import '@mswjs/interceptors'; +import '../../utils/internal/isIterable.js'; +import '../../typeUtils.js'; +import 'graphql'; +import '../../utils/matching/matchRequestUrl.js'; +import '../../handlers/WebSocketHandler.js'; +import 'strict-event-emitter'; +import '@mswjs/interceptors/WebSocket'; + +declare class NetworkFrameEvent extends TypedEvent { + frame: AnyNetworkFrame; + constructor(type: string, frame: AnyNetworkFrame); +} +type NetworkSourceEventMap = { + frame: NetworkFrameEvent; +}; +type ExtractSourceEvents = Source extends NetworkSource ? ExtractFrameEvents : never; +declare abstract class NetworkSource { + protected emitter: Emitter>; + constructor(); + abstract enable(): unknown | Promise; + queue(frame: Frame): Promise; + on>(type: Type, listener: Emitter.Listener, options?: TypedListenerOptions): void; + disable(): void | Promise; +} + +export { type ExtractSourceEvents, NetworkSource }; diff --git a/node_modules/msw/lib/core/experimental/sources/network-source.js b/node_modules/msw/lib/core/experimental/sources/network-source.js new file mode 100644 index 0000000000000000000000000000000000000000..2a720f267b4b5860aa23a107306255b2641d660f --- /dev/null +++ b/node_modules/msw/lib/core/experimental/sources/network-source.js @@ -0,0 +1,51 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var network_source_exports = {}; +__export(network_source_exports, { + NetworkSource: () => NetworkSource +}); +module.exports = __toCommonJS(network_source_exports); +var import_rettime = require("rettime"); +var import_network_frame = require("../frames/network-frame"); +class NetworkFrameEvent extends import_rettime.TypedEvent { + frame; + constructor(type, frame) { + super(...[type, {}]); + this.frame = frame; + } +} +class NetworkSource { + emitter; + constructor() { + this.emitter = new import_rettime.Emitter(); + } + async queue(frame) { + await this.emitter.emitAsPromise( + // @ts-expect-error Trouble handling a conditional type parameter. + new NetworkFrameEvent("frame", frame) + ); + } + on(type, listener, options) { + this.emitter.on(type, listener, options); + } + disable() { + this.emitter.removeAllListeners(); + } +} +//# sourceMappingURL=network-source.js.map \ No newline at end of file diff --git a/node_modules/msw/lib/core/experimental/sources/network-source.js.map b/node_modules/msw/lib/core/experimental/sources/network-source.js.map new file mode 100644 index 0000000000000000000000000000000000000000..7f704d6f1ece6c7187b7ba8216562686993a7176 --- /dev/null +++ b/node_modules/msw/lib/core/experimental/sources/network-source.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/core/experimental/sources/network-source.ts"],"sourcesContent":["import { Emitter, TypedEvent, type TypedListenerOptions } from 'rettime'\nimport {\n type AnyNetworkFrame,\n type ExtractFrameEvents,\n} from '../frames/network-frame'\n\nclass NetworkFrameEvent<\n DataType = void,\n ReturnType = void,\n EventType extends string = string,\n> extends TypedEvent {\n public frame: AnyNetworkFrame\n\n constructor(type: string, frame: AnyNetworkFrame) {\n super(...([type, {}] as any))\n this.frame = frame\n }\n}\n\ntype NetworkSourceEventMap = {\n frame: NetworkFrameEvent\n}\n\nexport type ExtractSourceEvents =\n Source extends NetworkSource ? ExtractFrameEvents : never\n\nexport abstract class NetworkSource<\n Frame extends AnyNetworkFrame = AnyNetworkFrame,\n> {\n protected emitter: Emitter>\n\n constructor() {\n this.emitter = new Emitter()\n }\n\n public abstract enable(): unknown | Promise\n\n public async queue(frame: Frame): Promise {\n await this.emitter.emitAsPromise(\n // @ts-expect-error Trouble handling a conditional type parameter.\n new NetworkFrameEvent('frame', frame),\n )\n }\n\n public on>(\n type: Type,\n listener: Emitter.Listener,\n options?: TypedListenerOptions,\n ): void {\n this.emitter.on(type, listener, options)\n }\n\n public disable(): void | Promise {\n this.emitter.removeAllListeners()\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,qBAA+D;AAC/D,2BAGO;AAEP,MAAM,0BAII,0BAA4C;AAAA,EAC7C;AAAA,EAEP,YAAY,MAAc,OAAwB;AAChD,UAAM,GAAI,CAAC,MAAM,CAAC,CAAC,CAAS;AAC5B,SAAK,QAAQ;AAAA,EACf;AACF;AASO,MAAe,cAEpB;AAAA,EACU;AAAA,EAEV,cAAc;AACZ,SAAK,UAAU,IAAI,uBAAQ;AAAA,EAC7B;AAAA,EAIA,MAAa,MAAM,OAA6B;AAC9C,UAAM,KAAK,QAAQ;AAAA;AAAA,MAEjB,IAAI,kBAAkB,SAAS,KAAK;AAAA,IACtC;AAAA,EACF;AAAA,EAEO,GACL,MACA,UACA,SACM;AACN,SAAK,QAAQ,GAAG,MAAM,UAAU,OAAO;AAAA,EACzC;AAAA,EAEO,UAAgC;AACrC,SAAK,QAAQ,mBAAmB;AAAA,EAClC;AACF;","names":[]} \ No newline at end of file diff --git a/node_modules/msw/lib/core/experimental/sources/network-source.mjs b/node_modules/msw/lib/core/experimental/sources/network-source.mjs new file mode 100644 index 0000000000000000000000000000000000000000..985498d44fbbb2c35c919014378115f22a95a78d --- /dev/null +++ b/node_modules/msw/lib/core/experimental/sources/network-source.mjs @@ -0,0 +1,32 @@ +import { Emitter, TypedEvent } from "rettime"; +import { +} from '../frames/network-frame.mjs'; +class NetworkFrameEvent extends TypedEvent { + frame; + constructor(type, frame) { + super(...[type, {}]); + this.frame = frame; + } +} +class NetworkSource { + emitter; + constructor() { + this.emitter = new Emitter(); + } + async queue(frame) { + await this.emitter.emitAsPromise( + // @ts-expect-error Trouble handling a conditional type parameter. + new NetworkFrameEvent("frame", frame) + ); + } + on(type, listener, options) { + this.emitter.on(type, listener, options); + } + disable() { + this.emitter.removeAllListeners(); + } +} +export { + NetworkSource +}; +//# sourceMappingURL=network-source.mjs.map \ No newline at end of file diff --git a/node_modules/msw/lib/core/experimental/sources/network-source.mjs.map b/node_modules/msw/lib/core/experimental/sources/network-source.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..cc205eebbc331343185abc203c2891477670dbc5 --- /dev/null +++ b/node_modules/msw/lib/core/experimental/sources/network-source.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/core/experimental/sources/network-source.ts"],"sourcesContent":["import { Emitter, TypedEvent, type TypedListenerOptions } from 'rettime'\nimport {\n type AnyNetworkFrame,\n type ExtractFrameEvents,\n} from '../frames/network-frame'\n\nclass NetworkFrameEvent<\n DataType = void,\n ReturnType = void,\n EventType extends string = string,\n> extends TypedEvent {\n public frame: AnyNetworkFrame\n\n constructor(type: string, frame: AnyNetworkFrame) {\n super(...([type, {}] as any))\n this.frame = frame\n }\n}\n\ntype NetworkSourceEventMap = {\n frame: NetworkFrameEvent\n}\n\nexport type ExtractSourceEvents =\n Source extends NetworkSource ? ExtractFrameEvents : never\n\nexport abstract class NetworkSource<\n Frame extends AnyNetworkFrame = AnyNetworkFrame,\n> {\n protected emitter: Emitter>\n\n constructor() {\n this.emitter = new Emitter()\n }\n\n public abstract enable(): unknown | Promise\n\n public async queue(frame: Frame): Promise {\n await this.emitter.emitAsPromise(\n // @ts-expect-error Trouble handling a conditional type parameter.\n new NetworkFrameEvent('frame', frame),\n )\n }\n\n public on>(\n type: Type,\n listener: Emitter.Listener,\n options?: TypedListenerOptions,\n ): void {\n this.emitter.on(type, listener, options)\n }\n\n public disable(): void | Promise {\n this.emitter.removeAllListeners()\n }\n}\n"],"mappings":"AAAA,SAAS,SAAS,kBAA6C;AAC/D;AAAA,OAGO;AAEP,MAAM,0BAII,WAA4C;AAAA,EAC7C;AAAA,EAEP,YAAY,MAAc,OAAwB;AAChD,UAAM,GAAI,CAAC,MAAM,CAAC,CAAC,CAAS;AAC5B,SAAK,QAAQ;AAAA,EACf;AACF;AASO,MAAe,cAEpB;AAAA,EACU;AAAA,EAEV,cAAc;AACZ,SAAK,UAAU,IAAI,QAAQ;AAAA,EAC7B;AAAA,EAIA,MAAa,MAAM,OAA6B;AAC9C,UAAM,KAAK,QAAQ;AAAA;AAAA,MAEjB,IAAI,kBAAkB,SAAS,KAAK;AAAA,IACtC;AAAA,EACF;AAAA,EAEO,GACL,MACA,UACA,SACM;AACN,SAAK,QAAQ,GAAG,MAAM,UAAU,OAAO;AAAA,EACzC;AAAA,EAEO,UAAgC;AACrC,SAAK,QAAQ,mBAAmB;AAAA,EAClC;AACF;","names":[]} \ No newline at end of file diff --git a/node_modules/msw/lib/core/getResponse.d.mts b/node_modules/msw/lib/core/getResponse.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..995a5d388cf2af33bbe5ee39710cc647384faa81 --- /dev/null +++ b/node_modules/msw/lib/core/getResponse.d.mts @@ -0,0 +1,18 @@ +import { R as RequestHandler, m as ResponseResolutionContext } from './HttpResponse-CQwYpuKo.mjs'; +import '@mswjs/interceptors'; +import './utils/internal/isIterable.mjs'; +import './typeUtils.mjs'; +import 'graphql'; +import './utils/matching/matchRequestUrl.mjs'; + +/** + * Finds a response for the given request instance + * in the array of request handlers. + * @param handlers The array of request handlers. + * @param request The `Request` instance. + * @param resolutionContext Request resolution options. + * @returns {Response} A mocked response, if any. + */ +declare const getResponse: (handlers: Array, request: Request, resolutionContext?: ResponseResolutionContext) => Promise; + +export { getResponse }; diff --git a/node_modules/msw/lib/core/getResponse.d.ts b/node_modules/msw/lib/core/getResponse.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..56d8eba4e02d1e95001a3fdd61f1dcaaa12f41a5 --- /dev/null +++ b/node_modules/msw/lib/core/getResponse.d.ts @@ -0,0 +1,18 @@ +import { R as RequestHandler, m as ResponseResolutionContext } from './HttpResponse-BFS34nkx.js'; +import '@mswjs/interceptors'; +import './utils/internal/isIterable.js'; +import './typeUtils.js'; +import 'graphql'; +import './utils/matching/matchRequestUrl.js'; + +/** + * Finds a response for the given request instance + * in the array of request handlers. + * @param handlers The array of request handlers. + * @param request The `Request` instance. + * @param resolutionContext Request resolution options. + * @returns {Response} A mocked response, if any. + */ +declare const getResponse: (handlers: Array, request: Request, resolutionContext?: ResponseResolutionContext) => Promise; + +export { getResponse }; diff --git a/node_modules/msw/lib/core/getResponse.js b/node_modules/msw/lib/core/getResponse.js new file mode 100644 index 0000000000000000000000000000000000000000..a9fc4d0bdd26282babfcb2b7024a34f7a3f11303 --- /dev/null +++ b/node_modules/msw/lib/core/getResponse.js @@ -0,0 +1,35 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var getResponse_exports = {}; +__export(getResponse_exports, { + getResponse: () => getResponse +}); +module.exports = __toCommonJS(getResponse_exports); +var import_interceptors = require("@mswjs/interceptors"); +var import_executeHandlers = require("./utils/executeHandlers"); +const getResponse = async (handlers, request, resolutionContext) => { + const result = await (0, import_executeHandlers.executeHandlers)({ + request, + requestId: (0, import_interceptors.createRequestId)(), + handlers, + resolutionContext + }); + return result?.response; +}; +//# sourceMappingURL=getResponse.js.map \ No newline at end of file diff --git a/node_modules/msw/lib/core/getResponse.js.map b/node_modules/msw/lib/core/getResponse.js.map new file mode 100644 index 0000000000000000000000000000000000000000..1d7182b36139b57356f423d6b514a6766b1dbdce --- /dev/null +++ b/node_modules/msw/lib/core/getResponse.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/core/getResponse.ts"],"sourcesContent":["import { createRequestId } from '@mswjs/interceptors'\nimport type { RequestHandler } from './handlers/RequestHandler'\nimport {\n executeHandlers,\n type ResponseResolutionContext,\n} from './utils/executeHandlers'\n\n/**\n * Finds a response for the given request instance\n * in the array of request handlers.\n * @param handlers The array of request handlers.\n * @param request The `Request` instance.\n * @param resolutionContext Request resolution options.\n * @returns {Response} A mocked response, if any.\n */\nexport const getResponse = async (\n handlers: Array,\n request: Request,\n resolutionContext?: ResponseResolutionContext,\n): Promise => {\n const result = await executeHandlers({\n request,\n requestId: createRequestId(),\n handlers,\n resolutionContext,\n })\n\n return result?.response\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,0BAAgC;AAEhC,6BAGO;AAUA,MAAM,cAAc,OACzB,UACA,SACA,sBACkC;AAClC,QAAM,SAAS,UAAM,wCAAgB;AAAA,IACnC;AAAA,IACA,eAAW,qCAAgB;AAAA,IAC3B;AAAA,IACA;AAAA,EACF,CAAC;AAED,SAAO,QAAQ;AACjB;","names":[]} \ No newline at end of file diff --git a/node_modules/msw/lib/core/getResponse.mjs b/node_modules/msw/lib/core/getResponse.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a5f707ce0f3b8a714b4051750b0f4cc19c51e0e7 --- /dev/null +++ b/node_modules/msw/lib/core/getResponse.mjs @@ -0,0 +1,17 @@ +import { createRequestId } from "@mswjs/interceptors"; +import { + executeHandlers +} from './utils/executeHandlers.mjs'; +const getResponse = async (handlers, request, resolutionContext) => { + const result = await executeHandlers({ + request, + requestId: createRequestId(), + handlers, + resolutionContext + }); + return result?.response; +}; +export { + getResponse +}; +//# sourceMappingURL=getResponse.mjs.map \ No newline at end of file diff --git a/node_modules/msw/lib/core/getResponse.mjs.map b/node_modules/msw/lib/core/getResponse.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..4ff1906c7cca2225c6d8eed1b7ef55628e9d5447 --- /dev/null +++ b/node_modules/msw/lib/core/getResponse.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/core/getResponse.ts"],"sourcesContent":["import { createRequestId } from '@mswjs/interceptors'\nimport type { RequestHandler } from './handlers/RequestHandler'\nimport {\n executeHandlers,\n type ResponseResolutionContext,\n} from './utils/executeHandlers'\n\n/**\n * Finds a response for the given request instance\n * in the array of request handlers.\n * @param handlers The array of request handlers.\n * @param request The `Request` instance.\n * @param resolutionContext Request resolution options.\n * @returns {Response} A mocked response, if any.\n */\nexport const getResponse = async (\n handlers: Array,\n request: Request,\n resolutionContext?: ResponseResolutionContext,\n): Promise => {\n const result = await executeHandlers({\n request,\n requestId: createRequestId(),\n handlers,\n resolutionContext,\n })\n\n return result?.response\n}\n"],"mappings":"AAAA,SAAS,uBAAuB;AAEhC;AAAA,EACE;AAAA,OAEK;AAUA,MAAM,cAAc,OACzB,UACA,SACA,sBACkC;AAClC,QAAM,SAAS,MAAM,gBAAgB;AAAA,IACnC;AAAA,IACA,WAAW,gBAAgB;AAAA,IAC3B;AAAA,IACA;AAAA,EACF,CAAC;AAED,SAAO,QAAQ;AACjB;","names":[]} \ No newline at end of file diff --git a/node_modules/msw/lib/core/graphql.d.mts b/node_modules/msw/lib/core/graphql.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..ba5c2aa2e6645daa31976ffd25d6bcc4b143d481 --- /dev/null +++ b/node_modules/msw/lib/core/graphql.d.mts @@ -0,0 +1,76 @@ +import { f as GraphQLQuery, g as GraphQLVariables, p as GraphQLPredicate, a as ResponseResolver, q as GraphQLResolverExtras, i as GraphQLResponseBody, c as RequestHandlerOptions, G as GraphQLHandler } from './HttpResponse-CQwYpuKo.mjs'; +import { Path } from './utils/matching/matchRequestUrl.mjs'; +import '@mswjs/interceptors'; +import './utils/internal/isIterable.mjs'; +import './typeUtils.mjs'; +import 'graphql'; + +type GraphQLRequestHandler = (predicate: GraphQLPredicate, resolver: GraphQLResponseResolver<[ + Query +] extends [never] ? GraphQLQuery : Query, Variables>, options?: RequestHandlerOptions) => GraphQLHandler; +type GraphQLOperationHandler = (resolver: GraphQLResponseResolver<[ + Query +] extends [never] ? GraphQLQuery : Query, Variables>, options?: RequestHandlerOptions) => GraphQLHandler; +type GraphQLResponseResolver = ResponseResolver, null, GraphQLResponseBody<[Query] extends [never] ? GraphQLQuery : Query>>; +interface GraphQLLinkHandlers { + query: GraphQLRequestHandler; + mutation: GraphQLRequestHandler; + operation: GraphQLOperationHandler; +} +/** + * A namespace to intercept and mock GraphQL operations + * + * @example + * graphql.query('GetUser', resolver) + * graphql.mutation('DeletePost', resolver) + * + * @see {@link https://mswjs.io/docs/api/graphql `graphql` API reference} + */ +declare const graphql: { + /** + * Intercepts a GraphQL query by a given name. + * + * @example + * graphql.query('GetUser', () => { + * return HttpResponse.json({ data: { user: { name: 'John' } } }) + * }) + * + * @see {@link https://mswjs.io/docs/api/graphql#graphqlqueryqueryname-resolver `graphql.query()` API reference} + */ + query: GraphQLRequestHandler; + /** + * Intercepts a GraphQL mutation by its name. + * + * @example + * graphql.mutation('SavePost', () => { + * return HttpResponse.json({ data: { post: { id: 'abc-123 } } }) + * }) + * + * @see {@link https://mswjs.io/docs/api/graphql#graphqlmutationmutationname-resolver `graphql.query()` API reference} + * + */ + mutation: GraphQLRequestHandler; + /** + * Intercepts any GraphQL operation, regardless of its type or name. + * + * @example + * graphql.operation(() => { + * return HttpResponse.json({ data: { name: 'John' } }) + * }) + * + * @see {@link https://mswjs.io/docs/api/graphql#graphqloperationresolver `graphql.operation()` API reference} + */ + operation: GraphQLOperationHandler; + /** + * Intercepts GraphQL operations scoped by the given URL. + * + * @example + * const github = graphql.link('https://api.github.com/graphql') + * github.query('GetRepo', resolver) + * + * @see {@link https://mswjs.io/docs/api/graphql#graphqllinkurl `graphql.link()` API reference} + */ + link(url: Path): GraphQLLinkHandlers; +}; + +export { type GraphQLLinkHandlers, type GraphQLOperationHandler, type GraphQLRequestHandler, type GraphQLResponseResolver, graphql }; diff --git a/node_modules/msw/lib/core/graphql.d.ts b/node_modules/msw/lib/core/graphql.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..766f9c8169b54aa6e1a9ea00e0842e6230027b27 --- /dev/null +++ b/node_modules/msw/lib/core/graphql.d.ts @@ -0,0 +1,76 @@ +import { f as GraphQLQuery, g as GraphQLVariables, p as GraphQLPredicate, a as ResponseResolver, q as GraphQLResolverExtras, i as GraphQLResponseBody, c as RequestHandlerOptions, G as GraphQLHandler } from './HttpResponse-BFS34nkx.js'; +import { Path } from './utils/matching/matchRequestUrl.js'; +import '@mswjs/interceptors'; +import './utils/internal/isIterable.js'; +import './typeUtils.js'; +import 'graphql'; + +type GraphQLRequestHandler = (predicate: GraphQLPredicate, resolver: GraphQLResponseResolver<[ + Query +] extends [never] ? GraphQLQuery : Query, Variables>, options?: RequestHandlerOptions) => GraphQLHandler; +type GraphQLOperationHandler = (resolver: GraphQLResponseResolver<[ + Query +] extends [never] ? GraphQLQuery : Query, Variables>, options?: RequestHandlerOptions) => GraphQLHandler; +type GraphQLResponseResolver = ResponseResolver, null, GraphQLResponseBody<[Query] extends [never] ? GraphQLQuery : Query>>; +interface GraphQLLinkHandlers { + query: GraphQLRequestHandler; + mutation: GraphQLRequestHandler; + operation: GraphQLOperationHandler; +} +/** + * A namespace to intercept and mock GraphQL operations + * + * @example + * graphql.query('GetUser', resolver) + * graphql.mutation('DeletePost', resolver) + * + * @see {@link https://mswjs.io/docs/api/graphql `graphql` API reference} + */ +declare const graphql: { + /** + * Intercepts a GraphQL query by a given name. + * + * @example + * graphql.query('GetUser', () => { + * return HttpResponse.json({ data: { user: { name: 'John' } } }) + * }) + * + * @see {@link https://mswjs.io/docs/api/graphql#graphqlqueryqueryname-resolver `graphql.query()` API reference} + */ + query: GraphQLRequestHandler; + /** + * Intercepts a GraphQL mutation by its name. + * + * @example + * graphql.mutation('SavePost', () => { + * return HttpResponse.json({ data: { post: { id: 'abc-123 } } }) + * }) + * + * @see {@link https://mswjs.io/docs/api/graphql#graphqlmutationmutationname-resolver `graphql.query()` API reference} + * + */ + mutation: GraphQLRequestHandler; + /** + * Intercepts any GraphQL operation, regardless of its type or name. + * + * @example + * graphql.operation(() => { + * return HttpResponse.json({ data: { name: 'John' } }) + * }) + * + * @see {@link https://mswjs.io/docs/api/graphql#graphqloperationresolver `graphql.operation()` API reference} + */ + operation: GraphQLOperationHandler; + /** + * Intercepts GraphQL operations scoped by the given URL. + * + * @example + * const github = graphql.link('https://api.github.com/graphql') + * github.query('GetRepo', resolver) + * + * @see {@link https://mswjs.io/docs/api/graphql#graphqllinkurl `graphql.link()` API reference} + */ + link(url: Path): GraphQLLinkHandlers; +}; + +export { type GraphQLLinkHandlers, type GraphQLOperationHandler, type GraphQLRequestHandler, type GraphQLResponseResolver, graphql }; diff --git a/node_modules/msw/lib/core/graphql.js b/node_modules/msw/lib/core/graphql.js new file mode 100644 index 0000000000000000000000000000000000000000..2489b7329f09e0bdc0fefc3140e46494235cca3d --- /dev/null +++ b/node_modules/msw/lib/core/graphql.js @@ -0,0 +1,91 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var graphql_exports = {}; +__export(graphql_exports, { + graphql: () => graphql +}); +module.exports = __toCommonJS(graphql_exports); +var import_RequestHandler = require("./handlers/RequestHandler"); +var import_GraphQLHandler = require("./handlers/GraphQLHandler"); +function createScopedGraphQLHandler(operationType, url) { + return (predicate, resolver, options = {}) => { + return new import_GraphQLHandler.GraphQLHandler(operationType, predicate, url, resolver, options); + }; +} +function createGraphQLOperationHandler(url) { + return (resolver, options) => { + return new import_GraphQLHandler.GraphQLHandler("all", new RegExp(".*"), url, resolver, options); + }; +} +const graphql = { + /** + * Intercepts a GraphQL query by a given name. + * + * @example + * graphql.query('GetUser', () => { + * return HttpResponse.json({ data: { user: { name: 'John' } } }) + * }) + * + * @see {@link https://mswjs.io/docs/api/graphql#graphqlqueryqueryname-resolver `graphql.query()` API reference} + */ + query: createScopedGraphQLHandler("query", "*"), + /** + * Intercepts a GraphQL mutation by its name. + * + * @example + * graphql.mutation('SavePost', () => { + * return HttpResponse.json({ data: { post: { id: 'abc-123 } } }) + * }) + * + * @see {@link https://mswjs.io/docs/api/graphql#graphqlmutationmutationname-resolver `graphql.query()` API reference} + * + */ + mutation: createScopedGraphQLHandler("mutation", "*"), + /** + * Intercepts any GraphQL operation, regardless of its type or name. + * + * @example + * graphql.operation(() => { + * return HttpResponse.json({ data: { name: 'John' } }) + * }) + * + * @see {@link https://mswjs.io/docs/api/graphql#graphqloperationresolver `graphql.operation()` API reference} + */ + operation: createGraphQLOperationHandler("*"), + /** + * Intercepts GraphQL operations scoped by the given URL. + * + * @example + * const github = graphql.link('https://api.github.com/graphql') + * github.query('GetRepo', resolver) + * + * @see {@link https://mswjs.io/docs/api/graphql#graphqllinkurl `graphql.link()` API reference} + */ + link(url) { + return { + operation: createGraphQLOperationHandler(url), + query: createScopedGraphQLHandler("query", url), + mutation: createScopedGraphQLHandler( + "mutation", + url + ) + }; + } +}; +//# sourceMappingURL=graphql.js.map \ No newline at end of file diff --git a/node_modules/msw/lib/core/graphql.js.map b/node_modules/msw/lib/core/graphql.js.map new file mode 100644 index 0000000000000000000000000000000000000000..07d1511b8309a8382b1fa6dec67797e47e5caa56 --- /dev/null +++ b/node_modules/msw/lib/core/graphql.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/core/graphql.ts"],"sourcesContent":["import type { OperationTypeNode } from 'graphql'\nimport {\n type ResponseResolver,\n type RequestHandlerOptions,\n} from './handlers/RequestHandler'\nimport {\n GraphQLHandler,\n type GraphQLVariables,\n type GraphQLOperationType,\n type GraphQLResolverExtras,\n type GraphQLResponseBody,\n type GraphQLQuery,\n type GraphQLPredicate,\n} from './handlers/GraphQLHandler'\nimport type { Path } from './utils/matching/matchRequestUrl'\n\nexport type GraphQLRequestHandler = <\n Query extends GraphQLQuery = GraphQLQuery,\n Variables extends GraphQLVariables = GraphQLVariables,\n>(\n predicate: GraphQLPredicate,\n resolver: GraphQLResponseResolver<\n [Query] extends [never] ? GraphQLQuery : Query,\n Variables\n >,\n options?: RequestHandlerOptions,\n) => GraphQLHandler\n\nexport type GraphQLOperationHandler = <\n Query extends GraphQLQuery = GraphQLQuery,\n Variables extends GraphQLVariables = GraphQLVariables,\n>(\n resolver: GraphQLResponseResolver<\n [Query] extends [never] ? GraphQLQuery : Query,\n Variables\n >,\n options?: RequestHandlerOptions,\n) => GraphQLHandler\n\nexport type GraphQLResponseResolver<\n Query extends GraphQLQuery = GraphQLQuery,\n Variables extends GraphQLVariables = GraphQLVariables,\n> = ResponseResolver<\n GraphQLResolverExtras,\n null,\n GraphQLResponseBody<[Query] extends [never] ? GraphQLQuery : Query>\n>\n\nfunction createScopedGraphQLHandler(\n operationType: GraphQLOperationType,\n url: Path,\n): GraphQLRequestHandler {\n return (predicate, resolver, options = {}) => {\n return new GraphQLHandler(operationType, predicate, url, resolver, options)\n }\n}\n\nfunction createGraphQLOperationHandler(url: Path): GraphQLOperationHandler {\n return (resolver, options) => {\n return new GraphQLHandler('all', new RegExp('.*'), url, resolver, options)\n }\n}\n\nexport interface GraphQLLinkHandlers {\n query: GraphQLRequestHandler\n mutation: GraphQLRequestHandler\n operation: GraphQLOperationHandler\n}\n\n/**\n * A namespace to intercept and mock GraphQL operations\n *\n * @example\n * graphql.query('GetUser', resolver)\n * graphql.mutation('DeletePost', resolver)\n *\n * @see {@link https://mswjs.io/docs/api/graphql `graphql` API reference}\n */\nexport const graphql = {\n /**\n * Intercepts a GraphQL query by a given name.\n *\n * @example\n * graphql.query('GetUser', () => {\n * return HttpResponse.json({ data: { user: { name: 'John' } } })\n * })\n *\n * @see {@link https://mswjs.io/docs/api/graphql#graphqlqueryqueryname-resolver `graphql.query()` API reference}\n */\n query: createScopedGraphQLHandler('query' as OperationTypeNode, '*'),\n\n /**\n * Intercepts a GraphQL mutation by its name.\n *\n * @example\n * graphql.mutation('SavePost', () => {\n * return HttpResponse.json({ data: { post: { id: 'abc-123 } } })\n * })\n *\n * @see {@link https://mswjs.io/docs/api/graphql#graphqlmutationmutationname-resolver `graphql.query()` API reference}\n *\n */\n mutation: createScopedGraphQLHandler('mutation' as OperationTypeNode, '*'),\n\n /**\n * Intercepts any GraphQL operation, regardless of its type or name.\n *\n * @example\n * graphql.operation(() => {\n * return HttpResponse.json({ data: { name: 'John' } })\n * })\n *\n * @see {@link https://mswjs.io/docs/api/graphql#graphqloperationresolver `graphql.operation()` API reference}\n */\n operation: createGraphQLOperationHandler('*'),\n\n /**\n * Intercepts GraphQL operations scoped by the given URL.\n *\n * @example\n * const github = graphql.link('https://api.github.com/graphql')\n * github.query('GetRepo', resolver)\n *\n * @see {@link https://mswjs.io/docs/api/graphql#graphqllinkurl `graphql.link()` API reference}\n */\n link(url: Path): GraphQLLinkHandlers {\n return {\n operation: createGraphQLOperationHandler(url),\n query: createScopedGraphQLHandler('query' as OperationTypeNode, url),\n mutation: createScopedGraphQLHandler(\n 'mutation' as OperationTypeNode,\n url,\n ),\n }\n },\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,4BAGO;AACP,4BAQO;AAmCP,SAAS,2BACP,eACA,KACuB;AACvB,SAAO,CAAC,WAAW,UAAU,UAAU,CAAC,MAAM;AAC5C,WAAO,IAAI,qCAAe,eAAe,WAAW,KAAK,UAAU,OAAO;AAAA,EAC5E;AACF;AAEA,SAAS,8BAA8B,KAAoC;AACzE,SAAO,CAAC,UAAU,YAAY;AAC5B,WAAO,IAAI,qCAAe,OAAO,IAAI,OAAO,IAAI,GAAG,KAAK,UAAU,OAAO;AAAA,EAC3E;AACF;AAiBO,MAAM,UAAU;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWrB,OAAO,2BAA2B,SAA8B,GAAG;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAanE,UAAU,2BAA2B,YAAiC,GAAG;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYzE,WAAW,8BAA8B,GAAG;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAW5C,KAAK,KAAgC;AACnC,WAAO;AAAA,MACL,WAAW,8BAA8B,GAAG;AAAA,MAC5C,OAAO,2BAA2B,SAA8B,GAAG;AAAA,MACnE,UAAU;AAAA,QACR;AAAA,QACA;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;","names":[]} \ No newline at end of file diff --git a/node_modules/msw/lib/core/graphql.mjs b/node_modules/msw/lib/core/graphql.mjs new file mode 100644 index 0000000000000000000000000000000000000000..d19e4290715aa2049d0fb914f9c2a46747ce6502 --- /dev/null +++ b/node_modules/msw/lib/core/graphql.mjs @@ -0,0 +1,74 @@ +import { +} from './handlers/RequestHandler.mjs'; +import { + GraphQLHandler +} from './handlers/GraphQLHandler.mjs'; +function createScopedGraphQLHandler(operationType, url) { + return (predicate, resolver, options = {}) => { + return new GraphQLHandler(operationType, predicate, url, resolver, options); + }; +} +function createGraphQLOperationHandler(url) { + return (resolver, options) => { + return new GraphQLHandler("all", new RegExp(".*"), url, resolver, options); + }; +} +const graphql = { + /** + * Intercepts a GraphQL query by a given name. + * + * @example + * graphql.query('GetUser', () => { + * return HttpResponse.json({ data: { user: { name: 'John' } } }) + * }) + * + * @see {@link https://mswjs.io/docs/api/graphql#graphqlqueryqueryname-resolver `graphql.query()` API reference} + */ + query: createScopedGraphQLHandler("query", "*"), + /** + * Intercepts a GraphQL mutation by its name. + * + * @example + * graphql.mutation('SavePost', () => { + * return HttpResponse.json({ data: { post: { id: 'abc-123 } } }) + * }) + * + * @see {@link https://mswjs.io/docs/api/graphql#graphqlmutationmutationname-resolver `graphql.query()` API reference} + * + */ + mutation: createScopedGraphQLHandler("mutation", "*"), + /** + * Intercepts any GraphQL operation, regardless of its type or name. + * + * @example + * graphql.operation(() => { + * return HttpResponse.json({ data: { name: 'John' } }) + * }) + * + * @see {@link https://mswjs.io/docs/api/graphql#graphqloperationresolver `graphql.operation()` API reference} + */ + operation: createGraphQLOperationHandler("*"), + /** + * Intercepts GraphQL operations scoped by the given URL. + * + * @example + * const github = graphql.link('https://api.github.com/graphql') + * github.query('GetRepo', resolver) + * + * @see {@link https://mswjs.io/docs/api/graphql#graphqllinkurl `graphql.link()` API reference} + */ + link(url) { + return { + operation: createGraphQLOperationHandler(url), + query: createScopedGraphQLHandler("query", url), + mutation: createScopedGraphQLHandler( + "mutation", + url + ) + }; + } +}; +export { + graphql +}; +//# sourceMappingURL=graphql.mjs.map \ No newline at end of file diff --git a/node_modules/msw/lib/core/graphql.mjs.map b/node_modules/msw/lib/core/graphql.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..8b4a0b28b9bfe5dad2b46374c8124f20ecd1eb28 --- /dev/null +++ b/node_modules/msw/lib/core/graphql.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/core/graphql.ts"],"sourcesContent":["import type { OperationTypeNode } from 'graphql'\nimport {\n type ResponseResolver,\n type RequestHandlerOptions,\n} from './handlers/RequestHandler'\nimport {\n GraphQLHandler,\n type GraphQLVariables,\n type GraphQLOperationType,\n type GraphQLResolverExtras,\n type GraphQLResponseBody,\n type GraphQLQuery,\n type GraphQLPredicate,\n} from './handlers/GraphQLHandler'\nimport type { Path } from './utils/matching/matchRequestUrl'\n\nexport type GraphQLRequestHandler = <\n Query extends GraphQLQuery = GraphQLQuery,\n Variables extends GraphQLVariables = GraphQLVariables,\n>(\n predicate: GraphQLPredicate,\n resolver: GraphQLResponseResolver<\n [Query] extends [never] ? GraphQLQuery : Query,\n Variables\n >,\n options?: RequestHandlerOptions,\n) => GraphQLHandler\n\nexport type GraphQLOperationHandler = <\n Query extends GraphQLQuery = GraphQLQuery,\n Variables extends GraphQLVariables = GraphQLVariables,\n>(\n resolver: GraphQLResponseResolver<\n [Query] extends [never] ? GraphQLQuery : Query,\n Variables\n >,\n options?: RequestHandlerOptions,\n) => GraphQLHandler\n\nexport type GraphQLResponseResolver<\n Query extends GraphQLQuery = GraphQLQuery,\n Variables extends GraphQLVariables = GraphQLVariables,\n> = ResponseResolver<\n GraphQLResolverExtras,\n null,\n GraphQLResponseBody<[Query] extends [never] ? GraphQLQuery : Query>\n>\n\nfunction createScopedGraphQLHandler(\n operationType: GraphQLOperationType,\n url: Path,\n): GraphQLRequestHandler {\n return (predicate, resolver, options = {}) => {\n return new GraphQLHandler(operationType, predicate, url, resolver, options)\n }\n}\n\nfunction createGraphQLOperationHandler(url: Path): GraphQLOperationHandler {\n return (resolver, options) => {\n return new GraphQLHandler('all', new RegExp('.*'), url, resolver, options)\n }\n}\n\nexport interface GraphQLLinkHandlers {\n query: GraphQLRequestHandler\n mutation: GraphQLRequestHandler\n operation: GraphQLOperationHandler\n}\n\n/**\n * A namespace to intercept and mock GraphQL operations\n *\n * @example\n * graphql.query('GetUser', resolver)\n * graphql.mutation('DeletePost', resolver)\n *\n * @see {@link https://mswjs.io/docs/api/graphql `graphql` API reference}\n */\nexport const graphql = {\n /**\n * Intercepts a GraphQL query by a given name.\n *\n * @example\n * graphql.query('GetUser', () => {\n * return HttpResponse.json({ data: { user: { name: 'John' } } })\n * })\n *\n * @see {@link https://mswjs.io/docs/api/graphql#graphqlqueryqueryname-resolver `graphql.query()` API reference}\n */\n query: createScopedGraphQLHandler('query' as OperationTypeNode, '*'),\n\n /**\n * Intercepts a GraphQL mutation by its name.\n *\n * @example\n * graphql.mutation('SavePost', () => {\n * return HttpResponse.json({ data: { post: { id: 'abc-123 } } })\n * })\n *\n * @see {@link https://mswjs.io/docs/api/graphql#graphqlmutationmutationname-resolver `graphql.query()` API reference}\n *\n */\n mutation: createScopedGraphQLHandler('mutation' as OperationTypeNode, '*'),\n\n /**\n * Intercepts any GraphQL operation, regardless of its type or name.\n *\n * @example\n * graphql.operation(() => {\n * return HttpResponse.json({ data: { name: 'John' } })\n * })\n *\n * @see {@link https://mswjs.io/docs/api/graphql#graphqloperationresolver `graphql.operation()` API reference}\n */\n operation: createGraphQLOperationHandler('*'),\n\n /**\n * Intercepts GraphQL operations scoped by the given URL.\n *\n * @example\n * const github = graphql.link('https://api.github.com/graphql')\n * github.query('GetRepo', resolver)\n *\n * @see {@link https://mswjs.io/docs/api/graphql#graphqllinkurl `graphql.link()` API reference}\n */\n link(url: Path): GraphQLLinkHandlers {\n return {\n operation: createGraphQLOperationHandler(url),\n query: createScopedGraphQLHandler('query' as OperationTypeNode, url),\n mutation: createScopedGraphQLHandler(\n 'mutation' as OperationTypeNode,\n url,\n ),\n }\n },\n}\n"],"mappings":"AACA;AAAA,OAGO;AACP;AAAA,EACE;AAAA,OAOK;AAmCP,SAAS,2BACP,eACA,KACuB;AACvB,SAAO,CAAC,WAAW,UAAU,UAAU,CAAC,MAAM;AAC5C,WAAO,IAAI,eAAe,eAAe,WAAW,KAAK,UAAU,OAAO;AAAA,EAC5E;AACF;AAEA,SAAS,8BAA8B,KAAoC;AACzE,SAAO,CAAC,UAAU,YAAY;AAC5B,WAAO,IAAI,eAAe,OAAO,IAAI,OAAO,IAAI,GAAG,KAAK,UAAU,OAAO;AAAA,EAC3E;AACF;AAiBO,MAAM,UAAU;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWrB,OAAO,2BAA2B,SAA8B,GAAG;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAanE,UAAU,2BAA2B,YAAiC,GAAG;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYzE,WAAW,8BAA8B,GAAG;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAW5C,KAAK,KAAgC;AACnC,WAAO;AAAA,MACL,WAAW,8BAA8B,GAAG;AAAA,MAC5C,OAAO,2BAA2B,SAA8B,GAAG;AAAA,MACnE,UAAU;AAAA,QACR;AAAA,QACA;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;","names":[]} \ No newline at end of file diff --git a/node_modules/msw/lib/core/handlers/GraphQLHandler.d.mts b/node_modules/msw/lib/core/handlers/GraphQLHandler.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..c353430030195b21d69ae93b16880fe910e28577 --- /dev/null +++ b/node_modules/msw/lib/core/handlers/GraphQLHandler.d.mts @@ -0,0 +1,6 @@ +import 'graphql'; +export { z as DocumentTypeDecoration, l as GraphQLCustomPredicate, F as GraphQLCustomPredicateResult, G as GraphQLHandler, C as GraphQLHandlerInfo, B as GraphQLHandlerNameSelector, j as GraphQLJsonRequestBody, k as GraphQLOperationType, p as GraphQLPredicate, f as GraphQLQuery, h as GraphQLRequestBody, E as GraphQLRequestParsedResult, q as GraphQLResolverExtras, i as GraphQLResponseBody, g as GraphQLVariables, I as isDocumentNode } from '../HttpResponse-CQwYpuKo.mjs'; +import '../utils/matching/matchRequestUrl.mjs'; +import '@mswjs/interceptors'; +import '../utils/internal/isIterable.mjs'; +import '../typeUtils.mjs'; diff --git a/node_modules/msw/lib/core/handlers/GraphQLHandler.d.ts b/node_modules/msw/lib/core/handlers/GraphQLHandler.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0627111f70e9ffcceac723df951461ee544d2147 --- /dev/null +++ b/node_modules/msw/lib/core/handlers/GraphQLHandler.d.ts @@ -0,0 +1,6 @@ +import 'graphql'; +export { z as DocumentTypeDecoration, l as GraphQLCustomPredicate, F as GraphQLCustomPredicateResult, G as GraphQLHandler, C as GraphQLHandlerInfo, B as GraphQLHandlerNameSelector, j as GraphQLJsonRequestBody, k as GraphQLOperationType, p as GraphQLPredicate, f as GraphQLQuery, h as GraphQLRequestBody, E as GraphQLRequestParsedResult, q as GraphQLResolverExtras, i as GraphQLResponseBody, g as GraphQLVariables, I as isDocumentNode } from '../HttpResponse-BFS34nkx.js'; +import '../utils/matching/matchRequestUrl.js'; +import '@mswjs/interceptors'; +import '../utils/internal/isIterable.js'; +import '../typeUtils.js'; diff --git a/node_modules/msw/lib/core/handlers/GraphQLHandler.js b/node_modules/msw/lib/core/handlers/GraphQLHandler.js new file mode 100644 index 0000000000000000000000000000000000000000..918df41c53dd4d2e4c8327b211d49dad3f0d7b3a --- /dev/null +++ b/node_modules/msw/lib/core/handlers/GraphQLHandler.js @@ -0,0 +1,232 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var GraphQLHandler_exports = {}; +__export(GraphQLHandler_exports, { + GraphQLHandler: () => GraphQLHandler, + isDocumentNode: () => isDocumentNode +}); +module.exports = __toCommonJS(GraphQLHandler_exports); +var import_outvariant = require("outvariant"); +var import_graphql = require("graphql"); +var import_RequestHandler = require("./RequestHandler"); +var import_getTimestamp = require("../utils/logging/getTimestamp"); +var import_getStatusCodeColor = require("../utils/logging/getStatusCodeColor"); +var import_serializeRequest = require("../utils/logging/serializeRequest"); +var import_serializeResponse = require("../utils/logging/serializeResponse"); +var import_matchRequestUrl = require("../utils/matching/matchRequestUrl"); +var import_parseGraphQLRequest = require("../utils/internal/parseGraphQLRequest"); +var import_toPublicUrl = require("../utils/request/toPublicUrl"); +var import_devUtils = require("../utils/internal/devUtils"); +var import_getRequestCookies = require("../utils/request/getRequestCookies"); +var import_executeHandlers = require("../utils/executeHandlers"); +var import_HttpResponse = require("../HttpResponse"); +var import_getAllAcceptedMimeTypes = require("../utils/request/getAllAcceptedMimeTypes"); +function isDocumentNode(value) { + if (value == null) { + return false; + } + return typeof value === "object" && "kind" in value && "definitions" in value; +} +function isDocumentTypeDecoration(value) { + return value instanceof String; +} +class GraphQLHandler extends import_RequestHandler.RequestHandler { + endpoint; + static parsedRequestCache = /* @__PURE__ */ new WeakMap(); + static #parseOperationName(predicate, operationType) { + const getOperationName = (node) => { + (0, import_outvariant.invariant)( + node.operationType === operationType, + 'Failed to create a GraphQL handler: provided a DocumentNode with a mismatched operation type (expected "%s" but got "%s").', + operationType, + node.operationType + ); + (0, import_outvariant.invariant)( + node.operationName, + "Failed to create a GraphQL handler: provided a DocumentNode without operation name" + ); + return node.operationName; + }; + if (isDocumentNode(predicate)) { + return getOperationName((0, import_parseGraphQLRequest.parseDocumentNode)(predicate)); + } + if (isDocumentTypeDecoration(predicate)) { + const documentNode = (0, import_graphql.parse)(predicate.toString()); + (0, import_outvariant.invariant)( + isDocumentNode(documentNode), + "Failed to create a GraphQL handler: given TypedDocumentString (%s) does not produce a valid DocumentNode", + predicate + ); + return getOperationName((0, import_parseGraphQLRequest.parseDocumentNode)(documentNode)); + } + return predicate; + } + constructor(operationType, predicate, endpoint, resolver, options) { + const operationName = GraphQLHandler.#parseOperationName( + predicate, + operationType + ); + const displayOperationName = typeof operationName === "function" ? "[custom predicate]" : operationName; + const header = operationType === "all" ? `${operationType} (origin: ${endpoint.toString()})` : `${operationType}${displayOperationName ? ` ${displayOperationName}` : ""} (origin: ${endpoint.toString()})`; + super({ + info: { + header, + operationType, + operationName: GraphQLHandler.#parseOperationName( + predicate, + operationType + ) + }, + resolver, + options + }); + this.endpoint = endpoint; + } + /** + * Parses the request body, once per request, cached across all + * GraphQL handlers. This is done to avoid multiple parsing of the + * request body, which each requires a clone of the request. + */ + async parseGraphQLRequestOrGetFromCache(request) { + if (!GraphQLHandler.parsedRequestCache.has(request)) { + GraphQLHandler.parsedRequestCache.set( + request, + await (0, import_parseGraphQLRequest.parseGraphQLRequest)(request).catch((error) => { + console.error(error); + return void 0; + }) + ); + } + return GraphQLHandler.parsedRequestCache.get(request); + } + async parse(args) { + const match = (0, import_matchRequestUrl.matchRequestUrl)(new URL(args.request.url), this.endpoint); + const cookies = (0, import_getRequestCookies.getAllRequestCookies)(args.request); + if (!match.matches) { + return { + match, + cookies + }; + } + const parsedResult = await this.parseGraphQLRequestOrGetFromCache( + args.request + ); + if (typeof parsedResult === "undefined") { + return { + match, + cookies + }; + } + return { + match, + cookies, + query: parsedResult.query, + operationType: parsedResult.operationType, + operationName: parsedResult.operationName, + variables: parsedResult.variables + }; + } + async predicate(args) { + if (args.parsedResult.operationType === void 0) { + return false; + } + if (!args.parsedResult.operationName && this.info.operationType !== "all") { + const publicUrl = (0, import_toPublicUrl.toPublicUrl)(args.request.url); + import_devUtils.devUtils.warn(`Failed to intercept a GraphQL request at "${args.request.method} ${publicUrl}": anonymous GraphQL operations are not supported. + +Consider naming this operation or using "graphql.operation()" request handler to intercept GraphQL requests regardless of their operation name/type. Read more: https://mswjs.io/docs/api/graphql/#graphqloperationresolver`); + return false; + } + const hasMatchingOperationType = this.info.operationType === "all" || args.parsedResult.operationType === this.info.operationType; + const hasMatchingOperationName = await this.matchOperationName({ + request: args.request, + parsedResult: args.parsedResult + }); + return args.parsedResult.match.matches && hasMatchingOperationType && hasMatchingOperationName; + } + async run(args) { + const result = await super.run(args); + if (result?.response == null) { + return result; + } + if (!(import_HttpResponse.kDefaultContentType in result.response)) { + return result; + } + const acceptedMimeTypes = (0, import_getAllAcceptedMimeTypes.getAllAcceptedMimeTypes)( + args.request.headers.get("accept") + ); + if (acceptedMimeTypes.length === 0) { + return result; + } + const graphqlResponseIndex = acceptedMimeTypes.indexOf( + "application/graphql-response+json" + ); + const jsonIndex = acceptedMimeTypes.indexOf("application/json"); + if (graphqlResponseIndex !== -1 && (jsonIndex === -1 || graphqlResponseIndex <= jsonIndex)) { + result.response.headers.set( + "content-type", + "application/graphql-response+json" + ); + } + return result; + } + async matchOperationName(args) { + if (typeof this.info.operationName === "function") { + const customPredicateResult = await this.info.operationName({ + request: args.request, + ...this.extendResolverArgs({ + request: args.request, + parsedResult: args.parsedResult + }) + }); + return typeof customPredicateResult === "boolean" ? customPredicateResult : customPredicateResult.matches; + } + if (this.info.operationName instanceof RegExp) { + return this.info.operationName.test(args.parsedResult.operationName || ""); + } + return args.parsedResult.operationName === this.info.operationName; + } + extendResolverArgs(args) { + return { + query: args.parsedResult.query || "", + operationType: args.parsedResult.operationType, + operationName: args.parsedResult.operationName || "", + variables: args.parsedResult.variables || {}, + cookies: args.parsedResult.cookies + }; + } + async log(args) { + const loggedRequest = await (0, import_serializeRequest.serializeRequest)(args.request); + const loggedResponse = await (0, import_serializeResponse.serializeResponse)(args.response); + const statusColor = (0, import_getStatusCodeColor.getStatusCodeColor)(loggedResponse.status); + const requestInfo = args.parsedResult.operationName ? `${args.parsedResult.operationType} ${args.parsedResult.operationName}` : `anonymous ${args.parsedResult.operationType}`; + console.groupCollapsed( + import_devUtils.devUtils.formatMessage( + `${(0, import_getTimestamp.getTimestamp)()} ${requestInfo} (%c${loggedResponse.status} ${loggedResponse.statusText}%c)` + ), + `color:${statusColor}`, + "color:inherit" + ); + console.log("Request:", loggedRequest); + console.log("Handler:", this); + console.log("Response:", loggedResponse); + console.groupEnd(); + } +} +//# sourceMappingURL=GraphQLHandler.js.map \ No newline at end of file diff --git a/node_modules/msw/lib/core/handlers/GraphQLHandler.js.map b/node_modules/msw/lib/core/handlers/GraphQLHandler.js.map new file mode 100644 index 0000000000000000000000000000000000000000..9f66cc12738e6e14294dea60585703f1c45d8e78 --- /dev/null +++ b/node_modules/msw/lib/core/handlers/GraphQLHandler.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/core/handlers/GraphQLHandler.ts"],"sourcesContent":["import { invariant } from 'outvariant'\nimport {\n parse,\n type DocumentNode,\n type GraphQLError,\n type OperationTypeNode,\n} from 'graphql'\nimport {\n RequestHandler,\n type DefaultBodyType,\n type RequestHandlerDefaultInfo,\n type RequestHandlerExecutionResult,\n type RequestHandlerOptions,\n type ResponseResolver,\n} from './RequestHandler'\nimport { getTimestamp } from '../utils/logging/getTimestamp'\nimport { getStatusCodeColor } from '../utils/logging/getStatusCodeColor'\nimport { serializeRequest } from '../utils/logging/serializeRequest'\nimport { serializeResponse } from '../utils/logging/serializeResponse'\nimport {\n type Match,\n matchRequestUrl,\n type Path,\n} from '../utils/matching/matchRequestUrl'\nimport {\n type ParsedGraphQLRequest,\n type GraphQLMultipartRequestBody,\n parseGraphQLRequest,\n parseDocumentNode,\n type ParsedGraphQLQuery,\n} from '../utils/internal/parseGraphQLRequest'\nimport { toPublicUrl } from '../utils/request/toPublicUrl'\nimport { devUtils } from '../utils/internal/devUtils'\nimport { getAllRequestCookies } from '../utils/request/getRequestCookies'\nimport { type ResponseResolutionContext } from '../utils/executeHandlers'\nimport { kDefaultContentType, type StrictRequest } from '../HttpResponse'\nimport { getAllAcceptedMimeTypes } from '../utils/request/getAllAcceptedMimeTypes'\n\nexport interface DocumentTypeDecoration<\n Result = { [key: string]: any },\n Variables = { [key: string]: any },\n> {\n __apiType?: (variables: Variables) => Result\n __resultType?: Result\n __variablesType?: Variables\n}\n\nexport type GraphQLOperationType = OperationTypeNode | 'all'\nexport type GraphQLHandlerNameSelector = DocumentNode | RegExp | string\n\nexport type GraphQLQuery = Record | null\nexport type GraphQLVariables = Record\n\nexport interface GraphQLHandlerInfo extends RequestHandlerDefaultInfo {\n operationType: GraphQLOperationType\n operationName: GraphQLHandlerNameSelector | GraphQLCustomPredicate\n}\n\nexport type GraphQLRequestParsedResult = {\n match: Match\n cookies: Record\n} & (\n | ParsedGraphQLRequest\n /**\n * An empty version of the ParsedGraphQLRequest\n * which simplifies the return type of the resolver\n * when the request is to a non-matching endpoint\n */\n | {\n operationType?: undefined\n operationName?: undefined\n query?: undefined\n variables?: undefined\n }\n)\n\nexport type GraphQLResolverExtras = {\n query: string\n operationName: string\n variables: Variables\n cookies: Record\n}\n\nexport type GraphQLRequestBody =\n | GraphQLJsonRequestBody\n | GraphQLMultipartRequestBody\n | Record\n | undefined\n\nexport interface GraphQLJsonRequestBody {\n query: string\n variables?: Variables\n}\n\nexport type GraphQLResponseBody =\n | {\n data?: BodyType | null\n errors?: readonly Partial[] | null\n extensions?: Record\n }\n | null\n | undefined\n\nexport type GraphQLCustomPredicate = (args: {\n request: Request\n query: string\n operationType: GraphQLOperationType\n operationName: string\n variables: GraphQLVariables\n cookies: Record\n}) => GraphQLCustomPredicateResult | Promise\n\nexport type GraphQLCustomPredicateResult = boolean | { matches: boolean }\n\nexport type GraphQLPredicate =\n | GraphQLHandlerNameSelector\n | DocumentTypeDecoration\n | GraphQLCustomPredicate\n\nexport function isDocumentNode(\n value: DocumentNode | any,\n): value is DocumentNode {\n if (value == null) {\n return false\n }\n\n return typeof value === 'object' && 'kind' in value && 'definitions' in value\n}\n\nfunction isDocumentTypeDecoration(\n value: unknown,\n): value is DocumentTypeDecoration {\n return value instanceof String\n}\n\nexport class GraphQLHandler extends RequestHandler<\n GraphQLHandlerInfo,\n GraphQLRequestParsedResult,\n GraphQLResolverExtras\n> {\n private endpoint: Path\n\n static parsedRequestCache = new WeakMap<\n Request,\n ParsedGraphQLRequest\n >()\n\n static #parseOperationName(\n predicate: GraphQLPredicate,\n operationType: GraphQLOperationType,\n ): GraphQLHandlerInfo['operationName'] {\n const getOperationName = (node: ParsedGraphQLQuery): string => {\n invariant(\n node.operationType === operationType,\n 'Failed to create a GraphQL handler: provided a DocumentNode with a mismatched operation type (expected \"%s\" but got \"%s\").',\n operationType,\n node.operationType,\n )\n\n invariant(\n node.operationName,\n 'Failed to create a GraphQL handler: provided a DocumentNode without operation name',\n )\n\n return node.operationName\n }\n\n if (isDocumentNode(predicate)) {\n return getOperationName(parseDocumentNode(predicate))\n }\n\n if (isDocumentTypeDecoration(predicate)) {\n const documentNode = parse(predicate.toString())\n\n invariant(\n isDocumentNode(documentNode),\n 'Failed to create a GraphQL handler: given TypedDocumentString (%s) does not produce a valid DocumentNode',\n predicate,\n )\n\n return getOperationName(parseDocumentNode(documentNode))\n }\n\n return predicate\n }\n\n constructor(\n operationType: GraphQLOperationType,\n predicate: GraphQLPredicate,\n endpoint: Path,\n resolver: ResponseResolver, any, any>,\n options?: RequestHandlerOptions,\n ) {\n const operationName = GraphQLHandler.#parseOperationName(\n predicate,\n operationType,\n )\n\n const displayOperationName =\n typeof operationName === 'function' ? '[custom predicate]' : operationName\n\n const header =\n operationType === 'all'\n ? `${operationType} (origin: ${endpoint.toString()})`\n : `${operationType}${displayOperationName ? ` ${displayOperationName}` : ''} (origin: ${endpoint.toString()})`\n\n super({\n info: {\n header,\n operationType,\n operationName: GraphQLHandler.#parseOperationName(\n predicate,\n operationType,\n ),\n },\n resolver,\n options,\n })\n\n this.endpoint = endpoint\n }\n\n /**\n * Parses the request body, once per request, cached across all\n * GraphQL handlers. This is done to avoid multiple parsing of the\n * request body, which each requires a clone of the request.\n */\n async parseGraphQLRequestOrGetFromCache(\n request: Request,\n ): Promise> {\n if (!GraphQLHandler.parsedRequestCache.has(request)) {\n GraphQLHandler.parsedRequestCache.set(\n request,\n await parseGraphQLRequest(request).catch((error) => {\n console.error(error)\n return undefined\n }),\n )\n }\n\n return GraphQLHandler.parsedRequestCache.get(request)\n }\n\n async parse(args: { request: Request }): Promise {\n /**\n * If the request doesn't match a specified endpoint, there's no\n * need to parse it since there's no case where we would handle this\n */\n const match = matchRequestUrl(new URL(args.request.url), this.endpoint)\n const cookies = getAllRequestCookies(args.request)\n\n if (!match.matches) {\n return {\n match,\n cookies,\n }\n }\n\n const parsedResult = await this.parseGraphQLRequestOrGetFromCache(\n args.request,\n )\n\n if (typeof parsedResult === 'undefined') {\n return {\n match,\n cookies,\n }\n }\n\n return {\n match,\n cookies,\n query: parsedResult.query,\n operationType: parsedResult.operationType,\n operationName: parsedResult.operationName,\n variables: parsedResult.variables,\n }\n }\n\n async predicate(args: {\n request: Request\n parsedResult: GraphQLRequestParsedResult\n }): Promise {\n if (args.parsedResult.operationType === undefined) {\n return false\n }\n\n if (!args.parsedResult.operationName && this.info.operationType !== 'all') {\n const publicUrl = toPublicUrl(args.request.url)\n\n devUtils.warn(`\\\nFailed to intercept a GraphQL request at \"${args.request.method} ${publicUrl}\": anonymous GraphQL operations are not supported.\n\nConsider naming this operation or using \"graphql.operation()\" request handler to intercept GraphQL requests regardless of their operation name/type. Read more: https://mswjs.io/docs/api/graphql/#graphqloperationresolver`)\n return false\n }\n\n const hasMatchingOperationType =\n this.info.operationType === 'all' ||\n args.parsedResult.operationType === this.info.operationType\n\n /**\n * Check if the operation name matches the outgoing GraphQL request.\n * @note Unlike the HTTP handler, the custom predicate functions are invoked\n * during predicate, not parsing, because GraphQL request parsing happens first,\n * and non-GraphQL requests are filtered out automatically.\n */\n const hasMatchingOperationName = await this.matchOperationName({\n request: args.request,\n parsedResult: args.parsedResult,\n })\n\n return (\n args.parsedResult.match.matches &&\n hasMatchingOperationType &&\n hasMatchingOperationName\n )\n }\n\n public async run(args: {\n request: StrictRequest\n requestId: string\n resolutionContext?: ResponseResolutionContext\n }): Promise | null> {\n const result = await super.run(args)\n\n if (result?.response == null) {\n return result\n }\n\n if (!(kDefaultContentType in result.response)) {\n return result\n }\n\n const acceptedMimeTypes = getAllAcceptedMimeTypes(\n args.request.headers.get('accept'),\n )\n\n if (acceptedMimeTypes.length === 0) {\n return result\n }\n\n const graphqlResponseIndex = acceptedMimeTypes.indexOf(\n 'application/graphql-response+json',\n )\n const jsonIndex = acceptedMimeTypes.indexOf('application/json')\n\n /**\n * Use the \"application/graphql-response+json\" response content type\n * only when the client accepts it AND prefers it over \"application/json\"\n * (i.e. it appears earlier in the precedence-sorted list, or \"application/json\"\n * is not listed at all).\n * @see https://github.com/graphql/graphql-over-http/blob/4d1df1fb829ec2dd3ecbf3c6aa4025bd356c270d/spec/GraphQLOverHTTP.md#accept\n */\n if (\n graphqlResponseIndex !== -1 &&\n (jsonIndex === -1 || graphqlResponseIndex <= jsonIndex)\n ) {\n result.response.headers.set(\n 'content-type',\n 'application/graphql-response+json',\n )\n }\n\n return result\n }\n\n private async matchOperationName(args: {\n request: Request\n parsedResult: GraphQLRequestParsedResult\n }): Promise {\n if (typeof this.info.operationName === 'function') {\n const customPredicateResult = await this.info.operationName({\n request: args.request,\n ...this.extendResolverArgs({\n request: args.request,\n parsedResult: args.parsedResult,\n }),\n })\n\n /**\n * @note Keep the { matches } signature in case we decide to support path parameters\n * in GraphQL handlers. If that happens, the custom predicate would have to be moved\n * to the parsing phase, the same as we have for the HttpHandler, and the user will\n * have a possibility to return parsed path parameters from the custom predicate.\n */\n return typeof customPredicateResult === 'boolean'\n ? customPredicateResult\n : customPredicateResult.matches\n }\n\n if (this.info.operationName instanceof RegExp) {\n return this.info.operationName.test(args.parsedResult.operationName || '')\n }\n\n return args.parsedResult.operationName === this.info.operationName\n }\n\n protected extendResolverArgs(args: {\n request: Request\n parsedResult: GraphQLRequestParsedResult\n }) {\n return {\n query: args.parsedResult.query || '',\n operationType: args.parsedResult.operationType!,\n operationName: args.parsedResult.operationName || '',\n variables: args.parsedResult.variables || {},\n cookies: args.parsedResult.cookies,\n }\n }\n\n async log(args: {\n request: Request\n response: Response\n parsedResult: GraphQLRequestParsedResult\n }) {\n const loggedRequest = await serializeRequest(args.request)\n const loggedResponse = await serializeResponse(args.response)\n const statusColor = getStatusCodeColor(loggedResponse.status)\n const requestInfo = args.parsedResult.operationName\n ? `${args.parsedResult.operationType} ${args.parsedResult.operationName}`\n : `anonymous ${args.parsedResult.operationType}`\n\n console.groupCollapsed(\n devUtils.formatMessage(\n `${getTimestamp()} ${requestInfo} (%c${loggedResponse.status} ${\n loggedResponse.statusText\n }%c)`,\n ),\n `color:${statusColor}`,\n 'color:inherit',\n )\n // eslint-disable-next-line no-console\n console.log('Request:', loggedRequest)\n // eslint-disable-next-line no-console\n console.log('Handler:', this)\n // eslint-disable-next-line no-console\n console.log('Response:', loggedResponse)\n console.groupEnd()\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,wBAA0B;AAC1B,qBAKO;AACP,4BAOO;AACP,0BAA6B;AAC7B,gCAAmC;AACnC,8BAAiC;AAC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AAAA,IAC5B;AAEA,QAAI,KAAK,KAAK,yBAAyB,QAAQ;AAC7C,aAAO,KAAK,KAAK,cAAc,KAAK,KAAK,aAAa,iBAAiB,EAAE;AAAA,IAC3E;AAEA,WAAO,KAAK,aAAa,kBAAkB,KAAK,KAAK;AAAA,EACvD;AAAA,EAEU,mBAAmB,MAG1B;AACD,WAAO;AAAA,MACL,OAAO,KAAK,aAAa,SAAS;AAAA,MAClC,eAAe,KAAK,aAAa;AAAA,MACjC,eAAe,KAAK,aAAa,iBAAiB;AAAA,MAClD,WAAW,KAAK,aAAa,aAAa,CAAC;AAAA,MAC3C,SAAS,KAAK,aAAa;AAAA,IAC7B;AAAA,EACF;AAAA,EAEA,MAAM,IAAI,MAIP;AACD,UAAM,gBAAgB,UAAM,0CAAiB,KAAK,OAAO;AACzD,UAAM,iBAAiB,UAAM,4CAAkB,KAAK,QAAQ;AAC5D,UAAM,kBAAc,8CAAmB,eAAe,MAAM;AAC5D,UAAM,cAAc,KAAK,aAAa,gBAClC,GAAG,KAAK,aAAa,aAAa,IAAI,KAAK,aAAa,aAAa,KACrE,aAAa,KAAK,aAAa,aAAa;AAEhD,YAAQ;AAAA,MACN,yBAAS;AAAA,QACP,OAAG,kCAAa,CAAC,IAAI,WAAW,OAAO,eAAe,MAAM,IAC1D,eAAe,UACjB;AAAA,MACF;AAAA,MACA,SAAS,WAAW;AAAA,MACpB;AAAA,IACF;AAEA,YAAQ,IAAI,YAAY,aAAa;AAErC,YAAQ,IAAI,YAAY,IAAI;AAE5B,YAAQ,IAAI,aAAa,cAAc;AACvC,YAAQ,SAAS;AAAA,EACnB;AACF;","names":[]} \ No newline at end of file diff --git a/node_modules/msw/lib/core/handlers/GraphQLHandler.mjs b/node_modules/msw/lib/core/handlers/GraphQLHandler.mjs new file mode 100644 index 0000000000000000000000000000000000000000..1874ef0f4671f0009f9991f3116ba779702511dc --- /dev/null +++ b/node_modules/msw/lib/core/handlers/GraphQLHandler.mjs @@ -0,0 +1,221 @@ +import { invariant } from "outvariant"; +import { + parse +} from "graphql"; +import { + RequestHandler +} from './RequestHandler.mjs'; +import { getTimestamp } from '../utils/logging/getTimestamp.mjs'; +import { getStatusCodeColor } from '../utils/logging/getStatusCodeColor.mjs'; +import { serializeRequest } from '../utils/logging/serializeRequest.mjs'; +import { serializeResponse } from '../utils/logging/serializeResponse.mjs'; +import { + matchRequestUrl +} from '../utils/matching/matchRequestUrl.mjs'; +import { + parseGraphQLRequest, + parseDocumentNode +} from '../utils/internal/parseGraphQLRequest.mjs'; +import { toPublicUrl } from '../utils/request/toPublicUrl.mjs'; +import { devUtils } from '../utils/internal/devUtils.mjs'; +import { getAllRequestCookies } from '../utils/request/getRequestCookies.mjs'; +import {} from '../utils/executeHandlers.mjs'; +import { kDefaultContentType } from '../HttpResponse.mjs'; +import { getAllAcceptedMimeTypes } from '../utils/request/getAllAcceptedMimeTypes.mjs'; +function isDocumentNode(value) { + if (value == null) { + return false; + } + return typeof value === "object" && "kind" in value && "definitions" in value; +} +function isDocumentTypeDecoration(value) { + return value instanceof String; +} +class GraphQLHandler extends RequestHandler { + endpoint; + static parsedRequestCache = /* @__PURE__ */ new WeakMap(); + static #parseOperationName(predicate, operationType) { + const getOperationName = (node) => { + invariant( + node.operationType === operationType, + 'Failed to create a GraphQL handler: provided a DocumentNode with a mismatched operation type (expected "%s" but got "%s").', + operationType, + node.operationType + ); + invariant( + node.operationName, + "Failed to create a GraphQL handler: provided a DocumentNode without operation name" + ); + return node.operationName; + }; + if (isDocumentNode(predicate)) { + return getOperationName(parseDocumentNode(predicate)); + } + if (isDocumentTypeDecoration(predicate)) { + const documentNode = parse(predicate.toString()); + invariant( + isDocumentNode(documentNode), + "Failed to create a GraphQL handler: given TypedDocumentString (%s) does not produce a valid DocumentNode", + predicate + ); + return getOperationName(parseDocumentNode(documentNode)); + } + return predicate; + } + constructor(operationType, predicate, endpoint, resolver, options) { + const operationName = GraphQLHandler.#parseOperationName( + predicate, + operationType + ); + const displayOperationName = typeof operationName === "function" ? "[custom predicate]" : operationName; + const header = operationType === "all" ? `${operationType} (origin: ${endpoint.toString()})` : `${operationType}${displayOperationName ? ` ${displayOperationName}` : ""} (origin: ${endpoint.toString()})`; + super({ + info: { + header, + operationType, + operationName: GraphQLHandler.#parseOperationName( + predicate, + operationType + ) + }, + resolver, + options + }); + this.endpoint = endpoint; + } + /** + * Parses the request body, once per request, cached across all + * GraphQL handlers. This is done to avoid multiple parsing of the + * request body, which each requires a clone of the request. + */ + async parseGraphQLRequestOrGetFromCache(request) { + if (!GraphQLHandler.parsedRequestCache.has(request)) { + GraphQLHandler.parsedRequestCache.set( + request, + await parseGraphQLRequest(request).catch((error) => { + console.error(error); + return void 0; + }) + ); + } + return GraphQLHandler.parsedRequestCache.get(request); + } + async parse(args) { + const match = matchRequestUrl(new URL(args.request.url), this.endpoint); + const cookies = getAllRequestCookies(args.request); + if (!match.matches) { + return { + match, + cookies + }; + } + const parsedResult = await this.parseGraphQLRequestOrGetFromCache( + args.request + ); + if (typeof parsedResult === "undefined") { + return { + match, + cookies + }; + } + return { + match, + cookies, + query: parsedResult.query, + operationType: parsedResult.operationType, + operationName: parsedResult.operationName, + variables: parsedResult.variables + }; + } + async predicate(args) { + if (args.parsedResult.operationType === void 0) { + return false; + } + if (!args.parsedResult.operationName && this.info.operationType !== "all") { + const publicUrl = toPublicUrl(args.request.url); + devUtils.warn(`Failed to intercept a GraphQL request at "${args.request.method} ${publicUrl}": anonymous GraphQL operations are not supported. + +Consider naming this operation or using "graphql.operation()" request handler to intercept GraphQL requests regardless of their operation name/type. Read more: https://mswjs.io/docs/api/graphql/#graphqloperationresolver`); + return false; + } + const hasMatchingOperationType = this.info.operationType === "all" || args.parsedResult.operationType === this.info.operationType; + const hasMatchingOperationName = await this.matchOperationName({ + request: args.request, + parsedResult: args.parsedResult + }); + return args.parsedResult.match.matches && hasMatchingOperationType && hasMatchingOperationName; + } + async run(args) { + const result = await super.run(args); + if (result?.response == null) { + return result; + } + if (!(kDefaultContentType in result.response)) { + return result; + } + const acceptedMimeTypes = getAllAcceptedMimeTypes( + args.request.headers.get("accept") + ); + if (acceptedMimeTypes.length === 0) { + return result; + } + const graphqlResponseIndex = acceptedMimeTypes.indexOf( + "application/graphql-response+json" + ); + const jsonIndex = acceptedMimeTypes.indexOf("application/json"); + if (graphqlResponseIndex !== -1 && (jsonIndex === -1 || graphqlResponseIndex <= jsonIndex)) { + result.response.headers.set( + "content-type", + "application/graphql-response+json" + ); + } + return result; + } + async matchOperationName(args) { + if (typeof this.info.operationName === "function") { + const customPredicateResult = await this.info.operationName({ + request: args.request, + ...this.extendResolverArgs({ + request: args.request, + parsedResult: args.parsedResult + }) + }); + return typeof customPredicateResult === "boolean" ? customPredicateResult : customPredicateResult.matches; + } + if (this.info.operationName instanceof RegExp) { + return this.info.operationName.test(args.parsedResult.operationName || ""); + } + return args.parsedResult.operationName === this.info.operationName; + } + extendResolverArgs(args) { + return { + query: args.parsedResult.query || "", + operationType: args.parsedResult.operationType, + operationName: args.parsedResult.operationName || "", + variables: args.parsedResult.variables || {}, + cookies: args.parsedResult.cookies + }; + } + async log(args) { + const loggedRequest = await serializeRequest(args.request); + const loggedResponse = await serializeResponse(args.response); + const statusColor = getStatusCodeColor(loggedResponse.status); + const requestInfo = args.parsedResult.operationName ? `${args.parsedResult.operationType} ${args.parsedResult.operationName}` : `anonymous ${args.parsedResult.operationType}`; + console.groupCollapsed( + devUtils.formatMessage( + `${getTimestamp()} ${requestInfo} (%c${loggedResponse.status} ${loggedResponse.statusText}%c)` + ), + `color:${statusColor}`, + "color:inherit" + ); + console.log("Request:", loggedRequest); + console.log("Handler:", this); + console.log("Response:", loggedResponse); + console.groupEnd(); + } +} +export { + GraphQLHandler, + isDocumentNode +}; +//# sourceMappingURL=GraphQLHandler.mjs.map \ No newline at end of file diff --git a/node_modules/msw/lib/core/handlers/GraphQLHandler.mjs.map b/node_modules/msw/lib/core/handlers/GraphQLHandler.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..245d129986102999518e06dc5d0cd4b4a17e6223 --- /dev/null +++ b/node_modules/msw/lib/core/handlers/GraphQLHandler.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/core/handlers/GraphQLHandler.ts"],"sourcesContent":["import { invariant } from 'outvariant'\nimport {\n parse,\n type DocumentNode,\n type GraphQLError,\n type OperationTypeNode,\n} from 'graphql'\nimport {\n RequestHandler,\n type DefaultBodyType,\n type RequestHandlerDefaultInfo,\n type RequestHandlerExecutionResult,\n type RequestHandlerOptions,\n type ResponseResolver,\n} from './RequestHandler'\nimport { getTimestamp } from '../utils/logging/getTimestamp'\nimport { getStatusCodeColor } from '../utils/logging/getStatusCodeColor'\nimport { serializeRequest } from '../utils/logging/serializeRequest'\nimport { serializeResponse } from '../utils/logging/serializeResponse'\nimport {\n type Match,\n matchRequestUrl,\n type Path,\n} from '../utils/matching/matchRequestUrl'\nimport {\n type ParsedGraphQLRequest,\n type GraphQLMultipartRequestBody,\n parseGraphQLRequest,\n parseDocumentNode,\n type ParsedGraphQLQuery,\n} from '../utils/internal/parseGraphQLRequest'\nimport { toPublicUrl } from '../utils/request/toPublicUrl'\nimport { devUtils } from '../utils/internal/devUtils'\nimport { getAllRequestCookies } from '../utils/request/getRequestCookies'\nimport { type ResponseResolutionContext } from '../utils/executeHandlers'\nimport { kDefaultContentType, type StrictRequest } from '../HttpResponse'\nimport { getAllAcceptedMimeTypes } from '../utils/request/getAllAcceptedMimeTypes'\n\nexport interface DocumentTypeDecoration<\n Result = { [key: string]: any },\n Variables = { [key: string]: any },\n> {\n __apiType?: (variables: Variables) => Result\n __resultType?: Result\n __variablesType?: Variables\n}\n\nexport type GraphQLOperationType = OperationTypeNode | 'all'\nexport type GraphQLHandlerNameSelector = DocumentNode | RegExp | string\n\nexport type GraphQLQuery = Record | null\nexport type GraphQLVariables = Record\n\nexport interface GraphQLHandlerInfo extends RequestHandlerDefaultInfo {\n operationType: GraphQLOperationType\n operationName: GraphQLHandlerNameSelector | GraphQLCustomPredicate\n}\n\nexport type GraphQLRequestParsedResult = {\n match: Match\n cookies: Record\n} & (\n | ParsedGraphQLRequest\n /**\n * An empty version of the ParsedGraphQLRequest\n * which simplifies the return type of the resolver\n * when the request is to a non-matching endpoint\n */\n | {\n operationType?: undefined\n operationName?: undefined\n query?: undefined\n variables?: undefined\n }\n)\n\nexport type GraphQLResolverExtras = {\n query: string\n operationName: string\n variables: Variables\n cookies: Record\n}\n\nexport type GraphQLRequestBody =\n | GraphQLJsonRequestBody\n | GraphQLMultipartRequestBody\n | Record\n | undefined\n\nexport interface GraphQLJsonRequestBody {\n query: string\n variables?: Variables\n}\n\nexport type GraphQLResponseBody =\n | {\n data?: BodyType | null\n errors?: readonly Partial[] | null\n extensions?: Record\n }\n | null\n | undefined\n\nexport type GraphQLCustomPredicate = (args: {\n request: Request\n query: string\n operationType: GraphQLOperationType\n operationName: string\n variables: GraphQLVariables\n cookies: Record\n}) => GraphQLCustomPredicateResult | Promise\n\nexport type GraphQLCustomPredicateResult = boolean | { matches: boolean }\n\nexport type GraphQLPredicate =\n | GraphQLHandlerNameSelector\n | DocumentTypeDecoration\n | GraphQLCustomPredicate\n\nexport function isDocumentNode(\n value: DocumentNode | any,\n): value is DocumentNode {\n if (value == null) {\n return false\n }\n\n return typeof value === 'object' && 'kind' in value && 'definitions' in value\n}\n\nfunction isDocumentTypeDecoration(\n value: unknown,\n): value is DocumentTypeDecoration {\n return value instanceof String\n}\n\nexport class GraphQLHandler extends RequestHandler<\n GraphQLHandlerInfo,\n GraphQLRequestParsedResult,\n GraphQLResolverExtras\n> {\n private endpoint: Path\n\n static parsedRequestCache = new WeakMap<\n Request,\n ParsedGraphQLRequest\n >()\n\n static #parseOperationName(\n predicate: GraphQLPredicate,\n operationType: GraphQLOperationType,\n ): GraphQLHandlerInfo['operationName'] {\n const getOperationName = (node: ParsedGraphQLQuery): string => {\n invariant(\n node.operationType === operationType,\n 'Failed to create a GraphQL handler: provided a DocumentNode with a mismatched operation type (expected \"%s\" but got \"%s\").',\n operationType,\n node.operationType,\n )\n\n invariant(\n node.operationName,\n 'Failed to create a GraphQL handler: provided a DocumentNode without operation name',\n )\n\n return node.operationName\n }\n\n if (isDocumentNode(predicate)) {\n return getOperationName(parseDocumentNode(predicate))\n }\n\n if (isDocumentTypeDecoration(predicate)) {\n const documentNode = parse(predicate.toString())\n\n invariant(\n isDocumentNode(documentNode),\n 'Failed to create a GraphQL handler: given TypedDocumentString (%s) does not produce a valid DocumentNode',\n predicate,\n )\n\n return getOperationName(parseDocumentNode(documentNode))\n }\n\n return predicate\n }\n\n constructor(\n operationType: GraphQLOperationType,\n predicate: GraphQLPredicate,\n endpoint: Path,\n resolver: ResponseResolver, any, any>,\n options?: RequestHandlerOptions,\n ) {\n const operationName = GraphQLHandler.#parseOperationName(\n predicate,\n operationType,\n )\n\n const displayOperationName =\n typeof operationName === 'function' ? '[custom predicate]' : operationName\n\n const header =\n operationType === 'all'\n ? `${operationType} (origin: ${endpoint.toString()})`\n : `${operationType}${displayOperationName ? ` ${displayOperationName}` : ''} (origin: ${endpoint.toString()})`\n\n super({\n info: {\n header,\n operationType,\n operationName: GraphQLHandler.#parseOperationName(\n predicate,\n operationType,\n ),\n },\n resolver,\n options,\n })\n\n this.endpoint = endpoint\n }\n\n /**\n * Parses the request body, once per request, cached across all\n * GraphQL handlers. This is done to avoid multiple parsing of the\n * request body, which each requires a clone of the request.\n */\n async parseGraphQLRequestOrGetFromCache(\n request: Request,\n ): Promise> {\n if (!GraphQLHandler.parsedRequestCache.has(request)) {\n GraphQLHandler.parsedRequestCache.set(\n request,\n await parseGraphQLRequest(request).catch((error) => {\n console.error(error)\n return undefined\n }),\n )\n }\n\n return GraphQLHandler.parsedRequestCache.get(request)\n }\n\n async parse(args: { request: Request }): Promise {\n /**\n * If the request doesn't match a specified endpoint, there's no\n * need to parse it since there's no case where we would handle this\n */\n const match = matchRequestUrl(new URL(args.request.url), this.endpoint)\n const cookies = getAllRequestCookies(args.request)\n\n if (!match.matches) {\n return {\n match,\n cookies,\n }\n }\n\n const parsedResult = await this.parseGraphQLRequestOrGetFromCache(\n args.request,\n )\n\n if (typeof parsedResult === 'undefined') {\n return {\n match,\n cookies,\n }\n }\n\n return {\n match,\n cookies,\n query: parsedResult.query,\n operationType: parsedResult.operationType,\n operationName: parsedResult.operationName,\n variables: parsedResult.variables,\n }\n }\n\n async predicate(args: {\n request: Request\n parsedResult: GraphQLRequestParsedResult\n }): Promise {\n if (args.parsedResult.operationType === undefined) {\n return false\n }\n\n if (!args.parsedResult.operationName && this.info.operationType !== 'all') {\n const publicUrl = toPublicUrl(args.request.url)\n\n devUtils.warn(`\\\nFailed to intercept a GraphQL request at \"${args.request.method} ${publicUrl}\": anonymous GraphQL operations are not supported.\n\nConsider naming this operation or using \"graphql.operation()\" request handler to intercept GraphQL requests regardless of their operation name/type. Read more: https://mswjs.io/docs/api/graphql/#graphqloperationresolver`)\n return false\n }\n\n const hasMatchingOperationType =\n this.info.operationType === 'all' ||\n args.parsedResult.operationType === this.info.operationType\n\n /**\n * Check if the operation name matches the outgoing GraphQL request.\n * @note Unlike the HTTP handler, the custom predicate functions are invoked\n * during predicate, not parsing, because GraphQL request parsing happens first,\n * and non-GraphQL requests are filtered out automatically.\n */\n const hasMatchingOperationName = await this.matchOperationName({\n request: args.request,\n parsedResult: args.parsedResult,\n })\n\n return (\n args.parsedResult.match.matches &&\n hasMatchingOperationType &&\n hasMatchingOperationName\n )\n }\n\n public async run(args: {\n request: StrictRequest\n requestId: string\n resolutionContext?: ResponseResolutionContext\n }): Promise | null> {\n const result = await super.run(args)\n\n if (result?.response == null) {\n return result\n }\n\n if (!(kDefaultContentType in result.response)) {\n return result\n }\n\n const acceptedMimeTypes = getAllAcceptedMimeTypes(\n args.request.headers.get('accept'),\n )\n\n if (acceptedMimeTypes.length === 0) {\n return result\n }\n\n const graphqlResponseIndex = acceptedMimeTypes.indexOf(\n 'application/graphql-response+json',\n )\n const jsonIndex = acceptedMimeTypes.indexOf('application/json')\n\n /**\n * Use the \"application/graphql-response+json\" response content type\n * only when the client accepts it AND prefers it over \"application/json\"\n * (i.e. it appears earlier in the precedence-sorted list, or \"application/json\"\n * is not listed at all).\n * @see https://github.com/graphql/graphql-over-http/blob/4d1df1fb829ec2dd3ecbf3c6aa4025bd356c270d/spec/GraphQLOverHTTP.md#accept\n */\n if (\n graphqlResponseIndex !== -1 &&\n (jsonIndex === -1 || graphqlResponseIndex <= jsonIndex)\n ) {\n result.response.headers.set(\n 'content-type',\n 'application/graphql-response+json',\n )\n }\n\n return result\n }\n\n private async matchOperationName(args: {\n request: Request\n parsedResult: GraphQLRequestParsedResult\n }): Promise {\n if (typeof this.info.operationName === 'function') {\n const customPredicateResult = await this.info.operationName({\n request: args.request,\n ...this.extendResolverArgs({\n request: args.request,\n parsedResult: args.parsedResult,\n }),\n })\n\n /**\n * @note Keep the { matches } signature in case we decide to support path parameters\n * in GraphQL handlers. If that happens, the custom predicate would have to be moved\n * to the parsing phase, the same as we have for the HttpHandler, and the user will\n * have a possibility to return parsed path parameters from the custom predicate.\n */\n return typeof customPredicateResult === 'boolean'\n ? customPredicateResult\n : customPredicateResult.matches\n }\n\n if (this.info.operationName instanceof RegExp) {\n return this.info.operationName.test(args.parsedResult.operationName || '')\n }\n\n return args.parsedResult.operationName === this.info.operationName\n }\n\n protected extendResolverArgs(args: {\n request: Request\n parsedResult: GraphQLRequestParsedResult\n }) {\n return {\n query: args.parsedResult.query || '',\n operationType: args.parsedResult.operationType!,\n operationName: args.parsedResult.operationName || '',\n variables: args.parsedResult.variables || {},\n cookies: args.parsedResult.cookies,\n }\n }\n\n async log(args: {\n request: Request\n response: Response\n parsedResult: GraphQLRequestParsedResult\n }) {\n const loggedRequest = await serializeRequest(args.request)\n const loggedResponse = await serializeResponse(args.response)\n const statusColor = getStatusCodeColor(loggedResponse.status)\n const requestInfo = args.parsedResult.operationName\n ? `${args.parsedResult.operationType} ${args.parsedResult.operationName}`\n : `anonymous ${args.parsedResult.operationType}`\n\n console.groupCollapsed(\n devUtils.formatMessage(\n `${getTimestamp()} ${requestInfo} (%c${loggedResponse.status} ${\n loggedResponse.statusText\n }%c)`,\n ),\n `color:${statusColor}`,\n 'color:inherit',\n )\n // eslint-disable-next-line no-console\n console.log('Request:', loggedRequest)\n // eslint-disable-next-line no-console\n console.log('Handler:', this)\n // eslint-disable-next-line no-console\n console.log('Response:', loggedResponse)\n console.groupEnd()\n }\n}\n"],"mappings":"AAAA,SAAS,iBAAiB;AAC1B;AAAA,EACE;AAAA,OAIK;AACP;AAAA,EACE;AAAA,OAMK;AACP,SAAS,oBAAoB;AAC7B,SAAS,0BAA0B;AACnC,SAAS,wBAAwB;AACjC,SAAS,yBAAyB;AAClC;AAAA,EAEE;AAAA,OAEK;AACP;AAAA,EAGE;AAAA,EACA;AAAA,OAEK;AACP,SAAS,mBAAmB;AAC5B,SAAS,gBAAgB;AACzB,SAAS,4BAA4B;AACrC,eAA+C;AAC/C,SAAS,2BAA+C;AACxD,SAAS,+BAA+B;AAmFjC,SAAS,eACd,OACuB;AACvB,MAAI,SAAS,MAAM;AACjB,WAAO;AAAA,EACT;AAEA,SAAO,OAAO,UAAU,YAAY,UAAU,SAAS,iBAAiB;AAC1E;AAEA,SAAS,yBACP,OAC2C;AAC3C,SAAO,iBAAiB;AAC1B;AAEO,MAAM,uBAAuB,eAIlC;AAAA,EACQ;AAAA,EAER,OAAO,qBAAqB,oBAAI,QAG9B;AAAA,EAEF,OAAO,oBACL,WACA,eACqC;AACrC,UAAM,mBAAmB,CAAC,SAAqC;AAC7D;AAAA,QACE,KAAK,kBAAkB;AAAA,QACvB;AAAA,QACA;AAAA,QACA,KAAK;AAAA,MACP;AAEA;AAAA,QACE,KAAK;AAAA,QACL;AAAA,MACF;AAEA,aAAO,KAAK;AAAA,IACd;AAEA,QAAI,eAAe,SAAS,GAAG;AAC7B,aAAO,iBAAiB,kBAAkB,SAAS,CAAC;AAAA,IACtD;AAEA,QAAI,yBAAyB,SAAS,GAAG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;AAAA,QACP,GAAG,aAAa,CAAC,IAAI,WAAW,OAAO,eAAe,MAAM,IAC1D,eAAe,UACjB;AAAA,MACF;AAAA,MACA,SAAS,WAAW;AAAA,MACpB;AAAA,IACF;AAEA,YAAQ,IAAI,YAAY,aAAa;AAErC,YAAQ,IAAI,YAAY,IAAI;AAE5B,YAAQ,IAAI,aAAa,cAAc;AACvC,YAAQ,SAAS;AAAA,EACnB;AACF;","names":[]} \ No newline at end of file diff --git a/node_modules/msw/lib/core/handlers/HttpHandler.d.mts b/node_modules/msw/lib/core/handlers/HttpHandler.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..a5a5d321819196a46568ee19e34270de50ec7ce4 --- /dev/null +++ b/node_modules/msw/lib/core/handlers/HttpHandler.d.mts @@ -0,0 +1,75 @@ +import { R as RequestHandler, r as RequestHandlerDefaultInfo, a as ResponseResolver, c as RequestHandlerOptions, m as ResponseResolutionContext } from '../HttpResponse-CQwYpuKo.mjs'; +import { PathParams, Path, Match } from '../utils/matching/matchRequestUrl.mjs'; +import '@mswjs/interceptors'; +import '../utils/internal/isIterable.mjs'; +import '../typeUtils.mjs'; +import 'graphql'; + +type HttpHandlerMethod = string | RegExp; +interface HttpHandlerInfo extends RequestHandlerDefaultInfo { + method: HttpHandlerMethod; + path: HttpRequestPredicate; +} +declare enum HttpMethods { + HEAD = "HEAD", + GET = "GET", + POST = "POST", + PUT = "PUT", + PATCH = "PATCH", + OPTIONS = "OPTIONS", + DELETE = "DELETE" +} +type RequestQuery = { + [queryName: string]: string; +}; +type HttpRequestParsedResult = { + match: Match; + cookies: Record; +}; +type HttpRequestResolverExtras = { + params: Params; + cookies: Record; +}; +type HttpCustomPredicate = (args: { + request: Request; + cookies: Record; +}) => HttpCustomPredicateResult | Promise>; +type HttpCustomPredicateResult = boolean | { + matches: boolean; + params: Params; +}; +type HttpRequestPredicate = Path | HttpCustomPredicate; +/** + * Request handler for HTTP requests. + * Provides request matching based on method and URL. + */ +declare class HttpHandler extends RequestHandler> { + constructor(method: HttpHandlerMethod, predicate: HttpRequestPredicate, resolver: ResponseResolver, any, any>, options?: RequestHandlerOptions); + private checkRedundantQueryParameters; + parse(args: { + request: Request; + resolutionContext?: ResponseResolutionContext; + }): Promise<{ + match: Match; + cookies: Record; + }>; + predicate(args: { + request: Request; + parsedResult: HttpRequestParsedResult; + resolutionContext?: ResponseResolutionContext; + }): Promise; + private matchMethod; + protected extendResolverArgs(args: { + request: Request; + parsedResult: HttpRequestParsedResult; + }): { + params: PathParams; + cookies: Record; + }; + log(args: { + request: Request; + response: Response; + }): Promise; +} + +export { type HttpCustomPredicate, type HttpCustomPredicateResult, HttpHandler, type HttpHandlerInfo, type HttpHandlerMethod, HttpMethods, type HttpRequestParsedResult, type HttpRequestPredicate, type HttpRequestResolverExtras, type RequestQuery }; diff --git a/node_modules/msw/lib/core/handlers/HttpHandler.d.ts b/node_modules/msw/lib/core/handlers/HttpHandler.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8f3b3f9b395a8f1574da31d151f2e0210c414d15 --- /dev/null +++ b/node_modules/msw/lib/core/handlers/HttpHandler.d.ts @@ -0,0 +1,75 @@ +import { R as RequestHandler, r as RequestHandlerDefaultInfo, a as ResponseResolver, c as RequestHandlerOptions, m as ResponseResolutionContext } from '../HttpResponse-BFS34nkx.js'; +import { PathParams, Path, Match } from '../utils/matching/matchRequestUrl.js'; +import '@mswjs/interceptors'; +import '../utils/internal/isIterable.js'; +import '../typeUtils.js'; +import 'graphql'; + +type HttpHandlerMethod = string | RegExp; +interface HttpHandlerInfo extends RequestHandlerDefaultInfo { + method: HttpHandlerMethod; + path: HttpRequestPredicate; +} +declare enum HttpMethods { + HEAD = "HEAD", + GET = "GET", + POST = "POST", + PUT = "PUT", + PATCH = "PATCH", + OPTIONS = "OPTIONS", + DELETE = "DELETE" +} +type RequestQuery = { + [queryName: string]: string; +}; +type HttpRequestParsedResult = { + match: Match; + cookies: Record; +}; +type HttpRequestResolverExtras = { + params: Params; + cookies: Record; +}; +type HttpCustomPredicate = (args: { + request: Request; + cookies: Record; +}) => HttpCustomPredicateResult | Promise>; +type HttpCustomPredicateResult = boolean | { + matches: boolean; + params: Params; +}; +type HttpRequestPredicate = Path | HttpCustomPredicate; +/** + * Request handler for HTTP requests. + * Provides request matching based on method and URL. + */ +declare class HttpHandler extends RequestHandler> { + constructor(method: HttpHandlerMethod, predicate: HttpRequestPredicate, resolver: ResponseResolver, any, any>, options?: RequestHandlerOptions); + private checkRedundantQueryParameters; + parse(args: { + request: Request; + resolutionContext?: ResponseResolutionContext; + }): Promise<{ + match: Match; + cookies: Record; + }>; + predicate(args: { + request: Request; + parsedResult: HttpRequestParsedResult; + resolutionContext?: ResponseResolutionContext; + }): Promise; + private matchMethod; + protected extendResolverArgs(args: { + request: Request; + parsedResult: HttpRequestParsedResult; + }): { + params: PathParams; + cookies: Record; + }; + log(args: { + request: Request; + response: Response; + }): Promise; +} + +export { type HttpCustomPredicate, type HttpCustomPredicateResult, HttpHandler, type HttpHandlerInfo, type HttpHandlerMethod, HttpMethods, type HttpRequestParsedResult, type HttpRequestPredicate, type HttpRequestResolverExtras, type RequestQuery }; diff --git a/node_modules/msw/lib/core/handlers/HttpHandler.js b/node_modules/msw/lib/core/handlers/HttpHandler.js new file mode 100644 index 0000000000000000000000000000000000000000..1c8d50c618b9d0f06f9e89a079718318970d3d2d --- /dev/null +++ b/node_modules/msw/lib/core/handlers/HttpHandler.js @@ -0,0 +1,129 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var HttpHandler_exports = {}; +__export(HttpHandler_exports, { + HttpHandler: () => HttpHandler, + HttpMethods: () => HttpMethods +}); +module.exports = __toCommonJS(HttpHandler_exports); +var import_executeHandlers = require("../utils/executeHandlers"); +var import_devUtils = require("../utils/internal/devUtils"); +var import_isStringEqual = require("../utils/internal/isStringEqual"); +var import_getStatusCodeColor = require("../utils/logging/getStatusCodeColor"); +var import_getTimestamp = require("../utils/logging/getTimestamp"); +var import_serializeRequest = require("../utils/logging/serializeRequest"); +var import_serializeResponse = require("../utils/logging/serializeResponse"); +var import_matchRequestUrl = require("../utils/matching/matchRequestUrl"); +var import_toPublicUrl = require("../utils/request/toPublicUrl"); +var import_getRequestCookies = require("../utils/request/getRequestCookies"); +var import_cleanUrl = require("../utils/url/cleanUrl"); +var import_RequestHandler = require("./RequestHandler"); +var HttpMethods = /* @__PURE__ */ ((HttpMethods2) => { + HttpMethods2["HEAD"] = "HEAD"; + HttpMethods2["GET"] = "GET"; + HttpMethods2["POST"] = "POST"; + HttpMethods2["PUT"] = "PUT"; + HttpMethods2["PATCH"] = "PATCH"; + HttpMethods2["OPTIONS"] = "OPTIONS"; + HttpMethods2["DELETE"] = "DELETE"; + return HttpMethods2; +})(HttpMethods || {}); +class HttpHandler extends import_RequestHandler.RequestHandler { + constructor(method, predicate, resolver, options) { + const displayPath = typeof predicate === "function" ? "[custom predicate]" : predicate; + super({ + info: { + header: `${method}${displayPath ? ` ${displayPath}` : ""}`, + path: predicate, + method + }, + resolver, + options + }); + this.checkRedundantQueryParameters(); + } + checkRedundantQueryParameters() { + const { method, path } = this.info; + if (!path || path instanceof RegExp || typeof path === "function") { + return; + } + const url = (0, import_cleanUrl.cleanUrl)(path); + if (url === path) { + return; + } + import_devUtils.devUtils.warn( + `Found a redundant usage of query parameters in the request handler URL for "${method} ${path}". Please match against a path instead and access query parameters using "new URL(request.url).searchParams" instead. Learn more: https://mswjs.io/docs/http/intercepting-requests#querysearch-parameters` + ); + } + async parse(args) { + const url = new URL(args.request.url); + const cookies = (0, import_getRequestCookies.getAllRequestCookies)(args.request); + if (typeof this.info.path === "function") { + const customPredicateResult = await this.info.path({ + request: args.request, + cookies + }); + const match2 = typeof customPredicateResult === "boolean" ? { + matches: customPredicateResult, + params: {} + } : customPredicateResult; + return { + match: match2, + cookies + }; + } + const match = this.info.path ? (0, import_matchRequestUrl.matchRequestUrl)(url, this.info.path, args.resolutionContext?.baseUrl) : { matches: false, params: {} }; + return { + match, + cookies + }; + } + async predicate(args) { + const hasMatchingMethod = this.matchMethod(args.request.method); + const hasMatchingUrl = args.parsedResult.match.matches; + return hasMatchingMethod && hasMatchingUrl; + } + matchMethod(actualMethod) { + return this.info.method instanceof RegExp ? this.info.method.test(actualMethod) : (0, import_isStringEqual.isStringEqual)(this.info.method, actualMethod); + } + extendResolverArgs(args) { + return { + params: args.parsedResult.match?.params || {}, + cookies: args.parsedResult.cookies + }; + } + async log(args) { + const publicUrl = (0, import_toPublicUrl.toPublicUrl)(args.request.url); + const loggedRequest = await (0, import_serializeRequest.serializeRequest)(args.request); + const loggedResponse = await (0, import_serializeResponse.serializeResponse)(args.response); + const statusColor = (0, import_getStatusCodeColor.getStatusCodeColor)(loggedResponse.status); + console.groupCollapsed( + import_devUtils.devUtils.formatMessage( + `${(0, import_getTimestamp.getTimestamp)()} ${args.request.method} ${publicUrl} (%c${loggedResponse.status} ${loggedResponse.statusText}%c)` + ), + `color:${statusColor}`, + "color:inherit" + ); + console.log("Request", loggedRequest); + console.log("Handler:", this); + console.log("Response", loggedResponse); + console.groupEnd(); + } +} +//# sourceMappingURL=HttpHandler.js.map \ No newline at end of file diff --git a/node_modules/msw/lib/core/handlers/HttpHandler.js.map b/node_modules/msw/lib/core/handlers/HttpHandler.js.map new file mode 100644 index 0000000000000000000000000000000000000000..a20ee48981d0b060af76e77c6a7a0318f7fe78f4 --- /dev/null +++ b/node_modules/msw/lib/core/handlers/HttpHandler.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/core/handlers/HttpHandler.ts"],"sourcesContent":["import { type ResponseResolutionContext } from '../utils/executeHandlers'\nimport { devUtils } from '../utils/internal/devUtils'\nimport { isStringEqual } from '../utils/internal/isStringEqual'\nimport { getStatusCodeColor } from '../utils/logging/getStatusCodeColor'\nimport { getTimestamp } from '../utils/logging/getTimestamp'\nimport { serializeRequest } from '../utils/logging/serializeRequest'\nimport { serializeResponse } from '../utils/logging/serializeResponse'\nimport {\n matchRequestUrl,\n type Match,\n type Path,\n type PathParams,\n} from '../utils/matching/matchRequestUrl'\nimport { toPublicUrl } from '../utils/request/toPublicUrl'\nimport { getAllRequestCookies } from '../utils/request/getRequestCookies'\nimport { cleanUrl } from '../utils/url/cleanUrl'\nimport {\n RequestHandler,\n type RequestHandlerDefaultInfo,\n type RequestHandlerOptions,\n type ResponseResolver,\n} from './RequestHandler'\n\nexport type HttpHandlerMethod = string | RegExp\n\nexport interface HttpHandlerInfo extends RequestHandlerDefaultInfo {\n method: HttpHandlerMethod\n path: HttpRequestPredicate\n}\n\nexport enum HttpMethods {\n HEAD = 'HEAD',\n GET = 'GET',\n POST = 'POST',\n PUT = 'PUT',\n PATCH = 'PATCH',\n OPTIONS = 'OPTIONS',\n DELETE = 'DELETE',\n}\n\nexport type RequestQuery = {\n [queryName: string]: string\n}\n\nexport type HttpRequestParsedResult = {\n match: Match\n cookies: Record\n}\n\nexport type HttpRequestResolverExtras = {\n params: Params\n cookies: Record\n}\n\nexport type HttpCustomPredicate = (args: {\n request: Request\n cookies: Record\n}) =>\n | HttpCustomPredicateResult\n | Promise>\n\nexport type HttpCustomPredicateResult =\n | boolean\n | {\n matches: boolean\n params: Params\n }\n\nexport type HttpRequestPredicate =\n | Path\n | HttpCustomPredicate\n\n/**\n * Request handler for HTTP requests.\n * Provides request matching based on method and URL.\n */\nexport class HttpHandler extends RequestHandler<\n HttpHandlerInfo,\n HttpRequestParsedResult,\n HttpRequestResolverExtras\n> {\n constructor(\n method: HttpHandlerMethod,\n predicate: HttpRequestPredicate,\n resolver: ResponseResolver, any, any>,\n options?: RequestHandlerOptions,\n ) {\n const displayPath =\n typeof predicate === 'function' ? '[custom predicate]' : predicate\n\n super({\n info: {\n header: `${method}${displayPath ? ` ${displayPath}` : ''}`,\n path: predicate,\n method,\n },\n resolver,\n options,\n })\n\n this.checkRedundantQueryParameters()\n }\n\n private checkRedundantQueryParameters() {\n const { method, path } = this.info\n\n if (!path || path instanceof RegExp || typeof path === 'function') {\n return\n }\n\n const url = cleanUrl(path)\n\n // Bypass request handler URLs that have no redundant characters.\n if (url === path) {\n return\n }\n\n devUtils.warn(\n `Found a redundant usage of query parameters in the request handler URL for \"${method} ${path}\". Please match against a path instead and access query parameters using \"new URL(request.url).searchParams\" instead. Learn more: https://mswjs.io/docs/http/intercepting-requests#querysearch-parameters`,\n )\n }\n\n async parse(args: {\n request: Request\n resolutionContext?: ResponseResolutionContext\n }) {\n const url = new URL(args.request.url)\n const cookies = getAllRequestCookies(args.request)\n\n /**\n * Handle custom predicate functions.\n * @note Invoke this during parsing so the user can parse the path parameters\n * manually. Otherwise, `params` is always an empty object, which isn't nice.\n */\n if (typeof this.info.path === 'function') {\n const customPredicateResult = await this.info.path({\n request: args.request,\n cookies,\n })\n\n const match =\n typeof customPredicateResult === 'boolean'\n ? {\n matches: customPredicateResult,\n params: {},\n }\n : customPredicateResult\n\n return {\n match,\n cookies,\n }\n }\n\n const match = this.info.path\n ? matchRequestUrl(url, this.info.path, args.resolutionContext?.baseUrl)\n : { matches: false, params: {} }\n\n return {\n match,\n cookies,\n }\n }\n\n async predicate(args: {\n request: Request\n parsedResult: HttpRequestParsedResult\n resolutionContext?: ResponseResolutionContext\n }) {\n const hasMatchingMethod = this.matchMethod(args.request.method)\n const hasMatchingUrl = args.parsedResult.match.matches\n return hasMatchingMethod && hasMatchingUrl\n }\n\n private matchMethod(actualMethod: string): boolean {\n return this.info.method instanceof RegExp\n ? this.info.method.test(actualMethod)\n : isStringEqual(this.info.method, actualMethod)\n }\n\n protected extendResolverArgs(args: {\n request: Request\n parsedResult: HttpRequestParsedResult\n }) {\n return {\n params: args.parsedResult.match?.params || {},\n cookies: args.parsedResult.cookies,\n }\n }\n\n async log(args: { request: Request; response: Response }) {\n const publicUrl = toPublicUrl(args.request.url)\n const loggedRequest = await serializeRequest(args.request)\n const loggedResponse = await serializeResponse(args.response)\n const statusColor = getStatusCodeColor(loggedResponse.status)\n\n console.groupCollapsed(\n devUtils.formatMessage(\n `${getTimestamp()} ${args.request.method} ${publicUrl} (%c${\n loggedResponse.status\n } ${loggedResponse.statusText}%c)`,\n ),\n `color:${statusColor}`,\n 'color:inherit',\n )\n // eslint-disable-next-line no-console\n console.log('Request', loggedRequest)\n // eslint-disable-next-line no-console\n console.log('Handler:', this)\n // eslint-disable-next-line no-console\n console.log('Response', loggedResponse)\n console.groupEnd()\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,6BAA+C;AAC/C,sBAAyB;AACzB,2BAA8B;AAC9B,gCAAmC;AACnC,0BAA6B;AAC7B,8BAAiC;AACjC,+BAAkC;AAClC,6BAKO;AACP,yBAA4B;AAC5B,+BAAqC;AACrC,sBAAyB;AACzB,4BAKO;AASA,IAAK,cAAL,kBAAKA,iBAAL;AACL,EAAAA,aAAA,UAAO;AACP,EAAAA,aAAA,SAAM;AACN,EAAAA,aAAA,UAAO;AACP,EAAAA,aAAA,SAAM;AACN,EAAAA,aAAA,WAAQ;AACR,EAAAA,aAAA,aAAU;AACV,EAAAA,aAAA,YAAS;AAPC,SAAAA;AAAA,GAAA;AA8CL,MAAM,oBAAoB,qCAI/B;AAAA,EACA,YACE,QACA,WACA,UACA,SACA;AACA,UAAM,cACJ,OAAO,cAAc,aAAa,uBAAuB;AAE3D,UAAM;AAAA,MACJ,MAAM;AAAA,QACJ,QAAQ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+B;AACjD,WAAO,KAAK,KAAK,kBAAkB,SAC/B,KAAK,KAAK,OAAO,KAAK,YAAY,QAClC,oCAAc,KAAK,KAAK,QAAQ,YAAY;AAAA,EAClD;AAAA,EAEU,mBAAmB,MAG1B;AACD,WAAO;AAAA,MACL,QAAQ,KAAK,aAAa,OAAO,UAAU,CAAC;AAAA,MAC5C,SAAS,KAAK,aAAa;AAAA,IAC7B;AAAA,EACF;AAAA,EAEA,MAAM,IAAI,MAAgD;AACxD,UAAM,gBAAY,gCAAY,KAAK,QAAQ,GAAG;AAC9C,UAAM,gBAAgB,UAAM,0CAAiB,KAAK,OAAO;AACzD,UAAM,iBAAiB,UAAM,4CAAkB,KAAK,QAAQ;AAC5D,UAAM,kBAAc,8CAAmB,eAAe,MAAM;AAE5D,YAAQ;AAAA,MACN,yBAAS;AAAA,QACP,OAAG,kCAAa,CAAC,IAAI,KAAK,QAAQ,MAAM,IAAI,SAAS,OACnD,eAAe,MACjB,IAAI,eAAe,UAAU;AAAA,MAC/B;AAAA,MACA,SAAS,WAAW;AAAA,MACpB;AAAA,IACF;AAEA,YAAQ,IAAI,WAAW,aAAa;AAEpC,YAAQ,IAAI,YAAY,IAAI;AAE5B,YAAQ,IAAI,YAAY,cAAc;AACtC,YAAQ,SAAS;AAAA,EACnB;AACF;","names":["HttpMethods","match"]} \ No newline at end of file diff --git a/node_modules/msw/lib/core/handlers/HttpHandler.mjs b/node_modules/msw/lib/core/handlers/HttpHandler.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c539ad503e5c7298e98272e1cf44f14113e7f368 --- /dev/null +++ b/node_modules/msw/lib/core/handlers/HttpHandler.mjs @@ -0,0 +1,113 @@ +import {} from '../utils/executeHandlers.mjs'; +import { devUtils } from '../utils/internal/devUtils.mjs'; +import { isStringEqual } from '../utils/internal/isStringEqual.mjs'; +import { getStatusCodeColor } from '../utils/logging/getStatusCodeColor.mjs'; +import { getTimestamp } from '../utils/logging/getTimestamp.mjs'; +import { serializeRequest } from '../utils/logging/serializeRequest.mjs'; +import { serializeResponse } from '../utils/logging/serializeResponse.mjs'; +import { + matchRequestUrl +} from '../utils/matching/matchRequestUrl.mjs'; +import { toPublicUrl } from '../utils/request/toPublicUrl.mjs'; +import { getAllRequestCookies } from '../utils/request/getRequestCookies.mjs'; +import { cleanUrl } from '../utils/url/cleanUrl.mjs'; +import { + RequestHandler +} from './RequestHandler.mjs'; +var HttpMethods = /* @__PURE__ */ ((HttpMethods2) => { + HttpMethods2["HEAD"] = "HEAD"; + HttpMethods2["GET"] = "GET"; + HttpMethods2["POST"] = "POST"; + HttpMethods2["PUT"] = "PUT"; + HttpMethods2["PATCH"] = "PATCH"; + HttpMethods2["OPTIONS"] = "OPTIONS"; + HttpMethods2["DELETE"] = "DELETE"; + return HttpMethods2; +})(HttpMethods || {}); +class HttpHandler extends RequestHandler { + constructor(method, predicate, resolver, options) { + const displayPath = typeof predicate === "function" ? "[custom predicate]" : predicate; + super({ + info: { + header: `${method}${displayPath ? ` ${displayPath}` : ""}`, + path: predicate, + method + }, + resolver, + options + }); + this.checkRedundantQueryParameters(); + } + checkRedundantQueryParameters() { + const { method, path } = this.info; + if (!path || path instanceof RegExp || typeof path === "function") { + return; + } + const url = cleanUrl(path); + if (url === path) { + return; + } + devUtils.warn( + `Found a redundant usage of query parameters in the request handler URL for "${method} ${path}". Please match against a path instead and access query parameters using "new URL(request.url).searchParams" instead. Learn more: https://mswjs.io/docs/http/intercepting-requests#querysearch-parameters` + ); + } + async parse(args) { + const url = new URL(args.request.url); + const cookies = getAllRequestCookies(args.request); + if (typeof this.info.path === "function") { + const customPredicateResult = await this.info.path({ + request: args.request, + cookies + }); + const match2 = typeof customPredicateResult === "boolean" ? { + matches: customPredicateResult, + params: {} + } : customPredicateResult; + return { + match: match2, + cookies + }; + } + const match = this.info.path ? matchRequestUrl(url, this.info.path, args.resolutionContext?.baseUrl) : { matches: false, params: {} }; + return { + match, + cookies + }; + } + async predicate(args) { + const hasMatchingMethod = this.matchMethod(args.request.method); + const hasMatchingUrl = args.parsedResult.match.matches; + return hasMatchingMethod && hasMatchingUrl; + } + matchMethod(actualMethod) { + return this.info.method instanceof RegExp ? this.info.method.test(actualMethod) : isStringEqual(this.info.method, actualMethod); + } + extendResolverArgs(args) { + return { + params: args.parsedResult.match?.params || {}, + cookies: args.parsedResult.cookies + }; + } + async log(args) { + const publicUrl = toPublicUrl(args.request.url); + const loggedRequest = await serializeRequest(args.request); + const loggedResponse = await serializeResponse(args.response); + const statusColor = getStatusCodeColor(loggedResponse.status); + console.groupCollapsed( + devUtils.formatMessage( + `${getTimestamp()} ${args.request.method} ${publicUrl} (%c${loggedResponse.status} ${loggedResponse.statusText}%c)` + ), + `color:${statusColor}`, + "color:inherit" + ); + console.log("Request", loggedRequest); + console.log("Handler:", this); + console.log("Response", loggedResponse); + console.groupEnd(); + } +} +export { + HttpHandler, + HttpMethods +}; +//# sourceMappingURL=HttpHandler.mjs.map \ No newline at end of file diff --git a/node_modules/msw/lib/core/handlers/HttpHandler.mjs.map b/node_modules/msw/lib/core/handlers/HttpHandler.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..e76e3c288722b9fc76fdb6f9be231a51611aa788 --- /dev/null +++ b/node_modules/msw/lib/core/handlers/HttpHandler.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/core/handlers/HttpHandler.ts"],"sourcesContent":["import { type ResponseResolutionContext } from '../utils/executeHandlers'\nimport { devUtils } from '../utils/internal/devUtils'\nimport { isStringEqual } from '../utils/internal/isStringEqual'\nimport { getStatusCodeColor } from '../utils/logging/getStatusCodeColor'\nimport { getTimestamp } from '../utils/logging/getTimestamp'\nimport { serializeRequest } from '../utils/logging/serializeRequest'\nimport { serializeResponse } from '../utils/logging/serializeResponse'\nimport {\n matchRequestUrl,\n type Match,\n type Path,\n type PathParams,\n} from '../utils/matching/matchRequestUrl'\nimport { toPublicUrl } from '../utils/request/toPublicUrl'\nimport { getAllRequestCookies } from '../utils/request/getRequestCookies'\nimport { cleanUrl } from '../utils/url/cleanUrl'\nimport {\n RequestHandler,\n type RequestHandlerDefaultInfo,\n type RequestHandlerOptions,\n type ResponseResolver,\n} from './RequestHandler'\n\nexport type HttpHandlerMethod = string | RegExp\n\nexport interface HttpHandlerInfo extends RequestHandlerDefaultInfo {\n method: HttpHandlerMethod\n path: HttpRequestPredicate\n}\n\nexport enum HttpMethods {\n HEAD = 'HEAD',\n GET = 'GET',\n POST = 'POST',\n PUT = 'PUT',\n PATCH = 'PATCH',\n OPTIONS = 'OPTIONS',\n DELETE = 'DELETE',\n}\n\nexport type RequestQuery = {\n [queryName: string]: string\n}\n\nexport type HttpRequestParsedResult = {\n match: Match\n cookies: Record\n}\n\nexport type HttpRequestResolverExtras = {\n params: Params\n cookies: Record\n}\n\nexport type HttpCustomPredicate = (args: {\n request: Request\n cookies: Record\n}) =>\n | HttpCustomPredicateResult\n | Promise>\n\nexport type HttpCustomPredicateResult =\n | boolean\n | {\n matches: boolean\n params: Params\n }\n\nexport type HttpRequestPredicate =\n | Path\n | HttpCustomPredicate\n\n/**\n * Request handler for HTTP requests.\n * Provides request matching based on method and URL.\n */\nexport class HttpHandler extends RequestHandler<\n HttpHandlerInfo,\n HttpRequestParsedResult,\n HttpRequestResolverExtras\n> {\n constructor(\n method: HttpHandlerMethod,\n predicate: HttpRequestPredicate,\n resolver: ResponseResolver, any, any>,\n options?: RequestHandlerOptions,\n ) {\n const displayPath =\n typeof predicate === 'function' ? '[custom predicate]' : predicate\n\n super({\n info: {\n header: `${method}${displayPath ? ` ${displayPath}` : ''}`,\n path: predicate,\n method,\n },\n resolver,\n options,\n })\n\n this.checkRedundantQueryParameters()\n }\n\n private checkRedundantQueryParameters() {\n const { method, path } = this.info\n\n if (!path || path instanceof RegExp || typeof path === 'function') {\n return\n }\n\n const url = cleanUrl(path)\n\n // Bypass request handler URLs that have no redundant characters.\n if (url === path) {\n return\n }\n\n devUtils.warn(\n `Found a redundant usage of query parameters in the request handler URL for \"${method} ${path}\". Please match against a path instead and access query parameters using \"new URL(request.url).searchParams\" instead. Learn more: https://mswjs.io/docs/http/intercepting-requests#querysearch-parameters`,\n )\n }\n\n async parse(args: {\n request: Request\n resolutionContext?: ResponseResolutionContext\n }) {\n const url = new URL(args.request.url)\n const cookies = getAllRequestCookies(args.request)\n\n /**\n * Handle custom predicate functions.\n * @note Invoke this during parsing so the user can parse the path parameters\n * manually. Otherwise, `params` is always an empty object, which isn't nice.\n */\n if (typeof this.info.path === 'function') {\n const customPredicateResult = await this.info.path({\n request: args.request,\n cookies,\n })\n\n const match =\n typeof customPredicateResult === 'boolean'\n ? {\n matches: customPredicateResult,\n params: {},\n }\n : customPredicateResult\n\n return {\n match,\n cookies,\n }\n }\n\n const match = this.info.path\n ? matchRequestUrl(url, this.info.path, args.resolutionContext?.baseUrl)\n : { matches: false, params: {} }\n\n return {\n match,\n cookies,\n }\n }\n\n async predicate(args: {\n request: Request\n parsedResult: HttpRequestParsedResult\n resolutionContext?: ResponseResolutionContext\n }) {\n const hasMatchingMethod = this.matchMethod(args.request.method)\n const hasMatchingUrl = args.parsedResult.match.matches\n return hasMatchingMethod && hasMatchingUrl\n }\n\n private matchMethod(actualMethod: string): boolean {\n return this.info.method instanceof RegExp\n ? this.info.method.test(actualMethod)\n : isStringEqual(this.info.method, actualMethod)\n }\n\n protected extendResolverArgs(args: {\n request: Request\n parsedResult: HttpRequestParsedResult\n }) {\n return {\n params: args.parsedResult.match?.params || {},\n cookies: args.parsedResult.cookies,\n }\n }\n\n async log(args: { request: Request; response: Response }) {\n const publicUrl = toPublicUrl(args.request.url)\n const loggedRequest = await serializeRequest(args.request)\n const loggedResponse = await serializeResponse(args.response)\n const statusColor = getStatusCodeColor(loggedResponse.status)\n\n console.groupCollapsed(\n devUtils.formatMessage(\n `${getTimestamp()} ${args.request.method} ${publicUrl} (%c${\n loggedResponse.status\n } ${loggedResponse.statusText}%c)`,\n ),\n `color:${statusColor}`,\n 'color:inherit',\n )\n // eslint-disable-next-line no-console\n console.log('Request', loggedRequest)\n // eslint-disable-next-line no-console\n console.log('Handler:', this)\n // eslint-disable-next-line no-console\n console.log('Response', loggedResponse)\n console.groupEnd()\n }\n}\n"],"mappings":"AAAA,eAA+C;AAC/C,SAAS,gBAAgB;AACzB,SAAS,qBAAqB;AAC9B,SAAS,0BAA0B;AACnC,SAAS,oBAAoB;AAC7B,SAAS,wBAAwB;AACjC,SAAS,yBAAyB;AAClC;AAAA,EACE;AAAA,OAIK;AACP,SAAS,mBAAmB;AAC5B,SAAS,4BAA4B;AACrC,SAAS,gBAAgB;AACzB;AAAA,EACE;AAAA,OAIK;AASA,IAAK,cAAL,kBAAKA,iBAAL;AACL,EAAAA,aAAA,UAAO;AACP,EAAAA,aAAA,SAAM;AACN,EAAAA,aAAA,UAAO;AACP,EAAAA,aAAA,SAAM;AACN,EAAAA,aAAA,WAAQ;AACR,EAAAA,aAAA,aAAU;AACV,EAAAA,aAAA,YAAS;AAPC,SAAAA;AAAA,GAAA;AA8CL,MAAM,oBAAoB,eAI/B;AAAA,EACA,YACE,QACA,WACA,UACA,SACA;AACA,UAAM,cACJ,OAAO,cAAc,aAAa,uBAAuB;AAE3D,UAAM;AAAA,MACJ,MAAM;AAAA,QACJ,QAAQ,GAAG,MAAM,GAAG,cAAc,IAAI,WAAW,KAAK,EAAE;AAAA,QACxD,MAAM;AAAA,QACN;AAAA,MACF;AAAA,MACA;AAAA,MACA;AAAA,IACF,CAAC;AAED,SAAK,8BAA8B;AAAA,EACrC;AAAA,EAEQ,gCAAgC;AACtC,UAAM,EAAE,QAAQ,KAAK,IAAI,KAAK;AAE9B,QAAI,CAAC,QAAQ,gBAAgB,UAAU,OAAO,SAAS,YAAY;AACjE;AAAA,IACF;AAEA,UAAM,MAAM,SAAS,IAAI;AAGzB,QAAI,QAAQ,MAAM;AAChB;AAAA,IACF;AAEA,aAAS;AAAA,MACP,+EAA+E,MAAM,IAAI,IAAI;AAAA,IAC/F;AAAA,EACF;AAAA,EAEA,MAAM,MAA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AAM;AAE5D,YAAQ;AAAA,MACN,SAAS;AAAA,QACP,GAAG,aAAa,CAAC,IAAI,KAAK,QAAQ,MAAM,IAAI,SAAS,OACnD,eAAe,MACjB,IAAI,eAAe,UAAU;AAAA,MAC/B;AAAA,MACA,SAAS,WAAW;AAAA,MACpB;AAAA,IACF;AAEA,YAAQ,IAAI,WAAW,aAAa;AAEpC,YAAQ,IAAI,YAAY,IAAI;AAE5B,YAAQ,IAAI,YAAY,cAAc;AACtC,YAAQ,SAAS;AAAA,EACnB;AACF;","names":["HttpMethods","match"]} \ No newline at end of file diff --git a/node_modules/msw/lib/core/handlers/RequestHandler.d.mts b/node_modules/msw/lib/core/handlers/RequestHandler.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..8d071328a5e9339e3fa5894c7cfc1558a63c5b2b --- /dev/null +++ b/node_modules/msw/lib/core/handlers/RequestHandler.d.mts @@ -0,0 +1,6 @@ +import '../utils/internal/isIterable.mjs'; +export { A as AsyncResponseResolverReturnType, D as DefaultBodyType, d as DefaultRequestMultipartBody, J as JsonBodyType, M as MaybeAsyncResponseResolverReturnType, R as RequestHandler, L as RequestHandlerArgs, r as RequestHandlerDefaultInfo, N as RequestHandlerExecutionResult, K as RequestHandlerInternalInfo, c as RequestHandlerOptions, a as ResponseResolver, e as ResponseResolverInfo, b as ResponseResolverReturnType, O as forwardResponseCookies } from '../HttpResponse-CQwYpuKo.mjs'; +import '../typeUtils.mjs'; +import '@mswjs/interceptors'; +import 'graphql'; +import '../utils/matching/matchRequestUrl.mjs'; diff --git a/node_modules/msw/lib/core/handlers/RequestHandler.d.ts b/node_modules/msw/lib/core/handlers/RequestHandler.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..54246ebc1022445efd8ab0d9906f261ab5ccf7c5 --- /dev/null +++ b/node_modules/msw/lib/core/handlers/RequestHandler.d.ts @@ -0,0 +1,6 @@ +import '../utils/internal/isIterable.js'; +export { A as AsyncResponseResolverReturnType, D as DefaultBodyType, d as DefaultRequestMultipartBody, J as JsonBodyType, M as MaybeAsyncResponseResolverReturnType, R as RequestHandler, L as RequestHandlerArgs, r as RequestHandlerDefaultInfo, N as RequestHandlerExecutionResult, K as RequestHandlerInternalInfo, c as RequestHandlerOptions, a as ResponseResolver, e as ResponseResolverInfo, b as ResponseResolverReturnType, O as forwardResponseCookies } from '../HttpResponse-BFS34nkx.js'; +import '../typeUtils.js'; +import '@mswjs/interceptors'; +import 'graphql'; +import '../utils/matching/matchRequestUrl.js'; diff --git a/node_modules/msw/lib/core/handlers/RequestHandler.js b/node_modules/msw/lib/core/handlers/RequestHandler.js new file mode 100644 index 0000000000000000000000000000000000000000..38ef929e9434787c5bf71d12c3c01350715c9f85 --- /dev/null +++ b/node_modules/msw/lib/core/handlers/RequestHandler.js @@ -0,0 +1,300 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var RequestHandler_exports = {}; +__export(RequestHandler_exports, { + RequestHandler: () => RequestHandler, + forwardResponseCookies: () => forwardResponseCookies +}); +module.exports = __toCommonJS(RequestHandler_exports); +var import_headers_polyfill = require("headers-polyfill"); +var import_getCallFrame = require("../utils/internal/getCallFrame"); +var import_isIterable = require("../utils/internal/isIterable"); +var import_HttpResponse = require("../HttpResponse"); +var import_devUtils = require("../utils/internal/devUtils"); +var import_decorators = require("../utils/HttpResponse/decorators"); +class RequestHandler { + static cache = /* @__PURE__ */ new WeakMap(); + kind = "request"; + resolver; + resolverIterator; + resolverIteratorResult; + resolverIteratorCleanups; + options; + scheduledCleanups; + info; + /** + * Indicates whether this request handler has been used + * (its resolver has successfully executed). + */ + isUsed; + constructor(args) { + this.resolver = args.resolver; + this.options = args.options; + this.scheduledCleanups = /* @__PURE__ */ new Map(); + const callFrame = (0, import_getCallFrame.getCallFrame)(new Error()); + this.info = { + ...args.info, + callFrame + }; + this.isUsed = false; + } + /** + * Reset the runtime state accumulated during response resolution, + * such as generator iterator progress. Called when this handler is + * removed from the active handlers list so re-adding it later starts + * from a clean state. + */ + reset() { + this.scheduledCleanups.clear(); + const iterator = this.resolverIterator; + this.resolverIterator = void 0; + this.resolverIteratorResult = void 0; + this.resolverIteratorCleanups = void 0; + if (typeof iterator?.return === "function") { + void Promise.resolve(iterator.return()); + } + } + /** + * Restore this handler so it can match requests again after being + * exhausted (e.g. via `{ once: true }`). Also clears any accumulated + * resolution state. + */ + restore() { + if (this.options?.once) { + this.reset(); + this.isUsed = false; + } + } + /** + * Parse the intercepted request to extract additional information from it. + * Parsed result is then exposed to other methods of this request handler. + */ + async parse(_args) { + return {}; + } + /** + * Test if this handler matches the given request. + * + * This method is not used internally but is exposed + * as a convenience method for consumers writing custom + * handlers. + */ + async test(args) { + const parsedResult = await this.parse({ + request: args.request, + resolutionContext: args.resolutionContext + }); + return this.predicate({ + request: args.request, + parsedResult, + resolutionContext: args.resolutionContext + }); + } + extendResolverArgs(_args) { + return {}; + } + // Clone the request instance before it's passed to the handler phases + // and the response resolver so we can always read it for logging. + // We only clone it once per request to avoid unnecessary overhead. + cloneRequestOrGetFromCache(request) { + const existingClone = RequestHandler.cache.get(request); + if (typeof existingClone !== "undefined") { + return existingClone; + } + const clonedRequest = request.clone(); + RequestHandler.cache.set(request, clonedRequest); + return clonedRequest; + } + /** + * Execute this request handler and produce a mocked response + * using the given resolver function. + */ + async run(args) { + if (this.isUsed && this.options?.once) { + return null; + } + const requestClone = this.cloneRequestOrGetFromCache(args.request); + const parsedResult = await this.parse({ + request: args.request, + resolutionContext: args.resolutionContext + }); + const shouldInterceptRequest = await this.predicate({ + request: args.request, + parsedResult, + resolutionContext: args.resolutionContext + }); + if (!shouldInterceptRequest) { + return null; + } + if (this.isUsed && this.options?.once) { + return null; + } + this.isUsed = true; + const executeResolver = this.wrapResolver(this.resolver); + const resolverExtras = this.extendResolverArgs({ + request: args.request, + parsedResult + }); + const listenerController = new AbortController(); + args.request.signal.addEventListener( + "abort", + () => this.runScheduledCleanups(args.requestId), + { + once: true, + signal: listenerController.signal + } + ); + const mockedResponsePromise = executeResolver({ + ...resolverExtras, + finalize: (callback) => { + this.scheduleCleanup(args.requestId, callback); + }, + requestId: args.requestId, + request: args.request + }).catch((errorOrResponse) => { + if (errorOrResponse instanceof Response) { + return errorOrResponse; + } + throw errorOrResponse; + }).finally(() => { + listenerController.abort(); + }); + const mockedResponse = await mockedResponsePromise; + if (mockedResponse) { + forwardResponseCookies(mockedResponse); + } + const executionResult = this.createExecutionResult({ + // Pass the cloned request to the result so that logging + // and other consumers could read its body once more. + request: requestClone, + requestId: args.requestId, + response: mockedResponse, + parsedResult + }); + return executionResult; + } + wrapResolver(resolver) { + return async (info) => { + if (!this.resolverIterator) { + let result; + try { + result = await resolver(info); + } catch (error) { + await this.runScheduledCleanups(info.requestId); + throw error; + } + if (!(0, import_isIterable.isIterable)(result)) { + await this.runScheduledCleanups(info.requestId); + return result; + } + const existingCleanups = this.scheduledCleanups.get(info.requestId); + if (existingCleanups != null && existingCleanups.length > 0) { + this.resolverIteratorCleanups = existingCleanups; + this.scheduledCleanups.delete(info.requestId); + } + this.resolverIterator = Symbol.iterator in result ? result[Symbol.iterator]() : result[Symbol.asyncIterator](); + } + this.isUsed = false; + const { done, value } = await this.resolverIterator.next(); + const nextResponse = await value; + if (nextResponse) { + this.resolverIteratorResult = nextResponse.clone(); + } + if (done) { + this.isUsed = true; + await this.runScheduledCleanups(info.requestId); + return this.resolverIteratorResult?.clone(); + } + return nextResponse; + }; + } + createExecutionResult(args) { + return { + handler: this, + request: args.request, + requestId: args.requestId, + response: args.response, + parsedResult: args.parsedResult + }; + } + scheduleCleanup(requestId, callback) { + if (this.resolverIterator) { + ; + (this.resolverIteratorCleanups ||= []).unshift(callback); + return; + } + const cleanups = this.scheduledCleanups.get(requestId) || []; + cleanups.unshift(callback); + this.scheduledCleanups.set(requestId, cleanups); + } + async exhaustCleanups(cleanups) { + const errors = []; + for (const cleanup of cleanups) { + try { + await cleanup(); + } catch (error) { + if (error instanceof Error) { + errors.push(error); + } + } + } + if (errors.length > 0) { + import_devUtils.devUtils.error( + 'Failed to execute cleanup for request handler "%s"', + this.info.header, + new AggregateError( + errors, + `Failed to execute cleanup for request handler "${this.info.header}"` + ) + ); + } + } + async runScheduledCleanups(requestId) { + if (this.resolverIterator && this.resolverIteratorCleanups != null && this.resolverIteratorCleanups.length > 0) { + try { + await this.exhaustCleanups(this.resolverIteratorCleanups); + } finally { + this.resolverIteratorCleanups = void 0; + } + return; + } + const cleanups = this.scheduledCleanups.get(requestId); + if (!cleanups || cleanups.length == 0) { + return; + } + await this.exhaustCleanups(cleanups); + this.scheduledCleanups.delete(requestId); + } +} +function forwardResponseCookies(response) { + if (typeof document === "undefined") { + return; + } + const responseCookies = (0, import_decorators.getRawSetCookie)(response); + if (!responseCookies) { + return; + } + const allResponseCookies = import_headers_polyfill.Headers.prototype.getSetCookie.call( + new Headers([["set-cookie", responseCookies]]) + ); + for (const cookieString of allResponseCookies) { + document.cookie = cookieString; + } +} +//# sourceMappingURL=RequestHandler.js.map \ No newline at end of file diff --git a/node_modules/msw/lib/core/handlers/RequestHandler.js.map b/node_modules/msw/lib/core/handlers/RequestHandler.js.map new file mode 100644 index 0000000000000000000000000000000000000000..afcd1f2e37c4cb87f3dbadd0c7c9b79dcaa04d07 --- /dev/null +++ b/node_modules/msw/lib/core/handlers/RequestHandler.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/core/handlers/RequestHandler.ts"],"sourcesContent":["import { Headers as HeadersPolyfill } from 'headers-polyfill'\nimport { getCallFrame } from '../utils/internal/getCallFrame'\nimport {\n isIterable,\n type AsyncIterable,\n type Iterable,\n} from '../utils/internal/isIterable'\nimport type { ResponseResolutionContext } from '../utils/executeHandlers'\nimport type { MaybePromise } from '../typeUtils'\nimport type { HttpResponse } from '../HttpResponse'\nimport {\n type StrictRequest,\n type DefaultUnsafeFetchResponse,\n} from '../HttpResponse'\nimport type { GraphQLRequestBody } from './GraphQLHandler'\nimport { devUtils } from '../utils/internal/devUtils'\nimport { getRawSetCookie } from '../utils/HttpResponse/decorators'\n\nexport type DefaultRequestMultipartBody = Record<\n string,\n string | File | Array\n>\n\nexport type DefaultBodyType =\n | Record\n | DefaultRequestMultipartBody\n | string\n | number\n | boolean\n | null\n | undefined\n\nexport type JsonBodyType =\n | Record\n | string\n | number\n | boolean\n | null\n | undefined\n\nexport interface RequestHandlerDefaultInfo {\n header: string\n}\n\nexport interface RequestHandlerInternalInfo {\n callFrame?: string\n}\n\nexport type ResponseResolverReturnType<\n ResponseBodyType extends DefaultBodyType = undefined,\n> =\n // If ResponseBodyType is a union and one of the types is `undefined`,\n // allow plain Response as the type.\n | ([ResponseBodyType] extends [undefined]\n ? Response\n : /**\n * Treat GraphQL response body type as a special case.\n * For esome reason, making the default HttpResponse | DefaultUnsafeFetchResponse\n * union breaks the body type inference for HTTP requests.\n * @see https://github.com/mswjs/msw/issues/2130\n */\n ResponseBodyType extends GraphQLRequestBody\n ? HttpResponse | DefaultUnsafeFetchResponse\n : HttpResponse)\n | undefined\n | void\n\nexport type MaybeAsyncResponseResolverReturnType<\n ResponseBodyType extends DefaultBodyType,\n> = MaybePromise>\n\nexport type AsyncResponseResolverReturnType<\n ResponseBodyType extends DefaultBodyType,\n> = MaybePromise<\n | ResponseResolverReturnType\n | Iterable<\n MaybeAsyncResponseResolverReturnType,\n MaybeAsyncResponseResolverReturnType,\n MaybeAsyncResponseResolverReturnType\n >\n | AsyncIterable<\n MaybeAsyncResponseResolverReturnType,\n MaybeAsyncResponseResolverReturnType,\n MaybeAsyncResponseResolverReturnType\n >\n>\n\nexport type ResponseResolverInfo<\n ResolverExtraInfo extends Record,\n RequestBodyType extends DefaultBodyType = DefaultBodyType,\n> = {\n request: StrictRequest\n requestId: string\n /**\n * Schedule a callback to run after this response resolver completes.\n * Handy for cleaning up the side effects introduced in the resolver.\n * @example\n * sse('/', ({ client, finalize }) => {\n * const interval = setInterval(() => client.send({ data: 'ping' }))\n * finalize(() => clearInterval(interval))\n * })\n */\n finalize: ResponseResolverFinalizeFunction\n} & ResolverExtraInfo\n\ntype ResponseResolverFinalizeFunction = (\n callback: () => MaybePromise,\n) => void\n\nexport type ResponseResolver<\n ResolverExtraInfo extends Record = Record,\n RequestBodyType extends DefaultBodyType = DefaultBodyType,\n ResponseBodyType extends DefaultBodyType = undefined,\n> = (\n info: ResponseResolverInfo,\n) => AsyncResponseResolverReturnType\n\nexport interface RequestHandlerArgs<\n HandlerInfo,\n HandlerOptions extends RequestHandlerOptions,\n> {\n info: HandlerInfo\n resolver: ResponseResolver\n options?: HandlerOptions\n}\n\nexport interface RequestHandlerOptions {\n once?: boolean\n}\n\nexport interface RequestHandlerExecutionResult<\n ParsedResult extends object | undefined,\n> {\n handler: RequestHandler\n parsedResult?: ParsedResult\n request: Request\n requestId: string\n response?: Response\n}\n\nexport abstract class RequestHandler<\n HandlerInfo extends RequestHandlerDefaultInfo = RequestHandlerDefaultInfo,\n ParsedResult extends Record | undefined = any,\n ResolverExtras extends Record = any,\n HandlerOptions extends RequestHandlerOptions = RequestHandlerOptions,\n> {\n static cache = new WeakMap<\n StrictRequest,\n StrictRequest\n >()\n\n public readonly kind = 'request' as const\n\n protected resolver: ResponseResolver\n private resolverIterator?:\n | Iterator<\n MaybeAsyncResponseResolverReturnType,\n MaybeAsyncResponseResolverReturnType,\n MaybeAsyncResponseResolverReturnType\n >\n | AsyncIterator<\n MaybeAsyncResponseResolverReturnType,\n MaybeAsyncResponseResolverReturnType,\n MaybeAsyncResponseResolverReturnType\n >\n private resolverIteratorResult?: Response | HttpResponse\n private resolverIteratorCleanups?: Array<() => MaybePromise>\n private options?: HandlerOptions\n private scheduledCleanups: Map MaybePromise>>\n\n public info: HandlerInfo & RequestHandlerInternalInfo\n\n /**\n * Indicates whether this request handler has been used\n * (its resolver has successfully executed).\n */\n public isUsed: boolean\n\n constructor(args: RequestHandlerArgs) {\n this.resolver = args.resolver\n this.options = args.options\n this.scheduledCleanups = new Map()\n\n const callFrame = getCallFrame(new Error())\n\n this.info = {\n ...args.info,\n callFrame,\n }\n\n this.isUsed = false\n }\n\n /**\n * Reset the runtime state accumulated during response resolution,\n * such as generator iterator progress. Called when this handler is\n * removed from the active handlers list so re-adding it later starts\n * from a clean state.\n */\n protected reset(): void {\n this.scheduledCleanups.clear()\n\n const iterator = this.resolverIterator\n this.resolverIterator = undefined\n this.resolverIteratorResult = undefined\n this.resolverIteratorCleanups = undefined\n\n if (typeof iterator?.return === 'function') {\n void Promise.resolve(iterator.return())\n }\n }\n\n /**\n * Restore this handler so it can match requests again after being\n * exhausted (e.g. via `{ once: true }`). Also clears any accumulated\n * resolution state.\n */\n protected restore(): void {\n if (this.options?.once) {\n this.reset()\n this.isUsed = false\n }\n }\n\n /**\n * Determine if the intercepted request should be mocked.\n */\n abstract predicate(args: {\n request: Request\n parsedResult: ParsedResult\n resolutionContext?: ResponseResolutionContext\n }): boolean | Promise\n\n /**\n * Print out the successfully handled request.\n */\n abstract log(args: {\n request: Request\n response: Response\n parsedResult: ParsedResult\n }): void\n\n /**\n * Parse the intercepted request to extract additional information from it.\n * Parsed result is then exposed to other methods of this request handler.\n */\n async parse(_args: {\n request: Request\n resolutionContext?: ResponseResolutionContext\n }): Promise {\n return {} as ParsedResult\n }\n\n /**\n * Test if this handler matches the given request.\n *\n * This method is not used internally but is exposed\n * as a convenience method for consumers writing custom\n * handlers.\n */\n public async test(args: {\n request: Request\n resolutionContext?: ResponseResolutionContext\n }): Promise {\n const parsedResult = await this.parse({\n request: args.request,\n resolutionContext: args.resolutionContext,\n })\n\n return this.predicate({\n request: args.request,\n parsedResult,\n resolutionContext: args.resolutionContext,\n })\n }\n\n protected extendResolverArgs(_args: {\n request: Request\n parsedResult: ParsedResult\n }): ResolverExtras {\n return {} as ResolverExtras\n }\n\n // Clone the request instance before it's passed to the handler phases\n // and the response resolver so we can always read it for logging.\n // We only clone it once per request to avoid unnecessary overhead.\n private cloneRequestOrGetFromCache(\n request: StrictRequest,\n ): StrictRequest {\n const existingClone = RequestHandler.cache.get(request)\n\n if (typeof existingClone !== 'undefined') {\n return existingClone\n }\n\n const clonedRequest = request.clone()\n RequestHandler.cache.set(request, clonedRequest)\n\n return clonedRequest\n }\n\n /**\n * Execute this request handler and produce a mocked response\n * using the given resolver function.\n */\n public async run(args: {\n request: StrictRequest\n requestId: string\n resolutionContext?: ResponseResolutionContext\n }): Promise | null> {\n if (this.isUsed && this.options?.once) {\n return null\n }\n\n // Clone the request.\n // If this is the first time MSW handles this request, a fresh clone\n // will be created and cached. Upon further handling of the same request,\n // the request clone from the cache will be reused to prevent abundant\n // \"abort\" listeners and save up resources on cloning.\n const requestClone = this.cloneRequestOrGetFromCache(args.request)\n\n const parsedResult = await this.parse({\n request: args.request,\n resolutionContext: args.resolutionContext,\n })\n const shouldInterceptRequest = await this.predicate({\n request: args.request,\n parsedResult,\n resolutionContext: args.resolutionContext,\n })\n\n if (!shouldInterceptRequest) {\n return null\n }\n\n // Re-check isUsed, in case another request hit this handler while we were\n // asynchronously parsing the request.\n if (this.isUsed && this.options?.once) {\n return null\n }\n\n // Preemptively mark the handler as used.\n // Generators will undo this because only when the resolver reaches the\n // \"done\" state of the generator that it considers the handler used.\n this.isUsed = true\n\n // Create a response extraction wrapper around the resolver\n // since it can be both an async function and a generator.\n const executeResolver = this.wrapResolver(this.resolver)\n\n const resolverExtras = this.extendResolverArgs({\n request: args.request,\n parsedResult,\n })\n\n const listenerController = new AbortController()\n\n args.request.signal.addEventListener(\n 'abort',\n () => this.runScheduledCleanups(args.requestId),\n {\n once: true,\n signal: listenerController.signal,\n },\n )\n\n const mockedResponsePromise = (\n executeResolver({\n ...resolverExtras,\n finalize: (callback) => {\n this.scheduleCleanup(args.requestId, callback)\n },\n requestId: args.requestId,\n request: args.request,\n }) as Promise\n )\n .catch((errorOrResponse) => {\n // Allow throwing a Response instance in a response resolver.\n if (errorOrResponse instanceof Response) {\n return errorOrResponse\n }\n\n // Otherwise, throw the error as-is.\n throw errorOrResponse\n })\n .finally(() => {\n listenerController.abort()\n })\n\n const mockedResponse = await mockedResponsePromise\n\n if (mockedResponse) {\n forwardResponseCookies(mockedResponse)\n }\n\n const executionResult = this.createExecutionResult({\n // Pass the cloned request to the result so that logging\n // and other consumers could read its body once more.\n request: requestClone,\n requestId: args.requestId,\n response: mockedResponse,\n parsedResult,\n })\n\n return executionResult\n }\n\n private wrapResolver(\n resolver: ResponseResolver,\n ): ResponseResolver {\n return async (info): Promise> => {\n if (!this.resolverIterator) {\n let result\n\n try {\n result = await resolver(info)\n } catch (error) {\n // Ensure cleanup if the resolver throws, regardless of the returned type.\n await this.runScheduledCleanups(info.requestId)\n\n // Re-throw the error for the \"run()\" method to handle (e.g. thrown responses).\n throw error\n }\n\n if (!isIterable(result)) {\n // Otherwise, run the cleanup immediately if it's a plain response resolver.\n await this.runScheduledCleanups(info.requestId)\n return result\n }\n\n /**\n * @note Carry over any previously registered cleanups onto the iterator cleanups.\n * This is only relevant if \"finalize()\" is called in a regular resolver that\n * returns an iterator.\n * @example\n * http.get('/', async ({ finalize }) => {\n * finalize(cleanup)\n * return (async function*() {})()\n * })\n */\n const existingCleanups = this.scheduledCleanups.get(info.requestId)\n if (existingCleanups != null && existingCleanups.length > 0) {\n this.resolverIteratorCleanups = existingCleanups\n this.scheduledCleanups.delete(info.requestId)\n }\n\n this.resolverIterator =\n Symbol.iterator in result\n ? result[Symbol.iterator]()\n : result[Symbol.asyncIterator]()\n }\n\n // Opt-out from marking this handler as used.\n this.isUsed = false\n\n const { done, value } = await this.resolverIterator.next()\n const nextResponse = await value\n\n if (nextResponse) {\n this.resolverIteratorResult = nextResponse.clone()\n }\n\n if (done) {\n // A one-time generator resolver stops affecting the network\n // only after it's been completely exhausted.\n this.isUsed = true\n\n await this.runScheduledCleanups(info.requestId)\n\n // Clone the previously stored response so it can be read\n // when receiving it repeatedly from the \"done\" generator.\n return this.resolverIteratorResult?.clone()\n }\n\n return nextResponse\n }\n }\n\n private createExecutionResult(args: {\n request: Request\n requestId: string\n parsedResult: ParsedResult\n response?: Response\n }): RequestHandlerExecutionResult {\n return {\n handler: this,\n request: args.request,\n requestId: args.requestId,\n response: args.response,\n parsedResult: args.parsedResult,\n }\n }\n\n private scheduleCleanup(\n requestId: string,\n callback: () => MaybePromise,\n ): void {\n if (this.resolverIterator) {\n ;(this.resolverIteratorCleanups ||= []).unshift(callback)\n return\n }\n\n const cleanups = this.scheduledCleanups.get(requestId) || []\n cleanups.unshift(callback)\n this.scheduledCleanups.set(requestId, cleanups)\n }\n\n private async exhaustCleanups(\n cleanups: Array<() => MaybePromise>,\n ): Promise {\n const errors: Array = []\n\n for (const cleanup of cleanups) {\n try {\n await cleanup()\n } catch (error) {\n if (error instanceof Error) {\n errors.push(error)\n }\n }\n }\n\n if (errors.length > 0) {\n devUtils.error(\n 'Failed to execute cleanup for request handler \"%s\"',\n this.info.header,\n new AggregateError(\n errors,\n `Failed to execute cleanup for request handler \"${this.info.header}\"`,\n ),\n )\n }\n }\n\n private async runScheduledCleanups(requestId: string): Promise {\n if (\n this.resolverIterator &&\n this.resolverIteratorCleanups != null &&\n this.resolverIteratorCleanups.length > 0\n ) {\n try {\n await this.exhaustCleanups(this.resolverIteratorCleanups)\n } finally {\n this.resolverIteratorCleanups = undefined\n }\n return\n }\n\n const cleanups = this.scheduledCleanups.get(requestId)\n\n if (!cleanups || cleanups.length == 0) {\n return\n }\n\n await this.exhaustCleanups(cleanups)\n this.scheduledCleanups.delete(requestId)\n }\n}\n\n/**\n * Forwards the cookies from the given response to `document.cookie`.\n */\nexport function forwardResponseCookies(response: Response): void {\n // Cookie forwarding is only relevant in the browser.\n if (typeof document === 'undefined') {\n return\n }\n\n const responseCookies = getRawSetCookie(response)\n\n if (!responseCookies) {\n return\n }\n\n // Write the mocked response cookies to the document.\n // Use `headers-polyfill` to get the Set-Cookie header value correctly.\n // This is an alternative until TypeScript 5.2\n // and Node.js v20 become the minimum supported versions\n // and \"Headers.prototype.getSetCookie\" can be used directly.\n const allResponseCookies = HeadersPolyfill.prototype.getSetCookie.call(\n new Headers([['set-cookie', responseCookies]]),\n )\n\n for (const cookieString of allResponseCookies) {\n document.cookie = cookieString\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,8BAA2C;AAC3C,0BAA6B;AAC7B,wBAIO;AAIP,0BAGO;AAEP,sBAAyB;AACzB,wBAAgC;AA4HzB,MAAe,eAKpB;AAAA,EACA,OAAO,QAAQ,oBAAI,QAGjB;AAAA,EAEc,OAAO;AAAA,EAEb;AAAA,EACF;AAAA,EAWA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAED;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA;AAAA,EAEP,YAAY,MAAuD;AACjE,SAAK,WAAW,KAAK;AACrB,SAAK,UAAU,KAAK;AACpB,SAAK,oBAAoB,oBAAI,IAAI;AAEjC,UAAM,gBAAY,kCAAa,IAAI,MAAM,CAAC;AAE1C,SAAK,OAAO;AAAA,MACV,GAAG,KAAK;AAAA,MACR;AAAA,IACF;AAEA,SAAK,SAAS;AAAA,EAChB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQU,QAAc;AACtB,SAAK,kBAAkB,MAAM;AAE7B,UAAM,WAAW,KAAK;AACtB,SAAK,mBAAmB;AACxB,SAAK,yBAAyB;AAC9B,SAAK,2BAA2B;AAEhC,QAAI,OAAO,UAAU,WAAW,YA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A,EAEA,MAAc,gBACZ,UACe;AACf,UAAM,SAAuB,CAAC;AAE9B,eAAW,WAAW,UAAU;AAC9B,UAAI;AACF,cAAM,QAAQ;AAAA,MAChB,SAAS,OAAO;AACd,YAAI,iBAAiB,OAAO;AAC1B,iBAAO,KAAK,KAAK;AAAA,QACnB;AAAA,MACF;AAAA,IACF;AAEA,QAAI,OAAO,SAAS,GAAG;AACrB,+BAAS;AAAA,QACP;AAAA,QACA,KAAK,KAAK;AAAA,QACV,IAAI;AAAA,UACF;AAAA,UACA,kDAAkD,KAAK,KAAK,MAAM;AAAA,QACpE;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAc,qBAAqB,WAAkC;AACnE,QACE,KAAK,oBACL,KAAK,4BAA4B,QACjC,KAAK,yBAAyB,SAAS,GACvC;AACA,UAAI;AACF,cAAM,KAAK,gBAAgB,KAAK,wBAAwB;AAAA,MAC1D,UAAE;AACA,aAAK,2BAA2B;AAAA,MAClC;AACA;AAAA,IACF;AAEA,UAAM,WAAW,KAAK,kBAAkB,IAAI,SAAS;AAErD,QAAI,CAAC,YAAY,SAAS,UAAU,GAAG;AACrC;AAAA,IACF;AAEA,UAAM,KAAK,gBAAgB,QAAQ;AACnC,SAAK,kBAAkB,OAAO,SAAS;AAAA,EACzC;AACF;AAKO,SAAS,uBAAuB,UAA0B;AAE/D,MAAI,OAAO,aAAa,aAAa;AACnC;AAAA,EACF;AAEA,QAAM,sBAAkB,mCAAgB,QAAQ;AAEhD,MAAI,CAAC,iBAAiB;AACpB;AAAA,EACF;AAOA,QAAM,qBAAqB,wBAAAA,QAAgB,UAAU,aAAa;AAAA,IAChE,IAAI,QAAQ,CAAC,CAAC,cAAc,eAAe,CAAC,CAAC;AAAA,EAC/C;AAEA,aAAW,gBAAgB,oBAAoB;AAC7C,aAAS,SAAS;AAAA,EACpB;AACF;","names":["HeadersPolyfill"]} \ No newline at end of file diff --git a/node_modules/msw/lib/core/handlers/RequestHandler.mjs b/node_modules/msw/lib/core/handlers/RequestHandler.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ca02376409909dfd9200c5fe16aad82b50fd52d6 --- /dev/null +++ b/node_modules/msw/lib/core/handlers/RequestHandler.mjs @@ -0,0 +1,283 @@ +import { Headers as HeadersPolyfill } from "headers-polyfill"; +import { getCallFrame } from '../utils/internal/getCallFrame.mjs'; +import { + isIterable +} from '../utils/internal/isIterable.mjs'; +import { +} from '../HttpResponse.mjs'; +import { devUtils } from '../utils/internal/devUtils.mjs'; +import { getRawSetCookie } from '../utils/HttpResponse/decorators.mjs'; +class RequestHandler { + static cache = /* @__PURE__ */ new WeakMap(); + kind = "request"; + resolver; + resolverIterator; + resolverIteratorResult; + resolverIteratorCleanups; + options; + scheduledCleanups; + info; + /** + * Indicates whether this request handler has been used + * (its resolver has successfully executed). + */ + isUsed; + constructor(args) { + this.resolver = args.resolver; + this.options = args.options; + this.scheduledCleanups = /* @__PURE__ */ new Map(); + const callFrame = getCallFrame(new Error()); + this.info = { + ...args.info, + callFrame + }; + this.isUsed = false; + } + /** + * Reset the runtime state accumulated during response resolution, + * such as generator iterator progress. Called when this handler is + * removed from the active handlers list so re-adding it later starts + * from a clean state. + */ + reset() { + this.scheduledCleanups.clear(); + const iterator = this.resolverIterator; + this.resolverIterator = void 0; + this.resolverIteratorResult = void 0; + this.resolverIteratorCleanups = void 0; + if (typeof iterator?.return === "function") { + void Promise.resolve(iterator.return()); + } + } + /** + * Restore this handler so it can match requests again after being + * exhausted (e.g. via `{ once: true }`). Also clears any accumulated + * resolution state. + */ + restore() { + if (this.options?.once) { + this.reset(); + this.isUsed = false; + } + } + /** + * Parse the intercepted request to extract additional information from it. + * Parsed result is then exposed to other methods of this request handler. + */ + async parse(_args) { + return {}; + } + /** + * Test if this handler matches the given request. + * + * This method is not used internally but is exposed + * as a convenience method for consumers writing custom + * handlers. + */ + async test(args) { + const parsedResult = await this.parse({ + request: args.request, + resolutionContext: args.resolutionContext + }); + return this.predicate({ + request: args.request, + parsedResult, + resolutionContext: args.resolutionContext + }); + } + extendResolverArgs(_args) { + return {}; + } + // Clone the request instance before it's passed to the handler phases + // and the response resolver so we can always read it for logging. + // We only clone it once per request to avoid unnecessary overhead. + cloneRequestOrGetFromCache(request) { + const existingClone = RequestHandler.cache.get(request); + if (typeof existingClone !== "undefined") { + return existingClone; + } + const clonedRequest = request.clone(); + RequestHandler.cache.set(request, clonedRequest); + return clonedRequest; + } + /** + * Execute this request handler and produce a mocked response + * using the given resolver function. + */ + async run(args) { + if (this.isUsed && this.options?.once) { + return null; + } + const requestClone = this.cloneRequestOrGetFromCache(args.request); + const parsedResult = await this.parse({ + request: args.request, + resolutionContext: args.resolutionContext + }); + const shouldInterceptRequest = await this.predicate({ + request: args.request, + parsedResult, + resolutionContext: args.resolutionContext + }); + if (!shouldInterceptRequest) { + return null; + } + if (this.isUsed && this.options?.once) { + return null; + } + this.isUsed = true; + const executeResolver = this.wrapResolver(this.resolver); + const resolverExtras = this.extendResolverArgs({ + request: args.request, + parsedResult + }); + const listenerController = new AbortController(); + args.request.signal.addEventListener( + "abort", + () => this.runScheduledCleanups(args.requestId), + { + once: true, + signal: listenerController.signal + } + ); + const mockedResponsePromise = executeResolver({ + ...resolverExtras, + finalize: (callback) => { + this.scheduleCleanup(args.requestId, callback); + }, + requestId: args.requestId, + request: args.request + }).catch((errorOrResponse) => { + if (errorOrResponse instanceof Response) { + return errorOrResponse; + } + throw errorOrResponse; + }).finally(() => { + listenerController.abort(); + }); + const mockedResponse = await mockedResponsePromise; + if (mockedResponse) { + forwardResponseCookies(mockedResponse); + } + const executionResult = this.createExecutionResult({ + // Pass the cloned request to the result so that logging + // and other consumers could read its body once more. + request: requestClone, + requestId: args.requestId, + response: mockedResponse, + parsedResult + }); + return executionResult; + } + wrapResolver(resolver) { + return async (info) => { + if (!this.resolverIterator) { + let result; + try { + result = await resolver(info); + } catch (error) { + await this.runScheduledCleanups(info.requestId); + throw error; + } + if (!isIterable(result)) { + await this.runScheduledCleanups(info.requestId); + return result; + } + const existingCleanups = this.scheduledCleanups.get(info.requestId); + if (existingCleanups != null && existingCleanups.length > 0) { + this.resolverIteratorCleanups = existingCleanups; + this.scheduledCleanups.delete(info.requestId); + } + this.resolverIterator = Symbol.iterator in result ? result[Symbol.iterator]() : result[Symbol.asyncIterator](); + } + this.isUsed = false; + const { done, value } = await this.resolverIterator.next(); + const nextResponse = await value; + if (nextResponse) { + this.resolverIteratorResult = nextResponse.clone(); + } + if (done) { + this.isUsed = true; + await this.runScheduledCleanups(info.requestId); + return this.resolverIteratorResult?.clone(); + } + return nextResponse; + }; + } + createExecutionResult(args) { + return { + handler: this, + request: args.request, + requestId: args.requestId, + response: args.response, + parsedResult: args.parsedResult + }; + } + scheduleCleanup(requestId, callback) { + if (this.resolverIterator) { + ; + (this.resolverIteratorCleanups ||= []).unshift(callback); + return; + } + const cleanups = this.scheduledCleanups.get(requestId) || []; + cleanups.unshift(callback); + this.scheduledCleanups.set(requestId, cleanups); + } + async exhaustCleanups(cleanups) { + const errors = []; + for (const cleanup of cleanups) { + try { + await cleanup(); + } catch (error) { + if (error instanceof Error) { + errors.push(error); + } + } + } + if (errors.length > 0) { + devUtils.error( + 'Failed to execute cleanup for request handler "%s"', + this.info.header, + new AggregateError( + errors, + `Failed to execute cleanup for request handler "${this.info.header}"` + ) + ); + } + } + async runScheduledCleanups(requestId) { + if (this.resolverIterator && this.resolverIteratorCleanups != null && this.resolverIteratorCleanups.length > 0) { + try { + await this.exhaustCleanups(this.resolverIteratorCleanups); + } finally { + this.resolverIteratorCleanups = void 0; + } + return; + } + const cleanups = this.scheduledCleanups.get(requestId); + if (!cleanups || cleanups.length == 0) { + return; + } + await this.exhaustCleanups(cleanups); + this.scheduledCleanups.delete(requestId); + } +} +function forwardResponseCookies(response) { + if (typeof document === "undefined") { + return; + } + const responseCookies = getRawSetCookie(response); + if (!responseCookies) { + return; + } + const allResponseCookies = HeadersPolyfill.prototype.getSetCookie.call( + new Headers([["set-cookie", responseCookies]]) + ); + for (const cookieString of allResponseCookies) { + document.cookie = cookieString; + } +} +export { + RequestHandler, + forwardResponseCookies +}; +//# sourceMappingURL=RequestHandler.mjs.map \ No newline at end of file diff --git a/node_modules/msw/lib/core/handlers/RequestHandler.mjs.map b/node_modules/msw/lib/core/handlers/RequestHandler.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..7c21484c1e573c444e83f14c5cd767f7ef0aff62 --- /dev/null +++ b/node_modules/msw/lib/core/handlers/RequestHandler.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/core/handlers/RequestHandler.ts"],"sourcesContent":["import { Headers as HeadersPolyfill } from 'headers-polyfill'\nimport { getCallFrame } from '../utils/internal/getCallFrame'\nimport {\n isIterable,\n type AsyncIterable,\n type Iterable,\n} from '../utils/internal/isIterable'\nimport type { ResponseResolutionContext } from '../utils/executeHandlers'\nimport type { MaybePromise } from '../typeUtils'\nimport type { HttpResponse } from '../HttpResponse'\nimport {\n type StrictRequest,\n type DefaultUnsafeFetchResponse,\n} from '../HttpResponse'\nimport type { GraphQLRequestBody } from './GraphQLHandler'\nimport { devUtils } from '../utils/internal/devUtils'\nimport { getRawSetCookie } from '../utils/HttpResponse/decorators'\n\nexport type DefaultRequestMultipartBody = Record<\n string,\n string | File | Array\n>\n\nexport type DefaultBodyType =\n | Record\n | DefaultRequestMultipartBody\n | string\n | number\n | boolean\n | null\n | undefined\n\nexport type JsonBodyType =\n | Record\n | string\n | number\n | boolean\n | null\n | undefined\n\nexport interface RequestHandlerDefaultInfo {\n header: string\n}\n\nexport interface RequestHandlerInternalInfo {\n callFrame?: string\n}\n\nexport type ResponseResolverReturnType<\n ResponseBodyType extends DefaultBodyType = undefined,\n> =\n // If ResponseBodyType is a union and one of the types is `undefined`,\n // allow plain Response as the type.\n | ([ResponseBodyType] extends [undefined]\n ? Response\n : /**\n * Treat GraphQL response body type as a special case.\n * For esome reason, making the default HttpResponse | DefaultUnsafeFetchResponse\n * union breaks the body type inference for HTTP requests.\n * @see https://github.com/mswjs/msw/issues/2130\n */\n ResponseBodyType extends GraphQLRequestBody\n ? HttpResponse | DefaultUnsafeFetchResponse\n : HttpResponse)\n | undefined\n | void\n\nexport type MaybeAsyncResponseResolverReturnType<\n ResponseBodyType extends DefaultBodyType,\n> = MaybePromise>\n\nexport type AsyncResponseResolverReturnType<\n ResponseBodyType extends DefaultBodyType,\n> = MaybePromise<\n | ResponseResolverReturnType\n | Iterable<\n MaybeAsyncResponseResolverReturnType,\n MaybeAsyncResponseResolverReturnType,\n MaybeAsyncResponseResolverReturnType\n >\n | AsyncIterable<\n MaybeAsyncResponseResolverReturnType,\n MaybeAsyncResponseResolverReturnType,\n MaybeAsyncResponseResolverReturnType\n >\n>\n\nexport type ResponseResolverInfo<\n ResolverExtraInfo extends Record,\n RequestBodyType extends DefaultBodyType = DefaultBodyType,\n> = {\n request: StrictRequest\n requestId: string\n /**\n * Schedule a callback to run after this response resolver completes.\n * Handy for cleaning up the side effects introduced in the resolver.\n * @example\n * sse('/', ({ client, finalize }) => {\n * const interval = setInterval(() => client.send({ data: 'ping' }))\n * finalize(() => clearInterval(interval))\n * })\n */\n finalize: ResponseResolverFinalizeFunction\n} & ResolverExtraInfo\n\ntype ResponseResolverFinalizeFunction = (\n callback: () => MaybePromise,\n) => void\n\nexport type ResponseResolver<\n ResolverExtraInfo extends Record = Record,\n RequestBodyType extends DefaultBodyType = DefaultBodyType,\n ResponseBodyType extends DefaultBodyType = undefined,\n> = (\n info: ResponseResolverInfo,\n) => AsyncResponseResolverReturnType\n\nexport interface RequestHandlerArgs<\n HandlerInfo,\n HandlerOptions extends RequestHandlerOptions,\n> {\n info: HandlerInfo\n resolver: ResponseResolver\n options?: HandlerOptions\n}\n\nexport interface RequestHandlerOptions {\n once?: boolean\n}\n\nexport interface RequestHandlerExecutionResult<\n ParsedResult extends object | undefined,\n> {\n handler: RequestHandler\n parsedResult?: ParsedResult\n request: Request\n requestId: string\n response?: Response\n}\n\nexport abstract class RequestHandler<\n HandlerInfo extends RequestHandlerDefaultInfo = RequestHandlerDefaultInfo,\n ParsedResult extends Record | undefined = any,\n ResolverExtras extends Record = any,\n HandlerOptions extends RequestHandlerOptions = RequestHandlerOptions,\n> {\n static cache = new WeakMap<\n StrictRequest,\n StrictRequest\n >()\n\n public readonly kind = 'request' as const\n\n protected resolver: ResponseResolver\n private resolverIterator?:\n | Iterator<\n MaybeAsyncResponseResolverReturnType,\n MaybeAsyncResponseResolverReturnType,\n MaybeAsyncResponseResolverReturnType\n >\n | AsyncIterator<\n MaybeAsyncResponseResolverReturnType,\n MaybeAsyncResponseResolverReturnType,\n MaybeAsyncResponseResolverReturnType\n >\n private resolverIteratorResult?: Response | HttpResponse\n private resolverIteratorCleanups?: Array<() => MaybePromise>\n private options?: HandlerOptions\n private scheduledCleanups: Map MaybePromise>>\n\n public info: HandlerInfo & RequestHandlerInternalInfo\n\n /**\n * Indicates whether this request handler has been used\n * (its resolver has successfully executed).\n */\n public isUsed: boolean\n\n constructor(args: RequestHandlerArgs) {\n this.resolver = args.resolver\n this.options = args.options\n this.scheduledCleanups = new Map()\n\n const callFrame = getCallFrame(new Error())\n\n this.info = {\n ...args.info,\n callFrame,\n }\n\n this.isUsed = false\n }\n\n /**\n * Reset the runtime state accumulated during response resolution,\n * such as generator iterator progress. Called when this handler is\n * removed from the active handlers list so re-adding it later starts\n * from a clean state.\n */\n protected reset(): void {\n this.scheduledCleanups.clear()\n\n const iterator = this.resolverIterator\n this.resolverIterator = undefined\n this.resolverIteratorResult = undefined\n this.resolverIteratorCleanups = undefined\n\n if (typeof iterator?.return === 'function') {\n void Promise.resolve(iterator.return())\n }\n }\n\n /**\n * Restore this handler so it can match requests again after being\n * exhausted (e.g. via `{ once: true }`). Also clears any accumulated\n * resolution state.\n */\n protected restore(): void {\n if (this.options?.once) {\n this.reset()\n this.isUsed = false\n }\n }\n\n /**\n * Determine if the intercepted request should be mocked.\n */\n abstract predicate(args: {\n request: Request\n parsedResult: ParsedResult\n resolutionContext?: ResponseResolutionContext\n }): boolean | Promise\n\n /**\n * Print out the successfully handled request.\n */\n abstract log(args: {\n request: Request\n response: Response\n parsedResult: ParsedResult\n }): void\n\n /**\n * Parse the intercepted request to extract additional information from it.\n * Parsed result is then exposed to other methods of this request handler.\n */\n async parse(_args: {\n request: Request\n resolutionContext?: ResponseResolutionContext\n }): Promise {\n return {} as ParsedResult\n }\n\n /**\n * Test if this handler matches the given request.\n *\n * This method is not used internally but is exposed\n * as a convenience method for consumers writing custom\n * handlers.\n */\n public async test(args: {\n request: Request\n resolutionContext?: ResponseResolutionContext\n }): Promise {\n const parsedResult = await this.parse({\n request: args.request,\n resolutionContext: args.resolutionContext,\n })\n\n return this.predicate({\n request: args.request,\n parsedResult,\n resolutionContext: args.resolutionContext,\n })\n }\n\n protected extendResolverArgs(_args: {\n request: Request\n parsedResult: ParsedResult\n }): ResolverExtras {\n return {} as ResolverExtras\n }\n\n // Clone the request instance before it's passed to the handler phases\n // and the response resolver so we can always read it for logging.\n // We only clone it once per request to avoid unnecessary overhead.\n private cloneRequestOrGetFromCache(\n request: StrictRequest,\n ): StrictRequest {\n const existingClone = RequestHandler.cache.get(request)\n\n if (typeof existingClone !== 'undefined') {\n return existingClone\n }\n\n const clonedRequest = request.clone()\n RequestHandler.cache.set(request, clonedRequest)\n\n return clonedRequest\n }\n\n /**\n * Execute this request handler and produce a mocked response\n * using the given resolver function.\n */\n public async run(args: {\n request: StrictRequest\n requestId: string\n resolutionContext?: ResponseResolutionContext\n }): Promise | null> {\n if (this.isUsed && this.options?.once) {\n return null\n }\n\n // Clone the request.\n // If this is the first time MSW handles this request, a fresh clone\n // will be created and cached. Upon further handling of the same request,\n // the request clone from the cache will be reused to prevent abundant\n // \"abort\" listeners and save up resources on cloning.\n const requestClone = this.cloneRequestOrGetFromCache(args.request)\n\n const parsedResult = await this.parse({\n request: args.request,\n resolutionContext: args.resolutionContext,\n })\n const shouldInterceptRequest = await this.predicate({\n request: args.request,\n parsedResult,\n resolutionContext: args.resolutionContext,\n })\n\n if (!shouldInterceptRequest) {\n return null\n }\n\n // Re-check isUsed, in case another request hit this handler while we were\n // asynchronously parsing the request.\n if (this.isUsed && this.options?.once) {\n return null\n }\n\n // Preemptively mark the handler as used.\n // Generators will undo this because only when the resolver reaches the\n // \"done\" state of the generator that it considers the handler used.\n this.isUsed = true\n\n // Create a response extraction wrapper around the resolver\n // since it can be both an async function and a generator.\n const executeResolver = this.wrapResolver(this.resolver)\n\n const resolverExtras = this.extendResolverArgs({\n request: args.request,\n parsedResult,\n })\n\n const listenerController = new AbortController()\n\n args.request.signal.addEventListener(\n 'abort',\n () => this.runScheduledCleanups(args.requestId),\n {\n once: true,\n signal: listenerController.signal,\n },\n )\n\n const mockedResponsePromise = (\n executeResolver({\n ...resolverExtras,\n finalize: (callback) => {\n this.scheduleCleanup(args.requestId, callback)\n },\n requestId: args.requestId,\n request: args.request,\n }) as Promise\n )\n .catch((errorOrResponse) => {\n // Allow throwing a Response instance in a response resolver.\n if (errorOrResponse instanceof Response) {\n return errorOrResponse\n }\n\n // Otherwise, throw the error as-is.\n throw errorOrResponse\n })\n .finally(() => {\n listenerController.abort()\n })\n\n const mockedResponse = await mockedResponsePromise\n\n if (mockedResponse) {\n forwardResponseCookies(mockedResponse)\n }\n\n const executionResult = this.createExecutionResult({\n // Pass the cloned request to the result so that logging\n // and other consumers could read its body once more.\n request: requestClone,\n requestId: args.requestId,\n response: mockedResponse,\n parsedResult,\n })\n\n return executionResult\n }\n\n private wrapResolver(\n resolver: ResponseResolver,\n ): ResponseResolver {\n return async (info): Promise> => {\n if (!this.resolverIterator) {\n let result\n\n try {\n result = await resolver(info)\n } catch (error) {\n // Ensure cleanup if the resolver throws, regardless of the returned type.\n await this.runScheduledCleanups(info.requestId)\n\n // Re-throw the error for the \"run()\" method to handle (e.g. thrown responses).\n throw error\n }\n\n if (!isIterable(result)) {\n // Otherwise, run the cleanup immediately if it's a plain response resolver.\n await this.runScheduledCleanups(info.requestId)\n return result\n }\n\n /**\n * @note Carry over any previously registered cleanups onto the iterator cleanups.\n * This is only relevant if \"finalize()\" is called in a regular resolver that\n * returns an iterator.\n * @example\n * http.get('/', async ({ finalize }) => {\n * finalize(cleanup)\n * return (async function*() {})()\n * })\n */\n const existingCleanups = this.scheduledCleanups.get(info.requestId)\n if (existingCleanups != null && existingCleanups.length > 0) {\n this.resolverIteratorCleanups = existingCleanups\n this.scheduledCleanups.delete(info.requestId)\n }\n\n this.resolverIterator =\n Symbol.iterator in result\n ? result[Symbol.iterator]()\n : result[Symbol.asyncIterator]()\n }\n\n // Opt-out from marking this handler as used.\n this.isUsed = false\n\n const { done, value } = await this.resolverIterator.next()\n const nextResponse = await value\n\n if (nextResponse) {\n this.resolverIteratorResult = nextResponse.clone()\n }\n\n if (done) {\n // A one-time generator resolver stops affecting the network\n // only after it's been completely exhausted.\n this.isUsed = true\n\n await this.runScheduledCleanups(info.requestId)\n\n // Clone the previously stored response so it can be read\n // when receiving it repeatedly from the \"done\" generator.\n return this.resolverIteratorResult?.clone()\n }\n\n return nextResponse\n }\n }\n\n private createExecutionResult(args: {\n request: Request\n requestId: string\n parsedResult: ParsedResult\n response?: Response\n }): RequestHandlerExecutionResult {\n return {\n handler: this,\n request: args.request,\n requestId: args.requestId,\n response: args.response,\n parsedResult: args.parsedResult,\n }\n }\n\n private scheduleCleanup(\n requestId: string,\n callback: () => MaybePromise,\n ): void {\n if (this.resolverIterator) {\n ;(this.resolverIteratorCleanups ||= []).unshift(callback)\n return\n }\n\n const cleanups = this.scheduledCleanups.get(requestId) || []\n cleanups.unshift(callback)\n this.scheduledCleanups.set(requestId, cleanups)\n }\n\n private async exhaustCleanups(\n cleanups: Array<() => MaybePromise>,\n ): Promise {\n const errors: Array = []\n\n for (const cleanup of cleanups) {\n try {\n await cleanup()\n } catch (error) {\n if (error instanceof Error) {\n errors.push(error)\n }\n }\n }\n\n if (errors.length > 0) {\n devUtils.error(\n 'Failed to execute cleanup for request handler \"%s\"',\n this.info.header,\n new AggregateError(\n errors,\n `Failed to execute cleanup for request handler \"${this.info.header}\"`,\n ),\n )\n }\n }\n\n private async runScheduledCleanups(requestId: string): Promise {\n if (\n this.resolverIterator &&\n this.resolverIteratorCleanups != null &&\n this.resolverIteratorCleanups.length > 0\n ) {\n try {\n await this.exhaustCleanups(this.resolverIteratorCleanups)\n } finally {\n this.resolverIteratorCleanups = undefined\n }\n return\n }\n\n const cleanups = this.scheduledCleanups.get(requestId)\n\n if (!cleanups || cleanups.length == 0) {\n return\n }\n\n await this.exhaustCleanups(cleanups)\n this.scheduledCleanups.delete(requestId)\n }\n}\n\n/**\n * Forwards the cookies from the given response to `document.cookie`.\n */\nexport function forwardResponseCookies(response: Response): void {\n // Cookie forwarding is only relevant in the browser.\n if (typeof document === 'undefined') {\n return\n }\n\n const responseCookies = getRawSetCookie(response)\n\n if (!responseCookies) {\n return\n }\n\n // Write the mocked response cookies to the document.\n // Use `headers-polyfill` to get the Set-Cookie header value correctly.\n // This is an alternative until TypeScript 5.2\n // and Node.js v20 become the minimum supported versions\n // and \"Headers.prototype.getSetCookie\" can be used directly.\n const allResponseCookies = HeadersPolyfill.prototype.getSetCookie.call(\n new Headers([['set-cookie', responseCookies]]),\n )\n\n for (const cookieString of allResponseCookies) {\n document.cookie = cookieString\n }\n}\n"],"mappings":"AAAA,SAAS,WAAW,uBAAuB;AAC3C,SAAS,oBAAoB;AAC7B;AAAA,EACE;AAAA,OAGK;AAIP;AAAA,OAGO;AAEP,SAAS,gBAAgB;AACzB,SAAS,uBAAuB;AA4HzB,MAAe,eAKpB;AAAA,EACA,OAAO,QAAQ,oBAAI,QAGjB;AAAA,EAEc,OAAO;AAAA,EAEb;AAAA,EACF;AAAA,EAWA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAED;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA;AAAA,EAEP,YAAY,MAAuD;AACjE,SAAK,WAAW,KAAK;AACrB,SAAK,UAAU,KAAK;AACpB,SAAK,oBAAoB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EACF;AAEA,QAAM,kBAAkB,gBAAgB,QAAQ;AAEhD,MAAI,CAAC,iBAAiB;AACpB;AAAA,EACF;AAOA,QAAM,qBAAqB,gBAAgB,UAAU,aAAa;AAAA,IAChE,IAAI,QAAQ,CAAC,CAAC,cAAc,eAAe,CAAC,CAAC;AAAA,EAC/C;AAEA,aAAW,gBAAgB,oBAAoB;AAC7C,aAAS,SAAS;AAAA,EACpB;AACF;","names":[]} \ No newline at end of file diff --git a/node_modules/msw/lib/core/handlers/WebSocketHandler.d.mts b/node_modules/msw/lib/core/handlers/WebSocketHandler.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..3d4e7afe90d9024550cecbdab1932bd5d7987bba --- /dev/null +++ b/node_modules/msw/lib/core/handlers/WebSocketHandler.d.mts @@ -0,0 +1,49 @@ +import { Emitter } from 'strict-event-emitter'; +import { WebSocketClientConnectionProtocol, WebSocketServerConnectionProtocol, WebSocketConnectionData } from '@mswjs/interceptors/WebSocket'; +import { Path, PathParams, Match } from '../utils/matching/matchRequestUrl.mjs'; + +type WebSocketHandlerParsedResult = { + match: Match; +}; +type WebSocketHandlerEventMap = { + connection: [args: WebSocketHandlerConnection]; +}; +interface WebSocketHandlerConnection { + client: WebSocketClientConnectionProtocol; + server: WebSocketServerConnectionProtocol; + info: WebSocketConnectionData['info']; + params: PathParams; +} +interface WebSocketResolutionContext { + baseUrl?: string; + [kAutoConnect]?: boolean; +} +declare const kEmitter: unique symbol; +declare const kSender: unique symbol; +declare const kConnect: unique symbol; +declare const kAutoConnect: unique symbol; +declare class WebSocketHandler { + #private; + protected readonly url: Path; + id: string; + callFrame?: string; + kind: "websocket"; + protected [kEmitter]: Emitter; + constructor(url: Path); + parse(args: { + url: string | URL; + resolutionContext?: WebSocketResolutionContext; + }): WebSocketHandlerParsedResult; + predicate(args: { + url: string | URL; + parsedResult: WebSocketHandlerParsedResult; + }): boolean; + test(url: string | URL, resolutionContext?: WebSocketResolutionContext & { + strict?: boolean; + }): boolean; + run(connection: WebSocketConnectionData, resolutionContext?: WebSocketResolutionContext): Promise; + protected [kConnect](connection: WebSocketHandlerConnection): boolean; + log(connection: WebSocketConnectionData): () => void; +} + +export { WebSocketHandler, type WebSocketHandlerConnection, type WebSocketHandlerEventMap, type WebSocketResolutionContext, kAutoConnect, kConnect, kEmitter, kSender }; diff --git a/node_modules/msw/lib/core/handlers/WebSocketHandler.d.ts b/node_modules/msw/lib/core/handlers/WebSocketHandler.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d1277ed5ab3b2526dba794c4a9b1fd1658b64249 --- /dev/null +++ b/node_modules/msw/lib/core/handlers/WebSocketHandler.d.ts @@ -0,0 +1,49 @@ +import { Emitter } from 'strict-event-emitter'; +import { WebSocketClientConnectionProtocol, WebSocketServerConnectionProtocol, WebSocketConnectionData } from '@mswjs/interceptors/WebSocket'; +import { Path, PathParams, Match } from '../utils/matching/matchRequestUrl.js'; + +type WebSocketHandlerParsedResult = { + match: Match; +}; +type WebSocketHandlerEventMap = { + connection: [args: WebSocketHandlerConnection]; +}; +interface WebSocketHandlerConnection { + client: WebSocketClientConnectionProtocol; + server: WebSocketServerConnectionProtocol; + info: WebSocketConnectionData['info']; + params: PathParams; +} +interface WebSocketResolutionContext { + baseUrl?: string; + [kAutoConnect]?: boolean; +} +declare const kEmitter: unique symbol; +declare const kSender: unique symbol; +declare const kConnect: unique symbol; +declare const kAutoConnect: unique symbol; +declare class WebSocketHandler { + #private; + protected readonly url: Path; + id: string; + callFrame?: string; + kind: "websocket"; + protected [kEmitter]: Emitter; + constructor(url: Path); + parse(args: { + url: string | URL; + resolutionContext?: WebSocketResolutionContext; + }): WebSocketHandlerParsedResult; + predicate(args: { + url: string | URL; + parsedResult: WebSocketHandlerParsedResult; + }): boolean; + test(url: string | URL, resolutionContext?: WebSocketResolutionContext & { + strict?: boolean; + }): boolean; + run(connection: WebSocketConnectionData, resolutionContext?: WebSocketResolutionContext): Promise; + protected [kConnect](connection: WebSocketHandlerConnection): boolean; + log(connection: WebSocketConnectionData): () => void; +} + +export { WebSocketHandler, type WebSocketHandlerConnection, type WebSocketHandlerEventMap, type WebSocketResolutionContext, kAutoConnect, kConnect, kEmitter, kSender }; diff --git a/node_modules/msw/lib/core/handlers/WebSocketHandler.js b/node_modules/msw/lib/core/handlers/WebSocketHandler.js new file mode 100644 index 0000000000000000000000000000000000000000..17a1b05cf5b09ef87e4d7998937b258dfdd1ee58 --- /dev/null +++ b/node_modules/msw/lib/core/handlers/WebSocketHandler.js @@ -0,0 +1,177 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var WebSocketHandler_exports = {}; +__export(WebSocketHandler_exports, { + WebSocketHandler: () => WebSocketHandler, + kAutoConnect: () => kAutoConnect, + kConnect: () => kConnect, + kEmitter: () => kEmitter, + kSender: () => kSender +}); +module.exports = __toCommonJS(WebSocketHandler_exports); +var import_strict_event_emitter = require("strict-event-emitter"); +var import_interceptors = require("@mswjs/interceptors"); +var import_matchRequestUrl = require("../utils/matching/matchRequestUrl"); +var import_getCallFrame = require("../utils/internal/getCallFrame"); +var import_attachWebSocketLogger = require("../ws/utils/attachWebSocketLogger"); +const kEmitter = Symbol("kEmitter"); +const kSender = Symbol("kSender"); +const kConnect = Symbol("kConnect"); +const kAutoConnect = Symbol("kAutoConnect"); +const kStopPropagationPatched = Symbol("kStopPropagationPatched"); +const KOnStopPropagation = Symbol("KOnStopPropagation"); +class WebSocketHandler { + constructor(url) { + this.url = url; + this.id = (0, import_interceptors.createRequestId)(); + this[kEmitter] = new import_strict_event_emitter.Emitter(); + this.callFrame = (0, import_getCallFrame.getCallFrame)(new Error()); + } + id; + callFrame; + kind = "websocket"; + [kEmitter]; + parse(args) { + const clientUrl = new URL(args.url); + const resolvedHandlerUrl = this.url instanceof RegExp || this.url.startsWith("*") ? this.url : this.#resolveWebSocketUrl(this.url, args.resolutionContext?.baseUrl); + clientUrl.pathname = clientUrl.pathname.replace(/^\/socket.io\//, "/"); + const match = (0, import_matchRequestUrl.matchRequestUrl)( + clientUrl, + resolvedHandlerUrl, + args.resolutionContext?.baseUrl + ); + return { + match + }; + } + predicate(args) { + return args.parsedResult.match.matches; + } + test(url, resolutionContext) { + return this.#match(url, resolutionContext) != null; + } + async run(connection, resolutionContext) { + const parsedResult = this.#match(connection.client.url, resolutionContext); + if (parsedResult == null) { + return null; + } + const resolvedConnection = { + ...connection, + params: parsedResult.match.params || {} + }; + if (resolutionContext?.[kAutoConnect] ?? true) { + if (this[kConnect](resolvedConnection)) { + return resolvedConnection; + } + return null; + } + return resolvedConnection; + } + #match(url, resolutionContext) { + const resolvedUrl = this.#resolveWebSocketUrl( + url.toString(), + resolutionContext?.baseUrl + ); + const parsedResult = this.parse({ + url: resolvedUrl, + resolutionContext + }); + if (this.predicate({ + url, + parsedResult + })) { + return parsedResult; + } + return null; + } + [kConnect](connection) { + connection.client.addEventListener( + "message", + createStopPropagationListener(this) + ); + connection.client.addEventListener( + "close", + createStopPropagationListener(this) + ); + connection.server.addEventListener( + "open", + createStopPropagationListener(this) + ); + connection.server.addEventListener( + "message", + createStopPropagationListener(this) + ); + connection.server.addEventListener( + "error", + createStopPropagationListener(this) + ); + connection.server.addEventListener( + "close", + createStopPropagationListener(this) + ); + return this[kEmitter].emit("connection", connection); + } + log(connection) { + return (0, import_attachWebSocketLogger.attachWebSocketLogger)(connection); + } + #resolveWebSocketUrl(url, baseUrl) { + const resolvedUrl = (0, import_interceptors.resolveWebSocketUrl)( + baseUrl ? ( + /** + * @note Resolve against the base URL preemtively because `resolveWebSocketUrl` only + * resolves against `location.href`, which is missing in Node.js. Base URL allows + * the handler to accept a relative URL in Node.js. + */ + new URL(url, baseUrl) + ) : url + ); + return resolvedUrl.replace(/\/$/, ""); + } +} +function createStopPropagationListener(handler) { + return function stopPropagationListener(event) { + const propagationStoppedAt = Reflect.get(event, "kPropagationStoppedAt"); + if (propagationStoppedAt && handler.id !== propagationStoppedAt) { + event.stopImmediatePropagation(); + return; + } + Object.defineProperty(event, KOnStopPropagation, { + value() { + Object.defineProperty(event, "kPropagationStoppedAt", { + value: handler.id + }); + }, + configurable: true + }); + if (!Reflect.get(event, kStopPropagationPatched)) { + event.stopPropagation = new Proxy(event.stopPropagation, { + apply: (target, thisArg, args) => { + Reflect.get(event, KOnStopPropagation)?.call(handler); + return Reflect.apply(target, thisArg, args); + } + }); + Object.defineProperty(event, kStopPropagationPatched, { + value: true, + // If something else attempts to redefine this, throw. + configurable: false + }); + } + }; +} +//# sourceMappingURL=WebSocketHandler.js.map \ No newline at end of file diff --git a/node_modules/msw/lib/core/handlers/WebSocketHandler.js.map b/node_modules/msw/lib/core/handlers/WebSocketHandler.js.map new file mode 100644 index 0000000000000000000000000000000000000000..9d26c938e8e39e4d4afb21978ec33cdd27a4fec4 --- /dev/null +++ b/node_modules/msw/lib/core/handlers/WebSocketHandler.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/core/handlers/WebSocketHandler.ts"],"sourcesContent":["import { Emitter } from 'strict-event-emitter'\nimport { createRequestId, resolveWebSocketUrl } from '@mswjs/interceptors'\nimport type {\n WebSocketClientConnectionProtocol,\n WebSocketConnectionData,\n WebSocketServerConnectionProtocol,\n} from '@mswjs/interceptors/WebSocket'\nimport {\n type Match,\n type Path,\n type PathParams,\n matchRequestUrl,\n} from '../utils/matching/matchRequestUrl'\nimport { getCallFrame } from '../utils/internal/getCallFrame'\nimport { attachWebSocketLogger } from '../ws/utils/attachWebSocketLogger'\n\ntype WebSocketHandlerParsedResult = {\n match: Match\n}\n\nexport type WebSocketHandlerEventMap = {\n connection: [args: WebSocketHandlerConnection]\n}\n\nexport interface WebSocketHandlerConnection {\n client: WebSocketClientConnectionProtocol\n server: WebSocketServerConnectionProtocol\n info: WebSocketConnectionData['info']\n params: PathParams\n}\n\nexport interface WebSocketResolutionContext {\n baseUrl?: string\n [kAutoConnect]?: boolean\n}\n\nexport const kEmitter = Symbol('kEmitter')\nexport const kSender = Symbol('kSender')\nexport const kConnect = Symbol('kConnect')\nexport const kAutoConnect = Symbol('kAutoConnect')\n\nconst kStopPropagationPatched = Symbol('kStopPropagationPatched')\nconst KOnStopPropagation = Symbol('KOnStopPropagation')\n\nexport class WebSocketHandler {\n public id: string\n public callFrame?: string\n public kind = 'websocket' as const\n\n protected [kEmitter]: Emitter\n\n constructor(protected readonly url: Path) {\n this.id = createRequestId()\n\n this[kEmitter] = new Emitter()\n this.callFrame = getCallFrame(new Error())\n }\n\n public parse(args: {\n url: string | URL\n resolutionContext?: WebSocketResolutionContext\n }): WebSocketHandlerParsedResult {\n const clientUrl = new URL(args.url)\n\n // Resolve the WebSocket handler path:\n // - Plain string URLs resolved as per the specification (via Interceptors).\n // - String URLs starting with a wildcard are preserved (prepending a scheme there will break them).\n // - RegExp paths are preserved.\n const resolvedHandlerUrl =\n this.url instanceof RegExp || this.url.startsWith('*')\n ? this.url\n : this.#resolveWebSocketUrl(this.url, args.resolutionContext?.baseUrl)\n\n /**\n * @note Remove the Socket.IO path prefix from the WebSocket\n * client URL. This is an exception to keep the users from\n * including the implementation details in their handlers.\n */\n clientUrl.pathname = clientUrl.pathname.replace(/^\\/socket.io\\//, '/')\n\n const match = matchRequestUrl(\n clientUrl,\n resolvedHandlerUrl,\n args.resolutionContext?.baseUrl,\n )\n\n return {\n match,\n }\n }\n\n public predicate(args: {\n url: string | URL\n parsedResult: WebSocketHandlerParsedResult\n }): boolean {\n return args.parsedResult.match.matches\n }\n\n public test(\n url: string | URL,\n resolutionContext?: WebSocketResolutionContext & { strict?: boolean },\n ): boolean {\n return this.#match(url, resolutionContext) != null\n }\n\n public async run(\n connection: WebSocketConnectionData,\n resolutionContext?: WebSocketResolutionContext,\n ): Promise {\n const parsedResult = this.#match(connection.client.url, resolutionContext)\n\n if (parsedResult == null) {\n return null\n }\n\n const resolvedConnection: WebSocketHandlerConnection = {\n ...connection,\n params: parsedResult.match.params || {},\n }\n\n if (resolutionContext?.[kAutoConnect] ?? true) {\n if (this[kConnect](resolvedConnection)) {\n return resolvedConnection\n }\n\n return null\n }\n\n return resolvedConnection\n }\n\n #match(\n url: string | URL,\n resolutionContext?: WebSocketResolutionContext & { strict?: boolean },\n ): WebSocketHandlerParsedResult | null {\n const resolvedUrl = this.#resolveWebSocketUrl(\n url.toString(),\n resolutionContext?.baseUrl,\n )\n const parsedResult = this.parse({\n url: resolvedUrl,\n resolutionContext,\n })\n\n if (\n this.predicate({\n url,\n parsedResult,\n })\n ) {\n return parsedResult\n }\n\n return null\n }\n\n protected [kConnect](connection: WebSocketHandlerConnection): boolean {\n // Support `event.stopPropagation()` for various client/server events.\n connection.client.addEventListener(\n 'message',\n createStopPropagationListener(this),\n )\n connection.client.addEventListener(\n 'close',\n createStopPropagationListener(this),\n )\n\n connection.server.addEventListener(\n 'open',\n createStopPropagationListener(this),\n )\n connection.server.addEventListener(\n 'message',\n createStopPropagationListener(this),\n )\n connection.server.addEventListener(\n 'error',\n createStopPropagationListener(this),\n )\n connection.server.addEventListener(\n 'close',\n createStopPropagationListener(this),\n )\n\n /**\n * @fixme Use \"rettime\" and await these events to have\n * exceptions propagate properly.\n */\n return this[kEmitter].emit('connection', connection)\n }\n\n public log(connection: WebSocketConnectionData): () => void {\n return attachWebSocketLogger(connection)\n }\n\n #resolveWebSocketUrl(url: string, baseUrl?: string): string {\n const resolvedUrl = resolveWebSocketUrl(\n baseUrl\n ? /**\n * @note Resolve against the base URL preemtively because `resolveWebSocketUrl` only\n * resolves against `location.href`, which is missing in Node.js. Base URL allows\n * the handler to accept a relative URL in Node.js.\n */\n new URL(url, baseUrl)\n : url,\n )\n\n /**\n * @note Omit the trailing slash.\n * While the browser always produces a trailing slash at the end of a WebSocket URL,\n * having it in as the handler's predicate would mean it is *required* in the actual URL.\n */\n return resolvedUrl.replace(/\\/$/, '')\n }\n}\n\nfunction createStopPropagationListener(handler: WebSocketHandler) {\n return function stopPropagationListener(event: Event) {\n const propagationStoppedAt = Reflect.get(event, 'kPropagationStoppedAt') as\n | string\n | undefined\n\n if (propagationStoppedAt && handler.id !== propagationStoppedAt) {\n event.stopImmediatePropagation()\n return\n }\n\n Object.defineProperty(event, KOnStopPropagation, {\n value(this: WebSocketHandler) {\n Object.defineProperty(event, 'kPropagationStoppedAt', {\n value: handler.id,\n })\n },\n configurable: true,\n })\n\n // Since the same event instance is shared between all client/server objects,\n // make sure to patch its `stopPropagation` method only once.\n if (!Reflect.get(event, kStopPropagationPatched)) {\n event.stopPropagation = new Proxy(event.stopPropagation, {\n apply: (target, thisArg, args) => {\n Reflect.get(event, KOnStopPropagation)?.call(handler)\n return Reflect.apply(target, thisArg, args)\n },\n })\n\n Object.defineProperty(event, kStopPropagationPatched, {\n value: true,\n // If something else attempts to redefine this, throw.\n configurable: false,\n })\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,kCAAwB;AACxB,0BAAqD;AAMrD,6BAKO;AACP,0BAA6B;AAC7B,mCAAsC;AAsB/B,MAAM,WAAW,OAAO,UAAU;AAClC,MAAM,UAAU,OAAO,SAAS;AAChC,MAAM,WAAW,OAAO,UAAU;AAClC,MAAM,eAAe,OAAO,cAAc;AAEjD,MAAM,0BAA0B,OAAO,yBAAyB;AAChE,MAAM,qBAAqB,OAAO,oBAAoB;AAE/C,MAAM,iBAAiB;AAAA,EAO5B,YAA+B,KAAW;AAAX;AAC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,QAAQ;AAAA,QACjB,CAAC;AAAA,MACH;AAAA,MACA,cAAc;AAAA,IAChB,CAAC;AAID,QAAI,CAAC,QAAQ,IAAI,OAAO,uBAAuB,GAAG;AAChD,YAAM,kBAAkB,IAAI,MAAM,MAAM,iBAAiB;AAAA,QACvD,OAAO,CAAC,QAAQ,SAAS,SAAS;AAChC,kBAAQ,IAAI,OAAO,kBAAkB,GAAG,KAAK,OAAO;AACpD,iBAAO,QAAQ,MAAM,QAAQ,SAAS,IAAI;AAAA,QAC5C;AAAA,MACF,CAAC;AAED,aAAO,eAAe,OAAO,yBAAyB;AAAA,QACpD,OAAO;AAAA;AAAA,QAEP,cAAc;AAAA,MAChB,CAAC;AAAA,IACH;AAAA,EACF;AACF;","names":[]} \ No newline at end of file diff --git a/node_modules/msw/lib/core/handlers/WebSocketHandler.mjs b/node_modules/msw/lib/core/handlers/WebSocketHandler.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ee061655be1527f40693fbc52039b1e04335bceb --- /dev/null +++ b/node_modules/msw/lib/core/handlers/WebSocketHandler.mjs @@ -0,0 +1,159 @@ +import { Emitter } from "strict-event-emitter"; +import { createRequestId, resolveWebSocketUrl } from "@mswjs/interceptors"; +import { + matchRequestUrl +} from '../utils/matching/matchRequestUrl.mjs'; +import { getCallFrame } from '../utils/internal/getCallFrame.mjs'; +import { attachWebSocketLogger } from '../ws/utils/attachWebSocketLogger.mjs'; +const kEmitter = Symbol("kEmitter"); +const kSender = Symbol("kSender"); +const kConnect = Symbol("kConnect"); +const kAutoConnect = Symbol("kAutoConnect"); +const kStopPropagationPatched = Symbol("kStopPropagationPatched"); +const KOnStopPropagation = Symbol("KOnStopPropagation"); +class WebSocketHandler { + constructor(url) { + this.url = url; + this.id = createRequestId(); + this[kEmitter] = new Emitter(); + this.callFrame = getCallFrame(new Error()); + } + id; + callFrame; + kind = "websocket"; + [kEmitter]; + parse(args) { + const clientUrl = new URL(args.url); + const resolvedHandlerUrl = this.url instanceof RegExp || this.url.startsWith("*") ? this.url : this.#resolveWebSocketUrl(this.url, args.resolutionContext?.baseUrl); + clientUrl.pathname = clientUrl.pathname.replace(/^\/socket.io\//, "/"); + const match = matchRequestUrl( + clientUrl, + resolvedHandlerUrl, + args.resolutionContext?.baseUrl + ); + return { + match + }; + } + predicate(args) { + return args.parsedResult.match.matches; + } + test(url, resolutionContext) { + return this.#match(url, resolutionContext) != null; + } + async run(connection, resolutionContext) { + const parsedResult = this.#match(connection.client.url, resolutionContext); + if (parsedResult == null) { + return null; + } + const resolvedConnection = { + ...connection, + params: parsedResult.match.params || {} + }; + if (resolutionContext?.[kAutoConnect] ?? true) { + if (this[kConnect](resolvedConnection)) { + return resolvedConnection; + } + return null; + } + return resolvedConnection; + } + #match(url, resolutionContext) { + const resolvedUrl = this.#resolveWebSocketUrl( + url.toString(), + resolutionContext?.baseUrl + ); + const parsedResult = this.parse({ + url: resolvedUrl, + resolutionContext + }); + if (this.predicate({ + url, + parsedResult + })) { + return parsedResult; + } + return null; + } + [kConnect](connection) { + connection.client.addEventListener( + "message", + createStopPropagationListener(this) + ); + connection.client.addEventListener( + "close", + createStopPropagationListener(this) + ); + connection.server.addEventListener( + "open", + createStopPropagationListener(this) + ); + connection.server.addEventListener( + "message", + createStopPropagationListener(this) + ); + connection.server.addEventListener( + "error", + createStopPropagationListener(this) + ); + connection.server.addEventListener( + "close", + createStopPropagationListener(this) + ); + return this[kEmitter].emit("connection", connection); + } + log(connection) { + return attachWebSocketLogger(connection); + } + #resolveWebSocketUrl(url, baseUrl) { + const resolvedUrl = resolveWebSocketUrl( + baseUrl ? ( + /** + * @note Resolve against the base URL preemtively because `resolveWebSocketUrl` only + * resolves against `location.href`, which is missing in Node.js. Base URL allows + * the handler to accept a relative URL in Node.js. + */ + new URL(url, baseUrl) + ) : url + ); + return resolvedUrl.replace(/\/$/, ""); + } +} +function createStopPropagationListener(handler) { + return function stopPropagationListener(event) { + const propagationStoppedAt = Reflect.get(event, "kPropagationStoppedAt"); + if (propagationStoppedAt && handler.id !== propagationStoppedAt) { + event.stopImmediatePropagation(); + return; + } + Object.defineProperty(event, KOnStopPropagation, { + value() { + Object.defineProperty(event, "kPropagationStoppedAt", { + value: handler.id + }); + }, + configurable: true + }); + if (!Reflect.get(event, kStopPropagationPatched)) { + event.stopPropagation = new Proxy(event.stopPropagation, { + apply: (target, thisArg, args) => { + Reflect.get(event, KOnStopPropagation)?.call(handler); + return Reflect.apply(target, thisArg, args); + } + }); + Object.defineProperty(event, kStopPropagationPatched, { + value: true, + // If something else attempts to redefine this, throw. + configurable: false + }); + } + }; +} +export { + WebSocketHandler, + kAutoConnect, + kConnect, + kEmitter, + kSender +}; +//# sourceMappingURL=WebSocketHandler.mjs.map \ No newline at end of file diff --git a/node_modules/msw/lib/core/handlers/WebSocketHandler.mjs.map b/node_modules/msw/lib/core/handlers/WebSocketHandler.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..7ef95d0d9bb1a659a1d3815bd57861f2ab47e947 --- /dev/null +++ b/node_modules/msw/lib/core/handlers/WebSocketHandler.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/core/handlers/WebSocketHandler.ts"],"sourcesContent":["import { Emitter } from 'strict-event-emitter'\nimport { createRequestId, resolveWebSocketUrl } from '@mswjs/interceptors'\nimport type {\n WebSocketClientConnectionProtocol,\n WebSocketConnectionData,\n WebSocketServerConnectionProtocol,\n} from '@mswjs/interceptors/WebSocket'\nimport {\n type Match,\n type Path,\n type PathParams,\n matchRequestUrl,\n} from '../utils/matching/matchRequestUrl'\nimport { getCallFrame } from '../utils/internal/getCallFrame'\nimport { attachWebSocketLogger } from '../ws/utils/attachWebSocketLogger'\n\ntype WebSocketHandlerParsedResult = {\n match: Match\n}\n\nexport type WebSocketHandlerEventMap = {\n connection: [args: WebSocketHandlerConnection]\n}\n\nexport interface WebSocketHandlerConnection {\n client: WebSocketClientConnectionProtocol\n server: WebSocketServerConnectionProtocol\n info: WebSocketConnectionData['info']\n params: PathParams\n}\n\nexport interface WebSocketResolutionContext {\n baseUrl?: string\n [kAutoConnect]?: boolean\n}\n\nexport const kEmitter = Symbol('kEmitter')\nexport const kSender = Symbol('kSender')\nexport const kConnect = Symbol('kConnect')\nexport const kAutoConnect = Symbol('kAutoConnect')\n\nconst kStopPropagationPatched = Symbol('kStopPropagationPatched')\nconst KOnStopPropagation = Symbol('KOnStopPropagation')\n\nexport class WebSocketHandler {\n public id: string\n public callFrame?: string\n public kind = 'websocket' as const\n\n protected [kEmitter]: Emitter\n\n constructor(protected readonly url: Path) {\n this.id = createRequestId()\n\n this[kEmitter] = new Emitter()\n this.callFrame = getCallFrame(new Error())\n }\n\n public parse(args: {\n url: string | URL\n resolutionContext?: WebSocketResolutionContext\n }): WebSocketHandlerParsedResult {\n const clientUrl = new URL(args.url)\n\n // Resolve the WebSocket handler path:\n // - Plain string URLs resolved as per the specification (via Interceptors).\n // - String URLs starting with a wildcard are preserved (prepending a scheme there will break them).\n // - RegExp paths are preserved.\n const resolvedHandlerUrl =\n this.url instanceof RegExp || this.url.startsWith('*')\n ? this.url\n : this.#resolveWebSocketUrl(this.url, args.resolutionContext?.baseUrl)\n\n /**\n * @note Remove the Socket.IO path prefix from the WebSocket\n * client URL. This is an exception to keep the users from\n * including the implementation details in their handlers.\n */\n clientUrl.pathname = clientUrl.pathname.replace(/^\\/socket.io\\//, '/')\n\n const match = matchRequestUrl(\n clientUrl,\n resolvedHandlerUrl,\n args.resolutionContext?.baseUrl,\n )\n\n return {\n match,\n }\n }\n\n public predicate(args: {\n url: string | URL\n parsedResult: WebSocketHandlerParsedResult\n }): boolean {\n return args.parsedResult.match.matches\n }\n\n public test(\n url: string | URL,\n resolutionContext?: WebSocketResolutionContext & { strict?: boolean },\n ): boolean {\n return this.#match(url, resolutionContext) != null\n }\n\n public async run(\n connection: WebSocketConnectionData,\n resolutionContext?: WebSocketResolutionContext,\n ): Promise {\n const parsedResult = this.#match(connection.client.url, resolutionContext)\n\n if (parsedResult == null) {\n return null\n }\n\n const resolvedConnection: WebSocketHandlerConnection = {\n ...connection,\n params: parsedResult.match.params || {},\n }\n\n if (resolutionContext?.[kAutoConnect] ?? true) {\n if (this[kConnect](resolvedConnection)) {\n return resolvedConnection\n }\n\n return null\n }\n\n return resolvedConnection\n }\n\n #match(\n url: string | URL,\n resolutionContext?: WebSocketResolutionContext & { strict?: boolean },\n ): WebSocketHandlerParsedResult | null {\n const resolvedUrl = this.#resolveWebSocketUrl(\n url.toString(),\n resolutionContext?.baseUrl,\n )\n const parsedResult = this.parse({\n url: resolvedUrl,\n resolutionContext,\n })\n\n if (\n this.predicate({\n url,\n parsedResult,\n })\n ) {\n return parsedResult\n }\n\n return null\n }\n\n protected [kConnect](connection: WebSocketHandlerConnection): boolean {\n // Support `event.stopPropagation()` for various client/server events.\n connection.client.addEventListener(\n 'message',\n createStopPropagationListener(this),\n )\n connection.client.addEventListener(\n 'close',\n createStopPropagationListener(this),\n )\n\n connection.server.addEventListener(\n 'open',\n createStopPropagationListener(this),\n )\n connection.server.addEventListener(\n 'message',\n createStopPropagationListener(this),\n )\n connection.server.addEventListener(\n 'error',\n createStopPropagationListener(this),\n )\n connection.server.addEventListener(\n 'close',\n createStopPropagationListener(this),\n )\n\n /**\n * @fixme Use \"rettime\" and await these events to have\n * exceptions propagate properly.\n */\n return this[kEmitter].emit('connection', connection)\n }\n\n public log(connection: WebSocketConnectionData): () => void {\n return attachWebSocketLogger(connection)\n }\n\n #resolveWebSocketUrl(url: string, baseUrl?: string): string {\n const resolvedUrl = resolveWebSocketUrl(\n baseUrl\n ? /**\n * @note Resolve against the base URL preemtively because `resolveWebSocketUrl` only\n * resolves against `location.href`, which is missing in Node.js. Base URL allows\n * the handler to accept a relative URL in Node.js.\n */\n new URL(url, baseUrl)\n : url,\n )\n\n /**\n * @note Omit the trailing slash.\n * While the browser always produces a trailing slash at the end of a WebSocket URL,\n * having it in as the handler's predicate would mean it is *required* in the actual URL.\n */\n return resolvedUrl.replace(/\\/$/, '')\n }\n}\n\nfunction createStopPropagationListener(handler: WebSocketHandler) {\n return function stopPropagationListener(event: Event) {\n const propagationStoppedAt = Reflect.get(event, 'kPropagationStoppedAt') as\n | string\n | undefined\n\n if (propagationStoppedAt && handler.id !== propagationStoppedAt) {\n event.stopImmediatePropagation()\n return\n }\n\n Object.defineProperty(event, KOnStopPropagation, {\n value(this: WebSocketHandler) {\n Object.defineProperty(event, 'kPropagationStoppedAt', {\n value: handler.id,\n })\n },\n configurable: true,\n })\n\n // Since the same event instance is shared between all client/server objects,\n // make sure to patch its `stopPropagation` method only once.\n if (!Reflect.get(event, kStopPropagationPatched)) {\n event.stopPropagation = new Proxy(event.stopPropagation, {\n apply: (target, thisArg, args) => {\n Reflect.get(event, KOnStopPropagation)?.call(handler)\n return Reflect.apply(target, thisArg, args)\n },\n })\n\n Object.defineProperty(event, kStopPropagationPatched, {\n value: true,\n // If something else attempts to redefine this, throw.\n configurable: false,\n })\n }\n }\n}\n"],"mappings":"AAAA,SAAS,eAAe;AACxB,SAAS,iBAAiB,2BAA2B;AAMrD;AAAA,EAIE;AAAA,OACK;AACP,SAAS,oBAAoB;AAC7B,SAAS,6BAA6B;AAsB/B,MAAM,WAAW,OAAO,UAAU;AAClC,MAAM,UAAU,OAAO,SAAS;AAChC,MAAM,WAAW,OAAO,UAAU;AAClC,MAAM,eAAe,OAAO,cAAc;AAEjD,MAAM,0BAA0B,OAAO,yBAAyB;AAChE,MAAM,qBAAqB,OAAO,oBAAoB;AAE/C,MAAM,iBAAiB;AAAA,EAO5B,YAA+B,KAAW;AAAX;AAC7B,SAAK,KAAK,gBAAgB;AAE1B,SAAK,QAAQ,IAAI,IAAI,QAAQ;AAC7B,SAAK,YAAY,aAAa,IAAI,MAAM,CAAC;AAAA,EAC3C;AAAA,EAXO;AAAA,EACA;AAAA,EACA,OAAO;AAAA,EAEd,CAAW,QAAQ;AAAA,EASZ,MAAM,MAGoB;AAC/B,UAAM,YAAY,IAAI,IAAI,KAAK,GAAG;AAMlC,UAAM,q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BAAO,QAAQ,MAAM,QAAQ,SAAS,IAAI;AAAA,QAC5C;AAAA,MACF,CAAC;AAED,aAAO,eAAe,OAAO,yBAAyB;AAAA,QACpD,OAAO;AAAA;AAAA,QAEP,cAAc;AAAA,MAChB,CAAC;AAAA,IACH;AAAA,EACF;AACF;","names":[]} \ No newline at end of file diff --git a/node_modules/msw/lib/core/http.d.mts b/node_modules/msw/lib/core/http.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..4bd3d59babbc4d32cb22f21d90068e3c65b50aaf --- /dev/null +++ b/node_modules/msw/lib/core/http.d.mts @@ -0,0 +1,31 @@ +import { D as DefaultBodyType, a as ResponseResolver, c as RequestHandlerOptions } from './HttpResponse-CQwYpuKo.mjs'; +import { HttpRequestPredicate, HttpRequestResolverExtras, HttpHandler } from './handlers/HttpHandler.mjs'; +import { PathParams } from './utils/matching/matchRequestUrl.mjs'; +import '@mswjs/interceptors'; +import './utils/internal/isIterable.mjs'; +import './typeUtils.mjs'; +import 'graphql'; + +type HttpRequestHandler = = PathParams, RequestBodyType extends DefaultBodyType = DefaultBodyType, ResponseBodyType extends DefaultBodyType = undefined>(predicate: HttpRequestPredicate, resolver: HttpResponseResolver, options?: RequestHandlerOptions) => HttpHandler; +type HttpResponseResolver = PathParams, RequestBodyType extends DefaultBodyType = DefaultBodyType, ResponseBodyType extends DefaultBodyType = DefaultBodyType> = ResponseResolver, RequestBodyType, ResponseBodyType>; +/** + * A namespace to intercept and mock HTTP requests. + * + * @example + * http.get('/user', resolver) + * http.post('/post/:id', resolver) + * + * @see {@link https://mswjs.io/docs/api/http `http` API reference} + */ +declare const http: { + all: HttpRequestHandler; + head: HttpRequestHandler; + get: HttpRequestHandler; + post: HttpRequestHandler; + put: HttpRequestHandler; + delete: HttpRequestHandler; + patch: HttpRequestHandler; + options: HttpRequestHandler; +}; + +export { type HttpRequestHandler, type HttpResponseResolver, http }; diff --git a/node_modules/msw/lib/core/http.d.ts b/node_modules/msw/lib/core/http.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..68cf00a97e7562cadb10b30910da662047169d6d --- /dev/null +++ b/node_modules/msw/lib/core/http.d.ts @@ -0,0 +1,31 @@ +import { D as DefaultBodyType, a as ResponseResolver, c as RequestHandlerOptions } from './HttpResponse-BFS34nkx.js'; +import { HttpRequestPredicate, HttpRequestResolverExtras, HttpHandler } from './handlers/HttpHandler.js'; +import { PathParams } from './utils/matching/matchRequestUrl.js'; +import '@mswjs/interceptors'; +import './utils/internal/isIterable.js'; +import './typeUtils.js'; +import 'graphql'; + +type HttpRequestHandler = = PathParams, RequestBodyType extends DefaultBodyType = DefaultBodyType, ResponseBodyType extends DefaultBodyType = undefined>(predicate: HttpRequestPredicate, resolver: HttpResponseResolver, options?: RequestHandlerOptions) => HttpHandler; +type HttpResponseResolver = PathParams, RequestBodyType extends DefaultBodyType = DefaultBodyType, ResponseBodyType extends DefaultBodyType = DefaultBodyType> = ResponseResolver, RequestBodyType, ResponseBodyType>; +/** + * A namespace to intercept and mock HTTP requests. + * + * @example + * http.get('/user', resolver) + * http.post('/post/:id', resolver) + * + * @see {@link https://mswjs.io/docs/api/http `http` API reference} + */ +declare const http: { + all: HttpRequestHandler; + head: HttpRequestHandler; + get: HttpRequestHandler; + post: HttpRequestHandler; + put: HttpRequestHandler; + delete: HttpRequestHandler; + patch: HttpRequestHandler; + options: HttpRequestHandler; +}; + +export { type HttpRequestHandler, type HttpResponseResolver, http }; diff --git a/node_modules/msw/lib/core/http.js b/node_modules/msw/lib/core/http.js new file mode 100644 index 0000000000000000000000000000000000000000..e74d2a5c476397e460d32e701cb8bb755fc631a1 --- /dev/null +++ b/node_modules/msw/lib/core/http.js @@ -0,0 +1,41 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var http_exports = {}; +__export(http_exports, { + http: () => http +}); +module.exports = __toCommonJS(http_exports); +var import_RequestHandler = require("./handlers/RequestHandler"); +var import_HttpHandler = require("./handlers/HttpHandler"); +function createHttpHandler(method) { + return (predicate, resolver, options = {}) => { + return new import_HttpHandler.HttpHandler(method, predicate, resolver, options); + }; +} +const http = { + all: createHttpHandler(/.+/), + head: createHttpHandler(import_HttpHandler.HttpMethods.HEAD), + get: createHttpHandler(import_HttpHandler.HttpMethods.GET), + post: createHttpHandler(import_HttpHandler.HttpMethods.POST), + put: createHttpHandler(import_HttpHandler.HttpMethods.PUT), + delete: createHttpHandler(import_HttpHandler.HttpMethods.DELETE), + patch: createHttpHandler(import_HttpHandler.HttpMethods.PATCH), + options: createHttpHandler(import_HttpHandler.HttpMethods.OPTIONS) +}; +//# sourceMappingURL=http.js.map \ No newline at end of file diff --git a/node_modules/msw/lib/core/http.js.map b/node_modules/msw/lib/core/http.js.map new file mode 100644 index 0000000000000000000000000000000000000000..6f74bf0923eabf9bdb3e283a81d07c49d343b6df --- /dev/null +++ b/node_modules/msw/lib/core/http.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/core/http.ts"],"sourcesContent":["import {\n type DefaultBodyType,\n type RequestHandlerOptions,\n type ResponseResolver,\n} from './handlers/RequestHandler'\nimport {\n HttpMethods,\n HttpHandler,\n type HttpRequestResolverExtras,\n type HttpRequestPredicate,\n} from './handlers/HttpHandler'\nimport type { PathParams } from './utils/matching/matchRequestUrl'\n\nexport type HttpRequestHandler = <\n Params extends PathParams = PathParams,\n RequestBodyType extends DefaultBodyType = DefaultBodyType,\n // Response body type MUST be undefined by default.\n // This is how we can distinguish between a handler that\n // returns plain \"Response\" and the one returning \"HttpResponse\"\n // to enforce a stricter response body type.\n ResponseBodyType extends DefaultBodyType = undefined,\n>(\n predicate: HttpRequestPredicate,\n resolver: HttpResponseResolver,\n options?: RequestHandlerOptions,\n) => HttpHandler\n\nexport type HttpResponseResolver<\n Params extends PathParams = PathParams,\n RequestBodyType extends DefaultBodyType = DefaultBodyType,\n ResponseBodyType extends DefaultBodyType = DefaultBodyType,\n> = ResponseResolver<\n HttpRequestResolverExtras,\n RequestBodyType,\n ResponseBodyType\n>\n\nfunction createHttpHandler(\n method: Method,\n): HttpRequestHandler {\n return (predicate, resolver, options = {}) => {\n return new HttpHandler(method, predicate, resolver, options)\n }\n}\n\n/**\n * A namespace to intercept and mock HTTP requests.\n *\n * @example\n * http.get('/user', resolver)\n * http.post('/post/:id', resolver)\n *\n * @see {@link https://mswjs.io/docs/api/http `http` API reference}\n */\nexport const http = {\n all: createHttpHandler(/.+/),\n head: createHttpHandler(HttpMethods.HEAD),\n get: createHttpHandler(HttpMethods.GET),\n post: createHttpHandler(HttpMethods.POST),\n put: createHttpHandler(HttpMethods.PUT),\n delete: createHttpHandler(HttpMethods.DELETE),\n patch: createHttpHandler(HttpMethods.PATCH),\n options: createHttpHandler(HttpMethods.OPTIONS),\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,4BAIO;AACP,yBAKO;AA2BP,SAAS,kBACP,QACoB;AACpB,SAAO,CAAC,WAAW,UAAU,UAAU,CAAC,MAAM;AAC5C,WAAO,IAAI,+BAAY,QAAQ,WAAW,UAAU,OAAO;AAAA,EAC7D;AACF;AAWO,MAAM,OAAO;AAAA,EAClB,KAAK,kBAAkB,IAAI;AAAA,EAC3B,MAAM,kBAAkB,+BAAY,IAAI;AAAA,EACxC,KAAK,kBAAkB,+BAAY,GAAG;AAAA,EACtC,MAAM,kBAAkB,+BAAY,IAAI;AAAA,EACxC,KAAK,kBAAkB,+BAAY,GAAG;AAAA,EACtC,QAAQ,kBAAkB,+BAAY,MAAM;AAAA,EAC5C,OAAO,kBAAkB,+BAAY,KAAK;AAAA,EAC1C,SAAS,kBAAkB,+BAAY,OAAO;AAChD;","names":[]} \ No newline at end of file diff --git a/node_modules/msw/lib/core/http.mjs b/node_modules/msw/lib/core/http.mjs new file mode 100644 index 0000000000000000000000000000000000000000..5302491ac1f1547a3105a5e8279e7dbc3be19c13 --- /dev/null +++ b/node_modules/msw/lib/core/http.mjs @@ -0,0 +1,25 @@ +import { +} from './handlers/RequestHandler.mjs'; +import { + HttpMethods, + HttpHandler +} from './handlers/HttpHandler.mjs'; +function createHttpHandler(method) { + return (predicate, resolver, options = {}) => { + return new HttpHandler(method, predicate, resolver, options); + }; +} +const http = { + all: createHttpHandler(/.+/), + head: createHttpHandler(HttpMethods.HEAD), + get: createHttpHandler(HttpMethods.GET), + post: createHttpHandler(HttpMethods.POST), + put: createHttpHandler(HttpMethods.PUT), + delete: createHttpHandler(HttpMethods.DELETE), + patch: createHttpHandler(HttpMethods.PATCH), + options: createHttpHandler(HttpMethods.OPTIONS) +}; +export { + http +}; +//# sourceMappingURL=http.mjs.map \ No newline at end of file diff --git a/node_modules/msw/lib/core/http.mjs.map b/node_modules/msw/lib/core/http.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..dc805597174f3aeddd337eb249ecbeca20e2fe2a --- /dev/null +++ b/node_modules/msw/lib/core/http.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/core/http.ts"],"sourcesContent":["import {\n type DefaultBodyType,\n type RequestHandlerOptions,\n type ResponseResolver,\n} from './handlers/RequestHandler'\nimport {\n HttpMethods,\n HttpHandler,\n type HttpRequestResolverExtras,\n type HttpRequestPredicate,\n} from './handlers/HttpHandler'\nimport type { PathParams } from './utils/matching/matchRequestUrl'\n\nexport type HttpRequestHandler = <\n Params extends PathParams = PathParams,\n RequestBodyType extends DefaultBodyType = DefaultBodyType,\n // Response body type MUST be undefined by default.\n // This is how we can distinguish between a handler that\n // returns plain \"Response\" and the one returning \"HttpResponse\"\n // to enforce a stricter response body type.\n ResponseBodyType extends DefaultBodyType = undefined,\n>(\n predicate: HttpRequestPredicate,\n resolver: HttpResponseResolver,\n options?: RequestHandlerOptions,\n) => HttpHandler\n\nexport type HttpResponseResolver<\n Params extends PathParams = PathParams,\n RequestBodyType extends DefaultBodyType = DefaultBodyType,\n ResponseBodyType extends DefaultBodyType = DefaultBodyType,\n> = ResponseResolver<\n HttpRequestResolverExtras,\n RequestBodyType,\n ResponseBodyType\n>\n\nfunction createHttpHandler(\n method: Method,\n): HttpRequestHandler {\n return (predicate, resolver, options = {}) => {\n return new HttpHandler(method, predicate, resolver, options)\n }\n}\n\n/**\n * A namespace to intercept and mock HTTP requests.\n *\n * @example\n * http.get('/user', resolver)\n * http.post('/post/:id', resolver)\n *\n * @see {@link https://mswjs.io/docs/api/http `http` API reference}\n */\nexport const http = {\n all: createHttpHandler(/.+/),\n head: createHttpHandler(HttpMethods.HEAD),\n get: createHttpHandler(HttpMethods.GET),\n post: createHttpHandler(HttpMethods.POST),\n put: createHttpHandler(HttpMethods.PUT),\n delete: createHttpHandler(HttpMethods.DELETE),\n patch: createHttpHandler(HttpMethods.PATCH),\n options: createHttpHandler(HttpMethods.OPTIONS),\n}\n"],"mappings":"AAAA;AAAA,OAIO;AACP;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AA2BP,SAAS,kBACP,QACoB;AACpB,SAAO,CAAC,WAAW,UAAU,UAAU,CAAC,MAAM;AAC5C,WAAO,IAAI,YAAY,QAAQ,WAAW,UAAU,OAAO;AAAA,EAC7D;AACF;AAWO,MAAM,OAAO;AAAA,EAClB,KAAK,kBAAkB,IAAI;AAAA,EAC3B,MAAM,kBAAkB,YAAY,IAAI;AAAA,EACxC,KAAK,kBAAkB,YAAY,GAAG;AAAA,EACtC,MAAM,kBAAkB,YAAY,IAAI;AAAA,EACxC,KAAK,kBAAkB,YAAY,GAAG;AAAA,EACtC,QAAQ,kBAAkB,YAAY,MAAM;AAAA,EAC5C,OAAO,kBAAkB,YAAY,KAAK;AAAA,EAC1C,SAAS,kBAAkB,YAAY,OAAO;AAChD;","names":[]} \ No newline at end of file diff --git a/node_modules/msw/lib/core/index.d.mts b/node_modules/msw/lib/core/index.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..20f7d2710eb208262418098f52bc477f5da3cfc2 --- /dev/null +++ b/node_modules/msw/lib/core/index.d.mts @@ -0,0 +1,27 @@ +export { SetupApi } from './experimental/setup-api.mjs'; +export { A as AsyncResponseResolverReturnType, D as DefaultBodyType, d as DefaultRequestMultipartBody, l as GraphQLCustomPredicate, G as GraphQLHandler, j as GraphQLJsonRequestBody, k as GraphQLOperationType, f as GraphQLQuery, h as GraphQLRequestBody, i as GraphQLResponseBody, g as GraphQLVariables, H as HttpResponse, n as HttpResponseInit, J as JsonBodyType, P as ParsedGraphQLRequest, R as RequestHandler, c as RequestHandlerOptions, m as ResponseResolutionContext, a as ResponseResolver, e as ResponseResolverInfo, b as ResponseResolverReturnType, S as StrictRequest, o as StrictResponse } from './HttpResponse-CQwYpuKo.mjs'; +export { HttpRequestHandler, HttpResponseResolver, http } from './http.mjs'; +export { HttpCustomPredicate, HttpHandler, HttpHandlerInfo, HttpHandlerMethod, HttpMethods, HttpRequestParsedResult, HttpRequestResolverExtras, RequestQuery } from './handlers/HttpHandler.mjs'; +export { GraphQLLinkHandlers, GraphQLOperationHandler, GraphQLRequestHandler, GraphQLResponseResolver, graphql } from './graphql.mjs'; +export { WebSocketEventListener, WebSocketLink, ws } from './ws.mjs'; +export { WebSocketHandler, WebSocketHandlerConnection, WebSocketHandlerEventMap } from './handlers/WebSocketHandler.mjs'; +export { ServerSentEventMessage, ServerSentEventRequestHandler, ServerSentEventResolver, ServerSentEventResolverExtras, sse } from './sse.mjs'; +export { Match, Path, PathParams, matchRequestUrl } from './utils/matching/matchRequestUrl.mjs'; +export { HandleRequestOptions, handleRequest } from './utils/handleRequest.mjs'; +export { UnhandledRequestCallback, UnhandledRequestStrategy, onUnhandledRequest } from './utils/request/onUnhandledRequest.mjs'; +export { getResponse } from './getResponse.mjs'; +export { cleanUrl } from './utils/url/cleanUrl.mjs'; +export { AnyHandler } from './experimental/handlers-controller.mjs'; +export { LifeCycleEventsMap, SharedOptions } from './sharedOptions.mjs'; +export { DelayMode, delay } from './delay.mjs'; +export { bypass } from './bypass.mjs'; +export { passthrough } from './passthrough.mjs'; +export { isCommonAssetRequest } from './isCommonAssetRequest.mjs'; +export { WebSocketData } from '@mswjs/interceptors/WebSocket'; +import 'rettime'; +import './utils/internal/Disposable.mjs'; +import '@mswjs/interceptors'; +import './utils/internal/isIterable.mjs'; +import './typeUtils.mjs'; +import 'graphql'; +import 'strict-event-emitter'; diff --git a/node_modules/msw/lib/core/index.d.ts b/node_modules/msw/lib/core/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2826f7325b02afd1f283f80aabcf4f58d58ff7c2 --- /dev/null +++ b/node_modules/msw/lib/core/index.d.ts @@ -0,0 +1,27 @@ +export { SetupApi } from './experimental/setup-api.js'; +export { A as AsyncResponseResolverReturnType, D as DefaultBodyType, d as DefaultRequestMultipartBody, l as GraphQLCustomPredicate, G as GraphQLHandler, j as GraphQLJsonRequestBody, k as GraphQLOperationType, f as GraphQLQuery, h as GraphQLRequestBody, i as GraphQLResponseBody, g as GraphQLVariables, H as HttpResponse, n as HttpResponseInit, J as JsonBodyType, P as ParsedGraphQLRequest, R as RequestHandler, c as RequestHandlerOptions, m as ResponseResolutionContext, a as ResponseResolver, e as ResponseResolverInfo, b as ResponseResolverReturnType, S as StrictRequest, o as StrictResponse } from './HttpResponse-BFS34nkx.js'; +export { HttpRequestHandler, HttpResponseResolver, http } from './http.js'; +export { HttpCustomPredicate, HttpHandler, HttpHandlerInfo, HttpHandlerMethod, HttpMethods, HttpRequestParsedResult, HttpRequestResolverExtras, RequestQuery } from './handlers/HttpHandler.js'; +export { GraphQLLinkHandlers, GraphQLOperationHandler, GraphQLRequestHandler, GraphQLResponseResolver, graphql } from './graphql.js'; +export { WebSocketEventListener, WebSocketLink, ws } from './ws.js'; +export { WebSocketHandler, WebSocketHandlerConnection, WebSocketHandlerEventMap } from './handlers/WebSocketHandler.js'; +export { ServerSentEventMessage, ServerSentEventRequestHandler, ServerSentEventResolver, ServerSentEventResolverExtras, sse } from './sse.js'; +export { Match, Path, PathParams, matchRequestUrl } from './utils/matching/matchRequestUrl.js'; +export { HandleRequestOptions, handleRequest } from './utils/handleRequest.js'; +export { UnhandledRequestCallback, UnhandledRequestStrategy, onUnhandledRequest } from './utils/request/onUnhandledRequest.js'; +export { getResponse } from './getResponse.js'; +export { cleanUrl } from './utils/url/cleanUrl.js'; +export { AnyHandler } from './experimental/handlers-controller.js'; +export { LifeCycleEventsMap, SharedOptions } from './sharedOptions.js'; +export { DelayMode, delay } from './delay.js'; +export { bypass } from './bypass.js'; +export { passthrough } from './passthrough.js'; +export { isCommonAssetRequest } from './isCommonAssetRequest.js'; +export { WebSocketData } from '@mswjs/interceptors/WebSocket'; +import 'rettime'; +import './utils/internal/Disposable.js'; +import '@mswjs/interceptors'; +import './utils/internal/isIterable.js'; +import './typeUtils.js'; +import 'graphql'; +import 'strict-event-emitter'; diff --git a/node_modules/msw/lib/core/index.js b/node_modules/msw/lib/core/index.js new file mode 100644 index 0000000000000000000000000000000000000000..96a923947dd390a0a71a930e84e643694fe88b61 --- /dev/null +++ b/node_modules/msw/lib/core/index.js @@ -0,0 +1,64 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var index_exports = {}; +__export(index_exports, { + GraphQLHandler: () => import_GraphQLHandler.GraphQLHandler, + HttpHandler: () => import_HttpHandler.HttpHandler, + HttpMethods: () => import_HttpHandler.HttpMethods, + HttpResponse: () => import_HttpResponse.HttpResponse, + RequestHandler: () => import_RequestHandler.RequestHandler, + SetupApi: () => import_setup_api.SetupApi, + WebSocketHandler: () => import_WebSocketHandler.WebSocketHandler, + bypass: () => import_bypass.bypass, + cleanUrl: () => import_cleanUrl.cleanUrl, + delay: () => import_delay.delay, + getResponse: () => import_getResponse.getResponse, + graphql: () => import_graphql.graphql, + handleRequest: () => import_handleRequest.handleRequest, + http: () => import_http.http, + isCommonAssetRequest: () => import_isCommonAssetRequest.isCommonAssetRequest, + matchRequestUrl: () => import_matchRequestUrl.matchRequestUrl, + onUnhandledRequest: () => import_onUnhandledRequest.onUnhandledRequest, + passthrough: () => import_passthrough.passthrough, + sse: () => import_sse.sse, + ws: () => import_ws.ws +}); +module.exports = __toCommonJS(index_exports); +var import_checkGlobals = require("./utils/internal/checkGlobals"); +var import_setup_api = require("./experimental/setup-api"); +var import_RequestHandler = require("./handlers/RequestHandler"); +var import_http = require("./http"); +var import_HttpHandler = require("./handlers/HttpHandler"); +var import_graphql = require("./graphql"); +var import_GraphQLHandler = require("./handlers/GraphQLHandler"); +var import_ws = require("./ws"); +var import_WebSocketHandler = require("./handlers/WebSocketHandler"); +var import_sse = require("./sse"); +var import_matchRequestUrl = require("./utils/matching/matchRequestUrl"); +var import_handleRequest = require("./utils/handleRequest"); +var import_onUnhandledRequest = require("./utils/request/onUnhandledRequest"); +var import_getResponse = require("./getResponse"); +var import_cleanUrl = require("./utils/url/cleanUrl"); +var import_HttpResponse = require("./HttpResponse"); +var import_delay = require("./delay"); +var import_bypass = require("./bypass"); +var import_passthrough = require("./passthrough"); +var import_isCommonAssetRequest = require("./isCommonAssetRequest"); +(0, import_checkGlobals.checkGlobals)(); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/msw/lib/core/index.js.map b/node_modules/msw/lib/core/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..87a8eb80b6ba94d75fb38a2e1ab1969df7dd7b97 --- /dev/null +++ b/node_modules/msw/lib/core/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/core/index.ts"],"sourcesContent":["import { checkGlobals } from './utils/internal/checkGlobals'\n\nexport { SetupApi } from './experimental/setup-api'\n\n/* HTTP handlers */\nexport { RequestHandler } from './handlers/RequestHandler'\nexport { http } from './http'\nexport { HttpHandler, HttpMethods } from './handlers/HttpHandler'\nexport { graphql } from './graphql'\nexport { GraphQLHandler } from './handlers/GraphQLHandler'\n\n/* WebSocket handler */\nexport { ws, type WebSocketLink } from './ws'\nexport {\n WebSocketHandler,\n type WebSocketHandlerEventMap,\n type WebSocketHandlerConnection,\n} from './handlers/WebSocketHandler'\n\n/* Server-Sent Events */\nexport {\n sse,\n type ServerSentEventRequestHandler,\n type ServerSentEventResolver,\n type ServerSentEventResolverExtras,\n type ServerSentEventMessage,\n} from './sse'\n\n/* Utils */\nexport { matchRequestUrl } from './utils/matching/matchRequestUrl'\nexport { handleRequest, type HandleRequestOptions } from './utils/handleRequest'\nexport {\n onUnhandledRequest,\n type UnhandledRequestStrategy,\n type UnhandledRequestCallback,\n} from './utils/request/onUnhandledRequest'\nexport { getResponse } from './getResponse'\nexport { cleanUrl } from './utils/url/cleanUrl'\n\n/**\n * Type definitions.\n */\n\nexport type { AnyHandler } from './experimental/handlers-controller'\n\nexport type { SharedOptions, LifeCycleEventsMap } from './sharedOptions'\n\nexport type {\n ResponseResolver,\n ResponseResolverReturnType,\n AsyncResponseResolverReturnType,\n RequestHandlerOptions,\n DefaultBodyType,\n DefaultRequestMultipartBody,\n JsonBodyType,\n ResponseResolverInfo,\n} from './handlers/RequestHandler'\n\nexport type {\n RequestQuery,\n HttpRequestParsedResult,\n HttpHandlerInfo,\n HttpRequestResolverExtras,\n HttpHandlerMethod,\n HttpCustomPredicate,\n} from './handlers/HttpHandler'\nexport type { HttpRequestHandler, HttpResponseResolver } from './http'\n\nexport type {\n GraphQLQuery,\n GraphQLVariables,\n GraphQLRequestBody,\n GraphQLResponseBody,\n GraphQLJsonRequestBody,\n GraphQLOperationType,\n GraphQLCustomPredicate,\n} from './handlers/GraphQLHandler'\nexport type {\n GraphQLRequestHandler,\n GraphQLOperationHandler,\n GraphQLResponseResolver,\n GraphQLLinkHandlers,\n} from './graphql'\n\nexport type { WebSocketData, WebSocketEventListener } from './ws'\n\nexport type { Path, PathParams, Match } from './utils/matching/matchRequestUrl'\nexport type { ParsedGraphQLRequest } from './utils/internal/parseGraphQLRequest'\nexport type { ResponseResolutionContext } from './utils/executeHandlers'\n\nexport {\n HttpResponse,\n type HttpResponseInit,\n type StrictRequest,\n type StrictResponse,\n} from './HttpResponse'\nexport { delay, type DelayMode } from './delay'\nexport { bypass } from './bypass'\nexport { passthrough } from './passthrough'\nexport { isCommonAssetRequest } from './isCommonAssetRequest'\n\n// Validate environmental globals before executing any code.\n// This ensures that the library gives user-friendly errors\n// when ran in the environments that require additional polyfills\n// from the end user.\ncheckGlobals()\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,0BAA6B;AAE7B,uBAAyB;AAGzB,4BAA+B;AAC/B,kBAAqB;AACrB,yBAAyC;AACzC,qBAAwB;AACxB,4BAA+B;AAG/B,gBAAuC;AACvC,8BAIO;AAGP,iBAMO;AAGP,6BAAgC;AAChC,2BAAyD;AACzD,gCAIO;AACP,yBAA4B;AAC5B,sBAAyB;AAqDzB,0BAKO;AACP,mBAAsC;AACtC,oBAAuB;AACvB,yBAA4B;AAC5B,kCAAqC;AAAA,IAMrC,kCAAa;","names":[]} \ No newline at end of file diff --git a/node_modules/msw/lib/core/index.mjs b/node_modules/msw/lib/core/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..df5368076ce351e4655d2ff0f66bba5c4d59f2a5 --- /dev/null +++ b/node_modules/msw/lib/core/index.mjs @@ -0,0 +1,52 @@ +import { checkGlobals } from './utils/internal/checkGlobals.mjs'; +import { SetupApi } from './experimental/setup-api.mjs'; +import { RequestHandler } from './handlers/RequestHandler.mjs'; +import { http } from './http.mjs'; +import { HttpHandler, HttpMethods } from './handlers/HttpHandler.mjs'; +import { graphql } from './graphql.mjs'; +import { GraphQLHandler } from './handlers/GraphQLHandler.mjs'; +import { ws } from './ws.mjs'; +import { + WebSocketHandler +} from './handlers/WebSocketHandler.mjs'; +import { + sse +} from './sse.mjs'; +import { matchRequestUrl } from './utils/matching/matchRequestUrl.mjs'; +import { handleRequest } from './utils/handleRequest.mjs'; +import { + onUnhandledRequest +} from './utils/request/onUnhandledRequest.mjs'; +import { getResponse } from './getResponse.mjs'; +import { cleanUrl } from './utils/url/cleanUrl.mjs'; +import { + HttpResponse +} from './HttpResponse.mjs'; +import { delay } from './delay.mjs'; +import { bypass } from './bypass.mjs'; +import { passthrough } from './passthrough.mjs'; +import { isCommonAssetRequest } from './isCommonAssetRequest.mjs'; +checkGlobals(); +export { + GraphQLHandler, + HttpHandler, + HttpMethods, + HttpResponse, + RequestHandler, + SetupApi, + WebSocketHandler, + bypass, + cleanUrl, + delay, + getResponse, + graphql, + handleRequest, + http, + isCommonAssetRequest, + matchRequestUrl, + onUnhandledRequest, + passthrough, + sse, + ws +}; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/node_modules/msw/lib/core/index.mjs.map b/node_modules/msw/lib/core/index.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..3ce9ae558de3b19a965c99d16f7b23476e2ea717 --- /dev/null +++ b/node_modules/msw/lib/core/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/core/index.ts"],"sourcesContent":["import { checkGlobals } from './utils/internal/checkGlobals'\n\nexport { SetupApi } from './experimental/setup-api'\n\n/* HTTP handlers */\nexport { RequestHandler } from './handlers/RequestHandler'\nexport { http } from './http'\nexport { HttpHandler, HttpMethods } from './handlers/HttpHandler'\nexport { graphql } from './graphql'\nexport { GraphQLHandler } from './handlers/GraphQLHandler'\n\n/* WebSocket handler */\nexport { ws, type WebSocketLink } from './ws'\nexport {\n WebSocketHandler,\n type WebSocketHandlerEventMap,\n type WebSocketHandlerConnection,\n} from './handlers/WebSocketHandler'\n\n/* Server-Sent Events */\nexport {\n sse,\n type ServerSentEventRequestHandler,\n type ServerSentEventResolver,\n type ServerSentEventResolverExtras,\n type ServerSentEventMessage,\n} from './sse'\n\n/* Utils */\nexport { matchRequestUrl } from './utils/matching/matchRequestUrl'\nexport { handleRequest, type HandleRequestOptions } from './utils/handleRequest'\nexport {\n onUnhandledRequest,\n type UnhandledRequestStrategy,\n type UnhandledRequestCallback,\n} from './utils/request/onUnhandledRequest'\nexport { getResponse } from './getResponse'\nexport { cleanUrl } from './utils/url/cleanUrl'\n\n/**\n * Type definitions.\n */\n\nexport type { AnyHandler } from './experimental/handlers-controller'\n\nexport type { SharedOptions, LifeCycleEventsMap } from './sharedOptions'\n\nexport type {\n ResponseResolver,\n ResponseResolverReturnType,\n AsyncResponseResolverReturnType,\n RequestHandlerOptions,\n DefaultBodyType,\n DefaultRequestMultipartBody,\n JsonBodyType,\n ResponseResolverInfo,\n} from './handlers/RequestHandler'\n\nexport type {\n RequestQuery,\n HttpRequestParsedResult,\n HttpHandlerInfo,\n HttpRequestResolverExtras,\n HttpHandlerMethod,\n HttpCustomPredicate,\n} from './handlers/HttpHandler'\nexport type { HttpRequestHandler, HttpResponseResolver } from './http'\n\nexport type {\n GraphQLQuery,\n GraphQLVariables,\n GraphQLRequestBody,\n GraphQLResponseBody,\n GraphQLJsonRequestBody,\n GraphQLOperationType,\n GraphQLCustomPredicate,\n} from './handlers/GraphQLHandler'\nexport type {\n GraphQLRequestHandler,\n GraphQLOperationHandler,\n GraphQLResponseResolver,\n GraphQLLinkHandlers,\n} from './graphql'\n\nexport type { WebSocketData, WebSocketEventListener } from './ws'\n\nexport type { Path, PathParams, Match } from './utils/matching/matchRequestUrl'\nexport type { ParsedGraphQLRequest } from './utils/internal/parseGraphQLRequest'\nexport type { ResponseResolutionContext } from './utils/executeHandlers'\n\nexport {\n HttpResponse,\n type HttpResponseInit,\n type StrictRequest,\n type StrictResponse,\n} from './HttpResponse'\nexport { delay, type DelayMode } from './delay'\nexport { bypass } from './bypass'\nexport { passthrough } from './passthrough'\nexport { isCommonAssetRequest } from './isCommonAssetRequest'\n\n// Validate environmental globals before executing any code.\n// This ensures that the library gives user-friendly errors\n// when ran in the environments that require additional polyfills\n// from the end user.\ncheckGlobals()\n"],"mappings":"AAAA,SAAS,oBAAoB;AAE7B,SAAS,gBAAgB;AAGzB,SAAS,sBAAsB;AAC/B,SAAS,YAAY;AACrB,SAAS,aAAa,mBAAmB;AACzC,SAAS,eAAe;AACxB,SAAS,sBAAsB;AAG/B,SAAS,UAA8B;AACvC;AAAA,EACE;AAAA,OAGK;AAGP;AAAA,EACE;AAAA,OAKK;AAGP,SAAS,uBAAuB;AAChC,SAAS,qBAAgD;AACzD;AAAA,EACE;AAAA,OAGK;AACP,SAAS,mBAAmB;AAC5B,SAAS,gBAAgB;AAqDzB;AAAA,EACE;AAAA,OAIK;AACP,SAAS,aAA6B;AACtC,SAAS,cAAc;AACvB,SAAS,mBAAmB;AAC5B,SAAS,4BAA4B;AAMrC,aAAa;","names":[]} \ No newline at end of file
    + + Get professional support for this package with a Tidelift subscription + +
    + + Tidelift helps make open source sustainable for maintainers while giving companies
    assurances about security, maintenance, and licensing for their dependencies. +
    +