Initial commit: New MoreminiMore website with fresh design
This commit is contained in:
586
node_modules/sitemap/CHANGELOG.md
generated
vendored
Normal file
586
node_modules/sitemap/CHANGELOG.md
generated
vendored
Normal file
@@ -0,0 +1,586 @@
|
||||
# Changelog
|
||||
|
||||
## 9.0.1 — Security Patch
|
||||
|
||||
- **BB-01**: Fix XML injection via unescaped `xslUrl` in stylesheet processing instruction — special characters (`&`, `"`, `<`, `>`) in the XSL URL are now escaped before being interpolated into the `<?xml-stylesheet?>` processing instruction
|
||||
- **BB-02**: Enforce 50,000 URL hard limit in `XMLToSitemapItemStream` — the parser now stops emitting items and emits an error when the limit is exceeded, rather than merely logging a warning
|
||||
- **BB-03**: Cap parser error array at 100 entries to prevent memory DoS — `XMLToSitemapItemStream` now tracks a separate `errorCount` and stops appending to the `errors` array beyond `LIMITS.MAX_PARSER_ERRORS`
|
||||
- **BB-04**: Reject absolute `destinationDir` paths in `simpleSitemapAndIndex` to prevent arbitrary file writes — passing an absolute path (e.g. `/tmp/sitemaps`) now throws immediately with a descriptive error
|
||||
- **BB-05**: `parseSitemapIndex` now destroys source and parser streams immediately when the `maxEntries` limit is exceeded, preventing unbounded memory consumption from large sitemap index files
|
||||
|
||||
## 9.0.0 - 2025-11-01
|
||||
|
||||
This major release modernizes the package with ESM-first architecture, drops support for Node.js < 20, and includes comprehensive security and robustness improvements.
|
||||
|
||||
### [BREAKING CHANGES]
|
||||
|
||||
#### Dropped Node.js < 20 Support
|
||||
|
||||
- **Node.js >=20.19.5 now required** (previously >=14.0.0)
|
||||
- **npm >=10.8.2 now required** (previously >=6.0.0)
|
||||
- Dropped support for Node.js 14, 16, and 18
|
||||
|
||||
#### ESM Conversion with Dual Package Support
|
||||
|
||||
- Package now uses `"type": "module"` in package.json
|
||||
- Built as dual ESM/CJS package with conditional exports
|
||||
- **Import paths in ESM require `.js` extensions** (TypeScript will add these automatically)
|
||||
- Both ESM and CommonJS imports continue to work:
|
||||
|
||||
```js
|
||||
// ESM (new default)
|
||||
import { SitemapStream } from 'sitemap'
|
||||
|
||||
// CommonJS (still supported)
|
||||
const { SitemapStream } = require('sitemap')
|
||||
```
|
||||
|
||||
- CLI remains ESM-only at `dist/esm/cli.js`
|
||||
|
||||
#### Build Output Changes
|
||||
|
||||
- ESM output: `dist/esm/` (was `dist/`)
|
||||
- CJS output: `dist/cjs/` (new)
|
||||
- TypeScript definitions: `dist/esm/index.d.ts` (was `dist/index.d.ts`)
|
||||
|
||||
#### Node.js Modernization
|
||||
|
||||
- All built-in Node.js modules now use `node:` protocol imports (`node:stream`, `node:fs`, etc.)
|
||||
- Uses native promise-based `pipeline` from `node:stream/promises` (instead of `promisify(pipeline)`)
|
||||
- TypeScript target updated to ES2023 (from ES2022)
|
||||
|
||||
### New Exports
|
||||
|
||||
The following validation functions and constants are now part of the public API:
|
||||
|
||||
**Validation Functions** (from `lib/validation.js`):
|
||||
|
||||
- `validateURL()`, `validatePath()`, `validateLimit()`, `validatePublicBasePath()`, `validateXSLUrl()`
|
||||
- Type guards: `isPriceType()`, `isResolution()`, `isValidChangeFreq()`, `isValidYesNo()`, `isAllowDeny()`
|
||||
- `validators` - object containing regex validators for all sitemap fields
|
||||
|
||||
**Constants** (from `lib/constants.js`):
|
||||
|
||||
- `LIMITS` - security limits object (max URL length, max items per sitemap, video/news/image constraints, etc.)
|
||||
- `DEFAULT_SITEMAP_ITEM_LIMIT` - default items per sitemap file (45,000)
|
||||
|
||||
**New Type Export**:
|
||||
|
||||
- `SimpleSitemapAndIndexOptions` interface now exported
|
||||
|
||||
### Features
|
||||
|
||||
#### Comprehensive Security Validation
|
||||
|
||||
- **Parser Security** (#461): Added resource limits and comprehensive validation to sitemap index parser and stream
|
||||
- Max 50K URLs per sitemap, 1K images, 100 videos per entry
|
||||
- String length limits on all fields
|
||||
- URL validation (http/https only, max 2048 chars)
|
||||
- Protocol injection prevention (blocks javascript:, data:, file:, ftp:)
|
||||
- Path traversal prevention (blocks `..` sequences)
|
||||
|
||||
- **Stream Validation** (#456, #455, #454): Added comprehensive validation to all stream classes
|
||||
- Enhanced XML entity escaping (including `>` character)
|
||||
- Attribute name validation
|
||||
- Date format validation (ISO 8601)
|
||||
- Input validation for numbers (reject NaN/Infinity), dates (check Invalid Date)
|
||||
- XSL URL validation to prevent script injection
|
||||
- Custom namespace validation (max 20 namespaces, max 512 chars each)
|
||||
|
||||
- **XML Generation Security** (#457): Comprehensive validation and documentation in sitemap-xml
|
||||
- Safe XML attribute and element generation
|
||||
- Protection against XML injection attacks
|
||||
|
||||
#### Robustness Improvements
|
||||
|
||||
- **Sitemap Item Stream** (#453): Improved robustness and type safety
|
||||
- **Sitemap Index Stream** (#449): Enhanced robustness and test coverage
|
||||
- **Sitemap Index Parser** (#448): Improved error handling and robustness
|
||||
- **Code Quality** (#458): Comprehensive security and code quality improvements across codebase
|
||||
|
||||
### Fixes
|
||||
|
||||
- Fixed TS151002 warning and test race condition (#455)
|
||||
- Improved sitemap-item-stream robustness and type safety (#453)
|
||||
- Enhanced sitemap-index-stream error handling (#449)
|
||||
- Improved sitemap-index-parser error handling (#448)
|
||||
- Fixed coverage reporting (#399, #434)
|
||||
- Fixed invalid XML regex for better performance (#437, #417)
|
||||
- Improved normalizeURL performance (#416)
|
||||
|
||||
### Refactoring
|
||||
|
||||
- **Architecture Reorganization** (#460): Consolidated constants and validation
|
||||
- Created `lib/constants.ts` - single source of truth for all shared constants
|
||||
- Created `lib/validation.ts` - centralized all validation logic and type guards
|
||||
- Eliminated duplicate constants and validation code across files
|
||||
- Prevents inconsistencies where different files used different values
|
||||
|
||||
### Infrastructure
|
||||
|
||||
#### Build System
|
||||
|
||||
- Dual ESM/CJS build with separate TypeScript configurations
|
||||
- `tsconfig.json` - ESM build (NodeNext module resolution)
|
||||
- `tsconfig.cjs.json` - CJS build (CommonJS module)
|
||||
- Build outputs `package.json` with `"type": "commonjs"` to `dist/cjs/`
|
||||
- Test infrastructure converted to ESM
|
||||
- Updated Jest configuration for ESM support
|
||||
|
||||
#### Testing
|
||||
|
||||
- Converted to ts-jest for better TypeScript support (#434)
|
||||
- All 172+ tests passing with 91%+ code coverage
|
||||
- Enhanced security-focused test coverage
|
||||
- Performance tests converted to `.mjs` format
|
||||
|
||||
#### Dependencies
|
||||
|
||||
- Updated `sax` from ^1.2.4 to ^1.4.1
|
||||
- Updated `@types/node` from ^17.0.5 to ^24.7.2
|
||||
- Removed unused dependencies (#459)
|
||||
- Updated all dev dependencies to latest versions
|
||||
- Replaced babel-based test setup with ts-jest
|
||||
|
||||
#### Developer Experience
|
||||
|
||||
- Updated examples to ESM syntax in README (#452)
|
||||
- Updated API documentation for accuracy and ESM syntax (#452)
|
||||
- Added comprehensive CLAUDE.md with architecture documentation
|
||||
- Improved ESLint and Prettier integration
|
||||
- Updated git hooks with Husky 9.x
|
||||
|
||||
### Upgrade Guide for 9.0.0
|
||||
|
||||
#### 1. Update Node.js Version
|
||||
|
||||
Ensure you are running Node.js >=20.19.5 and npm >=10.8.2:
|
||||
|
||||
```bash
|
||||
node --version # Should be 20.19.5 or higher
|
||||
npm --version # Should be 10.8.2 or higher
|
||||
```
|
||||
|
||||
#### 2. Update Package
|
||||
|
||||
```bash
|
||||
npm install sitemap@9.0.0
|
||||
```
|
||||
|
||||
#### 3. Import Syntax (No Changes Required for Most Users)
|
||||
|
||||
Both ESM and CommonJS imports continue to work:
|
||||
|
||||
```js
|
||||
// ESM - works the same as before
|
||||
import { SitemapStream, streamToPromise } from 'sitemap'
|
||||
|
||||
// CommonJS - works the same as before
|
||||
const { SitemapStream, streamToPromise } = require('sitemap')
|
||||
```
|
||||
|
||||
**Note**: If you're importing from the package in an ESM context, the module resolution happens automatically. If you're directly importing library files (not recommended), you'll need `.js` extensions.
|
||||
|
||||
#### 4. Existing Code Compatibility
|
||||
|
||||
- ✅ **All existing valid data continues to work unchanged**
|
||||
- ✅ **Public API is fully compatible** - same classes, methods, and options
|
||||
- ✅ **Stream behavior unchanged** - all streaming patterns continue to work
|
||||
- ✅ **Error handling unchanged** - `ErrorLevel.WARN` default behavior maintained
|
||||
- ⚠️ **Invalid data may now be rejected** due to enhanced security validation
|
||||
- URLs must be http/https protocol (no javascript:, data:, etc.)
|
||||
- String lengths enforced per sitemaps.org spec
|
||||
- Resource limits enforced (50K URLs, 1K images, 100 videos per entry)
|
||||
|
||||
#### 5. TypeScript Users
|
||||
|
||||
- Update `tsconfig.json` if needed to support ES2023
|
||||
- Type definitions are now at `dist/esm/index.d.ts` (automatically resolved by package.json exports)
|
||||
- No changes needed to your TypeScript code
|
||||
|
||||
#### 6. New Optional Features
|
||||
|
||||
You can now import validation utilities and constants if needed:
|
||||
|
||||
```js
|
||||
import { LIMITS, validateURL, validators } from 'sitemap'
|
||||
|
||||
// Check limits
|
||||
console.log(LIMITS.MAX_URL_LENGTH) // 2048
|
||||
|
||||
// Validate URLs
|
||||
const url = validateURL('https://example.com/page')
|
||||
|
||||
// Use validators
|
||||
if (validators['video:rating'].test('4.5')) {
|
||||
// valid rating
|
||||
}
|
||||
```
|
||||
|
||||
## 8.0.2 - Bug Fix Release
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
- **fix #464**: Support `xsi:schemaLocation` in custom namespaces - thanks @dzakki
|
||||
- Extended custom namespace validation to accept namespace-qualified attributes (like `xsi:schemaLocation`) in addition to `xmlns` declarations
|
||||
- The validation regex now matches both `xmlns:prefix="uri"` and `prefix:attribute="value"` patterns
|
||||
- Enables proper W3C schema validation while maintaining security validation for malicious content
|
||||
- Added comprehensive tests including security regression tests
|
||||
|
||||
### Example Usage
|
||||
|
||||
The following now works correctly (as documented in README):
|
||||
|
||||
```javascript
|
||||
const sms = new SitemapStream({
|
||||
xmlns: {
|
||||
custom: [
|
||||
'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"',
|
||||
'xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"'
|
||||
]
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
### Testing
|
||||
|
||||
- ✅ All existing tests passing
|
||||
- ✅ 8 new tests added covering positive and security scenarios
|
||||
- ✅ 100% backward compatible with 8.0.1
|
||||
|
||||
### Files Changed
|
||||
|
||||
2 files changed: 144 insertions, 5 deletions
|
||||
|
||||
## 8.0.1 - Security Patch Release
|
||||
|
||||
**SECURITY FIXES** - This release backports comprehensive security patches from 9.0.0 to 8.0.x
|
||||
|
||||
### Security Improvements
|
||||
|
||||
- **XML Injection Prevention**: Enhanced XML entity escaping, added `>` character escaping, attribute name validation
|
||||
- **Parser Security**: Added resource limits (max 50K URLs, 1K images, 100 videos per sitemap), string length limits, URL validation (http/https only, max 2048 chars)
|
||||
- **Protocol Injection Prevention**: Block dangerous protocols (javascript:, data:, file:, ftp:) in sitemap index parser
|
||||
- **DoS Protection**: Memory exhaustion protection, URL length validation, date format validation (ISO 8601)
|
||||
- **Path Traversal Prevention**: Block `..` sequences in file paths
|
||||
- **Command Injection Fix**: xmllint now uses stdin exclusively instead of file paths
|
||||
- **Input Validation**: Comprehensive validation for all user inputs - numbers (reject NaN/Infinity), dates (check Invalid Date), URLs, paths
|
||||
- **XSS Prevention**: XSL URL validation to prevent script injection
|
||||
- **Namespace Security**: Custom namespace validation (max 20, max 512 chars each)
|
||||
|
||||
### Infrastructure
|
||||
|
||||
- Added `lib/constants.ts` - Centralized security limits and constants
|
||||
- Added `lib/validation.ts` - Comprehensive validation functions
|
||||
- Added new security-related error classes
|
||||
|
||||
### Backward Compatibility
|
||||
|
||||
- ✅ **100% API compatible** with 8.0.0
|
||||
- Added `XMLToSitemapItemStream.error` getter for backward compatibility (returns `errors[0]`)
|
||||
- All existing valid inputs continue to work
|
||||
- Only rejects invalid/malicious inputs
|
||||
- Default `ErrorLevel.WARN` behavior unchanged
|
||||
|
||||
### Dependencies Updated
|
||||
|
||||
- `sax`: ^1.2.4 → ^1.4.1 (security updates)
|
||||
|
||||
### Files Changed
|
||||
|
||||
17 files changed: 2,122 additions, 245 deletions
|
||||
|
||||
### Testing
|
||||
|
||||
- All 94 existing tests passing
|
||||
- No breaking changes to public API
|
||||
|
||||
## 8.0.0
|
||||
|
||||
- fix #423 via #424 thanks @huntharo - Propagate errors in SitemapAndIndexStream
|
||||
- drop node 12 support
|
||||
|
||||
## 7.1.2
|
||||
|
||||
- fix #425 via #426 thanks to @huntharo update streamToPromise to bubble up errors + jsDoc
|
||||
- fix #415 thanks to @mohd-akram Fix circular dependency breaking Node.js 20.6
|
||||
- non-breaking updates of dependent packages
|
||||
|
||||
## 7.1.1
|
||||
|
||||
- fix #378 exit code not set on parse failure. A proper error will be set on the stream now.
|
||||
- fix #384 thanks @tomcek112 parseSitemapIndex not included in 7.1.0 release
|
||||
- fix #356 thanks @vandres - SitemapIndexStream now has lastmodDateOnly
|
||||
- Fix #375 thanks @huntharo parseSitemap and parseSitemapIndex uncatchable errors
|
||||
- Filter out null as well when writing XML thanks @huntharo #376
|
||||
|
||||
## 7.1.0
|
||||
|
||||
- bumped types dependency for node
|
||||
- bumped all dev dependencies - includes some prettier changes
|
||||
- package-lock updated to version 2
|
||||
|
||||
## 7.0.0
|
||||
|
||||
### [BREAKING]
|
||||
|
||||
- dropped support for Node 10, added support for Node 16
|
||||
- removed deprecated createSitemapsAndIndex. use SitemapAndIndexStream or simpleSitemapAndIndex
|
||||
- dropped deprecated `getSitemapStream` option for SitemapAndIndexStream that does not return a write stream
|
||||
- fixed invalid documentation for #357
|
||||
|
||||
### non-breaking
|
||||
|
||||
- Added option to simplesitemap `publicBasePath`: allows the user to set the location of sitemap files hosted on the site fixes [#359]
|
||||
- bumped dependencies
|
||||
|
||||
## 6.4.0
|
||||
|
||||
- added support for content_loc parsing #347 and uploader info attr
|
||||
- added error handler option to sitemapstream #349 Thanks @marcoreni
|
||||
|
||||
## 6.3.6
|
||||
|
||||
- bump dependencies
|
||||
|
||||
## 6.3.5
|
||||
|
||||
- Add option to silence or redirect logs from parse #337
|
||||
- `new XMLToSitemapItemStream({ logger: false })` or
|
||||
- `new XMLToSitemapItemStream({ level: ErrorLevel.SILENT })` or
|
||||
- `new XMLToSitemapItemStream({ logger: (level, ...message) => your.custom.logger(...message) })`
|
||||
|
||||
## 6.3.4
|
||||
|
||||
- bump dependencies
|
||||
- correct return type of xmllint. Was `Promise<null>` but actually returned `Promise<void>`
|
||||
- add alternate option for lang, hreflang as that is the actual name of the printed attribute
|
||||
|
||||
## 6.3.3
|
||||
|
||||
- bump ts to 4
|
||||
- change file reference in sitemap-index to include .gz fixes #334
|
||||
|
||||
## 6.3.2
|
||||
|
||||
- fix unreported timing issue in SitemapAndIndexStream uncovered in latest unit tests
|
||||
|
||||
## 6.3.1
|
||||
|
||||
- fix #331 incorrect type on sourceData in simpleSitemapAndIndex.
|
||||
|
||||
## 6.3.0
|
||||
|
||||
- simpleSitemap will create the dest directory if it doesn't exist
|
||||
- allow user to not gzip fixes #322
|
||||
|
||||
## 6.2.0
|
||||
|
||||
- Add simplified interface for creating sitemaps and index
|
||||
- fix bug where sitemap and index stream would not properly wait to emit finish event until all sitemaps had been written
|
||||
- bump deps
|
||||
|
||||
## 6.1.7
|
||||
|
||||
- Improve documentation and error messaging on ending a stream too early #317
|
||||
- bump dependencies
|
||||
|
||||
## 6.1.6
|
||||
|
||||
- support allow_embed #314
|
||||
- bump dependencies
|
||||
|
||||
## 6.1.5
|
||||
|
||||
- performance improvement for streamToPromise #307
|
||||
|
||||
## 6.1.4
|
||||
|
||||
- remove stale files from dist #298
|
||||
- Correct documentation on renamed XMLToSitemapOptions, XMLToSitemapItemStream #297
|
||||
- bump node typedef to 14.0.1
|
||||
|
||||
## 6.1.3
|
||||
|
||||
- bump node types resolves #293
|
||||
|
||||
## 6.1.2
|
||||
|
||||
- bump node types resolves #290
|
||||
|
||||
## 6.1.1
|
||||
|
||||
- Fix #286 sitemapindex tag not closing for deprecated createSitemapsAndIndex
|
||||
|
||||
## 6.1.0
|
||||
|
||||
- Added back xslUrl option removed in 5.0.0
|
||||
|
||||
## 6.0.0
|
||||
|
||||
- removed xmlbuilder as a dependency
|
||||
- added stronger validity checking on values supplied to sitemap
|
||||
- Added the ability to turn off or add custom xml namespaces
|
||||
- CLI and library now can accept a stream which will automatically write both the index and the sitemaps. See README for usage.
|
||||
|
||||
### 6.0.0 breaking changes
|
||||
|
||||
- renamed XMLToISitemapOptions to XMLToSitemapOptions
|
||||
- various error messages changed.
|
||||
- removed deprecated Sitemap and SitemapIndex classes
|
||||
- replaced buildSitemapIndex with SitemapIndexStream
|
||||
- Typescript: various types renamed or made more specific, removed I prefix
|
||||
- Typescript: view_count is now exclusively a number
|
||||
- Typescript: `price:type` and `price:resolution` are now more restrictive types
|
||||
- sitemap parser now returns a sitemapItem array rather than a config object that could be passed to the now removed Sitemap class
|
||||
- CLI no longer accepts multiple file arguments or a mixture of file and streams except as a part of a parameter eg. prepend
|
||||
|
||||
## 5.1.0
|
||||
|
||||
Fix for #255. Baidu does not like timestamp in its sitemap.xml, this adds an option to truncate lastmod
|
||||
|
||||
```js
|
||||
new SitemapStream({ lastmodDateOnly: true });
|
||||
```
|
||||
|
||||
## 5.0.1
|
||||
|
||||
Fix for issue #254.
|
||||
|
||||
```sh
|
||||
warning: failed to load external entity "./schema/all.xsd"
|
||||
Schemas parser error : Failed to locate the main schema resource at './schema/all.xsd'.
|
||||
WXS schema ./schema/all.xsd failed to compile
|
||||
```
|
||||
|
||||
## 5.0.0
|
||||
|
||||
### Streams
|
||||
|
||||
This release is heavily focused on converting the core methods of this library to use streams. Why? Overall its made the API ~20% faster and uses only 10% or less of the memory. Some tradeoffs had to be made as in their nature streams are operate on individual segments of data as opposed to the whole. For instance, the streaming interface does not support removal of sitemap items as it does not hold on to a sitemap item after its converted to XML. It should however be possible to create your own transform that filters out entries should you desire it. The existing synchronous interfaces will remain for this release at least. Do not be surprised if they go away in a future breaking release.
|
||||
|
||||
### Sitemap Index
|
||||
|
||||
This library interface has been overhauled to use streams internally. Although it would have been preferable to convert this to a stream as well, I could not think of an interface that wouldn't actually end up more complex or confusing. It may be altered in the near future to accept a stream in addition to a simple list.
|
||||
|
||||
### Misc
|
||||
|
||||
- runnable examples, some pulled straight from README have been added to the examples directory.
|
||||
- createSitemapsIndex was renamed createSitemapsAndIndex to more accurately reflect its function. It now returns a promise that resolves to true or throws with an error.
|
||||
- You can now add to existing sitemap.xml files via the cli using `npx sitemap --prepend existingSitemap.xml < listOfNewURLs.json.txt`
|
||||
|
||||
### 5.0 Breaking Changes
|
||||
|
||||
- Dropped support for mobile sitemap - Google appears to have deleted their dtd and all references to it, strongly implying that they do not want you to use it. As its absence now breaks the validator, it has been dropped.
|
||||
- normalizeURL(url, XMLRoot, hostname) -> normalizeURL(url, hostname)
|
||||
- The second argument was unused and has been eliminated
|
||||
- Support for Node 8 dropped - Node 8 is reaching its EOL December 2019
|
||||
- xslURL is being dropped from all apis - styling xml is out of scope of this library.
|
||||
- createSitemapIndex has been converted to a promised based api rather than callback.
|
||||
- createSitemapIndex now gzips by default - pass gzip: false to disable
|
||||
- cacheTime is being dropped from createSitemapIndex - This didn't actually cache the way it was written so this should be a non-breaking change in effect.
|
||||
- SitemapIndex as a class has been dropped. The class did all its work on construction and there was no reason to hold on to it once you created it.
|
||||
- The options for the cli have been overhauled
|
||||
- `--json` is now inferred
|
||||
- `--line-separated` has been flipped to `--single-line-json` to by default output options immediately compatible with feeding back into sitemap
|
||||
|
||||
## 4.1.1
|
||||
|
||||
Add a pretty print option to `toString(false)`
|
||||
pass true pretty print
|
||||
|
||||
Add an xmlparser that will output a config that would generate that same file
|
||||
|
||||
cli:
|
||||
use --parser to output the complete config --line-separated to print out line
|
||||
separated config compatible with the --json input option for cli
|
||||
|
||||
lib: import parseSitemap and pass it a stream
|
||||
|
||||
## 4.0.2
|
||||
|
||||
Fix npx script error - needs the shebang
|
||||
|
||||
## 4.0.1
|
||||
|
||||
Validation functions which depend on xmllint will now warn if you do not have xmllint installed.
|
||||
|
||||
## 4.0.0
|
||||
|
||||
This release is geared around overhauling the public api for this library. Many
|
||||
options have been introduced over the years and this has lead to some inconsistencies
|
||||
that make the library hard to use. Most have been cleaned up but a couple notable
|
||||
items remain, including the confusing names of buildSitemapIndex and createSitemapIndex
|
||||
|
||||
- A new experimental CLI
|
||||
- stream in a list of urls stream out xml
|
||||
- validate your generated sitemap
|
||||
- Sitemap video item now supports id element
|
||||
- Several schema errors have been cleaned up.
|
||||
- Docs have been updated and streamlined.
|
||||
|
||||
### breaking changes
|
||||
|
||||
- lastmod option parses all ISO8601 date-only strings as being in UTC rather than local time
|
||||
- lastmodISO is deprecated as it is equivalent to lastmod
|
||||
- lastmodfile now includes the file's time as well
|
||||
- lastmodrealtime is no longer necessary
|
||||
- The default export of sitemap lib is now just createSitemap
|
||||
- Sitemap constructor now uses a object for its constructor
|
||||
|
||||
```js
|
||||
const { Sitemap } = require('sitemap');
|
||||
const siteMap = new Sitemap({
|
||||
urls = [],
|
||||
hostname: 'https://example.com', // optional
|
||||
cacheTime = 0,
|
||||
xslUrl,
|
||||
xmlNs,
|
||||
level = 'warn'
|
||||
})
|
||||
```
|
||||
|
||||
- Sitemap no longer accepts a single string for its url
|
||||
- Drop support for node 6
|
||||
- Remove callback on toXML - This had no performance benefit
|
||||
- Direct modification of urls property on Sitemap has been dropped. Use add/remove/contains
|
||||
- When a Sitemap item is generated with invalid options it no longer throws by default
|
||||
- instead it console warns.
|
||||
- if you'd like to pre-verify your data the `validateSMIOptions` function is
|
||||
now available
|
||||
- To get the previous behavior pass level `createSitemap({...otheropts, level: 'throw' }) // ErrorLevel.THROW for TS users`
|
||||
|
||||
## 3.2.2
|
||||
|
||||
- revert https everywhere added in 3.2.0. xmlns is not url.
|
||||
- adds alias for lastmod in the form of lastmodiso
|
||||
- fixes bug in lastmod option for buildSitemapIndex where option would be overwritten if a lastmod option was provided with a single url
|
||||
- fixes #201, fixes #203
|
||||
|
||||
## 3.2.1
|
||||
|
||||
- no really fixes ts errors for real this time
|
||||
- fixes #193 in PR #198
|
||||
|
||||
## 3.2.0
|
||||
|
||||
- fixes #192, fixes #193 typescript errors
|
||||
- correct types on player:loc and restriction:relationship types
|
||||
- use https urls in xmlns
|
||||
|
||||
## 3.1.0
|
||||
|
||||
- fixes #187, #188 typescript errors
|
||||
- adds support for full precision priority #176
|
||||
|
||||
## 3.0.0
|
||||
|
||||
- Converted project to typescript
|
||||
- properly encode URLs #179
|
||||
- updated core dependency
|
||||
|
||||
### 3.0 breaking changes
|
||||
|
||||
This will likely not break anyone's code but we're bumping to be safe
|
||||
|
||||
- root domain URLs are now suffixed with / (eg. `https://www.ya.ru` -> `https://www.ya.ru/`) This is a side-effect of properly encoding passed in URLs
|
||||
346
node_modules/sitemap/CLAUDE.md
generated
vendored
Normal file
346
node_modules/sitemap/CLAUDE.md
generated
vendored
Normal file
@@ -0,0 +1,346 @@
|
||||
# CLAUDE.md
|
||||
|
||||
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
||||
|
||||
## Project Overview
|
||||
|
||||
sitemap.js is a TypeScript library and CLI tool for generating sitemap XML files compliant with the sitemaps.org protocol. It supports streaming large datasets, handles sitemap indexes for >50k URLs, and includes parsers for reading existing sitemaps.
|
||||
|
||||
## Development Commands
|
||||
|
||||
### Building
|
||||
```bash
|
||||
npm run build # Compile TypeScript to dist/esm/ and dist/cjs/
|
||||
npm run build:esm # Build ESM only (dist/esm/)
|
||||
npm run build:cjs # Build CJS only (dist/cjs/)
|
||||
```
|
||||
|
||||
### Testing
|
||||
```bash
|
||||
npm test # Run Jest tests with coverage
|
||||
npm run test:full # Run lint, build, Jest, and xmllint validation
|
||||
npm run test:typecheck # Type check only (tsc)
|
||||
npm run test:perf # Run performance tests (tests/perf.mjs)
|
||||
npm run test:xmllint # Validate XML schema (requires xmllint)
|
||||
```
|
||||
|
||||
### Linting
|
||||
```bash
|
||||
npx eslint lib/* ./cli.ts # Lint TypeScript files
|
||||
npx eslint lib/* ./cli.ts --fix # Auto-fix linting issues
|
||||
```
|
||||
|
||||
### Running CLI Locally
|
||||
```bash
|
||||
node dist/esm/cli.js < urls.txt # Run CLI from built dist
|
||||
./dist/esm/cli.js --version # Run directly (has shebang)
|
||||
npm link && sitemap --version # Link and test as global command
|
||||
```
|
||||
|
||||
## Code Architecture
|
||||
|
||||
### Entry Points
|
||||
- **[index.ts](index.ts)**: Main library entry point, exports all public APIs
|
||||
- **[cli.ts](cli.ts)**: Command-line interface for generating/parsing sitemaps
|
||||
|
||||
### File Organization & Responsibilities
|
||||
|
||||
The library follows a strict separation of concerns. Each file has a specific purpose:
|
||||
|
||||
**Core Infrastructure:**
|
||||
- **[lib/types.ts](lib/types.ts)**: ALL TypeScript type definitions, interfaces, and enums. NO implementation code.
|
||||
- **[lib/constants.ts](lib/constants.ts)**: Single source of truth for all shared constants (limits, regexes, defaults).
|
||||
- **[lib/validation.ts](lib/validation.ts)**: ALL validation logic, type guards, and validators centralized here.
|
||||
- **[lib/utils.ts](lib/utils.ts)**: Stream utilities, URL normalization, and general helper functions.
|
||||
- **[lib/errors.ts](lib/errors.ts)**: Custom error class definitions.
|
||||
- **[lib/sitemap-xml.ts](lib/sitemap-xml.ts)**: Low-level XML generation utilities (text escaping, tag building).
|
||||
|
||||
**Stream Processing:**
|
||||
- **[lib/sitemap-stream.ts](lib/sitemap-stream.ts)**: Main transform stream for URL → sitemap XML.
|
||||
- **[lib/sitemap-item-stream.ts](lib/sitemap-item-stream.ts)**: Lower-level stream for sitemap item → XML elements.
|
||||
- **[lib/sitemap-index-stream.ts](lib/sitemap-index-stream.ts)**: Streams for sitemap indexes and multi-file generation.
|
||||
|
||||
**Parsers:**
|
||||
- **[lib/sitemap-parser.ts](lib/sitemap-parser.ts)**: Parses sitemap XML → SitemapItem objects.
|
||||
- **[lib/sitemap-index-parser.ts](lib/sitemap-index-parser.ts)**: Parses sitemap index XML → IndexItem objects.
|
||||
|
||||
**High-Level API:**
|
||||
- **[lib/sitemap-simple.ts](lib/sitemap-simple.ts)**: Simplified API for common use cases.
|
||||
|
||||
### Core Streaming Architecture
|
||||
|
||||
The library is built on Node.js Transform streams for memory-efficient processing of large URL lists:
|
||||
|
||||
**Stream Chain Flow:**
|
||||
```
|
||||
Input → Transform Stream → Output
|
||||
```
|
||||
|
||||
**Key Stream Classes:**
|
||||
|
||||
1. **SitemapStream** ([lib/sitemap-stream.ts](lib/sitemap-stream.ts))
|
||||
- Core Transform stream that converts `SitemapItemLoose` objects to sitemap XML
|
||||
- Handles single sitemaps (up to ~50k URLs)
|
||||
- Automatically generates XML namespaces for images, videos, news, xhtml
|
||||
- Uses `SitemapItemStream` internally for XML element generation
|
||||
|
||||
2. **SitemapAndIndexStream** ([lib/sitemap-index-stream.ts](lib/sitemap-index-stream.ts))
|
||||
- Higher-level stream for handling >50k URLs
|
||||
- Automatically splits into multiple sitemap files when limit reached
|
||||
- Generates sitemap index XML pointing to individual sitemaps
|
||||
- Requires `getSitemapStream` callback to create output files
|
||||
|
||||
3. **SitemapItemStream** ([lib/sitemap-item-stream.ts](lib/sitemap-item-stream.ts))
|
||||
- Low-level Transform stream that converts sitemap items to XML elements
|
||||
- Validates and normalizes URLs
|
||||
- Handles image, video, news, and link extensions
|
||||
|
||||
4. **XMLToSitemapItemStream** ([lib/sitemap-parser.ts](lib/sitemap-parser.ts))
|
||||
- Parser that converts sitemap XML back to `SitemapItem` objects
|
||||
- Built on SAX parser for streaming large XML files
|
||||
|
||||
5. **SitemapIndexStream** ([lib/sitemap-index-stream.ts](lib/sitemap-index-stream.ts))
|
||||
- Generates sitemap index XML from a list of sitemap URLs
|
||||
- Used for organizing multiple sitemaps
|
||||
|
||||
### Type System
|
||||
|
||||
**[lib/types.ts](lib/types.ts)** defines the core data structures:
|
||||
|
||||
- **SitemapItemLoose**: Flexible input type (accepts strings, objects, arrays for images/videos)
|
||||
- **SitemapItem**: Strict normalized type (arrays only)
|
||||
- **ErrorLevel**: Enum controlling validation behavior (SILENT, WARN, THROW)
|
||||
- **NewsItem**, **Img**, **VideoItem**, **LinkItem**: Extension types for rich sitemap entries
|
||||
- **IndexItem**: Structure for sitemap index entries
|
||||
- **StringObj**: Generic object with string keys (used for XML attributes)
|
||||
|
||||
### Constants & Limits
|
||||
|
||||
**[lib/constants.ts](lib/constants.ts)** is the single source of truth for:
|
||||
- `LIMITS`: Security limits (max URL length, max items per sitemap, max video tags, etc.)
|
||||
- `DEFAULT_SITEMAP_ITEM_LIMIT`: Default items per sitemap file (45,000)
|
||||
|
||||
All limits are documented with references to sitemaps.org and Google specifications.
|
||||
|
||||
### Validation & Normalization
|
||||
|
||||
**[lib/validation.ts](lib/validation.ts)** centralizes ALL validation logic:
|
||||
- `validateSMIOptions()`: Validates complete sitemap item fields
|
||||
- `validateURL()`, `validatePath()`, `validateLimit()`: Input validation
|
||||
- `validators`: Regex patterns for field validation (price, language, genres, etc.)
|
||||
- Type guards: `isPriceType()`, `isResolution()`, `isValidChangeFreq()`, `isValidYesNo()`, `isAllowDeny()`
|
||||
|
||||
**[lib/utils.ts](lib/utils.ts)** contains utility functions:
|
||||
- `normalizeURL()`: Converts `SitemapItemLoose` to `SitemapItem` with validation
|
||||
- `lineSeparatedURLsToSitemapOptions()`: Stream transform for parsing line-delimited URLs
|
||||
- `ReadlineStream`: Helper for reading line-by-line input
|
||||
- `mergeStreams()`: Combines multiple streams into one
|
||||
|
||||
### XML Generation
|
||||
|
||||
**[lib/sitemap-xml.ts](lib/sitemap-xml.ts)** provides low-level XML building functions:
|
||||
- Tag generation helpers (`otag`, `ctag`, `element`)
|
||||
- Sitemap-specific element builders (images, videos, news, links)
|
||||
|
||||
### Error Handling
|
||||
|
||||
**[lib/errors.ts](lib/errors.ts)** defines custom error classes:
|
||||
- `EmptyStream`, `EmptySitemap`: Stream validation errors
|
||||
- `InvalidAttr`, `InvalidVideoFormat`, `InvalidNewsFormat`: Validation errors
|
||||
- `XMLLintUnavailable`: External tool errors
|
||||
|
||||
## When Making Changes
|
||||
|
||||
### Where to Add New Code
|
||||
|
||||
- **New type or interface?** → Add to [lib/types.ts](lib/types.ts)
|
||||
- **New constant or limit?** → Add to [lib/constants.ts](lib/constants.ts) (import from here everywhere)
|
||||
- **New validation function or type guard?** → Add to [lib/validation.ts](lib/validation.ts)
|
||||
- **New utility function?** → Add to [lib/utils.ts](lib/utils.ts)
|
||||
- **New error class?** → Add to [lib/errors.ts](lib/errors.ts)
|
||||
- **New public API?** → Export from [index.ts](index.ts)
|
||||
|
||||
### Common Pitfalls to Avoid
|
||||
|
||||
1. **DON'T duplicate constants** - Always import from [lib/constants.ts](lib/constants.ts)
|
||||
2. **DON'T define types in implementation files** - Put them in [lib/types.ts](lib/types.ts)
|
||||
3. **DON'T scatter validation logic** - Keep it all in [lib/validation.ts](lib/validation.ts)
|
||||
4. **DON'T break backward compatibility** - Use re-exports if moving code between files
|
||||
5. **DO update [index.ts](index.ts)** if adding new public API functions
|
||||
|
||||
### Adding a New Field to Sitemap Items
|
||||
|
||||
1. Add type to [lib/types.ts](lib/types.ts) in both `SitemapItem` and `SitemapItemLoose` interfaces
|
||||
2. Add XML generation logic in [lib/sitemap-item-stream.ts](lib/sitemap-item-stream.ts) `_transform` method
|
||||
3. Add parsing logic in [lib/sitemap-parser.ts](lib/sitemap-parser.ts) SAX event handlers
|
||||
4. Add validation in [lib/validation.ts](lib/validation.ts) `validateSMIOptions` if needed
|
||||
5. Add constants to [lib/constants.ts](lib/constants.ts) if limits are needed
|
||||
6. Write tests covering the new field
|
||||
|
||||
### Before Submitting Changes
|
||||
|
||||
```bash
|
||||
npm run test:full # Run all tests, linting, and validation
|
||||
npm run build # Ensure both ESM and CJS builds work
|
||||
npm test # Verify 90%+ code coverage maintained
|
||||
```
|
||||
|
||||
## Finding Code in the Codebase
|
||||
|
||||
### "Where is...?"
|
||||
|
||||
- **Validation for sitemap items?** → [lib/validation.ts](lib/validation.ts) (`validateSMIOptions`)
|
||||
- **URL validation?** → [lib/validation.ts](lib/validation.ts) (`validateURL`)
|
||||
- **Constants like max URL length?** → [lib/constants.ts](lib/constants.ts) (`LIMITS`)
|
||||
- **Type guards (isPriceType, isValidYesNo)?** → [lib/validation.ts](lib/validation.ts)
|
||||
- **Type definitions (SitemapItem, etc)?** → [lib/types.ts](lib/types.ts)
|
||||
- **XML escaping/generation?** → [lib/sitemap-xml.ts](lib/sitemap-xml.ts)
|
||||
- **URL normalization?** → [lib/utils.ts](lib/utils.ts) (`normalizeURL`)
|
||||
- **Stream utilities?** → [lib/utils.ts](lib/utils.ts) (`mergeStreams`, `lineSeparatedURLsToSitemapOptions`)
|
||||
|
||||
### "How do I...?"
|
||||
|
||||
- **Check if a value is valid?** → Import type guard from [lib/validation.ts](lib/validation.ts)
|
||||
- **Get a constant limit?** → Import `LIMITS` from [lib/constants.ts](lib/constants.ts)
|
||||
- **Validate user input?** → Use validation functions from [lib/validation.ts](lib/validation.ts)
|
||||
- **Generate XML safely?** → Use functions from [lib/sitemap-xml.ts](lib/sitemap-xml.ts) (auto-escapes)
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
Tests are in [tests/](tests/) directory with Jest:
|
||||
- **[tests/sitemap-stream.test.ts](tests/sitemap-stream.test.ts)**: Core streaming functionality
|
||||
- **[tests/sitemap-parser.test.ts](tests/sitemap-parser.test.ts)**: XML parsing
|
||||
- **[tests/sitemap-index.test.ts](tests/sitemap-index.test.ts)**: Index generation
|
||||
- **[tests/sitemap-simple.test.ts](tests/sitemap-simple.test.ts)**: High-level API
|
||||
- **[tests/cli.test.ts](tests/cli.test.ts)**: CLI argument parsing
|
||||
- **[tests/*-security.test.ts](tests/)**: Security-focused validation and injection tests
|
||||
- **[tests/sitemap-utils.test.ts](tests/sitemap-utils.test.ts)**: Utility function tests
|
||||
|
||||
### Coverage Requirements (enforced by jest.config.cjs)
|
||||
- Branches: 80%
|
||||
- Functions: 90%
|
||||
- Lines: 90%
|
||||
- Statements: 90%
|
||||
|
||||
### When to Write Tests
|
||||
- **Always** write tests for new validation functions
|
||||
- **Always** write tests for new security features
|
||||
- **Always** add security tests for user-facing inputs (URL validation, path traversal, etc.)
|
||||
- Write tests for bug fixes to prevent regression
|
||||
- Add edge case tests for data transformations
|
||||
|
||||
## TypeScript Configuration
|
||||
|
||||
The project uses a dual-build setup for ESM and CommonJS:
|
||||
|
||||
- **[tsconfig.json](tsconfig.json)**: ESM build (`module: "NodeNext"`, `moduleResolution: "NodeNext"`)
|
||||
- Outputs to `dist/esm/`
|
||||
- Includes both [index.ts](index.ts) and [cli.ts](cli.ts)
|
||||
- ES2023 target with strict null checks enabled
|
||||
|
||||
- **[tsconfig.cjs.json](tsconfig.cjs.json)**: CommonJS build (`module: "CommonJS"`)
|
||||
- Outputs to `dist/cjs/`
|
||||
- Excludes [cli.ts](cli.ts) (CLI is ESM-only)
|
||||
- Only includes [index.ts](index.ts) for library exports
|
||||
|
||||
**Important**: All relative imports must include `.js` extensions for ESM compatibility (e.g., `import { foo } from './types.js'`)
|
||||
|
||||
## Key Patterns
|
||||
|
||||
### Stream Creation
|
||||
Always create a new stream instance per operation. Streams cannot be reused.
|
||||
|
||||
```typescript
|
||||
const stream = new SitemapStream({ hostname: 'https://example.com' });
|
||||
stream.write({ url: '/page' });
|
||||
stream.end();
|
||||
```
|
||||
|
||||
### Memory Management
|
||||
For large datasets, use streaming patterns with `pipe()` rather than collecting all data in memory:
|
||||
|
||||
```typescript
|
||||
// Good - streams through
|
||||
lineSeparatedURLsToSitemapOptions(readStream).pipe(sitemapStream).pipe(outputStream);
|
||||
|
||||
// Bad - loads everything into memory
|
||||
const allUrls = await readAllUrls();
|
||||
allUrls.forEach(url => stream.write(url));
|
||||
```
|
||||
|
||||
### Error Levels
|
||||
Control validation strictness with `ErrorLevel`:
|
||||
- `SILENT`: Skip validation (fastest, use in production if data is pre-validated)
|
||||
- `WARN`: Log warnings (default, good for development)
|
||||
- `THROW`: Throw on invalid data (strict mode, good for testing)
|
||||
|
||||
## Package Distribution
|
||||
|
||||
The package is distributed as a dual ESM/CommonJS package with `"type": "module"` in package.json:
|
||||
|
||||
- **ESM**: `dist/esm/index.js` (ES modules)
|
||||
- **CJS**: `dist/cjs/index.js` (CommonJS, via conditional exports)
|
||||
- **Types**: `dist/esm/index.d.ts` (TypeScript definitions)
|
||||
- **Binary**: `dist/esm/cli.js` (ESM-only CLI, executable via `npx sitemap`)
|
||||
- **Engines**: Node.js >=20.19.5, npm >=10.8.2
|
||||
|
||||
### Dual Package Exports
|
||||
|
||||
The `exports` field in package.json provides conditional exports:
|
||||
|
||||
```json
|
||||
{
|
||||
"exports": {
|
||||
".": {
|
||||
"import": "./dist/esm/index.js",
|
||||
"require": "./dist/cjs/index.js"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This allows both:
|
||||
```javascript
|
||||
// ESM
|
||||
import { SitemapStream } from 'sitemap'
|
||||
|
||||
// CommonJS
|
||||
const { SitemapStream } = require('sitemap')
|
||||
```
|
||||
|
||||
## Git Hooks
|
||||
|
||||
Husky pre-commit hooks run lint-staged which:
|
||||
- Sorts package.json
|
||||
- Runs eslint --fix on TypeScript files
|
||||
- Runs prettier on TypeScript files
|
||||
|
||||
## Architecture Decisions
|
||||
|
||||
### Why This File Structure?
|
||||
|
||||
The codebase is organized around **separation of concerns** and **single source of truth** principles:
|
||||
|
||||
1. **Types in [lib/types.ts](lib/types.ts)**: All interfaces and enums live here, with NO implementation code. This makes types easy to find and prevents circular dependencies.
|
||||
|
||||
2. **Constants in [lib/constants.ts](lib/constants.ts)**: All shared constants (limits, regexes) defined once. This prevents inconsistencies where different files use different values.
|
||||
|
||||
3. **Validation in [lib/validation.ts](lib/validation.ts)**: All validation logic centralized. Easy to find, test, and maintain security rules.
|
||||
|
||||
4. **Clear file boundaries**: Each file has ONE responsibility. You know exactly where to look for specific functionality.
|
||||
|
||||
### Key Principles
|
||||
|
||||
- **Single Source of Truth**: Constants and validation logic exist in exactly one place
|
||||
- **No Duplication**: Import shared code rather than copying it
|
||||
- **Backward Compatibility**: Use re-exports when moving code between files to avoid breaking changes
|
||||
- **Types Separate from Implementation**: [lib/types.ts](lib/types.ts) contains only type definitions
|
||||
- **Security First**: All validation and limits are centralized for consistent security enforcement
|
||||
|
||||
### Benefits of This Organization
|
||||
|
||||
- **Discoverability**: Developers know exactly where to look for types, constants, or validation
|
||||
- **Maintainability**: Changes to limits or validation only require editing one file
|
||||
- **Consistency**: Importing from a single source prevents different parts of the code using different limits
|
||||
- **Testing**: Centralized validation makes it easy to write comprehensive security tests
|
||||
- **Refactoring**: Clear boundaries make it safe to refactor without affecting other modules
|
||||
76
node_modules/sitemap/CODE_OF_CONDUCT.md
generated
vendored
Normal file
76
node_modules/sitemap/CODE_OF_CONDUCT.md
generated
vendored
Normal file
@@ -0,0 +1,76 @@
|
||||
# Contributor Covenant Code of Conduct
|
||||
|
||||
## Our Pledge
|
||||
|
||||
In the interest of fostering an open and welcoming environment, we as
|
||||
contributors and maintainers pledge to making participation in our project and
|
||||
our community a harassment-free experience for everyone, regardless of age, body
|
||||
size, disability, ethnicity, sex characteristics, gender identity and expression,
|
||||
level of experience, education, socio-economic status, nationality, personal
|
||||
appearance, race, religion, or sexual identity and orientation.
|
||||
|
||||
## Our Standards
|
||||
|
||||
Examples of behavior that contributes to creating a positive environment
|
||||
include:
|
||||
|
||||
* Using welcoming and inclusive language
|
||||
* Being respectful of differing viewpoints and experiences
|
||||
* Gracefully accepting constructive criticism
|
||||
* Focusing on what is best for the community
|
||||
* Showing empathy towards other community members
|
||||
|
||||
Examples of unacceptable behavior by participants include:
|
||||
|
||||
* The use of sexualized language or imagery and unwelcome sexual attention or
|
||||
advances
|
||||
* Trolling, insulting/derogatory comments, and personal or political attacks
|
||||
* Public or private harassment
|
||||
* Publishing others' private information, such as a physical or electronic
|
||||
address, without explicit permission
|
||||
* Other conduct which could reasonably be considered inappropriate in a
|
||||
professional setting
|
||||
|
||||
## Our Responsibilities
|
||||
|
||||
Project maintainers are responsible for clarifying the standards of acceptable
|
||||
behavior and are expected to take appropriate and fair corrective action in
|
||||
response to any instances of unacceptable behavior.
|
||||
|
||||
Project maintainers have the right and responsibility to remove, edit, or
|
||||
reject comments, commits, code, wiki edits, issues, and other contributions
|
||||
that are not aligned to this Code of Conduct, or to ban temporarily or
|
||||
permanently any contributor for other behaviors that they deem inappropriate,
|
||||
threatening, offensive, or harmful.
|
||||
|
||||
## Scope
|
||||
|
||||
This Code of Conduct applies both within project spaces and in public spaces
|
||||
when an individual is representing the project or its community. Examples of
|
||||
representing a project or community include using an official project e-mail
|
||||
address, posting via an official social media account, or acting as an appointed
|
||||
representative at an online or offline event. Representation of a project may be
|
||||
further defined and clarified by project maintainers.
|
||||
|
||||
## Enforcement
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
||||
reported by contacting the project team at sitemap-cc@nimblerendition.com. All
|
||||
complaints will be reviewed and investigated and will result in a response that
|
||||
is deemed necessary and appropriate to the circumstances. The project team is
|
||||
obligated to maintain confidentiality with regard to the reporter of an incident.
|
||||
Further details of specific enforcement policies may be posted separately.
|
||||
|
||||
Project maintainers who do not follow or enforce the Code of Conduct in good
|
||||
faith may face temporary or permanent repercussions as determined by other
|
||||
members of the project's leadership.
|
||||
|
||||
## Attribution
|
||||
|
||||
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
|
||||
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
|
||||
|
||||
[homepage]: https://www.contributor-covenant.org
|
||||
|
||||
For answers to common questions about this code of conduct, see
|
||||
https://www.contributor-covenant.org/faq
|
||||
22
node_modules/sitemap/LICENSE
generated
vendored
Normal file
22
node_modules/sitemap/LICENSE
generated
vendored
Normal file
@@ -0,0 +1,22 @@
|
||||
(The MIT License)
|
||||
|
||||
Copyright (c) 2011 Eugene Kalinin
|
||||
|
||||
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.
|
||||
355
node_modules/sitemap/README.md
generated
vendored
Normal file
355
node_modules/sitemap/README.md
generated
vendored
Normal file
@@ -0,0 +1,355 @@
|
||||
# sitemap [](https://github.com/ekalinin/sitemap.js/actions)
|
||||
|
||||
**sitemap** is a high-level streaming sitemap-generating library/CLI that
|
||||
makes creating [sitemap XML](http://www.sitemaps.org/) files easy. [What is a sitemap?](https://support.google.com/webmasters/answer/156184?hl=en&ref_topic=4581190)
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Installation](#installation)
|
||||
- [Generate a one time sitemap from a list of urls](#generate-a-one-time-sitemap-from-a-list-of-urls)
|
||||
- [Example of using sitemap.js with](#serve-a-sitemap-from-a-server-and-periodically-update-it) [express](https://expressjs.com/)
|
||||
- [Generating more than one sitemap](#create-sitemap-and-index-files-from-one-large-list)
|
||||
- [Options you can pass](#options-you-can-pass)
|
||||
- [Examples](#examples)
|
||||
- [API](#api)
|
||||
- [Maintainers](#maintainers)
|
||||
- [License](#license)
|
||||
|
||||
## Installation
|
||||
|
||||
```sh
|
||||
npm install --save sitemap
|
||||
```
|
||||
|
||||
## Generate a one time sitemap from a list of urls
|
||||
|
||||
If you are just looking to take a giant list of URLs and turn it into some sitemaps, try out our CLI. The cli can also parse, update and validate existing sitemaps.
|
||||
|
||||
```sh
|
||||
npx sitemap < listofurls.txt # `npx sitemap -h` for more examples and a list of options.
|
||||
```
|
||||
|
||||
For programmatic one time generation of a sitemap try:
|
||||
|
||||
```js
|
||||
// ESM
|
||||
import { SitemapStream, streamToPromise } from 'sitemap'
|
||||
import { Readable } from 'stream'
|
||||
|
||||
// CommonJS
|
||||
const { SitemapStream, streamToPromise } = require('sitemap')
|
||||
const { Readable } = require('stream')
|
||||
|
||||
// An array with your links
|
||||
const links = [{ url: '/page-1/', changefreq: 'daily', priority: 0.3 }]
|
||||
|
||||
// Create a stream to write to
|
||||
const stream = new SitemapStream( { hostname: 'https://...' } )
|
||||
|
||||
// Return a promise that resolves with your XML string
|
||||
return streamToPromise(Readable.from(links).pipe(stream)).then((data) =>
|
||||
data.toString()
|
||||
)
|
||||
```
|
||||
|
||||
## Serve a sitemap from a server and periodically update it
|
||||
|
||||
Use this if you have less than 50 thousand urls. See SitemapAndIndexStream for if you have more.
|
||||
|
||||
```js
|
||||
// ESM
|
||||
import express from 'express'
|
||||
import { SitemapStream, streamToPromise } from 'sitemap'
|
||||
import { createGzip } from 'zlib'
|
||||
import { Readable } from 'stream'
|
||||
|
||||
// CommonJS
|
||||
const express = require('express')
|
||||
const { SitemapStream, streamToPromise } = require('sitemap')
|
||||
const { createGzip } = require('zlib')
|
||||
const { Readable } = require('stream')
|
||||
|
||||
const app = express()
|
||||
let sitemap
|
||||
|
||||
app.get('/sitemap.xml', function(req, res) {
|
||||
res.header('Content-Type', 'application/xml');
|
||||
res.header('Content-Encoding', 'gzip');
|
||||
// if we have a cached entry send it
|
||||
if (sitemap) {
|
||||
res.send(sitemap)
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const smStream = new SitemapStream({ hostname: 'https://example.com/' })
|
||||
const pipeline = smStream.pipe(createGzip())
|
||||
|
||||
// pipe your entries or directly write them.
|
||||
smStream.write({ url: '/page-1/', changefreq: 'daily', priority: 0.3 })
|
||||
smStream.write({ url: '/page-2/', changefreq: 'monthly', priority: 0.7 })
|
||||
smStream.write({ url: '/page-3/'}) // changefreq: 'weekly', priority: 0.5
|
||||
smStream.write({ url: '/page-4/', img: "http://urlTest.com" })
|
||||
/* or use
|
||||
Readable.from([{url: '/page-1'}...]).pipe(smStream)
|
||||
if you are looking to avoid writing your own loop.
|
||||
*/
|
||||
|
||||
// cache the response
|
||||
streamToPromise(pipeline).then(sm => sitemap = sm)
|
||||
// make sure to attach a write stream such as streamToPromise before ending
|
||||
smStream.end()
|
||||
// stream write the response
|
||||
pipeline.pipe(res).on('error', (e) => {throw e})
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
res.status(500).end()
|
||||
}
|
||||
})
|
||||
|
||||
app.listen(3000, () => {
|
||||
console.log('listening')
|
||||
});
|
||||
```
|
||||
|
||||
## Create sitemap and index files from one large list
|
||||
|
||||
If you know you are definitely going to have more than 50,000 urls in your sitemap, you can use this slightly more complex interface to create a new sitemap every 45,000 entries and add that file to a sitemap index.
|
||||
|
||||
```js
|
||||
// ESM
|
||||
import { createReadStream, createWriteStream } from 'fs'
|
||||
import { resolve } from 'path'
|
||||
import { createGzip } from 'zlib'
|
||||
import { simpleSitemapAndIndex, lineSeparatedURLsToSitemapOptions } from 'sitemap'
|
||||
|
||||
// CommonJS
|
||||
const { createReadStream, createWriteStream } = require('fs')
|
||||
const { resolve } = require('path')
|
||||
const { createGzip } = require('zlib')
|
||||
const {
|
||||
simpleSitemapAndIndex,
|
||||
lineSeparatedURLsToSitemapOptions
|
||||
} = require('sitemap')
|
||||
|
||||
// writes sitemaps and index out to the destination you provide.
|
||||
simpleSitemapAndIndex({
|
||||
hostname: 'https://example.com',
|
||||
destinationDir: './',
|
||||
sourceData: lineSeparatedURLsToSitemapOptions(
|
||||
createReadStream('./your-data.json.txt')
|
||||
),
|
||||
// sourceData can also be:
|
||||
// sourceData: [{ url: '/page-1/', changefreq: 'daily'}, ...],
|
||||
// or
|
||||
// sourceData: './your-data.json.txt',
|
||||
limit: 45000, // optional, default: 50000
|
||||
gzip: true, // optional, default: true
|
||||
publicBasePath: '/sitemaps/', // optional, default: './'
|
||||
xslUrl: 'https://example.com/sitemap.xsl', // optional XSL stylesheet
|
||||
}).then(() => {
|
||||
// Do follow up actions
|
||||
})
|
||||
```
|
||||
|
||||
Want to customize that?
|
||||
|
||||
```js
|
||||
// ESM
|
||||
import { createReadStream, createWriteStream } from 'fs'
|
||||
import { resolve } from 'path'
|
||||
import { createGzip } from 'zlib'
|
||||
import { Readable } from 'stream'
|
||||
import { SitemapAndIndexStream, SitemapStream, lineSeparatedURLsToSitemapOptions } from 'sitemap'
|
||||
|
||||
// CommonJS
|
||||
const { createReadStream, createWriteStream } = require('fs')
|
||||
const { resolve } = require('path')
|
||||
const { createGzip } = require('zlib')
|
||||
const { Readable } = require('stream')
|
||||
const {
|
||||
SitemapAndIndexStream,
|
||||
SitemapStream,
|
||||
lineSeparatedURLsToSitemapOptions
|
||||
} = require('sitemap')
|
||||
|
||||
const sms = new SitemapAndIndexStream({
|
||||
limit: 50000, // defaults to 45k
|
||||
lastmodDateOnly: false, // print date not time
|
||||
// SitemapAndIndexStream will call this user provided function every time
|
||||
// it needs to create a new sitemap file. You merely need to return a stream
|
||||
// for it to write the sitemap urls to and the expected url where that sitemap will be hosted
|
||||
getSitemapStream: (i) => {
|
||||
const sitemapStream = new SitemapStream({ hostname: 'https://example.com' });
|
||||
// if your server automatically serves sitemap.xml.gz when requesting sitemap.xml leave this line be
|
||||
// otherwise you will need to add .gz here and remove it a couple lines below so that both the index
|
||||
// and the actual file have a .gz extension
|
||||
const path = `./sitemap-${i}.xml`;
|
||||
|
||||
const ws = sitemapStream
|
||||
.pipe(createGzip()) // compress the output of the sitemap
|
||||
.pipe(createWriteStream(resolve(path + '.gz'))); // write it to sitemap-NUMBER.xml
|
||||
|
||||
return [new URL(path, 'https://example.com/subdir/').toString(), sitemapStream, ws];
|
||||
},
|
||||
});
|
||||
|
||||
// when reading from a file
|
||||
lineSeparatedURLsToSitemapOptions(
|
||||
createReadStream('./your-data.json.txt')
|
||||
)
|
||||
.pipe(sms)
|
||||
.pipe(createGzip())
|
||||
.pipe(createWriteStream(resolve('./sitemap-index.xml.gz')));
|
||||
|
||||
// or reading straight from an in-memory array
|
||||
sms
|
||||
.pipe(createGzip())
|
||||
.pipe(createWriteStream(resolve('./sitemap-index.xml.gz')));
|
||||
|
||||
const arrayOfSitemapItems = [{ url: '/page-1/', changefreq: 'daily'}, ...]
|
||||
Readable.from(arrayOfSitemapItems).pipe(sms)
|
||||
// or
|
||||
arrayOfSitemapItems.forEach(item => sms.write(item))
|
||||
sms.end() // necessary to let it know you've got nothing else to write
|
||||
```
|
||||
|
||||
### Options you can pass
|
||||
|
||||
```js
|
||||
// ESM
|
||||
import { SitemapStream, streamToPromise } from 'sitemap'
|
||||
|
||||
// CommonJS
|
||||
const { SitemapStream, streamToPromise } = require('sitemap')
|
||||
|
||||
const smStream = new SitemapStream({
|
||||
hostname: 'http://www.mywebsite.com',
|
||||
xslUrl: "https://example.com/style.xsl",
|
||||
lastmodDateOnly: false, // print date not time
|
||||
xmlns: { // trim the xml namespace
|
||||
news: true, // flip to false to omit the xml namespace for news
|
||||
xhtml: true,
|
||||
image: true,
|
||||
video: true,
|
||||
custom: [
|
||||
'xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"',
|
||||
'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"',
|
||||
],
|
||||
}
|
||||
})
|
||||
// coalesce stream to value
|
||||
// alternatively you can pipe to another stream
|
||||
streamToPromise(smStream).then(console.log)
|
||||
|
||||
smStream.write({
|
||||
url: '/page1',
|
||||
changefreq: 'weekly',
|
||||
priority: 0.8, // A hint to the crawler that it should prioritize this over items less than 0.8
|
||||
})
|
||||
|
||||
// each sitemap entry supports many options
|
||||
// See [Sitemap Item Options](./api.md#sitemap-item-options) below for details
|
||||
smStream.write({
|
||||
url: 'http://test.com/page-1/',
|
||||
img: [
|
||||
{
|
||||
url: 'http://test.com/img1.jpg',
|
||||
caption: 'An image',
|
||||
title: 'The Title of Image One',
|
||||
geoLocation: 'London, United Kingdom',
|
||||
license: 'https://creativecommons.org/licenses/by/4.0/'
|
||||
},
|
||||
{
|
||||
url: 'http://test.com/img2.jpg',
|
||||
caption: 'Another image',
|
||||
title: 'The Title of Image Two',
|
||||
geoLocation: 'London, United Kingdom',
|
||||
license: 'https://creativecommons.org/licenses/by/4.0/'
|
||||
}
|
||||
],
|
||||
video: [
|
||||
{
|
||||
thumbnail_loc: 'http://test.com/tmbn1.jpg',
|
||||
title: 'A video title',
|
||||
description: 'This is a video'
|
||||
},
|
||||
{
|
||||
thumbnail_loc: 'http://test.com/tmbn2.jpg',
|
||||
title: 'A video with an attribute',
|
||||
description: 'This is another video',
|
||||
'player_loc': 'http://www.example.com/videoplayer.mp4?video=123',
|
||||
'player_loc:autoplay': 'ap=1',
|
||||
'player_loc:allow_embed': 'yes'
|
||||
}
|
||||
],
|
||||
links: [
|
||||
{ lang: 'en', url: 'http://test.com/page-1/' },
|
||||
{ lang: 'ja', url: 'http://test.com/page-1/ja/' }
|
||||
],
|
||||
androidLink: 'android-app://com.company.test/page-1/',
|
||||
news: {
|
||||
publication: {
|
||||
name: 'The Example Times',
|
||||
language: 'en'
|
||||
},
|
||||
genres: 'PressRelease, Blog',
|
||||
publication_date: '2008-12-23',
|
||||
title: 'Companies A, B in Merger Talks',
|
||||
keywords: 'business, merger, acquisition, A, B',
|
||||
stock_tickers: 'NASDAQ:A, NASDAQ:B'
|
||||
}
|
||||
})
|
||||
// indicate there is nothing left to write
|
||||
smStream.end()
|
||||
```
|
||||
|
||||
## Filtering sitemap entries during parsing
|
||||
|
||||
You can filter or delete items from a sitemap while parsing by piping through a custom Transform stream. This is useful when you want to selectively process only certain URLs from an existing sitemap.
|
||||
|
||||
```js
|
||||
import { createReadStream } from 'fs'
|
||||
import { Transform } from 'stream'
|
||||
import { XMLToSitemapItemStream } from 'sitemap'
|
||||
|
||||
// Create a filter that only keeps certain URLs
|
||||
const filterStream = new Transform({
|
||||
objectMode: true,
|
||||
transform(item, encoding, callback) {
|
||||
// Only keep URLs containing '/blog/'
|
||||
if (item.url.includes('/blog/')) {
|
||||
callback(undefined, item) // Keep this item
|
||||
} else {
|
||||
callback() // Skip this item (effectively "deleting" it)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// Parse and filter
|
||||
createReadStream('./sitemap.xml')
|
||||
.pipe(new XMLToSitemapItemStream())
|
||||
.pipe(filterStream)
|
||||
.on('data', (item) => {
|
||||
console.log('Filtered URL:', item.url)
|
||||
})
|
||||
```
|
||||
|
||||
You can also chain multiple filters together, filter based on priority/changefreq, or use the filtered results to generate a new sitemap. See [examples/filter-sitemap.js](./examples/filter-sitemap.js) for more filtering patterns.
|
||||
|
||||
## Examples
|
||||
|
||||
For more examples see the [examples directory](./examples/)
|
||||
|
||||
## API
|
||||
|
||||
Full API docs can be found [here](./api.md)
|
||||
|
||||
## Maintainers
|
||||
|
||||
- [@ekalinin](https://github.com/ekalinin)
|
||||
- [@derduher](https://github.com/derduher)
|
||||
|
||||
## License
|
||||
|
||||
See [LICENSE](https://github.com/ekalinin/sitemap.js/blob/master/LICENSE) file.
|
||||
454
node_modules/sitemap/api.md
generated
vendored
Normal file
454
node_modules/sitemap/api.md
generated
vendored
Normal file
@@ -0,0 +1,454 @@
|
||||
# API
|
||||
|
||||
- [API](#api)
|
||||
- [SitemapStream](#sitemapstream)
|
||||
- [XMLToSitemapItemStream](#xmltositemapitemstream)
|
||||
- [SitemapAndIndexStream](#sitemapandindexstream)
|
||||
- [simpleSitemapAndIndex](#simplesitemapandindex)
|
||||
- [SitemapIndexStream](#sitemapindexstream)
|
||||
- [xmlLint](#xmllint)
|
||||
- [parseSitemap](#parsesitemap)
|
||||
- [lineSeparatedURLsToSitemapOptions](#lineseparatedurlstositemapoptions)
|
||||
- [streamToPromise](#streamtopromise)
|
||||
- [ObjectStreamToJSON](#objectstreamtojson)
|
||||
- [SitemapItemStream](#sitemapitemstream)
|
||||
- [Sitemap Item Options](#sitemap-item-options)
|
||||
- [SitemapImage](#sitemapimage)
|
||||
- [VideoItem](#videoitem)
|
||||
- [LinkItem](#linkitem)
|
||||
- [NewsItem](#newsitem)
|
||||
|
||||
## SitemapStream
|
||||
|
||||
A [Transform](https://nodejs.org/api/stream.html#stream_implementing_a_transform_stream) for turning a [Readable stream](https://nodejs.org/api/stream.html#stream_readable_streams) of either [SitemapItemOptions](#sitemap-item-options) or url strings into a Sitemap. The readable stream it transforms **must** be in object mode.
|
||||
|
||||
```javascript
|
||||
// ESM
|
||||
import { SitemapStream } from 'sitemap'
|
||||
|
||||
// CommonJS
|
||||
const { SitemapStream } = require('sitemap')
|
||||
|
||||
const sms = new SitemapStream({
|
||||
hostname: 'https://example.com', // optional only necessary if your paths are relative
|
||||
lastmodDateOnly: false // defaults to false, flip to true for baidu
|
||||
xmlns: { // XML namespaces to turn on - all by default
|
||||
news: true,
|
||||
xhtml: true,
|
||||
image: true,
|
||||
video: true,
|
||||
// custom: ['xmlns:custom="https://example.com"']
|
||||
},
|
||||
errorHandler: undefined // defaults to a standard errorLogger that logs to console or throws if the errorLevel is set to throw
|
||||
})
|
||||
const readable = // a readable stream of objects
|
||||
readable.pipe(sms).pipe(process.stdout)
|
||||
```
|
||||
|
||||
## XMLToSitemapItemStream
|
||||
|
||||
Takes a stream of xml and transforms it into a stream of SitemapOptions.
|
||||
Use this to parse existing sitemaps into config options compatible with this library
|
||||
|
||||
```javascript
|
||||
// ESM
|
||||
import { createReadStream, createWriteStream } from 'fs';
|
||||
import { XMLToSitemapItemStream, ObjectStreamToJSON, ErrorLevel } from 'sitemap';
|
||||
|
||||
// CommonJS
|
||||
const { createReadStream, createWriteStream } = require('fs');
|
||||
const { XMLToSitemapItemStream, ObjectStreamToJSON, ErrorLevel } = require('sitemap');
|
||||
|
||||
createReadStream('./some/sitemap.xml')
|
||||
// turn the xml into sitemap option item options
|
||||
.pipe(new XMLToSitemapItemStream({
|
||||
// optional
|
||||
level: ErrorLevel.WARN // default is WARN pass SILENT to silence
|
||||
logger: false // default is console log, pass false as another way to silence or your own custom logger
|
||||
}))
|
||||
// convert the object stream to JSON
|
||||
.pipe(new ObjectStreamToJSON())
|
||||
// write the library compatible options to disk
|
||||
.pipe(createWriteStream('./sitemapOptions.json'))
|
||||
```
|
||||
|
||||
## SitemapAndIndexStream
|
||||
|
||||
Use this to take a stream which may go over the max of 50000 items and split it into an index and sitemaps.
|
||||
SitemapAndIndexStream consumes a stream of urls and streams out index entries while writing individual urls to the streams you give it.
|
||||
Provide it with a function which when provided with a index returns a url where the sitemap will ultimately be hosted and a stream to write the current sitemap to. This function will be called everytime the next item in the stream would exceed the provided limit.
|
||||
|
||||
```js
|
||||
// ESM
|
||||
import { createReadStream, createWriteStream } from 'fs';
|
||||
import { resolve } from 'path';
|
||||
import { createGzip } from 'zlib';
|
||||
import {
|
||||
SitemapAndIndexStream,
|
||||
SitemapStream,
|
||||
lineSeparatedURLsToSitemapOptions
|
||||
} from 'sitemap';
|
||||
|
||||
// CommonJS
|
||||
const { createReadStream, createWriteStream } = require('fs');
|
||||
const { resolve } = require('path');
|
||||
const { createGzip } = require('zlib');
|
||||
const {
|
||||
SitemapAndIndexStream,
|
||||
SitemapStream,
|
||||
lineSeparatedURLsToSitemapOptions
|
||||
} = require('sitemap');
|
||||
|
||||
const sms = new SitemapAndIndexStream({
|
||||
limit: 10000, // defaults to 45k
|
||||
// SitemapAndIndexStream will call this user provided function every time
|
||||
// it needs to create a new sitemap file. You merely need to return a stream
|
||||
// for it to write the sitemap urls to and the expected url where that sitemap will be hosted
|
||||
getSitemapStream: (i) => {
|
||||
const sitemapStream = new SitemapStream();
|
||||
const path = `./sitemap-${i}.xml`;
|
||||
|
||||
const ws = sitemapStream
|
||||
.pipe(createGzip()) // compress the output of the sitemap
|
||||
.pipe(createWriteStream(resolve(path + '.gz'))); // write it to sitemap-NUMBER.xml
|
||||
|
||||
return [new URL(path, 'https://example.com/subdir/').toString(), sitemapStream, ws];
|
||||
},
|
||||
});
|
||||
|
||||
lineSeparatedURLsToSitemapOptions(
|
||||
createReadStream('./your-data.json.txt')
|
||||
)
|
||||
.pipe(sms)
|
||||
.pipe(createGzip())
|
||||
.pipe(createWriteStream(resolve('./sitemap-index.xml.gz')));
|
||||
```
|
||||
|
||||
## simpleSitemapAndIndex
|
||||
|
||||
A simpler interface for creating sitemaps and indexes. Automatically handles splitting large datasets into multiple sitemap files.
|
||||
|
||||
```js
|
||||
// ESM
|
||||
import { simpleSitemapAndIndex } from 'sitemap';
|
||||
|
||||
// CommonJS
|
||||
const { simpleSitemapAndIndex } = require('sitemap');
|
||||
|
||||
// writes sitemaps and index out to the destination you provide.
|
||||
await simpleSitemapAndIndex({
|
||||
hostname: 'https://example.com',
|
||||
destinationDir: './',
|
||||
sourceData: [
|
||||
{ url: '/page-1/', changefreq: 'daily', priority: 0.3 },
|
||||
{ url: '/page-2/', changefreq: 'weekly', priority: 0.7 },
|
||||
// ... more URLs
|
||||
],
|
||||
// optional: limit URLs per sitemap (default: 50000, must be 1-50000)
|
||||
limit: 45000,
|
||||
// optional: gzip the output files (default: true)
|
||||
gzip: true,
|
||||
// optional: public base path for sitemap URLs (default: './')
|
||||
publicBasePath: '/sitemaps/',
|
||||
// optional: XSL stylesheet URL for XML display
|
||||
xslUrl: 'https://example.com/sitemap.xsl',
|
||||
// or read from a file
|
||||
// sourceData: lineSeparatedURLsToSitemapOptions(createReadStream('./urls.txt')),
|
||||
// or
|
||||
// sourceData: './urls.txt',
|
||||
});
|
||||
```
|
||||
|
||||
### Options
|
||||
|
||||
- **hostname** (required): The base URL for all sitemap entries. Must be a valid `http://` or `https://` URL.
|
||||
- **sitemapHostname** (optional): The base URL for sitemap index entries if different from `hostname`. Must be a valid `http://` or `https://` URL.
|
||||
- **destinationDir** (required): Directory where sitemaps and index will be written. Can be relative or absolute, but must not contain path traversal sequences (`..`).
|
||||
- **sourceData** (required): URL source data. Can be:
|
||||
- Array of strings (URLs)
|
||||
- Array of `SitemapItemLoose` objects
|
||||
- String (file path to line-separated URLs)
|
||||
- Readable stream
|
||||
- **limit** (optional): Maximum URLs per sitemap file. Must be between 1 and 50,000 per [sitemaps.org spec](https://www.sitemaps.org/protocol.html). Default: 50000
|
||||
- **gzip** (optional): Whether to gzip compress the output files. Default: true
|
||||
- **publicBasePath** (optional): Base path for sitemap URLs in the index. Must not contain path traversal sequences. Default: './'
|
||||
- **xslUrl** (optional): URL to an XSL stylesheet for XML display. Must be a valid `http://` or `https://` URL.
|
||||
|
||||
### Security
|
||||
|
||||
`simpleSitemapAndIndex` includes comprehensive security validation to protect against common attacks:
|
||||
|
||||
**URL Validation:**
|
||||
- All URLs (hostname, sitemapHostname) must use `http://` or `https://` protocols only
|
||||
- Maximum URL length enforced at 2048 characters per sitemaps.org specification
|
||||
- URLs are parsed and validated to ensure they are well-formed
|
||||
|
||||
**Path Traversal Protection:**
|
||||
- `destinationDir` and `publicBasePath` are checked for path traversal sequences (`..`)
|
||||
- Validation detects `..` in all positions (beginning, middle, end, standalone)
|
||||
- Both Unix-style (`/`) and Windows-style (`\`) path separators are normalized and checked
|
||||
- Null bytes (`\0`) are rejected to prevent path manipulation attacks
|
||||
|
||||
**XSL Stylesheet Security:**
|
||||
- XSL URLs must use `http://` or `https://` protocols
|
||||
- Case-insensitive checks block dangerous content patterns:
|
||||
- Script tags: `<script`, `<ScRiPt`, `<SCRIPT>`, etc.
|
||||
- Dangerous protocols: `javascript:`, `data:`, `vbscript:`, `file:`, `about:`
|
||||
- URL-encoded attacks: `%3cscript`, `javascript%3a`, etc.
|
||||
- Maximum URL length enforced at 2048 characters
|
||||
|
||||
**Resource Limits:**
|
||||
- Limit validated to be an integer between 1 and 50,000 per sitemaps.org specification
|
||||
- Prevents resource exhaustion attacks and ensures search engine compatibility
|
||||
|
||||
**Data Validation:**
|
||||
- Video ratings are validated to be valid numbers between 0 and 5
|
||||
- Video view counts are validated to be non-negative integers
|
||||
- Date values (lastmod, lastmodISO) are validated to be parseable dates
|
||||
|
||||
### Errors
|
||||
|
||||
May throw:
|
||||
|
||||
- `InvalidHostnameError`: Invalid or malformed hostname/sitemapHostname
|
||||
- `InvalidPathError`: destinationDir contains path traversal or invalid characters
|
||||
- `InvalidPublicBasePathError`: publicBasePath contains path traversal or invalid characters
|
||||
- `InvalidLimitError`: limit is out of range (not 1-50,000)
|
||||
- `InvalidXSLUrlError`: xslUrl is invalid or potentially malicious
|
||||
- `Error`: Invalid sourceData type or file system errors
|
||||
|
||||
## SitemapIndexStream
|
||||
|
||||
Writes a sitemap index when given a stream urls.
|
||||
|
||||
```js
|
||||
// ESM
|
||||
import { SitemapIndexStream } from 'sitemap';
|
||||
|
||||
// CommonJS
|
||||
const { SitemapIndexStream } = require('sitemap');
|
||||
|
||||
/**
|
||||
* writes the following
|
||||
* <?xml version="1.0" encoding="UTF-8"?>
|
||||
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
|
||||
<sitemap>
|
||||
<loc>https://example.com/</loc>
|
||||
</sitemap>
|
||||
<sitemap>
|
||||
<loc>https://example.com/2</loc>
|
||||
</sitemap>
|
||||
*/
|
||||
const smis = new SitemapIndexStream({level: 'warn'})
|
||||
smis.write({url: 'https://example.com/'})
|
||||
smis.write({url: 'https://example.com/2'})
|
||||
smis.pipe(writestream)
|
||||
smis.end()
|
||||
```
|
||||
|
||||
## xmlLint
|
||||
|
||||
Resolve or reject depending on whether the passed in xml is a valid sitemap.
|
||||
This is just a wrapper around the xmlLint command line tool and thus requires
|
||||
xmlLint to be installed on the system.
|
||||
|
||||
**Security Note:** This function accepts XML content as a string or Readable stream
|
||||
and always pipes it via stdin to xmllint. It does NOT accept file paths to prevent
|
||||
command injection vulnerabilities.
|
||||
|
||||
```js
|
||||
// ESM
|
||||
import { createReadStream, readFileSync } from 'fs';
|
||||
import { xmlLint } from 'sitemap';
|
||||
|
||||
// CommonJS
|
||||
const { createReadStream, readFileSync } = require('fs');
|
||||
const { xmlLint } = require('sitemap');
|
||||
|
||||
// Validate using a stream
|
||||
xmlLint(createReadStream('./example.xml')).then(
|
||||
() => console.log('xml is valid'),
|
||||
([err, stderr]) => console.error('xml is invalid', stderr)
|
||||
)
|
||||
|
||||
// Validate using a string
|
||||
const xmlContent = readFileSync('./example.xml', 'utf8');
|
||||
xmlLint(xmlContent).then(
|
||||
() => console.log('xml is valid'),
|
||||
([err, stderr]) => console.error('xml is invalid', stderr)
|
||||
)
|
||||
```
|
||||
|
||||
## parseSitemap
|
||||
|
||||
Read xml and resolve with an array of sitemap items or reject with an error
|
||||
|
||||
```js
|
||||
// ESM
|
||||
import { createReadStream } from 'fs';
|
||||
import { parseSitemap } from 'sitemap';
|
||||
|
||||
// CommonJS
|
||||
const { createReadStream } = require('fs');
|
||||
const { parseSitemap } = require('sitemap');
|
||||
|
||||
parseSitemap(createReadStream('./example.xml')).then(
|
||||
(items) => {
|
||||
// items is an array of sitemap items
|
||||
console.log(items);
|
||||
},
|
||||
(err) => console.log(err)
|
||||
)
|
||||
```
|
||||
|
||||
## lineSeparatedURLsToSitemapOptions
|
||||
|
||||
Takes a stream of urls or sitemapoptions likely from fs.createReadStream('./path') and returns an object stream of sitemap items.
|
||||
|
||||
## streamToPromise
|
||||
|
||||
Takes a stream returns a promise that resolves when stream emits finish.
|
||||
|
||||
```javascript
|
||||
// ESM
|
||||
import { streamToPromise, SitemapStream } from 'sitemap';
|
||||
|
||||
// CommonJS
|
||||
const { streamToPromise, SitemapStream } = require('sitemap');
|
||||
|
||||
const sitemap = new SitemapStream({ hostname: 'http://example.com' });
|
||||
sitemap.write({ url: '/page-1/', changefreq: 'daily', priority: 0.3 })
|
||||
sitemap.end()
|
||||
streamToPromise(sitemap).then(buffer => console.log(buffer.toString())) // emits the full sitemap
|
||||
```
|
||||
|
||||
## ObjectStreamToJSON
|
||||
|
||||
A Transform that converts a stream of objects into a JSON Array or a line separated stringified JSON.
|
||||
|
||||
- @param [lineSeparated=false] whether to separate entries by a new line or comma
|
||||
|
||||
```javascript
|
||||
// ESM
|
||||
import { Readable } from 'stream';
|
||||
import { ObjectStreamToJSON } from 'sitemap';
|
||||
|
||||
// CommonJS
|
||||
const { Readable } = require('stream');
|
||||
const { ObjectStreamToJSON } = require('sitemap');
|
||||
|
||||
const stream = Readable.from([{a: 'b'}])
|
||||
.pipe(new ObjectStreamToJSON())
|
||||
.pipe(process.stdout)
|
||||
stream.end()
|
||||
// prints {"a":"b"}
|
||||
```
|
||||
|
||||
## SitemapItemStream
|
||||
|
||||
Takes a stream of SitemapItemOptions and spits out xml for each
|
||||
|
||||
```js
|
||||
// ESM
|
||||
import { SitemapItemStream } from 'sitemap';
|
||||
|
||||
// CommonJS
|
||||
const { SitemapItemStream } = require('sitemap');
|
||||
|
||||
// writes <url><loc>https://example.com</loc><url><url><loc>https://example.com/2</loc><url>
|
||||
const smis = new SitemapItemStream({level: 'warn'})
|
||||
smis.pipe(writestream)
|
||||
smis.write({url: 'https://example.com', img: [], video: [], links: []})
|
||||
smis.write({url: 'https://example.com/2', img: [], video: [], links: []})
|
||||
smis.end()
|
||||
```
|
||||
|
||||
## Sitemap Item Options
|
||||
|
||||
|Option|Type|eg|Description|
|
||||
|------|----|--|-----------|
|
||||
|url|string|`http://example.com/some/path`|The only required property for every sitemap entry|
|
||||
|lastmod|string|'2019-07-29' or '2019-07-22T05:58:37.037Z'|When the page we as last modified use the W3C Datetime ISO8601 subset <https://www.sitemaps.org/protocol.html#xmlTagDefinitions>|
|
||||
|changefreq|string|'weekly'|How frequently the page is likely to change. This value provides general information to search engines and may not correlate exactly to how often they crawl the page. Please note that the value of this tag is considered a hint and not a command. See <https://www.sitemaps.org/protocol.html#xmlTagDefinitions> for the acceptable values|
|
||||
|priority|number|0.6|The priority of this URL relative to other URLs on your site. Valid values range from 0.0 to 1.0. This value does not affect how your pages are compared to pages on other sites—it only lets the search engines know which pages you deem most important for the crawlers. The default priority of a page is 0.5. <https://www.sitemaps.org/protocol.html#xmlTagDefinitions>|
|
||||
|img|object[]|see [#SitemapImage](#sitemapimage)|<https://support.google.com/webmasters/answer/178636?hl=en&ref_topic=4581190>|
|
||||
|video|object[]|see [#VideoItem](#videoitem)|<https://support.google.com/webmasters/answer/80471?hl=en&ref_topic=4581190>|
|
||||
|links|object[]|see [#LinkItem](#linkitem)|Tell search engines about localized versions <https://support.google.com/webmasters/answer/189077>|
|
||||
|news|object|see [#NewsItem](#newsitem)|<https://support.google.com/webmasters/answer/74288?hl=en&ref_topic=4581190>|
|
||||
|ampLink|string|`http://ampproject.org/article.amp.html`||
|
||||
|cdata|boolean|true|wrap url in cdata xml escape|
|
||||
|
||||
## SitemapImage
|
||||
|
||||
Sitemap image
|
||||
<https://support.google.com/webmasters/answer/178636?hl=en&ref_topic=4581190>
|
||||
|
||||
|Option|Type|eg|Description|
|
||||
|------|----|--|-----------|
|
||||
|url|string|`http://example.com/image.jpg`|The URL of the image.|
|
||||
|caption|string - optional|'Here we did the stuff'|The caption of the image.|
|
||||
|title|string - optional|'Star Wars EP IV'|The title of the image.|
|
||||
|geoLocation|string - optional|'Limerick, Ireland'|The geographic location of the image.|
|
||||
|license|string - optional|`http://example.com/license.txt`|A URL to the license of the image.|
|
||||
|
||||
## VideoItem
|
||||
|
||||
Sitemap video. <https://support.google.com/webmasters/answer/80471?hl=en&ref_topic=4581190>
|
||||
|
||||
|Option|Type|eg|Description|
|
||||
|------|----|--|-----------|
|
||||
|thumbnail_loc|string|`"https://rtv3-img-roosterteeth.akamaized.net/store/0e841100-289b-4184-ae30-b6a16736960a.jpg/sm/thumb3.jpg"`|A URL pointing to the video thumbnail image file|
|
||||
|title|string|'2018:E6 - GoldenEye: Source'|The title of the video. |
|
||||
|description|string|'We play gun game in GoldenEye: Source with a good friend of ours. His name is Gruchy. Dan Gruchy.'|A description of the video. Maximum 2048 characters. |
|
||||
|content_loc|string - optional|`"http://streamserver.example.com/video123.mp4"`|A URL pointing to the actual video media file. Should be one of the supported formats. HTML is not a supported format. Flash is allowed, but no longer supported on most mobile platforms, and so may be indexed less well. Must not be the same as the `<loc>` URL.|
|
||||
|player_loc|string - optional|`"https://roosterteeth.com/embed/rouletsplay-2018-goldeneye-source"`|A URL pointing to a player for a specific video. Usually this is the information in the src element of an `<embed>` tag. Must not be the same as the `<loc>` URL|
|
||||
|'player_loc:autoplay'|string - optional|'ap=1'|a string the search engine can append as a query param to enable automatic playback|
|
||||
|'player_loc:allow_embed'|boolean - optional|'yes'|Whether the search engine can embed the video in search results. Allowed values are yes or no.|
|
||||
|duration|number - optional| 600| duration of video in seconds|
|
||||
|expiration_date| string - optional|"2012-07-16T19:20:30+08:00"|The date after which the video will no longer be available|
|
||||
|view_count|number - optional|'21000000000'|The number of times the video has been viewed.|
|
||||
|publication_date| string - optional|"2018-04-27T17:00:00.000Z"|The date the video was first published, in W3C format.|
|
||||
|category|string - optional|"Baking"|A short description of the broad category that the video belongs to. This is a string no longer than 256 characters.|
|
||||
|restriction|string - optional|"IE GB US CA"|Whether to show or hide your video in search results from specific countries.|
|
||||
|restriction:relationship| string - optional|"deny"||
|
||||
|gallery_loc| string - optional|`"https://roosterteeth.com/series/awhu"`|Currently not used.|
|
||||
|gallery_loc:title|string - optional|"awhu series page"|Currently not used.|
|
||||
|price|string - optional|"1.99"|The price to download or view the video. Omit this tag for free videos.|
|
||||
|price:resolution|string - optional|"HD"|Specifies the resolution of the purchased version. Supported values are hd and sd.|
|
||||
|price:currency| string - optional|"USD"|currency [Required] Specifies the currency in ISO 4217 format.|
|
||||
|price:type|string - optional|"rent"|type [Optional] Specifies the purchase option. Supported values are rent and own. |
|
||||
|uploader|string - optional|"GrillyMcGrillerson"|The video uploader's name. Only one <video:uploader> is allowed per video. String value, max 255 characters.|
|
||||
|uploader:info|string - optional|"https://example.com/about"|Specifies the URL of a webpage with additional information about this uploader. This URL must be in the same domain as the `<loc>` tag.
|
||||
|platform|string - optional|"tv"|Whether to show or hide your video in search results on specified platform types. This is a list of space-delimited platform types. See <https://support.google.com/webmasters/answer/80471?hl=en&ref_topic=4581190> for more detail|
|
||||
|platform:relationship|string 'Allow'\|'Deny' - optional|'Allow'||
|
||||
|id|string - optional|||
|
||||
|tag|string[] - optional|['Baking']|An arbitrary string tag describing the video. Tags are generally very short descriptions of key concepts associated with a video or piece of content.|
|
||||
|rating|number - optional|2.5|The rating of the video. Supported values are float numbers|
|
||||
|family_friendly|string 'YES'\|'NO' - optional|'YES'||
|
||||
|requires_subscription|string 'YES'\|'NO' - optional|'YES'|Indicates whether a subscription (either paid or free) is required to view the video. Allowed values are yes or no.|
|
||||
|live|string 'YES'\|'NO' - optional|'NO'|Indicates whether the video is a live stream. Supported values are yes or no.|
|
||||
|
||||
## LinkItem
|
||||
|
||||
<https://support.google.com/webmasters/answer/189077>
|
||||
|
||||
|Option|Type|eg|Description|
|
||||
|------|----|--|-----------|
|
||||
|lang|string|'en'||
|
||||
|url|string|`'http://example.com/en/'`||
|
||||
|
||||
## NewsItem
|
||||
|
||||
<https://support.google.com/webmasters/answer/74288?hl=en&ref_topic=4581190>
|
||||
|
||||
|Option|Type|eg|Description|
|
||||
|------|----|--|-----------|
|
||||
|access|string - 'Registration' \| 'Subscription'| 'Registration' - optional||
|
||||
|publication| object|see following options||
|
||||
|publication['name']| string|'The Example Times'|The `<name>` is the name of the news publication. It must exactly match the name as it appears on your articles on news.google.com, except for anything in parentheses.|
|
||||
|publication['language']|string|'en'|The `<language>` is the language of your publication. Use an ISO 639 language code (2 or 3 letters).|
|
||||
|genres|string - optional|'PressRelease, Blog'||
|
||||
|publication_date|string|'2008-12-23'|Article publication date in W3C format, using either the "complete date" (YYYY-MM-DD) format or the "complete date plus hours, minutes, and seconds"|
|
||||
|title|string|'Companies A, B in Merger Talks'|The title of the news article.|
|
||||
|keywords|string - optional|"business, merger, acquisition, A, B"||
|
||||
|stock_tickers|string - optional|"NASDAQ:A, NASDAQ:B"||
|
||||
17
node_modules/sitemap/dist/cjs/index.d.ts
generated
vendored
Normal file
17
node_modules/sitemap/dist/cjs/index.d.ts
generated
vendored
Normal file
@@ -0,0 +1,17 @@
|
||||
/*!
|
||||
* Sitemap
|
||||
* Copyright(c) 2011 Eugene Kalinin
|
||||
* MIT Licensed
|
||||
*/
|
||||
export { SitemapItemStream, SitemapItemStreamOptions, } from './lib/sitemap-item-stream.js';
|
||||
export { IndexTagNames, SitemapIndexStream, SitemapIndexStreamOptions, SitemapAndIndexStream, SitemapAndIndexStreamOptions, } from './lib/sitemap-index-stream.js';
|
||||
export { streamToPromise, SitemapStream, SitemapStreamOptions, } from './lib/sitemap-stream.js';
|
||||
export * from './lib/errors.js';
|
||||
export * from './lib/types.js';
|
||||
export { lineSeparatedURLsToSitemapOptions, mergeStreams, validateSMIOptions, normalizeURL, ReadlineStream, ReadlineStreamOptions, } from './lib/utils.js';
|
||||
export { xmlLint } from './lib/xmllint.js';
|
||||
export { parseSitemap, XMLToSitemapItemStream, XMLToSitemapItemStreamOptions, ObjectStreamToJSON, ObjectStreamToJSONOptions, } from './lib/sitemap-parser.js';
|
||||
export { parseSitemapIndex, XMLToSitemapIndexStream, XMLToSitemapIndexItemStreamOptions, IndexObjectStreamToJSON, IndexObjectStreamToJSONOptions, } from './lib/sitemap-index-parser.js';
|
||||
export { simpleSitemapAndIndex, SimpleSitemapAndIndexOptions, } from './lib/sitemap-simple.js';
|
||||
export { validateURL, validatePath, validateLimit, validatePublicBasePath, validateXSLUrl, validators, isPriceType, isResolution, isValidChangeFreq, isValidYesNo, isAllowDeny, } from './lib/validation.js';
|
||||
export { LIMITS, DEFAULT_SITEMAP_ITEM_LIMIT } from './lib/constants.js';
|
||||
66
node_modules/sitemap/dist/cjs/index.js
generated
vendored
Normal file
66
node_modules/sitemap/dist/cjs/index.js
generated
vendored
Normal file
@@ -0,0 +1,66 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
||||
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.DEFAULT_SITEMAP_ITEM_LIMIT = exports.LIMITS = exports.isAllowDeny = exports.isValidYesNo = exports.isValidChangeFreq = exports.isResolution = exports.isPriceType = exports.validators = exports.validateXSLUrl = exports.validatePublicBasePath = exports.validateLimit = exports.validatePath = exports.validateURL = exports.simpleSitemapAndIndex = exports.IndexObjectStreamToJSON = exports.XMLToSitemapIndexStream = exports.parseSitemapIndex = exports.ObjectStreamToJSON = exports.XMLToSitemapItemStream = exports.parseSitemap = exports.xmlLint = exports.ReadlineStream = exports.normalizeURL = exports.validateSMIOptions = exports.mergeStreams = exports.lineSeparatedURLsToSitemapOptions = exports.SitemapStream = exports.streamToPromise = exports.SitemapAndIndexStream = exports.SitemapIndexStream = exports.IndexTagNames = exports.SitemapItemStream = void 0;
|
||||
/*!
|
||||
* Sitemap
|
||||
* Copyright(c) 2011 Eugene Kalinin
|
||||
* MIT Licensed
|
||||
*/
|
||||
var sitemap_item_stream_js_1 = require("./lib/sitemap-item-stream.js");
|
||||
Object.defineProperty(exports, "SitemapItemStream", { enumerable: true, get: function () { return sitemap_item_stream_js_1.SitemapItemStream; } });
|
||||
var sitemap_index_stream_js_1 = require("./lib/sitemap-index-stream.js");
|
||||
Object.defineProperty(exports, "IndexTagNames", { enumerable: true, get: function () { return sitemap_index_stream_js_1.IndexTagNames; } });
|
||||
Object.defineProperty(exports, "SitemapIndexStream", { enumerable: true, get: function () { return sitemap_index_stream_js_1.SitemapIndexStream; } });
|
||||
Object.defineProperty(exports, "SitemapAndIndexStream", { enumerable: true, get: function () { return sitemap_index_stream_js_1.SitemapAndIndexStream; } });
|
||||
var sitemap_stream_js_1 = require("./lib/sitemap-stream.js");
|
||||
Object.defineProperty(exports, "streamToPromise", { enumerable: true, get: function () { return sitemap_stream_js_1.streamToPromise; } });
|
||||
Object.defineProperty(exports, "SitemapStream", { enumerable: true, get: function () { return sitemap_stream_js_1.SitemapStream; } });
|
||||
__exportStar(require("./lib/errors.js"), exports);
|
||||
__exportStar(require("./lib/types.js"), exports);
|
||||
var utils_js_1 = require("./lib/utils.js");
|
||||
Object.defineProperty(exports, "lineSeparatedURLsToSitemapOptions", { enumerable: true, get: function () { return utils_js_1.lineSeparatedURLsToSitemapOptions; } });
|
||||
Object.defineProperty(exports, "mergeStreams", { enumerable: true, get: function () { return utils_js_1.mergeStreams; } });
|
||||
Object.defineProperty(exports, "validateSMIOptions", { enumerable: true, get: function () { return utils_js_1.validateSMIOptions; } });
|
||||
Object.defineProperty(exports, "normalizeURL", { enumerable: true, get: function () { return utils_js_1.normalizeURL; } });
|
||||
Object.defineProperty(exports, "ReadlineStream", { enumerable: true, get: function () { return utils_js_1.ReadlineStream; } });
|
||||
var xmllint_js_1 = require("./lib/xmllint.js");
|
||||
Object.defineProperty(exports, "xmlLint", { enumerable: true, get: function () { return xmllint_js_1.xmlLint; } });
|
||||
var sitemap_parser_js_1 = require("./lib/sitemap-parser.js");
|
||||
Object.defineProperty(exports, "parseSitemap", { enumerable: true, get: function () { return sitemap_parser_js_1.parseSitemap; } });
|
||||
Object.defineProperty(exports, "XMLToSitemapItemStream", { enumerable: true, get: function () { return sitemap_parser_js_1.XMLToSitemapItemStream; } });
|
||||
Object.defineProperty(exports, "ObjectStreamToJSON", { enumerable: true, get: function () { return sitemap_parser_js_1.ObjectStreamToJSON; } });
|
||||
var sitemap_index_parser_js_1 = require("./lib/sitemap-index-parser.js");
|
||||
Object.defineProperty(exports, "parseSitemapIndex", { enumerable: true, get: function () { return sitemap_index_parser_js_1.parseSitemapIndex; } });
|
||||
Object.defineProperty(exports, "XMLToSitemapIndexStream", { enumerable: true, get: function () { return sitemap_index_parser_js_1.XMLToSitemapIndexStream; } });
|
||||
Object.defineProperty(exports, "IndexObjectStreamToJSON", { enumerable: true, get: function () { return sitemap_index_parser_js_1.IndexObjectStreamToJSON; } });
|
||||
var sitemap_simple_js_1 = require("./lib/sitemap-simple.js");
|
||||
Object.defineProperty(exports, "simpleSitemapAndIndex", { enumerable: true, get: function () { return sitemap_simple_js_1.simpleSitemapAndIndex; } });
|
||||
var validation_js_1 = require("./lib/validation.js");
|
||||
Object.defineProperty(exports, "validateURL", { enumerable: true, get: function () { return validation_js_1.validateURL; } });
|
||||
Object.defineProperty(exports, "validatePath", { enumerable: true, get: function () { return validation_js_1.validatePath; } });
|
||||
Object.defineProperty(exports, "validateLimit", { enumerable: true, get: function () { return validation_js_1.validateLimit; } });
|
||||
Object.defineProperty(exports, "validatePublicBasePath", { enumerable: true, get: function () { return validation_js_1.validatePublicBasePath; } });
|
||||
Object.defineProperty(exports, "validateXSLUrl", { enumerable: true, get: function () { return validation_js_1.validateXSLUrl; } });
|
||||
Object.defineProperty(exports, "validators", { enumerable: true, get: function () { return validation_js_1.validators; } });
|
||||
Object.defineProperty(exports, "isPriceType", { enumerable: true, get: function () { return validation_js_1.isPriceType; } });
|
||||
Object.defineProperty(exports, "isResolution", { enumerable: true, get: function () { return validation_js_1.isResolution; } });
|
||||
Object.defineProperty(exports, "isValidChangeFreq", { enumerable: true, get: function () { return validation_js_1.isValidChangeFreq; } });
|
||||
Object.defineProperty(exports, "isValidYesNo", { enumerable: true, get: function () { return validation_js_1.isValidYesNo; } });
|
||||
Object.defineProperty(exports, "isAllowDeny", { enumerable: true, get: function () { return validation_js_1.isAllowDeny; } });
|
||||
var constants_js_1 = require("./lib/constants.js");
|
||||
Object.defineProperty(exports, "LIMITS", { enumerable: true, get: function () { return constants_js_1.LIMITS; } });
|
||||
Object.defineProperty(exports, "DEFAULT_SITEMAP_ITEM_LIMIT", { enumerable: true, get: function () { return constants_js_1.DEFAULT_SITEMAP_ITEM_LIMIT; } });
|
||||
49
node_modules/sitemap/dist/cjs/lib/constants.d.ts
generated
vendored
Normal file
49
node_modules/sitemap/dist/cjs/lib/constants.d.ts
generated
vendored
Normal file
@@ -0,0 +1,49 @@
|
||||
/*!
|
||||
* Sitemap
|
||||
* Copyright(c) 2011 Eugene Kalinin
|
||||
* MIT Licensed
|
||||
*/
|
||||
/**
|
||||
* Shared constants used across the sitemap library
|
||||
* This file serves as a single source of truth for limits and validation patterns
|
||||
*/
|
||||
/**
|
||||
* Security limits for sitemap generation and parsing
|
||||
*
|
||||
* These limits are based on:
|
||||
* - sitemaps.org protocol specification
|
||||
* - Security best practices to prevent DoS and injection attacks
|
||||
* - Google's sitemap extension specifications
|
||||
*
|
||||
* @see https://www.sitemaps.org/protocol.html
|
||||
* @see https://developers.google.com/search/docs/advanced/sitemaps/build-sitemap
|
||||
*/
|
||||
export declare const LIMITS: {
|
||||
readonly MAX_URL_LENGTH: 2048;
|
||||
readonly URL_PROTOCOL_REGEX: RegExp;
|
||||
readonly MIN_SITEMAP_ITEM_LIMIT: 1;
|
||||
readonly MAX_SITEMAP_ITEM_LIMIT: 50000;
|
||||
readonly MAX_VIDEO_TITLE_LENGTH: 100;
|
||||
readonly MAX_VIDEO_DESCRIPTION_LENGTH: 2048;
|
||||
readonly MAX_VIDEO_CATEGORY_LENGTH: 256;
|
||||
readonly MAX_TAGS_PER_VIDEO: 32;
|
||||
readonly MAX_NEWS_TITLE_LENGTH: 200;
|
||||
readonly MAX_NEWS_NAME_LENGTH: 256;
|
||||
readonly MAX_IMAGE_CAPTION_LENGTH: 512;
|
||||
readonly MAX_IMAGE_TITLE_LENGTH: 512;
|
||||
readonly MAX_IMAGES_PER_URL: 1000;
|
||||
readonly MAX_VIDEOS_PER_URL: 100;
|
||||
readonly MAX_LINKS_PER_URL: 100;
|
||||
readonly MAX_URL_ENTRIES: 50000;
|
||||
readonly ISO_DATE_REGEX: RegExp;
|
||||
readonly MAX_CUSTOM_NAMESPACES: 20;
|
||||
readonly MAX_NAMESPACE_LENGTH: 512;
|
||||
readonly MAX_PARSER_ERRORS: 100;
|
||||
};
|
||||
/**
|
||||
* Default maximum number of items in each sitemap XML file
|
||||
* Set below the max to leave room for URLs added during processing
|
||||
*
|
||||
* @see https://www.sitemaps.org/protocol.html#index
|
||||
*/
|
||||
export declare const DEFAULT_SITEMAP_ITEM_LIMIT = 45000;
|
||||
63
node_modules/sitemap/dist/cjs/lib/constants.js
generated
vendored
Normal file
63
node_modules/sitemap/dist/cjs/lib/constants.js
generated
vendored
Normal file
@@ -0,0 +1,63 @@
|
||||
"use strict";
|
||||
/*!
|
||||
* Sitemap
|
||||
* Copyright(c) 2011 Eugene Kalinin
|
||||
* MIT Licensed
|
||||
*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.DEFAULT_SITEMAP_ITEM_LIMIT = exports.LIMITS = void 0;
|
||||
/**
|
||||
* Shared constants used across the sitemap library
|
||||
* This file serves as a single source of truth for limits and validation patterns
|
||||
*/
|
||||
/**
|
||||
* Security limits for sitemap generation and parsing
|
||||
*
|
||||
* These limits are based on:
|
||||
* - sitemaps.org protocol specification
|
||||
* - Security best practices to prevent DoS and injection attacks
|
||||
* - Google's sitemap extension specifications
|
||||
*
|
||||
* @see https://www.sitemaps.org/protocol.html
|
||||
* @see https://developers.google.com/search/docs/advanced/sitemaps/build-sitemap
|
||||
*/
|
||||
exports.LIMITS = {
|
||||
// URL constraints per sitemaps.org spec
|
||||
MAX_URL_LENGTH: 2048,
|
||||
URL_PROTOCOL_REGEX: /^https?:\/\//i,
|
||||
// Sitemap size limits per sitemaps.org spec
|
||||
MIN_SITEMAP_ITEM_LIMIT: 1,
|
||||
MAX_SITEMAP_ITEM_LIMIT: 50000,
|
||||
// Video field length constraints per Google spec
|
||||
MAX_VIDEO_TITLE_LENGTH: 100,
|
||||
MAX_VIDEO_DESCRIPTION_LENGTH: 2048,
|
||||
MAX_VIDEO_CATEGORY_LENGTH: 256,
|
||||
MAX_TAGS_PER_VIDEO: 32,
|
||||
// News field length constraints per Google spec
|
||||
MAX_NEWS_TITLE_LENGTH: 200,
|
||||
MAX_NEWS_NAME_LENGTH: 256,
|
||||
// Image field length constraints per Google spec
|
||||
MAX_IMAGE_CAPTION_LENGTH: 512,
|
||||
MAX_IMAGE_TITLE_LENGTH: 512,
|
||||
// Limits on number of items per URL entry
|
||||
MAX_IMAGES_PER_URL: 1000,
|
||||
MAX_VIDEOS_PER_URL: 100,
|
||||
MAX_LINKS_PER_URL: 100,
|
||||
// Total entries in a sitemap
|
||||
MAX_URL_ENTRIES: 50000,
|
||||
// Date validation - ISO 8601 / W3C format
|
||||
ISO_DATE_REGEX: /^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d{3})?([+-]\d{2}:\d{2}|Z)?)?$/,
|
||||
// Custom namespace limits to prevent DoS
|
||||
MAX_CUSTOM_NAMESPACES: 20,
|
||||
MAX_NAMESPACE_LENGTH: 512,
|
||||
// Cap on stored parser errors to prevent memory DoS (BB-03)
|
||||
// Errors beyond this limit are counted in errorCount but not retained as objects
|
||||
MAX_PARSER_ERRORS: 100,
|
||||
};
|
||||
/**
|
||||
* Default maximum number of items in each sitemap XML file
|
||||
* Set below the max to leave room for URLs added during processing
|
||||
*
|
||||
* @see https://www.sitemaps.org/protocol.html#index
|
||||
*/
|
||||
exports.DEFAULT_SITEMAP_ITEM_LIMIT = 45000;
|
||||
116
node_modules/sitemap/dist/cjs/lib/errors.d.ts
generated
vendored
Normal file
116
node_modules/sitemap/dist/cjs/lib/errors.d.ts
generated
vendored
Normal file
@@ -0,0 +1,116 @@
|
||||
/*!
|
||||
* Sitemap
|
||||
* Copyright(c) 2011 Eugene Kalinin
|
||||
* MIT Licensed
|
||||
*/
|
||||
/**
|
||||
* URL in SitemapItem does not exist
|
||||
*/
|
||||
export declare class NoURLError extends Error {
|
||||
constructor(message?: string);
|
||||
}
|
||||
/**
|
||||
* Config was not passed to SitemapItem constructor
|
||||
*/
|
||||
export declare class NoConfigError extends Error {
|
||||
constructor(message?: string);
|
||||
}
|
||||
/**
|
||||
* changefreq property in sitemap is invalid
|
||||
*/
|
||||
export declare class ChangeFreqInvalidError extends Error {
|
||||
constructor(url: string, changefreq: any);
|
||||
}
|
||||
/**
|
||||
* priority property in sitemap is invalid
|
||||
*/
|
||||
export declare class PriorityInvalidError extends Error {
|
||||
constructor(url: string, priority: any);
|
||||
}
|
||||
/**
|
||||
* SitemapIndex target Folder does not exists
|
||||
*/
|
||||
export declare class UndefinedTargetFolder extends Error {
|
||||
constructor(message?: string);
|
||||
}
|
||||
export declare class InvalidVideoFormat extends Error {
|
||||
constructor(url: string);
|
||||
}
|
||||
export declare class InvalidVideoDuration extends Error {
|
||||
constructor(url: string, duration: any);
|
||||
}
|
||||
export declare class InvalidVideoDescription extends Error {
|
||||
constructor(url: string, length: number);
|
||||
}
|
||||
export declare class InvalidVideoRating extends Error {
|
||||
constructor(url: string, title: any, rating: any);
|
||||
}
|
||||
export declare class InvalidAttrValue extends Error {
|
||||
constructor(key: string, val: any, validator: RegExp);
|
||||
}
|
||||
export declare class InvalidAttr extends Error {
|
||||
constructor(key: string);
|
||||
}
|
||||
export declare class InvalidNewsFormat extends Error {
|
||||
constructor(url: string);
|
||||
}
|
||||
export declare class InvalidNewsAccessValue extends Error {
|
||||
constructor(url: string, access: any);
|
||||
}
|
||||
export declare class XMLLintUnavailable extends Error {
|
||||
constructor(message?: string);
|
||||
}
|
||||
export declare class InvalidVideoTitle extends Error {
|
||||
constructor(url: string, length: number);
|
||||
}
|
||||
export declare class InvalidVideoViewCount extends Error {
|
||||
constructor(url: string, count: number);
|
||||
}
|
||||
export declare class InvalidVideoTagCount extends Error {
|
||||
constructor(url: string, count: number);
|
||||
}
|
||||
export declare class InvalidVideoCategory extends Error {
|
||||
constructor(url: string, count: number);
|
||||
}
|
||||
export declare class InvalidVideoFamilyFriendly extends Error {
|
||||
constructor(url: string, fam: string);
|
||||
}
|
||||
export declare class InvalidVideoRestriction extends Error {
|
||||
constructor(url: string, code: string);
|
||||
}
|
||||
export declare class InvalidVideoRestrictionRelationship extends Error {
|
||||
constructor(url: string, val?: string);
|
||||
}
|
||||
export declare class InvalidVideoPriceType extends Error {
|
||||
constructor(url: string, priceType?: string, price?: string);
|
||||
}
|
||||
export declare class InvalidVideoResolution extends Error {
|
||||
constructor(url: string, resolution: string);
|
||||
}
|
||||
export declare class InvalidVideoPriceCurrency extends Error {
|
||||
constructor(url: string, currency: string);
|
||||
}
|
||||
export declare class EmptyStream extends Error {
|
||||
constructor();
|
||||
}
|
||||
export declare class EmptySitemap extends Error {
|
||||
constructor();
|
||||
}
|
||||
export declare class InvalidPathError extends Error {
|
||||
constructor(path: string, reason: string);
|
||||
}
|
||||
export declare class InvalidHostnameError extends Error {
|
||||
constructor(hostname: string, reason: string);
|
||||
}
|
||||
export declare class InvalidLimitError extends Error {
|
||||
constructor(limit: any);
|
||||
}
|
||||
export declare class InvalidPublicBasePathError extends Error {
|
||||
constructor(publicBasePath: string, reason: string);
|
||||
}
|
||||
export declare class InvalidXSLUrlError extends Error {
|
||||
constructor(xslUrl: string, reason: string);
|
||||
}
|
||||
export declare class InvalidXMLAttributeNameError extends Error {
|
||||
constructor(attributeName: string);
|
||||
}
|
||||
291
node_modules/sitemap/dist/cjs/lib/errors.js
generated
vendored
Normal file
291
node_modules/sitemap/dist/cjs/lib/errors.js
generated
vendored
Normal file
@@ -0,0 +1,291 @@
|
||||
"use strict";
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
/*!
|
||||
* Sitemap
|
||||
* Copyright(c) 2011 Eugene Kalinin
|
||||
* MIT Licensed
|
||||
*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.InvalidXMLAttributeNameError = exports.InvalidXSLUrlError = exports.InvalidPublicBasePathError = exports.InvalidLimitError = exports.InvalidHostnameError = exports.InvalidPathError = exports.EmptySitemap = exports.EmptyStream = exports.InvalidVideoPriceCurrency = exports.InvalidVideoResolution = exports.InvalidVideoPriceType = exports.InvalidVideoRestrictionRelationship = exports.InvalidVideoRestriction = exports.InvalidVideoFamilyFriendly = exports.InvalidVideoCategory = exports.InvalidVideoTagCount = exports.InvalidVideoViewCount = exports.InvalidVideoTitle = exports.XMLLintUnavailable = exports.InvalidNewsAccessValue = exports.InvalidNewsFormat = exports.InvalidAttr = exports.InvalidAttrValue = exports.InvalidVideoRating = exports.InvalidVideoDescription = exports.InvalidVideoDuration = exports.InvalidVideoFormat = exports.UndefinedTargetFolder = exports.PriorityInvalidError = exports.ChangeFreqInvalidError = exports.NoConfigError = exports.NoURLError = void 0;
|
||||
/**
|
||||
* URL in SitemapItem does not exist
|
||||
*/
|
||||
class NoURLError extends Error {
|
||||
constructor(message) {
|
||||
super(message || 'URL is required');
|
||||
this.name = 'NoURLError';
|
||||
Error.captureStackTrace(this, NoURLError);
|
||||
}
|
||||
}
|
||||
exports.NoURLError = NoURLError;
|
||||
/**
|
||||
* Config was not passed to SitemapItem constructor
|
||||
*/
|
||||
class NoConfigError extends Error {
|
||||
constructor(message) {
|
||||
super(message || 'SitemapItem requires a configuration');
|
||||
this.name = 'NoConfigError';
|
||||
Error.captureStackTrace(this, NoConfigError);
|
||||
}
|
||||
}
|
||||
exports.NoConfigError = NoConfigError;
|
||||
/**
|
||||
* changefreq property in sitemap is invalid
|
||||
*/
|
||||
class ChangeFreqInvalidError extends Error {
|
||||
constructor(url, changefreq) {
|
||||
super(`${url}: changefreq "${changefreq}" is invalid`);
|
||||
this.name = 'ChangeFreqInvalidError';
|
||||
Error.captureStackTrace(this, ChangeFreqInvalidError);
|
||||
}
|
||||
}
|
||||
exports.ChangeFreqInvalidError = ChangeFreqInvalidError;
|
||||
/**
|
||||
* priority property in sitemap is invalid
|
||||
*/
|
||||
class PriorityInvalidError extends Error {
|
||||
constructor(url, priority) {
|
||||
super(`${url}: priority "${priority}" must be a number between 0 and 1 inclusive`);
|
||||
this.name = 'PriorityInvalidError';
|
||||
Error.captureStackTrace(this, PriorityInvalidError);
|
||||
}
|
||||
}
|
||||
exports.PriorityInvalidError = PriorityInvalidError;
|
||||
/**
|
||||
* SitemapIndex target Folder does not exists
|
||||
*/
|
||||
class UndefinedTargetFolder extends Error {
|
||||
constructor(message) {
|
||||
super(message || 'Target folder must exist');
|
||||
this.name = 'UndefinedTargetFolder';
|
||||
Error.captureStackTrace(this, UndefinedTargetFolder);
|
||||
}
|
||||
}
|
||||
exports.UndefinedTargetFolder = UndefinedTargetFolder;
|
||||
class InvalidVideoFormat extends Error {
|
||||
constructor(url) {
|
||||
super(`${url} video must include thumbnail_loc, title and description fields for videos`);
|
||||
this.name = 'InvalidVideoFormat';
|
||||
Error.captureStackTrace(this, InvalidVideoFormat);
|
||||
}
|
||||
}
|
||||
exports.InvalidVideoFormat = InvalidVideoFormat;
|
||||
class InvalidVideoDuration extends Error {
|
||||
constructor(url, duration) {
|
||||
super(`${url} duration "${duration}" must be an integer of seconds between 0 and 28800`);
|
||||
this.name = 'InvalidVideoDuration';
|
||||
Error.captureStackTrace(this, InvalidVideoDuration);
|
||||
}
|
||||
}
|
||||
exports.InvalidVideoDuration = InvalidVideoDuration;
|
||||
class InvalidVideoDescription extends Error {
|
||||
constructor(url, length) {
|
||||
const message = `${url}: video description is too long ${length} vs limit of 2048 characters.`;
|
||||
super(message);
|
||||
this.name = 'InvalidVideoDescription';
|
||||
Error.captureStackTrace(this, InvalidVideoDescription);
|
||||
}
|
||||
}
|
||||
exports.InvalidVideoDescription = InvalidVideoDescription;
|
||||
class InvalidVideoRating extends Error {
|
||||
constructor(url, title, rating) {
|
||||
super(`${url}: video "${title}" rating "${rating}" must be between 0 and 5 inclusive`);
|
||||
this.name = 'InvalidVideoRating';
|
||||
Error.captureStackTrace(this, InvalidVideoRating);
|
||||
}
|
||||
}
|
||||
exports.InvalidVideoRating = InvalidVideoRating;
|
||||
class InvalidAttrValue extends Error {
|
||||
constructor(key, val, validator) {
|
||||
super('"' +
|
||||
val +
|
||||
'" tested against: ' +
|
||||
validator +
|
||||
' is not a valid value for attr: "' +
|
||||
key +
|
||||
'"');
|
||||
this.name = 'InvalidAttrValue';
|
||||
Error.captureStackTrace(this, InvalidAttrValue);
|
||||
}
|
||||
}
|
||||
exports.InvalidAttrValue = InvalidAttrValue;
|
||||
// InvalidAttr is only thrown when attrbuilder is called incorrectly internally
|
||||
/* istanbul ignore next */
|
||||
class InvalidAttr extends Error {
|
||||
constructor(key) {
|
||||
super('"' + key + '" is malformed');
|
||||
this.name = 'InvalidAttr';
|
||||
Error.captureStackTrace(this, InvalidAttr);
|
||||
}
|
||||
}
|
||||
exports.InvalidAttr = InvalidAttr;
|
||||
class InvalidNewsFormat extends Error {
|
||||
constructor(url) {
|
||||
super(`${url} News must include publication, publication name, publication language, title, and publication_date for news`);
|
||||
this.name = 'InvalidNewsFormat';
|
||||
Error.captureStackTrace(this, InvalidNewsFormat);
|
||||
}
|
||||
}
|
||||
exports.InvalidNewsFormat = InvalidNewsFormat;
|
||||
class InvalidNewsAccessValue extends Error {
|
||||
constructor(url, access) {
|
||||
super(`${url} News access "${access}" must be either Registration, Subscription or not be present`);
|
||||
this.name = 'InvalidNewsAccessValue';
|
||||
Error.captureStackTrace(this, InvalidNewsAccessValue);
|
||||
}
|
||||
}
|
||||
exports.InvalidNewsAccessValue = InvalidNewsAccessValue;
|
||||
class XMLLintUnavailable extends Error {
|
||||
constructor(message) {
|
||||
super(message || 'xmlLint is not installed. XMLLint is required to validate');
|
||||
this.name = 'XMLLintUnavailable';
|
||||
Error.captureStackTrace(this, XMLLintUnavailable);
|
||||
}
|
||||
}
|
||||
exports.XMLLintUnavailable = XMLLintUnavailable;
|
||||
class InvalidVideoTitle extends Error {
|
||||
constructor(url, length) {
|
||||
super(`${url}: video title is too long ${length} vs 100 character limit`);
|
||||
this.name = 'InvalidVideoTitle';
|
||||
Error.captureStackTrace(this, InvalidVideoTitle);
|
||||
}
|
||||
}
|
||||
exports.InvalidVideoTitle = InvalidVideoTitle;
|
||||
class InvalidVideoViewCount extends Error {
|
||||
constructor(url, count) {
|
||||
super(`${url}: video view count must be positive, view count was ${count}`);
|
||||
this.name = 'InvalidVideoViewCount';
|
||||
Error.captureStackTrace(this, InvalidVideoViewCount);
|
||||
}
|
||||
}
|
||||
exports.InvalidVideoViewCount = InvalidVideoViewCount;
|
||||
class InvalidVideoTagCount extends Error {
|
||||
constructor(url, count) {
|
||||
super(`${url}: video can have no more than 32 tags, this has ${count}`);
|
||||
this.name = 'InvalidVideoTagCount';
|
||||
Error.captureStackTrace(this, InvalidVideoTagCount);
|
||||
}
|
||||
}
|
||||
exports.InvalidVideoTagCount = InvalidVideoTagCount;
|
||||
class InvalidVideoCategory extends Error {
|
||||
constructor(url, count) {
|
||||
super(`${url}: video category can only be 256 characters but was passed ${count}`);
|
||||
this.name = 'InvalidVideoCategory';
|
||||
Error.captureStackTrace(this, InvalidVideoCategory);
|
||||
}
|
||||
}
|
||||
exports.InvalidVideoCategory = InvalidVideoCategory;
|
||||
class InvalidVideoFamilyFriendly extends Error {
|
||||
constructor(url, fam) {
|
||||
super(`${url}: video family friendly must be yes or no, was passed "${fam}"`);
|
||||
this.name = 'InvalidVideoFamilyFriendly';
|
||||
Error.captureStackTrace(this, InvalidVideoFamilyFriendly);
|
||||
}
|
||||
}
|
||||
exports.InvalidVideoFamilyFriendly = InvalidVideoFamilyFriendly;
|
||||
class InvalidVideoRestriction extends Error {
|
||||
constructor(url, code) {
|
||||
super(`${url}: video restriction must be one or more two letter country codes. Was passed "${code}"`);
|
||||
this.name = 'InvalidVideoRestriction';
|
||||
Error.captureStackTrace(this, InvalidVideoRestriction);
|
||||
}
|
||||
}
|
||||
exports.InvalidVideoRestriction = InvalidVideoRestriction;
|
||||
class InvalidVideoRestrictionRelationship extends Error {
|
||||
constructor(url, val) {
|
||||
super(`${url}: video restriction relationship must be either allow or deny. Was passed "${val}"`);
|
||||
this.name = 'InvalidVideoRestrictionRelationship';
|
||||
Error.captureStackTrace(this, InvalidVideoRestrictionRelationship);
|
||||
}
|
||||
}
|
||||
exports.InvalidVideoRestrictionRelationship = InvalidVideoRestrictionRelationship;
|
||||
class InvalidVideoPriceType extends Error {
|
||||
constructor(url, priceType, price) {
|
||||
super(priceType === undefined && price === ''
|
||||
? `${url}: video priceType is required when price is not provided`
|
||||
: `${url}: video price type "${priceType}" is not "rent" or "purchase"`);
|
||||
this.name = 'InvalidVideoPriceType';
|
||||
Error.captureStackTrace(this, InvalidVideoPriceType);
|
||||
}
|
||||
}
|
||||
exports.InvalidVideoPriceType = InvalidVideoPriceType;
|
||||
class InvalidVideoResolution extends Error {
|
||||
constructor(url, resolution) {
|
||||
super(`${url}: video price resolution "${resolution}" is not hd or sd`);
|
||||
this.name = 'InvalidVideoResolution';
|
||||
Error.captureStackTrace(this, InvalidVideoResolution);
|
||||
}
|
||||
}
|
||||
exports.InvalidVideoResolution = InvalidVideoResolution;
|
||||
class InvalidVideoPriceCurrency extends Error {
|
||||
constructor(url, currency) {
|
||||
super(`${url}: video price currency "${currency}" must be a three capital letter abbrieviation for the country currency`);
|
||||
this.name = 'InvalidVideoPriceCurrency';
|
||||
Error.captureStackTrace(this, InvalidVideoPriceCurrency);
|
||||
}
|
||||
}
|
||||
exports.InvalidVideoPriceCurrency = InvalidVideoPriceCurrency;
|
||||
class EmptyStream extends Error {
|
||||
constructor() {
|
||||
super('You have ended the stream before anything was written. streamToPromise MUST be called before ending the stream.');
|
||||
this.name = 'EmptyStream';
|
||||
Error.captureStackTrace(this, EmptyStream);
|
||||
}
|
||||
}
|
||||
exports.EmptyStream = EmptyStream;
|
||||
class EmptySitemap extends Error {
|
||||
constructor() {
|
||||
super('You ended the stream without writing anything.');
|
||||
this.name = 'EmptySitemap';
|
||||
Error.captureStackTrace(this, EmptyStream);
|
||||
}
|
||||
}
|
||||
exports.EmptySitemap = EmptySitemap;
|
||||
class InvalidPathError extends Error {
|
||||
constructor(path, reason) {
|
||||
super(`Invalid path "${path}": ${reason}`);
|
||||
this.name = 'InvalidPathError';
|
||||
Error.captureStackTrace(this, InvalidPathError);
|
||||
}
|
||||
}
|
||||
exports.InvalidPathError = InvalidPathError;
|
||||
class InvalidHostnameError extends Error {
|
||||
constructor(hostname, reason) {
|
||||
super(`Invalid hostname "${hostname}": ${reason}`);
|
||||
this.name = 'InvalidHostnameError';
|
||||
Error.captureStackTrace(this, InvalidHostnameError);
|
||||
}
|
||||
}
|
||||
exports.InvalidHostnameError = InvalidHostnameError;
|
||||
class InvalidLimitError extends Error {
|
||||
constructor(limit) {
|
||||
super(`Invalid limit "${limit}": must be a number between 1 and 50000 (per sitemaps.org spec)`);
|
||||
this.name = 'InvalidLimitError';
|
||||
Error.captureStackTrace(this, InvalidLimitError);
|
||||
}
|
||||
}
|
||||
exports.InvalidLimitError = InvalidLimitError;
|
||||
class InvalidPublicBasePathError extends Error {
|
||||
constructor(publicBasePath, reason) {
|
||||
super(`Invalid publicBasePath "${publicBasePath}": ${reason}`);
|
||||
this.name = 'InvalidPublicBasePathError';
|
||||
Error.captureStackTrace(this, InvalidPublicBasePathError);
|
||||
}
|
||||
}
|
||||
exports.InvalidPublicBasePathError = InvalidPublicBasePathError;
|
||||
class InvalidXSLUrlError extends Error {
|
||||
constructor(xslUrl, reason) {
|
||||
super(`Invalid xslUrl "${xslUrl}": ${reason}`);
|
||||
this.name = 'InvalidXSLUrlError';
|
||||
Error.captureStackTrace(this, InvalidXSLUrlError);
|
||||
}
|
||||
}
|
||||
exports.InvalidXSLUrlError = InvalidXSLUrlError;
|
||||
class InvalidXMLAttributeNameError extends Error {
|
||||
constructor(attributeName) {
|
||||
super(`Invalid XML attribute name "${attributeName}": must contain only alphanumeric characters, hyphens, underscores, and colons`);
|
||||
this.name = 'InvalidXMLAttributeNameError';
|
||||
Error.captureStackTrace(this, InvalidXMLAttributeNameError);
|
||||
}
|
||||
}
|
||||
exports.InvalidXMLAttributeNameError = InvalidXMLAttributeNameError;
|
||||
55
node_modules/sitemap/dist/cjs/lib/sitemap-index-parser.d.ts
generated
vendored
Normal file
55
node_modules/sitemap/dist/cjs/lib/sitemap-index-parser.d.ts
generated
vendored
Normal file
@@ -0,0 +1,55 @@
|
||||
import type { SAXStream } from 'sax';
|
||||
import { Readable, Transform, TransformOptions, TransformCallback } from 'node:stream';
|
||||
import { IndexItem, ErrorLevel } from './types.js';
|
||||
type Logger = (level: 'warn' | 'error' | 'info' | 'log', ...message: Parameters<Console['log']>) => void;
|
||||
export interface XMLToSitemapIndexItemStreamOptions extends TransformOptions {
|
||||
level?: ErrorLevel;
|
||||
logger?: Logger | false;
|
||||
}
|
||||
/**
|
||||
* Takes a stream of xml and transforms it into a stream of IndexItems
|
||||
* Use this to parse existing sitemap indices into config options compatible with this library
|
||||
*/
|
||||
export declare class XMLToSitemapIndexStream extends Transform {
|
||||
level: ErrorLevel;
|
||||
logger: Logger;
|
||||
error: Error | null;
|
||||
saxStream: SAXStream;
|
||||
constructor(opts?: XMLToSitemapIndexItemStreamOptions);
|
||||
_transform(data: string, encoding: string, callback: TransformCallback): void;
|
||||
private err;
|
||||
}
|
||||
/**
|
||||
Read xml and resolve with the configuration that would produce it or reject with
|
||||
an error
|
||||
```
|
||||
const { createReadStream } = require('fs')
|
||||
const { parseSitemapIndex, createSitemap } = require('sitemap')
|
||||
parseSitemapIndex(createReadStream('./example-index.xml')).then(
|
||||
// produces the same xml
|
||||
// you can, of course, more practically modify it or store it
|
||||
(xmlConfig) => console.log(createSitemap(xmlConfig).toString()),
|
||||
(err) => console.log(err)
|
||||
)
|
||||
```
|
||||
@param {Readable} xml what to parse
|
||||
@param {number} maxEntries Maximum number of sitemap entries to parse (default: 50,000 per sitemaps.org spec)
|
||||
@return {Promise<IndexItem[]>} resolves with list of index items that can be fed into a SitemapIndexStream. Rejects with an Error object.
|
||||
*/
|
||||
export declare function parseSitemapIndex(xml: Readable, maxEntries?: number): Promise<IndexItem[]>;
|
||||
export interface IndexObjectStreamToJSONOptions extends TransformOptions {
|
||||
lineSeparated: boolean;
|
||||
}
|
||||
/**
|
||||
* A Transform that converts a stream of objects into a JSON Array or a line
|
||||
* separated stringified JSON
|
||||
* @param [lineSeparated=false] whether to separate entries by a new line or comma
|
||||
*/
|
||||
export declare class IndexObjectStreamToJSON extends Transform {
|
||||
lineSeparated: boolean;
|
||||
firstWritten: boolean;
|
||||
constructor(opts?: IndexObjectStreamToJSONOptions);
|
||||
_transform(chunk: IndexItem, encoding: string, cb: TransformCallback): void;
|
||||
_flush(cb: TransformCallback): void;
|
||||
}
|
||||
export {};
|
||||
271
node_modules/sitemap/dist/cjs/lib/sitemap-index-parser.js
generated
vendored
Normal file
271
node_modules/sitemap/dist/cjs/lib/sitemap-index-parser.js
generated
vendored
Normal file
@@ -0,0 +1,271 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.IndexObjectStreamToJSON = exports.XMLToSitemapIndexStream = void 0;
|
||||
exports.parseSitemapIndex = parseSitemapIndex;
|
||||
const sax_1 = __importDefault(require("sax"));
|
||||
const node_stream_1 = require("node:stream");
|
||||
const types_js_1 = require("./types.js");
|
||||
const validation_js_1 = require("./validation.js");
|
||||
const constants_js_1 = require("./constants.js");
|
||||
function isValidTagName(tagName) {
|
||||
// This only works because the enum name and value are the same
|
||||
return tagName in types_js_1.IndexTagNames;
|
||||
}
|
||||
function tagTemplate() {
|
||||
return {
|
||||
url: '',
|
||||
};
|
||||
}
|
||||
const defaultLogger = (level, ...message) => console[level](...message);
|
||||
const defaultStreamOpts = {
|
||||
logger: defaultLogger,
|
||||
};
|
||||
/**
|
||||
* Takes a stream of xml and transforms it into a stream of IndexItems
|
||||
* Use this to parse existing sitemap indices into config options compatible with this library
|
||||
*/
|
||||
class XMLToSitemapIndexStream extends node_stream_1.Transform {
|
||||
level;
|
||||
logger;
|
||||
error;
|
||||
saxStream;
|
||||
constructor(opts = defaultStreamOpts) {
|
||||
opts.objectMode = true;
|
||||
super(opts);
|
||||
this.error = null;
|
||||
this.saxStream = sax_1.default.createStream(true, {
|
||||
xmlns: true,
|
||||
// @ts-expect-error - SAX types don't include strictEntities option
|
||||
strictEntities: true,
|
||||
trim: true,
|
||||
});
|
||||
this.level = opts.level || types_js_1.ErrorLevel.WARN;
|
||||
if (this.level !== types_js_1.ErrorLevel.SILENT && opts.logger !== false) {
|
||||
this.logger = opts.logger ?? defaultLogger;
|
||||
}
|
||||
else {
|
||||
this.logger = () => undefined;
|
||||
}
|
||||
let currentItem = tagTemplate();
|
||||
let currentTag;
|
||||
this.saxStream.on('opentagstart', (tag) => {
|
||||
currentTag = tag.name;
|
||||
});
|
||||
this.saxStream.on('opentag', (tag) => {
|
||||
if (!isValidTagName(tag.name)) {
|
||||
this.logger('warn', 'unhandled tag', tag.name);
|
||||
this.err(`unhandled tag: ${tag.name}`);
|
||||
}
|
||||
});
|
||||
this.saxStream.on('text', (text) => {
|
||||
switch (currentTag) {
|
||||
case types_js_1.IndexTagNames.loc:
|
||||
// Validate URL for security: prevents protocol injection, checks length limits
|
||||
try {
|
||||
(0, validation_js_1.validateURL)(text, 'Sitemap index URL');
|
||||
currentItem.url = text;
|
||||
}
|
||||
catch (error) {
|
||||
const errMsg = error instanceof Error ? error.message : String(error);
|
||||
this.logger('warn', 'Invalid URL in sitemap index:', errMsg);
|
||||
this.err(`Invalid URL in sitemap index: ${errMsg}`);
|
||||
}
|
||||
break;
|
||||
case types_js_1.IndexTagNames.lastmod:
|
||||
// Validate date format for security and spec compliance
|
||||
if (text && !constants_js_1.LIMITS.ISO_DATE_REGEX.test(text)) {
|
||||
this.logger('warn', 'Invalid lastmod date format in sitemap index:', text);
|
||||
this.err(`Invalid lastmod date format: ${text}`);
|
||||
}
|
||||
else {
|
||||
currentItem.lastmod = text;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
this.logger('log', 'unhandled text for tag:', currentTag, `'${text}'`);
|
||||
this.err(`unhandled text for tag: ${currentTag} '${text}'`);
|
||||
break;
|
||||
}
|
||||
});
|
||||
this.saxStream.on('cdata', (text) => {
|
||||
switch (currentTag) {
|
||||
case types_js_1.IndexTagNames.loc:
|
||||
// Validate URL for security: prevents protocol injection, checks length limits
|
||||
try {
|
||||
(0, validation_js_1.validateURL)(text, 'Sitemap index URL');
|
||||
currentItem.url = text;
|
||||
}
|
||||
catch (error) {
|
||||
const errMsg = error instanceof Error ? error.message : String(error);
|
||||
this.logger('warn', 'Invalid URL in sitemap index:', errMsg);
|
||||
this.err(`Invalid URL in sitemap index: ${errMsg}`);
|
||||
}
|
||||
break;
|
||||
case types_js_1.IndexTagNames.lastmod:
|
||||
// Validate date format for security and spec compliance
|
||||
if (text && !constants_js_1.LIMITS.ISO_DATE_REGEX.test(text)) {
|
||||
this.logger('warn', 'Invalid lastmod date format in sitemap index:', text);
|
||||
this.err(`Invalid lastmod date format: ${text}`);
|
||||
}
|
||||
else {
|
||||
currentItem.lastmod = text;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
this.logger('log', 'unhandled cdata for tag:', currentTag);
|
||||
this.err(`unhandled cdata for tag: ${currentTag}`);
|
||||
break;
|
||||
}
|
||||
});
|
||||
this.saxStream.on('attribute', (attr) => {
|
||||
switch (currentTag) {
|
||||
case types_js_1.IndexTagNames.sitemapindex:
|
||||
break;
|
||||
default:
|
||||
this.logger('log', 'unhandled attr', currentTag, attr.name);
|
||||
this.err(`unhandled attr: ${currentTag} ${attr.name}`);
|
||||
}
|
||||
});
|
||||
this.saxStream.on('closetag', (tag) => {
|
||||
switch (tag) {
|
||||
case types_js_1.IndexTagNames.sitemap:
|
||||
// Only push items with valid URLs (non-empty after validation)
|
||||
if (currentItem.url) {
|
||||
this.push(currentItem);
|
||||
}
|
||||
currentItem = tagTemplate();
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
});
|
||||
}
|
||||
_transform(data, encoding, callback) {
|
||||
try {
|
||||
const cb = () => callback(this.level === types_js_1.ErrorLevel.THROW ? this.error : null);
|
||||
// correcting the type here can be done without making it a breaking change
|
||||
// TODO fix this
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
if (!this.saxStream.write(data, encoding)) {
|
||||
this.saxStream.once('drain', cb);
|
||||
}
|
||||
else {
|
||||
process.nextTick(cb);
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
callback(error);
|
||||
}
|
||||
}
|
||||
err(msg) {
|
||||
if (!this.error)
|
||||
this.error = new Error(msg);
|
||||
}
|
||||
}
|
||||
exports.XMLToSitemapIndexStream = XMLToSitemapIndexStream;
|
||||
/**
|
||||
Read xml and resolve with the configuration that would produce it or reject with
|
||||
an error
|
||||
```
|
||||
const { createReadStream } = require('fs')
|
||||
const { parseSitemapIndex, createSitemap } = require('sitemap')
|
||||
parseSitemapIndex(createReadStream('./example-index.xml')).then(
|
||||
// produces the same xml
|
||||
// you can, of course, more practically modify it or store it
|
||||
(xmlConfig) => console.log(createSitemap(xmlConfig).toString()),
|
||||
(err) => console.log(err)
|
||||
)
|
||||
```
|
||||
@param {Readable} xml what to parse
|
||||
@param {number} maxEntries Maximum number of sitemap entries to parse (default: 50,000 per sitemaps.org spec)
|
||||
@return {Promise<IndexItem[]>} resolves with list of index items that can be fed into a SitemapIndexStream. Rejects with an Error object.
|
||||
*/
|
||||
async function parseSitemapIndex(xml, maxEntries = constants_js_1.LIMITS.MAX_SITEMAP_ITEM_LIMIT) {
|
||||
const urls = [];
|
||||
return new Promise((resolve, reject) => {
|
||||
let settled = false;
|
||||
const parser = new XMLToSitemapIndexStream();
|
||||
// Handle source stream errors (prevents unhandled error events on xml)
|
||||
xml.on('error', (error) => {
|
||||
if (!settled) {
|
||||
settled = true;
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
xml
|
||||
.pipe(parser)
|
||||
.on('data', (smi) => {
|
||||
if (settled)
|
||||
return;
|
||||
// Security: Prevent memory exhaustion by limiting number of entries
|
||||
if (urls.length >= maxEntries) {
|
||||
settled = true;
|
||||
reject(new Error(`Sitemap index exceeds maximum allowed entries (${maxEntries})`));
|
||||
// Immediately destroy both streams to stop further processing (BB-05)
|
||||
parser.destroy();
|
||||
xml.destroy();
|
||||
return;
|
||||
}
|
||||
urls.push(smi);
|
||||
})
|
||||
.on('end', () => {
|
||||
if (!settled) {
|
||||
settled = true;
|
||||
resolve(urls);
|
||||
}
|
||||
})
|
||||
.on('error', (error) => {
|
||||
if (!settled) {
|
||||
settled = true;
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
const defaultObjectStreamOpts = {
|
||||
lineSeparated: false,
|
||||
};
|
||||
/**
|
||||
* A Transform that converts a stream of objects into a JSON Array or a line
|
||||
* separated stringified JSON
|
||||
* @param [lineSeparated=false] whether to separate entries by a new line or comma
|
||||
*/
|
||||
class IndexObjectStreamToJSON extends node_stream_1.Transform {
|
||||
lineSeparated;
|
||||
firstWritten;
|
||||
constructor(opts = defaultObjectStreamOpts) {
|
||||
opts.writableObjectMode = true;
|
||||
super(opts);
|
||||
this.lineSeparated = opts.lineSeparated;
|
||||
this.firstWritten = false;
|
||||
}
|
||||
_transform(chunk, encoding, cb) {
|
||||
if (!this.firstWritten) {
|
||||
this.firstWritten = true;
|
||||
if (!this.lineSeparated) {
|
||||
this.push('[');
|
||||
}
|
||||
}
|
||||
else if (this.lineSeparated) {
|
||||
this.push('\n');
|
||||
}
|
||||
else {
|
||||
this.push(',');
|
||||
}
|
||||
if (chunk) {
|
||||
this.push(JSON.stringify(chunk));
|
||||
}
|
||||
cb();
|
||||
}
|
||||
_flush(cb) {
|
||||
if (!this.lineSeparated) {
|
||||
this.push(']');
|
||||
}
|
||||
cb();
|
||||
}
|
||||
}
|
||||
exports.IndexObjectStreamToJSON = IndexObjectStreamToJSON;
|
||||
169
node_modules/sitemap/dist/cjs/lib/sitemap-index-stream.d.ts
generated
vendored
Normal file
169
node_modules/sitemap/dist/cjs/lib/sitemap-index-stream.d.ts
generated
vendored
Normal file
@@ -0,0 +1,169 @@
|
||||
import { WriteStream } from 'node:fs';
|
||||
import { Transform, TransformOptions, TransformCallback } from 'node:stream';
|
||||
import { IndexItem, SitemapItemLoose, ErrorLevel, IndexTagNames } from './types.js';
|
||||
import { SitemapStream } from './sitemap-stream.js';
|
||||
export { IndexTagNames };
|
||||
/**
|
||||
* Options for the SitemapIndexStream
|
||||
*/
|
||||
export interface SitemapIndexStreamOptions extends TransformOptions {
|
||||
/**
|
||||
* Whether to output the lastmod date only (no time)
|
||||
*
|
||||
* @default false
|
||||
*/
|
||||
lastmodDateOnly?: boolean;
|
||||
/**
|
||||
* How to handle errors in passed in urls
|
||||
*
|
||||
* @default ErrorLevel.WARN
|
||||
*/
|
||||
level?: ErrorLevel;
|
||||
/**
|
||||
* URL to an XSL stylesheet to include in the XML
|
||||
*/
|
||||
xslUrl?: string;
|
||||
}
|
||||
/**
|
||||
* `SitemapIndexStream` is a Transform stream that takes `IndexItem`s or sitemap URL strings and outputs a stream of sitemap index XML.
|
||||
*
|
||||
* It automatically handles the XML declaration and the opening and closing tags for the sitemap index.
|
||||
*
|
||||
* ⚠️ CAUTION: This object is `readable` and must be read (e.g. piped to a file or to /dev/null)
|
||||
* before `finish` will be emitted. Failure to read the stream will result in hangs.
|
||||
*
|
||||
* @extends {Transform}
|
||||
*/
|
||||
export declare class SitemapIndexStream extends Transform {
|
||||
lastmodDateOnly: boolean;
|
||||
level: ErrorLevel;
|
||||
xslUrl?: string;
|
||||
private hasHeadOutput;
|
||||
/**
|
||||
* `SitemapIndexStream` is a Transform stream that takes `IndexItem`s or sitemap URL strings and outputs a stream of sitemap index XML.
|
||||
*
|
||||
* It automatically handles the XML declaration and the opening and closing tags for the sitemap index.
|
||||
*
|
||||
* ⚠️ CAUTION: This object is `readable` and must be read (e.g. piped to a file or to /dev/null)
|
||||
* before `finish` will be emitted. Failure to read the stream will result in hangs.
|
||||
*
|
||||
* @param {SitemapIndexStreamOptions} [opts=defaultStreamOpts] - Stream options.
|
||||
*/
|
||||
constructor(opts?: SitemapIndexStreamOptions);
|
||||
private writeHeadOutput;
|
||||
_transform(item: IndexItem | string, encoding: string, callback: TransformCallback): void;
|
||||
_flush(cb: TransformCallback): void;
|
||||
}
|
||||
/**
|
||||
* Callback function type for creating new sitemap streams when the item limit is reached.
|
||||
*
|
||||
* This function is called by SitemapAndIndexStream to create a new sitemap file when
|
||||
* the current one reaches the item limit.
|
||||
*
|
||||
* @param i - The zero-based index of the sitemap file being created (0 for first sitemap,
|
||||
* 1 for second, etc.)
|
||||
* @returns A tuple containing:
|
||||
* - [0]: IndexItem or URL string to add to the sitemap index
|
||||
* - [1]: SitemapStream instance for writing sitemap items
|
||||
* - [2]: WriteStream where the sitemap will be piped (the stream will be
|
||||
* awaited for 'finish' before creating the next sitemap)
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const getSitemapStream = (i: number) => {
|
||||
* const sitemapStream = new SitemapStream();
|
||||
* const path = `./sitemap-${i}.xml`;
|
||||
* const writeStream = createWriteStream(path);
|
||||
* sitemapStream.pipe(writeStream);
|
||||
* return [`https://example.com/${path}`, sitemapStream, writeStream];
|
||||
* };
|
||||
* ```
|
||||
*/
|
||||
type getSitemapStreamFunc = (i: number) => [IndexItem | string, SitemapStream, WriteStream];
|
||||
/**
|
||||
* Options for the SitemapAndIndexStream
|
||||
*
|
||||
* @extends {SitemapIndexStreamOptions}
|
||||
*/
|
||||
export interface SitemapAndIndexStreamOptions extends SitemapIndexStreamOptions {
|
||||
/**
|
||||
* Max number of items in each sitemap XML file.
|
||||
*
|
||||
* When the limit is reached the current sitemap file will be closed,
|
||||
* a wait for `finish` on the target write stream will happen,
|
||||
* and a new sitemap file will be created.
|
||||
*
|
||||
* Range: 1 - 50,000
|
||||
*
|
||||
* @default 45000
|
||||
*/
|
||||
limit?: number;
|
||||
/**
|
||||
* Callback for SitemapIndexAndStream that creates a new sitemap stream for a given sitemap index.
|
||||
*
|
||||
* Called when a new sitemap file is needed.
|
||||
*
|
||||
* The write stream is the destination where the sitemap was piped.
|
||||
* SitemapAndIndexStream will wait for the `finish` event on each sitemap's
|
||||
* write stream before moving on to the next sitemap. This ensures that the
|
||||
* contents of the write stream will be fully written before being used
|
||||
* by any following operations (e.g. uploading, reading contents for unit tests).
|
||||
*
|
||||
* @param i - The index of the sitemap file
|
||||
* @returns A tuple containing the index item to be written into the sitemap index, the sitemap stream, and the write stream for the sitemap pipe destination
|
||||
*/
|
||||
getSitemapStream: getSitemapStreamFunc;
|
||||
}
|
||||
/**
|
||||
* `SitemapAndIndexStream` is a Transform stream that takes in sitemap items,
|
||||
* writes them to sitemap files, adds the sitemap files to a sitemap index,
|
||||
* and creates new sitemap files when the count limit is reached.
|
||||
*
|
||||
* It waits for the target stream of the current sitemap file to finish before
|
||||
* moving on to the next if the target stream is returned by the `getSitemapStream`
|
||||
* callback in the 3rd position of the tuple.
|
||||
*
|
||||
* ⚠️ CAUTION: This object is `readable` and must be read (e.g. piped to a file or to /dev/null)
|
||||
* before `finish` will be emitted. Failure to read the stream will result in hangs.
|
||||
*
|
||||
* @extends {SitemapIndexStream}
|
||||
*/
|
||||
export declare class SitemapAndIndexStream extends SitemapIndexStream {
|
||||
private itemsWritten;
|
||||
private getSitemapStream;
|
||||
private currentSitemap?;
|
||||
private limit;
|
||||
private currentSitemapPipeline?;
|
||||
/**
|
||||
* Flag to prevent race conditions when creating new sitemap files.
|
||||
* Set to true while waiting for the current sitemap to finish and
|
||||
* a new one to be created.
|
||||
*/
|
||||
private isCreatingSitemap;
|
||||
/**
|
||||
* `SitemapAndIndexStream` is a Transform stream that takes in sitemap items,
|
||||
* writes them to sitemap files, adds the sitemap files to a sitemap index,
|
||||
* and creates new sitemap files when the count limit is reached.
|
||||
*
|
||||
* It waits for the target stream of the current sitemap file to finish before
|
||||
* moving on to the next if the target stream is returned by the `getSitemapStream`
|
||||
* callback in the 3rd position of the tuple.
|
||||
*
|
||||
* ⚠️ CAUTION: This object is `readable` and must be read (e.g. piped to a file or to /dev/null)
|
||||
* before `finish` will be emitted. Failure to read the stream will result in hangs.
|
||||
*
|
||||
* @param {SitemapAndIndexStreamOptions} opts - Stream options.
|
||||
*/
|
||||
constructor(opts: SitemapAndIndexStreamOptions);
|
||||
_transform(item: SitemapItemLoose, encoding: string, callback: TransformCallback): void;
|
||||
private writeItem;
|
||||
/**
|
||||
* Called when the stream is finished.
|
||||
* If there is a current sitemap, we wait for it to finish before calling the callback.
|
||||
* Includes proper event listener cleanup to prevent memory leaks.
|
||||
*
|
||||
* @param cb - The callback to invoke when flushing is complete
|
||||
*/
|
||||
_flush(cb: TransformCallback): void;
|
||||
private createSitemap;
|
||||
}
|
||||
363
node_modules/sitemap/dist/cjs/lib/sitemap-index-stream.js
generated
vendored
Normal file
363
node_modules/sitemap/dist/cjs/lib/sitemap-index-stream.js
generated
vendored
Normal file
@@ -0,0 +1,363 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.SitemapAndIndexStream = exports.SitemapIndexStream = exports.IndexTagNames = void 0;
|
||||
const node_stream_1 = require("node:stream");
|
||||
const types_js_1 = require("./types.js");
|
||||
Object.defineProperty(exports, "IndexTagNames", { enumerable: true, get: function () { return types_js_1.IndexTagNames; } });
|
||||
const sitemap_stream_js_1 = require("./sitemap-stream.js");
|
||||
const sitemap_xml_js_1 = require("./sitemap-xml.js");
|
||||
const constants_js_1 = require("./constants.js");
|
||||
const validation_js_1 = require("./validation.js");
|
||||
const xmlDec = '<?xml version="1.0" encoding="UTF-8"?>';
|
||||
const sitemapIndexTagStart = '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
|
||||
const closetag = '</sitemapindex>';
|
||||
const defaultStreamOpts = {};
|
||||
/**
|
||||
* `SitemapIndexStream` is a Transform stream that takes `IndexItem`s or sitemap URL strings and outputs a stream of sitemap index XML.
|
||||
*
|
||||
* It automatically handles the XML declaration and the opening and closing tags for the sitemap index.
|
||||
*
|
||||
* ⚠️ CAUTION: This object is `readable` and must be read (e.g. piped to a file or to /dev/null)
|
||||
* before `finish` will be emitted. Failure to read the stream will result in hangs.
|
||||
*
|
||||
* @extends {Transform}
|
||||
*/
|
||||
class SitemapIndexStream extends node_stream_1.Transform {
|
||||
lastmodDateOnly;
|
||||
level;
|
||||
xslUrl;
|
||||
hasHeadOutput;
|
||||
/**
|
||||
* `SitemapIndexStream` is a Transform stream that takes `IndexItem`s or sitemap URL strings and outputs a stream of sitemap index XML.
|
||||
*
|
||||
* It automatically handles the XML declaration and the opening and closing tags for the sitemap index.
|
||||
*
|
||||
* ⚠️ CAUTION: This object is `readable` and must be read (e.g. piped to a file or to /dev/null)
|
||||
* before `finish` will be emitted. Failure to read the stream will result in hangs.
|
||||
*
|
||||
* @param {SitemapIndexStreamOptions} [opts=defaultStreamOpts] - Stream options.
|
||||
*/
|
||||
constructor(opts = defaultStreamOpts) {
|
||||
opts.objectMode = true;
|
||||
super(opts);
|
||||
this.hasHeadOutput = false;
|
||||
this.lastmodDateOnly = opts.lastmodDateOnly || false;
|
||||
this.level = opts.level ?? types_js_1.ErrorLevel.WARN;
|
||||
if (opts.xslUrl !== undefined) {
|
||||
(0, validation_js_1.validateXSLUrl)(opts.xslUrl);
|
||||
}
|
||||
this.xslUrl = opts.xslUrl;
|
||||
}
|
||||
writeHeadOutput() {
|
||||
this.hasHeadOutput = true;
|
||||
let stylesheet = '';
|
||||
if (this.xslUrl) {
|
||||
stylesheet = (0, sitemap_stream_js_1.stylesheetInclude)(this.xslUrl);
|
||||
}
|
||||
this.push(xmlDec + stylesheet + sitemapIndexTagStart);
|
||||
}
|
||||
_transform(item, encoding, callback) {
|
||||
if (!this.hasHeadOutput) {
|
||||
this.writeHeadOutput();
|
||||
}
|
||||
try {
|
||||
// Validate URL using centralized validation (checks protocol, length, format)
|
||||
const url = typeof item === 'string' ? item : item.url;
|
||||
if (!url || typeof url !== 'string') {
|
||||
const error = new Error('Invalid sitemap index item: URL must be a non-empty string');
|
||||
if (this.level === types_js_1.ErrorLevel.THROW) {
|
||||
callback(error);
|
||||
return;
|
||||
}
|
||||
else if (this.level === types_js_1.ErrorLevel.WARN) {
|
||||
console.warn(error.message, item);
|
||||
}
|
||||
// For SILENT or after WARN, skip this item
|
||||
callback();
|
||||
return;
|
||||
}
|
||||
// Security: Use centralized validation to enforce protocol restrictions,
|
||||
// length limits, and prevent injection attacks
|
||||
try {
|
||||
(0, validation_js_1.validateURL)(url, 'Sitemap index URL');
|
||||
}
|
||||
catch (error) {
|
||||
// Wrap the validation error with consistent message format
|
||||
const validationMsg = error instanceof Error ? error.message : String(error);
|
||||
const err = new Error(`Invalid URL in sitemap index: ${validationMsg}`);
|
||||
if (this.level === types_js_1.ErrorLevel.THROW) {
|
||||
callback(err);
|
||||
return;
|
||||
}
|
||||
else if (this.level === types_js_1.ErrorLevel.WARN) {
|
||||
console.warn(err.message);
|
||||
}
|
||||
// For SILENT or after WARN, skip this item
|
||||
callback();
|
||||
return;
|
||||
}
|
||||
this.push((0, sitemap_xml_js_1.otag)(types_js_1.IndexTagNames.sitemap));
|
||||
if (typeof item === 'string') {
|
||||
this.push((0, sitemap_xml_js_1.element)(types_js_1.IndexTagNames.loc, item));
|
||||
}
|
||||
else {
|
||||
this.push((0, sitemap_xml_js_1.element)(types_js_1.IndexTagNames.loc, item.url));
|
||||
if (item.lastmod) {
|
||||
try {
|
||||
const lastmod = new Date(item.lastmod).toISOString();
|
||||
this.push((0, sitemap_xml_js_1.element)(types_js_1.IndexTagNames.lastmod, this.lastmodDateOnly ? lastmod.slice(0, 10) : lastmod));
|
||||
}
|
||||
catch {
|
||||
const error = new Error(`Invalid lastmod date in sitemap index: ${item.lastmod}`);
|
||||
if (this.level === types_js_1.ErrorLevel.THROW) {
|
||||
callback(error);
|
||||
return;
|
||||
}
|
||||
else if (this.level === types_js_1.ErrorLevel.WARN) {
|
||||
console.warn(error.message);
|
||||
}
|
||||
// Continue without lastmod for SILENT or after WARN
|
||||
}
|
||||
}
|
||||
}
|
||||
this.push((0, sitemap_xml_js_1.ctag)(types_js_1.IndexTagNames.sitemap));
|
||||
callback();
|
||||
}
|
||||
catch (error) {
|
||||
callback(error instanceof Error ? error : new Error(String(error)));
|
||||
}
|
||||
}
|
||||
_flush(cb) {
|
||||
if (!this.hasHeadOutput) {
|
||||
this.writeHeadOutput();
|
||||
}
|
||||
this.push(closetag);
|
||||
cb();
|
||||
}
|
||||
}
|
||||
exports.SitemapIndexStream = SitemapIndexStream;
|
||||
/**
|
||||
* `SitemapAndIndexStream` is a Transform stream that takes in sitemap items,
|
||||
* writes them to sitemap files, adds the sitemap files to a sitemap index,
|
||||
* and creates new sitemap files when the count limit is reached.
|
||||
*
|
||||
* It waits for the target stream of the current sitemap file to finish before
|
||||
* moving on to the next if the target stream is returned by the `getSitemapStream`
|
||||
* callback in the 3rd position of the tuple.
|
||||
*
|
||||
* ⚠️ CAUTION: This object is `readable` and must be read (e.g. piped to a file or to /dev/null)
|
||||
* before `finish` will be emitted. Failure to read the stream will result in hangs.
|
||||
*
|
||||
* @extends {SitemapIndexStream}
|
||||
*/
|
||||
class SitemapAndIndexStream extends SitemapIndexStream {
|
||||
itemsWritten;
|
||||
getSitemapStream;
|
||||
currentSitemap;
|
||||
limit;
|
||||
currentSitemapPipeline;
|
||||
/**
|
||||
* Flag to prevent race conditions when creating new sitemap files.
|
||||
* Set to true while waiting for the current sitemap to finish and
|
||||
* a new one to be created.
|
||||
*/
|
||||
isCreatingSitemap;
|
||||
/**
|
||||
* `SitemapAndIndexStream` is a Transform stream that takes in sitemap items,
|
||||
* writes them to sitemap files, adds the sitemap files to a sitemap index,
|
||||
* and creates new sitemap files when the count limit is reached.
|
||||
*
|
||||
* It waits for the target stream of the current sitemap file to finish before
|
||||
* moving on to the next if the target stream is returned by the `getSitemapStream`
|
||||
* callback in the 3rd position of the tuple.
|
||||
*
|
||||
* ⚠️ CAUTION: This object is `readable` and must be read (e.g. piped to a file or to /dev/null)
|
||||
* before `finish` will be emitted. Failure to read the stream will result in hangs.
|
||||
*
|
||||
* @param {SitemapAndIndexStreamOptions} opts - Stream options.
|
||||
*/
|
||||
constructor(opts) {
|
||||
opts.objectMode = true;
|
||||
super(opts);
|
||||
this.itemsWritten = 0;
|
||||
this.getSitemapStream = opts.getSitemapStream;
|
||||
this.limit = opts.limit ?? constants_js_1.DEFAULT_SITEMAP_ITEM_LIMIT;
|
||||
this.isCreatingSitemap = false;
|
||||
// Validate limit is within acceptable range per sitemaps.org spec
|
||||
// See: https://www.sitemaps.org/protocol.html#index
|
||||
if (this.limit < constants_js_1.LIMITS.MIN_SITEMAP_ITEM_LIMIT ||
|
||||
this.limit > constants_js_1.LIMITS.MAX_SITEMAP_ITEM_LIMIT) {
|
||||
throw new Error(`limit must be between ${constants_js_1.LIMITS.MIN_SITEMAP_ITEM_LIMIT} and ${constants_js_1.LIMITS.MAX_SITEMAP_ITEM_LIMIT} per sitemaps.org spec, got ${this.limit}`);
|
||||
}
|
||||
}
|
||||
_transform(item, encoding, callback) {
|
||||
if (this.itemsWritten % this.limit === 0) {
|
||||
// Prevent race condition if multiple items arrive during sitemap creation
|
||||
if (this.isCreatingSitemap) {
|
||||
// Wait and retry on next tick
|
||||
process.nextTick(() => this._transform(item, encoding, callback));
|
||||
return;
|
||||
}
|
||||
if (this.currentSitemap) {
|
||||
this.isCreatingSitemap = true;
|
||||
const currentSitemap = this.currentSitemap;
|
||||
const currentPipeline = this.currentSitemapPipeline;
|
||||
// Set up promises with proper cleanup to prevent memory leaks
|
||||
const onFinish = new Promise((resolve, reject) => {
|
||||
const finishHandler = () => {
|
||||
currentSitemap.off('error', errorHandler);
|
||||
resolve();
|
||||
};
|
||||
const errorHandler = (err) => {
|
||||
currentSitemap.off('finish', finishHandler);
|
||||
reject(err);
|
||||
};
|
||||
currentSitemap.on('finish', finishHandler);
|
||||
currentSitemap.on('error', errorHandler);
|
||||
currentSitemap.end();
|
||||
});
|
||||
const onPipelineFinish = currentPipeline
|
||||
? new Promise((resolve, reject) => {
|
||||
const finishHandler = () => {
|
||||
currentPipeline.off('error', errorHandler);
|
||||
resolve();
|
||||
};
|
||||
const errorHandler = (err) => {
|
||||
currentPipeline.off('finish', finishHandler);
|
||||
reject(err);
|
||||
};
|
||||
currentPipeline.on('finish', finishHandler);
|
||||
currentPipeline.on('error', errorHandler);
|
||||
})
|
||||
: Promise.resolve();
|
||||
Promise.all([onFinish, onPipelineFinish])
|
||||
.then(() => {
|
||||
this.isCreatingSitemap = false;
|
||||
this.createSitemap(encoding);
|
||||
this.writeItem(item, callback);
|
||||
})
|
||||
.catch((err) => {
|
||||
this.isCreatingSitemap = false;
|
||||
callback(err);
|
||||
});
|
||||
return;
|
||||
}
|
||||
else {
|
||||
this.createSitemap(encoding);
|
||||
}
|
||||
}
|
||||
this.writeItem(item, callback);
|
||||
}
|
||||
writeItem(item, callback) {
|
||||
if (!this.currentSitemap) {
|
||||
callback(new Error('No sitemap stream available'));
|
||||
return;
|
||||
}
|
||||
if (!this.currentSitemap.write(item)) {
|
||||
this.currentSitemap.once('drain', callback);
|
||||
}
|
||||
else {
|
||||
process.nextTick(callback);
|
||||
}
|
||||
// Increment the count of items written
|
||||
this.itemsWritten++;
|
||||
}
|
||||
/**
|
||||
* Called when the stream is finished.
|
||||
* If there is a current sitemap, we wait for it to finish before calling the callback.
|
||||
* Includes proper event listener cleanup to prevent memory leaks.
|
||||
*
|
||||
* @param cb - The callback to invoke when flushing is complete
|
||||
*/
|
||||
_flush(cb) {
|
||||
const currentSitemap = this.currentSitemap;
|
||||
const currentPipeline = this.currentSitemapPipeline;
|
||||
const onFinish = new Promise((resolve, reject) => {
|
||||
if (currentSitemap) {
|
||||
const finishHandler = () => {
|
||||
currentSitemap.off('error', errorHandler);
|
||||
resolve();
|
||||
};
|
||||
const errorHandler = (err) => {
|
||||
currentSitemap.off('finish', finishHandler);
|
||||
reject(err);
|
||||
};
|
||||
currentSitemap.on('finish', finishHandler);
|
||||
currentSitemap.on('error', errorHandler);
|
||||
currentSitemap.end();
|
||||
}
|
||||
else {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
const onPipelineFinish = new Promise((resolve, reject) => {
|
||||
if (currentPipeline) {
|
||||
const finishHandler = () => {
|
||||
currentPipeline.off('error', errorHandler);
|
||||
resolve();
|
||||
};
|
||||
const errorHandler = (err) => {
|
||||
currentPipeline.off('finish', finishHandler);
|
||||
reject(err);
|
||||
};
|
||||
currentPipeline.on('finish', finishHandler);
|
||||
currentPipeline.on('error', errorHandler);
|
||||
// The pipeline (pipe target) will get its end() call
|
||||
// from the sitemap stream ending.
|
||||
}
|
||||
else {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
Promise.all([onFinish, onPipelineFinish])
|
||||
.then(() => {
|
||||
super._flush(cb);
|
||||
})
|
||||
.catch((err) => {
|
||||
cb(err);
|
||||
});
|
||||
}
|
||||
createSitemap(encoding) {
|
||||
const sitemapIndex = this.itemsWritten / this.limit;
|
||||
let result;
|
||||
try {
|
||||
result = this.getSitemapStream(sitemapIndex);
|
||||
}
|
||||
catch (err) {
|
||||
this.emit('error', new Error(`getSitemapStream callback threw an error for index ${sitemapIndex}: ${err instanceof Error ? err.message : String(err)}`));
|
||||
return;
|
||||
}
|
||||
// Validate the return value
|
||||
if (!Array.isArray(result) || result.length !== 3) {
|
||||
this.emit('error', new Error(`getSitemapStream must return a 3-element array [IndexItem | string, SitemapStream, WriteStream], got: ${typeof result}`));
|
||||
return;
|
||||
}
|
||||
const [idxItem, currentSitemap, currentSitemapPipeline] = result;
|
||||
// Validate each element
|
||||
if (!idxItem ||
|
||||
(typeof idxItem !== 'string' && typeof idxItem !== 'object')) {
|
||||
this.emit('error', new Error('getSitemapStream must return an IndexItem or string as the first element'));
|
||||
return;
|
||||
}
|
||||
if (!currentSitemap || typeof currentSitemap.write !== 'function') {
|
||||
this.emit('error', new Error('getSitemapStream must return a SitemapStream as the second element'));
|
||||
return;
|
||||
}
|
||||
if (currentSitemapPipeline &&
|
||||
typeof currentSitemapPipeline.write !== 'function') {
|
||||
this.emit('error', new Error('getSitemapStream must return a WriteStream or undefined as the third element'));
|
||||
return;
|
||||
}
|
||||
// Propagate errors from the sitemap stream
|
||||
currentSitemap.on('error', (err) => this.emit('error', err));
|
||||
this.currentSitemap = currentSitemap;
|
||||
this.currentSitemapPipeline = currentSitemapPipeline;
|
||||
super._transform(idxItem, encoding, () => {
|
||||
// We are not too concerned about waiting for the index item to be written
|
||||
// as we'll wait for the file to finish at the end, and index file write
|
||||
// volume tends to be small in comparison to sitemap writes.
|
||||
// noop
|
||||
});
|
||||
}
|
||||
}
|
||||
exports.SitemapAndIndexStream = SitemapAndIndexStream;
|
||||
21
node_modules/sitemap/dist/cjs/lib/sitemap-item-stream.d.ts
generated
vendored
Normal file
21
node_modules/sitemap/dist/cjs/lib/sitemap-item-stream.d.ts
generated
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
import { Transform, TransformOptions, TransformCallback } from 'node:stream';
|
||||
import { SitemapItem, ErrorLevel } from './types.js';
|
||||
export interface SitemapItemStreamOptions extends TransformOptions {
|
||||
level?: ErrorLevel;
|
||||
}
|
||||
/**
|
||||
* Takes a stream of SitemapItemOptions and spits out xml for each
|
||||
* @example
|
||||
* // writes <url><loc>https://example.com</loc><url><url><loc>https://example.com/2</loc><url>
|
||||
* const smis = new SitemapItemStream({level: 'warn'})
|
||||
* smis.pipe(writestream)
|
||||
* smis.write({url: 'https://example.com', img: [], video: [], links: []})
|
||||
* smis.write({url: 'https://example.com/2', img: [], video: [], links: []})
|
||||
* smis.end()
|
||||
* @param level - Error level
|
||||
*/
|
||||
export declare class SitemapItemStream extends Transform {
|
||||
level: ErrorLevel;
|
||||
constructor(opts?: SitemapItemStreamOptions);
|
||||
_transform(item: SitemapItem, encoding: string, callback: TransformCallback): void;
|
||||
}
|
||||
208
node_modules/sitemap/dist/cjs/lib/sitemap-item-stream.js
generated
vendored
Normal file
208
node_modules/sitemap/dist/cjs/lib/sitemap-item-stream.js
generated
vendored
Normal file
@@ -0,0 +1,208 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.SitemapItemStream = void 0;
|
||||
const node_stream_1 = require("node:stream");
|
||||
const errors_js_1 = require("./errors.js");
|
||||
const types_js_1 = require("./types.js");
|
||||
const sitemap_xml_js_1 = require("./sitemap-xml.js");
|
||||
/**
|
||||
* Builds an attributes object for XML elements from configuration object
|
||||
* Extracts attributes based on colon-delimited keys (e.g., 'price:currency' -> { currency: value })
|
||||
*
|
||||
* @param conf - Configuration object containing attribute values
|
||||
* @param keys - Single key or array of keys in format 'namespace:attribute'
|
||||
* @returns Record of attribute names to string values (may contain non-string values from conf)
|
||||
* @throws {InvalidAttr} When key format is invalid (must contain exactly one colon)
|
||||
*
|
||||
* @example
|
||||
* attrBuilder({ 'price:currency': 'USD', 'price:type': 'rent' }, ['price:currency', 'price:type'])
|
||||
* // Returns: { currency: 'USD', type: 'rent' }
|
||||
*/
|
||||
function attrBuilder(conf, keys) {
|
||||
if (typeof keys === 'string') {
|
||||
keys = [keys];
|
||||
}
|
||||
const iv = {};
|
||||
return keys.reduce((attrs, key) => {
|
||||
if (conf[key] !== undefined) {
|
||||
const keyAr = key.split(':');
|
||||
if (keyAr.length !== 2) {
|
||||
throw new errors_js_1.InvalidAttr(key);
|
||||
}
|
||||
attrs[keyAr[1]] = conf[key];
|
||||
}
|
||||
return attrs;
|
||||
}, iv);
|
||||
}
|
||||
/**
|
||||
* Takes a stream of SitemapItemOptions and spits out xml for each
|
||||
* @example
|
||||
* // writes <url><loc>https://example.com</loc><url><url><loc>https://example.com/2</loc><url>
|
||||
* const smis = new SitemapItemStream({level: 'warn'})
|
||||
* smis.pipe(writestream)
|
||||
* smis.write({url: 'https://example.com', img: [], video: [], links: []})
|
||||
* smis.write({url: 'https://example.com/2', img: [], video: [], links: []})
|
||||
* smis.end()
|
||||
* @param level - Error level
|
||||
*/
|
||||
class SitemapItemStream extends node_stream_1.Transform {
|
||||
level;
|
||||
constructor(opts = { level: types_js_1.ErrorLevel.WARN }) {
|
||||
opts.objectMode = true;
|
||||
super(opts);
|
||||
this.level = opts.level || types_js_1.ErrorLevel.WARN;
|
||||
}
|
||||
_transform(item, encoding, callback) {
|
||||
this.push((0, sitemap_xml_js_1.otag)(types_js_1.TagNames.url));
|
||||
this.push((0, sitemap_xml_js_1.element)(types_js_1.TagNames.loc, item.url));
|
||||
if (item.lastmod) {
|
||||
this.push((0, sitemap_xml_js_1.element)(types_js_1.TagNames.lastmod, item.lastmod));
|
||||
}
|
||||
if (item.changefreq) {
|
||||
this.push((0, sitemap_xml_js_1.element)(types_js_1.TagNames.changefreq, item.changefreq));
|
||||
}
|
||||
if (item.priority !== undefined && item.priority !== null) {
|
||||
if (item.fullPrecisionPriority) {
|
||||
this.push((0, sitemap_xml_js_1.element)(types_js_1.TagNames.priority, item.priority.toString()));
|
||||
}
|
||||
else {
|
||||
this.push((0, sitemap_xml_js_1.element)(types_js_1.TagNames.priority, item.priority.toFixed(1)));
|
||||
}
|
||||
}
|
||||
item.video.forEach((video) => {
|
||||
this.push((0, sitemap_xml_js_1.otag)(types_js_1.TagNames['video:video']));
|
||||
this.push((0, sitemap_xml_js_1.element)(types_js_1.TagNames['video:thumbnail_loc'], video.thumbnail_loc));
|
||||
this.push((0, sitemap_xml_js_1.element)(types_js_1.TagNames['video:title'], video.title));
|
||||
this.push((0, sitemap_xml_js_1.element)(types_js_1.TagNames['video:description'], video.description));
|
||||
if (video.content_loc) {
|
||||
this.push((0, sitemap_xml_js_1.element)(types_js_1.TagNames['video:content_loc'], video.content_loc));
|
||||
}
|
||||
if (video.player_loc) {
|
||||
this.push((0, sitemap_xml_js_1.element)(types_js_1.TagNames['video:player_loc'], attrBuilder(video, [
|
||||
'player_loc:autoplay',
|
||||
'player_loc:allow_embed',
|
||||
]), video.player_loc));
|
||||
}
|
||||
if (video.duration) {
|
||||
this.push((0, sitemap_xml_js_1.element)(types_js_1.TagNames['video:duration'], video.duration.toString()));
|
||||
}
|
||||
if (video.expiration_date) {
|
||||
this.push((0, sitemap_xml_js_1.element)(types_js_1.TagNames['video:expiration_date'], video.expiration_date));
|
||||
}
|
||||
if (video.rating !== undefined) {
|
||||
this.push((0, sitemap_xml_js_1.element)(types_js_1.TagNames['video:rating'], video.rating.toString()));
|
||||
}
|
||||
if (video.view_count !== undefined) {
|
||||
this.push((0, sitemap_xml_js_1.element)(types_js_1.TagNames['video:view_count'], String(video.view_count)));
|
||||
}
|
||||
if (video.publication_date) {
|
||||
this.push((0, sitemap_xml_js_1.element)(types_js_1.TagNames['video:publication_date'], video.publication_date));
|
||||
}
|
||||
if (video.tag && video.tag.length > 0) {
|
||||
for (const tag of video.tag) {
|
||||
this.push((0, sitemap_xml_js_1.element)(types_js_1.TagNames['video:tag'], tag));
|
||||
}
|
||||
}
|
||||
if (video.category) {
|
||||
this.push((0, sitemap_xml_js_1.element)(types_js_1.TagNames['video:category'], video.category));
|
||||
}
|
||||
if (video.family_friendly) {
|
||||
this.push((0, sitemap_xml_js_1.element)(types_js_1.TagNames['video:family_friendly'], video.family_friendly));
|
||||
}
|
||||
if (video.restriction) {
|
||||
this.push((0, sitemap_xml_js_1.element)(types_js_1.TagNames['video:restriction'], attrBuilder(video, 'restriction:relationship'), video.restriction));
|
||||
}
|
||||
if (video.gallery_loc) {
|
||||
this.push((0, sitemap_xml_js_1.element)(types_js_1.TagNames['video:gallery_loc'], attrBuilder(video, 'gallery_loc:title'), video.gallery_loc));
|
||||
}
|
||||
if (video.price) {
|
||||
this.push((0, sitemap_xml_js_1.element)(types_js_1.TagNames['video:price'], attrBuilder(video, [
|
||||
'price:resolution',
|
||||
'price:currency',
|
||||
'price:type',
|
||||
]), video.price));
|
||||
}
|
||||
if (video.requires_subscription) {
|
||||
this.push((0, sitemap_xml_js_1.element)(types_js_1.TagNames['video:requires_subscription'], video.requires_subscription));
|
||||
}
|
||||
if (video.uploader) {
|
||||
this.push((0, sitemap_xml_js_1.element)(types_js_1.TagNames['video:uploader'], attrBuilder(video, 'uploader:info'), video.uploader));
|
||||
}
|
||||
if (video.platform) {
|
||||
this.push((0, sitemap_xml_js_1.element)(types_js_1.TagNames['video:platform'], attrBuilder(video, 'platform:relationship'), video.platform));
|
||||
}
|
||||
if (video.live) {
|
||||
this.push((0, sitemap_xml_js_1.element)(types_js_1.TagNames['video:live'], video.live));
|
||||
}
|
||||
if (video.id) {
|
||||
this.push((0, sitemap_xml_js_1.element)(types_js_1.TagNames['video:id'], { type: 'url' }, video.id));
|
||||
}
|
||||
this.push((0, sitemap_xml_js_1.ctag)(types_js_1.TagNames['video:video']));
|
||||
});
|
||||
item.links.forEach((link) => {
|
||||
this.push((0, sitemap_xml_js_1.element)(types_js_1.TagNames['xhtml:link'], {
|
||||
rel: 'alternate',
|
||||
hreflang: link.lang || link.hreflang,
|
||||
href: link.url,
|
||||
}));
|
||||
});
|
||||
if (item.expires) {
|
||||
this.push((0, sitemap_xml_js_1.element)(types_js_1.TagNames.expires, new Date(item.expires).toISOString()));
|
||||
}
|
||||
if (item.androidLink) {
|
||||
this.push((0, sitemap_xml_js_1.element)(types_js_1.TagNames['xhtml:link'], {
|
||||
rel: 'alternate',
|
||||
href: item.androidLink,
|
||||
}));
|
||||
}
|
||||
if (item.ampLink) {
|
||||
this.push((0, sitemap_xml_js_1.element)(types_js_1.TagNames['xhtml:link'], {
|
||||
rel: 'amphtml',
|
||||
href: item.ampLink,
|
||||
}));
|
||||
}
|
||||
if (item.news) {
|
||||
this.push((0, sitemap_xml_js_1.otag)(types_js_1.TagNames['news:news']));
|
||||
this.push((0, sitemap_xml_js_1.otag)(types_js_1.TagNames['news:publication']));
|
||||
this.push((0, sitemap_xml_js_1.element)(types_js_1.TagNames['news:name'], item.news.publication.name));
|
||||
this.push((0, sitemap_xml_js_1.element)(types_js_1.TagNames['news:language'], item.news.publication.language));
|
||||
this.push((0, sitemap_xml_js_1.ctag)(types_js_1.TagNames['news:publication']));
|
||||
if (item.news.access) {
|
||||
this.push((0, sitemap_xml_js_1.element)(types_js_1.TagNames['news:access'], item.news.access));
|
||||
}
|
||||
if (item.news.genres) {
|
||||
this.push((0, sitemap_xml_js_1.element)(types_js_1.TagNames['news:genres'], item.news.genres));
|
||||
}
|
||||
this.push((0, sitemap_xml_js_1.element)(types_js_1.TagNames['news:publication_date'], item.news.publication_date));
|
||||
this.push((0, sitemap_xml_js_1.element)(types_js_1.TagNames['news:title'], item.news.title));
|
||||
if (item.news.keywords) {
|
||||
this.push((0, sitemap_xml_js_1.element)(types_js_1.TagNames['news:keywords'], item.news.keywords));
|
||||
}
|
||||
if (item.news.stock_tickers) {
|
||||
this.push((0, sitemap_xml_js_1.element)(types_js_1.TagNames['news:stock_tickers'], item.news.stock_tickers));
|
||||
}
|
||||
this.push((0, sitemap_xml_js_1.ctag)(types_js_1.TagNames['news:news']));
|
||||
}
|
||||
// Image handling
|
||||
item.img.forEach((image) => {
|
||||
this.push((0, sitemap_xml_js_1.otag)(types_js_1.TagNames['image:image']));
|
||||
this.push((0, sitemap_xml_js_1.element)(types_js_1.TagNames['image:loc'], image.url));
|
||||
if (image.caption) {
|
||||
this.push((0, sitemap_xml_js_1.element)(types_js_1.TagNames['image:caption'], image.caption));
|
||||
}
|
||||
if (image.geoLocation) {
|
||||
this.push((0, sitemap_xml_js_1.element)(types_js_1.TagNames['image:geo_location'], image.geoLocation));
|
||||
}
|
||||
if (image.title) {
|
||||
this.push((0, sitemap_xml_js_1.element)(types_js_1.TagNames['image:title'], image.title));
|
||||
}
|
||||
if (image.license) {
|
||||
this.push((0, sitemap_xml_js_1.element)(types_js_1.TagNames['image:license'], image.license));
|
||||
}
|
||||
this.push((0, sitemap_xml_js_1.ctag)(types_js_1.TagNames['image:image']));
|
||||
});
|
||||
this.push((0, sitemap_xml_js_1.ctag)(types_js_1.TagNames.url));
|
||||
callback();
|
||||
}
|
||||
}
|
||||
exports.SitemapItemStream = SitemapItemStream;
|
||||
62
node_modules/sitemap/dist/cjs/lib/sitemap-parser.d.ts
generated
vendored
Normal file
62
node_modules/sitemap/dist/cjs/lib/sitemap-parser.d.ts
generated
vendored
Normal file
@@ -0,0 +1,62 @@
|
||||
import type { SAXStream } from 'sax';
|
||||
import { Readable, Transform, TransformOptions, TransformCallback } from 'node:stream';
|
||||
import { SitemapItem, ErrorLevel } from './types.js';
|
||||
type Logger = (level: 'warn' | 'error' | 'info' | 'log', ...message: Parameters<Console['log']>[0]) => void;
|
||||
export interface XMLToSitemapItemStreamOptions extends TransformOptions {
|
||||
level?: ErrorLevel;
|
||||
logger?: Logger | false;
|
||||
}
|
||||
/**
|
||||
* Takes a stream of xml and transforms it into a stream of SitemapItems
|
||||
* Use this to parse existing sitemaps into config options compatible with this library
|
||||
*/
|
||||
export declare class XMLToSitemapItemStream extends Transform {
|
||||
level: ErrorLevel;
|
||||
logger: Logger;
|
||||
/**
|
||||
* Errors encountered during parsing, capped at LIMITS.MAX_PARSER_ERRORS entries
|
||||
* to prevent memory DoS from malformed XML (BB-03).
|
||||
* Use errorCount for the total number of errors regardless of the cap.
|
||||
*/
|
||||
errors: Error[];
|
||||
/** Total number of errors seen, including those beyond the stored cap. */
|
||||
errorCount: number;
|
||||
saxStream: SAXStream;
|
||||
urlCount: number;
|
||||
constructor(opts?: XMLToSitemapItemStreamOptions);
|
||||
_transform(data: string, encoding: string, callback: TransformCallback): void;
|
||||
private err;
|
||||
}
|
||||
/**
|
||||
Read xml and resolve with the configuration that would produce it or reject with
|
||||
an error
|
||||
```
|
||||
const { createReadStream } = require('fs')
|
||||
const { parseSitemap, createSitemap } = require('sitemap')
|
||||
parseSitemap(createReadStream('./example.xml')).then(
|
||||
// produces the same xml
|
||||
// you can, of course, more practically modify it or store it
|
||||
(xmlConfig) => console.log(createSitemap(xmlConfig).toString()),
|
||||
(err) => console.log(err)
|
||||
)
|
||||
```
|
||||
@param {Readable} xml what to parse
|
||||
@return {Promise<SitemapItem[]>} resolves with list of sitemap items that can be fed into a SitemapStream. Rejects with an Error object.
|
||||
*/
|
||||
export declare function parseSitemap(xml: Readable): Promise<SitemapItem[]>;
|
||||
export interface ObjectStreamToJSONOptions extends TransformOptions {
|
||||
lineSeparated: boolean;
|
||||
}
|
||||
/**
|
||||
* A Transform that converts a stream of objects into a JSON Array or a line
|
||||
* separated stringified JSON
|
||||
* @param [lineSeparated=false] whether to separate entries by a new line or comma
|
||||
*/
|
||||
export declare class ObjectStreamToJSON extends Transform {
|
||||
lineSeparated: boolean;
|
||||
firstWritten: boolean;
|
||||
constructor(opts?: ObjectStreamToJSONOptions);
|
||||
_transform(chunk: SitemapItem, encoding: string, cb: TransformCallback): void;
|
||||
_flush(cb: TransformCallback): void;
|
||||
}
|
||||
export {};
|
||||
788
node_modules/sitemap/dist/cjs/lib/sitemap-parser.js
generated
vendored
Normal file
788
node_modules/sitemap/dist/cjs/lib/sitemap-parser.js
generated
vendored
Normal file
@@ -0,0 +1,788 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ObjectStreamToJSON = exports.XMLToSitemapItemStream = void 0;
|
||||
exports.parseSitemap = parseSitemap;
|
||||
const sax_1 = __importDefault(require("sax"));
|
||||
const node_stream_1 = require("node:stream");
|
||||
const types_js_1 = require("./types.js");
|
||||
const validation_js_1 = require("./validation.js");
|
||||
const constants_js_1 = require("./constants.js");
|
||||
function isValidTagName(tagName) {
|
||||
// This only works because the enum name and value are the same
|
||||
return tagName in types_js_1.TagNames;
|
||||
}
|
||||
function getAttrValue(attr) {
|
||||
if (!attr)
|
||||
return undefined;
|
||||
return typeof attr === 'string' ? attr : attr.value;
|
||||
}
|
||||
function tagTemplate() {
|
||||
return {
|
||||
img: [],
|
||||
video: [],
|
||||
links: [],
|
||||
url: '',
|
||||
};
|
||||
}
|
||||
function videoTemplate() {
|
||||
return {
|
||||
tag: [],
|
||||
thumbnail_loc: '',
|
||||
title: '',
|
||||
description: '',
|
||||
};
|
||||
}
|
||||
const imageTemplate = {
|
||||
url: '',
|
||||
};
|
||||
const linkTemplate = {
|
||||
lang: '',
|
||||
url: '',
|
||||
};
|
||||
function newsTemplate() {
|
||||
return {
|
||||
publication: { name: '', language: '' },
|
||||
publication_date: '',
|
||||
title: '',
|
||||
};
|
||||
}
|
||||
const defaultLogger = (level, ...message) => console[level](...message);
|
||||
const defaultStreamOpts = {
|
||||
logger: defaultLogger,
|
||||
};
|
||||
// TODO does this need to end with `options`
|
||||
/**
|
||||
* Takes a stream of xml and transforms it into a stream of SitemapItems
|
||||
* Use this to parse existing sitemaps into config options compatible with this library
|
||||
*/
|
||||
class XMLToSitemapItemStream extends node_stream_1.Transform {
|
||||
level;
|
||||
logger;
|
||||
/**
|
||||
* Errors encountered during parsing, capped at LIMITS.MAX_PARSER_ERRORS entries
|
||||
* to prevent memory DoS from malformed XML (BB-03).
|
||||
* Use errorCount for the total number of errors regardless of the cap.
|
||||
*/
|
||||
errors;
|
||||
/** Total number of errors seen, including those beyond the stored cap. */
|
||||
errorCount;
|
||||
saxStream;
|
||||
urlCount;
|
||||
constructor(opts = defaultStreamOpts) {
|
||||
opts.objectMode = true;
|
||||
super(opts);
|
||||
this.errors = [];
|
||||
this.errorCount = 0;
|
||||
this.urlCount = 0;
|
||||
this.saxStream = sax_1.default.createStream(true, {
|
||||
xmlns: true,
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
strictEntities: true,
|
||||
trim: true,
|
||||
});
|
||||
this.level = opts.level || types_js_1.ErrorLevel.WARN;
|
||||
if (this.level !== types_js_1.ErrorLevel.SILENT && opts.logger !== false) {
|
||||
this.logger = opts.logger ?? defaultLogger;
|
||||
}
|
||||
else {
|
||||
this.logger = () => undefined;
|
||||
}
|
||||
let currentItem = tagTemplate();
|
||||
let currentTag;
|
||||
let currentVideo = videoTemplate();
|
||||
let currentImage = { ...imageTemplate };
|
||||
let currentLink = { ...linkTemplate };
|
||||
let dontpushCurrentLink = false;
|
||||
this.saxStream.on('opentagstart', (tag) => {
|
||||
currentTag = tag.name;
|
||||
if (currentTag.startsWith('news:') && !currentItem.news) {
|
||||
currentItem.news = newsTemplate();
|
||||
}
|
||||
});
|
||||
this.saxStream.on('opentag', (tag) => {
|
||||
if (isValidTagName(tag.name)) {
|
||||
if (tag.name === 'xhtml:link') {
|
||||
// SAX returns attributes as objects with {name, value, prefix, local, uri}
|
||||
// Check if required attributes exist and have values
|
||||
const rel = getAttrValue(tag.attributes.rel);
|
||||
const href = getAttrValue(tag.attributes.href);
|
||||
const hreflang = getAttrValue(tag.attributes.hreflang);
|
||||
if (!rel || !href) {
|
||||
this.logger('warn', 'xhtml:link missing required rel or href attribute');
|
||||
this.err('xhtml:link missing required rel or href attribute');
|
||||
return;
|
||||
}
|
||||
if (rel === 'alternate' && hreflang) {
|
||||
currentLink.url = href;
|
||||
currentLink.lang = hreflang;
|
||||
}
|
||||
else if (rel === 'alternate') {
|
||||
dontpushCurrentLink = true;
|
||||
currentItem.androidLink = href;
|
||||
}
|
||||
else if (rel === 'amphtml') {
|
||||
dontpushCurrentLink = true;
|
||||
currentItem.ampLink = href;
|
||||
}
|
||||
else {
|
||||
this.logger('log', 'unhandled attr for xhtml:link', tag.attributes);
|
||||
this.err(`unhandled attr for xhtml:link ${JSON.stringify(tag.attributes)}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
this.logger('warn', 'unhandled tag', tag.name);
|
||||
this.err(`unhandled tag: ${tag.name}`);
|
||||
}
|
||||
});
|
||||
this.saxStream.on('text', (text) => {
|
||||
switch (currentTag) {
|
||||
case 'mobile:mobile':
|
||||
break;
|
||||
case types_js_1.TagNames.loc:
|
||||
// Validate URL
|
||||
if (text.length > constants_js_1.LIMITS.MAX_URL_LENGTH) {
|
||||
this.logger('warn', `URL exceeds max length of ${constants_js_1.LIMITS.MAX_URL_LENGTH}: ${text.substring(0, 100)}...`);
|
||||
this.err(`URL exceeds max length of ${constants_js_1.LIMITS.MAX_URL_LENGTH}`);
|
||||
}
|
||||
else if (!constants_js_1.LIMITS.URL_PROTOCOL_REGEX.test(text)) {
|
||||
this.logger('warn', `URL must start with http:// or https://: ${text}`);
|
||||
this.err(`URL must start with http:// or https://: ${text}`);
|
||||
}
|
||||
else {
|
||||
currentItem.url = text;
|
||||
}
|
||||
break;
|
||||
case types_js_1.TagNames.changefreq:
|
||||
if ((0, validation_js_1.isValidChangeFreq)(text)) {
|
||||
currentItem.changefreq = text;
|
||||
}
|
||||
break;
|
||||
case types_js_1.TagNames.priority:
|
||||
{
|
||||
const priority = parseFloat(text);
|
||||
if (isNaN(priority) ||
|
||||
!isFinite(priority) ||
|
||||
priority < 0 ||
|
||||
priority > 1) {
|
||||
this.logger('warn', `Invalid priority "${text}" - must be between 0 and 1`);
|
||||
this.err(`Invalid priority "${text}" - must be between 0 and 1`);
|
||||
}
|
||||
else {
|
||||
currentItem.priority = priority;
|
||||
}
|
||||
}
|
||||
break;
|
||||
case types_js_1.TagNames.lastmod:
|
||||
if (constants_js_1.LIMITS.ISO_DATE_REGEX.test(text)) {
|
||||
currentItem.lastmod = text;
|
||||
}
|
||||
else {
|
||||
this.logger('warn', `Invalid lastmod date format "${text}" - expected ISO 8601 format`);
|
||||
this.err(`Invalid lastmod date format "${text}" - expected ISO 8601 format`);
|
||||
}
|
||||
break;
|
||||
case types_js_1.TagNames['video:thumbnail_loc']:
|
||||
currentVideo.thumbnail_loc = text;
|
||||
break;
|
||||
case types_js_1.TagNames['video:tag']:
|
||||
if (currentVideo.tag.length < constants_js_1.LIMITS.MAX_TAGS_PER_VIDEO) {
|
||||
currentVideo.tag.push(text);
|
||||
}
|
||||
else {
|
||||
this.logger('warn', `video has too many tags (max ${constants_js_1.LIMITS.MAX_TAGS_PER_VIDEO})`);
|
||||
this.err(`video has too many tags (max ${constants_js_1.LIMITS.MAX_TAGS_PER_VIDEO})`);
|
||||
}
|
||||
break;
|
||||
case types_js_1.TagNames['video:duration']:
|
||||
{
|
||||
const duration = parseInt(text, 10);
|
||||
if (isNaN(duration) ||
|
||||
!isFinite(duration) ||
|
||||
duration < 0 ||
|
||||
duration > 28800) {
|
||||
this.logger('warn', `Invalid video duration "${text}" - must be between 0 and 28800 seconds`);
|
||||
this.err(`Invalid video duration "${text}" - must be between 0 and 28800 seconds`);
|
||||
}
|
||||
else {
|
||||
currentVideo.duration = duration;
|
||||
}
|
||||
}
|
||||
break;
|
||||
case types_js_1.TagNames['video:player_loc']:
|
||||
currentVideo.player_loc = text;
|
||||
break;
|
||||
case types_js_1.TagNames['video:content_loc']:
|
||||
currentVideo.content_loc = text;
|
||||
break;
|
||||
case types_js_1.TagNames['video:requires_subscription']:
|
||||
if ((0, validation_js_1.isValidYesNo)(text)) {
|
||||
currentVideo.requires_subscription = text;
|
||||
}
|
||||
break;
|
||||
case types_js_1.TagNames['video:publication_date']:
|
||||
if (constants_js_1.LIMITS.ISO_DATE_REGEX.test(text)) {
|
||||
currentVideo.publication_date = text;
|
||||
}
|
||||
else {
|
||||
this.logger('warn', `Invalid video publication_date format "${text}" - expected ISO 8601 format`);
|
||||
this.err(`Invalid video publication_date format "${text}" - expected ISO 8601 format`);
|
||||
}
|
||||
break;
|
||||
case types_js_1.TagNames['video:id']:
|
||||
currentVideo.id = text;
|
||||
break;
|
||||
case types_js_1.TagNames['video:restriction']:
|
||||
currentVideo.restriction = text;
|
||||
break;
|
||||
case types_js_1.TagNames['video:view_count']:
|
||||
{
|
||||
const viewCount = parseInt(text, 10);
|
||||
if (isNaN(viewCount) || !isFinite(viewCount) || viewCount < 0) {
|
||||
this.logger('warn', `Invalid video view_count "${text}" - must be a positive integer`);
|
||||
this.err(`Invalid video view_count "${text}" - must be a positive integer`);
|
||||
}
|
||||
else {
|
||||
currentVideo.view_count = viewCount;
|
||||
}
|
||||
}
|
||||
break;
|
||||
case types_js_1.TagNames['video:uploader']:
|
||||
currentVideo.uploader = text;
|
||||
break;
|
||||
case types_js_1.TagNames['video:family_friendly']:
|
||||
if ((0, validation_js_1.isValidYesNo)(text)) {
|
||||
currentVideo.family_friendly = text;
|
||||
}
|
||||
break;
|
||||
case types_js_1.TagNames['video:expiration_date']:
|
||||
if (constants_js_1.LIMITS.ISO_DATE_REGEX.test(text)) {
|
||||
currentVideo.expiration_date = text;
|
||||
}
|
||||
else {
|
||||
this.logger('warn', `Invalid video expiration_date format "${text}" - expected ISO 8601 format`);
|
||||
this.err(`Invalid video expiration_date format "${text}" - expected ISO 8601 format`);
|
||||
}
|
||||
break;
|
||||
case types_js_1.TagNames['video:platform']:
|
||||
currentVideo.platform = text;
|
||||
break;
|
||||
case types_js_1.TagNames['video:price']:
|
||||
currentVideo.price = text;
|
||||
break;
|
||||
case types_js_1.TagNames['video:rating']:
|
||||
{
|
||||
const rating = parseFloat(text);
|
||||
if (isNaN(rating) ||
|
||||
!isFinite(rating) ||
|
||||
rating < 0 ||
|
||||
rating > 5) {
|
||||
this.logger('warn', `Invalid video rating "${text}" - must be between 0 and 5`);
|
||||
this.err(`Invalid video rating "${text}" - must be between 0 and 5`);
|
||||
}
|
||||
else {
|
||||
currentVideo.rating = rating;
|
||||
}
|
||||
}
|
||||
break;
|
||||
case types_js_1.TagNames['video:category']:
|
||||
currentVideo.category = text;
|
||||
break;
|
||||
case types_js_1.TagNames['video:live']:
|
||||
if ((0, validation_js_1.isValidYesNo)(text)) {
|
||||
currentVideo.live = text;
|
||||
}
|
||||
break;
|
||||
case types_js_1.TagNames['video:gallery_loc']:
|
||||
currentVideo.gallery_loc = text;
|
||||
break;
|
||||
case types_js_1.TagNames['image:loc']:
|
||||
currentImage.url = text;
|
||||
break;
|
||||
case types_js_1.TagNames['image:geo_location']:
|
||||
currentImage.geoLocation = text;
|
||||
break;
|
||||
case types_js_1.TagNames['image:license']:
|
||||
currentImage.license = text;
|
||||
break;
|
||||
case types_js_1.TagNames['news:access']:
|
||||
if (!currentItem.news) {
|
||||
currentItem.news = newsTemplate();
|
||||
}
|
||||
if (text === 'Registration' || text === 'Subscription') {
|
||||
currentItem.news.access = text;
|
||||
}
|
||||
else {
|
||||
this.logger('warn', `Invalid news:access value "${text}" - must be "Registration" or "Subscription"`);
|
||||
this.err(`Invalid news:access value "${text}" - must be "Registration" or "Subscription"`);
|
||||
}
|
||||
break;
|
||||
case types_js_1.TagNames['news:genres']:
|
||||
if (!currentItem.news) {
|
||||
currentItem.news = newsTemplate();
|
||||
}
|
||||
currentItem.news.genres = text;
|
||||
break;
|
||||
case types_js_1.TagNames['news:publication_date']:
|
||||
if (!currentItem.news) {
|
||||
currentItem.news = newsTemplate();
|
||||
}
|
||||
if (constants_js_1.LIMITS.ISO_DATE_REGEX.test(text)) {
|
||||
currentItem.news.publication_date = text;
|
||||
}
|
||||
else {
|
||||
this.logger('warn', `Invalid news publication_date format "${text}" - expected ISO 8601 format`);
|
||||
this.err(`Invalid news publication_date format "${text}" - expected ISO 8601 format`);
|
||||
}
|
||||
break;
|
||||
case types_js_1.TagNames['news:keywords']:
|
||||
if (!currentItem.news) {
|
||||
currentItem.news = newsTemplate();
|
||||
}
|
||||
currentItem.news.keywords = text;
|
||||
break;
|
||||
case types_js_1.TagNames['news:stock_tickers']:
|
||||
if (!currentItem.news) {
|
||||
currentItem.news = newsTemplate();
|
||||
}
|
||||
currentItem.news.stock_tickers = text;
|
||||
break;
|
||||
case types_js_1.TagNames['news:language']:
|
||||
if (!currentItem.news) {
|
||||
currentItem.news = newsTemplate();
|
||||
}
|
||||
currentItem.news.publication.language = text;
|
||||
break;
|
||||
case types_js_1.TagNames['video:title']:
|
||||
if (currentVideo.title.length + text.length <=
|
||||
constants_js_1.LIMITS.MAX_VIDEO_TITLE_LENGTH) {
|
||||
currentVideo.title += text;
|
||||
}
|
||||
else {
|
||||
this.logger('warn', `video title exceeds max length of ${constants_js_1.LIMITS.MAX_VIDEO_TITLE_LENGTH}`);
|
||||
this.err(`video title exceeds max length of ${constants_js_1.LIMITS.MAX_VIDEO_TITLE_LENGTH}`);
|
||||
}
|
||||
break;
|
||||
case types_js_1.TagNames['video:description']:
|
||||
if (currentVideo.description.length + text.length <=
|
||||
constants_js_1.LIMITS.MAX_VIDEO_DESCRIPTION_LENGTH) {
|
||||
currentVideo.description += text;
|
||||
}
|
||||
else {
|
||||
this.logger('warn', `video description exceeds max length of ${constants_js_1.LIMITS.MAX_VIDEO_DESCRIPTION_LENGTH}`);
|
||||
this.err(`video description exceeds max length of ${constants_js_1.LIMITS.MAX_VIDEO_DESCRIPTION_LENGTH}`);
|
||||
}
|
||||
break;
|
||||
case types_js_1.TagNames['news:name']:
|
||||
if (!currentItem.news) {
|
||||
currentItem.news = newsTemplate();
|
||||
}
|
||||
if (currentItem.news.publication.name.length + text.length <=
|
||||
constants_js_1.LIMITS.MAX_NEWS_NAME_LENGTH) {
|
||||
currentItem.news.publication.name += text;
|
||||
}
|
||||
else {
|
||||
this.logger('warn', `news name exceeds max length of ${constants_js_1.LIMITS.MAX_NEWS_NAME_LENGTH}`);
|
||||
this.err(`news name exceeds max length of ${constants_js_1.LIMITS.MAX_NEWS_NAME_LENGTH}`);
|
||||
}
|
||||
break;
|
||||
case types_js_1.TagNames['news:title']:
|
||||
if (!currentItem.news) {
|
||||
currentItem.news = newsTemplate();
|
||||
}
|
||||
if (currentItem.news.title.length + text.length <=
|
||||
constants_js_1.LIMITS.MAX_NEWS_TITLE_LENGTH) {
|
||||
currentItem.news.title += text;
|
||||
}
|
||||
else {
|
||||
this.logger('warn', `news title exceeds max length of ${constants_js_1.LIMITS.MAX_NEWS_TITLE_LENGTH}`);
|
||||
this.err(`news title exceeds max length of ${constants_js_1.LIMITS.MAX_NEWS_TITLE_LENGTH}`);
|
||||
}
|
||||
break;
|
||||
case types_js_1.TagNames['image:caption']:
|
||||
if (!currentImage.caption) {
|
||||
currentImage.caption =
|
||||
text.length <= constants_js_1.LIMITS.MAX_IMAGE_CAPTION_LENGTH
|
||||
? text
|
||||
: text.substring(0, constants_js_1.LIMITS.MAX_IMAGE_CAPTION_LENGTH);
|
||||
if (text.length > constants_js_1.LIMITS.MAX_IMAGE_CAPTION_LENGTH) {
|
||||
this.logger('warn', `image caption exceeds max length of ${constants_js_1.LIMITS.MAX_IMAGE_CAPTION_LENGTH}`);
|
||||
this.err(`image caption exceeds max length of ${constants_js_1.LIMITS.MAX_IMAGE_CAPTION_LENGTH}`);
|
||||
}
|
||||
}
|
||||
else if (currentImage.caption.length + text.length <=
|
||||
constants_js_1.LIMITS.MAX_IMAGE_CAPTION_LENGTH) {
|
||||
currentImage.caption += text;
|
||||
}
|
||||
else {
|
||||
this.logger('warn', `image caption exceeds max length of ${constants_js_1.LIMITS.MAX_IMAGE_CAPTION_LENGTH}`);
|
||||
this.err(`image caption exceeds max length of ${constants_js_1.LIMITS.MAX_IMAGE_CAPTION_LENGTH}`);
|
||||
}
|
||||
break;
|
||||
case types_js_1.TagNames['image:title']:
|
||||
if (!currentImage.title) {
|
||||
currentImage.title =
|
||||
text.length <= constants_js_1.LIMITS.MAX_IMAGE_TITLE_LENGTH
|
||||
? text
|
||||
: text.substring(0, constants_js_1.LIMITS.MAX_IMAGE_TITLE_LENGTH);
|
||||
if (text.length > constants_js_1.LIMITS.MAX_IMAGE_TITLE_LENGTH) {
|
||||
this.logger('warn', `image title exceeds max length of ${constants_js_1.LIMITS.MAX_IMAGE_TITLE_LENGTH}`);
|
||||
this.err(`image title exceeds max length of ${constants_js_1.LIMITS.MAX_IMAGE_TITLE_LENGTH}`);
|
||||
}
|
||||
}
|
||||
else if (currentImage.title.length + text.length <=
|
||||
constants_js_1.LIMITS.MAX_IMAGE_TITLE_LENGTH) {
|
||||
currentImage.title += text;
|
||||
}
|
||||
else {
|
||||
this.logger('warn', `image title exceeds max length of ${constants_js_1.LIMITS.MAX_IMAGE_TITLE_LENGTH}`);
|
||||
this.err(`image title exceeds max length of ${constants_js_1.LIMITS.MAX_IMAGE_TITLE_LENGTH}`);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
this.logger('log', 'unhandled text for tag:', currentTag, `'${text}'`);
|
||||
this.err(`unhandled text for tag: ${currentTag} '${text}'`);
|
||||
break;
|
||||
}
|
||||
});
|
||||
this.saxStream.on('cdata', (text) => {
|
||||
switch (currentTag) {
|
||||
case types_js_1.TagNames.loc:
|
||||
// Validate URL
|
||||
if (text.length > constants_js_1.LIMITS.MAX_URL_LENGTH) {
|
||||
this.logger('warn', `URL exceeds max length of ${constants_js_1.LIMITS.MAX_URL_LENGTH}: ${text.substring(0, 100)}...`);
|
||||
this.err(`URL exceeds max length of ${constants_js_1.LIMITS.MAX_URL_LENGTH}`);
|
||||
}
|
||||
else if (!constants_js_1.LIMITS.URL_PROTOCOL_REGEX.test(text)) {
|
||||
this.logger('warn', `URL must start with http:// or https://: ${text}`);
|
||||
this.err(`URL must start with http:// or https://: ${text}`);
|
||||
}
|
||||
else {
|
||||
currentItem.url = text;
|
||||
}
|
||||
break;
|
||||
case types_js_1.TagNames['image:loc']:
|
||||
currentImage.url = text;
|
||||
break;
|
||||
case types_js_1.TagNames['video:title']:
|
||||
if (currentVideo.title.length + text.length <=
|
||||
constants_js_1.LIMITS.MAX_VIDEO_TITLE_LENGTH) {
|
||||
currentVideo.title += text;
|
||||
}
|
||||
else {
|
||||
this.logger('warn', `video title exceeds max length of ${constants_js_1.LIMITS.MAX_VIDEO_TITLE_LENGTH}`);
|
||||
this.err(`video title exceeds max length of ${constants_js_1.LIMITS.MAX_VIDEO_TITLE_LENGTH}`);
|
||||
}
|
||||
break;
|
||||
case types_js_1.TagNames['video:description']:
|
||||
if (currentVideo.description.length + text.length <=
|
||||
constants_js_1.LIMITS.MAX_VIDEO_DESCRIPTION_LENGTH) {
|
||||
currentVideo.description += text;
|
||||
}
|
||||
else {
|
||||
this.logger('warn', `video description exceeds max length of ${constants_js_1.LIMITS.MAX_VIDEO_DESCRIPTION_LENGTH}`);
|
||||
this.err(`video description exceeds max length of ${constants_js_1.LIMITS.MAX_VIDEO_DESCRIPTION_LENGTH}`);
|
||||
}
|
||||
break;
|
||||
case types_js_1.TagNames['news:name']:
|
||||
if (!currentItem.news) {
|
||||
currentItem.news = newsTemplate();
|
||||
}
|
||||
if (currentItem.news.publication.name.length + text.length <=
|
||||
constants_js_1.LIMITS.MAX_NEWS_NAME_LENGTH) {
|
||||
currentItem.news.publication.name += text;
|
||||
}
|
||||
else {
|
||||
this.logger('warn', `news name exceeds max length of ${constants_js_1.LIMITS.MAX_NEWS_NAME_LENGTH}`);
|
||||
this.err(`news name exceeds max length of ${constants_js_1.LIMITS.MAX_NEWS_NAME_LENGTH}`);
|
||||
}
|
||||
break;
|
||||
case types_js_1.TagNames['news:title']:
|
||||
if (!currentItem.news) {
|
||||
currentItem.news = newsTemplate();
|
||||
}
|
||||
if (currentItem.news.title.length + text.length <=
|
||||
constants_js_1.LIMITS.MAX_NEWS_TITLE_LENGTH) {
|
||||
currentItem.news.title += text;
|
||||
}
|
||||
else {
|
||||
this.logger('warn', `news title exceeds max length of ${constants_js_1.LIMITS.MAX_NEWS_TITLE_LENGTH}`);
|
||||
this.err(`news title exceeds max length of ${constants_js_1.LIMITS.MAX_NEWS_TITLE_LENGTH}`);
|
||||
}
|
||||
break;
|
||||
case types_js_1.TagNames['image:caption']:
|
||||
if (!currentImage.caption) {
|
||||
currentImage.caption =
|
||||
text.length <= constants_js_1.LIMITS.MAX_IMAGE_CAPTION_LENGTH
|
||||
? text
|
||||
: text.substring(0, constants_js_1.LIMITS.MAX_IMAGE_CAPTION_LENGTH);
|
||||
if (text.length > constants_js_1.LIMITS.MAX_IMAGE_CAPTION_LENGTH) {
|
||||
this.logger('warn', `image caption exceeds max length of ${constants_js_1.LIMITS.MAX_IMAGE_CAPTION_LENGTH}`);
|
||||
this.err(`image caption exceeds max length of ${constants_js_1.LIMITS.MAX_IMAGE_CAPTION_LENGTH}`);
|
||||
}
|
||||
}
|
||||
else if (currentImage.caption.length + text.length <=
|
||||
constants_js_1.LIMITS.MAX_IMAGE_CAPTION_LENGTH) {
|
||||
currentImage.caption += text;
|
||||
}
|
||||
else {
|
||||
this.logger('warn', `image caption exceeds max length of ${constants_js_1.LIMITS.MAX_IMAGE_CAPTION_LENGTH}`);
|
||||
this.err(`image caption exceeds max length of ${constants_js_1.LIMITS.MAX_IMAGE_CAPTION_LENGTH}`);
|
||||
}
|
||||
break;
|
||||
case types_js_1.TagNames['image:title']:
|
||||
if (!currentImage.title) {
|
||||
currentImage.title =
|
||||
text.length <= constants_js_1.LIMITS.MAX_IMAGE_TITLE_LENGTH
|
||||
? text
|
||||
: text.substring(0, constants_js_1.LIMITS.MAX_IMAGE_TITLE_LENGTH);
|
||||
if (text.length > constants_js_1.LIMITS.MAX_IMAGE_TITLE_LENGTH) {
|
||||
this.logger('warn', `image title exceeds max length of ${constants_js_1.LIMITS.MAX_IMAGE_TITLE_LENGTH}`);
|
||||
this.err(`image title exceeds max length of ${constants_js_1.LIMITS.MAX_IMAGE_TITLE_LENGTH}`);
|
||||
}
|
||||
}
|
||||
else if (currentImage.title.length + text.length <=
|
||||
constants_js_1.LIMITS.MAX_IMAGE_TITLE_LENGTH) {
|
||||
currentImage.title += text;
|
||||
}
|
||||
else {
|
||||
this.logger('warn', `image title exceeds max length of ${constants_js_1.LIMITS.MAX_IMAGE_TITLE_LENGTH}`);
|
||||
this.err(`image title exceeds max length of ${constants_js_1.LIMITS.MAX_IMAGE_TITLE_LENGTH}`);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
this.logger('log', 'unhandled cdata for tag:', currentTag);
|
||||
this.err(`unhandled cdata for tag: ${currentTag}`);
|
||||
break;
|
||||
}
|
||||
});
|
||||
this.saxStream.on('attribute', (attr) => {
|
||||
switch (currentTag) {
|
||||
case types_js_1.TagNames['urlset']:
|
||||
case types_js_1.TagNames['xhtml:link']:
|
||||
case types_js_1.TagNames['video:id']:
|
||||
break;
|
||||
case types_js_1.TagNames['video:restriction']:
|
||||
if (attr.name === 'relationship' && (0, validation_js_1.isAllowDeny)(attr.value)) {
|
||||
currentVideo['restriction:relationship'] = attr.value;
|
||||
}
|
||||
else {
|
||||
this.logger('log', 'unhandled attr', currentTag, attr.name);
|
||||
this.err(`unhandled attr: ${currentTag} ${attr.name}`);
|
||||
}
|
||||
break;
|
||||
case types_js_1.TagNames['video:price']:
|
||||
if (attr.name === 'type' && (0, validation_js_1.isPriceType)(attr.value)) {
|
||||
currentVideo['price:type'] = attr.value;
|
||||
}
|
||||
else if (attr.name === 'currency') {
|
||||
currentVideo['price:currency'] = attr.value;
|
||||
}
|
||||
else if (attr.name === 'resolution' && (0, validation_js_1.isResolution)(attr.value)) {
|
||||
currentVideo['price:resolution'] = attr.value;
|
||||
}
|
||||
else {
|
||||
this.logger('log', 'unhandled attr for video:price', attr.name);
|
||||
this.err(`unhandled attr: ${currentTag} ${attr.name}`);
|
||||
}
|
||||
break;
|
||||
case types_js_1.TagNames['video:player_loc']:
|
||||
if (attr.name === 'autoplay') {
|
||||
currentVideo['player_loc:autoplay'] = attr.value;
|
||||
}
|
||||
else if (attr.name === 'allow_embed' && (0, validation_js_1.isValidYesNo)(attr.value)) {
|
||||
currentVideo['player_loc:allow_embed'] = attr.value;
|
||||
}
|
||||
else {
|
||||
this.logger('log', 'unhandled attr for video:player_loc', attr.name);
|
||||
this.err(`unhandled attr: ${currentTag} ${attr.name}`);
|
||||
}
|
||||
break;
|
||||
case types_js_1.TagNames['video:platform']:
|
||||
if (attr.name === 'relationship' && (0, validation_js_1.isAllowDeny)(attr.value)) {
|
||||
currentVideo['platform:relationship'] = attr.value;
|
||||
}
|
||||
else {
|
||||
this.logger('log', 'unhandled attr for video:platform', attr.name, attr.value);
|
||||
this.err(`unhandled attr: ${currentTag} ${attr.name} ${attr.value}`);
|
||||
}
|
||||
break;
|
||||
case types_js_1.TagNames['video:gallery_loc']:
|
||||
if (attr.name === 'title') {
|
||||
currentVideo['gallery_loc:title'] = attr.value;
|
||||
}
|
||||
else {
|
||||
this.logger('log', 'unhandled attr for video:galler_loc', attr.name);
|
||||
this.err(`unhandled attr: ${currentTag} ${attr.name}`);
|
||||
}
|
||||
break;
|
||||
case types_js_1.TagNames['video:uploader']:
|
||||
if (attr.name === 'info') {
|
||||
currentVideo['uploader:info'] = attr.value;
|
||||
}
|
||||
else {
|
||||
this.logger('log', 'unhandled attr for video:uploader', attr.name);
|
||||
this.err(`unhandled attr: ${currentTag} ${attr.name}`);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
this.logger('log', 'unhandled attr', currentTag, attr.name);
|
||||
this.err(`unhandled attr: ${currentTag} ${attr.name}`);
|
||||
}
|
||||
});
|
||||
this.saxStream.on('closetag', (tag) => {
|
||||
switch (tag) {
|
||||
case types_js_1.TagNames.url:
|
||||
this.urlCount++;
|
||||
if (this.urlCount > constants_js_1.LIMITS.MAX_URL_ENTRIES) {
|
||||
this.logger('error', `Sitemap exceeds maximum of ${constants_js_1.LIMITS.MAX_URL_ENTRIES} URLs`);
|
||||
this.err(`Sitemap exceeds maximum of ${constants_js_1.LIMITS.MAX_URL_ENTRIES} URLs`);
|
||||
currentItem = tagTemplate();
|
||||
break;
|
||||
}
|
||||
this.push(currentItem);
|
||||
currentItem = tagTemplate();
|
||||
break;
|
||||
case types_js_1.TagNames['video:video']:
|
||||
if (currentItem.video.length < constants_js_1.LIMITS.MAX_VIDEOS_PER_URL) {
|
||||
currentItem.video.push(currentVideo);
|
||||
}
|
||||
else {
|
||||
this.logger('warn', `URL has too many videos (max ${constants_js_1.LIMITS.MAX_VIDEOS_PER_URL})`);
|
||||
this.err(`URL has too many videos (max ${constants_js_1.LIMITS.MAX_VIDEOS_PER_URL})`);
|
||||
}
|
||||
currentVideo = videoTemplate();
|
||||
break;
|
||||
case types_js_1.TagNames['image:image']:
|
||||
if (currentItem.img.length < constants_js_1.LIMITS.MAX_IMAGES_PER_URL) {
|
||||
currentItem.img.push(currentImage);
|
||||
}
|
||||
else {
|
||||
this.logger('warn', `URL has too many images (max ${constants_js_1.LIMITS.MAX_IMAGES_PER_URL})`);
|
||||
this.err(`URL has too many images (max ${constants_js_1.LIMITS.MAX_IMAGES_PER_URL})`);
|
||||
}
|
||||
currentImage = { ...imageTemplate };
|
||||
break;
|
||||
case types_js_1.TagNames['xhtml:link']:
|
||||
if (!dontpushCurrentLink) {
|
||||
if (currentItem.links.length < constants_js_1.LIMITS.MAX_LINKS_PER_URL) {
|
||||
currentItem.links.push(currentLink);
|
||||
}
|
||||
else {
|
||||
this.logger('warn', `URL has too many links (max ${constants_js_1.LIMITS.MAX_LINKS_PER_URL})`);
|
||||
this.err(`URL has too many links (max ${constants_js_1.LIMITS.MAX_LINKS_PER_URL})`);
|
||||
}
|
||||
}
|
||||
currentLink = { ...linkTemplate };
|
||||
dontpushCurrentLink = false; // Reset flag for next link
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
});
|
||||
}
|
||||
_transform(data, encoding, callback) {
|
||||
try {
|
||||
const cb = () => callback(this.level === types_js_1.ErrorLevel.THROW && this.errors.length > 0
|
||||
? this.errors[0]
|
||||
: null);
|
||||
// correcting the type here can be done without making it a breaking change
|
||||
// TODO fix this
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
if (!this.saxStream.write(data, encoding)) {
|
||||
this.saxStream.once('drain', cb);
|
||||
}
|
||||
else {
|
||||
process.nextTick(cb);
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
callback(error);
|
||||
}
|
||||
}
|
||||
err(msg) {
|
||||
this.errorCount++;
|
||||
if (this.errors.length < constants_js_1.LIMITS.MAX_PARSER_ERRORS) {
|
||||
this.errors.push(new Error(msg));
|
||||
}
|
||||
}
|
||||
}
|
||||
exports.XMLToSitemapItemStream = XMLToSitemapItemStream;
|
||||
/**
|
||||
Read xml and resolve with the configuration that would produce it or reject with
|
||||
an error
|
||||
```
|
||||
const { createReadStream } = require('fs')
|
||||
const { parseSitemap, createSitemap } = require('sitemap')
|
||||
parseSitemap(createReadStream('./example.xml')).then(
|
||||
// produces the same xml
|
||||
// you can, of course, more practically modify it or store it
|
||||
(xmlConfig) => console.log(createSitemap(xmlConfig).toString()),
|
||||
(err) => console.log(err)
|
||||
)
|
||||
```
|
||||
@param {Readable} xml what to parse
|
||||
@return {Promise<SitemapItem[]>} resolves with list of sitemap items that can be fed into a SitemapStream. Rejects with an Error object.
|
||||
*/
|
||||
async function parseSitemap(xml) {
|
||||
const urls = [];
|
||||
return new Promise((resolve, reject) => {
|
||||
xml
|
||||
.pipe(new XMLToSitemapItemStream())
|
||||
.on('data', (smi) => urls.push(smi))
|
||||
.on('end', () => {
|
||||
resolve(urls);
|
||||
})
|
||||
.on('error', (error) => {
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
}
|
||||
const defaultObjectStreamOpts = {
|
||||
lineSeparated: false,
|
||||
};
|
||||
/**
|
||||
* A Transform that converts a stream of objects into a JSON Array or a line
|
||||
* separated stringified JSON
|
||||
* @param [lineSeparated=false] whether to separate entries by a new line or comma
|
||||
*/
|
||||
class ObjectStreamToJSON extends node_stream_1.Transform {
|
||||
lineSeparated;
|
||||
firstWritten;
|
||||
constructor(opts = defaultObjectStreamOpts) {
|
||||
opts.writableObjectMode = true;
|
||||
super(opts);
|
||||
this.lineSeparated = opts.lineSeparated;
|
||||
this.firstWritten = false;
|
||||
}
|
||||
_transform(chunk, encoding, cb) {
|
||||
if (!this.firstWritten) {
|
||||
this.firstWritten = true;
|
||||
if (!this.lineSeparated) {
|
||||
this.push('[');
|
||||
}
|
||||
}
|
||||
else if (this.lineSeparated) {
|
||||
this.push('\n');
|
||||
}
|
||||
else {
|
||||
this.push(',');
|
||||
}
|
||||
if (chunk) {
|
||||
this.push(JSON.stringify(chunk));
|
||||
}
|
||||
cb();
|
||||
}
|
||||
_flush(cb) {
|
||||
if (!this.lineSeparated) {
|
||||
this.push(']');
|
||||
}
|
||||
cb();
|
||||
}
|
||||
}
|
||||
exports.ObjectStreamToJSON = ObjectStreamToJSON;
|
||||
63
node_modules/sitemap/dist/cjs/lib/sitemap-simple.d.ts
generated
vendored
Normal file
63
node_modules/sitemap/dist/cjs/lib/sitemap-simple.d.ts
generated
vendored
Normal file
@@ -0,0 +1,63 @@
|
||||
import { Readable } from 'node:stream';
|
||||
import { SitemapItemLoose } from './types.js';
|
||||
/**
|
||||
* Options for the simpleSitemapAndIndex function
|
||||
*/
|
||||
export interface SimpleSitemapAndIndexOptions {
|
||||
/**
|
||||
* The hostname for all URLs
|
||||
* Must be a valid http:// or https:// URL
|
||||
*/
|
||||
hostname: string;
|
||||
/**
|
||||
* The hostname for the sitemaps if different than hostname
|
||||
* Must be a valid http:// or https:// URL
|
||||
*/
|
||||
sitemapHostname?: string;
|
||||
/**
|
||||
* The urls you want to make a sitemap out of.
|
||||
* Can be an array of items, a file path string, a Readable stream, or an array of strings
|
||||
*/
|
||||
sourceData: SitemapItemLoose[] | string | Readable | string[];
|
||||
/**
|
||||
* Where to write the sitemaps and index
|
||||
* Must be a relative path without path traversal sequences
|
||||
*/
|
||||
destinationDir: string;
|
||||
/**
|
||||
* Where the sitemaps are relative to the hostname. Defaults to root.
|
||||
* Must not contain path traversal sequences
|
||||
*/
|
||||
publicBasePath?: string;
|
||||
/**
|
||||
* How many URLs to write before switching to a new file
|
||||
* Must be between 1 and 50,000 per sitemaps.org spec
|
||||
* @default 50000
|
||||
*/
|
||||
limit?: number;
|
||||
/**
|
||||
* Whether to compress the written files
|
||||
* @default true
|
||||
*/
|
||||
gzip?: boolean;
|
||||
/**
|
||||
* Optional URL to an XSL stylesheet
|
||||
* Must be a valid http:// or https:// URL
|
||||
*/
|
||||
xslUrl?: string;
|
||||
}
|
||||
/**
|
||||
* A simpler interface for creating sitemaps and indexes.
|
||||
* Automatically handles splitting large datasets into multiple sitemap files.
|
||||
*
|
||||
* @param options - Configuration options
|
||||
* @returns A promise that resolves when all sitemaps and the index are written
|
||||
* @throws {InvalidHostnameError} If hostname or sitemapHostname is invalid
|
||||
* @throws {InvalidPathError} If destinationDir contains path traversal
|
||||
* @throws {InvalidPublicBasePathError} If publicBasePath is invalid
|
||||
* @throws {InvalidLimitError} If limit is out of range
|
||||
* @throws {InvalidXSLUrlError} If xslUrl is invalid
|
||||
* @throws {Error} If sourceData type is not supported
|
||||
*/
|
||||
export declare const simpleSitemapAndIndex: ({ hostname, sitemapHostname, sourceData, destinationDir, limit, gzip, publicBasePath, xslUrl, }: SimpleSitemapAndIndexOptions) => Promise<void>;
|
||||
export default simpleSitemapAndIndex;
|
||||
113
node_modules/sitemap/dist/cjs/lib/sitemap-simple.js
generated
vendored
Normal file
113
node_modules/sitemap/dist/cjs/lib/sitemap-simple.js
generated
vendored
Normal file
@@ -0,0 +1,113 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.simpleSitemapAndIndex = void 0;
|
||||
const sitemap_index_stream_js_1 = require("./sitemap-index-stream.js");
|
||||
const sitemap_stream_js_1 = require("./sitemap-stream.js");
|
||||
const utils_js_1 = require("./utils.js");
|
||||
const node_zlib_1 = require("node:zlib");
|
||||
const node_fs_1 = require("node:fs");
|
||||
const node_path_1 = require("node:path");
|
||||
const node_stream_1 = require("node:stream");
|
||||
const promises_1 = require("node:stream/promises");
|
||||
const node_url_1 = require("node:url");
|
||||
const validation_js_1 = require("./validation.js");
|
||||
/**
|
||||
* A simpler interface for creating sitemaps and indexes.
|
||||
* Automatically handles splitting large datasets into multiple sitemap files.
|
||||
*
|
||||
* @param options - Configuration options
|
||||
* @returns A promise that resolves when all sitemaps and the index are written
|
||||
* @throws {InvalidHostnameError} If hostname or sitemapHostname is invalid
|
||||
* @throws {InvalidPathError} If destinationDir contains path traversal
|
||||
* @throws {InvalidPublicBasePathError} If publicBasePath is invalid
|
||||
* @throws {InvalidLimitError} If limit is out of range
|
||||
* @throws {InvalidXSLUrlError} If xslUrl is invalid
|
||||
* @throws {Error} If sourceData type is not supported
|
||||
*/
|
||||
const simpleSitemapAndIndex = async ({ hostname, sitemapHostname = hostname, // if different
|
||||
sourceData, destinationDir, limit = 50000, gzip = true, publicBasePath = './', xslUrl, }) => {
|
||||
// Validate all inputs upfront
|
||||
(0, validation_js_1.validateURL)(hostname, 'hostname');
|
||||
(0, validation_js_1.validateURL)(sitemapHostname, 'sitemapHostname');
|
||||
(0, validation_js_1.validatePath)(destinationDir, 'destinationDir');
|
||||
(0, validation_js_1.validateLimit)(limit);
|
||||
(0, validation_js_1.validatePublicBasePath)(publicBasePath);
|
||||
if (xslUrl) {
|
||||
(0, validation_js_1.validateXSLUrl)(xslUrl);
|
||||
}
|
||||
// Create destination directory with error context
|
||||
try {
|
||||
await node_fs_1.promises.mkdir(destinationDir, { recursive: true });
|
||||
}
|
||||
catch (err) {
|
||||
throw new Error(`Failed to create destination directory "${destinationDir}": ${err instanceof Error ? err.message : String(err)}`);
|
||||
}
|
||||
// Normalize publicBasePath (don't mutate the parameter)
|
||||
const normalizedPublicBasePath = publicBasePath.endsWith('/')
|
||||
? publicBasePath
|
||||
: publicBasePath + '/';
|
||||
const sitemapAndIndexStream = new sitemap_index_stream_js_1.SitemapAndIndexStream({
|
||||
limit,
|
||||
getSitemapStream: (i) => {
|
||||
const sitemapStream = new sitemap_stream_js_1.SitemapStream({
|
||||
hostname,
|
||||
xslUrl,
|
||||
});
|
||||
const path = `./sitemap-${i}.xml`;
|
||||
const writePath = (0, node_path_1.resolve)(destinationDir, path + (gzip ? '.gz' : ''));
|
||||
// Construct public path for the sitemap index
|
||||
const publicPath = (0, node_path_1.normalize)(normalizedPublicBasePath + path);
|
||||
// Construct the URL with proper error handling
|
||||
let sitemapUrl;
|
||||
try {
|
||||
sitemapUrl = new node_url_1.URL(`${publicPath}${gzip ? '.gz' : ''}`, sitemapHostname).toString();
|
||||
}
|
||||
catch (err) {
|
||||
throw new Error(`Failed to construct sitemap URL for index ${i}: ${err instanceof Error ? err.message : String(err)}`);
|
||||
}
|
||||
let writeStream;
|
||||
if (gzip) {
|
||||
writeStream = sitemapStream
|
||||
.pipe((0, node_zlib_1.createGzip)()) // compress the output of the sitemap
|
||||
.pipe((0, node_fs_1.createWriteStream)(writePath)); // write it to sitemap-NUMBER.xml
|
||||
}
|
||||
else {
|
||||
writeStream = sitemapStream.pipe((0, node_fs_1.createWriteStream)(writePath)); // write it to sitemap-NUMBER.xml
|
||||
}
|
||||
return [sitemapUrl, sitemapStream, writeStream];
|
||||
},
|
||||
});
|
||||
// Handle different sourceData types with proper error handling
|
||||
let src;
|
||||
if (typeof sourceData === 'string') {
|
||||
try {
|
||||
src = (0, utils_js_1.lineSeparatedURLsToSitemapOptions)((0, node_fs_1.createReadStream)(sourceData));
|
||||
}
|
||||
catch (err) {
|
||||
throw new Error(`Failed to read sourceData file "${sourceData}": ${err instanceof Error ? err.message : String(err)}`);
|
||||
}
|
||||
}
|
||||
else if (sourceData instanceof node_stream_1.Readable) {
|
||||
src = sourceData;
|
||||
}
|
||||
else if (Array.isArray(sourceData)) {
|
||||
src = node_stream_1.Readable.from(sourceData);
|
||||
}
|
||||
else {
|
||||
throw new Error(`Invalid sourceData type: expected array, string (file path), or Readable stream, got ${typeof sourceData}`);
|
||||
}
|
||||
const writePath = (0, node_path_1.resolve)(destinationDir, `./sitemap-index.xml${gzip ? '.gz' : ''}`);
|
||||
try {
|
||||
if (gzip) {
|
||||
return await (0, promises_1.pipeline)(src, sitemapAndIndexStream, (0, node_zlib_1.createGzip)(), (0, node_fs_1.createWriteStream)(writePath));
|
||||
}
|
||||
else {
|
||||
return await (0, promises_1.pipeline)(src, sitemapAndIndexStream, (0, node_fs_1.createWriteStream)(writePath));
|
||||
}
|
||||
}
|
||||
catch (err) {
|
||||
throw new Error(`Failed to write sitemap files: ${err instanceof Error ? err.message : String(err)}`);
|
||||
}
|
||||
};
|
||||
exports.simpleSitemapAndIndex = simpleSitemapAndIndex;
|
||||
exports.default = exports.simpleSitemapAndIndex;
|
||||
79
node_modules/sitemap/dist/cjs/lib/sitemap-stream.d.ts
generated
vendored
Normal file
79
node_modules/sitemap/dist/cjs/lib/sitemap-stream.d.ts
generated
vendored
Normal file
@@ -0,0 +1,79 @@
|
||||
import { Transform, TransformOptions, TransformCallback, Readable } from 'node:stream';
|
||||
import { SitemapItemLoose, ErrorLevel, ErrorHandler } from './types.js';
|
||||
export declare const stylesheetInclude: (url: string) => string;
|
||||
export interface NSArgs {
|
||||
news: boolean;
|
||||
video: boolean;
|
||||
xhtml: boolean;
|
||||
image: boolean;
|
||||
custom?: string[];
|
||||
}
|
||||
export declare const closetag = "</urlset>";
|
||||
export interface SitemapStreamOptions extends TransformOptions {
|
||||
hostname?: string;
|
||||
level?: ErrorLevel;
|
||||
lastmodDateOnly?: boolean;
|
||||
xmlns?: NSArgs;
|
||||
xslUrl?: string;
|
||||
errorHandler?: ErrorHandler;
|
||||
}
|
||||
/**
|
||||
* A [Transform](https://nodejs.org/api/stream.html#stream_implementing_a_transform_stream)
|
||||
* for turning a
|
||||
* [Readable stream](https://nodejs.org/api/stream.html#stream_readable_streams)
|
||||
* of either [SitemapItemOptions](#sitemap-item-options) or url strings into a
|
||||
* Sitemap. The readable stream it transforms **must** be in object mode.
|
||||
*
|
||||
* @param {SitemapStreamOptions} opts - Configuration options
|
||||
* @param {string} [opts.hostname] - Base URL for relative paths. Must use http:// or https:// protocol
|
||||
* @param {ErrorLevel} [opts.level=ErrorLevel.WARN] - Error handling level (SILENT, WARN, or THROW)
|
||||
* @param {boolean} [opts.lastmodDateOnly=false] - Format lastmod as date only (YYYY-MM-DD)
|
||||
* @param {NSArgs} [opts.xmlns] - Control which XML namespaces to include in output
|
||||
* @param {string} [opts.xslUrl] - URL to XSL stylesheet for sitemap display. Must use http:// or https://
|
||||
* @param {ErrorHandler} [opts.errorHandler] - Custom error handler function
|
||||
*
|
||||
* @throws {InvalidHostnameError} If hostname is provided but invalid (non-http(s), malformed, or >2048 chars)
|
||||
* @throws {InvalidXSLUrlError} If xslUrl is provided but invalid (non-http(s), malformed, >2048 chars, or contains malicious content)
|
||||
* @throws {Error} If xmlns.custom contains invalid namespace declarations
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const stream = new SitemapStream({
|
||||
* hostname: 'https://example.com',
|
||||
* level: ErrorLevel.THROW
|
||||
* });
|
||||
* stream.write({ url: '/page', changefreq: 'daily' });
|
||||
* stream.end();
|
||||
* ```
|
||||
*
|
||||
* @security
|
||||
* - Hostname and xslUrl are validated to prevent URL injection attacks
|
||||
* - Custom namespaces are validated to prevent XML injection
|
||||
* - All URLs are normalized and validated before output
|
||||
* - XML content is properly escaped to prevent injection
|
||||
*/
|
||||
export declare class SitemapStream extends Transform {
|
||||
hostname?: string;
|
||||
level: ErrorLevel;
|
||||
hasHeadOutput: boolean;
|
||||
xmlNS: NSArgs;
|
||||
xslUrl?: string;
|
||||
errorHandler?: ErrorHandler;
|
||||
private smiStream;
|
||||
lastmodDateOnly: boolean;
|
||||
constructor(opts?: SitemapStreamOptions);
|
||||
_transform(item: SitemapItemLoose, encoding: string, callback: TransformCallback): void;
|
||||
_flush(cb: TransformCallback): void;
|
||||
}
|
||||
/**
|
||||
* Converts a readable stream into a promise that resolves with the concatenated data from the stream.
|
||||
*
|
||||
* The function listens for 'data' events from the stream, and when the stream ends, it resolves the promise with the concatenated data. If an error occurs while reading from the stream, the promise is rejected with the error.
|
||||
*
|
||||
* ⚠️ CAUTION: This function should not generally be used in production / when writing to files as it holds a copy of the entire file contents in memory until finished.
|
||||
*
|
||||
* @param {Readable} stream - The readable stream to convert to a promise.
|
||||
* @returns {Promise<Buffer>} A promise that resolves with the concatenated data from the stream as a Buffer, or rejects with an error if one occurred while reading from the stream. If the stream is empty, the promise is rejected with an EmptyStream error.
|
||||
* @throws {EmptyStream} If the stream is empty.
|
||||
*/
|
||||
export declare function streamToPromise(stream: Readable): Promise<Buffer>;
|
||||
218
node_modules/sitemap/dist/cjs/lib/sitemap-stream.js
generated
vendored
Normal file
218
node_modules/sitemap/dist/cjs/lib/sitemap-stream.js
generated
vendored
Normal file
@@ -0,0 +1,218 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.SitemapStream = exports.closetag = exports.stylesheetInclude = void 0;
|
||||
exports.streamToPromise = streamToPromise;
|
||||
const node_stream_1 = require("node:stream");
|
||||
const types_js_1 = require("./types.js");
|
||||
const utils_js_1 = require("./utils.js");
|
||||
const validation_js_1 = require("./validation.js");
|
||||
const sitemap_item_stream_js_1 = require("./sitemap-item-stream.js");
|
||||
const errors_js_1 = require("./errors.js");
|
||||
const constants_js_1 = require("./constants.js");
|
||||
const xmlDec = '<?xml version="1.0" encoding="UTF-8"?>';
|
||||
const stylesheetInclude = (url) => {
|
||||
const safe = url
|
||||
.replace(/&/g, '&')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>');
|
||||
return `<?xml-stylesheet type="text/xsl" href="${safe}"?>`;
|
||||
};
|
||||
exports.stylesheetInclude = stylesheetInclude;
|
||||
const urlsetTagStart = '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"';
|
||||
/**
|
||||
* Validates custom namespace declarations for security
|
||||
* @param custom - Array of custom namespace declarations
|
||||
* @throws {Error} If namespace format is invalid or contains malicious content
|
||||
*/
|
||||
function validateCustomNamespaces(custom) {
|
||||
if (!Array.isArray(custom)) {
|
||||
throw new Error('Custom namespaces must be an array');
|
||||
}
|
||||
// Limit number of custom namespaces to prevent DoS
|
||||
if (custom.length > constants_js_1.LIMITS.MAX_CUSTOM_NAMESPACES) {
|
||||
throw new Error(`Too many custom namespaces: ${custom.length} exceeds limit of ${constants_js_1.LIMITS.MAX_CUSTOM_NAMESPACES}`);
|
||||
}
|
||||
// Basic format validation for xmlns declarations and namespace-qualified attributes
|
||||
// Supports both xmlns:prefix="uri" and prefix:attribute="value" (e.g., xsi:schemaLocation)
|
||||
const xmlAttributePattern = /^[a-zA-Z_][\w.-]*:[a-zA-Z_][\w.-]*="[^"<>]*"$/;
|
||||
for (const ns of custom) {
|
||||
if (typeof ns !== 'string' || ns.length === 0) {
|
||||
throw new Error('Custom namespace must be a non-empty string');
|
||||
}
|
||||
if (ns.length > constants_js_1.LIMITS.MAX_NAMESPACE_LENGTH) {
|
||||
throw new Error(`Custom namespace exceeds maximum length of ${constants_js_1.LIMITS.MAX_NAMESPACE_LENGTH} characters: ${ns.substring(0, 50)}...`);
|
||||
}
|
||||
// Check for potentially malicious content BEFORE format check
|
||||
// (format check will reject < and > but we want specific error message)
|
||||
const lowerNs = ns.toLowerCase();
|
||||
if (lowerNs.includes('<script') ||
|
||||
lowerNs.includes('javascript:') ||
|
||||
lowerNs.includes('data:text/html')) {
|
||||
throw new Error(`Custom namespace contains potentially malicious content: ${ns.substring(0, 50)}`);
|
||||
}
|
||||
// Check format matches xmlns declaration or namespace-qualified attribute
|
||||
if (!xmlAttributePattern.test(ns)) {
|
||||
throw new Error(`Invalid namespace format (must be prefix:name="value", e.g., xmlns:prefix="uri" or xsi:schemaLocation="..."): ${ns.substring(0, 50)}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
const getURLSetNs = ({ news, video, image, xhtml, custom }, xslURL) => {
|
||||
let ns = xmlDec;
|
||||
if (xslURL) {
|
||||
ns += (0, exports.stylesheetInclude)(xslURL);
|
||||
}
|
||||
ns += urlsetTagStart;
|
||||
if (news) {
|
||||
ns += ' xmlns:news="http://www.google.com/schemas/sitemap-news/0.9"';
|
||||
}
|
||||
if (xhtml) {
|
||||
ns += ' xmlns:xhtml="http://www.w3.org/1999/xhtml"';
|
||||
}
|
||||
if (image) {
|
||||
ns += ' xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"';
|
||||
}
|
||||
if (video) {
|
||||
ns += ' xmlns:video="http://www.google.com/schemas/sitemap-video/1.1"';
|
||||
}
|
||||
if (custom) {
|
||||
validateCustomNamespaces(custom);
|
||||
ns += ' ' + custom.join(' ');
|
||||
}
|
||||
return ns + '>';
|
||||
};
|
||||
exports.closetag = '</urlset>';
|
||||
const defaultXMLNS = {
|
||||
news: true,
|
||||
xhtml: true,
|
||||
image: true,
|
||||
video: true,
|
||||
};
|
||||
const defaultStreamOpts = {
|
||||
xmlns: defaultXMLNS,
|
||||
};
|
||||
/**
|
||||
* A [Transform](https://nodejs.org/api/stream.html#stream_implementing_a_transform_stream)
|
||||
* for turning a
|
||||
* [Readable stream](https://nodejs.org/api/stream.html#stream_readable_streams)
|
||||
* of either [SitemapItemOptions](#sitemap-item-options) or url strings into a
|
||||
* Sitemap. The readable stream it transforms **must** be in object mode.
|
||||
*
|
||||
* @param {SitemapStreamOptions} opts - Configuration options
|
||||
* @param {string} [opts.hostname] - Base URL for relative paths. Must use http:// or https:// protocol
|
||||
* @param {ErrorLevel} [opts.level=ErrorLevel.WARN] - Error handling level (SILENT, WARN, or THROW)
|
||||
* @param {boolean} [opts.lastmodDateOnly=false] - Format lastmod as date only (YYYY-MM-DD)
|
||||
* @param {NSArgs} [opts.xmlns] - Control which XML namespaces to include in output
|
||||
* @param {string} [opts.xslUrl] - URL to XSL stylesheet for sitemap display. Must use http:// or https://
|
||||
* @param {ErrorHandler} [opts.errorHandler] - Custom error handler function
|
||||
*
|
||||
* @throws {InvalidHostnameError} If hostname is provided but invalid (non-http(s), malformed, or >2048 chars)
|
||||
* @throws {InvalidXSLUrlError} If xslUrl is provided but invalid (non-http(s), malformed, >2048 chars, or contains malicious content)
|
||||
* @throws {Error} If xmlns.custom contains invalid namespace declarations
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const stream = new SitemapStream({
|
||||
* hostname: 'https://example.com',
|
||||
* level: ErrorLevel.THROW
|
||||
* });
|
||||
* stream.write({ url: '/page', changefreq: 'daily' });
|
||||
* stream.end();
|
||||
* ```
|
||||
*
|
||||
* @security
|
||||
* - Hostname and xslUrl are validated to prevent URL injection attacks
|
||||
* - Custom namespaces are validated to prevent XML injection
|
||||
* - All URLs are normalized and validated before output
|
||||
* - XML content is properly escaped to prevent injection
|
||||
*/
|
||||
class SitemapStream extends node_stream_1.Transform {
|
||||
hostname;
|
||||
level;
|
||||
hasHeadOutput;
|
||||
xmlNS;
|
||||
xslUrl;
|
||||
errorHandler;
|
||||
smiStream;
|
||||
lastmodDateOnly;
|
||||
constructor(opts = defaultStreamOpts) {
|
||||
opts.objectMode = true;
|
||||
super(opts);
|
||||
// Validate hostname if provided
|
||||
if (opts.hostname !== undefined) {
|
||||
(0, validation_js_1.validateURL)(opts.hostname, 'hostname');
|
||||
}
|
||||
// Validate xslUrl if provided
|
||||
if (opts.xslUrl !== undefined) {
|
||||
(0, validation_js_1.validateXSLUrl)(opts.xslUrl);
|
||||
}
|
||||
this.hasHeadOutput = false;
|
||||
this.hostname = opts.hostname;
|
||||
this.level = opts.level || types_js_1.ErrorLevel.WARN;
|
||||
this.errorHandler = opts.errorHandler;
|
||||
this.smiStream = new sitemap_item_stream_js_1.SitemapItemStream({ level: opts.level });
|
||||
this.smiStream.on('data', (data) => this.push(data));
|
||||
this.lastmodDateOnly = opts.lastmodDateOnly || false;
|
||||
this.xmlNS = opts.xmlns || defaultXMLNS;
|
||||
this.xslUrl = opts.xslUrl;
|
||||
}
|
||||
_transform(item, encoding, callback) {
|
||||
if (!this.hasHeadOutput) {
|
||||
this.hasHeadOutput = true;
|
||||
this.push(getURLSetNs(this.xmlNS, this.xslUrl));
|
||||
}
|
||||
if (!this.smiStream.write((0, validation_js_1.validateSMIOptions)((0, utils_js_1.normalizeURL)(item, this.hostname, this.lastmodDateOnly), this.level, this.errorHandler))) {
|
||||
this.smiStream.once('drain', callback);
|
||||
}
|
||||
else {
|
||||
process.nextTick(callback);
|
||||
}
|
||||
}
|
||||
_flush(cb) {
|
||||
if (!this.hasHeadOutput) {
|
||||
cb(new errors_js_1.EmptySitemap());
|
||||
}
|
||||
else {
|
||||
this.push(exports.closetag);
|
||||
cb();
|
||||
}
|
||||
}
|
||||
}
|
||||
exports.SitemapStream = SitemapStream;
|
||||
/**
|
||||
* Converts a readable stream into a promise that resolves with the concatenated data from the stream.
|
||||
*
|
||||
* The function listens for 'data' events from the stream, and when the stream ends, it resolves the promise with the concatenated data. If an error occurs while reading from the stream, the promise is rejected with the error.
|
||||
*
|
||||
* ⚠️ CAUTION: This function should not generally be used in production / when writing to files as it holds a copy of the entire file contents in memory until finished.
|
||||
*
|
||||
* @param {Readable} stream - The readable stream to convert to a promise.
|
||||
* @returns {Promise<Buffer>} A promise that resolves with the concatenated data from the stream as a Buffer, or rejects with an error if one occurred while reading from the stream. If the stream is empty, the promise is rejected with an EmptyStream error.
|
||||
* @throws {EmptyStream} If the stream is empty.
|
||||
*/
|
||||
function streamToPromise(stream) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const drain = [];
|
||||
stream
|
||||
// Error propagation is not automatic
|
||||
// Bubble up errors on the read stream
|
||||
.on('error', reject)
|
||||
.pipe(new node_stream_1.Writable({
|
||||
write(chunk, enc, next) {
|
||||
drain.push(chunk);
|
||||
next();
|
||||
},
|
||||
}))
|
||||
// This bubbles up errors when writing to the internal buffer
|
||||
// This is unlikely to happen, but we have this for completeness
|
||||
.on('error', reject)
|
||||
.on('finish', () => {
|
||||
if (!drain.length) {
|
||||
reject(new errors_js_1.EmptyStream());
|
||||
}
|
||||
else {
|
||||
resolve(Buffer.concat(drain));
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
107
node_modules/sitemap/dist/cjs/lib/sitemap-xml.d.ts
generated
vendored
Normal file
107
node_modules/sitemap/dist/cjs/lib/sitemap-xml.d.ts
generated
vendored
Normal file
@@ -0,0 +1,107 @@
|
||||
/*!
|
||||
* Sitemap
|
||||
* Copyright(c) 2011 Eugene Kalinin
|
||||
* MIT Licensed
|
||||
*/
|
||||
import { TagNames, IndexTagNames, StringObj } from './types.js';
|
||||
/**
|
||||
* Escapes text content for safe inclusion in XML text nodes.
|
||||
*
|
||||
* **Security Model:**
|
||||
* - Escapes `&` → `&` (required to prevent entity interpretation)
|
||||
* - Escapes `<` → `<` (required to prevent tag injection)
|
||||
* - Escapes `>` → `>` (defense-in-depth, prevents CDATA injection)
|
||||
* - Does NOT escape `"` or `'` (not required in text content, only in attributes)
|
||||
* - Removes invalid XML Unicode characters per XML 1.0 spec
|
||||
*
|
||||
* **Why quotes aren't escaped:**
|
||||
* In XML text content (between tags), quotes have no special meaning and don't
|
||||
* need escaping. They only need escaping in attribute values, which is handled
|
||||
* by the `otag()` function.
|
||||
*
|
||||
* @param txt - The text content to escape
|
||||
* @returns XML-safe escaped text with invalid characters removed
|
||||
* @throws {TypeError} If txt is not a string
|
||||
*
|
||||
* @example
|
||||
* text('Hello & World'); // Returns: 'Hello & World'
|
||||
* text('5 < 10'); // Returns: '5 < 10'
|
||||
* text('Hello "World"'); // Returns: 'Hello "World"' (quotes OK in text)
|
||||
*
|
||||
* @see https://www.w3.org/TR/xml/#syntax
|
||||
*/
|
||||
export declare function text(txt: string): string;
|
||||
/**
|
||||
* Generates an opening XML tag with optional attributes.
|
||||
*
|
||||
* **Security Model:**
|
||||
* - Validates attribute names to prevent injection via malformed names
|
||||
* - Escapes all attribute values with proper XML entity encoding
|
||||
* - Escapes `&`, `<`, `>`, `"`, and `'` in attribute values
|
||||
* - Removes invalid XML Unicode characters
|
||||
*
|
||||
* Attribute values use full escaping (including quotes) because they appear
|
||||
* within quoted strings in the XML output: `<tag attr="value">`.
|
||||
*
|
||||
* @param nodeName - The XML element name (e.g., 'url', 'loc', 'video:title')
|
||||
* @param attrs - Optional object mapping attribute names to string values
|
||||
* @param selfClose - If true, generates a self-closing tag (e.g., `<tag/>`)
|
||||
* @returns Opening XML tag string
|
||||
* @throws {InvalidXMLAttributeNameError} If an attribute name contains invalid characters
|
||||
* @throws {TypeError} If nodeName is not a string or attrs values are not strings
|
||||
*
|
||||
* @example
|
||||
* otag('url'); // Returns: '<url>'
|
||||
* otag('video:player_loc', { autoplay: 'ap=1' }); // Returns: '<video:player_loc autoplay="ap=1">'
|
||||
* otag('image:image', {}, true); // Returns: '<image:image/>'
|
||||
*
|
||||
* @see https://www.w3.org/TR/xml/#NT-Attribute
|
||||
*/
|
||||
export declare function otag(nodeName: TagNames | IndexTagNames, attrs?: StringObj, selfClose?: boolean): string;
|
||||
/**
|
||||
* Generates a closing XML tag.
|
||||
*
|
||||
* @param nodeName - The XML element name (e.g., 'url', 'loc', 'video:title')
|
||||
* @returns Closing XML tag string
|
||||
* @throws {TypeError} If nodeName is not a string
|
||||
*
|
||||
* @example
|
||||
* ctag('url'); // Returns: '</url>'
|
||||
* ctag('video:title'); // Returns: '</video:title>'
|
||||
*/
|
||||
export declare function ctag(nodeName: TagNames | IndexTagNames): string;
|
||||
/**
|
||||
* Generates a complete XML element with optional attributes and text content.
|
||||
*
|
||||
* This is a convenience function that combines `otag()`, `text()`, and `ctag()`.
|
||||
* It supports three usage patterns via function overloading:
|
||||
*
|
||||
* 1. Element with text content: `element('loc', 'https://example.com')`
|
||||
* 2. Element with attributes and text: `element('video:player_loc', { autoplay: 'ap=1' }, 'https://...')`
|
||||
* 3. Self-closing element with attributes: `element('image:image', { href: '...' })`
|
||||
*
|
||||
* @param nodeName - The XML element name
|
||||
* @param attrs - Either a string (text content) or object (attributes)
|
||||
* @param innerText - Optional text content when attrs is an object
|
||||
* @returns Complete XML element string
|
||||
* @throws {InvalidXMLAttributeNameError} If an attribute name contains invalid characters
|
||||
* @throws {TypeError} If arguments have invalid types
|
||||
*
|
||||
* @example
|
||||
* // Pattern 1: Simple element with text
|
||||
* element('loc', 'https://example.com')
|
||||
* // Returns: '<loc>https://example.com</loc>'
|
||||
*
|
||||
* @example
|
||||
* // Pattern 2: Element with attributes and text
|
||||
* element('video:player_loc', { autoplay: 'ap=1' }, 'https://example.com/video')
|
||||
* // Returns: '<video:player_loc autoplay="ap=1">https://example.com/video</video:player_loc>'
|
||||
*
|
||||
* @example
|
||||
* // Pattern 3: Self-closing element with attributes
|
||||
* element('xhtml:link', { rel: 'alternate', href: 'https://example.com/fr' })
|
||||
* // Returns: '<xhtml:link rel="alternate" href="https://example.com/fr"/>'
|
||||
*/
|
||||
export declare function element(nodeName: TagNames, attrs: StringObj, innerText: string): string;
|
||||
export declare function element(nodeName: TagNames | IndexTagNames, innerText: string): string;
|
||||
export declare function element(nodeName: TagNames, attrs: StringObj): string;
|
||||
187
node_modules/sitemap/dist/cjs/lib/sitemap-xml.js
generated
vendored
Normal file
187
node_modules/sitemap/dist/cjs/lib/sitemap-xml.js
generated
vendored
Normal file
@@ -0,0 +1,187 @@
|
||||
"use strict";
|
||||
/*!
|
||||
* Sitemap
|
||||
* Copyright(c) 2011 Eugene Kalinin
|
||||
* MIT Licensed
|
||||
*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.text = text;
|
||||
exports.otag = otag;
|
||||
exports.ctag = ctag;
|
||||
exports.element = element;
|
||||
const errors_js_1 = require("./errors.js");
|
||||
/**
|
||||
* Regular expression matching invalid XML 1.0 Unicode characters that must be removed.
|
||||
*
|
||||
* Based on the XML 1.0 specification (https://www.w3.org/TR/xml/#charsets):
|
||||
* - Control characters (U+0000-U+001F except tab, newline, carriage return)
|
||||
* - Delete character (U+007F)
|
||||
* - Invalid control characters (U+0080-U+009F except U+0085)
|
||||
* - Surrogate pairs (U+D800-U+DFFF)
|
||||
* - Non-characters (\p{NChar} - permanently reserved code points)
|
||||
*
|
||||
* Performance note: This regex uses Unicode property escapes and may be slower
|
||||
* on very large strings (100KB+). Consider pre-validation for untrusted input.
|
||||
*
|
||||
* @see https://www.w3.org/TR/xml/#charsets
|
||||
*/
|
||||
const invalidXMLUnicodeRegex =
|
||||
// eslint-disable-next-line no-control-regex
|
||||
/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u0084\u0086-\u009F\uD800-\uDFFF\p{NChar}]/gu;
|
||||
/**
|
||||
* Regular expressions for XML entity escaping
|
||||
*/
|
||||
const amp = /&/g;
|
||||
const lt = /</g;
|
||||
const gt = />/g;
|
||||
const apos = /'/g;
|
||||
const quot = /"/g;
|
||||
/**
|
||||
* Valid XML attribute name pattern. XML names must:
|
||||
* - Start with a letter, underscore, or colon
|
||||
* - Contain only letters, digits, hyphens, underscores, colons, or periods
|
||||
*
|
||||
* This is a simplified validation that accepts the most common attribute names.
|
||||
* Note: In practice, this library only uses namespaced attributes like "video:title"
|
||||
* which are guaranteed to be valid.
|
||||
*
|
||||
* @see https://www.w3.org/TR/xml/#NT-Name
|
||||
*/
|
||||
const validAttributeNameRegex = /^[a-zA-Z_:][\w:.-]*$/;
|
||||
/**
|
||||
* Validates that an attribute name is a valid XML identifier.
|
||||
*
|
||||
* XML attribute names must start with a letter, underscore, or colon,
|
||||
* and contain only alphanumeric characters, hyphens, underscores, colons, or periods.
|
||||
*
|
||||
* @param name - The attribute name to validate
|
||||
* @throws {InvalidXMLAttributeNameError} If the attribute name is invalid
|
||||
*
|
||||
* @example
|
||||
* validateAttributeName('href'); // OK
|
||||
* validateAttributeName('xml:lang'); // OK
|
||||
* validateAttributeName('data-value'); // OK
|
||||
* validateAttributeName('<script>'); // Throws InvalidXMLAttributeNameError
|
||||
*/
|
||||
function validateAttributeName(name) {
|
||||
if (!validAttributeNameRegex.test(name)) {
|
||||
throw new errors_js_1.InvalidXMLAttributeNameError(name);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Escapes text content for safe inclusion in XML text nodes.
|
||||
*
|
||||
* **Security Model:**
|
||||
* - Escapes `&` → `&` (required to prevent entity interpretation)
|
||||
* - Escapes `<` → `<` (required to prevent tag injection)
|
||||
* - Escapes `>` → `>` (defense-in-depth, prevents CDATA injection)
|
||||
* - Does NOT escape `"` or `'` (not required in text content, only in attributes)
|
||||
* - Removes invalid XML Unicode characters per XML 1.0 spec
|
||||
*
|
||||
* **Why quotes aren't escaped:**
|
||||
* In XML text content (between tags), quotes have no special meaning and don't
|
||||
* need escaping. They only need escaping in attribute values, which is handled
|
||||
* by the `otag()` function.
|
||||
*
|
||||
* @param txt - The text content to escape
|
||||
* @returns XML-safe escaped text with invalid characters removed
|
||||
* @throws {TypeError} If txt is not a string
|
||||
*
|
||||
* @example
|
||||
* text('Hello & World'); // Returns: 'Hello & World'
|
||||
* text('5 < 10'); // Returns: '5 < 10'
|
||||
* text('Hello "World"'); // Returns: 'Hello "World"' (quotes OK in text)
|
||||
*
|
||||
* @see https://www.w3.org/TR/xml/#syntax
|
||||
*/
|
||||
function text(txt) {
|
||||
if (typeof txt !== 'string') {
|
||||
throw new TypeError(`text() requires a string, received ${typeof txt}: ${String(txt)}`);
|
||||
}
|
||||
return txt
|
||||
.replace(amp, '&')
|
||||
.replace(lt, '<')
|
||||
.replace(gt, '>')
|
||||
.replace(invalidXMLUnicodeRegex, '');
|
||||
}
|
||||
/**
|
||||
* Generates an opening XML tag with optional attributes.
|
||||
*
|
||||
* **Security Model:**
|
||||
* - Validates attribute names to prevent injection via malformed names
|
||||
* - Escapes all attribute values with proper XML entity encoding
|
||||
* - Escapes `&`, `<`, `>`, `"`, and `'` in attribute values
|
||||
* - Removes invalid XML Unicode characters
|
||||
*
|
||||
* Attribute values use full escaping (including quotes) because they appear
|
||||
* within quoted strings in the XML output: `<tag attr="value">`.
|
||||
*
|
||||
* @param nodeName - The XML element name (e.g., 'url', 'loc', 'video:title')
|
||||
* @param attrs - Optional object mapping attribute names to string values
|
||||
* @param selfClose - If true, generates a self-closing tag (e.g., `<tag/>`)
|
||||
* @returns Opening XML tag string
|
||||
* @throws {InvalidXMLAttributeNameError} If an attribute name contains invalid characters
|
||||
* @throws {TypeError} If nodeName is not a string or attrs values are not strings
|
||||
*
|
||||
* @example
|
||||
* otag('url'); // Returns: '<url>'
|
||||
* otag('video:player_loc', { autoplay: 'ap=1' }); // Returns: '<video:player_loc autoplay="ap=1">'
|
||||
* otag('image:image', {}, true); // Returns: '<image:image/>'
|
||||
*
|
||||
* @see https://www.w3.org/TR/xml/#NT-Attribute
|
||||
*/
|
||||
function otag(nodeName, attrs, selfClose = false) {
|
||||
if (typeof nodeName !== 'string') {
|
||||
throw new TypeError(`otag() nodeName must be a string, received ${typeof nodeName}: ${String(nodeName)}`);
|
||||
}
|
||||
let attrstr = '';
|
||||
for (const k in attrs) {
|
||||
// Validate attribute name to prevent injection
|
||||
validateAttributeName(k);
|
||||
const attrValue = attrs[k];
|
||||
if (typeof attrValue !== 'string') {
|
||||
throw new TypeError(`otag() attribute "${k}" value must be a string, received ${typeof attrValue}: ${String(attrValue)}`);
|
||||
}
|
||||
// Escape attribute value with full entity encoding
|
||||
const val = attrValue
|
||||
.replace(amp, '&')
|
||||
.replace(lt, '<')
|
||||
.replace(gt, '>')
|
||||
.replace(apos, ''')
|
||||
.replace(quot, '"')
|
||||
.replace(invalidXMLUnicodeRegex, '');
|
||||
attrstr += ` ${k}="${val}"`;
|
||||
}
|
||||
return `<${nodeName}${attrstr}${selfClose ? '/' : ''}>`;
|
||||
}
|
||||
/**
|
||||
* Generates a closing XML tag.
|
||||
*
|
||||
* @param nodeName - The XML element name (e.g., 'url', 'loc', 'video:title')
|
||||
* @returns Closing XML tag string
|
||||
* @throws {TypeError} If nodeName is not a string
|
||||
*
|
||||
* @example
|
||||
* ctag('url'); // Returns: '</url>'
|
||||
* ctag('video:title'); // Returns: '</video:title>'
|
||||
*/
|
||||
function ctag(nodeName) {
|
||||
if (typeof nodeName !== 'string') {
|
||||
throw new TypeError(`ctag() nodeName must be a string, received ${typeof nodeName}: ${String(nodeName)}`);
|
||||
}
|
||||
return `</${nodeName}>`;
|
||||
}
|
||||
function element(nodeName, attrs, innerText) {
|
||||
if (typeof attrs === 'string') {
|
||||
// Pattern 1: element(nodeName, textContent)
|
||||
return otag(nodeName) + text(attrs) + ctag(nodeName);
|
||||
}
|
||||
else if (innerText !== undefined) {
|
||||
// Pattern 2: element(nodeName, attrs, textContent)
|
||||
return otag(nodeName, attrs) + text(innerText) + ctag(nodeName);
|
||||
}
|
||||
else {
|
||||
// Pattern 3: element(nodeName, attrs) - self-closing
|
||||
return otag(nodeName, attrs, true);
|
||||
}
|
||||
}
|
||||
400
node_modules/sitemap/dist/cjs/lib/types.d.ts
generated
vendored
Normal file
400
node_modules/sitemap/dist/cjs/lib/types.d.ts
generated
vendored
Normal file
@@ -0,0 +1,400 @@
|
||||
import { URL } from 'node:url';
|
||||
/**
|
||||
* How frequently the page is likely to change. This value provides general
|
||||
* information to search engines and may not correlate exactly to how often they crawl the page. Please note that the
|
||||
* value of this tag is considered a hint and not a command. See
|
||||
* <https://www.sitemaps.org/protocol.html#xmlTagDefinitions> for the acceptable
|
||||
* values
|
||||
*/
|
||||
export declare enum EnumChangefreq {
|
||||
DAILY = "daily",
|
||||
MONTHLY = "monthly",
|
||||
ALWAYS = "always",
|
||||
HOURLY = "hourly",
|
||||
WEEKLY = "weekly",
|
||||
YEARLY = "yearly",
|
||||
NEVER = "never"
|
||||
}
|
||||
export declare enum EnumYesNo {
|
||||
YES = "YES",
|
||||
NO = "NO",
|
||||
Yes = "Yes",
|
||||
No = "No",
|
||||
yes = "yes",
|
||||
no = "no"
|
||||
}
|
||||
export declare enum EnumAllowDeny {
|
||||
ALLOW = "allow",
|
||||
DENY = "deny"
|
||||
}
|
||||
/**
|
||||
* https://support.google.com/webmasters/answer/74288?hl=en&ref_topic=4581190
|
||||
*/
|
||||
export interface NewsItem {
|
||||
access?: 'Registration' | 'Subscription';
|
||||
publication: {
|
||||
name: string;
|
||||
/**
|
||||
* The `<language>` is the language of your publication. Use an ISO 639
|
||||
* language code (2 or 3 letters).
|
||||
*/
|
||||
language: string;
|
||||
};
|
||||
/**
|
||||
* @example 'PressRelease, Blog'
|
||||
*/
|
||||
genres?: string;
|
||||
/**
|
||||
* Article publication date in W3C format, using either the "complete date" (YYYY-MM-DD) format or the "complete date
|
||||
* plus hours, minutes, and seconds"
|
||||
*/
|
||||
publication_date: string;
|
||||
/**
|
||||
* The title of the news article
|
||||
* @example 'Companies A, B in Merger Talks'
|
||||
*/
|
||||
title: string;
|
||||
/**
|
||||
* @example 'business, merger, acquisition'
|
||||
*/
|
||||
keywords?: string;
|
||||
/**
|
||||
* @example 'NASDAQ:A, NASDAQ:B'
|
||||
*/
|
||||
stock_tickers?: string;
|
||||
}
|
||||
/**
|
||||
* Sitemap Image
|
||||
* https://support.google.com/webmasters/answer/178636?hl=en&ref_topic=4581190
|
||||
*/
|
||||
export interface Img {
|
||||
/**
|
||||
* The URL of the image
|
||||
* @example 'https://example.com/image.jpg'
|
||||
*/
|
||||
url: string;
|
||||
/**
|
||||
* The caption of the image
|
||||
* @example 'Thanksgiving dinner'
|
||||
*/
|
||||
caption?: string;
|
||||
/**
|
||||
* The title of the image
|
||||
* @example 'Star Wars EP IV'
|
||||
*/
|
||||
title?: string;
|
||||
/**
|
||||
* The geographic location of the image.
|
||||
* @example 'Limerick, Ireland'
|
||||
*/
|
||||
geoLocation?: string;
|
||||
/**
|
||||
* A URL to the license of the image.
|
||||
* @example 'https://example.com/license.txt'
|
||||
*/
|
||||
license?: string;
|
||||
}
|
||||
interface VideoItemBase {
|
||||
/**
|
||||
* A URL pointing to the video thumbnail image file
|
||||
* @example "https://rtv3-img-roosterteeth.akamaized.net/store/0e841100-289b-4184-ae30-b6a16736960a.jpg/sm/thumb3.jpg"
|
||||
*/
|
||||
thumbnail_loc: string;
|
||||
/**
|
||||
* The title of the video
|
||||
* @example '2018:E6 - GoldenEye: Source'
|
||||
*/
|
||||
title: string;
|
||||
/**
|
||||
* A description of the video. Maximum 2048 characters.
|
||||
* @example 'We play gun game in GoldenEye: Source with a good friend of ours. His name is Gruchy. Dan Gruchy.'
|
||||
*/
|
||||
description: string;
|
||||
/**
|
||||
* A URL pointing to the actual video media file. Should be one of the supported formats. HTML is not a supported
|
||||
* format. Flash is allowed, but no longer supported on most mobile platforms, and so may be indexed less well. Must
|
||||
* not be the same as the `<loc>` URL.
|
||||
* @example "http://streamserver.example.com/video123.mp4"
|
||||
*/
|
||||
content_loc?: string;
|
||||
/**
|
||||
* A URL pointing to a player for a specific video. Usually this is the information in the src element of an `<embed>`
|
||||
* tag. Must not be the same as the `<loc>` URL
|
||||
* @example "https://roosterteeth.com/embed/rouletsplay-2018-goldeneye-source"
|
||||
*/
|
||||
player_loc?: string;
|
||||
/**
|
||||
* A string the search engine can append as a query param to enable automatic
|
||||
* playback. Equivilant to auto play attr on player_loc tag.
|
||||
* @example 'ap=1'
|
||||
*/
|
||||
'player_loc:autoplay'?: string;
|
||||
/**
|
||||
* Whether the search engine can embed the video in search results. Allowed values are yes or no.
|
||||
*/
|
||||
'player_loc:allow_embed'?: EnumYesNo;
|
||||
/**
|
||||
* The length of the video in seconds
|
||||
* @example 600
|
||||
*/
|
||||
duration?: number;
|
||||
/**
|
||||
* The date after which the video will no longer be available.
|
||||
* @example "2012-07-16T19:20:30+08:00"
|
||||
*/
|
||||
expiration_date?: string;
|
||||
/**
|
||||
* The number of times the video has been viewed
|
||||
*/
|
||||
view_count?: number;
|
||||
/**
|
||||
* The date the video was first published, in W3C format.
|
||||
* @example "2012-07-16T19:20:30+08:00"
|
||||
*/
|
||||
publication_date?: string;
|
||||
/**
|
||||
* A short description of the broad category that the video belongs to. This is a string no longer than 256 characters.
|
||||
* @example Baking
|
||||
*/
|
||||
category?: string;
|
||||
/**
|
||||
* Whether to show or hide your video in search results from specific countries.
|
||||
* @example "IE GB US CA"
|
||||
*/
|
||||
restriction?: string;
|
||||
/**
|
||||
* Whether the countries in restriction are allowed or denied
|
||||
* @example 'deny'
|
||||
*/
|
||||
'restriction:relationship'?: EnumAllowDeny;
|
||||
gallery_loc?: string;
|
||||
/**
|
||||
* [Optional] Specifies the URL of a webpage with additional information about this uploader. This URL must be in the same domain as the <loc> tag.
|
||||
* @see https://developers.google.com/search/docs/advanced/sitemaps/video-sitemaps
|
||||
* @example http://www.example.com/users/grillymcgrillerson
|
||||
*/
|
||||
'uploader:info'?: string;
|
||||
'gallery_loc:title'?: string;
|
||||
/**
|
||||
* The price to download or view the video. Omit this tag for free videos.
|
||||
* @example "1.99"
|
||||
*/
|
||||
price?: string;
|
||||
/**
|
||||
* Specifies the resolution of the purchased version. Supported values are hd and sd.
|
||||
* @example "HD"
|
||||
*/
|
||||
'price:resolution'?: Resolution;
|
||||
/**
|
||||
* Specifies the currency in ISO4217 format.
|
||||
* @example "USD"
|
||||
*/
|
||||
'price:currency'?: string;
|
||||
/**
|
||||
* Specifies the purchase option. Supported values are rend and own.
|
||||
* @example "rent"
|
||||
*/
|
||||
'price:type'?: PriceType;
|
||||
/**
|
||||
* The video uploader's name. Only one <video:uploader> is allowed per video. String value, max 255 characters.
|
||||
* @example "GrillyMcGrillerson"
|
||||
*/
|
||||
uploader?: string;
|
||||
/**
|
||||
* Whether to show or hide your video in search results on specified platform types. This is a list of space-delimited
|
||||
* platform types. See <https://support.google.com/webmasters/answer/80471?hl=en&ref_topic=4581190> for more detail
|
||||
* @example "tv"
|
||||
*/
|
||||
platform?: string;
|
||||
id?: string;
|
||||
'platform:relationship'?: EnumAllowDeny;
|
||||
}
|
||||
/**
|
||||
* Video price type - supports both lowercase and uppercase variants
|
||||
* as allowed by the Google Video Sitemap specification
|
||||
* @see https://developers.google.com/search/docs/advanced/sitemaps/video-sitemaps
|
||||
*/
|
||||
export type PriceType = 'rent' | 'purchase' | 'RENT' | 'PURCHASE';
|
||||
/**
|
||||
* Video resolution - supports both lowercase and uppercase variants
|
||||
* as allowed by the Google Video Sitemap specification
|
||||
* @see https://developers.google.com/search/docs/advanced/sitemaps/video-sitemaps
|
||||
*/
|
||||
export type Resolution = 'HD' | 'hd' | 'sd' | 'SD';
|
||||
/**
|
||||
* Sitemap video. <https://support.google.com/webmasters/answer/80471?hl=en&ref_topic=4581190>
|
||||
*/
|
||||
export interface VideoItem extends VideoItemBase {
|
||||
/**
|
||||
* An arbitrary string tag describing the video. Tags are generally very short descriptions of key concepts associated
|
||||
* with a video or piece of content.
|
||||
* @example ['Baking']
|
||||
*/
|
||||
tag: string[];
|
||||
/**
|
||||
* The rating of the video. Supported values are float numbers.
|
||||
* @example 2.5
|
||||
*/
|
||||
rating?: number;
|
||||
family_friendly?: EnumYesNo;
|
||||
/**
|
||||
* Indicates whether a subscription (either paid or free) is required to view
|
||||
* the video. Allowed values are yes or no.
|
||||
*/
|
||||
requires_subscription?: EnumYesNo;
|
||||
/**
|
||||
* Indicates whether the video is a live stream. Supported values are yes or no.
|
||||
*/
|
||||
live?: EnumYesNo;
|
||||
}
|
||||
/**
|
||||
* Sitemap video. <https://support.google.com/webmasters/answer/80471?hl=en&ref_topic=4581190>
|
||||
*/
|
||||
export interface VideoItemLoose extends VideoItemBase {
|
||||
/**
|
||||
* An arbitrary string tag describing the video. Tags are generally very short descriptions of key concepts associated
|
||||
* with a video or piece of content.
|
||||
* @example ['Baking']
|
||||
*/
|
||||
tag?: string | string[];
|
||||
/**
|
||||
* The rating of the video. Supported values are float numbers.
|
||||
* @example 2.5
|
||||
*/
|
||||
rating?: string | number;
|
||||
family_friendly?: EnumYesNo | boolean;
|
||||
requires_subscription?: EnumYesNo | boolean;
|
||||
/**
|
||||
* Indicates whether the video is a live stream. Supported values are yes or no.
|
||||
*/
|
||||
live?: EnumYesNo | boolean;
|
||||
}
|
||||
/**
|
||||
* https://support.google.com/webmasters/answer/189077
|
||||
*/
|
||||
export interface LinkItem {
|
||||
/**
|
||||
* @example 'en'
|
||||
*/
|
||||
lang: string;
|
||||
/**
|
||||
* @example 'en-us'
|
||||
*/
|
||||
hreflang?: string;
|
||||
url: string;
|
||||
}
|
||||
export interface IndexItem {
|
||||
url: string;
|
||||
lastmod?: string;
|
||||
}
|
||||
interface SitemapItemBase {
|
||||
lastmod?: string;
|
||||
changefreq?: EnumChangefreq;
|
||||
fullPrecisionPriority?: boolean;
|
||||
priority?: number;
|
||||
news?: NewsItem;
|
||||
expires?: string;
|
||||
androidLink?: string;
|
||||
ampLink?: string;
|
||||
url: string;
|
||||
}
|
||||
/**
|
||||
* Strict options for individual sitemap entries
|
||||
*/
|
||||
export interface SitemapItem extends SitemapItemBase {
|
||||
img: Img[];
|
||||
video: VideoItem[];
|
||||
links: LinkItem[];
|
||||
}
|
||||
/**
|
||||
* Options for individual sitemap entries prior to normalization
|
||||
*/
|
||||
export interface SitemapItemLoose extends SitemapItemBase {
|
||||
video?: VideoItemLoose | VideoItemLoose[];
|
||||
img?: string | Img | (string | Img)[];
|
||||
links?: LinkItem[];
|
||||
lastmodfile?: string | Buffer | URL;
|
||||
lastmodISO?: string;
|
||||
lastmodrealtime?: boolean;
|
||||
}
|
||||
/**
|
||||
* How to handle errors in passed in urls
|
||||
*/
|
||||
export declare enum ErrorLevel {
|
||||
/**
|
||||
* Validation will be skipped and nothing logged or thrown.
|
||||
*/
|
||||
SILENT = "silent",
|
||||
/**
|
||||
* If an invalid value is encountered, a console.warn will be called with details
|
||||
*/
|
||||
WARN = "warn",
|
||||
/**
|
||||
* An Error will be thrown on encountering invalid data.
|
||||
*/
|
||||
THROW = "throw"
|
||||
}
|
||||
export type ErrorHandler = (error: Error, level: ErrorLevel) => void;
|
||||
export declare enum TagNames {
|
||||
url = "url",
|
||||
loc = "loc",
|
||||
urlset = "urlset",
|
||||
lastmod = "lastmod",
|
||||
changefreq = "changefreq",
|
||||
priority = "priority",
|
||||
'video:thumbnail_loc' = "video:thumbnail_loc",
|
||||
'video:video' = "video:video",
|
||||
'video:title' = "video:title",
|
||||
'video:description' = "video:description",
|
||||
'video:tag' = "video:tag",
|
||||
'video:duration' = "video:duration",
|
||||
'video:player_loc' = "video:player_loc",
|
||||
'video:content_loc' = "video:content_loc",
|
||||
'image:image' = "image:image",
|
||||
'image:loc' = "image:loc",
|
||||
'image:geo_location' = "image:geo_location",
|
||||
'image:license' = "image:license",
|
||||
'image:title' = "image:title",
|
||||
'image:caption' = "image:caption",
|
||||
'video:requires_subscription' = "video:requires_subscription",
|
||||
'video:publication_date' = "video:publication_date",
|
||||
'video:id' = "video:id",
|
||||
'video:restriction' = "video:restriction",
|
||||
'video:family_friendly' = "video:family_friendly",
|
||||
'video:view_count' = "video:view_count",
|
||||
'video:uploader' = "video:uploader",
|
||||
'video:expiration_date' = "video:expiration_date",
|
||||
'video:platform' = "video:platform",
|
||||
'video:price' = "video:price",
|
||||
'video:rating' = "video:rating",
|
||||
'video:category' = "video:category",
|
||||
'video:live' = "video:live",
|
||||
'video:gallery_loc' = "video:gallery_loc",
|
||||
'news:news' = "news:news",
|
||||
'news:publication' = "news:publication",
|
||||
'news:name' = "news:name",
|
||||
'news:access' = "news:access",
|
||||
'news:genres' = "news:genres",
|
||||
'news:publication_date' = "news:publication_date",
|
||||
'news:title' = "news:title",
|
||||
'news:keywords' = "news:keywords",
|
||||
'news:stock_tickers' = "news:stock_tickers",
|
||||
'news:language' = "news:language",
|
||||
'mobile:mobile' = "mobile:mobile",
|
||||
'xhtml:link' = "xhtml:link",
|
||||
'expires' = "expires"
|
||||
}
|
||||
export declare enum IndexTagNames {
|
||||
sitemap = "sitemap",
|
||||
sitemapindex = "sitemapindex",
|
||||
loc = "loc",
|
||||
lastmod = "lastmod"
|
||||
}
|
||||
/**
|
||||
* Generic object with string keys and any values
|
||||
* Used for XML attribute building and other flexible data structures
|
||||
*/
|
||||
export interface StringObj {
|
||||
[index: string]: any;
|
||||
}
|
||||
export {};
|
||||
109
node_modules/sitemap/dist/cjs/lib/types.js
generated
vendored
Normal file
109
node_modules/sitemap/dist/cjs/lib/types.js
generated
vendored
Normal file
@@ -0,0 +1,109 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.IndexTagNames = exports.TagNames = exports.ErrorLevel = exports.EnumAllowDeny = exports.EnumYesNo = exports.EnumChangefreq = void 0;
|
||||
/**
|
||||
* How frequently the page is likely to change. This value provides general
|
||||
* information to search engines and may not correlate exactly to how often they crawl the page. Please note that the
|
||||
* value of this tag is considered a hint and not a command. See
|
||||
* <https://www.sitemaps.org/protocol.html#xmlTagDefinitions> for the acceptable
|
||||
* values
|
||||
*/
|
||||
var EnumChangefreq;
|
||||
(function (EnumChangefreq) {
|
||||
EnumChangefreq["DAILY"] = "daily";
|
||||
EnumChangefreq["MONTHLY"] = "monthly";
|
||||
EnumChangefreq["ALWAYS"] = "always";
|
||||
EnumChangefreq["HOURLY"] = "hourly";
|
||||
EnumChangefreq["WEEKLY"] = "weekly";
|
||||
EnumChangefreq["YEARLY"] = "yearly";
|
||||
EnumChangefreq["NEVER"] = "never";
|
||||
})(EnumChangefreq || (exports.EnumChangefreq = EnumChangefreq = {}));
|
||||
var EnumYesNo;
|
||||
(function (EnumYesNo) {
|
||||
EnumYesNo["YES"] = "YES";
|
||||
EnumYesNo["NO"] = "NO";
|
||||
EnumYesNo["Yes"] = "Yes";
|
||||
EnumYesNo["No"] = "No";
|
||||
EnumYesNo["yes"] = "yes";
|
||||
EnumYesNo["no"] = "no";
|
||||
})(EnumYesNo || (exports.EnumYesNo = EnumYesNo = {}));
|
||||
var EnumAllowDeny;
|
||||
(function (EnumAllowDeny) {
|
||||
EnumAllowDeny["ALLOW"] = "allow";
|
||||
EnumAllowDeny["DENY"] = "deny";
|
||||
})(EnumAllowDeny || (exports.EnumAllowDeny = EnumAllowDeny = {}));
|
||||
/**
|
||||
* How to handle errors in passed in urls
|
||||
*/
|
||||
var ErrorLevel;
|
||||
(function (ErrorLevel) {
|
||||
/**
|
||||
* Validation will be skipped and nothing logged or thrown.
|
||||
*/
|
||||
ErrorLevel["SILENT"] = "silent";
|
||||
/**
|
||||
* If an invalid value is encountered, a console.warn will be called with details
|
||||
*/
|
||||
ErrorLevel["WARN"] = "warn";
|
||||
/**
|
||||
* An Error will be thrown on encountering invalid data.
|
||||
*/
|
||||
ErrorLevel["THROW"] = "throw";
|
||||
})(ErrorLevel || (exports.ErrorLevel = ErrorLevel = {}));
|
||||
var TagNames;
|
||||
(function (TagNames) {
|
||||
TagNames["url"] = "url";
|
||||
TagNames["loc"] = "loc";
|
||||
TagNames["urlset"] = "urlset";
|
||||
TagNames["lastmod"] = "lastmod";
|
||||
TagNames["changefreq"] = "changefreq";
|
||||
TagNames["priority"] = "priority";
|
||||
TagNames["video:thumbnail_loc"] = "video:thumbnail_loc";
|
||||
TagNames["video:video"] = "video:video";
|
||||
TagNames["video:title"] = "video:title";
|
||||
TagNames["video:description"] = "video:description";
|
||||
TagNames["video:tag"] = "video:tag";
|
||||
TagNames["video:duration"] = "video:duration";
|
||||
TagNames["video:player_loc"] = "video:player_loc";
|
||||
TagNames["video:content_loc"] = "video:content_loc";
|
||||
TagNames["image:image"] = "image:image";
|
||||
TagNames["image:loc"] = "image:loc";
|
||||
TagNames["image:geo_location"] = "image:geo_location";
|
||||
TagNames["image:license"] = "image:license";
|
||||
TagNames["image:title"] = "image:title";
|
||||
TagNames["image:caption"] = "image:caption";
|
||||
TagNames["video:requires_subscription"] = "video:requires_subscription";
|
||||
TagNames["video:publication_date"] = "video:publication_date";
|
||||
TagNames["video:id"] = "video:id";
|
||||
TagNames["video:restriction"] = "video:restriction";
|
||||
TagNames["video:family_friendly"] = "video:family_friendly";
|
||||
TagNames["video:view_count"] = "video:view_count";
|
||||
TagNames["video:uploader"] = "video:uploader";
|
||||
TagNames["video:expiration_date"] = "video:expiration_date";
|
||||
TagNames["video:platform"] = "video:platform";
|
||||
TagNames["video:price"] = "video:price";
|
||||
TagNames["video:rating"] = "video:rating";
|
||||
TagNames["video:category"] = "video:category";
|
||||
TagNames["video:live"] = "video:live";
|
||||
TagNames["video:gallery_loc"] = "video:gallery_loc";
|
||||
TagNames["news:news"] = "news:news";
|
||||
TagNames["news:publication"] = "news:publication";
|
||||
TagNames["news:name"] = "news:name";
|
||||
TagNames["news:access"] = "news:access";
|
||||
TagNames["news:genres"] = "news:genres";
|
||||
TagNames["news:publication_date"] = "news:publication_date";
|
||||
TagNames["news:title"] = "news:title";
|
||||
TagNames["news:keywords"] = "news:keywords";
|
||||
TagNames["news:stock_tickers"] = "news:stock_tickers";
|
||||
TagNames["news:language"] = "news:language";
|
||||
TagNames["mobile:mobile"] = "mobile:mobile";
|
||||
TagNames["xhtml:link"] = "xhtml:link";
|
||||
TagNames["expires"] = "expires";
|
||||
})(TagNames || (exports.TagNames = TagNames = {}));
|
||||
var IndexTagNames;
|
||||
(function (IndexTagNames) {
|
||||
IndexTagNames["sitemap"] = "sitemap";
|
||||
IndexTagNames["sitemapindex"] = "sitemapindex";
|
||||
IndexTagNames["loc"] = "loc";
|
||||
IndexTagNames["lastmod"] = "lastmod";
|
||||
})(IndexTagNames || (exports.IndexTagNames = IndexTagNames = {}));
|
||||
48
node_modules/sitemap/dist/cjs/lib/utils.d.ts
generated
vendored
Normal file
48
node_modules/sitemap/dist/cjs/lib/utils.d.ts
generated
vendored
Normal file
@@ -0,0 +1,48 @@
|
||||
import { Readable, ReadableOptions, TransformOptions } from 'node:stream';
|
||||
import { SitemapItem, SitemapItemLoose } from './types.js';
|
||||
export { validateSMIOptions } from './validation.js';
|
||||
/**
|
||||
* Combines multiple streams into one
|
||||
* @param streams the streams to combine
|
||||
*/
|
||||
export declare function mergeStreams(streams: Readable[], options?: TransformOptions): Readable;
|
||||
export interface ReadlineStreamOptions extends ReadableOptions {
|
||||
input: Readable;
|
||||
}
|
||||
/**
|
||||
* Wraps node's ReadLine in a stream
|
||||
*/
|
||||
export declare class ReadlineStream extends Readable {
|
||||
private _source;
|
||||
constructor(options: ReadlineStreamOptions);
|
||||
_read(size: number): void;
|
||||
}
|
||||
/**
|
||||
* Takes a stream likely from fs.createReadStream('./path') and returns a stream
|
||||
* of sitemap items
|
||||
* @param stream a stream of line separated urls.
|
||||
* @param opts.isJSON is the stream line separated JSON. leave undefined to guess
|
||||
*/
|
||||
export declare function lineSeparatedURLsToSitemapOptions(stream: Readable, { isJSON }?: {
|
||||
isJSON?: boolean;
|
||||
}): Readable;
|
||||
/**
|
||||
* Based on lodash's implementation of chunk.
|
||||
*
|
||||
* Copyright JS Foundation and other contributors <https://js.foundation/>
|
||||
*
|
||||
* Based on Underscore.js, copyright Jeremy Ashkenas,
|
||||
* DocumentCloud and Investigative Reporters & Editors <http://underscorejs.org/>
|
||||
*
|
||||
* This software consists of voluntary contributions made by many
|
||||
* individuals. For exact contribution history, see the revision history
|
||||
* available at https://github.com/lodash/lodash
|
||||
*/
|
||||
export declare function chunk(array: any[], size?: number): any[];
|
||||
/**
|
||||
* Converts the passed in sitemap entry into one capable of being consumed by SitemapItem
|
||||
* @param {string | SitemapItemLoose} elem the string or object to be converted
|
||||
* @param {string} hostname
|
||||
* @returns SitemapItemOptions a strict sitemap item option
|
||||
*/
|
||||
export declare function normalizeURL(elem: string | SitemapItemLoose, hostname?: string, lastmodDateOnly?: boolean): SitemapItem;
|
||||
230
node_modules/sitemap/dist/cjs/lib/utils.js
generated
vendored
Normal file
230
node_modules/sitemap/dist/cjs/lib/utils.js
generated
vendored
Normal file
@@ -0,0 +1,230 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ReadlineStream = exports.validateSMIOptions = void 0;
|
||||
exports.mergeStreams = mergeStreams;
|
||||
exports.lineSeparatedURLsToSitemapOptions = lineSeparatedURLsToSitemapOptions;
|
||||
exports.chunk = chunk;
|
||||
exports.normalizeURL = normalizeURL;
|
||||
/*!
|
||||
* Sitemap
|
||||
* Copyright(c) 2011 Eugene Kalinin
|
||||
* MIT Licensed
|
||||
*/
|
||||
const node_fs_1 = require("node:fs");
|
||||
const node_stream_1 = require("node:stream");
|
||||
const node_readline_1 = require("node:readline");
|
||||
const node_url_1 = require("node:url");
|
||||
const types_js_1 = require("./types.js");
|
||||
// Re-export validateSMIOptions from validation.ts for backward compatibility
|
||||
var validation_js_1 = require("./validation.js");
|
||||
Object.defineProperty(exports, "validateSMIOptions", { enumerable: true, get: function () { return validation_js_1.validateSMIOptions; } });
|
||||
/**
|
||||
* Combines multiple streams into one
|
||||
* @param streams the streams to combine
|
||||
*/
|
||||
function mergeStreams(streams, options) {
|
||||
let pass = new node_stream_1.PassThrough(options);
|
||||
let waiting = streams.length;
|
||||
for (const stream of streams) {
|
||||
pass = stream.pipe(pass, { end: false });
|
||||
stream.once('end', () => --waiting === 0 && pass.emit('end'));
|
||||
}
|
||||
return pass;
|
||||
}
|
||||
/**
|
||||
* Wraps node's ReadLine in a stream
|
||||
*/
|
||||
class ReadlineStream extends node_stream_1.Readable {
|
||||
_source;
|
||||
constructor(options) {
|
||||
if (options.autoDestroy === undefined) {
|
||||
options.autoDestroy = true;
|
||||
}
|
||||
options.objectMode = true;
|
||||
super(options);
|
||||
this._source = (0, node_readline_1.createInterface)({
|
||||
input: options.input,
|
||||
terminal: false,
|
||||
crlfDelay: Infinity,
|
||||
});
|
||||
// Every time there's data, push it into the internal buffer.
|
||||
this._source.on('line', (chunk) => {
|
||||
// If push() returns false, then stop reading from source.
|
||||
if (!this.push(chunk))
|
||||
this._source.pause();
|
||||
});
|
||||
// When the source ends, push the EOF-signaling `null` chunk.
|
||||
this._source.on('close', () => {
|
||||
this.push(null);
|
||||
});
|
||||
}
|
||||
// _read() will be called when the stream wants to pull more data in.
|
||||
// The advisory size argument is ignored in this case.
|
||||
_read(size) {
|
||||
this._source.resume();
|
||||
}
|
||||
}
|
||||
exports.ReadlineStream = ReadlineStream;
|
||||
/**
|
||||
* Takes a stream likely from fs.createReadStream('./path') and returns a stream
|
||||
* of sitemap items
|
||||
* @param stream a stream of line separated urls.
|
||||
* @param opts.isJSON is the stream line separated JSON. leave undefined to guess
|
||||
*/
|
||||
function lineSeparatedURLsToSitemapOptions(stream, { isJSON } = {}) {
|
||||
return new ReadlineStream({ input: stream }).pipe(new node_stream_1.Transform({
|
||||
objectMode: true,
|
||||
transform: (line, encoding, cb) => {
|
||||
if (isJSON || (isJSON === undefined && line[0] === '{')) {
|
||||
cb(null, JSON.parse(line));
|
||||
}
|
||||
else {
|
||||
cb(null, line);
|
||||
}
|
||||
},
|
||||
}));
|
||||
}
|
||||
/**
|
||||
* Based on lodash's implementation of chunk.
|
||||
*
|
||||
* Copyright JS Foundation and other contributors <https://js.foundation/>
|
||||
*
|
||||
* Based on Underscore.js, copyright Jeremy Ashkenas,
|
||||
* DocumentCloud and Investigative Reporters & Editors <http://underscorejs.org/>
|
||||
*
|
||||
* This software consists of voluntary contributions made by many
|
||||
* individuals. For exact contribution history, see the revision history
|
||||
* available at https://github.com/lodash/lodash
|
||||
*/
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
function chunk(array, size = 1) {
|
||||
size = Math.max(Math.trunc(size), 0);
|
||||
const length = array ? array.length : 0;
|
||||
if (!length || size < 1) {
|
||||
return [];
|
||||
}
|
||||
const result = Array(Math.ceil(length / size));
|
||||
let index = 0, resIndex = 0;
|
||||
while (index < length) {
|
||||
result[resIndex++] = array.slice(index, (index += size));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
function boolToYESNO(bool) {
|
||||
if (bool === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
if (typeof bool === 'boolean') {
|
||||
return bool ? types_js_1.EnumYesNo.yes : types_js_1.EnumYesNo.no;
|
||||
}
|
||||
return bool;
|
||||
}
|
||||
/**
|
||||
* Converts the passed in sitemap entry into one capable of being consumed by SitemapItem
|
||||
* @param {string | SitemapItemLoose} elem the string or object to be converted
|
||||
* @param {string} hostname
|
||||
* @returns SitemapItemOptions a strict sitemap item option
|
||||
*/
|
||||
function normalizeURL(elem, hostname, lastmodDateOnly = false) {
|
||||
// SitemapItem
|
||||
// create object with url property
|
||||
const smi = {
|
||||
img: [],
|
||||
video: [],
|
||||
links: [],
|
||||
url: '',
|
||||
};
|
||||
if (typeof elem === 'string') {
|
||||
smi.url = new node_url_1.URL(elem, hostname).toString();
|
||||
return smi;
|
||||
}
|
||||
const { url, img, links, video, lastmodfile, lastmodISO, lastmod, ...other } = elem;
|
||||
Object.assign(smi, other);
|
||||
smi.url = new node_url_1.URL(url, hostname).toString();
|
||||
if (img) {
|
||||
// prepend hostname to all image urls
|
||||
smi.img = (Array.isArray(img) ? img : [img]).map((el) => typeof el === 'string'
|
||||
? { url: new node_url_1.URL(el, hostname).toString() }
|
||||
: { ...el, url: new node_url_1.URL(el.url, hostname).toString() });
|
||||
}
|
||||
if (links) {
|
||||
smi.links = links.map((link) => ({
|
||||
...link,
|
||||
url: new node_url_1.URL(link.url, hostname).toString(),
|
||||
}));
|
||||
}
|
||||
if (video) {
|
||||
smi.video = (Array.isArray(video) ? video : [video]).map((video) => {
|
||||
const nv = {
|
||||
...video,
|
||||
family_friendly: boolToYESNO(video.family_friendly),
|
||||
live: boolToYESNO(video.live),
|
||||
requires_subscription: boolToYESNO(video.requires_subscription),
|
||||
tag: [],
|
||||
rating: undefined,
|
||||
};
|
||||
if (video.tag !== undefined) {
|
||||
nv.tag = !Array.isArray(video.tag) ? [video.tag] : video.tag;
|
||||
}
|
||||
if (video.rating !== undefined) {
|
||||
if (typeof video.rating === 'string') {
|
||||
const parsedRating = parseFloat(video.rating);
|
||||
// Validate parsed rating is a valid number
|
||||
if (Number.isNaN(parsedRating)) {
|
||||
throw new Error(`Invalid video rating "${video.rating}" for URL "${elem.url}": must be a valid number`);
|
||||
}
|
||||
nv.rating = parsedRating;
|
||||
}
|
||||
else {
|
||||
nv.rating = video.rating;
|
||||
}
|
||||
}
|
||||
if (typeof video.view_count === 'string') {
|
||||
const parsedViewCount = parseInt(video.view_count, 10);
|
||||
// Validate parsed view count is a valid non-negative integer
|
||||
if (Number.isNaN(parsedViewCount)) {
|
||||
throw new Error(`Invalid video view_count "${video.view_count}" for URL "${elem.url}": must be a valid number`);
|
||||
}
|
||||
if (parsedViewCount < 0) {
|
||||
throw new Error(`Invalid video view_count "${video.view_count}" for URL "${elem.url}": cannot be negative`);
|
||||
}
|
||||
nv.view_count = parsedViewCount;
|
||||
}
|
||||
else if (typeof video.view_count === 'number') {
|
||||
nv.view_count = video.view_count;
|
||||
}
|
||||
return nv;
|
||||
});
|
||||
}
|
||||
// If given a file to use for last modified date
|
||||
if (lastmodfile) {
|
||||
const { mtime } = (0, node_fs_1.statSync)(lastmodfile);
|
||||
const lastmodDate = new Date(mtime);
|
||||
// Validate date is valid
|
||||
if (Number.isNaN(lastmodDate.getTime())) {
|
||||
throw new Error(`Invalid date from file stats for URL "${smi.url}": file modification time is invalid`);
|
||||
}
|
||||
smi.lastmod = lastmodDate.toISOString();
|
||||
// The date of last modification (YYYY-MM-DD)
|
||||
}
|
||||
else if (lastmodISO) {
|
||||
const lastmodDate = new Date(lastmodISO);
|
||||
// Validate date is valid
|
||||
if (Number.isNaN(lastmodDate.getTime())) {
|
||||
throw new Error(`Invalid lastmodISO "${lastmodISO}" for URL "${smi.url}": must be a valid date string`);
|
||||
}
|
||||
smi.lastmod = lastmodDate.toISOString();
|
||||
}
|
||||
else if (lastmod) {
|
||||
const lastmodDate = new Date(lastmod);
|
||||
// Validate date is valid
|
||||
if (Number.isNaN(lastmodDate.getTime())) {
|
||||
throw new Error(`Invalid lastmod "${lastmod}" for URL "${smi.url}": must be a valid date string`);
|
||||
}
|
||||
smi.lastmod = lastmodDate.toISOString();
|
||||
}
|
||||
if (lastmodDateOnly && smi.lastmod) {
|
||||
smi.lastmod = smi.lastmod.slice(0, 10);
|
||||
}
|
||||
return smi;
|
||||
}
|
||||
94
node_modules/sitemap/dist/cjs/lib/validation.d.ts
generated
vendored
Normal file
94
node_modules/sitemap/dist/cjs/lib/validation.d.ts
generated
vendored
Normal file
@@ -0,0 +1,94 @@
|
||||
/*!
|
||||
* Sitemap
|
||||
* Copyright(c) 2011 Eugene Kalinin
|
||||
* MIT Licensed
|
||||
*/
|
||||
import { SitemapItem, ErrorLevel, EnumChangefreq, EnumYesNo, EnumAllowDeny, PriceType, Resolution, ErrorHandler } from './types.js';
|
||||
export declare const validators: {
|
||||
[index: string]: RegExp;
|
||||
};
|
||||
/**
|
||||
* Type guard to check if a string is a valid price type
|
||||
*/
|
||||
export declare function isPriceType(pt: string | PriceType): pt is PriceType;
|
||||
/**
|
||||
* Type guard to check if a string is a valid resolution
|
||||
*/
|
||||
export declare function isResolution(res: string): res is Resolution;
|
||||
export declare function isValidChangeFreq(freq: string): freq is EnumChangefreq;
|
||||
/**
|
||||
* Type guard to check if a string is a valid yes/no value
|
||||
*/
|
||||
export declare function isValidYesNo(yn: string): yn is EnumYesNo;
|
||||
/**
|
||||
* Type guard to check if a string is a valid allow/deny value
|
||||
*/
|
||||
export declare function isAllowDeny(ad: string): ad is EnumAllowDeny;
|
||||
/**
|
||||
* Validates that a URL is well-formed and meets security requirements
|
||||
*
|
||||
* Security: This function enforces that URLs use safe protocols (http/https),
|
||||
* are within reasonable length limits (2048 chars per sitemaps.org spec),
|
||||
* and can be properly parsed. This prevents protocol injection attacks and
|
||||
* ensures compliance with sitemap specifications.
|
||||
*
|
||||
* @param url - The URL to validate
|
||||
* @param paramName - The parameter name for error messages
|
||||
* @throws {InvalidHostnameError} If the URL is invalid
|
||||
*/
|
||||
export declare function validateURL(url: string, paramName: string): void;
|
||||
/**
|
||||
* Validates that a path doesn't contain path traversal sequences
|
||||
*
|
||||
* Security: This function prevents path traversal attacks by detecting
|
||||
* any occurrence of '..' in the path, whether it appears as '../', '/..',
|
||||
* or standalone. This prevents attackers from accessing files outside
|
||||
* the intended directory structure.
|
||||
*
|
||||
* @param path - The path to validate
|
||||
* @param paramName - The parameter name for error messages
|
||||
* @throws {InvalidPathError} If the path contains traversal sequences
|
||||
*/
|
||||
export declare function validatePath(path: string, paramName: string): void;
|
||||
/**
|
||||
* Validates that a public base path is safe for URL construction
|
||||
*
|
||||
* Security: This function prevents path traversal attacks and validates
|
||||
* that the path is safe for use in URL construction within sitemap indexes.
|
||||
* It checks for '..' sequences, null bytes, and invalid whitespace that
|
||||
* could be used to manipulate URL structure or inject malicious content.
|
||||
*
|
||||
* @param publicBasePath - The public base path to validate
|
||||
* @throws {InvalidPublicBasePathError} If the path is invalid
|
||||
*/
|
||||
export declare function validatePublicBasePath(publicBasePath: string): void;
|
||||
/**
|
||||
* Validates that a limit is within acceptable range per sitemaps.org spec
|
||||
*
|
||||
* Security: This function enforces sitemap size limits (1-50,000 URLs per
|
||||
* sitemap) as specified by sitemaps.org. This prevents resource exhaustion
|
||||
* attacks and ensures compliance with search engine requirements.
|
||||
*
|
||||
* @param limit - The limit to validate
|
||||
* @throws {InvalidLimitError} If the limit is out of range
|
||||
*/
|
||||
export declare function validateLimit(limit: number): void;
|
||||
/**
|
||||
* Validates that an XSL URL is safe and well-formed
|
||||
*
|
||||
* Security: This function validates XSL stylesheet URLs to prevent
|
||||
* injection attacks. It blocks dangerous protocols and content patterns
|
||||
* that could be used for XSS or other attacks. The validation uses
|
||||
* case-insensitive matching to catch obfuscated attacks.
|
||||
*
|
||||
* @param xslUrl - The XSL URL to validate
|
||||
* @throws {InvalidXSLUrlError} If the URL is invalid
|
||||
*/
|
||||
export declare function validateXSLUrl(xslUrl: string): void;
|
||||
/**
|
||||
* Verifies all data passed in will comply with sitemap spec.
|
||||
* @param conf Options to validate
|
||||
* @param level logging level
|
||||
* @param errorHandler error handling func
|
||||
*/
|
||||
export declare function validateSMIOptions(conf: SitemapItem, level?: ErrorLevel, errorHandler?: ErrorHandler): SitemapItem;
|
||||
398
node_modules/sitemap/dist/cjs/lib/validation.js
generated
vendored
Normal file
398
node_modules/sitemap/dist/cjs/lib/validation.js
generated
vendored
Normal file
@@ -0,0 +1,398 @@
|
||||
"use strict";
|
||||
/*!
|
||||
* Sitemap
|
||||
* Copyright(c) 2011 Eugene Kalinin
|
||||
* MIT Licensed
|
||||
*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.validators = void 0;
|
||||
exports.isPriceType = isPriceType;
|
||||
exports.isResolution = isResolution;
|
||||
exports.isValidChangeFreq = isValidChangeFreq;
|
||||
exports.isValidYesNo = isValidYesNo;
|
||||
exports.isAllowDeny = isAllowDeny;
|
||||
exports.validateURL = validateURL;
|
||||
exports.validatePath = validatePath;
|
||||
exports.validatePublicBasePath = validatePublicBasePath;
|
||||
exports.validateLimit = validateLimit;
|
||||
exports.validateXSLUrl = validateXSLUrl;
|
||||
exports.validateSMIOptions = validateSMIOptions;
|
||||
const errors_js_1 = require("./errors.js");
|
||||
const types_js_1 = require("./types.js");
|
||||
const constants_js_1 = require("./constants.js");
|
||||
const node_path_1 = require("node:path");
|
||||
/**
|
||||
* Validator regular expressions for various sitemap fields
|
||||
*/
|
||||
const allowDeny = /^(?:allow|deny)$/;
|
||||
exports.validators = {
|
||||
'price:currency': /^[A-Z]{3}$/,
|
||||
'price:type': /^(?:rent|purchase|RENT|PURCHASE)$/,
|
||||
'price:resolution': /^(?:HD|hd|sd|SD)$/,
|
||||
'platform:relationship': allowDeny,
|
||||
'restriction:relationship': allowDeny,
|
||||
restriction: /^([A-Z]{2}( +[A-Z]{2})*)?$/,
|
||||
platform: /^((web|mobile|tv)( (web|mobile|tv))*)?$/,
|
||||
// Language codes: zh-cn, zh-tw, or ISO 639 2-3 letter codes
|
||||
language: /^(zh-cn|zh-tw|[a-z]{2,3})$/,
|
||||
genres: /^(PressRelease|Satire|Blog|OpEd|Opinion|UserGenerated)(, *(PressRelease|Satire|Blog|OpEd|Opinion|UserGenerated))*$/,
|
||||
stock_tickers: /^(\w+:\w+(, *\w+:\w+){0,4})?$/,
|
||||
};
|
||||
/**
|
||||
* Type guard to check if a string is a valid price type
|
||||
*/
|
||||
function isPriceType(pt) {
|
||||
return exports.validators['price:type'].test(pt);
|
||||
}
|
||||
/**
|
||||
* Type guard to check if a string is a valid resolution
|
||||
*/
|
||||
function isResolution(res) {
|
||||
return exports.validators['price:resolution'].test(res);
|
||||
}
|
||||
/**
|
||||
* Type guard to check if a string is a valid changefreq value
|
||||
*/
|
||||
const CHANGEFREQ = Object.values(types_js_1.EnumChangefreq);
|
||||
function isValidChangeFreq(freq) {
|
||||
return CHANGEFREQ.includes(freq);
|
||||
}
|
||||
/**
|
||||
* Type guard to check if a string is a valid yes/no value
|
||||
*/
|
||||
function isValidYesNo(yn) {
|
||||
return /^YES|NO|[Yy]es|[Nn]o$/.test(yn);
|
||||
}
|
||||
/**
|
||||
* Type guard to check if a string is a valid allow/deny value
|
||||
*/
|
||||
function isAllowDeny(ad) {
|
||||
return allowDeny.test(ad);
|
||||
}
|
||||
/**
|
||||
* Validates that a URL is well-formed and meets security requirements
|
||||
*
|
||||
* Security: This function enforces that URLs use safe protocols (http/https),
|
||||
* are within reasonable length limits (2048 chars per sitemaps.org spec),
|
||||
* and can be properly parsed. This prevents protocol injection attacks and
|
||||
* ensures compliance with sitemap specifications.
|
||||
*
|
||||
* @param url - The URL to validate
|
||||
* @param paramName - The parameter name for error messages
|
||||
* @throws {InvalidHostnameError} If the URL is invalid
|
||||
*/
|
||||
function validateURL(url, paramName) {
|
||||
if (!url || typeof url !== 'string') {
|
||||
throw new errors_js_1.InvalidHostnameError(url, `${paramName} must be a non-empty string`);
|
||||
}
|
||||
if (url.length > constants_js_1.LIMITS.MAX_URL_LENGTH) {
|
||||
throw new errors_js_1.InvalidHostnameError(url, `${paramName} exceeds maximum length of ${constants_js_1.LIMITS.MAX_URL_LENGTH} characters`);
|
||||
}
|
||||
if (!constants_js_1.LIMITS.URL_PROTOCOL_REGEX.test(url)) {
|
||||
throw new errors_js_1.InvalidHostnameError(url, `${paramName} must use http:// or https:// protocol`);
|
||||
}
|
||||
// Validate URL can be parsed
|
||||
try {
|
||||
new URL(url);
|
||||
}
|
||||
catch (err) {
|
||||
throw new errors_js_1.InvalidHostnameError(url, `${paramName} is not a valid URL: ${err instanceof Error ? err.message : String(err)}`);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Validates that a path doesn't contain path traversal sequences
|
||||
*
|
||||
* Security: This function prevents path traversal attacks by detecting
|
||||
* any occurrence of '..' in the path, whether it appears as '../', '/..',
|
||||
* or standalone. This prevents attackers from accessing files outside
|
||||
* the intended directory structure.
|
||||
*
|
||||
* @param path - The path to validate
|
||||
* @param paramName - The parameter name for error messages
|
||||
* @throws {InvalidPathError} If the path contains traversal sequences
|
||||
*/
|
||||
function validatePath(path, paramName) {
|
||||
if (!path || typeof path !== 'string') {
|
||||
throw new errors_js_1.InvalidPathError(path, `${paramName} must be a non-empty string`);
|
||||
}
|
||||
// Reject absolute paths to prevent arbitrary write location when caller input
|
||||
// reaches destinationDir (BB-04)
|
||||
if ((0, node_path_1.isAbsolute)(path)) {
|
||||
throw new errors_js_1.InvalidPathError(path, `${paramName} must be a relative path (absolute paths are not allowed)`);
|
||||
}
|
||||
// Check for path traversal sequences - must check before and after normalization
|
||||
// to catch both Windows-style (\) and Unix-style (/) separators
|
||||
if (path.includes('..')) {
|
||||
throw new errors_js_1.InvalidPathError(path, `${paramName} contains path traversal sequence (..)`);
|
||||
}
|
||||
// Additional check after normalization to catch encoded or obfuscated attempts
|
||||
const normalizedPath = path.replace(/\\/g, '/');
|
||||
const pathComponents = normalizedPath.split('/').filter((p) => p.length > 0);
|
||||
if (pathComponents.includes('..')) {
|
||||
throw new errors_js_1.InvalidPathError(path, `${paramName} contains path traversal sequence (..)`);
|
||||
}
|
||||
// Check for null bytes (security issue in some contexts)
|
||||
if (path.includes('\0')) {
|
||||
throw new errors_js_1.InvalidPathError(path, `${paramName} contains null byte character`);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Validates that a public base path is safe for URL construction
|
||||
*
|
||||
* Security: This function prevents path traversal attacks and validates
|
||||
* that the path is safe for use in URL construction within sitemap indexes.
|
||||
* It checks for '..' sequences, null bytes, and invalid whitespace that
|
||||
* could be used to manipulate URL structure or inject malicious content.
|
||||
*
|
||||
* @param publicBasePath - The public base path to validate
|
||||
* @throws {InvalidPublicBasePathError} If the path is invalid
|
||||
*/
|
||||
function validatePublicBasePath(publicBasePath) {
|
||||
if (!publicBasePath || typeof publicBasePath !== 'string') {
|
||||
throw new errors_js_1.InvalidPublicBasePathError(publicBasePath, 'must be a non-empty string');
|
||||
}
|
||||
// Check for path traversal - check the raw string first
|
||||
if (publicBasePath.includes('..')) {
|
||||
throw new errors_js_1.InvalidPublicBasePathError(publicBasePath, 'contains path traversal sequence (..)');
|
||||
}
|
||||
// Additional check for path components after normalization
|
||||
const normalizedPath = publicBasePath.replace(/\\/g, '/');
|
||||
const pathComponents = normalizedPath.split('/').filter((p) => p.length > 0);
|
||||
if (pathComponents.includes('..')) {
|
||||
throw new errors_js_1.InvalidPublicBasePathError(publicBasePath, 'contains path traversal sequence (..)');
|
||||
}
|
||||
// Check for null bytes
|
||||
if (publicBasePath.includes('\0')) {
|
||||
throw new errors_js_1.InvalidPublicBasePathError(publicBasePath, 'contains null byte character');
|
||||
}
|
||||
// Check for potentially dangerous characters that could break URL construction
|
||||
if (/[\r\n\t]/.test(publicBasePath)) {
|
||||
throw new errors_js_1.InvalidPublicBasePathError(publicBasePath, 'contains invalid whitespace characters');
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Validates that a limit is within acceptable range per sitemaps.org spec
|
||||
*
|
||||
* Security: This function enforces sitemap size limits (1-50,000 URLs per
|
||||
* sitemap) as specified by sitemaps.org. This prevents resource exhaustion
|
||||
* attacks and ensures compliance with search engine requirements.
|
||||
*
|
||||
* @param limit - The limit to validate
|
||||
* @throws {InvalidLimitError} If the limit is out of range
|
||||
*/
|
||||
function validateLimit(limit) {
|
||||
if (typeof limit !== 'number' ||
|
||||
!Number.isFinite(limit) ||
|
||||
Number.isNaN(limit)) {
|
||||
throw new errors_js_1.InvalidLimitError(limit);
|
||||
}
|
||||
if (limit < constants_js_1.LIMITS.MIN_SITEMAP_ITEM_LIMIT ||
|
||||
limit > constants_js_1.LIMITS.MAX_SITEMAP_ITEM_LIMIT) {
|
||||
throw new errors_js_1.InvalidLimitError(limit);
|
||||
}
|
||||
// Ensure it's an integer
|
||||
if (!Number.isInteger(limit)) {
|
||||
throw new errors_js_1.InvalidLimitError(limit);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Validates that an XSL URL is safe and well-formed
|
||||
*
|
||||
* Security: This function validates XSL stylesheet URLs to prevent
|
||||
* injection attacks. It blocks dangerous protocols and content patterns
|
||||
* that could be used for XSS or other attacks. The validation uses
|
||||
* case-insensitive matching to catch obfuscated attacks.
|
||||
*
|
||||
* @param xslUrl - The XSL URL to validate
|
||||
* @throws {InvalidXSLUrlError} If the URL is invalid
|
||||
*/
|
||||
function validateXSLUrl(xslUrl) {
|
||||
if (!xslUrl || typeof xslUrl !== 'string') {
|
||||
throw new errors_js_1.InvalidXSLUrlError(xslUrl, 'must be a non-empty string');
|
||||
}
|
||||
if (xslUrl.length > constants_js_1.LIMITS.MAX_URL_LENGTH) {
|
||||
throw new errors_js_1.InvalidXSLUrlError(xslUrl, `exceeds maximum length of ${constants_js_1.LIMITS.MAX_URL_LENGTH} characters`);
|
||||
}
|
||||
if (!constants_js_1.LIMITS.URL_PROTOCOL_REGEX.test(xslUrl)) {
|
||||
throw new errors_js_1.InvalidXSLUrlError(xslUrl, 'must use http:// or https:// protocol');
|
||||
}
|
||||
// Validate URL can be parsed
|
||||
try {
|
||||
new URL(xslUrl);
|
||||
}
|
||||
catch (err) {
|
||||
throw new errors_js_1.InvalidXSLUrlError(xslUrl, `is not a valid URL: ${err instanceof Error ? err.message : String(err)}`);
|
||||
}
|
||||
// Check for potentially dangerous content (case-insensitive)
|
||||
const lowerUrl = xslUrl.toLowerCase();
|
||||
// Block dangerous HTML/script content
|
||||
if (lowerUrl.includes('<script')) {
|
||||
throw new errors_js_1.InvalidXSLUrlError(xslUrl, 'contains potentially malicious content (<script tag)');
|
||||
}
|
||||
// Block dangerous protocols (already checked http/https above, but double-check for encoded variants)
|
||||
const dangerousProtocols = [
|
||||
'javascript:',
|
||||
'data:',
|
||||
'vbscript:',
|
||||
'file:',
|
||||
'about:',
|
||||
];
|
||||
for (const protocol of dangerousProtocols) {
|
||||
if (lowerUrl.includes(protocol)) {
|
||||
throw new errors_js_1.InvalidXSLUrlError(xslUrl, `contains dangerous protocol: ${protocol}`);
|
||||
}
|
||||
}
|
||||
// Check for URL-encoded variants of dangerous patterns
|
||||
// %3C = '<', %3E = '>', %3A = ':'
|
||||
const encodedPatterns = [
|
||||
'%3cscript', // <script
|
||||
'%3c%73%63%72%69%70%74', // <script (fully encoded)
|
||||
'javascript%3a', // javascript:
|
||||
'data%3a', // data:
|
||||
];
|
||||
for (const pattern of encodedPatterns) {
|
||||
if (lowerUrl.includes(pattern)) {
|
||||
throw new errors_js_1.InvalidXSLUrlError(xslUrl, 'contains URL-encoded malicious content');
|
||||
}
|
||||
}
|
||||
// Reject unencoded XML special characters — these must be percent-encoded in
|
||||
// valid URLs and could break out of XML attribute context if left raw.
|
||||
if (xslUrl.includes('"') || xslUrl.includes('<') || xslUrl.includes('>')) {
|
||||
throw new errors_js_1.InvalidXSLUrlError(xslUrl, 'contains unencoded XML special characters (" < >); percent-encode them in the URL');
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Internal helper to validate fields against their validators
|
||||
*/
|
||||
function validate(subject, name, url, level) {
|
||||
Object.keys(subject).forEach((key) => {
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
const val = subject[key];
|
||||
if (exports.validators[key] && !exports.validators[key].test(val)) {
|
||||
if (level === types_js_1.ErrorLevel.THROW) {
|
||||
throw new errors_js_1.InvalidAttrValue(key, val, exports.validators[key]);
|
||||
}
|
||||
else {
|
||||
console.warn(`${url}: ${name} key ${key} has invalid value: ${val}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Internal helper to handle errors based on error level
|
||||
*/
|
||||
function handleError(error, level) {
|
||||
if (level === types_js_1.ErrorLevel.THROW) {
|
||||
throw error;
|
||||
}
|
||||
else if (level === types_js_1.ErrorLevel.WARN) {
|
||||
console.warn(error.name, error.message);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Verifies all data passed in will comply with sitemap spec.
|
||||
* @param conf Options to validate
|
||||
* @param level logging level
|
||||
* @param errorHandler error handling func
|
||||
*/
|
||||
function validateSMIOptions(conf, level = types_js_1.ErrorLevel.WARN, errorHandler = handleError) {
|
||||
if (!conf) {
|
||||
throw new errors_js_1.NoConfigError();
|
||||
}
|
||||
if (level === types_js_1.ErrorLevel.SILENT) {
|
||||
return conf;
|
||||
}
|
||||
const { url, changefreq, priority, news, video } = conf;
|
||||
if (!url) {
|
||||
errorHandler(new errors_js_1.NoURLError(), level);
|
||||
}
|
||||
if (changefreq) {
|
||||
if (!isValidChangeFreq(changefreq)) {
|
||||
errorHandler(new errors_js_1.ChangeFreqInvalidError(url, changefreq), level);
|
||||
}
|
||||
}
|
||||
if (priority) {
|
||||
if (!(priority >= 0.0 && priority <= 1.0)) {
|
||||
errorHandler(new errors_js_1.PriorityInvalidError(url, priority), level);
|
||||
}
|
||||
}
|
||||
if (news) {
|
||||
if (news.access &&
|
||||
news.access !== 'Registration' &&
|
||||
news.access !== 'Subscription') {
|
||||
errorHandler(new errors_js_1.InvalidNewsAccessValue(url, news.access), level);
|
||||
}
|
||||
if (!news.publication ||
|
||||
!news.publication.name ||
|
||||
!news.publication.language ||
|
||||
!news.publication_date ||
|
||||
!news.title) {
|
||||
errorHandler(new errors_js_1.InvalidNewsFormat(url), level);
|
||||
}
|
||||
validate(news, 'news', url, level);
|
||||
validate(news.publication, 'publication', url, level);
|
||||
}
|
||||
if (video) {
|
||||
video.forEach((vid) => {
|
||||
if (vid.duration !== undefined) {
|
||||
if (vid.duration < 0 || vid.duration > 28800) {
|
||||
errorHandler(new errors_js_1.InvalidVideoDuration(url, vid.duration), level);
|
||||
}
|
||||
}
|
||||
if (vid.rating !== undefined && (vid.rating < 0 || vid.rating > 5)) {
|
||||
errorHandler(new errors_js_1.InvalidVideoRating(url, vid.title, vid.rating), level);
|
||||
}
|
||||
if (typeof vid !== 'object' ||
|
||||
!vid.thumbnail_loc ||
|
||||
!vid.title ||
|
||||
!vid.description) {
|
||||
// has to be an object and include required categories https://support.google.com/webmasters/answer/80471?hl=en&ref_topic=4581190
|
||||
errorHandler(new errors_js_1.InvalidVideoFormat(url), level);
|
||||
}
|
||||
if (vid.title.length > 100) {
|
||||
errorHandler(new errors_js_1.InvalidVideoTitle(url, vid.title.length), level);
|
||||
}
|
||||
if (vid.description.length > 2048) {
|
||||
errorHandler(new errors_js_1.InvalidVideoDescription(url, vid.description.length), level);
|
||||
}
|
||||
if (vid.view_count !== undefined && vid.view_count < 0) {
|
||||
errorHandler(new errors_js_1.InvalidVideoViewCount(url, vid.view_count), level);
|
||||
}
|
||||
if (vid.tag.length > 32) {
|
||||
errorHandler(new errors_js_1.InvalidVideoTagCount(url, vid.tag.length), level);
|
||||
}
|
||||
if (vid.category !== undefined && vid.category?.length > 256) {
|
||||
errorHandler(new errors_js_1.InvalidVideoCategory(url, vid.category.length), level);
|
||||
}
|
||||
if (vid.family_friendly !== undefined &&
|
||||
!isValidYesNo(vid.family_friendly)) {
|
||||
errorHandler(new errors_js_1.InvalidVideoFamilyFriendly(url, vid.family_friendly), level);
|
||||
}
|
||||
if (vid.restriction) {
|
||||
if (!exports.validators.restriction.test(vid.restriction)) {
|
||||
errorHandler(new errors_js_1.InvalidVideoRestriction(url, vid.restriction), level);
|
||||
}
|
||||
if (!vid['restriction:relationship'] ||
|
||||
!isAllowDeny(vid['restriction:relationship'])) {
|
||||
errorHandler(new errors_js_1.InvalidVideoRestrictionRelationship(url, vid['restriction:relationship']), level);
|
||||
}
|
||||
}
|
||||
// TODO price element should be unbounded
|
||||
if ((vid.price === '' && vid['price:type'] === undefined) ||
|
||||
(vid['price:type'] !== undefined && !isPriceType(vid['price:type']))) {
|
||||
errorHandler(new errors_js_1.InvalidVideoPriceType(url, vid['price:type'], vid.price), level);
|
||||
}
|
||||
if (vid['price:resolution'] !== undefined &&
|
||||
!isResolution(vid['price:resolution'])) {
|
||||
errorHandler(new errors_js_1.InvalidVideoResolution(url, vid['price:resolution']), level);
|
||||
}
|
||||
if (vid['price:currency'] !== undefined &&
|
||||
!exports.validators['price:currency'].test(vid['price:currency'])) {
|
||||
errorHandler(new errors_js_1.InvalidVideoPriceCurrency(url, vid['price:currency']), level);
|
||||
}
|
||||
validate(vid, 'video', url, level);
|
||||
});
|
||||
}
|
||||
return conf;
|
||||
}
|
||||
12
node_modules/sitemap/dist/cjs/lib/xmllint.d.ts
generated
vendored
Normal file
12
node_modules/sitemap/dist/cjs/lib/xmllint.d.ts
generated
vendored
Normal file
@@ -0,0 +1,12 @@
|
||||
import { Readable } from 'node:stream';
|
||||
/**
|
||||
* Verify the passed in xml is valid. Requires xmllib be installed
|
||||
*
|
||||
* Security: This function always pipes XML content via stdin to prevent
|
||||
* command injection vulnerabilities. Never pass user-controlled strings
|
||||
* as file path arguments to xmllint.
|
||||
*
|
||||
* @param xml what you want validated (string or Readable stream)
|
||||
* @return {Promise<void>} resolves on valid rejects [error stderr]
|
||||
*/
|
||||
export declare function xmlLint(xml: string | Readable): Promise<void>;
|
||||
81
node_modules/sitemap/dist/cjs/lib/xmllint.js
generated
vendored
Normal file
81
node_modules/sitemap/dist/cjs/lib/xmllint.js
generated
vendored
Normal file
@@ -0,0 +1,81 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.xmlLint = xmlLint;
|
||||
const node_fs_1 = require("node:fs");
|
||||
const node_path_1 = require("node:path");
|
||||
const node_child_process_1 = require("node:child_process");
|
||||
const errors_js_1 = require("./errors.js");
|
||||
/**
|
||||
* Finds the `schema` directory with robust path resolution.
|
||||
* Searches from the project root directory using process.cwd().
|
||||
* This works correctly regardless of whether the code is running from:
|
||||
* - Source: lib/xmllint.ts
|
||||
* - ESM build: dist/esm/lib/xmllint.js
|
||||
* - CJS build: dist/cjs/lib/xmllint.js
|
||||
* - Test environment
|
||||
*
|
||||
* @throws {Error} if the schema directory is not found
|
||||
* @returns {string} the path to the schema directory
|
||||
*/
|
||||
function findSchemaDir() {
|
||||
// Search for schema directory from project root
|
||||
// This works in test, build, and source environments
|
||||
const possiblePaths = [
|
||||
(0, node_path_1.resolve)(process.cwd(), 'schema'), // From project root
|
||||
(0, node_path_1.resolve)(process.cwd(), '..', 'schema'), // One level up
|
||||
(0, node_path_1.resolve)(process.cwd(), '..', '..', 'schema'), // Two levels up
|
||||
];
|
||||
for (const schemaPath of possiblePaths) {
|
||||
if ((0, node_fs_1.existsSync)(schemaPath)) {
|
||||
return schemaPath;
|
||||
}
|
||||
}
|
||||
throw new Error(`Schema directory not found. Searched paths: ${possiblePaths.join(', ')}`);
|
||||
}
|
||||
/**
|
||||
* Verify the passed in xml is valid. Requires xmllib be installed
|
||||
*
|
||||
* Security: This function always pipes XML content via stdin to prevent
|
||||
* command injection vulnerabilities. Never pass user-controlled strings
|
||||
* as file path arguments to xmllint.
|
||||
*
|
||||
* @param xml what you want validated (string or Readable stream)
|
||||
* @return {Promise<void>} resolves on valid rejects [error stderr]
|
||||
*/
|
||||
function xmlLint(xml) {
|
||||
const args = [
|
||||
'--schema',
|
||||
(0, node_path_1.resolve)(findSchemaDir(), 'all.xsd'),
|
||||
'--noout',
|
||||
'-', // Always read from stdin for security
|
||||
];
|
||||
return new Promise((resolve, reject) => {
|
||||
(0, node_child_process_1.execFile)('which', ['xmllint'], (error, stdout, stderr) => {
|
||||
if (error) {
|
||||
reject([new errors_js_1.XMLLintUnavailable()]);
|
||||
return;
|
||||
}
|
||||
const xmllint = (0, node_child_process_1.execFile)('xmllint', args, (error, stdout, stderr) => {
|
||||
if (error) {
|
||||
reject([error, stderr]);
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
// Always pipe XML content via stdin for security
|
||||
if (xmllint.stdin) {
|
||||
if (typeof xml === 'string') {
|
||||
// Convert string to stream and pipe to stdin
|
||||
xmllint.stdin.write(xml);
|
||||
xmllint.stdin.end();
|
||||
}
|
||||
else if (xml) {
|
||||
// Pipe readable stream to stdin
|
||||
xml.pipe(xmllint.stdin);
|
||||
}
|
||||
}
|
||||
if (xmllint.stdout) {
|
||||
xmllint.stdout.unpipe();
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
1
node_modules/sitemap/dist/cjs/package.json
generated
vendored
Normal file
1
node_modules/sitemap/dist/cjs/package.json
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
{"type":"commonjs"}
|
||||
2
node_modules/sitemap/dist/esm/cli.d.ts
generated
vendored
Normal file
2
node_modules/sitemap/dist/esm/cli.d.ts
generated
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
#!/usr/bin/env node
|
||||
export {};
|
||||
156
node_modules/sitemap/dist/esm/cli.js
generated
vendored
Executable file
156
node_modules/sitemap/dist/esm/cli.js
generated
vendored
Executable file
@@ -0,0 +1,156 @@
|
||||
#!/usr/bin/env node
|
||||
import { createReadStream, createWriteStream } from 'node:fs';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import { xmlLint } from './lib/xmllint.js';
|
||||
import { XMLLintUnavailable } from './lib/errors.js';
|
||||
import { ObjectStreamToJSON, XMLToSitemapItemStream, } from './lib/sitemap-parser.js';
|
||||
import { lineSeparatedURLsToSitemapOptions } from './lib/utils.js';
|
||||
import { SitemapStream } from './lib/sitemap-stream.js';
|
||||
import { SitemapAndIndexStream } from './lib/sitemap-index-stream.js';
|
||||
import { URL } from 'node:url';
|
||||
import { createGzip } from 'node:zlib';
|
||||
import { ErrorLevel } from './lib/types.js';
|
||||
import arg from 'arg';
|
||||
// Read package.json from the project root (one level up from dist/esm or dist/cjs)
|
||||
// In ESM, __dirname is not defined, so we use import.meta.url
|
||||
// In CJS, __dirname is defined and import.meta is not available
|
||||
let currentDir;
|
||||
try {
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore - __dirname may not be defined in ESM
|
||||
currentDir = __dirname;
|
||||
}
|
||||
catch {
|
||||
// ESM fallback using import.meta.url
|
||||
currentDir = new URL('.', import.meta.url).pathname;
|
||||
}
|
||||
const packageJson = JSON.parse(readFileSync(resolve(currentDir, '../../package.json'), 'utf8'));
|
||||
const pickStreamOrArg = (argv) => {
|
||||
if (!argv._.length) {
|
||||
return process.stdin;
|
||||
}
|
||||
else {
|
||||
return createReadStream(argv._[0], { encoding: 'utf8' });
|
||||
}
|
||||
};
|
||||
const argSpec = {
|
||||
'--help': Boolean,
|
||||
'--version': Boolean,
|
||||
'--validate': Boolean,
|
||||
'--index': Boolean,
|
||||
'--index-base-url': String,
|
||||
'--limit': Number,
|
||||
'--parse': Boolean,
|
||||
'--single-line-json': Boolean,
|
||||
'--prepend': String,
|
||||
'--gzip': Boolean,
|
||||
'-h': '--help',
|
||||
};
|
||||
const argv = arg(argSpec);
|
||||
function getStream() {
|
||||
if (argv._ && argv._.length) {
|
||||
return createReadStream(argv._[0]);
|
||||
}
|
||||
else {
|
||||
console.warn('Reading from stdin. If you are not piping anything in, this command is not doing anything');
|
||||
return process.stdin;
|
||||
}
|
||||
}
|
||||
if (argv['--version']) {
|
||||
console.log(packageJson.version);
|
||||
}
|
||||
else if (argv['--help']) {
|
||||
console.log(`
|
||||
Turn a list of urls into a sitemap xml.
|
||||
Options:
|
||||
--help Print this text
|
||||
--version Print the version
|
||||
--validate Ensure the passed in file is conforms to the sitemap spec
|
||||
--index Create an index and stream that out. Writes out sitemaps along the way.
|
||||
--index-base-url Base url the sitemaps will be hosted eg. https://example.com/sitemaps/
|
||||
--limit=45000 Set a custom limit to the items per sitemap
|
||||
--parse Parse fed xml and spit out config
|
||||
--prepend=sitemap.xml Prepend the streamed in sitemap configs to sitemap.xml
|
||||
--gzip Compress output
|
||||
--single-line-json When used with parse, it spits out each entry as json rather than the whole json.
|
||||
|
||||
# examples
|
||||
|
||||
Generate a sitemap index file as well as sitemaps
|
||||
npx sitemap --gzip --index --index-base-url https://example.com/path/to/sitemaps/ < listofurls.txt > sitemap-index.xml.gz
|
||||
|
||||
Add to a sitemap
|
||||
npx sitemap --prepend sitemap.xml < listofurls.json
|
||||
|
||||
Turn an existing sitemap into configuration understood by the sitemap library
|
||||
npx sitemap --parse sitemap.xml
|
||||
|
||||
Use XMLLib to validate your sitemap (requires xmllib)
|
||||
npx sitemap --validate sitemap.xml
|
||||
`);
|
||||
}
|
||||
else if (argv['--parse']) {
|
||||
let oStream = getStream()
|
||||
.pipe(new XMLToSitemapItemStream({ level: ErrorLevel.THROW }))
|
||||
.pipe(new ObjectStreamToJSON({ lineSeparated: !argv['--single-line-json'] }));
|
||||
if (argv['--gzip']) {
|
||||
oStream = oStream.pipe(createGzip());
|
||||
}
|
||||
oStream.pipe(process.stdout);
|
||||
}
|
||||
else if (argv['--validate']) {
|
||||
xmlLint(getStream())
|
||||
.then(() => console.log('valid'))
|
||||
.catch(([error, stderr]) => {
|
||||
if (error instanceof XMLLintUnavailable) {
|
||||
console.error(error.message);
|
||||
return;
|
||||
}
|
||||
else {
|
||||
console.log(stderr);
|
||||
}
|
||||
});
|
||||
}
|
||||
else if (argv['--index']) {
|
||||
const limit = argv['--limit'];
|
||||
const baseURL = argv['--index-base-url'];
|
||||
if (!baseURL) {
|
||||
throw new Error("You must specify where the sitemaps will be hosted. use --index-base-url 'https://example.com/path'");
|
||||
}
|
||||
const sms = new SitemapAndIndexStream({
|
||||
limit,
|
||||
getSitemapStream: (i) => {
|
||||
const sm = new SitemapStream();
|
||||
const path = `./sitemap-${i}.xml`;
|
||||
let ws;
|
||||
if (argv['--gzip']) {
|
||||
ws = sm.pipe(createGzip()).pipe(createWriteStream(path));
|
||||
}
|
||||
else {
|
||||
ws = sm.pipe(createWriteStream(path));
|
||||
}
|
||||
return [new URL(path, baseURL).toString(), sm, ws];
|
||||
},
|
||||
});
|
||||
let oStream = lineSeparatedURLsToSitemapOptions(pickStreamOrArg(argv)).pipe(sms);
|
||||
if (argv['--gzip']) {
|
||||
oStream = oStream.pipe(createGzip());
|
||||
}
|
||||
oStream.pipe(process.stdout);
|
||||
}
|
||||
else {
|
||||
const sms = new SitemapStream();
|
||||
if (argv['--prepend']) {
|
||||
createReadStream(argv['--prepend'])
|
||||
.pipe(new XMLToSitemapItemStream())
|
||||
.pipe(sms);
|
||||
}
|
||||
const oStream = lineSeparatedURLsToSitemapOptions(pickStreamOrArg(argv)).pipe(sms);
|
||||
if (argv['--gzip']) {
|
||||
oStream.pipe(createGzip()).pipe(process.stdout);
|
||||
}
|
||||
else {
|
||||
oStream.pipe(process.stdout);
|
||||
}
|
||||
}
|
||||
17
node_modules/sitemap/dist/esm/index.d.ts
generated
vendored
Normal file
17
node_modules/sitemap/dist/esm/index.d.ts
generated
vendored
Normal file
@@ -0,0 +1,17 @@
|
||||
/*!
|
||||
* Sitemap
|
||||
* Copyright(c) 2011 Eugene Kalinin
|
||||
* MIT Licensed
|
||||
*/
|
||||
export { SitemapItemStream, SitemapItemStreamOptions, } from './lib/sitemap-item-stream.js';
|
||||
export { IndexTagNames, SitemapIndexStream, SitemapIndexStreamOptions, SitemapAndIndexStream, SitemapAndIndexStreamOptions, } from './lib/sitemap-index-stream.js';
|
||||
export { streamToPromise, SitemapStream, SitemapStreamOptions, } from './lib/sitemap-stream.js';
|
||||
export * from './lib/errors.js';
|
||||
export * from './lib/types.js';
|
||||
export { lineSeparatedURLsToSitemapOptions, mergeStreams, validateSMIOptions, normalizeURL, ReadlineStream, ReadlineStreamOptions, } from './lib/utils.js';
|
||||
export { xmlLint } from './lib/xmllint.js';
|
||||
export { parseSitemap, XMLToSitemapItemStream, XMLToSitemapItemStreamOptions, ObjectStreamToJSON, ObjectStreamToJSONOptions, } from './lib/sitemap-parser.js';
|
||||
export { parseSitemapIndex, XMLToSitemapIndexStream, XMLToSitemapIndexItemStreamOptions, IndexObjectStreamToJSON, IndexObjectStreamToJSONOptions, } from './lib/sitemap-index-parser.js';
|
||||
export { simpleSitemapAndIndex, SimpleSitemapAndIndexOptions, } from './lib/sitemap-simple.js';
|
||||
export { validateURL, validatePath, validateLimit, validatePublicBasePath, validateXSLUrl, validators, isPriceType, isResolution, isValidChangeFreq, isValidYesNo, isAllowDeny, } from './lib/validation.js';
|
||||
export { LIMITS, DEFAULT_SITEMAP_ITEM_LIMIT } from './lib/constants.js';
|
||||
17
node_modules/sitemap/dist/esm/index.js
generated
vendored
Normal file
17
node_modules/sitemap/dist/esm/index.js
generated
vendored
Normal file
@@ -0,0 +1,17 @@
|
||||
/*!
|
||||
* Sitemap
|
||||
* Copyright(c) 2011 Eugene Kalinin
|
||||
* MIT Licensed
|
||||
*/
|
||||
export { SitemapItemStream, } from './lib/sitemap-item-stream.js';
|
||||
export { IndexTagNames, SitemapIndexStream, SitemapAndIndexStream, } from './lib/sitemap-index-stream.js';
|
||||
export { streamToPromise, SitemapStream, } from './lib/sitemap-stream.js';
|
||||
export * from './lib/errors.js';
|
||||
export * from './lib/types.js';
|
||||
export { lineSeparatedURLsToSitemapOptions, mergeStreams, validateSMIOptions, normalizeURL, ReadlineStream, } from './lib/utils.js';
|
||||
export { xmlLint } from './lib/xmllint.js';
|
||||
export { parseSitemap, XMLToSitemapItemStream, ObjectStreamToJSON, } from './lib/sitemap-parser.js';
|
||||
export { parseSitemapIndex, XMLToSitemapIndexStream, IndexObjectStreamToJSON, } from './lib/sitemap-index-parser.js';
|
||||
export { simpleSitemapAndIndex, } from './lib/sitemap-simple.js';
|
||||
export { validateURL, validatePath, validateLimit, validatePublicBasePath, validateXSLUrl, validators, isPriceType, isResolution, isValidChangeFreq, isValidYesNo, isAllowDeny, } from './lib/validation.js';
|
||||
export { LIMITS, DEFAULT_SITEMAP_ITEM_LIMIT } from './lib/constants.js';
|
||||
49
node_modules/sitemap/dist/esm/lib/constants.d.ts
generated
vendored
Normal file
49
node_modules/sitemap/dist/esm/lib/constants.d.ts
generated
vendored
Normal file
@@ -0,0 +1,49 @@
|
||||
/*!
|
||||
* Sitemap
|
||||
* Copyright(c) 2011 Eugene Kalinin
|
||||
* MIT Licensed
|
||||
*/
|
||||
/**
|
||||
* Shared constants used across the sitemap library
|
||||
* This file serves as a single source of truth for limits and validation patterns
|
||||
*/
|
||||
/**
|
||||
* Security limits for sitemap generation and parsing
|
||||
*
|
||||
* These limits are based on:
|
||||
* - sitemaps.org protocol specification
|
||||
* - Security best practices to prevent DoS and injection attacks
|
||||
* - Google's sitemap extension specifications
|
||||
*
|
||||
* @see https://www.sitemaps.org/protocol.html
|
||||
* @see https://developers.google.com/search/docs/advanced/sitemaps/build-sitemap
|
||||
*/
|
||||
export declare const LIMITS: {
|
||||
readonly MAX_URL_LENGTH: 2048;
|
||||
readonly URL_PROTOCOL_REGEX: RegExp;
|
||||
readonly MIN_SITEMAP_ITEM_LIMIT: 1;
|
||||
readonly MAX_SITEMAP_ITEM_LIMIT: 50000;
|
||||
readonly MAX_VIDEO_TITLE_LENGTH: 100;
|
||||
readonly MAX_VIDEO_DESCRIPTION_LENGTH: 2048;
|
||||
readonly MAX_VIDEO_CATEGORY_LENGTH: 256;
|
||||
readonly MAX_TAGS_PER_VIDEO: 32;
|
||||
readonly MAX_NEWS_TITLE_LENGTH: 200;
|
||||
readonly MAX_NEWS_NAME_LENGTH: 256;
|
||||
readonly MAX_IMAGE_CAPTION_LENGTH: 512;
|
||||
readonly MAX_IMAGE_TITLE_LENGTH: 512;
|
||||
readonly MAX_IMAGES_PER_URL: 1000;
|
||||
readonly MAX_VIDEOS_PER_URL: 100;
|
||||
readonly MAX_LINKS_PER_URL: 100;
|
||||
readonly MAX_URL_ENTRIES: 50000;
|
||||
readonly ISO_DATE_REGEX: RegExp;
|
||||
readonly MAX_CUSTOM_NAMESPACES: 20;
|
||||
readonly MAX_NAMESPACE_LENGTH: 512;
|
||||
readonly MAX_PARSER_ERRORS: 100;
|
||||
};
|
||||
/**
|
||||
* Default maximum number of items in each sitemap XML file
|
||||
* Set below the max to leave room for URLs added during processing
|
||||
*
|
||||
* @see https://www.sitemaps.org/protocol.html#index
|
||||
*/
|
||||
export declare const DEFAULT_SITEMAP_ITEM_LIMIT = 45000;
|
||||
60
node_modules/sitemap/dist/esm/lib/constants.js
generated
vendored
Normal file
60
node_modules/sitemap/dist/esm/lib/constants.js
generated
vendored
Normal file
@@ -0,0 +1,60 @@
|
||||
/*!
|
||||
* Sitemap
|
||||
* Copyright(c) 2011 Eugene Kalinin
|
||||
* MIT Licensed
|
||||
*/
|
||||
/**
|
||||
* Shared constants used across the sitemap library
|
||||
* This file serves as a single source of truth for limits and validation patterns
|
||||
*/
|
||||
/**
|
||||
* Security limits for sitemap generation and parsing
|
||||
*
|
||||
* These limits are based on:
|
||||
* - sitemaps.org protocol specification
|
||||
* - Security best practices to prevent DoS and injection attacks
|
||||
* - Google's sitemap extension specifications
|
||||
*
|
||||
* @see https://www.sitemaps.org/protocol.html
|
||||
* @see https://developers.google.com/search/docs/advanced/sitemaps/build-sitemap
|
||||
*/
|
||||
export const LIMITS = {
|
||||
// URL constraints per sitemaps.org spec
|
||||
MAX_URL_LENGTH: 2048,
|
||||
URL_PROTOCOL_REGEX: /^https?:\/\//i,
|
||||
// Sitemap size limits per sitemaps.org spec
|
||||
MIN_SITEMAP_ITEM_LIMIT: 1,
|
||||
MAX_SITEMAP_ITEM_LIMIT: 50000,
|
||||
// Video field length constraints per Google spec
|
||||
MAX_VIDEO_TITLE_LENGTH: 100,
|
||||
MAX_VIDEO_DESCRIPTION_LENGTH: 2048,
|
||||
MAX_VIDEO_CATEGORY_LENGTH: 256,
|
||||
MAX_TAGS_PER_VIDEO: 32,
|
||||
// News field length constraints per Google spec
|
||||
MAX_NEWS_TITLE_LENGTH: 200,
|
||||
MAX_NEWS_NAME_LENGTH: 256,
|
||||
// Image field length constraints per Google spec
|
||||
MAX_IMAGE_CAPTION_LENGTH: 512,
|
||||
MAX_IMAGE_TITLE_LENGTH: 512,
|
||||
// Limits on number of items per URL entry
|
||||
MAX_IMAGES_PER_URL: 1000,
|
||||
MAX_VIDEOS_PER_URL: 100,
|
||||
MAX_LINKS_PER_URL: 100,
|
||||
// Total entries in a sitemap
|
||||
MAX_URL_ENTRIES: 50000,
|
||||
// Date validation - ISO 8601 / W3C format
|
||||
ISO_DATE_REGEX: /^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d{3})?([+-]\d{2}:\d{2}|Z)?)?$/,
|
||||
// Custom namespace limits to prevent DoS
|
||||
MAX_CUSTOM_NAMESPACES: 20,
|
||||
MAX_NAMESPACE_LENGTH: 512,
|
||||
// Cap on stored parser errors to prevent memory DoS (BB-03)
|
||||
// Errors beyond this limit are counted in errorCount but not retained as objects
|
||||
MAX_PARSER_ERRORS: 100,
|
||||
};
|
||||
/**
|
||||
* Default maximum number of items in each sitemap XML file
|
||||
* Set below the max to leave room for URLs added during processing
|
||||
*
|
||||
* @see https://www.sitemaps.org/protocol.html#index
|
||||
*/
|
||||
export const DEFAULT_SITEMAP_ITEM_LIMIT = 45000;
|
||||
116
node_modules/sitemap/dist/esm/lib/errors.d.ts
generated
vendored
Normal file
116
node_modules/sitemap/dist/esm/lib/errors.d.ts
generated
vendored
Normal file
@@ -0,0 +1,116 @@
|
||||
/*!
|
||||
* Sitemap
|
||||
* Copyright(c) 2011 Eugene Kalinin
|
||||
* MIT Licensed
|
||||
*/
|
||||
/**
|
||||
* URL in SitemapItem does not exist
|
||||
*/
|
||||
export declare class NoURLError extends Error {
|
||||
constructor(message?: string);
|
||||
}
|
||||
/**
|
||||
* Config was not passed to SitemapItem constructor
|
||||
*/
|
||||
export declare class NoConfigError extends Error {
|
||||
constructor(message?: string);
|
||||
}
|
||||
/**
|
||||
* changefreq property in sitemap is invalid
|
||||
*/
|
||||
export declare class ChangeFreqInvalidError extends Error {
|
||||
constructor(url: string, changefreq: any);
|
||||
}
|
||||
/**
|
||||
* priority property in sitemap is invalid
|
||||
*/
|
||||
export declare class PriorityInvalidError extends Error {
|
||||
constructor(url: string, priority: any);
|
||||
}
|
||||
/**
|
||||
* SitemapIndex target Folder does not exists
|
||||
*/
|
||||
export declare class UndefinedTargetFolder extends Error {
|
||||
constructor(message?: string);
|
||||
}
|
||||
export declare class InvalidVideoFormat extends Error {
|
||||
constructor(url: string);
|
||||
}
|
||||
export declare class InvalidVideoDuration extends Error {
|
||||
constructor(url: string, duration: any);
|
||||
}
|
||||
export declare class InvalidVideoDescription extends Error {
|
||||
constructor(url: string, length: number);
|
||||
}
|
||||
export declare class InvalidVideoRating extends Error {
|
||||
constructor(url: string, title: any, rating: any);
|
||||
}
|
||||
export declare class InvalidAttrValue extends Error {
|
||||
constructor(key: string, val: any, validator: RegExp);
|
||||
}
|
||||
export declare class InvalidAttr extends Error {
|
||||
constructor(key: string);
|
||||
}
|
||||
export declare class InvalidNewsFormat extends Error {
|
||||
constructor(url: string);
|
||||
}
|
||||
export declare class InvalidNewsAccessValue extends Error {
|
||||
constructor(url: string, access: any);
|
||||
}
|
||||
export declare class XMLLintUnavailable extends Error {
|
||||
constructor(message?: string);
|
||||
}
|
||||
export declare class InvalidVideoTitle extends Error {
|
||||
constructor(url: string, length: number);
|
||||
}
|
||||
export declare class InvalidVideoViewCount extends Error {
|
||||
constructor(url: string, count: number);
|
||||
}
|
||||
export declare class InvalidVideoTagCount extends Error {
|
||||
constructor(url: string, count: number);
|
||||
}
|
||||
export declare class InvalidVideoCategory extends Error {
|
||||
constructor(url: string, count: number);
|
||||
}
|
||||
export declare class InvalidVideoFamilyFriendly extends Error {
|
||||
constructor(url: string, fam: string);
|
||||
}
|
||||
export declare class InvalidVideoRestriction extends Error {
|
||||
constructor(url: string, code: string);
|
||||
}
|
||||
export declare class InvalidVideoRestrictionRelationship extends Error {
|
||||
constructor(url: string, val?: string);
|
||||
}
|
||||
export declare class InvalidVideoPriceType extends Error {
|
||||
constructor(url: string, priceType?: string, price?: string);
|
||||
}
|
||||
export declare class InvalidVideoResolution extends Error {
|
||||
constructor(url: string, resolution: string);
|
||||
}
|
||||
export declare class InvalidVideoPriceCurrency extends Error {
|
||||
constructor(url: string, currency: string);
|
||||
}
|
||||
export declare class EmptyStream extends Error {
|
||||
constructor();
|
||||
}
|
||||
export declare class EmptySitemap extends Error {
|
||||
constructor();
|
||||
}
|
||||
export declare class InvalidPathError extends Error {
|
||||
constructor(path: string, reason: string);
|
||||
}
|
||||
export declare class InvalidHostnameError extends Error {
|
||||
constructor(hostname: string, reason: string);
|
||||
}
|
||||
export declare class InvalidLimitError extends Error {
|
||||
constructor(limit: any);
|
||||
}
|
||||
export declare class InvalidPublicBasePathError extends Error {
|
||||
constructor(publicBasePath: string, reason: string);
|
||||
}
|
||||
export declare class InvalidXSLUrlError extends Error {
|
||||
constructor(xslUrl: string, reason: string);
|
||||
}
|
||||
export declare class InvalidXMLAttributeNameError extends Error {
|
||||
constructor(attributeName: string);
|
||||
}
|
||||
256
node_modules/sitemap/dist/esm/lib/errors.js
generated
vendored
Normal file
256
node_modules/sitemap/dist/esm/lib/errors.js
generated
vendored
Normal file
@@ -0,0 +1,256 @@
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
/*!
|
||||
* Sitemap
|
||||
* Copyright(c) 2011 Eugene Kalinin
|
||||
* MIT Licensed
|
||||
*/
|
||||
/**
|
||||
* URL in SitemapItem does not exist
|
||||
*/
|
||||
export class NoURLError extends Error {
|
||||
constructor(message) {
|
||||
super(message || 'URL is required');
|
||||
this.name = 'NoURLError';
|
||||
Error.captureStackTrace(this, NoURLError);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Config was not passed to SitemapItem constructor
|
||||
*/
|
||||
export class NoConfigError extends Error {
|
||||
constructor(message) {
|
||||
super(message || 'SitemapItem requires a configuration');
|
||||
this.name = 'NoConfigError';
|
||||
Error.captureStackTrace(this, NoConfigError);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* changefreq property in sitemap is invalid
|
||||
*/
|
||||
export class ChangeFreqInvalidError extends Error {
|
||||
constructor(url, changefreq) {
|
||||
super(`${url}: changefreq "${changefreq}" is invalid`);
|
||||
this.name = 'ChangeFreqInvalidError';
|
||||
Error.captureStackTrace(this, ChangeFreqInvalidError);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* priority property in sitemap is invalid
|
||||
*/
|
||||
export class PriorityInvalidError extends Error {
|
||||
constructor(url, priority) {
|
||||
super(`${url}: priority "${priority}" must be a number between 0 and 1 inclusive`);
|
||||
this.name = 'PriorityInvalidError';
|
||||
Error.captureStackTrace(this, PriorityInvalidError);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* SitemapIndex target Folder does not exists
|
||||
*/
|
||||
export class UndefinedTargetFolder extends Error {
|
||||
constructor(message) {
|
||||
super(message || 'Target folder must exist');
|
||||
this.name = 'UndefinedTargetFolder';
|
||||
Error.captureStackTrace(this, UndefinedTargetFolder);
|
||||
}
|
||||
}
|
||||
export class InvalidVideoFormat extends Error {
|
||||
constructor(url) {
|
||||
super(`${url} video must include thumbnail_loc, title and description fields for videos`);
|
||||
this.name = 'InvalidVideoFormat';
|
||||
Error.captureStackTrace(this, InvalidVideoFormat);
|
||||
}
|
||||
}
|
||||
export class InvalidVideoDuration extends Error {
|
||||
constructor(url, duration) {
|
||||
super(`${url} duration "${duration}" must be an integer of seconds between 0 and 28800`);
|
||||
this.name = 'InvalidVideoDuration';
|
||||
Error.captureStackTrace(this, InvalidVideoDuration);
|
||||
}
|
||||
}
|
||||
export class InvalidVideoDescription extends Error {
|
||||
constructor(url, length) {
|
||||
const message = `${url}: video description is too long ${length} vs limit of 2048 characters.`;
|
||||
super(message);
|
||||
this.name = 'InvalidVideoDescription';
|
||||
Error.captureStackTrace(this, InvalidVideoDescription);
|
||||
}
|
||||
}
|
||||
export class InvalidVideoRating extends Error {
|
||||
constructor(url, title, rating) {
|
||||
super(`${url}: video "${title}" rating "${rating}" must be between 0 and 5 inclusive`);
|
||||
this.name = 'InvalidVideoRating';
|
||||
Error.captureStackTrace(this, InvalidVideoRating);
|
||||
}
|
||||
}
|
||||
export class InvalidAttrValue extends Error {
|
||||
constructor(key, val, validator) {
|
||||
super('"' +
|
||||
val +
|
||||
'" tested against: ' +
|
||||
validator +
|
||||
' is not a valid value for attr: "' +
|
||||
key +
|
||||
'"');
|
||||
this.name = 'InvalidAttrValue';
|
||||
Error.captureStackTrace(this, InvalidAttrValue);
|
||||
}
|
||||
}
|
||||
// InvalidAttr is only thrown when attrbuilder is called incorrectly internally
|
||||
/* istanbul ignore next */
|
||||
export class InvalidAttr extends Error {
|
||||
constructor(key) {
|
||||
super('"' + key + '" is malformed');
|
||||
this.name = 'InvalidAttr';
|
||||
Error.captureStackTrace(this, InvalidAttr);
|
||||
}
|
||||
}
|
||||
export class InvalidNewsFormat extends Error {
|
||||
constructor(url) {
|
||||
super(`${url} News must include publication, publication name, publication language, title, and publication_date for news`);
|
||||
this.name = 'InvalidNewsFormat';
|
||||
Error.captureStackTrace(this, InvalidNewsFormat);
|
||||
}
|
||||
}
|
||||
export class InvalidNewsAccessValue extends Error {
|
||||
constructor(url, access) {
|
||||
super(`${url} News access "${access}" must be either Registration, Subscription or not be present`);
|
||||
this.name = 'InvalidNewsAccessValue';
|
||||
Error.captureStackTrace(this, InvalidNewsAccessValue);
|
||||
}
|
||||
}
|
||||
export class XMLLintUnavailable extends Error {
|
||||
constructor(message) {
|
||||
super(message || 'xmlLint is not installed. XMLLint is required to validate');
|
||||
this.name = 'XMLLintUnavailable';
|
||||
Error.captureStackTrace(this, XMLLintUnavailable);
|
||||
}
|
||||
}
|
||||
export class InvalidVideoTitle extends Error {
|
||||
constructor(url, length) {
|
||||
super(`${url}: video title is too long ${length} vs 100 character limit`);
|
||||
this.name = 'InvalidVideoTitle';
|
||||
Error.captureStackTrace(this, InvalidVideoTitle);
|
||||
}
|
||||
}
|
||||
export class InvalidVideoViewCount extends Error {
|
||||
constructor(url, count) {
|
||||
super(`${url}: video view count must be positive, view count was ${count}`);
|
||||
this.name = 'InvalidVideoViewCount';
|
||||
Error.captureStackTrace(this, InvalidVideoViewCount);
|
||||
}
|
||||
}
|
||||
export class InvalidVideoTagCount extends Error {
|
||||
constructor(url, count) {
|
||||
super(`${url}: video can have no more than 32 tags, this has ${count}`);
|
||||
this.name = 'InvalidVideoTagCount';
|
||||
Error.captureStackTrace(this, InvalidVideoTagCount);
|
||||
}
|
||||
}
|
||||
export class InvalidVideoCategory extends Error {
|
||||
constructor(url, count) {
|
||||
super(`${url}: video category can only be 256 characters but was passed ${count}`);
|
||||
this.name = 'InvalidVideoCategory';
|
||||
Error.captureStackTrace(this, InvalidVideoCategory);
|
||||
}
|
||||
}
|
||||
export class InvalidVideoFamilyFriendly extends Error {
|
||||
constructor(url, fam) {
|
||||
super(`${url}: video family friendly must be yes or no, was passed "${fam}"`);
|
||||
this.name = 'InvalidVideoFamilyFriendly';
|
||||
Error.captureStackTrace(this, InvalidVideoFamilyFriendly);
|
||||
}
|
||||
}
|
||||
export class InvalidVideoRestriction extends Error {
|
||||
constructor(url, code) {
|
||||
super(`${url}: video restriction must be one or more two letter country codes. Was passed "${code}"`);
|
||||
this.name = 'InvalidVideoRestriction';
|
||||
Error.captureStackTrace(this, InvalidVideoRestriction);
|
||||
}
|
||||
}
|
||||
export class InvalidVideoRestrictionRelationship extends Error {
|
||||
constructor(url, val) {
|
||||
super(`${url}: video restriction relationship must be either allow or deny. Was passed "${val}"`);
|
||||
this.name = 'InvalidVideoRestrictionRelationship';
|
||||
Error.captureStackTrace(this, InvalidVideoRestrictionRelationship);
|
||||
}
|
||||
}
|
||||
export class InvalidVideoPriceType extends Error {
|
||||
constructor(url, priceType, price) {
|
||||
super(priceType === undefined && price === ''
|
||||
? `${url}: video priceType is required when price is not provided`
|
||||
: `${url}: video price type "${priceType}" is not "rent" or "purchase"`);
|
||||
this.name = 'InvalidVideoPriceType';
|
||||
Error.captureStackTrace(this, InvalidVideoPriceType);
|
||||
}
|
||||
}
|
||||
export class InvalidVideoResolution extends Error {
|
||||
constructor(url, resolution) {
|
||||
super(`${url}: video price resolution "${resolution}" is not hd or sd`);
|
||||
this.name = 'InvalidVideoResolution';
|
||||
Error.captureStackTrace(this, InvalidVideoResolution);
|
||||
}
|
||||
}
|
||||
export class InvalidVideoPriceCurrency extends Error {
|
||||
constructor(url, currency) {
|
||||
super(`${url}: video price currency "${currency}" must be a three capital letter abbrieviation for the country currency`);
|
||||
this.name = 'InvalidVideoPriceCurrency';
|
||||
Error.captureStackTrace(this, InvalidVideoPriceCurrency);
|
||||
}
|
||||
}
|
||||
export class EmptyStream extends Error {
|
||||
constructor() {
|
||||
super('You have ended the stream before anything was written. streamToPromise MUST be called before ending the stream.');
|
||||
this.name = 'EmptyStream';
|
||||
Error.captureStackTrace(this, EmptyStream);
|
||||
}
|
||||
}
|
||||
export class EmptySitemap extends Error {
|
||||
constructor() {
|
||||
super('You ended the stream without writing anything.');
|
||||
this.name = 'EmptySitemap';
|
||||
Error.captureStackTrace(this, EmptyStream);
|
||||
}
|
||||
}
|
||||
export class InvalidPathError extends Error {
|
||||
constructor(path, reason) {
|
||||
super(`Invalid path "${path}": ${reason}`);
|
||||
this.name = 'InvalidPathError';
|
||||
Error.captureStackTrace(this, InvalidPathError);
|
||||
}
|
||||
}
|
||||
export class InvalidHostnameError extends Error {
|
||||
constructor(hostname, reason) {
|
||||
super(`Invalid hostname "${hostname}": ${reason}`);
|
||||
this.name = 'InvalidHostnameError';
|
||||
Error.captureStackTrace(this, InvalidHostnameError);
|
||||
}
|
||||
}
|
||||
export class InvalidLimitError extends Error {
|
||||
constructor(limit) {
|
||||
super(`Invalid limit "${limit}": must be a number between 1 and 50000 (per sitemaps.org spec)`);
|
||||
this.name = 'InvalidLimitError';
|
||||
Error.captureStackTrace(this, InvalidLimitError);
|
||||
}
|
||||
}
|
||||
export class InvalidPublicBasePathError extends Error {
|
||||
constructor(publicBasePath, reason) {
|
||||
super(`Invalid publicBasePath "${publicBasePath}": ${reason}`);
|
||||
this.name = 'InvalidPublicBasePathError';
|
||||
Error.captureStackTrace(this, InvalidPublicBasePathError);
|
||||
}
|
||||
}
|
||||
export class InvalidXSLUrlError extends Error {
|
||||
constructor(xslUrl, reason) {
|
||||
super(`Invalid xslUrl "${xslUrl}": ${reason}`);
|
||||
this.name = 'InvalidXSLUrlError';
|
||||
Error.captureStackTrace(this, InvalidXSLUrlError);
|
||||
}
|
||||
}
|
||||
export class InvalidXMLAttributeNameError extends Error {
|
||||
constructor(attributeName) {
|
||||
super(`Invalid XML attribute name "${attributeName}": must contain only alphanumeric characters, hyphens, underscores, and colons`);
|
||||
this.name = 'InvalidXMLAttributeNameError';
|
||||
Error.captureStackTrace(this, InvalidXMLAttributeNameError);
|
||||
}
|
||||
}
|
||||
55
node_modules/sitemap/dist/esm/lib/sitemap-index-parser.d.ts
generated
vendored
Normal file
55
node_modules/sitemap/dist/esm/lib/sitemap-index-parser.d.ts
generated
vendored
Normal file
@@ -0,0 +1,55 @@
|
||||
import type { SAXStream } from 'sax';
|
||||
import { Readable, Transform, TransformOptions, TransformCallback } from 'node:stream';
|
||||
import { IndexItem, ErrorLevel } from './types.js';
|
||||
type Logger = (level: 'warn' | 'error' | 'info' | 'log', ...message: Parameters<Console['log']>) => void;
|
||||
export interface XMLToSitemapIndexItemStreamOptions extends TransformOptions {
|
||||
level?: ErrorLevel;
|
||||
logger?: Logger | false;
|
||||
}
|
||||
/**
|
||||
* Takes a stream of xml and transforms it into a stream of IndexItems
|
||||
* Use this to parse existing sitemap indices into config options compatible with this library
|
||||
*/
|
||||
export declare class XMLToSitemapIndexStream extends Transform {
|
||||
level: ErrorLevel;
|
||||
logger: Logger;
|
||||
error: Error | null;
|
||||
saxStream: SAXStream;
|
||||
constructor(opts?: XMLToSitemapIndexItemStreamOptions);
|
||||
_transform(data: string, encoding: string, callback: TransformCallback): void;
|
||||
private err;
|
||||
}
|
||||
/**
|
||||
Read xml and resolve with the configuration that would produce it or reject with
|
||||
an error
|
||||
```
|
||||
const { createReadStream } = require('fs')
|
||||
const { parseSitemapIndex, createSitemap } = require('sitemap')
|
||||
parseSitemapIndex(createReadStream('./example-index.xml')).then(
|
||||
// produces the same xml
|
||||
// you can, of course, more practically modify it or store it
|
||||
(xmlConfig) => console.log(createSitemap(xmlConfig).toString()),
|
||||
(err) => console.log(err)
|
||||
)
|
||||
```
|
||||
@param {Readable} xml what to parse
|
||||
@param {number} maxEntries Maximum number of sitemap entries to parse (default: 50,000 per sitemaps.org spec)
|
||||
@return {Promise<IndexItem[]>} resolves with list of index items that can be fed into a SitemapIndexStream. Rejects with an Error object.
|
||||
*/
|
||||
export declare function parseSitemapIndex(xml: Readable, maxEntries?: number): Promise<IndexItem[]>;
|
||||
export interface IndexObjectStreamToJSONOptions extends TransformOptions {
|
||||
lineSeparated: boolean;
|
||||
}
|
||||
/**
|
||||
* A Transform that converts a stream of objects into a JSON Array or a line
|
||||
* separated stringified JSON
|
||||
* @param [lineSeparated=false] whether to separate entries by a new line or comma
|
||||
*/
|
||||
export declare class IndexObjectStreamToJSON extends Transform {
|
||||
lineSeparated: boolean;
|
||||
firstWritten: boolean;
|
||||
constructor(opts?: IndexObjectStreamToJSONOptions);
|
||||
_transform(chunk: IndexItem, encoding: string, cb: TransformCallback): void;
|
||||
_flush(cb: TransformCallback): void;
|
||||
}
|
||||
export {};
|
||||
262
node_modules/sitemap/dist/esm/lib/sitemap-index-parser.js
generated
vendored
Normal file
262
node_modules/sitemap/dist/esm/lib/sitemap-index-parser.js
generated
vendored
Normal file
@@ -0,0 +1,262 @@
|
||||
import sax from 'sax';
|
||||
import { Transform, } from 'node:stream';
|
||||
import { ErrorLevel, IndexTagNames } from './types.js';
|
||||
import { validateURL } from './validation.js';
|
||||
import { LIMITS } from './constants.js';
|
||||
function isValidTagName(tagName) {
|
||||
// This only works because the enum name and value are the same
|
||||
return tagName in IndexTagNames;
|
||||
}
|
||||
function tagTemplate() {
|
||||
return {
|
||||
url: '',
|
||||
};
|
||||
}
|
||||
const defaultLogger = (level, ...message) => console[level](...message);
|
||||
const defaultStreamOpts = {
|
||||
logger: defaultLogger,
|
||||
};
|
||||
/**
|
||||
* Takes a stream of xml and transforms it into a stream of IndexItems
|
||||
* Use this to parse existing sitemap indices into config options compatible with this library
|
||||
*/
|
||||
export class XMLToSitemapIndexStream extends Transform {
|
||||
level;
|
||||
logger;
|
||||
error;
|
||||
saxStream;
|
||||
constructor(opts = defaultStreamOpts) {
|
||||
opts.objectMode = true;
|
||||
super(opts);
|
||||
this.error = null;
|
||||
this.saxStream = sax.createStream(true, {
|
||||
xmlns: true,
|
||||
// @ts-expect-error - SAX types don't include strictEntities option
|
||||
strictEntities: true,
|
||||
trim: true,
|
||||
});
|
||||
this.level = opts.level || ErrorLevel.WARN;
|
||||
if (this.level !== ErrorLevel.SILENT && opts.logger !== false) {
|
||||
this.logger = opts.logger ?? defaultLogger;
|
||||
}
|
||||
else {
|
||||
this.logger = () => undefined;
|
||||
}
|
||||
let currentItem = tagTemplate();
|
||||
let currentTag;
|
||||
this.saxStream.on('opentagstart', (tag) => {
|
||||
currentTag = tag.name;
|
||||
});
|
||||
this.saxStream.on('opentag', (tag) => {
|
||||
if (!isValidTagName(tag.name)) {
|
||||
this.logger('warn', 'unhandled tag', tag.name);
|
||||
this.err(`unhandled tag: ${tag.name}`);
|
||||
}
|
||||
});
|
||||
this.saxStream.on('text', (text) => {
|
||||
switch (currentTag) {
|
||||
case IndexTagNames.loc:
|
||||
// Validate URL for security: prevents protocol injection, checks length limits
|
||||
try {
|
||||
validateURL(text, 'Sitemap index URL');
|
||||
currentItem.url = text;
|
||||
}
|
||||
catch (error) {
|
||||
const errMsg = error instanceof Error ? error.message : String(error);
|
||||
this.logger('warn', 'Invalid URL in sitemap index:', errMsg);
|
||||
this.err(`Invalid URL in sitemap index: ${errMsg}`);
|
||||
}
|
||||
break;
|
||||
case IndexTagNames.lastmod:
|
||||
// Validate date format for security and spec compliance
|
||||
if (text && !LIMITS.ISO_DATE_REGEX.test(text)) {
|
||||
this.logger('warn', 'Invalid lastmod date format in sitemap index:', text);
|
||||
this.err(`Invalid lastmod date format: ${text}`);
|
||||
}
|
||||
else {
|
||||
currentItem.lastmod = text;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
this.logger('log', 'unhandled text for tag:', currentTag, `'${text}'`);
|
||||
this.err(`unhandled text for tag: ${currentTag} '${text}'`);
|
||||
break;
|
||||
}
|
||||
});
|
||||
this.saxStream.on('cdata', (text) => {
|
||||
switch (currentTag) {
|
||||
case IndexTagNames.loc:
|
||||
// Validate URL for security: prevents protocol injection, checks length limits
|
||||
try {
|
||||
validateURL(text, 'Sitemap index URL');
|
||||
currentItem.url = text;
|
||||
}
|
||||
catch (error) {
|
||||
const errMsg = error instanceof Error ? error.message : String(error);
|
||||
this.logger('warn', 'Invalid URL in sitemap index:', errMsg);
|
||||
this.err(`Invalid URL in sitemap index: ${errMsg}`);
|
||||
}
|
||||
break;
|
||||
case IndexTagNames.lastmod:
|
||||
// Validate date format for security and spec compliance
|
||||
if (text && !LIMITS.ISO_DATE_REGEX.test(text)) {
|
||||
this.logger('warn', 'Invalid lastmod date format in sitemap index:', text);
|
||||
this.err(`Invalid lastmod date format: ${text}`);
|
||||
}
|
||||
else {
|
||||
currentItem.lastmod = text;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
this.logger('log', 'unhandled cdata for tag:', currentTag);
|
||||
this.err(`unhandled cdata for tag: ${currentTag}`);
|
||||
break;
|
||||
}
|
||||
});
|
||||
this.saxStream.on('attribute', (attr) => {
|
||||
switch (currentTag) {
|
||||
case IndexTagNames.sitemapindex:
|
||||
break;
|
||||
default:
|
||||
this.logger('log', 'unhandled attr', currentTag, attr.name);
|
||||
this.err(`unhandled attr: ${currentTag} ${attr.name}`);
|
||||
}
|
||||
});
|
||||
this.saxStream.on('closetag', (tag) => {
|
||||
switch (tag) {
|
||||
case IndexTagNames.sitemap:
|
||||
// Only push items with valid URLs (non-empty after validation)
|
||||
if (currentItem.url) {
|
||||
this.push(currentItem);
|
||||
}
|
||||
currentItem = tagTemplate();
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
});
|
||||
}
|
||||
_transform(data, encoding, callback) {
|
||||
try {
|
||||
const cb = () => callback(this.level === ErrorLevel.THROW ? this.error : null);
|
||||
// correcting the type here can be done without making it a breaking change
|
||||
// TODO fix this
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
if (!this.saxStream.write(data, encoding)) {
|
||||
this.saxStream.once('drain', cb);
|
||||
}
|
||||
else {
|
||||
process.nextTick(cb);
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
callback(error);
|
||||
}
|
||||
}
|
||||
err(msg) {
|
||||
if (!this.error)
|
||||
this.error = new Error(msg);
|
||||
}
|
||||
}
|
||||
/**
|
||||
Read xml and resolve with the configuration that would produce it or reject with
|
||||
an error
|
||||
```
|
||||
const { createReadStream } = require('fs')
|
||||
const { parseSitemapIndex, createSitemap } = require('sitemap')
|
||||
parseSitemapIndex(createReadStream('./example-index.xml')).then(
|
||||
// produces the same xml
|
||||
// you can, of course, more practically modify it or store it
|
||||
(xmlConfig) => console.log(createSitemap(xmlConfig).toString()),
|
||||
(err) => console.log(err)
|
||||
)
|
||||
```
|
||||
@param {Readable} xml what to parse
|
||||
@param {number} maxEntries Maximum number of sitemap entries to parse (default: 50,000 per sitemaps.org spec)
|
||||
@return {Promise<IndexItem[]>} resolves with list of index items that can be fed into a SitemapIndexStream. Rejects with an Error object.
|
||||
*/
|
||||
export async function parseSitemapIndex(xml, maxEntries = LIMITS.MAX_SITEMAP_ITEM_LIMIT) {
|
||||
const urls = [];
|
||||
return new Promise((resolve, reject) => {
|
||||
let settled = false;
|
||||
const parser = new XMLToSitemapIndexStream();
|
||||
// Handle source stream errors (prevents unhandled error events on xml)
|
||||
xml.on('error', (error) => {
|
||||
if (!settled) {
|
||||
settled = true;
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
xml
|
||||
.pipe(parser)
|
||||
.on('data', (smi) => {
|
||||
if (settled)
|
||||
return;
|
||||
// Security: Prevent memory exhaustion by limiting number of entries
|
||||
if (urls.length >= maxEntries) {
|
||||
settled = true;
|
||||
reject(new Error(`Sitemap index exceeds maximum allowed entries (${maxEntries})`));
|
||||
// Immediately destroy both streams to stop further processing (BB-05)
|
||||
parser.destroy();
|
||||
xml.destroy();
|
||||
return;
|
||||
}
|
||||
urls.push(smi);
|
||||
})
|
||||
.on('end', () => {
|
||||
if (!settled) {
|
||||
settled = true;
|
||||
resolve(urls);
|
||||
}
|
||||
})
|
||||
.on('error', (error) => {
|
||||
if (!settled) {
|
||||
settled = true;
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
const defaultObjectStreamOpts = {
|
||||
lineSeparated: false,
|
||||
};
|
||||
/**
|
||||
* A Transform that converts a stream of objects into a JSON Array or a line
|
||||
* separated stringified JSON
|
||||
* @param [lineSeparated=false] whether to separate entries by a new line or comma
|
||||
*/
|
||||
export class IndexObjectStreamToJSON extends Transform {
|
||||
lineSeparated;
|
||||
firstWritten;
|
||||
constructor(opts = defaultObjectStreamOpts) {
|
||||
opts.writableObjectMode = true;
|
||||
super(opts);
|
||||
this.lineSeparated = opts.lineSeparated;
|
||||
this.firstWritten = false;
|
||||
}
|
||||
_transform(chunk, encoding, cb) {
|
||||
if (!this.firstWritten) {
|
||||
this.firstWritten = true;
|
||||
if (!this.lineSeparated) {
|
||||
this.push('[');
|
||||
}
|
||||
}
|
||||
else if (this.lineSeparated) {
|
||||
this.push('\n');
|
||||
}
|
||||
else {
|
||||
this.push(',');
|
||||
}
|
||||
if (chunk) {
|
||||
this.push(JSON.stringify(chunk));
|
||||
}
|
||||
cb();
|
||||
}
|
||||
_flush(cb) {
|
||||
if (!this.lineSeparated) {
|
||||
this.push(']');
|
||||
}
|
||||
cb();
|
||||
}
|
||||
}
|
||||
169
node_modules/sitemap/dist/esm/lib/sitemap-index-stream.d.ts
generated
vendored
Normal file
169
node_modules/sitemap/dist/esm/lib/sitemap-index-stream.d.ts
generated
vendored
Normal file
@@ -0,0 +1,169 @@
|
||||
import { WriteStream } from 'node:fs';
|
||||
import { Transform, TransformOptions, TransformCallback } from 'node:stream';
|
||||
import { IndexItem, SitemapItemLoose, ErrorLevel, IndexTagNames } from './types.js';
|
||||
import { SitemapStream } from './sitemap-stream.js';
|
||||
export { IndexTagNames };
|
||||
/**
|
||||
* Options for the SitemapIndexStream
|
||||
*/
|
||||
export interface SitemapIndexStreamOptions extends TransformOptions {
|
||||
/**
|
||||
* Whether to output the lastmod date only (no time)
|
||||
*
|
||||
* @default false
|
||||
*/
|
||||
lastmodDateOnly?: boolean;
|
||||
/**
|
||||
* How to handle errors in passed in urls
|
||||
*
|
||||
* @default ErrorLevel.WARN
|
||||
*/
|
||||
level?: ErrorLevel;
|
||||
/**
|
||||
* URL to an XSL stylesheet to include in the XML
|
||||
*/
|
||||
xslUrl?: string;
|
||||
}
|
||||
/**
|
||||
* `SitemapIndexStream` is a Transform stream that takes `IndexItem`s or sitemap URL strings and outputs a stream of sitemap index XML.
|
||||
*
|
||||
* It automatically handles the XML declaration and the opening and closing tags for the sitemap index.
|
||||
*
|
||||
* ⚠️ CAUTION: This object is `readable` and must be read (e.g. piped to a file or to /dev/null)
|
||||
* before `finish` will be emitted. Failure to read the stream will result in hangs.
|
||||
*
|
||||
* @extends {Transform}
|
||||
*/
|
||||
export declare class SitemapIndexStream extends Transform {
|
||||
lastmodDateOnly: boolean;
|
||||
level: ErrorLevel;
|
||||
xslUrl?: string;
|
||||
private hasHeadOutput;
|
||||
/**
|
||||
* `SitemapIndexStream` is a Transform stream that takes `IndexItem`s or sitemap URL strings and outputs a stream of sitemap index XML.
|
||||
*
|
||||
* It automatically handles the XML declaration and the opening and closing tags for the sitemap index.
|
||||
*
|
||||
* ⚠️ CAUTION: This object is `readable` and must be read (e.g. piped to a file or to /dev/null)
|
||||
* before `finish` will be emitted. Failure to read the stream will result in hangs.
|
||||
*
|
||||
* @param {SitemapIndexStreamOptions} [opts=defaultStreamOpts] - Stream options.
|
||||
*/
|
||||
constructor(opts?: SitemapIndexStreamOptions);
|
||||
private writeHeadOutput;
|
||||
_transform(item: IndexItem | string, encoding: string, callback: TransformCallback): void;
|
||||
_flush(cb: TransformCallback): void;
|
||||
}
|
||||
/**
|
||||
* Callback function type for creating new sitemap streams when the item limit is reached.
|
||||
*
|
||||
* This function is called by SitemapAndIndexStream to create a new sitemap file when
|
||||
* the current one reaches the item limit.
|
||||
*
|
||||
* @param i - The zero-based index of the sitemap file being created (0 for first sitemap,
|
||||
* 1 for second, etc.)
|
||||
* @returns A tuple containing:
|
||||
* - [0]: IndexItem or URL string to add to the sitemap index
|
||||
* - [1]: SitemapStream instance for writing sitemap items
|
||||
* - [2]: WriteStream where the sitemap will be piped (the stream will be
|
||||
* awaited for 'finish' before creating the next sitemap)
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const getSitemapStream = (i: number) => {
|
||||
* const sitemapStream = new SitemapStream();
|
||||
* const path = `./sitemap-${i}.xml`;
|
||||
* const writeStream = createWriteStream(path);
|
||||
* sitemapStream.pipe(writeStream);
|
||||
* return [`https://example.com/${path}`, sitemapStream, writeStream];
|
||||
* };
|
||||
* ```
|
||||
*/
|
||||
type getSitemapStreamFunc = (i: number) => [IndexItem | string, SitemapStream, WriteStream];
|
||||
/**
|
||||
* Options for the SitemapAndIndexStream
|
||||
*
|
||||
* @extends {SitemapIndexStreamOptions}
|
||||
*/
|
||||
export interface SitemapAndIndexStreamOptions extends SitemapIndexStreamOptions {
|
||||
/**
|
||||
* Max number of items in each sitemap XML file.
|
||||
*
|
||||
* When the limit is reached the current sitemap file will be closed,
|
||||
* a wait for `finish` on the target write stream will happen,
|
||||
* and a new sitemap file will be created.
|
||||
*
|
||||
* Range: 1 - 50,000
|
||||
*
|
||||
* @default 45000
|
||||
*/
|
||||
limit?: number;
|
||||
/**
|
||||
* Callback for SitemapIndexAndStream that creates a new sitemap stream for a given sitemap index.
|
||||
*
|
||||
* Called when a new sitemap file is needed.
|
||||
*
|
||||
* The write stream is the destination where the sitemap was piped.
|
||||
* SitemapAndIndexStream will wait for the `finish` event on each sitemap's
|
||||
* write stream before moving on to the next sitemap. This ensures that the
|
||||
* contents of the write stream will be fully written before being used
|
||||
* by any following operations (e.g. uploading, reading contents for unit tests).
|
||||
*
|
||||
* @param i - The index of the sitemap file
|
||||
* @returns A tuple containing the index item to be written into the sitemap index, the sitemap stream, and the write stream for the sitemap pipe destination
|
||||
*/
|
||||
getSitemapStream: getSitemapStreamFunc;
|
||||
}
|
||||
/**
|
||||
* `SitemapAndIndexStream` is a Transform stream that takes in sitemap items,
|
||||
* writes them to sitemap files, adds the sitemap files to a sitemap index,
|
||||
* and creates new sitemap files when the count limit is reached.
|
||||
*
|
||||
* It waits for the target stream of the current sitemap file to finish before
|
||||
* moving on to the next if the target stream is returned by the `getSitemapStream`
|
||||
* callback in the 3rd position of the tuple.
|
||||
*
|
||||
* ⚠️ CAUTION: This object is `readable` and must be read (e.g. piped to a file or to /dev/null)
|
||||
* before `finish` will be emitted. Failure to read the stream will result in hangs.
|
||||
*
|
||||
* @extends {SitemapIndexStream}
|
||||
*/
|
||||
export declare class SitemapAndIndexStream extends SitemapIndexStream {
|
||||
private itemsWritten;
|
||||
private getSitemapStream;
|
||||
private currentSitemap?;
|
||||
private limit;
|
||||
private currentSitemapPipeline?;
|
||||
/**
|
||||
* Flag to prevent race conditions when creating new sitemap files.
|
||||
* Set to true while waiting for the current sitemap to finish and
|
||||
* a new one to be created.
|
||||
*/
|
||||
private isCreatingSitemap;
|
||||
/**
|
||||
* `SitemapAndIndexStream` is a Transform stream that takes in sitemap items,
|
||||
* writes them to sitemap files, adds the sitemap files to a sitemap index,
|
||||
* and creates new sitemap files when the count limit is reached.
|
||||
*
|
||||
* It waits for the target stream of the current sitemap file to finish before
|
||||
* moving on to the next if the target stream is returned by the `getSitemapStream`
|
||||
* callback in the 3rd position of the tuple.
|
||||
*
|
||||
* ⚠️ CAUTION: This object is `readable` and must be read (e.g. piped to a file or to /dev/null)
|
||||
* before `finish` will be emitted. Failure to read the stream will result in hangs.
|
||||
*
|
||||
* @param {SitemapAndIndexStreamOptions} opts - Stream options.
|
||||
*/
|
||||
constructor(opts: SitemapAndIndexStreamOptions);
|
||||
_transform(item: SitemapItemLoose, encoding: string, callback: TransformCallback): void;
|
||||
private writeItem;
|
||||
/**
|
||||
* Called when the stream is finished.
|
||||
* If there is a current sitemap, we wait for it to finish before calling the callback.
|
||||
* Includes proper event listener cleanup to prevent memory leaks.
|
||||
*
|
||||
* @param cb - The callback to invoke when flushing is complete
|
||||
*/
|
||||
_flush(cb: TransformCallback): void;
|
||||
private createSitemap;
|
||||
}
|
||||
359
node_modules/sitemap/dist/esm/lib/sitemap-index-stream.js
generated
vendored
Normal file
359
node_modules/sitemap/dist/esm/lib/sitemap-index-stream.js
generated
vendored
Normal file
@@ -0,0 +1,359 @@
|
||||
import { Transform } from 'node:stream';
|
||||
import { ErrorLevel, IndexTagNames, } from './types.js';
|
||||
import { stylesheetInclude } from './sitemap-stream.js';
|
||||
import { element, otag, ctag } from './sitemap-xml.js';
|
||||
import { LIMITS, DEFAULT_SITEMAP_ITEM_LIMIT } from './constants.js';
|
||||
import { validateURL, validateXSLUrl } from './validation.js';
|
||||
// Re-export IndexTagNames for backward compatibility
|
||||
export { IndexTagNames };
|
||||
const xmlDec = '<?xml version="1.0" encoding="UTF-8"?>';
|
||||
const sitemapIndexTagStart = '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
|
||||
const closetag = '</sitemapindex>';
|
||||
const defaultStreamOpts = {};
|
||||
/**
|
||||
* `SitemapIndexStream` is a Transform stream that takes `IndexItem`s or sitemap URL strings and outputs a stream of sitemap index XML.
|
||||
*
|
||||
* It automatically handles the XML declaration and the opening and closing tags for the sitemap index.
|
||||
*
|
||||
* ⚠️ CAUTION: This object is `readable` and must be read (e.g. piped to a file or to /dev/null)
|
||||
* before `finish` will be emitted. Failure to read the stream will result in hangs.
|
||||
*
|
||||
* @extends {Transform}
|
||||
*/
|
||||
export class SitemapIndexStream extends Transform {
|
||||
lastmodDateOnly;
|
||||
level;
|
||||
xslUrl;
|
||||
hasHeadOutput;
|
||||
/**
|
||||
* `SitemapIndexStream` is a Transform stream that takes `IndexItem`s or sitemap URL strings and outputs a stream of sitemap index XML.
|
||||
*
|
||||
* It automatically handles the XML declaration and the opening and closing tags for the sitemap index.
|
||||
*
|
||||
* ⚠️ CAUTION: This object is `readable` and must be read (e.g. piped to a file or to /dev/null)
|
||||
* before `finish` will be emitted. Failure to read the stream will result in hangs.
|
||||
*
|
||||
* @param {SitemapIndexStreamOptions} [opts=defaultStreamOpts] - Stream options.
|
||||
*/
|
||||
constructor(opts = defaultStreamOpts) {
|
||||
opts.objectMode = true;
|
||||
super(opts);
|
||||
this.hasHeadOutput = false;
|
||||
this.lastmodDateOnly = opts.lastmodDateOnly || false;
|
||||
this.level = opts.level ?? ErrorLevel.WARN;
|
||||
if (opts.xslUrl !== undefined) {
|
||||
validateXSLUrl(opts.xslUrl);
|
||||
}
|
||||
this.xslUrl = opts.xslUrl;
|
||||
}
|
||||
writeHeadOutput() {
|
||||
this.hasHeadOutput = true;
|
||||
let stylesheet = '';
|
||||
if (this.xslUrl) {
|
||||
stylesheet = stylesheetInclude(this.xslUrl);
|
||||
}
|
||||
this.push(xmlDec + stylesheet + sitemapIndexTagStart);
|
||||
}
|
||||
_transform(item, encoding, callback) {
|
||||
if (!this.hasHeadOutput) {
|
||||
this.writeHeadOutput();
|
||||
}
|
||||
try {
|
||||
// Validate URL using centralized validation (checks protocol, length, format)
|
||||
const url = typeof item === 'string' ? item : item.url;
|
||||
if (!url || typeof url !== 'string') {
|
||||
const error = new Error('Invalid sitemap index item: URL must be a non-empty string');
|
||||
if (this.level === ErrorLevel.THROW) {
|
||||
callback(error);
|
||||
return;
|
||||
}
|
||||
else if (this.level === ErrorLevel.WARN) {
|
||||
console.warn(error.message, item);
|
||||
}
|
||||
// For SILENT or after WARN, skip this item
|
||||
callback();
|
||||
return;
|
||||
}
|
||||
// Security: Use centralized validation to enforce protocol restrictions,
|
||||
// length limits, and prevent injection attacks
|
||||
try {
|
||||
validateURL(url, 'Sitemap index URL');
|
||||
}
|
||||
catch (error) {
|
||||
// Wrap the validation error with consistent message format
|
||||
const validationMsg = error instanceof Error ? error.message : String(error);
|
||||
const err = new Error(`Invalid URL in sitemap index: ${validationMsg}`);
|
||||
if (this.level === ErrorLevel.THROW) {
|
||||
callback(err);
|
||||
return;
|
||||
}
|
||||
else if (this.level === ErrorLevel.WARN) {
|
||||
console.warn(err.message);
|
||||
}
|
||||
// For SILENT or after WARN, skip this item
|
||||
callback();
|
||||
return;
|
||||
}
|
||||
this.push(otag(IndexTagNames.sitemap));
|
||||
if (typeof item === 'string') {
|
||||
this.push(element(IndexTagNames.loc, item));
|
||||
}
|
||||
else {
|
||||
this.push(element(IndexTagNames.loc, item.url));
|
||||
if (item.lastmod) {
|
||||
try {
|
||||
const lastmod = new Date(item.lastmod).toISOString();
|
||||
this.push(element(IndexTagNames.lastmod, this.lastmodDateOnly ? lastmod.slice(0, 10) : lastmod));
|
||||
}
|
||||
catch {
|
||||
const error = new Error(`Invalid lastmod date in sitemap index: ${item.lastmod}`);
|
||||
if (this.level === ErrorLevel.THROW) {
|
||||
callback(error);
|
||||
return;
|
||||
}
|
||||
else if (this.level === ErrorLevel.WARN) {
|
||||
console.warn(error.message);
|
||||
}
|
||||
// Continue without lastmod for SILENT or after WARN
|
||||
}
|
||||
}
|
||||
}
|
||||
this.push(ctag(IndexTagNames.sitemap));
|
||||
callback();
|
||||
}
|
||||
catch (error) {
|
||||
callback(error instanceof Error ? error : new Error(String(error)));
|
||||
}
|
||||
}
|
||||
_flush(cb) {
|
||||
if (!this.hasHeadOutput) {
|
||||
this.writeHeadOutput();
|
||||
}
|
||||
this.push(closetag);
|
||||
cb();
|
||||
}
|
||||
}
|
||||
/**
|
||||
* `SitemapAndIndexStream` is a Transform stream that takes in sitemap items,
|
||||
* writes them to sitemap files, adds the sitemap files to a sitemap index,
|
||||
* and creates new sitemap files when the count limit is reached.
|
||||
*
|
||||
* It waits for the target stream of the current sitemap file to finish before
|
||||
* moving on to the next if the target stream is returned by the `getSitemapStream`
|
||||
* callback in the 3rd position of the tuple.
|
||||
*
|
||||
* ⚠️ CAUTION: This object is `readable` and must be read (e.g. piped to a file or to /dev/null)
|
||||
* before `finish` will be emitted. Failure to read the stream will result in hangs.
|
||||
*
|
||||
* @extends {SitemapIndexStream}
|
||||
*/
|
||||
export class SitemapAndIndexStream extends SitemapIndexStream {
|
||||
itemsWritten;
|
||||
getSitemapStream;
|
||||
currentSitemap;
|
||||
limit;
|
||||
currentSitemapPipeline;
|
||||
/**
|
||||
* Flag to prevent race conditions when creating new sitemap files.
|
||||
* Set to true while waiting for the current sitemap to finish and
|
||||
* a new one to be created.
|
||||
*/
|
||||
isCreatingSitemap;
|
||||
/**
|
||||
* `SitemapAndIndexStream` is a Transform stream that takes in sitemap items,
|
||||
* writes them to sitemap files, adds the sitemap files to a sitemap index,
|
||||
* and creates new sitemap files when the count limit is reached.
|
||||
*
|
||||
* It waits for the target stream of the current sitemap file to finish before
|
||||
* moving on to the next if the target stream is returned by the `getSitemapStream`
|
||||
* callback in the 3rd position of the tuple.
|
||||
*
|
||||
* ⚠️ CAUTION: This object is `readable` and must be read (e.g. piped to a file or to /dev/null)
|
||||
* before `finish` will be emitted. Failure to read the stream will result in hangs.
|
||||
*
|
||||
* @param {SitemapAndIndexStreamOptions} opts - Stream options.
|
||||
*/
|
||||
constructor(opts) {
|
||||
opts.objectMode = true;
|
||||
super(opts);
|
||||
this.itemsWritten = 0;
|
||||
this.getSitemapStream = opts.getSitemapStream;
|
||||
this.limit = opts.limit ?? DEFAULT_SITEMAP_ITEM_LIMIT;
|
||||
this.isCreatingSitemap = false;
|
||||
// Validate limit is within acceptable range per sitemaps.org spec
|
||||
// See: https://www.sitemaps.org/protocol.html#index
|
||||
if (this.limit < LIMITS.MIN_SITEMAP_ITEM_LIMIT ||
|
||||
this.limit > LIMITS.MAX_SITEMAP_ITEM_LIMIT) {
|
||||
throw new Error(`limit must be between ${LIMITS.MIN_SITEMAP_ITEM_LIMIT} and ${LIMITS.MAX_SITEMAP_ITEM_LIMIT} per sitemaps.org spec, got ${this.limit}`);
|
||||
}
|
||||
}
|
||||
_transform(item, encoding, callback) {
|
||||
if (this.itemsWritten % this.limit === 0) {
|
||||
// Prevent race condition if multiple items arrive during sitemap creation
|
||||
if (this.isCreatingSitemap) {
|
||||
// Wait and retry on next tick
|
||||
process.nextTick(() => this._transform(item, encoding, callback));
|
||||
return;
|
||||
}
|
||||
if (this.currentSitemap) {
|
||||
this.isCreatingSitemap = true;
|
||||
const currentSitemap = this.currentSitemap;
|
||||
const currentPipeline = this.currentSitemapPipeline;
|
||||
// Set up promises with proper cleanup to prevent memory leaks
|
||||
const onFinish = new Promise((resolve, reject) => {
|
||||
const finishHandler = () => {
|
||||
currentSitemap.off('error', errorHandler);
|
||||
resolve();
|
||||
};
|
||||
const errorHandler = (err) => {
|
||||
currentSitemap.off('finish', finishHandler);
|
||||
reject(err);
|
||||
};
|
||||
currentSitemap.on('finish', finishHandler);
|
||||
currentSitemap.on('error', errorHandler);
|
||||
currentSitemap.end();
|
||||
});
|
||||
const onPipelineFinish = currentPipeline
|
||||
? new Promise((resolve, reject) => {
|
||||
const finishHandler = () => {
|
||||
currentPipeline.off('error', errorHandler);
|
||||
resolve();
|
||||
};
|
||||
const errorHandler = (err) => {
|
||||
currentPipeline.off('finish', finishHandler);
|
||||
reject(err);
|
||||
};
|
||||
currentPipeline.on('finish', finishHandler);
|
||||
currentPipeline.on('error', errorHandler);
|
||||
})
|
||||
: Promise.resolve();
|
||||
Promise.all([onFinish, onPipelineFinish])
|
||||
.then(() => {
|
||||
this.isCreatingSitemap = false;
|
||||
this.createSitemap(encoding);
|
||||
this.writeItem(item, callback);
|
||||
})
|
||||
.catch((err) => {
|
||||
this.isCreatingSitemap = false;
|
||||
callback(err);
|
||||
});
|
||||
return;
|
||||
}
|
||||
else {
|
||||
this.createSitemap(encoding);
|
||||
}
|
||||
}
|
||||
this.writeItem(item, callback);
|
||||
}
|
||||
writeItem(item, callback) {
|
||||
if (!this.currentSitemap) {
|
||||
callback(new Error('No sitemap stream available'));
|
||||
return;
|
||||
}
|
||||
if (!this.currentSitemap.write(item)) {
|
||||
this.currentSitemap.once('drain', callback);
|
||||
}
|
||||
else {
|
||||
process.nextTick(callback);
|
||||
}
|
||||
// Increment the count of items written
|
||||
this.itemsWritten++;
|
||||
}
|
||||
/**
|
||||
* Called when the stream is finished.
|
||||
* If there is a current sitemap, we wait for it to finish before calling the callback.
|
||||
* Includes proper event listener cleanup to prevent memory leaks.
|
||||
*
|
||||
* @param cb - The callback to invoke when flushing is complete
|
||||
*/
|
||||
_flush(cb) {
|
||||
const currentSitemap = this.currentSitemap;
|
||||
const currentPipeline = this.currentSitemapPipeline;
|
||||
const onFinish = new Promise((resolve, reject) => {
|
||||
if (currentSitemap) {
|
||||
const finishHandler = () => {
|
||||
currentSitemap.off('error', errorHandler);
|
||||
resolve();
|
||||
};
|
||||
const errorHandler = (err) => {
|
||||
currentSitemap.off('finish', finishHandler);
|
||||
reject(err);
|
||||
};
|
||||
currentSitemap.on('finish', finishHandler);
|
||||
currentSitemap.on('error', errorHandler);
|
||||
currentSitemap.end();
|
||||
}
|
||||
else {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
const onPipelineFinish = new Promise((resolve, reject) => {
|
||||
if (currentPipeline) {
|
||||
const finishHandler = () => {
|
||||
currentPipeline.off('error', errorHandler);
|
||||
resolve();
|
||||
};
|
||||
const errorHandler = (err) => {
|
||||
currentPipeline.off('finish', finishHandler);
|
||||
reject(err);
|
||||
};
|
||||
currentPipeline.on('finish', finishHandler);
|
||||
currentPipeline.on('error', errorHandler);
|
||||
// The pipeline (pipe target) will get its end() call
|
||||
// from the sitemap stream ending.
|
||||
}
|
||||
else {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
Promise.all([onFinish, onPipelineFinish])
|
||||
.then(() => {
|
||||
super._flush(cb);
|
||||
})
|
||||
.catch((err) => {
|
||||
cb(err);
|
||||
});
|
||||
}
|
||||
createSitemap(encoding) {
|
||||
const sitemapIndex = this.itemsWritten / this.limit;
|
||||
let result;
|
||||
try {
|
||||
result = this.getSitemapStream(sitemapIndex);
|
||||
}
|
||||
catch (err) {
|
||||
this.emit('error', new Error(`getSitemapStream callback threw an error for index ${sitemapIndex}: ${err instanceof Error ? err.message : String(err)}`));
|
||||
return;
|
||||
}
|
||||
// Validate the return value
|
||||
if (!Array.isArray(result) || result.length !== 3) {
|
||||
this.emit('error', new Error(`getSitemapStream must return a 3-element array [IndexItem | string, SitemapStream, WriteStream], got: ${typeof result}`));
|
||||
return;
|
||||
}
|
||||
const [idxItem, currentSitemap, currentSitemapPipeline] = result;
|
||||
// Validate each element
|
||||
if (!idxItem ||
|
||||
(typeof idxItem !== 'string' && typeof idxItem !== 'object')) {
|
||||
this.emit('error', new Error('getSitemapStream must return an IndexItem or string as the first element'));
|
||||
return;
|
||||
}
|
||||
if (!currentSitemap || typeof currentSitemap.write !== 'function') {
|
||||
this.emit('error', new Error('getSitemapStream must return a SitemapStream as the second element'));
|
||||
return;
|
||||
}
|
||||
if (currentSitemapPipeline &&
|
||||
typeof currentSitemapPipeline.write !== 'function') {
|
||||
this.emit('error', new Error('getSitemapStream must return a WriteStream or undefined as the third element'));
|
||||
return;
|
||||
}
|
||||
// Propagate errors from the sitemap stream
|
||||
currentSitemap.on('error', (err) => this.emit('error', err));
|
||||
this.currentSitemap = currentSitemap;
|
||||
this.currentSitemapPipeline = currentSitemapPipeline;
|
||||
super._transform(idxItem, encoding, () => {
|
||||
// We are not too concerned about waiting for the index item to be written
|
||||
// as we'll wait for the file to finish at the end, and index file write
|
||||
// volume tends to be small in comparison to sitemap writes.
|
||||
// noop
|
||||
});
|
||||
}
|
||||
}
|
||||
21
node_modules/sitemap/dist/esm/lib/sitemap-item-stream.d.ts
generated
vendored
Normal file
21
node_modules/sitemap/dist/esm/lib/sitemap-item-stream.d.ts
generated
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
import { Transform, TransformOptions, TransformCallback } from 'node:stream';
|
||||
import { SitemapItem, ErrorLevel } from './types.js';
|
||||
export interface SitemapItemStreamOptions extends TransformOptions {
|
||||
level?: ErrorLevel;
|
||||
}
|
||||
/**
|
||||
* Takes a stream of SitemapItemOptions and spits out xml for each
|
||||
* @example
|
||||
* // writes <url><loc>https://example.com</loc><url><url><loc>https://example.com/2</loc><url>
|
||||
* const smis = new SitemapItemStream({level: 'warn'})
|
||||
* smis.pipe(writestream)
|
||||
* smis.write({url: 'https://example.com', img: [], video: [], links: []})
|
||||
* smis.write({url: 'https://example.com/2', img: [], video: [], links: []})
|
||||
* smis.end()
|
||||
* @param level - Error level
|
||||
*/
|
||||
export declare class SitemapItemStream extends Transform {
|
||||
level: ErrorLevel;
|
||||
constructor(opts?: SitemapItemStreamOptions);
|
||||
_transform(item: SitemapItem, encoding: string, callback: TransformCallback): void;
|
||||
}
|
||||
204
node_modules/sitemap/dist/esm/lib/sitemap-item-stream.js
generated
vendored
Normal file
204
node_modules/sitemap/dist/esm/lib/sitemap-item-stream.js
generated
vendored
Normal file
@@ -0,0 +1,204 @@
|
||||
import { Transform } from 'node:stream';
|
||||
import { InvalidAttr } from './errors.js';
|
||||
import { ErrorLevel, TagNames } from './types.js';
|
||||
import { element, otag, ctag } from './sitemap-xml.js';
|
||||
/**
|
||||
* Builds an attributes object for XML elements from configuration object
|
||||
* Extracts attributes based on colon-delimited keys (e.g., 'price:currency' -> { currency: value })
|
||||
*
|
||||
* @param conf - Configuration object containing attribute values
|
||||
* @param keys - Single key or array of keys in format 'namespace:attribute'
|
||||
* @returns Record of attribute names to string values (may contain non-string values from conf)
|
||||
* @throws {InvalidAttr} When key format is invalid (must contain exactly one colon)
|
||||
*
|
||||
* @example
|
||||
* attrBuilder({ 'price:currency': 'USD', 'price:type': 'rent' }, ['price:currency', 'price:type'])
|
||||
* // Returns: { currency: 'USD', type: 'rent' }
|
||||
*/
|
||||
function attrBuilder(conf, keys) {
|
||||
if (typeof keys === 'string') {
|
||||
keys = [keys];
|
||||
}
|
||||
const iv = {};
|
||||
return keys.reduce((attrs, key) => {
|
||||
if (conf[key] !== undefined) {
|
||||
const keyAr = key.split(':');
|
||||
if (keyAr.length !== 2) {
|
||||
throw new InvalidAttr(key);
|
||||
}
|
||||
attrs[keyAr[1]] = conf[key];
|
||||
}
|
||||
return attrs;
|
||||
}, iv);
|
||||
}
|
||||
/**
|
||||
* Takes a stream of SitemapItemOptions and spits out xml for each
|
||||
* @example
|
||||
* // writes <url><loc>https://example.com</loc><url><url><loc>https://example.com/2</loc><url>
|
||||
* const smis = new SitemapItemStream({level: 'warn'})
|
||||
* smis.pipe(writestream)
|
||||
* smis.write({url: 'https://example.com', img: [], video: [], links: []})
|
||||
* smis.write({url: 'https://example.com/2', img: [], video: [], links: []})
|
||||
* smis.end()
|
||||
* @param level - Error level
|
||||
*/
|
||||
export class SitemapItemStream extends Transform {
|
||||
level;
|
||||
constructor(opts = { level: ErrorLevel.WARN }) {
|
||||
opts.objectMode = true;
|
||||
super(opts);
|
||||
this.level = opts.level || ErrorLevel.WARN;
|
||||
}
|
||||
_transform(item, encoding, callback) {
|
||||
this.push(otag(TagNames.url));
|
||||
this.push(element(TagNames.loc, item.url));
|
||||
if (item.lastmod) {
|
||||
this.push(element(TagNames.lastmod, item.lastmod));
|
||||
}
|
||||
if (item.changefreq) {
|
||||
this.push(element(TagNames.changefreq, item.changefreq));
|
||||
}
|
||||
if (item.priority !== undefined && item.priority !== null) {
|
||||
if (item.fullPrecisionPriority) {
|
||||
this.push(element(TagNames.priority, item.priority.toString()));
|
||||
}
|
||||
else {
|
||||
this.push(element(TagNames.priority, item.priority.toFixed(1)));
|
||||
}
|
||||
}
|
||||
item.video.forEach((video) => {
|
||||
this.push(otag(TagNames['video:video']));
|
||||
this.push(element(TagNames['video:thumbnail_loc'], video.thumbnail_loc));
|
||||
this.push(element(TagNames['video:title'], video.title));
|
||||
this.push(element(TagNames['video:description'], video.description));
|
||||
if (video.content_loc) {
|
||||
this.push(element(TagNames['video:content_loc'], video.content_loc));
|
||||
}
|
||||
if (video.player_loc) {
|
||||
this.push(element(TagNames['video:player_loc'], attrBuilder(video, [
|
||||
'player_loc:autoplay',
|
||||
'player_loc:allow_embed',
|
||||
]), video.player_loc));
|
||||
}
|
||||
if (video.duration) {
|
||||
this.push(element(TagNames['video:duration'], video.duration.toString()));
|
||||
}
|
||||
if (video.expiration_date) {
|
||||
this.push(element(TagNames['video:expiration_date'], video.expiration_date));
|
||||
}
|
||||
if (video.rating !== undefined) {
|
||||
this.push(element(TagNames['video:rating'], video.rating.toString()));
|
||||
}
|
||||
if (video.view_count !== undefined) {
|
||||
this.push(element(TagNames['video:view_count'], String(video.view_count)));
|
||||
}
|
||||
if (video.publication_date) {
|
||||
this.push(element(TagNames['video:publication_date'], video.publication_date));
|
||||
}
|
||||
if (video.tag && video.tag.length > 0) {
|
||||
for (const tag of video.tag) {
|
||||
this.push(element(TagNames['video:tag'], tag));
|
||||
}
|
||||
}
|
||||
if (video.category) {
|
||||
this.push(element(TagNames['video:category'], video.category));
|
||||
}
|
||||
if (video.family_friendly) {
|
||||
this.push(element(TagNames['video:family_friendly'], video.family_friendly));
|
||||
}
|
||||
if (video.restriction) {
|
||||
this.push(element(TagNames['video:restriction'], attrBuilder(video, 'restriction:relationship'), video.restriction));
|
||||
}
|
||||
if (video.gallery_loc) {
|
||||
this.push(element(TagNames['video:gallery_loc'], attrBuilder(video, 'gallery_loc:title'), video.gallery_loc));
|
||||
}
|
||||
if (video.price) {
|
||||
this.push(element(TagNames['video:price'], attrBuilder(video, [
|
||||
'price:resolution',
|
||||
'price:currency',
|
||||
'price:type',
|
||||
]), video.price));
|
||||
}
|
||||
if (video.requires_subscription) {
|
||||
this.push(element(TagNames['video:requires_subscription'], video.requires_subscription));
|
||||
}
|
||||
if (video.uploader) {
|
||||
this.push(element(TagNames['video:uploader'], attrBuilder(video, 'uploader:info'), video.uploader));
|
||||
}
|
||||
if (video.platform) {
|
||||
this.push(element(TagNames['video:platform'], attrBuilder(video, 'platform:relationship'), video.platform));
|
||||
}
|
||||
if (video.live) {
|
||||
this.push(element(TagNames['video:live'], video.live));
|
||||
}
|
||||
if (video.id) {
|
||||
this.push(element(TagNames['video:id'], { type: 'url' }, video.id));
|
||||
}
|
||||
this.push(ctag(TagNames['video:video']));
|
||||
});
|
||||
item.links.forEach((link) => {
|
||||
this.push(element(TagNames['xhtml:link'], {
|
||||
rel: 'alternate',
|
||||
hreflang: link.lang || link.hreflang,
|
||||
href: link.url,
|
||||
}));
|
||||
});
|
||||
if (item.expires) {
|
||||
this.push(element(TagNames.expires, new Date(item.expires).toISOString()));
|
||||
}
|
||||
if (item.androidLink) {
|
||||
this.push(element(TagNames['xhtml:link'], {
|
||||
rel: 'alternate',
|
||||
href: item.androidLink,
|
||||
}));
|
||||
}
|
||||
if (item.ampLink) {
|
||||
this.push(element(TagNames['xhtml:link'], {
|
||||
rel: 'amphtml',
|
||||
href: item.ampLink,
|
||||
}));
|
||||
}
|
||||
if (item.news) {
|
||||
this.push(otag(TagNames['news:news']));
|
||||
this.push(otag(TagNames['news:publication']));
|
||||
this.push(element(TagNames['news:name'], item.news.publication.name));
|
||||
this.push(element(TagNames['news:language'], item.news.publication.language));
|
||||
this.push(ctag(TagNames['news:publication']));
|
||||
if (item.news.access) {
|
||||
this.push(element(TagNames['news:access'], item.news.access));
|
||||
}
|
||||
if (item.news.genres) {
|
||||
this.push(element(TagNames['news:genres'], item.news.genres));
|
||||
}
|
||||
this.push(element(TagNames['news:publication_date'], item.news.publication_date));
|
||||
this.push(element(TagNames['news:title'], item.news.title));
|
||||
if (item.news.keywords) {
|
||||
this.push(element(TagNames['news:keywords'], item.news.keywords));
|
||||
}
|
||||
if (item.news.stock_tickers) {
|
||||
this.push(element(TagNames['news:stock_tickers'], item.news.stock_tickers));
|
||||
}
|
||||
this.push(ctag(TagNames['news:news']));
|
||||
}
|
||||
// Image handling
|
||||
item.img.forEach((image) => {
|
||||
this.push(otag(TagNames['image:image']));
|
||||
this.push(element(TagNames['image:loc'], image.url));
|
||||
if (image.caption) {
|
||||
this.push(element(TagNames['image:caption'], image.caption));
|
||||
}
|
||||
if (image.geoLocation) {
|
||||
this.push(element(TagNames['image:geo_location'], image.geoLocation));
|
||||
}
|
||||
if (image.title) {
|
||||
this.push(element(TagNames['image:title'], image.title));
|
||||
}
|
||||
if (image.license) {
|
||||
this.push(element(TagNames['image:license'], image.license));
|
||||
}
|
||||
this.push(ctag(TagNames['image:image']));
|
||||
});
|
||||
this.push(ctag(TagNames.url));
|
||||
callback();
|
||||
}
|
||||
}
|
||||
62
node_modules/sitemap/dist/esm/lib/sitemap-parser.d.ts
generated
vendored
Normal file
62
node_modules/sitemap/dist/esm/lib/sitemap-parser.d.ts
generated
vendored
Normal file
@@ -0,0 +1,62 @@
|
||||
import type { SAXStream } from 'sax';
|
||||
import { Readable, Transform, TransformOptions, TransformCallback } from 'node:stream';
|
||||
import { SitemapItem, ErrorLevel } from './types.js';
|
||||
type Logger = (level: 'warn' | 'error' | 'info' | 'log', ...message: Parameters<Console['log']>[0]) => void;
|
||||
export interface XMLToSitemapItemStreamOptions extends TransformOptions {
|
||||
level?: ErrorLevel;
|
||||
logger?: Logger | false;
|
||||
}
|
||||
/**
|
||||
* Takes a stream of xml and transforms it into a stream of SitemapItems
|
||||
* Use this to parse existing sitemaps into config options compatible with this library
|
||||
*/
|
||||
export declare class XMLToSitemapItemStream extends Transform {
|
||||
level: ErrorLevel;
|
||||
logger: Logger;
|
||||
/**
|
||||
* Errors encountered during parsing, capped at LIMITS.MAX_PARSER_ERRORS entries
|
||||
* to prevent memory DoS from malformed XML (BB-03).
|
||||
* Use errorCount for the total number of errors regardless of the cap.
|
||||
*/
|
||||
errors: Error[];
|
||||
/** Total number of errors seen, including those beyond the stored cap. */
|
||||
errorCount: number;
|
||||
saxStream: SAXStream;
|
||||
urlCount: number;
|
||||
constructor(opts?: XMLToSitemapItemStreamOptions);
|
||||
_transform(data: string, encoding: string, callback: TransformCallback): void;
|
||||
private err;
|
||||
}
|
||||
/**
|
||||
Read xml and resolve with the configuration that would produce it or reject with
|
||||
an error
|
||||
```
|
||||
const { createReadStream } = require('fs')
|
||||
const { parseSitemap, createSitemap } = require('sitemap')
|
||||
parseSitemap(createReadStream('./example.xml')).then(
|
||||
// produces the same xml
|
||||
// you can, of course, more practically modify it or store it
|
||||
(xmlConfig) => console.log(createSitemap(xmlConfig).toString()),
|
||||
(err) => console.log(err)
|
||||
)
|
||||
```
|
||||
@param {Readable} xml what to parse
|
||||
@return {Promise<SitemapItem[]>} resolves with list of sitemap items that can be fed into a SitemapStream. Rejects with an Error object.
|
||||
*/
|
||||
export declare function parseSitemap(xml: Readable): Promise<SitemapItem[]>;
|
||||
export interface ObjectStreamToJSONOptions extends TransformOptions {
|
||||
lineSeparated: boolean;
|
||||
}
|
||||
/**
|
||||
* A Transform that converts a stream of objects into a JSON Array or a line
|
||||
* separated stringified JSON
|
||||
* @param [lineSeparated=false] whether to separate entries by a new line or comma
|
||||
*/
|
||||
export declare class ObjectStreamToJSON extends Transform {
|
||||
lineSeparated: boolean;
|
||||
firstWritten: boolean;
|
||||
constructor(opts?: ObjectStreamToJSONOptions);
|
||||
_transform(chunk: SitemapItem, encoding: string, cb: TransformCallback): void;
|
||||
_flush(cb: TransformCallback): void;
|
||||
}
|
||||
export {};
|
||||
779
node_modules/sitemap/dist/esm/lib/sitemap-parser.js
generated
vendored
Normal file
779
node_modules/sitemap/dist/esm/lib/sitemap-parser.js
generated
vendored
Normal file
@@ -0,0 +1,779 @@
|
||||
import sax from 'sax';
|
||||
import { Transform, } from 'node:stream';
|
||||
import { ErrorLevel, TagNames, } from './types.js';
|
||||
import { isValidChangeFreq, isValidYesNo, isAllowDeny, isPriceType, isResolution, } from './validation.js';
|
||||
import { LIMITS } from './constants.js';
|
||||
function isValidTagName(tagName) {
|
||||
// This only works because the enum name and value are the same
|
||||
return tagName in TagNames;
|
||||
}
|
||||
function getAttrValue(attr) {
|
||||
if (!attr)
|
||||
return undefined;
|
||||
return typeof attr === 'string' ? attr : attr.value;
|
||||
}
|
||||
function tagTemplate() {
|
||||
return {
|
||||
img: [],
|
||||
video: [],
|
||||
links: [],
|
||||
url: '',
|
||||
};
|
||||
}
|
||||
function videoTemplate() {
|
||||
return {
|
||||
tag: [],
|
||||
thumbnail_loc: '',
|
||||
title: '',
|
||||
description: '',
|
||||
};
|
||||
}
|
||||
const imageTemplate = {
|
||||
url: '',
|
||||
};
|
||||
const linkTemplate = {
|
||||
lang: '',
|
||||
url: '',
|
||||
};
|
||||
function newsTemplate() {
|
||||
return {
|
||||
publication: { name: '', language: '' },
|
||||
publication_date: '',
|
||||
title: '',
|
||||
};
|
||||
}
|
||||
const defaultLogger = (level, ...message) => console[level](...message);
|
||||
const defaultStreamOpts = {
|
||||
logger: defaultLogger,
|
||||
};
|
||||
// TODO does this need to end with `options`
|
||||
/**
|
||||
* Takes a stream of xml and transforms it into a stream of SitemapItems
|
||||
* Use this to parse existing sitemaps into config options compatible with this library
|
||||
*/
|
||||
export class XMLToSitemapItemStream extends Transform {
|
||||
level;
|
||||
logger;
|
||||
/**
|
||||
* Errors encountered during parsing, capped at LIMITS.MAX_PARSER_ERRORS entries
|
||||
* to prevent memory DoS from malformed XML (BB-03).
|
||||
* Use errorCount for the total number of errors regardless of the cap.
|
||||
*/
|
||||
errors;
|
||||
/** Total number of errors seen, including those beyond the stored cap. */
|
||||
errorCount;
|
||||
saxStream;
|
||||
urlCount;
|
||||
constructor(opts = defaultStreamOpts) {
|
||||
opts.objectMode = true;
|
||||
super(opts);
|
||||
this.errors = [];
|
||||
this.errorCount = 0;
|
||||
this.urlCount = 0;
|
||||
this.saxStream = sax.createStream(true, {
|
||||
xmlns: true,
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
strictEntities: true,
|
||||
trim: true,
|
||||
});
|
||||
this.level = opts.level || ErrorLevel.WARN;
|
||||
if (this.level !== ErrorLevel.SILENT && opts.logger !== false) {
|
||||
this.logger = opts.logger ?? defaultLogger;
|
||||
}
|
||||
else {
|
||||
this.logger = () => undefined;
|
||||
}
|
||||
let currentItem = tagTemplate();
|
||||
let currentTag;
|
||||
let currentVideo = videoTemplate();
|
||||
let currentImage = { ...imageTemplate };
|
||||
let currentLink = { ...linkTemplate };
|
||||
let dontpushCurrentLink = false;
|
||||
this.saxStream.on('opentagstart', (tag) => {
|
||||
currentTag = tag.name;
|
||||
if (currentTag.startsWith('news:') && !currentItem.news) {
|
||||
currentItem.news = newsTemplate();
|
||||
}
|
||||
});
|
||||
this.saxStream.on('opentag', (tag) => {
|
||||
if (isValidTagName(tag.name)) {
|
||||
if (tag.name === 'xhtml:link') {
|
||||
// SAX returns attributes as objects with {name, value, prefix, local, uri}
|
||||
// Check if required attributes exist and have values
|
||||
const rel = getAttrValue(tag.attributes.rel);
|
||||
const href = getAttrValue(tag.attributes.href);
|
||||
const hreflang = getAttrValue(tag.attributes.hreflang);
|
||||
if (!rel || !href) {
|
||||
this.logger('warn', 'xhtml:link missing required rel or href attribute');
|
||||
this.err('xhtml:link missing required rel or href attribute');
|
||||
return;
|
||||
}
|
||||
if (rel === 'alternate' && hreflang) {
|
||||
currentLink.url = href;
|
||||
currentLink.lang = hreflang;
|
||||
}
|
||||
else if (rel === 'alternate') {
|
||||
dontpushCurrentLink = true;
|
||||
currentItem.androidLink = href;
|
||||
}
|
||||
else if (rel === 'amphtml') {
|
||||
dontpushCurrentLink = true;
|
||||
currentItem.ampLink = href;
|
||||
}
|
||||
else {
|
||||
this.logger('log', 'unhandled attr for xhtml:link', tag.attributes);
|
||||
this.err(`unhandled attr for xhtml:link ${JSON.stringify(tag.attributes)}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
this.logger('warn', 'unhandled tag', tag.name);
|
||||
this.err(`unhandled tag: ${tag.name}`);
|
||||
}
|
||||
});
|
||||
this.saxStream.on('text', (text) => {
|
||||
switch (currentTag) {
|
||||
case 'mobile:mobile':
|
||||
break;
|
||||
case TagNames.loc:
|
||||
// Validate URL
|
||||
if (text.length > LIMITS.MAX_URL_LENGTH) {
|
||||
this.logger('warn', `URL exceeds max length of ${LIMITS.MAX_URL_LENGTH}: ${text.substring(0, 100)}...`);
|
||||
this.err(`URL exceeds max length of ${LIMITS.MAX_URL_LENGTH}`);
|
||||
}
|
||||
else if (!LIMITS.URL_PROTOCOL_REGEX.test(text)) {
|
||||
this.logger('warn', `URL must start with http:// or https://: ${text}`);
|
||||
this.err(`URL must start with http:// or https://: ${text}`);
|
||||
}
|
||||
else {
|
||||
currentItem.url = text;
|
||||
}
|
||||
break;
|
||||
case TagNames.changefreq:
|
||||
if (isValidChangeFreq(text)) {
|
||||
currentItem.changefreq = text;
|
||||
}
|
||||
break;
|
||||
case TagNames.priority:
|
||||
{
|
||||
const priority = parseFloat(text);
|
||||
if (isNaN(priority) ||
|
||||
!isFinite(priority) ||
|
||||
priority < 0 ||
|
||||
priority > 1) {
|
||||
this.logger('warn', `Invalid priority "${text}" - must be between 0 and 1`);
|
||||
this.err(`Invalid priority "${text}" - must be between 0 and 1`);
|
||||
}
|
||||
else {
|
||||
currentItem.priority = priority;
|
||||
}
|
||||
}
|
||||
break;
|
||||
case TagNames.lastmod:
|
||||
if (LIMITS.ISO_DATE_REGEX.test(text)) {
|
||||
currentItem.lastmod = text;
|
||||
}
|
||||
else {
|
||||
this.logger('warn', `Invalid lastmod date format "${text}" - expected ISO 8601 format`);
|
||||
this.err(`Invalid lastmod date format "${text}" - expected ISO 8601 format`);
|
||||
}
|
||||
break;
|
||||
case TagNames['video:thumbnail_loc']:
|
||||
currentVideo.thumbnail_loc = text;
|
||||
break;
|
||||
case TagNames['video:tag']:
|
||||
if (currentVideo.tag.length < LIMITS.MAX_TAGS_PER_VIDEO) {
|
||||
currentVideo.tag.push(text);
|
||||
}
|
||||
else {
|
||||
this.logger('warn', `video has too many tags (max ${LIMITS.MAX_TAGS_PER_VIDEO})`);
|
||||
this.err(`video has too many tags (max ${LIMITS.MAX_TAGS_PER_VIDEO})`);
|
||||
}
|
||||
break;
|
||||
case TagNames['video:duration']:
|
||||
{
|
||||
const duration = parseInt(text, 10);
|
||||
if (isNaN(duration) ||
|
||||
!isFinite(duration) ||
|
||||
duration < 0 ||
|
||||
duration > 28800) {
|
||||
this.logger('warn', `Invalid video duration "${text}" - must be between 0 and 28800 seconds`);
|
||||
this.err(`Invalid video duration "${text}" - must be between 0 and 28800 seconds`);
|
||||
}
|
||||
else {
|
||||
currentVideo.duration = duration;
|
||||
}
|
||||
}
|
||||
break;
|
||||
case TagNames['video:player_loc']:
|
||||
currentVideo.player_loc = text;
|
||||
break;
|
||||
case TagNames['video:content_loc']:
|
||||
currentVideo.content_loc = text;
|
||||
break;
|
||||
case TagNames['video:requires_subscription']:
|
||||
if (isValidYesNo(text)) {
|
||||
currentVideo.requires_subscription = text;
|
||||
}
|
||||
break;
|
||||
case TagNames['video:publication_date']:
|
||||
if (LIMITS.ISO_DATE_REGEX.test(text)) {
|
||||
currentVideo.publication_date = text;
|
||||
}
|
||||
else {
|
||||
this.logger('warn', `Invalid video publication_date format "${text}" - expected ISO 8601 format`);
|
||||
this.err(`Invalid video publication_date format "${text}" - expected ISO 8601 format`);
|
||||
}
|
||||
break;
|
||||
case TagNames['video:id']:
|
||||
currentVideo.id = text;
|
||||
break;
|
||||
case TagNames['video:restriction']:
|
||||
currentVideo.restriction = text;
|
||||
break;
|
||||
case TagNames['video:view_count']:
|
||||
{
|
||||
const viewCount = parseInt(text, 10);
|
||||
if (isNaN(viewCount) || !isFinite(viewCount) || viewCount < 0) {
|
||||
this.logger('warn', `Invalid video view_count "${text}" - must be a positive integer`);
|
||||
this.err(`Invalid video view_count "${text}" - must be a positive integer`);
|
||||
}
|
||||
else {
|
||||
currentVideo.view_count = viewCount;
|
||||
}
|
||||
}
|
||||
break;
|
||||
case TagNames['video:uploader']:
|
||||
currentVideo.uploader = text;
|
||||
break;
|
||||
case TagNames['video:family_friendly']:
|
||||
if (isValidYesNo(text)) {
|
||||
currentVideo.family_friendly = text;
|
||||
}
|
||||
break;
|
||||
case TagNames['video:expiration_date']:
|
||||
if (LIMITS.ISO_DATE_REGEX.test(text)) {
|
||||
currentVideo.expiration_date = text;
|
||||
}
|
||||
else {
|
||||
this.logger('warn', `Invalid video expiration_date format "${text}" - expected ISO 8601 format`);
|
||||
this.err(`Invalid video expiration_date format "${text}" - expected ISO 8601 format`);
|
||||
}
|
||||
break;
|
||||
case TagNames['video:platform']:
|
||||
currentVideo.platform = text;
|
||||
break;
|
||||
case TagNames['video:price']:
|
||||
currentVideo.price = text;
|
||||
break;
|
||||
case TagNames['video:rating']:
|
||||
{
|
||||
const rating = parseFloat(text);
|
||||
if (isNaN(rating) ||
|
||||
!isFinite(rating) ||
|
||||
rating < 0 ||
|
||||
rating > 5) {
|
||||
this.logger('warn', `Invalid video rating "${text}" - must be between 0 and 5`);
|
||||
this.err(`Invalid video rating "${text}" - must be between 0 and 5`);
|
||||
}
|
||||
else {
|
||||
currentVideo.rating = rating;
|
||||
}
|
||||
}
|
||||
break;
|
||||
case TagNames['video:category']:
|
||||
currentVideo.category = text;
|
||||
break;
|
||||
case TagNames['video:live']:
|
||||
if (isValidYesNo(text)) {
|
||||
currentVideo.live = text;
|
||||
}
|
||||
break;
|
||||
case TagNames['video:gallery_loc']:
|
||||
currentVideo.gallery_loc = text;
|
||||
break;
|
||||
case TagNames['image:loc']:
|
||||
currentImage.url = text;
|
||||
break;
|
||||
case TagNames['image:geo_location']:
|
||||
currentImage.geoLocation = text;
|
||||
break;
|
||||
case TagNames['image:license']:
|
||||
currentImage.license = text;
|
||||
break;
|
||||
case TagNames['news:access']:
|
||||
if (!currentItem.news) {
|
||||
currentItem.news = newsTemplate();
|
||||
}
|
||||
if (text === 'Registration' || text === 'Subscription') {
|
||||
currentItem.news.access = text;
|
||||
}
|
||||
else {
|
||||
this.logger('warn', `Invalid news:access value "${text}" - must be "Registration" or "Subscription"`);
|
||||
this.err(`Invalid news:access value "${text}" - must be "Registration" or "Subscription"`);
|
||||
}
|
||||
break;
|
||||
case TagNames['news:genres']:
|
||||
if (!currentItem.news) {
|
||||
currentItem.news = newsTemplate();
|
||||
}
|
||||
currentItem.news.genres = text;
|
||||
break;
|
||||
case TagNames['news:publication_date']:
|
||||
if (!currentItem.news) {
|
||||
currentItem.news = newsTemplate();
|
||||
}
|
||||
if (LIMITS.ISO_DATE_REGEX.test(text)) {
|
||||
currentItem.news.publication_date = text;
|
||||
}
|
||||
else {
|
||||
this.logger('warn', `Invalid news publication_date format "${text}" - expected ISO 8601 format`);
|
||||
this.err(`Invalid news publication_date format "${text}" - expected ISO 8601 format`);
|
||||
}
|
||||
break;
|
||||
case TagNames['news:keywords']:
|
||||
if (!currentItem.news) {
|
||||
currentItem.news = newsTemplate();
|
||||
}
|
||||
currentItem.news.keywords = text;
|
||||
break;
|
||||
case TagNames['news:stock_tickers']:
|
||||
if (!currentItem.news) {
|
||||
currentItem.news = newsTemplate();
|
||||
}
|
||||
currentItem.news.stock_tickers = text;
|
||||
break;
|
||||
case TagNames['news:language']:
|
||||
if (!currentItem.news) {
|
||||
currentItem.news = newsTemplate();
|
||||
}
|
||||
currentItem.news.publication.language = text;
|
||||
break;
|
||||
case TagNames['video:title']:
|
||||
if (currentVideo.title.length + text.length <=
|
||||
LIMITS.MAX_VIDEO_TITLE_LENGTH) {
|
||||
currentVideo.title += text;
|
||||
}
|
||||
else {
|
||||
this.logger('warn', `video title exceeds max length of ${LIMITS.MAX_VIDEO_TITLE_LENGTH}`);
|
||||
this.err(`video title exceeds max length of ${LIMITS.MAX_VIDEO_TITLE_LENGTH}`);
|
||||
}
|
||||
break;
|
||||
case TagNames['video:description']:
|
||||
if (currentVideo.description.length + text.length <=
|
||||
LIMITS.MAX_VIDEO_DESCRIPTION_LENGTH) {
|
||||
currentVideo.description += text;
|
||||
}
|
||||
else {
|
||||
this.logger('warn', `video description exceeds max length of ${LIMITS.MAX_VIDEO_DESCRIPTION_LENGTH}`);
|
||||
this.err(`video description exceeds max length of ${LIMITS.MAX_VIDEO_DESCRIPTION_LENGTH}`);
|
||||
}
|
||||
break;
|
||||
case TagNames['news:name']:
|
||||
if (!currentItem.news) {
|
||||
currentItem.news = newsTemplate();
|
||||
}
|
||||
if (currentItem.news.publication.name.length + text.length <=
|
||||
LIMITS.MAX_NEWS_NAME_LENGTH) {
|
||||
currentItem.news.publication.name += text;
|
||||
}
|
||||
else {
|
||||
this.logger('warn', `news name exceeds max length of ${LIMITS.MAX_NEWS_NAME_LENGTH}`);
|
||||
this.err(`news name exceeds max length of ${LIMITS.MAX_NEWS_NAME_LENGTH}`);
|
||||
}
|
||||
break;
|
||||
case TagNames['news:title']:
|
||||
if (!currentItem.news) {
|
||||
currentItem.news = newsTemplate();
|
||||
}
|
||||
if (currentItem.news.title.length + text.length <=
|
||||
LIMITS.MAX_NEWS_TITLE_LENGTH) {
|
||||
currentItem.news.title += text;
|
||||
}
|
||||
else {
|
||||
this.logger('warn', `news title exceeds max length of ${LIMITS.MAX_NEWS_TITLE_LENGTH}`);
|
||||
this.err(`news title exceeds max length of ${LIMITS.MAX_NEWS_TITLE_LENGTH}`);
|
||||
}
|
||||
break;
|
||||
case TagNames['image:caption']:
|
||||
if (!currentImage.caption) {
|
||||
currentImage.caption =
|
||||
text.length <= LIMITS.MAX_IMAGE_CAPTION_LENGTH
|
||||
? text
|
||||
: text.substring(0, LIMITS.MAX_IMAGE_CAPTION_LENGTH);
|
||||
if (text.length > LIMITS.MAX_IMAGE_CAPTION_LENGTH) {
|
||||
this.logger('warn', `image caption exceeds max length of ${LIMITS.MAX_IMAGE_CAPTION_LENGTH}`);
|
||||
this.err(`image caption exceeds max length of ${LIMITS.MAX_IMAGE_CAPTION_LENGTH}`);
|
||||
}
|
||||
}
|
||||
else if (currentImage.caption.length + text.length <=
|
||||
LIMITS.MAX_IMAGE_CAPTION_LENGTH) {
|
||||
currentImage.caption += text;
|
||||
}
|
||||
else {
|
||||
this.logger('warn', `image caption exceeds max length of ${LIMITS.MAX_IMAGE_CAPTION_LENGTH}`);
|
||||
this.err(`image caption exceeds max length of ${LIMITS.MAX_IMAGE_CAPTION_LENGTH}`);
|
||||
}
|
||||
break;
|
||||
case TagNames['image:title']:
|
||||
if (!currentImage.title) {
|
||||
currentImage.title =
|
||||
text.length <= LIMITS.MAX_IMAGE_TITLE_LENGTH
|
||||
? text
|
||||
: text.substring(0, LIMITS.MAX_IMAGE_TITLE_LENGTH);
|
||||
if (text.length > LIMITS.MAX_IMAGE_TITLE_LENGTH) {
|
||||
this.logger('warn', `image title exceeds max length of ${LIMITS.MAX_IMAGE_TITLE_LENGTH}`);
|
||||
this.err(`image title exceeds max length of ${LIMITS.MAX_IMAGE_TITLE_LENGTH}`);
|
||||
}
|
||||
}
|
||||
else if (currentImage.title.length + text.length <=
|
||||
LIMITS.MAX_IMAGE_TITLE_LENGTH) {
|
||||
currentImage.title += text;
|
||||
}
|
||||
else {
|
||||
this.logger('warn', `image title exceeds max length of ${LIMITS.MAX_IMAGE_TITLE_LENGTH}`);
|
||||
this.err(`image title exceeds max length of ${LIMITS.MAX_IMAGE_TITLE_LENGTH}`);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
this.logger('log', 'unhandled text for tag:', currentTag, `'${text}'`);
|
||||
this.err(`unhandled text for tag: ${currentTag} '${text}'`);
|
||||
break;
|
||||
}
|
||||
});
|
||||
this.saxStream.on('cdata', (text) => {
|
||||
switch (currentTag) {
|
||||
case TagNames.loc:
|
||||
// Validate URL
|
||||
if (text.length > LIMITS.MAX_URL_LENGTH) {
|
||||
this.logger('warn', `URL exceeds max length of ${LIMITS.MAX_URL_LENGTH}: ${text.substring(0, 100)}...`);
|
||||
this.err(`URL exceeds max length of ${LIMITS.MAX_URL_LENGTH}`);
|
||||
}
|
||||
else if (!LIMITS.URL_PROTOCOL_REGEX.test(text)) {
|
||||
this.logger('warn', `URL must start with http:// or https://: ${text}`);
|
||||
this.err(`URL must start with http:// or https://: ${text}`);
|
||||
}
|
||||
else {
|
||||
currentItem.url = text;
|
||||
}
|
||||
break;
|
||||
case TagNames['image:loc']:
|
||||
currentImage.url = text;
|
||||
break;
|
||||
case TagNames['video:title']:
|
||||
if (currentVideo.title.length + text.length <=
|
||||
LIMITS.MAX_VIDEO_TITLE_LENGTH) {
|
||||
currentVideo.title += text;
|
||||
}
|
||||
else {
|
||||
this.logger('warn', `video title exceeds max length of ${LIMITS.MAX_VIDEO_TITLE_LENGTH}`);
|
||||
this.err(`video title exceeds max length of ${LIMITS.MAX_VIDEO_TITLE_LENGTH}`);
|
||||
}
|
||||
break;
|
||||
case TagNames['video:description']:
|
||||
if (currentVideo.description.length + text.length <=
|
||||
LIMITS.MAX_VIDEO_DESCRIPTION_LENGTH) {
|
||||
currentVideo.description += text;
|
||||
}
|
||||
else {
|
||||
this.logger('warn', `video description exceeds max length of ${LIMITS.MAX_VIDEO_DESCRIPTION_LENGTH}`);
|
||||
this.err(`video description exceeds max length of ${LIMITS.MAX_VIDEO_DESCRIPTION_LENGTH}`);
|
||||
}
|
||||
break;
|
||||
case TagNames['news:name']:
|
||||
if (!currentItem.news) {
|
||||
currentItem.news = newsTemplate();
|
||||
}
|
||||
if (currentItem.news.publication.name.length + text.length <=
|
||||
LIMITS.MAX_NEWS_NAME_LENGTH) {
|
||||
currentItem.news.publication.name += text;
|
||||
}
|
||||
else {
|
||||
this.logger('warn', `news name exceeds max length of ${LIMITS.MAX_NEWS_NAME_LENGTH}`);
|
||||
this.err(`news name exceeds max length of ${LIMITS.MAX_NEWS_NAME_LENGTH}`);
|
||||
}
|
||||
break;
|
||||
case TagNames['news:title']:
|
||||
if (!currentItem.news) {
|
||||
currentItem.news = newsTemplate();
|
||||
}
|
||||
if (currentItem.news.title.length + text.length <=
|
||||
LIMITS.MAX_NEWS_TITLE_LENGTH) {
|
||||
currentItem.news.title += text;
|
||||
}
|
||||
else {
|
||||
this.logger('warn', `news title exceeds max length of ${LIMITS.MAX_NEWS_TITLE_LENGTH}`);
|
||||
this.err(`news title exceeds max length of ${LIMITS.MAX_NEWS_TITLE_LENGTH}`);
|
||||
}
|
||||
break;
|
||||
case TagNames['image:caption']:
|
||||
if (!currentImage.caption) {
|
||||
currentImage.caption =
|
||||
text.length <= LIMITS.MAX_IMAGE_CAPTION_LENGTH
|
||||
? text
|
||||
: text.substring(0, LIMITS.MAX_IMAGE_CAPTION_LENGTH);
|
||||
if (text.length > LIMITS.MAX_IMAGE_CAPTION_LENGTH) {
|
||||
this.logger('warn', `image caption exceeds max length of ${LIMITS.MAX_IMAGE_CAPTION_LENGTH}`);
|
||||
this.err(`image caption exceeds max length of ${LIMITS.MAX_IMAGE_CAPTION_LENGTH}`);
|
||||
}
|
||||
}
|
||||
else if (currentImage.caption.length + text.length <=
|
||||
LIMITS.MAX_IMAGE_CAPTION_LENGTH) {
|
||||
currentImage.caption += text;
|
||||
}
|
||||
else {
|
||||
this.logger('warn', `image caption exceeds max length of ${LIMITS.MAX_IMAGE_CAPTION_LENGTH}`);
|
||||
this.err(`image caption exceeds max length of ${LIMITS.MAX_IMAGE_CAPTION_LENGTH}`);
|
||||
}
|
||||
break;
|
||||
case TagNames['image:title']:
|
||||
if (!currentImage.title) {
|
||||
currentImage.title =
|
||||
text.length <= LIMITS.MAX_IMAGE_TITLE_LENGTH
|
||||
? text
|
||||
: text.substring(0, LIMITS.MAX_IMAGE_TITLE_LENGTH);
|
||||
if (text.length > LIMITS.MAX_IMAGE_TITLE_LENGTH) {
|
||||
this.logger('warn', `image title exceeds max length of ${LIMITS.MAX_IMAGE_TITLE_LENGTH}`);
|
||||
this.err(`image title exceeds max length of ${LIMITS.MAX_IMAGE_TITLE_LENGTH}`);
|
||||
}
|
||||
}
|
||||
else if (currentImage.title.length + text.length <=
|
||||
LIMITS.MAX_IMAGE_TITLE_LENGTH) {
|
||||
currentImage.title += text;
|
||||
}
|
||||
else {
|
||||
this.logger('warn', `image title exceeds max length of ${LIMITS.MAX_IMAGE_TITLE_LENGTH}`);
|
||||
this.err(`image title exceeds max length of ${LIMITS.MAX_IMAGE_TITLE_LENGTH}`);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
this.logger('log', 'unhandled cdata for tag:', currentTag);
|
||||
this.err(`unhandled cdata for tag: ${currentTag}`);
|
||||
break;
|
||||
}
|
||||
});
|
||||
this.saxStream.on('attribute', (attr) => {
|
||||
switch (currentTag) {
|
||||
case TagNames['urlset']:
|
||||
case TagNames['xhtml:link']:
|
||||
case TagNames['video:id']:
|
||||
break;
|
||||
case TagNames['video:restriction']:
|
||||
if (attr.name === 'relationship' && isAllowDeny(attr.value)) {
|
||||
currentVideo['restriction:relationship'] = attr.value;
|
||||
}
|
||||
else {
|
||||
this.logger('log', 'unhandled attr', currentTag, attr.name);
|
||||
this.err(`unhandled attr: ${currentTag} ${attr.name}`);
|
||||
}
|
||||
break;
|
||||
case TagNames['video:price']:
|
||||
if (attr.name === 'type' && isPriceType(attr.value)) {
|
||||
currentVideo['price:type'] = attr.value;
|
||||
}
|
||||
else if (attr.name === 'currency') {
|
||||
currentVideo['price:currency'] = attr.value;
|
||||
}
|
||||
else if (attr.name === 'resolution' && isResolution(attr.value)) {
|
||||
currentVideo['price:resolution'] = attr.value;
|
||||
}
|
||||
else {
|
||||
this.logger('log', 'unhandled attr for video:price', attr.name);
|
||||
this.err(`unhandled attr: ${currentTag} ${attr.name}`);
|
||||
}
|
||||
break;
|
||||
case TagNames['video:player_loc']:
|
||||
if (attr.name === 'autoplay') {
|
||||
currentVideo['player_loc:autoplay'] = attr.value;
|
||||
}
|
||||
else if (attr.name === 'allow_embed' && isValidYesNo(attr.value)) {
|
||||
currentVideo['player_loc:allow_embed'] = attr.value;
|
||||
}
|
||||
else {
|
||||
this.logger('log', 'unhandled attr for video:player_loc', attr.name);
|
||||
this.err(`unhandled attr: ${currentTag} ${attr.name}`);
|
||||
}
|
||||
break;
|
||||
case TagNames['video:platform']:
|
||||
if (attr.name === 'relationship' && isAllowDeny(attr.value)) {
|
||||
currentVideo['platform:relationship'] = attr.value;
|
||||
}
|
||||
else {
|
||||
this.logger('log', 'unhandled attr for video:platform', attr.name, attr.value);
|
||||
this.err(`unhandled attr: ${currentTag} ${attr.name} ${attr.value}`);
|
||||
}
|
||||
break;
|
||||
case TagNames['video:gallery_loc']:
|
||||
if (attr.name === 'title') {
|
||||
currentVideo['gallery_loc:title'] = attr.value;
|
||||
}
|
||||
else {
|
||||
this.logger('log', 'unhandled attr for video:galler_loc', attr.name);
|
||||
this.err(`unhandled attr: ${currentTag} ${attr.name}`);
|
||||
}
|
||||
break;
|
||||
case TagNames['video:uploader']:
|
||||
if (attr.name === 'info') {
|
||||
currentVideo['uploader:info'] = attr.value;
|
||||
}
|
||||
else {
|
||||
this.logger('log', 'unhandled attr for video:uploader', attr.name);
|
||||
this.err(`unhandled attr: ${currentTag} ${attr.name}`);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
this.logger('log', 'unhandled attr', currentTag, attr.name);
|
||||
this.err(`unhandled attr: ${currentTag} ${attr.name}`);
|
||||
}
|
||||
});
|
||||
this.saxStream.on('closetag', (tag) => {
|
||||
switch (tag) {
|
||||
case TagNames.url:
|
||||
this.urlCount++;
|
||||
if (this.urlCount > LIMITS.MAX_URL_ENTRIES) {
|
||||
this.logger('error', `Sitemap exceeds maximum of ${LIMITS.MAX_URL_ENTRIES} URLs`);
|
||||
this.err(`Sitemap exceeds maximum of ${LIMITS.MAX_URL_ENTRIES} URLs`);
|
||||
currentItem = tagTemplate();
|
||||
break;
|
||||
}
|
||||
this.push(currentItem);
|
||||
currentItem = tagTemplate();
|
||||
break;
|
||||
case TagNames['video:video']:
|
||||
if (currentItem.video.length < LIMITS.MAX_VIDEOS_PER_URL) {
|
||||
currentItem.video.push(currentVideo);
|
||||
}
|
||||
else {
|
||||
this.logger('warn', `URL has too many videos (max ${LIMITS.MAX_VIDEOS_PER_URL})`);
|
||||
this.err(`URL has too many videos (max ${LIMITS.MAX_VIDEOS_PER_URL})`);
|
||||
}
|
||||
currentVideo = videoTemplate();
|
||||
break;
|
||||
case TagNames['image:image']:
|
||||
if (currentItem.img.length < LIMITS.MAX_IMAGES_PER_URL) {
|
||||
currentItem.img.push(currentImage);
|
||||
}
|
||||
else {
|
||||
this.logger('warn', `URL has too many images (max ${LIMITS.MAX_IMAGES_PER_URL})`);
|
||||
this.err(`URL has too many images (max ${LIMITS.MAX_IMAGES_PER_URL})`);
|
||||
}
|
||||
currentImage = { ...imageTemplate };
|
||||
break;
|
||||
case TagNames['xhtml:link']:
|
||||
if (!dontpushCurrentLink) {
|
||||
if (currentItem.links.length < LIMITS.MAX_LINKS_PER_URL) {
|
||||
currentItem.links.push(currentLink);
|
||||
}
|
||||
else {
|
||||
this.logger('warn', `URL has too many links (max ${LIMITS.MAX_LINKS_PER_URL})`);
|
||||
this.err(`URL has too many links (max ${LIMITS.MAX_LINKS_PER_URL})`);
|
||||
}
|
||||
}
|
||||
currentLink = { ...linkTemplate };
|
||||
dontpushCurrentLink = false; // Reset flag for next link
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
});
|
||||
}
|
||||
_transform(data, encoding, callback) {
|
||||
try {
|
||||
const cb = () => callback(this.level === ErrorLevel.THROW && this.errors.length > 0
|
||||
? this.errors[0]
|
||||
: null);
|
||||
// correcting the type here can be done without making it a breaking change
|
||||
// TODO fix this
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
if (!this.saxStream.write(data, encoding)) {
|
||||
this.saxStream.once('drain', cb);
|
||||
}
|
||||
else {
|
||||
process.nextTick(cb);
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
callback(error);
|
||||
}
|
||||
}
|
||||
err(msg) {
|
||||
this.errorCount++;
|
||||
if (this.errors.length < LIMITS.MAX_PARSER_ERRORS) {
|
||||
this.errors.push(new Error(msg));
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
Read xml and resolve with the configuration that would produce it or reject with
|
||||
an error
|
||||
```
|
||||
const { createReadStream } = require('fs')
|
||||
const { parseSitemap, createSitemap } = require('sitemap')
|
||||
parseSitemap(createReadStream('./example.xml')).then(
|
||||
// produces the same xml
|
||||
// you can, of course, more practically modify it or store it
|
||||
(xmlConfig) => console.log(createSitemap(xmlConfig).toString()),
|
||||
(err) => console.log(err)
|
||||
)
|
||||
```
|
||||
@param {Readable} xml what to parse
|
||||
@return {Promise<SitemapItem[]>} resolves with list of sitemap items that can be fed into a SitemapStream. Rejects with an Error object.
|
||||
*/
|
||||
export async function parseSitemap(xml) {
|
||||
const urls = [];
|
||||
return new Promise((resolve, reject) => {
|
||||
xml
|
||||
.pipe(new XMLToSitemapItemStream())
|
||||
.on('data', (smi) => urls.push(smi))
|
||||
.on('end', () => {
|
||||
resolve(urls);
|
||||
})
|
||||
.on('error', (error) => {
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
}
|
||||
const defaultObjectStreamOpts = {
|
||||
lineSeparated: false,
|
||||
};
|
||||
/**
|
||||
* A Transform that converts a stream of objects into a JSON Array or a line
|
||||
* separated stringified JSON
|
||||
* @param [lineSeparated=false] whether to separate entries by a new line or comma
|
||||
*/
|
||||
export class ObjectStreamToJSON extends Transform {
|
||||
lineSeparated;
|
||||
firstWritten;
|
||||
constructor(opts = defaultObjectStreamOpts) {
|
||||
opts.writableObjectMode = true;
|
||||
super(opts);
|
||||
this.lineSeparated = opts.lineSeparated;
|
||||
this.firstWritten = false;
|
||||
}
|
||||
_transform(chunk, encoding, cb) {
|
||||
if (!this.firstWritten) {
|
||||
this.firstWritten = true;
|
||||
if (!this.lineSeparated) {
|
||||
this.push('[');
|
||||
}
|
||||
}
|
||||
else if (this.lineSeparated) {
|
||||
this.push('\n');
|
||||
}
|
||||
else {
|
||||
this.push(',');
|
||||
}
|
||||
if (chunk) {
|
||||
this.push(JSON.stringify(chunk));
|
||||
}
|
||||
cb();
|
||||
}
|
||||
_flush(cb) {
|
||||
if (!this.lineSeparated) {
|
||||
this.push(']');
|
||||
}
|
||||
cb();
|
||||
}
|
||||
}
|
||||
63
node_modules/sitemap/dist/esm/lib/sitemap-simple.d.ts
generated
vendored
Normal file
63
node_modules/sitemap/dist/esm/lib/sitemap-simple.d.ts
generated
vendored
Normal file
@@ -0,0 +1,63 @@
|
||||
import { Readable } from 'node:stream';
|
||||
import { SitemapItemLoose } from './types.js';
|
||||
/**
|
||||
* Options for the simpleSitemapAndIndex function
|
||||
*/
|
||||
export interface SimpleSitemapAndIndexOptions {
|
||||
/**
|
||||
* The hostname for all URLs
|
||||
* Must be a valid http:// or https:// URL
|
||||
*/
|
||||
hostname: string;
|
||||
/**
|
||||
* The hostname for the sitemaps if different than hostname
|
||||
* Must be a valid http:// or https:// URL
|
||||
*/
|
||||
sitemapHostname?: string;
|
||||
/**
|
||||
* The urls you want to make a sitemap out of.
|
||||
* Can be an array of items, a file path string, a Readable stream, or an array of strings
|
||||
*/
|
||||
sourceData: SitemapItemLoose[] | string | Readable | string[];
|
||||
/**
|
||||
* Where to write the sitemaps and index
|
||||
* Must be a relative path without path traversal sequences
|
||||
*/
|
||||
destinationDir: string;
|
||||
/**
|
||||
* Where the sitemaps are relative to the hostname. Defaults to root.
|
||||
* Must not contain path traversal sequences
|
||||
*/
|
||||
publicBasePath?: string;
|
||||
/**
|
||||
* How many URLs to write before switching to a new file
|
||||
* Must be between 1 and 50,000 per sitemaps.org spec
|
||||
* @default 50000
|
||||
*/
|
||||
limit?: number;
|
||||
/**
|
||||
* Whether to compress the written files
|
||||
* @default true
|
||||
*/
|
||||
gzip?: boolean;
|
||||
/**
|
||||
* Optional URL to an XSL stylesheet
|
||||
* Must be a valid http:// or https:// URL
|
||||
*/
|
||||
xslUrl?: string;
|
||||
}
|
||||
/**
|
||||
* A simpler interface for creating sitemaps and indexes.
|
||||
* Automatically handles splitting large datasets into multiple sitemap files.
|
||||
*
|
||||
* @param options - Configuration options
|
||||
* @returns A promise that resolves when all sitemaps and the index are written
|
||||
* @throws {InvalidHostnameError} If hostname or sitemapHostname is invalid
|
||||
* @throws {InvalidPathError} If destinationDir contains path traversal
|
||||
* @throws {InvalidPublicBasePathError} If publicBasePath is invalid
|
||||
* @throws {InvalidLimitError} If limit is out of range
|
||||
* @throws {InvalidXSLUrlError} If xslUrl is invalid
|
||||
* @throws {Error} If sourceData type is not supported
|
||||
*/
|
||||
export declare const simpleSitemapAndIndex: ({ hostname, sitemapHostname, sourceData, destinationDir, limit, gzip, publicBasePath, xslUrl, }: SimpleSitemapAndIndexOptions) => Promise<void>;
|
||||
export default simpleSitemapAndIndex;
|
||||
109
node_modules/sitemap/dist/esm/lib/sitemap-simple.js
generated
vendored
Normal file
109
node_modules/sitemap/dist/esm/lib/sitemap-simple.js
generated
vendored
Normal file
@@ -0,0 +1,109 @@
|
||||
import { SitemapAndIndexStream } from './sitemap-index-stream.js';
|
||||
import { SitemapStream } from './sitemap-stream.js';
|
||||
import { lineSeparatedURLsToSitemapOptions } from './utils.js';
|
||||
import { createGzip } from 'node:zlib';
|
||||
import { createWriteStream, createReadStream, promises, } from 'node:fs';
|
||||
import { normalize, resolve } from 'node:path';
|
||||
import { Readable } from 'node:stream';
|
||||
import { pipeline } from 'node:stream/promises';
|
||||
import { URL } from 'node:url';
|
||||
import { validateURL, validatePath, validateLimit, validatePublicBasePath, validateXSLUrl, } from './validation.js';
|
||||
/**
|
||||
* A simpler interface for creating sitemaps and indexes.
|
||||
* Automatically handles splitting large datasets into multiple sitemap files.
|
||||
*
|
||||
* @param options - Configuration options
|
||||
* @returns A promise that resolves when all sitemaps and the index are written
|
||||
* @throws {InvalidHostnameError} If hostname or sitemapHostname is invalid
|
||||
* @throws {InvalidPathError} If destinationDir contains path traversal
|
||||
* @throws {InvalidPublicBasePathError} If publicBasePath is invalid
|
||||
* @throws {InvalidLimitError} If limit is out of range
|
||||
* @throws {InvalidXSLUrlError} If xslUrl is invalid
|
||||
* @throws {Error} If sourceData type is not supported
|
||||
*/
|
||||
export const simpleSitemapAndIndex = async ({ hostname, sitemapHostname = hostname, // if different
|
||||
sourceData, destinationDir, limit = 50000, gzip = true, publicBasePath = './', xslUrl, }) => {
|
||||
// Validate all inputs upfront
|
||||
validateURL(hostname, 'hostname');
|
||||
validateURL(sitemapHostname, 'sitemapHostname');
|
||||
validatePath(destinationDir, 'destinationDir');
|
||||
validateLimit(limit);
|
||||
validatePublicBasePath(publicBasePath);
|
||||
if (xslUrl) {
|
||||
validateXSLUrl(xslUrl);
|
||||
}
|
||||
// Create destination directory with error context
|
||||
try {
|
||||
await promises.mkdir(destinationDir, { recursive: true });
|
||||
}
|
||||
catch (err) {
|
||||
throw new Error(`Failed to create destination directory "${destinationDir}": ${err instanceof Error ? err.message : String(err)}`);
|
||||
}
|
||||
// Normalize publicBasePath (don't mutate the parameter)
|
||||
const normalizedPublicBasePath = publicBasePath.endsWith('/')
|
||||
? publicBasePath
|
||||
: publicBasePath + '/';
|
||||
const sitemapAndIndexStream = new SitemapAndIndexStream({
|
||||
limit,
|
||||
getSitemapStream: (i) => {
|
||||
const sitemapStream = new SitemapStream({
|
||||
hostname,
|
||||
xslUrl,
|
||||
});
|
||||
const path = `./sitemap-${i}.xml`;
|
||||
const writePath = resolve(destinationDir, path + (gzip ? '.gz' : ''));
|
||||
// Construct public path for the sitemap index
|
||||
const publicPath = normalize(normalizedPublicBasePath + path);
|
||||
// Construct the URL with proper error handling
|
||||
let sitemapUrl;
|
||||
try {
|
||||
sitemapUrl = new URL(`${publicPath}${gzip ? '.gz' : ''}`, sitemapHostname).toString();
|
||||
}
|
||||
catch (err) {
|
||||
throw new Error(`Failed to construct sitemap URL for index ${i}: ${err instanceof Error ? err.message : String(err)}`);
|
||||
}
|
||||
let writeStream;
|
||||
if (gzip) {
|
||||
writeStream = sitemapStream
|
||||
.pipe(createGzip()) // compress the output of the sitemap
|
||||
.pipe(createWriteStream(writePath)); // write it to sitemap-NUMBER.xml
|
||||
}
|
||||
else {
|
||||
writeStream = sitemapStream.pipe(createWriteStream(writePath)); // write it to sitemap-NUMBER.xml
|
||||
}
|
||||
return [sitemapUrl, sitemapStream, writeStream];
|
||||
},
|
||||
});
|
||||
// Handle different sourceData types with proper error handling
|
||||
let src;
|
||||
if (typeof sourceData === 'string') {
|
||||
try {
|
||||
src = lineSeparatedURLsToSitemapOptions(createReadStream(sourceData));
|
||||
}
|
||||
catch (err) {
|
||||
throw new Error(`Failed to read sourceData file "${sourceData}": ${err instanceof Error ? err.message : String(err)}`);
|
||||
}
|
||||
}
|
||||
else if (sourceData instanceof Readable) {
|
||||
src = sourceData;
|
||||
}
|
||||
else if (Array.isArray(sourceData)) {
|
||||
src = Readable.from(sourceData);
|
||||
}
|
||||
else {
|
||||
throw new Error(`Invalid sourceData type: expected array, string (file path), or Readable stream, got ${typeof sourceData}`);
|
||||
}
|
||||
const writePath = resolve(destinationDir, `./sitemap-index.xml${gzip ? '.gz' : ''}`);
|
||||
try {
|
||||
if (gzip) {
|
||||
return await pipeline(src, sitemapAndIndexStream, createGzip(), createWriteStream(writePath));
|
||||
}
|
||||
else {
|
||||
return await pipeline(src, sitemapAndIndexStream, createWriteStream(writePath));
|
||||
}
|
||||
}
|
||||
catch (err) {
|
||||
throw new Error(`Failed to write sitemap files: ${err instanceof Error ? err.message : String(err)}`);
|
||||
}
|
||||
};
|
||||
export default simpleSitemapAndIndex;
|
||||
79
node_modules/sitemap/dist/esm/lib/sitemap-stream.d.ts
generated
vendored
Normal file
79
node_modules/sitemap/dist/esm/lib/sitemap-stream.d.ts
generated
vendored
Normal file
@@ -0,0 +1,79 @@
|
||||
import { Transform, TransformOptions, TransformCallback, Readable } from 'node:stream';
|
||||
import { SitemapItemLoose, ErrorLevel, ErrorHandler } from './types.js';
|
||||
export declare const stylesheetInclude: (url: string) => string;
|
||||
export interface NSArgs {
|
||||
news: boolean;
|
||||
video: boolean;
|
||||
xhtml: boolean;
|
||||
image: boolean;
|
||||
custom?: string[];
|
||||
}
|
||||
export declare const closetag = "</urlset>";
|
||||
export interface SitemapStreamOptions extends TransformOptions {
|
||||
hostname?: string;
|
||||
level?: ErrorLevel;
|
||||
lastmodDateOnly?: boolean;
|
||||
xmlns?: NSArgs;
|
||||
xslUrl?: string;
|
||||
errorHandler?: ErrorHandler;
|
||||
}
|
||||
/**
|
||||
* A [Transform](https://nodejs.org/api/stream.html#stream_implementing_a_transform_stream)
|
||||
* for turning a
|
||||
* [Readable stream](https://nodejs.org/api/stream.html#stream_readable_streams)
|
||||
* of either [SitemapItemOptions](#sitemap-item-options) or url strings into a
|
||||
* Sitemap. The readable stream it transforms **must** be in object mode.
|
||||
*
|
||||
* @param {SitemapStreamOptions} opts - Configuration options
|
||||
* @param {string} [opts.hostname] - Base URL for relative paths. Must use http:// or https:// protocol
|
||||
* @param {ErrorLevel} [opts.level=ErrorLevel.WARN] - Error handling level (SILENT, WARN, or THROW)
|
||||
* @param {boolean} [opts.lastmodDateOnly=false] - Format lastmod as date only (YYYY-MM-DD)
|
||||
* @param {NSArgs} [opts.xmlns] - Control which XML namespaces to include in output
|
||||
* @param {string} [opts.xslUrl] - URL to XSL stylesheet for sitemap display. Must use http:// or https://
|
||||
* @param {ErrorHandler} [opts.errorHandler] - Custom error handler function
|
||||
*
|
||||
* @throws {InvalidHostnameError} If hostname is provided but invalid (non-http(s), malformed, or >2048 chars)
|
||||
* @throws {InvalidXSLUrlError} If xslUrl is provided but invalid (non-http(s), malformed, >2048 chars, or contains malicious content)
|
||||
* @throws {Error} If xmlns.custom contains invalid namespace declarations
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const stream = new SitemapStream({
|
||||
* hostname: 'https://example.com',
|
||||
* level: ErrorLevel.THROW
|
||||
* });
|
||||
* stream.write({ url: '/page', changefreq: 'daily' });
|
||||
* stream.end();
|
||||
* ```
|
||||
*
|
||||
* @security
|
||||
* - Hostname and xslUrl are validated to prevent URL injection attacks
|
||||
* - Custom namespaces are validated to prevent XML injection
|
||||
* - All URLs are normalized and validated before output
|
||||
* - XML content is properly escaped to prevent injection
|
||||
*/
|
||||
export declare class SitemapStream extends Transform {
|
||||
hostname?: string;
|
||||
level: ErrorLevel;
|
||||
hasHeadOutput: boolean;
|
||||
xmlNS: NSArgs;
|
||||
xslUrl?: string;
|
||||
errorHandler?: ErrorHandler;
|
||||
private smiStream;
|
||||
lastmodDateOnly: boolean;
|
||||
constructor(opts?: SitemapStreamOptions);
|
||||
_transform(item: SitemapItemLoose, encoding: string, callback: TransformCallback): void;
|
||||
_flush(cb: TransformCallback): void;
|
||||
}
|
||||
/**
|
||||
* Converts a readable stream into a promise that resolves with the concatenated data from the stream.
|
||||
*
|
||||
* The function listens for 'data' events from the stream, and when the stream ends, it resolves the promise with the concatenated data. If an error occurs while reading from the stream, the promise is rejected with the error.
|
||||
*
|
||||
* ⚠️ CAUTION: This function should not generally be used in production / when writing to files as it holds a copy of the entire file contents in memory until finished.
|
||||
*
|
||||
* @param {Readable} stream - The readable stream to convert to a promise.
|
||||
* @returns {Promise<Buffer>} A promise that resolves with the concatenated data from the stream as a Buffer, or rejects with an error if one occurred while reading from the stream. If the stream is empty, the promise is rejected with an EmptyStream error.
|
||||
* @throws {EmptyStream} If the stream is empty.
|
||||
*/
|
||||
export declare function streamToPromise(stream: Readable): Promise<Buffer>;
|
||||
212
node_modules/sitemap/dist/esm/lib/sitemap-stream.js
generated
vendored
Normal file
212
node_modules/sitemap/dist/esm/lib/sitemap-stream.js
generated
vendored
Normal file
@@ -0,0 +1,212 @@
|
||||
import { Transform, Writable, } from 'node:stream';
|
||||
import { ErrorLevel } from './types.js';
|
||||
import { normalizeURL } from './utils.js';
|
||||
import { validateSMIOptions, validateURL, validateXSLUrl, } from './validation.js';
|
||||
import { SitemapItemStream } from './sitemap-item-stream.js';
|
||||
import { EmptyStream, EmptySitemap } from './errors.js';
|
||||
import { LIMITS } from './constants.js';
|
||||
const xmlDec = '<?xml version="1.0" encoding="UTF-8"?>';
|
||||
export const stylesheetInclude = (url) => {
|
||||
const safe = url
|
||||
.replace(/&/g, '&')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>');
|
||||
return `<?xml-stylesheet type="text/xsl" href="${safe}"?>`;
|
||||
};
|
||||
const urlsetTagStart = '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"';
|
||||
/**
|
||||
* Validates custom namespace declarations for security
|
||||
* @param custom - Array of custom namespace declarations
|
||||
* @throws {Error} If namespace format is invalid or contains malicious content
|
||||
*/
|
||||
function validateCustomNamespaces(custom) {
|
||||
if (!Array.isArray(custom)) {
|
||||
throw new Error('Custom namespaces must be an array');
|
||||
}
|
||||
// Limit number of custom namespaces to prevent DoS
|
||||
if (custom.length > LIMITS.MAX_CUSTOM_NAMESPACES) {
|
||||
throw new Error(`Too many custom namespaces: ${custom.length} exceeds limit of ${LIMITS.MAX_CUSTOM_NAMESPACES}`);
|
||||
}
|
||||
// Basic format validation for xmlns declarations and namespace-qualified attributes
|
||||
// Supports both xmlns:prefix="uri" and prefix:attribute="value" (e.g., xsi:schemaLocation)
|
||||
const xmlAttributePattern = /^[a-zA-Z_][\w.-]*:[a-zA-Z_][\w.-]*="[^"<>]*"$/;
|
||||
for (const ns of custom) {
|
||||
if (typeof ns !== 'string' || ns.length === 0) {
|
||||
throw new Error('Custom namespace must be a non-empty string');
|
||||
}
|
||||
if (ns.length > LIMITS.MAX_NAMESPACE_LENGTH) {
|
||||
throw new Error(`Custom namespace exceeds maximum length of ${LIMITS.MAX_NAMESPACE_LENGTH} characters: ${ns.substring(0, 50)}...`);
|
||||
}
|
||||
// Check for potentially malicious content BEFORE format check
|
||||
// (format check will reject < and > but we want specific error message)
|
||||
const lowerNs = ns.toLowerCase();
|
||||
if (lowerNs.includes('<script') ||
|
||||
lowerNs.includes('javascript:') ||
|
||||
lowerNs.includes('data:text/html')) {
|
||||
throw new Error(`Custom namespace contains potentially malicious content: ${ns.substring(0, 50)}`);
|
||||
}
|
||||
// Check format matches xmlns declaration or namespace-qualified attribute
|
||||
if (!xmlAttributePattern.test(ns)) {
|
||||
throw new Error(`Invalid namespace format (must be prefix:name="value", e.g., xmlns:prefix="uri" or xsi:schemaLocation="..."): ${ns.substring(0, 50)}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
const getURLSetNs = ({ news, video, image, xhtml, custom }, xslURL) => {
|
||||
let ns = xmlDec;
|
||||
if (xslURL) {
|
||||
ns += stylesheetInclude(xslURL);
|
||||
}
|
||||
ns += urlsetTagStart;
|
||||
if (news) {
|
||||
ns += ' xmlns:news="http://www.google.com/schemas/sitemap-news/0.9"';
|
||||
}
|
||||
if (xhtml) {
|
||||
ns += ' xmlns:xhtml="http://www.w3.org/1999/xhtml"';
|
||||
}
|
||||
if (image) {
|
||||
ns += ' xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"';
|
||||
}
|
||||
if (video) {
|
||||
ns += ' xmlns:video="http://www.google.com/schemas/sitemap-video/1.1"';
|
||||
}
|
||||
if (custom) {
|
||||
validateCustomNamespaces(custom);
|
||||
ns += ' ' + custom.join(' ');
|
||||
}
|
||||
return ns + '>';
|
||||
};
|
||||
export const closetag = '</urlset>';
|
||||
const defaultXMLNS = {
|
||||
news: true,
|
||||
xhtml: true,
|
||||
image: true,
|
||||
video: true,
|
||||
};
|
||||
const defaultStreamOpts = {
|
||||
xmlns: defaultXMLNS,
|
||||
};
|
||||
/**
|
||||
* A [Transform](https://nodejs.org/api/stream.html#stream_implementing_a_transform_stream)
|
||||
* for turning a
|
||||
* [Readable stream](https://nodejs.org/api/stream.html#stream_readable_streams)
|
||||
* of either [SitemapItemOptions](#sitemap-item-options) or url strings into a
|
||||
* Sitemap. The readable stream it transforms **must** be in object mode.
|
||||
*
|
||||
* @param {SitemapStreamOptions} opts - Configuration options
|
||||
* @param {string} [opts.hostname] - Base URL for relative paths. Must use http:// or https:// protocol
|
||||
* @param {ErrorLevel} [opts.level=ErrorLevel.WARN] - Error handling level (SILENT, WARN, or THROW)
|
||||
* @param {boolean} [opts.lastmodDateOnly=false] - Format lastmod as date only (YYYY-MM-DD)
|
||||
* @param {NSArgs} [opts.xmlns] - Control which XML namespaces to include in output
|
||||
* @param {string} [opts.xslUrl] - URL to XSL stylesheet for sitemap display. Must use http:// or https://
|
||||
* @param {ErrorHandler} [opts.errorHandler] - Custom error handler function
|
||||
*
|
||||
* @throws {InvalidHostnameError} If hostname is provided but invalid (non-http(s), malformed, or >2048 chars)
|
||||
* @throws {InvalidXSLUrlError} If xslUrl is provided but invalid (non-http(s), malformed, >2048 chars, or contains malicious content)
|
||||
* @throws {Error} If xmlns.custom contains invalid namespace declarations
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const stream = new SitemapStream({
|
||||
* hostname: 'https://example.com',
|
||||
* level: ErrorLevel.THROW
|
||||
* });
|
||||
* stream.write({ url: '/page', changefreq: 'daily' });
|
||||
* stream.end();
|
||||
* ```
|
||||
*
|
||||
* @security
|
||||
* - Hostname and xslUrl are validated to prevent URL injection attacks
|
||||
* - Custom namespaces are validated to prevent XML injection
|
||||
* - All URLs are normalized and validated before output
|
||||
* - XML content is properly escaped to prevent injection
|
||||
*/
|
||||
export class SitemapStream extends Transform {
|
||||
hostname;
|
||||
level;
|
||||
hasHeadOutput;
|
||||
xmlNS;
|
||||
xslUrl;
|
||||
errorHandler;
|
||||
smiStream;
|
||||
lastmodDateOnly;
|
||||
constructor(opts = defaultStreamOpts) {
|
||||
opts.objectMode = true;
|
||||
super(opts);
|
||||
// Validate hostname if provided
|
||||
if (opts.hostname !== undefined) {
|
||||
validateURL(opts.hostname, 'hostname');
|
||||
}
|
||||
// Validate xslUrl if provided
|
||||
if (opts.xslUrl !== undefined) {
|
||||
validateXSLUrl(opts.xslUrl);
|
||||
}
|
||||
this.hasHeadOutput = false;
|
||||
this.hostname = opts.hostname;
|
||||
this.level = opts.level || ErrorLevel.WARN;
|
||||
this.errorHandler = opts.errorHandler;
|
||||
this.smiStream = new SitemapItemStream({ level: opts.level });
|
||||
this.smiStream.on('data', (data) => this.push(data));
|
||||
this.lastmodDateOnly = opts.lastmodDateOnly || false;
|
||||
this.xmlNS = opts.xmlns || defaultXMLNS;
|
||||
this.xslUrl = opts.xslUrl;
|
||||
}
|
||||
_transform(item, encoding, callback) {
|
||||
if (!this.hasHeadOutput) {
|
||||
this.hasHeadOutput = true;
|
||||
this.push(getURLSetNs(this.xmlNS, this.xslUrl));
|
||||
}
|
||||
if (!this.smiStream.write(validateSMIOptions(normalizeURL(item, this.hostname, this.lastmodDateOnly), this.level, this.errorHandler))) {
|
||||
this.smiStream.once('drain', callback);
|
||||
}
|
||||
else {
|
||||
process.nextTick(callback);
|
||||
}
|
||||
}
|
||||
_flush(cb) {
|
||||
if (!this.hasHeadOutput) {
|
||||
cb(new EmptySitemap());
|
||||
}
|
||||
else {
|
||||
this.push(closetag);
|
||||
cb();
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Converts a readable stream into a promise that resolves with the concatenated data from the stream.
|
||||
*
|
||||
* The function listens for 'data' events from the stream, and when the stream ends, it resolves the promise with the concatenated data. If an error occurs while reading from the stream, the promise is rejected with the error.
|
||||
*
|
||||
* ⚠️ CAUTION: This function should not generally be used in production / when writing to files as it holds a copy of the entire file contents in memory until finished.
|
||||
*
|
||||
* @param {Readable} stream - The readable stream to convert to a promise.
|
||||
* @returns {Promise<Buffer>} A promise that resolves with the concatenated data from the stream as a Buffer, or rejects with an error if one occurred while reading from the stream. If the stream is empty, the promise is rejected with an EmptyStream error.
|
||||
* @throws {EmptyStream} If the stream is empty.
|
||||
*/
|
||||
export function streamToPromise(stream) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const drain = [];
|
||||
stream
|
||||
// Error propagation is not automatic
|
||||
// Bubble up errors on the read stream
|
||||
.on('error', reject)
|
||||
.pipe(new Writable({
|
||||
write(chunk, enc, next) {
|
||||
drain.push(chunk);
|
||||
next();
|
||||
},
|
||||
}))
|
||||
// This bubbles up errors when writing to the internal buffer
|
||||
// This is unlikely to happen, but we have this for completeness
|
||||
.on('error', reject)
|
||||
.on('finish', () => {
|
||||
if (!drain.length) {
|
||||
reject(new EmptyStream());
|
||||
}
|
||||
else {
|
||||
resolve(Buffer.concat(drain));
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
107
node_modules/sitemap/dist/esm/lib/sitemap-xml.d.ts
generated
vendored
Normal file
107
node_modules/sitemap/dist/esm/lib/sitemap-xml.d.ts
generated
vendored
Normal file
@@ -0,0 +1,107 @@
|
||||
/*!
|
||||
* Sitemap
|
||||
* Copyright(c) 2011 Eugene Kalinin
|
||||
* MIT Licensed
|
||||
*/
|
||||
import { TagNames, IndexTagNames, StringObj } from './types.js';
|
||||
/**
|
||||
* Escapes text content for safe inclusion in XML text nodes.
|
||||
*
|
||||
* **Security Model:**
|
||||
* - Escapes `&` → `&` (required to prevent entity interpretation)
|
||||
* - Escapes `<` → `<` (required to prevent tag injection)
|
||||
* - Escapes `>` → `>` (defense-in-depth, prevents CDATA injection)
|
||||
* - Does NOT escape `"` or `'` (not required in text content, only in attributes)
|
||||
* - Removes invalid XML Unicode characters per XML 1.0 spec
|
||||
*
|
||||
* **Why quotes aren't escaped:**
|
||||
* In XML text content (between tags), quotes have no special meaning and don't
|
||||
* need escaping. They only need escaping in attribute values, which is handled
|
||||
* by the `otag()` function.
|
||||
*
|
||||
* @param txt - The text content to escape
|
||||
* @returns XML-safe escaped text with invalid characters removed
|
||||
* @throws {TypeError} If txt is not a string
|
||||
*
|
||||
* @example
|
||||
* text('Hello & World'); // Returns: 'Hello & World'
|
||||
* text('5 < 10'); // Returns: '5 < 10'
|
||||
* text('Hello "World"'); // Returns: 'Hello "World"' (quotes OK in text)
|
||||
*
|
||||
* @see https://www.w3.org/TR/xml/#syntax
|
||||
*/
|
||||
export declare function text(txt: string): string;
|
||||
/**
|
||||
* Generates an opening XML tag with optional attributes.
|
||||
*
|
||||
* **Security Model:**
|
||||
* - Validates attribute names to prevent injection via malformed names
|
||||
* - Escapes all attribute values with proper XML entity encoding
|
||||
* - Escapes `&`, `<`, `>`, `"`, and `'` in attribute values
|
||||
* - Removes invalid XML Unicode characters
|
||||
*
|
||||
* Attribute values use full escaping (including quotes) because they appear
|
||||
* within quoted strings in the XML output: `<tag attr="value">`.
|
||||
*
|
||||
* @param nodeName - The XML element name (e.g., 'url', 'loc', 'video:title')
|
||||
* @param attrs - Optional object mapping attribute names to string values
|
||||
* @param selfClose - If true, generates a self-closing tag (e.g., `<tag/>`)
|
||||
* @returns Opening XML tag string
|
||||
* @throws {InvalidXMLAttributeNameError} If an attribute name contains invalid characters
|
||||
* @throws {TypeError} If nodeName is not a string or attrs values are not strings
|
||||
*
|
||||
* @example
|
||||
* otag('url'); // Returns: '<url>'
|
||||
* otag('video:player_loc', { autoplay: 'ap=1' }); // Returns: '<video:player_loc autoplay="ap=1">'
|
||||
* otag('image:image', {}, true); // Returns: '<image:image/>'
|
||||
*
|
||||
* @see https://www.w3.org/TR/xml/#NT-Attribute
|
||||
*/
|
||||
export declare function otag(nodeName: TagNames | IndexTagNames, attrs?: StringObj, selfClose?: boolean): string;
|
||||
/**
|
||||
* Generates a closing XML tag.
|
||||
*
|
||||
* @param nodeName - The XML element name (e.g., 'url', 'loc', 'video:title')
|
||||
* @returns Closing XML tag string
|
||||
* @throws {TypeError} If nodeName is not a string
|
||||
*
|
||||
* @example
|
||||
* ctag('url'); // Returns: '</url>'
|
||||
* ctag('video:title'); // Returns: '</video:title>'
|
||||
*/
|
||||
export declare function ctag(nodeName: TagNames | IndexTagNames): string;
|
||||
/**
|
||||
* Generates a complete XML element with optional attributes and text content.
|
||||
*
|
||||
* This is a convenience function that combines `otag()`, `text()`, and `ctag()`.
|
||||
* It supports three usage patterns via function overloading:
|
||||
*
|
||||
* 1. Element with text content: `element('loc', 'https://example.com')`
|
||||
* 2. Element with attributes and text: `element('video:player_loc', { autoplay: 'ap=1' }, 'https://...')`
|
||||
* 3. Self-closing element with attributes: `element('image:image', { href: '...' })`
|
||||
*
|
||||
* @param nodeName - The XML element name
|
||||
* @param attrs - Either a string (text content) or object (attributes)
|
||||
* @param innerText - Optional text content when attrs is an object
|
||||
* @returns Complete XML element string
|
||||
* @throws {InvalidXMLAttributeNameError} If an attribute name contains invalid characters
|
||||
* @throws {TypeError} If arguments have invalid types
|
||||
*
|
||||
* @example
|
||||
* // Pattern 1: Simple element with text
|
||||
* element('loc', 'https://example.com')
|
||||
* // Returns: '<loc>https://example.com</loc>'
|
||||
*
|
||||
* @example
|
||||
* // Pattern 2: Element with attributes and text
|
||||
* element('video:player_loc', { autoplay: 'ap=1' }, 'https://example.com/video')
|
||||
* // Returns: '<video:player_loc autoplay="ap=1">https://example.com/video</video:player_loc>'
|
||||
*
|
||||
* @example
|
||||
* // Pattern 3: Self-closing element with attributes
|
||||
* element('xhtml:link', { rel: 'alternate', href: 'https://example.com/fr' })
|
||||
* // Returns: '<xhtml:link rel="alternate" href="https://example.com/fr"/>'
|
||||
*/
|
||||
export declare function element(nodeName: TagNames, attrs: StringObj, innerText: string): string;
|
||||
export declare function element(nodeName: TagNames | IndexTagNames, innerText: string): string;
|
||||
export declare function element(nodeName: TagNames, attrs: StringObj): string;
|
||||
181
node_modules/sitemap/dist/esm/lib/sitemap-xml.js
generated
vendored
Normal file
181
node_modules/sitemap/dist/esm/lib/sitemap-xml.js
generated
vendored
Normal file
@@ -0,0 +1,181 @@
|
||||
/*!
|
||||
* Sitemap
|
||||
* Copyright(c) 2011 Eugene Kalinin
|
||||
* MIT Licensed
|
||||
*/
|
||||
import { InvalidXMLAttributeNameError } from './errors.js';
|
||||
/**
|
||||
* Regular expression matching invalid XML 1.0 Unicode characters that must be removed.
|
||||
*
|
||||
* Based on the XML 1.0 specification (https://www.w3.org/TR/xml/#charsets):
|
||||
* - Control characters (U+0000-U+001F except tab, newline, carriage return)
|
||||
* - Delete character (U+007F)
|
||||
* - Invalid control characters (U+0080-U+009F except U+0085)
|
||||
* - Surrogate pairs (U+D800-U+DFFF)
|
||||
* - Non-characters (\p{NChar} - permanently reserved code points)
|
||||
*
|
||||
* Performance note: This regex uses Unicode property escapes and may be slower
|
||||
* on very large strings (100KB+). Consider pre-validation for untrusted input.
|
||||
*
|
||||
* @see https://www.w3.org/TR/xml/#charsets
|
||||
*/
|
||||
const invalidXMLUnicodeRegex =
|
||||
// eslint-disable-next-line no-control-regex
|
||||
/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u0084\u0086-\u009F\uD800-\uDFFF\p{NChar}]/gu;
|
||||
/**
|
||||
* Regular expressions for XML entity escaping
|
||||
*/
|
||||
const amp = /&/g;
|
||||
const lt = /</g;
|
||||
const gt = />/g;
|
||||
const apos = /'/g;
|
||||
const quot = /"/g;
|
||||
/**
|
||||
* Valid XML attribute name pattern. XML names must:
|
||||
* - Start with a letter, underscore, or colon
|
||||
* - Contain only letters, digits, hyphens, underscores, colons, or periods
|
||||
*
|
||||
* This is a simplified validation that accepts the most common attribute names.
|
||||
* Note: In practice, this library only uses namespaced attributes like "video:title"
|
||||
* which are guaranteed to be valid.
|
||||
*
|
||||
* @see https://www.w3.org/TR/xml/#NT-Name
|
||||
*/
|
||||
const validAttributeNameRegex = /^[a-zA-Z_:][\w:.-]*$/;
|
||||
/**
|
||||
* Validates that an attribute name is a valid XML identifier.
|
||||
*
|
||||
* XML attribute names must start with a letter, underscore, or colon,
|
||||
* and contain only alphanumeric characters, hyphens, underscores, colons, or periods.
|
||||
*
|
||||
* @param name - The attribute name to validate
|
||||
* @throws {InvalidXMLAttributeNameError} If the attribute name is invalid
|
||||
*
|
||||
* @example
|
||||
* validateAttributeName('href'); // OK
|
||||
* validateAttributeName('xml:lang'); // OK
|
||||
* validateAttributeName('data-value'); // OK
|
||||
* validateAttributeName('<script>'); // Throws InvalidXMLAttributeNameError
|
||||
*/
|
||||
function validateAttributeName(name) {
|
||||
if (!validAttributeNameRegex.test(name)) {
|
||||
throw new InvalidXMLAttributeNameError(name);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Escapes text content for safe inclusion in XML text nodes.
|
||||
*
|
||||
* **Security Model:**
|
||||
* - Escapes `&` → `&` (required to prevent entity interpretation)
|
||||
* - Escapes `<` → `<` (required to prevent tag injection)
|
||||
* - Escapes `>` → `>` (defense-in-depth, prevents CDATA injection)
|
||||
* - Does NOT escape `"` or `'` (not required in text content, only in attributes)
|
||||
* - Removes invalid XML Unicode characters per XML 1.0 spec
|
||||
*
|
||||
* **Why quotes aren't escaped:**
|
||||
* In XML text content (between tags), quotes have no special meaning and don't
|
||||
* need escaping. They only need escaping in attribute values, which is handled
|
||||
* by the `otag()` function.
|
||||
*
|
||||
* @param txt - The text content to escape
|
||||
* @returns XML-safe escaped text with invalid characters removed
|
||||
* @throws {TypeError} If txt is not a string
|
||||
*
|
||||
* @example
|
||||
* text('Hello & World'); // Returns: 'Hello & World'
|
||||
* text('5 < 10'); // Returns: '5 < 10'
|
||||
* text('Hello "World"'); // Returns: 'Hello "World"' (quotes OK in text)
|
||||
*
|
||||
* @see https://www.w3.org/TR/xml/#syntax
|
||||
*/
|
||||
export function text(txt) {
|
||||
if (typeof txt !== 'string') {
|
||||
throw new TypeError(`text() requires a string, received ${typeof txt}: ${String(txt)}`);
|
||||
}
|
||||
return txt
|
||||
.replace(amp, '&')
|
||||
.replace(lt, '<')
|
||||
.replace(gt, '>')
|
||||
.replace(invalidXMLUnicodeRegex, '');
|
||||
}
|
||||
/**
|
||||
* Generates an opening XML tag with optional attributes.
|
||||
*
|
||||
* **Security Model:**
|
||||
* - Validates attribute names to prevent injection via malformed names
|
||||
* - Escapes all attribute values with proper XML entity encoding
|
||||
* - Escapes `&`, `<`, `>`, `"`, and `'` in attribute values
|
||||
* - Removes invalid XML Unicode characters
|
||||
*
|
||||
* Attribute values use full escaping (including quotes) because they appear
|
||||
* within quoted strings in the XML output: `<tag attr="value">`.
|
||||
*
|
||||
* @param nodeName - The XML element name (e.g., 'url', 'loc', 'video:title')
|
||||
* @param attrs - Optional object mapping attribute names to string values
|
||||
* @param selfClose - If true, generates a self-closing tag (e.g., `<tag/>`)
|
||||
* @returns Opening XML tag string
|
||||
* @throws {InvalidXMLAttributeNameError} If an attribute name contains invalid characters
|
||||
* @throws {TypeError} If nodeName is not a string or attrs values are not strings
|
||||
*
|
||||
* @example
|
||||
* otag('url'); // Returns: '<url>'
|
||||
* otag('video:player_loc', { autoplay: 'ap=1' }); // Returns: '<video:player_loc autoplay="ap=1">'
|
||||
* otag('image:image', {}, true); // Returns: '<image:image/>'
|
||||
*
|
||||
* @see https://www.w3.org/TR/xml/#NT-Attribute
|
||||
*/
|
||||
export function otag(nodeName, attrs, selfClose = false) {
|
||||
if (typeof nodeName !== 'string') {
|
||||
throw new TypeError(`otag() nodeName must be a string, received ${typeof nodeName}: ${String(nodeName)}`);
|
||||
}
|
||||
let attrstr = '';
|
||||
for (const k in attrs) {
|
||||
// Validate attribute name to prevent injection
|
||||
validateAttributeName(k);
|
||||
const attrValue = attrs[k];
|
||||
if (typeof attrValue !== 'string') {
|
||||
throw new TypeError(`otag() attribute "${k}" value must be a string, received ${typeof attrValue}: ${String(attrValue)}`);
|
||||
}
|
||||
// Escape attribute value with full entity encoding
|
||||
const val = attrValue
|
||||
.replace(amp, '&')
|
||||
.replace(lt, '<')
|
||||
.replace(gt, '>')
|
||||
.replace(apos, ''')
|
||||
.replace(quot, '"')
|
||||
.replace(invalidXMLUnicodeRegex, '');
|
||||
attrstr += ` ${k}="${val}"`;
|
||||
}
|
||||
return `<${nodeName}${attrstr}${selfClose ? '/' : ''}>`;
|
||||
}
|
||||
/**
|
||||
* Generates a closing XML tag.
|
||||
*
|
||||
* @param nodeName - The XML element name (e.g., 'url', 'loc', 'video:title')
|
||||
* @returns Closing XML tag string
|
||||
* @throws {TypeError} If nodeName is not a string
|
||||
*
|
||||
* @example
|
||||
* ctag('url'); // Returns: '</url>'
|
||||
* ctag('video:title'); // Returns: '</video:title>'
|
||||
*/
|
||||
export function ctag(nodeName) {
|
||||
if (typeof nodeName !== 'string') {
|
||||
throw new TypeError(`ctag() nodeName must be a string, received ${typeof nodeName}: ${String(nodeName)}`);
|
||||
}
|
||||
return `</${nodeName}>`;
|
||||
}
|
||||
export function element(nodeName, attrs, innerText) {
|
||||
if (typeof attrs === 'string') {
|
||||
// Pattern 1: element(nodeName, textContent)
|
||||
return otag(nodeName) + text(attrs) + ctag(nodeName);
|
||||
}
|
||||
else if (innerText !== undefined) {
|
||||
// Pattern 2: element(nodeName, attrs, textContent)
|
||||
return otag(nodeName, attrs) + text(innerText) + ctag(nodeName);
|
||||
}
|
||||
else {
|
||||
// Pattern 3: element(nodeName, attrs) - self-closing
|
||||
return otag(nodeName, attrs, true);
|
||||
}
|
||||
}
|
||||
400
node_modules/sitemap/dist/esm/lib/types.d.ts
generated
vendored
Normal file
400
node_modules/sitemap/dist/esm/lib/types.d.ts
generated
vendored
Normal file
@@ -0,0 +1,400 @@
|
||||
import { URL } from 'node:url';
|
||||
/**
|
||||
* How frequently the page is likely to change. This value provides general
|
||||
* information to search engines and may not correlate exactly to how often they crawl the page. Please note that the
|
||||
* value of this tag is considered a hint and not a command. See
|
||||
* <https://www.sitemaps.org/protocol.html#xmlTagDefinitions> for the acceptable
|
||||
* values
|
||||
*/
|
||||
export declare enum EnumChangefreq {
|
||||
DAILY = "daily",
|
||||
MONTHLY = "monthly",
|
||||
ALWAYS = "always",
|
||||
HOURLY = "hourly",
|
||||
WEEKLY = "weekly",
|
||||
YEARLY = "yearly",
|
||||
NEVER = "never"
|
||||
}
|
||||
export declare enum EnumYesNo {
|
||||
YES = "YES",
|
||||
NO = "NO",
|
||||
Yes = "Yes",
|
||||
No = "No",
|
||||
yes = "yes",
|
||||
no = "no"
|
||||
}
|
||||
export declare enum EnumAllowDeny {
|
||||
ALLOW = "allow",
|
||||
DENY = "deny"
|
||||
}
|
||||
/**
|
||||
* https://support.google.com/webmasters/answer/74288?hl=en&ref_topic=4581190
|
||||
*/
|
||||
export interface NewsItem {
|
||||
access?: 'Registration' | 'Subscription';
|
||||
publication: {
|
||||
name: string;
|
||||
/**
|
||||
* The `<language>` is the language of your publication. Use an ISO 639
|
||||
* language code (2 or 3 letters).
|
||||
*/
|
||||
language: string;
|
||||
};
|
||||
/**
|
||||
* @example 'PressRelease, Blog'
|
||||
*/
|
||||
genres?: string;
|
||||
/**
|
||||
* Article publication date in W3C format, using either the "complete date" (YYYY-MM-DD) format or the "complete date
|
||||
* plus hours, minutes, and seconds"
|
||||
*/
|
||||
publication_date: string;
|
||||
/**
|
||||
* The title of the news article
|
||||
* @example 'Companies A, B in Merger Talks'
|
||||
*/
|
||||
title: string;
|
||||
/**
|
||||
* @example 'business, merger, acquisition'
|
||||
*/
|
||||
keywords?: string;
|
||||
/**
|
||||
* @example 'NASDAQ:A, NASDAQ:B'
|
||||
*/
|
||||
stock_tickers?: string;
|
||||
}
|
||||
/**
|
||||
* Sitemap Image
|
||||
* https://support.google.com/webmasters/answer/178636?hl=en&ref_topic=4581190
|
||||
*/
|
||||
export interface Img {
|
||||
/**
|
||||
* The URL of the image
|
||||
* @example 'https://example.com/image.jpg'
|
||||
*/
|
||||
url: string;
|
||||
/**
|
||||
* The caption of the image
|
||||
* @example 'Thanksgiving dinner'
|
||||
*/
|
||||
caption?: string;
|
||||
/**
|
||||
* The title of the image
|
||||
* @example 'Star Wars EP IV'
|
||||
*/
|
||||
title?: string;
|
||||
/**
|
||||
* The geographic location of the image.
|
||||
* @example 'Limerick, Ireland'
|
||||
*/
|
||||
geoLocation?: string;
|
||||
/**
|
||||
* A URL to the license of the image.
|
||||
* @example 'https://example.com/license.txt'
|
||||
*/
|
||||
license?: string;
|
||||
}
|
||||
interface VideoItemBase {
|
||||
/**
|
||||
* A URL pointing to the video thumbnail image file
|
||||
* @example "https://rtv3-img-roosterteeth.akamaized.net/store/0e841100-289b-4184-ae30-b6a16736960a.jpg/sm/thumb3.jpg"
|
||||
*/
|
||||
thumbnail_loc: string;
|
||||
/**
|
||||
* The title of the video
|
||||
* @example '2018:E6 - GoldenEye: Source'
|
||||
*/
|
||||
title: string;
|
||||
/**
|
||||
* A description of the video. Maximum 2048 characters.
|
||||
* @example 'We play gun game in GoldenEye: Source with a good friend of ours. His name is Gruchy. Dan Gruchy.'
|
||||
*/
|
||||
description: string;
|
||||
/**
|
||||
* A URL pointing to the actual video media file. Should be one of the supported formats. HTML is not a supported
|
||||
* format. Flash is allowed, but no longer supported on most mobile platforms, and so may be indexed less well. Must
|
||||
* not be the same as the `<loc>` URL.
|
||||
* @example "http://streamserver.example.com/video123.mp4"
|
||||
*/
|
||||
content_loc?: string;
|
||||
/**
|
||||
* A URL pointing to a player for a specific video. Usually this is the information in the src element of an `<embed>`
|
||||
* tag. Must not be the same as the `<loc>` URL
|
||||
* @example "https://roosterteeth.com/embed/rouletsplay-2018-goldeneye-source"
|
||||
*/
|
||||
player_loc?: string;
|
||||
/**
|
||||
* A string the search engine can append as a query param to enable automatic
|
||||
* playback. Equivilant to auto play attr on player_loc tag.
|
||||
* @example 'ap=1'
|
||||
*/
|
||||
'player_loc:autoplay'?: string;
|
||||
/**
|
||||
* Whether the search engine can embed the video in search results. Allowed values are yes or no.
|
||||
*/
|
||||
'player_loc:allow_embed'?: EnumYesNo;
|
||||
/**
|
||||
* The length of the video in seconds
|
||||
* @example 600
|
||||
*/
|
||||
duration?: number;
|
||||
/**
|
||||
* The date after which the video will no longer be available.
|
||||
* @example "2012-07-16T19:20:30+08:00"
|
||||
*/
|
||||
expiration_date?: string;
|
||||
/**
|
||||
* The number of times the video has been viewed
|
||||
*/
|
||||
view_count?: number;
|
||||
/**
|
||||
* The date the video was first published, in W3C format.
|
||||
* @example "2012-07-16T19:20:30+08:00"
|
||||
*/
|
||||
publication_date?: string;
|
||||
/**
|
||||
* A short description of the broad category that the video belongs to. This is a string no longer than 256 characters.
|
||||
* @example Baking
|
||||
*/
|
||||
category?: string;
|
||||
/**
|
||||
* Whether to show or hide your video in search results from specific countries.
|
||||
* @example "IE GB US CA"
|
||||
*/
|
||||
restriction?: string;
|
||||
/**
|
||||
* Whether the countries in restriction are allowed or denied
|
||||
* @example 'deny'
|
||||
*/
|
||||
'restriction:relationship'?: EnumAllowDeny;
|
||||
gallery_loc?: string;
|
||||
/**
|
||||
* [Optional] Specifies the URL of a webpage with additional information about this uploader. This URL must be in the same domain as the <loc> tag.
|
||||
* @see https://developers.google.com/search/docs/advanced/sitemaps/video-sitemaps
|
||||
* @example http://www.example.com/users/grillymcgrillerson
|
||||
*/
|
||||
'uploader:info'?: string;
|
||||
'gallery_loc:title'?: string;
|
||||
/**
|
||||
* The price to download or view the video. Omit this tag for free videos.
|
||||
* @example "1.99"
|
||||
*/
|
||||
price?: string;
|
||||
/**
|
||||
* Specifies the resolution of the purchased version. Supported values are hd and sd.
|
||||
* @example "HD"
|
||||
*/
|
||||
'price:resolution'?: Resolution;
|
||||
/**
|
||||
* Specifies the currency in ISO4217 format.
|
||||
* @example "USD"
|
||||
*/
|
||||
'price:currency'?: string;
|
||||
/**
|
||||
* Specifies the purchase option. Supported values are rend and own.
|
||||
* @example "rent"
|
||||
*/
|
||||
'price:type'?: PriceType;
|
||||
/**
|
||||
* The video uploader's name. Only one <video:uploader> is allowed per video. String value, max 255 characters.
|
||||
* @example "GrillyMcGrillerson"
|
||||
*/
|
||||
uploader?: string;
|
||||
/**
|
||||
* Whether to show or hide your video in search results on specified platform types. This is a list of space-delimited
|
||||
* platform types. See <https://support.google.com/webmasters/answer/80471?hl=en&ref_topic=4581190> for more detail
|
||||
* @example "tv"
|
||||
*/
|
||||
platform?: string;
|
||||
id?: string;
|
||||
'platform:relationship'?: EnumAllowDeny;
|
||||
}
|
||||
/**
|
||||
* Video price type - supports both lowercase and uppercase variants
|
||||
* as allowed by the Google Video Sitemap specification
|
||||
* @see https://developers.google.com/search/docs/advanced/sitemaps/video-sitemaps
|
||||
*/
|
||||
export type PriceType = 'rent' | 'purchase' | 'RENT' | 'PURCHASE';
|
||||
/**
|
||||
* Video resolution - supports both lowercase and uppercase variants
|
||||
* as allowed by the Google Video Sitemap specification
|
||||
* @see https://developers.google.com/search/docs/advanced/sitemaps/video-sitemaps
|
||||
*/
|
||||
export type Resolution = 'HD' | 'hd' | 'sd' | 'SD';
|
||||
/**
|
||||
* Sitemap video. <https://support.google.com/webmasters/answer/80471?hl=en&ref_topic=4581190>
|
||||
*/
|
||||
export interface VideoItem extends VideoItemBase {
|
||||
/**
|
||||
* An arbitrary string tag describing the video. Tags are generally very short descriptions of key concepts associated
|
||||
* with a video or piece of content.
|
||||
* @example ['Baking']
|
||||
*/
|
||||
tag: string[];
|
||||
/**
|
||||
* The rating of the video. Supported values are float numbers.
|
||||
* @example 2.5
|
||||
*/
|
||||
rating?: number;
|
||||
family_friendly?: EnumYesNo;
|
||||
/**
|
||||
* Indicates whether a subscription (either paid or free) is required to view
|
||||
* the video. Allowed values are yes or no.
|
||||
*/
|
||||
requires_subscription?: EnumYesNo;
|
||||
/**
|
||||
* Indicates whether the video is a live stream. Supported values are yes or no.
|
||||
*/
|
||||
live?: EnumYesNo;
|
||||
}
|
||||
/**
|
||||
* Sitemap video. <https://support.google.com/webmasters/answer/80471?hl=en&ref_topic=4581190>
|
||||
*/
|
||||
export interface VideoItemLoose extends VideoItemBase {
|
||||
/**
|
||||
* An arbitrary string tag describing the video. Tags are generally very short descriptions of key concepts associated
|
||||
* with a video or piece of content.
|
||||
* @example ['Baking']
|
||||
*/
|
||||
tag?: string | string[];
|
||||
/**
|
||||
* The rating of the video. Supported values are float numbers.
|
||||
* @example 2.5
|
||||
*/
|
||||
rating?: string | number;
|
||||
family_friendly?: EnumYesNo | boolean;
|
||||
requires_subscription?: EnumYesNo | boolean;
|
||||
/**
|
||||
* Indicates whether the video is a live stream. Supported values are yes or no.
|
||||
*/
|
||||
live?: EnumYesNo | boolean;
|
||||
}
|
||||
/**
|
||||
* https://support.google.com/webmasters/answer/189077
|
||||
*/
|
||||
export interface LinkItem {
|
||||
/**
|
||||
* @example 'en'
|
||||
*/
|
||||
lang: string;
|
||||
/**
|
||||
* @example 'en-us'
|
||||
*/
|
||||
hreflang?: string;
|
||||
url: string;
|
||||
}
|
||||
export interface IndexItem {
|
||||
url: string;
|
||||
lastmod?: string;
|
||||
}
|
||||
interface SitemapItemBase {
|
||||
lastmod?: string;
|
||||
changefreq?: EnumChangefreq;
|
||||
fullPrecisionPriority?: boolean;
|
||||
priority?: number;
|
||||
news?: NewsItem;
|
||||
expires?: string;
|
||||
androidLink?: string;
|
||||
ampLink?: string;
|
||||
url: string;
|
||||
}
|
||||
/**
|
||||
* Strict options for individual sitemap entries
|
||||
*/
|
||||
export interface SitemapItem extends SitemapItemBase {
|
||||
img: Img[];
|
||||
video: VideoItem[];
|
||||
links: LinkItem[];
|
||||
}
|
||||
/**
|
||||
* Options for individual sitemap entries prior to normalization
|
||||
*/
|
||||
export interface SitemapItemLoose extends SitemapItemBase {
|
||||
video?: VideoItemLoose | VideoItemLoose[];
|
||||
img?: string | Img | (string | Img)[];
|
||||
links?: LinkItem[];
|
||||
lastmodfile?: string | Buffer | URL;
|
||||
lastmodISO?: string;
|
||||
lastmodrealtime?: boolean;
|
||||
}
|
||||
/**
|
||||
* How to handle errors in passed in urls
|
||||
*/
|
||||
export declare enum ErrorLevel {
|
||||
/**
|
||||
* Validation will be skipped and nothing logged or thrown.
|
||||
*/
|
||||
SILENT = "silent",
|
||||
/**
|
||||
* If an invalid value is encountered, a console.warn will be called with details
|
||||
*/
|
||||
WARN = "warn",
|
||||
/**
|
||||
* An Error will be thrown on encountering invalid data.
|
||||
*/
|
||||
THROW = "throw"
|
||||
}
|
||||
export type ErrorHandler = (error: Error, level: ErrorLevel) => void;
|
||||
export declare enum TagNames {
|
||||
url = "url",
|
||||
loc = "loc",
|
||||
urlset = "urlset",
|
||||
lastmod = "lastmod",
|
||||
changefreq = "changefreq",
|
||||
priority = "priority",
|
||||
'video:thumbnail_loc' = "video:thumbnail_loc",
|
||||
'video:video' = "video:video",
|
||||
'video:title' = "video:title",
|
||||
'video:description' = "video:description",
|
||||
'video:tag' = "video:tag",
|
||||
'video:duration' = "video:duration",
|
||||
'video:player_loc' = "video:player_loc",
|
||||
'video:content_loc' = "video:content_loc",
|
||||
'image:image' = "image:image",
|
||||
'image:loc' = "image:loc",
|
||||
'image:geo_location' = "image:geo_location",
|
||||
'image:license' = "image:license",
|
||||
'image:title' = "image:title",
|
||||
'image:caption' = "image:caption",
|
||||
'video:requires_subscription' = "video:requires_subscription",
|
||||
'video:publication_date' = "video:publication_date",
|
||||
'video:id' = "video:id",
|
||||
'video:restriction' = "video:restriction",
|
||||
'video:family_friendly' = "video:family_friendly",
|
||||
'video:view_count' = "video:view_count",
|
||||
'video:uploader' = "video:uploader",
|
||||
'video:expiration_date' = "video:expiration_date",
|
||||
'video:platform' = "video:platform",
|
||||
'video:price' = "video:price",
|
||||
'video:rating' = "video:rating",
|
||||
'video:category' = "video:category",
|
||||
'video:live' = "video:live",
|
||||
'video:gallery_loc' = "video:gallery_loc",
|
||||
'news:news' = "news:news",
|
||||
'news:publication' = "news:publication",
|
||||
'news:name' = "news:name",
|
||||
'news:access' = "news:access",
|
||||
'news:genres' = "news:genres",
|
||||
'news:publication_date' = "news:publication_date",
|
||||
'news:title' = "news:title",
|
||||
'news:keywords' = "news:keywords",
|
||||
'news:stock_tickers' = "news:stock_tickers",
|
||||
'news:language' = "news:language",
|
||||
'mobile:mobile' = "mobile:mobile",
|
||||
'xhtml:link' = "xhtml:link",
|
||||
'expires' = "expires"
|
||||
}
|
||||
export declare enum IndexTagNames {
|
||||
sitemap = "sitemap",
|
||||
sitemapindex = "sitemapindex",
|
||||
loc = "loc",
|
||||
lastmod = "lastmod"
|
||||
}
|
||||
/**
|
||||
* Generic object with string keys and any values
|
||||
* Used for XML attribute building and other flexible data structures
|
||||
*/
|
||||
export interface StringObj {
|
||||
[index: string]: any;
|
||||
}
|
||||
export {};
|
||||
106
node_modules/sitemap/dist/esm/lib/types.js
generated
vendored
Normal file
106
node_modules/sitemap/dist/esm/lib/types.js
generated
vendored
Normal file
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* How frequently the page is likely to change. This value provides general
|
||||
* information to search engines and may not correlate exactly to how often they crawl the page. Please note that the
|
||||
* value of this tag is considered a hint and not a command. See
|
||||
* <https://www.sitemaps.org/protocol.html#xmlTagDefinitions> for the acceptable
|
||||
* values
|
||||
*/
|
||||
export var EnumChangefreq;
|
||||
(function (EnumChangefreq) {
|
||||
EnumChangefreq["DAILY"] = "daily";
|
||||
EnumChangefreq["MONTHLY"] = "monthly";
|
||||
EnumChangefreq["ALWAYS"] = "always";
|
||||
EnumChangefreq["HOURLY"] = "hourly";
|
||||
EnumChangefreq["WEEKLY"] = "weekly";
|
||||
EnumChangefreq["YEARLY"] = "yearly";
|
||||
EnumChangefreq["NEVER"] = "never";
|
||||
})(EnumChangefreq || (EnumChangefreq = {}));
|
||||
export var EnumYesNo;
|
||||
(function (EnumYesNo) {
|
||||
EnumYesNo["YES"] = "YES";
|
||||
EnumYesNo["NO"] = "NO";
|
||||
EnumYesNo["Yes"] = "Yes";
|
||||
EnumYesNo["No"] = "No";
|
||||
EnumYesNo["yes"] = "yes";
|
||||
EnumYesNo["no"] = "no";
|
||||
})(EnumYesNo || (EnumYesNo = {}));
|
||||
export var EnumAllowDeny;
|
||||
(function (EnumAllowDeny) {
|
||||
EnumAllowDeny["ALLOW"] = "allow";
|
||||
EnumAllowDeny["DENY"] = "deny";
|
||||
})(EnumAllowDeny || (EnumAllowDeny = {}));
|
||||
/**
|
||||
* How to handle errors in passed in urls
|
||||
*/
|
||||
export var ErrorLevel;
|
||||
(function (ErrorLevel) {
|
||||
/**
|
||||
* Validation will be skipped and nothing logged or thrown.
|
||||
*/
|
||||
ErrorLevel["SILENT"] = "silent";
|
||||
/**
|
||||
* If an invalid value is encountered, a console.warn will be called with details
|
||||
*/
|
||||
ErrorLevel["WARN"] = "warn";
|
||||
/**
|
||||
* An Error will be thrown on encountering invalid data.
|
||||
*/
|
||||
ErrorLevel["THROW"] = "throw";
|
||||
})(ErrorLevel || (ErrorLevel = {}));
|
||||
export var TagNames;
|
||||
(function (TagNames) {
|
||||
TagNames["url"] = "url";
|
||||
TagNames["loc"] = "loc";
|
||||
TagNames["urlset"] = "urlset";
|
||||
TagNames["lastmod"] = "lastmod";
|
||||
TagNames["changefreq"] = "changefreq";
|
||||
TagNames["priority"] = "priority";
|
||||
TagNames["video:thumbnail_loc"] = "video:thumbnail_loc";
|
||||
TagNames["video:video"] = "video:video";
|
||||
TagNames["video:title"] = "video:title";
|
||||
TagNames["video:description"] = "video:description";
|
||||
TagNames["video:tag"] = "video:tag";
|
||||
TagNames["video:duration"] = "video:duration";
|
||||
TagNames["video:player_loc"] = "video:player_loc";
|
||||
TagNames["video:content_loc"] = "video:content_loc";
|
||||
TagNames["image:image"] = "image:image";
|
||||
TagNames["image:loc"] = "image:loc";
|
||||
TagNames["image:geo_location"] = "image:geo_location";
|
||||
TagNames["image:license"] = "image:license";
|
||||
TagNames["image:title"] = "image:title";
|
||||
TagNames["image:caption"] = "image:caption";
|
||||
TagNames["video:requires_subscription"] = "video:requires_subscription";
|
||||
TagNames["video:publication_date"] = "video:publication_date";
|
||||
TagNames["video:id"] = "video:id";
|
||||
TagNames["video:restriction"] = "video:restriction";
|
||||
TagNames["video:family_friendly"] = "video:family_friendly";
|
||||
TagNames["video:view_count"] = "video:view_count";
|
||||
TagNames["video:uploader"] = "video:uploader";
|
||||
TagNames["video:expiration_date"] = "video:expiration_date";
|
||||
TagNames["video:platform"] = "video:platform";
|
||||
TagNames["video:price"] = "video:price";
|
||||
TagNames["video:rating"] = "video:rating";
|
||||
TagNames["video:category"] = "video:category";
|
||||
TagNames["video:live"] = "video:live";
|
||||
TagNames["video:gallery_loc"] = "video:gallery_loc";
|
||||
TagNames["news:news"] = "news:news";
|
||||
TagNames["news:publication"] = "news:publication";
|
||||
TagNames["news:name"] = "news:name";
|
||||
TagNames["news:access"] = "news:access";
|
||||
TagNames["news:genres"] = "news:genres";
|
||||
TagNames["news:publication_date"] = "news:publication_date";
|
||||
TagNames["news:title"] = "news:title";
|
||||
TagNames["news:keywords"] = "news:keywords";
|
||||
TagNames["news:stock_tickers"] = "news:stock_tickers";
|
||||
TagNames["news:language"] = "news:language";
|
||||
TagNames["mobile:mobile"] = "mobile:mobile";
|
||||
TagNames["xhtml:link"] = "xhtml:link";
|
||||
TagNames["expires"] = "expires";
|
||||
})(TagNames || (TagNames = {}));
|
||||
export var IndexTagNames;
|
||||
(function (IndexTagNames) {
|
||||
IndexTagNames["sitemap"] = "sitemap";
|
||||
IndexTagNames["sitemapindex"] = "sitemapindex";
|
||||
IndexTagNames["loc"] = "loc";
|
||||
IndexTagNames["lastmod"] = "lastmod";
|
||||
})(IndexTagNames || (IndexTagNames = {}));
|
||||
48
node_modules/sitemap/dist/esm/lib/utils.d.ts
generated
vendored
Normal file
48
node_modules/sitemap/dist/esm/lib/utils.d.ts
generated
vendored
Normal file
@@ -0,0 +1,48 @@
|
||||
import { Readable, ReadableOptions, TransformOptions } from 'node:stream';
|
||||
import { SitemapItem, SitemapItemLoose } from './types.js';
|
||||
export { validateSMIOptions } from './validation.js';
|
||||
/**
|
||||
* Combines multiple streams into one
|
||||
* @param streams the streams to combine
|
||||
*/
|
||||
export declare function mergeStreams(streams: Readable[], options?: TransformOptions): Readable;
|
||||
export interface ReadlineStreamOptions extends ReadableOptions {
|
||||
input: Readable;
|
||||
}
|
||||
/**
|
||||
* Wraps node's ReadLine in a stream
|
||||
*/
|
||||
export declare class ReadlineStream extends Readable {
|
||||
private _source;
|
||||
constructor(options: ReadlineStreamOptions);
|
||||
_read(size: number): void;
|
||||
}
|
||||
/**
|
||||
* Takes a stream likely from fs.createReadStream('./path') and returns a stream
|
||||
* of sitemap items
|
||||
* @param stream a stream of line separated urls.
|
||||
* @param opts.isJSON is the stream line separated JSON. leave undefined to guess
|
||||
*/
|
||||
export declare function lineSeparatedURLsToSitemapOptions(stream: Readable, { isJSON }?: {
|
||||
isJSON?: boolean;
|
||||
}): Readable;
|
||||
/**
|
||||
* Based on lodash's implementation of chunk.
|
||||
*
|
||||
* Copyright JS Foundation and other contributors <https://js.foundation/>
|
||||
*
|
||||
* Based on Underscore.js, copyright Jeremy Ashkenas,
|
||||
* DocumentCloud and Investigative Reporters & Editors <http://underscorejs.org/>
|
||||
*
|
||||
* This software consists of voluntary contributions made by many
|
||||
* individuals. For exact contribution history, see the revision history
|
||||
* available at https://github.com/lodash/lodash
|
||||
*/
|
||||
export declare function chunk(array: any[], size?: number): any[];
|
||||
/**
|
||||
* Converts the passed in sitemap entry into one capable of being consumed by SitemapItem
|
||||
* @param {string | SitemapItemLoose} elem the string or object to be converted
|
||||
* @param {string} hostname
|
||||
* @returns SitemapItemOptions a strict sitemap item option
|
||||
*/
|
||||
export declare function normalizeURL(elem: string | SitemapItemLoose, hostname?: string, lastmodDateOnly?: boolean): SitemapItem;
|
||||
221
node_modules/sitemap/dist/esm/lib/utils.js
generated
vendored
Normal file
221
node_modules/sitemap/dist/esm/lib/utils.js
generated
vendored
Normal file
@@ -0,0 +1,221 @@
|
||||
/*!
|
||||
* Sitemap
|
||||
* Copyright(c) 2011 Eugene Kalinin
|
||||
* MIT Licensed
|
||||
*/
|
||||
import { statSync } from 'node:fs';
|
||||
import { Readable, Transform, PassThrough, } from 'node:stream';
|
||||
import { createInterface } from 'node:readline';
|
||||
import { URL } from 'node:url';
|
||||
import { EnumYesNo, } from './types.js';
|
||||
// Re-export validateSMIOptions from validation.ts for backward compatibility
|
||||
export { validateSMIOptions } from './validation.js';
|
||||
/**
|
||||
* Combines multiple streams into one
|
||||
* @param streams the streams to combine
|
||||
*/
|
||||
export function mergeStreams(streams, options) {
|
||||
let pass = new PassThrough(options);
|
||||
let waiting = streams.length;
|
||||
for (const stream of streams) {
|
||||
pass = stream.pipe(pass, { end: false });
|
||||
stream.once('end', () => --waiting === 0 && pass.emit('end'));
|
||||
}
|
||||
return pass;
|
||||
}
|
||||
/**
|
||||
* Wraps node's ReadLine in a stream
|
||||
*/
|
||||
export class ReadlineStream extends Readable {
|
||||
_source;
|
||||
constructor(options) {
|
||||
if (options.autoDestroy === undefined) {
|
||||
options.autoDestroy = true;
|
||||
}
|
||||
options.objectMode = true;
|
||||
super(options);
|
||||
this._source = createInterface({
|
||||
input: options.input,
|
||||
terminal: false,
|
||||
crlfDelay: Infinity,
|
||||
});
|
||||
// Every time there's data, push it into the internal buffer.
|
||||
this._source.on('line', (chunk) => {
|
||||
// If push() returns false, then stop reading from source.
|
||||
if (!this.push(chunk))
|
||||
this._source.pause();
|
||||
});
|
||||
// When the source ends, push the EOF-signaling `null` chunk.
|
||||
this._source.on('close', () => {
|
||||
this.push(null);
|
||||
});
|
||||
}
|
||||
// _read() will be called when the stream wants to pull more data in.
|
||||
// The advisory size argument is ignored in this case.
|
||||
_read(size) {
|
||||
this._source.resume();
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Takes a stream likely from fs.createReadStream('./path') and returns a stream
|
||||
* of sitemap items
|
||||
* @param stream a stream of line separated urls.
|
||||
* @param opts.isJSON is the stream line separated JSON. leave undefined to guess
|
||||
*/
|
||||
export function lineSeparatedURLsToSitemapOptions(stream, { isJSON } = {}) {
|
||||
return new ReadlineStream({ input: stream }).pipe(new Transform({
|
||||
objectMode: true,
|
||||
transform: (line, encoding, cb) => {
|
||||
if (isJSON || (isJSON === undefined && line[0] === '{')) {
|
||||
cb(null, JSON.parse(line));
|
||||
}
|
||||
else {
|
||||
cb(null, line);
|
||||
}
|
||||
},
|
||||
}));
|
||||
}
|
||||
/**
|
||||
* Based on lodash's implementation of chunk.
|
||||
*
|
||||
* Copyright JS Foundation and other contributors <https://js.foundation/>
|
||||
*
|
||||
* Based on Underscore.js, copyright Jeremy Ashkenas,
|
||||
* DocumentCloud and Investigative Reporters & Editors <http://underscorejs.org/>
|
||||
*
|
||||
* This software consists of voluntary contributions made by many
|
||||
* individuals. For exact contribution history, see the revision history
|
||||
* available at https://github.com/lodash/lodash
|
||||
*/
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
export function chunk(array, size = 1) {
|
||||
size = Math.max(Math.trunc(size), 0);
|
||||
const length = array ? array.length : 0;
|
||||
if (!length || size < 1) {
|
||||
return [];
|
||||
}
|
||||
const result = Array(Math.ceil(length / size));
|
||||
let index = 0, resIndex = 0;
|
||||
while (index < length) {
|
||||
result[resIndex++] = array.slice(index, (index += size));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
function boolToYESNO(bool) {
|
||||
if (bool === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
if (typeof bool === 'boolean') {
|
||||
return bool ? EnumYesNo.yes : EnumYesNo.no;
|
||||
}
|
||||
return bool;
|
||||
}
|
||||
/**
|
||||
* Converts the passed in sitemap entry into one capable of being consumed by SitemapItem
|
||||
* @param {string | SitemapItemLoose} elem the string or object to be converted
|
||||
* @param {string} hostname
|
||||
* @returns SitemapItemOptions a strict sitemap item option
|
||||
*/
|
||||
export function normalizeURL(elem, hostname, lastmodDateOnly = false) {
|
||||
// SitemapItem
|
||||
// create object with url property
|
||||
const smi = {
|
||||
img: [],
|
||||
video: [],
|
||||
links: [],
|
||||
url: '',
|
||||
};
|
||||
if (typeof elem === 'string') {
|
||||
smi.url = new URL(elem, hostname).toString();
|
||||
return smi;
|
||||
}
|
||||
const { url, img, links, video, lastmodfile, lastmodISO, lastmod, ...other } = elem;
|
||||
Object.assign(smi, other);
|
||||
smi.url = new URL(url, hostname).toString();
|
||||
if (img) {
|
||||
// prepend hostname to all image urls
|
||||
smi.img = (Array.isArray(img) ? img : [img]).map((el) => typeof el === 'string'
|
||||
? { url: new URL(el, hostname).toString() }
|
||||
: { ...el, url: new URL(el.url, hostname).toString() });
|
||||
}
|
||||
if (links) {
|
||||
smi.links = links.map((link) => ({
|
||||
...link,
|
||||
url: new URL(link.url, hostname).toString(),
|
||||
}));
|
||||
}
|
||||
if (video) {
|
||||
smi.video = (Array.isArray(video) ? video : [video]).map((video) => {
|
||||
const nv = {
|
||||
...video,
|
||||
family_friendly: boolToYESNO(video.family_friendly),
|
||||
live: boolToYESNO(video.live),
|
||||
requires_subscription: boolToYESNO(video.requires_subscription),
|
||||
tag: [],
|
||||
rating: undefined,
|
||||
};
|
||||
if (video.tag !== undefined) {
|
||||
nv.tag = !Array.isArray(video.tag) ? [video.tag] : video.tag;
|
||||
}
|
||||
if (video.rating !== undefined) {
|
||||
if (typeof video.rating === 'string') {
|
||||
const parsedRating = parseFloat(video.rating);
|
||||
// Validate parsed rating is a valid number
|
||||
if (Number.isNaN(parsedRating)) {
|
||||
throw new Error(`Invalid video rating "${video.rating}" for URL "${elem.url}": must be a valid number`);
|
||||
}
|
||||
nv.rating = parsedRating;
|
||||
}
|
||||
else {
|
||||
nv.rating = video.rating;
|
||||
}
|
||||
}
|
||||
if (typeof video.view_count === 'string') {
|
||||
const parsedViewCount = parseInt(video.view_count, 10);
|
||||
// Validate parsed view count is a valid non-negative integer
|
||||
if (Number.isNaN(parsedViewCount)) {
|
||||
throw new Error(`Invalid video view_count "${video.view_count}" for URL "${elem.url}": must be a valid number`);
|
||||
}
|
||||
if (parsedViewCount < 0) {
|
||||
throw new Error(`Invalid video view_count "${video.view_count}" for URL "${elem.url}": cannot be negative`);
|
||||
}
|
||||
nv.view_count = parsedViewCount;
|
||||
}
|
||||
else if (typeof video.view_count === 'number') {
|
||||
nv.view_count = video.view_count;
|
||||
}
|
||||
return nv;
|
||||
});
|
||||
}
|
||||
// If given a file to use for last modified date
|
||||
if (lastmodfile) {
|
||||
const { mtime } = statSync(lastmodfile);
|
||||
const lastmodDate = new Date(mtime);
|
||||
// Validate date is valid
|
||||
if (Number.isNaN(lastmodDate.getTime())) {
|
||||
throw new Error(`Invalid date from file stats for URL "${smi.url}": file modification time is invalid`);
|
||||
}
|
||||
smi.lastmod = lastmodDate.toISOString();
|
||||
// The date of last modification (YYYY-MM-DD)
|
||||
}
|
||||
else if (lastmodISO) {
|
||||
const lastmodDate = new Date(lastmodISO);
|
||||
// Validate date is valid
|
||||
if (Number.isNaN(lastmodDate.getTime())) {
|
||||
throw new Error(`Invalid lastmodISO "${lastmodISO}" for URL "${smi.url}": must be a valid date string`);
|
||||
}
|
||||
smi.lastmod = lastmodDate.toISOString();
|
||||
}
|
||||
else if (lastmod) {
|
||||
const lastmodDate = new Date(lastmod);
|
||||
// Validate date is valid
|
||||
if (Number.isNaN(lastmodDate.getTime())) {
|
||||
throw new Error(`Invalid lastmod "${lastmod}" for URL "${smi.url}": must be a valid date string`);
|
||||
}
|
||||
smi.lastmod = lastmodDate.toISOString();
|
||||
}
|
||||
if (lastmodDateOnly && smi.lastmod) {
|
||||
smi.lastmod = smi.lastmod.slice(0, 10);
|
||||
}
|
||||
return smi;
|
||||
}
|
||||
94
node_modules/sitemap/dist/esm/lib/validation.d.ts
generated
vendored
Normal file
94
node_modules/sitemap/dist/esm/lib/validation.d.ts
generated
vendored
Normal file
@@ -0,0 +1,94 @@
|
||||
/*!
|
||||
* Sitemap
|
||||
* Copyright(c) 2011 Eugene Kalinin
|
||||
* MIT Licensed
|
||||
*/
|
||||
import { SitemapItem, ErrorLevel, EnumChangefreq, EnumYesNo, EnumAllowDeny, PriceType, Resolution, ErrorHandler } from './types.js';
|
||||
export declare const validators: {
|
||||
[index: string]: RegExp;
|
||||
};
|
||||
/**
|
||||
* Type guard to check if a string is a valid price type
|
||||
*/
|
||||
export declare function isPriceType(pt: string | PriceType): pt is PriceType;
|
||||
/**
|
||||
* Type guard to check if a string is a valid resolution
|
||||
*/
|
||||
export declare function isResolution(res: string): res is Resolution;
|
||||
export declare function isValidChangeFreq(freq: string): freq is EnumChangefreq;
|
||||
/**
|
||||
* Type guard to check if a string is a valid yes/no value
|
||||
*/
|
||||
export declare function isValidYesNo(yn: string): yn is EnumYesNo;
|
||||
/**
|
||||
* Type guard to check if a string is a valid allow/deny value
|
||||
*/
|
||||
export declare function isAllowDeny(ad: string): ad is EnumAllowDeny;
|
||||
/**
|
||||
* Validates that a URL is well-formed and meets security requirements
|
||||
*
|
||||
* Security: This function enforces that URLs use safe protocols (http/https),
|
||||
* are within reasonable length limits (2048 chars per sitemaps.org spec),
|
||||
* and can be properly parsed. This prevents protocol injection attacks and
|
||||
* ensures compliance with sitemap specifications.
|
||||
*
|
||||
* @param url - The URL to validate
|
||||
* @param paramName - The parameter name for error messages
|
||||
* @throws {InvalidHostnameError} If the URL is invalid
|
||||
*/
|
||||
export declare function validateURL(url: string, paramName: string): void;
|
||||
/**
|
||||
* Validates that a path doesn't contain path traversal sequences
|
||||
*
|
||||
* Security: This function prevents path traversal attacks by detecting
|
||||
* any occurrence of '..' in the path, whether it appears as '../', '/..',
|
||||
* or standalone. This prevents attackers from accessing files outside
|
||||
* the intended directory structure.
|
||||
*
|
||||
* @param path - The path to validate
|
||||
* @param paramName - The parameter name for error messages
|
||||
* @throws {InvalidPathError} If the path contains traversal sequences
|
||||
*/
|
||||
export declare function validatePath(path: string, paramName: string): void;
|
||||
/**
|
||||
* Validates that a public base path is safe for URL construction
|
||||
*
|
||||
* Security: This function prevents path traversal attacks and validates
|
||||
* that the path is safe for use in URL construction within sitemap indexes.
|
||||
* It checks for '..' sequences, null bytes, and invalid whitespace that
|
||||
* could be used to manipulate URL structure or inject malicious content.
|
||||
*
|
||||
* @param publicBasePath - The public base path to validate
|
||||
* @throws {InvalidPublicBasePathError} If the path is invalid
|
||||
*/
|
||||
export declare function validatePublicBasePath(publicBasePath: string): void;
|
||||
/**
|
||||
* Validates that a limit is within acceptable range per sitemaps.org spec
|
||||
*
|
||||
* Security: This function enforces sitemap size limits (1-50,000 URLs per
|
||||
* sitemap) as specified by sitemaps.org. This prevents resource exhaustion
|
||||
* attacks and ensures compliance with search engine requirements.
|
||||
*
|
||||
* @param limit - The limit to validate
|
||||
* @throws {InvalidLimitError} If the limit is out of range
|
||||
*/
|
||||
export declare function validateLimit(limit: number): void;
|
||||
/**
|
||||
* Validates that an XSL URL is safe and well-formed
|
||||
*
|
||||
* Security: This function validates XSL stylesheet URLs to prevent
|
||||
* injection attacks. It blocks dangerous protocols and content patterns
|
||||
* that could be used for XSS or other attacks. The validation uses
|
||||
* case-insensitive matching to catch obfuscated attacks.
|
||||
*
|
||||
* @param xslUrl - The XSL URL to validate
|
||||
* @throws {InvalidXSLUrlError} If the URL is invalid
|
||||
*/
|
||||
export declare function validateXSLUrl(xslUrl: string): void;
|
||||
/**
|
||||
* Verifies all data passed in will comply with sitemap spec.
|
||||
* @param conf Options to validate
|
||||
* @param level logging level
|
||||
* @param errorHandler error handling func
|
||||
*/
|
||||
export declare function validateSMIOptions(conf: SitemapItem, level?: ErrorLevel, errorHandler?: ErrorHandler): SitemapItem;
|
||||
384
node_modules/sitemap/dist/esm/lib/validation.js
generated
vendored
Normal file
384
node_modules/sitemap/dist/esm/lib/validation.js
generated
vendored
Normal file
@@ -0,0 +1,384 @@
|
||||
/*!
|
||||
* Sitemap
|
||||
* Copyright(c) 2011 Eugene Kalinin
|
||||
* MIT Licensed
|
||||
*/
|
||||
import { InvalidPathError, InvalidHostnameError, InvalidLimitError, InvalidPublicBasePathError, InvalidXSLUrlError, ChangeFreqInvalidError, InvalidAttrValue, InvalidNewsAccessValue, InvalidNewsFormat, InvalidVideoDescription, InvalidVideoDuration, InvalidVideoFormat, InvalidVideoRating, NoURLError, NoConfigError, PriorityInvalidError, InvalidVideoTitle, InvalidVideoViewCount, InvalidVideoTagCount, InvalidVideoCategory, InvalidVideoFamilyFriendly, InvalidVideoRestriction, InvalidVideoRestrictionRelationship, InvalidVideoPriceType, InvalidVideoResolution, InvalidVideoPriceCurrency, } from './errors.js';
|
||||
import { ErrorLevel, EnumChangefreq, } from './types.js';
|
||||
import { LIMITS } from './constants.js';
|
||||
import { isAbsolute } from 'node:path';
|
||||
/**
|
||||
* Validator regular expressions for various sitemap fields
|
||||
*/
|
||||
const allowDeny = /^(?:allow|deny)$/;
|
||||
export const validators = {
|
||||
'price:currency': /^[A-Z]{3}$/,
|
||||
'price:type': /^(?:rent|purchase|RENT|PURCHASE)$/,
|
||||
'price:resolution': /^(?:HD|hd|sd|SD)$/,
|
||||
'platform:relationship': allowDeny,
|
||||
'restriction:relationship': allowDeny,
|
||||
restriction: /^([A-Z]{2}( +[A-Z]{2})*)?$/,
|
||||
platform: /^((web|mobile|tv)( (web|mobile|tv))*)?$/,
|
||||
// Language codes: zh-cn, zh-tw, or ISO 639 2-3 letter codes
|
||||
language: /^(zh-cn|zh-tw|[a-z]{2,3})$/,
|
||||
genres: /^(PressRelease|Satire|Blog|OpEd|Opinion|UserGenerated)(, *(PressRelease|Satire|Blog|OpEd|Opinion|UserGenerated))*$/,
|
||||
stock_tickers: /^(\w+:\w+(, *\w+:\w+){0,4})?$/,
|
||||
};
|
||||
/**
|
||||
* Type guard to check if a string is a valid price type
|
||||
*/
|
||||
export function isPriceType(pt) {
|
||||
return validators['price:type'].test(pt);
|
||||
}
|
||||
/**
|
||||
* Type guard to check if a string is a valid resolution
|
||||
*/
|
||||
export function isResolution(res) {
|
||||
return validators['price:resolution'].test(res);
|
||||
}
|
||||
/**
|
||||
* Type guard to check if a string is a valid changefreq value
|
||||
*/
|
||||
const CHANGEFREQ = Object.values(EnumChangefreq);
|
||||
export function isValidChangeFreq(freq) {
|
||||
return CHANGEFREQ.includes(freq);
|
||||
}
|
||||
/**
|
||||
* Type guard to check if a string is a valid yes/no value
|
||||
*/
|
||||
export function isValidYesNo(yn) {
|
||||
return /^YES|NO|[Yy]es|[Nn]o$/.test(yn);
|
||||
}
|
||||
/**
|
||||
* Type guard to check if a string is a valid allow/deny value
|
||||
*/
|
||||
export function isAllowDeny(ad) {
|
||||
return allowDeny.test(ad);
|
||||
}
|
||||
/**
|
||||
* Validates that a URL is well-formed and meets security requirements
|
||||
*
|
||||
* Security: This function enforces that URLs use safe protocols (http/https),
|
||||
* are within reasonable length limits (2048 chars per sitemaps.org spec),
|
||||
* and can be properly parsed. This prevents protocol injection attacks and
|
||||
* ensures compliance with sitemap specifications.
|
||||
*
|
||||
* @param url - The URL to validate
|
||||
* @param paramName - The parameter name for error messages
|
||||
* @throws {InvalidHostnameError} If the URL is invalid
|
||||
*/
|
||||
export function validateURL(url, paramName) {
|
||||
if (!url || typeof url !== 'string') {
|
||||
throw new InvalidHostnameError(url, `${paramName} must be a non-empty string`);
|
||||
}
|
||||
if (url.length > LIMITS.MAX_URL_LENGTH) {
|
||||
throw new InvalidHostnameError(url, `${paramName} exceeds maximum length of ${LIMITS.MAX_URL_LENGTH} characters`);
|
||||
}
|
||||
if (!LIMITS.URL_PROTOCOL_REGEX.test(url)) {
|
||||
throw new InvalidHostnameError(url, `${paramName} must use http:// or https:// protocol`);
|
||||
}
|
||||
// Validate URL can be parsed
|
||||
try {
|
||||
new URL(url);
|
||||
}
|
||||
catch (err) {
|
||||
throw new InvalidHostnameError(url, `${paramName} is not a valid URL: ${err instanceof Error ? err.message : String(err)}`);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Validates that a path doesn't contain path traversal sequences
|
||||
*
|
||||
* Security: This function prevents path traversal attacks by detecting
|
||||
* any occurrence of '..' in the path, whether it appears as '../', '/..',
|
||||
* or standalone. This prevents attackers from accessing files outside
|
||||
* the intended directory structure.
|
||||
*
|
||||
* @param path - The path to validate
|
||||
* @param paramName - The parameter name for error messages
|
||||
* @throws {InvalidPathError} If the path contains traversal sequences
|
||||
*/
|
||||
export function validatePath(path, paramName) {
|
||||
if (!path || typeof path !== 'string') {
|
||||
throw new InvalidPathError(path, `${paramName} must be a non-empty string`);
|
||||
}
|
||||
// Reject absolute paths to prevent arbitrary write location when caller input
|
||||
// reaches destinationDir (BB-04)
|
||||
if (isAbsolute(path)) {
|
||||
throw new InvalidPathError(path, `${paramName} must be a relative path (absolute paths are not allowed)`);
|
||||
}
|
||||
// Check for path traversal sequences - must check before and after normalization
|
||||
// to catch both Windows-style (\) and Unix-style (/) separators
|
||||
if (path.includes('..')) {
|
||||
throw new InvalidPathError(path, `${paramName} contains path traversal sequence (..)`);
|
||||
}
|
||||
// Additional check after normalization to catch encoded or obfuscated attempts
|
||||
const normalizedPath = path.replace(/\\/g, '/');
|
||||
const pathComponents = normalizedPath.split('/').filter((p) => p.length > 0);
|
||||
if (pathComponents.includes('..')) {
|
||||
throw new InvalidPathError(path, `${paramName} contains path traversal sequence (..)`);
|
||||
}
|
||||
// Check for null bytes (security issue in some contexts)
|
||||
if (path.includes('\0')) {
|
||||
throw new InvalidPathError(path, `${paramName} contains null byte character`);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Validates that a public base path is safe for URL construction
|
||||
*
|
||||
* Security: This function prevents path traversal attacks and validates
|
||||
* that the path is safe for use in URL construction within sitemap indexes.
|
||||
* It checks for '..' sequences, null bytes, and invalid whitespace that
|
||||
* could be used to manipulate URL structure or inject malicious content.
|
||||
*
|
||||
* @param publicBasePath - The public base path to validate
|
||||
* @throws {InvalidPublicBasePathError} If the path is invalid
|
||||
*/
|
||||
export function validatePublicBasePath(publicBasePath) {
|
||||
if (!publicBasePath || typeof publicBasePath !== 'string') {
|
||||
throw new InvalidPublicBasePathError(publicBasePath, 'must be a non-empty string');
|
||||
}
|
||||
// Check for path traversal - check the raw string first
|
||||
if (publicBasePath.includes('..')) {
|
||||
throw new InvalidPublicBasePathError(publicBasePath, 'contains path traversal sequence (..)');
|
||||
}
|
||||
// Additional check for path components after normalization
|
||||
const normalizedPath = publicBasePath.replace(/\\/g, '/');
|
||||
const pathComponents = normalizedPath.split('/').filter((p) => p.length > 0);
|
||||
if (pathComponents.includes('..')) {
|
||||
throw new InvalidPublicBasePathError(publicBasePath, 'contains path traversal sequence (..)');
|
||||
}
|
||||
// Check for null bytes
|
||||
if (publicBasePath.includes('\0')) {
|
||||
throw new InvalidPublicBasePathError(publicBasePath, 'contains null byte character');
|
||||
}
|
||||
// Check for potentially dangerous characters that could break URL construction
|
||||
if (/[\r\n\t]/.test(publicBasePath)) {
|
||||
throw new InvalidPublicBasePathError(publicBasePath, 'contains invalid whitespace characters');
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Validates that a limit is within acceptable range per sitemaps.org spec
|
||||
*
|
||||
* Security: This function enforces sitemap size limits (1-50,000 URLs per
|
||||
* sitemap) as specified by sitemaps.org. This prevents resource exhaustion
|
||||
* attacks and ensures compliance with search engine requirements.
|
||||
*
|
||||
* @param limit - The limit to validate
|
||||
* @throws {InvalidLimitError} If the limit is out of range
|
||||
*/
|
||||
export function validateLimit(limit) {
|
||||
if (typeof limit !== 'number' ||
|
||||
!Number.isFinite(limit) ||
|
||||
Number.isNaN(limit)) {
|
||||
throw new InvalidLimitError(limit);
|
||||
}
|
||||
if (limit < LIMITS.MIN_SITEMAP_ITEM_LIMIT ||
|
||||
limit > LIMITS.MAX_SITEMAP_ITEM_LIMIT) {
|
||||
throw new InvalidLimitError(limit);
|
||||
}
|
||||
// Ensure it's an integer
|
||||
if (!Number.isInteger(limit)) {
|
||||
throw new InvalidLimitError(limit);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Validates that an XSL URL is safe and well-formed
|
||||
*
|
||||
* Security: This function validates XSL stylesheet URLs to prevent
|
||||
* injection attacks. It blocks dangerous protocols and content patterns
|
||||
* that could be used for XSS or other attacks. The validation uses
|
||||
* case-insensitive matching to catch obfuscated attacks.
|
||||
*
|
||||
* @param xslUrl - The XSL URL to validate
|
||||
* @throws {InvalidXSLUrlError} If the URL is invalid
|
||||
*/
|
||||
export function validateXSLUrl(xslUrl) {
|
||||
if (!xslUrl || typeof xslUrl !== 'string') {
|
||||
throw new InvalidXSLUrlError(xslUrl, 'must be a non-empty string');
|
||||
}
|
||||
if (xslUrl.length > LIMITS.MAX_URL_LENGTH) {
|
||||
throw new InvalidXSLUrlError(xslUrl, `exceeds maximum length of ${LIMITS.MAX_URL_LENGTH} characters`);
|
||||
}
|
||||
if (!LIMITS.URL_PROTOCOL_REGEX.test(xslUrl)) {
|
||||
throw new InvalidXSLUrlError(xslUrl, 'must use http:// or https:// protocol');
|
||||
}
|
||||
// Validate URL can be parsed
|
||||
try {
|
||||
new URL(xslUrl);
|
||||
}
|
||||
catch (err) {
|
||||
throw new InvalidXSLUrlError(xslUrl, `is not a valid URL: ${err instanceof Error ? err.message : String(err)}`);
|
||||
}
|
||||
// Check for potentially dangerous content (case-insensitive)
|
||||
const lowerUrl = xslUrl.toLowerCase();
|
||||
// Block dangerous HTML/script content
|
||||
if (lowerUrl.includes('<script')) {
|
||||
throw new InvalidXSLUrlError(xslUrl, 'contains potentially malicious content (<script tag)');
|
||||
}
|
||||
// Block dangerous protocols (already checked http/https above, but double-check for encoded variants)
|
||||
const dangerousProtocols = [
|
||||
'javascript:',
|
||||
'data:',
|
||||
'vbscript:',
|
||||
'file:',
|
||||
'about:',
|
||||
];
|
||||
for (const protocol of dangerousProtocols) {
|
||||
if (lowerUrl.includes(protocol)) {
|
||||
throw new InvalidXSLUrlError(xslUrl, `contains dangerous protocol: ${protocol}`);
|
||||
}
|
||||
}
|
||||
// Check for URL-encoded variants of dangerous patterns
|
||||
// %3C = '<', %3E = '>', %3A = ':'
|
||||
const encodedPatterns = [
|
||||
'%3cscript', // <script
|
||||
'%3c%73%63%72%69%70%74', // <script (fully encoded)
|
||||
'javascript%3a', // javascript:
|
||||
'data%3a', // data:
|
||||
];
|
||||
for (const pattern of encodedPatterns) {
|
||||
if (lowerUrl.includes(pattern)) {
|
||||
throw new InvalidXSLUrlError(xslUrl, 'contains URL-encoded malicious content');
|
||||
}
|
||||
}
|
||||
// Reject unencoded XML special characters — these must be percent-encoded in
|
||||
// valid URLs and could break out of XML attribute context if left raw.
|
||||
if (xslUrl.includes('"') || xslUrl.includes('<') || xslUrl.includes('>')) {
|
||||
throw new InvalidXSLUrlError(xslUrl, 'contains unencoded XML special characters (" < >); percent-encode them in the URL');
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Internal helper to validate fields against their validators
|
||||
*/
|
||||
function validate(subject, name, url, level) {
|
||||
Object.keys(subject).forEach((key) => {
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
const val = subject[key];
|
||||
if (validators[key] && !validators[key].test(val)) {
|
||||
if (level === ErrorLevel.THROW) {
|
||||
throw new InvalidAttrValue(key, val, validators[key]);
|
||||
}
|
||||
else {
|
||||
console.warn(`${url}: ${name} key ${key} has invalid value: ${val}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Internal helper to handle errors based on error level
|
||||
*/
|
||||
function handleError(error, level) {
|
||||
if (level === ErrorLevel.THROW) {
|
||||
throw error;
|
||||
}
|
||||
else if (level === ErrorLevel.WARN) {
|
||||
console.warn(error.name, error.message);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Verifies all data passed in will comply with sitemap spec.
|
||||
* @param conf Options to validate
|
||||
* @param level logging level
|
||||
* @param errorHandler error handling func
|
||||
*/
|
||||
export function validateSMIOptions(conf, level = ErrorLevel.WARN, errorHandler = handleError) {
|
||||
if (!conf) {
|
||||
throw new NoConfigError();
|
||||
}
|
||||
if (level === ErrorLevel.SILENT) {
|
||||
return conf;
|
||||
}
|
||||
const { url, changefreq, priority, news, video } = conf;
|
||||
if (!url) {
|
||||
errorHandler(new NoURLError(), level);
|
||||
}
|
||||
if (changefreq) {
|
||||
if (!isValidChangeFreq(changefreq)) {
|
||||
errorHandler(new ChangeFreqInvalidError(url, changefreq), level);
|
||||
}
|
||||
}
|
||||
if (priority) {
|
||||
if (!(priority >= 0.0 && priority <= 1.0)) {
|
||||
errorHandler(new PriorityInvalidError(url, priority), level);
|
||||
}
|
||||
}
|
||||
if (news) {
|
||||
if (news.access &&
|
||||
news.access !== 'Registration' &&
|
||||
news.access !== 'Subscription') {
|
||||
errorHandler(new InvalidNewsAccessValue(url, news.access), level);
|
||||
}
|
||||
if (!news.publication ||
|
||||
!news.publication.name ||
|
||||
!news.publication.language ||
|
||||
!news.publication_date ||
|
||||
!news.title) {
|
||||
errorHandler(new InvalidNewsFormat(url), level);
|
||||
}
|
||||
validate(news, 'news', url, level);
|
||||
validate(news.publication, 'publication', url, level);
|
||||
}
|
||||
if (video) {
|
||||
video.forEach((vid) => {
|
||||
if (vid.duration !== undefined) {
|
||||
if (vid.duration < 0 || vid.duration > 28800) {
|
||||
errorHandler(new InvalidVideoDuration(url, vid.duration), level);
|
||||
}
|
||||
}
|
||||
if (vid.rating !== undefined && (vid.rating < 0 || vid.rating > 5)) {
|
||||
errorHandler(new InvalidVideoRating(url, vid.title, vid.rating), level);
|
||||
}
|
||||
if (typeof vid !== 'object' ||
|
||||
!vid.thumbnail_loc ||
|
||||
!vid.title ||
|
||||
!vid.description) {
|
||||
// has to be an object and include required categories https://support.google.com/webmasters/answer/80471?hl=en&ref_topic=4581190
|
||||
errorHandler(new InvalidVideoFormat(url), level);
|
||||
}
|
||||
if (vid.title.length > 100) {
|
||||
errorHandler(new InvalidVideoTitle(url, vid.title.length), level);
|
||||
}
|
||||
if (vid.description.length > 2048) {
|
||||
errorHandler(new InvalidVideoDescription(url, vid.description.length), level);
|
||||
}
|
||||
if (vid.view_count !== undefined && vid.view_count < 0) {
|
||||
errorHandler(new InvalidVideoViewCount(url, vid.view_count), level);
|
||||
}
|
||||
if (vid.tag.length > 32) {
|
||||
errorHandler(new InvalidVideoTagCount(url, vid.tag.length), level);
|
||||
}
|
||||
if (vid.category !== undefined && vid.category?.length > 256) {
|
||||
errorHandler(new InvalidVideoCategory(url, vid.category.length), level);
|
||||
}
|
||||
if (vid.family_friendly !== undefined &&
|
||||
!isValidYesNo(vid.family_friendly)) {
|
||||
errorHandler(new InvalidVideoFamilyFriendly(url, vid.family_friendly), level);
|
||||
}
|
||||
if (vid.restriction) {
|
||||
if (!validators.restriction.test(vid.restriction)) {
|
||||
errorHandler(new InvalidVideoRestriction(url, vid.restriction), level);
|
||||
}
|
||||
if (!vid['restriction:relationship'] ||
|
||||
!isAllowDeny(vid['restriction:relationship'])) {
|
||||
errorHandler(new InvalidVideoRestrictionRelationship(url, vid['restriction:relationship']), level);
|
||||
}
|
||||
}
|
||||
// TODO price element should be unbounded
|
||||
if ((vid.price === '' && vid['price:type'] === undefined) ||
|
||||
(vid['price:type'] !== undefined && !isPriceType(vid['price:type']))) {
|
||||
errorHandler(new InvalidVideoPriceType(url, vid['price:type'], vid.price), level);
|
||||
}
|
||||
if (vid['price:resolution'] !== undefined &&
|
||||
!isResolution(vid['price:resolution'])) {
|
||||
errorHandler(new InvalidVideoResolution(url, vid['price:resolution']), level);
|
||||
}
|
||||
if (vid['price:currency'] !== undefined &&
|
||||
!validators['price:currency'].test(vid['price:currency'])) {
|
||||
errorHandler(new InvalidVideoPriceCurrency(url, vid['price:currency']), level);
|
||||
}
|
||||
validate(vid, 'video', url, level);
|
||||
});
|
||||
}
|
||||
return conf;
|
||||
}
|
||||
12
node_modules/sitemap/dist/esm/lib/xmllint.d.ts
generated
vendored
Normal file
12
node_modules/sitemap/dist/esm/lib/xmllint.d.ts
generated
vendored
Normal file
@@ -0,0 +1,12 @@
|
||||
import { Readable } from 'node:stream';
|
||||
/**
|
||||
* Verify the passed in xml is valid. Requires xmllib be installed
|
||||
*
|
||||
* Security: This function always pipes XML content via stdin to prevent
|
||||
* command injection vulnerabilities. Never pass user-controlled strings
|
||||
* as file path arguments to xmllint.
|
||||
*
|
||||
* @param xml what you want validated (string or Readable stream)
|
||||
* @return {Promise<void>} resolves on valid rejects [error stderr]
|
||||
*/
|
||||
export declare function xmlLint(xml: string | Readable): Promise<void>;
|
||||
78
node_modules/sitemap/dist/esm/lib/xmllint.js
generated
vendored
Normal file
78
node_modules/sitemap/dist/esm/lib/xmllint.js
generated
vendored
Normal file
@@ -0,0 +1,78 @@
|
||||
import { existsSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import { execFile } from 'node:child_process';
|
||||
import { XMLLintUnavailable } from './errors.js';
|
||||
/**
|
||||
* Finds the `schema` directory with robust path resolution.
|
||||
* Searches from the project root directory using process.cwd().
|
||||
* This works correctly regardless of whether the code is running from:
|
||||
* - Source: lib/xmllint.ts
|
||||
* - ESM build: dist/esm/lib/xmllint.js
|
||||
* - CJS build: dist/cjs/lib/xmllint.js
|
||||
* - Test environment
|
||||
*
|
||||
* @throws {Error} if the schema directory is not found
|
||||
* @returns {string} the path to the schema directory
|
||||
*/
|
||||
function findSchemaDir() {
|
||||
// Search for schema directory from project root
|
||||
// This works in test, build, and source environments
|
||||
const possiblePaths = [
|
||||
resolve(process.cwd(), 'schema'), // From project root
|
||||
resolve(process.cwd(), '..', 'schema'), // One level up
|
||||
resolve(process.cwd(), '..', '..', 'schema'), // Two levels up
|
||||
];
|
||||
for (const schemaPath of possiblePaths) {
|
||||
if (existsSync(schemaPath)) {
|
||||
return schemaPath;
|
||||
}
|
||||
}
|
||||
throw new Error(`Schema directory not found. Searched paths: ${possiblePaths.join(', ')}`);
|
||||
}
|
||||
/**
|
||||
* Verify the passed in xml is valid. Requires xmllib be installed
|
||||
*
|
||||
* Security: This function always pipes XML content via stdin to prevent
|
||||
* command injection vulnerabilities. Never pass user-controlled strings
|
||||
* as file path arguments to xmllint.
|
||||
*
|
||||
* @param xml what you want validated (string or Readable stream)
|
||||
* @return {Promise<void>} resolves on valid rejects [error stderr]
|
||||
*/
|
||||
export function xmlLint(xml) {
|
||||
const args = [
|
||||
'--schema',
|
||||
resolve(findSchemaDir(), 'all.xsd'),
|
||||
'--noout',
|
||||
'-', // Always read from stdin for security
|
||||
];
|
||||
return new Promise((resolve, reject) => {
|
||||
execFile('which', ['xmllint'], (error, stdout, stderr) => {
|
||||
if (error) {
|
||||
reject([new XMLLintUnavailable()]);
|
||||
return;
|
||||
}
|
||||
const xmllint = execFile('xmllint', args, (error, stdout, stderr) => {
|
||||
if (error) {
|
||||
reject([error, stderr]);
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
// Always pipe XML content via stdin for security
|
||||
if (xmllint.stdin) {
|
||||
if (typeof xml === 'string') {
|
||||
// Convert string to stream and pipe to stdin
|
||||
xmllint.stdin.write(xml);
|
||||
xmllint.stdin.end();
|
||||
}
|
||||
else if (xml) {
|
||||
// Pipe readable stream to stdin
|
||||
xml.pipe(xmllint.stdin);
|
||||
}
|
||||
}
|
||||
if (xmllint.stdout) {
|
||||
xmllint.stdout.unpipe();
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
102
node_modules/sitemap/eslint.config.mjs
generated
vendored
Normal file
102
node_modules/sitemap/eslint.config.mjs
generated
vendored
Normal file
@@ -0,0 +1,102 @@
|
||||
import { defineConfig, globalIgnores } from "eslint/config";
|
||||
import jest from "eslint-plugin-jest";
|
||||
import typescriptEslint from "@typescript-eslint/eslint-plugin";
|
||||
import globals from "globals";
|
||||
import tsParser from "@typescript-eslint/parser";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import js from "@eslint/js";
|
||||
import { FlatCompat } from "@eslint/eslintrc";
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
const compat = new FlatCompat({
|
||||
baseDirectory: __dirname,
|
||||
recommendedConfig: js.configs.recommended,
|
||||
allConfig: js.configs.all
|
||||
});
|
||||
|
||||
export default defineConfig([globalIgnores([
|
||||
"test/",
|
||||
"**/__test__",
|
||||
"**/__tests__",
|
||||
"**/node_modules",
|
||||
"node_modules/",
|
||||
"**/node_modules/",
|
||||
"**/.idea",
|
||||
"**/.nyc_output",
|
||||
"**/coverage",
|
||||
"**/*.d.ts",
|
||||
"bin/**/*",
|
||||
]), {
|
||||
extends: compat.extends(
|
||||
"eslint:recommended",
|
||||
"plugin:@typescript-eslint/eslint-recommended",
|
||||
"plugin:@typescript-eslint/recommended",
|
||||
"prettier",
|
||||
"plugin:prettier/recommended",
|
||||
),
|
||||
|
||||
plugins: {
|
||||
jest,
|
||||
"@typescript-eslint": typescriptEslint,
|
||||
},
|
||||
|
||||
languageOptions: {
|
||||
globals: {
|
||||
...globals.jest,
|
||||
...globals.node,
|
||||
},
|
||||
|
||||
parser: tsParser,
|
||||
ecmaVersion: 2023,
|
||||
sourceType: "module",
|
||||
},
|
||||
|
||||
rules: {
|
||||
indent: "off",
|
||||
|
||||
"lines-between-class-members": ["error", "always", {
|
||||
exceptAfterSingleLine: true,
|
||||
}],
|
||||
|
||||
"no-case-declarations": 0,
|
||||
"no-console": 0,
|
||||
"no-dupe-class-members": "off",
|
||||
"no-unused-vars": 0,
|
||||
|
||||
"padding-line-between-statements": ["error", {
|
||||
blankLine: "always",
|
||||
prev: "multiline-expression",
|
||||
next: "multiline-expression",
|
||||
}],
|
||||
|
||||
"@typescript-eslint/ban-ts-comment": ["error", {
|
||||
"ts-expect-error": "allow-with-description",
|
||||
}],
|
||||
|
||||
"@typescript-eslint/explicit-member-accessibility": "off",
|
||||
|
||||
"@typescript-eslint/naming-convention": ["error", {
|
||||
selector: "default",
|
||||
format: null,
|
||||
}, {
|
||||
selector: "interface",
|
||||
prefix: [],
|
||||
format: null,
|
||||
}],
|
||||
|
||||
"@typescript-eslint/no-parameter-properties": "off",
|
||||
|
||||
"@typescript-eslint/no-unused-vars": ["error", {
|
||||
args: "none",
|
||||
}],
|
||||
},
|
||||
}, {
|
||||
files: ["**/*.js"],
|
||||
|
||||
rules: {
|
||||
"@typescript-eslint/explicit-function-return-type": "off",
|
||||
"@typescript-eslint/no-var-requires": "off",
|
||||
},
|
||||
}]);
|
||||
36
node_modules/sitemap/jest.config.cjs
generated
vendored
Normal file
36
node_modules/sitemap/jest.config.cjs
generated
vendored
Normal file
@@ -0,0 +1,36 @@
|
||||
/** @type {import('jest').Config} */
|
||||
const config = {
|
||||
preset: 'ts-jest',
|
||||
transform: {
|
||||
'^.+\\.ts?$': [
|
||||
'ts-jest',
|
||||
{
|
||||
tsconfig: 'tsconfig.jest.json',
|
||||
diagnostics: {
|
||||
ignoreCodes: [151002],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
moduleNameMapper: {
|
||||
'^(\\.{1,2}/.*)\\.js$': '$1',
|
||||
},
|
||||
modulePathIgnorePatterns: ['<rootDir>/dist/'],
|
||||
collectCoverage: true,
|
||||
collectCoverageFrom: [
|
||||
'lib/**/*.ts',
|
||||
'!lib/**/*.d.ts',
|
||||
'!lib/xmllint.ts',
|
||||
'!node_modules/',
|
||||
],
|
||||
coverageThreshold: {
|
||||
global: {
|
||||
branches: 80,
|
||||
functions: 90,
|
||||
lines: 90,
|
||||
statements: 90,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
module.exports = config;
|
||||
21
node_modules/sitemap/node_modules/@types/node/LICENSE
generated
vendored
Normal file
21
node_modules/sitemap/node_modules/@types/node/LICENSE
generated
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) Microsoft Corporation.
|
||||
|
||||
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/sitemap/node_modules/@types/node/README.md
generated
vendored
Normal file
15
node_modules/sitemap/node_modules/@types/node/README.md
generated
vendored
Normal file
@@ -0,0 +1,15 @@
|
||||
# Installation
|
||||
> `npm install --save @types/node`
|
||||
|
||||
# Summary
|
||||
This package contains type definitions for node (https://nodejs.org/).
|
||||
|
||||
# Details
|
||||
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node/v24.
|
||||
|
||||
### Additional Details
|
||||
* Last updated: Fri, 03 Apr 2026 11:14:41 GMT
|
||||
* Dependencies: [undici-types](https://npmjs.com/package/undici-types)
|
||||
|
||||
# Credits
|
||||
These definitions were written by [Microsoft TypeScript](https://github.com/Microsoft), [Alberto Schiabel](https://github.com/jkomyno), [Andrew Makarov](https://github.com/r3nya), [Benjamin Toueg](https://github.com/btoueg), [David Junger](https://github.com/touffy), [Mohsen Azimi](https://github.com/mohsen1), [Nikita Galkin](https://github.com/galkin), [Sebastian Silbermann](https://github.com/eps1lon), [Wilco Bakker](https://github.com/WilcoBakker), [Marcin Kopacz](https://github.com/chyzwar), [Trivikram Kamat](https://github.com/trivikr), [Junxiao Shi](https://github.com/yoursunny), [Ilia Baryshnikov](https://github.com/qwelias), [ExE Boss](https://github.com/ExE-Boss), [Piotr Błażejewicz](https://github.com/peterblazejewicz), [Anna Henningsen](https://github.com/addaleax), [Victor Perin](https://github.com/victorperin), [NodeJS Contributors](https://github.com/NodeJS), [Linus Unnebäck](https://github.com/LinusU), [wafuwafu13](https://github.com/wafuwafu13), [Matteo Collina](https://github.com/mcollina), [Dmitry Semigradsky](https://github.com/Semigradsky), [René](https://github.com/Renegade334), and [Yagiz Nizipli](https://github.com/anonrig).
|
||||
1115
node_modules/sitemap/node_modules/@types/node/assert.d.ts
generated
vendored
Normal file
1115
node_modules/sitemap/node_modules/@types/node/assert.d.ts
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
111
node_modules/sitemap/node_modules/@types/node/assert/strict.d.ts
generated
vendored
Normal file
111
node_modules/sitemap/node_modules/@types/node/assert/strict.d.ts
generated
vendored
Normal file
@@ -0,0 +1,111 @@
|
||||
/**
|
||||
* In strict assertion mode, non-strict methods behave like their corresponding
|
||||
* strict methods. For example, `assert.deepEqual()` will behave like
|
||||
* `assert.deepStrictEqual()`.
|
||||
*
|
||||
* In strict assertion mode, error messages for objects display a diff. In legacy
|
||||
* assertion mode, error messages for objects display the objects, often truncated.
|
||||
*
|
||||
* To use strict assertion mode:
|
||||
*
|
||||
* ```js
|
||||
* import { strict as assert } from 'node:assert';
|
||||
* ```
|
||||
*
|
||||
* ```js
|
||||
* import assert from 'node:assert/strict';
|
||||
* ```
|
||||
*
|
||||
* Example error diff:
|
||||
*
|
||||
* ```js
|
||||
* import { strict as assert } from 'node:assert';
|
||||
*
|
||||
* assert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]);
|
||||
* // AssertionError: Expected inputs to be strictly deep-equal:
|
||||
* // + actual - expected ... Lines skipped
|
||||
* //
|
||||
* // [
|
||||
* // [
|
||||
* // ...
|
||||
* // 2,
|
||||
* // + 3
|
||||
* // - '3'
|
||||
* // ],
|
||||
* // ...
|
||||
* // 5
|
||||
* // ]
|
||||
* ```
|
||||
*
|
||||
* To deactivate the colors, use the `NO_COLOR` or `NODE_DISABLE_COLORS`
|
||||
* environment variables. This will also deactivate the colors in the REPL. For
|
||||
* more on color support in terminal environments, read the tty
|
||||
* [`getColorDepth()`](https://nodejs.org/docs/latest-v24.x/api/tty.html#writestreamgetcolordepthenv) documentation.
|
||||
* @since v15.0.0
|
||||
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/assert/strict.js)
|
||||
*/
|
||||
declare module "assert/strict" {
|
||||
import {
|
||||
Assert,
|
||||
AssertionError,
|
||||
AssertionErrorOptions,
|
||||
AssertOptions,
|
||||
AssertPredicate,
|
||||
AssertStrict,
|
||||
CallTracker,
|
||||
CallTrackerCall,
|
||||
CallTrackerReportInformation,
|
||||
deepStrictEqual,
|
||||
doesNotMatch,
|
||||
doesNotReject,
|
||||
doesNotThrow,
|
||||
fail,
|
||||
ifError,
|
||||
match,
|
||||
notDeepStrictEqual,
|
||||
notStrictEqual,
|
||||
ok,
|
||||
partialDeepStrictEqual,
|
||||
rejects,
|
||||
strictEqual,
|
||||
throws,
|
||||
} from "node:assert";
|
||||
function strict(value: unknown, message?: string | Error): asserts value;
|
||||
namespace strict {
|
||||
export {
|
||||
Assert,
|
||||
AssertionError,
|
||||
AssertionErrorOptions,
|
||||
AssertOptions,
|
||||
AssertPredicate,
|
||||
AssertStrict,
|
||||
CallTracker,
|
||||
CallTrackerCall,
|
||||
CallTrackerReportInformation,
|
||||
deepStrictEqual,
|
||||
deepStrictEqual as deepEqual,
|
||||
doesNotMatch,
|
||||
doesNotReject,
|
||||
doesNotThrow,
|
||||
fail,
|
||||
ifError,
|
||||
match,
|
||||
notDeepStrictEqual,
|
||||
notDeepStrictEqual as notDeepEqual,
|
||||
notStrictEqual,
|
||||
notStrictEqual as notEqual,
|
||||
ok,
|
||||
partialDeepStrictEqual,
|
||||
rejects,
|
||||
strict,
|
||||
strictEqual,
|
||||
strictEqual as equal,
|
||||
throws,
|
||||
};
|
||||
}
|
||||
export = strict;
|
||||
}
|
||||
declare module "node:assert/strict" {
|
||||
import strict = require("assert/strict");
|
||||
export = strict;
|
||||
}
|
||||
623
node_modules/sitemap/node_modules/@types/node/async_hooks.d.ts
generated
vendored
Normal file
623
node_modules/sitemap/node_modules/@types/node/async_hooks.d.ts
generated
vendored
Normal file
@@ -0,0 +1,623 @@
|
||||
/**
|
||||
* We strongly discourage the use of the `async_hooks` API.
|
||||
* Other APIs that can cover most of its use cases include:
|
||||
*
|
||||
* * [`AsyncLocalStorage`](https://nodejs.org/docs/latest-v24.x/api/async_context.html#class-asynclocalstorage) tracks async context
|
||||
* * [`process.getActiveResourcesInfo()`](https://nodejs.org/docs/latest-v24.x/api/process.html#processgetactiveresourcesinfo) tracks active resources
|
||||
*
|
||||
* The `node:async_hooks` module provides an API to track asynchronous resources.
|
||||
* It can be accessed using:
|
||||
*
|
||||
* ```js
|
||||
* import async_hooks from 'node:async_hooks';
|
||||
* ```
|
||||
* @experimental
|
||||
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/async_hooks.js)
|
||||
*/
|
||||
declare module "async_hooks" {
|
||||
/**
|
||||
* ```js
|
||||
* import { executionAsyncId } from 'node:async_hooks';
|
||||
* import fs from 'node:fs';
|
||||
*
|
||||
* console.log(executionAsyncId()); // 1 - bootstrap
|
||||
* const path = '.';
|
||||
* fs.open(path, 'r', (err, fd) => {
|
||||
* console.log(executionAsyncId()); // 6 - open()
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* The ID returned from `executionAsyncId()` is related to execution timing, not
|
||||
* causality (which is covered by `triggerAsyncId()`):
|
||||
*
|
||||
* ```js
|
||||
* const server = net.createServer((conn) => {
|
||||
* // Returns the ID of the server, not of the new connection, because the
|
||||
* // callback runs in the execution scope of the server's MakeCallback().
|
||||
* async_hooks.executionAsyncId();
|
||||
*
|
||||
* }).listen(port, () => {
|
||||
* // Returns the ID of a TickObject (process.nextTick()) because all
|
||||
* // callbacks passed to .listen() are wrapped in a nextTick().
|
||||
* async_hooks.executionAsyncId();
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* Promise contexts may not get precise `executionAsyncIds` by default.
|
||||
* See the section on [promise execution tracking](https://nodejs.org/docs/latest-v24.x/api/async_hooks.html#promise-execution-tracking).
|
||||
* @since v8.1.0
|
||||
* @return The `asyncId` of the current execution context. Useful to track when something calls.
|
||||
*/
|
||||
function executionAsyncId(): number;
|
||||
/**
|
||||
* Resource objects returned by `executionAsyncResource()` are most often internal
|
||||
* Node.js handle objects with undocumented APIs. Using any functions or properties
|
||||
* on the object is likely to crash your application and should be avoided.
|
||||
*
|
||||
* Using `executionAsyncResource()` in the top-level execution context will
|
||||
* return an empty object as there is no handle or request object to use,
|
||||
* but having an object representing the top-level can be helpful.
|
||||
*
|
||||
* ```js
|
||||
* import { open } from 'node:fs';
|
||||
* import { executionAsyncId, executionAsyncResource } from 'node:async_hooks';
|
||||
*
|
||||
* console.log(executionAsyncId(), executionAsyncResource()); // 1 {}
|
||||
* open(new URL(import.meta.url), 'r', (err, fd) => {
|
||||
* console.log(executionAsyncId(), executionAsyncResource()); // 7 FSReqWrap
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* This can be used to implement continuation local storage without the
|
||||
* use of a tracking `Map` to store the metadata:
|
||||
*
|
||||
* ```js
|
||||
* import { createServer } from 'node:http';
|
||||
* import {
|
||||
* executionAsyncId,
|
||||
* executionAsyncResource,
|
||||
* createHook,
|
||||
* } from 'node:async_hooks';
|
||||
* const sym = Symbol('state'); // Private symbol to avoid pollution
|
||||
*
|
||||
* createHook({
|
||||
* init(asyncId, type, triggerAsyncId, resource) {
|
||||
* const cr = executionAsyncResource();
|
||||
* if (cr) {
|
||||
* resource[sym] = cr[sym];
|
||||
* }
|
||||
* },
|
||||
* }).enable();
|
||||
*
|
||||
* const server = createServer((req, res) => {
|
||||
* executionAsyncResource()[sym] = { state: req.url };
|
||||
* setTimeout(function() {
|
||||
* res.end(JSON.stringify(executionAsyncResource()[sym]));
|
||||
* }, 100);
|
||||
* }).listen(3000);
|
||||
* ```
|
||||
* @since v13.9.0, v12.17.0
|
||||
* @return The resource representing the current execution. Useful to store data within the resource.
|
||||
*/
|
||||
function executionAsyncResource(): object;
|
||||
/**
|
||||
* ```js
|
||||
* const server = net.createServer((conn) => {
|
||||
* // The resource that caused (or triggered) this callback to be called
|
||||
* // was that of the new connection. Thus the return value of triggerAsyncId()
|
||||
* // is the asyncId of "conn".
|
||||
* async_hooks.triggerAsyncId();
|
||||
*
|
||||
* }).listen(port, () => {
|
||||
* // Even though all callbacks passed to .listen() are wrapped in a nextTick()
|
||||
* // the callback itself exists because the call to the server's .listen()
|
||||
* // was made. So the return value would be the ID of the server.
|
||||
* async_hooks.triggerAsyncId();
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* Promise contexts may not get valid `triggerAsyncId`s by default. See
|
||||
* the section on [promise execution tracking](https://nodejs.org/docs/latest-v24.x/api/async_hooks.html#promise-execution-tracking).
|
||||
* @return The ID of the resource responsible for calling the callback that is currently being executed.
|
||||
*/
|
||||
function triggerAsyncId(): number;
|
||||
interface HookCallbacks {
|
||||
/**
|
||||
* Called when a class is constructed that has the possibility to emit an asynchronous event.
|
||||
* @param asyncId A unique ID for the async resource
|
||||
* @param type The type of the async resource
|
||||
* @param triggerAsyncId The unique ID of the async resource in whose execution context this async resource was created
|
||||
* @param resource Reference to the resource representing the async operation, needs to be released during destroy
|
||||
*/
|
||||
init?(asyncId: number, type: string, triggerAsyncId: number, resource: object): void;
|
||||
/**
|
||||
* When an asynchronous operation is initiated or completes a callback is called to notify the user.
|
||||
* The before callback is called just before said callback is executed.
|
||||
* @param asyncId the unique identifier assigned to the resource about to execute the callback.
|
||||
*/
|
||||
before?(asyncId: number): void;
|
||||
/**
|
||||
* Called immediately after the callback specified in `before` is completed.
|
||||
*
|
||||
* If an uncaught exception occurs during execution of the callback, then `after` will run after the `'uncaughtException'` event is emitted or a `domain`'s handler runs.
|
||||
* @param asyncId the unique identifier assigned to the resource which has executed the callback.
|
||||
*/
|
||||
after?(asyncId: number): void;
|
||||
/**
|
||||
* Called when a promise has resolve() called. This may not be in the same execution id
|
||||
* as the promise itself.
|
||||
* @param asyncId the unique id for the promise that was resolve()d.
|
||||
*/
|
||||
promiseResolve?(asyncId: number): void;
|
||||
/**
|
||||
* Called after the resource corresponding to asyncId is destroyed
|
||||
* @param asyncId a unique ID for the async resource
|
||||
*/
|
||||
destroy?(asyncId: number): void;
|
||||
}
|
||||
interface AsyncHook {
|
||||
/**
|
||||
* Enable the callbacks for a given AsyncHook instance. If no callbacks are provided enabling is a noop.
|
||||
*/
|
||||
enable(): this;
|
||||
/**
|
||||
* Disable the callbacks for a given AsyncHook instance from the global pool of AsyncHook callbacks to be executed. Once a hook has been disabled it will not be called again until enabled.
|
||||
*/
|
||||
disable(): this;
|
||||
}
|
||||
/**
|
||||
* Registers functions to be called for different lifetime events of each async
|
||||
* operation.
|
||||
*
|
||||
* The callbacks `init()`/`before()`/`after()`/`destroy()` are called for the
|
||||
* respective asynchronous event during a resource's lifetime.
|
||||
*
|
||||
* All callbacks are optional. For example, if only resource cleanup needs to
|
||||
* be tracked, then only the `destroy` callback needs to be passed. The
|
||||
* specifics of all functions that can be passed to `callbacks` is in the `Hook Callbacks` section.
|
||||
*
|
||||
* ```js
|
||||
* import { createHook } from 'node:async_hooks';
|
||||
*
|
||||
* const asyncHook = createHook({
|
||||
* init(asyncId, type, triggerAsyncId, resource) { },
|
||||
* destroy(asyncId) { },
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* The callbacks will be inherited via the prototype chain:
|
||||
*
|
||||
* ```js
|
||||
* class MyAsyncCallbacks {
|
||||
* init(asyncId, type, triggerAsyncId, resource) { }
|
||||
* destroy(asyncId) {}
|
||||
* }
|
||||
*
|
||||
* class MyAddedCallbacks extends MyAsyncCallbacks {
|
||||
* before(asyncId) { }
|
||||
* after(asyncId) { }
|
||||
* }
|
||||
*
|
||||
* const asyncHook = async_hooks.createHook(new MyAddedCallbacks());
|
||||
* ```
|
||||
*
|
||||
* Because promises are asynchronous resources whose lifecycle is tracked
|
||||
* via the async hooks mechanism, the `init()`, `before()`, `after()`, and`destroy()` callbacks _must not_ be async functions that return promises.
|
||||
* @since v8.1.0
|
||||
* @param callbacks The `Hook Callbacks` to register
|
||||
* @return Instance used for disabling and enabling hooks
|
||||
*/
|
||||
function createHook(callbacks: HookCallbacks): AsyncHook;
|
||||
interface AsyncResourceOptions {
|
||||
/**
|
||||
* The ID of the execution context that created this async event.
|
||||
* @default executionAsyncId()
|
||||
*/
|
||||
triggerAsyncId?: number | undefined;
|
||||
/**
|
||||
* Disables automatic `emitDestroy` when the object is garbage collected.
|
||||
* This usually does not need to be set (even if `emitDestroy` is called
|
||||
* manually), unless the resource's `asyncId` is retrieved and the
|
||||
* sensitive API's `emitDestroy` is called with it.
|
||||
* @default false
|
||||
*/
|
||||
requireManualDestroy?: boolean | undefined;
|
||||
}
|
||||
/**
|
||||
* The class `AsyncResource` is designed to be extended by the embedder's async
|
||||
* resources. Using this, users can easily trigger the lifetime events of their
|
||||
* own resources.
|
||||
*
|
||||
* The `init` hook will trigger when an `AsyncResource` is instantiated.
|
||||
*
|
||||
* The following is an overview of the `AsyncResource` API.
|
||||
*
|
||||
* ```js
|
||||
* import { AsyncResource, executionAsyncId } from 'node:async_hooks';
|
||||
*
|
||||
* // AsyncResource() is meant to be extended. Instantiating a
|
||||
* // new AsyncResource() also triggers init. If triggerAsyncId is omitted then
|
||||
* // async_hook.executionAsyncId() is used.
|
||||
* const asyncResource = new AsyncResource(
|
||||
* type, { triggerAsyncId: executionAsyncId(), requireManualDestroy: false },
|
||||
* );
|
||||
*
|
||||
* // Run a function in the execution context of the resource. This will
|
||||
* // * establish the context of the resource
|
||||
* // * trigger the AsyncHooks before callbacks
|
||||
* // * call the provided function `fn` with the supplied arguments
|
||||
* // * trigger the AsyncHooks after callbacks
|
||||
* // * restore the original execution context
|
||||
* asyncResource.runInAsyncScope(fn, thisArg, ...args);
|
||||
*
|
||||
* // Call AsyncHooks destroy callbacks.
|
||||
* asyncResource.emitDestroy();
|
||||
*
|
||||
* // Return the unique ID assigned to the AsyncResource instance.
|
||||
* asyncResource.asyncId();
|
||||
*
|
||||
* // Return the trigger ID for the AsyncResource instance.
|
||||
* asyncResource.triggerAsyncId();
|
||||
* ```
|
||||
*/
|
||||
class AsyncResource {
|
||||
/**
|
||||
* AsyncResource() is meant to be extended. Instantiating a
|
||||
* new AsyncResource() also triggers init. If triggerAsyncId is omitted then
|
||||
* async_hook.executionAsyncId() is used.
|
||||
* @param type The type of async event.
|
||||
* @param triggerAsyncId The ID of the execution context that created
|
||||
* this async event (default: `executionAsyncId()`), or an
|
||||
* AsyncResourceOptions object (since v9.3.0)
|
||||
*/
|
||||
constructor(type: string, triggerAsyncId?: number | AsyncResourceOptions);
|
||||
/**
|
||||
* Binds the given function to the current execution context.
|
||||
* @since v14.8.0, v12.19.0
|
||||
* @param fn The function to bind to the current execution context.
|
||||
* @param type An optional name to associate with the underlying `AsyncResource`.
|
||||
*/
|
||||
static bind<Func extends (this: ThisArg, ...args: any[]) => any, ThisArg>(
|
||||
fn: Func,
|
||||
type?: string,
|
||||
thisArg?: ThisArg,
|
||||
): Func;
|
||||
/**
|
||||
* Binds the given function to execute to this `AsyncResource`'s scope.
|
||||
* @since v14.8.0, v12.19.0
|
||||
* @param fn The function to bind to the current `AsyncResource`.
|
||||
*/
|
||||
bind<Func extends (...args: any[]) => any>(fn: Func): Func;
|
||||
/**
|
||||
* Call the provided function with the provided arguments in the execution context
|
||||
* of the async resource. This will establish the context, trigger the AsyncHooks
|
||||
* before callbacks, call the function, trigger the AsyncHooks after callbacks, and
|
||||
* then restore the original execution context.
|
||||
* @since v9.6.0
|
||||
* @param fn The function to call in the execution context of this async resource.
|
||||
* @param thisArg The receiver to be used for the function call.
|
||||
* @param args Optional arguments to pass to the function.
|
||||
*/
|
||||
runInAsyncScope<This, Result>(
|
||||
fn: (this: This, ...args: any[]) => Result,
|
||||
thisArg?: This,
|
||||
...args: any[]
|
||||
): Result;
|
||||
/**
|
||||
* Call all `destroy` hooks. This should only ever be called once. An error will
|
||||
* be thrown if it is called more than once. This **must** be manually called. If
|
||||
* the resource is left to be collected by the GC then the `destroy` hooks will
|
||||
* never be called.
|
||||
* @return A reference to `asyncResource`.
|
||||
*/
|
||||
emitDestroy(): this;
|
||||
/**
|
||||
* @return The unique `asyncId` assigned to the resource.
|
||||
*/
|
||||
asyncId(): number;
|
||||
/**
|
||||
* @return The same `triggerAsyncId` that is passed to the `AsyncResource` constructor.
|
||||
*/
|
||||
triggerAsyncId(): number;
|
||||
}
|
||||
interface AsyncLocalStorageOptions {
|
||||
/**
|
||||
* The default value to be used when no store is provided.
|
||||
*/
|
||||
defaultValue?: any;
|
||||
/**
|
||||
* A name for the `AsyncLocalStorage` value.
|
||||
*/
|
||||
name?: string | undefined;
|
||||
}
|
||||
/**
|
||||
* This class creates stores that stay coherent through asynchronous operations.
|
||||
*
|
||||
* While you can create your own implementation on top of the `node:async_hooks` module, `AsyncLocalStorage` should be preferred as it is a performant and memory
|
||||
* safe implementation that involves significant optimizations that are non-obvious
|
||||
* to implement.
|
||||
*
|
||||
* The following example uses `AsyncLocalStorage` to build a simple logger
|
||||
* that assigns IDs to incoming HTTP requests and includes them in messages
|
||||
* logged within each request.
|
||||
*
|
||||
* ```js
|
||||
* import http from 'node:http';
|
||||
* import { AsyncLocalStorage } from 'node:async_hooks';
|
||||
*
|
||||
* const asyncLocalStorage = new AsyncLocalStorage();
|
||||
*
|
||||
* function logWithId(msg) {
|
||||
* const id = asyncLocalStorage.getStore();
|
||||
* console.log(`${id !== undefined ? id : '-'}:`, msg);
|
||||
* }
|
||||
*
|
||||
* let idSeq = 0;
|
||||
* http.createServer((req, res) => {
|
||||
* asyncLocalStorage.run(idSeq++, () => {
|
||||
* logWithId('start');
|
||||
* // Imagine any chain of async operations here
|
||||
* setImmediate(() => {
|
||||
* logWithId('finish');
|
||||
* res.end();
|
||||
* });
|
||||
* });
|
||||
* }).listen(8080);
|
||||
*
|
||||
* http.get('http://localhost:8080');
|
||||
* http.get('http://localhost:8080');
|
||||
* // Prints:
|
||||
* // 0: start
|
||||
* // 0: finish
|
||||
* // 1: start
|
||||
* // 1: finish
|
||||
* ```
|
||||
*
|
||||
* Each instance of `AsyncLocalStorage` maintains an independent storage context.
|
||||
* Multiple instances can safely exist simultaneously without risk of interfering
|
||||
* with each other's data.
|
||||
* @since v13.10.0, v12.17.0
|
||||
*/
|
||||
class AsyncLocalStorage<T> {
|
||||
/**
|
||||
* Creates a new instance of `AsyncLocalStorage`. Store is only provided within a
|
||||
* `run()` call or after an `enterWith()` call.
|
||||
*/
|
||||
constructor(options?: AsyncLocalStorageOptions);
|
||||
/**
|
||||
* Binds the given function to the current execution context.
|
||||
* @since v19.8.0
|
||||
* @param fn The function to bind to the current execution context.
|
||||
* @return A new function that calls `fn` within the captured execution context.
|
||||
*/
|
||||
static bind<Func extends (...args: any[]) => any>(fn: Func): Func;
|
||||
/**
|
||||
* Captures the current execution context and returns a function that accepts a
|
||||
* function as an argument. Whenever the returned function is called, it
|
||||
* calls the function passed to it within the captured context.
|
||||
*
|
||||
* ```js
|
||||
* const asyncLocalStorage = new AsyncLocalStorage();
|
||||
* const runInAsyncScope = asyncLocalStorage.run(123, () => AsyncLocalStorage.snapshot());
|
||||
* const result = asyncLocalStorage.run(321, () => runInAsyncScope(() => asyncLocalStorage.getStore()));
|
||||
* console.log(result); // returns 123
|
||||
* ```
|
||||
*
|
||||
* AsyncLocalStorage.snapshot() can replace the use of AsyncResource for simple
|
||||
* async context tracking purposes, for example:
|
||||
*
|
||||
* ```js
|
||||
* class Foo {
|
||||
* #runInAsyncScope = AsyncLocalStorage.snapshot();
|
||||
*
|
||||
* get() { return this.#runInAsyncScope(() => asyncLocalStorage.getStore()); }
|
||||
* }
|
||||
*
|
||||
* const foo = asyncLocalStorage.run(123, () => new Foo());
|
||||
* console.log(asyncLocalStorage.run(321, () => foo.get())); // returns 123
|
||||
* ```
|
||||
* @since v19.8.0
|
||||
* @return A new function with the signature `(fn: (...args) : R, ...args) : R`.
|
||||
*/
|
||||
static snapshot(): <R, TArgs extends any[]>(fn: (...args: TArgs) => R, ...args: TArgs) => R;
|
||||
/**
|
||||
* Disables the instance of `AsyncLocalStorage`. All subsequent calls
|
||||
* to `asyncLocalStorage.getStore()` will return `undefined` until `asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()` is called again.
|
||||
*
|
||||
* When calling `asyncLocalStorage.disable()`, all current contexts linked to the
|
||||
* instance will be exited.
|
||||
*
|
||||
* Calling `asyncLocalStorage.disable()` is required before the `asyncLocalStorage` can be garbage collected. This does not apply to stores
|
||||
* provided by the `asyncLocalStorage`, as those objects are garbage collected
|
||||
* along with the corresponding async resources.
|
||||
*
|
||||
* Use this method when the `asyncLocalStorage` is not in use anymore
|
||||
* in the current process.
|
||||
* @since v13.10.0, v12.17.0
|
||||
* @experimental
|
||||
*/
|
||||
disable(): void;
|
||||
/**
|
||||
* Returns the current store.
|
||||
* If called outside of an asynchronous context initialized by
|
||||
* calling `asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()`, it
|
||||
* returns `undefined`.
|
||||
* @since v13.10.0, v12.17.0
|
||||
*/
|
||||
getStore(): T | undefined;
|
||||
/**
|
||||
* The name of the `AsyncLocalStorage` instance if provided.
|
||||
* @since v24.0.0
|
||||
*/
|
||||
readonly name: string;
|
||||
/**
|
||||
* Runs a function synchronously within a context and returns its
|
||||
* return value. The store is not accessible outside of the callback function.
|
||||
* The store is accessible to any asynchronous operations created within the
|
||||
* callback.
|
||||
*
|
||||
* The optional `args` are passed to the callback function.
|
||||
*
|
||||
* If the callback function throws an error, the error is thrown by `run()` too.
|
||||
* The stacktrace is not impacted by this call and the context is exited.
|
||||
*
|
||||
* Example:
|
||||
*
|
||||
* ```js
|
||||
* const store = { id: 2 };
|
||||
* try {
|
||||
* asyncLocalStorage.run(store, () => {
|
||||
* asyncLocalStorage.getStore(); // Returns the store object
|
||||
* setTimeout(() => {
|
||||
* asyncLocalStorage.getStore(); // Returns the store object
|
||||
* }, 200);
|
||||
* throw new Error();
|
||||
* });
|
||||
* } catch (e) {
|
||||
* asyncLocalStorage.getStore(); // Returns undefined
|
||||
* // The error will be caught here
|
||||
* }
|
||||
* ```
|
||||
* @since v13.10.0, v12.17.0
|
||||
*/
|
||||
run<R>(store: T, callback: () => R): R;
|
||||
run<R, TArgs extends any[]>(store: T, callback: (...args: TArgs) => R, ...args: TArgs): R;
|
||||
/**
|
||||
* Runs a function synchronously outside of a context and returns its
|
||||
* return value. The store is not accessible within the callback function or
|
||||
* the asynchronous operations created within the callback. Any `getStore()` call done within the callback function will always return `undefined`.
|
||||
*
|
||||
* The optional `args` are passed to the callback function.
|
||||
*
|
||||
* If the callback function throws an error, the error is thrown by `exit()` too.
|
||||
* The stacktrace is not impacted by this call and the context is re-entered.
|
||||
*
|
||||
* Example:
|
||||
*
|
||||
* ```js
|
||||
* // Within a call to run
|
||||
* try {
|
||||
* asyncLocalStorage.getStore(); // Returns the store object or value
|
||||
* asyncLocalStorage.exit(() => {
|
||||
* asyncLocalStorage.getStore(); // Returns undefined
|
||||
* throw new Error();
|
||||
* });
|
||||
* } catch (e) {
|
||||
* asyncLocalStorage.getStore(); // Returns the same object or value
|
||||
* // The error will be caught here
|
||||
* }
|
||||
* ```
|
||||
* @since v13.10.0, v12.17.0
|
||||
* @experimental
|
||||
*/
|
||||
exit<R, TArgs extends any[]>(callback: (...args: TArgs) => R, ...args: TArgs): R;
|
||||
/**
|
||||
* Transitions into the context for the remainder of the current
|
||||
* synchronous execution and then persists the store through any following
|
||||
* asynchronous calls.
|
||||
*
|
||||
* Example:
|
||||
*
|
||||
* ```js
|
||||
* const store = { id: 1 };
|
||||
* // Replaces previous store with the given store object
|
||||
* asyncLocalStorage.enterWith(store);
|
||||
* asyncLocalStorage.getStore(); // Returns the store object
|
||||
* someAsyncOperation(() => {
|
||||
* asyncLocalStorage.getStore(); // Returns the same object
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* This transition will continue for the _entire_ synchronous execution.
|
||||
* This means that if, for example, the context is entered within an event
|
||||
* handler subsequent event handlers will also run within that context unless
|
||||
* specifically bound to another context with an `AsyncResource`. That is why `run()` should be preferred over `enterWith()` unless there are strong reasons
|
||||
* to use the latter method.
|
||||
*
|
||||
* ```js
|
||||
* const store = { id: 1 };
|
||||
*
|
||||
* emitter.on('my-event', () => {
|
||||
* asyncLocalStorage.enterWith(store);
|
||||
* });
|
||||
* emitter.on('my-event', () => {
|
||||
* asyncLocalStorage.getStore(); // Returns the same object
|
||||
* });
|
||||
*
|
||||
* asyncLocalStorage.getStore(); // Returns undefined
|
||||
* emitter.emit('my-event');
|
||||
* asyncLocalStorage.getStore(); // Returns the same object
|
||||
* ```
|
||||
* @since v13.11.0, v12.17.0
|
||||
* @experimental
|
||||
*/
|
||||
enterWith(store: T): void;
|
||||
}
|
||||
/**
|
||||
* @since v17.2.0, v16.14.0
|
||||
* @return A map of provider types to the corresponding numeric id.
|
||||
* This map contains all the event types that might be emitted by the `async_hooks.init()` event.
|
||||
*/
|
||||
namespace asyncWrapProviders {
|
||||
const NONE: number;
|
||||
const DIRHANDLE: number;
|
||||
const DNSCHANNEL: number;
|
||||
const ELDHISTOGRAM: number;
|
||||
const FILEHANDLE: number;
|
||||
const FILEHANDLECLOSEREQ: number;
|
||||
const FIXEDSIZEBLOBCOPY: number;
|
||||
const FSEVENTWRAP: number;
|
||||
const FSREQCALLBACK: number;
|
||||
const FSREQPROMISE: number;
|
||||
const GETADDRINFOREQWRAP: number;
|
||||
const GETNAMEINFOREQWRAP: number;
|
||||
const HEAPSNAPSHOT: number;
|
||||
const HTTP2SESSION: number;
|
||||
const HTTP2STREAM: number;
|
||||
const HTTP2PING: number;
|
||||
const HTTP2SETTINGS: number;
|
||||
const HTTPINCOMINGMESSAGE: number;
|
||||
const HTTPCLIENTREQUEST: number;
|
||||
const JSSTREAM: number;
|
||||
const JSUDPWRAP: number;
|
||||
const MESSAGEPORT: number;
|
||||
const PIPECONNECTWRAP: number;
|
||||
const PIPESERVERWRAP: number;
|
||||
const PIPEWRAP: number;
|
||||
const PROCESSWRAP: number;
|
||||
const PROMISE: number;
|
||||
const QUERYWRAP: number;
|
||||
const SHUTDOWNWRAP: number;
|
||||
const SIGNALWRAP: number;
|
||||
const STATWATCHER: number;
|
||||
const STREAMPIPE: number;
|
||||
const TCPCONNECTWRAP: number;
|
||||
const TCPSERVERWRAP: number;
|
||||
const TCPWRAP: number;
|
||||
const TTYWRAP: number;
|
||||
const UDPSENDWRAP: number;
|
||||
const UDPWRAP: number;
|
||||
const SIGINTWATCHDOG: number;
|
||||
const WORKER: number;
|
||||
const WORKERHEAPSNAPSHOT: number;
|
||||
const WRITEWRAP: number;
|
||||
const ZLIB: number;
|
||||
const CHECKPRIMEREQUEST: number;
|
||||
const PBKDF2REQUEST: number;
|
||||
const KEYPAIRGENREQUEST: number;
|
||||
const KEYGENREQUEST: number;
|
||||
const KEYEXPORTREQUEST: number;
|
||||
const CIPHERREQUEST: number;
|
||||
const DERIVEBITSREQUEST: number;
|
||||
const HASHREQUEST: number;
|
||||
const RANDOMBYTESREQUEST: number;
|
||||
const RANDOMPRIMEREQUEST: number;
|
||||
const SCRYPTREQUEST: number;
|
||||
const SIGNREQUEST: number;
|
||||
const TLSWRAP: number;
|
||||
const VERIFYREQUEST: number;
|
||||
}
|
||||
}
|
||||
declare module "node:async_hooks" {
|
||||
export * from "async_hooks";
|
||||
}
|
||||
472
node_modules/sitemap/node_modules/@types/node/buffer.buffer.d.ts
generated
vendored
Normal file
472
node_modules/sitemap/node_modules/@types/node/buffer.buffer.d.ts
generated
vendored
Normal file
@@ -0,0 +1,472 @@
|
||||
declare module "buffer" {
|
||||
type ImplicitArrayBuffer<T extends WithImplicitCoercion<ArrayBufferLike>> = T extends
|
||||
{ valueOf(): infer V extends ArrayBufferLike } ? V : T;
|
||||
global {
|
||||
interface BufferConstructor {
|
||||
// see buffer.d.ts for implementation shared with all TypeScript versions
|
||||
|
||||
/**
|
||||
* Allocates a new buffer containing the given {str}.
|
||||
*
|
||||
* @param str String to store in buffer.
|
||||
* @param encoding encoding to use, optional. Default is 'utf8'
|
||||
* @deprecated since v10.0.0 - Use `Buffer.from(string[, encoding])` instead.
|
||||
*/
|
||||
new(str: string, encoding?: BufferEncoding): Buffer<ArrayBuffer>;
|
||||
/**
|
||||
* Allocates a new buffer of {size} octets.
|
||||
*
|
||||
* @param size count of octets to allocate.
|
||||
* @deprecated since v10.0.0 - Use `Buffer.alloc()` instead (also see `Buffer.allocUnsafe()`).
|
||||
*/
|
||||
new(size: number): Buffer<ArrayBuffer>;
|
||||
/**
|
||||
* Allocates a new buffer containing the given {array} of octets.
|
||||
*
|
||||
* @param array The octets to store.
|
||||
* @deprecated since v10.0.0 - Use `Buffer.from(array)` instead.
|
||||
*/
|
||||
new(array: ArrayLike<number>): Buffer<ArrayBuffer>;
|
||||
/**
|
||||
* Produces a Buffer backed by the same allocated memory as
|
||||
* the given {ArrayBuffer}/{SharedArrayBuffer}.
|
||||
*
|
||||
* @param arrayBuffer The ArrayBuffer with which to share memory.
|
||||
* @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead.
|
||||
*/
|
||||
new<TArrayBuffer extends ArrayBufferLike = ArrayBuffer>(arrayBuffer: TArrayBuffer): Buffer<TArrayBuffer>;
|
||||
/**
|
||||
* Allocates a new `Buffer` using an `array` of bytes in the range `0` – `255`.
|
||||
* Array entries outside that range will be truncated to fit into it.
|
||||
*
|
||||
* ```js
|
||||
* import { Buffer } from 'node:buffer';
|
||||
*
|
||||
* // Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'.
|
||||
* const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]);
|
||||
* ```
|
||||
*
|
||||
* If `array` is an `Array`-like object (that is, one with a `length` property of
|
||||
* type `number`), it is treated as if it is an array, unless it is a `Buffer` or
|
||||
* a `Uint8Array`. This means all other `TypedArray` variants get treated as an
|
||||
* `Array`. To create a `Buffer` from the bytes backing a `TypedArray`, use
|
||||
* `Buffer.copyBytesFrom()`.
|
||||
*
|
||||
* A `TypeError` will be thrown if `array` is not an `Array` or another type
|
||||
* appropriate for `Buffer.from()` variants.
|
||||
*
|
||||
* `Buffer.from(array)` and `Buffer.from(string)` may also use the internal
|
||||
* `Buffer` pool like `Buffer.allocUnsafe()` does.
|
||||
* @since v5.10.0
|
||||
*/
|
||||
from(array: WithImplicitCoercion<ArrayLike<number>>): Buffer<ArrayBuffer>;
|
||||
/**
|
||||
* This creates a view of the `ArrayBuffer` without copying the underlying
|
||||
* memory. For example, when passed a reference to the `.buffer` property of a
|
||||
* `TypedArray` instance, the newly created `Buffer` will share the same
|
||||
* allocated memory as the `TypedArray`'s underlying `ArrayBuffer`.
|
||||
*
|
||||
* ```js
|
||||
* import { Buffer } from 'node:buffer';
|
||||
*
|
||||
* const arr = new Uint16Array(2);
|
||||
*
|
||||
* arr[0] = 5000;
|
||||
* arr[1] = 4000;
|
||||
*
|
||||
* // Shares memory with `arr`.
|
||||
* const buf = Buffer.from(arr.buffer);
|
||||
*
|
||||
* console.log(buf);
|
||||
* // Prints: <Buffer 88 13 a0 0f>
|
||||
*
|
||||
* // Changing the original Uint16Array changes the Buffer also.
|
||||
* arr[1] = 6000;
|
||||
*
|
||||
* console.log(buf);
|
||||
* // Prints: <Buffer 88 13 70 17>
|
||||
* ```
|
||||
*
|
||||
* The optional `byteOffset` and `length` arguments specify a memory range within
|
||||
* the `arrayBuffer` that will be shared by the `Buffer`.
|
||||
*
|
||||
* ```js
|
||||
* import { Buffer } from 'node:buffer';
|
||||
*
|
||||
* const ab = new ArrayBuffer(10);
|
||||
* const buf = Buffer.from(ab, 0, 2);
|
||||
*
|
||||
* console.log(buf.length);
|
||||
* // Prints: 2
|
||||
* ```
|
||||
*
|
||||
* A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer` or a
|
||||
* `SharedArrayBuffer` or another type appropriate for `Buffer.from()`
|
||||
* variants.
|
||||
*
|
||||
* It is important to remember that a backing `ArrayBuffer` can cover a range
|
||||
* of memory that extends beyond the bounds of a `TypedArray` view. A new
|
||||
* `Buffer` created using the `buffer` property of a `TypedArray` may extend
|
||||
* beyond the range of the `TypedArray`:
|
||||
*
|
||||
* ```js
|
||||
* import { Buffer } from 'node:buffer';
|
||||
*
|
||||
* const arrA = Uint8Array.from([0x63, 0x64, 0x65, 0x66]); // 4 elements
|
||||
* const arrB = new Uint8Array(arrA.buffer, 1, 2); // 2 elements
|
||||
* console.log(arrA.buffer === arrB.buffer); // true
|
||||
*
|
||||
* const buf = Buffer.from(arrB.buffer);
|
||||
* console.log(buf);
|
||||
* // Prints: <Buffer 63 64 65 66>
|
||||
* ```
|
||||
* @since v5.10.0
|
||||
* @param arrayBuffer An `ArrayBuffer`, `SharedArrayBuffer`, for example the
|
||||
* `.buffer` property of a `TypedArray`.
|
||||
* @param byteOffset Index of first byte to expose. **Default:** `0`.
|
||||
* @param length Number of bytes to expose. **Default:**
|
||||
* `arrayBuffer.byteLength - byteOffset`.
|
||||
*/
|
||||
from<TArrayBuffer extends WithImplicitCoercion<ArrayBufferLike>>(
|
||||
arrayBuffer: TArrayBuffer,
|
||||
byteOffset?: number,
|
||||
length?: number,
|
||||
): Buffer<ImplicitArrayBuffer<TArrayBuffer>>;
|
||||
/**
|
||||
* Creates a new `Buffer` containing `string`. The `encoding` parameter identifies
|
||||
* the character encoding to be used when converting `string` into bytes.
|
||||
*
|
||||
* ```js
|
||||
* import { Buffer } from 'node:buffer';
|
||||
*
|
||||
* const buf1 = Buffer.from('this is a tést');
|
||||
* const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex');
|
||||
*
|
||||
* console.log(buf1.toString());
|
||||
* // Prints: this is a tést
|
||||
* console.log(buf2.toString());
|
||||
* // Prints: this is a tést
|
||||
* console.log(buf1.toString('latin1'));
|
||||
* // Prints: this is a tést
|
||||
* ```
|
||||
*
|
||||
* A `TypeError` will be thrown if `string` is not a string or another type
|
||||
* appropriate for `Buffer.from()` variants.
|
||||
*
|
||||
* `Buffer.from(string)` may also use the internal `Buffer` pool like
|
||||
* `Buffer.allocUnsafe()` does.
|
||||
* @since v5.10.0
|
||||
* @param string A string to encode.
|
||||
* @param encoding The encoding of `string`. **Default:** `'utf8'`.
|
||||
*/
|
||||
from(string: WithImplicitCoercion<string>, encoding?: BufferEncoding): Buffer<ArrayBuffer>;
|
||||
from(arrayOrString: WithImplicitCoercion<ArrayLike<number> | string>): Buffer<ArrayBuffer>;
|
||||
/**
|
||||
* Creates a new Buffer using the passed {data}
|
||||
* @param values to create a new Buffer
|
||||
*/
|
||||
of(...items: number[]): Buffer<ArrayBuffer>;
|
||||
/**
|
||||
* Returns a new `Buffer` which is the result of concatenating all the `Buffer` instances in the `list` together.
|
||||
*
|
||||
* If the list has no items, or if the `totalLength` is 0, then a new zero-length `Buffer` is returned.
|
||||
*
|
||||
* If `totalLength` is not provided, it is calculated from the `Buffer` instances
|
||||
* in `list` by adding their lengths.
|
||||
*
|
||||
* If `totalLength` is provided, it is coerced to an unsigned integer. If the
|
||||
* combined length of the `Buffer`s in `list` exceeds `totalLength`, the result is
|
||||
* truncated to `totalLength`. If the combined length of the `Buffer`s in `list` is
|
||||
* less than `totalLength`, the remaining space is filled with zeros.
|
||||
*
|
||||
* ```js
|
||||
* import { Buffer } from 'node:buffer';
|
||||
*
|
||||
* // Create a single `Buffer` from a list of three `Buffer` instances.
|
||||
*
|
||||
* const buf1 = Buffer.alloc(10);
|
||||
* const buf2 = Buffer.alloc(14);
|
||||
* const buf3 = Buffer.alloc(18);
|
||||
* const totalLength = buf1.length + buf2.length + buf3.length;
|
||||
*
|
||||
* console.log(totalLength);
|
||||
* // Prints: 42
|
||||
*
|
||||
* const bufA = Buffer.concat([buf1, buf2, buf3], totalLength);
|
||||
*
|
||||
* console.log(bufA);
|
||||
* // Prints: <Buffer 00 00 00 00 ...>
|
||||
* console.log(bufA.length);
|
||||
* // Prints: 42
|
||||
* ```
|
||||
*
|
||||
* `Buffer.concat()` may also use the internal `Buffer` pool like `Buffer.allocUnsafe()` does.
|
||||
* @since v0.7.11
|
||||
* @param list List of `Buffer` or {@link Uint8Array} instances to concatenate.
|
||||
* @param totalLength Total length of the `Buffer` instances in `list` when concatenated.
|
||||
*/
|
||||
concat(list: readonly Uint8Array[], totalLength?: number): Buffer<ArrayBuffer>;
|
||||
/**
|
||||
* Copies the underlying memory of `view` into a new `Buffer`.
|
||||
*
|
||||
* ```js
|
||||
* const u16 = new Uint16Array([0, 0xffff]);
|
||||
* const buf = Buffer.copyBytesFrom(u16, 1, 1);
|
||||
* u16[1] = 0;
|
||||
* console.log(buf.length); // 2
|
||||
* console.log(buf[0]); // 255
|
||||
* console.log(buf[1]); // 255
|
||||
* ```
|
||||
* @since v19.8.0
|
||||
* @param view The {TypedArray} to copy.
|
||||
* @param [offset=0] The starting offset within `view`.
|
||||
* @param [length=view.length - offset] The number of elements from `view` to copy.
|
||||
*/
|
||||
copyBytesFrom(view: NodeJS.TypedArray, offset?: number, length?: number): Buffer<ArrayBuffer>;
|
||||
/**
|
||||
* Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the`Buffer` will be zero-filled.
|
||||
*
|
||||
* ```js
|
||||
* import { Buffer } from 'node:buffer';
|
||||
*
|
||||
* const buf = Buffer.alloc(5);
|
||||
*
|
||||
* console.log(buf);
|
||||
* // Prints: <Buffer 00 00 00 00 00>
|
||||
* ```
|
||||
*
|
||||
* If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown.
|
||||
*
|
||||
* If `fill` is specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill)`.
|
||||
*
|
||||
* ```js
|
||||
* import { Buffer } from 'node:buffer';
|
||||
*
|
||||
* const buf = Buffer.alloc(5, 'a');
|
||||
*
|
||||
* console.log(buf);
|
||||
* // Prints: <Buffer 61 61 61 61 61>
|
||||
* ```
|
||||
*
|
||||
* If both `fill` and `encoding` are specified, the allocated `Buffer` will be
|
||||
* initialized by calling `buf.fill(fill, encoding)`.
|
||||
*
|
||||
* ```js
|
||||
* import { Buffer } from 'node:buffer';
|
||||
*
|
||||
* const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64');
|
||||
*
|
||||
* console.log(buf);
|
||||
* // Prints: <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64>
|
||||
* ```
|
||||
*
|
||||
* Calling `Buffer.alloc()` can be measurably slower than the alternative `Buffer.allocUnsafe()` but ensures that the newly created `Buffer` instance
|
||||
* contents will never contain sensitive data from previous allocations, including
|
||||
* data that might not have been allocated for `Buffer`s.
|
||||
*
|
||||
* A `TypeError` will be thrown if `size` is not a number.
|
||||
* @since v5.10.0
|
||||
* @param size The desired length of the new `Buffer`.
|
||||
* @param [fill=0] A value to pre-fill the new `Buffer` with.
|
||||
* @param [encoding='utf8'] If `fill` is a string, this is its encoding.
|
||||
*/
|
||||
alloc(size: number, fill?: string | Uint8Array | number, encoding?: BufferEncoding): Buffer<ArrayBuffer>;
|
||||
/**
|
||||
* Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown.
|
||||
*
|
||||
* The underlying memory for `Buffer` instances created in this way is _not_
|
||||
* _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `Buffer.alloc()` instead to initialize`Buffer` instances with zeroes.
|
||||
*
|
||||
* ```js
|
||||
* import { Buffer } from 'node:buffer';
|
||||
*
|
||||
* const buf = Buffer.allocUnsafe(10);
|
||||
*
|
||||
* console.log(buf);
|
||||
* // Prints (contents may vary): <Buffer a0 8b 28 3f 01 00 00 00 50 32>
|
||||
*
|
||||
* buf.fill(0);
|
||||
*
|
||||
* console.log(buf);
|
||||
* // Prints: <Buffer 00 00 00 00 00 00 00 00 00 00>
|
||||
* ```
|
||||
*
|
||||
* A `TypeError` will be thrown if `size` is not a number.
|
||||
*
|
||||
* The `Buffer` module pre-allocates an internal `Buffer` instance of
|
||||
* size `Buffer.poolSize` that is used as a pool for the fast allocation of new `Buffer` instances created using `Buffer.allocUnsafe()`, `Buffer.from(array)`,
|
||||
* and `Buffer.concat()` only when `size` is less than `Buffer.poolSize >>> 1` (floor of `Buffer.poolSize` divided by two).
|
||||
*
|
||||
* Use of this pre-allocated internal memory pool is a key difference between
|
||||
* calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`.
|
||||
* Specifically, `Buffer.alloc(size, fill)` will _never_ use the internal `Buffer`pool, while `Buffer.allocUnsafe(size).fill(fill)`_will_ use the internal`Buffer` pool if `size` is less
|
||||
* than or equal to half `Buffer.poolSize`. The
|
||||
* difference is subtle but can be important when an application requires the
|
||||
* additional performance that `Buffer.allocUnsafe()` provides.
|
||||
* @since v5.10.0
|
||||
* @param size The desired length of the new `Buffer`.
|
||||
*/
|
||||
allocUnsafe(size: number): Buffer<ArrayBuffer>;
|
||||
/**
|
||||
* Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. A zero-length `Buffer` is created if
|
||||
* `size` is 0.
|
||||
*
|
||||
* The underlying memory for `Buffer` instances created in this way is _not_
|
||||
* _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `buf.fill(0)` to initialize
|
||||
* such `Buffer` instances with zeroes.
|
||||
*
|
||||
* When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances,
|
||||
* allocations under 4 KiB are sliced from a single pre-allocated `Buffer`. This
|
||||
* allows applications to avoid the garbage collection overhead of creating many
|
||||
* individually allocated `Buffer` instances. This approach improves both
|
||||
* performance and memory usage by eliminating the need to track and clean up as
|
||||
* many individual `ArrayBuffer` objects.
|
||||
*
|
||||
* However, in the case where a developer may need to retain a small chunk of
|
||||
* memory from a pool for an indeterminate amount of time, it may be appropriate
|
||||
* to create an un-pooled `Buffer` instance using `Buffer.allocUnsafeSlow()` and
|
||||
* then copying out the relevant bits.
|
||||
*
|
||||
* ```js
|
||||
* import { Buffer } from 'node:buffer';
|
||||
*
|
||||
* // Need to keep around a few small chunks of memory.
|
||||
* const store = [];
|
||||
*
|
||||
* socket.on('readable', () => {
|
||||
* let data;
|
||||
* while (null !== (data = readable.read())) {
|
||||
* // Allocate for retained data.
|
||||
* const sb = Buffer.allocUnsafeSlow(10);
|
||||
*
|
||||
* // Copy the data into the new allocation.
|
||||
* data.copy(sb, 0, 0, 10);
|
||||
*
|
||||
* store.push(sb);
|
||||
* }
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* A `TypeError` will be thrown if `size` is not a number.
|
||||
* @since v5.12.0
|
||||
* @param size The desired length of the new `Buffer`.
|
||||
*/
|
||||
allocUnsafeSlow(size: number): Buffer<ArrayBuffer>;
|
||||
}
|
||||
interface Buffer<TArrayBuffer extends ArrayBufferLike = ArrayBufferLike> extends Uint8Array<TArrayBuffer> {
|
||||
// see buffer.d.ts for implementation shared with all TypeScript versions
|
||||
|
||||
/**
|
||||
* Returns a new `Buffer` that references the same memory as the original, but
|
||||
* offset and cropped by the `start` and `end` indices.
|
||||
*
|
||||
* This method is not compatible with the `Uint8Array.prototype.slice()`,
|
||||
* which is a superclass of `Buffer`. To copy the slice, use`Uint8Array.prototype.slice()`.
|
||||
*
|
||||
* ```js
|
||||
* import { Buffer } from 'node:buffer';
|
||||
*
|
||||
* const buf = Buffer.from('buffer');
|
||||
*
|
||||
* const copiedBuf = Uint8Array.prototype.slice.call(buf);
|
||||
* copiedBuf[0]++;
|
||||
* console.log(copiedBuf.toString());
|
||||
* // Prints: cuffer
|
||||
*
|
||||
* console.log(buf.toString());
|
||||
* // Prints: buffer
|
||||
*
|
||||
* // With buf.slice(), the original buffer is modified.
|
||||
* const notReallyCopiedBuf = buf.slice();
|
||||
* notReallyCopiedBuf[0]++;
|
||||
* console.log(notReallyCopiedBuf.toString());
|
||||
* // Prints: cuffer
|
||||
* console.log(buf.toString());
|
||||
* // Also prints: cuffer (!)
|
||||
* ```
|
||||
* @since v0.3.0
|
||||
* @deprecated Use `subarray` instead.
|
||||
* @param [start=0] Where the new `Buffer` will start.
|
||||
* @param [end=buf.length] Where the new `Buffer` will end (not inclusive).
|
||||
*/
|
||||
slice(start?: number, end?: number): Buffer<ArrayBuffer>;
|
||||
/**
|
||||
* Returns a new `Buffer` that references the same memory as the original, but
|
||||
* offset and cropped by the `start` and `end` indices.
|
||||
*
|
||||
* Specifying `end` greater than `buf.length` will return the same result as
|
||||
* that of `end` equal to `buf.length`.
|
||||
*
|
||||
* This method is inherited from [`TypedArray.prototype.subarray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray).
|
||||
*
|
||||
* Modifying the new `Buffer` slice will modify the memory in the original `Buffer`because the allocated memory of the two objects overlap.
|
||||
*
|
||||
* ```js
|
||||
* import { Buffer } from 'node:buffer';
|
||||
*
|
||||
* // Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte
|
||||
* // from the original `Buffer`.
|
||||
*
|
||||
* const buf1 = Buffer.allocUnsafe(26);
|
||||
*
|
||||
* for (let i = 0; i < 26; i++) {
|
||||
* // 97 is the decimal ASCII value for 'a'.
|
||||
* buf1[i] = i + 97;
|
||||
* }
|
||||
*
|
||||
* const buf2 = buf1.subarray(0, 3);
|
||||
*
|
||||
* console.log(buf2.toString('ascii', 0, buf2.length));
|
||||
* // Prints: abc
|
||||
*
|
||||
* buf1[0] = 33;
|
||||
*
|
||||
* console.log(buf2.toString('ascii', 0, buf2.length));
|
||||
* // Prints: !bc
|
||||
* ```
|
||||
*
|
||||
* Specifying negative indexes causes the slice to be generated relative to the
|
||||
* end of `buf` rather than the beginning.
|
||||
*
|
||||
* ```js
|
||||
* import { Buffer } from 'node:buffer';
|
||||
*
|
||||
* const buf = Buffer.from('buffer');
|
||||
*
|
||||
* console.log(buf.subarray(-6, -1).toString());
|
||||
* // Prints: buffe
|
||||
* // (Equivalent to buf.subarray(0, 5).)
|
||||
*
|
||||
* console.log(buf.subarray(-6, -2).toString());
|
||||
* // Prints: buff
|
||||
* // (Equivalent to buf.subarray(0, 4).)
|
||||
*
|
||||
* console.log(buf.subarray(-5, -2).toString());
|
||||
* // Prints: uff
|
||||
* // (Equivalent to buf.subarray(1, 4).)
|
||||
* ```
|
||||
* @since v3.0.0
|
||||
* @param [start=0] Where the new `Buffer` will start.
|
||||
* @param [end=buf.length] Where the new `Buffer` will end (not inclusive).
|
||||
*/
|
||||
subarray(start?: number, end?: number): Buffer<TArrayBuffer>;
|
||||
}
|
||||
// TODO: remove globals in future version
|
||||
/**
|
||||
* @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports
|
||||
* TypeScript versions earlier than 5.7.
|
||||
*/
|
||||
type NonSharedBuffer = Buffer<ArrayBuffer>;
|
||||
/**
|
||||
* @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports
|
||||
* TypeScript versions earlier than 5.7.
|
||||
*/
|
||||
type AllowSharedBuffer = Buffer<ArrayBufferLike>;
|
||||
}
|
||||
/** @deprecated Use `Buffer.allocUnsafeSlow()` instead. */
|
||||
var SlowBuffer: {
|
||||
/** @deprecated Use `Buffer.allocUnsafeSlow()` instead. */
|
||||
new(size: number): Buffer<ArrayBuffer>;
|
||||
prototype: Buffer;
|
||||
};
|
||||
}
|
||||
1934
node_modules/sitemap/node_modules/@types/node/buffer.d.ts
generated
vendored
Normal file
1934
node_modules/sitemap/node_modules/@types/node/buffer.d.ts
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
1476
node_modules/sitemap/node_modules/@types/node/child_process.d.ts
generated
vendored
Normal file
1476
node_modules/sitemap/node_modules/@types/node/child_process.d.ts
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
578
node_modules/sitemap/node_modules/@types/node/cluster.d.ts
generated
vendored
Normal file
578
node_modules/sitemap/node_modules/@types/node/cluster.d.ts
generated
vendored
Normal file
@@ -0,0 +1,578 @@
|
||||
/**
|
||||
* Clusters of Node.js processes can be used to run multiple instances of Node.js
|
||||
* that can distribute workloads among their application threads. When process isolation
|
||||
* is not needed, use the [`worker_threads`](https://nodejs.org/docs/latest-v24.x/api/worker_threads.html)
|
||||
* module instead, which allows running multiple application threads within a single Node.js instance.
|
||||
*
|
||||
* The cluster module allows easy creation of child processes that all share
|
||||
* server ports.
|
||||
*
|
||||
* ```js
|
||||
* import cluster from 'node:cluster';
|
||||
* import http from 'node:http';
|
||||
* import { availableParallelism } from 'node:os';
|
||||
* import process from 'node:process';
|
||||
*
|
||||
* const numCPUs = availableParallelism();
|
||||
*
|
||||
* if (cluster.isPrimary) {
|
||||
* console.log(`Primary ${process.pid} is running`);
|
||||
*
|
||||
* // Fork workers.
|
||||
* for (let i = 0; i < numCPUs; i++) {
|
||||
* cluster.fork();
|
||||
* }
|
||||
*
|
||||
* cluster.on('exit', (worker, code, signal) => {
|
||||
* console.log(`worker ${worker.process.pid} died`);
|
||||
* });
|
||||
* } else {
|
||||
* // Workers can share any TCP connection
|
||||
* // In this case it is an HTTP server
|
||||
* http.createServer((req, res) => {
|
||||
* res.writeHead(200);
|
||||
* res.end('hello world\n');
|
||||
* }).listen(8000);
|
||||
*
|
||||
* console.log(`Worker ${process.pid} started`);
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* Running Node.js will now share port 8000 between the workers:
|
||||
*
|
||||
* ```console
|
||||
* $ node server.js
|
||||
* Primary 3596 is running
|
||||
* Worker 4324 started
|
||||
* Worker 4520 started
|
||||
* Worker 6056 started
|
||||
* Worker 5644 started
|
||||
* ```
|
||||
*
|
||||
* On Windows, it is not yet possible to set up a named pipe server in a worker.
|
||||
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/cluster.js)
|
||||
*/
|
||||
declare module "cluster" {
|
||||
import * as child from "node:child_process";
|
||||
import EventEmitter = require("node:events");
|
||||
import * as net from "node:net";
|
||||
type SerializationType = "json" | "advanced";
|
||||
export interface ClusterSettings {
|
||||
/**
|
||||
* List of string arguments passed to the Node.js executable.
|
||||
* @default process.execArgv
|
||||
*/
|
||||
execArgv?: string[] | undefined;
|
||||
/**
|
||||
* File path to worker file.
|
||||
* @default process.argv[1]
|
||||
*/
|
||||
exec?: string | undefined;
|
||||
/**
|
||||
* String arguments passed to worker.
|
||||
* @default process.argv.slice(2)
|
||||
*/
|
||||
args?: readonly string[] | undefined;
|
||||
/**
|
||||
* Whether or not to send output to parent's stdio.
|
||||
* @default false
|
||||
*/
|
||||
silent?: boolean | undefined;
|
||||
/**
|
||||
* Configures the stdio of forked processes. Because the cluster module relies on IPC to function, this configuration must
|
||||
* contain an `'ipc'` entry. When this option is provided, it overrides `silent`. See [`child_prcess.spawn()`](https://nodejs.org/docs/latest-v24.x/api/child_process.html#child_processspawncommand-args-options)'s
|
||||
* [`stdio`](https://nodejs.org/docs/latest-v24.x/api/child_process.html#optionsstdio).
|
||||
*/
|
||||
stdio?: any[] | undefined;
|
||||
/**
|
||||
* Sets the user identity of the process. (See [`setuid(2)`](https://man7.org/linux/man-pages/man2/setuid.2.html).)
|
||||
*/
|
||||
uid?: number | undefined;
|
||||
/**
|
||||
* Sets the group identity of the process. (See [`setgid(2)`](https://man7.org/linux/man-pages/man2/setgid.2.html).)
|
||||
*/
|
||||
gid?: number | undefined;
|
||||
/**
|
||||
* Sets inspector port of worker. This can be a number, or a function that takes no arguments and returns a number.
|
||||
* By default each worker gets its own port, incremented from the primary's `process.debugPort`.
|
||||
*/
|
||||
inspectPort?: number | (() => number) | undefined;
|
||||
/**
|
||||
* Specify the kind of serialization used for sending messages between processes. Possible values are `'json'` and `'advanced'`.
|
||||
* See [Advanced serialization for `child_process`](https://nodejs.org/docs/latest-v24.x/api/child_process.html#advanced-serialization) for more details.
|
||||
* @default false
|
||||
*/
|
||||
serialization?: SerializationType | undefined;
|
||||
/**
|
||||
* Current working directory of the worker process.
|
||||
* @default undefined (inherits from parent process)
|
||||
*/
|
||||
cwd?: string | undefined;
|
||||
/**
|
||||
* Hide the forked processes console window that would normally be created on Windows systems.
|
||||
* @default false
|
||||
*/
|
||||
windowsHide?: boolean | undefined;
|
||||
}
|
||||
export interface Address {
|
||||
address: string;
|
||||
port: number;
|
||||
/**
|
||||
* The `addressType` is one of:
|
||||
*
|
||||
* * `4` (TCPv4)
|
||||
* * `6` (TCPv6)
|
||||
* * `-1` (Unix domain socket)
|
||||
* * `'udp4'` or `'udp6'` (UDPv4 or UDPv6)
|
||||
*/
|
||||
addressType: 4 | 6 | -1 | "udp4" | "udp6";
|
||||
}
|
||||
/**
|
||||
* A `Worker` object contains all public information and method about a worker.
|
||||
* In the primary it can be obtained using `cluster.workers`. In a worker
|
||||
* it can be obtained using `cluster.worker`.
|
||||
* @since v0.7.0
|
||||
*/
|
||||
export class Worker extends EventEmitter {
|
||||
/**
|
||||
* Each new worker is given its own unique id, this id is stored in the `id`.
|
||||
*
|
||||
* While a worker is alive, this is the key that indexes it in `cluster.workers`.
|
||||
* @since v0.8.0
|
||||
*/
|
||||
id: number;
|
||||
/**
|
||||
* All workers are created using [`child_process.fork()`](https://nodejs.org/docs/latest-v24.x/api/child_process.html#child_processforkmodulepath-args-options), the returned object
|
||||
* from this function is stored as `.process`. In a worker, the global `process` is stored.
|
||||
*
|
||||
* See: [Child Process module](https://nodejs.org/docs/latest-v24.x/api/child_process.html#child_processforkmodulepath-args-options).
|
||||
*
|
||||
* Workers will call `process.exit(0)` if the `'disconnect'` event occurs
|
||||
* on `process` and `.exitedAfterDisconnect` is not `true`. This protects against
|
||||
* accidental disconnection.
|
||||
* @since v0.7.0
|
||||
*/
|
||||
process: child.ChildProcess;
|
||||
/**
|
||||
* Send a message to a worker or primary, optionally with a handle.
|
||||
*
|
||||
* In the primary, this sends a message to a specific worker. It is identical to [`ChildProcess.send()`](https://nodejs.org/docs/latest-v24.x/api/child_process.html#subprocesssendmessage-sendhandle-options-callback).
|
||||
*
|
||||
* In a worker, this sends a message to the primary. It is identical to `process.send()`.
|
||||
*
|
||||
* This example will echo back all messages from the primary:
|
||||
*
|
||||
* ```js
|
||||
* if (cluster.isPrimary) {
|
||||
* const worker = cluster.fork();
|
||||
* worker.send('hi there');
|
||||
*
|
||||
* } else if (cluster.isWorker) {
|
||||
* process.on('message', (msg) => {
|
||||
* process.send(msg);
|
||||
* });
|
||||
* }
|
||||
* ```
|
||||
* @since v0.7.0
|
||||
* @param options The `options` argument, if present, is an object used to parameterize the sending of certain types of handles.
|
||||
*/
|
||||
send(message: child.Serializable, callback?: (error: Error | null) => void): boolean;
|
||||
send(
|
||||
message: child.Serializable,
|
||||
sendHandle: child.SendHandle,
|
||||
callback?: (error: Error | null) => void,
|
||||
): boolean;
|
||||
send(
|
||||
message: child.Serializable,
|
||||
sendHandle: child.SendHandle,
|
||||
options?: child.MessageOptions,
|
||||
callback?: (error: Error | null) => void,
|
||||
): boolean;
|
||||
/**
|
||||
* This function will kill the worker. In the primary worker, it does this by
|
||||
* disconnecting the `worker.process`, and once disconnected, killing with `signal`. In the worker, it does it by killing the process with `signal`.
|
||||
*
|
||||
* The `kill()` function kills the worker process without waiting for a graceful
|
||||
* disconnect, it has the same behavior as `worker.process.kill()`.
|
||||
*
|
||||
* This method is aliased as `worker.destroy()` for backwards compatibility.
|
||||
*
|
||||
* In a worker, `process.kill()` exists, but it is not this function;
|
||||
* it is [`kill()`](https://nodejs.org/docs/latest-v24.x/api/process.html#processkillpid-signal).
|
||||
* @since v0.9.12
|
||||
* @param [signal='SIGTERM'] Name of the kill signal to send to the worker process.
|
||||
*/
|
||||
kill(signal?: string): void;
|
||||
destroy(signal?: string): void;
|
||||
/**
|
||||
* In a worker, this function will close all servers, wait for the `'close'` event
|
||||
* on those servers, and then disconnect the IPC channel.
|
||||
*
|
||||
* In the primary, an internal message is sent to the worker causing it to call `.disconnect()` on itself.
|
||||
*
|
||||
* Causes `.exitedAfterDisconnect` to be set.
|
||||
*
|
||||
* After a server is closed, it will no longer accept new connections,
|
||||
* but connections may be accepted by any other listening worker. Existing
|
||||
* connections will be allowed to close as usual. When no more connections exist,
|
||||
* see `server.close()`, the IPC channel to the worker will close allowing it
|
||||
* to die gracefully.
|
||||
*
|
||||
* The above applies _only_ to server connections, client connections are not
|
||||
* automatically closed by workers, and disconnect does not wait for them to close
|
||||
* before exiting.
|
||||
*
|
||||
* In a worker, `process.disconnect` exists, but it is not this function;
|
||||
* it is `disconnect()`.
|
||||
*
|
||||
* Because long living server connections may block workers from disconnecting, it
|
||||
* may be useful to send a message, so application specific actions may be taken to
|
||||
* close them. It also may be useful to implement a timeout, killing a worker if
|
||||
* the `'disconnect'` event has not been emitted after some time.
|
||||
*
|
||||
* ```js
|
||||
* import net from 'node:net';
|
||||
*
|
||||
* if (cluster.isPrimary) {
|
||||
* const worker = cluster.fork();
|
||||
* let timeout;
|
||||
*
|
||||
* worker.on('listening', (address) => {
|
||||
* worker.send('shutdown');
|
||||
* worker.disconnect();
|
||||
* timeout = setTimeout(() => {
|
||||
* worker.kill();
|
||||
* }, 2000);
|
||||
* });
|
||||
*
|
||||
* worker.on('disconnect', () => {
|
||||
* clearTimeout(timeout);
|
||||
* });
|
||||
*
|
||||
* } else if (cluster.isWorker) {
|
||||
* const server = net.createServer((socket) => {
|
||||
* // Connections never end
|
||||
* });
|
||||
*
|
||||
* server.listen(8000);
|
||||
*
|
||||
* process.on('message', (msg) => {
|
||||
* if (msg === 'shutdown') {
|
||||
* // Initiate graceful close of any connections to server
|
||||
* }
|
||||
* });
|
||||
* }
|
||||
* ```
|
||||
* @since v0.7.7
|
||||
* @return A reference to `worker`.
|
||||
*/
|
||||
disconnect(): this;
|
||||
/**
|
||||
* This function returns `true` if the worker is connected to its primary via its
|
||||
* IPC channel, `false` otherwise. A worker is connected to its primary after it
|
||||
* has been created. It is disconnected after the `'disconnect'` event is emitted.
|
||||
* @since v0.11.14
|
||||
*/
|
||||
isConnected(): boolean;
|
||||
/**
|
||||
* This function returns `true` if the worker's process has terminated (either
|
||||
* because of exiting or being signaled). Otherwise, it returns `false`.
|
||||
*
|
||||
* ```js
|
||||
* import cluster from 'node:cluster';
|
||||
* import http from 'node:http';
|
||||
* import { availableParallelism } from 'node:os';
|
||||
* import process from 'node:process';
|
||||
*
|
||||
* const numCPUs = availableParallelism();
|
||||
*
|
||||
* if (cluster.isPrimary) {
|
||||
* console.log(`Primary ${process.pid} is running`);
|
||||
*
|
||||
* // Fork workers.
|
||||
* for (let i = 0; i < numCPUs; i++) {
|
||||
* cluster.fork();
|
||||
* }
|
||||
*
|
||||
* cluster.on('fork', (worker) => {
|
||||
* console.log('worker is dead:', worker.isDead());
|
||||
* });
|
||||
*
|
||||
* cluster.on('exit', (worker, code, signal) => {
|
||||
* console.log('worker is dead:', worker.isDead());
|
||||
* });
|
||||
* } else {
|
||||
* // Workers can share any TCP connection. In this case, it is an HTTP server.
|
||||
* http.createServer((req, res) => {
|
||||
* res.writeHead(200);
|
||||
* res.end(`Current process\n ${process.pid}`);
|
||||
* process.kill(process.pid);
|
||||
* }).listen(8000);
|
||||
* }
|
||||
* ```
|
||||
* @since v0.11.14
|
||||
*/
|
||||
isDead(): boolean;
|
||||
/**
|
||||
* This property is `true` if the worker exited due to `.disconnect()`.
|
||||
* If the worker exited any other way, it is `false`. If the
|
||||
* worker has not exited, it is `undefined`.
|
||||
*
|
||||
* The boolean `worker.exitedAfterDisconnect` allows distinguishing between
|
||||
* voluntary and accidental exit, the primary may choose not to respawn a worker
|
||||
* based on this value.
|
||||
*
|
||||
* ```js
|
||||
* cluster.on('exit', (worker, code, signal) => {
|
||||
* if (worker.exitedAfterDisconnect === true) {
|
||||
* console.log('Oh, it was just voluntary – no need to worry');
|
||||
* }
|
||||
* });
|
||||
*
|
||||
* // kill worker
|
||||
* worker.kill();
|
||||
* ```
|
||||
* @since v6.0.0
|
||||
*/
|
||||
exitedAfterDisconnect: boolean;
|
||||
/**
|
||||
* events.EventEmitter
|
||||
* 1. disconnect
|
||||
* 2. error
|
||||
* 3. exit
|
||||
* 4. listening
|
||||
* 5. message
|
||||
* 6. online
|
||||
*/
|
||||
addListener(event: string, listener: (...args: any[]) => void): this;
|
||||
addListener(event: "disconnect", listener: () => void): this;
|
||||
addListener(event: "error", listener: (error: Error) => void): this;
|
||||
addListener(event: "exit", listener: (code: number, signal: string) => void): this;
|
||||
addListener(event: "listening", listener: (address: Address) => void): this;
|
||||
addListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
|
||||
addListener(event: "online", listener: () => void): this;
|
||||
emit(event: string | symbol, ...args: any[]): boolean;
|
||||
emit(event: "disconnect"): boolean;
|
||||
emit(event: "error", error: Error): boolean;
|
||||
emit(event: "exit", code: number, signal: string): boolean;
|
||||
emit(event: "listening", address: Address): boolean;
|
||||
emit(event: "message", message: any, handle: net.Socket | net.Server): boolean;
|
||||
emit(event: "online"): boolean;
|
||||
on(event: string, listener: (...args: any[]) => void): this;
|
||||
on(event: "disconnect", listener: () => void): this;
|
||||
on(event: "error", listener: (error: Error) => void): this;
|
||||
on(event: "exit", listener: (code: number, signal: string) => void): this;
|
||||
on(event: "listening", listener: (address: Address) => void): this;
|
||||
on(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
|
||||
on(event: "online", listener: () => void): this;
|
||||
once(event: string, listener: (...args: any[]) => void): this;
|
||||
once(event: "disconnect", listener: () => void): this;
|
||||
once(event: "error", listener: (error: Error) => void): this;
|
||||
once(event: "exit", listener: (code: number, signal: string) => void): this;
|
||||
once(event: "listening", listener: (address: Address) => void): this;
|
||||
once(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
|
||||
once(event: "online", listener: () => void): this;
|
||||
prependListener(event: string, listener: (...args: any[]) => void): this;
|
||||
prependListener(event: "disconnect", listener: () => void): this;
|
||||
prependListener(event: "error", listener: (error: Error) => void): this;
|
||||
prependListener(event: "exit", listener: (code: number, signal: string) => void): this;
|
||||
prependListener(event: "listening", listener: (address: Address) => void): this;
|
||||
prependListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
|
||||
prependListener(event: "online", listener: () => void): this;
|
||||
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
|
||||
prependOnceListener(event: "disconnect", listener: () => void): this;
|
||||
prependOnceListener(event: "error", listener: (error: Error) => void): this;
|
||||
prependOnceListener(event: "exit", listener: (code: number, signal: string) => void): this;
|
||||
prependOnceListener(event: "listening", listener: (address: Address) => void): this;
|
||||
prependOnceListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
|
||||
prependOnceListener(event: "online", listener: () => void): this;
|
||||
}
|
||||
export interface Cluster extends EventEmitter {
|
||||
disconnect(callback?: () => void): void;
|
||||
/**
|
||||
* Spawn a new worker process.
|
||||
*
|
||||
* This can only be called from the primary process.
|
||||
* @param env Key/value pairs to add to worker process environment.
|
||||
* @since v0.6.0
|
||||
*/
|
||||
fork(env?: any): Worker;
|
||||
/** @deprecated since v16.0.0 - use isPrimary. */
|
||||
readonly isMaster: boolean;
|
||||
/**
|
||||
* True if the process is a primary. This is determined by the `process.env.NODE_UNIQUE_ID`. If `process.env.NODE_UNIQUE_ID`
|
||||
* is undefined, then `isPrimary` is `true`.
|
||||
* @since v16.0.0
|
||||
*/
|
||||
readonly isPrimary: boolean;
|
||||
/**
|
||||
* True if the process is not a primary (it is the negation of `cluster.isPrimary`).
|
||||
* @since v0.6.0
|
||||
*/
|
||||
readonly isWorker: boolean;
|
||||
/**
|
||||
* The scheduling policy, either `cluster.SCHED_RR` for round-robin or `cluster.SCHED_NONE` to leave it to the operating system. This is a
|
||||
* global setting and effectively frozen once either the first worker is spawned, or [`.setupPrimary()`](https://nodejs.org/docs/latest-v24.x/api/cluster.html#clustersetupprimarysettings)
|
||||
* is called, whichever comes first.
|
||||
*
|
||||
* `SCHED_RR` is the default on all operating systems except Windows. Windows will change to `SCHED_RR` once libuv is able to effectively distribute
|
||||
* IOCP handles without incurring a large performance hit.
|
||||
*
|
||||
* `cluster.schedulingPolicy` can also be set through the `NODE_CLUSTER_SCHED_POLICY` environment variable. Valid values are `'rr'` and `'none'`.
|
||||
* @since v0.11.2
|
||||
*/
|
||||
schedulingPolicy: number;
|
||||
/**
|
||||
* After calling [`.setupPrimary()`](https://nodejs.org/docs/latest-v24.x/api/cluster.html#clustersetupprimarysettings)
|
||||
* (or [`.fork()`](https://nodejs.org/docs/latest-v24.x/api/cluster.html#clusterforkenv)) this settings object will contain
|
||||
* the settings, including the default values.
|
||||
*
|
||||
* This object is not intended to be changed or set manually.
|
||||
* @since v0.7.1
|
||||
*/
|
||||
readonly settings: ClusterSettings;
|
||||
/** @deprecated since v16.0.0 - use [`.setupPrimary()`](https://nodejs.org/docs/latest-v24.x/api/cluster.html#clustersetupprimarysettings) instead. */
|
||||
setupMaster(settings?: ClusterSettings): void;
|
||||
/**
|
||||
* `setupPrimary` is used to change the default 'fork' behavior. Once called, the settings will be present in `cluster.settings`.
|
||||
*
|
||||
* Any settings changes only affect future calls to [`.fork()`](https://nodejs.org/docs/latest-v24.x/api/cluster.html#clusterforkenv)
|
||||
* and have no effect on workers that are already running.
|
||||
*
|
||||
* The only attribute of a worker that cannot be set via `.setupPrimary()` is the `env` passed to
|
||||
* [`.fork()`](https://nodejs.org/docs/latest-v24.x/api/cluster.html#clusterforkenv).
|
||||
*
|
||||
* The defaults above apply to the first call only; the defaults for later calls are the current values at the time of
|
||||
* `cluster.setupPrimary()` is called.
|
||||
*
|
||||
* ```js
|
||||
* import cluster from 'node:cluster';
|
||||
*
|
||||
* cluster.setupPrimary({
|
||||
* exec: 'worker.js',
|
||||
* args: ['--use', 'https'],
|
||||
* silent: true,
|
||||
* });
|
||||
* cluster.fork(); // https worker
|
||||
* cluster.setupPrimary({
|
||||
* exec: 'worker.js',
|
||||
* args: ['--use', 'http'],
|
||||
* });
|
||||
* cluster.fork(); // http worker
|
||||
* ```
|
||||
*
|
||||
* This can only be called from the primary process.
|
||||
* @since v16.0.0
|
||||
*/
|
||||
setupPrimary(settings?: ClusterSettings): void;
|
||||
/**
|
||||
* A reference to the current worker object. Not available in the primary process.
|
||||
*
|
||||
* ```js
|
||||
* import cluster from 'node:cluster';
|
||||
*
|
||||
* if (cluster.isPrimary) {
|
||||
* console.log('I am primary');
|
||||
* cluster.fork();
|
||||
* cluster.fork();
|
||||
* } else if (cluster.isWorker) {
|
||||
* console.log(`I am worker #${cluster.worker.id}`);
|
||||
* }
|
||||
* ```
|
||||
* @since v0.7.0
|
||||
*/
|
||||
readonly worker?: Worker;
|
||||
/**
|
||||
* A hash that stores the active worker objects, keyed by `id` field. This makes it easy to loop through all the workers. It is only available in the primary process.
|
||||
*
|
||||
* A worker is removed from `cluster.workers` after the worker has disconnected _and_ exited. The order between these two events cannot be determined in advance. However, it
|
||||
* is guaranteed that the removal from the `cluster.workers` list happens before the last `'disconnect'` or `'exit'` event is emitted.
|
||||
*
|
||||
* ```js
|
||||
* import cluster from 'node:cluster';
|
||||
*
|
||||
* for (const worker of Object.values(cluster.workers)) {
|
||||
* worker.send('big announcement to all workers');
|
||||
* }
|
||||
* ```
|
||||
* @since v0.7.0
|
||||
*/
|
||||
readonly workers?: NodeJS.Dict<Worker>;
|
||||
readonly SCHED_NONE: number;
|
||||
readonly SCHED_RR: number;
|
||||
/**
|
||||
* events.EventEmitter
|
||||
* 1. disconnect
|
||||
* 2. exit
|
||||
* 3. fork
|
||||
* 4. listening
|
||||
* 5. message
|
||||
* 6. online
|
||||
* 7. setup
|
||||
*/
|
||||
addListener(event: string, listener: (...args: any[]) => void): this;
|
||||
addListener(event: "disconnect", listener: (worker: Worker) => void): this;
|
||||
addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this;
|
||||
addListener(event: "fork", listener: (worker: Worker) => void): this;
|
||||
addListener(event: "listening", listener: (worker: Worker, address: Address) => void): this;
|
||||
addListener(
|
||||
event: "message",
|
||||
listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void,
|
||||
): this; // the handle is a net.Socket or net.Server object, or undefined.
|
||||
addListener(event: "online", listener: (worker: Worker) => void): this;
|
||||
addListener(event: "setup", listener: (settings: ClusterSettings) => void): this;
|
||||
emit(event: string | symbol, ...args: any[]): boolean;
|
||||
emit(event: "disconnect", worker: Worker): boolean;
|
||||
emit(event: "exit", worker: Worker, code: number, signal: string): boolean;
|
||||
emit(event: "fork", worker: Worker): boolean;
|
||||
emit(event: "listening", worker: Worker, address: Address): boolean;
|
||||
emit(event: "message", worker: Worker, message: any, handle: net.Socket | net.Server): boolean;
|
||||
emit(event: "online", worker: Worker): boolean;
|
||||
emit(event: "setup", settings: ClusterSettings): boolean;
|
||||
on(event: string, listener: (...args: any[]) => void): this;
|
||||
on(event: "disconnect", listener: (worker: Worker) => void): this;
|
||||
on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this;
|
||||
on(event: "fork", listener: (worker: Worker) => void): this;
|
||||
on(event: "listening", listener: (worker: Worker, address: Address) => void): this;
|
||||
on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
|
||||
on(event: "online", listener: (worker: Worker) => void): this;
|
||||
on(event: "setup", listener: (settings: ClusterSettings) => void): this;
|
||||
once(event: string, listener: (...args: any[]) => void): this;
|
||||
once(event: "disconnect", listener: (worker: Worker) => void): this;
|
||||
once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this;
|
||||
once(event: "fork", listener: (worker: Worker) => void): this;
|
||||
once(event: "listening", listener: (worker: Worker, address: Address) => void): this;
|
||||
once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
|
||||
once(event: "online", listener: (worker: Worker) => void): this;
|
||||
once(event: "setup", listener: (settings: ClusterSettings) => void): this;
|
||||
prependListener(event: string, listener: (...args: any[]) => void): this;
|
||||
prependListener(event: "disconnect", listener: (worker: Worker) => void): this;
|
||||
prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this;
|
||||
prependListener(event: "fork", listener: (worker: Worker) => void): this;
|
||||
prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): this;
|
||||
prependListener(
|
||||
event: "message",
|
||||
listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void,
|
||||
): this;
|
||||
prependListener(event: "online", listener: (worker: Worker) => void): this;
|
||||
prependListener(event: "setup", listener: (settings: ClusterSettings) => void): this;
|
||||
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
|
||||
prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): this;
|
||||
prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this;
|
||||
prependOnceListener(event: "fork", listener: (worker: Worker) => void): this;
|
||||
prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): this;
|
||||
// the handle is a net.Socket or net.Server object, or undefined.
|
||||
prependOnceListener(
|
||||
event: "message",
|
||||
listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void,
|
||||
): this;
|
||||
prependOnceListener(event: "online", listener: (worker: Worker) => void): this;
|
||||
prependOnceListener(event: "setup", listener: (settings: ClusterSettings) => void): this;
|
||||
}
|
||||
const cluster: Cluster;
|
||||
export default cluster;
|
||||
}
|
||||
declare module "node:cluster" {
|
||||
export * from "cluster";
|
||||
export { default as default } from "cluster";
|
||||
}
|
||||
21
node_modules/sitemap/node_modules/@types/node/compatibility/iterators.d.ts
generated
vendored
Normal file
21
node_modules/sitemap/node_modules/@types/node/compatibility/iterators.d.ts
generated
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
// Backwards-compatible iterator interfaces, augmented with iterator helper methods by lib.esnext.iterator in TypeScript 5.6.
|
||||
// The IterableIterator interface does not contain these methods, which creates assignability issues in places where IteratorObjects
|
||||
// are expected (eg. DOM-compatible APIs) if lib.esnext.iterator is loaded.
|
||||
// Also ensures that iterators returned by the Node API, which inherit from Iterator.prototype, correctly expose the iterator helper methods
|
||||
// if lib.esnext.iterator is loaded.
|
||||
// TODO: remove once this package no longer supports TS 5.5, and replace NodeJS.BuiltinIteratorReturn with BuiltinIteratorReturn.
|
||||
|
||||
// Placeholders for TS <5.6
|
||||
interface IteratorObject<T, TReturn, TNext> {}
|
||||
interface AsyncIteratorObject<T, TReturn, TNext> {}
|
||||
|
||||
declare namespace NodeJS {
|
||||
// Populate iterator methods for TS <5.6
|
||||
interface Iterator<T, TReturn, TNext> extends globalThis.Iterator<T, TReturn, TNext> {}
|
||||
interface AsyncIterator<T, TReturn, TNext> extends globalThis.AsyncIterator<T, TReturn, TNext> {}
|
||||
|
||||
// Polyfill for TS 5.6's instrinsic BuiltinIteratorReturn type, required for DOM-compatible iterators
|
||||
type BuiltinIteratorReturn = ReturnType<any[][typeof Symbol.iterator]> extends
|
||||
globalThis.Iterator<any, infer TReturn> ? TReturn
|
||||
: any;
|
||||
}
|
||||
453
node_modules/sitemap/node_modules/@types/node/console.d.ts
generated
vendored
Normal file
453
node_modules/sitemap/node_modules/@types/node/console.d.ts
generated
vendored
Normal file
@@ -0,0 +1,453 @@
|
||||
/**
|
||||
* The `node:console` module provides a simple debugging console that is similar to
|
||||
* the JavaScript console mechanism provided by web browsers.
|
||||
*
|
||||
* The module exports two specific components:
|
||||
*
|
||||
* * A `Console` class with methods such as `console.log()`, `console.error()`, and `console.warn()` that can be used to write to any Node.js stream.
|
||||
* * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstdout) and
|
||||
* [`process.stderr`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
|
||||
*
|
||||
* _**Warning**_: The global console object's methods are neither consistently
|
||||
* synchronous like the browser APIs they resemble, nor are they consistently
|
||||
* asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v24.x/api/process.html#a-note-on-process-io) for
|
||||
* more information.
|
||||
*
|
||||
* Example using the global `console`:
|
||||
*
|
||||
* ```js
|
||||
* console.log('hello world');
|
||||
* // Prints: hello world, to stdout
|
||||
* console.log('hello %s', 'world');
|
||||
* // Prints: hello world, to stdout
|
||||
* console.error(new Error('Whoops, something bad happened'));
|
||||
* // Prints error message and stack trace to stderr:
|
||||
* // Error: Whoops, something bad happened
|
||||
* // at [eval]:5:15
|
||||
* // at Script.runInThisContext (node:vm:132:18)
|
||||
* // at Object.runInThisContext (node:vm:309:38)
|
||||
* // at node:internal/process/execution:77:19
|
||||
* // at [eval]-wrapper:6:22
|
||||
* // at evalScript (node:internal/process/execution:76:60)
|
||||
* // at node:internal/main/eval_string:23:3
|
||||
*
|
||||
* const name = 'Will Robinson';
|
||||
* console.warn(`Danger ${name}! Danger!`);
|
||||
* // Prints: Danger Will Robinson! Danger!, to stderr
|
||||
* ```
|
||||
*
|
||||
* Example using the `Console` class:
|
||||
*
|
||||
* ```js
|
||||
* const out = getStreamSomehow();
|
||||
* const err = getStreamSomehow();
|
||||
* const myConsole = new console.Console(out, err);
|
||||
*
|
||||
* myConsole.log('hello world');
|
||||
* // Prints: hello world, to out
|
||||
* myConsole.log('hello %s', 'world');
|
||||
* // Prints: hello world, to out
|
||||
* myConsole.error(new Error('Whoops, something bad happened'));
|
||||
* // Prints: [Error: Whoops, something bad happened], to err
|
||||
*
|
||||
* const name = 'Will Robinson';
|
||||
* myConsole.warn(`Danger ${name}! Danger!`);
|
||||
* // Prints: Danger Will Robinson! Danger!, to err
|
||||
* ```
|
||||
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/console.js)
|
||||
*/
|
||||
declare module "console" {
|
||||
import console = require("node:console");
|
||||
export = console;
|
||||
}
|
||||
declare module "node:console" {
|
||||
import { InspectOptions } from "node:util";
|
||||
global {
|
||||
// This needs to be global to avoid TS2403 in case lib.dom.d.ts is present in the same build
|
||||
interface Console {
|
||||
Console: console.ConsoleConstructor;
|
||||
/**
|
||||
* `console.assert()` writes a message if `value` is [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) or omitted. It only
|
||||
* writes a message and does not otherwise affect execution. The output always
|
||||
* starts with `"Assertion failed"`. If provided, `message` is formatted using
|
||||
* [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args).
|
||||
*
|
||||
* If `value` is [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy), nothing happens.
|
||||
*
|
||||
* ```js
|
||||
* console.assert(true, 'does nothing');
|
||||
*
|
||||
* console.assert(false, 'Whoops %s work', 'didn\'t');
|
||||
* // Assertion failed: Whoops didn't work
|
||||
*
|
||||
* console.assert();
|
||||
* // Assertion failed
|
||||
* ```
|
||||
* @since v0.1.101
|
||||
* @param value The value tested for being truthy.
|
||||
* @param message All arguments besides `value` are used as error message.
|
||||
*/
|
||||
assert(value: any, message?: string, ...optionalParams: any[]): void;
|
||||
/**
|
||||
* When `stdout` is a TTY, calling `console.clear()` will attempt to clear the
|
||||
* TTY. When `stdout` is not a TTY, this method does nothing.
|
||||
*
|
||||
* The specific operation of `console.clear()` can vary across operating systems
|
||||
* and terminal types. For most Linux operating systems, `console.clear()` operates similarly to the `clear` shell command. On Windows, `console.clear()` will clear only the output in the
|
||||
* current terminal viewport for the Node.js
|
||||
* binary.
|
||||
* @since v8.3.0
|
||||
*/
|
||||
clear(): void;
|
||||
/**
|
||||
* Maintains an internal counter specific to `label` and outputs to `stdout` the
|
||||
* number of times `console.count()` has been called with the given `label`.
|
||||
*
|
||||
* ```js
|
||||
* > console.count()
|
||||
* default: 1
|
||||
* undefined
|
||||
* > console.count('default')
|
||||
* default: 2
|
||||
* undefined
|
||||
* > console.count('abc')
|
||||
* abc: 1
|
||||
* undefined
|
||||
* > console.count('xyz')
|
||||
* xyz: 1
|
||||
* undefined
|
||||
* > console.count('abc')
|
||||
* abc: 2
|
||||
* undefined
|
||||
* > console.count()
|
||||
* default: 3
|
||||
* undefined
|
||||
* >
|
||||
* ```
|
||||
* @since v8.3.0
|
||||
* @param [label='default'] The display label for the counter.
|
||||
*/
|
||||
count(label?: string): void;
|
||||
/**
|
||||
* Resets the internal counter specific to `label`.
|
||||
*
|
||||
* ```js
|
||||
* > console.count('abc');
|
||||
* abc: 1
|
||||
* undefined
|
||||
* > console.countReset('abc');
|
||||
* undefined
|
||||
* > console.count('abc');
|
||||
* abc: 1
|
||||
* undefined
|
||||
* >
|
||||
* ```
|
||||
* @since v8.3.0
|
||||
* @param [label='default'] The display label for the counter.
|
||||
*/
|
||||
countReset(label?: string): void;
|
||||
/**
|
||||
* The `console.debug()` function is an alias for {@link log}.
|
||||
* @since v8.0.0
|
||||
*/
|
||||
debug(message?: any, ...optionalParams: any[]): void;
|
||||
/**
|
||||
* Uses [`util.inspect()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilinspectobject-options) on `obj` and prints the resulting string to `stdout`.
|
||||
* This function bypasses any custom `inspect()` function defined on `obj`.
|
||||
* @since v0.1.101
|
||||
*/
|
||||
dir(obj: any, options?: InspectOptions): void;
|
||||
/**
|
||||
* This method calls `console.log()` passing it the arguments received.
|
||||
* This method does not produce any XML formatting.
|
||||
* @since v8.0.0
|
||||
*/
|
||||
dirxml(...data: any[]): void;
|
||||
/**
|
||||
* Prints to `stderr` with newline. Multiple arguments can be passed, with the
|
||||
* first used as the primary message and all additional used as substitution
|
||||
* values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
|
||||
* (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args)).
|
||||
*
|
||||
* ```js
|
||||
* const code = 5;
|
||||
* console.error('error #%d', code);
|
||||
* // Prints: error #5, to stderr
|
||||
* console.error('error', code);
|
||||
* // Prints: error 5, to stderr
|
||||
* ```
|
||||
*
|
||||
* If formatting elements (e.g. `%d`) are not found in the first string then
|
||||
* [`util.inspect()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilinspectobject-options) is called on each argument and the
|
||||
* resulting string values are concatenated. See [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args)
|
||||
* for more information.
|
||||
* @since v0.1.100
|
||||
*/
|
||||
error(message?: any, ...optionalParams: any[]): void;
|
||||
/**
|
||||
* Increases indentation of subsequent lines by spaces for `groupIndentation` length.
|
||||
*
|
||||
* If one or more `label`s are provided, those are printed first without the
|
||||
* additional indentation.
|
||||
* @since v8.5.0
|
||||
*/
|
||||
group(...label: any[]): void;
|
||||
/**
|
||||
* An alias for {@link group}.
|
||||
* @since v8.5.0
|
||||
*/
|
||||
groupCollapsed(...label: any[]): void;
|
||||
/**
|
||||
* Decreases indentation of subsequent lines by spaces for `groupIndentation` length.
|
||||
* @since v8.5.0
|
||||
*/
|
||||
groupEnd(): void;
|
||||
/**
|
||||
* The `console.info()` function is an alias for {@link log}.
|
||||
* @since v0.1.100
|
||||
*/
|
||||
info(message?: any, ...optionalParams: any[]): void;
|
||||
/**
|
||||
* Prints to `stdout` with newline. Multiple arguments can be passed, with the
|
||||
* first used as the primary message and all additional used as substitution
|
||||
* values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
|
||||
* (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args)).
|
||||
*
|
||||
* ```js
|
||||
* const count = 5;
|
||||
* console.log('count: %d', count);
|
||||
* // Prints: count: 5, to stdout
|
||||
* console.log('count:', count);
|
||||
* // Prints: count: 5, to stdout
|
||||
* ```
|
||||
*
|
||||
* See [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args) for more information.
|
||||
* @since v0.1.100
|
||||
*/
|
||||
log(message?: any, ...optionalParams: any[]): void;
|
||||
/**
|
||||
* Try to construct a table with the columns of the properties of `tabularData` (or use `properties`) and rows of `tabularData` and log it. Falls back to just
|
||||
* logging the argument if it can't be parsed as tabular.
|
||||
*
|
||||
* ```js
|
||||
* // These can't be parsed as tabular data
|
||||
* console.table(Symbol());
|
||||
* // Symbol()
|
||||
*
|
||||
* console.table(undefined);
|
||||
* // undefined
|
||||
*
|
||||
* console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }]);
|
||||
* // ┌─────────┬─────┬─────┐
|
||||
* // │ (index) │ a │ b │
|
||||
* // ├─────────┼─────┼─────┤
|
||||
* // │ 0 │ 1 │ 'Y' │
|
||||
* // │ 1 │ 'Z' │ 2 │
|
||||
* // └─────────┴─────┴─────┘
|
||||
*
|
||||
* console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }], ['a']);
|
||||
* // ┌─────────┬─────┐
|
||||
* // │ (index) │ a │
|
||||
* // ├─────────┼─────┤
|
||||
* // │ 0 │ 1 │
|
||||
* // │ 1 │ 'Z' │
|
||||
* // └─────────┴─────┘
|
||||
* ```
|
||||
* @since v10.0.0
|
||||
* @param properties Alternate properties for constructing the table.
|
||||
*/
|
||||
table(tabularData: any, properties?: readonly string[]): void;
|
||||
/**
|
||||
* Starts a timer that can be used to compute the duration of an operation. Timers
|
||||
* are identified by a unique `label`. Use the same `label` when calling {@link timeEnd} to stop the timer and output the elapsed time in
|
||||
* suitable time units to `stdout`. For example, if the elapsed
|
||||
* time is 3869ms, `console.timeEnd()` displays "3.869s".
|
||||
* @since v0.1.104
|
||||
* @param [label='default']
|
||||
*/
|
||||
time(label?: string): void;
|
||||
/**
|
||||
* Stops a timer that was previously started by calling {@link time} and
|
||||
* prints the result to `stdout`:
|
||||
*
|
||||
* ```js
|
||||
* console.time('bunch-of-stuff');
|
||||
* // Do a bunch of stuff.
|
||||
* console.timeEnd('bunch-of-stuff');
|
||||
* // Prints: bunch-of-stuff: 225.438ms
|
||||
* ```
|
||||
* @since v0.1.104
|
||||
* @param [label='default']
|
||||
*/
|
||||
timeEnd(label?: string): void;
|
||||
/**
|
||||
* For a timer that was previously started by calling {@link time}, prints
|
||||
* the elapsed time and other `data` arguments to `stdout`:
|
||||
*
|
||||
* ```js
|
||||
* console.time('process');
|
||||
* const value = expensiveProcess1(); // Returns 42
|
||||
* console.timeLog('process', value);
|
||||
* // Prints "process: 365.227ms 42".
|
||||
* doExpensiveProcess2(value);
|
||||
* console.timeEnd('process');
|
||||
* ```
|
||||
* @since v10.7.0
|
||||
* @param [label='default']
|
||||
*/
|
||||
timeLog(label?: string, ...data: any[]): void;
|
||||
/**
|
||||
* Prints to `stderr` the string `'Trace: '`, followed by the [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args)
|
||||
* formatted message and stack trace to the current position in the code.
|
||||
*
|
||||
* ```js
|
||||
* console.trace('Show me');
|
||||
* // Prints: (stack trace will vary based on where trace is called)
|
||||
* // Trace: Show me
|
||||
* // at repl:2:9
|
||||
* // at REPLServer.defaultEval (repl.js:248:27)
|
||||
* // at bound (domain.js:287:14)
|
||||
* // at REPLServer.runBound [as eval] (domain.js:300:12)
|
||||
* // at REPLServer.<anonymous> (repl.js:412:12)
|
||||
* // at emitOne (events.js:82:20)
|
||||
* // at REPLServer.emit (events.js:169:7)
|
||||
* // at REPLServer.Interface._onLine (readline.js:210:10)
|
||||
* // at REPLServer.Interface._line (readline.js:549:8)
|
||||
* // at REPLServer.Interface._ttyWrite (readline.js:826:14)
|
||||
* ```
|
||||
* @since v0.1.104
|
||||
*/
|
||||
trace(message?: any, ...optionalParams: any[]): void;
|
||||
/**
|
||||
* The `console.warn()` function is an alias for {@link error}.
|
||||
* @since v0.1.100
|
||||
*/
|
||||
warn(message?: any, ...optionalParams: any[]): void;
|
||||
// --- Inspector mode only ---
|
||||
/**
|
||||
* This method does not display anything unless used in the inspector. The `console.profile()`
|
||||
* method starts a JavaScript CPU profile with an optional label until {@link profileEnd}
|
||||
* is called. The profile is then added to the Profile panel of the inspector.
|
||||
*
|
||||
* ```js
|
||||
* console.profile('MyLabel');
|
||||
* // Some code
|
||||
* console.profileEnd('MyLabel');
|
||||
* // Adds the profile 'MyLabel' to the Profiles panel of the inspector.
|
||||
* ```
|
||||
* @since v8.0.0
|
||||
*/
|
||||
profile(label?: string): void;
|
||||
/**
|
||||
* This method does not display anything unless used in the inspector. Stops the current
|
||||
* JavaScript CPU profiling session if one has been started and prints the report to the
|
||||
* Profiles panel of the inspector. See {@link profile} for an example.
|
||||
*
|
||||
* If this method is called without a label, the most recently started profile is stopped.
|
||||
* @since v8.0.0
|
||||
*/
|
||||
profileEnd(label?: string): void;
|
||||
/**
|
||||
* This method does not display anything unless used in the inspector. The `console.timeStamp()`
|
||||
* method adds an event with the label `'label'` to the Timeline panel of the inspector.
|
||||
* @since v8.0.0
|
||||
*/
|
||||
timeStamp(label?: string): void;
|
||||
}
|
||||
/**
|
||||
* The `console` module provides a simple debugging console that is similar to the
|
||||
* JavaScript console mechanism provided by web browsers.
|
||||
*
|
||||
* The module exports two specific components:
|
||||
*
|
||||
* * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
|
||||
* * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstdout) and
|
||||
* [`process.stderr`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
|
||||
*
|
||||
* _**Warning**_: The global console object's methods are neither consistently
|
||||
* synchronous like the browser APIs they resemble, nor are they consistently
|
||||
* asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v24.x/api/process.html#a-note-on-process-io) for
|
||||
* more information.
|
||||
*
|
||||
* Example using the global `console`:
|
||||
*
|
||||
* ```js
|
||||
* console.log('hello world');
|
||||
* // Prints: hello world, to stdout
|
||||
* console.log('hello %s', 'world');
|
||||
* // Prints: hello world, to stdout
|
||||
* console.error(new Error('Whoops, something bad happened'));
|
||||
* // Prints error message and stack trace to stderr:
|
||||
* // Error: Whoops, something bad happened
|
||||
* // at [eval]:5:15
|
||||
* // at Script.runInThisContext (node:vm:132:18)
|
||||
* // at Object.runInThisContext (node:vm:309:38)
|
||||
* // at node:internal/process/execution:77:19
|
||||
* // at [eval]-wrapper:6:22
|
||||
* // at evalScript (node:internal/process/execution:76:60)
|
||||
* // at node:internal/main/eval_string:23:3
|
||||
*
|
||||
* const name = 'Will Robinson';
|
||||
* console.warn(`Danger ${name}! Danger!`);
|
||||
* // Prints: Danger Will Robinson! Danger!, to stderr
|
||||
* ```
|
||||
*
|
||||
* Example using the `Console` class:
|
||||
*
|
||||
* ```js
|
||||
* const out = getStreamSomehow();
|
||||
* const err = getStreamSomehow();
|
||||
* const myConsole = new console.Console(out, err);
|
||||
*
|
||||
* myConsole.log('hello world');
|
||||
* // Prints: hello world, to out
|
||||
* myConsole.log('hello %s', 'world');
|
||||
* // Prints: hello world, to out
|
||||
* myConsole.error(new Error('Whoops, something bad happened'));
|
||||
* // Prints: [Error: Whoops, something bad happened], to err
|
||||
*
|
||||
* const name = 'Will Robinson';
|
||||
* myConsole.warn(`Danger ${name}! Danger!`);
|
||||
* // Prints: Danger Will Robinson! Danger!, to err
|
||||
* ```
|
||||
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/console.js)
|
||||
*/
|
||||
namespace console {
|
||||
interface ConsoleConstructorOptions {
|
||||
stdout: NodeJS.WritableStream;
|
||||
stderr?: NodeJS.WritableStream | undefined;
|
||||
/**
|
||||
* Ignore errors when writing to the underlying streams.
|
||||
* @default true
|
||||
*/
|
||||
ignoreErrors?: boolean | undefined;
|
||||
/**
|
||||
* Set color support for this `Console` instance. Setting to true enables coloring while inspecting
|
||||
* values. Setting to `false` disables coloring while inspecting values. Setting to `'auto'` makes color
|
||||
* support depend on the value of the `isTTY` property and the value returned by `getColorDepth()` on the
|
||||
* respective stream. This option can not be used, if `inspectOptions.colors` is set as well.
|
||||
* @default auto
|
||||
*/
|
||||
colorMode?: boolean | "auto" | undefined;
|
||||
/**
|
||||
* Specifies options that are passed along to
|
||||
* `util.inspect()`. Can be an options object or, if different options
|
||||
* for stdout and stderr are desired, a `Map` from stream objects to options.
|
||||
*/
|
||||
inspectOptions?: InspectOptions | ReadonlyMap<NodeJS.WritableStream, InspectOptions> | undefined;
|
||||
/**
|
||||
* Set group indentation.
|
||||
* @default 2
|
||||
*/
|
||||
groupIndentation?: number | undefined;
|
||||
}
|
||||
interface ConsoleConstructor {
|
||||
prototype: Console;
|
||||
new(stdout: NodeJS.WritableStream, stderr?: NodeJS.WritableStream, ignoreErrors?: boolean): Console;
|
||||
new(options: ConsoleConstructorOptions): Console;
|
||||
}
|
||||
}
|
||||
var console: Console;
|
||||
}
|
||||
export = globalThis.console;
|
||||
}
|
||||
21
node_modules/sitemap/node_modules/@types/node/constants.d.ts
generated
vendored
Normal file
21
node_modules/sitemap/node_modules/@types/node/constants.d.ts
generated
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
/**
|
||||
* @deprecated The `node:constants` module is deprecated. When requiring access to constants
|
||||
* relevant to specific Node.js builtin modules, developers should instead refer
|
||||
* to the `constants` property exposed by the relevant module. For instance,
|
||||
* `require('node:fs').constants` and `require('node:os').constants`.
|
||||
*/
|
||||
declare module "constants" {
|
||||
const constants:
|
||||
& typeof import("node:os").constants.dlopen
|
||||
& typeof import("node:os").constants.errno
|
||||
& typeof import("node:os").constants.priority
|
||||
& typeof import("node:os").constants.signals
|
||||
& typeof import("node:fs").constants
|
||||
& typeof import("node:crypto").constants;
|
||||
export = constants;
|
||||
}
|
||||
|
||||
declare module "node:constants" {
|
||||
import constants = require("constants");
|
||||
export = constants;
|
||||
}
|
||||
5417
node_modules/sitemap/node_modules/@types/node/crypto.d.ts
generated
vendored
Normal file
5417
node_modules/sitemap/node_modules/@types/node/crypto.d.ts
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
600
node_modules/sitemap/node_modules/@types/node/dgram.d.ts
generated
vendored
Normal file
600
node_modules/sitemap/node_modules/@types/node/dgram.d.ts
generated
vendored
Normal file
@@ -0,0 +1,600 @@
|
||||
/**
|
||||
* The `node:dgram` module provides an implementation of UDP datagram sockets.
|
||||
*
|
||||
* ```js
|
||||
* import dgram from 'node:dgram';
|
||||
*
|
||||
* const server = dgram.createSocket('udp4');
|
||||
*
|
||||
* server.on('error', (err) => {
|
||||
* console.error(`server error:\n${err.stack}`);
|
||||
* server.close();
|
||||
* });
|
||||
*
|
||||
* server.on('message', (msg, rinfo) => {
|
||||
* console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);
|
||||
* });
|
||||
*
|
||||
* server.on('listening', () => {
|
||||
* const address = server.address();
|
||||
* console.log(`server listening ${address.address}:${address.port}`);
|
||||
* });
|
||||
*
|
||||
* server.bind(41234);
|
||||
* // Prints: server listening 0.0.0.0:41234
|
||||
* ```
|
||||
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/dgram.js)
|
||||
*/
|
||||
declare module "dgram" {
|
||||
import { NonSharedBuffer } from "node:buffer";
|
||||
import { AddressInfo, BlockList } from "node:net";
|
||||
import * as dns from "node:dns";
|
||||
import { Abortable, EventEmitter } from "node:events";
|
||||
interface RemoteInfo {
|
||||
address: string;
|
||||
family: "IPv4" | "IPv6";
|
||||
port: number;
|
||||
size: number;
|
||||
}
|
||||
interface BindOptions {
|
||||
port?: number | undefined;
|
||||
address?: string | undefined;
|
||||
exclusive?: boolean | undefined;
|
||||
fd?: number | undefined;
|
||||
}
|
||||
type SocketType = "udp4" | "udp6";
|
||||
interface SocketOptions extends Abortable {
|
||||
type: SocketType;
|
||||
reuseAddr?: boolean | undefined;
|
||||
reusePort?: boolean | undefined;
|
||||
/**
|
||||
* @default false
|
||||
*/
|
||||
ipv6Only?: boolean | undefined;
|
||||
recvBufferSize?: number | undefined;
|
||||
sendBufferSize?: number | undefined;
|
||||
lookup?:
|
||||
| ((
|
||||
hostname: string,
|
||||
options: dns.LookupOneOptions,
|
||||
callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void,
|
||||
) => void)
|
||||
| undefined;
|
||||
receiveBlockList?: BlockList | undefined;
|
||||
sendBlockList?: BlockList | undefined;
|
||||
}
|
||||
/**
|
||||
* Creates a `dgram.Socket` object. Once the socket is created, calling `socket.bind()` will instruct the socket to begin listening for datagram
|
||||
* messages. When `address` and `port` are not passed to `socket.bind()` the
|
||||
* method will bind the socket to the "all interfaces" address on a random port
|
||||
* (it does the right thing for both `udp4` and `udp6` sockets). The bound address
|
||||
* and port can be retrieved using `socket.address().address` and `socket.address().port`.
|
||||
*
|
||||
* If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.close()` on the socket:
|
||||
*
|
||||
* ```js
|
||||
* const controller = new AbortController();
|
||||
* const { signal } = controller;
|
||||
* const server = dgram.createSocket({ type: 'udp4', signal });
|
||||
* server.on('message', (msg, rinfo) => {
|
||||
* console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);
|
||||
* });
|
||||
* // Later, when you want to close the server.
|
||||
* controller.abort();
|
||||
* ```
|
||||
* @since v0.11.13
|
||||
* @param options Available options are:
|
||||
* @param callback Attached as a listener for `'message'` events. Optional.
|
||||
*/
|
||||
function createSocket(type: SocketType, callback?: (msg: NonSharedBuffer, rinfo: RemoteInfo) => void): Socket;
|
||||
function createSocket(options: SocketOptions, callback?: (msg: NonSharedBuffer, rinfo: RemoteInfo) => void): Socket;
|
||||
/**
|
||||
* Encapsulates the datagram functionality.
|
||||
*
|
||||
* New instances of `dgram.Socket` are created using {@link createSocket}.
|
||||
* The `new` keyword is not to be used to create `dgram.Socket` instances.
|
||||
* @since v0.1.99
|
||||
*/
|
||||
class Socket extends EventEmitter {
|
||||
/**
|
||||
* Tells the kernel to join a multicast group at the given `multicastAddress` and `multicastInterface` using the `IP_ADD_MEMBERSHIP` socket option. If the `multicastInterface` argument is not
|
||||
* specified, the operating system will choose
|
||||
* one interface and will add membership to it. To add membership to every
|
||||
* available interface, call `addMembership` multiple times, once per interface.
|
||||
*
|
||||
* When called on an unbound socket, this method will implicitly bind to a random
|
||||
* port, listening on all interfaces.
|
||||
*
|
||||
* When sharing a UDP socket across multiple `cluster` workers, the`socket.addMembership()` function must be called only once or an`EADDRINUSE` error will occur:
|
||||
*
|
||||
* ```js
|
||||
* import cluster from 'node:cluster';
|
||||
* import dgram from 'node:dgram';
|
||||
*
|
||||
* if (cluster.isPrimary) {
|
||||
* cluster.fork(); // Works ok.
|
||||
* cluster.fork(); // Fails with EADDRINUSE.
|
||||
* } else {
|
||||
* const s = dgram.createSocket('udp4');
|
||||
* s.bind(1234, () => {
|
||||
* s.addMembership('224.0.0.114');
|
||||
* });
|
||||
* }
|
||||
* ```
|
||||
* @since v0.6.9
|
||||
*/
|
||||
addMembership(multicastAddress: string, multicastInterface?: string): void;
|
||||
/**
|
||||
* Returns an object containing the address information for a socket.
|
||||
* For UDP sockets, this object will contain `address`, `family`, and `port` properties.
|
||||
*
|
||||
* This method throws `EBADF` if called on an unbound socket.
|
||||
* @since v0.1.99
|
||||
*/
|
||||
address(): AddressInfo;
|
||||
/**
|
||||
* For UDP sockets, causes the `dgram.Socket` to listen for datagram
|
||||
* messages on a named `port` and optional `address`. If `port` is not
|
||||
* specified or is `0`, the operating system will attempt to bind to a
|
||||
* random port. If `address` is not specified, the operating system will
|
||||
* attempt to listen on all addresses. Once binding is complete, a `'listening'` event is emitted and the optional `callback` function is
|
||||
* called.
|
||||
*
|
||||
* Specifying both a `'listening'` event listener and passing a `callback` to the `socket.bind()` method is not harmful but not very
|
||||
* useful.
|
||||
*
|
||||
* A bound datagram socket keeps the Node.js process running to receive
|
||||
* datagram messages.
|
||||
*
|
||||
* If binding fails, an `'error'` event is generated. In rare case (e.g.
|
||||
* attempting to bind with a closed socket), an `Error` may be thrown.
|
||||
*
|
||||
* Example of a UDP server listening on port 41234:
|
||||
*
|
||||
* ```js
|
||||
* import dgram from 'node:dgram';
|
||||
*
|
||||
* const server = dgram.createSocket('udp4');
|
||||
*
|
||||
* server.on('error', (err) => {
|
||||
* console.error(`server error:\n${err.stack}`);
|
||||
* server.close();
|
||||
* });
|
||||
*
|
||||
* server.on('message', (msg, rinfo) => {
|
||||
* console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);
|
||||
* });
|
||||
*
|
||||
* server.on('listening', () => {
|
||||
* const address = server.address();
|
||||
* console.log(`server listening ${address.address}:${address.port}`);
|
||||
* });
|
||||
*
|
||||
* server.bind(41234);
|
||||
* // Prints: server listening 0.0.0.0:41234
|
||||
* ```
|
||||
* @since v0.1.99
|
||||
* @param callback with no parameters. Called when binding is complete.
|
||||
*/
|
||||
bind(port?: number, address?: string, callback?: () => void): this;
|
||||
bind(port?: number, callback?: () => void): this;
|
||||
bind(callback?: () => void): this;
|
||||
bind(options: BindOptions, callback?: () => void): this;
|
||||
/**
|
||||
* Close the underlying socket and stop listening for data on it. If a callback is
|
||||
* provided, it is added as a listener for the `'close'` event.
|
||||
* @since v0.1.99
|
||||
* @param callback Called when the socket has been closed.
|
||||
*/
|
||||
close(callback?: () => void): this;
|
||||
/**
|
||||
* Associates the `dgram.Socket` to a remote address and port. Every
|
||||
* message sent by this handle is automatically sent to that destination. Also,
|
||||
* the socket will only receive messages from that remote peer.
|
||||
* Trying to call `connect()` on an already connected socket will result
|
||||
* in an `ERR_SOCKET_DGRAM_IS_CONNECTED` exception. If `address` is not
|
||||
* provided, `'127.0.0.1'` (for `udp4` sockets) or `'::1'` (for `udp6` sockets)
|
||||
* will be used by default. Once the connection is complete, a `'connect'` event
|
||||
* is emitted and the optional `callback` function is called. In case of failure,
|
||||
* the `callback` is called or, failing this, an `'error'` event is emitted.
|
||||
* @since v12.0.0
|
||||
* @param callback Called when the connection is completed or on error.
|
||||
*/
|
||||
connect(port: number, address?: string, callback?: () => void): void;
|
||||
connect(port: number, callback: () => void): void;
|
||||
/**
|
||||
* A synchronous function that disassociates a connected `dgram.Socket` from
|
||||
* its remote address. Trying to call `disconnect()` on an unbound or already
|
||||
* disconnected socket will result in an `ERR_SOCKET_DGRAM_NOT_CONNECTED` exception.
|
||||
* @since v12.0.0
|
||||
*/
|
||||
disconnect(): void;
|
||||
/**
|
||||
* Instructs the kernel to leave a multicast group at `multicastAddress` using the `IP_DROP_MEMBERSHIP` socket option. This method is automatically called by the
|
||||
* kernel when the socket is closed or the process terminates, so most apps will
|
||||
* never have reason to call this.
|
||||
*
|
||||
* If `multicastInterface` is not specified, the operating system will attempt to
|
||||
* drop membership on all valid interfaces.
|
||||
* @since v0.6.9
|
||||
*/
|
||||
dropMembership(multicastAddress: string, multicastInterface?: string): void;
|
||||
/**
|
||||
* This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket.
|
||||
* @since v8.7.0
|
||||
* @return the `SO_RCVBUF` socket receive buffer size in bytes.
|
||||
*/
|
||||
getRecvBufferSize(): number;
|
||||
/**
|
||||
* This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket.
|
||||
* @since v8.7.0
|
||||
* @return the `SO_SNDBUF` socket send buffer size in bytes.
|
||||
*/
|
||||
getSendBufferSize(): number;
|
||||
/**
|
||||
* @since v18.8.0, v16.19.0
|
||||
* @return Number of bytes queued for sending.
|
||||
*/
|
||||
getSendQueueSize(): number;
|
||||
/**
|
||||
* @since v18.8.0, v16.19.0
|
||||
* @return Number of send requests currently in the queue awaiting to be processed.
|
||||
*/
|
||||
getSendQueueCount(): number;
|
||||
/**
|
||||
* By default, binding a socket will cause it to block the Node.js process from
|
||||
* exiting as long as the socket is open. The `socket.unref()` method can be used
|
||||
* to exclude the socket from the reference counting that keeps the Node.js
|
||||
* process active. The `socket.ref()` method adds the socket back to the reference
|
||||
* counting and restores the default behavior.
|
||||
*
|
||||
* Calling `socket.ref()` multiples times will have no additional effect.
|
||||
*
|
||||
* The `socket.ref()` method returns a reference to the socket so calls can be
|
||||
* chained.
|
||||
* @since v0.9.1
|
||||
*/
|
||||
ref(): this;
|
||||
/**
|
||||
* Returns an object containing the `address`, `family`, and `port` of the remote
|
||||
* endpoint. This method throws an `ERR_SOCKET_DGRAM_NOT_CONNECTED` exception
|
||||
* if the socket is not connected.
|
||||
* @since v12.0.0
|
||||
*/
|
||||
remoteAddress(): AddressInfo;
|
||||
/**
|
||||
* Broadcasts a datagram on the socket.
|
||||
* For connectionless sockets, the destination `port` and `address` must be
|
||||
* specified. Connected sockets, on the other hand, will use their associated
|
||||
* remote endpoint, so the `port` and `address` arguments must not be set.
|
||||
*
|
||||
* The `msg` argument contains the message to be sent.
|
||||
* Depending on its type, different behavior can apply. If `msg` is a `Buffer`,
|
||||
* any `TypedArray` or a `DataView`,
|
||||
* the `offset` and `length` specify the offset within the `Buffer` where the
|
||||
* message begins and the number of bytes in the message, respectively.
|
||||
* If `msg` is a `String`, then it is automatically converted to a `Buffer` with `'utf8'` encoding. With messages that
|
||||
* contain multi-byte characters, `offset` and `length` will be calculated with
|
||||
* respect to `byte length` and not the character position.
|
||||
* If `msg` is an array, `offset` and `length` must not be specified.
|
||||
*
|
||||
* The `address` argument is a string. If the value of `address` is a host name,
|
||||
* DNS will be used to resolve the address of the host. If `address` is not
|
||||
* provided or otherwise nullish, `'127.0.0.1'` (for `udp4` sockets) or `'::1'` (for `udp6` sockets) will be used by default.
|
||||
*
|
||||
* If the socket has not been previously bound with a call to `bind`, the socket
|
||||
* is assigned a random port number and is bound to the "all interfaces" address
|
||||
* (`'0.0.0.0'` for `udp4` sockets, `'::0'` for `udp6` sockets.)
|
||||
*
|
||||
* An optional `callback` function may be specified to as a way of reporting
|
||||
* DNS errors or for determining when it is safe to reuse the `buf` object.
|
||||
* DNS lookups delay the time to send for at least one tick of the
|
||||
* Node.js event loop.
|
||||
*
|
||||
* The only way to know for sure that the datagram has been sent is by using a `callback`. If an error occurs and a `callback` is given, the error will be
|
||||
* passed as the first argument to the `callback`. If a `callback` is not given,
|
||||
* the error is emitted as an `'error'` event on the `socket` object.
|
||||
*
|
||||
* Offset and length are optional but both _must_ be set if either are used.
|
||||
* They are supported only when the first argument is a `Buffer`, a `TypedArray`,
|
||||
* or a `DataView`.
|
||||
*
|
||||
* This method throws `ERR_SOCKET_BAD_PORT` if called on an unbound socket.
|
||||
*
|
||||
* Example of sending a UDP packet to a port on `localhost`;
|
||||
*
|
||||
* ```js
|
||||
* import dgram from 'node:dgram';
|
||||
* import { Buffer } from 'node:buffer';
|
||||
*
|
||||
* const message = Buffer.from('Some bytes');
|
||||
* const client = dgram.createSocket('udp4');
|
||||
* client.send(message, 41234, 'localhost', (err) => {
|
||||
* client.close();
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* Example of sending a UDP packet composed of multiple buffers to a port on`127.0.0.1`;
|
||||
*
|
||||
* ```js
|
||||
* import dgram from 'node:dgram';
|
||||
* import { Buffer } from 'node:buffer';
|
||||
*
|
||||
* const buf1 = Buffer.from('Some ');
|
||||
* const buf2 = Buffer.from('bytes');
|
||||
* const client = dgram.createSocket('udp4');
|
||||
* client.send([buf1, buf2], 41234, (err) => {
|
||||
* client.close();
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* Sending multiple buffers might be faster or slower depending on the
|
||||
* application and operating system. Run benchmarks to
|
||||
* determine the optimal strategy on a case-by-case basis. Generally speaking,
|
||||
* however, sending multiple buffers is faster.
|
||||
*
|
||||
* Example of sending a UDP packet using a socket connected to a port on `localhost`:
|
||||
*
|
||||
* ```js
|
||||
* import dgram from 'node:dgram';
|
||||
* import { Buffer } from 'node:buffer';
|
||||
*
|
||||
* const message = Buffer.from('Some bytes');
|
||||
* const client = dgram.createSocket('udp4');
|
||||
* client.connect(41234, 'localhost', (err) => {
|
||||
* client.send(message, (err) => {
|
||||
* client.close();
|
||||
* });
|
||||
* });
|
||||
* ```
|
||||
* @since v0.1.99
|
||||
* @param msg Message to be sent.
|
||||
* @param offset Offset in the buffer where the message starts.
|
||||
* @param length Number of bytes in the message.
|
||||
* @param port Destination port.
|
||||
* @param address Destination host name or IP address.
|
||||
* @param callback Called when the message has been sent.
|
||||
*/
|
||||
send(
|
||||
msg: string | NodeJS.ArrayBufferView | readonly any[],
|
||||
port?: number,
|
||||
address?: string,
|
||||
callback?: (error: Error | null, bytes: number) => void,
|
||||
): void;
|
||||
send(
|
||||
msg: string | NodeJS.ArrayBufferView | readonly any[],
|
||||
port?: number,
|
||||
callback?: (error: Error | null, bytes: number) => void,
|
||||
): void;
|
||||
send(
|
||||
msg: string | NodeJS.ArrayBufferView | readonly any[],
|
||||
callback?: (error: Error | null, bytes: number) => void,
|
||||
): void;
|
||||
send(
|
||||
msg: string | NodeJS.ArrayBufferView,
|
||||
offset: number,
|
||||
length: number,
|
||||
port?: number,
|
||||
address?: string,
|
||||
callback?: (error: Error | null, bytes: number) => void,
|
||||
): void;
|
||||
send(
|
||||
msg: string | NodeJS.ArrayBufferView,
|
||||
offset: number,
|
||||
length: number,
|
||||
port?: number,
|
||||
callback?: (error: Error | null, bytes: number) => void,
|
||||
): void;
|
||||
send(
|
||||
msg: string | NodeJS.ArrayBufferView,
|
||||
offset: number,
|
||||
length: number,
|
||||
callback?: (error: Error | null, bytes: number) => void,
|
||||
): void;
|
||||
/**
|
||||
* Sets or clears the `SO_BROADCAST` socket option. When set to `true`, UDP
|
||||
* packets may be sent to a local interface's broadcast address.
|
||||
*
|
||||
* This method throws `EBADF` if called on an unbound socket.
|
||||
* @since v0.6.9
|
||||
*/
|
||||
setBroadcast(flag: boolean): void;
|
||||
/**
|
||||
* _All references to scope in this section are referring to [IPv6 Zone Indices](https://en.wikipedia.org/wiki/IPv6_address#Scoped_literal_IPv6_addresses), which are defined by [RFC
|
||||
* 4007](https://tools.ietf.org/html/rfc4007). In string form, an IP_
|
||||
* _with a scope index is written as `'IP%scope'` where scope is an interface name_
|
||||
* _or interface number._
|
||||
*
|
||||
* Sets the default outgoing multicast interface of the socket to a chosen
|
||||
* interface or back to system interface selection. The `multicastInterface` must
|
||||
* be a valid string representation of an IP from the socket's family.
|
||||
*
|
||||
* For IPv4 sockets, this should be the IP configured for the desired physical
|
||||
* interface. All packets sent to multicast on the socket will be sent on the
|
||||
* interface determined by the most recent successful use of this call.
|
||||
*
|
||||
* For IPv6 sockets, `multicastInterface` should include a scope to indicate the
|
||||
* interface as in the examples that follow. In IPv6, individual `send` calls can
|
||||
* also use explicit scope in addresses, so only packets sent to a multicast
|
||||
* address without specifying an explicit scope are affected by the most recent
|
||||
* successful use of this call.
|
||||
*
|
||||
* This method throws `EBADF` if called on an unbound socket.
|
||||
*
|
||||
* #### Example: IPv6 outgoing multicast interface
|
||||
*
|
||||
* On most systems, where scope format uses the interface name:
|
||||
*
|
||||
* ```js
|
||||
* const socket = dgram.createSocket('udp6');
|
||||
*
|
||||
* socket.bind(1234, () => {
|
||||
* socket.setMulticastInterface('::%eth1');
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* On Windows, where scope format uses an interface number:
|
||||
*
|
||||
* ```js
|
||||
* const socket = dgram.createSocket('udp6');
|
||||
*
|
||||
* socket.bind(1234, () => {
|
||||
* socket.setMulticastInterface('::%2');
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* #### Example: IPv4 outgoing multicast interface
|
||||
*
|
||||
* All systems use an IP of the host on the desired physical interface:
|
||||
*
|
||||
* ```js
|
||||
* const socket = dgram.createSocket('udp4');
|
||||
*
|
||||
* socket.bind(1234, () => {
|
||||
* socket.setMulticastInterface('10.0.0.2');
|
||||
* });
|
||||
* ```
|
||||
* @since v8.6.0
|
||||
*/
|
||||
setMulticastInterface(multicastInterface: string): void;
|
||||
/**
|
||||
* Sets or clears the `IP_MULTICAST_LOOP` socket option. When set to `true`,
|
||||
* multicast packets will also be received on the local interface.
|
||||
*
|
||||
* This method throws `EBADF` if called on an unbound socket.
|
||||
* @since v0.3.8
|
||||
*/
|
||||
setMulticastLoopback(flag: boolean): boolean;
|
||||
/**
|
||||
* Sets the `IP_MULTICAST_TTL` socket option. While TTL generally stands for
|
||||
* "Time to Live", in this context it specifies the number of IP hops that a
|
||||
* packet is allowed to travel through, specifically for multicast traffic. Each
|
||||
* router or gateway that forwards a packet decrements the TTL. If the TTL is
|
||||
* decremented to 0 by a router, it will not be forwarded.
|
||||
*
|
||||
* The `ttl` argument may be between 0 and 255\. The default on most systems is `1`.
|
||||
*
|
||||
* This method throws `EBADF` if called on an unbound socket.
|
||||
* @since v0.3.8
|
||||
*/
|
||||
setMulticastTTL(ttl: number): number;
|
||||
/**
|
||||
* Sets the `SO_RCVBUF` socket option. Sets the maximum socket receive buffer
|
||||
* in bytes.
|
||||
*
|
||||
* This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket.
|
||||
* @since v8.7.0
|
||||
*/
|
||||
setRecvBufferSize(size: number): void;
|
||||
/**
|
||||
* Sets the `SO_SNDBUF` socket option. Sets the maximum socket send buffer
|
||||
* in bytes.
|
||||
*
|
||||
* This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket.
|
||||
* @since v8.7.0
|
||||
*/
|
||||
setSendBufferSize(size: number): void;
|
||||
/**
|
||||
* Sets the `IP_TTL` socket option. While TTL generally stands for "Time to Live",
|
||||
* in this context it specifies the number of IP hops that a packet is allowed to
|
||||
* travel through. Each router or gateway that forwards a packet decrements the
|
||||
* TTL. If the TTL is decremented to 0 by a router, it will not be forwarded.
|
||||
* Changing TTL values is typically done for network probes or when multicasting.
|
||||
*
|
||||
* The `ttl` argument may be between 1 and 255\. The default on most systems
|
||||
* is 64.
|
||||
*
|
||||
* This method throws `EBADF` if called on an unbound socket.
|
||||
* @since v0.1.101
|
||||
*/
|
||||
setTTL(ttl: number): number;
|
||||
/**
|
||||
* By default, binding a socket will cause it to block the Node.js process from
|
||||
* exiting as long as the socket is open. The `socket.unref()` method can be used
|
||||
* to exclude the socket from the reference counting that keeps the Node.js
|
||||
* process active, allowing the process to exit even if the socket is still
|
||||
* listening.
|
||||
*
|
||||
* Calling `socket.unref()` multiple times will have no additional effect.
|
||||
*
|
||||
* The `socket.unref()` method returns a reference to the socket so calls can be
|
||||
* chained.
|
||||
* @since v0.9.1
|
||||
*/
|
||||
unref(): this;
|
||||
/**
|
||||
* Tells the kernel to join a source-specific multicast channel at the given `sourceAddress` and `groupAddress`, using the `multicastInterface` with the `IP_ADD_SOURCE_MEMBERSHIP` socket
|
||||
* option. If the `multicastInterface` argument
|
||||
* is not specified, the operating system will choose one interface and will add
|
||||
* membership to it. To add membership to every available interface, call `socket.addSourceSpecificMembership()` multiple times, once per interface.
|
||||
*
|
||||
* When called on an unbound socket, this method will implicitly bind to a random
|
||||
* port, listening on all interfaces.
|
||||
* @since v13.1.0, v12.16.0
|
||||
*/
|
||||
addSourceSpecificMembership(sourceAddress: string, groupAddress: string, multicastInterface?: string): void;
|
||||
/**
|
||||
* Instructs the kernel to leave a source-specific multicast channel at the given `sourceAddress` and `groupAddress` using the `IP_DROP_SOURCE_MEMBERSHIP` socket option. This method is
|
||||
* automatically called by the kernel when the
|
||||
* socket is closed or the process terminates, so most apps will never have
|
||||
* reason to call this.
|
||||
*
|
||||
* If `multicastInterface` is not specified, the operating system will attempt to
|
||||
* drop membership on all valid interfaces.
|
||||
* @since v13.1.0, v12.16.0
|
||||
*/
|
||||
dropSourceSpecificMembership(sourceAddress: string, groupAddress: string, multicastInterface?: string): void;
|
||||
/**
|
||||
* events.EventEmitter
|
||||
* 1. close
|
||||
* 2. connect
|
||||
* 3. error
|
||||
* 4. listening
|
||||
* 5. message
|
||||
*/
|
||||
addListener(event: string, listener: (...args: any[]) => void): this;
|
||||
addListener(event: "close", listener: () => void): this;
|
||||
addListener(event: "connect", listener: () => void): this;
|
||||
addListener(event: "error", listener: (err: Error) => void): this;
|
||||
addListener(event: "listening", listener: () => void): this;
|
||||
addListener(event: "message", listener: (msg: NonSharedBuffer, rinfo: RemoteInfo) => void): this;
|
||||
emit(event: string | symbol, ...args: any[]): boolean;
|
||||
emit(event: "close"): boolean;
|
||||
emit(event: "connect"): boolean;
|
||||
emit(event: "error", err: Error): boolean;
|
||||
emit(event: "listening"): boolean;
|
||||
emit(event: "message", msg: NonSharedBuffer, rinfo: RemoteInfo): boolean;
|
||||
on(event: string, listener: (...args: any[]) => void): this;
|
||||
on(event: "close", listener: () => void): this;
|
||||
on(event: "connect", listener: () => void): this;
|
||||
on(event: "error", listener: (err: Error) => void): this;
|
||||
on(event: "listening", listener: () => void): this;
|
||||
on(event: "message", listener: (msg: NonSharedBuffer, rinfo: RemoteInfo) => void): this;
|
||||
once(event: string, listener: (...args: any[]) => void): this;
|
||||
once(event: "close", listener: () => void): this;
|
||||
once(event: "connect", listener: () => void): this;
|
||||
once(event: "error", listener: (err: Error) => void): this;
|
||||
once(event: "listening", listener: () => void): this;
|
||||
once(event: "message", listener: (msg: NonSharedBuffer, rinfo: RemoteInfo) => void): this;
|
||||
prependListener(event: string, listener: (...args: any[]) => void): this;
|
||||
prependListener(event: "close", listener: () => void): this;
|
||||
prependListener(event: "connect", listener: () => void): this;
|
||||
prependListener(event: "error", listener: (err: Error) => void): this;
|
||||
prependListener(event: "listening", listener: () => void): this;
|
||||
prependListener(event: "message", listener: (msg: NonSharedBuffer, rinfo: RemoteInfo) => void): this;
|
||||
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
|
||||
prependOnceListener(event: "close", listener: () => void): this;
|
||||
prependOnceListener(event: "connect", listener: () => void): this;
|
||||
prependOnceListener(event: "error", listener: (err: Error) => void): this;
|
||||
prependOnceListener(event: "listening", listener: () => void): this;
|
||||
prependOnceListener(event: "message", listener: (msg: NonSharedBuffer, rinfo: RemoteInfo) => void): this;
|
||||
/**
|
||||
* Calls `socket.close()` and returns a promise that fulfills when the socket has closed.
|
||||
* @since v20.5.0
|
||||
*/
|
||||
[Symbol.asyncDispose](): Promise<void>;
|
||||
}
|
||||
}
|
||||
declare module "node:dgram" {
|
||||
export * from "dgram";
|
||||
}
|
||||
576
node_modules/sitemap/node_modules/@types/node/diagnostics_channel.d.ts
generated
vendored
Normal file
576
node_modules/sitemap/node_modules/@types/node/diagnostics_channel.d.ts
generated
vendored
Normal file
@@ -0,0 +1,576 @@
|
||||
/**
|
||||
* The `node:diagnostics_channel` module provides an API to create named channels
|
||||
* to report arbitrary message data for diagnostics purposes.
|
||||
*
|
||||
* It can be accessed using:
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
* ```
|
||||
*
|
||||
* It is intended that a module writer wanting to report diagnostics messages
|
||||
* will create one or many top-level channels to report messages through.
|
||||
* Channels may also be acquired at runtime but it is not encouraged
|
||||
* due to the additional overhead of doing so. Channels may be exported for
|
||||
* convenience, but as long as the name is known it can be acquired anywhere.
|
||||
*
|
||||
* If you intend for your module to produce diagnostics data for others to
|
||||
* consume it is recommended that you include documentation of what named
|
||||
* channels are used along with the shape of the message data. Channel names
|
||||
* should generally include the module name to avoid collisions with data from
|
||||
* other modules.
|
||||
* @since v15.1.0, v14.17.0
|
||||
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/diagnostics_channel.js)
|
||||
*/
|
||||
declare module "diagnostics_channel" {
|
||||
import { AsyncLocalStorage } from "node:async_hooks";
|
||||
/**
|
||||
* Check if there are active subscribers to the named channel. This is helpful if
|
||||
* the message you want to send might be expensive to prepare.
|
||||
*
|
||||
* This API is optional but helpful when trying to publish messages from very
|
||||
* performance-sensitive code.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
*
|
||||
* if (diagnostics_channel.hasSubscribers('my-channel')) {
|
||||
* // There are subscribers, prepare and publish message
|
||||
* }
|
||||
* ```
|
||||
* @since v15.1.0, v14.17.0
|
||||
* @param name The channel name
|
||||
* @return If there are active subscribers
|
||||
*/
|
||||
function hasSubscribers(name: string | symbol): boolean;
|
||||
/**
|
||||
* This is the primary entry-point for anyone wanting to publish to a named
|
||||
* channel. It produces a channel object which is optimized to reduce overhead at
|
||||
* publish time as much as possible.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
*
|
||||
* const channel = diagnostics_channel.channel('my-channel');
|
||||
* ```
|
||||
* @since v15.1.0, v14.17.0
|
||||
* @param name The channel name
|
||||
* @return The named channel object
|
||||
*/
|
||||
function channel(name: string | symbol): Channel;
|
||||
type ChannelListener = (message: unknown, name: string | symbol) => void;
|
||||
/**
|
||||
* Register a message handler to subscribe to this channel. This message handler
|
||||
* will be run synchronously whenever a message is published to the channel. Any
|
||||
* errors thrown in the message handler will trigger an `'uncaughtException'`.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
*
|
||||
* diagnostics_channel.subscribe('my-channel', (message, name) => {
|
||||
* // Received data
|
||||
* });
|
||||
* ```
|
||||
* @since v18.7.0, v16.17.0
|
||||
* @param name The channel name
|
||||
* @param onMessage The handler to receive channel messages
|
||||
*/
|
||||
function subscribe(name: string | symbol, onMessage: ChannelListener): void;
|
||||
/**
|
||||
* Remove a message handler previously registered to this channel with {@link subscribe}.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
*
|
||||
* function onMessage(message, name) {
|
||||
* // Received data
|
||||
* }
|
||||
*
|
||||
* diagnostics_channel.subscribe('my-channel', onMessage);
|
||||
*
|
||||
* diagnostics_channel.unsubscribe('my-channel', onMessage);
|
||||
* ```
|
||||
* @since v18.7.0, v16.17.0
|
||||
* @param name The channel name
|
||||
* @param onMessage The previous subscribed handler to remove
|
||||
* @return `true` if the handler was found, `false` otherwise.
|
||||
*/
|
||||
function unsubscribe(name: string | symbol, onMessage: ChannelListener): boolean;
|
||||
/**
|
||||
* Creates a `TracingChannel` wrapper for the given `TracingChannel Channels`. If a name is given, the corresponding tracing
|
||||
* channels will be created in the form of `tracing:${name}:${eventType}` where `eventType` corresponds to the types of `TracingChannel Channels`.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
*
|
||||
* const channelsByName = diagnostics_channel.tracingChannel('my-channel');
|
||||
*
|
||||
* // or...
|
||||
*
|
||||
* const channelsByCollection = diagnostics_channel.tracingChannel({
|
||||
* start: diagnostics_channel.channel('tracing:my-channel:start'),
|
||||
* end: diagnostics_channel.channel('tracing:my-channel:end'),
|
||||
* asyncStart: diagnostics_channel.channel('tracing:my-channel:asyncStart'),
|
||||
* asyncEnd: diagnostics_channel.channel('tracing:my-channel:asyncEnd'),
|
||||
* error: diagnostics_channel.channel('tracing:my-channel:error'),
|
||||
* });
|
||||
* ```
|
||||
* @since v19.9.0
|
||||
* @experimental
|
||||
* @param nameOrChannels Channel name or object containing all the `TracingChannel Channels`
|
||||
* @return Collection of channels to trace with
|
||||
*/
|
||||
function tracingChannel<
|
||||
StoreType = unknown,
|
||||
ContextType extends object = StoreType extends object ? StoreType : object,
|
||||
>(
|
||||
nameOrChannels: string | TracingChannelCollection<StoreType, ContextType>,
|
||||
): TracingChannel<StoreType, ContextType>;
|
||||
/**
|
||||
* The class `Channel` represents an individual named channel within the data
|
||||
* pipeline. It is used to track subscribers and to publish messages when there
|
||||
* are subscribers present. It exists as a separate object to avoid channel
|
||||
* lookups at publish time, enabling very fast publish speeds and allowing
|
||||
* for heavy use while incurring very minimal cost. Channels are created with {@link channel}, constructing a channel directly
|
||||
* with `new Channel(name)` is not supported.
|
||||
* @since v15.1.0, v14.17.0
|
||||
*/
|
||||
class Channel<StoreType = unknown, ContextType = StoreType> {
|
||||
readonly name: string | symbol;
|
||||
/**
|
||||
* Check if there are active subscribers to this channel. This is helpful if
|
||||
* the message you want to send might be expensive to prepare.
|
||||
*
|
||||
* This API is optional but helpful when trying to publish messages from very
|
||||
* performance-sensitive code.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
*
|
||||
* const channel = diagnostics_channel.channel('my-channel');
|
||||
*
|
||||
* if (channel.hasSubscribers) {
|
||||
* // There are subscribers, prepare and publish message
|
||||
* }
|
||||
* ```
|
||||
* @since v15.1.0, v14.17.0
|
||||
*/
|
||||
readonly hasSubscribers: boolean;
|
||||
private constructor(name: string | symbol);
|
||||
/**
|
||||
* Publish a message to any subscribers to the channel. This will trigger
|
||||
* message handlers synchronously so they will execute within the same context.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
*
|
||||
* const channel = diagnostics_channel.channel('my-channel');
|
||||
*
|
||||
* channel.publish({
|
||||
* some: 'message',
|
||||
* });
|
||||
* ```
|
||||
* @since v15.1.0, v14.17.0
|
||||
* @param message The message to send to the channel subscribers
|
||||
*/
|
||||
publish(message: unknown): void;
|
||||
/**
|
||||
* Register a message handler to subscribe to this channel. This message handler
|
||||
* will be run synchronously whenever a message is published to the channel. Any
|
||||
* errors thrown in the message handler will trigger an `'uncaughtException'`.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
*
|
||||
* const channel = diagnostics_channel.channel('my-channel');
|
||||
*
|
||||
* channel.subscribe((message, name) => {
|
||||
* // Received data
|
||||
* });
|
||||
* ```
|
||||
* @since v15.1.0, v14.17.0
|
||||
* @param onMessage The handler to receive channel messages
|
||||
*/
|
||||
subscribe(onMessage: ChannelListener): void;
|
||||
/**
|
||||
* Remove a message handler previously registered to this channel with `channel.subscribe(onMessage)`.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
*
|
||||
* const channel = diagnostics_channel.channel('my-channel');
|
||||
*
|
||||
* function onMessage(message, name) {
|
||||
* // Received data
|
||||
* }
|
||||
*
|
||||
* channel.subscribe(onMessage);
|
||||
*
|
||||
* channel.unsubscribe(onMessage);
|
||||
* ```
|
||||
* @since v15.1.0, v14.17.0
|
||||
* @param onMessage The previous subscribed handler to remove
|
||||
* @return `true` if the handler was found, `false` otherwise.
|
||||
*/
|
||||
unsubscribe(onMessage: ChannelListener): void;
|
||||
/**
|
||||
* When `channel.runStores(context, ...)` is called, the given context data
|
||||
* will be applied to any store bound to the channel. If the store has already been
|
||||
* bound the previous `transform` function will be replaced with the new one.
|
||||
* The `transform` function may be omitted to set the given context data as the
|
||||
* context directly.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
* import { AsyncLocalStorage } from 'node:async_hooks';
|
||||
*
|
||||
* const store = new AsyncLocalStorage();
|
||||
*
|
||||
* const channel = diagnostics_channel.channel('my-channel');
|
||||
*
|
||||
* channel.bindStore(store, (data) => {
|
||||
* return { data };
|
||||
* });
|
||||
* ```
|
||||
* @since v19.9.0
|
||||
* @experimental
|
||||
* @param store The store to which to bind the context data
|
||||
* @param transform Transform context data before setting the store context
|
||||
*/
|
||||
bindStore(store: AsyncLocalStorage<StoreType>, transform?: (context: ContextType) => StoreType): void;
|
||||
/**
|
||||
* Remove a message handler previously registered to this channel with `channel.bindStore(store)`.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
* import { AsyncLocalStorage } from 'node:async_hooks';
|
||||
*
|
||||
* const store = new AsyncLocalStorage();
|
||||
*
|
||||
* const channel = diagnostics_channel.channel('my-channel');
|
||||
*
|
||||
* channel.bindStore(store);
|
||||
* channel.unbindStore(store);
|
||||
* ```
|
||||
* @since v19.9.0
|
||||
* @experimental
|
||||
* @param store The store to unbind from the channel.
|
||||
* @return `true` if the store was found, `false` otherwise.
|
||||
*/
|
||||
unbindStore(store: AsyncLocalStorage<StoreType>): boolean;
|
||||
/**
|
||||
* Applies the given data to any AsyncLocalStorage instances bound to the channel
|
||||
* for the duration of the given function, then publishes to the channel within
|
||||
* the scope of that data is applied to the stores.
|
||||
*
|
||||
* If a transform function was given to `channel.bindStore(store)` it will be
|
||||
* applied to transform the message data before it becomes the context value for
|
||||
* the store. The prior storage context is accessible from within the transform
|
||||
* function in cases where context linking is required.
|
||||
*
|
||||
* The context applied to the store should be accessible in any async code which
|
||||
* continues from execution which began during the given function, however
|
||||
* there are some situations in which `context loss` may occur.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
* import { AsyncLocalStorage } from 'node:async_hooks';
|
||||
*
|
||||
* const store = new AsyncLocalStorage();
|
||||
*
|
||||
* const channel = diagnostics_channel.channel('my-channel');
|
||||
*
|
||||
* channel.bindStore(store, (message) => {
|
||||
* const parent = store.getStore();
|
||||
* return new Span(message, parent);
|
||||
* });
|
||||
* channel.runStores({ some: 'message' }, () => {
|
||||
* store.getStore(); // Span({ some: 'message' })
|
||||
* });
|
||||
* ```
|
||||
* @since v19.9.0
|
||||
* @experimental
|
||||
* @param context Message to send to subscribers and bind to stores
|
||||
* @param fn Handler to run within the entered storage context
|
||||
* @param thisArg The receiver to be used for the function call.
|
||||
* @param args Optional arguments to pass to the function.
|
||||
*/
|
||||
runStores<ThisArg = any, Args extends any[] = any[], Result = any>(
|
||||
context: ContextType,
|
||||
fn: (this: ThisArg, ...args: Args) => Result,
|
||||
thisArg?: ThisArg,
|
||||
...args: Args
|
||||
): Result;
|
||||
}
|
||||
interface TracingChannelSubscribers<ContextType extends object> {
|
||||
start: (message: ContextType) => void;
|
||||
end: (
|
||||
message: ContextType & {
|
||||
error?: unknown;
|
||||
result?: unknown;
|
||||
},
|
||||
) => void;
|
||||
asyncStart: (
|
||||
message: ContextType & {
|
||||
error?: unknown;
|
||||
result?: unknown;
|
||||
},
|
||||
) => void;
|
||||
asyncEnd: (
|
||||
message: ContextType & {
|
||||
error?: unknown;
|
||||
result?: unknown;
|
||||
},
|
||||
) => void;
|
||||
error: (
|
||||
message: ContextType & {
|
||||
error: unknown;
|
||||
},
|
||||
) => void;
|
||||
}
|
||||
interface TracingChannelCollection<StoreType = unknown, ContextType = StoreType> {
|
||||
start: Channel<StoreType, ContextType>;
|
||||
end: Channel<StoreType, ContextType>;
|
||||
asyncStart: Channel<StoreType, ContextType>;
|
||||
asyncEnd: Channel<StoreType, ContextType>;
|
||||
error: Channel<StoreType, ContextType>;
|
||||
}
|
||||
/**
|
||||
* The class `TracingChannel` is a collection of `TracingChannel Channels` which
|
||||
* together express a single traceable action. It is used to formalize and
|
||||
* simplify the process of producing events for tracing application flow. {@link tracingChannel} is used to construct a `TracingChannel`. As with `Channel` it is recommended to create and reuse a
|
||||
* single `TracingChannel` at the top-level of the file rather than creating them
|
||||
* dynamically.
|
||||
* @since v19.9.0
|
||||
* @experimental
|
||||
*/
|
||||
class TracingChannel<StoreType = unknown, ContextType extends object = {}> implements TracingChannelCollection {
|
||||
start: Channel<StoreType, ContextType>;
|
||||
end: Channel<StoreType, ContextType>;
|
||||
asyncStart: Channel<StoreType, ContextType>;
|
||||
asyncEnd: Channel<StoreType, ContextType>;
|
||||
error: Channel<StoreType, ContextType>;
|
||||
/**
|
||||
* Helper to subscribe a collection of functions to the corresponding channels.
|
||||
* This is the same as calling `channel.subscribe(onMessage)` on each channel
|
||||
* individually.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
*
|
||||
* const channels = diagnostics_channel.tracingChannel('my-channel');
|
||||
*
|
||||
* channels.subscribe({
|
||||
* start(message) {
|
||||
* // Handle start message
|
||||
* },
|
||||
* end(message) {
|
||||
* // Handle end message
|
||||
* },
|
||||
* asyncStart(message) {
|
||||
* // Handle asyncStart message
|
||||
* },
|
||||
* asyncEnd(message) {
|
||||
* // Handle asyncEnd message
|
||||
* },
|
||||
* error(message) {
|
||||
* // Handle error message
|
||||
* },
|
||||
* });
|
||||
* ```
|
||||
* @since v19.9.0
|
||||
* @experimental
|
||||
* @param subscribers Set of `TracingChannel Channels` subscribers
|
||||
*/
|
||||
subscribe(subscribers: TracingChannelSubscribers<ContextType>): void;
|
||||
/**
|
||||
* Helper to unsubscribe a collection of functions from the corresponding channels.
|
||||
* This is the same as calling `channel.unsubscribe(onMessage)` on each channel
|
||||
* individually.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
*
|
||||
* const channels = diagnostics_channel.tracingChannel('my-channel');
|
||||
*
|
||||
* channels.unsubscribe({
|
||||
* start(message) {
|
||||
* // Handle start message
|
||||
* },
|
||||
* end(message) {
|
||||
* // Handle end message
|
||||
* },
|
||||
* asyncStart(message) {
|
||||
* // Handle asyncStart message
|
||||
* },
|
||||
* asyncEnd(message) {
|
||||
* // Handle asyncEnd message
|
||||
* },
|
||||
* error(message) {
|
||||
* // Handle error message
|
||||
* },
|
||||
* });
|
||||
* ```
|
||||
* @since v19.9.0
|
||||
* @experimental
|
||||
* @param subscribers Set of `TracingChannel Channels` subscribers
|
||||
* @return `true` if all handlers were successfully unsubscribed, and `false` otherwise.
|
||||
*/
|
||||
unsubscribe(subscribers: TracingChannelSubscribers<ContextType>): void;
|
||||
/**
|
||||
* Trace a synchronous function call. This will always produce a `start event` and `end event` around the execution and may produce an `error event` if the given function throws an error.
|
||||
* This will run the given function using `channel.runStores(context, ...)` on the `start` channel which ensures all
|
||||
* events should have any bound stores set to match this trace context.
|
||||
*
|
||||
* To ensure only correct trace graphs are formed, events will only be published if subscribers are present prior to starting the trace. Subscriptions
|
||||
* which are added after the trace begins will not receive future events from that trace, only future traces will be seen.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
*
|
||||
* const channels = diagnostics_channel.tracingChannel('my-channel');
|
||||
*
|
||||
* channels.traceSync(() => {
|
||||
* // Do something
|
||||
* }, {
|
||||
* some: 'thing',
|
||||
* });
|
||||
* ```
|
||||
* @since v19.9.0
|
||||
* @experimental
|
||||
* @param fn Function to wrap a trace around
|
||||
* @param context Shared object to correlate events through
|
||||
* @param thisArg The receiver to be used for the function call
|
||||
* @param args Optional arguments to pass to the function
|
||||
* @return The return value of the given function
|
||||
*/
|
||||
traceSync<ThisArg = any, Args extends any[] = any[], Result = any>(
|
||||
fn: (this: ThisArg, ...args: Args) => Result,
|
||||
context?: ContextType,
|
||||
thisArg?: ThisArg,
|
||||
...args: Args
|
||||
): Result;
|
||||
/**
|
||||
* Trace a promise-returning function call. This will always produce a `start event` and `end event` around the synchronous portion of the
|
||||
* function execution, and will produce an `asyncStart event` and `asyncEnd event` when a promise continuation is reached. It may also
|
||||
* produce an `error event` if the given function throws an error or the
|
||||
* returned promise rejects. This will run the given function using `channel.runStores(context, ...)` on the `start` channel which ensures all
|
||||
* events should have any bound stores set to match this trace context.
|
||||
*
|
||||
* To ensure only correct trace graphs are formed, events will only be published if subscribers are present prior to starting the trace. Subscriptions
|
||||
* which are added after the trace begins will not receive future events from that trace, only future traces will be seen.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
*
|
||||
* const channels = diagnostics_channel.tracingChannel('my-channel');
|
||||
*
|
||||
* channels.tracePromise(async () => {
|
||||
* // Do something
|
||||
* }, {
|
||||
* some: 'thing',
|
||||
* });
|
||||
* ```
|
||||
* @since v19.9.0
|
||||
* @experimental
|
||||
* @param fn Promise-returning function to wrap a trace around
|
||||
* @param context Shared object to correlate trace events through
|
||||
* @param thisArg The receiver to be used for the function call
|
||||
* @param args Optional arguments to pass to the function
|
||||
* @return Chained from promise returned by the given function
|
||||
*/
|
||||
tracePromise<ThisArg = any, Args extends any[] = any[], Result = any>(
|
||||
fn: (this: ThisArg, ...args: Args) => Promise<Result>,
|
||||
context?: ContextType,
|
||||
thisArg?: ThisArg,
|
||||
...args: Args
|
||||
): Promise<Result>;
|
||||
/**
|
||||
* Trace a callback-receiving function call. This will always produce a `start event` and `end event` around the synchronous portion of the
|
||||
* function execution, and will produce a `asyncStart event` and `asyncEnd event` around the callback execution. It may also produce an `error event` if the given function throws an error or
|
||||
* the returned
|
||||
* promise rejects. This will run the given function using `channel.runStores(context, ...)` on the `start` channel which ensures all
|
||||
* events should have any bound stores set to match this trace context.
|
||||
*
|
||||
* The `position` will be -1 by default to indicate the final argument should
|
||||
* be used as the callback.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
*
|
||||
* const channels = diagnostics_channel.tracingChannel('my-channel');
|
||||
*
|
||||
* channels.traceCallback((arg1, callback) => {
|
||||
* // Do something
|
||||
* callback(null, 'result');
|
||||
* }, 1, {
|
||||
* some: 'thing',
|
||||
* }, thisArg, arg1, callback);
|
||||
* ```
|
||||
*
|
||||
* The callback will also be run with `channel.runStores(context, ...)` which
|
||||
* enables context loss recovery in some cases.
|
||||
*
|
||||
* To ensure only correct trace graphs are formed, events will only be published if subscribers are present prior to starting the trace. Subscriptions
|
||||
* which are added after the trace begins will not receive future events from that trace, only future traces will be seen.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
* import { AsyncLocalStorage } from 'node:async_hooks';
|
||||
*
|
||||
* const channels = diagnostics_channel.tracingChannel('my-channel');
|
||||
* const myStore = new AsyncLocalStorage();
|
||||
*
|
||||
* // The start channel sets the initial store data to something
|
||||
* // and stores that store data value on the trace context object
|
||||
* channels.start.bindStore(myStore, (data) => {
|
||||
* const span = new Span(data);
|
||||
* data.span = span;
|
||||
* return span;
|
||||
* });
|
||||
*
|
||||
* // Then asyncStart can restore from that data it stored previously
|
||||
* channels.asyncStart.bindStore(myStore, (data) => {
|
||||
* return data.span;
|
||||
* });
|
||||
* ```
|
||||
* @since v19.9.0
|
||||
* @experimental
|
||||
* @param fn callback using function to wrap a trace around
|
||||
* @param position Zero-indexed argument position of expected callback
|
||||
* @param context Shared object to correlate trace events through
|
||||
* @param thisArg The receiver to be used for the function call
|
||||
* @param args Optional arguments to pass to the function
|
||||
* @return The return value of the given function
|
||||
*/
|
||||
traceCallback<ThisArg = any, Args extends any[] = any[], Result = any>(
|
||||
fn: (this: ThisArg, ...args: Args) => Result,
|
||||
position?: number,
|
||||
context?: ContextType,
|
||||
thisArg?: ThisArg,
|
||||
...args: Args
|
||||
): Result;
|
||||
/**
|
||||
* `true` if any of the individual channels has a subscriber, `false` if not.
|
||||
*
|
||||
* This is a helper method available on a {@link TracingChannel} instance to check
|
||||
* if any of the [TracingChannel Channels](https://nodejs.org/api/diagnostics_channel.html#tracingchannel-channels) have subscribers.
|
||||
* A `true` is returned if any of them have at least one subscriber, a `false` is returned otherwise.
|
||||
*
|
||||
* ```js
|
||||
* const diagnostics_channel = require('node:diagnostics_channel');
|
||||
*
|
||||
* const channels = diagnostics_channel.tracingChannel('my-channel');
|
||||
*
|
||||
* if (channels.hasSubscribers) {
|
||||
* // Do something
|
||||
* }
|
||||
* ```
|
||||
* @since v22.0.0, v20.13.0
|
||||
*/
|
||||
readonly hasSubscribers: boolean;
|
||||
}
|
||||
}
|
||||
declare module "node:diagnostics_channel" {
|
||||
export * from "diagnostics_channel";
|
||||
}
|
||||
923
node_modules/sitemap/node_modules/@types/node/dns.d.ts
generated
vendored
Normal file
923
node_modules/sitemap/node_modules/@types/node/dns.d.ts
generated
vendored
Normal file
@@ -0,0 +1,923 @@
|
||||
/**
|
||||
* The `node:dns` module enables name resolution. For example, use it to look up IP
|
||||
* addresses of host names.
|
||||
*
|
||||
* Although named for the [Domain Name System (DNS)](https://en.wikipedia.org/wiki/Domain_Name_System), it does not always use the
|
||||
* DNS protocol for lookups. {@link lookup} uses the operating system
|
||||
* facilities to perform name resolution. It may not need to perform any network
|
||||
* communication. To perform name resolution the way other applications on the same
|
||||
* system do, use {@link lookup}.
|
||||
*
|
||||
* ```js
|
||||
* import dns from 'node:dns';
|
||||
*
|
||||
* dns.lookup('example.org', (err, address, family) => {
|
||||
* console.log('address: %j family: IPv%s', address, family);
|
||||
* });
|
||||
* // address: "93.184.216.34" family: IPv4
|
||||
* ```
|
||||
*
|
||||
* All other functions in the `node:dns` module connect to an actual DNS server to
|
||||
* perform name resolution. They will always use the network to perform DNS
|
||||
* queries. These functions do not use the same set of configuration files used by {@link lookup} (e.g. `/etc/hosts`). Use these functions to always perform
|
||||
* DNS queries, bypassing other name-resolution facilities.
|
||||
*
|
||||
* ```js
|
||||
* import dns from 'node:dns';
|
||||
*
|
||||
* dns.resolve4('archive.org', (err, addresses) => {
|
||||
* if (err) throw err;
|
||||
*
|
||||
* console.log(`addresses: ${JSON.stringify(addresses)}`);
|
||||
*
|
||||
* addresses.forEach((a) => {
|
||||
* dns.reverse(a, (err, hostnames) => {
|
||||
* if (err) {
|
||||
* throw err;
|
||||
* }
|
||||
* console.log(`reverse for ${a}: ${JSON.stringify(hostnames)}`);
|
||||
* });
|
||||
* });
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* See the [Implementation considerations section](https://nodejs.org/docs/latest-v24.x/api/dns.html#implementation-considerations) for more information.
|
||||
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/dns.js)
|
||||
*/
|
||||
declare module "dns" {
|
||||
import * as dnsPromises from "node:dns/promises";
|
||||
// Supported getaddrinfo flags.
|
||||
/**
|
||||
* Limits returned address types to the types of non-loopback addresses configured on the system. For example, IPv4 addresses are
|
||||
* only returned if the current system has at least one IPv4 address configured.
|
||||
*/
|
||||
export const ADDRCONFIG: number;
|
||||
/**
|
||||
* If the IPv6 family was specified, but no IPv6 addresses were found, then return IPv4 mapped IPv6 addresses. It is not supported
|
||||
* on some operating systems (e.g. FreeBSD 10.1).
|
||||
*/
|
||||
export const V4MAPPED: number;
|
||||
/**
|
||||
* If `dns.V4MAPPED` is specified, return resolved IPv6 addresses as
|
||||
* well as IPv4 mapped IPv6 addresses.
|
||||
*/
|
||||
export const ALL: number;
|
||||
export interface LookupOptions {
|
||||
/**
|
||||
* The record family. Must be `4`, `6`, or `0`. For backward compatibility reasons, `'IPv4'` and `'IPv6'` are interpreted
|
||||
* as `4` and `6` respectively. The value 0 indicates that either an IPv4 or IPv6 address is returned. If the value `0` is used
|
||||
* with `{ all: true } (see below)`, both IPv4 and IPv6 addresses are returned.
|
||||
* @default 0
|
||||
*/
|
||||
family?: number | "IPv4" | "IPv6" | undefined;
|
||||
/**
|
||||
* One or more [supported `getaddrinfo`](https://nodejs.org/docs/latest-v24.x/api/dns.html#supported-getaddrinfo-flags) flags. Multiple flags may be
|
||||
* passed by bitwise `OR`ing their values.
|
||||
*/
|
||||
hints?: number | undefined;
|
||||
/**
|
||||
* When `true`, the callback returns all resolved addresses in an array. Otherwise, returns a single address.
|
||||
* @default false
|
||||
*/
|
||||
all?: boolean | undefined;
|
||||
/**
|
||||
* When `verbatim`, the resolved addresses are return unsorted. When `ipv4first`, the resolved addresses are sorted
|
||||
* by placing IPv4 addresses before IPv6 addresses. When `ipv6first`, the resolved addresses are sorted by placing IPv6
|
||||
* addresses before IPv4 addresses. Default value is configurable using
|
||||
* {@link setDefaultResultOrder} or [`--dns-result-order`](https://nodejs.org/docs/latest-v24.x/api/cli.html#--dns-result-orderorder).
|
||||
* @default `verbatim` (addresses are not reordered)
|
||||
* @since v22.1.0
|
||||
*/
|
||||
order?: "ipv4first" | "ipv6first" | "verbatim" | undefined;
|
||||
/**
|
||||
* When `true`, the callback receives IPv4 and IPv6 addresses in the order the DNS resolver returned them. When `false`, IPv4
|
||||
* addresses are placed before IPv6 addresses. This option will be deprecated in favor of `order`. When both are specified,
|
||||
* `order` has higher precedence. New code should only use `order`. Default value is configurable using {@link setDefaultResultOrder}
|
||||
* @default true (addresses are not reordered)
|
||||
* @deprecated Please use `order` option
|
||||
*/
|
||||
verbatim?: boolean | undefined;
|
||||
}
|
||||
export interface LookupOneOptions extends LookupOptions {
|
||||
all?: false | undefined;
|
||||
}
|
||||
export interface LookupAllOptions extends LookupOptions {
|
||||
all: true;
|
||||
}
|
||||
export interface LookupAddress {
|
||||
/**
|
||||
* A string representation of an IPv4 or IPv6 address.
|
||||
*/
|
||||
address: string;
|
||||
/**
|
||||
* `4` or `6`, denoting the family of `address`, or `0` if the address is not an IPv4 or IPv6 address. `0` is a likely indicator of a
|
||||
* bug in the name resolution service used by the operating system.
|
||||
*/
|
||||
family: number;
|
||||
}
|
||||
/**
|
||||
* Resolves a host name (e.g. `'nodejs.org'`) into the first found A (IPv4) or
|
||||
* AAAA (IPv6) record. All `option` properties are optional. If `options` is an
|
||||
* integer, then it must be `4` or `6` – if `options` is `0` or not provided, then
|
||||
* IPv4 and IPv6 addresses are both returned if found.
|
||||
*
|
||||
* With the `all` option set to `true`, the arguments for `callback` change to `(err, addresses)`, with `addresses` being an array of objects with the
|
||||
* properties `address` and `family`.
|
||||
*
|
||||
* On error, `err` is an `Error` object, where `err.code` is the error code.
|
||||
* Keep in mind that `err.code` will be set to `'ENOTFOUND'` not only when
|
||||
* the host name does not exist but also when the lookup fails in other ways
|
||||
* such as no available file descriptors.
|
||||
*
|
||||
* `dns.lookup()` does not necessarily have anything to do with the DNS protocol.
|
||||
* The implementation uses an operating system facility that can associate names
|
||||
* with addresses and vice versa. This implementation can have subtle but
|
||||
* important consequences on the behavior of any Node.js program. Please take some
|
||||
* time to consult the [Implementation considerations section](https://nodejs.org/docs/latest-v24.x/api/dns.html#implementation-considerations)
|
||||
* before using `dns.lookup()`.
|
||||
*
|
||||
* Example usage:
|
||||
*
|
||||
* ```js
|
||||
* import dns from 'node:dns';
|
||||
* const options = {
|
||||
* family: 6,
|
||||
* hints: dns.ADDRCONFIG | dns.V4MAPPED,
|
||||
* };
|
||||
* dns.lookup('example.com', options, (err, address, family) =>
|
||||
* console.log('address: %j family: IPv%s', address, family));
|
||||
* // address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6
|
||||
*
|
||||
* // When options.all is true, the result will be an Array.
|
||||
* options.all = true;
|
||||
* dns.lookup('example.com', options, (err, addresses) =>
|
||||
* console.log('addresses: %j', addresses));
|
||||
* // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}]
|
||||
* ```
|
||||
*
|
||||
* If this method is invoked as its [util.promisify()](https://nodejs.org/docs/latest-v24.x/api/util.html#utilpromisifyoriginal) ed
|
||||
* version, and `all` is not set to `true`, it returns a `Promise` for an `Object` with `address` and `family` properties.
|
||||
* @since v0.1.90
|
||||
*/
|
||||
export function lookup(
|
||||
hostname: string,
|
||||
family: number,
|
||||
callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void,
|
||||
): void;
|
||||
export function lookup(
|
||||
hostname: string,
|
||||
options: LookupOneOptions,
|
||||
callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void,
|
||||
): void;
|
||||
export function lookup(
|
||||
hostname: string,
|
||||
options: LookupAllOptions,
|
||||
callback: (err: NodeJS.ErrnoException | null, addresses: LookupAddress[]) => void,
|
||||
): void;
|
||||
export function lookup(
|
||||
hostname: string,
|
||||
options: LookupOptions,
|
||||
callback: (err: NodeJS.ErrnoException | null, address: string | LookupAddress[], family: number) => void,
|
||||
): void;
|
||||
export function lookup(
|
||||
hostname: string,
|
||||
callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void,
|
||||
): void;
|
||||
export namespace lookup {
|
||||
function __promisify__(hostname: string, options: LookupAllOptions): Promise<LookupAddress[]>;
|
||||
function __promisify__(hostname: string, options?: LookupOneOptions | number): Promise<LookupAddress>;
|
||||
function __promisify__(hostname: string, options: LookupOptions): Promise<LookupAddress | LookupAddress[]>;
|
||||
}
|
||||
/**
|
||||
* Resolves the given `address` and `port` into a host name and service using
|
||||
* the operating system's underlying `getnameinfo` implementation.
|
||||
*
|
||||
* If `address` is not a valid IP address, a `TypeError` will be thrown.
|
||||
* The `port` will be coerced to a number. If it is not a legal port, a `TypeError` will be thrown.
|
||||
*
|
||||
* On an error, `err` is an [`Error`](https://nodejs.org/docs/latest-v24.x/api/errors.html#class-error) object,
|
||||
* where `err.code` is the error code.
|
||||
*
|
||||
* ```js
|
||||
* import dns from 'node:dns';
|
||||
* dns.lookupService('127.0.0.1', 22, (err, hostname, service) => {
|
||||
* console.log(hostname, service);
|
||||
* // Prints: localhost ssh
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* If this method is invoked as its [util.promisify()](https://nodejs.org/docs/latest-v24.x/api/util.html#utilpromisifyoriginal) ed
|
||||
* version, it returns a `Promise` for an `Object` with `hostname` and `service` properties.
|
||||
* @since v0.11.14
|
||||
*/
|
||||
export function lookupService(
|
||||
address: string,
|
||||
port: number,
|
||||
callback: (err: NodeJS.ErrnoException | null, hostname: string, service: string) => void,
|
||||
): void;
|
||||
export namespace lookupService {
|
||||
function __promisify__(
|
||||
address: string,
|
||||
port: number,
|
||||
): Promise<{
|
||||
hostname: string;
|
||||
service: string;
|
||||
}>;
|
||||
}
|
||||
export interface ResolveOptions {
|
||||
ttl: boolean;
|
||||
}
|
||||
export interface ResolveWithTtlOptions extends ResolveOptions {
|
||||
ttl: true;
|
||||
}
|
||||
export interface RecordWithTtl {
|
||||
address: string;
|
||||
ttl: number;
|
||||
}
|
||||
/** @deprecated Use `AnyARecord` or `AnyAaaaRecord` instead. */
|
||||
export type AnyRecordWithTtl = AnyARecord | AnyAaaaRecord;
|
||||
export interface AnyARecord extends RecordWithTtl {
|
||||
type: "A";
|
||||
}
|
||||
export interface AnyAaaaRecord extends RecordWithTtl {
|
||||
type: "AAAA";
|
||||
}
|
||||
export interface CaaRecord {
|
||||
critical: number;
|
||||
issue?: string | undefined;
|
||||
issuewild?: string | undefined;
|
||||
iodef?: string | undefined;
|
||||
contactemail?: string | undefined;
|
||||
contactphone?: string | undefined;
|
||||
}
|
||||
export interface AnyCaaRecord extends CaaRecord {
|
||||
type: "CAA";
|
||||
}
|
||||
export interface MxRecord {
|
||||
priority: number;
|
||||
exchange: string;
|
||||
}
|
||||
export interface AnyMxRecord extends MxRecord {
|
||||
type: "MX";
|
||||
}
|
||||
export interface NaptrRecord {
|
||||
flags: string;
|
||||
service: string;
|
||||
regexp: string;
|
||||
replacement: string;
|
||||
order: number;
|
||||
preference: number;
|
||||
}
|
||||
export interface AnyNaptrRecord extends NaptrRecord {
|
||||
type: "NAPTR";
|
||||
}
|
||||
export interface SoaRecord {
|
||||
nsname: string;
|
||||
hostmaster: string;
|
||||
serial: number;
|
||||
refresh: number;
|
||||
retry: number;
|
||||
expire: number;
|
||||
minttl: number;
|
||||
}
|
||||
export interface AnySoaRecord extends SoaRecord {
|
||||
type: "SOA";
|
||||
}
|
||||
export interface SrvRecord {
|
||||
priority: number;
|
||||
weight: number;
|
||||
port: number;
|
||||
name: string;
|
||||
}
|
||||
export interface AnySrvRecord extends SrvRecord {
|
||||
type: "SRV";
|
||||
}
|
||||
export interface TlsaRecord {
|
||||
certUsage: number;
|
||||
selector: number;
|
||||
match: number;
|
||||
data: ArrayBuffer;
|
||||
}
|
||||
export interface AnyTlsaRecord extends TlsaRecord {
|
||||
type: "TLSA";
|
||||
}
|
||||
export interface AnyTxtRecord {
|
||||
type: "TXT";
|
||||
entries: string[];
|
||||
}
|
||||
export interface AnyNsRecord {
|
||||
type: "NS";
|
||||
value: string;
|
||||
}
|
||||
export interface AnyPtrRecord {
|
||||
type: "PTR";
|
||||
value: string;
|
||||
}
|
||||
export interface AnyCnameRecord {
|
||||
type: "CNAME";
|
||||
value: string;
|
||||
}
|
||||
export type AnyRecord =
|
||||
| AnyARecord
|
||||
| AnyAaaaRecord
|
||||
| AnyCaaRecord
|
||||
| AnyCnameRecord
|
||||
| AnyMxRecord
|
||||
| AnyNaptrRecord
|
||||
| AnyNsRecord
|
||||
| AnyPtrRecord
|
||||
| AnySoaRecord
|
||||
| AnySrvRecord
|
||||
| AnyTlsaRecord
|
||||
| AnyTxtRecord;
|
||||
/**
|
||||
* Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array
|
||||
* of the resource records. The `callback` function has arguments `(err, records)`. When successful, `records` will be an array of resource
|
||||
* records. The type and structure of individual results varies based on `rrtype`:
|
||||
*
|
||||
* <omitted>
|
||||
*
|
||||
* On error, `err` is an [`Error`](https://nodejs.org/docs/latest-v24.x/api/errors.html#class-error) object,
|
||||
* where `err.code` is one of the `DNS error codes`.
|
||||
* @since v0.1.27
|
||||
* @param hostname Host name to resolve.
|
||||
* @param [rrtype='A'] Resource record type.
|
||||
*/
|
||||
export function resolve(
|
||||
hostname: string,
|
||||
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void,
|
||||
): void;
|
||||
export function resolve(
|
||||
hostname: string,
|
||||
rrtype: "A" | "AAAA" | "CNAME" | "NS" | "PTR",
|
||||
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void,
|
||||
): void;
|
||||
export function resolve(
|
||||
hostname: string,
|
||||
rrtype: "ANY",
|
||||
callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void,
|
||||
): void;
|
||||
export function resolve(
|
||||
hostname: string,
|
||||
rrtype: "CAA",
|
||||
callback: (err: NodeJS.ErrnoException | null, address: CaaRecord[]) => void,
|
||||
): void;
|
||||
export function resolve(
|
||||
hostname: string,
|
||||
rrtype: "MX",
|
||||
callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void,
|
||||
): void;
|
||||
export function resolve(
|
||||
hostname: string,
|
||||
rrtype: "NAPTR",
|
||||
callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void,
|
||||
): void;
|
||||
export function resolve(
|
||||
hostname: string,
|
||||
rrtype: "SOA",
|
||||
callback: (err: NodeJS.ErrnoException | null, addresses: SoaRecord) => void,
|
||||
): void;
|
||||
export function resolve(
|
||||
hostname: string,
|
||||
rrtype: "SRV",
|
||||
callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void,
|
||||
): void;
|
||||
export function resolve(
|
||||
hostname: string,
|
||||
rrtype: "TLSA",
|
||||
callback: (err: NodeJS.ErrnoException | null, addresses: TlsaRecord[]) => void,
|
||||
): void;
|
||||
export function resolve(
|
||||
hostname: string,
|
||||
rrtype: "TXT",
|
||||
callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void,
|
||||
): void;
|
||||
export function resolve(
|
||||
hostname: string,
|
||||
rrtype: string,
|
||||
callback: (
|
||||
err: NodeJS.ErrnoException | null,
|
||||
addresses:
|
||||
| string[]
|
||||
| CaaRecord[]
|
||||
| MxRecord[]
|
||||
| NaptrRecord[]
|
||||
| SoaRecord
|
||||
| SrvRecord[]
|
||||
| TlsaRecord[]
|
||||
| string[][]
|
||||
| AnyRecord[],
|
||||
) => void,
|
||||
): void;
|
||||
export namespace resolve {
|
||||
function __promisify__(hostname: string, rrtype?: "A" | "AAAA" | "CNAME" | "NS" | "PTR"): Promise<string[]>;
|
||||
function __promisify__(hostname: string, rrtype: "ANY"): Promise<AnyRecord[]>;
|
||||
function __promisify__(hostname: string, rrtype: "CAA"): Promise<CaaRecord[]>;
|
||||
function __promisify__(hostname: string, rrtype: "MX"): Promise<MxRecord[]>;
|
||||
function __promisify__(hostname: string, rrtype: "NAPTR"): Promise<NaptrRecord[]>;
|
||||
function __promisify__(hostname: string, rrtype: "SOA"): Promise<SoaRecord>;
|
||||
function __promisify__(hostname: string, rrtype: "SRV"): Promise<SrvRecord[]>;
|
||||
function __promisify__(hostname: string, rrtype: "TLSA"): Promise<TlsaRecord[]>;
|
||||
function __promisify__(hostname: string, rrtype: "TXT"): Promise<string[][]>;
|
||||
function __promisify__(
|
||||
hostname: string,
|
||||
rrtype: string,
|
||||
): Promise<
|
||||
| string[]
|
||||
| CaaRecord[]
|
||||
| MxRecord[]
|
||||
| NaptrRecord[]
|
||||
| SoaRecord
|
||||
| SrvRecord[]
|
||||
| TlsaRecord[]
|
||||
| string[][]
|
||||
| AnyRecord[]
|
||||
>;
|
||||
}
|
||||
/**
|
||||
* Uses the DNS protocol to resolve a IPv4 addresses (`A` records) for the `hostname`. The `addresses` argument passed to the `callback` function
|
||||
* will contain an array of IPv4 addresses (e.g.`['74.125.79.104', '74.125.79.105', '74.125.79.106']`).
|
||||
* @since v0.1.16
|
||||
* @param hostname Host name to resolve.
|
||||
*/
|
||||
export function resolve4(
|
||||
hostname: string,
|
||||
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void,
|
||||
): void;
|
||||
export function resolve4(
|
||||
hostname: string,
|
||||
options: ResolveWithTtlOptions,
|
||||
callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void,
|
||||
): void;
|
||||
export function resolve4(
|
||||
hostname: string,
|
||||
options: ResolveOptions,
|
||||
callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void,
|
||||
): void;
|
||||
export namespace resolve4 {
|
||||
function __promisify__(hostname: string): Promise<string[]>;
|
||||
function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise<RecordWithTtl[]>;
|
||||
function __promisify__(hostname: string, options?: ResolveOptions): Promise<string[] | RecordWithTtl[]>;
|
||||
}
|
||||
/**
|
||||
* Uses the DNS protocol to resolve IPv6 addresses (`AAAA` records) for the `hostname`. The `addresses` argument passed to the `callback` function
|
||||
* will contain an array of IPv6 addresses.
|
||||
* @since v0.1.16
|
||||
* @param hostname Host name to resolve.
|
||||
*/
|
||||
export function resolve6(
|
||||
hostname: string,
|
||||
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void,
|
||||
): void;
|
||||
export function resolve6(
|
||||
hostname: string,
|
||||
options: ResolveWithTtlOptions,
|
||||
callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void,
|
||||
): void;
|
||||
export function resolve6(
|
||||
hostname: string,
|
||||
options: ResolveOptions,
|
||||
callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void,
|
||||
): void;
|
||||
export namespace resolve6 {
|
||||
function __promisify__(hostname: string): Promise<string[]>;
|
||||
function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise<RecordWithTtl[]>;
|
||||
function __promisify__(hostname: string, options?: ResolveOptions): Promise<string[] | RecordWithTtl[]>;
|
||||
}
|
||||
/**
|
||||
* Uses the DNS protocol to resolve `CNAME` records for the `hostname`. The `addresses` argument passed to the `callback` function
|
||||
* will contain an array of canonical name records available for the `hostname` (e.g. `['bar.example.com']`).
|
||||
* @since v0.3.2
|
||||
*/
|
||||
export function resolveCname(
|
||||
hostname: string,
|
||||
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void,
|
||||
): void;
|
||||
export namespace resolveCname {
|
||||
function __promisify__(hostname: string): Promise<string[]>;
|
||||
}
|
||||
/**
|
||||
* Uses the DNS protocol to resolve `CAA` records for the `hostname`. The `addresses` argument passed to the `callback` function
|
||||
* will contain an array of certification authority authorization records
|
||||
* available for the `hostname` (e.g. `[{critical: 0, iodef: 'mailto:pki@example.com'}, {critical: 128, issue: 'pki.example.com'}]`).
|
||||
* @since v15.0.0, v14.17.0
|
||||
*/
|
||||
export function resolveCaa(
|
||||
hostname: string,
|
||||
callback: (err: NodeJS.ErrnoException | null, records: CaaRecord[]) => void,
|
||||
): void;
|
||||
export namespace resolveCaa {
|
||||
function __promisify__(hostname: string): Promise<CaaRecord[]>;
|
||||
}
|
||||
/**
|
||||
* Uses the DNS protocol to resolve mail exchange records (`MX` records) for the `hostname`. The `addresses` argument passed to the `callback` function will
|
||||
* contain an array of objects containing both a `priority` and `exchange` property (e.g. `[{priority: 10, exchange: 'mx.example.com'}, ...]`).
|
||||
* @since v0.1.27
|
||||
*/
|
||||
export function resolveMx(
|
||||
hostname: string,
|
||||
callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void,
|
||||
): void;
|
||||
export namespace resolveMx {
|
||||
function __promisify__(hostname: string): Promise<MxRecord[]>;
|
||||
}
|
||||
/**
|
||||
* Uses the DNS protocol to resolve regular expression-based records (`NAPTR` records) for the `hostname`. The `addresses` argument passed to the `callback` function will contain an array of
|
||||
* objects with the following properties:
|
||||
*
|
||||
* * `flags`
|
||||
* * `service`
|
||||
* * `regexp`
|
||||
* * `replacement`
|
||||
* * `order`
|
||||
* * `preference`
|
||||
*
|
||||
* ```js
|
||||
* {
|
||||
* flags: 's',
|
||||
* service: 'SIP+D2U',
|
||||
* regexp: '',
|
||||
* replacement: '_sip._udp.example.com',
|
||||
* order: 30,
|
||||
* preference: 100
|
||||
* }
|
||||
* ```
|
||||
* @since v0.9.12
|
||||
*/
|
||||
export function resolveNaptr(
|
||||
hostname: string,
|
||||
callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void,
|
||||
): void;
|
||||
export namespace resolveNaptr {
|
||||
function __promisify__(hostname: string): Promise<NaptrRecord[]>;
|
||||
}
|
||||
/**
|
||||
* Uses the DNS protocol to resolve name server records (`NS` records) for the `hostname`. The `addresses` argument passed to the `callback` function will
|
||||
* contain an array of name server records available for `hostname` (e.g. `['ns1.example.com', 'ns2.example.com']`).
|
||||
* @since v0.1.90
|
||||
*/
|
||||
export function resolveNs(
|
||||
hostname: string,
|
||||
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void,
|
||||
): void;
|
||||
export namespace resolveNs {
|
||||
function __promisify__(hostname: string): Promise<string[]>;
|
||||
}
|
||||
/**
|
||||
* Uses the DNS protocol to resolve pointer records (`PTR` records) for the `hostname`. The `addresses` argument passed to the `callback` function will
|
||||
* be an array of strings containing the reply records.
|
||||
* @since v6.0.0
|
||||
*/
|
||||
export function resolvePtr(
|
||||
hostname: string,
|
||||
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void,
|
||||
): void;
|
||||
export namespace resolvePtr {
|
||||
function __promisify__(hostname: string): Promise<string[]>;
|
||||
}
|
||||
/**
|
||||
* Uses the DNS protocol to resolve a start of authority record (`SOA` record) for
|
||||
* the `hostname`. The `address` argument passed to the `callback` function will
|
||||
* be an object with the following properties:
|
||||
*
|
||||
* * `nsname`
|
||||
* * `hostmaster`
|
||||
* * `serial`
|
||||
* * `refresh`
|
||||
* * `retry`
|
||||
* * `expire`
|
||||
* * `minttl`
|
||||
*
|
||||
* ```js
|
||||
* {
|
||||
* nsname: 'ns.example.com',
|
||||
* hostmaster: 'root.example.com',
|
||||
* serial: 2013101809,
|
||||
* refresh: 10000,
|
||||
* retry: 2400,
|
||||
* expire: 604800,
|
||||
* minttl: 3600
|
||||
* }
|
||||
* ```
|
||||
* @since v0.11.10
|
||||
*/
|
||||
export function resolveSoa(
|
||||
hostname: string,
|
||||
callback: (err: NodeJS.ErrnoException | null, address: SoaRecord) => void,
|
||||
): void;
|
||||
export namespace resolveSoa {
|
||||
function __promisify__(hostname: string): Promise<SoaRecord>;
|
||||
}
|
||||
/**
|
||||
* Uses the DNS protocol to resolve service records (`SRV` records) for the `hostname`. The `addresses` argument passed to the `callback` function will
|
||||
* be an array of objects with the following properties:
|
||||
*
|
||||
* * `priority`
|
||||
* * `weight`
|
||||
* * `port`
|
||||
* * `name`
|
||||
*
|
||||
* ```js
|
||||
* {
|
||||
* priority: 10,
|
||||
* weight: 5,
|
||||
* port: 21223,
|
||||
* name: 'service.example.com'
|
||||
* }
|
||||
* ```
|
||||
* @since v0.1.27
|
||||
*/
|
||||
export function resolveSrv(
|
||||
hostname: string,
|
||||
callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void,
|
||||
): void;
|
||||
export namespace resolveSrv {
|
||||
function __promisify__(hostname: string): Promise<SrvRecord[]>;
|
||||
}
|
||||
/**
|
||||
* Uses the DNS protocol to resolve certificate associations (`TLSA` records) for
|
||||
* the `hostname`. The `records` argument passed to the `callback` function is an
|
||||
* array of objects with these properties:
|
||||
*
|
||||
* * `certUsage`
|
||||
* * `selector`
|
||||
* * `match`
|
||||
* * `data`
|
||||
*
|
||||
* ```js
|
||||
* {
|
||||
* certUsage: 3,
|
||||
* selector: 1,
|
||||
* match: 1,
|
||||
* data: [ArrayBuffer]
|
||||
* }
|
||||
* ```
|
||||
* @since v23.9.0, v22.15.0
|
||||
*/
|
||||
export function resolveTlsa(
|
||||
hostname: string,
|
||||
callback: (err: NodeJS.ErrnoException | null, addresses: TlsaRecord[]) => void,
|
||||
): void;
|
||||
export namespace resolveTlsa {
|
||||
function __promisify__(hostname: string): Promise<TlsaRecord[]>;
|
||||
}
|
||||
/**
|
||||
* Uses the DNS protocol to resolve text queries (`TXT` records) for the `hostname`. The `records` argument passed to the `callback` function is a
|
||||
* two-dimensional array of the text records available for `hostname` (e.g.`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of
|
||||
* one record. Depending on the use case, these could be either joined together or
|
||||
* treated separately.
|
||||
* @since v0.1.27
|
||||
*/
|
||||
export function resolveTxt(
|
||||
hostname: string,
|
||||
callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void,
|
||||
): void;
|
||||
export namespace resolveTxt {
|
||||
function __promisify__(hostname: string): Promise<string[][]>;
|
||||
}
|
||||
/**
|
||||
* Uses the DNS protocol to resolve all records (also known as `ANY` or `*` query).
|
||||
* The `ret` argument passed to the `callback` function will be an array containing
|
||||
* various types of records. Each object has a property `type` that indicates the
|
||||
* type of the current record. And depending on the `type`, additional properties
|
||||
* will be present on the object:
|
||||
*
|
||||
* <omitted>
|
||||
*
|
||||
* Here is an example of the `ret` object passed to the callback:
|
||||
*
|
||||
* ```js
|
||||
* [ { type: 'A', address: '127.0.0.1', ttl: 299 },
|
||||
* { type: 'CNAME', value: 'example.com' },
|
||||
* { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 },
|
||||
* { type: 'NS', value: 'ns1.example.com' },
|
||||
* { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] },
|
||||
* { type: 'SOA',
|
||||
* nsname: 'ns1.example.com',
|
||||
* hostmaster: 'admin.example.com',
|
||||
* serial: 156696742,
|
||||
* refresh: 900,
|
||||
* retry: 900,
|
||||
* expire: 1800,
|
||||
* minttl: 60 } ]
|
||||
* ```
|
||||
*
|
||||
* DNS server operators may choose not to respond to `ANY` queries. It may be better to call individual methods like {@link resolve4}, {@link resolveMx}, and so on. For more details, see
|
||||
* [RFC 8482](https://tools.ietf.org/html/rfc8482).
|
||||
*/
|
||||
export function resolveAny(
|
||||
hostname: string,
|
||||
callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void,
|
||||
): void;
|
||||
export namespace resolveAny {
|
||||
function __promisify__(hostname: string): Promise<AnyRecord[]>;
|
||||
}
|
||||
/**
|
||||
* Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an
|
||||
* array of host names.
|
||||
*
|
||||
* On error, `err` is an [`Error`](https://nodejs.org/docs/latest-v24.x/api/errors.html#class-error) object, where `err.code` is
|
||||
* one of the [DNS error codes](https://nodejs.org/docs/latest-v24.x/api/dns.html#error-codes).
|
||||
* @since v0.1.16
|
||||
*/
|
||||
export function reverse(
|
||||
ip: string,
|
||||
callback: (err: NodeJS.ErrnoException | null, hostnames: string[]) => void,
|
||||
): void;
|
||||
/**
|
||||
* Get the default value for `order` in {@link lookup} and [`dnsPromises.lookup()`](https://nodejs.org/docs/latest-v24.x/api/dns.html#dnspromiseslookuphostname-options).
|
||||
* The value could be:
|
||||
*
|
||||
* * `ipv4first`: for `order` defaulting to `ipv4first`.
|
||||
* * `ipv6first`: for `order` defaulting to `ipv6first`.
|
||||
* * `verbatim`: for `order` defaulting to `verbatim`.
|
||||
* @since v18.17.0
|
||||
*/
|
||||
export function getDefaultResultOrder(): "ipv4first" | "ipv6first" | "verbatim";
|
||||
/**
|
||||
* Sets the IP address and port of servers to be used when performing DNS
|
||||
* resolution. The `servers` argument is an array of [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6) formatted
|
||||
* addresses. If the port is the IANA default DNS port (53) it can be omitted.
|
||||
*
|
||||
* ```js
|
||||
* dns.setServers([
|
||||
* '4.4.4.4',
|
||||
* '[2001:4860:4860::8888]',
|
||||
* '4.4.4.4:1053',
|
||||
* '[2001:4860:4860::8888]:1053',
|
||||
* ]);
|
||||
* ```
|
||||
*
|
||||
* An error will be thrown if an invalid address is provided.
|
||||
*
|
||||
* The `dns.setServers()` method must not be called while a DNS query is in
|
||||
* progress.
|
||||
*
|
||||
* The {@link setServers} method affects only {@link resolve}, `dns.resolve*()` and {@link reverse} (and specifically _not_ {@link lookup}).
|
||||
*
|
||||
* This method works much like [resolve.conf](https://man7.org/linux/man-pages/man5/resolv.conf.5.html).
|
||||
* That is, if attempting to resolve with the first server provided results in a `NOTFOUND` error, the `resolve()` method will _not_ attempt to resolve with
|
||||
* subsequent servers provided. Fallback DNS servers will only be used if the
|
||||
* earlier ones time out or result in some other error.
|
||||
* @since v0.11.3
|
||||
* @param servers array of [RFC 5952](https://datatracker.ietf.org/doc/html/rfc5952#section-6) formatted addresses
|
||||
*/
|
||||
export function setServers(servers: readonly string[]): void;
|
||||
/**
|
||||
* Returns an array of IP address strings, formatted according to [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6),
|
||||
* that are currently configured for DNS resolution. A string will include a port
|
||||
* section if a custom port is used.
|
||||
*
|
||||
* ```js
|
||||
* [
|
||||
* '4.4.4.4',
|
||||
* '2001:4860:4860::8888',
|
||||
* '4.4.4.4:1053',
|
||||
* '[2001:4860:4860::8888]:1053',
|
||||
* ]
|
||||
* ```
|
||||
* @since v0.11.3
|
||||
*/
|
||||
export function getServers(): string[];
|
||||
/**
|
||||
* Set the default value of `order` in {@link lookup} and [`dnsPromises.lookup()`](https://nodejs.org/docs/latest-v24.x/api/dns.html#dnspromiseslookuphostname-options).
|
||||
* The value could be:
|
||||
*
|
||||
* * `ipv4first`: sets default `order` to `ipv4first`.
|
||||
* * `ipv6first`: sets default `order` to `ipv6first`.
|
||||
* * `verbatim`: sets default `order` to `verbatim`.
|
||||
*
|
||||
* The default is `verbatim` and {@link setDefaultResultOrder} have higher
|
||||
* priority than [`--dns-result-order`](https://nodejs.org/docs/latest-v24.x/api/cli.html#--dns-result-orderorder). When using
|
||||
* [worker threads](https://nodejs.org/docs/latest-v24.x/api/worker_threads.html), {@link setDefaultResultOrder} from the main
|
||||
* thread won't affect the default dns orders in workers.
|
||||
* @since v16.4.0, v14.18.0
|
||||
* @param order must be `'ipv4first'`, `'ipv6first'` or `'verbatim'`.
|
||||
*/
|
||||
export function setDefaultResultOrder(order: "ipv4first" | "ipv6first" | "verbatim"): void;
|
||||
// Error codes
|
||||
export const NODATA: "ENODATA";
|
||||
export const FORMERR: "EFORMERR";
|
||||
export const SERVFAIL: "ESERVFAIL";
|
||||
export const NOTFOUND: "ENOTFOUND";
|
||||
export const NOTIMP: "ENOTIMP";
|
||||
export const REFUSED: "EREFUSED";
|
||||
export const BADQUERY: "EBADQUERY";
|
||||
export const BADNAME: "EBADNAME";
|
||||
export const BADFAMILY: "EBADFAMILY";
|
||||
export const BADRESP: "EBADRESP";
|
||||
export const CONNREFUSED: "ECONNREFUSED";
|
||||
export const TIMEOUT: "ETIMEOUT";
|
||||
export const EOF: "EOF";
|
||||
export const FILE: "EFILE";
|
||||
export const NOMEM: "ENOMEM";
|
||||
export const DESTRUCTION: "EDESTRUCTION";
|
||||
export const BADSTR: "EBADSTR";
|
||||
export const BADFLAGS: "EBADFLAGS";
|
||||
export const NONAME: "ENONAME";
|
||||
export const BADHINTS: "EBADHINTS";
|
||||
export const NOTINITIALIZED: "ENOTINITIALIZED";
|
||||
export const LOADIPHLPAPI: "ELOADIPHLPAPI";
|
||||
export const ADDRGETNETWORKPARAMS: "EADDRGETNETWORKPARAMS";
|
||||
export const CANCELLED: "ECANCELLED";
|
||||
export interface ResolverOptions {
|
||||
/**
|
||||
* Query timeout in milliseconds, or `-1` to use the default timeout.
|
||||
*/
|
||||
timeout?: number | undefined;
|
||||
/**
|
||||
* The number of tries the resolver will try contacting each name server before giving up.
|
||||
* @default 4
|
||||
*/
|
||||
tries?: number | undefined;
|
||||
/**
|
||||
* The max retry timeout, in milliseconds.
|
||||
* @default 0
|
||||
*/
|
||||
maxTimeout?: number | undefined;
|
||||
}
|
||||
/**
|
||||
* An independent resolver for DNS requests.
|
||||
*
|
||||
* Creating a new resolver uses the default server settings. Setting
|
||||
* the servers used for a resolver using [`resolver.setServers()`](https://nodejs.org/docs/latest-v24.x/api/dns.html#dnssetserversservers) does not affect
|
||||
* other resolvers:
|
||||
*
|
||||
* ```js
|
||||
* import { Resolver } from 'node:dns';
|
||||
* const resolver = new Resolver();
|
||||
* resolver.setServers(['4.4.4.4']);
|
||||
*
|
||||
* // This request will use the server at 4.4.4.4, independent of global settings.
|
||||
* resolver.resolve4('example.org', (err, addresses) => {
|
||||
* // ...
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* The following methods from the `node:dns` module are available:
|
||||
*
|
||||
* * `resolver.getServers()`
|
||||
* * `resolver.resolve()`
|
||||
* * `resolver.resolve4()`
|
||||
* * `resolver.resolve6()`
|
||||
* * `resolver.resolveAny()`
|
||||
* * `resolver.resolveCaa()`
|
||||
* * `resolver.resolveCname()`
|
||||
* * `resolver.resolveMx()`
|
||||
* * `resolver.resolveNaptr()`
|
||||
* * `resolver.resolveNs()`
|
||||
* * `resolver.resolvePtr()`
|
||||
* * `resolver.resolveSoa()`
|
||||
* * `resolver.resolveSrv()`
|
||||
* * `resolver.resolveTxt()`
|
||||
* * `resolver.reverse()`
|
||||
* * `resolver.setServers()`
|
||||
* @since v8.3.0
|
||||
*/
|
||||
export class Resolver {
|
||||
constructor(options?: ResolverOptions);
|
||||
/**
|
||||
* Cancel all outstanding DNS queries made by this resolver. The corresponding
|
||||
* callbacks will be called with an error with code `ECANCELLED`.
|
||||
* @since v8.3.0
|
||||
*/
|
||||
cancel(): void;
|
||||
getServers: typeof getServers;
|
||||
resolve: typeof resolve;
|
||||
resolve4: typeof resolve4;
|
||||
resolve6: typeof resolve6;
|
||||
resolveAny: typeof resolveAny;
|
||||
resolveCaa: typeof resolveCaa;
|
||||
resolveCname: typeof resolveCname;
|
||||
resolveMx: typeof resolveMx;
|
||||
resolveNaptr: typeof resolveNaptr;
|
||||
resolveNs: typeof resolveNs;
|
||||
resolvePtr: typeof resolvePtr;
|
||||
resolveSoa: typeof resolveSoa;
|
||||
resolveSrv: typeof resolveSrv;
|
||||
resolveTlsa: typeof resolveTlsa;
|
||||
resolveTxt: typeof resolveTxt;
|
||||
reverse: typeof reverse;
|
||||
/**
|
||||
* The resolver instance will send its requests from the specified IP address.
|
||||
* This allows programs to specify outbound interfaces when used on multi-homed
|
||||
* systems.
|
||||
*
|
||||
* If a v4 or v6 address is not specified, it is set to the default and the
|
||||
* operating system will choose a local address automatically.
|
||||
*
|
||||
* The resolver will use the v4 local address when making requests to IPv4 DNS
|
||||
* servers, and the v6 local address when making requests to IPv6 DNS servers.
|
||||
* The `rrtype` of resolution requests has no impact on the local address used.
|
||||
* @since v15.1.0, v14.17.0
|
||||
* @param [ipv4='0.0.0.0'] A string representation of an IPv4 address.
|
||||
* @param [ipv6='::0'] A string representation of an IPv6 address.
|
||||
*/
|
||||
setLocalAddress(ipv4?: string, ipv6?: string): void;
|
||||
setServers: typeof setServers;
|
||||
}
|
||||
export { dnsPromises as promises };
|
||||
}
|
||||
declare module "node:dns" {
|
||||
export * from "dns";
|
||||
}
|
||||
503
node_modules/sitemap/node_modules/@types/node/dns/promises.d.ts
generated
vendored
Normal file
503
node_modules/sitemap/node_modules/@types/node/dns/promises.d.ts
generated
vendored
Normal file
@@ -0,0 +1,503 @@
|
||||
/**
|
||||
* The `dns.promises` API provides an alternative set of asynchronous DNS methods
|
||||
* that return `Promise` objects rather than using callbacks. The API is accessible
|
||||
* via `import { promises as dnsPromises } from 'node:dns'` or `import dnsPromises from 'node:dns/promises'`.
|
||||
* @since v10.6.0
|
||||
*/
|
||||
declare module "dns/promises" {
|
||||
import {
|
||||
AnyRecord,
|
||||
CaaRecord,
|
||||
LookupAddress,
|
||||
LookupAllOptions,
|
||||
LookupOneOptions,
|
||||
LookupOptions,
|
||||
MxRecord,
|
||||
NaptrRecord,
|
||||
RecordWithTtl,
|
||||
ResolveOptions,
|
||||
ResolverOptions,
|
||||
ResolveWithTtlOptions,
|
||||
SoaRecord,
|
||||
SrvRecord,
|
||||
TlsaRecord,
|
||||
} from "node:dns";
|
||||
/**
|
||||
* Returns an array of IP address strings, formatted according to [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6),
|
||||
* that are currently configured for DNS resolution. A string will include a port
|
||||
* section if a custom port is used.
|
||||
*
|
||||
* ```js
|
||||
* [
|
||||
* '4.4.4.4',
|
||||
* '2001:4860:4860::8888',
|
||||
* '4.4.4.4:1053',
|
||||
* '[2001:4860:4860::8888]:1053',
|
||||
* ]
|
||||
* ```
|
||||
* @since v10.6.0
|
||||
*/
|
||||
function getServers(): string[];
|
||||
/**
|
||||
* Resolves a host name (e.g. `'nodejs.org'`) into the first found A (IPv4) or
|
||||
* AAAA (IPv6) record. All `option` properties are optional. If `options` is an
|
||||
* integer, then it must be `4` or `6` – if `options` is not provided, then IPv4
|
||||
* and IPv6 addresses are both returned if found.
|
||||
*
|
||||
* With the `all` option set to `true`, the `Promise` is resolved with `addresses` being an array of objects with the properties `address` and `family`.
|
||||
*
|
||||
* On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code` is the error code.
|
||||
* Keep in mind that `err.code` will be set to `'ENOTFOUND'` not only when
|
||||
* the host name does not exist but also when the lookup fails in other ways
|
||||
* such as no available file descriptors.
|
||||
*
|
||||
* [`dnsPromises.lookup()`](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromiseslookuphostname-options) does not necessarily have anything to do with the DNS
|
||||
* protocol. The implementation uses an operating system facility that can
|
||||
* associate names with addresses and vice versa. This implementation can have
|
||||
* subtle but important consequences on the behavior of any Node.js program. Please
|
||||
* take some time to consult the [Implementation considerations section](https://nodejs.org/docs/latest-v20.x/api/dns.html#implementation-considerations) before
|
||||
* using `dnsPromises.lookup()`.
|
||||
*
|
||||
* Example usage:
|
||||
*
|
||||
* ```js
|
||||
* import dns from 'node:dns';
|
||||
* const dnsPromises = dns.promises;
|
||||
* const options = {
|
||||
* family: 6,
|
||||
* hints: dns.ADDRCONFIG | dns.V4MAPPED,
|
||||
* };
|
||||
*
|
||||
* dnsPromises.lookup('example.com', options).then((result) => {
|
||||
* console.log('address: %j family: IPv%s', result.address, result.family);
|
||||
* // address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6
|
||||
* });
|
||||
*
|
||||
* // When options.all is true, the result will be an Array.
|
||||
* options.all = true;
|
||||
* dnsPromises.lookup('example.com', options).then((result) => {
|
||||
* console.log('addresses: %j', result);
|
||||
* // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}]
|
||||
* });
|
||||
* ```
|
||||
* @since v10.6.0
|
||||
*/
|
||||
function lookup(hostname: string, family: number): Promise<LookupAddress>;
|
||||
function lookup(hostname: string, options: LookupOneOptions): Promise<LookupAddress>;
|
||||
function lookup(hostname: string, options: LookupAllOptions): Promise<LookupAddress[]>;
|
||||
function lookup(hostname: string, options: LookupOptions): Promise<LookupAddress | LookupAddress[]>;
|
||||
function lookup(hostname: string): Promise<LookupAddress>;
|
||||
/**
|
||||
* Resolves the given `address` and `port` into a host name and service using
|
||||
* the operating system's underlying `getnameinfo` implementation.
|
||||
*
|
||||
* If `address` is not a valid IP address, a `TypeError` will be thrown.
|
||||
* The `port` will be coerced to a number. If it is not a legal port, a `TypeError` will be thrown.
|
||||
*
|
||||
* On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code` is the error code.
|
||||
*
|
||||
* ```js
|
||||
* import dnsPromises from 'node:dns';
|
||||
* dnsPromises.lookupService('127.0.0.1', 22).then((result) => {
|
||||
* console.log(result.hostname, result.service);
|
||||
* // Prints: localhost ssh
|
||||
* });
|
||||
* ```
|
||||
* @since v10.6.0
|
||||
*/
|
||||
function lookupService(
|
||||
address: string,
|
||||
port: number,
|
||||
): Promise<{
|
||||
hostname: string;
|
||||
service: string;
|
||||
}>;
|
||||
/**
|
||||
* Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array
|
||||
* of the resource records. When successful, the `Promise` is resolved with an
|
||||
* array of resource records. The type and structure of individual results vary
|
||||
* based on `rrtype`:
|
||||
*
|
||||
* <omitted>
|
||||
*
|
||||
* On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code`
|
||||
* is one of the [DNS error codes](https://nodejs.org/docs/latest-v20.x/api/dns.html#error-codes).
|
||||
* @since v10.6.0
|
||||
* @param hostname Host name to resolve.
|
||||
* @param [rrtype='A'] Resource record type.
|
||||
*/
|
||||
function resolve(hostname: string): Promise<string[]>;
|
||||
function resolve(hostname: string, rrtype: "A" | "AAAA" | "CNAME" | "NS" | "PTR"): Promise<string[]>;
|
||||
function resolve(hostname: string, rrtype: "ANY"): Promise<AnyRecord[]>;
|
||||
function resolve(hostname: string, rrtype: "CAA"): Promise<CaaRecord[]>;
|
||||
function resolve(hostname: string, rrtype: "MX"): Promise<MxRecord[]>;
|
||||
function resolve(hostname: string, rrtype: "NAPTR"): Promise<NaptrRecord[]>;
|
||||
function resolve(hostname: string, rrtype: "SOA"): Promise<SoaRecord>;
|
||||
function resolve(hostname: string, rrtype: "SRV"): Promise<SrvRecord[]>;
|
||||
function resolve(hostname: string, rrtype: "TLSA"): Promise<TlsaRecord[]>;
|
||||
function resolve(hostname: string, rrtype: "TXT"): Promise<string[][]>;
|
||||
function resolve(hostname: string, rrtype: string): Promise<
|
||||
| string[]
|
||||
| CaaRecord[]
|
||||
| MxRecord[]
|
||||
| NaptrRecord[]
|
||||
| SoaRecord
|
||||
| SrvRecord[]
|
||||
| TlsaRecord[]
|
||||
| string[][]
|
||||
| AnyRecord[]
|
||||
>;
|
||||
/**
|
||||
* Uses the DNS protocol to resolve IPv4 addresses (`A` records) for the `hostname`. On success, the `Promise` is resolved with an array of IPv4
|
||||
* addresses (e.g. `['74.125.79.104', '74.125.79.105', '74.125.79.106']`).
|
||||
* @since v10.6.0
|
||||
* @param hostname Host name to resolve.
|
||||
*/
|
||||
function resolve4(hostname: string): Promise<string[]>;
|
||||
function resolve4(hostname: string, options: ResolveWithTtlOptions): Promise<RecordWithTtl[]>;
|
||||
function resolve4(hostname: string, options: ResolveOptions): Promise<string[] | RecordWithTtl[]>;
|
||||
/**
|
||||
* Uses the DNS protocol to resolve IPv6 addresses (`AAAA` records) for the `hostname`. On success, the `Promise` is resolved with an array of IPv6
|
||||
* addresses.
|
||||
* @since v10.6.0
|
||||
* @param hostname Host name to resolve.
|
||||
*/
|
||||
function resolve6(hostname: string): Promise<string[]>;
|
||||
function resolve6(hostname: string, options: ResolveWithTtlOptions): Promise<RecordWithTtl[]>;
|
||||
function resolve6(hostname: string, options: ResolveOptions): Promise<string[] | RecordWithTtl[]>;
|
||||
/**
|
||||
* Uses the DNS protocol to resolve all records (also known as `ANY` or `*` query).
|
||||
* On success, the `Promise` is resolved with an array containing various types of
|
||||
* records. Each object has a property `type` that indicates the type of the
|
||||
* current record. And depending on the `type`, additional properties will be
|
||||
* present on the object:
|
||||
*
|
||||
* <omitted>
|
||||
*
|
||||
* Here is an example of the result object:
|
||||
*
|
||||
* ```js
|
||||
* [ { type: 'A', address: '127.0.0.1', ttl: 299 },
|
||||
* { type: 'CNAME', value: 'example.com' },
|
||||
* { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 },
|
||||
* { type: 'NS', value: 'ns1.example.com' },
|
||||
* { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] },
|
||||
* { type: 'SOA',
|
||||
* nsname: 'ns1.example.com',
|
||||
* hostmaster: 'admin.example.com',
|
||||
* serial: 156696742,
|
||||
* refresh: 900,
|
||||
* retry: 900,
|
||||
* expire: 1800,
|
||||
* minttl: 60 } ]
|
||||
* ```
|
||||
* @since v10.6.0
|
||||
*/
|
||||
function resolveAny(hostname: string): Promise<AnyRecord[]>;
|
||||
/**
|
||||
* Uses the DNS protocol to resolve `CAA` records for the `hostname`. On success,
|
||||
* the `Promise` is resolved with an array of objects containing available
|
||||
* certification authority authorization records available for the `hostname` (e.g. `[{critical: 0, iodef: 'mailto:pki@example.com'},{critical: 128, issue: 'pki.example.com'}]`).
|
||||
* @since v15.0.0, v14.17.0
|
||||
*/
|
||||
function resolveCaa(hostname: string): Promise<CaaRecord[]>;
|
||||
/**
|
||||
* Uses the DNS protocol to resolve `CNAME` records for the `hostname`. On success,
|
||||
* the `Promise` is resolved with an array of canonical name records available for
|
||||
* the `hostname` (e.g. `['bar.example.com']`).
|
||||
* @since v10.6.0
|
||||
*/
|
||||
function resolveCname(hostname: string): Promise<string[]>;
|
||||
/**
|
||||
* Uses the DNS protocol to resolve mail exchange records (`MX` records) for the `hostname`. On success, the `Promise` is resolved with an array of objects
|
||||
* containing both a `priority` and `exchange` property (e.g.`[{priority: 10, exchange: 'mx.example.com'}, ...]`).
|
||||
* @since v10.6.0
|
||||
*/
|
||||
function resolveMx(hostname: string): Promise<MxRecord[]>;
|
||||
/**
|
||||
* Uses the DNS protocol to resolve regular expression-based records (`NAPTR` records) for the `hostname`. On success, the `Promise` is resolved with an array
|
||||
* of objects with the following properties:
|
||||
*
|
||||
* * `flags`
|
||||
* * `service`
|
||||
* * `regexp`
|
||||
* * `replacement`
|
||||
* * `order`
|
||||
* * `preference`
|
||||
*
|
||||
* ```js
|
||||
* {
|
||||
* flags: 's',
|
||||
* service: 'SIP+D2U',
|
||||
* regexp: '',
|
||||
* replacement: '_sip._udp.example.com',
|
||||
* order: 30,
|
||||
* preference: 100
|
||||
* }
|
||||
* ```
|
||||
* @since v10.6.0
|
||||
*/
|
||||
function resolveNaptr(hostname: string): Promise<NaptrRecord[]>;
|
||||
/**
|
||||
* Uses the DNS protocol to resolve name server records (`NS` records) for the `hostname`. On success, the `Promise` is resolved with an array of name server
|
||||
* records available for `hostname` (e.g.`['ns1.example.com', 'ns2.example.com']`).
|
||||
* @since v10.6.0
|
||||
*/
|
||||
function resolveNs(hostname: string): Promise<string[]>;
|
||||
/**
|
||||
* Uses the DNS protocol to resolve pointer records (`PTR` records) for the `hostname`. On success, the `Promise` is resolved with an array of strings
|
||||
* containing the reply records.
|
||||
* @since v10.6.0
|
||||
*/
|
||||
function resolvePtr(hostname: string): Promise<string[]>;
|
||||
/**
|
||||
* Uses the DNS protocol to resolve a start of authority record (`SOA` record) for
|
||||
* the `hostname`. On success, the `Promise` is resolved with an object with the
|
||||
* following properties:
|
||||
*
|
||||
* * `nsname`
|
||||
* * `hostmaster`
|
||||
* * `serial`
|
||||
* * `refresh`
|
||||
* * `retry`
|
||||
* * `expire`
|
||||
* * `minttl`
|
||||
*
|
||||
* ```js
|
||||
* {
|
||||
* nsname: 'ns.example.com',
|
||||
* hostmaster: 'root.example.com',
|
||||
* serial: 2013101809,
|
||||
* refresh: 10000,
|
||||
* retry: 2400,
|
||||
* expire: 604800,
|
||||
* minttl: 3600
|
||||
* }
|
||||
* ```
|
||||
* @since v10.6.0
|
||||
*/
|
||||
function resolveSoa(hostname: string): Promise<SoaRecord>;
|
||||
/**
|
||||
* Uses the DNS protocol to resolve service records (`SRV` records) for the `hostname`. On success, the `Promise` is resolved with an array of objects with
|
||||
* the following properties:
|
||||
*
|
||||
* * `priority`
|
||||
* * `weight`
|
||||
* * `port`
|
||||
* * `name`
|
||||
*
|
||||
* ```js
|
||||
* {
|
||||
* priority: 10,
|
||||
* weight: 5,
|
||||
* port: 21223,
|
||||
* name: 'service.example.com'
|
||||
* }
|
||||
* ```
|
||||
* @since v10.6.0
|
||||
*/
|
||||
function resolveSrv(hostname: string): Promise<SrvRecord[]>;
|
||||
/**
|
||||
* Uses the DNS protocol to resolve certificate associations (`TLSA` records) for
|
||||
* the `hostname`. On success, the `Promise` is resolved with an array of objectsAdd commentMore actions
|
||||
* with these properties:
|
||||
*
|
||||
* * `certUsage`
|
||||
* * `selector`
|
||||
* * `match`
|
||||
* * `data`
|
||||
*
|
||||
* ```js
|
||||
* {
|
||||
* certUsage: 3,
|
||||
* selector: 1,
|
||||
* match: 1,
|
||||
* data: [ArrayBuffer]
|
||||
* }
|
||||
* ```
|
||||
* @since v23.9.0, v22.15.0
|
||||
*/
|
||||
function resolveTlsa(hostname: string): Promise<TlsaRecord[]>;
|
||||
/**
|
||||
* Uses the DNS protocol to resolve text queries (`TXT` records) for the `hostname`. On success, the `Promise` is resolved with a two-dimensional array
|
||||
* of the text records available for `hostname` (e.g.`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of
|
||||
* one record. Depending on the use case, these could be either joined together or
|
||||
* treated separately.
|
||||
* @since v10.6.0
|
||||
*/
|
||||
function resolveTxt(hostname: string): Promise<string[][]>;
|
||||
/**
|
||||
* Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an
|
||||
* array of host names.
|
||||
*
|
||||
* On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code`
|
||||
* is one of the [DNS error codes](https://nodejs.org/docs/latest-v20.x/api/dns.html#error-codes).
|
||||
* @since v10.6.0
|
||||
*/
|
||||
function reverse(ip: string): Promise<string[]>;
|
||||
/**
|
||||
* Get the default value for `verbatim` in {@link lookup} and [dnsPromises.lookup()](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromiseslookuphostname-options).
|
||||
* The value could be:
|
||||
*
|
||||
* * `ipv4first`: for `verbatim` defaulting to `false`.
|
||||
* * `verbatim`: for `verbatim` defaulting to `true`.
|
||||
* @since v20.1.0
|
||||
*/
|
||||
function getDefaultResultOrder(): "ipv4first" | "verbatim";
|
||||
/**
|
||||
* Sets the IP address and port of servers to be used when performing DNS
|
||||
* resolution. The `servers` argument is an array of [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6) formatted
|
||||
* addresses. If the port is the IANA default DNS port (53) it can be omitted.
|
||||
*
|
||||
* ```js
|
||||
* dnsPromises.setServers([
|
||||
* '4.4.4.4',
|
||||
* '[2001:4860:4860::8888]',
|
||||
* '4.4.4.4:1053',
|
||||
* '[2001:4860:4860::8888]:1053',
|
||||
* ]);
|
||||
* ```
|
||||
*
|
||||
* An error will be thrown if an invalid address is provided.
|
||||
*
|
||||
* The `dnsPromises.setServers()` method must not be called while a DNS query is in
|
||||
* progress.
|
||||
*
|
||||
* This method works much like [resolve.conf](https://man7.org/linux/man-pages/man5/resolv.conf.5.html).
|
||||
* That is, if attempting to resolve with the first server provided results in a `NOTFOUND` error, the `resolve()` method will _not_ attempt to resolve with
|
||||
* subsequent servers provided. Fallback DNS servers will only be used if the
|
||||
* earlier ones time out or result in some other error.
|
||||
* @since v10.6.0
|
||||
* @param servers array of `RFC 5952` formatted addresses
|
||||
*/
|
||||
function setServers(servers: readonly string[]): void;
|
||||
/**
|
||||
* Set the default value of `order` in `dns.lookup()` and `{@link lookup}`. The value could be:
|
||||
*
|
||||
* * `ipv4first`: sets default `order` to `ipv4first`.
|
||||
* * `ipv6first`: sets default `order` to `ipv6first`.
|
||||
* * `verbatim`: sets default `order` to `verbatim`.
|
||||
*
|
||||
* The default is `verbatim` and [dnsPromises.setDefaultResultOrder()](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromisessetdefaultresultorderorder)
|
||||
* have higher priority than [`--dns-result-order`](https://nodejs.org/docs/latest-v20.x/api/cli.html#--dns-result-orderorder).
|
||||
* When using [worker threads](https://nodejs.org/docs/latest-v20.x/api/worker_threads.html), [`dnsPromises.setDefaultResultOrder()`](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromisessetdefaultresultorderorder)
|
||||
* from the main thread won't affect the default dns orders in workers.
|
||||
* @since v16.4.0, v14.18.0
|
||||
* @param order must be `'ipv4first'`, `'ipv6first'` or `'verbatim'`.
|
||||
*/
|
||||
function setDefaultResultOrder(order: "ipv4first" | "ipv6first" | "verbatim"): void;
|
||||
// Error codes
|
||||
const NODATA: "ENODATA";
|
||||
const FORMERR: "EFORMERR";
|
||||
const SERVFAIL: "ESERVFAIL";
|
||||
const NOTFOUND: "ENOTFOUND";
|
||||
const NOTIMP: "ENOTIMP";
|
||||
const REFUSED: "EREFUSED";
|
||||
const BADQUERY: "EBADQUERY";
|
||||
const BADNAME: "EBADNAME";
|
||||
const BADFAMILY: "EBADFAMILY";
|
||||
const BADRESP: "EBADRESP";
|
||||
const CONNREFUSED: "ECONNREFUSED";
|
||||
const TIMEOUT: "ETIMEOUT";
|
||||
const EOF: "EOF";
|
||||
const FILE: "EFILE";
|
||||
const NOMEM: "ENOMEM";
|
||||
const DESTRUCTION: "EDESTRUCTION";
|
||||
const BADSTR: "EBADSTR";
|
||||
const BADFLAGS: "EBADFLAGS";
|
||||
const NONAME: "ENONAME";
|
||||
const BADHINTS: "EBADHINTS";
|
||||
const NOTINITIALIZED: "ENOTINITIALIZED";
|
||||
const LOADIPHLPAPI: "ELOADIPHLPAPI";
|
||||
const ADDRGETNETWORKPARAMS: "EADDRGETNETWORKPARAMS";
|
||||
const CANCELLED: "ECANCELLED";
|
||||
|
||||
/**
|
||||
* An independent resolver for DNS requests.
|
||||
*
|
||||
* Creating a new resolver uses the default server settings. Setting
|
||||
* the servers used for a resolver using [`resolver.setServers()`](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromisessetserversservers) does not affect
|
||||
* other resolvers:
|
||||
*
|
||||
* ```js
|
||||
* import { promises } from 'node:dns';
|
||||
* const resolver = new promises.Resolver();
|
||||
* resolver.setServers(['4.4.4.4']);
|
||||
*
|
||||
* // This request will use the server at 4.4.4.4, independent of global settings.
|
||||
* resolver.resolve4('example.org').then((addresses) => {
|
||||
* // ...
|
||||
* });
|
||||
*
|
||||
* // Alternatively, the same code can be written using async-await style.
|
||||
* (async function() {
|
||||
* const addresses = await resolver.resolve4('example.org');
|
||||
* })();
|
||||
* ```
|
||||
*
|
||||
* The following methods from the `dnsPromises` API are available:
|
||||
*
|
||||
* * `resolver.getServers()`
|
||||
* * `resolver.resolve()`
|
||||
* * `resolver.resolve4()`
|
||||
* * `resolver.resolve6()`
|
||||
* * `resolver.resolveAny()`
|
||||
* * `resolver.resolveCaa()`
|
||||
* * `resolver.resolveCname()`
|
||||
* * `resolver.resolveMx()`
|
||||
* * `resolver.resolveNaptr()`
|
||||
* * `resolver.resolveNs()`
|
||||
* * `resolver.resolvePtr()`
|
||||
* * `resolver.resolveSoa()`
|
||||
* * `resolver.resolveSrv()`
|
||||
* * `resolver.resolveTxt()`
|
||||
* * `resolver.reverse()`
|
||||
* * `resolver.setServers()`
|
||||
* @since v10.6.0
|
||||
*/
|
||||
class Resolver {
|
||||
constructor(options?: ResolverOptions);
|
||||
/**
|
||||
* Cancel all outstanding DNS queries made by this resolver. The corresponding
|
||||
* callbacks will be called with an error with code `ECANCELLED`.
|
||||
* @since v8.3.0
|
||||
*/
|
||||
cancel(): void;
|
||||
getServers: typeof getServers;
|
||||
resolve: typeof resolve;
|
||||
resolve4: typeof resolve4;
|
||||
resolve6: typeof resolve6;
|
||||
resolveAny: typeof resolveAny;
|
||||
resolveCaa: typeof resolveCaa;
|
||||
resolveCname: typeof resolveCname;
|
||||
resolveMx: typeof resolveMx;
|
||||
resolveNaptr: typeof resolveNaptr;
|
||||
resolveNs: typeof resolveNs;
|
||||
resolvePtr: typeof resolvePtr;
|
||||
resolveSoa: typeof resolveSoa;
|
||||
resolveSrv: typeof resolveSrv;
|
||||
resolveTlsa: typeof resolveTlsa;
|
||||
resolveTxt: typeof resolveTxt;
|
||||
reverse: typeof reverse;
|
||||
/**
|
||||
* The resolver instance will send its requests from the specified IP address.
|
||||
* This allows programs to specify outbound interfaces when used on multi-homed
|
||||
* systems.
|
||||
*
|
||||
* If a v4 or v6 address is not specified, it is set to the default and the
|
||||
* operating system will choose a local address automatically.
|
||||
*
|
||||
* The resolver will use the v4 local address when making requests to IPv4 DNS
|
||||
* servers, and the v6 local address when making requests to IPv6 DNS servers.
|
||||
* The `rrtype` of resolution requests has no impact on the local address used.
|
||||
* @since v15.1.0, v14.17.0
|
||||
* @param [ipv4='0.0.0.0'] A string representation of an IPv4 address.
|
||||
* @param [ipv6='::0'] A string representation of an IPv6 address.
|
||||
*/
|
||||
setLocalAddress(ipv4?: string, ipv6?: string): void;
|
||||
setServers: typeof setServers;
|
||||
}
|
||||
}
|
||||
declare module "node:dns/promises" {
|
||||
export * from "dns/promises";
|
||||
}
|
||||
170
node_modules/sitemap/node_modules/@types/node/domain.d.ts
generated
vendored
Normal file
170
node_modules/sitemap/node_modules/@types/node/domain.d.ts
generated
vendored
Normal file
@@ -0,0 +1,170 @@
|
||||
/**
|
||||
* **This module is pending deprecation.** Once a replacement API has been
|
||||
* finalized, this module will be fully deprecated. Most developers should
|
||||
* **not** have cause to use this module. Users who absolutely must have
|
||||
* the functionality that domains provide may rely on it for the time being
|
||||
* but should expect to have to migrate to a different solution
|
||||
* in the future.
|
||||
*
|
||||
* Domains provide a way to handle multiple different IO operations as a
|
||||
* single group. If any of the event emitters or callbacks registered to a
|
||||
* domain emit an `'error'` event, or throw an error, then the domain object
|
||||
* will be notified, rather than losing the context of the error in the `process.on('uncaughtException')` handler, or causing the program to
|
||||
* exit immediately with an error code.
|
||||
* @deprecated Since v1.4.2 - Deprecated
|
||||
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/domain.js)
|
||||
*/
|
||||
declare module "domain" {
|
||||
import EventEmitter = require("node:events");
|
||||
/**
|
||||
* The `Domain` class encapsulates the functionality of routing errors and
|
||||
* uncaught exceptions to the active `Domain` object.
|
||||
*
|
||||
* To handle the errors that it catches, listen to its `'error'` event.
|
||||
*/
|
||||
class Domain extends EventEmitter {
|
||||
/**
|
||||
* An array of timers and event emitters that have been explicitly added
|
||||
* to the domain.
|
||||
*/
|
||||
members: Array<EventEmitter | NodeJS.Timer>;
|
||||
/**
|
||||
* The `enter()` method is plumbing used by the `run()`, `bind()`, and `intercept()` methods to set the active domain. It sets `domain.active` and `process.domain` to the domain, and implicitly
|
||||
* pushes the domain onto the domain
|
||||
* stack managed by the domain module (see {@link exit} for details on the
|
||||
* domain stack). The call to `enter()` delimits the beginning of a chain of
|
||||
* asynchronous calls and I/O operations bound to a domain.
|
||||
*
|
||||
* Calling `enter()` changes only the active domain, and does not alter the domain
|
||||
* itself. `enter()` and `exit()` can be called an arbitrary number of times on a
|
||||
* single domain.
|
||||
*/
|
||||
enter(): void;
|
||||
/**
|
||||
* The `exit()` method exits the current domain, popping it off the domain stack.
|
||||
* Any time execution is going to switch to the context of a different chain of
|
||||
* asynchronous calls, it's important to ensure that the current domain is exited.
|
||||
* The call to `exit()` delimits either the end of or an interruption to the chain
|
||||
* of asynchronous calls and I/O operations bound to a domain.
|
||||
*
|
||||
* If there are multiple, nested domains bound to the current execution context, `exit()` will exit any domains nested within this domain.
|
||||
*
|
||||
* Calling `exit()` changes only the active domain, and does not alter the domain
|
||||
* itself. `enter()` and `exit()` can be called an arbitrary number of times on a
|
||||
* single domain.
|
||||
*/
|
||||
exit(): void;
|
||||
/**
|
||||
* Run the supplied function in the context of the domain, implicitly
|
||||
* binding all event emitters, timers, and low-level requests that are
|
||||
* created in that context. Optionally, arguments can be passed to
|
||||
* the function.
|
||||
*
|
||||
* This is the most basic way to use a domain.
|
||||
*
|
||||
* ```js
|
||||
* import domain from 'node:domain';
|
||||
* import fs from 'node:fs';
|
||||
* const d = domain.create();
|
||||
* d.on('error', (er) => {
|
||||
* console.error('Caught error!', er);
|
||||
* });
|
||||
* d.run(() => {
|
||||
* process.nextTick(() => {
|
||||
* setTimeout(() => { // Simulating some various async stuff
|
||||
* fs.open('non-existent file', 'r', (er, fd) => {
|
||||
* if (er) throw er;
|
||||
* // proceed...
|
||||
* });
|
||||
* }, 100);
|
||||
* });
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* In this example, the `d.on('error')` handler will be triggered, rather
|
||||
* than crashing the program.
|
||||
*/
|
||||
run<T>(fn: (...args: any[]) => T, ...args: any[]): T;
|
||||
/**
|
||||
* Explicitly adds an emitter to the domain. If any event handlers called by
|
||||
* the emitter throw an error, or if the emitter emits an `'error'` event, it
|
||||
* will be routed to the domain's `'error'` event, just like with implicit
|
||||
* binding.
|
||||
*
|
||||
* This also works with timers that are returned from `setInterval()` and `setTimeout()`. If their callback function throws, it will be caught by
|
||||
* the domain `'error'` handler.
|
||||
*
|
||||
* If the Timer or `EventEmitter` was already bound to a domain, it is removed
|
||||
* from that one, and bound to this one instead.
|
||||
* @param emitter emitter or timer to be added to the domain
|
||||
*/
|
||||
add(emitter: EventEmitter | NodeJS.Timer): void;
|
||||
/**
|
||||
* The opposite of {@link add}. Removes domain handling from the
|
||||
* specified emitter.
|
||||
* @param emitter emitter or timer to be removed from the domain
|
||||
*/
|
||||
remove(emitter: EventEmitter | NodeJS.Timer): void;
|
||||
/**
|
||||
* The returned function will be a wrapper around the supplied callback
|
||||
* function. When the returned function is called, any errors that are
|
||||
* thrown will be routed to the domain's `'error'` event.
|
||||
*
|
||||
* ```js
|
||||
* const d = domain.create();
|
||||
*
|
||||
* function readSomeFile(filename, cb) {
|
||||
* fs.readFile(filename, 'utf8', d.bind((er, data) => {
|
||||
* // If this throws, it will also be passed to the domain.
|
||||
* return cb(er, data ? JSON.parse(data) : null);
|
||||
* }));
|
||||
* }
|
||||
*
|
||||
* d.on('error', (er) => {
|
||||
* // An error occurred somewhere. If we throw it now, it will crash the program
|
||||
* // with the normal line number and stack message.
|
||||
* });
|
||||
* ```
|
||||
* @param callback The callback function
|
||||
* @return The bound function
|
||||
*/
|
||||
bind<T extends Function>(callback: T): T;
|
||||
/**
|
||||
* This method is almost identical to {@link bind}. However, in
|
||||
* addition to catching thrown errors, it will also intercept `Error` objects sent as the first argument to the function.
|
||||
*
|
||||
* In this way, the common `if (err) return callback(err);` pattern can be replaced
|
||||
* with a single error handler in a single place.
|
||||
*
|
||||
* ```js
|
||||
* const d = domain.create();
|
||||
*
|
||||
* function readSomeFile(filename, cb) {
|
||||
* fs.readFile(filename, 'utf8', d.intercept((data) => {
|
||||
* // Note, the first argument is never passed to the
|
||||
* // callback since it is assumed to be the 'Error' argument
|
||||
* // and thus intercepted by the domain.
|
||||
*
|
||||
* // If this throws, it will also be passed to the domain
|
||||
* // so the error-handling logic can be moved to the 'error'
|
||||
* // event on the domain instead of being repeated throughout
|
||||
* // the program.
|
||||
* return cb(null, JSON.parse(data));
|
||||
* }));
|
||||
* }
|
||||
*
|
||||
* d.on('error', (er) => {
|
||||
* // An error occurred somewhere. If we throw it now, it will crash the program
|
||||
* // with the normal line number and stack message.
|
||||
* });
|
||||
* ```
|
||||
* @param callback The callback function
|
||||
* @return The intercepted function
|
||||
*/
|
||||
intercept<T extends Function>(callback: T): T;
|
||||
}
|
||||
function create(): Domain;
|
||||
}
|
||||
declare module "node:domain" {
|
||||
export * from "domain";
|
||||
}
|
||||
976
node_modules/sitemap/node_modules/@types/node/events.d.ts
generated
vendored
Normal file
976
node_modules/sitemap/node_modules/@types/node/events.d.ts
generated
vendored
Normal file
@@ -0,0 +1,976 @@
|
||||
/**
|
||||
* Much of the Node.js core API is built around an idiomatic asynchronous
|
||||
* event-driven architecture in which certain kinds of objects (called "emitters")
|
||||
* emit named events that cause `Function` objects ("listeners") to be called.
|
||||
*
|
||||
* For instance: a `net.Server` object emits an event each time a peer
|
||||
* connects to it; a `fs.ReadStream` emits an event when the file is opened;
|
||||
* a `stream` emits an event whenever data is available to be read.
|
||||
*
|
||||
* All objects that emit events are instances of the `EventEmitter` class. These
|
||||
* objects expose an `eventEmitter.on()` function that allows one or more
|
||||
* functions to be attached to named events emitted by the object. Typically,
|
||||
* event names are camel-cased strings but any valid JavaScript property key
|
||||
* can be used.
|
||||
*
|
||||
* When the `EventEmitter` object emits an event, all of the functions attached
|
||||
* to that specific event are called _synchronously_. Any values returned by the
|
||||
* called listeners are _ignored_ and discarded.
|
||||
*
|
||||
* The following example shows a simple `EventEmitter` instance with a single
|
||||
* listener. The `eventEmitter.on()` method is used to register listeners, while
|
||||
* the `eventEmitter.emit()` method is used to trigger the event.
|
||||
*
|
||||
* ```js
|
||||
* import { EventEmitter } from 'node:events';
|
||||
*
|
||||
* class MyEmitter extends EventEmitter {}
|
||||
*
|
||||
* const myEmitter = new MyEmitter();
|
||||
* myEmitter.on('event', () => {
|
||||
* console.log('an event occurred!');
|
||||
* });
|
||||
* myEmitter.emit('event');
|
||||
* ```
|
||||
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/events.js)
|
||||
*/
|
||||
declare module "events" {
|
||||
import { AsyncResource, AsyncResourceOptions } from "node:async_hooks";
|
||||
interface EventEmitterOptions {
|
||||
/**
|
||||
* Enables automatic capturing of promise rejection.
|
||||
*/
|
||||
captureRejections?: boolean | undefined;
|
||||
}
|
||||
interface StaticEventEmitterOptions {
|
||||
/**
|
||||
* Can be used to cancel awaiting events.
|
||||
*/
|
||||
signal?: AbortSignal | undefined;
|
||||
}
|
||||
interface StaticEventEmitterIteratorOptions extends StaticEventEmitterOptions {
|
||||
/**
|
||||
* Names of events that will end the iteration.
|
||||
*/
|
||||
close?: string[] | undefined;
|
||||
/**
|
||||
* The high watermark. The emitter is paused every time the size of events being buffered is higher than it.
|
||||
* Supported only on emitters implementing `pause()` and `resume()` methods.
|
||||
* @default Number.MAX_SAFE_INTEGER
|
||||
*/
|
||||
highWaterMark?: number | undefined;
|
||||
/**
|
||||
* The low watermark. The emitter is resumed every time the size of events being buffered is lower than it.
|
||||
* Supported only on emitters implementing `pause()` and `resume()` methods.
|
||||
* @default 1
|
||||
*/
|
||||
lowWaterMark?: number | undefined;
|
||||
}
|
||||
interface EventEmitter<T extends EventMap<T> = DefaultEventMap> extends NodeJS.EventEmitter<T> {}
|
||||
type EventMap<T> = Record<keyof T, any[]> | DefaultEventMap;
|
||||
type DefaultEventMap = [never];
|
||||
type AnyRest = [...args: any[]];
|
||||
type Args<K, T> = T extends DefaultEventMap ? AnyRest : (
|
||||
K extends keyof T ? T[K] : never
|
||||
);
|
||||
type Key<K, T> = T extends DefaultEventMap ? string | symbol : K | keyof T;
|
||||
type Key2<K, T> = T extends DefaultEventMap ? string | symbol : K & keyof T;
|
||||
type Listener<K, T, F> = T extends DefaultEventMap ? F : (
|
||||
K extends keyof T ? (
|
||||
T[K] extends unknown[] ? (...args: T[K]) => void : never
|
||||
)
|
||||
: never
|
||||
);
|
||||
type Listener1<K, T> = Listener<K, T, (...args: any[]) => void>;
|
||||
type Listener2<K, T> = Listener<K, T, Function>;
|
||||
|
||||
/**
|
||||
* The `EventEmitter` class is defined and exposed by the `node:events` module:
|
||||
*
|
||||
* ```js
|
||||
* import { EventEmitter } from 'node:events';
|
||||
* ```
|
||||
*
|
||||
* All `EventEmitter`s emit the event `'newListener'` when new listeners are
|
||||
* added and `'removeListener'` when existing listeners are removed.
|
||||
*
|
||||
* It supports the following option:
|
||||
* @since v0.1.26
|
||||
*/
|
||||
class EventEmitter<T extends EventMap<T> = DefaultEventMap> {
|
||||
constructor(options?: EventEmitterOptions);
|
||||
|
||||
[EventEmitter.captureRejectionSymbol]?<K>(error: Error, event: Key<K, T>, ...args: Args<K, T>): void;
|
||||
|
||||
/**
|
||||
* Creates a `Promise` that is fulfilled when the `EventEmitter` emits the given
|
||||
* event or that is rejected if the `EventEmitter` emits `'error'` while waiting.
|
||||
* The `Promise` will resolve with an array of all the arguments emitted to the
|
||||
* given event.
|
||||
*
|
||||
* This method is intentionally generic and works with the web platform [EventTarget](https://dom.spec.whatwg.org/#interface-eventtarget) interface, which has no special`'error'` event
|
||||
* semantics and does not listen to the `'error'` event.
|
||||
*
|
||||
* ```js
|
||||
* import { once, EventEmitter } from 'node:events';
|
||||
* import process from 'node:process';
|
||||
*
|
||||
* const ee = new EventEmitter();
|
||||
*
|
||||
* process.nextTick(() => {
|
||||
* ee.emit('myevent', 42);
|
||||
* });
|
||||
*
|
||||
* const [value] = await once(ee, 'myevent');
|
||||
* console.log(value);
|
||||
*
|
||||
* const err = new Error('kaboom');
|
||||
* process.nextTick(() => {
|
||||
* ee.emit('error', err);
|
||||
* });
|
||||
*
|
||||
* try {
|
||||
* await once(ee, 'myevent');
|
||||
* } catch (err) {
|
||||
* console.error('error happened', err);
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* The special handling of the `'error'` event is only used when `events.once()` is used to wait for another event. If `events.once()` is used to wait for the
|
||||
* '`error'` event itself, then it is treated as any other kind of event without
|
||||
* special handling:
|
||||
*
|
||||
* ```js
|
||||
* import { EventEmitter, once } from 'node:events';
|
||||
*
|
||||
* const ee = new EventEmitter();
|
||||
*
|
||||
* once(ee, 'error')
|
||||
* .then(([err]) => console.log('ok', err.message))
|
||||
* .catch((err) => console.error('error', err.message));
|
||||
*
|
||||
* ee.emit('error', new Error('boom'));
|
||||
*
|
||||
* // Prints: ok boom
|
||||
* ```
|
||||
*
|
||||
* An `AbortSignal` can be used to cancel waiting for the event:
|
||||
*
|
||||
* ```js
|
||||
* import { EventEmitter, once } from 'node:events';
|
||||
*
|
||||
* const ee = new EventEmitter();
|
||||
* const ac = new AbortController();
|
||||
*
|
||||
* async function foo(emitter, event, signal) {
|
||||
* try {
|
||||
* await once(emitter, event, { signal });
|
||||
* console.log('event emitted!');
|
||||
* } catch (error) {
|
||||
* if (error.name === 'AbortError') {
|
||||
* console.error('Waiting for the event was canceled!');
|
||||
* } else {
|
||||
* console.error('There was an error', error.message);
|
||||
* }
|
||||
* }
|
||||
* }
|
||||
*
|
||||
* foo(ee, 'foo', ac.signal);
|
||||
* ac.abort(); // Abort waiting for the event
|
||||
* ee.emit('foo'); // Prints: Waiting for the event was canceled!
|
||||
* ```
|
||||
* @since v11.13.0, v10.16.0
|
||||
*/
|
||||
static once(
|
||||
emitter: NodeJS.EventEmitter,
|
||||
eventName: string | symbol,
|
||||
options?: StaticEventEmitterOptions,
|
||||
): Promise<any[]>;
|
||||
static once(emitter: EventTarget, eventName: string, options?: StaticEventEmitterOptions): Promise<any[]>;
|
||||
/**
|
||||
* ```js
|
||||
* import { on, EventEmitter } from 'node:events';
|
||||
* import process from 'node:process';
|
||||
*
|
||||
* const ee = new EventEmitter();
|
||||
*
|
||||
* // Emit later on
|
||||
* process.nextTick(() => {
|
||||
* ee.emit('foo', 'bar');
|
||||
* ee.emit('foo', 42);
|
||||
* });
|
||||
*
|
||||
* for await (const event of on(ee, 'foo')) {
|
||||
* // The execution of this inner block is synchronous and it
|
||||
* // processes one event at a time (even with await). Do not use
|
||||
* // if concurrent execution is required.
|
||||
* console.log(event); // prints ['bar'] [42]
|
||||
* }
|
||||
* // Unreachable here
|
||||
* ```
|
||||
*
|
||||
* Returns an `AsyncIterator` that iterates `eventName` events. It will throw
|
||||
* if the `EventEmitter` emits `'error'`. It removes all listeners when
|
||||
* exiting the loop. The `value` returned by each iteration is an array
|
||||
* composed of the emitted event arguments.
|
||||
*
|
||||
* An `AbortSignal` can be used to cancel waiting on events:
|
||||
*
|
||||
* ```js
|
||||
* import { on, EventEmitter } from 'node:events';
|
||||
* import process from 'node:process';
|
||||
*
|
||||
* const ac = new AbortController();
|
||||
*
|
||||
* (async () => {
|
||||
* const ee = new EventEmitter();
|
||||
*
|
||||
* // Emit later on
|
||||
* process.nextTick(() => {
|
||||
* ee.emit('foo', 'bar');
|
||||
* ee.emit('foo', 42);
|
||||
* });
|
||||
*
|
||||
* for await (const event of on(ee, 'foo', { signal: ac.signal })) {
|
||||
* // The execution of this inner block is synchronous and it
|
||||
* // processes one event at a time (even with await). Do not use
|
||||
* // if concurrent execution is required.
|
||||
* console.log(event); // prints ['bar'] [42]
|
||||
* }
|
||||
* // Unreachable here
|
||||
* })();
|
||||
*
|
||||
* process.nextTick(() => ac.abort());
|
||||
* ```
|
||||
*
|
||||
* Use the `close` option to specify an array of event names that will end the iteration:
|
||||
*
|
||||
* ```js
|
||||
* import { on, EventEmitter } from 'node:events';
|
||||
* import process from 'node:process';
|
||||
*
|
||||
* const ee = new EventEmitter();
|
||||
*
|
||||
* // Emit later on
|
||||
* process.nextTick(() => {
|
||||
* ee.emit('foo', 'bar');
|
||||
* ee.emit('foo', 42);
|
||||
* ee.emit('close');
|
||||
* });
|
||||
*
|
||||
* for await (const event of on(ee, 'foo', { close: ['close'] })) {
|
||||
* console.log(event); // prints ['bar'] [42]
|
||||
* }
|
||||
* // the loop will exit after 'close' is emitted
|
||||
* console.log('done'); // prints 'done'
|
||||
* ```
|
||||
* @since v13.6.0, v12.16.0
|
||||
* @return An `AsyncIterator` that iterates `eventName` events emitted by the `emitter`
|
||||
*/
|
||||
static on(
|
||||
emitter: NodeJS.EventEmitter,
|
||||
eventName: string | symbol,
|
||||
options?: StaticEventEmitterIteratorOptions,
|
||||
): NodeJS.AsyncIterator<any[]>;
|
||||
static on(
|
||||
emitter: EventTarget,
|
||||
eventName: string,
|
||||
options?: StaticEventEmitterIteratorOptions,
|
||||
): NodeJS.AsyncIterator<any[]>;
|
||||
/**
|
||||
* A class method that returns the number of listeners for the given `eventName` registered on the given `emitter`.
|
||||
*
|
||||
* ```js
|
||||
* import { EventEmitter, listenerCount } from 'node:events';
|
||||
*
|
||||
* const myEmitter = new EventEmitter();
|
||||
* myEmitter.on('event', () => {});
|
||||
* myEmitter.on('event', () => {});
|
||||
* console.log(listenerCount(myEmitter, 'event'));
|
||||
* // Prints: 2
|
||||
* ```
|
||||
* @since v0.9.12
|
||||
* @deprecated Since v3.2.0 - Use `listenerCount` instead.
|
||||
* @param emitter The emitter to query
|
||||
* @param eventName The event name
|
||||
*/
|
||||
static listenerCount(emitter: NodeJS.EventEmitter, eventName: string | symbol): number;
|
||||
/**
|
||||
* Returns a copy of the array of listeners for the event named `eventName`.
|
||||
*
|
||||
* For `EventEmitter`s this behaves exactly the same as calling `.listeners` on
|
||||
* the emitter.
|
||||
*
|
||||
* For `EventTarget`s this is the only way to get the event listeners for the
|
||||
* event target. This is useful for debugging and diagnostic purposes.
|
||||
*
|
||||
* ```js
|
||||
* import { getEventListeners, EventEmitter } from 'node:events';
|
||||
*
|
||||
* {
|
||||
* const ee = new EventEmitter();
|
||||
* const listener = () => console.log('Events are fun');
|
||||
* ee.on('foo', listener);
|
||||
* console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ]
|
||||
* }
|
||||
* {
|
||||
* const et = new EventTarget();
|
||||
* const listener = () => console.log('Events are fun');
|
||||
* et.addEventListener('foo', listener);
|
||||
* console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ]
|
||||
* }
|
||||
* ```
|
||||
* @since v15.2.0, v14.17.0
|
||||
*/
|
||||
static getEventListeners(emitter: EventTarget | NodeJS.EventEmitter, name: string | symbol): Function[];
|
||||
/**
|
||||
* Returns the currently set max amount of listeners.
|
||||
*
|
||||
* For `EventEmitter`s this behaves exactly the same as calling `.getMaxListeners` on
|
||||
* the emitter.
|
||||
*
|
||||
* For `EventTarget`s this is the only way to get the max event listeners for the
|
||||
* event target. If the number of event handlers on a single EventTarget exceeds
|
||||
* the max set, the EventTarget will print a warning.
|
||||
*
|
||||
* ```js
|
||||
* import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events';
|
||||
*
|
||||
* {
|
||||
* const ee = new EventEmitter();
|
||||
* console.log(getMaxListeners(ee)); // 10
|
||||
* setMaxListeners(11, ee);
|
||||
* console.log(getMaxListeners(ee)); // 11
|
||||
* }
|
||||
* {
|
||||
* const et = new EventTarget();
|
||||
* console.log(getMaxListeners(et)); // 10
|
||||
* setMaxListeners(11, et);
|
||||
* console.log(getMaxListeners(et)); // 11
|
||||
* }
|
||||
* ```
|
||||
* @since v19.9.0
|
||||
*/
|
||||
static getMaxListeners(emitter: EventTarget | NodeJS.EventEmitter): number;
|
||||
/**
|
||||
* ```js
|
||||
* import { setMaxListeners, EventEmitter } from 'node:events';
|
||||
*
|
||||
* const target = new EventTarget();
|
||||
* const emitter = new EventEmitter();
|
||||
*
|
||||
* setMaxListeners(5, target, emitter);
|
||||
* ```
|
||||
* @since v15.4.0
|
||||
* @param n A non-negative number. The maximum number of listeners per `EventTarget` event.
|
||||
* @param eventTargets Zero or more {EventTarget} or {EventEmitter} instances. If none are specified, `n` is set as the default max for all newly created {EventTarget} and {EventEmitter}
|
||||
* objects.
|
||||
*/
|
||||
static setMaxListeners(n?: number, ...eventTargets: Array<EventTarget | NodeJS.EventEmitter>): void;
|
||||
/**
|
||||
* Listens once to the `abort` event on the provided `signal`.
|
||||
*
|
||||
* Listening to the `abort` event on abort signals is unsafe and may
|
||||
* lead to resource leaks since another third party with the signal can
|
||||
* call `e.stopImmediatePropagation()`. Unfortunately Node.js cannot change
|
||||
* this since it would violate the web standard. Additionally, the original
|
||||
* API makes it easy to forget to remove listeners.
|
||||
*
|
||||
* This API allows safely using `AbortSignal`s in Node.js APIs by solving these
|
||||
* two issues by listening to the event such that `stopImmediatePropagation` does
|
||||
* not prevent the listener from running.
|
||||
*
|
||||
* Returns a disposable so that it may be unsubscribed from more easily.
|
||||
*
|
||||
* ```js
|
||||
* import { addAbortListener } from 'node:events';
|
||||
*
|
||||
* function example(signal) {
|
||||
* let disposable;
|
||||
* try {
|
||||
* signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
|
||||
* disposable = addAbortListener(signal, (e) => {
|
||||
* // Do something when signal is aborted.
|
||||
* });
|
||||
* } finally {
|
||||
* disposable?.[Symbol.dispose]();
|
||||
* }
|
||||
* }
|
||||
* ```
|
||||
* @since v20.5.0
|
||||
* @return Disposable that removes the `abort` listener.
|
||||
*/
|
||||
static addAbortListener(signal: AbortSignal, resource: (event: Event) => void): Disposable;
|
||||
/**
|
||||
* This symbol shall be used to install a listener for only monitoring `'error'` events. Listeners installed using this symbol are called before the regular `'error'` listeners are called.
|
||||
*
|
||||
* Installing a listener using this symbol does not change the behavior once an `'error'` event is emitted. Therefore, the process will still crash if no
|
||||
* regular `'error'` listener is installed.
|
||||
* @since v13.6.0, v12.17.0
|
||||
*/
|
||||
static readonly errorMonitor: unique symbol;
|
||||
/**
|
||||
* Value: `Symbol.for('nodejs.rejection')`
|
||||
*
|
||||
* See how to write a custom `rejection handler`.
|
||||
* @since v13.4.0, v12.16.0
|
||||
*/
|
||||
static readonly captureRejectionSymbol: unique symbol;
|
||||
/**
|
||||
* Value: [boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
|
||||
*
|
||||
* Change the default `captureRejections` option on all new `EventEmitter` objects.
|
||||
* @since v13.4.0, v12.16.0
|
||||
*/
|
||||
static captureRejections: boolean;
|
||||
/**
|
||||
* By default, a maximum of `10` listeners can be registered for any single
|
||||
* event. This limit can be changed for individual `EventEmitter` instances
|
||||
* using the `emitter.setMaxListeners(n)` method. To change the default
|
||||
* for _all_`EventEmitter` instances, the `events.defaultMaxListeners` property
|
||||
* can be used. If this value is not a positive number, a `RangeError` is thrown.
|
||||
*
|
||||
* Take caution when setting the `events.defaultMaxListeners` because the
|
||||
* change affects _all_ `EventEmitter` instances, including those created before
|
||||
* the change is made. However, calling `emitter.setMaxListeners(n)` still has
|
||||
* precedence over `events.defaultMaxListeners`.
|
||||
*
|
||||
* This is not a hard limit. The `EventEmitter` instance will allow
|
||||
* more listeners to be added but will output a trace warning to stderr indicating
|
||||
* that a "possible EventEmitter memory leak" has been detected. For any single
|
||||
* `EventEmitter`, the `emitter.getMaxListeners()` and `emitter.setMaxListeners()` methods can be used to
|
||||
* temporarily avoid this warning:
|
||||
*
|
||||
* ```js
|
||||
* import { EventEmitter } from 'node:events';
|
||||
* const emitter = new EventEmitter();
|
||||
* emitter.setMaxListeners(emitter.getMaxListeners() + 1);
|
||||
* emitter.once('event', () => {
|
||||
* // do stuff
|
||||
* emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* The `--trace-warnings` command-line flag can be used to display the
|
||||
* stack trace for such warnings.
|
||||
*
|
||||
* The emitted warning can be inspected with `process.on('warning')` and will
|
||||
* have the additional `emitter`, `type`, and `count` properties, referring to
|
||||
* the event emitter instance, the event's name and the number of attached
|
||||
* listeners, respectively.
|
||||
* Its `name` property is set to `'MaxListenersExceededWarning'`.
|
||||
* @since v0.11.2
|
||||
*/
|
||||
static defaultMaxListeners: number;
|
||||
}
|
||||
import internal = require("node:events");
|
||||
namespace EventEmitter {
|
||||
// Should just be `export { EventEmitter }`, but that doesn't work in TypeScript 3.4
|
||||
export { internal as EventEmitter };
|
||||
export interface Abortable {
|
||||
/**
|
||||
* When provided the corresponding `AbortController` can be used to cancel an asynchronous action.
|
||||
*/
|
||||
signal?: AbortSignal | undefined;
|
||||
}
|
||||
|
||||
export interface EventEmitterReferencingAsyncResource extends AsyncResource {
|
||||
readonly eventEmitter: EventEmitterAsyncResource;
|
||||
}
|
||||
|
||||
export interface EventEmitterAsyncResourceOptions extends AsyncResourceOptions, EventEmitterOptions {
|
||||
/**
|
||||
* The type of async event, this is required when instantiating `EventEmitterAsyncResource`
|
||||
* directly rather than as a child class.
|
||||
* @default new.target.name if instantiated as a child class.
|
||||
*/
|
||||
name?: string | undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Integrates `EventEmitter` with `AsyncResource` for `EventEmitter`s that
|
||||
* require manual async tracking. Specifically, all events emitted by instances
|
||||
* of `events.EventEmitterAsyncResource` will run within its `async context`.
|
||||
*
|
||||
* ```js
|
||||
* import { EventEmitterAsyncResource, EventEmitter } from 'node:events';
|
||||
* import { notStrictEqual, strictEqual } from 'node:assert';
|
||||
* import { executionAsyncId, triggerAsyncId } from 'node:async_hooks';
|
||||
*
|
||||
* // Async tracking tooling will identify this as 'Q'.
|
||||
* const ee1 = new EventEmitterAsyncResource({ name: 'Q' });
|
||||
*
|
||||
* // 'foo' listeners will run in the EventEmitters async context.
|
||||
* ee1.on('foo', () => {
|
||||
* strictEqual(executionAsyncId(), ee1.asyncId);
|
||||
* strictEqual(triggerAsyncId(), ee1.triggerAsyncId);
|
||||
* });
|
||||
*
|
||||
* const ee2 = new EventEmitter();
|
||||
*
|
||||
* // 'foo' listeners on ordinary EventEmitters that do not track async
|
||||
* // context, however, run in the same async context as the emit().
|
||||
* ee2.on('foo', () => {
|
||||
* notStrictEqual(executionAsyncId(), ee2.asyncId);
|
||||
* notStrictEqual(triggerAsyncId(), ee2.triggerAsyncId);
|
||||
* });
|
||||
*
|
||||
* Promise.resolve().then(() => {
|
||||
* ee1.emit('foo');
|
||||
* ee2.emit('foo');
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* The `EventEmitterAsyncResource` class has the same methods and takes the
|
||||
* same options as `EventEmitter` and `AsyncResource` themselves.
|
||||
* @since v17.4.0, v16.14.0
|
||||
*/
|
||||
export class EventEmitterAsyncResource extends EventEmitter {
|
||||
/**
|
||||
* @param options Only optional in child class.
|
||||
*/
|
||||
constructor(options?: EventEmitterAsyncResourceOptions);
|
||||
/**
|
||||
* Call all `destroy` hooks. This should only ever be called once. An error will
|
||||
* be thrown if it is called more than once. This **must** be manually called. If
|
||||
* the resource is left to be collected by the GC then the `destroy` hooks will
|
||||
* never be called.
|
||||
*/
|
||||
emitDestroy(): void;
|
||||
/**
|
||||
* The unique `asyncId` assigned to the resource.
|
||||
*/
|
||||
readonly asyncId: number;
|
||||
/**
|
||||
* The same triggerAsyncId that is passed to the AsyncResource constructor.
|
||||
*/
|
||||
readonly triggerAsyncId: number;
|
||||
/**
|
||||
* The returned `AsyncResource` object has an additional `eventEmitter` property
|
||||
* that provides a reference to this `EventEmitterAsyncResource`.
|
||||
*/
|
||||
readonly asyncResource: EventEmitterReferencingAsyncResource;
|
||||
}
|
||||
/**
|
||||
* The `NodeEventTarget` is a Node.js-specific extension to `EventTarget`
|
||||
* that emulates a subset of the `EventEmitter` API.
|
||||
* @since v14.5.0
|
||||
*/
|
||||
export interface NodeEventTarget extends EventTarget {
|
||||
/**
|
||||
* Node.js-specific extension to the `EventTarget` class that emulates the
|
||||
* equivalent `EventEmitter` API. The only difference between `addListener()` and
|
||||
* `addEventListener()` is that `addListener()` will return a reference to the
|
||||
* `EventTarget`.
|
||||
* @since v14.5.0
|
||||
*/
|
||||
addListener(type: string, listener: (arg: any) => void): this;
|
||||
/**
|
||||
* Node.js-specific extension to the `EventTarget` class that dispatches the
|
||||
* `arg` to the list of handlers for `type`.
|
||||
* @since v15.2.0
|
||||
* @returns `true` if event listeners registered for the `type` exist,
|
||||
* otherwise `false`.
|
||||
*/
|
||||
emit(type: string, arg: any): boolean;
|
||||
/**
|
||||
* Node.js-specific extension to the `EventTarget` class that returns an array
|
||||
* of event `type` names for which event listeners are registered.
|
||||
* @since 14.5.0
|
||||
*/
|
||||
eventNames(): string[];
|
||||
/**
|
||||
* Node.js-specific extension to the `EventTarget` class that returns the number
|
||||
* of event listeners registered for the `type`.
|
||||
* @since v14.5.0
|
||||
*/
|
||||
listenerCount(type: string): number;
|
||||
/**
|
||||
* Node.js-specific extension to the `EventTarget` class that sets the number
|
||||
* of max event listeners as `n`.
|
||||
* @since v14.5.0
|
||||
*/
|
||||
setMaxListeners(n: number): void;
|
||||
/**
|
||||
* Node.js-specific extension to the `EventTarget` class that returns the number
|
||||
* of max event listeners.
|
||||
* @since v14.5.0
|
||||
*/
|
||||
getMaxListeners(): number;
|
||||
/**
|
||||
* Node.js-specific alias for `eventTarget.removeEventListener()`.
|
||||
* @since v14.5.0
|
||||
*/
|
||||
off(type: string, listener: (arg: any) => void, options?: EventListenerOptions): this;
|
||||
/**
|
||||
* Node.js-specific alias for `eventTarget.addEventListener()`.
|
||||
* @since v14.5.0
|
||||
*/
|
||||
on(type: string, listener: (arg: any) => void): this;
|
||||
/**
|
||||
* Node.js-specific extension to the `EventTarget` class that adds a `once`
|
||||
* listener for the given event `type`. This is equivalent to calling `on`
|
||||
* with the `once` option set to `true`.
|
||||
* @since v14.5.0
|
||||
*/
|
||||
once(type: string, listener: (arg: any) => void): this;
|
||||
/**
|
||||
* Node.js-specific extension to the `EventTarget` class. If `type` is specified,
|
||||
* removes all registered listeners for `type`, otherwise removes all registered
|
||||
* listeners.
|
||||
* @since v14.5.0
|
||||
*/
|
||||
removeAllListeners(type?: string): this;
|
||||
/**
|
||||
* Node.js-specific extension to the `EventTarget` class that removes the
|
||||
* `listener` for the given `type`. The only difference between `removeListener()`
|
||||
* and `removeEventListener()` is that `removeListener()` will return a reference
|
||||
* to the `EventTarget`.
|
||||
* @since v14.5.0
|
||||
*/
|
||||
removeListener(type: string, listener: (arg: any) => void, options?: EventListenerOptions): this;
|
||||
}
|
||||
}
|
||||
global {
|
||||
namespace NodeJS {
|
||||
interface EventEmitter<T extends EventMap<T> = DefaultEventMap> {
|
||||
[EventEmitter.captureRejectionSymbol]?<K>(error: Error, event: Key<K, T>, ...args: Args<K, T>): void;
|
||||
/**
|
||||
* Alias for `emitter.on(eventName, listener)`.
|
||||
* @since v0.1.26
|
||||
*/
|
||||
addListener<K>(eventName: Key<K, T>, listener: Listener1<K, T>): this;
|
||||
/**
|
||||
* Adds the `listener` function to the end of the listeners array for the event
|
||||
* named `eventName`. No checks are made to see if the `listener` has already
|
||||
* been added. Multiple calls passing the same combination of `eventName` and
|
||||
* `listener` will result in the `listener` being added, and called, multiple times.
|
||||
*
|
||||
* ```js
|
||||
* server.on('connection', (stream) => {
|
||||
* console.log('someone connected!');
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* Returns a reference to the `EventEmitter`, so that calls can be chained.
|
||||
*
|
||||
* By default, event listeners are invoked in the order they are added. The `emitter.prependListener()` method can be used as an alternative to add the
|
||||
* event listener to the beginning of the listeners array.
|
||||
*
|
||||
* ```js
|
||||
* import { EventEmitter } from 'node:events';
|
||||
* const myEE = new EventEmitter();
|
||||
* myEE.on('foo', () => console.log('a'));
|
||||
* myEE.prependListener('foo', () => console.log('b'));
|
||||
* myEE.emit('foo');
|
||||
* // Prints:
|
||||
* // b
|
||||
* // a
|
||||
* ```
|
||||
* @since v0.1.101
|
||||
* @param eventName The name of the event.
|
||||
* @param listener The callback function
|
||||
*/
|
||||
on<K>(eventName: Key<K, T>, listener: Listener1<K, T>): this;
|
||||
/**
|
||||
* Adds a **one-time** `listener` function for the event named `eventName`. The
|
||||
* next time `eventName` is triggered, this listener is removed and then invoked.
|
||||
*
|
||||
* ```js
|
||||
* server.once('connection', (stream) => {
|
||||
* console.log('Ah, we have our first user!');
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* Returns a reference to the `EventEmitter`, so that calls can be chained.
|
||||
*
|
||||
* By default, event listeners are invoked in the order they are added. The `emitter.prependOnceListener()` method can be used as an alternative to add the
|
||||
* event listener to the beginning of the listeners array.
|
||||
*
|
||||
* ```js
|
||||
* import { EventEmitter } from 'node:events';
|
||||
* const myEE = new EventEmitter();
|
||||
* myEE.once('foo', () => console.log('a'));
|
||||
* myEE.prependOnceListener('foo', () => console.log('b'));
|
||||
* myEE.emit('foo');
|
||||
* // Prints:
|
||||
* // b
|
||||
* // a
|
||||
* ```
|
||||
* @since v0.3.0
|
||||
* @param eventName The name of the event.
|
||||
* @param listener The callback function
|
||||
*/
|
||||
once<K>(eventName: Key<K, T>, listener: Listener1<K, T>): this;
|
||||
/**
|
||||
* Removes the specified `listener` from the listener array for the event named `eventName`.
|
||||
*
|
||||
* ```js
|
||||
* const callback = (stream) => {
|
||||
* console.log('someone connected!');
|
||||
* };
|
||||
* server.on('connection', callback);
|
||||
* // ...
|
||||
* server.removeListener('connection', callback);
|
||||
* ```
|
||||
*
|
||||
* `removeListener()` will remove, at most, one instance of a listener from the
|
||||
* listener array. If any single listener has been added multiple times to the
|
||||
* listener array for the specified `eventName`, then `removeListener()` must be
|
||||
* called multiple times to remove each instance.
|
||||
*
|
||||
* Once an event is emitted, all listeners attached to it at the
|
||||
* time of emitting are called in order. This implies that any `removeListener()` or `removeAllListeners()` calls _after_ emitting and _before_ the last listener finishes execution
|
||||
* will not remove them from`emit()` in progress. Subsequent events behave as expected.
|
||||
*
|
||||
* ```js
|
||||
* import { EventEmitter } from 'node:events';
|
||||
* class MyEmitter extends EventEmitter {}
|
||||
* const myEmitter = new MyEmitter();
|
||||
*
|
||||
* const callbackA = () => {
|
||||
* console.log('A');
|
||||
* myEmitter.removeListener('event', callbackB);
|
||||
* };
|
||||
*
|
||||
* const callbackB = () => {
|
||||
* console.log('B');
|
||||
* };
|
||||
*
|
||||
* myEmitter.on('event', callbackA);
|
||||
*
|
||||
* myEmitter.on('event', callbackB);
|
||||
*
|
||||
* // callbackA removes listener callbackB but it will still be called.
|
||||
* // Internal listener array at time of emit [callbackA, callbackB]
|
||||
* myEmitter.emit('event');
|
||||
* // Prints:
|
||||
* // A
|
||||
* // B
|
||||
*
|
||||
* // callbackB is now removed.
|
||||
* // Internal listener array [callbackA]
|
||||
* myEmitter.emit('event');
|
||||
* // Prints:
|
||||
* // A
|
||||
* ```
|
||||
*
|
||||
* Because listeners are managed using an internal array, calling this will
|
||||
* change the position indices of any listener registered _after_ the listener
|
||||
* being removed. This will not impact the order in which listeners are called,
|
||||
* but it means that any copies of the listener array as returned by
|
||||
* the `emitter.listeners()` method will need to be recreated.
|
||||
*
|
||||
* When a single function has been added as a handler multiple times for a single
|
||||
* event (as in the example below), `removeListener()` will remove the most
|
||||
* recently added instance. In the example the `once('ping')` listener is removed:
|
||||
*
|
||||
* ```js
|
||||
* import { EventEmitter } from 'node:events';
|
||||
* const ee = new EventEmitter();
|
||||
*
|
||||
* function pong() {
|
||||
* console.log('pong');
|
||||
* }
|
||||
*
|
||||
* ee.on('ping', pong);
|
||||
* ee.once('ping', pong);
|
||||
* ee.removeListener('ping', pong);
|
||||
*
|
||||
* ee.emit('ping');
|
||||
* ee.emit('ping');
|
||||
* ```
|
||||
*
|
||||
* Returns a reference to the `EventEmitter`, so that calls can be chained.
|
||||
* @since v0.1.26
|
||||
*/
|
||||
removeListener<K>(eventName: Key<K, T>, listener: Listener1<K, T>): this;
|
||||
/**
|
||||
* Alias for `emitter.removeListener()`.
|
||||
* @since v10.0.0
|
||||
*/
|
||||
off<K>(eventName: Key<K, T>, listener: Listener1<K, T>): this;
|
||||
/**
|
||||
* Removes all listeners, or those of the specified `eventName`.
|
||||
*
|
||||
* It is bad practice to remove listeners added elsewhere in the code,
|
||||
* particularly when the `EventEmitter` instance was created by some other
|
||||
* component or module (e.g. sockets or file streams).
|
||||
*
|
||||
* Returns a reference to the `EventEmitter`, so that calls can be chained.
|
||||
* @since v0.1.26
|
||||
*/
|
||||
removeAllListeners(eventName?: Key<unknown, T>): this;
|
||||
/**
|
||||
* By default `EventEmitter`s will print a warning if more than `10` listeners are
|
||||
* added for a particular event. This is a useful default that helps finding
|
||||
* memory leaks. The `emitter.setMaxListeners()` method allows the limit to be
|
||||
* modified for this specific `EventEmitter` instance. The value can be set to `Infinity` (or `0`) to indicate an unlimited number of listeners.
|
||||
*
|
||||
* Returns a reference to the `EventEmitter`, so that calls can be chained.
|
||||
* @since v0.3.5
|
||||
*/
|
||||
setMaxListeners(n: number): this;
|
||||
/**
|
||||
* Returns the current max listener value for the `EventEmitter` which is either
|
||||
* set by `emitter.setMaxListeners(n)` or defaults to {@link EventEmitter.defaultMaxListeners}.
|
||||
* @since v1.0.0
|
||||
*/
|
||||
getMaxListeners(): number;
|
||||
/**
|
||||
* Returns a copy of the array of listeners for the event named `eventName`.
|
||||
*
|
||||
* ```js
|
||||
* server.on('connection', (stream) => {
|
||||
* console.log('someone connected!');
|
||||
* });
|
||||
* console.log(util.inspect(server.listeners('connection')));
|
||||
* // Prints: [ [Function] ]
|
||||
* ```
|
||||
* @since v0.1.26
|
||||
*/
|
||||
listeners<K>(eventName: Key<K, T>): Array<Listener2<K, T>>;
|
||||
/**
|
||||
* Returns a copy of the array of listeners for the event named `eventName`,
|
||||
* including any wrappers (such as those created by `.once()`).
|
||||
*
|
||||
* ```js
|
||||
* import { EventEmitter } from 'node:events';
|
||||
* const emitter = new EventEmitter();
|
||||
* emitter.once('log', () => console.log('log once'));
|
||||
*
|
||||
* // Returns a new Array with a function `onceWrapper` which has a property
|
||||
* // `listener` which contains the original listener bound above
|
||||
* const listeners = emitter.rawListeners('log');
|
||||
* const logFnWrapper = listeners[0];
|
||||
*
|
||||
* // Logs "log once" to the console and does not unbind the `once` event
|
||||
* logFnWrapper.listener();
|
||||
*
|
||||
* // Logs "log once" to the console and removes the listener
|
||||
* logFnWrapper();
|
||||
*
|
||||
* emitter.on('log', () => console.log('log persistently'));
|
||||
* // Will return a new Array with a single function bound by `.on()` above
|
||||
* const newListeners = emitter.rawListeners('log');
|
||||
*
|
||||
* // Logs "log persistently" twice
|
||||
* newListeners[0]();
|
||||
* emitter.emit('log');
|
||||
* ```
|
||||
* @since v9.4.0
|
||||
*/
|
||||
rawListeners<K>(eventName: Key<K, T>): Array<Listener2<K, T>>;
|
||||
/**
|
||||
* Synchronously calls each of the listeners registered for the event named `eventName`, in the order they were registered, passing the supplied arguments
|
||||
* to each.
|
||||
*
|
||||
* Returns `true` if the event had listeners, `false` otherwise.
|
||||
*
|
||||
* ```js
|
||||
* import { EventEmitter } from 'node:events';
|
||||
* const myEmitter = new EventEmitter();
|
||||
*
|
||||
* // First listener
|
||||
* myEmitter.on('event', function firstListener() {
|
||||
* console.log('Helloooo! first listener');
|
||||
* });
|
||||
* // Second listener
|
||||
* myEmitter.on('event', function secondListener(arg1, arg2) {
|
||||
* console.log(`event with parameters ${arg1}, ${arg2} in second listener`);
|
||||
* });
|
||||
* // Third listener
|
||||
* myEmitter.on('event', function thirdListener(...args) {
|
||||
* const parameters = args.join(', ');
|
||||
* console.log(`event with parameters ${parameters} in third listener`);
|
||||
* });
|
||||
*
|
||||
* console.log(myEmitter.listeners('event'));
|
||||
*
|
||||
* myEmitter.emit('event', 1, 2, 3, 4, 5);
|
||||
*
|
||||
* // Prints:
|
||||
* // [
|
||||
* // [Function: firstListener],
|
||||
* // [Function: secondListener],
|
||||
* // [Function: thirdListener]
|
||||
* // ]
|
||||
* // Helloooo! first listener
|
||||
* // event with parameters 1, 2 in second listener
|
||||
* // event with parameters 1, 2, 3, 4, 5 in third listener
|
||||
* ```
|
||||
* @since v0.1.26
|
||||
*/
|
||||
emit<K>(eventName: Key<K, T>, ...args: Args<K, T>): boolean;
|
||||
/**
|
||||
* Returns the number of listeners listening for the event named `eventName`.
|
||||
* If `listener` is provided, it will return how many times the listener is found
|
||||
* in the list of the listeners of the event.
|
||||
* @since v3.2.0
|
||||
* @param eventName The name of the event being listened for
|
||||
* @param listener The event handler function
|
||||
*/
|
||||
listenerCount<K>(eventName: Key<K, T>, listener?: Listener2<K, T>): number;
|
||||
/**
|
||||
* Adds the `listener` function to the _beginning_ of the listeners array for the
|
||||
* event named `eventName`. No checks are made to see if the `listener` has
|
||||
* already been added. Multiple calls passing the same combination of `eventName`
|
||||
* and `listener` will result in the `listener` being added, and called, multiple times.
|
||||
*
|
||||
* ```js
|
||||
* server.prependListener('connection', (stream) => {
|
||||
* console.log('someone connected!');
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* Returns a reference to the `EventEmitter`, so that calls can be chained.
|
||||
* @since v6.0.0
|
||||
* @param eventName The name of the event.
|
||||
* @param listener The callback function
|
||||
*/
|
||||
prependListener<K>(eventName: Key<K, T>, listener: Listener1<K, T>): this;
|
||||
/**
|
||||
* Adds a **one-time**`listener` function for the event named `eventName` to the _beginning_ of the listeners array. The next time `eventName` is triggered, this
|
||||
* listener is removed, and then invoked.
|
||||
*
|
||||
* ```js
|
||||
* server.prependOnceListener('connection', (stream) => {
|
||||
* console.log('Ah, we have our first user!');
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* Returns a reference to the `EventEmitter`, so that calls can be chained.
|
||||
* @since v6.0.0
|
||||
* @param eventName The name of the event.
|
||||
* @param listener The callback function
|
||||
*/
|
||||
prependOnceListener<K>(eventName: Key<K, T>, listener: Listener1<K, T>): this;
|
||||
/**
|
||||
* Returns an array listing the events for which the emitter has registered
|
||||
* listeners. The values in the array are strings or `Symbol`s.
|
||||
*
|
||||
* ```js
|
||||
* import { EventEmitter } from 'node:events';
|
||||
*
|
||||
* const myEE = new EventEmitter();
|
||||
* myEE.on('foo', () => {});
|
||||
* myEE.on('bar', () => {});
|
||||
*
|
||||
* const sym = Symbol('symbol');
|
||||
* myEE.on(sym, () => {});
|
||||
*
|
||||
* console.log(myEE.eventNames());
|
||||
* // Prints: [ 'foo', 'bar', Symbol(symbol) ]
|
||||
* ```
|
||||
* @since v6.0.0
|
||||
*/
|
||||
eventNames(): Array<(string | symbol) & Key2<unknown, T>>;
|
||||
}
|
||||
}
|
||||
}
|
||||
export = EventEmitter;
|
||||
}
|
||||
declare module "node:events" {
|
||||
import events = require("events");
|
||||
export = events;
|
||||
}
|
||||
4714
node_modules/sitemap/node_modules/@types/node/fs.d.ts
generated
vendored
Normal file
4714
node_modules/sitemap/node_modules/@types/node/fs.d.ts
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
1330
node_modules/sitemap/node_modules/@types/node/fs/promises.d.ts
generated
vendored
Normal file
1330
node_modules/sitemap/node_modules/@types/node/fs/promises.d.ts
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
170
node_modules/sitemap/node_modules/@types/node/globals.d.ts
generated
vendored
Normal file
170
node_modules/sitemap/node_modules/@types/node/globals.d.ts
generated
vendored
Normal file
@@ -0,0 +1,170 @@
|
||||
declare var global: typeof globalThis;
|
||||
|
||||
declare var process: NodeJS.Process;
|
||||
declare var console: Console;
|
||||
|
||||
interface ErrorConstructor {
|
||||
/**
|
||||
* Creates a `.stack` property on `targetObject`, which when accessed returns
|
||||
* a string representing the location in the code at which
|
||||
* `Error.captureStackTrace()` was called.
|
||||
*
|
||||
* ```js
|
||||
* const myObject = {};
|
||||
* Error.captureStackTrace(myObject);
|
||||
* myObject.stack; // Similar to `new Error().stack`
|
||||
* ```
|
||||
*
|
||||
* The first line of the trace will be prefixed with
|
||||
* `${myObject.name}: ${myObject.message}`.
|
||||
*
|
||||
* The optional `constructorOpt` argument accepts a function. If given, all frames
|
||||
* above `constructorOpt`, including `constructorOpt`, will be omitted from the
|
||||
* generated stack trace.
|
||||
*
|
||||
* The `constructorOpt` argument is useful for hiding implementation
|
||||
* details of error generation from the user. For instance:
|
||||
*
|
||||
* ```js
|
||||
* function a() {
|
||||
* b();
|
||||
* }
|
||||
*
|
||||
* function b() {
|
||||
* c();
|
||||
* }
|
||||
*
|
||||
* function c() {
|
||||
* // Create an error without stack trace to avoid calculating the stack trace twice.
|
||||
* const { stackTraceLimit } = Error;
|
||||
* Error.stackTraceLimit = 0;
|
||||
* const error = new Error();
|
||||
* Error.stackTraceLimit = stackTraceLimit;
|
||||
*
|
||||
* // Capture the stack trace above function b
|
||||
* Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace
|
||||
* throw error;
|
||||
* }
|
||||
*
|
||||
* a();
|
||||
* ```
|
||||
*/
|
||||
captureStackTrace(targetObject: object, constructorOpt?: Function): void;
|
||||
/**
|
||||
* @see https://v8.dev/docs/stack-trace-api#customizing-stack-traces
|
||||
*/
|
||||
prepareStackTrace(err: Error, stackTraces: NodeJS.CallSite[]): any;
|
||||
/**
|
||||
* The `Error.stackTraceLimit` property specifies the number of stack frames
|
||||
* collected by a stack trace (whether generated by `new Error().stack` or
|
||||
* `Error.captureStackTrace(obj)`).
|
||||
*
|
||||
* The default value is `10` but may be set to any valid JavaScript number. Changes
|
||||
* will affect any stack trace captured _after_ the value has been changed.
|
||||
*
|
||||
* If set to a non-number value, or set to a negative number, stack traces will
|
||||
* not capture any frames.
|
||||
*/
|
||||
stackTraceLimit: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enable this API with the `--expose-gc` CLI flag.
|
||||
*/
|
||||
declare var gc: NodeJS.GCFunction | undefined;
|
||||
|
||||
declare namespace NodeJS {
|
||||
interface CallSite {
|
||||
getColumnNumber(): number | null;
|
||||
getEnclosingColumnNumber(): number | null;
|
||||
getEnclosingLineNumber(): number | null;
|
||||
getEvalOrigin(): string | undefined;
|
||||
getFileName(): string | null;
|
||||
getFunction(): Function | undefined;
|
||||
getFunctionName(): string | null;
|
||||
getLineNumber(): number | null;
|
||||
getMethodName(): string | null;
|
||||
getPosition(): number;
|
||||
getPromiseIndex(): number | null;
|
||||
getScriptHash(): string;
|
||||
getScriptNameOrSourceURL(): string | null;
|
||||
getThis(): unknown;
|
||||
getTypeName(): string | null;
|
||||
isAsync(): boolean;
|
||||
isConstructor(): boolean;
|
||||
isEval(): boolean;
|
||||
isNative(): boolean;
|
||||
isPromiseAll(): boolean;
|
||||
isToplevel(): boolean;
|
||||
}
|
||||
|
||||
interface ErrnoException extends Error {
|
||||
errno?: number | undefined;
|
||||
code?: string | undefined;
|
||||
path?: string | undefined;
|
||||
syscall?: string | undefined;
|
||||
}
|
||||
|
||||
interface ReadableStream extends EventEmitter {
|
||||
readable: boolean;
|
||||
read(size?: number): string | Buffer;
|
||||
setEncoding(encoding: BufferEncoding): this;
|
||||
pause(): this;
|
||||
resume(): this;
|
||||
isPaused(): boolean;
|
||||
pipe<T extends WritableStream>(destination: T, options?: { end?: boolean | undefined }): T;
|
||||
unpipe(destination?: WritableStream): this;
|
||||
unshift(chunk: string | Uint8Array, encoding?: BufferEncoding): void;
|
||||
wrap(oldStream: ReadableStream): this;
|
||||
[Symbol.asyncIterator](): AsyncIterableIterator<string | Buffer>;
|
||||
}
|
||||
|
||||
interface WritableStream extends EventEmitter {
|
||||
writable: boolean;
|
||||
write(buffer: Uint8Array | string, cb?: (err?: Error | null) => void): boolean;
|
||||
write(str: string, encoding?: BufferEncoding, cb?: (err?: Error | null) => void): boolean;
|
||||
end(cb?: () => void): this;
|
||||
end(data: string | Uint8Array, cb?: () => void): this;
|
||||
end(str: string, encoding?: BufferEncoding, cb?: () => void): this;
|
||||
}
|
||||
|
||||
interface ReadWriteStream extends ReadableStream, WritableStream {}
|
||||
|
||||
interface RefCounted {
|
||||
ref(): this;
|
||||
unref(): this;
|
||||
}
|
||||
|
||||
interface Dict<T> {
|
||||
[key: string]: T | undefined;
|
||||
}
|
||||
|
||||
interface ReadOnlyDict<T> {
|
||||
readonly [key: string]: T | undefined;
|
||||
}
|
||||
|
||||
type PartialOptions<T> = { [K in keyof T]?: T[K] | undefined };
|
||||
|
||||
interface GCFunction {
|
||||
(minor?: boolean): void;
|
||||
(options: NodeJS.GCOptions & { execution: "async" }): Promise<void>;
|
||||
(options: NodeJS.GCOptions): void;
|
||||
}
|
||||
|
||||
interface GCOptions {
|
||||
execution?: "sync" | "async" | undefined;
|
||||
flavor?: "regular" | "last-resort" | undefined;
|
||||
type?: "major-snapshot" | "major" | "minor" | undefined;
|
||||
filename?: string | undefined;
|
||||
}
|
||||
|
||||
/** An iterable iterator returned by the Node.js API. */
|
||||
interface Iterator<T, TReturn = undefined, TNext = any> extends IteratorObject<T, TReturn, TNext> {
|
||||
[Symbol.iterator](): NodeJS.Iterator<T, TReturn, TNext>;
|
||||
}
|
||||
|
||||
/** An async iterable iterator returned by the Node.js API. */
|
||||
interface AsyncIterator<T, TReturn = undefined, TNext = any> extends AsyncIteratorObject<T, TReturn, TNext> {
|
||||
[Symbol.asyncIterator](): NodeJS.AsyncIterator<T, TReturn, TNext>;
|
||||
}
|
||||
}
|
||||
41
node_modules/sitemap/node_modules/@types/node/globals.typedarray.d.ts
generated
vendored
Normal file
41
node_modules/sitemap/node_modules/@types/node/globals.typedarray.d.ts
generated
vendored
Normal file
@@ -0,0 +1,41 @@
|
||||
export {}; // Make this a module
|
||||
|
||||
declare global {
|
||||
namespace NodeJS {
|
||||
type TypedArray<TArrayBuffer extends ArrayBufferLike = ArrayBufferLike> =
|
||||
| Uint8Array<TArrayBuffer>
|
||||
| Uint8ClampedArray<TArrayBuffer>
|
||||
| Uint16Array<TArrayBuffer>
|
||||
| Uint32Array<TArrayBuffer>
|
||||
| Int8Array<TArrayBuffer>
|
||||
| Int16Array<TArrayBuffer>
|
||||
| Int32Array<TArrayBuffer>
|
||||
| BigUint64Array<TArrayBuffer>
|
||||
| BigInt64Array<TArrayBuffer>
|
||||
| Float16Array<TArrayBuffer>
|
||||
| Float32Array<TArrayBuffer>
|
||||
| Float64Array<TArrayBuffer>;
|
||||
type ArrayBufferView<TArrayBuffer extends ArrayBufferLike = ArrayBufferLike> =
|
||||
| TypedArray<TArrayBuffer>
|
||||
| DataView<TArrayBuffer>;
|
||||
|
||||
// The following aliases are required to allow use of non-shared ArrayBufferViews in @types/node
|
||||
// while maintaining compatibility with TS <=5.6.
|
||||
// TODO: remove once @types/node no longer supports TS 5.6, and replace with native types.
|
||||
type NonSharedUint8Array = Uint8Array<ArrayBuffer>;
|
||||
type NonSharedUint8ClampedArray = Uint8ClampedArray<ArrayBuffer>;
|
||||
type NonSharedUint16Array = Uint16Array<ArrayBuffer>;
|
||||
type NonSharedUint32Array = Uint32Array<ArrayBuffer>;
|
||||
type NonSharedInt8Array = Int8Array<ArrayBuffer>;
|
||||
type NonSharedInt16Array = Int16Array<ArrayBuffer>;
|
||||
type NonSharedInt32Array = Int32Array<ArrayBuffer>;
|
||||
type NonSharedBigUint64Array = BigUint64Array<ArrayBuffer>;
|
||||
type NonSharedBigInt64Array = BigInt64Array<ArrayBuffer>;
|
||||
type NonSharedFloat16Array = Float16Array<ArrayBuffer>;
|
||||
type NonSharedFloat32Array = Float32Array<ArrayBuffer>;
|
||||
type NonSharedFloat64Array = Float64Array<ArrayBuffer>;
|
||||
type NonSharedDataView = DataView<ArrayBuffer>;
|
||||
type NonSharedTypedArray = TypedArray<ArrayBuffer>;
|
||||
type NonSharedArrayBufferView = ArrayBufferView<ArrayBuffer>;
|
||||
}
|
||||
}
|
||||
2154
node_modules/sitemap/node_modules/@types/node/http.d.ts
generated
vendored
Normal file
2154
node_modules/sitemap/node_modules/@types/node/http.d.ts
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
2756
node_modules/sitemap/node_modules/@types/node/http2.d.ts
generated
vendored
Normal file
2756
node_modules/sitemap/node_modules/@types/node/http2.d.ts
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
585
node_modules/sitemap/node_modules/@types/node/https.d.ts
generated
vendored
Normal file
585
node_modules/sitemap/node_modules/@types/node/https.d.ts
generated
vendored
Normal file
@@ -0,0 +1,585 @@
|
||||
/**
|
||||
* HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a
|
||||
* separate module.
|
||||
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/https.js)
|
||||
*/
|
||||
declare module "https" {
|
||||
import { NonSharedBuffer } from "node:buffer";
|
||||
import { Duplex } from "node:stream";
|
||||
import * as tls from "node:tls";
|
||||
import * as http from "node:http";
|
||||
import { URL } from "node:url";
|
||||
interface ServerOptions<
|
||||
Request extends typeof http.IncomingMessage = typeof http.IncomingMessage,
|
||||
Response extends typeof http.ServerResponse<InstanceType<Request>> = typeof http.ServerResponse,
|
||||
> extends http.ServerOptions<Request, Response>, tls.TlsOptions {}
|
||||
interface RequestOptions extends http.RequestOptions, tls.SecureContextOptions {
|
||||
checkServerIdentity?:
|
||||
| ((hostname: string, cert: tls.DetailedPeerCertificate) => Error | undefined)
|
||||
| undefined;
|
||||
rejectUnauthorized?: boolean | undefined; // Defaults to true
|
||||
servername?: string | undefined; // SNI TLS Extension
|
||||
}
|
||||
interface AgentOptions extends http.AgentOptions, tls.ConnectionOptions {
|
||||
maxCachedSessions?: number | undefined;
|
||||
}
|
||||
/**
|
||||
* An `Agent` object for HTTPS similar to `http.Agent`. See {@link request} for more information.
|
||||
*
|
||||
* Like `http.Agent`, the `createConnection(options[, callback])` method can be overridden to customize
|
||||
* how TLS connections are established.
|
||||
*
|
||||
* > See [`agent.createConnection()`](https://nodejs.org/docs/latest-v24.x/api/http.html#agentcreateconnectionoptions-callback)
|
||||
* for details on overriding this method, including asynchronous socket creation with a callback.
|
||||
* @since v0.4.5
|
||||
*/
|
||||
class Agent extends http.Agent {
|
||||
constructor(options?: AgentOptions);
|
||||
options: AgentOptions;
|
||||
createConnection(
|
||||
options: RequestOptions,
|
||||
callback?: (err: Error | null, stream: Duplex) => void,
|
||||
): Duplex | null | undefined;
|
||||
getName(options?: RequestOptions): string;
|
||||
}
|
||||
interface Server<
|
||||
Request extends typeof http.IncomingMessage = typeof http.IncomingMessage,
|
||||
Response extends typeof http.ServerResponse<InstanceType<Request>> = typeof http.ServerResponse,
|
||||
> extends http.Server<Request, Response> {}
|
||||
/**
|
||||
* See `http.Server` for more information.
|
||||
* @since v0.3.4
|
||||
*/
|
||||
class Server<
|
||||
Request extends typeof http.IncomingMessage = typeof http.IncomingMessage,
|
||||
Response extends typeof http.ServerResponse<InstanceType<Request>> = typeof http.ServerResponse,
|
||||
> extends tls.Server {
|
||||
constructor(requestListener?: http.RequestListener<Request, Response>);
|
||||
constructor(
|
||||
options: ServerOptions<Request, Response>,
|
||||
requestListener?: http.RequestListener<Request, Response>,
|
||||
);
|
||||
/**
|
||||
* Closes all connections connected to this server.
|
||||
* @since v18.2.0
|
||||
*/
|
||||
closeAllConnections(): void;
|
||||
/**
|
||||
* Closes all connections connected to this server which are not sending a request or waiting for a response.
|
||||
* @since v18.2.0
|
||||
*/
|
||||
closeIdleConnections(): void;
|
||||
addListener(event: string, listener: (...args: any[]) => void): this;
|
||||
addListener(event: "keylog", listener: (line: NonSharedBuffer, tlsSocket: tls.TLSSocket) => void): this;
|
||||
addListener(
|
||||
event: "newSession",
|
||||
listener: (sessionId: NonSharedBuffer, sessionData: NonSharedBuffer, callback: () => void) => void,
|
||||
): this;
|
||||
addListener(
|
||||
event: "OCSPRequest",
|
||||
listener: (
|
||||
certificate: NonSharedBuffer,
|
||||
issuer: NonSharedBuffer,
|
||||
callback: (err: Error | null, resp: Buffer | null) => void,
|
||||
) => void,
|
||||
): this;
|
||||
addListener(
|
||||
event: "resumeSession",
|
||||
listener: (
|
||||
sessionId: NonSharedBuffer,
|
||||
callback: (err: Error | null, sessionData: Buffer | null) => void,
|
||||
) => void,
|
||||
): this;
|
||||
addListener(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this;
|
||||
addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this;
|
||||
addListener(event: "close", listener: () => void): this;
|
||||
addListener(event: "connection", listener: (socket: Duplex) => void): this;
|
||||
addListener(event: "error", listener: (err: Error) => void): this;
|
||||
addListener(event: "listening", listener: () => void): this;
|
||||
addListener(event: "checkContinue", listener: http.RequestListener<Request, Response>): this;
|
||||
addListener(event: "checkExpectation", listener: http.RequestListener<Request, Response>): this;
|
||||
addListener(event: "clientError", listener: (err: Error, socket: Duplex) => void): this;
|
||||
addListener(
|
||||
event: "connect",
|
||||
listener: (req: InstanceType<Request>, socket: Duplex, head: NonSharedBuffer) => void,
|
||||
): this;
|
||||
addListener(event: "request", listener: http.RequestListener<Request, Response>): this;
|
||||
addListener(
|
||||
event: "upgrade",
|
||||
listener: (req: InstanceType<Request>, socket: Duplex, head: NonSharedBuffer) => void,
|
||||
): this;
|
||||
emit(event: string, ...args: any[]): boolean;
|
||||
emit(event: "keylog", line: NonSharedBuffer, tlsSocket: tls.TLSSocket): boolean;
|
||||
emit(
|
||||
event: "newSession",
|
||||
sessionId: NonSharedBuffer,
|
||||
sessionData: NonSharedBuffer,
|
||||
callback: () => void,
|
||||
): boolean;
|
||||
emit(
|
||||
event: "OCSPRequest",
|
||||
certificate: NonSharedBuffer,
|
||||
issuer: NonSharedBuffer,
|
||||
callback: (err: Error | null, resp: Buffer | null) => void,
|
||||
): boolean;
|
||||
emit(
|
||||
event: "resumeSession",
|
||||
sessionId: NonSharedBuffer,
|
||||
callback: (err: Error | null, sessionData: Buffer | null) => void,
|
||||
): boolean;
|
||||
emit(event: "secureConnection", tlsSocket: tls.TLSSocket): boolean;
|
||||
emit(event: "tlsClientError", err: Error, tlsSocket: tls.TLSSocket): boolean;
|
||||
emit(event: "close"): boolean;
|
||||
emit(event: "connection", socket: Duplex): boolean;
|
||||
emit(event: "error", err: Error): boolean;
|
||||
emit(event: "listening"): boolean;
|
||||
emit(
|
||||
event: "checkContinue",
|
||||
req: InstanceType<Request>,
|
||||
res: InstanceType<Response>,
|
||||
): boolean;
|
||||
emit(
|
||||
event: "checkExpectation",
|
||||
req: InstanceType<Request>,
|
||||
res: InstanceType<Response>,
|
||||
): boolean;
|
||||
emit(event: "clientError", err: Error, socket: Duplex): boolean;
|
||||
emit(event: "connect", req: InstanceType<Request>, socket: Duplex, head: NonSharedBuffer): boolean;
|
||||
emit(
|
||||
event: "request",
|
||||
req: InstanceType<Request>,
|
||||
res: InstanceType<Response>,
|
||||
): boolean;
|
||||
emit(event: "upgrade", req: InstanceType<Request>, socket: Duplex, head: NonSharedBuffer): boolean;
|
||||
on(event: string, listener: (...args: any[]) => void): this;
|
||||
on(event: "keylog", listener: (line: NonSharedBuffer, tlsSocket: tls.TLSSocket) => void): this;
|
||||
on(
|
||||
event: "newSession",
|
||||
listener: (sessionId: NonSharedBuffer, sessionData: NonSharedBuffer, callback: () => void) => void,
|
||||
): this;
|
||||
on(
|
||||
event: "OCSPRequest",
|
||||
listener: (
|
||||
certificate: NonSharedBuffer,
|
||||
issuer: NonSharedBuffer,
|
||||
callback: (err: Error | null, resp: Buffer | null) => void,
|
||||
) => void,
|
||||
): this;
|
||||
on(
|
||||
event: "resumeSession",
|
||||
listener: (
|
||||
sessionId: NonSharedBuffer,
|
||||
callback: (err: Error | null, sessionData: Buffer | null) => void,
|
||||
) => void,
|
||||
): this;
|
||||
on(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this;
|
||||
on(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this;
|
||||
on(event: "close", listener: () => void): this;
|
||||
on(event: "connection", listener: (socket: Duplex) => void): this;
|
||||
on(event: "error", listener: (err: Error) => void): this;
|
||||
on(event: "listening", listener: () => void): this;
|
||||
on(event: "checkContinue", listener: http.RequestListener<Request, Response>): this;
|
||||
on(event: "checkExpectation", listener: http.RequestListener<Request, Response>): this;
|
||||
on(event: "clientError", listener: (err: Error, socket: Duplex) => void): this;
|
||||
on(
|
||||
event: "connect",
|
||||
listener: (req: InstanceType<Request>, socket: Duplex, head: NonSharedBuffer) => void,
|
||||
): this;
|
||||
on(event: "request", listener: http.RequestListener<Request, Response>): this;
|
||||
on(
|
||||
event: "upgrade",
|
||||
listener: (req: InstanceType<Request>, socket: Duplex, head: NonSharedBuffer) => void,
|
||||
): this;
|
||||
once(event: string, listener: (...args: any[]) => void): this;
|
||||
once(event: "keylog", listener: (line: NonSharedBuffer, tlsSocket: tls.TLSSocket) => void): this;
|
||||
once(
|
||||
event: "newSession",
|
||||
listener: (sessionId: NonSharedBuffer, sessionData: NonSharedBuffer, callback: () => void) => void,
|
||||
): this;
|
||||
once(
|
||||
event: "OCSPRequest",
|
||||
listener: (
|
||||
certificate: NonSharedBuffer,
|
||||
issuer: NonSharedBuffer,
|
||||
callback: (err: Error | null, resp: Buffer | null) => void,
|
||||
) => void,
|
||||
): this;
|
||||
once(
|
||||
event: "resumeSession",
|
||||
listener: (
|
||||
sessionId: NonSharedBuffer,
|
||||
callback: (err: Error | null, sessionData: Buffer | null) => void,
|
||||
) => void,
|
||||
): this;
|
||||
once(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this;
|
||||
once(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this;
|
||||
once(event: "close", listener: () => void): this;
|
||||
once(event: "connection", listener: (socket: Duplex) => void): this;
|
||||
once(event: "error", listener: (err: Error) => void): this;
|
||||
once(event: "listening", listener: () => void): this;
|
||||
once(event: "checkContinue", listener: http.RequestListener<Request, Response>): this;
|
||||
once(event: "checkExpectation", listener: http.RequestListener<Request, Response>): this;
|
||||
once(event: "clientError", listener: (err: Error, socket: Duplex) => void): this;
|
||||
once(
|
||||
event: "connect",
|
||||
listener: (req: InstanceType<Request>, socket: Duplex, head: NonSharedBuffer) => void,
|
||||
): this;
|
||||
once(event: "request", listener: http.RequestListener<Request, Response>): this;
|
||||
once(
|
||||
event: "upgrade",
|
||||
listener: (req: InstanceType<Request>, socket: Duplex, head: NonSharedBuffer) => void,
|
||||
): this;
|
||||
prependListener(event: string, listener: (...args: any[]) => void): this;
|
||||
prependListener(event: "keylog", listener: (line: NonSharedBuffer, tlsSocket: tls.TLSSocket) => void): this;
|
||||
prependListener(
|
||||
event: "newSession",
|
||||
listener: (sessionId: NonSharedBuffer, sessionData: NonSharedBuffer, callback: () => void) => void,
|
||||
): this;
|
||||
prependListener(
|
||||
event: "OCSPRequest",
|
||||
listener: (
|
||||
certificate: NonSharedBuffer,
|
||||
issuer: NonSharedBuffer,
|
||||
callback: (err: Error | null, resp: Buffer | null) => void,
|
||||
) => void,
|
||||
): this;
|
||||
prependListener(
|
||||
event: "resumeSession",
|
||||
listener: (
|
||||
sessionId: NonSharedBuffer,
|
||||
callback: (err: Error | null, sessionData: Buffer | null) => void,
|
||||
) => void,
|
||||
): this;
|
||||
prependListener(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this;
|
||||
prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this;
|
||||
prependListener(event: "close", listener: () => void): this;
|
||||
prependListener(event: "connection", listener: (socket: Duplex) => void): this;
|
||||
prependListener(event: "error", listener: (err: Error) => void): this;
|
||||
prependListener(event: "listening", listener: () => void): this;
|
||||
prependListener(event: "checkContinue", listener: http.RequestListener<Request, Response>): this;
|
||||
prependListener(event: "checkExpectation", listener: http.RequestListener<Request, Response>): this;
|
||||
prependListener(event: "clientError", listener: (err: Error, socket: Duplex) => void): this;
|
||||
prependListener(
|
||||
event: "connect",
|
||||
listener: (req: InstanceType<Request>, socket: Duplex, head: NonSharedBuffer) => void,
|
||||
): this;
|
||||
prependListener(event: "request", listener: http.RequestListener<Request, Response>): this;
|
||||
prependListener(
|
||||
event: "upgrade",
|
||||
listener: (req: InstanceType<Request>, socket: Duplex, head: NonSharedBuffer) => void,
|
||||
): this;
|
||||
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
|
||||
prependOnceListener(event: "keylog", listener: (line: NonSharedBuffer, tlsSocket: tls.TLSSocket) => void): this;
|
||||
prependOnceListener(
|
||||
event: "newSession",
|
||||
listener: (sessionId: NonSharedBuffer, sessionData: NonSharedBuffer, callback: () => void) => void,
|
||||
): this;
|
||||
prependOnceListener(
|
||||
event: "OCSPRequest",
|
||||
listener: (
|
||||
certificate: NonSharedBuffer,
|
||||
issuer: NonSharedBuffer,
|
||||
callback: (err: Error | null, resp: Buffer | null) => void,
|
||||
) => void,
|
||||
): this;
|
||||
prependOnceListener(
|
||||
event: "resumeSession",
|
||||
listener: (
|
||||
sessionId: NonSharedBuffer,
|
||||
callback: (err: Error | null, sessionData: Buffer | null) => void,
|
||||
) => void,
|
||||
): this;
|
||||
prependOnceListener(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this;
|
||||
prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this;
|
||||
prependOnceListener(event: "close", listener: () => void): this;
|
||||
prependOnceListener(event: "connection", listener: (socket: Duplex) => void): this;
|
||||
prependOnceListener(event: "error", listener: (err: Error) => void): this;
|
||||
prependOnceListener(event: "listening", listener: () => void): this;
|
||||
prependOnceListener(event: "checkContinue", listener: http.RequestListener<Request, Response>): this;
|
||||
prependOnceListener(event: "checkExpectation", listener: http.RequestListener<Request, Response>): this;
|
||||
prependOnceListener(event: "clientError", listener: (err: Error, socket: Duplex) => void): this;
|
||||
prependOnceListener(
|
||||
event: "connect",
|
||||
listener: (req: InstanceType<Request>, socket: Duplex, head: NonSharedBuffer) => void,
|
||||
): this;
|
||||
prependOnceListener(event: "request", listener: http.RequestListener<Request, Response>): this;
|
||||
prependOnceListener(
|
||||
event: "upgrade",
|
||||
listener: (req: InstanceType<Request>, socket: Duplex, head: NonSharedBuffer) => void,
|
||||
): this;
|
||||
}
|
||||
/**
|
||||
* ```js
|
||||
* // curl -k https://localhost:8000/
|
||||
* import https from 'node:https';
|
||||
* import fs from 'node:fs';
|
||||
*
|
||||
* const options = {
|
||||
* key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
|
||||
* cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'),
|
||||
* };
|
||||
*
|
||||
* https.createServer(options, (req, res) => {
|
||||
* res.writeHead(200);
|
||||
* res.end('hello world\n');
|
||||
* }).listen(8000);
|
||||
* ```
|
||||
*
|
||||
* Or
|
||||
*
|
||||
* ```js
|
||||
* import https from 'node:https';
|
||||
* import fs from 'node:fs';
|
||||
*
|
||||
* const options = {
|
||||
* pfx: fs.readFileSync('test/fixtures/test_cert.pfx'),
|
||||
* passphrase: 'sample',
|
||||
* };
|
||||
*
|
||||
* https.createServer(options, (req, res) => {
|
||||
* res.writeHead(200);
|
||||
* res.end('hello world\n');
|
||||
* }).listen(8000);
|
||||
* ```
|
||||
* @since v0.3.4
|
||||
* @param options Accepts `options` from `createServer`, `createSecureContext` and `createServer`.
|
||||
* @param requestListener A listener to be added to the `'request'` event.
|
||||
*/
|
||||
function createServer<
|
||||
Request extends typeof http.IncomingMessage = typeof http.IncomingMessage,
|
||||
Response extends typeof http.ServerResponse<InstanceType<Request>> = typeof http.ServerResponse,
|
||||
>(requestListener?: http.RequestListener<Request, Response>): Server<Request, Response>;
|
||||
function createServer<
|
||||
Request extends typeof http.IncomingMessage = typeof http.IncomingMessage,
|
||||
Response extends typeof http.ServerResponse<InstanceType<Request>> = typeof http.ServerResponse,
|
||||
>(
|
||||
options: ServerOptions<Request, Response>,
|
||||
requestListener?: http.RequestListener<Request, Response>,
|
||||
): Server<Request, Response>;
|
||||
/**
|
||||
* Makes a request to a secure web server.
|
||||
*
|
||||
* The following additional `options` from `tls.connect()` are also accepted: `ca`, `cert`, `ciphers`, `clientCertEngine`, `crl`, `dhparam`, `ecdhCurve`, `honorCipherOrder`, `key`, `passphrase`,
|
||||
* `pfx`, `rejectUnauthorized`, `secureOptions`, `secureProtocol`, `servername`, `sessionIdContext`, `highWaterMark`.
|
||||
*
|
||||
* `options` can be an object, a string, or a `URL` object. If `options` is a
|
||||
* string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object.
|
||||
*
|
||||
* `https.request()` returns an instance of the `http.ClientRequest` class. The `ClientRequest` instance is a writable stream. If one needs to
|
||||
* upload a file with a POST request, then write to the `ClientRequest` object.
|
||||
*
|
||||
* ```js
|
||||
* import https from 'node:https';
|
||||
*
|
||||
* const options = {
|
||||
* hostname: 'encrypted.google.com',
|
||||
* port: 443,
|
||||
* path: '/',
|
||||
* method: 'GET',
|
||||
* };
|
||||
*
|
||||
* const req = https.request(options, (res) => {
|
||||
* console.log('statusCode:', res.statusCode);
|
||||
* console.log('headers:', res.headers);
|
||||
*
|
||||
* res.on('data', (d) => {
|
||||
* process.stdout.write(d);
|
||||
* });
|
||||
* });
|
||||
*
|
||||
* req.on('error', (e) => {
|
||||
* console.error(e);
|
||||
* });
|
||||
* req.end();
|
||||
* ```
|
||||
*
|
||||
* Example using options from `tls.connect()`:
|
||||
*
|
||||
* ```js
|
||||
* const options = {
|
||||
* hostname: 'encrypted.google.com',
|
||||
* port: 443,
|
||||
* path: '/',
|
||||
* method: 'GET',
|
||||
* key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
|
||||
* cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'),
|
||||
* };
|
||||
* options.agent = new https.Agent(options);
|
||||
*
|
||||
* const req = https.request(options, (res) => {
|
||||
* // ...
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* Alternatively, opt out of connection pooling by not using an `Agent`.
|
||||
*
|
||||
* ```js
|
||||
* const options = {
|
||||
* hostname: 'encrypted.google.com',
|
||||
* port: 443,
|
||||
* path: '/',
|
||||
* method: 'GET',
|
||||
* key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
|
||||
* cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'),
|
||||
* agent: false,
|
||||
* };
|
||||
*
|
||||
* const req = https.request(options, (res) => {
|
||||
* // ...
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* Example using a `URL` as `options`:
|
||||
*
|
||||
* ```js
|
||||
* const options = new URL('https://abc:xyz@example.com');
|
||||
*
|
||||
* const req = https.request(options, (res) => {
|
||||
* // ...
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* Example pinning on certificate fingerprint, or the public key (similar to`pin-sha256`):
|
||||
*
|
||||
* ```js
|
||||
* import tls from 'node:tls';
|
||||
* import https from 'node:https';
|
||||
* import crypto from 'node:crypto';
|
||||
*
|
||||
* function sha256(s) {
|
||||
* return crypto.createHash('sha256').update(s).digest('base64');
|
||||
* }
|
||||
* const options = {
|
||||
* hostname: 'github.com',
|
||||
* port: 443,
|
||||
* path: '/',
|
||||
* method: 'GET',
|
||||
* checkServerIdentity: function(host, cert) {
|
||||
* // Make sure the certificate is issued to the host we are connected to
|
||||
* const err = tls.checkServerIdentity(host, cert);
|
||||
* if (err) {
|
||||
* return err;
|
||||
* }
|
||||
*
|
||||
* // Pin the public key, similar to HPKP pin-sha256 pinning
|
||||
* const pubkey256 = 'pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU=';
|
||||
* if (sha256(cert.pubkey) !== pubkey256) {
|
||||
* const msg = 'Certificate verification error: ' +
|
||||
* `The public key of '${cert.subject.CN}' ` +
|
||||
* 'does not match our pinned fingerprint';
|
||||
* return new Error(msg);
|
||||
* }
|
||||
*
|
||||
* // Pin the exact certificate, rather than the pub key
|
||||
* const cert256 = '25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:' +
|
||||
* 'D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16';
|
||||
* if (cert.fingerprint256 !== cert256) {
|
||||
* const msg = 'Certificate verification error: ' +
|
||||
* `The certificate of '${cert.subject.CN}' ` +
|
||||
* 'does not match our pinned fingerprint';
|
||||
* return new Error(msg);
|
||||
* }
|
||||
*
|
||||
* // This loop is informational only.
|
||||
* // Print the certificate and public key fingerprints of all certs in the
|
||||
* // chain. Its common to pin the public key of the issuer on the public
|
||||
* // internet, while pinning the public key of the service in sensitive
|
||||
* // environments.
|
||||
* do {
|
||||
* console.log('Subject Common Name:', cert.subject.CN);
|
||||
* console.log(' Certificate SHA256 fingerprint:', cert.fingerprint256);
|
||||
*
|
||||
* hash = crypto.createHash('sha256');
|
||||
* console.log(' Public key ping-sha256:', sha256(cert.pubkey));
|
||||
*
|
||||
* lastprint256 = cert.fingerprint256;
|
||||
* cert = cert.issuerCertificate;
|
||||
* } while (cert.fingerprint256 !== lastprint256);
|
||||
*
|
||||
* },
|
||||
* };
|
||||
*
|
||||
* options.agent = new https.Agent(options);
|
||||
* const req = https.request(options, (res) => {
|
||||
* console.log('All OK. Server matched our pinned cert or public key');
|
||||
* console.log('statusCode:', res.statusCode);
|
||||
* // Print the HPKP values
|
||||
* console.log('headers:', res.headers['public-key-pins']);
|
||||
*
|
||||
* res.on('data', (d) => {});
|
||||
* });
|
||||
*
|
||||
* req.on('error', (e) => {
|
||||
* console.error(e.message);
|
||||
* });
|
||||
* req.end();
|
||||
* ```
|
||||
*
|
||||
* Outputs for example:
|
||||
*
|
||||
* ```text
|
||||
* Subject Common Name: github.com
|
||||
* Certificate SHA256 fingerprint: 25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16
|
||||
* Public key ping-sha256: pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU=
|
||||
* Subject Common Name: DigiCert SHA2 Extended Validation Server CA
|
||||
* Certificate SHA256 fingerprint: 40:3E:06:2A:26:53:05:91:13:28:5B:AF:80:A0:D4:AE:42:2C:84:8C:9F:78:FA:D0:1F:C9:4B:C5:B8:7F:EF:1A
|
||||
* Public key ping-sha256: RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho=
|
||||
* Subject Common Name: DigiCert High Assurance EV Root CA
|
||||
* Certificate SHA256 fingerprint: 74:31:E5:F4:C3:C1:CE:46:90:77:4F:0B:61:E0:54:40:88:3B:A9:A0:1E:D0:0B:A6:AB:D7:80:6E:D3:B1:18:CF
|
||||
* Public key ping-sha256: WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18=
|
||||
* All OK. Server matched our pinned cert or public key
|
||||
* statusCode: 200
|
||||
* headers: max-age=0; pin-sha256="WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18="; pin-sha256="RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho=";
|
||||
* pin-sha256="k2v657xBsOVe1PQRwOsHsw3bsGT2VzIqz5K+59sNQws="; pin-sha256="K87oWBWM9UZfyddvDfoxL+8lpNyoUB2ptGtn0fv6G2Q="; pin-sha256="IQBnNBEiFuhj+8x6X8XLgh01V9Ic5/V3IRQLNFFc7v4=";
|
||||
* pin-sha256="iie1VXtL7HzAMF+/PVPR9xzT80kQxdZeJ+zduCB3uj0="; pin-sha256="LvRiGEjRqfzurezaWuj8Wie2gyHMrW5Q06LspMnox7A="; includeSubDomains
|
||||
* ```
|
||||
* @since v0.3.6
|
||||
* @param options Accepts all `options` from `request`, with some differences in default values:
|
||||
*/
|
||||
function request(
|
||||
options: RequestOptions | string | URL,
|
||||
callback?: (res: http.IncomingMessage) => void,
|
||||
): http.ClientRequest;
|
||||
function request(
|
||||
url: string | URL,
|
||||
options: RequestOptions,
|
||||
callback?: (res: http.IncomingMessage) => void,
|
||||
): http.ClientRequest;
|
||||
/**
|
||||
* Like `http.get()` but for HTTPS.
|
||||
*
|
||||
* `options` can be an object, a string, or a `URL` object. If `options` is a
|
||||
* string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object.
|
||||
*
|
||||
* ```js
|
||||
* import https from 'node:https';
|
||||
*
|
||||
* https.get('https://encrypted.google.com/', (res) => {
|
||||
* console.log('statusCode:', res.statusCode);
|
||||
* console.log('headers:', res.headers);
|
||||
*
|
||||
* res.on('data', (d) => {
|
||||
* process.stdout.write(d);
|
||||
* });
|
||||
*
|
||||
* }).on('error', (e) => {
|
||||
* console.error(e);
|
||||
* });
|
||||
* ```
|
||||
* @since v0.3.6
|
||||
* @param options Accepts the same `options` as {@link request}, with the `method` always set to `GET`.
|
||||
*/
|
||||
function get(
|
||||
options: RequestOptions | string | URL,
|
||||
callback?: (res: http.IncomingMessage) => void,
|
||||
): http.ClientRequest;
|
||||
function get(
|
||||
url: string | URL,
|
||||
options: RequestOptions,
|
||||
callback?: (res: http.IncomingMessage) => void,
|
||||
): http.ClientRequest;
|
||||
let globalAgent: Agent;
|
||||
}
|
||||
declare module "node:https" {
|
||||
export * from "https";
|
||||
}
|
||||
101
node_modules/sitemap/node_modules/@types/node/index.d.ts
generated
vendored
Normal file
101
node_modules/sitemap/node_modules/@types/node/index.d.ts
generated
vendored
Normal file
@@ -0,0 +1,101 @@
|
||||
/**
|
||||
* License for programmatically and manually incorporated
|
||||
* documentation aka. `JSDoc` from https://github.com/nodejs/node/tree/master/doc
|
||||
*
|
||||
* Copyright Node.js contributors. All rights reserved.
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to
|
||||
* deal in the Software without restriction, including without limitation the
|
||||
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
|
||||
* sell copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
||||
* IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
// NOTE: These definitions support Node.js and TypeScript 5.8+.
|
||||
|
||||
// Reference required TypeScript libraries:
|
||||
/// <reference lib="es2020" />
|
||||
/// <reference lib="esnext.disposable" />
|
||||
/// <reference lib="esnext.float16" />
|
||||
|
||||
// Iterator definitions required for compatibility with TypeScript <5.6:
|
||||
/// <reference path="compatibility/iterators.d.ts" />
|
||||
|
||||
// Definitions for Node.js modules specific to TypeScript 5.7+:
|
||||
/// <reference path="globals.typedarray.d.ts" />
|
||||
/// <reference path="buffer.buffer.d.ts" />
|
||||
|
||||
// Definitions for Node.js modules that are not specific to any version of TypeScript:
|
||||
/// <reference path="globals.d.ts" />
|
||||
/// <reference path="web-globals/abortcontroller.d.ts" />
|
||||
/// <reference path="web-globals/crypto.d.ts" />
|
||||
/// <reference path="web-globals/domexception.d.ts" />
|
||||
/// <reference path="web-globals/events.d.ts" />
|
||||
/// <reference path="web-globals/fetch.d.ts" />
|
||||
/// <reference path="web-globals/navigator.d.ts" />
|
||||
/// <reference path="web-globals/storage.d.ts" />
|
||||
/// <reference path="web-globals/streams.d.ts" />
|
||||
/// <reference path="assert.d.ts" />
|
||||
/// <reference path="assert/strict.d.ts" />
|
||||
/// <reference path="async_hooks.d.ts" />
|
||||
/// <reference path="buffer.d.ts" />
|
||||
/// <reference path="child_process.d.ts" />
|
||||
/// <reference path="cluster.d.ts" />
|
||||
/// <reference path="console.d.ts" />
|
||||
/// <reference path="constants.d.ts" />
|
||||
/// <reference path="crypto.d.ts" />
|
||||
/// <reference path="dgram.d.ts" />
|
||||
/// <reference path="diagnostics_channel.d.ts" />
|
||||
/// <reference path="dns.d.ts" />
|
||||
/// <reference path="dns/promises.d.ts" />
|
||||
/// <reference path="domain.d.ts" />
|
||||
/// <reference path="events.d.ts" />
|
||||
/// <reference path="fs.d.ts" />
|
||||
/// <reference path="fs/promises.d.ts" />
|
||||
/// <reference path="http.d.ts" />
|
||||
/// <reference path="http2.d.ts" />
|
||||
/// <reference path="https.d.ts" />
|
||||
/// <reference path="inspector.d.ts" />
|
||||
/// <reference path="inspector.generated.d.ts" />
|
||||
/// <reference path="module.d.ts" />
|
||||
/// <reference path="net.d.ts" />
|
||||
/// <reference path="os.d.ts" />
|
||||
/// <reference path="path.d.ts" />
|
||||
/// <reference path="perf_hooks.d.ts" />
|
||||
/// <reference path="process.d.ts" />
|
||||
/// <reference path="punycode.d.ts" />
|
||||
/// <reference path="querystring.d.ts" />
|
||||
/// <reference path="readline.d.ts" />
|
||||
/// <reference path="readline/promises.d.ts" />
|
||||
/// <reference path="repl.d.ts" />
|
||||
/// <reference path="sea.d.ts" />
|
||||
/// <reference path="sqlite.d.ts" />
|
||||
/// <reference path="stream.d.ts" />
|
||||
/// <reference path="stream/promises.d.ts" />
|
||||
/// <reference path="stream/consumers.d.ts" />
|
||||
/// <reference path="stream/web.d.ts" />
|
||||
/// <reference path="string_decoder.d.ts" />
|
||||
/// <reference path="test.d.ts" />
|
||||
/// <reference path="timers.d.ts" />
|
||||
/// <reference path="timers/promises.d.ts" />
|
||||
/// <reference path="tls.d.ts" />
|
||||
/// <reference path="trace_events.d.ts" />
|
||||
/// <reference path="tty.d.ts" />
|
||||
/// <reference path="url.d.ts" />
|
||||
/// <reference path="util.d.ts" />
|
||||
/// <reference path="v8.d.ts" />
|
||||
/// <reference path="vm.d.ts" />
|
||||
/// <reference path="wasi.d.ts" />
|
||||
/// <reference path="worker_threads.d.ts" />
|
||||
/// <reference path="zlib.d.ts" />
|
||||
277
node_modules/sitemap/node_modules/@types/node/inspector.d.ts
generated
vendored
Normal file
277
node_modules/sitemap/node_modules/@types/node/inspector.d.ts
generated
vendored
Normal file
@@ -0,0 +1,277 @@
|
||||
/**
|
||||
* The `node:inspector` module provides an API for interacting with the V8
|
||||
* inspector.
|
||||
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/inspector.js)
|
||||
*/
|
||||
declare module "inspector" {
|
||||
import EventEmitter = require("node:events");
|
||||
/**
|
||||
* The `inspector.Session` is used for dispatching messages to the V8 inspector
|
||||
* back-end and receiving message responses and notifications.
|
||||
*/
|
||||
class Session extends EventEmitter {
|
||||
/**
|
||||
* Create a new instance of the inspector.Session class.
|
||||
* The inspector session needs to be connected through `session.connect()` before the messages can be dispatched to the inspector backend.
|
||||
*/
|
||||
constructor();
|
||||
/**
|
||||
* Connects a session to the inspector back-end.
|
||||
*/
|
||||
connect(): void;
|
||||
/**
|
||||
* Connects a session to the inspector back-end.
|
||||
* An exception will be thrown if this API was not called on a Worker thread.
|
||||
* @since v12.11.0
|
||||
*/
|
||||
connectToMainThread(): void;
|
||||
/**
|
||||
* Immediately close the session. All pending message callbacks will be called with an error.
|
||||
* `session.connect()` will need to be called to be able to send messages again.
|
||||
* Reconnected session will lose all inspector state, such as enabled agents or configured breakpoints.
|
||||
*/
|
||||
disconnect(): void;
|
||||
}
|
||||
/**
|
||||
* Activate inspector on host and port. Equivalent to `node --inspect=[[host:]port]`, but can be done programmatically after node has
|
||||
* started.
|
||||
*
|
||||
* If wait is `true`, will block until a client has connected to the inspect port
|
||||
* and flow control has been passed to the debugger client.
|
||||
*
|
||||
* See the [security warning](https://nodejs.org/docs/latest-v24.x/api/cli.html#warning-binding-inspector-to-a-public-ipport-combination-is-insecure)
|
||||
* regarding the `host` parameter usage.
|
||||
* @param port Port to listen on for inspector connections. Defaults to what was specified on the CLI.
|
||||
* @param host Host to listen on for inspector connections. Defaults to what was specified on the CLI.
|
||||
* @param wait Block until a client has connected. Defaults to what was specified on the CLI.
|
||||
* @returns Disposable that calls `inspector.close()`.
|
||||
*/
|
||||
function open(port?: number, host?: string, wait?: boolean): Disposable;
|
||||
/**
|
||||
* Deactivate the inspector. Blocks until there are no active connections.
|
||||
*/
|
||||
function close(): void;
|
||||
/**
|
||||
* Return the URL of the active inspector, or `undefined` if there is none.
|
||||
*
|
||||
* ```console
|
||||
* $ node --inspect -p 'inspector.url()'
|
||||
* Debugger listening on ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34
|
||||
* For help, see: https://nodejs.org/en/docs/inspector
|
||||
* ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34
|
||||
*
|
||||
* $ node --inspect=localhost:3000 -p 'inspector.url()'
|
||||
* Debugger listening on ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a
|
||||
* For help, see: https://nodejs.org/en/docs/inspector
|
||||
* ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a
|
||||
*
|
||||
* $ node -p 'inspector.url()'
|
||||
* undefined
|
||||
* ```
|
||||
*/
|
||||
function url(): string | undefined;
|
||||
/**
|
||||
* Blocks until a client (existing or connected later) has sent `Runtime.runIfWaitingForDebugger` command.
|
||||
*
|
||||
* An exception will be thrown if there is no active inspector.
|
||||
* @since v12.7.0
|
||||
*/
|
||||
function waitForDebugger(): void;
|
||||
// These methods are exposed by the V8 inspector console API (inspector/v8-console.h).
|
||||
// The method signatures differ from those of the Node.js console, and are deliberately
|
||||
// typed permissively.
|
||||
interface InspectorConsole {
|
||||
debug(...data: any[]): void;
|
||||
error(...data: any[]): void;
|
||||
info(...data: any[]): void;
|
||||
log(...data: any[]): void;
|
||||
warn(...data: any[]): void;
|
||||
dir(...data: any[]): void;
|
||||
dirxml(...data: any[]): void;
|
||||
table(...data: any[]): void;
|
||||
trace(...data: any[]): void;
|
||||
group(...data: any[]): void;
|
||||
groupCollapsed(...data: any[]): void;
|
||||
groupEnd(...data: any[]): void;
|
||||
clear(...data: any[]): void;
|
||||
count(label?: any): void;
|
||||
countReset(label?: any): void;
|
||||
assert(value?: any, ...data: any[]): void;
|
||||
profile(label?: any): void;
|
||||
profileEnd(label?: any): void;
|
||||
time(label?: any): void;
|
||||
timeLog(label?: any): void;
|
||||
timeStamp(label?: any): void;
|
||||
}
|
||||
/**
|
||||
* An object to send messages to the remote inspector console.
|
||||
* @since v11.0.0
|
||||
*/
|
||||
const console: InspectorConsole;
|
||||
// DevTools protocol event broadcast methods
|
||||
namespace Network {
|
||||
/**
|
||||
* This feature is only available with the `--experimental-network-inspection` flag enabled.
|
||||
*
|
||||
* Broadcasts the `Network.requestWillBeSent` event to connected frontends. This event indicates that
|
||||
* the application is about to send an HTTP request.
|
||||
* @since v22.6.0
|
||||
*/
|
||||
function requestWillBeSent(params: RequestWillBeSentEventDataType): void;
|
||||
/**
|
||||
* This feature is only available with the `--experimental-network-inspection` flag enabled.
|
||||
*
|
||||
* Broadcasts the `Network.dataReceived` event to connected frontends, or buffers the data if
|
||||
* `Network.streamResourceContent` command was not invoked for the given request yet.
|
||||
*
|
||||
* Also enables `Network.getResponseBody` command to retrieve the response data.
|
||||
* @since v24.2.0
|
||||
*/
|
||||
function dataReceived(params: DataReceivedEventDataType): void;
|
||||
/**
|
||||
* This feature is only available with the `--experimental-network-inspection` flag enabled.
|
||||
*
|
||||
* Enables `Network.getRequestPostData` command to retrieve the request data.
|
||||
* @since v24.3.0
|
||||
*/
|
||||
function dataSent(params: unknown): void;
|
||||
/**
|
||||
* This feature is only available with the `--experimental-network-inspection` flag enabled.
|
||||
*
|
||||
* Broadcasts the `Network.responseReceived` event to connected frontends. This event indicates that
|
||||
* HTTP response is available.
|
||||
* @since v22.6.0
|
||||
*/
|
||||
function responseReceived(params: ResponseReceivedEventDataType): void;
|
||||
/**
|
||||
* This feature is only available with the `--experimental-network-inspection` flag enabled.
|
||||
*
|
||||
* Broadcasts the `Network.loadingFinished` event to connected frontends. This event indicates that
|
||||
* HTTP request has finished loading.
|
||||
* @since v22.6.0
|
||||
*/
|
||||
function loadingFinished(params: LoadingFinishedEventDataType): void;
|
||||
/**
|
||||
* This feature is only available with the `--experimental-network-inspection` flag enabled.
|
||||
*
|
||||
* Broadcasts the `Network.loadingFailed` event to connected frontends. This event indicates that
|
||||
* HTTP request has failed to load.
|
||||
* @since v22.7.0
|
||||
*/
|
||||
function loadingFailed(params: LoadingFailedEventDataType): void;
|
||||
/**
|
||||
* This feature is only available with the `--experimental-network-inspection` flag enabled.
|
||||
*
|
||||
* Broadcasts the `Network.webSocketCreated` event to connected frontends. This event indicates that
|
||||
* a WebSocket connection has been initiated.
|
||||
* @since v24.7.0
|
||||
*/
|
||||
function webSocketCreated(params: WebSocketCreatedEventDataType): void;
|
||||
/**
|
||||
* This feature is only available with the `--experimental-network-inspection` flag enabled.
|
||||
*
|
||||
* Broadcasts the `Network.webSocketHandshakeResponseReceived` event to connected frontends.
|
||||
* This event indicates that the WebSocket handshake response has been received.
|
||||
* @since v24.7.0
|
||||
*/
|
||||
function webSocketHandshakeResponseReceived(params: WebSocketHandshakeResponseReceivedEventDataType): void;
|
||||
/**
|
||||
* This feature is only available with the `--experimental-network-inspection` flag enabled.
|
||||
*
|
||||
* Broadcasts the `Network.webSocketClosed` event to connected frontends.
|
||||
* This event indicates that a WebSocket connection has been closed.
|
||||
* @since v24.7.0
|
||||
*/
|
||||
function webSocketClosed(params: WebSocketClosedEventDataType): void;
|
||||
}
|
||||
namespace NetworkResources {
|
||||
/**
|
||||
* This feature is only available with the `--experimental-inspector-network-resource` flag enabled.
|
||||
*
|
||||
* The inspector.NetworkResources.put method is used to provide a response for a loadNetworkResource
|
||||
* request issued via the Chrome DevTools Protocol (CDP).
|
||||
* This is typically triggered when a source map is specified by URL, and a DevTools frontend—such as
|
||||
* Chrome—requests the resource to retrieve the source map.
|
||||
*
|
||||
* This method allows developers to predefine the resource content to be served in response to such CDP requests.
|
||||
*
|
||||
* ```js
|
||||
* const inspector = require('node:inspector');
|
||||
* // By preemptively calling put to register the resource, a source map can be resolved when
|
||||
* // a loadNetworkResource request is made from the frontend.
|
||||
* async function setNetworkResources() {
|
||||
* const mapUrl = 'http://localhost:3000/dist/app.js.map';
|
||||
* const tsUrl = 'http://localhost:3000/src/app.ts';
|
||||
* const distAppJsMap = await fetch(mapUrl).then((res) => res.text());
|
||||
* const srcAppTs = await fetch(tsUrl).then((res) => res.text());
|
||||
* inspector.NetworkResources.put(mapUrl, distAppJsMap);
|
||||
* inspector.NetworkResources.put(tsUrl, srcAppTs);
|
||||
* };
|
||||
* setNetworkResources().then(() => {
|
||||
* require('./dist/app');
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* For more details, see the official CDP documentation: [Network.loadNetworkResource](https://chromedevtools.github.io/devtools-protocol/tot/Network/#method-loadNetworkResource)
|
||||
* @since v24.5.0
|
||||
* @experimental
|
||||
*/
|
||||
function put(url: string, data: string): void;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The `node:inspector` module provides an API for interacting with the V8
|
||||
* inspector.
|
||||
*/
|
||||
declare module "node:inspector" {
|
||||
export * from "inspector";
|
||||
}
|
||||
|
||||
/**
|
||||
* The `node:inspector/promises` module provides an API for interacting with the V8
|
||||
* inspector.
|
||||
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/inspector/promises.js)
|
||||
* @since v19.0.0
|
||||
*/
|
||||
declare module "inspector/promises" {
|
||||
import EventEmitter = require("node:events");
|
||||
export { close, console, NetworkResources, open, url, waitForDebugger } from "inspector";
|
||||
/**
|
||||
* The `inspector.Session` is used for dispatching messages to the V8 inspector
|
||||
* back-end and receiving message responses and notifications.
|
||||
* @since v19.0.0
|
||||
*/
|
||||
export class Session extends EventEmitter {
|
||||
/**
|
||||
* Create a new instance of the inspector.Session class.
|
||||
* The inspector session needs to be connected through `session.connect()` before the messages can be dispatched to the inspector backend.
|
||||
*/
|
||||
constructor();
|
||||
/**
|
||||
* Connects a session to the inspector back-end.
|
||||
*/
|
||||
connect(): void;
|
||||
/**
|
||||
* Connects a session to the inspector back-end.
|
||||
* An exception will be thrown if this API was not called on a Worker thread.
|
||||
* @since v12.11.0
|
||||
*/
|
||||
connectToMainThread(): void;
|
||||
/**
|
||||
* Immediately close the session. All pending message callbacks will be called with an error.
|
||||
* `session.connect()` will need to be called to be able to send messages again.
|
||||
* Reconnected session will lose all inspector state, such as enabled agents or configured breakpoints.
|
||||
*/
|
||||
disconnect(): void;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The `node:inspector/promises` module provides an API for interacting with the V8
|
||||
* inspector.
|
||||
* @since v19.0.0
|
||||
*/
|
||||
declare module "node:inspector/promises" {
|
||||
export * from "inspector/promises";
|
||||
}
|
||||
4246
node_modules/sitemap/node_modules/@types/node/inspector.generated.d.ts
generated
vendored
Normal file
4246
node_modules/sitemap/node_modules/@types/node/inspector.generated.d.ts
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
905
node_modules/sitemap/node_modules/@types/node/module.d.ts
generated
vendored
Normal file
905
node_modules/sitemap/node_modules/@types/node/module.d.ts
generated
vendored
Normal file
@@ -0,0 +1,905 @@
|
||||
/**
|
||||
* @since v0.3.7
|
||||
*/
|
||||
declare module "module" {
|
||||
import { URL } from "node:url";
|
||||
class Module {
|
||||
constructor(id: string, parent?: Module);
|
||||
}
|
||||
interface Module extends NodeJS.Module {}
|
||||
namespace Module {
|
||||
export { Module };
|
||||
}
|
||||
namespace Module {
|
||||
/**
|
||||
* A list of the names of all modules provided by Node.js. Can be used to verify
|
||||
* if a module is maintained by a third party or not.
|
||||
*
|
||||
* Note: the list doesn't contain prefix-only modules like `node:test`.
|
||||
* @since v9.3.0, v8.10.0, v6.13.0
|
||||
*/
|
||||
const builtinModules: readonly string[];
|
||||
/**
|
||||
* @since v12.2.0
|
||||
* @param path Filename to be used to construct the require
|
||||
* function. Must be a file URL object, file URL string, or absolute path
|
||||
* string.
|
||||
*/
|
||||
function createRequire(path: string | URL): NodeJS.Require;
|
||||
namespace constants {
|
||||
/**
|
||||
* The following constants are returned as the `status` field in the object returned by
|
||||
* {@link enableCompileCache} to indicate the result of the attempt to enable the
|
||||
* [module compile cache](https://nodejs.org/docs/latest-v24.x/api/module.html#module-compile-cache).
|
||||
* @since v22.8.0
|
||||
*/
|
||||
namespace compileCacheStatus {
|
||||
/**
|
||||
* Node.js has enabled the compile cache successfully. The directory used to store the
|
||||
* compile cache will be returned in the `directory` field in the
|
||||
* returned object.
|
||||
*/
|
||||
const ENABLED: number;
|
||||
/**
|
||||
* The compile cache has already been enabled before, either by a previous call to
|
||||
* {@link enableCompileCache}, or by the `NODE_COMPILE_CACHE=dir`
|
||||
* environment variable. The directory used to store the
|
||||
* compile cache will be returned in the `directory` field in the
|
||||
* returned object.
|
||||
*/
|
||||
const ALREADY_ENABLED: number;
|
||||
/**
|
||||
* Node.js fails to enable the compile cache. This can be caused by the lack of
|
||||
* permission to use the specified directory, or various kinds of file system errors.
|
||||
* The detail of the failure will be returned in the `message` field in the
|
||||
* returned object.
|
||||
*/
|
||||
const FAILED: number;
|
||||
/**
|
||||
* Node.js cannot enable the compile cache because the environment variable
|
||||
* `NODE_DISABLE_COMPILE_CACHE=1` has been set.
|
||||
*/
|
||||
const DISABLED: number;
|
||||
}
|
||||
}
|
||||
interface EnableCompileCacheResult {
|
||||
/**
|
||||
* One of the {@link constants.compileCacheStatus}
|
||||
*/
|
||||
status: number;
|
||||
/**
|
||||
* If Node.js cannot enable the compile cache, this contains
|
||||
* the error message. Only set if `status` is `module.constants.compileCacheStatus.FAILED`.
|
||||
*/
|
||||
message?: string;
|
||||
/**
|
||||
* If the compile cache is enabled, this contains the directory
|
||||
* where the compile cache is stored. Only set if `status` is
|
||||
* `module.constants.compileCacheStatus.ENABLED` or
|
||||
* `module.constants.compileCacheStatus.ALREADY_ENABLED`.
|
||||
*/
|
||||
directory?: string;
|
||||
}
|
||||
interface EnableCompileCacheOptions {
|
||||
/**
|
||||
* Optional. Directory to store the compile cache. If not specified, the directory specified by
|
||||
* the [`NODE_COMPILE_CACHE=dir`](https://nodejs.org/docs/latest-v24.x/api/cli.html#node_compile_cachedir)
|
||||
* environment variable will be used if it's set, or `path.join(os.tmpdir(), 'node-compile-cache')` otherwise.
|
||||
* @since v24.12.0
|
||||
*/
|
||||
directory?: string | undefined;
|
||||
/**
|
||||
* Optional. If `true`, enables portable compile cache so that the cache can be reused even if the project directory
|
||||
* is moved. This is a best-effort feature. If not specified, it will depend on whether the environment variable
|
||||
* [NODE_COMPILE_CACHE_PORTABLE=1](https://nodejs.org/docs/latest-v24.x/api/cli.html#node_compile_cache_portable1) is set.
|
||||
* @since v24.12.0
|
||||
*/
|
||||
portable?: boolean | undefined;
|
||||
}
|
||||
/**
|
||||
* Enable [module compile cache](https://nodejs.org/docs/latest-v24.x/api/module.html#module-compile-cache)
|
||||
* in the current Node.js instance.
|
||||
*
|
||||
* For general use cases, it's recommended to call `module.enableCompileCache()` without specifying the
|
||||
* `options.directory`, so that the directory can be overridden by the `NODE_COMPILE_CACHE` environment
|
||||
* variable when necessary.
|
||||
*
|
||||
* Since compile cache is supposed to be a optimization that is not mission critical, this method is
|
||||
* designed to not throw any exception when the compile cache cannot be enabled. Instead, it will return
|
||||
* an object containing an error message in the `message` field to aid debugging. If compile cache is
|
||||
* enabled successfully, the `directory` field in the returned object contains the path to the directory
|
||||
* where the compile cache is stored. The `status` field in the returned object would be one of the
|
||||
* `module.constants.compileCacheStatus` values to indicate the result of the attempt to enable the
|
||||
* [module compile cache](https://nodejs.org/docs/latest-v24.x/api/module.html#module-compile-cache).
|
||||
*
|
||||
* This method only affects the current Node.js instance. To enable it in child worker threads,
|
||||
* either call this method in child worker threads too, or set the
|
||||
* `process.env.NODE_COMPILE_CACHE` value to compile cache directory so the behavior can
|
||||
* be inherited into the child workers. The directory can be obtained either from the
|
||||
* `directory` field returned by this method, or with {@link getCompileCacheDir `module.getCompileCacheDir()`}.
|
||||
* @since v22.8.0
|
||||
* @param options Optional. If a string is passed, it is considered to be `options.directory`.
|
||||
* will be stored/retrieved.
|
||||
*/
|
||||
function enableCompileCache(options?: string | EnableCompileCacheOptions): EnableCompileCacheResult;
|
||||
/**
|
||||
* Flush the [module compile cache](https://nodejs.org/docs/latest-v24.x/api/module.html#module-compile-cache)
|
||||
* accumulated from modules already loaded
|
||||
* in the current Node.js instance to disk. This returns after all the flushing
|
||||
* file system operations come to an end, no matter they succeed or not. If there
|
||||
* are any errors, this will fail silently, since compile cache misses should not
|
||||
* interfere with the actual operation of the application.
|
||||
* @since v22.10.0
|
||||
*/
|
||||
function flushCompileCache(): void;
|
||||
/**
|
||||
* @since v22.8.0
|
||||
* @return Path to the [module compile cache](https://nodejs.org/docs/latest-v24.x/api/module.html#module-compile-cache)
|
||||
* directory if it is enabled, or `undefined` otherwise.
|
||||
*/
|
||||
function getCompileCacheDir(): string | undefined;
|
||||
/**
|
||||
* ```text
|
||||
* /path/to/project
|
||||
* ├ packages/
|
||||
* ├ bar/
|
||||
* ├ bar.js
|
||||
* └ package.json // name = '@foo/bar'
|
||||
* └ qux/
|
||||
* ├ node_modules/
|
||||
* └ some-package/
|
||||
* └ package.json // name = 'some-package'
|
||||
* ├ qux.js
|
||||
* └ package.json // name = '@foo/qux'
|
||||
* ├ main.js
|
||||
* └ package.json // name = '@foo'
|
||||
* ```
|
||||
* ```js
|
||||
* // /path/to/project/packages/bar/bar.js
|
||||
* import { findPackageJSON } from 'node:module';
|
||||
*
|
||||
* findPackageJSON('..', import.meta.url);
|
||||
* // '/path/to/project/package.json'
|
||||
* // Same result when passing an absolute specifier instead:
|
||||
* findPackageJSON(new URL('../', import.meta.url));
|
||||
* findPackageJSON(import.meta.resolve('../'));
|
||||
*
|
||||
* findPackageJSON('some-package', import.meta.url);
|
||||
* // '/path/to/project/packages/bar/node_modules/some-package/package.json'
|
||||
* // When passing an absolute specifier, you might get a different result if the
|
||||
* // resolved module is inside a subfolder that has nested `package.json`.
|
||||
* findPackageJSON(import.meta.resolve('some-package'));
|
||||
* // '/path/to/project/packages/bar/node_modules/some-package/some-subfolder/package.json'
|
||||
*
|
||||
* findPackageJSON('@foo/qux', import.meta.url);
|
||||
* // '/path/to/project/packages/qux/package.json'
|
||||
* ```
|
||||
* @since v22.14.0
|
||||
* @param specifier The specifier for the module whose `package.json` to
|
||||
* retrieve. When passing a _bare specifier_, the `package.json` at the root of
|
||||
* the package is returned. When passing a _relative specifier_ or an _absolute specifier_,
|
||||
* the closest parent `package.json` is returned.
|
||||
* @param base The absolute location (`file:` URL string or FS path) of the
|
||||
* containing module. For CJS, use `__filename` (not `__dirname`!); for ESM, use
|
||||
* `import.meta.url`. You do not need to pass it if `specifier` is an _absolute specifier_.
|
||||
* @returns A path if the `package.json` is found. When `startLocation`
|
||||
* is a package, the package's root `package.json`; when a relative or unresolved, the closest
|
||||
* `package.json` to the `startLocation`.
|
||||
*/
|
||||
function findPackageJSON(specifier: string | URL, base?: string | URL): string | undefined;
|
||||
/**
|
||||
* @since v18.6.0, v16.17.0
|
||||
*/
|
||||
function isBuiltin(moduleName: string): boolean;
|
||||
interface RegisterOptions<Data> {
|
||||
/**
|
||||
* If you want to resolve `specifier` relative to a
|
||||
* base URL, such as `import.meta.url`, you can pass that URL here. This
|
||||
* property is ignored if the `parentURL` is supplied as the second argument.
|
||||
* @default 'data:'
|
||||
*/
|
||||
parentURL?: string | URL | undefined;
|
||||
/**
|
||||
* Any arbitrary, cloneable JavaScript value to pass into the
|
||||
* {@link initialize} hook.
|
||||
*/
|
||||
data?: Data | undefined;
|
||||
/**
|
||||
* [Transferable objects](https://nodejs.org/docs/latest-v24.x/api/worker_threads.html#portpostmessagevalue-transferlist)
|
||||
* to be passed into the `initialize` hook.
|
||||
*/
|
||||
transferList?: any[] | undefined;
|
||||
}
|
||||
/* eslint-disable @definitelytyped/no-unnecessary-generics */
|
||||
/**
|
||||
* Register a module that exports hooks that customize Node.js module
|
||||
* resolution and loading behavior. See
|
||||
* [Customization hooks](https://nodejs.org/docs/latest-v24.x/api/module.html#customization-hooks).
|
||||
*
|
||||
* This feature requires `--allow-worker` if used with the
|
||||
* [Permission Model](https://nodejs.org/docs/latest-v24.x/api/permissions.html#permission-model).
|
||||
* @since v20.6.0, v18.19.0
|
||||
* @param specifier Customization hooks to be registered; this should be
|
||||
* the same string that would be passed to `import()`, except that if it is
|
||||
* relative, it is resolved relative to `parentURL`.
|
||||
* @param parentURL f you want to resolve `specifier` relative to a base
|
||||
* URL, such as `import.meta.url`, you can pass that URL here.
|
||||
*/
|
||||
function register<Data = any>(
|
||||
specifier: string | URL,
|
||||
parentURL?: string | URL,
|
||||
options?: RegisterOptions<Data>,
|
||||
): void;
|
||||
function register<Data = any>(specifier: string | URL, options?: RegisterOptions<Data>): void;
|
||||
interface RegisterHooksOptions {
|
||||
/**
|
||||
* See [load hook](https://nodejs.org/docs/latest-v24.x/api/module.html#loadurl-context-nextload).
|
||||
* @default undefined
|
||||
*/
|
||||
load?: LoadHookSync | undefined;
|
||||
/**
|
||||
* See [resolve hook](https://nodejs.org/docs/latest-v24.x/api/module.html#resolvespecifier-context-nextresolve).
|
||||
* @default undefined
|
||||
*/
|
||||
resolve?: ResolveHookSync | undefined;
|
||||
}
|
||||
interface ModuleHooks {
|
||||
/**
|
||||
* Deregister the hook instance.
|
||||
*/
|
||||
deregister(): void;
|
||||
}
|
||||
/**
|
||||
* Register [hooks](https://nodejs.org/docs/latest-v24.x/api/module.html#customization-hooks)
|
||||
* that customize Node.js module resolution and loading behavior.
|
||||
* @since v22.15.0
|
||||
* @experimental
|
||||
*/
|
||||
function registerHooks(options: RegisterHooksOptions): ModuleHooks;
|
||||
interface StripTypeScriptTypesOptions {
|
||||
/**
|
||||
* Possible values are:
|
||||
* * `'strip'` Only strip type annotations without performing the transformation of TypeScript features.
|
||||
* * `'transform'` Strip type annotations and transform TypeScript features to JavaScript.
|
||||
* @default 'strip'
|
||||
*/
|
||||
mode?: "strip" | "transform" | undefined;
|
||||
/**
|
||||
* Only when `mode` is `'transform'`, if `true`, a source map
|
||||
* will be generated for the transformed code.
|
||||
* @default false
|
||||
*/
|
||||
sourceMap?: boolean | undefined;
|
||||
/**
|
||||
* Specifies the source url used in the source map.
|
||||
*/
|
||||
sourceUrl?: string | undefined;
|
||||
}
|
||||
/**
|
||||
* `module.stripTypeScriptTypes()` removes type annotations from TypeScript code. It
|
||||
* can be used to strip type annotations from TypeScript code before running it
|
||||
* with `vm.runInContext()` or `vm.compileFunction()`.
|
||||
* By default, it will throw an error if the code contains TypeScript features
|
||||
* that require transformation such as `Enums`,
|
||||
* see [type-stripping](https://nodejs.org/docs/latest-v24.x/api/typescript.md#type-stripping) for more information.
|
||||
* When mode is `'transform'`, it also transforms TypeScript features to JavaScript,
|
||||
* see [transform TypeScript features](https://nodejs.org/docs/latest-v24.x/api/typescript.md#typescript-features) for more information.
|
||||
* When mode is `'strip'`, source maps are not generated, because locations are preserved.
|
||||
* If `sourceMap` is provided, when mode is `'strip'`, an error will be thrown.
|
||||
*
|
||||
* _WARNING_: The output of this function should not be considered stable across Node.js versions,
|
||||
* due to changes in the TypeScript parser.
|
||||
*
|
||||
* ```js
|
||||
* import { stripTypeScriptTypes } from 'node:module';
|
||||
* const code = 'const a: number = 1;';
|
||||
* const strippedCode = stripTypeScriptTypes(code);
|
||||
* console.log(strippedCode);
|
||||
* // Prints: const a = 1;
|
||||
* ```
|
||||
*
|
||||
* If `sourceUrl` is provided, it will be used appended as a comment at the end of the output:
|
||||
*
|
||||
* ```js
|
||||
* import { stripTypeScriptTypes } from 'node:module';
|
||||
* const code = 'const a: number = 1;';
|
||||
* const strippedCode = stripTypeScriptTypes(code, { mode: 'strip', sourceUrl: 'source.ts' });
|
||||
* console.log(strippedCode);
|
||||
* // Prints: const a = 1\n\n//# sourceURL=source.ts;
|
||||
* ```
|
||||
*
|
||||
* When `mode` is `'transform'`, the code is transformed to JavaScript:
|
||||
*
|
||||
* ```js
|
||||
* import { stripTypeScriptTypes } from 'node:module';
|
||||
* const code = `
|
||||
* namespace MathUtil {
|
||||
* export const add = (a: number, b: number) => a + b;
|
||||
* }`;
|
||||
* const strippedCode = stripTypeScriptTypes(code, { mode: 'transform', sourceMap: true });
|
||||
* console.log(strippedCode);
|
||||
* // Prints:
|
||||
* // var MathUtil;
|
||||
* // (function(MathUtil) {
|
||||
* // MathUtil.add = (a, b)=>a + b;
|
||||
* // })(MathUtil || (MathUtil = {}));
|
||||
* // # sourceMappingURL=data:application/json;base64, ...
|
||||
* ```
|
||||
* @since v22.13.0
|
||||
* @param code The code to strip type annotations from.
|
||||
* @returns The code with type annotations stripped.
|
||||
*/
|
||||
function stripTypeScriptTypes(code: string, options?: StripTypeScriptTypesOptions): string;
|
||||
/* eslint-enable @definitelytyped/no-unnecessary-generics */
|
||||
/**
|
||||
* The `module.syncBuiltinESMExports()` method updates all the live bindings for
|
||||
* builtin `ES Modules` to match the properties of the `CommonJS` exports. It
|
||||
* does not add or remove exported names from the `ES Modules`.
|
||||
*
|
||||
* ```js
|
||||
* import fs from 'node:fs';
|
||||
* import assert from 'node:assert';
|
||||
* import { syncBuiltinESMExports } from 'node:module';
|
||||
*
|
||||
* fs.readFile = newAPI;
|
||||
*
|
||||
* delete fs.readFileSync;
|
||||
*
|
||||
* function newAPI() {
|
||||
* // ...
|
||||
* }
|
||||
*
|
||||
* fs.newAPI = newAPI;
|
||||
*
|
||||
* syncBuiltinESMExports();
|
||||
*
|
||||
* import('node:fs').then((esmFS) => {
|
||||
* // It syncs the existing readFile property with the new value
|
||||
* assert.strictEqual(esmFS.readFile, newAPI);
|
||||
* // readFileSync has been deleted from the required fs
|
||||
* assert.strictEqual('readFileSync' in fs, false);
|
||||
* // syncBuiltinESMExports() does not remove readFileSync from esmFS
|
||||
* assert.strictEqual('readFileSync' in esmFS, true);
|
||||
* // syncBuiltinESMExports() does not add names
|
||||
* assert.strictEqual(esmFS.newAPI, undefined);
|
||||
* });
|
||||
* ```
|
||||
* @since v12.12.0
|
||||
*/
|
||||
function syncBuiltinESMExports(): void;
|
||||
interface ImportAttributes extends NodeJS.Dict<string> {
|
||||
type?: string | undefined;
|
||||
}
|
||||
type ImportPhase = "source" | "evaluation";
|
||||
type ModuleFormat =
|
||||
| "addon"
|
||||
| "builtin"
|
||||
| "commonjs"
|
||||
| "commonjs-typescript"
|
||||
| "json"
|
||||
| "module"
|
||||
| "module-typescript"
|
||||
| "wasm";
|
||||
type ModuleSource = string | ArrayBuffer | NodeJS.TypedArray;
|
||||
/**
|
||||
* The `initialize` hook provides a way to define a custom function that runs in
|
||||
* the hooks thread when the hooks module is initialized. Initialization happens
|
||||
* when the hooks module is registered via {@link register}.
|
||||
*
|
||||
* This hook can receive data from a {@link register} invocation, including
|
||||
* ports and other transferable objects. The return value of `initialize` can be a
|
||||
* `Promise`, in which case it will be awaited before the main application thread
|
||||
* execution resumes.
|
||||
*/
|
||||
type InitializeHook<Data = any> = (data: Data) => void | Promise<void>;
|
||||
interface ResolveHookContext {
|
||||
/**
|
||||
* Export conditions of the relevant `package.json`
|
||||
*/
|
||||
conditions: string[];
|
||||
/**
|
||||
* An object whose key-value pairs represent the assertions for the module to import
|
||||
*/
|
||||
importAttributes: ImportAttributes;
|
||||
/**
|
||||
* The module importing this one, or undefined if this is the Node.js entry point
|
||||
*/
|
||||
parentURL: string | undefined;
|
||||
}
|
||||
interface ResolveFnOutput {
|
||||
/**
|
||||
* A hint to the load hook (it might be ignored); can be an intermediary value.
|
||||
*/
|
||||
format?: string | null | undefined;
|
||||
/**
|
||||
* The import attributes to use when caching the module (optional; if excluded the input will be used)
|
||||
*/
|
||||
importAttributes?: ImportAttributes | undefined;
|
||||
/**
|
||||
* A signal that this hook intends to terminate the chain of `resolve` hooks.
|
||||
* @default false
|
||||
*/
|
||||
shortCircuit?: boolean | undefined;
|
||||
/**
|
||||
* The absolute URL to which this input resolves
|
||||
*/
|
||||
url: string;
|
||||
}
|
||||
/**
|
||||
* The `resolve` hook chain is responsible for telling Node.js where to find and
|
||||
* how to cache a given `import` statement or expression, or `require` call. It can
|
||||
* optionally return a format (such as `'module'`) as a hint to the `load` hook. If
|
||||
* a format is specified, the `load` hook is ultimately responsible for providing
|
||||
* the final `format` value (and it is free to ignore the hint provided by
|
||||
* `resolve`); if `resolve` provides a `format`, a custom `load` hook is required
|
||||
* even if only to pass the value to the Node.js default `load` hook.
|
||||
*/
|
||||
type ResolveHook = (
|
||||
specifier: string,
|
||||
context: ResolveHookContext,
|
||||
nextResolve: (
|
||||
specifier: string,
|
||||
context?: Partial<ResolveHookContext>,
|
||||
) => ResolveFnOutput | Promise<ResolveFnOutput>,
|
||||
) => ResolveFnOutput | Promise<ResolveFnOutput>;
|
||||
type ResolveHookSync = (
|
||||
specifier: string,
|
||||
context: ResolveHookContext,
|
||||
nextResolve: (
|
||||
specifier: string,
|
||||
context?: Partial<ResolveHookContext>,
|
||||
) => ResolveFnOutput,
|
||||
) => ResolveFnOutput;
|
||||
interface LoadHookContext {
|
||||
/**
|
||||
* Export conditions of the relevant `package.json`
|
||||
*/
|
||||
conditions: string[];
|
||||
/**
|
||||
* The format optionally supplied by the `resolve` hook chain (can be an intermediary value).
|
||||
*/
|
||||
format: string | null | undefined;
|
||||
/**
|
||||
* An object whose key-value pairs represent the assertions for the module to import
|
||||
*/
|
||||
importAttributes: ImportAttributes;
|
||||
}
|
||||
interface LoadFnOutput {
|
||||
format: string | null | undefined;
|
||||
/**
|
||||
* A signal that this hook intends to terminate the chain of `resolve` hooks.
|
||||
* @default false
|
||||
*/
|
||||
shortCircuit?: boolean | undefined;
|
||||
/**
|
||||
* The source for Node.js to evaluate
|
||||
*/
|
||||
source?: ModuleSource | undefined;
|
||||
}
|
||||
/**
|
||||
* The `load` hook provides a way to define a custom method of determining how a
|
||||
* URL should be interpreted, retrieved, and parsed. It is also in charge of
|
||||
* validating the import attributes.
|
||||
*/
|
||||
type LoadHook = (
|
||||
url: string,
|
||||
context: LoadHookContext,
|
||||
nextLoad: (
|
||||
url: string,
|
||||
context?: Partial<LoadHookContext>,
|
||||
) => LoadFnOutput | Promise<LoadFnOutput>,
|
||||
) => LoadFnOutput | Promise<LoadFnOutput>;
|
||||
type LoadHookSync = (
|
||||
url: string,
|
||||
context: LoadHookContext,
|
||||
nextLoad: (
|
||||
url: string,
|
||||
context?: Partial<LoadHookContext>,
|
||||
) => LoadFnOutput,
|
||||
) => LoadFnOutput;
|
||||
interface SourceMapsSupport {
|
||||
/**
|
||||
* If the source maps support is enabled
|
||||
*/
|
||||
enabled: boolean;
|
||||
/**
|
||||
* If the support is enabled for files in `node_modules`.
|
||||
*/
|
||||
nodeModules: boolean;
|
||||
/**
|
||||
* If the support is enabled for generated code from `eval` or `new Function`.
|
||||
*/
|
||||
generatedCode: boolean;
|
||||
}
|
||||
/**
|
||||
* This method returns whether the [Source Map v3](https://tc39.es/ecma426/) support for stack
|
||||
* traces is enabled.
|
||||
* @since v23.7.0, v22.14.0
|
||||
*/
|
||||
function getSourceMapsSupport(): SourceMapsSupport;
|
||||
/**
|
||||
* `path` is the resolved path for the file for which a corresponding source map
|
||||
* should be fetched.
|
||||
* @since v13.7.0, v12.17.0
|
||||
* @return Returns `module.SourceMap` if a source map is found, `undefined` otherwise.
|
||||
*/
|
||||
function findSourceMap(path: string): SourceMap | undefined;
|
||||
interface SetSourceMapsSupportOptions {
|
||||
/**
|
||||
* If enabling the support for files in `node_modules`.
|
||||
* @default false
|
||||
*/
|
||||
nodeModules?: boolean | undefined;
|
||||
/**
|
||||
* If enabling the support for generated code from `eval` or `new Function`.
|
||||
* @default false
|
||||
*/
|
||||
generatedCode?: boolean | undefined;
|
||||
}
|
||||
/**
|
||||
* This function enables or disables the [Source Map v3](https://tc39.es/ecma426/) support for
|
||||
* stack traces.
|
||||
*
|
||||
* It provides same features as launching Node.js process with commandline options
|
||||
* `--enable-source-maps`, with additional options to alter the support for files
|
||||
* in `node_modules` or generated codes.
|
||||
*
|
||||
* Only source maps in JavaScript files that are loaded after source maps has been
|
||||
* enabled will be parsed and loaded. Preferably, use the commandline options
|
||||
* `--enable-source-maps` to avoid losing track of source maps of modules loaded
|
||||
* before this API call.
|
||||
* @since v23.7.0, v22.14.0
|
||||
*/
|
||||
function setSourceMapsSupport(enabled: boolean, options?: SetSourceMapsSupportOptions): void;
|
||||
interface SourceMapConstructorOptions {
|
||||
/**
|
||||
* @since v21.0.0, v20.5.0
|
||||
*/
|
||||
lineLengths?: readonly number[] | undefined;
|
||||
}
|
||||
interface SourceMapPayload {
|
||||
file: string;
|
||||
version: number;
|
||||
sources: string[];
|
||||
sourcesContent: string[];
|
||||
names: string[];
|
||||
mappings: string;
|
||||
sourceRoot: string;
|
||||
}
|
||||
interface SourceMapping {
|
||||
generatedLine: number;
|
||||
generatedColumn: number;
|
||||
originalSource: string;
|
||||
originalLine: number;
|
||||
originalColumn: number;
|
||||
}
|
||||
interface SourceOrigin {
|
||||
/**
|
||||
* The name of the range in the source map, if one was provided
|
||||
*/
|
||||
name: string | undefined;
|
||||
/**
|
||||
* The file name of the original source, as reported in the SourceMap
|
||||
*/
|
||||
fileName: string;
|
||||
/**
|
||||
* The 1-indexed lineNumber of the corresponding call site in the original source
|
||||
*/
|
||||
lineNumber: number;
|
||||
/**
|
||||
* The 1-indexed columnNumber of the corresponding call site in the original source
|
||||
*/
|
||||
columnNumber: number;
|
||||
}
|
||||
/**
|
||||
* @since v13.7.0, v12.17.0
|
||||
*/
|
||||
class SourceMap {
|
||||
constructor(payload: SourceMapPayload, options?: SourceMapConstructorOptions);
|
||||
/**
|
||||
* Getter for the payload used to construct the `SourceMap` instance.
|
||||
*/
|
||||
readonly payload: SourceMapPayload;
|
||||
/**
|
||||
* Given a line offset and column offset in the generated source
|
||||
* file, returns an object representing the SourceMap range in the
|
||||
* original file if found, or an empty object if not.
|
||||
*
|
||||
* The object returned contains the following keys:
|
||||
*
|
||||
* The returned value represents the raw range as it appears in the
|
||||
* SourceMap, based on zero-indexed offsets, _not_ 1-indexed line and
|
||||
* column numbers as they appear in Error messages and CallSite
|
||||
* objects.
|
||||
*
|
||||
* To get the corresponding 1-indexed line and column numbers from a
|
||||
* lineNumber and columnNumber as they are reported by Error stacks
|
||||
* and CallSite objects, use `sourceMap.findOrigin(lineNumber, columnNumber)`
|
||||
* @param lineOffset The zero-indexed line number offset in the generated source
|
||||
* @param columnOffset The zero-indexed column number offset in the generated source
|
||||
*/
|
||||
findEntry(lineOffset: number, columnOffset: number): SourceMapping | {};
|
||||
/**
|
||||
* Given a 1-indexed `lineNumber` and `columnNumber` from a call site in the generated source,
|
||||
* find the corresponding call site location in the original source.
|
||||
*
|
||||
* If the `lineNumber` and `columnNumber` provided are not found in any source map,
|
||||
* then an empty object is returned.
|
||||
* @param lineNumber The 1-indexed line number of the call site in the generated source
|
||||
* @param columnNumber The 1-indexed column number of the call site in the generated source
|
||||
*/
|
||||
findOrigin(lineNumber: number, columnNumber: number): SourceOrigin | {};
|
||||
}
|
||||
function runMain(main?: string): void;
|
||||
function wrap(script: string): string;
|
||||
}
|
||||
global {
|
||||
interface ImportMeta {
|
||||
/**
|
||||
* The directory name of the current module.
|
||||
*
|
||||
* This is the same as the `path.dirname()` of the `import.meta.filename`.
|
||||
*
|
||||
* > **Caveat**: only present on `file:` modules.
|
||||
* @since v21.2.0, v20.11.0
|
||||
*/
|
||||
dirname: string;
|
||||
/**
|
||||
* The full absolute path and filename of the current module, with
|
||||
* symlinks resolved.
|
||||
*
|
||||
* This is the same as the `url.fileURLToPath()` of the `import.meta.url`.
|
||||
*
|
||||
* > **Caveat** only local modules support this property. Modules not using the
|
||||
* > `file:` protocol will not provide it.
|
||||
* @since v21.2.0, v20.11.0
|
||||
*/
|
||||
filename: string;
|
||||
/**
|
||||
* The absolute `file:` URL of the module.
|
||||
*
|
||||
* This is defined exactly the same as it is in browsers providing the URL of the
|
||||
* current module file.
|
||||
*
|
||||
* This enables useful patterns such as relative file loading:
|
||||
*
|
||||
* ```js
|
||||
* import { readFileSync } from 'node:fs';
|
||||
* const buffer = readFileSync(new URL('./data.proto', import.meta.url));
|
||||
* ```
|
||||
*/
|
||||
url: string;
|
||||
/**
|
||||
* `import.meta.resolve` is a module-relative resolution function scoped to
|
||||
* each module, returning the URL string.
|
||||
*
|
||||
* ```js
|
||||
* const dependencyAsset = import.meta.resolve('component-lib/asset.css');
|
||||
* // file:///app/node_modules/component-lib/asset.css
|
||||
* import.meta.resolve('./dep.js');
|
||||
* // file:///app/dep.js
|
||||
* ```
|
||||
*
|
||||
* All features of the Node.js module resolution are supported. Dependency
|
||||
* resolutions are subject to the permitted exports resolutions within the package.
|
||||
*
|
||||
* **Caveats**:
|
||||
*
|
||||
* * This can result in synchronous file-system operations, which
|
||||
* can impact performance similarly to `require.resolve`.
|
||||
* * This feature is not available within custom loaders (it would
|
||||
* create a deadlock).
|
||||
* @since v13.9.0, v12.16.0
|
||||
* @param specifier The module specifier to resolve relative to the
|
||||
* current module.
|
||||
* @param parent An optional absolute parent module URL to resolve from.
|
||||
* **Default:** `import.meta.url`
|
||||
* @returns The absolute URL string that the specifier would resolve to.
|
||||
*/
|
||||
resolve(specifier: string, parent?: string | URL): string;
|
||||
/**
|
||||
* `true` when the current module is the entry point of the current process; `false` otherwise.
|
||||
*
|
||||
* Equivalent to `require.main === module` in CommonJS.
|
||||
*
|
||||
* Analogous to Python's `__name__ == "__main__"`.
|
||||
*
|
||||
* ```js
|
||||
* export function foo() {
|
||||
* return 'Hello, world';
|
||||
* }
|
||||
*
|
||||
* function main() {
|
||||
* const message = foo();
|
||||
* console.log(message);
|
||||
* }
|
||||
*
|
||||
* if (import.meta.main) main();
|
||||
* // `foo` can be imported from another module without possible side-effects from `main`
|
||||
* ```
|
||||
* @since v24.2.0
|
||||
* @experimental
|
||||
*/
|
||||
main: boolean;
|
||||
}
|
||||
namespace NodeJS {
|
||||
interface Module {
|
||||
/**
|
||||
* The module objects required for the first time by this one.
|
||||
* @since v0.1.16
|
||||
*/
|
||||
children: Module[];
|
||||
/**
|
||||
* The `module.exports` object is created by the `Module` system. Sometimes this is
|
||||
* not acceptable; many want their module to be an instance of some class. To do
|
||||
* this, assign the desired export object to `module.exports`.
|
||||
* @since v0.1.16
|
||||
*/
|
||||
exports: any;
|
||||
/**
|
||||
* The fully resolved filename of the module.
|
||||
* @since v0.1.16
|
||||
*/
|
||||
filename: string;
|
||||
/**
|
||||
* The identifier for the module. Typically this is the fully resolved
|
||||
* filename.
|
||||
* @since v0.1.16
|
||||
*/
|
||||
id: string;
|
||||
/**
|
||||
* `true` if the module is running during the Node.js preload
|
||||
* phase.
|
||||
* @since v15.4.0, v14.17.0
|
||||
*/
|
||||
isPreloading: boolean;
|
||||
/**
|
||||
* Whether or not the module is done loading, or is in the process of
|
||||
* loading.
|
||||
* @since v0.1.16
|
||||
*/
|
||||
loaded: boolean;
|
||||
/**
|
||||
* The module that first required this one, or `null` if the current module is the
|
||||
* entry point of the current process, or `undefined` if the module was loaded by
|
||||
* something that is not a CommonJS module (e.g. REPL or `import`).
|
||||
* @since v0.1.16
|
||||
* @deprecated Please use `require.main` and `module.children` instead.
|
||||
*/
|
||||
parent: Module | null | undefined;
|
||||
/**
|
||||
* The directory name of the module. This is usually the same as the
|
||||
* `path.dirname()` of the `module.id`.
|
||||
* @since v11.14.0
|
||||
*/
|
||||
path: string;
|
||||
/**
|
||||
* The search paths for the module.
|
||||
* @since v0.4.0
|
||||
*/
|
||||
paths: string[];
|
||||
/**
|
||||
* The `module.require()` method provides a way to load a module as if
|
||||
* `require()` was called from the original module.
|
||||
* @since v0.5.1
|
||||
*/
|
||||
require(id: string): any;
|
||||
}
|
||||
interface Require {
|
||||
/**
|
||||
* Used to import modules, `JSON`, and local files.
|
||||
* @since v0.1.13
|
||||
*/
|
||||
(id: string): any;
|
||||
/**
|
||||
* Modules are cached in this object when they are required. By deleting a key
|
||||
* value from this object, the next `require` will reload the module.
|
||||
* This does not apply to
|
||||
* [native addons](https://nodejs.org/docs/latest-v24.x/api/addons.html),
|
||||
* for which reloading will result in an error.
|
||||
* @since v0.3.0
|
||||
*/
|
||||
cache: Dict<Module>;
|
||||
/**
|
||||
* Instruct `require` on how to handle certain file extensions.
|
||||
* @since v0.3.0
|
||||
* @deprecated
|
||||
*/
|
||||
extensions: RequireExtensions;
|
||||
/**
|
||||
* The `Module` object representing the entry script loaded when the Node.js
|
||||
* process launched, or `undefined` if the entry point of the program is not a
|
||||
* CommonJS module.
|
||||
* @since v0.1.17
|
||||
*/
|
||||
main: Module | undefined;
|
||||
/**
|
||||
* @since v0.3.0
|
||||
*/
|
||||
resolve: RequireResolve;
|
||||
}
|
||||
/** @deprecated */
|
||||
interface RequireExtensions extends Dict<(module: Module, filename: string) => any> {
|
||||
".js": (module: Module, filename: string) => any;
|
||||
".json": (module: Module, filename: string) => any;
|
||||
".node": (module: Module, filename: string) => any;
|
||||
}
|
||||
interface RequireResolveOptions {
|
||||
/**
|
||||
* Paths to resolve module location from. If present, these
|
||||
* paths are used instead of the default resolution paths, with the exception
|
||||
* of
|
||||
* [GLOBAL\_FOLDERS](https://nodejs.org/docs/latest-v24.x/api/modules.html#loading-from-the-global-folders)
|
||||
* like `$HOME/.node_modules`, which are
|
||||
* always included. Each of these paths is used as a starting point for
|
||||
* the module resolution algorithm, meaning that the `node_modules` hierarchy
|
||||
* is checked from this location.
|
||||
* @since v8.9.0
|
||||
*/
|
||||
paths?: string[] | undefined;
|
||||
}
|
||||
interface RequireResolve {
|
||||
/**
|
||||
* Use the internal `require()` machinery to look up the location of a module,
|
||||
* but rather than loading the module, just return the resolved filename.
|
||||
*
|
||||
* If the module can not be found, a `MODULE_NOT_FOUND` error is thrown.
|
||||
* @since v0.3.0
|
||||
* @param request The module path to resolve.
|
||||
*/
|
||||
(request: string, options?: RequireResolveOptions): string;
|
||||
/**
|
||||
* Returns an array containing the paths searched during resolution of `request` or
|
||||
* `null` if the `request` string references a core module, for example `http` or
|
||||
* `fs`.
|
||||
* @since v8.9.0
|
||||
* @param request The module path whose lookup paths are being retrieved.
|
||||
*/
|
||||
paths(request: string): string[] | null;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* The directory name of the current module. This is the same as the
|
||||
* `path.dirname()` of the `__filename`.
|
||||
* @since v0.1.27
|
||||
*/
|
||||
var __dirname: string;
|
||||
/**
|
||||
* The file name of the current module. This is the current module file's absolute
|
||||
* path with symlinks resolved.
|
||||
*
|
||||
* For a main program this is not necessarily the same as the file name used in the
|
||||
* command line.
|
||||
* @since v0.0.1
|
||||
*/
|
||||
var __filename: string;
|
||||
/**
|
||||
* The `exports` variable is available within a module's file-level scope, and is
|
||||
* assigned the value of `module.exports` before the module is evaluated.
|
||||
* @since v0.1.16
|
||||
*/
|
||||
var exports: NodeJS.Module["exports"];
|
||||
/**
|
||||
* A reference to the current module.
|
||||
* @since v0.1.16
|
||||
*/
|
||||
var module: NodeJS.Module;
|
||||
/**
|
||||
* @since v0.1.13
|
||||
*/
|
||||
var require: NodeJS.Require;
|
||||
// Global-scope aliases for backwards compatibility with @types/node <13.0.x
|
||||
// TODO: consider removing in a future major version update
|
||||
/** @deprecated Use `NodeJS.Module` instead. */
|
||||
interface NodeModule extends NodeJS.Module {}
|
||||
/** @deprecated Use `NodeJS.Require` instead. */
|
||||
interface NodeRequire extends NodeJS.Require {}
|
||||
/** @deprecated Use `NodeJS.RequireResolve` instead. */
|
||||
interface RequireResolve extends NodeJS.RequireResolve {}
|
||||
}
|
||||
export = Module;
|
||||
}
|
||||
declare module "node:module" {
|
||||
import module = require("module");
|
||||
export = module;
|
||||
}
|
||||
1073
node_modules/sitemap/node_modules/@types/node/net.d.ts
generated
vendored
Normal file
1073
node_modules/sitemap/node_modules/@types/node/net.d.ts
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
507
node_modules/sitemap/node_modules/@types/node/os.d.ts
generated
vendored
Normal file
507
node_modules/sitemap/node_modules/@types/node/os.d.ts
generated
vendored
Normal file
@@ -0,0 +1,507 @@
|
||||
/**
|
||||
* The `node:os` module provides operating system-related utility methods and
|
||||
* properties. It can be accessed using:
|
||||
*
|
||||
* ```js
|
||||
* import os from 'node:os';
|
||||
* ```
|
||||
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/os.js)
|
||||
*/
|
||||
declare module "os" {
|
||||
import { NonSharedBuffer } from "buffer";
|
||||
interface CpuInfo {
|
||||
model: string;
|
||||
speed: number;
|
||||
times: {
|
||||
/** The number of milliseconds the CPU has spent in user mode. */
|
||||
user: number;
|
||||
/** The number of milliseconds the CPU has spent in nice mode. */
|
||||
nice: number;
|
||||
/** The number of milliseconds the CPU has spent in sys mode. */
|
||||
sys: number;
|
||||
/** The number of milliseconds the CPU has spent in idle mode. */
|
||||
idle: number;
|
||||
/** The number of milliseconds the CPU has spent in irq mode. */
|
||||
irq: number;
|
||||
};
|
||||
}
|
||||
interface NetworkInterfaceBase {
|
||||
address: string;
|
||||
netmask: string;
|
||||
mac: string;
|
||||
internal: boolean;
|
||||
cidr: string | null;
|
||||
scopeid?: number;
|
||||
}
|
||||
interface NetworkInterfaceInfoIPv4 extends NetworkInterfaceBase {
|
||||
family: "IPv4";
|
||||
}
|
||||
interface NetworkInterfaceInfoIPv6 extends NetworkInterfaceBase {
|
||||
family: "IPv6";
|
||||
scopeid: number;
|
||||
}
|
||||
interface UserInfo<T> {
|
||||
username: T;
|
||||
uid: number;
|
||||
gid: number;
|
||||
shell: T | null;
|
||||
homedir: T;
|
||||
}
|
||||
type NetworkInterfaceInfo = NetworkInterfaceInfoIPv4 | NetworkInterfaceInfoIPv6;
|
||||
/**
|
||||
* Returns the host name of the operating system as a string.
|
||||
* @since v0.3.3
|
||||
*/
|
||||
function hostname(): string;
|
||||
/**
|
||||
* Returns an array containing the 1, 5, and 15 minute load averages.
|
||||
*
|
||||
* The load average is a measure of system activity calculated by the operating
|
||||
* system and expressed as a fractional number.
|
||||
*
|
||||
* The load average is a Unix-specific concept. On Windows, the return value is
|
||||
* always `[0, 0, 0]`.
|
||||
* @since v0.3.3
|
||||
*/
|
||||
function loadavg(): number[];
|
||||
/**
|
||||
* Returns the system uptime in number of seconds.
|
||||
* @since v0.3.3
|
||||
*/
|
||||
function uptime(): number;
|
||||
/**
|
||||
* Returns the amount of free system memory in bytes as an integer.
|
||||
* @since v0.3.3
|
||||
*/
|
||||
function freemem(): number;
|
||||
/**
|
||||
* Returns the total amount of system memory in bytes as an integer.
|
||||
* @since v0.3.3
|
||||
*/
|
||||
function totalmem(): number;
|
||||
/**
|
||||
* Returns an array of objects containing information about each logical CPU core.
|
||||
* The array will be empty if no CPU information is available, such as if the `/proc` file system is unavailable.
|
||||
*
|
||||
* The properties included on each object include:
|
||||
*
|
||||
* ```js
|
||||
* [
|
||||
* {
|
||||
* model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',
|
||||
* speed: 2926,
|
||||
* times: {
|
||||
* user: 252020,
|
||||
* nice: 0,
|
||||
* sys: 30340,
|
||||
* idle: 1070356870,
|
||||
* irq: 0,
|
||||
* },
|
||||
* },
|
||||
* {
|
||||
* model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',
|
||||
* speed: 2926,
|
||||
* times: {
|
||||
* user: 306960,
|
||||
* nice: 0,
|
||||
* sys: 26980,
|
||||
* idle: 1071569080,
|
||||
* irq: 0,
|
||||
* },
|
||||
* },
|
||||
* {
|
||||
* model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',
|
||||
* speed: 2926,
|
||||
* times: {
|
||||
* user: 248450,
|
||||
* nice: 0,
|
||||
* sys: 21750,
|
||||
* idle: 1070919370,
|
||||
* irq: 0,
|
||||
* },
|
||||
* },
|
||||
* {
|
||||
* model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',
|
||||
* speed: 2926,
|
||||
* times: {
|
||||
* user: 256880,
|
||||
* nice: 0,
|
||||
* sys: 19430,
|
||||
* idle: 1070905480,
|
||||
* irq: 20,
|
||||
* },
|
||||
* },
|
||||
* ]
|
||||
* ```
|
||||
*
|
||||
* `nice` values are POSIX-only. On Windows, the `nice` values of all processors
|
||||
* are always 0.
|
||||
*
|
||||
* `os.cpus().length` should not be used to calculate the amount of parallelism
|
||||
* available to an application. Use {@link availableParallelism} for this purpose.
|
||||
* @since v0.3.3
|
||||
*/
|
||||
function cpus(): CpuInfo[];
|
||||
/**
|
||||
* Returns an estimate of the default amount of parallelism a program should use.
|
||||
* Always returns a value greater than zero.
|
||||
*
|
||||
* This function is a small wrapper about libuv's [`uv_available_parallelism()`](https://docs.libuv.org/en/v1.x/misc.html#c.uv_available_parallelism).
|
||||
* @since v19.4.0, v18.14.0
|
||||
*/
|
||||
function availableParallelism(): number;
|
||||
/**
|
||||
* Returns the operating system name as returned by [`uname(3)`](https://linux.die.net/man/3/uname). For example, it
|
||||
* returns `'Linux'` on Linux, `'Darwin'` on macOS, and `'Windows_NT'` on Windows.
|
||||
*
|
||||
* See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for additional information
|
||||
* about the output of running [`uname(3)`](https://linux.die.net/man/3/uname) on various operating systems.
|
||||
* @since v0.3.3
|
||||
*/
|
||||
function type(): string;
|
||||
/**
|
||||
* Returns the operating system as a string.
|
||||
*
|
||||
* On POSIX systems, the operating system release is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `GetVersionExW()` is used. See
|
||||
* [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information.
|
||||
* @since v0.3.3
|
||||
*/
|
||||
function release(): string;
|
||||
/**
|
||||
* Returns an object containing network interfaces that have been assigned a
|
||||
* network address.
|
||||
*
|
||||
* Each key on the returned object identifies a network interface. The associated
|
||||
* value is an array of objects that each describe an assigned network address.
|
||||
*
|
||||
* The properties available on the assigned network address object include:
|
||||
*
|
||||
* ```js
|
||||
* {
|
||||
* lo: [
|
||||
* {
|
||||
* address: '127.0.0.1',
|
||||
* netmask: '255.0.0.0',
|
||||
* family: 'IPv4',
|
||||
* mac: '00:00:00:00:00:00',
|
||||
* internal: true,
|
||||
* cidr: '127.0.0.1/8'
|
||||
* },
|
||||
* {
|
||||
* address: '::1',
|
||||
* netmask: 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff',
|
||||
* family: 'IPv6',
|
||||
* mac: '00:00:00:00:00:00',
|
||||
* scopeid: 0,
|
||||
* internal: true,
|
||||
* cidr: '::1/128'
|
||||
* }
|
||||
* ],
|
||||
* eth0: [
|
||||
* {
|
||||
* address: '192.168.1.108',
|
||||
* netmask: '255.255.255.0',
|
||||
* family: 'IPv4',
|
||||
* mac: '01:02:03:0a:0b:0c',
|
||||
* internal: false,
|
||||
* cidr: '192.168.1.108/24'
|
||||
* },
|
||||
* {
|
||||
* address: 'fe80::a00:27ff:fe4e:66a1',
|
||||
* netmask: 'ffff:ffff:ffff:ffff::',
|
||||
* family: 'IPv6',
|
||||
* mac: '01:02:03:0a:0b:0c',
|
||||
* scopeid: 1,
|
||||
* internal: false,
|
||||
* cidr: 'fe80::a00:27ff:fe4e:66a1/64'
|
||||
* }
|
||||
* ]
|
||||
* }
|
||||
* ```
|
||||
* @since v0.6.0
|
||||
*/
|
||||
function networkInterfaces(): NodeJS.Dict<NetworkInterfaceInfo[]>;
|
||||
/**
|
||||
* Returns the string path of the current user's home directory.
|
||||
*
|
||||
* On POSIX, it uses the `$HOME` environment variable if defined. Otherwise it
|
||||
* uses the [effective UID](https://en.wikipedia.org/wiki/User_identifier#Effective_user_ID) to look up the user's home directory.
|
||||
*
|
||||
* On Windows, it uses the `USERPROFILE` environment variable if defined.
|
||||
* Otherwise it uses the path to the profile directory of the current user.
|
||||
* @since v2.3.0
|
||||
*/
|
||||
function homedir(): string;
|
||||
interface UserInfoOptions {
|
||||
encoding?: BufferEncoding | "buffer" | undefined;
|
||||
}
|
||||
interface UserInfoOptionsWithBufferEncoding extends UserInfoOptions {
|
||||
encoding: "buffer";
|
||||
}
|
||||
interface UserInfoOptionsWithStringEncoding extends UserInfoOptions {
|
||||
encoding?: BufferEncoding | undefined;
|
||||
}
|
||||
/**
|
||||
* Returns information about the currently effective user. On POSIX platforms,
|
||||
* this is typically a subset of the password file. The returned object includes
|
||||
* the `username`, `uid`, `gid`, `shell`, and `homedir`. On Windows, the `uid` and `gid` fields are `-1`, and `shell` is `null`.
|
||||
*
|
||||
* The value of `homedir` returned by `os.userInfo()` is provided by the operating
|
||||
* system. This differs from the result of `os.homedir()`, which queries
|
||||
* environment variables for the home directory before falling back to the
|
||||
* operating system response.
|
||||
*
|
||||
* Throws a [`SystemError`](https://nodejs.org/docs/latest-v24.x/api/errors.html#class-systemerror) if a user has no `username` or `homedir`.
|
||||
* @since v6.0.0
|
||||
*/
|
||||
function userInfo(options?: UserInfoOptionsWithStringEncoding): UserInfo<string>;
|
||||
function userInfo(options: UserInfoOptionsWithBufferEncoding): UserInfo<NonSharedBuffer>;
|
||||
function userInfo(options: UserInfoOptions): UserInfo<string | NonSharedBuffer>;
|
||||
type SignalConstants = {
|
||||
[key in NodeJS.Signals]: number;
|
||||
};
|
||||
namespace constants {
|
||||
const UV_UDP_REUSEADDR: number;
|
||||
namespace signals {}
|
||||
const signals: SignalConstants;
|
||||
namespace errno {
|
||||
const E2BIG: number;
|
||||
const EACCES: number;
|
||||
const EADDRINUSE: number;
|
||||
const EADDRNOTAVAIL: number;
|
||||
const EAFNOSUPPORT: number;
|
||||
const EAGAIN: number;
|
||||
const EALREADY: number;
|
||||
const EBADF: number;
|
||||
const EBADMSG: number;
|
||||
const EBUSY: number;
|
||||
const ECANCELED: number;
|
||||
const ECHILD: number;
|
||||
const ECONNABORTED: number;
|
||||
const ECONNREFUSED: number;
|
||||
const ECONNRESET: number;
|
||||
const EDEADLK: number;
|
||||
const EDESTADDRREQ: number;
|
||||
const EDOM: number;
|
||||
const EDQUOT: number;
|
||||
const EEXIST: number;
|
||||
const EFAULT: number;
|
||||
const EFBIG: number;
|
||||
const EHOSTUNREACH: number;
|
||||
const EIDRM: number;
|
||||
const EILSEQ: number;
|
||||
const EINPROGRESS: number;
|
||||
const EINTR: number;
|
||||
const EINVAL: number;
|
||||
const EIO: number;
|
||||
const EISCONN: number;
|
||||
const EISDIR: number;
|
||||
const ELOOP: number;
|
||||
const EMFILE: number;
|
||||
const EMLINK: number;
|
||||
const EMSGSIZE: number;
|
||||
const EMULTIHOP: number;
|
||||
const ENAMETOOLONG: number;
|
||||
const ENETDOWN: number;
|
||||
const ENETRESET: number;
|
||||
const ENETUNREACH: number;
|
||||
const ENFILE: number;
|
||||
const ENOBUFS: number;
|
||||
const ENODATA: number;
|
||||
const ENODEV: number;
|
||||
const ENOENT: number;
|
||||
const ENOEXEC: number;
|
||||
const ENOLCK: number;
|
||||
const ENOLINK: number;
|
||||
const ENOMEM: number;
|
||||
const ENOMSG: number;
|
||||
const ENOPROTOOPT: number;
|
||||
const ENOSPC: number;
|
||||
const ENOSR: number;
|
||||
const ENOSTR: number;
|
||||
const ENOSYS: number;
|
||||
const ENOTCONN: number;
|
||||
const ENOTDIR: number;
|
||||
const ENOTEMPTY: number;
|
||||
const ENOTSOCK: number;
|
||||
const ENOTSUP: number;
|
||||
const ENOTTY: number;
|
||||
const ENXIO: number;
|
||||
const EOPNOTSUPP: number;
|
||||
const EOVERFLOW: number;
|
||||
const EPERM: number;
|
||||
const EPIPE: number;
|
||||
const EPROTO: number;
|
||||
const EPROTONOSUPPORT: number;
|
||||
const EPROTOTYPE: number;
|
||||
const ERANGE: number;
|
||||
const EROFS: number;
|
||||
const ESPIPE: number;
|
||||
const ESRCH: number;
|
||||
const ESTALE: number;
|
||||
const ETIME: number;
|
||||
const ETIMEDOUT: number;
|
||||
const ETXTBSY: number;
|
||||
const EWOULDBLOCK: number;
|
||||
const EXDEV: number;
|
||||
const WSAEINTR: number;
|
||||
const WSAEBADF: number;
|
||||
const WSAEACCES: number;
|
||||
const WSAEFAULT: number;
|
||||
const WSAEINVAL: number;
|
||||
const WSAEMFILE: number;
|
||||
const WSAEWOULDBLOCK: number;
|
||||
const WSAEINPROGRESS: number;
|
||||
const WSAEALREADY: number;
|
||||
const WSAENOTSOCK: number;
|
||||
const WSAEDESTADDRREQ: number;
|
||||
const WSAEMSGSIZE: number;
|
||||
const WSAEPROTOTYPE: number;
|
||||
const WSAENOPROTOOPT: number;
|
||||
const WSAEPROTONOSUPPORT: number;
|
||||
const WSAESOCKTNOSUPPORT: number;
|
||||
const WSAEOPNOTSUPP: number;
|
||||
const WSAEPFNOSUPPORT: number;
|
||||
const WSAEAFNOSUPPORT: number;
|
||||
const WSAEADDRINUSE: number;
|
||||
const WSAEADDRNOTAVAIL: number;
|
||||
const WSAENETDOWN: number;
|
||||
const WSAENETUNREACH: number;
|
||||
const WSAENETRESET: number;
|
||||
const WSAECONNABORTED: number;
|
||||
const WSAECONNRESET: number;
|
||||
const WSAENOBUFS: number;
|
||||
const WSAEISCONN: number;
|
||||
const WSAENOTCONN: number;
|
||||
const WSAESHUTDOWN: number;
|
||||
const WSAETOOMANYREFS: number;
|
||||
const WSAETIMEDOUT: number;
|
||||
const WSAECONNREFUSED: number;
|
||||
const WSAELOOP: number;
|
||||
const WSAENAMETOOLONG: number;
|
||||
const WSAEHOSTDOWN: number;
|
||||
const WSAEHOSTUNREACH: number;
|
||||
const WSAENOTEMPTY: number;
|
||||
const WSAEPROCLIM: number;
|
||||
const WSAEUSERS: number;
|
||||
const WSAEDQUOT: number;
|
||||
const WSAESTALE: number;
|
||||
const WSAEREMOTE: number;
|
||||
const WSASYSNOTREADY: number;
|
||||
const WSAVERNOTSUPPORTED: number;
|
||||
const WSANOTINITIALISED: number;
|
||||
const WSAEDISCON: number;
|
||||
const WSAENOMORE: number;
|
||||
const WSAECANCELLED: number;
|
||||
const WSAEINVALIDPROCTABLE: number;
|
||||
const WSAEINVALIDPROVIDER: number;
|
||||
const WSAEPROVIDERFAILEDINIT: number;
|
||||
const WSASYSCALLFAILURE: number;
|
||||
const WSASERVICE_NOT_FOUND: number;
|
||||
const WSATYPE_NOT_FOUND: number;
|
||||
const WSA_E_NO_MORE: number;
|
||||
const WSA_E_CANCELLED: number;
|
||||
const WSAEREFUSED: number;
|
||||
}
|
||||
namespace dlopen {
|
||||
const RTLD_LAZY: number;
|
||||
const RTLD_NOW: number;
|
||||
const RTLD_GLOBAL: number;
|
||||
const RTLD_LOCAL: number;
|
||||
const RTLD_DEEPBIND: number;
|
||||
}
|
||||
namespace priority {
|
||||
const PRIORITY_LOW: number;
|
||||
const PRIORITY_BELOW_NORMAL: number;
|
||||
const PRIORITY_NORMAL: number;
|
||||
const PRIORITY_ABOVE_NORMAL: number;
|
||||
const PRIORITY_HIGH: number;
|
||||
const PRIORITY_HIGHEST: number;
|
||||
}
|
||||
}
|
||||
const devNull: string;
|
||||
/**
|
||||
* The operating system-specific end-of-line marker.
|
||||
* * `\n` on POSIX
|
||||
* * `\r\n` on Windows
|
||||
*/
|
||||
const EOL: string;
|
||||
/**
|
||||
* Returns the operating system CPU architecture for which the Node.js binary was
|
||||
* compiled. Possible values are `'arm'`, `'arm64'`, `'ia32'`, `'loong64'`,
|
||||
* `'mips'`, `'mipsel'`, `'ppc64'`, `'riscv64'`, `'s390x'`, and `'x64'`.
|
||||
*
|
||||
* The return value is equivalent to [process.arch](https://nodejs.org/docs/latest-v24.x/api/process.html#processarch).
|
||||
* @since v0.5.0
|
||||
*/
|
||||
function arch(): NodeJS.Architecture;
|
||||
/**
|
||||
* Returns a string identifying the kernel version.
|
||||
*
|
||||
* On POSIX systems, the operating system release is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `RtlGetVersion()` is used, and if it is not
|
||||
* available, `GetVersionExW()` will be used. See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information.
|
||||
* @since v13.11.0, v12.17.0
|
||||
*/
|
||||
function version(): string;
|
||||
/**
|
||||
* Returns a string identifying the operating system platform for which
|
||||
* the Node.js binary was compiled. The value is set at compile time.
|
||||
* Possible values are `'aix'`, `'darwin'`, `'freebsd'`, `'linux'`, `'openbsd'`, `'sunos'`, and `'win32'`.
|
||||
*
|
||||
* The return value is equivalent to `process.platform`.
|
||||
*
|
||||
* The value `'android'` may also be returned if Node.js is built on the Android
|
||||
* operating system. [Android support is experimental](https://github.com/nodejs/node/blob/HEAD/BUILDING.md#androidandroid-based-devices-eg-firefox-os).
|
||||
* @since v0.5.0
|
||||
*/
|
||||
function platform(): NodeJS.Platform;
|
||||
/**
|
||||
* Returns the machine type as a string, such as `arm`, `arm64`, `aarch64`,
|
||||
* `mips`, `mips64`, `ppc64`, `ppc64le`, `s390x`, `i386`, `i686`, `x86_64`.
|
||||
*
|
||||
* On POSIX systems, the machine type is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `RtlGetVersion()` is used, and if it is not
|
||||
* available, `GetVersionExW()` will be used. See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information.
|
||||
* @since v18.9.0, v16.18.0
|
||||
*/
|
||||
function machine(): string;
|
||||
/**
|
||||
* Returns the operating system's default directory for temporary files as a
|
||||
* string.
|
||||
* @since v0.9.9
|
||||
*/
|
||||
function tmpdir(): string;
|
||||
/**
|
||||
* Returns a string identifying the endianness of the CPU for which the Node.js
|
||||
* binary was compiled.
|
||||
*
|
||||
* Possible values are `'BE'` for big endian and `'LE'` for little endian.
|
||||
* @since v0.9.4
|
||||
*/
|
||||
function endianness(): "BE" | "LE";
|
||||
/**
|
||||
* Returns the scheduling priority for the process specified by `pid`. If `pid` is
|
||||
* not provided or is `0`, the priority of the current process is returned.
|
||||
* @since v10.10.0
|
||||
* @param [pid=0] The process ID to retrieve scheduling priority for.
|
||||
*/
|
||||
function getPriority(pid?: number): number;
|
||||
/**
|
||||
* Attempts to set the scheduling priority for the process specified by `pid`. If `pid` is not provided or is `0`, the process ID of the current process is used.
|
||||
*
|
||||
* The `priority` input must be an integer between `-20` (high priority) and `19` (low priority). Due to differences between Unix priority levels and Windows
|
||||
* priority classes, `priority` is mapped to one of six priority constants in `os.constants.priority`. When retrieving a process priority level, this range
|
||||
* mapping may cause the return value to be slightly different on Windows. To avoid
|
||||
* confusion, set `priority` to one of the priority constants.
|
||||
*
|
||||
* On Windows, setting priority to `PRIORITY_HIGHEST` requires elevated user
|
||||
* privileges. Otherwise the set priority will be silently reduced to `PRIORITY_HIGH`.
|
||||
* @since v10.10.0
|
||||
* @param [pid=0] The process ID to set scheduling priority for.
|
||||
* @param priority The scheduling priority to assign to the process.
|
||||
*/
|
||||
function setPriority(priority: number): void;
|
||||
function setPriority(pid: number, priority: number): void;
|
||||
}
|
||||
declare module "node:os" {
|
||||
export * from "os";
|
||||
}
|
||||
155
node_modules/sitemap/node_modules/@types/node/package.json
generated
vendored
Normal file
155
node_modules/sitemap/node_modules/@types/node/package.json
generated
vendored
Normal file
@@ -0,0 +1,155 @@
|
||||
{
|
||||
"name": "@types/node",
|
||||
"version": "24.12.2",
|
||||
"description": "TypeScript definitions for node",
|
||||
"homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node",
|
||||
"license": "MIT",
|
||||
"contributors": [
|
||||
{
|
||||
"name": "Microsoft TypeScript",
|
||||
"githubUsername": "Microsoft",
|
||||
"url": "https://github.com/Microsoft"
|
||||
},
|
||||
{
|
||||
"name": "Alberto Schiabel",
|
||||
"githubUsername": "jkomyno",
|
||||
"url": "https://github.com/jkomyno"
|
||||
},
|
||||
{
|
||||
"name": "Andrew Makarov",
|
||||
"githubUsername": "r3nya",
|
||||
"url": "https://github.com/r3nya"
|
||||
},
|
||||
{
|
||||
"name": "Benjamin Toueg",
|
||||
"githubUsername": "btoueg",
|
||||
"url": "https://github.com/btoueg"
|
||||
},
|
||||
{
|
||||
"name": "David Junger",
|
||||
"githubUsername": "touffy",
|
||||
"url": "https://github.com/touffy"
|
||||
},
|
||||
{
|
||||
"name": "Mohsen Azimi",
|
||||
"githubUsername": "mohsen1",
|
||||
"url": "https://github.com/mohsen1"
|
||||
},
|
||||
{
|
||||
"name": "Nikita Galkin",
|
||||
"githubUsername": "galkin",
|
||||
"url": "https://github.com/galkin"
|
||||
},
|
||||
{
|
||||
"name": "Sebastian Silbermann",
|
||||
"githubUsername": "eps1lon",
|
||||
"url": "https://github.com/eps1lon"
|
||||
},
|
||||
{
|
||||
"name": "Wilco Bakker",
|
||||
"githubUsername": "WilcoBakker",
|
||||
"url": "https://github.com/WilcoBakker"
|
||||
},
|
||||
{
|
||||
"name": "Marcin Kopacz",
|
||||
"githubUsername": "chyzwar",
|
||||
"url": "https://github.com/chyzwar"
|
||||
},
|
||||
{
|
||||
"name": "Trivikram Kamat",
|
||||
"githubUsername": "trivikr",
|
||||
"url": "https://github.com/trivikr"
|
||||
},
|
||||
{
|
||||
"name": "Junxiao Shi",
|
||||
"githubUsername": "yoursunny",
|
||||
"url": "https://github.com/yoursunny"
|
||||
},
|
||||
{
|
||||
"name": "Ilia Baryshnikov",
|
||||
"githubUsername": "qwelias",
|
||||
"url": "https://github.com/qwelias"
|
||||
},
|
||||
{
|
||||
"name": "ExE Boss",
|
||||
"githubUsername": "ExE-Boss",
|
||||
"url": "https://github.com/ExE-Boss"
|
||||
},
|
||||
{
|
||||
"name": "Piotr Błażejewicz",
|
||||
"githubUsername": "peterblazejewicz",
|
||||
"url": "https://github.com/peterblazejewicz"
|
||||
},
|
||||
{
|
||||
"name": "Anna Henningsen",
|
||||
"githubUsername": "addaleax",
|
||||
"url": "https://github.com/addaleax"
|
||||
},
|
||||
{
|
||||
"name": "Victor Perin",
|
||||
"githubUsername": "victorperin",
|
||||
"url": "https://github.com/victorperin"
|
||||
},
|
||||
{
|
||||
"name": "NodeJS Contributors",
|
||||
"githubUsername": "NodeJS",
|
||||
"url": "https://github.com/NodeJS"
|
||||
},
|
||||
{
|
||||
"name": "Linus Unnebäck",
|
||||
"githubUsername": "LinusU",
|
||||
"url": "https://github.com/LinusU"
|
||||
},
|
||||
{
|
||||
"name": "wafuwafu13",
|
||||
"githubUsername": "wafuwafu13",
|
||||
"url": "https://github.com/wafuwafu13"
|
||||
},
|
||||
{
|
||||
"name": "Matteo Collina",
|
||||
"githubUsername": "mcollina",
|
||||
"url": "https://github.com/mcollina"
|
||||
},
|
||||
{
|
||||
"name": "Dmitry Semigradsky",
|
||||
"githubUsername": "Semigradsky",
|
||||
"url": "https://github.com/Semigradsky"
|
||||
},
|
||||
{
|
||||
"name": "René",
|
||||
"githubUsername": "Renegade334",
|
||||
"url": "https://github.com/Renegade334"
|
||||
},
|
||||
{
|
||||
"name": "Yagiz Nizipli",
|
||||
"githubUsername": "anonrig",
|
||||
"url": "https://github.com/anonrig"
|
||||
}
|
||||
],
|
||||
"main": "",
|
||||
"types": "index.d.ts",
|
||||
"typesVersions": {
|
||||
"<=5.6": {
|
||||
"*": [
|
||||
"ts5.6/*"
|
||||
]
|
||||
},
|
||||
"<=5.7": {
|
||||
"*": [
|
||||
"ts5.7/*"
|
||||
]
|
||||
}
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git",
|
||||
"directory": "types/node"
|
||||
},
|
||||
"scripts": {},
|
||||
"dependencies": {
|
||||
"undici-types": "~7.16.0"
|
||||
},
|
||||
"peerDependencies": {},
|
||||
"typesPublisherContentHash": "d7203ff42f0a932fc10105074ec5f78418782e8d306c14cb314ce869dff07f43",
|
||||
"typeScriptVersion": "5.3"
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user