Project Init

This commit is contained in:
Muluhabt
2026-05-29 15:23:46 +03:00
commit 2fbc557aac
67387 changed files with 6063341 additions and 0 deletions

BIN
node_modules/@rspack/.DS_Store generated vendored Normal file

Binary file not shown.

21
node_modules/@rspack/binding-darwin-arm64/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2022-present Bytedance Inc and its affiliates.
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.

17
node_modules/@rspack/binding-darwin-arm64/README.md generated vendored Normal file
View File

@@ -0,0 +1,17 @@
<picture>
<img alt="Rspack Banner" src="https://assets.rspack.rs/rspack/rspack-banner.png">
</picture>
# @rspack/binding-darwin-arm64
Private node binding crate for rspack.
This package does *NOT* follow [semantic versioning](https://semver.org/).
## Documentation
See [https://rspack.rs](https://rspack.rs) for details.
## License
Rspack is [MIT licensed](https://github.com/web-infra-dev/rspack/blob/main/LICENSE).

26
node_modules/@rspack/binding-darwin-arm64/package.json generated vendored Normal file
View File

@@ -0,0 +1,26 @@
{
"name": "@rspack/binding-darwin-arm64",
"version": "1.6.8",
"license": "MIT",
"description": "Node binding for rspack",
"main": "rspack.darwin-arm64.node",
"homepage": "https://rspack.rs",
"bugs": "https://github.com/web-infra-dev/rspack/issues",
"repository": {
"type": "git",
"url": "https://github.com/web-infra-dev/rspack",
"directory": "packages/rspack"
},
"publishConfig": {
"access": "public"
},
"files": [
"rspack.darwin-arm64.node"
],
"os": [
"darwin"
],
"cpu": [
"arm64"
]
}

Binary file not shown.

22
node_modules/@rspack/binding/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,22 @@
MIT License
Copyright (c) 2022-present Bytedance, Inc. and its affiliates.
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.

17
node_modules/@rspack/binding/README.md generated vendored Normal file
View File

@@ -0,0 +1,17 @@
<picture>
<img alt="Rspack Banner" src="https://assets.rspack.rs/rspack/rspack-banner.png">
</picture>
# @rspack/binding
Private node binding crate for rspack.
> Rspack's internal package, don't use it directly in your project, This package does _NOT_ follow [semantic versioning](https://semver.org/).
## Documentation
See [https://rspack.rs](https://rspack.rs) for details.
## License
Rspack is [MIT licensed](https://github.com/web-infra-dev/rspack/blob/main/LICENSE).

8
node_modules/@rspack/binding/binding.d.ts generated vendored Normal file
View File

@@ -0,0 +1,8 @@
/**
* We manually create binding.d.ts and re-export everything of the dts generated by napi to fix the cjs-esm interop
*/
import * as binding from "./napi-binding";
export * from "./napi-binding"
export default binding;

406
node_modules/@rspack/binding/binding.js generated vendored Normal file
View File

@@ -0,0 +1,406 @@
// prettier-ignore
/* eslint-disable */
// @ts-nocheck
/* auto-generated by NAPI-RS */
const { createRequire } = require('node:module')
require = createRequire(__filename)
const { readFileSync } = require('node:fs')
let nativeBinding = null
const loadErrors = []
const isMusl = () => {
let musl = false
if (process.platform === 'linux') {
musl = isMuslFromFilesystem()
if (musl === null) {
musl = isMuslFromReport()
}
if (musl === null) {
musl = isMuslFromChildProcess()
}
}
return musl
}
const isFileMusl = (f) => f.includes('libc.musl-') || f.includes('ld-musl-')
const isMuslFromFilesystem = () => {
try {
return readFileSync('/usr/bin/ldd', 'utf-8').includes('musl')
} catch {
return null
}
}
const isMuslFromReport = () => {
let report = null
if (typeof process.report?.getReport === 'function') {
process.report.excludeNetwork = true
report = process.report.getReport()
}
if (!report) {
return null
}
if (report.header && report.header.glibcVersionRuntime) {
return false
}
if (Array.isArray(report.sharedObjects)) {
if (report.sharedObjects.some(isFileMusl)) {
return true
}
}
return false
}
const isMuslFromChildProcess = () => {
try {
return require('child_process').execSync('ldd --version', { encoding: 'utf8' }).includes('musl')
} catch (e) {
// If we reach this case, we don't know if the system is musl or not, so is better to just fallback to false
return false
}
}
function requireNative() {
if (process.env.NAPI_RS_NATIVE_LIBRARY_PATH) {
try {
return require(process.env.NAPI_RS_NATIVE_LIBRARY_PATH);
} catch (err) {
loadErrors.push(err)
}
} else if (process.platform === 'android') {
if (process.arch === 'arm64') {
try {
return require('./rspack.android-arm64.node')
} catch (e) {
loadErrors.push(e)
}
try {
return require('@rspack/binding-android-arm64')
} catch (e) {
loadErrors.push(e)
}
} else if (process.arch === 'arm') {
try {
return require('./rspack.android-arm-eabi.node')
} catch (e) {
loadErrors.push(e)
}
try {
return require('@rspack/binding-android-arm-eabi')
} catch (e) {
loadErrors.push(e)
}
} else {
loadErrors.push(new Error(`Unsupported architecture on Android ${process.arch}`))
}
} else if (process.platform === 'win32') {
if (process.arch === 'x64') {
try {
return require('./rspack.win32-x64-msvc.node')
} catch (e) {
loadErrors.push(e)
}
try {
return require('@rspack/binding-win32-x64-msvc')
} catch (e) {
loadErrors.push(e)
}
} else if (process.arch === 'ia32') {
try {
return require('./rspack.win32-ia32-msvc.node')
} catch (e) {
loadErrors.push(e)
}
try {
return require('@rspack/binding-win32-ia32-msvc')
} catch (e) {
loadErrors.push(e)
}
} else if (process.arch === 'arm64') {
try {
return require('./rspack.win32-arm64-msvc.node')
} catch (e) {
loadErrors.push(e)
}
try {
return require('@rspack/binding-win32-arm64-msvc')
} catch (e) {
loadErrors.push(e)
}
} else {
loadErrors.push(new Error(`Unsupported architecture on Windows: ${process.arch}`))
}
} else if (process.platform === 'darwin') {
try {
return require('./rspack.darwin-universal.node')
} catch (e) {
loadErrors.push(e)
}
try {
return require('@rspack/binding-darwin-universal')
} catch (e) {
loadErrors.push(e)
}
if (process.arch === 'x64') {
try {
return require('./rspack.darwin-x64.node')
} catch (e) {
loadErrors.push(e)
}
try {
return require('@rspack/binding-darwin-x64')
} catch (e) {
loadErrors.push(e)
}
} else if (process.arch === 'arm64') {
try {
return require('./rspack.darwin-arm64.node')
} catch (e) {
loadErrors.push(e)
}
try {
return require('@rspack/binding-darwin-arm64')
} catch (e) {
loadErrors.push(e)
}
} else {
loadErrors.push(new Error(`Unsupported architecture on macOS: ${process.arch}`))
}
} else if (process.platform === 'freebsd') {
if (process.arch === 'x64') {
try {
return require('./rspack.freebsd-x64.node')
} catch (e) {
loadErrors.push(e)
}
try {
return require('@rspack/binding-freebsd-x64')
} catch (e) {
loadErrors.push(e)
}
} else if (process.arch === 'arm64') {
try {
return require('./rspack.freebsd-arm64.node')
} catch (e) {
loadErrors.push(e)
}
try {
return require('@rspack/binding-freebsd-arm64')
} catch (e) {
loadErrors.push(e)
}
} else {
loadErrors.push(new Error(`Unsupported architecture on FreeBSD: ${process.arch}`))
}
} else if (process.platform === 'linux') {
if (process.arch === 'x64') {
if (isMusl()) {
try {
return require('./rspack.linux-x64-musl.node')
} catch (e) {
loadErrors.push(e)
}
try {
return require('@rspack/binding-linux-x64-musl')
} catch (e) {
loadErrors.push(e)
}
} else {
try {
return require('./rspack.linux-x64-gnu.node')
} catch (e) {
loadErrors.push(e)
}
try {
return require('@rspack/binding-linux-x64-gnu')
} catch (e) {
loadErrors.push(e)
}
}
} else if (process.arch === 'arm64') {
if (isMusl()) {
try {
return require('./rspack.linux-arm64-musl.node')
} catch (e) {
loadErrors.push(e)
}
try {
return require('@rspack/binding-linux-arm64-musl')
} catch (e) {
loadErrors.push(e)
}
} else {
try {
return require('./rspack.linux-arm64-gnu.node')
} catch (e) {
loadErrors.push(e)
}
try {
return require('@rspack/binding-linux-arm64-gnu')
} catch (e) {
loadErrors.push(e)
}
}
} else if (process.arch === 'arm') {
if (isMusl()) {
try {
return require('./rspack.linux-arm-musleabihf.node')
} catch (e) {
loadErrors.push(e)
}
try {
return require('@rspack/binding-linux-arm-musleabihf')
} catch (e) {
loadErrors.push(e)
}
} else {
try {
return require('./rspack.linux-arm-gnueabihf.node')
} catch (e) {
loadErrors.push(e)
}
try {
return require('@rspack/binding-linux-arm-gnueabihf')
} catch (e) {
loadErrors.push(e)
}
}
} else if (process.arch === 'riscv64') {
if (isMusl()) {
try {
return require('./rspack.linux-riscv64-musl.node')
} catch (e) {
loadErrors.push(e)
}
try {
return require('@rspack/binding-linux-riscv64-musl')
} catch (e) {
loadErrors.push(e)
}
} else {
try {
return require('./rspack.linux-riscv64-gnu.node')
} catch (e) {
loadErrors.push(e)
}
try {
return require('@rspack/binding-linux-riscv64-gnu')
} catch (e) {
loadErrors.push(e)
}
}
} else if (process.arch === 'ppc64') {
try {
return require('./rspack.linux-ppc64-gnu.node')
} catch (e) {
loadErrors.push(e)
}
try {
return require('@rspack/binding-linux-ppc64-gnu')
} catch (e) {
loadErrors.push(e)
}
} else if (process.arch === 's390x') {
try {
return require('./rspack.linux-s390x-gnu.node')
} catch (e) {
loadErrors.push(e)
}
try {
return require('@rspack/binding-linux-s390x-gnu')
} catch (e) {
loadErrors.push(e)
}
} else {
loadErrors.push(new Error(`Unsupported architecture on Linux: ${process.arch}`))
}
} else if (process.platform === 'openharmony') {
if (process.arch === 'arm64') {
try {
return require('./rspack.linux-arm64-ohos.node')
} catch (e) {
loadErrors.push(e)
}
try {
return require('@rspack/binding-linux-arm64-ohos')
} catch (e) {
loadErrors.push(e)
}
} else if (process.arch === 'x64') {
try {
return require('./rspack.linux-x64-ohos.node')
} catch (e) {
loadErrors.push(e)
}
try {
return require('@rspack/binding-linux-x64-ohos')
} catch (e) {
loadErrors.push(e)
}
} else if (process.arch === 'arm') {
try {
return require('./rspack.linux-arm-ohos.node')
} catch (e) {
loadErrors.push(e)
}
try {
return require('@rspack/binding-linux-arm-ohos')
} catch (e) {
loadErrors.push(e)
}
} else {
loadErrors.push(new Error(`Unsupported architecture on OpenHarmony: ${process.arch}`))
}
} else {
loadErrors.push(new Error(`Unsupported OS: ${process.platform}, architecture: ${process.arch}`))
}
}
nativeBinding = requireNative()
if (!nativeBinding || process.env.NAPI_RS_FORCE_WASI) {
try {
nativeBinding = require('./rspack.wasi.cjs')
} catch (err) {
if (process.env.NAPI_RS_FORCE_WASI) {
loadErrors.push(err)
}
}
if (!nativeBinding) {
try {
nativeBinding = require('@rspack/binding-wasm32-wasi')
} catch (err) {
if (process.env.NAPI_RS_FORCE_WASI) {
loadErrors.push(err)
}
}
}
}
if (!nativeBinding && globalThis.process?.versions?.["webcontainer"]) {
try {
nativeBinding = require("./webcontainer-fallback.cjs")
} catch (err) {
if (process.env.NAPI_RS_FORCE_WASI) {
loadErrors.push(err)
}
}
}
if (!nativeBinding) {
if (loadErrors.length > 0) {
throw new Error(
`Cannot find native binding. ` +
`npm has a bug related to optional dependencies (https://github.com/npm/cli/issues/4828). ` +
'Please try `npm i` again after removing both package-lock.json and node_modules directory.' +
`\n\n${loadErrors.map((e) => e.message).join('\n')}`,
{ cause: loadErrors }
)
}
throw new Error(`Failed to load native binding`)
}
module.exports.default = module.exports = nativeBinding

3139
node_modules/@rspack/binding/napi-binding.d.ts generated vendored Normal file

File diff suppressed because it is too large Load Diff

78
node_modules/@rspack/binding/package.json generated vendored Normal file
View File

@@ -0,0 +1,78 @@
{
"name": "@rspack/binding",
"version": "1.6.8",
"license": "MIT",
"description": "Node binding for rspack",
"main": "binding.js",
"types": "binding.d.ts",
"publishConfig": {
"access": "public",
"provenance": true
},
"files": [
"binding.js",
"binding.d.ts",
"napi-binding.d.ts",
"webcontainer-fallback.cjs"
],
"homepage": "https://rspack.rs",
"bugs": "https://github.com/web-infra-dev/rspack/issues",
"repository": "web-infra-dev/rspack",
"devDependencies": {
"@napi-rs/cli": "3.0.4",
"@napi-rs/wasm-runtime": "1.0.7",
"emnapi": "^1.7.1",
"typescript": "^5.9.3"
},
"napi": {
"binaryName": "rspack",
"packageName": "@rspack/binding",
"targets": [
"x86_64-apple-darwin",
"x86_64-pc-windows-msvc",
"x86_64-unknown-linux-gnu",
"x86_64-unknown-linux-musl",
"x86_64-unknown-freebsd",
"i686-pc-windows-msvc",
"armv7-unknown-linux-gnueabihf",
"aarch64-unknown-linux-gnu",
"aarch64-apple-darwin",
"aarch64-unknown-linux-musl",
"aarch64-pc-windows-msvc",
"wasm32-wasip1-threads"
],
"wasm": {
"initialMemory": 16384,
"browser": {
"fs": true,
"asyncInit": true,
"buffer": true
}
}
},
"optionalDependencies": {
"@rspack/binding-darwin-arm64": "1.6.8",
"@rspack/binding-win32-arm64-msvc": "1.6.8",
"@rspack/binding-linux-arm64-gnu": "1.6.8",
"@rspack/binding-linux-arm64-musl": "1.6.8",
"@rspack/binding-wasm32-wasi": "1.6.8",
"@rspack/binding-darwin-x64": "1.6.8",
"@rspack/binding-win32-ia32-msvc": "1.6.8",
"@rspack/binding-linux-x64-musl": "1.6.8",
"@rspack/binding-linux-x64-gnu": "1.6.8",
"@rspack/binding-win32-x64-msvc": "1.6.8"
},
"scripts": {
"build:dev": "node scripts/build.js",
"build:debug": "node scripts/build.js --profile release-debug",
"build:ci": "node scripts/build.js --profile ci",
"build:profiling": "node scripts/build.js --profile profiling",
"build:release": "node scripts/build.js --profile release",
"build:dev:wasm": "DISABLE_PLUGIN=1 RUST_TARGET=wasm32-wasip1-threads node scripts/build.js",
"build:release:wasm": "DISABLE_PLUGIN=1 RUST_TARGET=wasm32-wasip1-threads node scripts/build.js --profile release-wasi",
"build:dev:browser": "DISABLE_PLUGIN=1 RUST_TARGET=wasm32-wasip1-threads RSPACK_TARGET_BROWSER=1 node scripts/build.js",
"build:release:browser": "DISABLE_PLUGIN=1 RUST_TARGET=wasm32-wasip1-threads RSPACK_TARGET_BROWSER=1 node scripts/build.js --profile release-wasi",
"move-binding": "node scripts/move-binding",
"test": "tsc -p tsconfig.type-test.json"
}
}

23
node_modules/@rspack/binding/webcontainer-fallback.cjs generated vendored Normal file
View File

@@ -0,0 +1,23 @@
const fs = require('node:fs');
const path = require('node:path');
const childProcess = require('node:child_process');
const pkg = JSON.parse(
fs.readFileSync(path.join(__dirname, 'package.json'), 'utf-8'),
);
const version = pkg.version;
const baseDir = `/tmp/rspack-${version}`;
const bindingEntry = `${baseDir}/node_modules/${pkg.name}-wasm32-wasi/rspack.wasi.cjs`;
if (!fs.existsSync(bindingEntry)) {
fs.rmSync(baseDir, { recursive: true, force: true });
fs.mkdirSync(baseDir, { recursive: true });
const bindingPkg = `${pkg.name}-wasm32-wasi@${version}`;
console.log(`[rspack] Downloading ${bindingPkg} on WebContainer...`);
childProcess.execFileSync('pnpm', ['i', bindingPkg], {
cwd: baseDir,
stdio: 'inherit',
});
}
module.exports = require(bindingEntry);

22
node_modules/@rspack/core/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,22 @@
MIT License
Copyright (c) 2022-present Bytedance, Inc. and its affiliates.
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.

15
node_modules/@rspack/core/README.md generated vendored Normal file
View File

@@ -0,0 +1,15 @@
<picture>
<img alt="Rspack Banner" src="https://assets.rspack.rs/rspack/rspack-banner.png">
</picture>
# @rspack/core
The fast Rust-based web bundler with webpack-compatible API.
## Documentation
See <https://rspack.rs> for details.
## License
Rspack is [MIT licensed](https://github.com/web-infra-dev/rspack/blob/main/LICENSE).

2134
node_modules/@rspack/core/compiled/@swc/types/index.d.ts generated vendored Normal file

File diff suppressed because it is too large Load Diff

19
node_modules/@rspack/core/compiled/@swc/types/index.js generated vendored Normal file
View File

@@ -0,0 +1,19 @@
/******/ (() => { // webpackBootstrap
/******/ "use strict";
/******/ /* webpack/runtime/compat */
/******/
/******/ if (typeof __nccwpck_require__ !== 'undefined') __nccwpck_require__.ab = __dirname + "/";
/******/
/************************************************************************/
var __webpack_exports__ = {};
// This entry need to be wrapped in an IIFE because it uses a non-standard name for the exports (exports).
(() => {
var exports = __webpack_exports__;
Object.defineProperty(exports, "__esModule", ({ value: true }));
})();
module.exports = __webpack_exports__;
/******/ })()
;

201
node_modules/@rspack/core/compiled/@swc/types/license generated vendored Normal file
View File

@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2024 SWC contributors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -0,0 +1 @@
{"name":"@swc/types","author":"강동윤 <kdy1997.dev@gmail.com>","version":"0.1.25","license":"Apache-2.0","types":"index.d.ts","type":"commonjs"}

View File

@@ -0,0 +1,21 @@
declare function findConfig(from: string): Record<string, string[]> | undefined;
type LoadConfigOptions = {
/**
* Specify the path to the configuration file
* If both `config` and `path` are provided, `config` will be used
*/
config?: string;
/**
* Specify the directory where the configuration file is located
*/
path?: string;
/**
* Specify the environment to load
* @default "production"
*/
env?: string;
};
declare function loadConfig(opts: LoadConfigOptions): string[] | undefined;
export { findConfig, loadConfig };
export type { LoadConfigOptions };

View File

@@ -0,0 +1,252 @@
/******/ (() => { // webpackBootstrap
/******/ "use strict";
/******/ var __webpack_modules__ = ({
/***/ 24:
/***/ ((module) => {
module.exports = require("node:fs");
/***/ }),
/***/ 760:
/***/ ((module) => {
module.exports = require("node:path");
/***/ }),
/***/ 867:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
var __nested_webpack_require_18__ = {};
(()=>{
__nested_webpack_require_18__.n = (module)=>{
var getter = module && module.__esModule ? ()=>module['default'] : ()=>module;
__nested_webpack_require_18__.d(getter, {
a: getter
});
return getter;
};
})();
(()=>{
__nested_webpack_require_18__.d = (exports1, definition)=>{
for(var key in definition)if (__nested_webpack_require_18__.o(definition, key) && !__nested_webpack_require_18__.o(exports1, key)) Object.defineProperty(exports1, key, {
enumerable: true,
get: definition[key]
});
};
})();
(()=>{
__nested_webpack_require_18__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
})();
(()=>{
__nested_webpack_require_18__.r = (exports1)=>{
if ('undefined' != typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
value: 'Module'
});
Object.defineProperty(exports1, '__esModule', {
value: true
});
};
})();
var __nested_webpack_exports__ = {};
__nested_webpack_require_18__.r(__nested_webpack_exports__);
__nested_webpack_require_18__.d(__nested_webpack_exports__, {
loadConfig: ()=>loadConfig,
findConfig: ()=>findConfig
});
const external_node_fs_namespaceObject = __nccwpck_require__(24);
var external_node_fs_default = /*#__PURE__*/ __nested_webpack_require_18__.n(external_node_fs_namespaceObject);
const external_node_path_namespaceObject = __nccwpck_require__(760);
var external_node_path_default = /*#__PURE__*/ __nested_webpack_require_18__.n(external_node_path_namespaceObject);
function _define_property(obj, key, value) {
if (key in obj) Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
else obj[key] = value;
return obj;
}
class BrowserslistError extends Error {
constructor(message){
super(message), _define_property(this, "browserslist", void 0);
this.name = 'BrowserslistError';
this.browserslist = true;
if (Error.captureStackTrace) Error.captureStackTrace(this, BrowserslistError);
}
}
const isFileCache = {};
function isFile(file) {
if (file in isFileCache) return isFileCache[file];
const result = external_node_fs_default().existsSync(file) && external_node_fs_default().statSync(file).isFile();
isFileCache[file] = result;
return result;
}
function check(section) {
const FORMAT = 'Browserslist config should be a string or an array of strings with browser queries';
if (Array.isArray(section)) {
for(let i = 0; i < section.length; i++)if ('string' != typeof section[i]) throw new BrowserslistError(FORMAT);
} else if ('string' != typeof section) throw new BrowserslistError(FORMAT);
}
function parsePackage(file) {
const config = JSON.parse(external_node_fs_default().readFileSync(file).toString().replace(/^\uFEFF/m, ''));
if (config.browserlist && !config.browserslist) throw new BrowserslistError(`\`browserlist\` key instead of \`browserslist\` in ${file}`);
let list = config.browserslist;
if (Array.isArray(list)) list = {
defaults: list
};
if ('string' == typeof list) list = parseConfig(list);
for(const i in list)check(list[i]);
return list;
}
const IS_SECTION = /^\s*\[(.+)]\s*$/;
function parseConfig(string) {
const result = {
defaults: []
};
let sections = [
'defaults'
];
string.toString().replace(/#[^\n]*/g, '').split(/\n|,/).map((line)=>line.trim()).filter((line)=>'' !== line).forEach((line)=>{
const matched = line.match(IS_SECTION);
if (matched) {
sections = matched[1].trim().split(' ');
sections.forEach((section)=>{
if (result[section]) throw new BrowserslistError(`Duplicate section ${section} in Browserslist config`);
result[section] = [];
});
} else sections.forEach((section)=>{
result[section].push(line);
});
});
return result;
}
function readConfig(file) {
if (!isFile(file)) throw new BrowserslistError(`Can't read ${file} config`);
return parseConfig(external_node_fs_default().readFileSync(file, 'utf-8'));
}
function parsePackageOrReadConfig(file) {
if ('package.json' === external_node_path_default().basename(file)) return parsePackage(file);
return readConfig(file);
}
function pickEnv(config, opts) {
if ('object' != typeof config) return config;
let name;
name = 'string' == typeof opts.env ? opts.env : process.env.BROWSERSLIST_ENV ? process.env.BROWSERSLIST_ENV : process.env.NODE_ENV ? process.env.NODE_ENV : 'production';
return config[name] || config.defaults;
}
function eachParent(file, callback) {
const dir = isFile(file) ? external_node_path_default().dirname(file) : file;
let loc = external_node_path_default().resolve(dir);
do {
const result = callback(loc);
if (void 0 !== result) return result;
}while (loc !== (loc = external_node_path_default().dirname(loc)));
}
function findConfigFile(from) {
return eachParent(from, (dir)=>{
const config = external_node_path_default().join(dir, 'browserslist');
const pkg = external_node_path_default().join(dir, 'package.json');
const rc = external_node_path_default().join(dir, '.browserslistrc');
let pkgBrowserslist;
if (isFile(pkg)) try {
pkgBrowserslist = parsePackage(pkg);
} catch (e) {
if (e instanceof BrowserslistError) throw e;
console.warn(`[Browserslist] Could not parse ${pkg}. Ignoring it.`);
}
if (isFile(config) && pkgBrowserslist) throw new BrowserslistError(`${dir} contains both browserslist and package.json with browsers`);
if (isFile(rc) && pkgBrowserslist) throw new BrowserslistError(`${dir} contains both .browserslistrc and package.json with browsers`);
if (isFile(config) && isFile(rc)) throw new BrowserslistError(`${dir} contains both .browserslistrc and browserslist`);
if (isFile(config)) return config;
if (isFile(rc)) return rc;
if (pkgBrowserslist) return pkg;
});
}
const configCache = {};
function findConfig(from) {
from = external_node_path_default().resolve(from);
const fromDir = isFile(from) ? external_node_path_default().dirname(from) : from;
if (fromDir in configCache) return configCache[fromDir];
let resolved;
const configFile = findConfigFile(from);
if (configFile) resolved = parsePackageOrReadConfig(configFile);
const configDir = configFile && external_node_path_default().dirname(configFile);
eachParent(from, (dir)=>{
if (resolved) configCache[dir] = resolved;
if (dir === configDir) return null;
});
return resolved;
}
function loadConfig(opts) {
if (opts.config) return pickEnv(parsePackageOrReadConfig(opts.config), opts);
if (opts.path) {
const config = findConfig(opts.path);
if (!config) return;
return pickEnv(config, opts);
}
}
exports.findConfig = __nested_webpack_exports__.findConfig;
exports.loadConfig = __nested_webpack_exports__.loadConfig;
for(var __webpack_i__ in __nested_webpack_exports__)if (-1 === [
"findConfig",
"loadConfig"
].indexOf(__webpack_i__)) exports[__webpack_i__] = __nested_webpack_exports__[__webpack_i__];
Object.defineProperty(exports, "__esModule", ({
value: true
}));
/***/ })
/******/ });
/************************************************************************/
/******/ // The module cache
/******/ var __webpack_module_cache__ = {};
/******/
/******/ // The require function
/******/ function __nccwpck_require__(moduleId) {
/******/ // Check if module is in cache
/******/ var cachedModule = __webpack_module_cache__[moduleId];
/******/ if (cachedModule !== undefined) {
/******/ return cachedModule.exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = __webpack_module_cache__[moduleId] = {
/******/ // no module.id needed
/******/ // no module.loaded needed
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ var threw = true;
/******/ try {
/******/ __webpack_modules__[moduleId](module, module.exports, __nccwpck_require__);
/******/ threw = false;
/******/ } finally {
/******/ if(threw) delete __webpack_module_cache__[moduleId];
/******/ }
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/************************************************************************/
/******/ /* webpack/runtime/compat */
/******/
/******/ if (typeof __nccwpck_require__ !== 'undefined') __nccwpck_require__.ab = __dirname + "/";
/******/
/************************************************************************/
/******/
/******/ // startup
/******/ // Load entry module and return exports
/******/ // This entry module is referenced by other modules so it can't be inlined
/******/ var __webpack_exports__ = __nccwpck_require__(867);
/******/ module.exports = __webpack_exports__;
/******/
/******/ })()
;

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2024 Rspack Contrib
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1 @@
{"name":"browserslist-load-config","version":"1.0.1","license":"MIT","types":"index.d.ts","type":"commonjs"}

24
node_modules/@rspack/core/compiled/tinypool/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,24 @@
The MIT License (MIT)
Copyright (c) 2020 James M Snell and the Piscina contributors
Piscina contributors listed at https://github.com/jasnell/piscina#the-team and
in the README file.
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.

20
node_modules/@rspack/core/compiled/tinypool/README.md generated vendored Normal file
View File

@@ -0,0 +1,20 @@
# Tinypool - the node.js worker pool 🧵
> Piscina: A fast, efficient Node.js Worker Thread Pool implementation
Tinypool is a fork of piscina. What we try to achieve in this library, is to eliminate some dependencies and features that our target users don't need (currently, our main user will be Vitest). Tinypool's install size (38KB) can then be smaller than Piscina's install size (6MB when Tinypool was created, Piscina has since reduced it's size to ~800KB). If you need features like [utilization](https://github.com/piscinajs/piscina#property-utilization-readonly) or OS-specific thread priority setting, [Piscina](https://github.com/piscinajs/piscina) is a better choice for you. We think that Piscina is an amazing library, and we may try to upstream some of the dependencies optimization in this fork.
- ✅ Smaller install size, 38KB
- ✅ Minimal
- ✅ No dependencies
- ✅ Physical cores instead of Logical cores with [physical-cpu-count](https://www.npmjs.com/package/physical-cpu-count)
- ✅ Supports `worker_threads` and `child_process`
- ❌ No utilization
- ❌ No OS-specific thread priority setting
- Written in TypeScript, and ESM support only. For Node.js 18.x and higher.
_In case you need more tiny libraries like tinypool or tinyspy, please consider submitting an [RFC](https://github.com/tinylibs/rfcs)_
## Docs
Read **[full docs](https://github.com/tinylibs/tinypool#readme)** on GitHub.

View File

@@ -0,0 +1,28 @@
//#region src/common.ts
const kMovable = Symbol("Tinypool.kMovable");
const kTransferable = Symbol.for("Tinypool.transferable");
const kValue = Symbol.for("Tinypool.valueOf");
const kQueueOptions = Symbol.for("Tinypool.queueOptions");
function isTransferable(value) {
return value != null && typeof value === "object" && kTransferable in value && kValue in value;
}
function isMovable(value) {
return isTransferable(value) && value[kMovable] === true;
}
function markMovable(value) {
Object.defineProperty(value, kMovable, {
enumerable: false,
configurable: true,
writable: true,
value: true
});
}
function isTaskQueue(value) {
return typeof value === "object" && value !== null && "size" in value && typeof value.shift === "function" && typeof value.remove === "function" && typeof value.push === "function";
}
const kRequestCountField = 0;
const kResponseCountField = 1;
const kFieldCount = 2;
//#endregion
export { isMovable, isTaskQueue, isTransferable, kFieldCount, kQueueOptions, kRequestCountField, kResponseCountField, kTransferable, kValue, markMovable };

View File

@@ -0,0 +1 @@
export { };

View File

@@ -0,0 +1,72 @@
import { stderr, stdout } from "../utils-De75vAgL.js";
import { getHandler, throwInNextTick } from "../utils-B--2TaWv.js";
//#region src/entry/process.ts
process.__tinypool_state__ = {
isChildProcess: true,
isTinypoolWorker: true,
workerData: null,
workerId: Number(process.env.TINYPOOL_WORKER_ID)
};
const memoryUsage = process.memoryUsage.bind(process);
const send = process.send.bind(process);
process.on("message", (message) => {
if (!message || !message.__tinypool_worker_message__) return;
if (message.source === "pool") {
const { filename, name } = message;
(async function() {
if (filename !== null) await getHandler(filename, name);
send({
ready: true,
source: "pool",
__tinypool_worker_message__: true
}, () => {});
})().catch(throwInNextTick);
return;
}
if (message.source === "port") {
onMessage(message).catch(throwInNextTick);
return;
}
throw new Error(`Unexpected TinypoolWorkerMessage ${JSON.stringify(message)}`);
});
async function onMessage(message) {
const { taskId, task, filename, name } = message;
let response;
try {
const handler = await getHandler(filename, name);
if (handler === null) throw new Error(`No handler function "${name}" exported from "${filename}"`);
const result = await handler(task);
response = {
source: "port",
__tinypool_worker_message__: true,
taskId,
result,
error: null,
usedMemory: memoryUsage().heapUsed
};
if (stdout()?.writableLength > 0) await new Promise((resolve) => process.stdout.write("", resolve));
if (stderr()?.writableLength > 0) await new Promise((resolve) => process.stderr.write("", resolve));
} catch (error) {
response = {
source: "port",
__tinypool_worker_message__: true,
taskId,
result: null,
error: serializeError(error),
usedMemory: memoryUsage().heapUsed
};
}
send(response);
}
function serializeError(error) {
if (error instanceof Error) return {
...error,
name: error.name,
stack: error.stack,
message: error.message
};
return String(error);
}
//#endregion

View File

@@ -0,0 +1,7 @@
//#region src/entry/utils.d.ts
type Handler = Function;
declare function getHandler(filename: string, name: string): Promise<Handler | null>;
declare function throwInNextTick(error: Error): void;
//#endregion
export { getHandler, throwInNextTick };

View File

@@ -0,0 +1,3 @@
import { getHandler, throwInNextTick } from "../utils-B--2TaWv.js";
export { getHandler, throwInNextTick };

View File

@@ -0,0 +1 @@
export { };

View File

@@ -0,0 +1,76 @@
import { isMovable, kRequestCountField, kResponseCountField, kTransferable, kValue } from "../common-Qw-RoVFD.js";
import { stderr, stdout } from "../utils-De75vAgL.js";
import { getHandler, throwInNextTick } from "../utils-B--2TaWv.js";
import { parentPort, receiveMessageOnPort, workerData } from "node:worker_threads";
//#region src/entry/worker.ts
const [tinypoolPrivateData, workerData$1] = workerData;
process.__tinypool_state__ = {
isWorkerThread: true,
isTinypoolWorker: true,
workerData: workerData$1,
workerId: tinypoolPrivateData.workerId
};
const memoryUsage = process.memoryUsage.bind(process);
let useAtomics = process.env.PISCINA_DISABLE_ATOMICS !== "1";
parentPort.on("message", (message) => {
useAtomics = process.env.PISCINA_DISABLE_ATOMICS === "1" ? false : message.useAtomics;
const { port, sharedBuffer, filename, name } = message;
(async function() {
if (filename !== null) await getHandler(filename, name);
const readyMessage = { ready: true };
parentPort.postMessage(readyMessage);
port.start();
port.on("message", onMessage.bind(null, port, sharedBuffer));
atomicsWaitLoop(port, sharedBuffer);
})().catch(throwInNextTick);
});
let currentTasks = 0;
let lastSeenRequestCount = 0;
function atomicsWaitLoop(port, sharedBuffer) {
if (!useAtomics) return;
while (currentTasks === 0) {
Atomics.wait(sharedBuffer, kRequestCountField, lastSeenRequestCount);
lastSeenRequestCount = Atomics.load(sharedBuffer, kRequestCountField);
let entry;
while ((entry = receiveMessageOnPort(port)) !== void 0) onMessage(port, sharedBuffer, entry.message);
}
}
function onMessage(port, sharedBuffer, message) {
currentTasks++;
const { taskId, task, filename, name } = message;
(async function() {
let response;
let transferList = [];
try {
const handler = await getHandler(filename, name);
if (handler === null) throw new Error(`No handler function "${name}" exported from "${filename}"`);
let result = await handler(task);
if (isMovable(result)) {
transferList = transferList.concat(result[kTransferable]);
result = result[kValue];
}
response = {
taskId,
result,
error: null,
usedMemory: memoryUsage().heapUsed
};
if (stdout()?.writableLength > 0) await new Promise((resolve) => process.stdout.write("", resolve));
if (stderr()?.writableLength > 0) await new Promise((resolve) => process.stderr.write("", resolve));
} catch (error) {
response = {
taskId,
result: null,
error,
usedMemory: memoryUsage().heapUsed
};
}
currentTasks--;
port.postMessage(response, transferList);
Atomics.add(sharedBuffer, kResponseCountField, 1);
atomicsWaitLoop(port, sharedBuffer);
})().catch(throwInNextTick);
}
//#endregion

View File

@@ -0,0 +1,195 @@
/// <reference types="node" />
import { MessagePort, TransferListItem } from "node:worker_threads";
import { EventEmitterAsyncResource } from "node:events";
//#region src/common.d.ts
/** Channel for communicating between main thread and workers */
/** Channel for communicating between main thread and workers */
interface TinypoolChannel {
/** Workers subscribing to messages */
onMessage?: (callback: (message: any) => void) => void;
/** Called with worker's messages */
postMessage?: (message: any) => void;
/** Called when channel can be closed */
onClose?: () => void;
}
interface TinypoolWorker {
runtime: string;
initialize(options: {
env?: Record<string, string>;
argv?: string[];
execArgv?: string[];
resourceLimits?: any;
workerData: TinypoolData;
trackUnmanagedFds?: boolean;
}): void;
terminate(): Promise<any>;
postMessage(message: any, transferListItem?: TransferListItem[]): void;
setChannel?: (channel: TinypoolChannel) => void;
on(event: string, listener: (...args: any[]) => void): void;
once(event: string, listener: (...args: any[]) => void): void;
emit(event: string, ...data: any[]): void;
ref?: () => void;
unref?: () => void;
threadId: number;
}
/**
* Tinypool's internal messaging between main thread and workers.
* - Utilizers can use `__tinypool_worker_message__` property to identify
* these messages and ignore them.
*/
interface TinypoolWorkerMessage<T extends 'port' | 'pool' = 'port' | 'pool'> {
__tinypool_worker_message__: true;
source: T;
}
interface StartupMessage {
filename: string | null;
name: string;
port: MessagePort;
sharedBuffer: Int32Array;
useAtomics: boolean;
}
interface RequestMessage {
taskId: number;
task: any;
filename: string;
name: string;
}
interface ReadyMessage {
ready: true;
}
interface ResponseMessage {
taskId: number;
result: any;
error: unknown | null;
usedMemory: number;
}
interface TinypoolPrivateData {
workerId: number;
}
type TinypoolData = [TinypoolPrivateData, any];
declare const kTransferable: unique symbol;
declare const kValue: unique symbol;
declare const kQueueOptions: unique symbol;
declare function isTransferable(value: any): boolean;
declare function isMovable(value: any): boolean;
declare function markMovable(value: object): void;
interface Transferable {
readonly [kTransferable]: object;
readonly [kValue]: object;
}
interface Task {
readonly [kQueueOptions]: object | null;
cancel(): void;
}
interface TaskQueue {
readonly size: number;
shift(): Task | null;
remove(task: Task): void;
push(task: Task): void;
cancel(): void;
}
declare function isTaskQueue(value: any): boolean;
declare const kRequestCountField = 0;
declare const kResponseCountField = 1;
declare const kFieldCount = 2; //#endregion
//#region src/index.d.ts
declare global {
namespace NodeJS {
interface Process {
__tinypool_state__: {
isTinypoolWorker: boolean;
isWorkerThread?: boolean;
isChildProcess?: boolean;
workerData: any;
workerId: number;
};
}
}
}
interface AbortSignalEventTargetAddOptions {
once: boolean;
}
interface AbortSignalEventTarget {
addEventListener: (name: 'abort', listener: () => void, options?: AbortSignalEventTargetAddOptions) => void;
removeEventListener: (name: 'abort', listener: () => void) => void;
aborted?: boolean;
}
interface AbortSignalEventEmitter {
off: (name: 'abort', listener: () => void) => void;
once: (name: 'abort', listener: () => void) => void;
}
type AbortSignalAny = AbortSignalEventTarget | AbortSignalEventEmitter;
type ResourceLimits = Worker extends {
resourceLimits?: infer T;
} ? T : object;
interface Options {
filename?: string | null;
runtime?: 'worker_threads' | 'child_process';
name?: string;
minThreads?: number;
maxThreads?: number;
idleTimeout?: number;
terminateTimeout?: number;
maxQueue?: number | 'auto';
concurrentTasksPerWorker?: number;
useAtomics?: boolean;
resourceLimits?: ResourceLimits;
maxMemoryLimitBeforeRecycle?: number;
argv?: string[];
execArgv?: string[];
env?: Record<string, string>;
workerData?: any;
taskQueue?: TaskQueue;
trackUnmanagedFds?: boolean;
isolateWorkers?: boolean;
teardown?: string;
}
interface FilledOptions extends Options {
filename: string | null;
name: string;
runtime: NonNullable<Options['runtime']>;
minThreads: number;
maxThreads: number;
idleTimeout: number;
maxQueue: number;
concurrentTasksPerWorker: number;
useAtomics: boolean;
taskQueue: TaskQueue;
}
interface RunOptions {
transferList?: TransferList;
channel?: TinypoolChannel;
filename?: string | null;
signal?: AbortSignalAny | null;
name?: string | null;
runtime?: Options['runtime'];
}
type TransferList = MessagePort extends {
postMessage(value: any, transferList: infer T): any;
} ? T : never;
type TransferListItem$1 = TransferList extends (infer T)[] ? T : never;
declare class Tinypool extends EventEmitterAsyncResource {
#private;
constructor(options?: Options);
run(task: any, options?: RunOptions): Promise<any>;
destroy(): Promise<void>;
get options(): FilledOptions;
get threads(): TinypoolWorker[];
get queueSize(): number;
cancelPendingTasks(): void;
recycleWorkers(options?: Pick<Options, 'runtime'>): Promise<void>;
get completed(): number;
get duration(): number;
static get isWorkerThread(): boolean;
static get workerData(): any;
static get version(): string;
static move(val: Transferable | TransferListItem$1 | ArrayBufferView | ArrayBuffer | MessagePort): MessagePort | ArrayBuffer | Transferable | ArrayBufferView;
static get transferableSymbol(): symbol;
static get valueSymbol(): symbol;
static get queueOptionsSymbol(): symbol;
}
declare const _workerId: number;
//#endregion
export { Options, ReadyMessage, RequestMessage, ResponseMessage, StartupMessage, Task, TaskQueue, Tinypool, TinypoolChannel, TinypoolData, TinypoolPrivateData, TinypoolWorker, TinypoolWorkerMessage, Transferable, Tinypool as default, isMovable, isTaskQueue, isTransferable, kFieldCount, kQueueOptions, kRequestCountField, kResponseCountField, kTransferable, kValue, markMovable, _workerId as workerId };

View File

@@ -0,0 +1,820 @@
import { isMovable, isTaskQueue, isTransferable, kFieldCount, kQueueOptions, kRequestCountField, kResponseCountField, kTransferable, kValue, markMovable } from "./common-Qw-RoVFD.js";
import { MessageChannel, MessagePort, Worker, receiveMessageOnPort } from "node:worker_threads";
import { EventEmitterAsyncResource, once } from "node:events";
import { AsyncResource } from "node:async_hooks";
import { URL, fileURLToPath } from "node:url";
import { join } from "node:path";
import { inspect, types } from "node:util";
import assert from "node:assert";
import { performance } from "node:perf_hooks";
import { readFileSync } from "node:fs";
import os from "node:os";
import childProcess, { fork } from "node:child_process";
//#region src/physicalCpuCount.ts
function exec(command) {
const output = childProcess.execSync(command, {
encoding: "utf8",
stdio: [
null,
null,
null
]
});
return output;
}
let amount;
try {
const platform = os.platform();
if (platform === "linux") {
const output1 = exec("cat /proc/cpuinfo | grep \"physical id\" | sort |uniq | wc -l");
const output2 = exec("cat /proc/cpuinfo | grep \"core id\" | sort | uniq | wc -l");
const physicalCpuAmount = parseInt(output1.trim(), 10);
const physicalCoreAmount = parseInt(output2.trim(), 10);
amount = physicalCpuAmount * physicalCoreAmount;
} else if (platform === "darwin") {
const output = exec("sysctl -n hw.physicalcpu_max");
amount = parseInt(output.trim(), 10);
} else if (platform === "win32") throw new Error();
else {
const cores = os.cpus().filter(function(cpu, index) {
const hasHyperthreading = cpu.model.includes("Intel");
const isOdd = index % 2 === 1;
return !hasHyperthreading || isOdd;
});
amount = cores.length;
}
} catch {
amount = os.cpus().length;
}
if (amount === 0) amount = os.cpus().length;
//#endregion
//#region src/runtime/thread-worker.ts
var ThreadWorker = class {
name = "ThreadWorker";
runtime = "worker_threads";
initialize(options) {
this.thread = new Worker(fileURLToPath(import.meta.url + "/../entry/worker.js"), options);
this.threadId = this.thread.threadId;
}
async terminate() {
const output = await this.thread.terminate();
this.channel?.onClose?.();
return output;
}
postMessage(message, transferListItem) {
return this.thread.postMessage(message, transferListItem);
}
on(event, callback) {
return this.thread.on(event, callback);
}
once(event, callback) {
return this.thread.once(event, callback);
}
emit(event, ...data) {
return this.thread.emit(event, ...data);
}
ref() {
return this.thread.ref();
}
unref() {
return this.thread.unref();
}
setChannel(channel) {
if (channel.onMessage) throw new Error("{ runtime: 'worker_threads' } doesn't support channel.onMessage. Use transferListItem for listening to messages instead.");
if (channel.postMessage) throw new Error("{ runtime: 'worker_threads' } doesn't support channel.postMessage. Use transferListItem for sending to messages instead.");
if (this.channel && this.channel !== channel) this.channel.onClose?.();
this.channel = channel;
}
};
//#endregion
//#region src/runtime/process-worker.ts
const __tinypool_worker_message__ = true;
const SIGKILL_TIMEOUT = 1e3;
var ProcessWorker = class {
name = "ProcessWorker";
runtime = "child_process";
isTerminating = false;
initialize(options) {
this.process = fork(fileURLToPath(import.meta.url + "/../entry/process.js"), options.argv, {
...options,
stdio: "pipe",
env: {
...options.env,
TINYPOOL_WORKER_ID: options.workerData[0].workerId.toString()
}
});
process.stdout.setMaxListeners(1 + process.stdout.getMaxListeners());
process.stderr.setMaxListeners(1 + process.stderr.getMaxListeners());
this.process.stdout?.pipe(process.stdout);
this.process.stderr?.pipe(process.stderr);
this.threadId = this.process.pid;
this.process.on("exit", this.onUnexpectedExit);
this.waitForExit = new Promise((r) => this.process.on("exit", r));
}
onUnexpectedExit = () => {
this.process.emit("error", new Error("Worker exited unexpectedly"));
};
async terminate() {
this.isTerminating = true;
this.process.off("exit", this.onUnexpectedExit);
const sigkillTimeout = setTimeout(() => this.process.kill("SIGKILL"), SIGKILL_TIMEOUT);
this.process.kill();
await this.waitForExit;
this.process.stdout?.unpipe(process.stdout);
this.process.stderr?.unpipe(process.stderr);
this.port?.close();
this.channel?.onClose?.();
clearTimeout(sigkillTimeout);
}
setChannel(channel) {
if (this.channel && this.channel !== channel) this.channel.onClose?.();
this.channel = channel;
this.channel.onMessage?.((message) => {
this.send(message);
});
}
send(message) {
if (!this.isTerminating) this.process.send(message);
}
postMessage(message, transferListItem) {
transferListItem?.forEach((item) => {
if (item instanceof MessagePort) {
this.port = item;
this.port.start();
}
});
if (this.port) this.port.on("message", (message$1) => this.send({
...message$1,
source: "port",
__tinypool_worker_message__
}));
return this.send({
...message,
source: "pool",
__tinypool_worker_message__
});
}
on(event, callback) {
return this.process.on(event, (data) => {
if (event === "error") return callback(data);
if (!data || !data.__tinypool_worker_message__) return this.channel?.postMessage?.(data);
if (data.source === "pool") callback(data);
else if (data.source === "port") this.port.postMessage(data);
});
}
once(event, callback) {
return this.process.once(event, callback);
}
emit(event, ...data) {
return this.process.emit(event, ...data);
}
ref() {
return this.process.ref();
}
unref() {
this.port?.unref();
this.process.channel?.unref?.();
if (hasUnref(this.process.stdout)) this.process.stdout.unref();
if (hasUnref(this.process.stderr)) this.process.stderr.unref();
return this.process.unref();
}
};
function hasUnref(stream) {
return stream != null && "unref" in stream && typeof stream.unref === "function";
}
//#endregion
//#region src/index.ts
const cpuCount = amount;
function onabort(abortSignal, listener) {
if ("addEventListener" in abortSignal) abortSignal.addEventListener("abort", listener, { once: true });
else abortSignal.once("abort", listener);
}
var AbortError = class extends Error {
constructor() {
super("The task has been aborted");
}
get name() {
return "AbortError";
}
};
var CancelError = class extends Error {
constructor() {
super("The task has been cancelled");
}
get name() {
return "CancelError";
}
};
var ArrayTaskQueue = class {
tasks = [];
get size() {
return this.tasks.length;
}
shift() {
return this.tasks.shift();
}
push(task) {
this.tasks.push(task);
}
remove(task) {
const index = this.tasks.indexOf(task);
assert.notStrictEqual(index, -1);
this.tasks.splice(index, 1);
}
cancel() {
while (this.tasks.length > 0) {
const task = this.tasks.pop();
task?.cancel();
}
}
};
const kDefaultOptions = {
filename: null,
name: "default",
runtime: "worker_threads",
minThreads: Math.max(cpuCount / 2, 1),
maxThreads: cpuCount,
idleTimeout: 0,
maxQueue: Infinity,
concurrentTasksPerWorker: 1,
useAtomics: true,
taskQueue: new ArrayTaskQueue(),
trackUnmanagedFds: true
};
const kDefaultRunOptions = {
transferList: void 0,
filename: null,
signal: null,
name: null
};
var DirectlyTransferable = class {
#value;
constructor(value) {
this.#value = value;
}
get [kTransferable]() {
return this.#value;
}
get [kValue]() {
return this.#value;
}
};
var ArrayBufferViewTransferable = class {
#view;
constructor(view) {
this.#view = view;
}
get [kTransferable]() {
return this.#view.buffer;
}
get [kValue]() {
return this.#view;
}
};
let taskIdCounter = 0;
function maybeFileURLToPath(filename) {
return filename.startsWith("file:") ? fileURLToPath(new URL(filename)) : filename;
}
var TaskInfo = class extends AsyncResource {
abortListener = null;
workerInfo = null;
constructor(task, transferList, filename, name, callback, abortSignal, triggerAsyncId, channel) {
super("Tinypool.Task", {
requireManualDestroy: true,
triggerAsyncId
});
this.callback = callback;
this.task = task;
this.transferList = transferList;
this.cancel = () => this.callback(new CancelError(), null);
this.channel = channel;
if (isMovable(task)) {
/* istanbul ignore if */
if (this.transferList == null) this.transferList = [];
this.transferList = this.transferList.concat(task[kTransferable]);
this.task = task[kValue];
}
this.filename = filename;
this.name = name;
this.taskId = taskIdCounter++;
this.abortSignal = abortSignal;
this.created = performance.now();
this.started = 0;
}
releaseTask() {
const ret = this.task;
this.task = null;
return ret;
}
done(err, result) {
this.emitDestroy();
this.runInAsyncScope(this.callback, null, err, result);
if (this.abortSignal && this.abortListener) if ("removeEventListener" in this.abortSignal && this.abortListener) this.abortSignal.removeEventListener("abort", this.abortListener);
else this.abortSignal.off("abort", this.abortListener);
}
get [kQueueOptions]() {
return kQueueOptions in this.task ? this.task[kQueueOptions] : null;
}
};
var AsynchronouslyCreatedResource = class {
onreadyListeners = [];
markAsReady() {
const listeners = this.onreadyListeners;
assert(listeners !== null);
this.onreadyListeners = null;
for (const listener of listeners) listener();
}
isReady() {
return this.onreadyListeners === null;
}
onReady(fn) {
if (this.onreadyListeners === null) {
fn();
return;
}
this.onreadyListeners.push(fn);
}
};
var AsynchronouslyCreatedResourcePool = class {
pendingItems = new Set();
readyItems = new Set();
constructor(maximumUsage) {
this.maximumUsage = maximumUsage;
this.onAvailableListeners = [];
}
add(item) {
this.pendingItems.add(item);
item.onReady(() => {
/* istanbul ignore else */
if (this.pendingItems.has(item)) {
this.pendingItems.delete(item);
this.readyItems.add(item);
this.maybeAvailable(item);
}
});
}
delete(item) {
this.pendingItems.delete(item);
this.readyItems.delete(item);
}
findAvailable() {
let minUsage = this.maximumUsage;
let candidate = null;
for (const item of this.readyItems) {
const usage = item.currentUsage();
if (usage === 0) return item;
if (usage < minUsage) {
candidate = item;
minUsage = usage;
}
}
return candidate;
}
*[Symbol.iterator]() {
yield* this.pendingItems;
yield* this.readyItems;
}
get size() {
return this.pendingItems.size + this.readyItems.size;
}
maybeAvailable(item) {
/* istanbul ignore else */
if (item.currentUsage() < this.maximumUsage) for (const listener of this.onAvailableListeners) listener(item);
}
onAvailable(fn) {
this.onAvailableListeners.push(fn);
}
};
const Errors = {
ThreadTermination: () => new Error("Terminating worker thread"),
FilenameNotProvided: () => new Error("filename must be provided to run() or in options object"),
TaskQueueAtLimit: () => new Error("Task queue is at limit"),
NoTaskQueueAvailable: () => new Error("No task queue available and all Workers are busy")
};
var WorkerInfo = class extends AsynchronouslyCreatedResource {
idleTimeout = null;
lastSeenResponseCount = 0;
constructor(worker, port, workerId, freeWorkerId, onMessage, filename, teardown) {
super();
this.worker = worker;
this.workerId = workerId;
this.freeWorkerId = freeWorkerId;
this.teardown = teardown;
this.filename = filename;
this.port = port;
this.port.on("message", (message) => this._handleResponse(message));
this.onMessage = onMessage;
this.taskInfos = new Map();
this.sharedBuffer = new Int32Array(new SharedArrayBuffer(kFieldCount * Int32Array.BYTES_PER_ELEMENT));
}
async destroy(timeout) {
let resolve;
let reject;
const ret = new Promise((res, rej) => {
resolve = res;
reject = rej;
});
if (this.teardown && this.filename) {
const { teardown, filename } = this;
await new Promise((resolve$1, reject$1) => {
this.postTask(new TaskInfo({}, [], filename, teardown, (error, result) => error ? reject$1(error) : resolve$1(result), null, 1, void 0));
});
}
const timer = timeout ? setTimeout(() => reject(new Error("Failed to terminate worker")), timeout) : null;
this.worker.terminate().then(() => {
if (timer !== null) clearTimeout(timer);
this.port.close();
this.clearIdleTimeout();
for (const taskInfo of this.taskInfos.values()) taskInfo.done(Errors.ThreadTermination());
this.taskInfos.clear();
resolve();
});
return ret;
}
clearIdleTimeout() {
if (this.idleTimeout !== null) {
clearTimeout(this.idleTimeout);
this.idleTimeout = null;
}
}
ref() {
this.port.ref();
return this;
}
unref() {
this.port.unref();
return this;
}
_handleResponse(message) {
this.usedMemory = message.usedMemory;
this.onMessage(message);
if (this.taskInfos.size === 0) this.unref();
}
postTask(taskInfo) {
assert(!this.taskInfos.has(taskInfo.taskId));
const message = {
task: taskInfo.releaseTask(),
taskId: taskInfo.taskId,
filename: taskInfo.filename,
name: taskInfo.name
};
try {
if (taskInfo.channel) this.worker.setChannel?.(taskInfo.channel);
this.port.postMessage(message, taskInfo.transferList);
} catch (err) {
taskInfo.done(err);
return;
}
taskInfo.workerInfo = this;
this.taskInfos.set(taskInfo.taskId, taskInfo);
this.ref();
this.clearIdleTimeout();
Atomics.add(this.sharedBuffer, kRequestCountField, 1);
Atomics.notify(this.sharedBuffer, kRequestCountField, 1);
}
processPendingMessages() {
const actualResponseCount = Atomics.load(this.sharedBuffer, kResponseCountField);
if (actualResponseCount !== this.lastSeenResponseCount) {
this.lastSeenResponseCount = actualResponseCount;
let entry;
while ((entry = receiveMessageOnPort(this.port)) !== void 0) this._handleResponse(entry.message);
}
}
isRunningAbortableTask() {
if (this.taskInfos.size !== 1) return false;
const [first] = this.taskInfos;
const [, task] = first || [];
return task?.abortSignal !== null;
}
currentUsage() {
if (this.isRunningAbortableTask()) return Infinity;
return this.taskInfos.size;
}
};
var ThreadPool = class {
skipQueue = [];
completed = 0;
start = performance.now();
inProcessPendingMessages = false;
startingUp = false;
workerFailsDuringBootstrap = false;
constructor(publicInterface, options) {
this.publicInterface = publicInterface;
this.taskQueue = options.taskQueue || new ArrayTaskQueue();
const filename = options.filename ? maybeFileURLToPath(options.filename) : null;
this.options = {
...kDefaultOptions,
...options,
filename,
maxQueue: 0
};
if (options.maxThreads !== void 0 && this.options.minThreads >= options.maxThreads) this.options.minThreads = options.maxThreads;
if (options.minThreads !== void 0 && this.options.maxThreads <= options.minThreads) this.options.maxThreads = options.minThreads;
if (options.maxQueue === "auto") this.options.maxQueue = this.options.maxThreads ** 2;
else this.options.maxQueue = options.maxQueue ?? kDefaultOptions.maxQueue;
this.workerIds = new Map(new Array(this.options.maxThreads).fill(0).map((_, i) => [i + 1, true]));
this.workers = new AsynchronouslyCreatedResourcePool(this.options.concurrentTasksPerWorker);
this.workers.onAvailable((w) => this._onWorkerAvailable(w));
this.startingUp = true;
this._ensureMinimumWorkers();
this.startingUp = false;
}
_ensureEnoughWorkersForTaskQueue() {
while (this.workers.size < this.taskQueue.size && this.workers.size < this.options.maxThreads) this._addNewWorker();
}
_ensureMaximumWorkers() {
while (this.workers.size < this.options.maxThreads) this._addNewWorker();
}
_ensureMinimumWorkers() {
while (this.workers.size < this.options.minThreads) this._addNewWorker();
}
_addNewWorker() {
const workerIds = this.workerIds;
let workerId;
workerIds.forEach((isIdAvailable, _workerId$1) => {
if (isIdAvailable && !workerId) {
workerId = _workerId$1;
workerIds.set(_workerId$1, false);
}
});
const tinypoolPrivateData = { workerId };
const worker = this.options.runtime === "child_process" ? new ProcessWorker() : new ThreadWorker();
worker.initialize({
env: this.options.env,
argv: this.options.argv,
execArgv: this.options.execArgv,
resourceLimits: this.options.resourceLimits,
workerData: [tinypoolPrivateData, this.options.workerData],
trackUnmanagedFds: this.options.trackUnmanagedFds
});
const onMessage = (message$1) => {
const { taskId, result } = message$1;
const taskInfo = workerInfo.taskInfos.get(taskId);
workerInfo.taskInfos.delete(taskId);
if (!this.shouldRecycleWorker(taskInfo)) this.workers.maybeAvailable(workerInfo);
/* istanbul ignore if */
if (taskInfo === void 0) {
const err = new Error(`Unexpected message from Worker: ${inspect(message$1)}`);
this.publicInterface.emit("error", err);
} else taskInfo.done(message$1.error, result);
this._processPendingMessages();
};
const { port1, port2 } = new MessageChannel();
const workerInfo = new WorkerInfo(worker, port1, workerId, () => workerIds.set(workerId, true), onMessage, this.options.filename, this.options.teardown);
if (this.startingUp) workerInfo.markAsReady();
const message = {
filename: this.options.filename,
name: this.options.name,
port: port2,
sharedBuffer: workerInfo.sharedBuffer,
useAtomics: this.options.useAtomics
};
worker.postMessage(message, [port2]);
worker.on("message", (message$1) => {
if (message$1.ready === true) {
port1.start();
if (workerInfo.currentUsage() === 0) workerInfo.unref();
if (!workerInfo.isReady()) workerInfo.markAsReady();
return;
}
worker.emit("error", new Error(`Unexpected message on Worker: ${inspect(message$1)}`));
});
worker.on("error", (err) => {
worker.ref = () => {};
const taskInfos = [...workerInfo.taskInfos.values()];
workerInfo.taskInfos.clear();
this._removeWorker(workerInfo);
if (workerInfo.isReady() && !this.workerFailsDuringBootstrap) this._ensureMinimumWorkers();
else this.workerFailsDuringBootstrap = true;
if (taskInfos.length > 0) for (const taskInfo of taskInfos) taskInfo.done(err, null);
else this.publicInterface.emit("error", err);
});
worker.unref();
port1.on("close", () => {
worker.ref();
});
this.workers.add(workerInfo);
}
_processPendingMessages() {
if (this.inProcessPendingMessages || !this.options.useAtomics) return;
this.inProcessPendingMessages = true;
try {
for (const workerInfo of this.workers) workerInfo.processPendingMessages();
} finally {
this.inProcessPendingMessages = false;
}
}
_removeWorker(workerInfo) {
workerInfo.freeWorkerId();
this.workers.delete(workerInfo);
return workerInfo.destroy(this.options.terminateTimeout);
}
_onWorkerAvailable(workerInfo) {
while ((this.taskQueue.size > 0 || this.skipQueue.length > 0) && workerInfo.currentUsage() < this.options.concurrentTasksPerWorker) {
const taskInfo = this.skipQueue.shift() || this.taskQueue.shift();
if (taskInfo.abortSignal && workerInfo.taskInfos.size > 0) {
this.skipQueue.push(taskInfo);
break;
}
const now = performance.now();
taskInfo.started = now;
workerInfo.postTask(taskInfo);
this._maybeDrain();
return;
}
if (workerInfo.taskInfos.size === 0 && this.workers.size > this.options.minThreads) workerInfo.idleTimeout = setTimeout(() => {
assert.strictEqual(workerInfo.taskInfos.size, 0);
if (this.workers.size > this.options.minThreads) this._removeWorker(workerInfo);
}, this.options.idleTimeout).unref();
}
runTask(task, options) {
let { filename, name } = options;
const { transferList = [], signal = null, channel } = options;
if (filename == null) filename = this.options.filename;
if (name == null) name = this.options.name;
if (typeof filename !== "string") return Promise.reject(Errors.FilenameNotProvided());
filename = maybeFileURLToPath(filename);
let resolve;
let reject;
const ret = new Promise((res, rej) => {
resolve = res;
reject = rej;
});
const taskInfo = new TaskInfo(task, transferList, filename, name, (err, result) => {
this.completed++;
if (err !== null) reject(err);
if (this.shouldRecycleWorker(taskInfo)) this._removeWorker(taskInfo.workerInfo).then(() => this._ensureMinimumWorkers()).then(() => this._ensureEnoughWorkersForTaskQueue()).then(() => resolve(result)).catch(reject);
else resolve(result);
}, signal, this.publicInterface.asyncResource.asyncId(), channel);
if (signal !== null) {
if (signal.aborted) return Promise.reject(new AbortError());
taskInfo.abortListener = () => {
reject(new AbortError());
if (taskInfo.workerInfo !== null) {
this._removeWorker(taskInfo.workerInfo);
this._ensureMinimumWorkers();
} else this.taskQueue.remove(taskInfo);
};
onabort(signal, taskInfo.abortListener);
}
if (this.taskQueue.size > 0) {
const totalCapacity = this.options.maxQueue + this.pendingCapacity();
if (this.taskQueue.size >= totalCapacity) if (this.options.maxQueue === 0) return Promise.reject(Errors.NoTaskQueueAvailable());
else return Promise.reject(Errors.TaskQueueAtLimit());
else {
if (this.workers.size < this.options.maxThreads) this._addNewWorker();
this.taskQueue.push(taskInfo);
}
return ret;
}
let workerInfo = this.workers.findAvailable();
if (workerInfo !== null && workerInfo.currentUsage() > 0 && signal) workerInfo = null;
let waitingForNewWorker = false;
if ((workerInfo === null || workerInfo.currentUsage() > 0) && this.workers.size < this.options.maxThreads) {
this._addNewWorker();
waitingForNewWorker = true;
}
if (workerInfo === null) {
if (this.options.maxQueue <= 0 && !waitingForNewWorker) return Promise.reject(Errors.NoTaskQueueAvailable());
else this.taskQueue.push(taskInfo);
return ret;
}
const now = performance.now();
taskInfo.started = now;
workerInfo.postTask(taskInfo);
this._maybeDrain();
return ret;
}
shouldRecycleWorker(taskInfo) {
if (taskInfo?.workerInfo?.shouldRecycle) return true;
if (this.options.isolateWorkers && taskInfo?.workerInfo) return true;
if (!this.options.isolateWorkers && this.options.maxMemoryLimitBeforeRecycle !== void 0 && (taskInfo?.workerInfo?.usedMemory || 0) > this.options.maxMemoryLimitBeforeRecycle) return true;
return false;
}
pendingCapacity() {
return this.workers.pendingItems.size * this.options.concurrentTasksPerWorker;
}
_maybeDrain() {
if (this.taskQueue.size === 0 && this.skipQueue.length === 0) this.publicInterface.emit("drain");
}
async destroy() {
while (this.skipQueue.length > 0) {
const taskInfo = this.skipQueue.shift();
taskInfo.done(new Error("Terminating worker thread"));
}
while (this.taskQueue.size > 0) {
const taskInfo = this.taskQueue.shift();
taskInfo.done(new Error("Terminating worker thread"));
}
const exitEvents = [];
while (this.workers.size > 0) {
const [workerInfo] = this.workers;
exitEvents.push(once(workerInfo.worker, "exit"));
this._removeWorker(workerInfo);
}
await Promise.all(exitEvents);
}
async recycleWorkers(options = {}) {
const runtimeChanged = options?.runtime && options.runtime !== this.options.runtime;
if (options?.runtime) this.options.runtime = options.runtime;
if (this.options.isolateWorkers && !runtimeChanged) return;
const exitEvents = [];
Array.from(this.workers).filter((workerInfo) => {
if (workerInfo.currentUsage() === 0) {
exitEvents.push(once(workerInfo.worker, "exit"));
this._removeWorker(workerInfo);
} else workerInfo.shouldRecycle = true;
});
await Promise.all(exitEvents);
this._ensureMinimumWorkers();
}
};
var Tinypool = class extends EventEmitterAsyncResource {
#pool;
constructor(options = {}) {
if (options.minThreads !== void 0 && options.minThreads > 0 && options.minThreads < 1) options.minThreads = Math.max(1, Math.floor(options.minThreads * cpuCount));
if (options.maxThreads !== void 0 && options.maxThreads > 0 && options.maxThreads < 1) options.maxThreads = Math.max(1, Math.floor(options.maxThreads * cpuCount));
super({
...options,
name: "Tinypool"
});
if (options.minThreads !== void 0 && options.maxThreads !== void 0 && options.minThreads > options.maxThreads) throw new RangeError("options.minThreads and options.maxThreads must not conflict");
this.#pool = new ThreadPool(this, options);
}
run(task, options = kDefaultRunOptions) {
const { transferList, filename, name, signal, runtime, channel } = options;
return this.#pool.runTask(task, {
transferList,
filename,
name,
signal,
runtime,
channel
});
}
async destroy() {
await this.#pool.destroy();
this.emitDestroy();
}
get options() {
return this.#pool.options;
}
get threads() {
const ret = [];
for (const workerInfo of this.#pool.workers) ret.push(workerInfo.worker);
return ret;
}
get queueSize() {
const pool = this.#pool;
return Math.max(pool.taskQueue.size - pool.pendingCapacity(), 0);
}
cancelPendingTasks() {
const pool = this.#pool;
pool.taskQueue.cancel();
}
async recycleWorkers(options = {}) {
await this.#pool.recycleWorkers(options);
}
get completed() {
return this.#pool.completed;
}
get duration() {
return performance.now() - this.#pool.start;
}
static get isWorkerThread() {
return process.__tinypool_state__?.isWorkerThread || false;
}
static get workerData() {
return process.__tinypool_state__?.workerData || void 0;
}
static get version() {
const { version } = JSON.parse(readFileSync(join(__dirname, "../package.json"), "utf-8"));
return version;
}
static move(val) {
if (val != null && typeof val === "object" && typeof val !== "function") {
if (!isTransferable(val)) if (types.isArrayBufferView(val)) val = new ArrayBufferViewTransferable(val);
else val = new DirectlyTransferable(val);
markMovable(val);
}
return val;
}
static get transferableSymbol() {
return kTransferable;
}
static get valueSymbol() {
return kValue;
}
static get queueOptionsSymbol() {
return kQueueOptions;
}
};
const _workerId = process.__tinypool_state__?.workerId;
var src_default = Tinypool;
//#endregion
export { Tinypool, src_default as default, isMovable, isTaskQueue, isTransferable, kFieldCount, kQueueOptions, kRequestCountField, kResponseCountField, kTransferable, kValue, markMovable, _workerId as workerId };

View File

@@ -0,0 +1,38 @@
import { pathToFileURL } from "node:url";
//#region src/entry/utils.ts
let importESMCached;
function getImportESM() {
if (importESMCached === void 0) importESMCached = new Function("specifier", "return import(specifier)");
return importESMCached;
}
const handlerCache = new Map();
async function getHandler(filename, name) {
let handler = handlerCache.get(`${filename}/${name}`);
if (handler !== void 0) return handler;
try {
const handlerModule = await import(filename);
handler = typeof handlerModule.default !== "function" && handlerModule.default || handlerModule;
if (typeof handler !== "function") handler = await handler[name];
} catch {}
if (typeof handler !== "function") {
handler = await getImportESM()(pathToFileURL(filename).href);
if (typeof handler !== "function") handler = await handler[name];
}
if (typeof handler !== "function") return null;
if (handlerCache.size > 1e3) {
const [handler$1] = handlerCache;
const key = handler$1[0];
handlerCache.delete(key);
}
handlerCache.set(`${filename}/${name}`, handler);
return handler;
}
function throwInNextTick(error) {
process.nextTick(() => {
throw error;
});
}
//#endregion
export { getHandler, throwInNextTick };

View File

@@ -0,0 +1,10 @@
//#region src/utils.ts
function stdout() {
return console._stdout || process.stdout || void 0;
}
function stderr() {
return console._stderr || process.stderr || void 0;
}
//#endregion
export { stderr, stdout };

View File

@@ -0,0 +1,39 @@
{
"name": "tinypool",
"type": "module",
"version": "1.1.1",
"packageManager": "pnpm@9.0.6",
"description": "A minimal and tiny Node.js Worker Thread Pool implementation, a fork of piscina, but with fewer features",
"license": "MIT",
"homepage": "https://github.com/tinylibs/tinypool#readme",
"repository": {
"type": "git",
"url": "https://github.com/tinylibs/tinypool.git"
},
"bugs": {
"url": "https://github.com/tinylibs/tinypool/issues"
},
"keywords": [
"fast",
"worker threads",
"thread pool"
],
"exports": {
".": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"./package.json": "./package.json"
},
"main": "./dist/index.js",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"files": [
"dist"
],
"pnpm": {
"overrides": {
"vitest>tinypool": "link:./"
}
}
}

217
node_modules/@rspack/core/compiled/watchpack/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,217 @@
/// <reference types="node" />
import { EventEmitter } from 'events';
// @ts-ignore
import fs from 'graceful-fs';
declare class DirectoryWatcher extends EventEmitter {
options: Watchpack.WatcherOptions;
directories: {
[path: string]: Watcher | true;
};
files: {
[path: string]: [number, number];
};
initialScan: boolean;
initialScanRemoved: string[];
nestedWatching: boolean;
path: string;
refs: number;
watcher: fs.FSWatcher;
watchers: {
[path: string]: Watcher[];
};
constructor(directoryPath: string, options: Watchpack.WatcherOptions);
setFileTime(filePath: string, mtime: number, initial: boolean, type?: string | boolean): void;
setDirectory(directoryPath: string, exist: boolean, initial: boolean): void;
createNestedWatcher(directoryPath: string): void;
setNestedWatching(flag: boolean): void;
watch(filePath: string, startTime: number): Watcher;
onFileAdded(filePath: string, stat: fs.Stats): void;
onDirectoryAdded(directoryPath: string): void;
onChange(filePath: string, stat: fs.Stats): void;
onFileUnlinked(filePath: string): void;
onDirectoryUnlinked(directoryPath: string): void;
onWatcherError(): void;
doInitialScan(): void;
getTimes(): {
[path: string]: number;
};
close(): void;
}
declare class Watcher extends EventEmitter {
data: number;
directoryWatcher: DirectoryWatcher;
path: string;
startTime: number;
constructor(directoryWatcher: DirectoryWatcher, filePath: string, startTime: number);
checkStartTime(mtime: number, initial: boolean): boolean;
close(): void;
}
interface Entry {
/** A point in time at which is it safe to say all changes happened before that */
safeTime: number;
/** Only for file entries: the last modified timestamp of the file */
timestamp: number;
}
declare class Watchpack extends EventEmitter {
aggregatedChanges: Set<string>;
aggregatedRemovals: Set<string>;
aggregateTimeout: number;
dirWatchers: Watcher[];
fileWatchers: Watcher[];
/** Last modified times for files by path */
mtimes: {
[path: string]: number;
};
options: Watchpack.WatchOptions;
paused: boolean;
watcherOptions: Watchpack.WatcherOptions;
constructor(options: Watchpack.WatchOptions);
/**
* Starts watching these files and directories
* Calling this again will override the files and directories
*/
watch(options: {
/**
* Can be files or directories
* For files: content and existence changes are tracked
* For directories: only existence and timestamp changes are tracked
*/
files?: Iterable<string>;
/**
* Can only be directories
* Directory content (and content of children, ...) and existence changes are tracked.
* For files: content and existence changes are tracked
* Assumed to exist, when directory is not found without further information a remove event is emitted
*/
directories?: Iterable<string>;
/**
* Can be files or directories
* Only existence changes are tracked
* Assued to not exist, no remove event is emitted when not found initially
*/
missing?: Iterable<string>;
startTime?: number;
}): void;
on(
eventName: "change",
listener: (
/** The changed file or directory */
filePath: string,
/** The last modified time of the changed file */
modifiedTime: number,
/** Textual information how this change was detected */
explanation: string,
) => void,
): this;
on(
eventName: "remove",
listener: (
/** The removed file or directory */
filePath: string,
/** Textual information how this change was detected */
explanation: string,
) => void,
): this;
on(
eventName: "aggregated",
listener: (
/** Set of all changed files */
changes: Set<string>,
/** Set of all removed files */
removals: Set<string>,
) => void,
): this;
/**
* Stops emitting events, but keeps watchers open
* The next "watch" call can reuse the watchers
* The watcher will keep aggregating events which can be received with `getAggregated()`
*/
pause(): void;
/**
* Stops emitting events and closes all watchers
*/
close(): void;
/**
* Returns the current aggregated info and removes that from the watcher
* The next aggregated event won't include that info and will only emitted when futher changes happen
* Can be used when paused
*/
getAggregated(): {
changes: Set<string>;
removals: Set<string>;
};
/**
* Collects time info objects for all known files and directories
* This includes info from files not directly watched
*/
collectTimeInfoEntries(fileInfoEntries: Map<string, Entry>, directoryInfoEntries: Map<string, Entry>): void;
/**
* Returns a `Map` with all known time info objects for files and directories
* Similar to `collectTimeInfoEntries()` but returns a single map with all entries
*/
getTimeInfoEntries(): Map<string, Entry>;
/**
* Returns an object with all known change times for files
* This include timestamps from files not directly watched
* Key: absolute path, value: timestamp as number
* @deprecated
*/
getTimes(): {
[path: string]: number;
};
_fileWatcher(file: string, watcher: Watcher): Watcher;
_dirWatcher(item: string, watcher: Watcher): Watcher;
_onChange(item: string, mtime: number, file?: string): void;
_onTimeout(): void;
}
declare namespace Watchpack {
interface WatcherOptions {
ignored?: string[] | string | RegExp | ((path: string) => boolean) | undefined;
poll?: boolean | number | undefined;
followSymlinks?: boolean;
}
interface WatchOptions extends WatcherOptions {
aggregateTimeout?: number | undefined;
}
}
export { Watchpack as default };

3124
node_modules/@rspack/core/compiled/watchpack/index.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

20
node_modules/@rspack/core/compiled/watchpack/license generated vendored Normal file
View File

@@ -0,0 +1,20 @@
Copyright JS Foundation and other contributors
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1 @@
{"name":"watchpack","author":"Tobias Koppers @sokra","version":"2.4.4","license":"MIT","types":"index.d.ts","type":"commonjs"}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2017 JS Foundation and other contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1 @@
{"name":"webpack-sources","author":"Tobias Koppers @sokra","version":"3.3.3","license":"MIT","types":"types.d.ts","type":"commonjs"}

View File

@@ -0,0 +1,458 @@
/*
* This file was automatically generated.
* DO NOT MODIFY BY HAND.
* Run `yarn fix:special` to update
*/
import { Buffer } from "buffer";
declare interface BufferEntry {
map?: null | RawSourceMap;
bufferedMap?: null | BufferedMap;
}
declare interface BufferedMap {
/**
* version
*/
version: number;
/**
* sources
*/
sources: string[];
/**
* name
*/
names: string[];
/**
* source root
*/
sourceRoot?: string;
/**
* sources content
*/
sourcesContent?: ("" | Buffer)[];
/**
* mappings
*/
mappings?: Buffer;
/**
* file
*/
file: string;
}
declare interface CachedData {
/**
* source
*/
source?: boolean;
/**
* buffer
*/
buffer: Buffer;
/**
* size
*/
size?: number;
/**
* maps
*/
maps: Map<string, BufferEntry>;
/**
* hash
*/
hash?: (string | Buffer)[];
}
declare class CachedSource extends Source {
constructor(source: Source | (() => Source), cachedData?: CachedData);
getCachedData(): CachedData;
originalLazy(): Source | (() => Source);
original(): Source;
streamChunks(
options: StreamChunksOptions,
onChunk: (
chunk: undefined | string,
generatedLine: number,
generatedColumn: number,
sourceIndex: number,
originalLine: number,
originalColumn: number,
nameIndex: number,
) => void,
onSource: (
sourceIndex: number,
source: null | string,
sourceContent?: string,
) => void,
onName: (nameIndex: number, name: string) => void,
): GeneratedSourceInfo;
}
declare class CompatSource extends Source {
constructor(sourceLike: SourceLike);
static from(sourceLike: SourceLike): Source;
}
declare class ConcatSource extends Source {
constructor(...args: ConcatSourceChild[]);
getChildren(): Source[];
add(item: ConcatSourceChild): void;
addAllSkipOptimizing(items: ConcatSourceChild[]): void;
streamChunks(
options: StreamChunksOptions,
onChunk: (
chunk: undefined | string,
generatedLine: number,
generatedColumn: number,
sourceIndex: number,
originalLine: number,
originalColumn: number,
nameIndex: number,
) => void,
onSource: (
sourceIndex: number,
source: null | string,
sourceContent?: string,
) => void,
onName: (nameIndex: number, name: string) => void,
): GeneratedSourceInfo;
}
type ConcatSourceChild = string | Source | SourceLike;
declare interface GeneratedSourceInfo {
/**
* generated line
*/
generatedLine?: number;
/**
* generated column
*/
generatedColumn?: number;
/**
* source
*/
source?: string;
}
declare interface HashLike {
/**
* make hash update
*/
update: (data: string | Buffer, inputEncoding?: string) => HashLike;
/**
* get hash digest
*/
digest: (encoding?: string) => string | Buffer;
}
declare interface MapOptions {
/**
* need columns?
*/
columns?: boolean;
/**
* is module
*/
module?: boolean;
}
declare class OriginalSource extends Source {
constructor(value: string | Buffer, name: string);
getName(): string;
streamChunks(
options: StreamChunksOptions,
onChunk: (
chunk: undefined | string,
generatedLine: number,
generatedColumn: number,
sourceIndex: number,
originalLine: number,
originalColumn: number,
nameIndex: number,
) => void,
onSource: (
sourceIndex: number,
source: null | string,
sourceContent?: string,
) => void,
_onName: (nameIndex: number, name: string) => void,
): GeneratedSourceInfo;
}
declare class PrefixSource extends Source {
constructor(prefix: string, source: string | Source | Buffer);
getPrefix(): string;
original(): Source;
streamChunks(
options: StreamChunksOptions,
onChunk: (
chunk: undefined | string,
generatedLine: number,
generatedColumn: number,
sourceIndex: number,
originalLine: number,
originalColumn: number,
nameIndex: number,
) => void,
onSource: (
sourceIndex: number,
source: null | string,
sourceContent?: string,
) => void,
onName: (nameIndex: number, name: string) => void,
): GeneratedSourceInfo;
}
declare class RawSource extends Source {
constructor(value: string | Buffer, convertToString?: boolean);
isBuffer(): boolean;
streamChunks(
options: StreamChunksOptions,
onChunk: (
chunk: undefined | string,
generatedLine: number,
generatedColumn: number,
sourceIndex: number,
originalLine: number,
originalColumn: number,
nameIndex: number,
) => void,
onSource: (
sourceIndex: number,
source: null | string,
sourceContent?: string,
) => void,
onName: (nameIndex: number, name: string) => void,
): GeneratedSourceInfo;
}
declare interface RawSourceMap {
/**
* version
*/
version: number;
/**
* sources
*/
sources: string[];
/**
* names
*/
names: string[];
/**
* source root
*/
sourceRoot?: string;
/**
* sources content
*/
sourcesContent?: string[];
/**
* mappings
*/
mappings: string;
/**
* file
*/
file: string;
/**
* debug id
*/
debugId?: string;
/**
* ignore list
*/
ignoreList?: number[];
}
declare class ReplaceSource extends Source {
constructor(source: Source, name?: string);
getName(): undefined | string;
getReplacements(): Replacement[];
replace(start: number, end: number, newValue: string, name?: string): void;
insert(pos: number, newValue: string, name?: string): void;
original(): Source;
streamChunks(
options: StreamChunksOptions,
onChunk: (
chunk: undefined | string,
generatedLine: number,
generatedColumn: number,
sourceIndex: number,
originalLine: number,
originalColumn: number,
nameIndex: number,
) => void,
onSource: (
sourceIndex: number,
source: null | string,
sourceContent?: string,
) => void,
onName: (nameIndex: number, name: string) => void,
): GeneratedSourceInfo;
static Replacement: typeof Replacement;
}
declare class Replacement {
constructor(start: number, end: number, content: string, name?: string);
start: number;
end: number;
content: string;
name?: string;
index?: number;
}
declare class SizeOnlySource extends Source {
constructor(size: number);
}
declare class Source {
constructor();
source(): SourceValue;
buffer(): Buffer;
size(): number;
map(options?: MapOptions): null | RawSourceMap;
sourceAndMap(options?: MapOptions): SourceAndMap;
updateHash(hash: HashLike): void;
}
declare interface SourceAndMap {
/**
* source
*/
source: SourceValue;
/**
* map
*/
map: null | RawSourceMap;
}
declare interface SourceLike {
/**
* source
*/
source: () => SourceValue;
/**
* buffer
*/
buffer?: () => Buffer;
/**
* size
*/
size?: () => number;
/**
* map
*/
map?: (options?: MapOptions) => null | RawSourceMap;
/**
* source and map
*/
sourceAndMap?: (options?: MapOptions) => SourceAndMap;
/**
* hash updater
*/
updateHash?: (hash: HashLike) => void;
}
declare class SourceMapSource extends Source {
constructor(
value: string | Buffer,
name: string,
sourceMap?: string | RawSourceMap | Buffer,
originalSource?: string | Buffer,
innerSourceMap?: string | RawSourceMap | Buffer,
removeOriginalSource?: boolean,
);
getArgsAsBuffers(): [
Buffer,
string,
Buffer,
undefined | Buffer,
undefined | Buffer,
undefined | boolean,
];
streamChunks(
options: StreamChunksOptions,
onChunk: (
chunk: undefined | string,
generatedLine: number,
generatedColumn: number,
sourceIndex: number,
originalLine: number,
originalColumn: number,
nameIndex: number,
) => void,
onSource: (
sourceIndex: number,
source: null | string,
sourceContent?: string,
) => void,
onName: (nameIndex: number, name: string) => void,
): GeneratedSourceInfo;
}
type SourceValue = string | Buffer;
declare interface StreamChunksOptions {
source?: boolean;
finalSource?: boolean;
columns?: boolean;
}
export namespace util {
export namespace stringBufferUtils {
export let disableDualStringBufferCaching: () => void;
export let enableDualStringBufferCaching: () => void;
export let internString: (str: string) => string;
export let isDualStringBufferCachingEnabled: () => boolean;
export let enterStringInterningRange: () => void;
export let exitStringInterningRange: () => void;
}
}
export type OnChunk = (
chunk: undefined | string,
generatedLine: number,
generatedColumn: number,
sourceIndex: number,
originalLine: number,
originalColumn: number,
nameIndex: number,
) => void;
export type OnName = (nameIndex: number, name: string) => void;
export type OnSource = (
sourceIndex: number,
source: null | string,
sourceContent?: string,
) => void;
export {
Source,
RawSource,
OriginalSource,
SourceMapSource,
CachedSource,
ConcatSource,
ReplaceSource,
PrefixSource,
SizeOnlySource,
CompatSource,
CachedData,
SourceLike,
ConcatSourceChild,
Replacement,
HashLike,
MapOptions,
RawSourceMap,
SourceAndMap,
SourceValue,
GeneratedSourceInfo,
StreamChunksOptions,
};

17
node_modules/@rspack/core/dist/BuildInfo.d.ts generated vendored Normal file
View File

@@ -0,0 +1,17 @@
import binding from "@rspack/binding";
import type { Source } from "../compiled/webpack-sources";
declare const $assets: unique symbol;
declare module "@rspack/binding" {
interface Assets {
[$assets]: Record<string, Source>;
}
interface KnownBuildInfo {
assets: Record<string, Source>;
fileDependencies: Set<string>;
contextDependencies: Set<string>;
missingDependencies: Set<string>;
buildDependencies: Set<string>;
}
}
export type { BuildInfo } from "@rspack/binding";
export declare const commitCustomFieldsToRust: (buildInfo: binding.BuildInfo) => void;

16
node_modules/@rspack/core/dist/Chunk.d.ts generated vendored Normal file
View File

@@ -0,0 +1,16 @@
import { type ChunkGroup } from "@rspack/binding";
interface ChunkMaps {
hash: Record<string | number, string>;
contentHash: Record<string | number, Record<string, string>>;
name: Record<string | number, string>;
}
declare module "@rspack/binding" {
interface Chunk {
readonly files: ReadonlySet<string>;
readonly runtime: ReadonlySet<string>;
readonly auxiliaryFiles: ReadonlySet<string>;
readonly groupsIterable: ReadonlySet<ChunkGroup>;
getChunkMaps(realHash: boolean): ChunkMaps;
}
}
export { Chunk } from "@rspack/binding";

9
node_modules/@rspack/core/dist/ChunkGraph.d.ts generated vendored Normal file
View File

@@ -0,0 +1,9 @@
import type { RuntimeSpec } from "./util/runtime";
declare module "@rspack/binding" {
interface ChunkGraph {
getModuleChunksIterable(module: Module): Iterable<Chunk>;
getOrderedChunkModulesIterable(chunk: Chunk, compareFn: (a: Module, b: Module) => number): Iterable<Module>;
getModuleHash(module: Module, runtime: RuntimeSpec): string | null;
}
}
export { ChunkGraph } from "@rspack/binding";

12
node_modules/@rspack/core/dist/Chunks.d.ts generated vendored Normal file
View File

@@ -0,0 +1,12 @@
import { Chunks } from "@rspack/binding";
declare module "@rspack/binding" {
interface Chunks {
[Symbol.iterator](): SetIterator<Chunk>;
entries(): SetIterator<[Chunk, Chunk]>;
values(): SetIterator<Chunk>;
keys(): SetIterator<Chunk>;
forEach(callbackfn: (value: Chunk, value2: Chunk, set: ReadonlySet<Chunk>) => void, thisArg?: any): void;
has(value: Chunk): boolean;
}
}
export default Chunks;

View File

@@ -0,0 +1 @@
export {};

417
node_modules/@rspack/core/dist/Compilation.d.ts generated vendored Normal file
View File

@@ -0,0 +1,417 @@
/**
* The following code is modified based on
* https://github.com/webpack/webpack/blob/4b4ca3bb53f36a5b8fc6bc1bd976ed7af161bd80/lib/Compilation.js
*
* MIT Licensed
* Author Tobias Koppers @sokra
* Copyright (c) JS Foundation and other contributors
* https://github.com/webpack/webpack/blob/main/LICENSE
*/
import type { AssetInfo, ChunkGroup, Dependency, ExternalObject, JsCompilation, JsRuntimeModule } from "@rspack/binding";
import binding from "@rspack/binding";
export type { AssetInfo } from "@rspack/binding";
import * as liteTapable from "@rspack/lite-tapable";
import type { Source } from "../compiled/webpack-sources";
import type { EntryOptions, EntryPlugin } from "./builtin-plugin";
import type { Chunk } from "./Chunk";
import type { ChunkGraph } from "./ChunkGraph";
import type { Compiler } from "./Compiler";
import type { ContextModuleFactory } from "./ContextModuleFactory";
import type { OutputNormalized, RspackOptionsNormalized, RspackPluginInstance, StatsOptions, StatsValue } from "./config";
import type { Entrypoint } from "./Entrypoint";
import WebpackError from "./lib/WebpackError";
import { Logger } from "./logging/Logger";
import type { Module } from "./Module";
import ModuleGraph from "./ModuleGraph";
import type { NormalModuleCompilationHooks } from "./NormalModule";
import type { NormalModuleFactory } from "./NormalModuleFactory";
import type { ResolverFactory } from "./ResolverFactory";
import type { RspackError } from "./RspackError";
import { RuntimeModule } from "./RuntimeModule";
import { Stats, type StatsAsset, type StatsError, type StatsModule } from "./Stats";
import { StatsFactory } from "./stats/StatsFactory";
import { StatsPrinter } from "./stats/StatsPrinter";
import type { InputFileSystem } from "./util/fs";
import type Hash from "./util/hash";
import "./Chunk";
import "./Chunks";
import "./ChunkGraph";
import "./CodeGenerationResults";
import type { CodeGenerationResult } from "./taps/compilation";
export type Assets = Record<string, Source>;
export interface Asset {
name: string;
source: Source;
info: AssetInfo;
}
export type ChunkPathData = {
id?: string;
name?: string;
hash?: string;
contentHash?: Record<string, string>;
};
export type PathData = {
filename?: string;
hash?: string;
contentHash?: string;
runtime?: string;
url?: string;
id?: string;
chunk?: Chunk | ChunkPathData;
contentHashType?: string;
};
export interface LogEntry {
type: string;
args: any[];
time?: number;
trace?: string[];
}
export interface CompilationParams {
normalModuleFactory: NormalModuleFactory;
contextModuleFactory: ContextModuleFactory;
}
export interface KnownCreateStatsOptionsContext {
forToString?: boolean;
}
export interface ExecuteModuleArgument {
codeGenerationResult: CodeGenerationResult;
moduleObject: {
id: string;
exports: any;
loaded: boolean;
error?: Error;
};
}
export interface ExecuteModuleContext {
[key: string]: (id: string) => any;
}
export interface KnownNormalizedStatsOptions {
context: string;
chunksSort: string;
modulesSort: string;
chunkModulesSort: string;
nestedModulesSort: string;
assetsSort: string;
ids: boolean;
cachedAssets: boolean;
groupAssetsByEmitStatus: boolean;
groupAssetsByPath: boolean;
groupAssetsByExtension: boolean;
assetsSpace: number;
excludeAssets: ((value: string, asset: StatsAsset) => boolean)[];
excludeModules: ((name: string, module: StatsModule, type: "module" | "chunk" | "root-of-chunk" | "nested") => boolean)[];
warningsFilter: ((warning: StatsError, textValue: string) => boolean)[];
cachedModules: boolean;
orphanModules: boolean;
dependentModules: boolean;
runtimeModules: boolean;
groupModulesByCacheStatus: boolean;
groupModulesByLayer: boolean;
groupModulesByAttributes: boolean;
groupModulesByPath: boolean;
groupModulesByExtension: boolean;
groupModulesByType: boolean;
entrypoints: boolean | "auto";
chunkGroups: boolean;
chunkGroupAuxiliary: boolean;
chunkGroupChildren: boolean;
chunkGroupMaxAssets: number;
modulesSpace: number;
chunkModulesSpace: number;
nestedModulesSpace: number;
logging: false | "none" | "error" | "warn" | "info" | "log" | "verbose";
loggingDebug: ((value: string) => boolean)[];
loggingTrace: boolean;
chunkModules: boolean;
chunkRelations: boolean;
reasons: boolean;
moduleAssets: boolean;
nestedModules: boolean;
source: boolean;
usedExports: boolean;
providedExports: boolean;
optimizationBailout: boolean;
depth: boolean;
assets: boolean;
chunks: boolean;
errors: boolean;
errorsCount: boolean;
hash: boolean;
modules: boolean;
warnings: boolean;
warningsCount: boolean;
}
export type CreateStatsOptionsContext = KnownCreateStatsOptionsContext & Record<string, any>;
export type NormalizedStatsOptions = KnownNormalizedStatsOptions & Omit<StatsOptions, keyof KnownNormalizedStatsOptions> & Record<string, any>;
export declare const checkCompilation: (compilation: Compilation) => void;
export declare class Compilation {
#private;
hooks: Readonly<{
processAssets: liteTapable.AsyncSeriesHook<Assets>;
afterProcessAssets: liteTapable.SyncHook<Assets>;
childCompiler: liteTapable.SyncHook<[Compiler, string, number]>;
log: liteTapable.SyncBailHook<[string, LogEntry], true>;
additionalAssets: any;
optimizeModules: liteTapable.SyncBailHook<Iterable<Module>, void>;
afterOptimizeModules: liteTapable.SyncHook<Iterable<Module>>;
optimizeTree: liteTapable.AsyncSeriesHook<[
Iterable<Chunk>,
Iterable<Module>
]>;
optimizeChunkModules: liteTapable.AsyncSeriesBailHook<[
Iterable<Chunk>,
Iterable<Module>
], void>;
finishModules: liteTapable.AsyncSeriesHook<[Iterable<Module>], void>;
chunkHash: liteTapable.SyncHook<[Chunk, Hash]>;
chunkAsset: liteTapable.SyncHook<[Chunk, string]>;
processWarnings: liteTapable.SyncWaterfallHook<[WebpackError[]]>;
succeedModule: liteTapable.SyncHook<[Module]>;
stillValidModule: liteTapable.SyncHook<[Module]>;
statsPreset: liteTapable.HookMap<liteTapable.SyncHook<[Partial<StatsOptions>, CreateStatsOptionsContext]>>;
statsNormalize: liteTapable.SyncHook<[
Partial<StatsOptions>,
CreateStatsOptionsContext
]>;
statsFactory: liteTapable.SyncHook<[StatsFactory, StatsOptions]>;
statsPrinter: liteTapable.SyncHook<[StatsPrinter, StatsOptions]>;
buildModule: liteTapable.SyncHook<[Module]>;
executeModule: liteTapable.SyncHook<[
ExecuteModuleArgument,
ExecuteModuleContext
]>;
additionalTreeRuntimeRequirements: liteTapable.SyncHook<[
Chunk,
Set<string>
]>;
runtimeRequirementInTree: liteTapable.HookMap<liteTapable.SyncBailHook<[Chunk, Set<string>], void>>;
runtimeModule: liteTapable.SyncHook<[JsRuntimeModule, Chunk]>;
seal: liteTapable.SyncHook<[]>;
afterSeal: liteTapable.AsyncSeriesHook<[], void>;
needAdditionalPass: liteTapable.SyncBailHook<[], boolean>;
}>;
name?: string;
startTime?: number;
endTime?: number;
compiler: Compiler;
resolverFactory: ResolverFactory;
inputFileSystem: InputFileSystem | null;
options: RspackOptionsNormalized;
outputOptions: OutputNormalized;
logging: Map<string, LogEntry[]>;
childrenCounters: Record<string, number>;
children: Compilation[];
chunkGraph: ChunkGraph;
moduleGraph: ModuleGraph;
fileSystemInfo: {
createSnapshot(): null;
};
needAdditionalPass: boolean;
[binding.COMPILATION_HOOKS_MAP_SYMBOL]: WeakMap<Compilation, NormalModuleCompilationHooks>;
constructor(compiler: Compiler, inner: JsCompilation);
get hash(): Readonly<string | null>;
get fullHash(): Readonly<string | null>;
/**
* Get a map of all assets.
*/
get assets(): Record<string, Source>;
/**
* Get a map of all entrypoints.
*/
get entrypoints(): ReadonlyMap<string, Entrypoint>;
get chunkGroups(): readonly ChunkGroup[];
/**
* Get the named chunk groups.
*
* Note: This is a proxy for webpack internal API, only method `get`, `keys`, `values` and `entries` are supported now.
*/
get namedChunkGroups(): ReadonlyMap<string, Readonly<ChunkGroup>>;
get modules(): ReadonlySet<Module>;
get builtModules(): ReadonlySet<Module>;
get chunks(): ReadonlySet<Chunk>;
/**
* Get the named chunks.
*
* Note: This is a proxy for webpack internal API, only method `get`, `keys`, `values` and `entries` are supported now.
*/
get namedChunks(): ReadonlyMap<string, Readonly<binding.Chunk>>;
get entries(): Map<string, EntryData>;
get codeGenerationResults(): binding.CodeGenerationResults;
getCache(name: string): import("./lib/CacheFacade").CacheFacade;
createStatsOptions(statsValue: StatsValue | undefined, context?: CreateStatsOptionsContext): NormalizedStatsOptions;
createStatsFactory(options: StatsOptions): StatsFactory;
createStatsPrinter(options: StatsOptions): StatsPrinter;
/**
* Update an existing asset. Trying to update an asset that doesn't exist will throw an error.
*/
updateAsset(filename: string, newSourceOrFunction: Source | ((source: Source) => Source), assetInfoUpdateOrFunction?: AssetInfo | ((assetInfo: AssetInfo) => AssetInfo | undefined)): void;
/**
* Emit an not existing asset. Trying to emit an asset that already exists will throw an error.
*
* @param file - file name
* @param source - asset source
* @param assetInfo - extra asset information
*/
emitAsset(filename: string, source: Source, assetInfo?: AssetInfo): void;
deleteAsset(filename: string): void;
renameAsset(filename: string, newFilename: string): void;
/**
* Get an array of Asset
*/
getAssets(): readonly Asset[];
getAsset(name: string): Readonly<Asset> | void;
/**
* Note: This is not a webpack public API, maybe removed in future.
*
* @internal
*/
__internal__pushRspackDiagnostic(diagnostic: binding.JsRspackDiagnostic): void;
/**
* Note: This is not a webpack public API, maybe removed in future.
*
* @internal
*/
__internal__pushDiagnostic(diagnostic: ExternalObject<"Diagnostic">): void;
/**
* Note: This is not a webpack public API, maybe removed in future.
*
* @internal
*/
__internal__pushDiagnostics(diagnostics: ExternalObject<"Diagnostic[]">): void;
get errors(): RspackError[];
set errors(errors: RspackError[]);
get warnings(): RspackError[];
set warnings(warnings: RspackError[]);
getPath(filename: string, data?: PathData): string;
getPathWithInfo(filename: string, data?: PathData): binding.PathWithInfo;
getAssetPath(filename: string, data?: PathData): string;
getAssetPathWithInfo(filename: string, data?: PathData): binding.PathWithInfo;
getLogger(name: string | (() => string)): Logger;
fileDependencies: {
[Symbol.iterator](): Generator<string, void, unknown>;
has(dep: string): boolean;
add: (dep: string) => void;
addAll: (deps: Iterable<string>) => void;
};
get __internal__addedFileDependencies(): string[];
get __internal__removedFileDependencies(): string[];
get __internal__addedContextDependencies(): string[];
get __internal__removedContextDependencies(): string[];
get __internal__addedMissingDependencies(): string[];
get __internal__removedMissingDependencies(): string[];
contextDependencies: {
[Symbol.iterator](): Generator<string, void, unknown>;
has(dep: string): boolean;
add: (dep: string) => void;
addAll: (deps: Iterable<string>) => void;
};
missingDependencies: {
[Symbol.iterator](): Generator<string, void, unknown>;
has(dep: string): boolean;
add: (dep: string) => void;
addAll: (deps: Iterable<string>) => void;
};
buildDependencies: {
[Symbol.iterator](): Generator<string, void, unknown>;
has(dep: string): boolean;
add: (dep: string) => void;
addAll: (deps: Iterable<string>) => void;
};
getStats(): Stats;
createChildCompiler(name: string, outputOptions: OutputNormalized, plugins: RspackPluginInstance[]): Compiler;
rebuildModule(module: Module, f: (err: Error | null, module: Module | null) => void): void;
addRuntimeModule(chunk: Chunk, runtimeModule: RuntimeModule): void;
addInclude(context: string, dependency: ReturnType<typeof EntryPlugin.createDependency>, options: EntryOptions, callback: (err?: null | WebpackError, module?: Module) => void): void;
addEntry(context: string, dependency: ReturnType<typeof EntryPlugin.createDependency>, optionsOrName: EntryOptions | string, callback: (err?: null | WebpackError, module?: Module) => void): void;
getWarnings(): WebpackError[];
getErrors(): WebpackError[];
/**
* Get the `Source` of a given asset filename.
*
* Note: This is not a webpack public API, maybe removed in the future.
*
* @internal
*/
__internal__getAssetSource(filename: string): Source | void;
/**
* Set the `Source` of an given asset filename.
*
* Note: This is not a webpack public API, maybe removed in future.
*
* @internal
*/
__internal__setAssetSource(filename: string, source: Source): void;
/**
* Delete the `Source` of an given asset filename.
*
* Note: This is not a webpack public API, maybe removed in future.
*
* @internal
*/
__internal__deleteAssetSource(filename: string): void;
/**
* Get a list of asset filenames.
*
* Note: This is not a webpack public API, maybe removed in future.
*
* @internal
*/
__internal__getAssetFilenames(): string[];
/**
* Test if an asset exists.
*
* Note: This is not a webpack public API, maybe removed in future.
*
* @internal
*/
__internal__hasAsset(name: string): boolean;
/**
* Note: This is not a webpack public API, maybe removed in future.
*
* @internal
*/
__internal_getInner(): JsCompilation;
get __internal__shutdown(): boolean;
set __internal__shutdown(shutdown: boolean);
seal(): void;
unseal(): void;
static PROCESS_ASSETS_STAGE_ADDITIONAL: number;
static PROCESS_ASSETS_STAGE_PRE_PROCESS: number;
static PROCESS_ASSETS_STAGE_DERIVED: number;
static PROCESS_ASSETS_STAGE_ADDITIONS: number;
static PROCESS_ASSETS_STAGE_NONE: number;
static PROCESS_ASSETS_STAGE_OPTIMIZE: number;
static PROCESS_ASSETS_STAGE_OPTIMIZE_COUNT: number;
static PROCESS_ASSETS_STAGE_OPTIMIZE_COMPATIBILITY: number;
static PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE: number;
static PROCESS_ASSETS_STAGE_DEV_TOOLING: number;
static PROCESS_ASSETS_STAGE_OPTIMIZE_INLINE: number;
static PROCESS_ASSETS_STAGE_SUMMARIZE: number;
static PROCESS_ASSETS_STAGE_OPTIMIZE_HASH: number;
static PROCESS_ASSETS_STAGE_OPTIMIZE_TRANSFER: number;
static PROCESS_ASSETS_STAGE_ANALYSE: number;
static PROCESS_ASSETS_STAGE_REPORT: number;
}
export declare class EntryData {
dependencies: Dependency[];
includeDependencies: Dependency[];
options: binding.JsEntryOptions;
static __from_binding(binding: binding.JsEntryData): EntryData;
private constructor();
}
export declare class Entries implements Map<string, EntryData> {
#private;
constructor(data: binding.JsEntries);
clear(): void;
forEach(callback: (value: EntryData, key: string, map: Map<string, EntryData>) => void, thisArg?: any): void;
get size(): number;
entries(): ReturnType<Map<string, EntryData>["entries"]>;
values(): ReturnType<Map<string, EntryData>["values"]>;
[Symbol.iterator](): ReturnType<Map<string, EntryData>["entries"]>;
readonly [Symbol.toStringTag] = "Map";
has(key: string): boolean;
set(key: string, value: EntryData): this;
delete(key: string): boolean;
get(key: string): EntryData | undefined;
keys(): ReturnType<Map<string, EntryData>["keys"]>;
}

223
node_modules/@rspack/core/dist/Compiler.d.ts generated vendored Normal file
View File

@@ -0,0 +1,223 @@
/**
* The following code is modified based on
* https://github.com/webpack/webpack/blob/4b4ca3bb53f36a5b8fc6bc1bd976ed7af161bd80/lib/Compiler.js
*
* MIT Licensed
* Author Tobias Koppers @sokra
* Copyright (c) JS Foundation and other contributors
* https://github.com/webpack/webpack/blob/main/LICENSE
*/
import type binding from "@rspack/binding";
import * as liteTapable from "@rspack/lite-tapable";
import type Watchpack from "../compiled/watchpack";
import type { Source } from "../compiled/webpack-sources";
import type { Chunk } from "./Chunk";
import type { CompilationParams } from "./Compilation";
import { Compilation } from "./Compilation";
import { ContextModuleFactory } from "./ContextModuleFactory";
import type { EntryNormalized, OutputNormalized, RspackOptionsNormalized, RspackPluginInstance } from "./config";
import type { FileSystemInfoEntry } from "./FileSystemInfo";
import { rspack } from "./index";
import Cache from "./lib/Cache";
import CacheFacade from "./lib/CacheFacade";
import { Logger } from "./logging/Logger";
import { NormalModuleFactory } from "./NormalModuleFactory";
import { ResolverFactory } from "./ResolverFactory";
import { RuleSetCompiler } from "./RuleSetCompiler";
import { Stats } from "./Stats";
import type { InputFileSystem, IntermediateFileSystem, OutputFileSystem, WatchFileSystem } from "./util/fs";
import { Watching } from "./Watching";
export interface AssetEmittedInfo {
content: Buffer;
source: Source;
outputPath: string;
targetPath: string;
compilation: Compilation;
}
export type CompilerHooks = {
done: liteTapable.AsyncSeriesHook<Stats>;
afterDone: liteTapable.SyncHook<Stats>;
thisCompilation: liteTapable.SyncHook<[Compilation, CompilationParams]>;
compilation: liteTapable.SyncHook<[Compilation, CompilationParams]>;
invalid: liteTapable.SyncHook<[string | null, number]>;
compile: liteTapable.SyncHook<[CompilationParams]>;
normalModuleFactory: liteTapable.SyncHook<NormalModuleFactory>;
contextModuleFactory: liteTapable.SyncHook<ContextModuleFactory>;
initialize: liteTapable.SyncHook<[]>;
shouldEmit: liteTapable.SyncBailHook<[Compilation], boolean>;
/**
* Called when infrastructure logging is triggered, allowing plugins to intercept, modify, or handle log messages.
* If the hook returns `true`, the default infrastructure logging will be prevented.
* If it returns `undefined`, the default logging will proceed.
* @param name - The name of the logger
* @param type - The log type (e.g., 'log', 'warn', 'error', ...)
* @param args - An array of arguments passed to the logging method
*/
infrastructureLog: liteTapable.SyncBailHook<[
string,
string,
any[]
], true | void>;
beforeRun: liteTapable.AsyncSeriesHook<[Compiler]>;
run: liteTapable.AsyncSeriesHook<[Compiler]>;
emit: liteTapable.AsyncSeriesHook<[Compilation]>;
assetEmitted: liteTapable.AsyncSeriesHook<[string, AssetEmittedInfo]>;
afterEmit: liteTapable.AsyncSeriesHook<[Compilation]>;
failed: liteTapable.SyncHook<[Error]>;
shutdown: liteTapable.AsyncSeriesHook<[]>;
watchRun: liteTapable.AsyncSeriesHook<[Compiler]>;
watchClose: liteTapable.SyncHook<[]>;
environment: liteTapable.SyncHook<[]>;
afterEnvironment: liteTapable.SyncHook<[]>;
afterPlugins: liteTapable.SyncHook<[Compiler]>;
afterResolvers: liteTapable.SyncHook<[Compiler]>;
make: liteTapable.AsyncParallelHook<[Compilation]>;
beforeCompile: liteTapable.AsyncSeriesHook<[CompilationParams]>;
afterCompile: liteTapable.AsyncSeriesHook<[Compilation]>;
finishMake: liteTapable.AsyncSeriesHook<[Compilation]>;
entryOption: liteTapable.SyncBailHook<[string, EntryNormalized], any>;
additionalPass: liteTapable.AsyncSeriesHook<[]>;
};
declare class Compiler {
#private;
hooks: CompilerHooks;
webpack: typeof rspack;
rspack: typeof rspack;
name?: string;
parentCompilation?: Compilation;
root: Compiler;
outputPath: string;
running: boolean;
idle: boolean;
resolverFactory: ResolverFactory;
infrastructureLogger: any;
watching?: Watching;
inputFileSystem: InputFileSystem | null;
intermediateFileSystem: IntermediateFileSystem | null;
outputFileSystem: OutputFileSystem | null;
watchFileSystem: WatchFileSystem | null;
records: Record<string, any[]>;
modifiedFiles?: ReadonlySet<string>;
removedFiles?: ReadonlySet<string>;
fileTimestamps?: ReadonlyMap<string, FileSystemInfoEntry | "ignore" | null>;
contextTimestamps?: ReadonlyMap<string, FileSystemInfoEntry | "ignore" | null>;
fsStartTime?: number;
watchMode: boolean;
context: string;
cache: Cache;
compilerPath: string;
options: RspackOptionsNormalized;
/**
* Whether to skip dropping Rust compiler instance to improve performance.
* This is an internal option api and could be removed or changed at any time.
* @internal
* true: Skip dropping Rust compiler instance.
* false: Drop Rust compiler instance when Compiler is garbage collected.
*/
unsafeFastDrop: boolean;
/**
* Note: This is not a webpack public API, maybe removed in future.
* @internal
*/
__internal_browser_require: (id: string) => unknown;
constructor(context: string, options: RspackOptionsNormalized);
get recordsInputPath(): never;
get recordsOutputPath(): never;
get managedPaths(): never;
get immutablePaths(): never;
get _lastCompilation(): Compilation | undefined;
/**
* Note: This is not a webpack public API, maybe removed in future.
* @internal
*/
get __internal__builtinPlugins(): binding.BuiltinPlugin[];
/**
* Note: This is not a webpack public API, maybe removed in future.
* @internal
*/
get __internal__ruleSet(): RuleSetCompiler;
/**
* @param name - cache name
* @returns the cache facade instance
*/
getCache(name: string): CacheFacade;
/**
* @param name - name of the logger, or function called once to get the logger name
* @returns a logger with that name
*/
getInfrastructureLogger(name: string | (() => string)): Logger;
/**
* @param watchOptions - the watcher's options
* @param handler - signals when the call finishes
* @returns a compiler watcher
*/
watch(watchOptions: Watchpack.WatchOptions, handler: liteTapable.Callback<Error, Stats>): Watching;
/**
* @param callback - signals when the call finishes
* @param options - additional data like modifiedFiles, removedFiles
*/
run(callback: liteTapable.Callback<Error, Stats>, options?: {
modifiedFiles?: ReadonlySet<string>;
removedFiles?: ReadonlySet<string>;
}): void;
runAsChild(callback: (err?: null | Error, entries?: Chunk[], compilation?: Compilation) => any): void;
purgeInputFileSystem(): void;
/**
* @param compilation - the compilation
* @param compilerName - the compiler's name
* @param compilerIndex - the compiler's index
* @param outputOptions - the output options
* @param plugins - the plugins to apply
* @returns a child compiler
*/
createChildCompiler(compilation: Compilation, compilerName: string, compilerIndex: number, outputOptions: OutputNormalized, plugins: RspackPluginInstance[]): Compiler;
isChild(): boolean;
/**
* Create a compilation and run it, which is the basic method that `compiler.run` and `compiler.watch` depend on.
* TODO: make this method private in the next major release
* @private this method is only used in Rspack core
*/
compile(callback: liteTapable.Callback<Error, Compilation>): void;
close(callback: (error?: Error | null) => void): void;
/**
* Note: This is not a webpack public API, maybe removed in future.
* @internal
*/
__internal__rebuild(modifiedFiles?: ReadonlySet<string>, removedFiles?: ReadonlySet<string>, callback?: (error: Error | null) => void): void;
/**
* Note: This is not a webpack public API, maybe removed in future.
* @internal
*/
__internal__create_compilation(native: binding.JsCompilation): Compilation;
/**
* Note: This is not a webpack public API, maybe removed in future.
* @internal
*/
__internal__get_virtual_file_store(): binding.VirtualFileStore | null | undefined;
/**
* Note: This is not a webpack public API, maybe removed in future.
* @internal
*/
__internal__registerBuiltinPlugin(plugin: binding.BuiltinPlugin): void;
/**
* Note: This is not a webpack public API, maybe removed in future.
* @internal
*/
__internal__takeModuleExecutionResult(id: number): any;
/**
* Note: This is not a webpack public API, maybe removed in future.
* @internal
*/
__internal__get_compilation(): Compilation | undefined;
/**
* Note: This is not a webpack public API, maybe removed in future.
* @internal
*/
__internal__get_compilation_params(): CompilationParams | undefined;
/**
* Note: This is not a webpack public API, maybe removed in future.
* @internal
*/
__internal__get_module_execution_results_map(): Map<number, any>;
}
export { Compiler };

View File

@@ -0,0 +1 @@
export { ConcatenatedModule } from "@rspack/binding";

1
node_modules/@rspack/core/dist/ContextModule.d.ts generated vendored Normal file
View File

@@ -0,0 +1 @@
export { ContextModule } from "@rspack/binding";

View File

@@ -0,0 +1,13 @@
import * as liteTapable from "@rspack/lite-tapable";
import type { ContextModuleFactoryAfterResolveResult, ContextModuleFactoryBeforeResolveResult } from "./Module";
export declare class ContextModuleFactory {
hooks: {
beforeResolve: liteTapable.AsyncSeriesWaterfallHook<[
ContextModuleFactoryBeforeResolveResult
], ContextModuleFactoryBeforeResolveResult | void>;
afterResolve: liteTapable.AsyncSeriesWaterfallHook<[
ContextModuleFactoryAfterResolveResult
], ContextModuleFactoryAfterResolveResult | void>;
};
constructor();
}

7
node_modules/@rspack/core/dist/Diagnostics.d.ts generated vendored Normal file
View File

@@ -0,0 +1,7 @@
import type { Diagnostics } from "@rspack/binding";
import type { RspackError } from "./RspackError";
declare const $proxy: unique symbol;
export declare function createDiagnosticArray(adm: Diagnostics & {
[$proxy]?: RspackError[];
}): RspackError[];
export {};

2
node_modules/@rspack/core/dist/Entrypoint.d.ts generated vendored Normal file
View File

@@ -0,0 +1,2 @@
import type { ChunkGroup } from "@rspack/binding";
export type Entrypoint = ChunkGroup;

3
node_modules/@rspack/core/dist/ErrorHelpers.d.ts generated vendored Normal file
View File

@@ -0,0 +1,3 @@
export declare const cutOffLoaderExecution: (stack: string) => string;
export declare const cleanUp: (stack: string, name: string, message: string) => string;
export declare const cutOffMessage: (stack: string, name: string, message: string) => string;

View File

@@ -0,0 +1,4 @@
import type { Compiler } from "./Compiler";
export default class ExecuteModulePlugin {
apply(compiler: Compiler): void;
}

20
node_modules/@rspack/core/dist/ExportsInfo.d.ts generated vendored Normal file
View File

@@ -0,0 +1,20 @@
import type { JsExportsInfo } from "@rspack/binding";
import type { RuntimeSpec } from "./util/runtime";
/**
* Unused: 0
* OnlyPropertiesUsed: 1
* NoInfo: 2
* Unknown: 3
* Used: 4
*/
type UsageStateType = 0 | 1 | 2 | 3 | 4;
export declare class ExportsInfo {
#private;
static __from_binding(binding: JsExportsInfo): ExportsInfo;
private constructor();
isUsed(runtime: RuntimeSpec): boolean;
isModuleUsed(runtime: RuntimeSpec): boolean;
setUsedInUnknownWay(runtime: RuntimeSpec): boolean;
getUsed(name: string | string[], runtime: RuntimeSpec): UsageStateType;
}
export {};

1
node_modules/@rspack/core/dist/ExternalModule.d.ts generated vendored Normal file
View File

@@ -0,0 +1 @@
export { ExternalModule } from "@rspack/binding";

54
node_modules/@rspack/core/dist/FileSystem.d.ts generated vendored Normal file
View File

@@ -0,0 +1,54 @@
import type { NodeFsStats, ThreadsafeNodeFS } from "@rspack/binding";
import { type InputFileSystem, type IntermediateFileSystem, type OutputFileSystem } from "./util/fs";
declare class ThreadsafeInputNodeFS implements ThreadsafeNodeFS {
writeFile: (name: string, content: Buffer) => Promise<void>;
removeFile: (name: string) => Promise<void>;
mkdir: (name: string) => Promise<void>;
mkdirp: (name: string) => Promise<string | void>;
removeDirAll: (name: string) => Promise<string | void>;
readDir: (name: string) => Promise<string[] | void>;
readFile: (name: string) => Promise<Buffer | string | void>;
stat: (name: string) => Promise<NodeFsStats | void>;
lstat: (name: string) => Promise<NodeFsStats | void>;
chmod?: (name: string, mode: number) => Promise<void>;
realpath: (name: string) => Promise<string | void>;
open: (name: string, flags: string) => Promise<number | void>;
rename: (from: string, to: string) => Promise<void>;
close: (fd: number) => Promise<void>;
write: (fd: number, content: Buffer, position: number) => Promise<number | void>;
writeAll: (fd: number, content: Buffer) => Promise<number | void>;
read: (fd: number, length: number, position: number) => Promise<Buffer | void>;
readUntil: (fd: number, code: number, position: number) => Promise<Buffer | void>;
readToEnd: (fd: number, position: number) => Promise<Buffer | void>;
constructor(fs?: InputFileSystem);
static __to_binding(fs?: InputFileSystem): ThreadsafeInputNodeFS;
static needsBinding(ifs?: false | RegExp[]): boolean;
}
declare class ThreadsafeOutputNodeFS implements ThreadsafeNodeFS {
writeFile: (name: string, content: Buffer) => Promise<void>;
removeFile: (name: string) => Promise<void>;
mkdir: (name: string) => Promise<void>;
mkdirp: (name: string) => Promise<string | void>;
removeDirAll: (name: string) => Promise<string | void>;
readDir: (name: string) => Promise<string[] | void>;
readFile: (name: string) => Promise<Buffer | string | void>;
stat: (name: string) => Promise<NodeFsStats | void>;
lstat: (name: string) => Promise<NodeFsStats | void>;
chmod?: (name: string, mode: number) => Promise<void>;
realpath: (name: string) => Promise<string | void>;
open: (name: string, flags: string) => Promise<number | void>;
rename: (from: string, to: string) => Promise<void>;
close: (fd: number) => Promise<void>;
write: (fd: number, content: Buffer, position: number) => Promise<number | void>;
writeAll: (fd: number, content: Buffer) => Promise<number | void>;
read: (fd: number, length: number, position: number) => Promise<Buffer | void>;
readUntil: (fd: number, code: number, position: number) => Promise<Buffer | void>;
readToEnd: (fd: number, position: number) => Promise<Buffer | void>;
constructor(fs?: OutputFileSystem);
static __to_binding(fs?: OutputFileSystem): ThreadsafeOutputNodeFS;
}
declare class ThreadsafeIntermediateNodeFS extends ThreadsafeOutputNodeFS {
constructor(fs?: IntermediateFileSystem);
static __to_binding(fs?: IntermediateFileSystem): ThreadsafeIntermediateNodeFS;
}
export { ThreadsafeInputNodeFS, ThreadsafeOutputNodeFS, ThreadsafeIntermediateNodeFS };

5
node_modules/@rspack/core/dist/FileSystemInfo.d.ts generated vendored Normal file
View File

@@ -0,0 +1,5 @@
interface FileSystemInfoEntry {
safeTime: number;
timestamp?: number;
}
export type { FileSystemInfoEntry };

42
node_modules/@rspack/core/dist/Module.d.ts generated vendored Normal file
View File

@@ -0,0 +1,42 @@
import binding, { type AssetInfo } from "@rspack/binding";
import type { Source } from "../compiled/webpack-sources";
import type { ResourceData } from "./Resolver";
import "./BuildInfo";
export type ResourceDataWithData = ResourceData & {
data?: Record<string, any>;
};
export type CreateData = binding.JsCreateData;
export type ContextInfo = binding.ContextInfo;
export type ResolveData = binding.JsResolveData;
export declare class ContextModuleFactoryBeforeResolveData {
#private;
context: string;
request: string;
regExp: RegExp | undefined;
recursive: boolean;
static __from_binding(binding: binding.JsContextModuleFactoryBeforeResolveData): ContextModuleFactoryBeforeResolveData;
static __to_binding(data: ContextModuleFactoryBeforeResolveData): binding.JsContextModuleFactoryBeforeResolveData;
private constructor();
}
export type ContextModuleFactoryBeforeResolveResult = false | ContextModuleFactoryBeforeResolveData;
export declare class ContextModuleFactoryAfterResolveData {
#private;
resource: number;
context: string;
request: string;
regExp: RegExp | undefined;
recursive: boolean;
readonly dependencies: binding.Dependency[];
static __from_binding(binding: binding.JsContextModuleFactoryAfterResolveData): ContextModuleFactoryAfterResolveData;
static __to_binding(data: ContextModuleFactoryAfterResolveData): binding.JsContextModuleFactoryAfterResolveData;
private constructor();
}
export type ContextModuleFactoryAfterResolveResult = false | ContextModuleFactoryAfterResolveData;
declare module "@rspack/binding" {
interface Module {
identifier(): string;
originalSource(): Source | null;
emitFile(filename: string, source: Source, assetInfo?: AssetInfo): void;
}
}
export { Module } from "@rspack/binding";

19
node_modules/@rspack/core/dist/ModuleGraph.d.ts generated vendored Normal file
View File

@@ -0,0 +1,19 @@
import type { Dependency, JsModuleGraph, ModuleGraphConnection } from "@rspack/binding";
import { ExportsInfo } from "./ExportsInfo";
import type { Module } from "./Module";
export default class ModuleGraph {
#private;
static __from_binding(binding: JsModuleGraph): ModuleGraph;
constructor(binding: JsModuleGraph);
getModule(dependency: Dependency): Module | null;
getResolvedModule(dependency: Dependency): Module | null;
getParentModule(dependency: Dependency): Module | null;
getIssuer(module: Module): Module | null;
getExportsInfo(module: Module): ExportsInfo;
getConnection(dependency: Dependency): ModuleGraphConnection | null;
getOutgoingConnections(module: Module): ModuleGraphConnection[];
getIncomingConnections(module: Module): ModuleGraphConnection[];
getParentBlockIndex(dependency: Dependency): number;
isAsync(module: Module): boolean;
getOutgoingConnectionsInOrder(module: Module): ModuleGraphConnection[];
}

View File

@@ -0,0 +1,8 @@
/**
* This is the module type used for JSON files. JSON files are always parsed as ES Module.
*/
export declare const JSON_MODULE_TYPE = "json";
/**
* This is the module type used for automatically choosing between `asset/inline`, `asset/resource` based on asset size limit (8096).
*/
export declare const ASSET_MODULE_TYPE = "asset";

82
node_modules/@rspack/core/dist/MultiCompiler.d.ts generated vendored Normal file
View File

@@ -0,0 +1,82 @@
/**
* The following code is modified based on
* https://github.com/webpack/webpack/blob/4b4ca3b/lib/MultiCompiler.js
*
* MIT Licensed
* Author Tobias Koppers @sokra
* Copyright (c) JS Foundation and other contributors
* https://github.com/webpack/webpack/blob/main/LICENSE
*/
import * as liteTapable from "@rspack/lite-tapable";
import type { CompilationParams, Compiler, CompilerHooks, RspackOptions } from ".";
import type { WatchOptions } from "./config";
import MultiStats from "./MultiStats";
import MultiWatching from "./MultiWatching";
import type { InputFileSystem, IntermediateFileSystem, WatchFileSystem } from "./util/fs";
export interface MultiCompilerOptions {
/**
* how many Compilers are allows to run at the same time in parallel
*/
parallelism?: number;
}
export type MultiRspackOptions = readonly RspackOptions[] & MultiCompilerOptions;
export declare class MultiCompiler {
#private;
compilers: Compiler[];
dependencies: WeakMap<Compiler, string[]>;
hooks: {
done: liteTapable.SyncHook<MultiStats>;
invalid: liteTapable.MultiHook<liteTapable.SyncHook<[string | null, number]>>;
beforeCompile: liteTapable.MultiHook<liteTapable.AsyncSeriesHook<[CompilationParams]>>;
shutdown: liteTapable.MultiHook<liteTapable.AsyncSeriesHook<[]>>;
run: liteTapable.MultiHook<liteTapable.AsyncSeriesHook<[Compiler]>>;
watchClose: liteTapable.SyncHook<[]>;
watchRun: liteTapable.MultiHook<liteTapable.AsyncSeriesHook<[Compiler]>>;
/**
* @see {@link CompilerHooks['infrastructureLog']}
*/
infrastructureLog: liteTapable.MultiHook<CompilerHooks["infrastructureLog"]>;
};
_options: MultiCompilerOptions;
running: boolean;
watching?: MultiWatching;
constructor(compilers: Compiler[] | Record<string, Compiler>, options?: MultiCompilerOptions);
set unsafeFastDrop(value: boolean);
get options(): import(".").RspackOptionsNormalized[] & MultiCompilerOptions;
get outputPath(): string;
get inputFileSystem(): InputFileSystem;
get outputFileSystem(): typeof import("fs");
get watchFileSystem(): WatchFileSystem;
get intermediateFileSystem(): IntermediateFileSystem;
set inputFileSystem(value: InputFileSystem);
set outputFileSystem(value: typeof import("fs"));
set watchFileSystem(value: WatchFileSystem);
set intermediateFileSystem(value: IntermediateFileSystem);
getInfrastructureLogger(name: string): import("./logging/Logger").Logger;
/**
* @param compiler - the child compiler
* @param dependencies - its dependencies
*/
setDependencies(compiler: Compiler, dependencies: string[]): void;
/**
* @param callback - signals when the validation is complete
* @returns true if the dependencies are valid
*/
validateDependencies(callback: liteTapable.Callback<Error, MultiStats>): boolean;
/**
* @param watchOptions - the watcher's options
* @param handler - signals when the call finishes
* @returns a compiler watcher
*/
watch(watchOptions: WatchOptions | WatchOptions[], handler: liteTapable.Callback<Error, MultiStats>): MultiWatching;
/**
* @param callback - signals when the call finishes
* @param options - additional data like modifiedFiles, removedFiles
*/
run(callback: liteTapable.Callback<Error, MultiStats>, options?: {
modifiedFiles?: ReadonlySet<string>;
removedFiles?: ReadonlySet<string>;
}): void;
purgeInputFileSystem(): void;
close(callback: liteTapable.Callback<Error, void>): void;
}

23
node_modules/@rspack/core/dist/MultiStats.d.ts generated vendored Normal file
View File

@@ -0,0 +1,23 @@
/**
* The following code is modified based on
* https://github.com/webpack/webpack/blob/4b4ca3b/lib/MultiStats.js
*
* MIT Licensed
* Author Tobias Koppers @sokra
* Copyright (c) JS Foundation and other contributors
* https://github.com/webpack/webpack/blob/main/LICENSE
*/
import type { MultiStatsOptions, StatsPresets } from "./config";
import type { Stats } from "./Stats";
import type { StatsCompilation } from "./stats/statsFactoryUtils";
export default class MultiStats {
#private;
stats: Stats[];
constructor(stats: Stats[]);
get hash(): string;
hasErrors(): boolean;
hasWarnings(): boolean;
toJson(options: boolean | StatsPresets | MultiStatsOptions): StatsCompilation;
toString(options: boolean | StatsPresets | MultiStatsOptions): string;
}
export { MultiStats };

27
node_modules/@rspack/core/dist/MultiWatching.d.ts generated vendored Normal file
View File

@@ -0,0 +1,27 @@
/**
* The following code is modified based on
* https://github.com/webpack/webpack/blob/4b4ca3b/lib/MultiWatching.js
*
* MIT Licensed
* Author Tobias Koppers @sokra
* Copyright (c) JS Foundation and other contributors
* https://github.com/webpack/webpack/blob/main/LICENSE
*/
import type { Callback } from "@rspack/lite-tapable";
import type { MultiCompiler } from "./MultiCompiler";
import type { Watching } from "./Watching";
declare class MultiWatching {
watchings: Watching[];
compiler: MultiCompiler;
/**
* @param watchings - child compilers' watchers
* @param compiler - the compiler
*/
constructor(watchings: Watching[], compiler: MultiCompiler);
invalidate(callback?: Callback<Error, void>): void;
invalidateWithChangesAndRemovals(changedFiles?: Set<string>, removedFiles?: Set<string>, callback?: Callback<Error, void>): void;
close(callback: Callback<Error, void>): void;
suspend(): void;
resume(): void;
}
export default MultiWatching;

View File

@@ -0,0 +1,23 @@
import binding from "@rspack/binding";
import type Watchpack from "../compiled/watchpack";
import type { FileSystemInfoEntry, InputFileSystem, Watcher, WatchFileSystem } from "./util/fs";
export default class NativeWatchFileSystem implements WatchFileSystem {
#private;
constructor(inputFileSystem: InputFileSystem);
watch(files: Iterable<string> & {
added?: Iterable<string>;
removed?: Iterable<string>;
}, directories: Iterable<string> & {
added?: Iterable<string>;
removed?: Iterable<string>;
}, missing: Iterable<string> & {
added?: Iterable<string>;
removed?: Iterable<string>;
}, startTime: number, options: Watchpack.WatchOptions, callback: (error: Error | null, fileTimeInfoEntries: Map<string, FileSystemInfoEntry | "ignore">, contextTimeInfoEntries: Map<string, FileSystemInfoEntry | "ignore">, changedFiles: Set<string>, removedFiles: Set<string>) => void, callbackUndelayed: (fileName: string, changeTime: number) => void): Watcher;
getNativeWatcher(options: Watchpack.WatchOptions): binding.NativeWatcher;
triggerEvent(kind: "change" | "remove" | "create", path: string): void;
formatWatchDependencies(dependencies: Iterable<string> & {
added?: Iterable<string>;
removed?: Iterable<string>;
}): [string[], string[]];
}

15
node_modules/@rspack/core/dist/NormalModule.d.ts generated vendored Normal file
View File

@@ -0,0 +1,15 @@
import * as liteTapable from "@rspack/lite-tapable";
import type { Compilation } from "./Compilation";
import type { LoaderContext } from "./config";
import type { Module } from "./Module";
export interface NormalModuleCompilationHooks {
loader: liteTapable.SyncHook<[LoaderContext, Module]>;
readResourceForScheme: any;
readResource: liteTapable.HookMap<liteTapable.AsyncSeriesBailHook<[LoaderContext], string | Buffer>>;
}
declare module "@rspack/binding" {
interface NormalModuleConstructor {
getCompilationHooks(compilation: Compilation): NormalModuleCompilationHooks;
}
}
export { NormalModule } from "@rspack/binding";

View File

@@ -0,0 +1,23 @@
import type binding from "@rspack/binding";
import * as liteTapable from "@rspack/lite-tapable";
import type { ResolveData, ResourceDataWithData } from "./Module";
import type { ResolveOptionsWithDependencyType, ResolverFactory } from "./ResolverFactory";
export type NormalModuleCreateData = binding.JsNormalModuleFactoryCreateModuleArgs & {
settings: {};
};
export declare class NormalModuleFactory {
hooks: {
resolveForScheme: liteTapable.HookMap<liteTapable.AsyncSeriesBailHook<[ResourceDataWithData], true | void>>;
beforeResolve: liteTapable.AsyncSeriesBailHook<[ResolveData], false | void>;
factorize: liteTapable.AsyncSeriesBailHook<[ResolveData], void>;
resolve: liteTapable.AsyncSeriesBailHook<[ResolveData], void>;
afterResolve: liteTapable.AsyncSeriesBailHook<[ResolveData], false | void>;
createModule: liteTapable.AsyncSeriesBailHook<[
NormalModuleCreateData,
{}
], void>;
};
resolverFactory: ResolverFactory;
constructor(resolverFactory: ResolverFactory);
getResolver(type: string, resolveOptions: ResolveOptionsWithDependencyType): import("./ResolverFactory").ResolverWithOptions;
}

30
node_modules/@rspack/core/dist/Resolver.d.ts generated vendored Normal file
View File

@@ -0,0 +1,30 @@
import type binding from "@rspack/binding";
import type { ResolveCallback } from "./config/adapterRuleUse";
export type ResolveContext = {
contextDependencies?: {
add: (context: string) => void;
};
missingDependencies?: {
add: (dependency: string) => void;
};
fileDependencies?: {
add: (dependency: string) => void;
};
};
export type ResourceData = binding.JsResourceData;
export interface ResolveRequest {
path: string;
query: string;
fragment: string;
descriptionFileData?: string;
descriptionFilePath?: string;
fileDependencies?: string[];
missingDependencies?: string[];
contextDependencies?: string[];
}
export declare class Resolver {
#private;
constructor(binding: binding.JsResolver);
resolveSync(context: object, path: string, request: string): string | false;
resolve(context: object, path: string, request: string, resolveContext: ResolveContext, callback: ResolveCallback): void;
}

17
node_modules/@rspack/core/dist/ResolverFactory.d.ts generated vendored Normal file
View File

@@ -0,0 +1,17 @@
import binding from "@rspack/binding";
import { type Resolve } from "./config";
import { Resolver } from "./Resolver";
export type ResolveOptionsWithDependencyType = Resolve & {
dependencyType?: string;
resolveToContext?: boolean;
};
export type WithOptions = {
withOptions: (options: ResolveOptionsWithDependencyType) => ResolverWithOptions;
};
export type ResolverWithOptions = Resolver & WithOptions;
export declare class ResolverFactory {
#private;
static __to_binding(resolver_factory: ResolverFactory): binding.JsResolverFactory;
constructor(pnp: boolean, resolveOptions: Resolve, loaderResolveOptions: Resolve);
get(type: string, resolveOptions?: ResolveOptionsWithDependencyType): ResolverWithOptions;
}

12
node_modules/@rspack/core/dist/RspackError.d.ts generated vendored Normal file
View File

@@ -0,0 +1,12 @@
import type binding from "@rspack/binding";
export type { RspackError } from "@rspack/binding";
export type RspackSeverity = binding.JsRspackSeverity;
export declare class NonErrorEmittedError extends Error {
constructor(error: Error);
}
export declare class DeadlockRiskError extends Error {
constructor(message: string);
}
export declare class ValidationError extends Error {
constructor(message: string);
}

9
node_modules/@rspack/core/dist/RuleSetCompiler.d.ts generated vendored Normal file
View File

@@ -0,0 +1,9 @@
declare class RuleSetCompiler {
references: Map<string, any>;
/**
* builtin references that should be serializable and passed to Rust.
*/
builtinReferences: Map<string, any>;
constructor();
}
export { RuleSetCompiler };

356
node_modules/@rspack/core/dist/RuntimeGlobals.d.ts generated vendored Normal file
View File

@@ -0,0 +1,356 @@
/**
* The following code is modified based on
* https://github.com/webpack/webpack/blob/v5.88.2/lib/RuntimeGlobals.js
*
* MIT Licensed
* Author Tobias Koppers \@sokra
* Copyright (c) JS Foundation and other contributors
* https://github.com/webpack/webpack/blob/main/LICENSE
*/
import type { JsRuntimeGlobals } from "@rspack/binding";
import type { RspackOptionsNormalized } from "./config";
export declare function __from_binding_runtime_globals(runtimeRequirements: JsRuntimeGlobals, compilerRuntimeGlobals: Record<string, string>): Set<string>;
export declare function __to_binding_runtime_globals(runtimeRequirements: Set<string>, compilerRuntimeGlobals: Record<string, string>): JsRuntimeGlobals;
declare enum RuntimeGlobals {
/**
* the internal require function
*/
require = 0,
/**
* access to properties of the internal require function/object
*/
requireScope = 1,
/**
* the internal exports object
*/
exports = 2,
/**
* top-level this need to be the exports object
*/
thisAsExports = 3,
/**
* runtime need to return the exports of the last entry module
*/
returnExportsFromRuntime = 4,
/**
* the internal module object
*/
module = 5,
/**
* the internal module object
*/
moduleId = 6,
/**
* the internal module object
*/
moduleLoaded = 7,
/**
* the bundle public path
*/
publicPath = 8,
/**
* the module id of the entry point
*/
entryModuleId = 9,
/**
* the module cache
*/
moduleCache = 10,
/**
* the module functions
*/
moduleFactories = 11,
/**
* the module functions, with only write access
*/
moduleFactoriesAddOnly = 12,
/**
* the chunk ensure function
*/
ensureChunk = 13,
/**
* an object with handlers to ensure a chunk
*/
ensureChunkHandlers = 14,
/**
* a runtime requirement if ensureChunkHandlers should include loading of chunk needed for entries
*/
ensureChunkIncludeEntries = 15,
/**
* the chunk prefetch function
*/
prefetchChunk = 16,
/**
* an object with handlers to prefetch a chunk
*/
prefetchChunkHandlers = 17,
/**
* the chunk preload function
*/
preloadChunk = 18,
/**
* an object with handlers to preload a chunk
*/
preloadChunkHandlers = 19,
/**
* the exported property define getters function
*/
definePropertyGetters = 20,
/**
* define compatibility on export
*/
makeNamespaceObject = 21,
/**
* create a fake namespace object
*/
createFakeNamespaceObject = 22,
/**
* compatibility get default export
*/
compatGetDefaultExport = 23,
/**
* ES modules decorator
*/
harmonyModuleDecorator = 24,
/**
* node.js module decorator
*/
nodeModuleDecorator = 25,
/**
* the webpack hash
*/
getFullHash = 26,
/**
* an object containing all installed WebAssembly.Instance export objects keyed by module id
*/
wasmInstances = 27,
/**
* instantiate a wasm instance from module exports object, id, hash and importsObject
*/
instantiateWasm = 28,
/**
* the uncaught error handler for the webpack runtime
*/
uncaughtErrorHandler = 29,
/**
* the script nonce
*/
scriptNonce = 30,
/**
* function to load a script tag.
* Arguments: (url: string, done: (event) =\> void), key?: string | number, chunkId?: string | number) =\> void
* done function is called when loading has finished or timeout occurred.
* It will attach to existing script tags with data-webpack == uniqueName + ":" + key or src == url.
*/
loadScript = 31,
/**
* function to promote a string to a TrustedScript using webpack's Trusted
* Types policy
* Arguments: (script: string) =\> TrustedScript
*/
createScript = 32,
/**
* function to promote a string to a TrustedScriptURL using webpack's Trusted
* Types policy
* Arguments: (url: string) =\> TrustedScriptURL
*/
createScriptUrl = 33,
/**
* function to return webpack's Trusted Types policy
* Arguments: () =\> TrustedTypePolicy
*/
getTrustedTypesPolicy = 34,
/**
* a flag when a chunk has a fetch priority
*/
hasFetchPriority = 35,
/**
* the chunk name of the chunk with the runtime
*/
chunkName = 36,
/**
* the runtime id of the current runtime
*/
runtimeId = 37,
/**
* the filename of the script part of the chunk
*/
getChunkScriptFilename = 38,
/**
* the filename of the css part of the chunk
*/
getChunkCssFilename = 39,
/**
* rspack version
* @internal
*/
rspackVersion = 40,
/**
* a flag when a module/chunk/tree has css modules
*/
hasCssModules = 41,
/**
* rspack unique id
* @internal
*/
rspackUniqueId = 42,
/**
* the filename of the script part of the hot update chunk
*/
getChunkUpdateScriptFilename = 43,
/**
* the filename of the css part of the hot update chunk
*/
getChunkUpdateCssFilename = 44,
/**
* startup signal from runtime
* This will be called when the runtime chunk has been loaded.
*/
startup = 45,
/**
* @deprecated
* creating a default startup function with the entry modules
*/
startupNoDefault = 46,
/**
* startup signal from runtime but only used to add logic after the startup
*/
startupOnlyAfter = 47,
/**
* startup signal from runtime but only used to add sync logic before the startup
*/
startupOnlyBefore = 48,
/**
* global callback functions for installing chunks
*/
chunkCallback = 49,
/**
* method to startup an entrypoint with needed chunks.
* Signature: (moduleId: Id, chunkIds: Id[]) =\> any.
* Returns the exports of the module or a Promise
*/
startupEntrypoint = 50,
/**
* startup signal from runtime for chunk dependencies
*/
startupChunkDependencies = 51,
/**
* register deferred code, which will run when certain
* chunks are loaded.
* Signature: (chunkIds: Id[], fn: () =\> any, priority: int \>= 0 = 0) =\> any
* Returned value will be returned directly when all chunks are already loaded
* When (priority & 1) it will wait for all other handlers with lower priority to
* be executed before itself is executed
*/
onChunksLoaded = 52,
/**
* method to install a chunk that was loaded somehow
* Signature: (\{ id, ids, modules, runtime \}) =\> void
*/
externalInstallChunk = 53,
/**
* interceptor for module executions
*/
interceptModuleExecution = 54,
/**
* the global object
*/
global = 55,
/**
* an object with all share scopes
*/
shareScopeMap = 56,
/**
* The sharing init sequence function (only runs once per share scope).
* Has one argument, the name of the share scope.
* Creates a share scope if not existing
*/
initializeSharing = 57,
/**
* The current scope when getting a module from a remote
*/
currentRemoteGetScope = 58,
/**
* the filename of the HMR manifest
*/
getUpdateManifestFilename = 59,
/**
* function downloading the update manifest
*/
hmrDownloadManifest = 60,
/**
* array with handler functions to download chunk updates
*/
hmrDownloadUpdateHandlers = 61,
/**
* object with all hmr module data for all modules
*/
hmrModuleData = 62,
/**
* array with handler functions when a module should be invalidated
*/
hmrInvalidateModuleHandlers = 63,
/**
* the prefix for storing state of runtime modules when hmr is enabled
*/
hmrRuntimeStatePrefix = 64,
/**
* the AMD define function
*/
amdDefine = 65,
/**
* the AMD options
*/
amdOptions = 66,
/**
* the System polyfill object
*/
system = 67,
/**
* the shorthand for Object.prototype.hasOwnProperty
* using of it decreases the compiled bundle size
*/
hasOwnProperty = 68,
/**
* the System.register context object
*/
systemContext = 69,
/**
* the baseURI of current document
*/
baseURI = 70,
/**
* a RelativeURL class when relative URLs are used
*/
relativeUrl = 71,
/**
* Creates an async module. The body function must be a async function.
* "module.exports" will be decorated with an AsyncModulePromise.
* The body function will be called.
* To handle async dependencies correctly do this: "([a, b, c] = await handleDependencies([a, b, c]));".
* If "hasAwaitAfterDependencies" is truthy, "handleDependencies()" must be called at the end of the body function.
* Signature: function(
* module: Module,
* body: (handleDependencies: (deps: AsyncModulePromise[]) =\> Promise\<any[]\> & () =\> void,
* hasAwaitAfterDependencies?: boolean
* ) =\> void
*/
asyncModule = 72,
asyncModuleExportSymbol = 73,
makeDeferredNamespaceObject = 74,
makeDeferredNamespaceObjectSymbol = 75
}
export declare const isReservedRuntimeGlobal: (r: string, compilerRuntimeGlobals: Record<string, string>) => boolean;
export declare function renderModulePrefix(_compilerOptions: RspackOptionsNormalized): string;
export declare enum RuntimeVariable {
Require = 0,
Modules = 1,
ModuleCache = 2,
Module = 3,
Exports = 4,
StartupExec = 5
}
export declare function renderRuntimeVariables(variable: RuntimeVariable, _compilerOptions?: RspackOptionsNormalized): string;
export declare function createCompilerRuntimeGlobals(compilerOptions?: RspackOptionsNormalized): typeof RuntimeGlobals;
declare const DefaultRuntimeGlobals: typeof RuntimeGlobals;
export { DefaultRuntimeGlobals as RuntimeGlobals };

32
node_modules/@rspack/core/dist/RuntimeModule.d.ts generated vendored Normal file
View File

@@ -0,0 +1,32 @@
import type { JsAddingRuntimeModule } from "@rspack/binding";
import type { Chunk } from "./Chunk";
import type { ChunkGraph } from "./ChunkGraph";
import type { Compilation } from "./Compilation";
export declare enum RuntimeModuleStage {
NORMAL = 0,
BASIC = 5,
ATTACH = 10,
TRIGGER = 20
}
export declare class RuntimeModule {
static STAGE_NORMAL: RuntimeModuleStage;
static STAGE_BASIC: RuntimeModuleStage;
static STAGE_ATTACH: RuntimeModuleStage;
static STAGE_TRIGGER: RuntimeModuleStage;
static __to_binding(module: RuntimeModule): JsAddingRuntimeModule;
private _name;
private _stage;
fullHash: boolean;
dependentHash: boolean;
protected chunk: Chunk | null;
protected compilation: Compilation | null;
protected chunkGraph: ChunkGraph | null;
constructor(name: string, stage?: RuntimeModuleStage);
attach(compilation: Compilation, chunk: Chunk, chunkGraph: ChunkGraph): void;
get name(): string;
get stage(): RuntimeModuleStage;
identifier(): string;
readableIdentifier(): string;
shouldIsolate(): boolean;
generate(): string;
}

17
node_modules/@rspack/core/dist/Stats.d.ts generated vendored Normal file
View File

@@ -0,0 +1,17 @@
import type { Compilation } from "./Compilation";
import type { StatsOptions, StatsValue } from "./config";
import type { StatsCompilation } from "./stats/statsFactoryUtils";
export type { StatsAsset, StatsChunk, StatsCompilation, StatsError, StatsModule } from "./stats/statsFactoryUtils";
export declare class Stats {
#private;
constructor(compilation: Compilation);
get compilation(): Compilation;
get hash(): Readonly<string | null>;
get startTime(): number | undefined;
get endTime(): number | undefined;
hasErrors(): boolean;
hasWarnings(): boolean;
toJson(opts?: StatsValue, forToString?: boolean): StatsCompilation;
toString(opts?: StatsValue): string;
}
export declare function normalizeStatsPreset(options?: StatsValue): StatsOptions;

77
node_modules/@rspack/core/dist/Template.d.ts generated vendored Normal file
View File

@@ -0,0 +1,77 @@
/**
* The following code is modified based on
* https://github.com/webpack/webpack/blob/4b4ca3b/lib/Template.js
*
* MIT Licensed
* Author Tobias Koppers @sokra
* Copyright (c) JS Foundation and other contributors
* https://github.com/webpack/webpack/blob/main/LICENSE
*/
declare class Template {
/**
*
* @param fn a runtime function (.runtime.js) "template"
* @returns the updated and normalized function string
*/
static getFunctionContent(fn: Function): string;
/**
* @param str the string converted to identifier
* @returns created identifier
*/
static toIdentifier(str: any): string;
/**
*
* @param str string to be converted to commented in bundle code
* @returns returns a commented version of string
*/
static toComment(str: string): string;
/**
*
* @param str string to be converted to "normal comment"
* @returns returns a commented version of string
*/
static toNormalComment(str: string): string;
/**
* @param str string path to be normalized
* @returns normalized bundle-safe path
*/
static toPath(str: string): string;
/**
* @param num number to convert to ident
* @returns returns single character ident
*/
static numberToIdentifier(num: number): string;
/**
* @param num number to convert to ident
* @returns returns single character ident
*/
static numberToIdentifierContinuation(num: number): string;
/**
*
* @param s string to convert to identity
* @returns converted identity
*/
static indent(s: string | string[]): string;
/**
*
* @param s string to create prefix for
* @param prefix prefix to compose
* @returns returns new prefix string
*/
static prefix(s: string | string[], prefix: string): string;
/**
*
* @param str string or string collection
* @returns returns a single string from array
*/
static asString(str: string | string[]): string;
/**
* @param modules a collection of modules to get array bounds for
* @returns returns the upper and lower array bounds
* or false if not every module has a number based id
*/
static getModulesArrayBounds(modules: {
id: string | number;
}[]): [number, number] | false;
}
export { Template };

View File

@@ -0,0 +1,12 @@
import type { Compiler } from "./Compiler";
export declare class VirtualModulesPlugin {
#private;
constructor(modules?: Record<string, string>);
apply(compiler: Compiler): void;
writeModule(filePath: string, contents: string): void;
private getVirtualFileStore;
static __internal__take_virtual_files(compiler: Compiler): {
path: string;
content: string;
}[] | undefined;
}

56
node_modules/@rspack/core/dist/Watching.d.ts generated vendored Normal file
View File

@@ -0,0 +1,56 @@
/**
* The following code is modified based on
* https://github.com/webpack/webpack/blob/4b4ca3b/lib/Watching.js
*
* MIT Licensed
* Author Tobias Koppers @sokra
* Copyright (c) JS Foundation and other contributors
* https://github.com/webpack/webpack/blob/main/LICENSE
*/
import type { Callback } from "@rspack/lite-tapable";
import type { Compiler } from ".";
import { Stats } from ".";
import type { WatchOptions } from "./config";
import type { Watcher } from "./util/fs";
export declare class Watching {
#private;
watcher?: Watcher;
pausedWatcher?: Watcher;
compiler: Compiler;
handler: Callback<Error, Stats>;
callbacks: Callback<Error, void>[];
watchOptions: WatchOptions;
lastWatcherStartTime: number;
running: boolean;
blocked: boolean;
isBlocked: () => boolean;
onChange: () => void;
onInvalid: () => void;
invalid: boolean;
startTime?: number;
suspended: boolean;
constructor(compiler: Compiler, watchOptions: WatchOptions, handler: Callback<Error, Stats>);
watch(files: Iterable<string> & {
added?: Iterable<string>;
removed?: Iterable<string>;
}, dirs: Iterable<string> & {
added?: Iterable<string>;
removed?: Iterable<string>;
}, missing: Iterable<string> & {
added?: Iterable<string>;
removed?: Iterable<string>;
}): void;
close(callback?: () => void): void;
invalidate(callback?: Callback<Error, void>): void;
/**
* @internal This is not a public API yet, still unstable, might change in the future
*/
invalidateWithChangesAndRemovals(changedFiles?: Set<string>, removedFiles?: Set<string>, callback?: Callback<Error, void>): void;
/**
* The reason why this is _done instead of #done, is that in Webpack,
* it will rewrite this function to another function
*/
private _done;
suspend(): void;
resume(): void;
}

View File

@@ -0,0 +1 @@
export * from "./swc";

View File

@@ -0,0 +1,117 @@
/**
MIT License
Copyright (c) 2021-present Devon Govett
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.
*/
export declare function toFeatures(featureOptions: FeatureOptions): Features;
export declare enum Features {
Empty = 0,
Nesting = 1,
NotSelectorList = 2,
DirSelector = 4,
LangSelectorList = 8,
IsSelector = 16,
TextDecorationThicknessPercent = 32,
MediaIntervalSyntax = 64,
MediaRangeSyntax = 128,
CustomMediaQueries = 256,
ClampFunction = 512,
ColorFunction = 1024,
OklabColors = 2048,
LabColors = 4096,
P3Colors = 8192,
HexAlphaColors = 16384,
SpaceSeparatedColorNotation = 32768,
FontFamilySystemUi = 65536,
DoublePositionGradients = 131072,
VendorPrefixes = 262144,
LogicalProperties = 524288,
Selectors = 31,
MediaQueries = 448,
Color = 64512
}
export interface Targets {
android?: number;
chrome?: number;
edge?: number;
firefox?: number;
ie?: number;
ios_saf?: number;
opera?: number;
safari?: number;
samsung?: number;
}
export interface Drafts {
/** Whether to enable @custom-media rules. */
customMedia?: boolean;
}
export interface NonStandard {
/** Whether to enable the non-standard >>> and /deep/ selector combinators used by Angular and Vue. */
deepSelectorCombinator?: boolean;
}
export interface PseudoClasses {
hover?: string;
active?: string;
focus?: string;
focusVisible?: string;
focusWithin?: string;
}
export type FeatureOptions = {
nesting?: boolean;
notSelectorList?: boolean;
dirSelector?: boolean;
langSelectorList?: boolean;
isSelector?: boolean;
textDecorationThicknessPercent?: boolean;
mediaIntervalSyntax?: boolean;
mediaRangeSyntax?: boolean;
customMediaQueries?: boolean;
clampFunction?: boolean;
colorFunction?: boolean;
oklabColors?: boolean;
labColors?: boolean;
p3Colors?: boolean;
hexAlphaColors?: boolean;
spaceSeparatedColorNotation?: boolean;
fontFamilySystemUi?: boolean;
doublePositionGradients?: boolean;
vendorPrefixes?: boolean;
logicalProperties?: boolean;
selectors?: boolean;
mediaQueries?: boolean;
color?: boolean;
};
export type LoaderOptions = {
minify?: boolean;
errorRecovery?: boolean;
targets?: Targets | string[] | string;
include?: FeatureOptions;
exclude?: FeatureOptions;
/**
* @deprecated Use `drafts` instead.
* This will be removed in the next major version.
*/
draft?: Drafts;
drafts?: Drafts;
nonStandard?: NonStandard;
pseudoClasses?: PseudoClasses;
unusedSymbols?: string[];
};

View File

@@ -0,0 +1,21 @@
export type CollectTypeScriptInfoOptions = {
/**
* Whether to collect type exports information for `typeReexportsPresence`.
* This is used to check type exports of submodules when running in `'tolerant'` mode.
* @default false
*/
typeExports?: boolean;
/**
* Whether to collect information about exported `enum`s.
* - `true` will collect all `enum` information, including `const enum`s and regular `enum`s.
* - `false` will not collect any `enum` information.
* - `'const-only'` will gather only `const enum`s, enabling Rspack to perform cross-module
* inlining optimizations for them.
* @default false
*/
exportedEnum?: boolean | "const-only";
};
export declare function resolveCollectTypeScriptInfo(options: CollectTypeScriptInfoOptions): {
typeExports: boolean | undefined;
exportedEnum: string;
};

View File

@@ -0,0 +1,5 @@
export type { CollectTypeScriptInfoOptions } from "./collectTypeScriptInfo";
export { resolveCollectTypeScriptInfo } from "./collectTypeScriptInfo";
export type { PluginImportOptions } from "./pluginImport";
export { resolvePluginImport } from "./pluginImport";
export type { SwcLoaderEnvConfig, SwcLoaderEsParserConfig, SwcLoaderJscConfig, SwcLoaderModuleConfig, SwcLoaderOptions, SwcLoaderParserConfig, SwcLoaderTransformConfig, SwcLoaderTsParserConfig } from "./types";

View File

@@ -0,0 +1,33 @@
type RawStyleConfig = {
styleLibraryDirectory?: string;
custom?: string;
css?: string;
bool?: boolean;
};
type RawPluginImportConfig = {
libraryName: string;
libraryDirectory?: string;
customName?: string;
customStyleName?: string;
style?: RawStyleConfig;
camelToDashComponentName?: boolean;
transformToDefaultImport?: boolean;
ignoreEsComponent?: string[];
ignoreStyleComponent?: string[];
};
type PluginImportConfig = {
libraryName: string;
libraryDirectory?: string;
customName?: string;
customStyleName?: string;
style?: string | boolean;
styleLibraryDirectory?: string;
camelToDashComponentName?: boolean;
transformToDefaultImport?: boolean;
ignoreEsComponent?: string[];
ignoreStyleComponent?: string[];
};
type PluginImportOptions = PluginImportConfig[];
declare function resolvePluginImport(pluginImport: PluginImportOptions): RawPluginImportConfig[] | undefined;
export { resolvePluginImport };
export type { PluginImportOptions };

View File

@@ -0,0 +1,83 @@
import type { Config, EnvConfig, EsParserConfig, JscConfig, ModuleConfig, ParserConfig, TerserEcmaVersion, TransformConfig, TsParserConfig } from "../../../compiled/@swc/types";
import type { CollectTypeScriptInfoOptions } from "./collectTypeScriptInfo";
import type { PluginImportOptions } from "./pluginImport";
export type SwcLoaderEnvConfig = EnvConfig;
export type SwcLoaderJscConfig = JscConfig;
export type SwcLoaderModuleConfig = ModuleConfig;
export type SwcLoaderParserConfig = ParserConfig;
export type SwcLoaderEsParserConfig = EsParserConfig;
export type SwcLoaderTsParserConfig = TsParserConfig;
export type SwcLoaderTransformConfig = TransformConfig;
export type SwcLoaderOptions = Config & {
isModule?: boolean | "unknown";
/**
* Experimental features provided by Rspack.
* @experimental
*/
rspackExperiments?: {
import?: PluginImportOptions;
/**
* Collects information from TypeScript's AST for consumption by subsequent Rspack processes,
* providing better TypeScript development experience and smaller output bundle size.
*/
collectTypeScriptInfo?: CollectTypeScriptInfoOptions;
};
};
export interface TerserCompressOptions {
arguments?: boolean;
arrows?: boolean;
booleans?: boolean;
booleans_as_integers?: boolean;
collapse_vars?: boolean;
comparisons?: boolean;
computed_props?: boolean;
conditionals?: boolean;
dead_code?: boolean;
defaults?: boolean;
directives?: boolean;
drop_console?: boolean;
drop_debugger?: boolean;
ecma?: TerserEcmaVersion;
evaluate?: boolean;
expression?: boolean;
global_defs?: any;
hoist_funs?: boolean;
hoist_props?: boolean;
hoist_vars?: boolean;
ie8?: boolean;
if_return?: boolean;
inline?: 0 | 1 | 2 | 3;
join_vars?: boolean;
keep_classnames?: boolean;
keep_fargs?: boolean;
keep_fnames?: boolean;
keep_infinity?: boolean;
loops?: boolean;
negate_iife?: boolean;
passes?: number;
properties?: boolean;
pure_getters?: any;
pure_funcs?: string[];
reduce_funcs?: boolean;
reduce_vars?: boolean;
sequences?: any;
side_effects?: boolean;
switches?: boolean;
top_retain?: any;
toplevel?: any;
typeofs?: boolean;
unsafe?: boolean;
unsafe_passes?: boolean;
unsafe_arrows?: boolean;
unsafe_comps?: boolean;
unsafe_function?: boolean;
unsafe_math?: boolean;
unsafe_symbols?: boolean;
unsafe_methods?: boolean;
unsafe_proto?: boolean;
unsafe_regexp?: boolean;
unsafe_undefined?: boolean;
unused?: boolean;
const_to_let?: boolean;
module?: boolean;
}

View File

@@ -0,0 +1,9 @@
export declare const APIPlugin: {
new (): {
name: string;
_args: [];
affectedHooks: keyof import("..").CompilerHooks | undefined;
raw(compiler: import("..").Compiler): import("@rspack/binding").BuiltinPlugin;
apply(compiler: import("..").Compiler): void;
};
};

View File

@@ -0,0 +1,9 @@
export declare const ArrayPushCallbackChunkFormatPlugin: {
new (): {
name: string;
_args: [];
affectedHooks: keyof import("..").CompilerHooks | undefined;
raw(compiler: import("..").Compiler): import("@rspack/binding").BuiltinPlugin;
apply(compiler: import("..").Compiler): void;
};
};

View File

@@ -0,0 +1,9 @@
export declare const AssetModulesPlugin: {
new (): {
name: string;
_args: [];
affectedHooks: keyof import("..").CompilerHooks | undefined;
raw(compiler: import("..").Compiler): import("@rspack/binding").BuiltinPlugin;
apply(compiler: import("..").Compiler): void;
};
};

View File

@@ -0,0 +1,9 @@
export declare const AsyncWebAssemblyModulesPlugin: {
new (): {
name: string;
_args: [];
affectedHooks: keyof import("..").CompilerHooks | undefined;
raw(compiler: import("..").Compiler): import("@rspack/binding").BuiltinPlugin;
apply(compiler: import("..").Compiler): void;
};
};

View File

@@ -0,0 +1,40 @@
import { type Chunk } from "@rspack/binding";
export type Rule = string | RegExp;
export type Rules = Rule[] | Rule;
export type BannerFunction = (args: {
hash: string;
chunk: Chunk;
filename: string;
}) => string;
export type BannerContent = string | BannerFunction;
export type BannerPluginOptions = {
/** Specifies the banner, it will be wrapped in a comment. */
banner: BannerContent;
/** If true, the banner will only be added to the entry chunks. */
entryOnly?: boolean;
/** Exclude all modules matching any of these conditions. */
exclude?: Rules;
/** Include all modules matching any of these conditions. */
include?: Rules;
/** If true, banner will not be wrapped in a comment. */
raw?: boolean;
/** If true, banner will be placed at the end of the output. */
footer?: boolean;
/**
* The stage of the compilation in which the banner should be injected.
* @default PROCESS_ASSETS_STAGE_ADDITIONS (-100)
*/
stage?: number;
/** Include all modules that pass test assertion. */
test?: Rules;
};
export type BannerPluginArgument = BannerContent | BannerPluginOptions;
export declare const BannerPlugin: {
new (args: BannerPluginArgument): {
name: string;
_args: [args: BannerPluginArgument];
affectedHooks: keyof import("..").CompilerHooks | undefined;
raw(compiler: import("..").Compiler): import("@rspack/binding").BuiltinPlugin;
apply(compiler: import("..").Compiler): void;
};
};

View File

@@ -0,0 +1,14 @@
export type BundleInfoOptions = {
version?: string;
bundler?: string;
force?: boolean | string[];
};
export declare const BundlerInfoRspackPlugin: {
new (options: BundleInfoOptions): {
name: string;
_args: [options: BundleInfoOptions];
affectedHooks: keyof import("..").CompilerHooks | undefined;
raw(compiler: import("..").Compiler): import("@rspack/binding").BuiltinPlugin;
apply(compiler: import("..").Compiler): void;
};
};

View File

@@ -0,0 +1,9 @@
export declare const ChunkPrefetchPreloadPlugin: {
new (): {
name: string;
_args: [];
affectedHooks: keyof import("..").CompilerHooks | undefined;
raw(compiler: import("..").Compiler): import("@rspack/binding").BuiltinPlugin;
apply(compiler: import("..").Compiler): void;
};
};

View File

@@ -0,0 +1,59 @@
import { type BuiltinPlugin, BuiltinPluginName } from "@rspack/binding";
import type { Compilation } from "../Compilation";
import type { Compiler } from "../Compiler";
import type { Module } from "../Module";
import { RspackBuiltinPlugin } from "./base";
export type CircularDependencyRspackPluginOptions = {
/**
* When `true`, the plugin will emit `ERROR` diagnostics rather than the
* default `WARN` level.
*/
failOnError?: boolean;
/**
* When `true`, asynchronous imports like `import("some-module")` will not
* be considered connections that can create cycles.
*/
allowAsyncCycles?: boolean;
/**
* Cycles containing any module name that matches this regex will _not_ be
* counted as a cycle.
*/
exclude?: RegExp;
/**
* List of dependency connections that should not count for creating cycles.
* Connections are represented as `[from, to]`, where each entry is matched
* against the _identifier_ for that module in the connection. The
* identifier contains the full, unique path for the module, including all
* of the loaders that were applied to it and any request parameters.
*
* When an entry is a String, it is tested as a _substring_ of the
* identifier. For example, the entry "components/Button" would match the
* module "app/design/components/Button.tsx". When the entry is a RegExp,
* it is tested against the entire identifier.
*/
ignoredConnections?: [string | RegExp, string | RegExp][];
/**
* Called once for every detected cycle. Providing this handler overrides the
* default behavior of adding diagnostics to the compilation.
*/
onDetected?(entrypoint: Module, modules: string[], compilation: Compilation): void;
/**
* Called once for every detected cycle that was ignored because of a rule,
* either from `exclude` or `ignoredConnections`.
*/
onIgnored?(entrypoint: Module, modules: string[], compilation: Compilation): void;
/**
* Called before cycle detection begins.
*/
onStart?(compilation: Compilation): void;
/**
* Called after cycle detection finishes.
*/
onEnd?(compilation: Compilation): void;
};
export declare class CircularDependencyRspackPlugin extends RspackBuiltinPlugin {
name: BuiltinPluginName;
_options: CircularDependencyRspackPluginOptions;
constructor(options: CircularDependencyRspackPluginOptions);
raw(compiler: Compiler): BuiltinPlugin;
}

View File

@@ -0,0 +1,9 @@
export declare const CommonJsChunkFormatPlugin: {
new (): {
name: string;
_args: [];
affectedHooks: keyof import("..").CompilerHooks | undefined;
raw(compiler: import("..").Compiler): import("@rspack/binding").BuiltinPlugin;
apply(compiler: import("..").Compiler): void;
};
};

View File

@@ -0,0 +1,9 @@
export declare const ContextReplacementPlugin: {
new (resourceRegExp: RegExp, newContentResource?: any, newContentRecursive?: any, newContentRegExp?: any): {
name: string;
_args: [resourceRegExp: RegExp, newContentResource?: any, newContentRecursive?: any, newContentRegExp?: any];
affectedHooks: keyof import("..").CompilerHooks | undefined;
raw(compiler: import("..").Compiler): import("@rspack/binding").BuiltinPlugin;
apply(compiler: import("..").Compiler): void;
};
};

View File

@@ -0,0 +1,14 @@
import { type RawCopyPattern } from "@rspack/binding";
export type CopyRspackPluginOptions = {
/** An array of objects that describe the copy operations to be performed. */
patterns: (string | (Pick<RawCopyPattern, "from"> & Partial<Omit<RawCopyPattern, "from">>))[];
};
export declare const CopyRspackPlugin: {
new (copy: CopyRspackPluginOptions): {
name: string;
_args: [copy: CopyRspackPluginOptions];
affectedHooks: keyof import("..").CompilerHooks | undefined;
raw(compiler: import("..").Compiler): import("@rspack/binding").BuiltinPlugin;
apply(compiler: import("..").Compiler): void;
};
};

View File

@@ -0,0 +1,21 @@
import binding from "@rspack/binding";
export interface CssChunkingPluginOptions {
strict?: boolean;
minSize?: number;
maxSize?: number;
/**
* This plugin is intended to be generic, but currently requires some special handling for Next.js.
* A `next` option has been added to accommodate this.
* In the future, once the design of CssChunkingPlugin becomes more stable, this option may be removed.
*/
nextjs?: boolean;
}
export declare const CssChunkingPlugin: {
new (options?: CssChunkingPluginOptions | undefined): {
name: string;
_args: [options?: CssChunkingPluginOptions | undefined];
affectedHooks: keyof import("..").CompilerHooks | undefined;
raw(compiler: import("..").Compiler): binding.BuiltinPlugin;
apply(compiler: import("..").Compiler): void;
};
};

View File

@@ -0,0 +1,9 @@
export declare const CssModulesPlugin: {
new (): {
name: string;
_args: [];
affectedHooks: keyof import("..").CompilerHooks | undefined;
raw(compiler: import("..").Compiler): import("@rspack/binding").BuiltinPlugin;
apply(compiler: import("..").Compiler): void;
};
};

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