diff --git a/.gitattributes b/.gitattributes index c722c3c8aa605ed89435d4dd91c9f10d280e6801..88aa59f00f6dc80d586ad874af4ba550bed6cfae 100644 --- a/.gitattributes +++ b/.gitattributes @@ -3526,3 +3526,4 @@ novas/novacore-zephyr/claude-code-router/ui/node_modules/monaco-editor/esm/vs/la novas/novacore-zephyr/claude-code-router/ui/node_modules/monaco-editor/dev/vs/editor/editor.main.js.map filter=lfs diff=lfs merge=lfs -text novas/novacore-zephyr/claude-code-router/ui/node_modules/monaco-editor/dev/vs/language/typescript/tsWorker.js filter=lfs diff=lfs merge=lfs -text novas/novacore-zephyr/claude-code-router/ui/node_modules/monaco-editor/min-maps/vs/editor/editor.main.js.map filter=lfs diff=lfs merge=lfs -text +novas/novacore-zephyr/claude-code-router/node_modules/@esbuild/linux-x64/bin/esbuild filter=lfs diff=lfs merge=lfs -text diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@esbuild/linux-x64/README.md b/novas/novacore-zephyr/claude-code-router/node_modules/@esbuild/linux-x64/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b2f19300430eb75c1a1fc7d5700ad0b6e7e69333 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@esbuild/linux-x64/README.md @@ -0,0 +1,3 @@ +# esbuild + +This is the Linux 64-bit binary for esbuild, a JavaScript bundler and minifier. See https://github.com/evanw/esbuild for details. diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@esbuild/linux-x64/bin/esbuild b/novas/novacore-zephyr/claude-code-router/node_modules/@esbuild/linux-x64/bin/esbuild new file mode 100644 index 0000000000000000000000000000000000000000..3765666cffdc3384d80d0e09f73cfbf9eb2fc83a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@esbuild/linux-x64/bin/esbuild @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:92d1ca653cf188da8d7650ddfe1c32d5a139bf3a9a2808f3e622e6d667ce0389 +size 10305688 diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@esbuild/linux-x64/package.json b/novas/novacore-zephyr/claude-code-router/node_modules/@esbuild/linux-x64/package.json new file mode 100644 index 0000000000000000000000000000000000000000..8d0ec96f9e48c2f361197a0511349e58177d25e2 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@esbuild/linux-x64/package.json @@ -0,0 +1,20 @@ +{ + "name": "@esbuild/linux-x64", + "version": "0.25.9", + "description": "The Linux 64-bit binary for esbuild, a JavaScript bundler.", + "repository": { + "type": "git", + "url": "git+https://github.com/evanw/esbuild.git" + }, + "license": "MIT", + "preferUnplugged": true, + "engines": { + "node": ">=18" + }, + "os": [ + "linux" + ], + "cpu": [ + "x64" + ] +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/accept-negotiator/LICENSE b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/accept-negotiator/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..232b5877afcb8515a79501239b1d567813681592 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/accept-negotiator/LICENSE @@ -0,0 +1,22 @@ +The MIT License + +Copyright (c) 2022 The Fastify Team + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/accept-negotiator/README.md b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/accept-negotiator/README.md new file mode 100644 index 0000000000000000000000000000000000000000..4ec8b613bb5f58d4a7a75c714a9eee26a987437e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/accept-negotiator/README.md @@ -0,0 +1,52 @@ +# @fastify/accept-negotiator + + +[![CI](https://github.com/fastify/accept-negotiator/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/fastify/accept-negotiator/actions/workflows/ci.yml) +[![NPM version](https://img.shields.io/npm/v/@fastify/accept-negotiator.svg?style=flat)](https://www.npmjs.com/package/@fastify/accept-negotiator) +[![neostandard javascript style](https://img.shields.io/badge/code_style-neostandard-brightgreen?style=flat)](https://github.com/neostandard/neostandard) + +A negotiator for accept-* headers. + +### Install +``` +npm i @fastify/accept-negotiator +``` + +### Usage + +The module exports a function that you can use for negotiating an accept-* header such as [`accept-encoding`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Encoding). It takes 2 parameters: + +``` +negotiate(header, supportedValues) +``` + +- `header` (`string`, required) - The accept-header, e.g. accept-encoding +- `supportedValues` (`string[]`, required) - The values, which are supported + +```js +const negotiate = require('@fastify/accept-negotiator').negotiate +const encoding = negotiate('gzip, deflate, br', ['br']) +console.log(encoding) // 'br* +``` + +The module also exports a class that you can use for negotiating an accept-* header, and use caching for better performance. + + +``` +Negotiate(supportedValues) +``` + +- `supportedValues` (`string[]`, required) - The values, which are supported +- `cache` (`{ set: Function; get: Function; has: Function }`, optional) - A Cache-Store, e.g. ES6-Map or mnemonist LRUCache + +```js +const Negotiator = require('@fastify/accept-negotiator').Negotiator +const encodingNegotiator = new Negotiator({ supportedValues: ['br'], cache: new Map() }) + +const encoding = encodingNegotiator.negotiate('gzip, deflate, br') +console.log(encoding) // 'br* +``` + +## License + +Licensed under [MIT](./LICENSE). diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/accept-negotiator/index.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/accept-negotiator/index.js new file mode 100644 index 0000000000000000000000000000000000000000..7798845589db201df410ba4c215c03944e72bd1e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/accept-negotiator/index.js @@ -0,0 +1,170 @@ +'use strict' + +function Negotiator (options) { + if (!new.target) { + return new Negotiator(options) + } + + const { + supportedValues = [], + cache + } = (options && typeof options === 'object' && options) || {} + + this.supportedValues = supportedValues + + this.cache = cache +} + +Negotiator.prototype.negotiate = function (header) { + if (typeof header !== 'string') { + return null + } + if (!this.cache) { + return negotiate(header, this.supportedValues) + } + if (!this.cache.has(header)) { + this.cache.set(header, negotiate(header, this.supportedValues)) + } + return this.cache.get(header) +} + +function negotiate (header, supportedValues) { + if ( + !header || + !Array.isArray(supportedValues) || + supportedValues.length === 0 + ) { + return null + } + + if (header === '*') { + return supportedValues[0] + } + + let preferredEncoding = null + let preferredEncodingPriority = Infinity + let preferredEncodingQuality = 0 + + function processMatch (enc, quality) { + if (quality === 0 || preferredEncodingQuality > quality) { + return false + } + + const encoding = (enc === '*' && supportedValues[0]) || enc + const priority = supportedValues.indexOf(encoding) + if (priority === -1) { + return false + } + + if (priority === 0 && quality === 1) { + preferredEncoding = encoding + return true + } else if (preferredEncodingQuality < quality) { + preferredEncoding = encoding + preferredEncodingPriority = priority + preferredEncodingQuality = quality + } else if (preferredEncodingPriority > priority) { + preferredEncoding = encoding + preferredEncodingPriority = priority + preferredEncodingQuality = quality + } + return false + } + + parse(header, processMatch) + + return preferredEncoding +} + +const BEGIN = 0 +const TOKEN = 1 +const QUALITY = 2 +const END = 3 + +function parse (header, processMatch) { + let str = '' + let quality + let state = BEGIN + for (let i = 0, il = header.length; i < il; ++i) { + const char = header[i] + + if (char === ' ' || char === '\t') { + continue + } else if (char === ';') { + if (state === TOKEN) { + state = QUALITY + quality = '' + } + continue + } else if (char === ',') { + if (state === TOKEN) { + if (processMatch(str, 1)) { + state = END + break + } + state = BEGIN + str = '' + } else if (state === QUALITY) { + if (processMatch(str, parseFloat(quality) || 0)) { + state = END + break + } + state = BEGIN + str = '' + quality = '' + } + continue + } else if ( + state === QUALITY + ) { + if (char === 'q' || char === '=') { + continue + } else if ( + char === '.' || + char === '1' || + char === '0' || + char === '2' || + char === '3' || + char === '4' || + char === '5' || + char === '6' || + char === '7' || + char === '8' || + char === '9' + ) { + quality += char + continue + } + } else if (state === BEGIN) { + state = TOKEN + str += char + continue + } + if (state === TOKEN) { + const prevChar = header[i - 1] + if (prevChar === ' ' || prevChar === '\t') { + str = '' + } + str += char + continue + } + if (processMatch(str, parseFloat(quality) || 0)) { + state = END + break + } + state = BEGIN + str = char + quality = '' + } + + if (state === TOKEN) { + processMatch(str, 1) + } else if (state === QUALITY) { + processMatch(str, parseFloat(quality) || 0) + } +} + +module.exports = negotiate +module.exports.default = negotiate +module.exports.negotiate = negotiate +module.exports.Negotiator = Negotiator diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/accept-negotiator/package.json b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/accept-negotiator/package.json new file mode 100644 index 0000000000000000000000000000000000000000..96084b529ed415db3d606f8c8664e0ec14d88b0c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/accept-negotiator/package.json @@ -0,0 +1,77 @@ +{ + "name": "@fastify/accept-negotiator", + "version": "2.0.1", + "description": "a negotiator for the accept-headers", + "type": "commonjs", + "main": "index.js", + "types": "types/index.d.ts", + "scripts": { + "lint": "eslint", + "lint:fix": "eslint --fix", + "test": "npm run test:unit && npm run test:typescript", + "test:unit": "c8 --100 node --test", + "test:typescript": "tsd" + }, + "keywords": [ + "encoding", + "negotiator", + "accept-encoding", + "accept", + "http", + "header" + ], + "files": [ + "README.md", + "LICENSE", + "index.js", + "types/index.d.ts" + ], + "author": "Aras Abbasi ", + "contributors": [ + { + "name": "Matteo Collina", + "email": "hello@matteocollina.com" + }, + { + "name": "Manuel Spigolon", + "email": "behemoth89@gmail.com" + }, + { + "name": "James Sumners", + "url": "https://james.sumners.info" + }, + { + "name": "Frazer Smith", + "email": "frazer.dev@icloud.com", + "url": "https://github.com/fdawgs" + } + ], + "license": "MIT", + "devDependencies": { + "@fastify/pre-commit": "^2.1.0", + "@matteo.collina/tspl": "^0.1.1", + "benchmark": "2.1.4", + "c8": "^10.1.2", + "eslint": "^9.17.0", + "neostandard": "^0.12.0", + "tsd": "^0.31.0" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/fastify/accept-negotiator.git" + }, + "bugs": { + "url": "https://github.com/fastify/accept-negotiator/issues" + }, + "homepage": "https://github.com/fastify/accept-negotiator#readme", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ] +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/accept-negotiator/types/index.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/accept-negotiator/types/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b7ba9982ac976c47b5d38683e7a0adb3144cbd02 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/accept-negotiator/types/index.d.ts @@ -0,0 +1,17 @@ +type CacheStore = { set: (key: string, value: string) => CacheStore, get: (key: string) => string | undefined, has: (key: string) => boolean } + +type NegotiateFn = typeof negotiate + +declare namespace negotiate { + export class Negotiator { + constructor (options: { supportedValues: K[]; cache?: CacheStore }) + + negotiate (header: string): K | null + } + + export const negotiate: NegotiateFn + export { negotiate as default } +} + +declare function negotiate (header: string, supportedValues: K[]): K | null +export = negotiate diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/.gitattributes b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..a0e7df931f90e194cc6b80313f8f07744d9fc6d8 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/.gitattributes @@ -0,0 +1,2 @@ +# Set default behavior to automatically convert line endings +* text=auto eol=lf diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/.github/.stale.yml b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/.github/.stale.yml new file mode 100644 index 0000000000000000000000000000000000000000..2ee12691a4fc015ba9eea94b53f14c037dc8f164 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/.github/.stale.yml @@ -0,0 +1,21 @@ +# Number of days of inactivity before an issue becomes stale +daysUntilStale: 15 +# Number of days of inactivity before a stale issue is closed +daysUntilClose: 7 +# Issues with these labels will never be considered stale +exemptLabels: + - "discussion" + - "feature request" + - "bug" + - "help wanted" + - "plugin suggestion" + - "good first issue" +# Label to use when marking an issue as stale +staleLabel: stale +# Comment to post when marking an issue as stale. Set to `false` to disable +markComment: > + This issue has been automatically marked as stale because it has not had + recent activity. It will be closed if no further activity occurs. Thank you + for your contributions. +# Comment to post when closing a stale issue. Set to `false` to disable +closeComment: false \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/.github/dependabot.yml b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..dfa7fa6cba823110c8476a4b4ebcc07cfda12535 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/.github/dependabot.yml @@ -0,0 +1,13 @@ +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "monthly" + open-pull-requests-limit: 10 + + - package-ecosystem: "npm" + directory: "/" + schedule: + interval: "weekly" + open-pull-requests-limit: 10 diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/.github/tests_checker.yml b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/.github/tests_checker.yml new file mode 100644 index 0000000000000000000000000000000000000000..769469b2ab26d4ee6ed08df8d5747abff384b43f --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/.github/tests_checker.yml @@ -0,0 +1,8 @@ +comment: | + Hello! Thank you for contributing! + It appears that you have changed the code, but the tests that verify your change are missing. Could you please add them? +fileExtensions: + - '.ts' + - '.js' + +testDir: 'test' \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/.github/workflows/ci.yml b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/.github/workflows/ci.yml new file mode 100644 index 0000000000000000000000000000000000000000..d373acea174e183db5e10e28adc2e84026a7e6a7 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/.github/workflows/ci.yml @@ -0,0 +1,26 @@ +name: CI + +on: + push: + branches: + - main + - master + - next + - 'v*' + paths-ignore: + - 'docs/**' + - '*.md' + pull_request: + paths-ignore: + - 'docs/**' + - '*.md' + +env: + TZ: 'UTC' + +jobs: + test: + uses: fastify/workflows/.github/workflows/plugins-ci.yml@v5 + with: + lint: true + license-check: true diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/.taprc b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/.taprc new file mode 100644 index 0000000000000000000000000000000000000000..7695d35cfa1d0e719b5f816000e440366f4c2f78 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/.taprc @@ -0,0 +1,2 @@ +files: + - test/**/*.test.js \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/LICENSE b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..7f6f482410494a28532f44ca8239ef863f36ea9d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/LICENSE @@ -0,0 +1,24 @@ +MIT License + +Copyright (c) The Fastify Team + +The Fastify team members are listed at https://github.com/fastify/fastify#team +and in the README file. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/README.md b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6186fe349f4f7d3702bd94a588c65b67aaabff8f --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/README.md @@ -0,0 +1,237 @@ +# @fastify/ajv-compiler + +[![CI](https://github.com/fastify/ajv-compiler/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/fastify/ajv-compiler/actions/workflows/ci.yml) +[![NPM version](https://img.shields.io/npm/v/@fastify/ajv-compiler.svg?style=flat)](https://www.npmjs.com/package/@fastify/ajv-compiler) +[![neostandard javascript style](https://img.shields.io/badge/code_style-neostandard-brightgreen?style=flat)](https://github.com/neostandard/neostandard) + +This module manages the [`ajv`](https://www.npmjs.com/package/ajv) instances for the Fastify framework. +It isolates the `ajv` dependency so that the AJV version is not tightly coupled to the Fastify version. +This allows the user to decide which version of AJV to use in their Fastify-based application. + + +## Versions + +| `@fastify/ajv-compiler` | `ajv` | Default in `fastify` | +|------------------------:|------:|---------------------:| +| v4.x | v8.x | ^5.x | +| v3.x | v8.x | ^4.x | +| v2.x | v8.x | - | +| v1.x | v6.x | ^3.14 | + +### AJV Configuration + +The Fastify's default [`ajv` options](https://github.com/ajv-validator/ajv/tree/v6#options) are: + +```js +{ + coerceTypes: 'array', + useDefaults: true, + removeAdditional: true, + uriResolver: require('fast-uri'), + addUsedSchema: false, + // Explicitly set allErrors to `false`. + // When set to `true`, a DoS attack is possible. + allErrors: false +} +``` + +Moreover, the [`ajv-formats`](https://www.npmjs.com/package/ajv-formats) module is included by default. +If you need to customize it, check the _usage_ section below. + +To customize the `ajv` options, see how in the [Fastify documentation](https://fastify.dev/docs/latest/Reference/Server/#ajv). + + +## Usage + +This module is already used as default by Fastify. +If you need to provide your server instance with a different version, refer to [the Fastify docs](https://fastify.dev/docs/latest/Reference/Server/#schemacontroller). + +### Customize the `ajv-formats` plugin + +The `format` keyword is not part of the official `ajv` module since v7. To use it, you need to install the `ajv-formats` module and this module +does it for you with the default configuration. + +If you need to configure the `ajv-formats` plugin you can do it using the standard Fastify configuration: + +```js +const app = fastify({ + ajv: { + plugins: [[require('ajv-formats'), { mode: 'fast' }]] + } +}) +``` + +In this way, your setup will have precedence over the `@fastify/ajv-compiler` default configuration. + +### Customize the `ajv` instance + +If you need to customize the `ajv` instance and take full control of its configuration, you can do it by +using the `onCreate` option in the Fastify configuration that accepts a synchronous function that receives the `ajv` instance: + +```js +const app = fastify({ + ajv: { + onCreate: (ajv) => { + // Modify the ajv instance as you need. + ajv.addFormat('myFormat', (data) => typeof data === 'string') + } + } +}) +``` + +### Fastify with JTD + +The [JSON Type Definition](https://jsontypedef.com/) feature is supported by AJV v8.x and you can benefit from it in your Fastify application. + +With Fastify v3.20.x and higher, you can use the `@fastify/ajv-compiler` module to load JSON Type Definitions like so: + +```js +const factory = require('@fastify/ajv-compiler')() + +const app = fastify({ + jsonShorthand: false, + ajv: { + customOptions: { }, // additional JTD options + mode: 'JTD' + }, + schemaController: { + compilersFactory: { + buildValidator: factory + } + } +}) +``` + +The default AJV JTD options are the same as [Fastify's default options](#AJV-Configuration). + +#### Fastify with JTD and serialization + +You can use JTD Schemas to serialize your response object too: + +```js +const factoryValidator = require('@fastify/ajv-compiler')() +const factorySerializer = require('@fastify/ajv-compiler')({ jtdSerializer: true }) + +const app = fastify({ + jsonShorthand: false, + ajv: { + customOptions: { }, // additional JTD options + mode: 'JTD' + }, + schemaController: { + compilersFactory: { + buildValidator: factoryValidator, + buildSerializer: factorySerializer + } + } +}) +``` + + +### AJV Standalone + +AJV v8 introduced a [standalone feature](https://ajv.js.org/standalone.html) that lets you pre-compile your schemas and use them in your application for a faster startup. + +To use this feature, you must be aware of the following: + +1. You must generate and save the application's compiled schemas. +2. Read the compiled schemas from the file and provide them back to your Fastify application. + + +#### Generate and save the compiled schemas + +Fastify helps you to generate the validation schemas functions and it is your choice to save them where you want. +To accomplish this, you must use a new compiler: `StandaloneValidator`. + +You must provide 2 parameters to this compiler: + +- `readMode: false`: a boolean to indicate that you want to generate the schemas functions string. +- `storeFunction`" a sync function that must store the source code of the schemas functions. You may provide an async function too, but you must manage errors. + +When `readMode: false`, **the compiler is meant to be used in development ONLY**. + + +```js +const { StandaloneValidator } = require('@fastify/ajv-compiler') +const factory = StandaloneValidator({ + readMode: false, + storeFunction (routeOpts, schemaValidationCode) { + // routeOpts is like: { schema, method, url, httpPart } + // schemaValidationCode is a string source code that is the compiled schema function + const fileName = generateFileName(routeOpts) + fs.writeFileSync(path.join(__dirname, fileName), schemaValidationCode) + } +}) + +const app = fastify({ + jsonShorthand: false, + schemaController: { + compilersFactory: { + buildValidator: factory + } + } +}) + +// ... add all your routes with schemas ... + +app.ready().then(() => { + // at this stage all your schemas are compiled and stored in the file system + // now it is important to turn off the readMode +}) +``` + +#### Read the compiled schemas functions + +At this stage, you should have a file for every route's schema. +To use them, you must use the `StandaloneValidator` with the parameters: + +- `readMode: true`: a boolean to indicate that you want to read and use the schemas functions string. +- `restoreFunction`" a sync function that must return a function to validate the route. + +Important keep away before you continue reading the documentation: + +- when you use the `readMode: true`, the application schemas are not compiled (they are ignored). So, if you change your schemas, you must recompile them! +- as you can see, you must relate the route's schema to the file name using the `routeOpts` object. You may use the `routeOpts.schema.$id` field to do so, it is up to you to define a unique schema identifier. + +```js +const { StandaloneValidator } = require('@fastify/ajv-compiler') +const factory = StandaloneValidator({ + readMode: true, + restoreFunction (routeOpts) { + // routeOpts is like: { schema, method, url, httpPart } + const fileName = generateFileName(routeOpts) + return require(path.join(__dirname, fileName)) + } +}) + +const app = fastify({ + jsonShorthand: false, + schemaController: { + compilersFactory: { + buildValidator: factory + } + } +}) + +// ... add all your routes with schemas as before... + +app.listen({ port: 3000 }) +``` + +### How it works + +This module provides a factory function to produce [Validator Compilers](https://fastify.dev/docs/latest/Reference/Server/#validatorcompiler) functions. + +The Fastify factory function is just one per server instance and it is called for every encapsulated context created by the application through the `fastify.register()` call. + +Every Validator Compiler produced has a dedicated AJV instance, so this factory will try to produce as less as possible AJV instances to reduce the memory footprint and the startup time. + +The variables involved to choose if a Validator Compiler can be reused are: + +- the AJV configuration: it is [one per server](https://fastify.dev/docs/latest/Reference/Server/#ajv) +- the external JSON schemas: once a new schema is added to a fastify's context, calling `fastify.addSchema()`, it will cause a new AJV initialization + + +## License + +Licensed under [MIT](./LICENSE). diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/benchmark/small-object.mjs b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/benchmark/small-object.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a206582330dcda14bb680f1f6b79ddc3383f72da --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/benchmark/small-object.mjs @@ -0,0 +1,37 @@ +import cronometro from 'cronometro' + +import fjs from 'fast-json-stringify' +import AjvCompiler from '../index.js' + +const fjsSerialize = buildFJSSerializerFunction({ + type: 'object', + properties: { + hello: { type: 'string' }, + name: { type: 'string' } + } +}) +const ajvSerialize = buildAJVSerializerFunction({ + properties: { + hello: { type: 'string' }, + name: { type: 'string' } + } +}) + +await cronometro({ + 'fast-json-stringify': function () { + fjsSerialize({ hello: 'Ciao', name: 'Manuel' }) + }, + 'ajv serializer': function () { + ajvSerialize({ hello: 'Ciao', name: 'Manuel' }) + } +}) + +function buildFJSSerializerFunction (schema) { + return fjs(schema) +} + +function buildAJVSerializerFunction (schema) { + const factory = AjvCompiler({ jtdSerializer: true }) + const compiler = factory({}, { customOptions: {} }) + return compiler({ schema }) +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/eslint.config.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/eslint.config.js new file mode 100644 index 0000000000000000000000000000000000000000..89fd678fe2a82d7fe3be869fffd71b3631c61c6a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/eslint.config.js @@ -0,0 +1,6 @@ +'use strict' + +module.exports = require('neostandard')({ + ignores: require('neostandard').resolveIgnoresFromGitignore(), + ts: true +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/index.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/index.js new file mode 100644 index 0000000000000000000000000000000000000000..2274766bab959c39ed1c990b3170204af822b407 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/index.js @@ -0,0 +1,53 @@ +'use strict' + +const AjvReference = Symbol.for('fastify.ajv-compiler.reference') +const ValidatorCompiler = require('./lib/validator-compiler') +const SerializerCompiler = require('./lib/serializer-compiler') + +function AjvCompiler (opts) { + const validatorPool = new Map() + const serializerPool = new Map() + + if (opts && opts.jtdSerializer === true) { + return function buildSerializerFromPool (externalSchemas, serializerOpts) { + const uniqueAjvKey = getPoolKey({}, serializerOpts) + if (serializerPool.has(uniqueAjvKey)) { + return serializerPool.get(uniqueAjvKey) + } + + const compiler = new SerializerCompiler(externalSchemas, serializerOpts) + const ret = compiler.buildSerializerFunction.bind(compiler) + serializerPool.set(uniqueAjvKey, ret) + + return ret + } + } + + return function buildCompilerFromPool (externalSchemas, options) { + const uniqueAjvKey = getPoolKey(externalSchemas, options.customOptions) + if (validatorPool.has(uniqueAjvKey)) { + return validatorPool.get(uniqueAjvKey) + } + + const compiler = new ValidatorCompiler(externalSchemas, options) + const ret = compiler.buildValidatorFunction.bind(compiler) + validatorPool.set(uniqueAjvKey, ret) + + if (options.customOptions.code !== undefined) { + ret[AjvReference] = compiler + } + + return ret + } +} + +function getPoolKey (externalSchemas, options) { + const externals = JSON.stringify(externalSchemas) + const ajvConfig = JSON.stringify(options) + return `${externals}${ajvConfig}` +} +module.exports = AjvCompiler +module.exports.default = AjvCompiler +module.exports.AjvCompiler = AjvCompiler +module.exports.AjvReference = AjvReference +module.exports.StandaloneValidator = require('./standalone') diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/lib/default-ajv-options.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/lib/default-ajv-options.js new file mode 100644 index 0000000000000000000000000000000000000000..57c1fd8bb5fa2bfe988efdb66343fbadcad74fda --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/lib/default-ajv-options.js @@ -0,0 +1,14 @@ +'use strict' + +const fastUri = require('fast-uri') + +module.exports = Object.freeze({ + coerceTypes: 'array', + useDefaults: true, + removeAdditional: true, + uriResolver: fastUri, + addUsedSchema: false, + // Explicitly set allErrors to `false`. + // When set to `true`, a DoS attack is possible. + allErrors: false +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/lib/serializer-compiler.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/lib/serializer-compiler.js new file mode 100644 index 0000000000000000000000000000000000000000..4b54f3e758e75629a6daa38b2facb144203111f7 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/lib/serializer-compiler.js @@ -0,0 +1,27 @@ +'use strict' + +const AjvJTD = require('ajv/dist/jtd') + +const defaultAjvOptions = require('./default-ajv-options') + +class SerializerCompiler { + constructor (_externalSchemas, options) { + this.ajv = new AjvJTD(Object.assign({}, defaultAjvOptions, options)) + + /** + * https://ajv.js.org/json-type-definition.html#ref-form + * Unlike JSON Schema, JTD does not allow to reference: + * - any schema fragment other than root level definitions member + * - root of the schema - there is another way to define a self-recursive schema (see Example 2) + * - another schema file (but you can still combine schemas from multiple files using JavaScript). + * + * So we ignore the externalSchemas parameter. + */ + } + + buildSerializerFunction ({ schema/*, method, url, httpStatus */ }) { + return this.ajv.compileSerializer(schema) + } +} + +module.exports = SerializerCompiler diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/lib/validator-compiler.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/lib/validator-compiler.js new file mode 100644 index 0000000000000000000000000000000000000000..890d004122513abced6b3a10a8ff551b3fbc6a03 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/lib/validator-compiler.js @@ -0,0 +1,58 @@ +'use strict' + +const Ajv = require('ajv').default +const AjvJTD = require('ajv/dist/jtd') + +const defaultAjvOptions = require('./default-ajv-options') + +class ValidatorCompiler { + constructor (externalSchemas, options) { + // This instance of Ajv is private + // it should not be customized or used + if (options.mode === 'JTD') { + this.ajv = new AjvJTD(Object.assign({}, defaultAjvOptions, options.customOptions)) + } else { + this.ajv = new Ajv(Object.assign({}, defaultAjvOptions, options.customOptions)) + } + + let addFormatPlugin = true + if (options.plugins && options.plugins.length > 0) { + for (const plugin of options.plugins) { + if (Array.isArray(plugin)) { + addFormatPlugin = addFormatPlugin && plugin[0].name !== 'formatsPlugin' + plugin[0](this.ajv, plugin[1]) + } else { + addFormatPlugin = addFormatPlugin && plugin.name !== 'formatsPlugin' + plugin(this.ajv) + } + } + } + + if (addFormatPlugin) { + require('ajv-formats')(this.ajv) + } + + options.onCreate?.(this.ajv) + + const sourceSchemas = Object.values(externalSchemas) + for (const extSchema of sourceSchemas) { + this.ajv.addSchema(extSchema) + } + } + + buildValidatorFunction ({ schema/*, method, url, httpPart */ }) { + // Ajv does not support compiling two schemas with the same + // id inside the same instance. Therefore if we have already + // compiled the schema with the given id, we just return it. + if (schema.$id) { + const stored = this.ajv.getSchema(schema.$id) + if (stored) { + return stored + } + } + + return this.ajv.compile(schema) + } +} + +module.exports = ValidatorCompiler diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/package.json b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/package.json new file mode 100644 index 0000000000000000000000000000000000000000..92d48a9c32847ceb5d217d5dd4d925b36ede09f7 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/package.json @@ -0,0 +1,84 @@ +{ + "name": "@fastify/ajv-compiler", + "version": "4.0.2", + "description": "Build and manage the AJV instances for the fastify framework", + "main": "index.js", + "type": "commonjs", + "types": "types/index.d.ts", + "directories": { + "test": "test" + }, + "scripts": { + "lint": "eslint", + "lint:fix": "eslint --fix", + "unit": "tap", + "test": "npm run unit && npm run test:typescript", + "test:typescript": "tsd", + "ajv:compile": "ajv compile -s test/source.json -o test/validate_schema.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/fastify/ajv-compiler.git" + }, + "keywords": [ + "ajv", + "validator", + "schema", + "compiler", + "fastify" + ], + "author": "Manuel Spigolon (https://github.com/Eomm)", + "contributors": [ + { + "name": "Matteo Collina", + "email": "hello@matteocollina.com" + }, + { + "name": "Aras Abbasi", + "email": "aras.abbasi@gmail.com" + }, + { + "name": "James Sumners", + "url": "https://james.sumners.info" + }, + { + "name": "Frazer Smith", + "email": "frazer.dev@icloud.com", + "url": "https://github.com/fdawgs" + } + ], + "license": "MIT", + "bugs": { + "url": "https://github.com/fastify/ajv-compiler/issues" + }, + "homepage": "https://github.com/fastify/ajv-compiler#readme", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "devDependencies": { + "ajv-cli": "^5.0.0", + "ajv-errors": "^3.0.0", + "ajv-i18n": "^4.2.0", + "ajv-merge-patch": "^5.0.1", + "cronometro": "^4.0.0", + "eslint": "^9.17.0", + "fastify": "^5.0.0", + "neostandard": "^0.12.0", + "require-from-string": "^2.0.2", + "sanitize-filename": "^1.6.3", + "tap": "^19.0.0", + "tsd": "^0.31.0" + }, + "dependencies": { + "ajv": "^8.12.0", + "ajv-formats": "^3.0.1", + "fast-uri": "^3.0.0" + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/standalone.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/standalone.js new file mode 100644 index 0000000000000000000000000000000000000000..42428a0d66746fdf8a86a53f56c04b2994e0ba29 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/standalone.js @@ -0,0 +1,44 @@ +'use strict' + +const ValidatorSelector = require('./index') +const standaloneCode = require('ajv/dist/standalone').default + +function StandaloneValidator (options = { readMode: true }) { + if (options.readMode === true && !options.restoreFunction) { + throw new Error('You must provide a restoreFunction options when readMode ON') + } + + if (options.readMode !== true && !options.storeFunction) { + throw new Error('You must provide a storeFunction options when readMode OFF') + } + + if (options.readMode === true) { + // READ MODE: it behalf only in the restore function provided by the user + return function wrapper () { + return function (opts) { + return options.restoreFunction(opts) + } + } + } + + // WRITE MODE: it behalf on the default ValidatorSelector, wrapping the API to run the Ajv Standalone code generation + const factory = ValidatorSelector() + return function wrapper (externalSchemas, ajvOptions = {}) { + if (!ajvOptions.customOptions || !ajvOptions.customOptions.code) { + // to generate the validation source code, these options are mandatory + ajvOptions.customOptions = Object.assign({}, ajvOptions.customOptions, { code: { source: true } }) + } + + const compiler = factory(externalSchemas, ajvOptions) + return function (opts) { // { schema/*, method, url, httpPart */ } + const validationFunc = compiler(opts) + + const schemaValidationCode = standaloneCode(compiler[ValidatorSelector.AjvReference].ajv, validationFunc) + options.storeFunction(opts, schemaValidationCode) + + return validationFunc + } + } +} + +module.exports = StandaloneValidator diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/test/.gitkeep b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/test/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/test/duplicated-id-compile.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/test/duplicated-id-compile.test.js new file mode 100644 index 0000000000000000000000000000000000000000..849016c6c01cf92d8f65f0aa9501745dadbc684a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/test/duplicated-id-compile.test.js @@ -0,0 +1,59 @@ +'use strict' + +const t = require('tap') +const AjvCompiler = require('../index') + +const postSchema = Object.freeze({ + $schema: 'http://json-schema.org/draft-07/schema#', + type: 'object', + $id: 'http://mydomain.com/user', + title: 'User schema', + description: 'Contains all user fields', + properties: { + username: { type: 'string', minLength: 4 }, + firstName: { type: 'string', minLength: 1 }, + lastName: { type: 'string', minLength: 1 }, + email: { type: 'string' }, + password: { type: 'string', minLength: 6 }, + bio: { type: 'string' } + }, + required: ['username', 'firstName', 'lastName', 'email', 'bio', 'password'] +}) + +const patchSchema = Object.freeze({ + $schema: 'http://json-schema.org/draft-07/schema#', + type: 'object', + $id: 'http://mydomain.com/user', + title: 'User schema', + description: 'Contains all user fields', + properties: { + firstName: { type: 'string', minLength: 1 }, + lastName: { type: 'string', minLength: 1 }, + bio: { type: 'string' } + } +}) + +const fastifyAjvOptionsDefault = Object.freeze({ + customOptions: {} +}) + +t.test('must not store schema on compile', t => { + t.plan(4) + const factory = AjvCompiler() + const compiler = factory({}, fastifyAjvOptionsDefault) + const postFn = compiler({ schema: postSchema }) + const patchFn = compiler({ schema: patchSchema }) + + const resultForPost = postFn({}) + t.equal(resultForPost, false) + t.has(postFn.errors, [ + { + keyword: 'required', + message: "must have required property 'username'" + } + ]) + + const resultForPatch = patchFn({}) + t.ok(resultForPatch) + t.notOk(patchFn.errors) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/test/index.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/test/index.test.js new file mode 100644 index 0000000000000000000000000000000000000000..fe1427ce81877b16d7407d91ac4c5f40d2e02868 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/test/index.test.js @@ -0,0 +1,307 @@ +'use strict' + +const t = require('tap') +const fastify = require('fastify') +const AjvCompiler = require('../index') + +const sym = Symbol.for('fastify.ajv-compiler.reference') + +const sampleSchema = Object.freeze({ + $id: 'example1', + type: 'object', + properties: { + name: { type: 'string' } + } +}) + +const externalSchemas1 = Object.freeze({}) +const externalSchemas2 = Object.freeze({ + foo: { + $id: 'foo', + type: 'object', + properties: { + name: { type: 'string' } + } + } +}) + +const fastifyAjvOptionsDefault = Object.freeze({ + customOptions: {} +}) + +const fastifyJtdDefault = Object.freeze({ + customOptions: { }, + mode: 'JTD' +}) + +const fastifyAjvOptionsCustom = Object.freeze({ + customOptions: { + allErrors: true, + removeAdditional: false + }, + plugins: [ + require('ajv-formats'), + [require('ajv-errors'), { singleError: false }] + ] +}) + +t.test('basic usage', t => { + t.plan(1) + const factory = AjvCompiler() + const compiler = factory(externalSchemas1, fastifyAjvOptionsDefault) + const validatorFunc = compiler({ schema: sampleSchema }) + const result = validatorFunc({ name: 'hello' }) + t.equal(result, true) +}) + +t.test('array coercion', t => { + t.plan(2) + const factory = AjvCompiler() + const compiler = factory(externalSchemas1, fastifyAjvOptionsDefault) + + const arraySchema = { + $id: 'example1', + type: 'object', + properties: { + name: { type: 'array', items: { type: 'string' } } + } + } + + const validatorFunc = compiler({ schema: arraySchema }) + + const inputObj = { name: 'hello' } + t.equal(validatorFunc(inputObj), true) + t.same(inputObj, { name: ['hello'] }, 'the name property should be coerced to an array') +}) + +t.test('nullable default', t => { + t.plan(2) + const factory = AjvCompiler() + const compiler = factory({}, fastifyAjvOptionsDefault) + const validatorFunc = compiler({ + schema: { + type: 'object', + properties: { + nullable: { type: 'string', nullable: true }, + notNullable: { type: 'string' } + } + } + }) + const input = { nullable: null, notNullable: null } + const result = validatorFunc(input) + t.equal(result, true) + t.same(input, { nullable: null, notNullable: '' }, 'the notNullable field has been coerced') +}) + +t.test('plugin loading', t => { + t.plan(3) + const factory = AjvCompiler() + const compiler = factory(externalSchemas1, fastifyAjvOptionsCustom) + const validatorFunc = compiler({ + schema: { + type: 'object', + properties: { + q: { + type: 'string', + format: 'date', + formatMinimum: '2016-02-06', + formatExclusiveMaximum: '2016-12-27' + } + }, + required: ['q'], + errorMessage: 'hello world' + } + }) + const result = validatorFunc({ q: '2016-10-02' }) + t.equal(result, true) + + const resultFail = validatorFunc({}) + t.equal(resultFail, false) + t.equal(validatorFunc.errors[0].message, 'hello world') +}) + +t.test('optimization - cache ajv instance', t => { + t.plan(5) + const factory = AjvCompiler() + const compiler1 = factory(externalSchemas1, fastifyAjvOptionsDefault) + const compiler2 = factory(externalSchemas1, fastifyAjvOptionsDefault) + t.equal(compiler1, compiler2, 'same instance') + t.same(compiler1, compiler2, 'same instance') + + const compiler3 = factory(externalSchemas2, fastifyAjvOptionsDefault) + t.not(compiler3, compiler1, 'new ajv instance when externa schema change') + + const compiler4 = factory(externalSchemas1, fastifyAjvOptionsCustom) + t.not(compiler4, compiler1, 'new ajv instance when externa schema change') + t.not(compiler4, compiler3, 'new ajv instance when externa schema change') +}) + +t.test('the onCreate callback can enhance the ajv instance', t => { + t.plan(2) + const factory = AjvCompiler() + + const fastifyAjvCustomOptionsFormats = Object.freeze({ + onCreate (ajv) { + for (const [formatName, format] of Object.entries(this.customOptions.formats)) { + ajv.addFormat(formatName, format) + } + }, + customOptions: { + formats: { + date: /foo/ + } + } + }) + + const compiler1 = factory(externalSchemas1, fastifyAjvCustomOptionsFormats) + const validatorFunc = compiler1({ + schema: { + type: 'string', + format: 'date' + } + }) + const result = validatorFunc('foo') + t.equal(result, true) + + const resultFail = validatorFunc('2016-10-02') + t.equal(resultFail, false) +}) + +// https://github.com/fastify/fastify/pull/2969 +t.test('compile same $id when in external schema', t => { + t.plan(3) + const factory = AjvCompiler() + + const base = { + $id: 'urn:schema:base', + definitions: { + hello: { type: 'string' } + }, + type: 'object', + properties: { + hello: { $ref: '#/definitions/hello' } + } + } + + const refSchema = { + $id: 'urn:schema:ref', + type: 'object', + properties: { + hello: { $ref: 'urn:schema:base#/definitions/hello' } + } + } + + const compiler = factory({ + [base.$id]: base, + [refSchema.$id]: refSchema + + }, fastifyAjvOptionsDefault) + + t.notOk(compiler[sym], 'the ajv reference do not exists if code is not activated') + + const validatorFunc1 = compiler({ + schema: { + $id: 'urn:schema:ref' + } + }) + + const validatorFunc2 = compiler({ + schema: { + $id: 'urn:schema:ref' + } + }) + + t.pass('the compile does not fail if the schema compiled is already in the external schemas') + t.equal(validatorFunc1, validatorFunc2, 'the returned function is the same') +}) + +t.test('JTD MODE', t => { + t.plan(2) + + t.test('compile jtd schema', t => { + t.plan(4) + const factory = AjvCompiler() + + const jtdSchema = { + discriminator: 'version', + mapping: { + 1: { + properties: { + foo: { type: 'uint8' } + } + }, + 2: { + properties: { + foo: { type: 'string' } + } + } + } + } + + const compiler = factory({}, fastifyJtdDefault) + const validatorFunc = compiler({ schema: jtdSchema }) + t.pass('generated validation function for JTD SCHEMA') + + const result = validatorFunc({ + version: '2', + foo: [] + }) + t.notOk(result, 'failed validation') + t.type(validatorFunc.errors, 'Array') + + const success = validatorFunc({ + version: '1', + foo: 42 + }) + t.ok(success) + }) + + t.test('fastify integration', async t => { + const factory = AjvCompiler() + + const app = fastify({ + jsonShorthand: false, + ajv: { + customOptions: { }, + mode: 'JTD' + }, + schemaController: { + compilersFactory: { + buildValidator: factory + } + } + }) + + app.post('/', { + schema: { + body: { + discriminator: 'version', + mapping: { + 1: { + properties: { + foo: { type: 'uint8' } + } + }, + 2: { + properties: { + foo: { type: 'string' } + } + } + } + } + } + }, () => {}) + + const res = await app.inject({ + url: '/', + method: 'POST', + payload: { + version: '1', + foo: 'this is not a number' + } + }) + + t.equal(res.statusCode, 400) + t.equal(res.json().message, 'body/foo must be uint8') + }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/test/plugins.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/test/plugins.test.js new file mode 100644 index 0000000000000000000000000000000000000000..dacb0e893676ac713f48381cebfd380a3b1d3ef4 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/test/plugins.test.js @@ -0,0 +1,264 @@ +'use strict' + +const t = require('tap') +const fastify = require('fastify') +const AjvCompiler = require('../index') + +const ajvFormats = require('ajv-formats') +const ajvErrors = require('ajv-errors') +const localize = require('ajv-i18n') + +t.test('Format Baseline test', async (t) => { + const app = buildApplication({ + customOptions: { + validateFormats: false + } + }) + + const res = await app.inject({ + url: '/hello', + headers: { + 'x-foo': 'hello', + 'x-date': 'not a date', + 'x-email': 'not an email' + }, + query: { + foo: 'hello', + date: 'not a date', + email: 'not an email' + } + }) + t.equal(res.statusCode, 200, 'format validation does not apply as configured') + t.equal(res.payload, 'hello') +}) + +t.test('Custom Format plugin loading test', (t) => { + t.plan(6) + const app = buildApplication({ + customOptions: { + validateFormats: true + }, + plugins: [[ajvFormats, { mode: 'fast' }]] + }) + + app.inject('/hello', (err, res) => { + t.error(err) + t.equal(res.statusCode, 400, 'format validation applies') + }) + + app.inject('/2ad0612c-7578-4b18-9a6f-579863f40e0b', (err, res) => { + t.error(err) + t.equal(res.statusCode, 400, 'format validation applies') + }) + + app.inject({ + url: '/2ad0612c-7578-4b18-9a6f-579863f40e0b', + headers: { + 'x-foo': 'hello', + 'x-date': new Date().toISOString(), + 'x-email': 'foo@bar.baz' + }, + query: { + foo: 'hello', + date: new Date().toISOString(), + email: 'foo@bar.baz' + } + }, (err, res) => { + t.error(err) + t.equal(res.statusCode, 200) + }) +}) + +t.test('Format plugin set by default test', (t) => { + t.plan(6) + const app = buildApplication({}) + + app.inject('/hello', (err, res) => { + t.error(err) + t.equal(res.statusCode, 400, 'format validation applies') + }) + + app.inject('/2ad0612c-7578-4b18-9a6f-579863f40e0b', (err, res) => { + t.error(err) + t.equal(res.statusCode, 400, 'format validation applies') + }) + + app.inject({ + url: '/2ad0612c-7578-4b18-9a6f-579863f40e0b', + headers: { + 'x-foo': 'hello', + 'x-date': new Date().toISOString(), + 'x-email': 'foo@bar.baz' + }, + query: { + foo: 'hello', + date: new Date().toISOString(), + email: 'foo@bar.baz' + } + }, (err, res) => { + t.error(err) + t.equal(res.statusCode, 200) + }) +}) + +t.test('Custom error messages', (t) => { + t.plan(9) + + const app = buildApplication({ + customOptions: { + removeAdditional: false, + allErrors: true + }, + plugins: [ajvFormats, ajvErrors] + }) + + const errorMessage = { + required: 'custom miss', + type: 'custom type', // will not replace internal "type" error for the property "foo" + _: 'custom type', // this prop will do it + additionalProperties: 'custom too many params' + } + + app.post('/', { + handler: () => { t.fail('dont call me') }, + schema: { + body: { + type: 'object', + required: ['foo'], + properties: { + foo: { type: 'integer' } + }, + additionalProperties: false, + errorMessage + } + } + }) + + app.inject({ + url: '/', + method: 'post', + payload: {} + }, (err, res) => { + t.error(err) + t.equal(res.statusCode, 400) + t.match(res.json().message, errorMessage.required) + }) + + app.inject({ + url: '/', + method: 'post', + payload: { foo: 'not a number' } + }, (err, res) => { + t.error(err) + t.equal(res.statusCode, 400) + t.match(res.json().message, errorMessage.type) + }) + + app.inject({ + url: '/', + method: 'post', + payload: { foo: 3, bar: 'ops' } + }, (err, res) => { + t.error(err) + t.equal(res.statusCode, 400) + t.match(res.json().message, errorMessage.additionalProperties) + }) +}) + +t.test('Custom i18n error messages', (t) => { + t.plan(3) + + const app = buildApplication({ + customOptions: { + allErrors: true, + messages: false + }, + plugins: [ajvFormats] + }) + + app.post('/', { + handler: () => { t.fail('dont call me') }, + schema: { + body: { + type: 'object', + required: ['foo'], + properties: { + foo: { type: 'integer' } + } + } + } + }) + + app.setErrorHandler((error, request, reply) => { + t.pass('Error handler executed') + if (error.validation) { + localize.ru(error.validation) + reply.status(400).send(error.validation) + return + } + t.fail('not other errors') + }) + + app.inject({ + method: 'POST', + url: '/', + payload: { + foo: 'string' + } + }, (err, res) => { + t.error(err) + t.equal(res.json()[0].message, 'должно быть integer') + }) +}) + +function buildApplication (ajvOptions) { + const factory = AjvCompiler() + + const app = fastify({ + ajv: ajvOptions, + schemaController: { + compilersFactory: { + buildValidator: factory + } + } + }) + + app.get('/:id', { + schema: { + headers: { + type: 'object', + required: [ + 'x-foo', + 'x-date', + 'x-email' + ], + properties: { + 'x-foo': { type: 'string' }, + 'x-date': { type: 'string', format: 'date-time' }, + 'x-email': { type: 'string', format: 'email' } + } + }, + query: { + type: 'object', + required: [ + 'foo', + 'date', + 'email' + ], + properties: { + foo: { type: 'string' }, + date: { type: 'string', format: 'date-time' }, + email: { type: 'string', format: 'email' } + } + }, + params: { + type: 'object', + properties: { + id: { type: 'string', format: 'uuid' } + } + } + } + }, async () => 'hello') + + return app +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/test/serialization.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/test/serialization.test.js new file mode 100644 index 0000000000000000000000000000000000000000..20821e0d1fc1a4849b9d0dfae98d7f38f8f81cdd --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/test/serialization.test.js @@ -0,0 +1,279 @@ +'use strict' + +const t = require('tap') +const fastify = require('fastify') +const AjvCompiler = require('../index') + +const jtdSchema = { + discriminator: 'version', + mapping: { + 1: { + properties: { + foo: { type: 'uint8' } + } + }, + 2: { + properties: { + foo: { type: 'string' } + } + } + } +} + +const externalSchemas1 = Object.freeze({}) +const externalSchemas2 = Object.freeze({ + foo: { + definitions: { + coordinates: { + properties: { + lat: { type: 'float32' }, + lng: { type: 'float32' } + } + } + } + } +}) + +const fastifyAjvOptionsDefault = Object.freeze({ + customOptions: {} +}) + +t.test('basic serializer usage', t => { + t.plan(4) + const factory = AjvCompiler({ jtdSerializer: true }) + const compiler = factory(externalSchemas1, fastifyAjvOptionsDefault) + const serializeFunc = compiler({ schema: jtdSchema }) + t.equal(serializeFunc({ version: '1', foo: 42 }), '{"version":"1","foo":42}') + t.equal(serializeFunc({ version: '2', foo: 'hello' }), '{"version":"2","foo":"hello"}') + t.equal(serializeFunc({ version: '3', foo: 'hello' }), '{"version":"3"}') + t.equal(serializeFunc({ version: '2', foo: ['not', 1, { string: 'string' }] }), '{"version":"2","foo":"not,1,[object Object]"}') +}) + +t.test('external schemas are ignored', t => { + t.plan(1) + const factory = AjvCompiler({ jtdSerializer: true }) + const compiler = factory(externalSchemas2, fastifyAjvOptionsDefault) + const serializeFunc = compiler({ + schema: { + definitions: { + coordinates: { + properties: { + lat: { type: 'float32' }, + lng: { type: 'float32' } + } + } + }, + properties: { + userLoc: { ref: 'coordinates' }, + serverLoc: { ref: 'coordinates' } + } + } + }) + t.equal(serializeFunc( + { userLoc: { lat: 50, lng: -90 }, serverLoc: { lat: -15, lng: 50 } }), + '{"userLoc":{"lat":50,"lng":-90},"serverLoc":{"lat":-15,"lng":50}}' + ) +}) + +t.test('fastify integration within JTD serializer', async t => { + const factoryValidator = AjvCompiler() + const factorySerializer = AjvCompiler({ jtdSerializer: true }) + + const app = fastify({ + jsonShorthand: false, + ajv: { + customOptions: { }, + mode: 'JTD' + }, + schemaController: { + compilersFactory: { + buildValidator: factoryValidator, + buildSerializer: factorySerializer + } + } + }) + + app.post('/', { + schema: { + body: jtdSchema, + response: { + 200: { + properties: { + id: { type: 'string' }, + createdAt: { type: 'timestamp' }, + karma: { type: 'int32' }, + isAdmin: { type: 'boolean' } + } + }, + 400: jtdSchema + } + } + }, async () => { + return { + id: '123', + createdAt: new Date('1999-01-31T23:00:00.000Z'), + karma: 42, + isAdmin: true, + remove: 'me' + } + }) + + { + const res = await app.inject({ + url: '/', + method: 'POST', + payload: { + version: '1', + foo: 'not a number' + } + }) + + t.equal(res.statusCode, 400) + t.same(res.json(), { version: 'undefined' }) + } + + { + const res = await app.inject({ + url: '/', + method: 'POST', + payload: { + version: '1', + foo: 32 + } + }) + + t.equal(res.statusCode, 200) + t.same(res.json(), { + id: '123', + createdAt: '1999-01-31T23:00:00.000Z', + karma: 42, + isAdmin: true + }) + } +}) + +t.test('fastify integration and cached serializer', async t => { + const factoryValidator = AjvCompiler() + const factorySerializer = AjvCompiler({ jtdSerializer: true }) + + const app = fastify({ + jsonShorthand: false, + ajv: { + customOptions: { }, + mode: 'JTD' + }, + schemaController: { + compilersFactory: { + buildValidator: factoryValidator, + buildSerializer: factorySerializer + } + } + }) + + app.register(async function plugin (app, opts) { + app.post('/', { + schema: { + body: jtdSchema, + response: { + 200: { + properties: { + id: { type: 'string' }, + createdAt: { type: 'timestamp' }, + karma: { type: 'int32' }, + isAdmin: { type: 'boolean' } + } + }, + 400: jtdSchema + } + } + }, async () => { + return { + id: '123', + createdAt: new Date('1999-01-31T23:00:00.000Z'), + karma: 42, + isAdmin: true, + remove: 'me' + } + }) + }) + + app.register(async function plugin (app, opts) { + app.post('/two', { + schema: { + body: jtdSchema, + response: { + 400: jtdSchema + } + } + }, () => {}) + }) + + { + const res = await app.inject({ + url: '/', + method: 'POST', + payload: { + version: '1', + foo: 'not a number' + } + }) + + t.equal(res.statusCode, 400) + t.same(res.json(), { version: 'undefined' }) + } + + { + const res = await app.inject({ + url: '/', + method: 'POST', + payload: { + version: '1', + foo: 32 + } + }) + + t.equal(res.statusCode, 200) + t.same(res.json(), { + id: '123', + createdAt: '1999-01-31T23:00:00.000Z', + karma: 42, + isAdmin: true + }) + } +}) + +t.test('fastify integration within JTD serializer and custom options', async t => { + const factorySerializer = AjvCompiler({ jtdSerializer: true }) + + const app = fastify({ + jsonShorthand: false, + serializerOpts: { + allErrors: true, + logger: 'wrong-value' + }, + schemaController: { + compilersFactory: { + buildSerializer: factorySerializer + } + } + }) + + app.post('/', { + schema: { + response: { + 200: { + properties: { + test: { type: 'boolean' } + } + } + } + } + }, async () => { }) + + try { + await app.ready() + t.fail('should throw') + } catch (error) { + t.equal(error.message, 'logger must implement log, warn and error methods', 'the wrong setting is forwarded to ajv/jtd') + } +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/test/standalone.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/test/standalone.test.js new file mode 100644 index 0000000000000000000000000000000000000000..f32fcbac727e99e073e9a4e369042b2cfde7db44 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/test/standalone.test.js @@ -0,0 +1,203 @@ +'use strict' + +const fs = require('node:fs') +const path = require('node:path') +const t = require('tap') +const fastify = require('fastify') +const sanitize = require('sanitize-filename') + +const { StandaloneValidator: AjvStandaloneValidator } = require('../') + +function generateFileName (routeOpts) { + return `/ajv-generated-${sanitize(routeOpts.schema.$id)}-${routeOpts.method}-${routeOpts.httpPart}-${sanitize(routeOpts.url)}.js` +} + +const generatedFileNames = [] + +t.test('standalone', t => { + t.plan(4) + + t.teardown(async () => { + for (const fileName of generatedFileNames) { + await fs.promises.unlink(path.join(__dirname, fileName)) + } + }) + + t.test('errors', t => { + t.plan(2) + t.throws(() => { + AjvStandaloneValidator() + }, 'missing restoreFunction') + t.throws(() => { + AjvStandaloneValidator({ readMode: false }) + }, 'missing storeFunction') + }) + + t.test('generate standalone code', t => { + t.plan(5) + + const base = { + $id: 'urn:schema:base', + definitions: { + hello: { type: 'string' } + }, + type: 'object', + properties: { + hello: { $ref: '#/definitions/hello' } + } + } + + const refSchema = { + $id: 'urn:schema:ref', + type: 'object', + properties: { + hello: { $ref: 'urn:schema:base#/definitions/hello' } + } + } + + const endpointSchema = { + schema: { + $id: 'urn:schema:endpoint', + $ref: 'urn:schema:ref' + } + } + + const schemaMap = { + [base.$id]: base, + [refSchema.$id]: refSchema + } + + const factory = AjvStandaloneValidator({ + readMode: false, + storeFunction (routeOpts, schemaValidationCode) { + t.same(routeOpts, endpointSchema) + t.type(schemaValidationCode, 'string') + fs.writeFileSync(path.join(__dirname, '/ajv-generated.js'), schemaValidationCode) + generatedFileNames.push('/ajv-generated.js') + t.pass('stored the validation function') + } + }) + + const compiler = factory(schemaMap) + compiler(endpointSchema) + t.pass('compiled the endpoint schema') + + t.test('usage standalone code', t => { + t.plan(3) + const standaloneValidate = require('./ajv-generated') + + const valid = standaloneValidate({ hello: 'world' }) + t.ok(valid) + + const invalid = standaloneValidate({ hello: [] }) + t.notOk(invalid) + + t.ok(standaloneValidate) + }) + }) + + t.test('fastify integration - writeMode', async t => { + t.plan(6) + + const factory = AjvStandaloneValidator({ + readMode: false, + storeFunction (routeOpts, schemaValidationCode) { + const fileName = generateFileName(routeOpts) + t.ok(routeOpts) + fs.writeFileSync(path.join(__dirname, fileName), schemaValidationCode) + t.pass('stored the validation function') + generatedFileNames.push(fileName) + }, + restoreFunction () { + t.fail('write mode ON') + } + }) + + const app = buildApp(factory) + await app.ready() + }) + + t.test('fastify integration - readMode', async t => { + t.plan(6) + + const factory = AjvStandaloneValidator({ + readMode: true, + storeFunction () { + t.fail('read mode ON') + }, + restoreFunction (routeOpts) { + t.pass('restore the validation function') + const fileName = generateFileName(routeOpts) + return require(path.join(__dirname, fileName)) + } + }) + + const app = buildApp(factory) + await app.ready() + + let res = await app.inject({ + url: '/foo', + method: 'POST', + payload: { hello: [] } + }) + t.equal(res.statusCode, 400) + + res = await app.inject({ + url: '/bar?lang=invalid', + method: 'GET' + }) + t.equal(res.statusCode, 400) + + res = await app.inject({ + url: '/bar?lang=it', + method: 'GET' + }) + t.equal(res.statusCode, 200) + }) + + function buildApp (factory) { + const app = fastify({ + jsonShorthand: false, + schemaController: { + compilersFactory: { + buildValidator: factory + } + } + }) + + app.addSchema({ + $id: 'urn:schema:foo', + type: 'object', + properties: { + name: { type: 'string' }, + id: { type: 'integer' } + } + }) + + app.post('/foo', { + schema: { + body: { + $id: 'urn:schema:body', + type: 'object', + properties: { + hello: { $ref: 'urn:schema:foo#/properties/name' } + } + } + } + }, () => { return 'ok' }) + + app.get('/bar', { + schema: { + query: { + $id: 'urn:schema:query', + type: 'object', + properties: { + lang: { type: 'string', enum: ['it', 'en'] } + } + } + } + }, () => { return 'ok' }) + + return app + } +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/types/index.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/types/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0749dfaac89500a81f72acf10c297a0b7cdacc09 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/types/index.d.ts @@ -0,0 +1,72 @@ +import _ajv, { AnySchema, Options as AjvOptions, ValidateFunction } from 'ajv' +import AjvJTD, { JTDOptions } from 'ajv/dist/jtd' +import type { Options, ErrorObject } from 'ajv' +import { AnyValidateFunction } from 'ajv/dist/core' + +type Ajv = _ajv +type AjvSerializerGenerator = typeof AjvCompiler + +type AjvJTDCompile = AjvJTD['compileSerializer'] +type AjvCompile = (schema: AnySchema, _meta?: boolean) => AnyValidateFunction + +declare function buildCompilerFromPool (externalSchemas: { [key: string]: AnySchema | AnySchema[] }, options?: { mode: 'JTD'; customOptions?: JTDOptions; onCreate?: (ajvInstance: Ajv) => void }): AjvCompile +declare function buildCompilerFromPool (externalSchemas: { [key: string]: AnySchema | AnySchema[] }, options?: { mode?: never; customOptions?: AjvOptions; onCreate?: (ajvInstance: Ajv) => void }): AjvCompile + +declare function buildSerializerFromPool (externalSchemas: any, serializerOpts?: { mode?: never; } & JTDOptions): AjvJTDCompile + +declare function AjvCompiler (opts: { jtdSerializer: true }): AjvCompiler.BuildSerializerFromPool +declare function AjvCompiler (opts?: { jtdSerializer?: false }): AjvCompiler.BuildCompilerFromPool + +declare function StandaloneValidator (options: AjvCompiler.StandaloneOptions): AjvCompiler.BuildCompilerFromPool + +declare namespace AjvCompiler { + export type { Options, ErrorObject } + export { Ajv } + + export type BuildSerializerFromPool = typeof buildSerializerFromPool + + export type BuildCompilerFromPool = typeof buildCompilerFromPool + + export const AjvReference: Symbol + + export enum HttpParts { + Body = 'body', + Headers = 'headers', + Params = 'params', + Query = 'querystring', + } + + export type RouteDefinition = { + method: string, + url: string, + httpPart: HttpParts, + schema?: unknown, + } + + export type StandaloneRestoreFunction = (opts: RouteDefinition) => ValidateFunction + + export type StandaloneStoreFunction = (opts: RouteDefinition, schemaValidationCode: string) => void + + export type StandaloneOptionsReadModeOn = { + readMode: true; + restoreFunction?: StandaloneRestoreFunction + } + + export type StandaloneOptionsReadModeOff = { + readMode?: false | undefined; + storeFunction?: StandaloneStoreFunction; + } + + export type StandaloneOptions = StandaloneOptionsReadModeOn | StandaloneOptionsReadModeOff + + export type ValidatorFactory = BuildCompilerFromPool | BuildSerializerFromPool + + export type ValidatorCompiler = ReturnType + + export { StandaloneValidator } + + export const AjvCompiler: AjvSerializerGenerator + export { AjvCompiler as default } +} + +export = AjvCompiler diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/types/index.test-d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/types/index.test-d.ts new file mode 100644 index 0000000000000000000000000000000000000000..391e7b7ad24d9e16f0218d599df6abb87d521d38 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/ajv-compiler/types/index.test-d.ts @@ -0,0 +1,226 @@ +import { AnySchemaObject, ValidateFunction } from 'ajv' +import { AnyValidateFunction } from 'ajv/dist/core' +import { expectAssignable, expectType } from 'tsd' +import AjvCompiler, { AjvReference, ValidatorFactory, StandaloneValidator, RouteDefinition, ErrorObject, BuildCompilerFromPool, BuildSerializerFromPool, ValidatorCompiler } from '..' + +{ + const compiler = AjvCompiler({}) + expectType(compiler) +} +{ + const compiler = AjvCompiler() + expectType(compiler) +} +{ + const compiler = AjvCompiler({ jtdSerializer: false }) + expectType(compiler) +} + +{ + const factory = AjvCompiler({ jtdSerializer: false }) + expectType(factory) + factory({}, { + onCreate (ajv) { + expectType(ajv) + } + }) +} + +{ + const compiler = AjvCompiler({ jtdSerializer: true }) + expectType(compiler) +} +const reader = StandaloneValidator({ + readMode: true, + restoreFunction: (route: RouteDefinition) => { + expectAssignable(route) + return {} as ValidateFunction + }, +}) +expectAssignable(reader) + +const writer = StandaloneValidator({ + readMode: false, + storeFunction: (route: RouteDefinition, code: string) => { + expectAssignable(route) + expectAssignable(code) + }, +}) +expectAssignable(writer) + +expectType(({} as ErrorObject).data) +expectType(({} as ErrorObject).instancePath) +expectType(({} as ErrorObject).keyword) +expectType(({} as ErrorObject).message) +expectType>(({} as ErrorObject).params) +expectType(({} as ErrorObject).parentSchema) +expectType(({} as ErrorObject).propertyName) +expectType(({} as ErrorObject).schema) +expectType(({} as ErrorObject).schemaPath) + +expectType(AjvReference) + +{ + const jtdSchema = { + discriminator: 'version', + mapping: { + 1: { + properties: { + foo: { type: 'uint8' } + } + }, + 2: { + properties: { + foo: { type: 'string' } + } + } + } + } + + const externalSchemas1 = { + foo: { + definitions: { + coordinates: { + properties: { + lat: { type: 'float32' }, + lng: { type: 'float32' } + } + } + } + } + } + + const factory = AjvCompiler({ jtdSerializer: true }) + expectType(factory) + const compiler = factory(externalSchemas1, {}) + expectAssignable(compiler) + const serializeFunc = compiler({ schema: jtdSchema }) + expectType<(data: unknown) => string>(serializeFunc) + expectType(serializeFunc({ version: '1', foo: 42 })) +} +// JTD +{ + const factory = AjvCompiler() + expectType(factory) + + const jtdSchema = { + discriminator: 'version', + mapping: { + 1: { + properties: { + foo: { type: 'uint8' } + } + }, + 2: { + properties: { + foo: { type: 'string' } + } + } + } + } + + const compiler = factory({}, { + customOptions: {}, + mode: 'JTD' + }) + expectAssignable(compiler) + const validatorFunc = compiler({ schema: jtdSchema }) + expectAssignable(validatorFunc) + + expectType>(validatorFunc({ + version: '2', + foo: [] + })) +} + +// generate standalone code +{ + const base = { + $id: 'urn:schema:base', + definitions: { + hello: { type: 'string' } + }, + type: 'object', + properties: { + hello: { $ref: '#/definitions/hello' } + } + } + + const refSchema = { + $id: 'urn:schema:ref', + type: 'object', + properties: { + hello: { $ref: 'urn:schema:base#/definitions/hello' } + } + } + + const endpointSchema = { + schema: { + $id: 'urn:schema:endpoint', + $ref: 'urn:schema:ref' + } + } + + const schemaMap = { + [base.$id]: base, + [refSchema.$id]: refSchema + } + + const factory = StandaloneValidator({ + readMode: false, + storeFunction (routeOpts, schemaValidationCode) { + expectType(routeOpts) + expectType(schemaValidationCode) + } + }) + expectAssignable(factory) + + const compiler = factory(schemaMap) + expectAssignable(compiler) + expectAssignable(compiler(endpointSchema)) +} + +{ + const base = { + $id: 'urn:schema:base', + definitions: { + hello: { type: 'string' } + }, + type: 'object', + properties: { + hello: { $ref: '#/definitions/hello' } + } + } + + const refSchema = { + $id: 'urn:schema:ref', + type: 'object', + properties: { + hello: { $ref: 'urn:schema:base#/definitions/hello' } + } + } + + const endpointSchema = { + schema: { + $id: 'urn:schema:endpoint', + $ref: 'urn:schema:ref' + } + } + + const schemaMap = { + [base.$id]: base, + [refSchema.$id]: refSchema + } + const factory = StandaloneValidator({ + readMode: true, + restoreFunction (routeOpts) { + expectType(routeOpts) + return {} as ValidateFunction + } + }) + expectAssignable(factory) + + const compiler = factory(schemaMap) + expectAssignable(compiler) + expectType>(compiler(endpointSchema)) +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/.editorconfig b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/.editorconfig new file mode 100644 index 0000000000000000000000000000000000000000..db87e1fb3f74f240d34c36c112c06adae84792eb --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/.editorconfig @@ -0,0 +1,8 @@ +root = true + +[*] +indent_style = space +indent_size = 2 +charset = utf-8 +trim_trailing_whitespace = false +insert_final_newline = false \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/.gitattributes b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..cad1c32e3deb59f649a90fb55994a7c6a0685f64 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/.gitattributes @@ -0,0 +1,5 @@ +# Set the default behavior, in case people don't have core.autocrlf set +* text=auto + +# Require Unix line endings +* text eol=lf diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/.github/dependabot.yml b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..35d66ca7ac75f125b9c9c5b3dee0987fdfca4a45 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/.github/dependabot.yml @@ -0,0 +1,13 @@ +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "monthly" + open-pull-requests-limit: 10 + + - package-ecosystem: "npm" + directory: "/" + schedule: + interval: "monthly" + open-pull-requests-limit: 10 diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/.github/stale.yml b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/.github/stale.yml new file mode 100644 index 0000000000000000000000000000000000000000..d51ce639022226bc44471aa18bb218b50876cd52 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/.github/stale.yml @@ -0,0 +1,21 @@ +# Number of days of inactivity before an issue becomes stale +daysUntilStale: 15 +# Number of days of inactivity before a stale issue is closed +daysUntilClose: 7 +# Issues with these labels will never be considered stale +exemptLabels: + - "discussion" + - "feature request" + - "bug" + - "help wanted" + - "plugin suggestion" + - "good first issue" +# Label to use when marking an issue as stale +staleLabel: stale +# Comment to post when marking an issue as stale. Set to `false` to disable +markComment: > + This issue has been automatically marked as stale because it has not had + recent activity. It will be closed if no further activity occurs. Thank you + for your contributions. +# Comment to post when closing a stale issue. Set to `false` to disable +closeComment: false diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/.github/workflows/ci.yml b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/.github/workflows/ci.yml new file mode 100644 index 0000000000000000000000000000000000000000..fd45202abff682784e3a60d54fbfee567d304b26 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/.github/workflows/ci.yml @@ -0,0 +1,28 @@ +name: CI + +on: + push: + branches: + - main + - next + - 'v*' + paths-ignore: + - 'docs/**' + - '*.md' + pull_request: + paths-ignore: + - 'docs/**' + - '*.md' + +permissions: + contents: read + +jobs: + test: + permissions: + contents: write + pull-requests: write + uses: fastify/workflows/.github/workflows/plugins-ci.yml@v5 + with: + license-check: true + lint: true diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/LICENSE b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..cebd3e423c211bdeb61d51b83a3fe5692894a76a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/LICENSE @@ -0,0 +1,23 @@ +MIT License + +Copyright (c) 2018-present The Fastify team + +The Fastify team members are listed at https://github.com/fastify/fastify#team. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/README.md b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/README.md new file mode 100644 index 0000000000000000000000000000000000000000..271214c54e66e16ec9857d3b96631bba2c668920 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/README.md @@ -0,0 +1,198 @@ +# @fastify/cors + +[![CI](https://github.com/fastify/fastify-cors/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/fastify/fastify-cors/actions/workflows/ci.yml) +[![NPM version](https://img.shields.io/npm/v/@fastify/cors.svg?style=flat)](https://www.npmjs.com/package/@fastify/cors) +[![neostandard javascript style](https://img.shields.io/badge/code_style-neostandard-brightgreen?style=flat)](https://github.com/neostandard/neostandard) + +`@fastify/cors` enables the use of [CORS](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing) in a Fastify application. + +## Install +``` +npm i @fastify/cors +``` + +### Compatibility + +| Plugin version | Fastify version | +| ---------------|-----------------| +| `^11.x` | `^5.x` | +| `^10.x` | `^5.x` | +| `^8.x` | `^4.x` | +| `^7.x` | `^3.x` | +| `>=3.x <7.x` | `^2.x` | +| `>=1.x <3.x` | `^1.x` | + +Please note that if a Fastify version is out of support, then so are the corresponding versions of this plugin +in the table above. +See [Fastify's LTS policy](https://github.com/fastify/fastify/blob/main/docs/Reference/LTS.md) for more details. + +## Usage +Require `@fastify/cors` and register it as any other plugin. It adds an `onRequest` hook and a [wildcard options route](https://github.com/fastify/fastify/issues/326#issuecomment-411360862). +```js +import Fastify from 'fastify' +import cors from '@fastify/cors' + +const fastify = Fastify() +await fastify.register(cors, { + // put your options here +}) + +fastify.get('/', (req, reply) => { + reply.send({ hello: 'world' }) +}) + +await fastify.listen({ port: 3000 }) +``` +You can use it as is without passing any option or you can configure it as explained below. +### Options +* `origin`: Configures the **Access-Control-Allow-Origin** CORS header. The value of origin can be: + - `Boolean`: Set to `true` to reflect the [request origin](http://tools.ietf.org/html/draft-abarth-origin-09), or `false` to disable CORS. + - `String`: Set to a specific origin (e.g., `"http://example.com"`). The special `*` value (default) allows any origin. + - `RegExp`: Set to a regular expression pattern to test the request origin. If it matches, the request origin is reflected (e.g., `/example\.com$/` returns the origin only if it ends with `example.com`). + - `Array`: Set to an array of valid origins, each being a `String` or `RegExp` (e.g., `["http://example1.com", /\.example2\.com$/]`). + - `Function`: Set to a function with custom logic. The function takes the request origin as the first parameter and a callback as the second (signature `err [Error | null], origin`). *Async-await* and promises are supported. The Fastify instance is bound to the function call and can be accessed via `this`. For example: + ```js + origin: (origin, cb) => { + const hostname = new URL(origin).hostname + if(hostname === "localhost"){ + // Request from localhost will pass + cb(null, true) + return + } + // Generate an error on other origins, disabling access + cb(new Error("Not allowed"), false) + } + ``` +* `methods`: Configures the **Access-Control-Allow-Methods** CORS header. Expects a comma-delimited string (e.g., 'GET,HEAD,POST') or an array (e.g., `['GET', 'HEAD', 'POST']`). Default: [CORS-safelisted methods](https://fetch.spec.whatwg.org/#methods) `GET,HEAD,POST`. +* `hook`: See [Custom Fastify hook name](#custom-fastify-hook-name). Default: `onRequest`. +* `allowedHeaders`: Configures the **Access-Control-Allow-Headers** CORS header. Expects a comma-delimited string (e.g., `'Content-Type,Authorization'`) or an array (e.g., `['Content-Type', 'Authorization']`). Defaults to reflecting the headers specified in the request's **Access-Control-Request-Headers** header if not specified. +* `exposedHeaders`: Configures the **Access-Control-Expose-Headers** CORS header. Expects a comma-delimited string (e.g., `'Content-Range,X-Content-Range'`) or an array (e.g., `['Content-Range', 'X-Content-Range']`). No custom headers are exposed if not specified. +* `credentials`: Configures the **Access-Control-Allow-Credentials** CORS header. Set to `true` to pass the header; otherwise, it is omitted. +* `maxAge`: Configures the **Access-Control-Max-Age** CORS header in seconds. Set to an integer to pass the header; otherwise, it is omitted. +* `cacheControl`: Configures the **Cache-Control** header for CORS preflight responses. Set to an integer to pass the header as `Cache-Control: max-age=${cacheControl}`, or set to a string to pass the header as `Cache-Control: ${cacheControl}`. Otherwise, the header is omitted. +* `preflightContinue`: Passes the CORS preflight response to the route handler. Default: `false`. +* `optionsSuccessStatus`: Provides a status code for successful `OPTIONS` requests, as some legacy browsers (IE11, various SmartTVs) choke on `204`. +* `preflight`: Disables preflight by passing `false`. Default: `true`. +* `strictPreflight`: Enforces strict requirements for the CORS preflight request headers (**Access-Control-Request-Method** and **Origin**) as defined by the [W3C CORS specification](https://www.w3.org/TR/2020/SPSD-cors-20200602/#resource-preflight-requests). Preflight requests without the required headers result in 400 errors when set to `true`. Default: `true`. +* `hideOptionsRoute`: Hides the options route from documentation built using [@fastify/swagger](https://github.com/fastify/fastify-swagger). Default: `true`. +* `logLevel`: Sets the Fastify log level **only** for the internal CORS pre-flight `OPTIONS *` route. + Pass `'silent'` to suppress these requests in your logs, or any valid Fastify + log level (`'trace'`, `'debug'`, `'info'`, `'warn'`, `'error'`, `'fatal'`). + Default: inherits Fastify’s global log level. + +#### :warning: DoS attacks + +Using `RegExp` or a `function` for the `origin` parameter may enable Denial of Service attacks. +Craft with extreme care. + +### Configuring CORS Asynchronously + +```js +const fastify = require('fastify')() + +fastify.register(require('@fastify/cors'), (instance) => { + return (req, callback) => { + const corsOptions = { + // This is NOT recommended for production as it enables reflection exploits + origin: true + }; + + // do not include CORS headers for requests from localhost + if (/^localhost$/m.test(req.headers.origin)) { + corsOptions.origin = false + } + + // callback expects two parameters: error and options + callback(null, corsOptions) + } +}) + +fastify.register(async function (fastify) { + fastify.get('/', (req, reply) => { + reply.send({ hello: 'world' }) + }) +}) + +fastify.listen({ port: 3000 }) +``` + +### Disabling CORS for a specific route + +CORS can be disabled at the route level by setting the `cors` option to `false`. + +```js +const fastify = require('fastify')() + +fastify.register(require('@fastify/cors'), { origin: '*' }) + +fastify.get('/cors-enabled', (_req, reply) => { + reply.send('CORS headers') +}) + +fastify.get('/cors-disabled', { cors: false }, (_req, reply) => { + reply.send('No CORS headers') +}) + +fastify.listen({ port: 3000 }) +``` + +### Custom Fastify hook name + +By default, `@fastify/cors` adds an `onRequest` hook for validation and header injection. This can be customized by passing `hook` in the options. Valid values are `onRequest`, `preParsing`, `preValidation`, `preHandler`, `preSerialization`, and `onSend`. + +```js +import Fastify from 'fastify' +import cors from '@fastify/cors' + +const fastify = Fastify() +await fastify.register(cors, { + hook: 'preHandler', +}) + +fastify.get('/', (req, reply) => { + reply.send({ hello: 'world' }) +}) + +await fastify.listen({ port: 3000 }) +``` + +To configure CORS asynchronously, provide an object with the `delegator` key: + +```js +const fastify = require('fastify')() + +fastify.register(require('@fastify/cors'), { + hook: 'preHandler', + delegator: (req, callback) => { + const corsOptions = { + // This is NOT recommended for production as it enables reflection exploits + origin: true + }; + + // do not include CORS headers for requests from localhost + if (/^localhost$/m.test(req.headers.origin)) { + corsOptions.origin = false + } + + // callback expects two parameters: error and options + callback(null, corsOptions) + }, +}) + +fastify.register(async function (fastify) { + fastify.get('/', (req, reply) => { + reply.send({ hello: 'world' }) + }) +}) + +fastify.listen({ port: 3000 }) +``` + +## Acknowledgments + +The code is a port for Fastify of [`expressjs/cors`](https://github.com/expressjs/cors). + +## License + +Licensed under [MIT](./LICENSE).
+[`expressjs/cors` license](https://github.com/expressjs/cors/blob/master/LICENSE) \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/bench.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/bench.js new file mode 100644 index 0000000000000000000000000000000000000000..30dd09a26e956a65601ccc7465a8d396e02600d2 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/bench.js @@ -0,0 +1,17 @@ +'use strict' + +const fastify = require('fastify')() + +fastify.register((instance, _opts, next) => { + instance.register(require('./index')) + instance.get('/fastify', (_req, reply) => reply.send('ok')) + next() +}) + +fastify.register((instance, _opts, next) => { + instance.use(require('cors')()) + instance.get('/express', (_req, reply) => reply.send('ok')) + next() +}) + +fastify.listen({ port: 3000 }) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/benchmark/package.json b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/benchmark/package.json new file mode 100644 index 0000000000000000000000000000000000000000..15818d33bebbacf3a87f948d0af6227164af467e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/benchmark/package.json @@ -0,0 +1,15 @@ +{ + "name": "benchmark", + "version": "1.0.0", + "description": "", + "main": "vary.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "author": "", + "license": "ISC", + "dependencies": { + "benchmark": "^2.1.4", + "vary": "^1.1.2" + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/benchmark/vary.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/benchmark/vary.js new file mode 100644 index 0000000000000000000000000000000000000000..4aca63d803c065af6efd9464865bad42696eac1d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/benchmark/vary.js @@ -0,0 +1,34 @@ +'use strict' + +const benchmark = require('benchmark') +const vary = require('vary') +const createAddFieldnameToVary = require('../vary').createAddFieldnameToVary + +const replyMock = (header) => ({ + getHeader () { return header }, + setHeader () { }, + header () { } +}) + +const addAcceptToVary = createAddFieldnameToVary('Accept') +const addWildcardToVary = createAddFieldnameToVary('*') +const addAcceptEncodingToVary = createAddFieldnameToVary('Accept-Encoding') +const addXFooToVary = createAddFieldnameToVary('X-Foo') + +new benchmark.Suite() + .add('vary - field to undefined', function () { vary(replyMock(undefined), 'Accept-Encoding') }, { minSamples: 100 }) + .add('vary - field to *', function () { vary(replyMock('*'), 'Accept-Encoding') }, { minSamples: 100 }) + .add('vary - * to field', function () { vary(replyMock('Accept-Encoding'), '*') }, { minSamples: 100 }) + .add('vary - field to empty', function () { vary(replyMock(''), 'Accept-Encoding') }, { minSamples: 100 }) + .add('vary - fields string to empty', function () { vary(replyMock(''), 'Accept') }, { minSamples: 100 }) + .add('vary - field to fields', function () { vary(replyMock('Accept, Accept-Encoding, Accept-Language'), 'X-Foo') }, { minSamples: 100 }) + + .add('cors - field to undefined', function () { addAcceptEncodingToVary(replyMock(undefined)) }, { minSamples: 100 }) + .add('cors - field to *', function () { addAcceptEncodingToVary(replyMock('*')) }, { minSamples: 100 }) + .add('cors - * to field', function () { addWildcardToVary(replyMock('Accept-Encoding')) }, { minSamples: 100 }) + .add('cors - field to empty', function () { addAcceptEncodingToVary(replyMock('')) }, { minSamples: 100 }) + .add('cors - fields string to empty', function () { addAcceptToVary(replyMock('')) }, { minSamples: 100 }) + .add('cors - field to fields', function () { addXFooToVary(replyMock('Accept, Accept-Encoding, Accept-Language')) }, { minSamples: 100 }) + + .on('cycle', function onCycle (event) { console.log(String(event.target)) }) + .run({ async: false }) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/eslint.config.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/eslint.config.js new file mode 100644 index 0000000000000000000000000000000000000000..89fd678fe2a82d7fe3be869fffd71b3631c61c6a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/eslint.config.js @@ -0,0 +1,6 @@ +'use strict' + +module.exports = require('neostandard')({ + ignores: require('neostandard').resolveIgnoresFromGitignore(), + ts: true +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/index.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/index.js new file mode 100644 index 0000000000000000000000000000000000000000..ca946f99e95060ff11b3fe36da9bc9a75577434b --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/index.js @@ -0,0 +1,316 @@ +'use strict' + +const fp = require('fastify-plugin') +const { + addAccessControlRequestHeadersToVaryHeader, + addOriginToVaryHeader +} = require('./vary') + +const defaultOptions = { + origin: '*', + methods: 'GET,HEAD,POST', + hook: 'onRequest', + preflightContinue: false, + optionsSuccessStatus: 204, + credentials: false, + exposedHeaders: null, + allowedHeaders: null, + maxAge: null, + preflight: true, + strictPreflight: true +} + +const validHooks = [ + 'onRequest', + 'preParsing', + 'preValidation', + 'preHandler', + 'preSerialization', + 'onSend' +] + +const hookWithPayload = [ + 'preSerialization', + 'preParsing', + 'onSend' +] + +function validateHook (value, next) { + if (validHooks.indexOf(value) !== -1) { + return + } + next(new TypeError('@fastify/cors: Invalid hook option provided.')) +} + +function fastifyCors (fastify, opts, next) { + fastify.decorateRequest('corsPreflightEnabled', false) + + let hideOptionsRoute = true + let logLevel + + if (typeof opts === 'function') { + handleCorsOptionsDelegator(opts, fastify, { hook: defaultOptions.hook }, next) + } else if (opts.delegator) { + const { delegator, ...options } = opts + handleCorsOptionsDelegator(delegator, fastify, options, next) + } else { + const corsOptions = normalizeCorsOptions(opts) + validateHook(corsOptions.hook, next) + if (hookWithPayload.indexOf(corsOptions.hook) !== -1) { + fastify.addHook(corsOptions.hook, function handleCors (req, reply, _payload, next) { + addCorsHeadersHandler(fastify, corsOptions, req, reply, next) + }) + } else { + fastify.addHook(corsOptions.hook, function handleCors (req, reply, next) { + addCorsHeadersHandler(fastify, corsOptions, req, reply, next) + }) + } + } + if (opts.logLevel !== undefined) logLevel = opts.logLevel + if (opts.hideOptionsRoute !== undefined) hideOptionsRoute = opts.hideOptionsRoute + + // The preflight reply must occur in the hook. This allows fastify-cors to reply to + // preflight requests BEFORE possible authentication plugins. If the preflight reply + // occurred in this handler, other plugins may deny the request since the browser will + // remove most headers (such as the Authentication header). + // + // This route simply enables fastify to accept preflight requests. + + fastify.options('*', { schema: { hide: hideOptionsRoute }, logLevel }, (req, reply) => { + if (!req.corsPreflightEnabled) { + // Do not handle preflight requests if the origin option disabled CORS + reply.callNotFound() + return + } + + reply.send() + }) + + next() +} + +function handleCorsOptionsDelegator (optionsResolver, fastify, opts, next) { + const hook = opts?.hook || defaultOptions.hook + validateHook(hook, next) + if (optionsResolver.length === 2) { + if (hookWithPayload.indexOf(hook) !== -1) { + fastify.addHook(hook, function handleCors (req, reply, _payload, next) { + handleCorsOptionsCallbackDelegator(optionsResolver, fastify, req, reply, next) + }) + } else { + fastify.addHook(hook, function handleCors (req, reply, next) { + handleCorsOptionsCallbackDelegator(optionsResolver, fastify, req, reply, next) + }) + } + } else { + if (hookWithPayload.indexOf(hook) !== -1) { + // handle delegator based on Promise + fastify.addHook(hook, function handleCors (req, reply, _payload, next) { + const ret = optionsResolver(req) + if (ret && typeof ret.then === 'function') { + ret.then(options => addCorsHeadersHandler(fastify, normalizeCorsOptions(options, true), req, reply, next)).catch(next) + return + } + next(new Error('Invalid CORS origin option')) + }) + } else { + // handle delegator based on Promise + fastify.addHook(hook, function handleCors (req, reply, next) { + const ret = optionsResolver(req) + if (ret && typeof ret.then === 'function') { + ret.then(options => addCorsHeadersHandler(fastify, normalizeCorsOptions(options, true), req, reply, next)).catch(next) + return + } + next(new Error('Invalid CORS origin option')) + }) + } + } +} + +function handleCorsOptionsCallbackDelegator (optionsResolver, fastify, req, reply, next) { + optionsResolver(req, (err, options) => { + if (err) { + next(err) + } else { + addCorsHeadersHandler(fastify, normalizeCorsOptions(options, true), req, reply, next) + } + }) +} + +/** + * @param {import('./types').FastifyCorsOptions} opts + */ +function normalizeCorsOptions (opts, dynamic) { + const corsOptions = { ...defaultOptions, ...opts } + if (Array.isArray(opts.origin) && opts.origin.indexOf('*') !== -1) { + corsOptions.origin = '*' + } + if (Number.isInteger(corsOptions.cacheControl)) { + // integer numbers are formatted this way + corsOptions.cacheControl = `max-age=${corsOptions.cacheControl}` + } else if (typeof corsOptions.cacheControl !== 'string') { + // strings are applied directly and any other value is ignored + corsOptions.cacheControl = null + } + corsOptions.dynamic = dynamic || false + return corsOptions +} + +function addCorsHeadersHandler (fastify, options, req, reply, next) { + if ((typeof options.origin !== 'string' && options.origin !== false) || options.dynamic) { + // Always set Vary header for non-static origin option + // https://fetch.spec.whatwg.org/#cors-protocol-and-http-caches + addOriginToVaryHeader(reply) + } + + const resolveOriginOption = typeof options.origin === 'function' ? resolveOriginWrapper(fastify, options.origin) : (_, cb) => cb(null, options.origin) + + resolveOriginOption(req, (error, resolvedOriginOption) => { + if (error !== null) { + return next(error) + } + + // Disable CORS and preflight if false + if (resolvedOriginOption === false) { + return next() + } + + // Allow routes to disable CORS individually + if (req.routeOptions.config?.cors === false) { + return next() + } + + // Falsy values are invalid + if (!resolvedOriginOption) { + return next(new Error('Invalid CORS origin option')) + } + + addCorsHeaders(req, reply, resolvedOriginOption, options) + + if (req.raw.method === 'OPTIONS' && options.preflight === true) { + // Strict mode enforces the required headers for preflight + if (options.strictPreflight === true && (!req.headers.origin || !req.headers['access-control-request-method'])) { + reply.status(400).type('text/plain').send('Invalid Preflight Request') + return + } + + req.corsPreflightEnabled = true + + addPreflightHeaders(req, reply, options) + + if (!options.preflightContinue) { + // Do not call the hook callback and terminate the request + // Safari (and potentially other browsers) need content-length 0, + // for 204 or they just hang waiting for a body + reply + .code(options.optionsSuccessStatus) + .header('Content-Length', '0') + .send() + return + } + } + + return next() + }) +} + +function addCorsHeaders (req, reply, originOption, corsOptions) { + const origin = getAccessControlAllowOriginHeader(req.headers.origin, originOption) + // In the case of origin not allowed the header is not + // written in the response. + // https://github.com/fastify/fastify-cors/issues/127 + if (origin) { + reply.header('Access-Control-Allow-Origin', origin) + } + + if (corsOptions.credentials) { + reply.header('Access-Control-Allow-Credentials', 'true') + } + + if (corsOptions.exposedHeaders !== null) { + reply.header( + 'Access-Control-Expose-Headers', + Array.isArray(corsOptions.exposedHeaders) ? corsOptions.exposedHeaders.join(', ') : corsOptions.exposedHeaders + ) + } +} + +function addPreflightHeaders (req, reply, corsOptions) { + reply.header( + 'Access-Control-Allow-Methods', + Array.isArray(corsOptions.methods) ? corsOptions.methods.join(', ') : corsOptions.methods + ) + + if (corsOptions.allowedHeaders === null) { + addAccessControlRequestHeadersToVaryHeader(reply) + const reqAllowedHeaders = req.headers['access-control-request-headers'] + if (reqAllowedHeaders !== undefined) { + reply.header('Access-Control-Allow-Headers', reqAllowedHeaders) + } + } else { + reply.header( + 'Access-Control-Allow-Headers', + Array.isArray(corsOptions.allowedHeaders) ? corsOptions.allowedHeaders.join(', ') : corsOptions.allowedHeaders + ) + } + + if (corsOptions.maxAge !== null) { + reply.header('Access-Control-Max-Age', String(corsOptions.maxAge)) + } + + if (corsOptions.cacheControl) { + reply.header('Cache-Control', corsOptions.cacheControl) + } +} + +function resolveOriginWrapper (fastify, origin) { + return function (req, cb) { + const result = origin.call(fastify, req.headers.origin, cb) + + // Allow for promises + if (result && typeof result.then === 'function') { + result.then(res => cb(null, res), cb) + } + } +} + +function getAccessControlAllowOriginHeader (reqOrigin, originOption) { + if (typeof originOption === 'string') { + // fixed or any origin ('*') + return originOption + } + + // reflect origin + return isRequestOriginAllowed(reqOrigin, originOption) ? reqOrigin : false +} + +function isRequestOriginAllowed (reqOrigin, allowedOrigin) { + if (Array.isArray(allowedOrigin)) { + for (let i = 0; i < allowedOrigin.length; ++i) { + if (isRequestOriginAllowed(reqOrigin, allowedOrigin[i])) { + return true + } + } + return false + } else if (typeof allowedOrigin === 'string') { + return reqOrigin === allowedOrigin + } else if (allowedOrigin instanceof RegExp) { + allowedOrigin.lastIndex = 0 + return allowedOrigin.test(reqOrigin) + } else { + return !!allowedOrigin + } +} + +const _fastifyCors = fp(fastifyCors, { + fastify: '5.x', + name: '@fastify/cors' +}) + +/** + * These export configurations enable JS and TS developers + * to consumer fastify in whatever way best suits their needs. + */ +module.exports = _fastifyCors +module.exports.fastifyCors = _fastifyCors +module.exports.default = _fastifyCors diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/package.json b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/package.json new file mode 100644 index 0000000000000000000000000000000000000000..08be4c7c6f67d5a8a05fbe418c103f9afb330071 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/package.json @@ -0,0 +1,86 @@ +{ + "name": "@fastify/cors", + "version": "11.1.0", + "description": "Fastify CORS", + "main": "index.js", + "type": "commonjs", + "types": "types/index.d.ts", + "scripts": { + "lint": "eslint", + "lint:fix": "eslint --fix", + "test": "npm run test:unit && npm run test:typescript", + "test:typescript": "tsd", + "test:unit": "c8 --100 node --test" + }, + "keywords": [ + "fastify", + "cors", + "headers", + "access", + "control" + ], + "author": "Tomas Della Vedova - @delvedor (http://delved.org)", + "contributors": [ + { + "name": "Matteo Collina", + "email": "hello@matteocollina.com" + }, + { + "name": "Manuel Spigolon", + "email": "behemoth89@gmail.com" + }, + { + "name": "Cemre Mengu", + "email": "cemremengu@gmail.com" + }, + { + "name": "Frazer Smith", + "email": "frazer.dev@icloud.com", + "url": "https://github.com/fdawgs" + } + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/fastify/fastify-cors.git" + }, + "bugs": { + "url": "https://github.com/fastify/fastify-cors/issues" + }, + "homepage": "https://github.com/fastify/fastify-cors#readme", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "devDependencies": { + "@fastify/pre-commit": "^2.1.0", + "@types/node": "^24.0.8", + "c8": "^10.1.2", + "cors": "^2.8.5", + "eslint": "^9.17.0", + "fastify": "^5.0.0", + "neostandard": "^0.12.0", + "tsd": "^0.32.0", + "typescript": "~5.8.2" + }, + "dependencies": { + "fastify-plugin": "^5.0.0", + "toad-cache": "^3.7.0" + }, + "tsd": { + "directory": "test" + }, + "publishConfig": { + "access": "public" + }, + "pre-commit": [ + "lint", + "test" + ] +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/test/cors.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/test/cors.test.js new file mode 100644 index 0000000000000000000000000000000000000000..d64c48acfc672acd147640e931c41a3fee7219bb --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/test/cors.test.js @@ -0,0 +1,1052 @@ +'use strict' + +const { test } = require('node:test') +const { createReadStream, statSync, readFileSync } = require('node:fs') +const Fastify = require('fastify') +const cors = require('../') +const { resolve } = require('node:path') +const { setTimeout: sleep } = require('node:timers/promises') + +test('Should add cors headers', async t => { + t.plan(4) + + const fastify = Fastify() + fastify.register(cors) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + const res = await fastify.inject({ + method: 'GET', + url: '/' + }) + + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + t.assert.deepStrictEqual(res.headers['access-control-allow-origin'], + '*' + ) +}) + +test('Should add cors headers when payload is a stream', async t => { + t.plan(4) + + const fastify = Fastify() + fastify.register(cors) + const filePath = resolve(__dirname, __filename) + + fastify.get('/', (_req, reply) => { + const stream = createReadStream(filePath) + reply + .type('application/json') + .header('Content-Length', statSync(filePath).size) + .send(stream) + }) + + const fileContent = readFileSync(filePath, 'utf-8') + + const res = await fastify.inject({ + method: 'GET', + url: '/' + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, fileContent) + const actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'content-length': res.headers['content-length'] + + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': '*', + 'content-length': statSync(filePath).size.toString() + }) +}) + +test('Should add cors headers (custom values)', async t => { + t.plan(10) + + const fastify = Fastify() + fastify.register(cors, { + origin: 'example.com', + methods: 'GET', + credentials: true, + exposedHeaders: ['foo', 'bar'], + allowedHeaders: ['baz', 'woo'], + maxAge: 123, + cacheControl: 321 + }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + let res = await fastify.inject({ + method: 'OPTIONS', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 204) + t.assert.strictEqual(res.payload, '') + const actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-credentials': res.headers['access-control-allow-credentials'], + 'access-control-expose-headers': res.headers['access-control-expose-headers'], + 'access-control-allow-methods': res.headers['access-control-allow-methods'], + 'access-control-allow-headers': res.headers['access-control-allow-headers'], + 'access-control-max-age': res.headers['access-control-max-age'], + 'cache-control': res.headers['cache-control'], + 'content-length': res.headers['content-length'] + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': 'example.com', + 'access-control-allow-credentials': 'true', + 'access-control-expose-headers': 'foo, bar', + 'access-control-allow-methods': 'GET', + 'access-control-allow-headers': 'baz, woo', + 'access-control-max-age': '123', + 'cache-control': 'max-age=321', + 'content-length': '0' + }) + t.assert.notDeepEqual(res.headers, { vary: 'Origin' }) + + res = await fastify.inject({ + method: 'GET', + url: '/' + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + const actualHeaders2 = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-credentials': res.headers['access-control-allow-credentials'], + 'access-control-expose-headers': res.headers['access-control-expose-headers'], + 'content-length': res.headers['content-length'] + } + t.assert.deepStrictEqual(actualHeaders2, { + 'access-control-allow-origin': 'example.com', + 'access-control-allow-credentials': 'true', + 'access-control-expose-headers': 'foo, bar', + 'content-length': '2' + }) + t.assert.notDeepEqual(res.headers, { vary: 'Origin' }) +}) + +test('Should support dynamic config (callback)', async t => { + t.plan(16) + + const configs = [{ + origin: 'example.com', + methods: 'GET', + credentials: true, + exposedHeaders: ['foo', 'bar'], + allowedHeaders: ['baz', 'woo'], + maxAge: 123, + cacheControl: 456 + }, { + origin: 'sample.com', + methods: 'GET', + credentials: true, + exposedHeaders: ['zoo', 'bar'], + allowedHeaders: ['baz', 'foo'], + maxAge: 321, + cacheControl: '456' + }] + + const fastify = Fastify() + let requestId = 0 + const configDelegation = async function (req, cb) { + // request should have id + t.assert.ok(req.id) + // request should not have send + t.assert.ifError(req.send) + + const config = configs[requestId] + requestId++ + if (config) { + cb(null, config) + } else { + cb(new Error('ouch')) + } + } + await fastify.register(cors, () => configDelegation) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + let res = await fastify.inject({ + method: 'GET', + url: '/' + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + const actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-credentials': res.headers['access-control-allow-credentials'], + 'access-control-expose-headers': res.headers['access-control-expose-headers'], + 'content-length': res.headers['content-length'], + vary: res.headers.vary + } + // Sleep to wait for callback + sleep() + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': 'example.com', + 'access-control-allow-credentials': 'true', + 'access-control-expose-headers': 'foo, bar', + 'content-length': '2', + vary: 'Origin' + }) + + res = await fastify.inject({ + method: 'OPTIONS', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 204) + t.assert.strictEqual(res.payload, '') + const actualHeaders2 = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-credentials': res.headers['access-control-allow-credentials'], + 'access-control-expose-headers': res.headers['access-control-expose-headers'], + 'access-control-allow-methods': res.headers['access-control-allow-methods'], + 'access-control-allow-headers': res.headers['access-control-allow-headers'], + 'access-control-max-age': res.headers['access-control-max-age'], + 'cache-control': res.headers['cache-control'], + 'content-length': res.headers['content-length'], + vary: res.headers.vary + } + // Sleep to wait for callback + sleep() + t.assert.deepStrictEqual(actualHeaders2, { + 'access-control-allow-origin': 'sample.com', + 'access-control-allow-credentials': 'true', + 'access-control-expose-headers': 'zoo, bar', + 'access-control-allow-methods': 'GET', + 'access-control-allow-headers': 'baz, foo', + 'access-control-max-age': '321', + 'cache-control': '456', + 'content-length': '0', + vary: 'Origin' + }) + + res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + t.assert.strictEqual(res.statusCode, 500) +}) + +test('Should support dynamic config (Promise)', async t => { + t.plan(23) + + const configs = [{ + origin: 'example.com', + methods: 'GET', + credentials: true, + exposedHeaders: ['foo', 'bar'], + allowedHeaders: ['baz', 'woo'], + maxAge: 123, + cacheControl: 456 + }, { + origin: 'sample.com', + methods: 'GET', + credentials: true, + exposedHeaders: ['zoo', 'bar'], + allowedHeaders: ['baz', 'foo'], + maxAge: 321, + cacheControl: true // Invalid value should be ignored + }, { + origin: 'sample.com', + methods: 'GET', + credentials: true, + exposedHeaders: ['zoo', 'bar'], + allowedHeaders: ['baz', 'foo'], + maxAge: 321, + cacheControl: 'public, max-age=456' + }] + + const fastify = Fastify() + let requestId = 0 + const configDelegation = async function (req) { + // request should have id + t.assert.ok(req.id) + // request should not have send + t.assert.ifError(req.send) + const config = configs[requestId] + requestId++ + if (config) { + return Promise.resolve(config) + } else { + return Promise.reject(new Error('ouch')) + } + } + await fastify.register(cors, () => configDelegation) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + let res = await fastify.inject({ + method: 'GET', + url: '/' + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + const actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-credentials': res.headers['access-control-allow-credentials'], + 'access-control-expose-headers': res.headers['access-control-expose-headers'], + 'content-length': res.headers['content-length'], + vary: res.headers.vary + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': 'example.com', + 'access-control-allow-credentials': 'true', + 'access-control-expose-headers': 'foo, bar', + 'content-length': '2', + vary: 'Origin' + }) + + res = await fastify.inject({ + method: 'OPTIONS', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'sample.com' + } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 204) + t.assert.strictEqual(res.payload, '') + const acutalHeaders2 = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-credentials': res.headers['access-control-allow-credentials'], + 'access-control-expose-headers': res.headers['access-control-expose-headers'], + 'access-control-allow-methods': res.headers['access-control-allow-methods'], + 'access-control-allow-headers': res.headers['access-control-allow-headers'], + 'access-control-max-age': res.headers['access-control-max-age'], + 'content-length': res.headers['content-length'], + vary: res.headers.vary + } + t.assert.deepStrictEqual(acutalHeaders2, { + 'access-control-allow-origin': 'sample.com', + 'access-control-allow-credentials': 'true', + 'access-control-expose-headers': 'zoo, bar', + 'access-control-allow-methods': 'GET', + 'access-control-allow-headers': 'baz, foo', + 'access-control-max-age': '321', + 'content-length': '0', + vary: 'Origin' + }) + t.assert.strictEqual(res.headers['cache-control'], undefined, 'cache-control omitted (invalid value)') + + res = await fastify.inject({ + method: 'OPTIONS', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 204) + t.assert.strictEqual(res.payload, '') + const actualHeaders3 = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-credentials': res.headers['access-control-allow-credentials'], + 'access-control-expose-headers': res.headers['access-control-expose-headers'], + 'access-control-allow-methods': res.headers['access-control-allow-methods'], + 'access-control-allow-headers': res.headers['access-control-allow-headers'], + 'access-control-max-age': res.headers['access-control-max-age'], + 'cache-control': res.headers['cache-control'], + 'content-length': res.headers['content-length'], + vary: res.headers.vary + } + t.assert.deepStrictEqual(actualHeaders3, { + 'access-control-allow-origin': 'sample.com', + 'access-control-allow-credentials': 'true', + 'access-control-expose-headers': 'zoo, bar', + 'access-control-allow-methods': 'GET', + 'access-control-allow-headers': 'baz, foo', + 'access-control-max-age': '321', + 'cache-control': 'public, max-age=456', // cache-control included (custom string) + 'content-length': '0', + vary: 'Origin' + }) + + res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + t.assert.strictEqual(res.statusCode, 500) +}) + +test('Should support dynamic config. (Invalid function)', async t => { + t.plan(2) + + const fastify = Fastify() + fastify.register(cors, () => () => {}) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + const res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + t.assert.strictEqual(res.statusCode, 500) +}) + +test('Dynamic origin resolution (valid origin)', async t => { + t.plan(6) + + const fastify = Fastify() + const origin = function (header, cb) { + t.assert.strictEqual(header, 'example.com') + t.assert.equal(this, fastify) + cb(null, true) + } + fastify.register(cors, { origin }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + const res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { origin: 'example.com' } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + const actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + vary: res.headers.vary + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': 'example.com', + vary: 'Origin' + }) +}) + +test('Dynamic origin resolution (not valid origin)', async t => { + t.plan(5) + + const fastify = Fastify() + const origin = (header, cb) => { + t.assert.strictEqual(header, 'example.com') + cb(null, false) + } + fastify.register(cors, { origin }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + const res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { origin: 'example.com' } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + const actualHeaders = { + 'content-length': res.headers['content-length'], + 'content-type': res.headers['content-type'], + connection: res.headers.connection, + vary: res.headers.vary + } + t.assert.deepStrictEqual(actualHeaders, { + 'content-length': '2', + 'content-type': 'text/plain; charset=utf-8', + connection: 'keep-alive', + vary: 'Origin' + }) +}) + +test('Dynamic origin resolution (errored)', async t => { + t.plan(3) + + const fastify = Fastify() + const origin = (header, cb) => { + t.assert.strictEqual(header, 'example.com') + cb(new Error('ouch')) + } + fastify.register(cors, { origin }) + + const res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { origin: 'example.com' } + }) + t.assert.ok(res) + t.assert.strictEqual(res.statusCode, 500) +}) + +test('Dynamic origin resolution (invalid result)', async t => { + t.plan(3) + + const fastify = Fastify() + const origin = (header, cb) => { + t.assert.strictEqual(header, 'example.com') + cb(null, undefined) + } + fastify.register(cors, { origin }) + + const res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { origin: 'example.com' } + }) + t.assert.ok(res) + t.assert.strictEqual(res.statusCode, 500) +}) + +test('Dynamic origin resolution (valid origin - promises)', async t => { + t.plan(5) + + const fastify = Fastify() + const origin = (header) => { + return new Promise((resolve) => { + t.assert.strictEqual(header, 'example.com') + resolve(true) + }) + } + fastify.register(cors, { origin }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + const res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { origin: 'example.com' } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + const actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + vary: res.headers.vary + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': 'example.com', + vary: 'Origin' + }) +}) + +test('Dynamic origin resolution (not valid origin - promises)', async t => { + t.plan(5) + + const fastify = Fastify() + const origin = (header) => { + return new Promise((resolve) => { + t.assert.strictEqual(header, 'example.com') + resolve(false) + }) + } + fastify.register(cors, { origin }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + const res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { origin: 'example.com' } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + const actualHeaders = { + 'content-length': res.headers['content-length'], + 'content-type': res.headers['content-type'], + connection: res.headers.connection, + vary: res.headers.vary + } + t.assert.deepStrictEqual(actualHeaders, { + 'content-length': '2', + 'content-type': 'text/plain; charset=utf-8', + connection: 'keep-alive', + vary: 'Origin' + }) +}) + +test('Dynamic origin resolution (errored - promises)', async t => { + t.plan(3) + + const fastify = Fastify() + const origin = (header) => { + return new Promise((_resolve, reject) => { + t.assert.strictEqual(header, 'example.com') + reject(new Error('ouch')) + }) + } + fastify.register(cors, { origin }) + + const res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { origin: 'example.com' } + }) + t.assert.ok(res) + t.assert.strictEqual(res.statusCode, 500) +}) + +test('Should reply 404 without cors headers when origin is false', async t => { + t.plan(8) + + const fastify = Fastify() + fastify.register(cors, { + origin: false, + methods: 'GET', + credentials: true, + exposedHeaders: ['foo', 'bar'], + allowedHeaders: ['baz', 'woo'], + maxAge: 123 + }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + let res = await fastify.inject({ + method: 'OPTIONS', + url: '/' + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 404) + t.assert.strictEqual(res.payload, '{"message":"Route OPTIONS:/ not found","error":"Not Found","statusCode":404}') + const actualHeaders = { + 'content-length': res.headers['content-length'], + 'content-type': res.headers['content-type'], + connection: res.headers.connection + } + t.assert.deepStrictEqual(actualHeaders, { + 'content-length': '76', + 'content-type': 'application/json; charset=utf-8', + connection: 'keep-alive' + }) + + res = await fastify.inject({ + method: 'GET', + url: '/' + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + t.assert.deepStrictEqual(res.headers, { + 'content-length': '2', + 'content-type': 'text/plain; charset=utf-8', + connection: 'keep-alive' + }) +}) + +test('Server error if origin option is falsy but not false', async t => { + t.plan(4) + + const fastify = Fastify() + fastify.register(cors, { origin: '' }) + + const res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { origin: 'example.com' } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 500) + t.assert.deepStrictEqual(res.json(), { statusCode: 500, error: 'Internal Server Error', message: 'Invalid CORS origin option' }) + const actualHeaders = { + 'content-length': res.headers['content-length'], + 'content-type': res.headers['content-type'], + connection: res.headers.connection + } + t.assert.deepStrictEqual(actualHeaders, { + 'content-length': '89', + 'content-type': 'application/json; charset=utf-8', + connection: 'keep-alive' + }) +}) + +test('Allow only request from a specific origin', async t => { + t.plan(5) + + const fastify = Fastify() + fastify.register(cors, { origin: 'other.io' }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + const res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { origin: 'example.com' } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + t.assert.deepStrictEqual(res.headers['access-control-allow-origin'], + 'other.io' + ) + t.assert.notDeepEqual(res.headers, { vary: 'Origin' }) +}) + +test('Allow only request from multiple specific origin', async t => { + t.plan(9) + + const fastify = Fastify() + fastify.register(cors, { origin: ['other.io', 'example.com'] }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + let res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { origin: 'other.io' } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + const actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + vary: res.headers.vary + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': 'other.io', + vary: 'Origin' + }) + + res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { origin: 'foo.com' } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + t.assert.deepStrictEqual(res.headers.vary, + 'Origin' + ) + t.assert.strictEqual(res.headers['access-control-allow-origin'], undefined) +}) + +test('Allow only request from a specific origin using regex', async t => { + t.plan(8) + + const fastify = Fastify() + fastify.register(cors, { origin: /(?:example|other)\.com\/?$/giu }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + // .test was previously used, which caused 2 consecutive requests to return + // different results with global (e.g. /g) regexes. Therefore, check this + // twice to check consistency + for (let i = 0; i < 2; i++) { + const res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { origin: 'https://www.example.com/' } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + const actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + vary: res.headers.vary + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': 'https://www.example.com/', + vary: 'Origin' + }) + } +}) + +test('Disable preflight', async t => { + t.plan(7) + + const fastify = Fastify() + fastify.register(cors, { preflight: false }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + let res = await fastify.inject({ + method: 'OPTIONS', + url: '/hello' + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 404) + t.assert.strictEqual(res.headers['access-control-allow-origin'], + '*' + ) + + res = await fastify.inject({ + method: 'GET', + url: '/' + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + t.assert.strictEqual(res.headers['access-control-allow-origin'], + '*' + ) +}) + +test('Should always add vary header to `Origin` for reflected origin', async t => { + t.plan(12) + + const fastify = Fastify() + fastify.register(cors, { origin: true }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + // Invalid Preflight + let res = await fastify.inject({ + method: 'OPTIONS', + url: '/' + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 400) + t.assert.strictEqual(res.payload, 'Invalid Preflight Request') + t.assert.strictEqual(res.headers.vary, + 'Origin' + ) + + // Valid Preflight + res = await fastify.inject({ + method: 'OPTIONS', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 204) + t.assert.strictEqual(res.payload, '') + t.assert.strictEqual(res.headers.vary, + 'Origin, Access-Control-Request-Headers' + ) + + // Other Route + res = await fastify.inject({ + method: 'GET', + url: '/' + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + t.assert.strictEqual(res.headers.vary, + 'Origin' + ) +}) + +test('Should always add vary header to `Origin` for reflected origin (vary is array)', async t => { + t.plan(4) + + const fastify = Fastify() + + // Mock getHeader function + fastify.decorateReply('getHeader', () => ['foo', 'bar']) + + fastify.register(cors, { origin: true }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + const res = await fastify.inject({ + method: 'GET', + url: '/' + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + t.assert.strictEqual(res.headers.vary, + 'foo, bar, Origin' + ) +}) + +test('Allow only request from with specific headers', async t => { + t.plan(8) + + const fastify = Fastify() + fastify.register(cors, { + allowedHeaders: 'foo', + exposedHeaders: 'bar' + }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + let res = await fastify.inject({ + method: 'OPTIONS', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 204) + t.assert.deepStrictEqual(res.headers['access-control-allow-headers'], + 'foo' + ) + t.assert.notDeepEqual(res.headers.vary, 'Origin') + + res = await fastify.inject({ + method: 'GET', + url: '/' + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + t.assert.strictEqual(res.headers['access-control-expose-headers'], + 'bar' + ) +}) + +test('Should support wildcard config /1', async t => { + t.plan(4) + + const fastify = Fastify() + fastify.register(cors, { origin: '*' }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + const res = await fastify.inject({ + method: 'GET', + url: '/' + }) + t.assert.ok(res) + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + t.assert.strictEqual(res.headers['access-control-allow-origin'], '*') +}) + +test('Should support wildcard config /2', async t => { + t.plan(4) + + const fastify = Fastify() + fastify.register(cors, { origin: ['*'] }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + const res = await fastify.inject({ + method: 'GET', + url: '/' + }) + t.assert.ok(res) + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + t.assert.strictEqual(res.headers['access-control-allow-origin'], '*') +}) + +test('Should allow routes to disable CORS individually', async t => { + t.plan(6) + + const fastify = Fastify() + fastify.register(cors, { origin: '*' }) + + fastify.get('/cors-enabled', (_req, reply) => { + reply.send('ok') + }) + + fastify.get('/cors-disabled', { config: { cors: false } }, (_req, reply) => { + reply.send('ok') + }) + + // Test CORS enabled route + let res = await fastify.inject({ + method: 'GET', + url: '/cors-enabled', + headers: { origin: 'example.com' } + }) + t.assert.ok(res) + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.headers['access-control-allow-origin'], '*') + + // Test CORS disabled route + res = await fastify.inject({ + method: 'GET', + url: '/cors-disabled', + headers: { origin: 'example.com' } + }) + t.assert.ok(res) + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.headers['access-control-allow-origin'], undefined) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/test/hooks.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/test/hooks.test.js new file mode 100644 index 0000000000000000000000000000000000000000..74ccf22592b1759ce552ded6861abe1366e8619e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/test/hooks.test.js @@ -0,0 +1,787 @@ +'use strict' + +const { test } = require('node:test') +const Fastify = require('fastify') +const kFastifyContext = require('fastify/lib/symbols').kRouteContext +const cors = require('..') +const { setTimeout: sleep } = require('node:timers/promises') + +test('Should error on invalid hook option', async (t) => { + t.plan(3) + + const fastify = Fastify() + await t.assert.rejects( + async () => fastify.register(cors, { hook: 'invalid' }), + (err) => { + t.assert.strictEqual(err.name, 'TypeError') + t.assert.strictEqual(err.message, '@fastify/cors: Invalid hook option provided.') + return true + } + ) +}) + +test('Should set hook onRequest if hook option is not set', async (t) => { + t.plan(10) + + const fastify = Fastify() + + fastify.register(cors) + + fastify.addHook('onResponse', (request, _reply, done) => { + t.assert.strictEqual(request[kFastifyContext].onError, null) + t.assert.strictEqual(request[kFastifyContext].onRequest.length, 1) + t.assert.strictEqual(request[kFastifyContext].onSend, null) + t.assert.strictEqual(request[kFastifyContext].preHandler, null) + t.assert.strictEqual(request[kFastifyContext].preParsing, null) + t.assert.strictEqual(request[kFastifyContext].preSerialization, null) + t.assert.strictEqual(request[kFastifyContext].preValidation, null) + done() + }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + await fastify.ready() + + const res = await fastify.inject({ + method: 'GET', + url: '/' + }) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + const actualHeader = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'] + } + t.assert.deepStrictEqual(actualHeader, { + 'access-control-allow-origin': '*' + }) +}) + +test('Should set hook onRequest if hook option is set to onRequest', async (t) => { + t.plan(10) + + const fastify = Fastify() + + fastify.register(cors, { + hook: 'onRequest' + }) + + fastify.addHook('onResponse', (request, _reply, done) => { + t.assert.strictEqual(request[kFastifyContext].onError, null) + t.assert.strictEqual(request[kFastifyContext].onRequest.length, 1) + t.assert.strictEqual(request[kFastifyContext].onSend, null) + t.assert.strictEqual(request[kFastifyContext].preHandler, null) + t.assert.strictEqual(request[kFastifyContext].preParsing, null) + t.assert.strictEqual(request[kFastifyContext].preSerialization, null) + t.assert.strictEqual(request[kFastifyContext].preValidation, null) + done() + }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + await fastify.ready() + + const res = await fastify.inject({ + method: 'GET', + url: '/' + }) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + const actualHeader = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'] + } + t.assert.deepStrictEqual(actualHeader, { + 'access-control-allow-origin': '*' + }) +}) + +test('Should set hook preParsing if hook option is set to preParsing', async (t) => { + t.plan(11) + + const fastify = Fastify() + + fastify.register(cors, { + hook: 'preParsing' + }) + + fastify.addHook('onResponse', (request, _reply, done) => { + t.assert.strictEqual(request[kFastifyContext].onError, null) + t.assert.strictEqual(request[kFastifyContext].onRequest, null) + t.assert.strictEqual(request[kFastifyContext].onSend, null) + t.assert.strictEqual(request[kFastifyContext].preHandler, null) + t.assert.strictEqual(request[kFastifyContext].preParsing.length, 1) + t.assert.strictEqual(request[kFastifyContext].preSerialization, null) + t.assert.strictEqual(request[kFastifyContext].preValidation, null) + done() + }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + await fastify.ready() + + const res = await fastify.inject({ + method: 'GET', + url: '/' + }) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + const actualHeader = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'] + } + t.assert.deepStrictEqual(actualHeader, { + 'access-control-allow-origin': '*' + }) + t.assert.notStrictEqual(res.headers.vary, 'Origin') +}) + +test('Should set hook preValidation if hook option is set to preValidation', async (t) => { + t.plan(11) + + const fastify = Fastify() + + fastify.register(cors, { + hook: 'preValidation' + }) + + fastify.addHook('onResponse', (request, _reply, done) => { + t.assert.strictEqual(request[kFastifyContext].onError, null) + t.assert.strictEqual(request[kFastifyContext].onRequest, null) + t.assert.strictEqual(request[kFastifyContext].onSend, null) + t.assert.strictEqual(request[kFastifyContext].preHandler, null) + t.assert.strictEqual(request[kFastifyContext].preParsing, null) + t.assert.strictEqual(request[kFastifyContext].preSerialization, null) + t.assert.strictEqual(request[kFastifyContext].preValidation.length, 1) + done() + }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + await fastify.ready() + + const res = await fastify.inject({ + method: 'GET', + url: '/' + }) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + const actualHeader = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'] + } + t.assert.deepStrictEqual(actualHeader, { + 'access-control-allow-origin': '*' + }) + t.assert.notStrictEqual(res.headers.vary, 'Origin') +}) + +test('Should set hook preParsing if hook option is set to preParsing', async (t) => { + t.plan(11) + + const fastify = Fastify() + + fastify.register(cors, { + hook: 'preParsing' + }) + + fastify.addHook('onResponse', (request, _reply, done) => { + t.assert.strictEqual(request[kFastifyContext].onError, null) + t.assert.strictEqual(request[kFastifyContext].onRequest, null) + t.assert.strictEqual(request[kFastifyContext].onSend, null) + t.assert.strictEqual(request[kFastifyContext].preHandler, null) + t.assert.strictEqual(request[kFastifyContext].preParsing.length, 1) + t.assert.strictEqual(request[kFastifyContext].preSerialization, null) + t.assert.strictEqual(request[kFastifyContext].preValidation, null) + done() + }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + await fastify.ready() + + const res = await fastify.inject({ + method: 'GET', + url: '/' + }) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + const actualHeader = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'] + } + t.assert.deepStrictEqual(actualHeader, { + 'access-control-allow-origin': '*' + }) + t.assert.notStrictEqual(res.headers.vary, 'Origin') +}) + +test('Should set hook preHandler if hook option is set to preHandler', async (t) => { + t.plan(11) + + const fastify = Fastify() + + fastify.register(cors, { + hook: 'preHandler' + }) + + fastify.addHook('onResponse', (request, _reply, done) => { + t.assert.strictEqual(request[kFastifyContext].onError, null) + t.assert.strictEqual(request[kFastifyContext].onRequest, null) + t.assert.strictEqual(request[kFastifyContext].onSend, null) + t.assert.strictEqual(request[kFastifyContext].preHandler.length, 1) + t.assert.strictEqual(request[kFastifyContext].preParsing, null) + t.assert.strictEqual(request[kFastifyContext].preSerialization, null) + t.assert.strictEqual(request[kFastifyContext].preValidation, null) + done() + }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + await fastify.ready() + + const res = await fastify.inject({ + method: 'GET', + url: '/' + }) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + const actualHeader = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'] + } + t.assert.deepStrictEqual(actualHeader, { + 'access-control-allow-origin': '*' + }) + t.assert.notStrictEqual(res.headers.vary, 'Origin') +}) + +test('Should set hook onSend if hook option is set to onSend', async (t) => { + t.plan(11) + + const fastify = Fastify() + + fastify.register(cors, { + hook: 'onSend' + }) + + fastify.addHook('onResponse', (request, _reply, done) => { + t.assert.strictEqual(request[kFastifyContext].onError, null) + t.assert.strictEqual(request[kFastifyContext].onRequest, null) + t.assert.strictEqual(request[kFastifyContext].onSend.length, 1) + t.assert.strictEqual(request[kFastifyContext].preHandler, null) + t.assert.strictEqual(request[kFastifyContext].preParsing, null) + t.assert.strictEqual(request[kFastifyContext].preSerialization, null) + t.assert.strictEqual(request[kFastifyContext].preValidation, null) + done() + }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + await fastify.ready() + + const res = await fastify.inject({ + method: 'GET', + url: '/' + }) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + const actualHeader = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'] + } + t.assert.deepStrictEqual(actualHeader, { + 'access-control-allow-origin': '*' + }) + t.assert.notStrictEqual(res.headers.vary, 'Origin') +}) + +test('Should set hook preSerialization if hook option is set to preSerialization', async (t) => { + t.plan(11) + + const fastify = Fastify() + + fastify.register(cors, { + hook: 'preSerialization' + }) + + fastify.addHook('onResponse', (request, _reply, done) => { + t.assert.strictEqual(request[kFastifyContext].onError, null) + t.assert.strictEqual(request[kFastifyContext].onRequest, null) + t.assert.strictEqual(request[kFastifyContext].onSend, null) + t.assert.strictEqual(request[kFastifyContext].preHandler, null) + t.assert.strictEqual(request[kFastifyContext].preParsing, null) + t.assert.strictEqual(request[kFastifyContext].preSerialization.length, 1) + t.assert.strictEqual(request[kFastifyContext].preValidation, null) + done() + }) + + fastify.get('/', (_req, reply) => { + reply.send({ nonString: true }) + }) + + await fastify.ready() + + const res = await fastify.inject({ + method: 'GET', + url: '/' + }) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, '{"nonString":true}') + const actualHeader = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'] + } + t.assert.deepStrictEqual(actualHeader, { + 'access-control-allow-origin': '*' + }) + t.assert.notStrictEqual(res.headers.vary, 'Origin') +}) + +test('Should support custom hook with dynamic config', async t => { + t.plan(16) + + const configs = [{ + origin: 'example.com', + methods: 'GET', + credentials: true, + exposedHeaders: ['foo', 'bar'], + allowedHeaders: ['baz', 'woo'], + maxAge: 123 + }, { + origin: 'sample.com', + methods: 'GET', + credentials: true, + exposedHeaders: ['zoo', 'bar'], + allowedHeaders: ['baz', 'foo'], + maxAge: 321 + }] + + const fastify = Fastify() + let requestId = 0 + const configDelegation = async function (req) { + // request should have id + t.assert.ok(req.id) + // request should not have send + t.assert.ifError(req.send) + const config = configs[requestId] + requestId++ + if (config) { + return Promise.resolve(config) + } else { + return Promise.reject(new Error('ouch')) + } + } + await fastify.register(cors, { + hook: 'preHandler', + delegator: configDelegation + }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + let res = await fastify.inject({ + method: 'GET', + url: '/' + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + let actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-credentials': res.headers['access-control-allow-credentials'], + 'access-control-expose-headers': res.headers['access-control-expose-headers'], + 'content-length': res.headers['content-length'], + vary: res.headers.vary + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': 'example.com', + 'access-control-allow-credentials': 'true', + 'access-control-expose-headers': 'foo, bar', + 'content-length': '2', + vary: 'Origin' + }) + + res = await fastify.inject({ + method: 'OPTIONS', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 204) + t.assert.strictEqual(res.payload, '') + actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-credentials': res.headers['access-control-allow-credentials'], + 'access-control-expose-headers': res.headers['access-control-expose-headers'], + 'access-control-allow-methods': res.headers['access-control-allow-methods'], + 'access-control-allow-headers': res.headers['access-control-allow-headers'], + 'access-control-max-age': res.headers['access-control-max-age'], + 'content-length': res.headers['content-length'], + vary: res.headers.vary + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': 'sample.com', + 'access-control-allow-credentials': 'true', + 'access-control-expose-headers': 'zoo, bar', + 'access-control-allow-methods': 'GET', + 'access-control-allow-headers': 'baz, foo', + 'access-control-max-age': '321', + 'content-length': '0', + vary: 'Origin' + }) + + res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + t.assert.strictEqual(res.statusCode, 500) +}) + +test('Should support custom hook with dynamic config (callback)', async t => { + t.plan(16) + + const configs = [{ + origin: 'example.com', + methods: 'GET', + credentials: true, + exposedHeaders: ['foo', 'bar'], + allowedHeaders: ['baz', 'woo'], + maxAge: 123 + }, { + origin: 'sample.com', + methods: 'GET', + credentials: true, + exposedHeaders: ['zoo', 'bar'], + allowedHeaders: ['baz', 'foo'], + maxAge: 321 + }] + + const fastify = Fastify() + let requestId = 0 + const configDelegation = function (req, cb) { + // request should have id + t.assert.ok(req.id) + // request should not have send + t.assert.ifError(req.send) + const config = configs[requestId] + requestId++ + if (config) { + cb(null, config) + } else { + cb(new Error('ouch')) + } + } + fastify.register(cors, { + hook: 'preParsing', + delegator: configDelegation + }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + fastify.inject({ + method: 'GET', + url: '/' + }, (err, res) => { + t.assert.ifError(err) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + const actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-credentials': res.headers['access-control-allow-credentials'], + 'access-control-expose-headers': res.headers['access-control-expose-headers'], + 'content-length': res.headers['content-length'], + vary: res.headers.vary + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': 'example.com', + 'access-control-allow-credentials': 'true', + 'access-control-expose-headers': 'foo, bar', + 'content-length': '2', + vary: 'Origin' + }) + }) + + fastify.inject({ + method: 'OPTIONS', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }, (err, res) => { + t.assert.ifError(err) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 204) + t.assert.strictEqual(res.payload, '') + const actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-credentials': res.headers['access-control-allow-credentials'], + 'access-control-expose-headers': res.headers['access-control-expose-headers'], + 'access-control-allow-methods': res.headers['access-control-allow-methods'], + 'access-control-allow-headers': res.headers['access-control-allow-headers'], + 'access-control-max-age': res.headers['access-control-max-age'], + 'content-length': res.headers['content-length'], + vary: res.headers.vary + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': 'sample.com', + 'access-control-allow-credentials': 'true', + 'access-control-expose-headers': 'zoo, bar', + 'access-control-allow-methods': 'GET', + 'access-control-allow-headers': 'baz, foo', + 'access-control-max-age': '321', + 'content-length': '0', + vary: 'Origin' + }) + }) + + fastify.inject({ + method: 'GET', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }, (err, res) => { + t.assert.ifError(err) + t.assert.strictEqual(res.statusCode, 500) + }) + await sleep() +}) + +test('Should support custom hook with dynamic config (Promise)', async t => { + t.plan(16) + + const configs = [{ + origin: 'example.com', + methods: 'GET', + credentials: true, + exposedHeaders: ['foo', 'bar'], + allowedHeaders: ['baz', 'woo'], + maxAge: 123 + }, { + origin: 'sample.com', + methods: 'GET', + credentials: true, + exposedHeaders: ['zoo', 'bar'], + allowedHeaders: ['baz', 'foo'], + maxAge: 321 + }] + + const fastify = Fastify() + let requestId = 0 + const configDelegation = async function (req) { + // request should have id + t.assert.ok(req.id) + // request should not have send + t.assert.ifError(req.send) + const config = configs[requestId] + requestId++ + if (config) { + return Promise.resolve(config) + } else { + return Promise.reject(new Error('ouch')) + } + } + + await fastify.register(cors, { + hook: 'preParsing', + delegator: configDelegation + }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + let res = await fastify.inject({ + method: 'GET', + url: '/' + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + let actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-credentials': res.headers['access-control-allow-credentials'], + 'access-control-expose-headers': res.headers['access-control-expose-headers'], + 'content-length': res.headers['content-length'], + vary: res.headers.vary + } + + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': 'example.com', + 'access-control-allow-credentials': 'true', + 'access-control-expose-headers': 'foo, bar', + 'content-length': '2', + vary: 'Origin' + }) + + res = await fastify.inject({ + method: 'OPTIONS', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 204) + t.assert.strictEqual(res.payload, '') + actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-credentials': res.headers['access-control-allow-credentials'], + 'access-control-expose-headers': res.headers['access-control-expose-headers'], + 'access-control-allow-methods': res.headers['access-control-allow-methods'], + 'access-control-allow-headers': res.headers['access-control-allow-headers'], + 'access-control-max-age': res.headers['access-control-max-age'], + 'content-length': res.headers['content-length'], + vary: res.headers.vary + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': 'sample.com', + 'access-control-allow-credentials': 'true', + 'access-control-expose-headers': 'zoo, bar', + 'access-control-allow-methods': 'GET', + 'access-control-allow-headers': 'baz, foo', + 'access-control-max-age': '321', + 'content-length': '0', + vary: 'Origin' + }) + + res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + t.assert.strictEqual(res.statusCode, 500) +}) + +test('Should support custom hook with dynamic config (Promise), but should error /1', async t => { + t.plan(6) + + const fastify = Fastify() + const configDelegation = function () { + return false + } + + await fastify.register(cors, { + hook: 'preParsing', + delegator: configDelegation + }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + let res = await fastify.inject({ + method: 'OPTIONS', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 500) + t.assert.strictEqual(res.payload, '{"statusCode":500,"error":"Internal Server Error","message":"Invalid CORS origin option"}') + const actualHeaders = { + 'content-length': res.headers['content-length'] + } + t.assert.deepStrictEqual(actualHeaders, { + 'content-length': '89' + }) + + res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + t.assert.strictEqual(res.statusCode, 500) +}) + +test('Should support custom hook with dynamic config (Promise), but should error /2', async t => { + t.plan(6) + + const fastify = Fastify() + const configDelegation = function () { + return false + } + + await fastify.register(cors, { + delegator: configDelegation + }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + let res = await fastify.inject({ + method: 'OPTIONS', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 500) + t.assert.strictEqual(res.payload, '{"statusCode":500,"error":"Internal Server Error","message":"Invalid CORS origin option"}') + const actualHeaders = { + 'content-length': res.headers['content-length'] + } + t.assert.deepStrictEqual(actualHeaders, { + 'content-length': '89' + }) + + res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + t.assert.strictEqual(res.statusCode, 500) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/test/preflight.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/test/preflight.test.js new file mode 100644 index 0000000000000000000000000000000000000000..7a20de20c7e7c63089da6dc9a0100187df06eb79 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/test/preflight.test.js @@ -0,0 +1,590 @@ +'use strict' + +const { test } = require('node:test') +const Fastify = require('fastify') +const cors = require('../') + +test('Should reply to preflight requests', async t => { + t.plan(4) + + const fastify = Fastify() + await fastify.register(cors) + + const res = await fastify.inject({ + method: 'OPTIONS', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 204) + t.assert.strictEqual(res.payload, '') + const actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-methods': res.headers['access-control-allow-methods'], + vary: res.headers.vary, + 'content-length': res.headers['content-length'] + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': '*', + 'access-control-allow-methods': 'GET,HEAD,POST', + vary: 'Access-Control-Request-Headers', + 'content-length': '0' + }) +}) + +test('Should add access-control-allow-headers to response if preflight req has access-control-request-headers', async t => { + t.plan(4) + + const fastify = Fastify() + await fastify.register(cors) + + const res = await fastify.inject({ + method: 'OPTIONS', + url: '/', + headers: { + 'access-control-request-headers': 'x-requested-with', + 'access-control-request-method': 'GET', + origin: 'example.com' + } + + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 204) + t.assert.strictEqual(res.payload, '') + const actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-methods': res.headers['access-control-allow-methods'], + 'access-control-allow-headers': res.headers['access-control-allow-headers'], + vary: res.headers.vary, + 'content-length': res.headers['content-length'] + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': '*', + 'access-control-allow-methods': 'GET,HEAD,POST', + 'access-control-allow-headers': 'x-requested-with', + vary: 'Access-Control-Request-Headers', + 'content-length': '0' + }) +}) + +test('Should reply to preflight requests with custom status code', async t => { + t.plan(4) + + const fastify = Fastify() + await fastify.register(cors, { optionsSuccessStatus: 200 }) + + const res = await fastify.inject({ + method: 'OPTIONS', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, '') + const actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-methods': res.headers['access-control-allow-methods'], + vary: res.headers.vary, + 'content-length': res.headers['content-length'] + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': '*', + 'access-control-allow-methods': 'GET,HEAD,POST', + vary: 'Access-Control-Request-Headers', + 'content-length': '0' + }) +}) + +test('Should be able to override preflight response with a route', async t => { + t.plan(5) + + const fastify = Fastify() + await fastify.register(cors, { preflightContinue: true }) + + fastify.options('/', (_req, reply) => { + reply.send('ok') + }) + + const res = await fastify.inject({ + method: 'OPTIONS', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + const actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'] + } + t.assert.deepStrictEqual(actualHeaders, { + // Only the base cors headers and no preflight headers + 'access-control-allow-origin': '*' + }) + t.assert.notStrictEqual(res.headers.vary, 'Origin') +}) + +test('Should reply to all options requests', async t => { + t.plan(4) + + const fastify = Fastify() + await fastify.register(cors) + + const res = await fastify.inject({ + method: 'OPTIONS', + url: '/hello', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 204) + t.assert.strictEqual(res.payload, '') + const actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-methods': res.headers['access-control-allow-methods'], + vary: res.headers.vary, + 'content-length': res.headers['content-length'] + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': '*', + 'access-control-allow-methods': 'GET,HEAD,POST', + vary: 'Access-Control-Request-Headers', + 'content-length': '0' + }) +}) + +test('Should support a prefix for preflight requests', async t => { + t.plan(6) + + const fastify = Fastify() + await fastify.register((instance, _opts, next) => { + instance.register(cors) + next() + }, { prefix: '/subsystem' }) + + let res = await fastify.inject({ + method: 'OPTIONS', + url: '/hello' + }) + t.assert.ok(res) + t.assert.strictEqual(res.statusCode, 404) + + res = await fastify.inject({ + method: 'OPTIONS', + url: '/subsystem/hello', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 204) + t.assert.strictEqual(res.payload, '') + const actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-methods': res.headers['access-control-allow-methods'], + vary: res.headers.vary, + 'content-length': res.headers['content-length'] + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': '*', + 'access-control-allow-methods': 'GET,HEAD,POST', + vary: 'Access-Control-Request-Headers', + 'content-length': '0' + }) +}) + +test('hide options route by default', async t => { + t.plan(2) + + const fastify = Fastify() + + fastify.addHook('onRoute', (route) => { + if (route.method === 'OPTIONS' && route.url === '*') { + t.assert.strictEqual(route.schema.hide, true) + } + }) + await fastify.register(cors) + + const ready = await fastify.ready() + t.assert.ok(ready) +}) + +test('show options route', async t => { + t.plan(2) + + const fastify = Fastify() + + fastify.addHook('onRoute', (route) => { + if (route.method === 'OPTIONS' && route.url === '*') { + t.assert.strictEqual(route.schema.hide, false) + } + }) + await fastify.register(cors, { hideOptionsRoute: false }) + + const ready = await fastify.ready() + t.assert.ok(ready) +}) + +test('Allow only request from with specific methods', async t => { + t.plan(4) + + const fastify = Fastify() + await fastify.register(cors, { methods: ['GET', 'POST'] }) + + const res = await fastify.inject({ + method: 'OPTIONS', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 204) + const actualHeaders = { + 'access-control-allow-methods': res.headers['access-control-allow-methods'] + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-methods': 'GET, POST' + }) + t.assert.notStrictEqual(res.headers.vary, 'Origin') +}) + +test('Should reply with 400 error to OPTIONS requests missing origin header when default strictPreflight', async t => { + t.plan(3) + + const fastify = Fastify() + await fastify.register(cors) + + const res = await fastify.inject({ + method: 'OPTIONS', + url: '/', + headers: { + 'access-control-request-method': 'GET' + } + }) + t.assert.ok(res) + t.assert.strictEqual(res.statusCode, 400) + t.assert.strictEqual(res.payload, 'Invalid Preflight Request') +}) + +test('Should reply with 400 to OPTIONS requests when missing Access-Control-Request-Method header when default strictPreflight', async t => { + t.plan(3) + + const fastify = Fastify() + await fastify.register(cors, { + strictPreflight: true + }) + + const res = await fastify.inject({ + method: 'OPTIONS', + url: '/', + headers: { + origin: 'example.com' + } + }) + t.assert.ok(res) + t.assert.strictEqual(res.statusCode, 400) + t.assert.strictEqual(res.payload, 'Invalid Preflight Request') +}) + +test('Should reply to all preflight requests when strictPreflight is disabled', async t => { + t.plan(4) + + const fastify = Fastify() + await fastify.register(cors, { strictPreflight: false }) + + const res = await fastify.inject({ + method: 'OPTIONS', + url: '/' + // No access-control-request-method or origin headers + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 204) + t.assert.strictEqual(res.payload, '') + const actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-methods': res.headers['access-control-allow-methods'], + vary: res.headers.vary, + 'content-length': res.headers['content-length'] + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': '*', + 'access-control-allow-methods': 'GET,HEAD,POST', + vary: 'Access-Control-Request-Headers', + 'content-length': '0' + }) +}) + +test('Default empty 200 response with preflightContinue on OPTIONS routes', async t => { + t.plan(4) + + const fastify = Fastify() + await fastify.register(cors, { preflightContinue: true }) + + const res = await fastify.inject({ + method: 'OPTIONS', + url: '/doesnotexist', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, '') + const actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-methods': res.headers['access-control-allow-methods'], + vary: res.headers.vary + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': '*', + 'access-control-allow-methods': 'GET,HEAD,POST', + vary: 'Access-Control-Request-Headers' + }) +}) + +test('Can override preflight response with preflightContinue', async t => { + t.plan(4) + + const fastify = Fastify() + await fastify.register(cors, { preflightContinue: true }) + + fastify.options('/', (_req, reply) => { + reply.send('ok') + }) + + const res = await fastify.inject({ + method: 'OPTIONS', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + const actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-methods': res.headers['access-control-allow-methods'], + vary: res.headers.vary + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': '*', + 'access-control-allow-methods': 'GET,HEAD,POST', + vary: 'Access-Control-Request-Headers' + }) +}) + +test('Should support ongoing prefix ', async t => { + t.plan(12) + + const fastify = Fastify() + + await fastify.register(async (instance) => { + instance.register(cors) + }, { prefix: '/prefix' }) + + // support prefixed route + let res = await fastify.inject({ + method: 'OPTIONS', + url: '/prefix', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 204) + t.assert.strictEqual(res.payload, '') + let actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-methods': res.headers['access-control-allow-methods'], + vary: res.headers.vary, + 'content-length': res.headers['content-length'] + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': '*', + 'access-control-allow-methods': 'GET,HEAD,POST', + vary: 'Access-Control-Request-Headers', + 'content-length': '0' + }) + + // support prefixed route without / continue + res = await fastify.inject({ + method: 'OPTIONS', + url: '/prefixfoo', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 204) + t.assert.strictEqual(res.payload, '') + actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-methods': res.headers['access-control-allow-methods'], + vary: res.headers.vary, + 'content-length': res.headers['content-length'] + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': '*', + 'access-control-allow-methods': 'GET,HEAD,POST', + vary: 'Access-Control-Request-Headers', + 'content-length': '0' + }) + + // support prefixed route with / continue + res = await fastify.inject({ + method: 'OPTIONS', + url: '/prefix/foo', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 204) + t.assert.strictEqual(res.payload, '') + actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-methods': res.headers['access-control-allow-methods'], + vary: res.headers.vary, + 'content-length': res.headers['content-length'] + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': '*', + 'access-control-allow-methods': 'GET,HEAD,POST', + vary: 'Access-Control-Request-Headers', + 'content-length': '0' + }) +}) + +test('Silences preflight logs when logLevel is "silent"', async t => { + const logs = [] + const fastify = Fastify({ + logger: { + level: 'info', + stream: { + write (line) { + try { + logs.push(JSON.parse(line)) + } catch { + } + } + } + } + }) + + await fastify.register(cors, { logLevel: 'silent' }) + + fastify.get('/', async () => ({ ok: true })) + + await fastify.ready() + t.assert.ok(fastify) + + await fastify.inject({ + method: 'OPTIONS', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'https://example.com' + } + }) + + await fastify.inject({ method: 'GET', url: '/' }) + + const hasOptionsLog = logs.some(l => l.req && l.req.method === 'OPTIONS') + const hasGetLog = logs.some(l => l.req && l.req.method === 'GET') + + t.assert.strictEqual(hasOptionsLog, false) + t.assert.strictEqual(hasGetLog, true) + + await fastify.close() +}) +test('delegator + logLevel:"silent" → OPTIONS logs are suppressed', async t => { + t.plan(3) + + const logs = [] + const app = Fastify({ + logger: { + level: 'info', + stream: { write: l => { try { logs.push(JSON.parse(l)) } catch {} } } + } + }) + + await app.register(cors, { + delegator: () => ({ origin: '*' }), + logLevel: 'silent' + }) + + app.get('/', () => ({ ok: true })) + await app.ready() + t.assert.ok(app) + + await app.inject({ + method: 'OPTIONS', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'https://example.com' + } + }) + + await app.inject({ method: 'GET', url: '/' }) + + const hasOptionsLog = logs.some(l => l.req?.method === 'OPTIONS') + const hasGetLog = logs.some(l => l.req?.method === 'GET') + + t.assert.strictEqual(hasOptionsLog, false) + t.assert.strictEqual(hasGetLog, true) + + await app.close() +}) +test('delegator + hideOptionsRoute:false → OPTIONS route is visible', async t => { + t.plan(2) + + const app = Fastify() + + app.addHook('onRoute', route => { + if (route.method === 'OPTIONS' && route.url === '*') { + t.assert.strictEqual(route.schema.hide, false) + } + }) + + await app.register(cors, { + delegator: () => ({ origin: '*' }), + hideOptionsRoute: false + }) + + await app.ready() + t.assert.ok(app) + await app.close() +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/test/vary.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/test/vary.test.js new file mode 100644 index 0000000000000000000000000000000000000000..4357add02a890853b0183e6b54bdf15cda561f86 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/test/vary.test.js @@ -0,0 +1,237 @@ +'use strict' + +const { test } = require('node:test') +const { createAddFieldnameToVary } = require('../vary') +const { parse } = require('../vary') + +test('Should set * even if we set a specific field', async t => { + t.plan(1) + + const addOriginToVary = createAddFieldnameToVary('Origin') + const replyMock = { + getHeader () { + return '*' + }, + header () { + t.fail('Should not be here') + } + } + + addOriginToVary(replyMock) + t.assert.ok(true) // equalivant to tap t.pass() +}) + +test('Should set * even if we set a specific field', t => { + t.plan(2) + + const addWildcardToVary = createAddFieldnameToVary('*') + const replyMock = { + getHeader () { + return 'Origin' + }, + header (name, value) { + t.assert.deepStrictEqual(name, 'Vary') + t.assert.deepStrictEqual(value, '*') + } + } + + addWildcardToVary(replyMock) +}) + +test('Should set * when field contains a *', t => { + t.plan(3) + + const addOriginToVary = createAddFieldnameToVary('Origin') + const replyMock = { + getHeader () { + return ['Origin', '*', 'Access-Control-Request-Headers'] + }, + header (name, value) { + t.assert.deepStrictEqual(name, 'Vary') + t.assert.deepStrictEqual(value, '*') + } + } + + addOriginToVary(replyMock) + t.assert.ok(true) // equalivant to tap t.pass() +}) + +test('Should concat vary values', t => { + t.plan(3) + + const addOriginToVary = createAddFieldnameToVary('Origin') + const replyMock = { + getHeader () { + return 'Access-Control-Request-Headers' + }, + header (name, value) { + t.assert.deepStrictEqual(name, 'Vary') + t.assert.deepStrictEqual(value, 'Access-Control-Request-Headers, Origin') + } + } + + addOriginToVary(replyMock) + t.assert.ok(true) // equalivant to tap t.pass() +}) + +test('Should concat vary values ignoring consecutive commas', t => { + t.plan(3) + + const addOriginToVary = createAddFieldnameToVary('Origin') + const replyMock = { + getHeader () { + return ' Access-Control-Request-Headers,Access-Control-Request-Method' + }, + header (name, value) { + t.assert.deepStrictEqual(name, 'Vary') + t.assert.deepStrictEqual(value, ' Access-Control-Request-Headers,Access-Control-Request-Method, Origin') + } + } + + addOriginToVary(replyMock) + t.assert.ok(true) // equalivant to tap t.pass() +}) + +test('Should concat vary values ignoring whitespace', t => { + t.plan(3) + + const addOriginToVary = createAddFieldnameToVary('Origin') + const replyMock = { + getHeader () { + return ' Access-Control-Request-Headers ,Access-Control-Request-Method' + }, + header (name, value) { + t.assert.deepStrictEqual(name, 'Vary') + t.assert.deepStrictEqual(value, ' Access-Control-Request-Headers ,Access-Control-Request-Method, Origin') + } + } + + addOriginToVary(replyMock) + t.assert.ok(true) // equalivant to tap t.pass() +}) + +test('Should set the field as value for vary if no vary is defined', t => { + t.plan(2) + + const addOriginToVary = createAddFieldnameToVary('Origin') + const replyMock = { + getHeader () { + return undefined + }, + header (name, value) { + t.assert.deepStrictEqual(name, 'Vary') + t.assert.deepStrictEqual(value, 'Origin') + } + } + + addOriginToVary(replyMock) +}) + +test('Should set * as value for vary if vary contains *', t => { + t.plan(2) + + const addOriginToVary = createAddFieldnameToVary('Origin') + const replyMock = { + getHeader () { + return 'Accept,*' + }, + header (name, value) { + t.assert.deepStrictEqual(name, 'Vary') + t.assert.deepStrictEqual(value, '*') + } + } + + addOriginToVary(replyMock) +}) + +test('Should set Accept-Encoding as value for vary if vary is empty string', t => { + t.plan(2) + + const addAcceptEncodingToVary = createAddFieldnameToVary('Accept-Encoding') + const replyMock = { + getHeader () { + return '' + }, + header (name, value) { + t.assert.deepStrictEqual(name, 'Vary') + t.assert.deepStrictEqual(value, 'Accept-Encoding') + } + } + + addAcceptEncodingToVary(replyMock) +}) + +test('Should have no issues with values containing dashes', t => { + t.plan(2) + + const addXFooToVary = createAddFieldnameToVary('X-Foo') + const replyMock = { + value: 'Accept-Encoding', + getHeader () { + return this.value + }, + header (name, value) { + t.assert.deepStrictEqual(name, 'Vary') + t.assert.deepStrictEqual(value, 'Accept-Encoding, X-Foo') + this.value = value + } + } + + addXFooToVary(replyMock) + addXFooToVary(replyMock) +}) + +test('Should ignore the header as value for vary if it is already in vary', t => { + t.plan(1) + + const addOriginToVary = createAddFieldnameToVary('Origin') + const replyMock = { + getHeader () { + return 'Origin' + }, + header () { + t.fail('Should not be here') + } + } + addOriginToVary(replyMock) + addOriginToVary(replyMock) + + t.assert.ok(true) // equalivant to tap t.pass() +}) + +test('parse', t => { + t.plan(18) + t.assert.deepStrictEqual(parse(''), []) + t.assert.deepStrictEqual(parse('a'), ['a']) + t.assert.deepStrictEqual(parse('a,b'), ['a', 'b']) + t.assert.deepStrictEqual(parse(' a,b'), ['a', 'b']) + t.assert.deepStrictEqual(parse('a,b '), ['a', 'b']) + t.assert.deepStrictEqual(parse('a,b,c'), ['a', 'b', 'c']) + t.assert.deepStrictEqual(parse('A,b,c'), ['a', 'b', 'c']) + t.assert.deepStrictEqual(parse('a,b,c,'), ['a', 'b', 'c']) + t.assert.deepStrictEqual(parse('a,b,c, '), ['a', 'b', 'c']) + t.assert.deepStrictEqual(parse(',a,b,c'), ['a', 'b', 'c']) + t.assert.deepStrictEqual(parse(' ,a,b,c'), ['a', 'b', 'c']) + t.assert.deepStrictEqual(parse('a,,b,c'), ['a', 'b', 'c']) + t.assert.deepStrictEqual(parse('a,,,b,,c'), ['a', 'b', 'c']) + t.assert.deepStrictEqual(parse('a, b,c'), ['a', 'b', 'c']) + t.assert.deepStrictEqual(parse('a, b,c'), ['a', 'b', 'c']) + t.assert.deepStrictEqual(parse('a, , b,c'), ['a', 'b', 'c']) + t.assert.deepStrictEqual(parse('a, , b,c'), ['a', 'b', 'c']) + + // one for the cache + t.assert.deepStrictEqual(parse('A,b,c'), ['a', 'b', 'c']) +}) + +test('createAddFieldnameToVary', async t => { + t.plan(4) + t.assert.strictEqual(typeof createAddFieldnameToVary('valid-header'), 'function') + await t.assert.rejects( + async () => createAddFieldnameToVary('invalid:header'), + (err) => { + t.assert.strictEqual(err.name, 'TypeError') + t.assert.strictEqual(err.message, 'Fieldname contains invalid characters.') + return true + } + ) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/types/index.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/types/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..eab0b1ba66177929766c574ec77c2f62e6c0cfbb --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/types/index.d.ts @@ -0,0 +1,126 @@ +/// + +import { FastifyInstance, FastifyPluginCallback, FastifyRequest, LogLevel } from 'fastify' + +type OriginCallback = (err: Error | null, origin: ValueOrArray) => void +type OriginType = string | boolean | RegExp +type ValueOrArray = T | ArrayOfValueOrArray + +interface ArrayOfValueOrArray extends Array> { +} + +type FastifyCorsPlugin = FastifyPluginCallback< + NonNullable | fastifyCors.FastifyCorsOptionsDelegate +> + +type FastifyCorsHook = + | 'onRequest' + | 'preParsing' + | 'preValidation' + | 'preHandler' + | 'preSerialization' + | 'onSend' + +declare namespace fastifyCors { + export type OriginFunction = (origin: string | undefined, callback: OriginCallback) => void + export type AsyncOriginFunction = (origin: string | undefined) => Promise> + + export interface FastifyCorsOptions { + /** + * Configures the Lifecycle Hook. + */ + hook?: FastifyCorsHook; + + /** + * Configures the delegate function. + */ + delegator?: FastifyCorsOptionsDelegate; + + /** + * Configures the Access-Control-Allow-Origin CORS header. + */ + origin?: ValueOrArray | fastifyCors.AsyncOriginFunction | fastifyCors.OriginFunction; + /** + * Configures the Access-Control-Allow-Credentials CORS header. + * Set to true to pass the header, otherwise it is omitted. + */ + credentials?: boolean; + /** + * Configures the Access-Control-Expose-Headers CORS header. + * Expects a comma-delimited string (ex: 'Content-Range,X-Content-Range') + * or an array (ex: ['Content-Range', 'X-Content-Range']). + * If not specified, no custom headers are exposed. + */ + exposedHeaders?: string | string[]; + /** + * Configures the Access-Control-Allow-Headers CORS header. + * Expects a comma-delimited string (ex: 'Content-Type,Authorization') + * or an array (ex: ['Content-Type', 'Authorization']). If not + * specified, defaults to reflecting the headers specified in the + * request's Access-Control-Request-Headers header. + */ + allowedHeaders?: string | string[]; + /** + * Configures the Access-Control-Allow-Methods CORS header. + * Expects a comma-delimited string (ex: 'GET,PUT,POST') or an array (ex: ['GET', 'PUT', 'POST']). + */ + methods?: string | string[]; + /** + * Configures the Access-Control-Max-Age CORS header. + * Set to an integer to pass the header, otherwise it is omitted. + */ + maxAge?: number; + /** + * Configures the Cache-Control header for CORS preflight responses. + * Set to an integer to pass the header as `Cache-Control: max-age=${cacheControl}`, + * or set to a string to pass the header as `Cache-Control: ${cacheControl}` (fully define + * the header value), otherwise the header is omitted. + */ + cacheControl?: number | string; + /** + * Pass the CORS preflight response to the route handler (default: false). + */ + preflightContinue?: boolean; + /** + * Provides a status code to use for successful OPTIONS requests, + * since some legacy browsers (IE11, various SmartTVs) choke on 204. + */ + optionsSuccessStatus?: number; + /** + * Pass the CORS preflight response to the route handler (default: true). + */ + preflight?: boolean; + /** + * Enforces strict requirement of the CORS preflight request headers (Access-Control-Request-Method and Origin). + * Preflight requests without the required headers will result in 400 errors when set to `true` (default: `true`). + */ + strictPreflight?: boolean; + /** + * Hide options route from the documentation built using fastify-swagger (default: true). + */ + hideOptionsRoute?: boolean; + + /** + * Sets the Fastify log level specifically for the internal OPTIONS route + * used to handle CORS preflight requests. For example, setting this to `'silent'` + * will prevent these requests from being logged. + * Useful for reducing noise in application logs. + * Default: inherits Fastify's global log level. + */ + logLevel?: LogLevel; + } + + export interface FastifyCorsOptionsDelegateCallback { (req: FastifyRequest, cb: (error: Error | null, corsOptions?: FastifyCorsOptions) => void): void } + export interface FastifyCorsOptionsDelegatePromise { (req: FastifyRequest): Promise } + export type FastifyCorsOptionsDelegate = FastifyCorsOptionsDelegateCallback | FastifyCorsOptionsDelegatePromise + export type FastifyPluginOptionsDelegate = (instance: FastifyInstance) => T + + export const fastifyCors: FastifyCorsPlugin + export { fastifyCors as default } +} + +declare function fastifyCors ( + ...params: Parameters +): ReturnType + +export = fastifyCors diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/types/index.test-d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/types/index.test-d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4040e6666a0656edf01db4b08a1ddc400764f4f1 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/types/index.test-d.ts @@ -0,0 +1,388 @@ +import fastify, { FastifyRequest } from 'fastify' +import { expectType } from 'tsd' +import fastifyCors, { + AsyncOriginFunction, + FastifyCorsOptions, + FastifyCorsOptionsDelegate, + FastifyCorsOptionsDelegatePromise, + FastifyPluginOptionsDelegate, + OriginFunction +} from '..' + +const app = fastify() + +app.register(fastifyCors) + +app.register(fastifyCors, { + origin: true, + allowedHeaders: 'authorization,content-type', + methods: 'GET,POST,PUT,PATCH,DELETE,OPTIONS', + credentials: true, + exposedHeaders: 'authorization', + maxAge: 13000, + cacheControl: 13000, + preflightContinue: false, + optionsSuccessStatus: 200, + preflight: false, + strictPreflight: false +}) + +app.register(fastifyCors, { + origin: true, + allowedHeaders: ['authorization', 'content-type'], + methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], + credentials: true, + exposedHeaders: ['authorization'], + maxAge: 13000, + cacheControl: 'public, max-age=3500', + preflightContinue: false, + optionsSuccessStatus: 200, + preflight: false, + strictPreflight: false +}) + +app.register(fastifyCors, { + origin: '*', + allowedHeaders: ['authorization', 'content-type'], + methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], + credentials: true, + exposedHeaders: ['authorization'], + maxAge: 13000, + cacheControl: 13000, + preflightContinue: false, + optionsSuccessStatus: 200, + preflight: false, + strictPreflight: false +}) + +app.register(fastifyCors, { + origin: /\*/, + allowedHeaders: ['authorization', 'content-type'], + methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], + credentials: true, + exposedHeaders: ['authorization'], + maxAge: 13000, + cacheControl: 13000, + preflightContinue: false, + optionsSuccessStatus: 200, + preflight: false, + strictPreflight: false +}) + +app.register(fastifyCors, { + origin: ['*', 'something'], + allowedHeaders: ['authorization', 'content-type'], + methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], + credentials: true, + exposedHeaders: ['authorization'], + maxAge: 13000, + cacheControl: 13000, + preflightContinue: false, + optionsSuccessStatus: 200, + preflight: false, + strictPreflight: false +}) + +app.register(fastifyCors, { + origin: [/\*/, /something/], + allowedHeaders: ['authorization', 'content-type'], + methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], + credentials: true, + exposedHeaders: ['authorization'], + maxAge: 13000, + cacheControl: 13000, + preflightContinue: false, + optionsSuccessStatus: 200, + preflight: false, + strictPreflight: false +}) + +const corsDelegate: OriginFunction = (origin, cb) => { + if (origin === undefined || /localhost/.test(origin)) { + cb(null, true) + return + } + cb(new Error(), false) +} + +app.register(fastifyCors, { + origin: corsDelegate, + allowedHeaders: ['authorization', 'content-type'], + methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], + credentials: true, + exposedHeaders: ['authorization'], + maxAge: 13000, + cacheControl: 13000, + optionsSuccessStatus: 200, + preflight: false, + strictPreflight: false +}) + +const asyncCorsDelegate: OriginFunction = async (origin) => { + if (origin === undefined || /localhost/.test(origin)) { + return true + } + return false +} + +app.register(fastifyCors, { + origin: asyncCorsDelegate, + allowedHeaders: ['authorization', 'content-type'], + methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], + credentials: true, + exposedHeaders: ['authorization'], + maxAge: 13000, + cacheControl: 13000, + optionsSuccessStatus: 200, + preflight: false, + strictPreflight: false +}) + +app.register(fastifyCors, { + origin: (_origin, cb) => cb(null, true) +}) + +app.register(fastifyCors, { + origin: (_origin, cb) => cb(null, '*') +}) + +app.register(fastifyCors, { + origin: (_origin, cb) => cb(null, /\*/) +}) + +const appHttp2 = fastify({ http2: true }) + +appHttp2.register(fastifyCors) + +appHttp2.register(fastifyCors, { + origin: true, + allowedHeaders: 'authorization,content-type', + methods: 'GET,POST,PUT,PATCH,DELETE,OPTIONS', + credentials: true, + exposedHeaders: 'authorization', + maxAge: 13000, + cacheControl: 13000, + preflightContinue: false, + optionsSuccessStatus: 200, + preflight: false, + strictPreflight: false, + logLevel: 'silent' +}) + +appHttp2.register(fastifyCors, { + origin: true, + allowedHeaders: ['authorization', 'content-type'], + methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], + credentials: true, + exposedHeaders: ['authorization'], + maxAge: 13000, + cacheControl: 13000, + preflightContinue: false, + optionsSuccessStatus: 200, + preflight: false, + strictPreflight: false +}) + +appHttp2.register(fastifyCors, { + origin: '*', + allowedHeaders: ['authorization', 'content-type'], + methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], + credentials: true, + exposedHeaders: ['authorization'], + maxAge: 13000, + cacheControl: 13000, + preflightContinue: false, + optionsSuccessStatus: 200, + preflight: false, + strictPreflight: false +}) + +appHttp2.register(fastifyCors, { + origin: /\*/, + allowedHeaders: ['authorization', 'content-type'], + methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], + credentials: true, + exposedHeaders: ['authorization'], + maxAge: 13000, + cacheControl: 13000, + preflightContinue: false, + optionsSuccessStatus: 200, + preflight: false, + strictPreflight: false +}) + +appHttp2.register(fastifyCors, { + origin: ['*', 'something'], + allowedHeaders: ['authorization', 'content-type'], + methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], + credentials: true, + exposedHeaders: ['authorization'], + maxAge: 13000, + cacheControl: 13000, + preflightContinue: false, + optionsSuccessStatus: 200, + preflight: false, + strictPreflight: false +}) + +appHttp2.register(fastifyCors, { + origin: [/\*/, /something/], + allowedHeaders: ['authorization', 'content-type'], + methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], + credentials: true, + exposedHeaders: ['authorization'], + maxAge: 13000, + cacheControl: 13000, + preflightContinue: false, + optionsSuccessStatus: 200, + preflight: false, + strictPreflight: false +}) + +appHttp2.register(fastifyCors, { + origin: (origin: string | undefined, cb: (err: Error | null, allow: boolean) => void) => { + if (origin === undefined || /localhost/.test(origin)) { + cb(null, true) + return + } + cb(new Error(), false) + }, + allowedHeaders: ['authorization', 'content-type'], + methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], + credentials: true, + exposedHeaders: ['authorization'], + maxAge: 13000, + cacheControl: 13000, + preflightContinue: false, + optionsSuccessStatus: 200, + preflight: false, + strictPreflight: false +}) + +appHttp2.register(fastifyCors, (): FastifyCorsOptionsDelegate => (_req, cb) => { + cb(null, { + origin: [/\*/, /something/], + allowedHeaders: ['authorization', 'content-type'], + methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], + credentials: true, + exposedHeaders: ['authorization'], + maxAge: 13000, + cacheControl: 13000, + preflightContinue: false, + optionsSuccessStatus: 200, + preflight: false, + strictPreflight: false + }) +}) + +appHttp2.register(fastifyCors, (): FastifyCorsOptionsDelegatePromise => () => { + return Promise.resolve({ + origin: [/\*/, /something/], + allowedHeaders: ['authorization', 'content-type'], + methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], + credentials: true, + exposedHeaders: ['authorization'], + maxAge: 13000, + cacheControl: 13000, + preflightContinue: false, + optionsSuccessStatus: 200, + preflight: false, + strictPreflight: false + }) +}) + +const delegate: FastifyPluginOptionsDelegate = () => async () => { + return { + origin: [/\*/, /something/], + allowedHeaders: ['authorization', 'content-type'], + methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], + credentials: true, + exposedHeaders: ['authorization'], + maxAge: 13000, + cacheControl: 13000, + preflightContinue: false, + optionsSuccessStatus: 200, + preflight: false, + strictPreflight: false + } +} + +appHttp2.register(fastifyCors, { + hook: 'onRequest' +}) +appHttp2.register(fastifyCors, { + hook: 'preParsing' +}) +appHttp2.register(fastifyCors, { + hook: 'preValidation' +}) +appHttp2.register(fastifyCors, { + hook: 'preHandler' +}) +appHttp2.register(fastifyCors, { + hook: 'preSerialization' +}) +appHttp2.register(fastifyCors, { + hook: 'onSend' +}) + +appHttp2.register(fastifyCors, { + hook: 'preParsing', + delegator: (req, cb) => { + if (req.url.startsWith('/some-value')) { + cb(new Error()) + } + cb(null, { + origin: [/\*/, /something/], + allowedHeaders: ['authorization', 'content-type'], + methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], + credentials: true, + exposedHeaders: ['authorization'], + maxAge: 13000, + cacheControl: 12000, + preflightContinue: false, + optionsSuccessStatus: 200, + preflight: false, + strictPreflight: false + }) + } +}) + +appHttp2.register(fastifyCors, { + hook: 'preParsing', + delegator: async (_req: FastifyRequest): Promise => { + return { + origin: [/\*/, /something/], + allowedHeaders: ['authorization', 'content-type'], + methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], + credentials: true, + exposedHeaders: ['authorization'], + maxAge: 13000, + cacheControl: 'public, max-age=3500', + preflightContinue: false, + optionsSuccessStatus: 200, + preflight: false, + strictPreflight: false + } + } +}) + +appHttp2.register(fastifyCors, delegate) + +appHttp2.register(fastifyCors, { + hook: 'preParsing', + origin: function (origin, cb) { + expectType(origin) + cb(null, false) + }, +}) + +const asyncOriginFn: AsyncOriginFunction = async function (origin): Promise { + expectType(origin) + return false +} + +appHttp2.register(fastifyCors, { + hook: 'preParsing', + origin: asyncOriginFn, +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/vary.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/vary.js new file mode 100644 index 0000000000000000000000000000000000000000..73b3551e7071cd5decd34582f1c4b221216a37f2 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/cors/vary.js @@ -0,0 +1,116 @@ +'use strict' + +const { FifoMap: FifoCache } = require('toad-cache') + +/** + * Field Value Components + * Most HTTP header field values are defined using common syntax + * components (token, quoted-string, and comment) separated by + * whitespace or specific delimiting characters. Delimiters are chosen + * from the set of US-ASCII visual characters not allowed in a token + * (DQUOTE and "(),/:;<=>?@[\]{}"). + * + * field-name = token + * token = 1*tchar + * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" + * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" + * / DIGIT / ALPHA + * ; any VCHAR, except delimiters + * + * @see https://datatracker.ietf.org/doc/html/rfc7230#section-3.2.6 + */ + +const validFieldnameRE = /^[!#$%&'*+\-.^\w`|~]+$/u +function validateFieldname (fieldname) { + if (validFieldnameRE.test(fieldname) === false) { + throw new TypeError('Fieldname contains invalid characters.') + } +} + +function parse (header) { + header = header.trim().toLowerCase() + const result = [] + + if (header.length === 0) { + // pass through + } else if (header.indexOf(',') === -1) { + result.push(header) + } else { + const il = header.length + let i = 0 + let pos = 0 + let char + + // tokenize the header + for (i; i < il; ++i) { + char = header[i] + // when we have whitespace set the pos to the next position + if (char === ' ') { + pos = i + 1 + // `,` is the separator of vary-values + } else if (char === ',') { + // if pos and current position are not the same we have a valid token + if (pos !== i) { + result.push(header.slice(pos, i)) + } + // reset the positions + pos = i + 1 + } + } + + if (pos !== i) { + result.push(header.slice(pos, i)) + } + } + + return result +} + +function createAddFieldnameToVary (fieldname) { + const headerCache = new FifoCache(1000) + + validateFieldname(fieldname) + + return function (reply) { + let header = reply.getHeader('Vary') + + if (!header) { + reply.header('Vary', fieldname) + return + } + + if (header === '*') { + return + } + + if (fieldname === '*') { + reply.header('Vary', '*') + return + } + + if (Array.isArray(header)) { + header = header.join(', ') + } + + if (headerCache.get(header) === undefined) { + const vals = parse(header) + + if (vals.indexOf('*') !== -1) { + headerCache.set(header, '*') + } else if (vals.indexOf(fieldname.toLowerCase()) === -1) { + headerCache.set(header, header + ', ' + fieldname) + } else { + headerCache.set(header, null) + } + } + const cached = headerCache.get(header) + if (cached !== null) { + reply.header('Vary', cached) + } + } +} + +module.exports.createAddFieldnameToVary = createAddFieldnameToVary +module.exports.addOriginToVaryHeader = createAddFieldnameToVary('Origin') +module.exports.addAccessControlRequestHeadersToVaryHeader = createAddFieldnameToVary('Access-Control-Request-Headers') +module.exports.parse = parse diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/error/.gitattributes b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/error/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..a0e7df931f90e194cc6b80313f8f07744d9fc6d8 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/error/.gitattributes @@ -0,0 +1,2 @@ +# Set default behavior to automatically convert line endings +* text=auto eol=lf diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/error/.github/dependabot.yml b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/error/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..35d66ca7ac75f125b9c9c5b3dee0987fdfca4a45 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/error/.github/dependabot.yml @@ -0,0 +1,13 @@ +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "monthly" + open-pull-requests-limit: 10 + + - package-ecosystem: "npm" + directory: "/" + schedule: + interval: "monthly" + open-pull-requests-limit: 10 diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/error/.github/workflows/ci.yml b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/error/.github/workflows/ci.yml new file mode 100644 index 0000000000000000000000000000000000000000..fd45202abff682784e3a60d54fbfee567d304b26 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/error/.github/workflows/ci.yml @@ -0,0 +1,28 @@ +name: CI + +on: + push: + branches: + - main + - next + - 'v*' + paths-ignore: + - 'docs/**' + - '*.md' + pull_request: + paths-ignore: + - 'docs/**' + - '*.md' + +permissions: + contents: read + +jobs: + test: + permissions: + contents: write + pull-requests: write + uses: fastify/workflows/.github/workflows/plugins-ci.yml@v5 + with: + license-check: true + lint: true diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/error/LICENSE b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/error/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..08250b880441a047520f6d39ee6b08c6bcee2220 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/error/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Fastify + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/error/README.md b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/error/README.md new file mode 100644 index 0000000000000000000000000000000000000000..94814fe686890e199320bea2980fde24b2182d81 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/error/README.md @@ -0,0 +1,140 @@ +# @fastify/error + +[![CI](https://github.com/fastify/fastify-error/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/fastify/fastify-error/actions/workflows/ci.yml) +[![NPM version](https://img.shields.io/npm/v/@fastify/error.svg?style=flat)](https://www.npmjs.com/package/@fastify/error) +[![neostandard javascript style](https://img.shields.io/badge/code_style-neostandard-brightgreen?style=flat)](https://github.com/neostandard/neostandard) + +A small utility, used by Fastify itself, for generating consistent error objects across your codebase and plugins. + +### Install +``` +npm i @fastify/error +``` + +### Usage + +The module exports a function that you can use for consistent error objects, it takes 4 parameters: + +```js +createError(code, message [, statusCode [, Base [, captureStackTrace]]]) +``` + +- `code` (`string`, required) - The error code, you can access it later with `error.code`. For consistency, we recommend prefixing plugin error codes with `FST_` +- `message` (`string`, required) - The error message. You can also use interpolated strings for formatting the message. +- `statusCode` (`number`, optional) - The status code that Fastify will use if the error is sent via HTTP. +- `Base` (`ErrorConstructor`, optional) - The base error object that will be used. (eg `TypeError`, `RangeError`) +- `captureStackTrace` (`boolean`, optional) - Whether to capture the stack trace or not. + +```js +const createError = require('@fastify/error') +const CustomError = createError('ERROR_CODE', 'Hello') +console.log(new CustomError()) // error.message => 'Hello' +``` + +How to use an interpolated string: +```js +const createError = require('@fastify/error') +const CustomError = createError('ERROR_CODE', 'Hello %s') +console.log(new CustomError('world')) // error.message => 'Hello world' +``` + +How to add cause: +```js +const createError = require('@fastify/error') +const CustomError = createError('ERROR_CODE', 'Hello %s') +console.log(new CustomError('world', {cause: new Error('cause')})) +// error.message => 'Hello world' +// error.cause => Error('cause') +``` + +### TypeScript + +It is possible to limit your error constructor with a generic type using TypeScript: + +```ts +const CustomError = createError<[string]>('ERROR_CODE', 'Hello %s') +new CustomError('world') +//@ts-expect-error +new CustomError(1) +``` + +### instanceof + +All errors created with `createError` will be instances of the base error constructor you provided, or `Error` if none was provided. + +```js +const createError = require('@fastify/error') +const CustomError = createError('ERROR_CODE', 'Hello %s', 500, TypeError) +const customError = new CustomError('world') + +console.log(customError instanceof CustomError) // true +console.log(customError instanceof TypeError) // true +console.log(customError instanceof Error) // true +``` + +All instantiated errors are instances of the `FastifyError` class, which can be required directly from the module. + +```js +const { createError, FastifyError } = require('@fastify/error') +const CustomError = createError('ERROR_CODE', 'Hello %s', 500, TypeError) +const customError = new CustomError('world') + +console.log(customError instanceof FastifyError) // true +``` + +A `FastifyError` created by `createError` can extend another `FastifyError` while maintaining correct `instanceof` behavior. + +```js +const { createError, FastifyError } = require('@fastify/error') + +const CustomError = createError('ERROR_CODE', 'Hello %s', 500, TypeError) +const ChildCustomError = createError('CHILD_ERROR_CODE', 'Hello %s', 500, CustomError) + +const customError = new ChildCustomError('world') + +console.log(customError instanceof ChildCustomError) // true +console.log(customError instanceof CustomError) // true +console.log(customError instanceof FastifyError) // true +console.log(customError instanceof TypeError) // true +console.log(customError instanceof Error) // true +``` + +If `fastify-error` is installed multiple times directly or as a transitive dependency, `instanceof` checks for errors created by `createError` will still work correctly across these installations, as long as their error codes (e.g., `FST_ERR_CUSTOM_ERROR`) are identical. + +```js +const { createError, FastifyError } = require('@fastify/error') + +// CustomError from `@fastify/some-plugin` is created with `createError` and +// has its own `@fastify/error` installation as dependency. CustomError has +// FST_ERR_CUSTOM_ERROR as code. +const { CustomError: CustomErrorFromPlugin } = require('@fastify/some-plugin') + +const CustomError = createError('FST_ERR_CUSTOM_ERROR', 'Hello %s', 500) + +const customError = new CustomError('world') +const customErrorFromPlugin = new CustomErrorFromPlugin('world') + +console.log(customError instanceof CustomError) // true +console.log(customError instanceof CustomErrorFromPlugin) // true +console.log(customErrorFromPlugin instanceof CustomError) // true +console.log(customErrorFromPlugin instanceof CustomErrorFromPlugin) // true +``` + +Changing the code of an instantiated Error will not change the result of the `instanceof` operator. + +```js +const { createError, FastifyError } = require('@fastify/error') + +const CustomError = createError('ERROR_CODE', 'Hello %s', 500, TypeError) +const AnotherCustomError = createError('ANOTHER_ERROR_CODE', 'Hello %s', 500, CustomError) + +const customError = new CustomError('world') +customError.code = 'ANOTHER_ERROR_CODE' + +console.log(customError instanceof CustomError) // true +console.log(customError instanceof AnotherCustomError) // false +``` + +## License + +Licensed under [MIT](./LICENSE). diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/error/benchmarks/create.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/error/benchmarks/create.js new file mode 100644 index 0000000000000000000000000000000000000000..bb9abbfe1b34856cb81ea8fd7157ef8726c671fa --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/error/benchmarks/create.js @@ -0,0 +1,9 @@ +'use strict' + +const benchmark = require('benchmark') +const createError = require('..') + +new benchmark.Suite() + .add('create FastifyError', function () { createError('CODE', 'Not available') }, { minSamples: 100 }) + .on('cycle', function onCycle (event) { console.log(String(event.target)) }) + .run({ async: false }) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/error/benchmarks/instantiate.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/error/benchmarks/instantiate.js new file mode 100644 index 0000000000000000000000000000000000000000..890aaf0ac18f6ba3cb75e36d58421e1ac8f84673 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/error/benchmarks/instantiate.js @@ -0,0 +1,18 @@ +'use strict' + +const benchmark = require('benchmark') +const createError = require('..') + +const FastifyError = createError('CODE', 'Not available') +const FastifyError1 = createError('CODE', 'Not %s available') +const FastifyError2 = createError('CODE', 'Not %s available %s') + +const cause = new Error('cause') +new benchmark.Suite() + .add('instantiate Error', function () { new Error() }, { minSamples: 100 }) // eslint-disable-line no-new + .add('instantiate FastifyError', function () { new FastifyError() }, { minSamples: 100 }) // eslint-disable-line no-new + .add('instantiate FastifyError arg 1', function () { new FastifyError1('q') }, { minSamples: 100 }) // eslint-disable-line no-new + .add('instantiate FastifyError arg 2', function () { new FastifyError2('qq', 'ss') }, { minSamples: 100 }) // eslint-disable-line no-new + .add('instantiate FastifyError cause', function () { new FastifyError2({ cause }) }, { minSamples: 100 }) // eslint-disable-line no-new + .on('cycle', function onCycle (event) { console.log(String(event.target)) }) + .run({ async: false }) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/error/benchmarks/no-stack.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/error/benchmarks/no-stack.js new file mode 100644 index 0000000000000000000000000000000000000000..b626b5c79da786de28356722976d5ed3af0fe958 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/error/benchmarks/no-stack.js @@ -0,0 +1,13 @@ +'use strict' + +const benchmark = require('benchmark') +const createError = require('..') + +const FastifyError = createError('CODE', 'Not available') +Error.stackTraceLimit = 0 + +new benchmark.Suite() + .add('no-stack instantiate Error', function () { new Error() }, { minSamples: 100 }) // eslint-disable-line no-new + .add('no-stack instantiate FastifyError', function () { new FastifyError() }, { minSamples: 100 }) // eslint-disable-line no-new + .on('cycle', function onCycle (event) { console.log(String(event.target)) }) + .run({ async: false }) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/error/benchmarks/toString.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/error/benchmarks/toString.js new file mode 100644 index 0000000000000000000000000000000000000000..119154925ed8f6072c5f670c95ced9a52ca395f7 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/error/benchmarks/toString.js @@ -0,0 +1,11 @@ +'use strict' + +const benchmark = require('benchmark') +const createError = require('..') + +const FastifyError = createError('CODE', 'Not available') + +new benchmark.Suite() + .add('FastifyError toString', function () { new FastifyError().toString() }, { minSamples: 100 }) + .on('cycle', function onCycle (event) { console.log(String(event.target)) }) + .run({ async: false }) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/error/eslint.config.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/error/eslint.config.js new file mode 100644 index 0000000000000000000000000000000000000000..89fd678fe2a82d7fe3be869fffd71b3631c61c6a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/error/eslint.config.js @@ -0,0 +1,6 @@ +'use strict' + +module.exports = require('neostandard')({ + ignores: require('neostandard').resolveIgnoresFromGitignore(), + ts: true +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/error/index.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/error/index.js new file mode 100644 index 0000000000000000000000000000000000000000..4d8da8e5e15cdf3f3457965067687c3c54a15b99 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/error/index.js @@ -0,0 +1,100 @@ +'use strict' + +const { format } = require('node:util') + +function toString () { + return `${this.name} [${this.code}]: ${this.message}` +} + +const FastifyGenericErrorSymbol = Symbol.for('fastify-error-generic') + +function createError (code, message, statusCode = 500, Base = Error, captureStackTrace = createError.captureStackTrace) { + const shouldCreateFastifyGenericError = code === FastifyGenericErrorSymbol + + if (shouldCreateFastifyGenericError) { + code = 'FST_ERR' + } + + if (!code) throw new Error('Fastify error code must not be empty') + if (!message) throw new Error('Fastify error message must not be empty') + + code = code.toUpperCase() + !statusCode && (statusCode = undefined) + + const FastifySpecificErrorSymbol = Symbol.for(`fastify-error ${code}`) + + function FastifyError (...args) { + if (!new.target) { + return new FastifyError(...args) + } + + this.code = code + this.name = 'FastifyError' + this.statusCode = statusCode + + const lastElement = args.length - 1 + if (lastElement !== -1 && args[lastElement] && typeof args[lastElement] === 'object' && 'cause' in args[lastElement]) { + this.cause = args.pop().cause + } + + this.message = format(message, ...args) + + Error.stackTraceLimit && captureStackTrace && Error.captureStackTrace(this, FastifyError) + } + + FastifyError.prototype = Object.create(Base.prototype, { + constructor: { + value: FastifyError, + enumerable: false, + writable: true, + configurable: true + }, + [FastifyGenericErrorSymbol]: { + value: true, + enumerable: false, + writable: false, + configurable: false + }, + [FastifySpecificErrorSymbol]: { + value: true, + enumerable: false, + writable: false, + configurable: false + } + }) + + if (shouldCreateFastifyGenericError) { + Object.defineProperty(FastifyError, Symbol.hasInstance, { + value (instance) { + return instance && instance[FastifyGenericErrorSymbol] + }, + configurable: false, + writable: false, + enumerable: false + }) + } else { + Object.defineProperty(FastifyError, Symbol.hasInstance, { + value (instance) { + return instance && instance[FastifySpecificErrorSymbol] + }, + configurable: false, + writable: false, + enumerable: false + }) + } + + FastifyError.prototype[Symbol.toStringTag] = 'Error' + + FastifyError.prototype.toString = toString + + return FastifyError +} + +createError.captureStackTrace = true + +const FastifyErrorConstructor = createError(FastifyGenericErrorSymbol, 'Fastify Error', 500, Error) + +module.exports = createError +module.exports.FastifyError = FastifyErrorConstructor +module.exports.default = createError +module.exports.createError = createError diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/error/package.json b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/error/package.json new file mode 100644 index 0000000000000000000000000000000000000000..9a9beb89181430aaedec7ddd002272a9916895c3 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/error/package.json @@ -0,0 +1,75 @@ +{ + "name": "@fastify/error", + "version": "4.2.0", + "description": "A small utility, used by Fastify itself, for generating consistent error objects across your codebase and plugins.", + "main": "index.js", + "type": "commonjs", + "types": "types/index.d.ts", + "scripts": { + "lint": "eslint", + "lint:fix": "eslint --fix", + "test": "npm run test:unit && npm run test:typescript", + "test:unit": "c8 --100 node --test", + "test:typescript": "tsd" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/fastify/fastify-error.git" + }, + "keywords": [ + "fastify", + "error", + "utility", + "plugin" + ], + "author": "Tomas Della Vedova", + "contributors": [ + { + "name": "Matteo Collina", + "email": "hello@matteocollina.com" + }, + { + "name": "James Sumners", + "url": "https://james.sumners.info" + }, + { + "name": "Aras Abbasi", + "email": "aras.abbasi@gmail.com" + }, + { + "name": "Frazer Smith", + "email": "frazer.dev@icloud.com", + "url": "https://github.com/fdawgs" + } + ], + "license": "MIT", + "bugs": { + "url": "https://github.com/fastify/fastify-error/issues" + }, + "homepage": "https://github.com/fastify/fastify-error#readme", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "devDependencies": { + "benchmark": "^2.1.4", + "c8": "^10.1.2", + "eslint": "^9.17.0", + "neostandard": "^0.12.0", + "tsd": "^0.32.0" + }, + "tsd": { + "compilerOptions": { + "esModuleInterop": true + } + }, + "publishConfig": { + "access": "public" + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/error/test/index.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/error/test/index.test.js new file mode 100644 index 0000000000000000000000000000000000000000..3ad97f6d3941237231d553259daee284e7ca4596 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/error/test/index.test.js @@ -0,0 +1,232 @@ +'use strict' + +const test = require('node:test') +const { createError, FastifyError } = require('..') + +test('Create error with zero parameter', (t) => { + t.plan(6) + + const NewError = createError('CODE', 'Not available') + const err = new NewError() + t.assert.ok(err instanceof Error) + t.assert.equal(err.name, 'FastifyError') + t.assert.equal(err.message, 'Not available') + t.assert.equal(err.code, 'CODE') + t.assert.equal(err.statusCode, 500) + t.assert.ok(err.stack) +}) + +test('Create error with 1 parameter', (t) => { + t.plan(6) + + const NewError = createError('CODE', 'hey %s') + const err = new NewError('alice') + t.assert.equal(err.name, 'FastifyError') + t.assert.ok(err instanceof Error) + t.assert.equal(err.message, 'hey alice') + t.assert.equal(err.code, 'CODE') + t.assert.equal(err.statusCode, 500) + t.assert.ok(err.stack) +}) + +test('Create error with 1 parameter set to undefined', (t) => { + t.plan(1) + + const NewError = createError('CODE', 'hey %s') + const err = new NewError(undefined) + t.assert.equal(err.message, 'hey undefined') +}) + +test('Create error with 2 parameters', (t) => { + t.plan(6) + + const NewError = createError('CODE', 'hey %s, I like your %s') + const err = new NewError('alice', 'attitude') + t.assert.ok(err instanceof Error) + t.assert.equal(err.name, 'FastifyError') + t.assert.equal(err.message, 'hey alice, I like your attitude') + t.assert.equal(err.code, 'CODE') + t.assert.equal(err.statusCode, 500) + t.assert.ok(err.stack) +}) + +test('Create error with 2 parameters set to undefined', (t) => { + t.plan(1) + + const NewError = createError('CODE', 'hey %s, I like your %s') + const err = new NewError(undefined, undefined) + t.assert.equal(err.message, 'hey undefined, I like your undefined') +}) + +test('Create error with 3 parameters', (t) => { + t.plan(6) + + const NewError = createError('CODE', 'hey %s, I like your %s %s') + const err = new NewError('alice', 'attitude', 'see you') + t.assert.ok(err instanceof Error) + t.assert.equal(err.name, 'FastifyError') + t.assert.equal(err.message, 'hey alice, I like your attitude see you') + t.assert.equal(err.code, 'CODE') + t.assert.equal(err.statusCode, 500) + t.assert.ok(err.stack) +}) + +test('Create error with 3 parameters set to undefined', (t) => { + t.plan(4) + + const NewError = createError('CODE', 'hey %s, I like your %s %s') + const err = new NewError(undefined, undefined, undefined) + t.assert.equal(err.message, 'hey undefined, I like your undefined undefined') + t.assert.equal(err.code, 'CODE') + t.assert.equal(err.statusCode, 500) + t.assert.ok(err.stack) +}) + +test('Create error with 4 parameters set to undefined', (t) => { + t.plan(4) + + const NewError = createError('CODE', 'hey %s, I like your %s %s and %s') + const err = new NewError(undefined, undefined, undefined, undefined) + t.assert.equal( + err.message, + 'hey undefined, I like your undefined undefined and undefined' + ) + t.assert.equal(err.code, 'CODE') + t.assert.equal(err.statusCode, 500) + t.assert.ok(err.stack) +}) + +test('Create error with no statusCode property', (t) => { + t.plan(6) + + const NewError = createError('CODE', 'hey %s', 0) + const err = new NewError('dude') + t.assert.ok(err instanceof Error) + t.assert.equal(err.name, 'FastifyError') + t.assert.equal(err.message, 'hey dude') + t.assert.equal(err.code, 'CODE') + t.assert.equal(err.statusCode, undefined) + t.assert.ok(err.stack) +}) + +test('Should throw when error code has no fastify code', (t) => { + t.plan(1) + t.assert.throws( + () => createError(), + new Error('Fastify error code must not be empty') + ) +}) + +test('Should throw when error code has no message', (t) => { + t.assert.throws( + () => createError('code'), + new Error('Fastify error message must not be empty') + ) +}) + +test('Create error with different base', (t) => { + t.plan(7) + + const NewError = createError('CODE', 'hey %s', 500, TypeError) + const err = new NewError('dude') + t.assert.ok(err instanceof Error) + t.assert.ok(err instanceof TypeError) + t.assert.equal(err.name, 'FastifyError') + t.assert.equal(err.message, 'hey dude') + t.assert.equal(err.code, 'CODE') + t.assert.equal(err.statusCode, 500) + t.assert.ok(err.stack) +}) + +test('Create error with different base (no stack) (global)', (t) => { + t.plan(7) + + createError.captureStackTrace = false + const NewError = createError('CODE', 'hey %s', 500, TypeError) + const err = new NewError('dude') + t.assert.ok(err instanceof Error) + t.assert.ok(err instanceof TypeError) + t.assert.equal(err.name, 'FastifyError') + t.assert.equal(err.message, 'hey dude') + t.assert.equal(err.code, 'CODE') + t.assert.equal(err.statusCode, 500) + t.assert.equal(err.stack, undefined) + createError.captureStackTrace = true +}) + +test('Create error with different base (no stack) (parameter)', (t) => { + t.plan(7) + + const NewError = createError('CODE', 'hey %s', 500, TypeError, false) + const err = new NewError('dude') + t.assert.ok(err instanceof Error) + t.assert.ok(err instanceof TypeError) + t.assert.equal(err.name, 'FastifyError') + t.assert.equal(err.message, 'hey dude') + t.assert.equal(err.code, 'CODE') + t.assert.equal(err.statusCode, 500) + t.assert.equal(err.stack, undefined) +}) + +test('FastifyError.toString returns code', (t) => { + t.plan(1) + + const NewError = createError('CODE', 'foo') + const err = new NewError() + t.assert.equal(err.toString(), 'FastifyError [CODE]: foo') +}) + +test('Create the error without the new keyword', (t) => { + t.plan(6) + + const NewError = createError('CODE', 'Not available') + const err = NewError() + t.assert.ok(err instanceof Error) + t.assert.equal(err.name, 'FastifyError') + t.assert.equal(err.message, 'Not available') + t.assert.equal(err.code, 'CODE') + t.assert.equal(err.statusCode, 500) + t.assert.ok(err.stack) +}) + +test('Create an error with cause', (t) => { + t.plan(2) + + const cause = new Error('HEY') + const NewError = createError('CODE', 'Not available') + const err = NewError({ cause }) + + t.assert.ok(err instanceof Error) + t.assert.equal(err.cause, cause) +}) + +test('Create an error with cause and message', (t) => { + t.plan(2) + + const cause = new Error('HEY') + const NewError = createError('CODE', 'Not available: %s') + const err = NewError('foo', { cause }) + + t.assert.ok(err instanceof Error) + t.assert.equal(err.cause, cause) +}) + +test('Create an error with last argument null', (t) => { + t.plan(2) + + const cause = new Error('HEY') + const NewError = createError('CODE', 'Not available') + const err = NewError({ cause }, null) + + t.assert.ok(err instanceof Error) + t.assert.ifError(err.cause) +}) + +test('check if FastifyError is instantiable', (t) => { + t.plan(2) + + const err = new FastifyError() + + t.assert.ok(err instanceof FastifyError) + t.assert.ok(err instanceof Error) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/error/test/instanceof.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/error/test/instanceof.test.js new file mode 100644 index 0000000000000000000000000000000000000000..34d56fbf92cc1fcb391d8abdb2a543d4f09d0afa --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/error/test/instanceof.test.js @@ -0,0 +1,263 @@ +'use strict' + +const cp = require('node:child_process') +const fs = require('node:fs') +const path = require('node:path') +const os = require('node:os') +const test = require('node:test') +const { createError, FastifyError } = require('..') + +test('Readme: All errors created with `createError` will be instances of the base error constructor you provided, or `Error` if none was provided.', (t) => { + t.plan(3) + + const CustomError = createError('ERROR_CODE', 'Hello %s', 500, TypeError) + const customError = new CustomError('world') + + t.assert.ok(customError instanceof CustomError) + t.assert.ok(customError instanceof TypeError) + t.assert.ok(customError instanceof Error) +}) + +test('Readme: All instantiated errors will be instances of the `FastifyError` class. The `FastifyError` class can be required from the module directly.', (t) => { + t.plan(1) + + const CustomError = createError('ERROR_CODE', 'Hello %s', 500, TypeError) + const customError = new CustomError('world') + + t.assert.ok(customError instanceof FastifyError) +}) + +test('Readme: It is possible to create a `FastifyError` that extends another `FastifyError`, created by `createError`, while instanceof working correctly.', (t) => { + t.plan(5) + + const CustomError = createError('ERROR_CODE', 'Hello %s', 500, TypeError) + const ChildCustomError = createError('CHILD_ERROR_CODE', 'Hello %s', 500, CustomError) + + const customError = new ChildCustomError('world') + + t.assert.ok(customError instanceof ChildCustomError) + t.assert.ok(customError instanceof CustomError) + t.assert.ok(customError instanceof FastifyError) + t.assert.ok(customError instanceof TypeError) + t.assert.ok(customError instanceof Error) +}) + +test('Readme: Changing the code of an instantiated Error will not change the result of the `instanceof` operator.', (t) => { + t.plan(3) + + const CustomError = createError('ERROR_CODE', 'Hello %s', 500, TypeError) + const AnotherCustomError = createError('ANOTHER_ERROR_CODE', 'Hello %s', 500, CustomError) + + const customError = new CustomError('world') + customError.code = 'ANOTHER_ERROR_CODE' + + t.assert.ok(customError instanceof CustomError) + t.assert.ok(customError instanceof AnotherCustomError === false) + t.assert.ok(customError instanceof FastifyError) +}) + +test('check if createError creates an Error which is instanceof Error', (t) => { + t.plan(3) + + const CustomFastifyError = createError('CODE', 'Not available') + const err = CustomFastifyError() + + t.assert.ok(err instanceof Error) + t.assert.ok(err instanceof SyntaxError === false) + t.assert.ok(err instanceof TypeError === false) +}) + +test('check if createError creates an Error which is instanceof FastifyError', (t) => { + t.plan(4) + + const CustomFastifyError = createError('CODE', 'Not available') + const err = CustomFastifyError() + + t.assert.ok(err instanceof Error) + t.assert.ok(err instanceof FastifyError) + t.assert.ok(err instanceof SyntaxError === false) + t.assert.ok(err instanceof TypeError === false) +}) + +test('check if createError creates an Error with the right BaseConstructor', (t) => { + t.plan(2) + + const CustomFastifyError = createError('CODE', 'Not available', 500, TypeError) + const err = CustomFastifyError() + + t.assert.ok(err instanceof Error) + t.assert.ok(err instanceof TypeError) +}) + +test('check if createError creates an Error with the right BaseConstructor, which is a FastifyError', (t) => { + t.plan(6) + + const BaseFastifyError = createError('CODE', 'Not available', 500, TypeError) + const CustomFastifyError = createError('CODE', 'Not available', 500, BaseFastifyError) + const err = CustomFastifyError() + + t.assert.ok(err instanceof Error) + t.assert.ok(err instanceof TypeError) + t.assert.ok(err instanceof FastifyError) + t.assert.ok(err instanceof BaseFastifyError) + t.assert.ok(err instanceof CustomFastifyError) + t.assert.ok(err instanceof SyntaxError === false) +}) + +// for more information see https://github.com/fastify/fastify-error/pull/86#issuecomment-1301466407 +test('ensure that instanceof works accross different installations of the fastify-error module', async (t) => { + const assertsPlanned = 5 + t.plan(assertsPlanned) + + // We need to create a test environment where fastify-error is installed in two different locations + // and then we will check if the error created in one location is instanceof the error created in the other location + // This is done by creating a test directory with the following structure: + + // / + // ├── index.js + // └── node_modules/ + // ├── fastify-error/ + // │ └── index.js + // └── dep/ + // ├── index.js + // └── node_modules/ + // └── fastify-error/ + // └── index.js + + const testDirectoryPrefix = 'fastify-error-instanceof-test-' + + const testCwd = path.resolve(os.tmpdir(), `${testDirectoryPrefix}${Math.random().toString(36).substring(2, 15)}`) + fs.mkdirSync(testCwd, { recursive: true }) + + // Create the index.js. It will be executed as a forked process, so we need to + // use process.send to send messages back to the parent process. + fs.writeFileSync(path.resolve(testCwd, 'index.js'), ` + 'use strict' + + const path = require('node:path') + const { createError, FastifyError } = require('fastify-error') + const { foo } = require('dep') + + const actualPathOfFastifyError = require.resolve('fastify-error') + const expectedPathOfFastifyError = path.resolve('node_modules', 'fastify-error', 'index.js') + + // Ensure that fastify-error is required from the node_modules directory of the test-project + if (actualPathOfFastifyError !== expectedPathOfFastifyError) { + console.error('actualPathOfFastifyError', actualPathOfFastifyError) + console.error('expectedPathOfFastifyError', expectedPathOfFastifyError) + throw new Error('fastify-error should be required from the node_modules directory of the test-project') + } + + const Boom = createError('Boom', 'Boom', 500) + const ChildBoom = createError('ChildBoom', 'Boom', 500, Boom) + const NotChildBoom = createError('NotChildBoom', 'NotChildBoom', 500, Boom) + + try { + foo() + } catch (err) { + process.send(err instanceof Error) + process.send(err instanceof FastifyError) + process.send(err instanceof NotChildBoom) + process.send(err instanceof Boom) + process.send(err instanceof ChildBoom) + } + `) + + // Create /node_modules/fastify-error directory + // Copy the index.js file to the fastify-error directory + fs.mkdirSync(path.resolve(testCwd, 'node_modules', 'fastify-error'), { recursive: true }) + fs.copyFileSync(path.resolve(process.cwd(), 'index.js'), path.resolve(testCwd, 'node_modules', 'fastify-error', 'index.js')) + + // Create /node_modules/dep/node_modules/fastify-error directory + // Copy the index.js to the fastify-error directory + fs.mkdirSync(path.resolve(testCwd, 'node_modules', 'dep', 'node_modules', 'fastify-error'), { recursive: true }) + fs.copyFileSync(path.resolve(process.cwd(), 'index.js'), path.resolve(testCwd, 'node_modules', 'dep', 'node_modules', 'fastify-error', 'index.js')) + + // Create /node_modules/dep/index.js. It will export a function foo which will + // throw an error when called. The error will be an instance of ChildBoom, created + // by the fastify-error module in the node_modules directory of dep. + fs.writeFileSync(path.resolve(testCwd, 'node_modules', 'dep', 'index.js'), ` + 'use strict' + + const path = require('node:path') + const { createError } = require('fastify-error') + + const actualPathOfFastifyError = require.resolve('fastify-error') + const expectedPathOfFastifyError = path.resolve('node_modules', 'dep', 'node_modules', 'fastify-error', 'index.js') + + // Ensure that fastify-error is required from the node_modules directory of the test-project + if (actualPathOfFastifyError !== expectedPathOfFastifyError) { + console.error('actualPathOfFastifyError', actualPathOfFastifyError) + console.error('expectedPathOfFastifyError', expectedPathOfFastifyError) + throw new Error('fastify-error should be required from the node_modules directory of dep') + } + + const Boom = createError('Boom', 'Boom', 500) + const ChildBoom = createError('ChildBoom', 'Boom', 500, Boom) + + module.exports.foo = function foo () { + throw new ChildBoom('foo go Boom') + } + `) + + const finishedPromise = { + promise: undefined, + reject: undefined, + resolve: undefined, + } + + finishedPromise.promise = new Promise((resolve, reject) => { + finishedPromise.resolve = resolve + finishedPromise.reject = reject + }) + + const child = cp.fork(path.resolve(testCwd, 'index.js'), { + cwd: testCwd, + stdio: 'inherit', + env: { + ...process.env, + NODE_OPTIONS: '--no-warnings' + }, + }) + + let messageCount = 0 + child.on('message', message => { + try { + switch (messageCount) { + case 0: + t.assert.strictEqual(message, true, 'instanceof Error') + break + case 1: + t.assert.strictEqual(message, true, 'instanceof FastifyError') + break + case 2: + t.assert.strictEqual(message, false, 'instanceof NotChildBoom') + break + case 3: + t.assert.strictEqual(message, true, 'instanceof Boom') + break + case 4: + t.assert.strictEqual(message, true, 'instanceof ChildBoom') + break + } + if (++messageCount === assertsPlanned) { + finishedPromise.resolve() + } + } catch (err) { + finishedPromise.reject(err) + } + }) + + child.on('error', err => { + finishedPromise.reject(err) + }) + + await finishedPromise.promise + + // Cleanup + // As we are creating the test-setup on the fly in the /tmp directory, we can remove it + // safely when we are done. It is not relevant for the test if the deletion fails. + try { + fs.rmSync(testCwd, { recursive: true, force: true }) + } catch {} +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/error/types/index.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/error/types/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2e59d9febe28d1cad109f914d95c02551097ec59 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/error/types/index.d.ts @@ -0,0 +1,49 @@ +declare function createError ( + code: C, + message: string, + statusCode: SC, + Base?: ErrorConstructor, + captureStackTrace?: boolean +): createError.FastifyErrorConstructor<{ code: C, statusCode: SC }, Arg> + +declare function createError ( + code: C, + message: string, + statusCode?: number, + Base?: ErrorConstructor, + captureStackTrace?: boolean +): createError.FastifyErrorConstructor<{ code: C }, Arg> + +declare function createError ( + code: string, + message: string, + statusCode?: number, + Base?: ErrorConstructor, + captureStackTrace?: boolean +): createError.FastifyErrorConstructor<{ code: string }, Arg> + +type CreateError = typeof createError + +declare namespace createError { + export interface FastifyError extends Error { + code: string + name: string + statusCode?: number + } + + export interface FastifyErrorConstructor< + E extends { code: string, statusCode?: number } = { code: string, statusCode?: number }, + T extends unknown[] = [any?, any?, any?] + > { + new(...arg: T): FastifyError & E + (...arg: T): FastifyError & E + readonly prototype: FastifyError & E + } + + export const FastifyError: FastifyErrorConstructor + + export const createError: CreateError + export { createError as default } +} + +export = createError diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/error/types/index.test-d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/error/types/index.test-d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1a4398d4a452995bea323b67f7f2b041a6332af3 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/error/types/index.test-d.ts @@ -0,0 +1,92 @@ +import createError, { FastifyError, FastifyErrorConstructor } from '..' +import { expectType, expectError } from 'tsd' + +const CustomError = createError('ERROR_CODE', 'message') +expectType>(CustomError) +const err = new CustomError() +expectType(err) +expectType<'ERROR_CODE'>(err.code) +expectType(err.message) +expectType(err.statusCode) + +const CustomErrorNoStackTrace = createError('ERROR_CODE', 'message', undefined, undefined, false) +expectType>(CustomErrorNoStackTrace) +const errNoStackTrace = new CustomErrorNoStackTrace() +expectType(errNoStackTrace) +expectType<'ERROR_CODE'>(errNoStackTrace.code) +expectType(errNoStackTrace.message) +expectType(errNoStackTrace.statusCode) + +const CustomTypedError = createError('OTHER_CODE', 'message', 400) +expectType>(CustomTypedError) +const typed = new CustomTypedError() +expectType(typed) +expectType<'OTHER_CODE'>(typed.code) +expectType(typed.message) +expectType<400>(typed.statusCode) + +/* eslint-disable no-new */ +const CustomTypedArgError = createError<[string]>('OTHER_CODE', 'expect %s message', 400) +CustomTypedArgError('a') +expectError(CustomTypedArgError('a', 'b')) +expectError(new CustomTypedArgError('a', 'b')) +expectError(CustomTypedArgError(1)) +expectError(new CustomTypedArgError(1)) + +const CustomTypedArgError2 = createError('OTHER_CODE', 'expect %s message', 400) +CustomTypedArgError2('a') +expectError(CustomTypedArgError2('a', 'b')) +expectError(new CustomTypedArgError2('a', 'b')) +expectError(CustomTypedArgError2(1)) +expectError(new CustomTypedArgError2(1)) + +const CustomTypedArgError3 = createError('OTHER_CODE', 'expect %s message but got %s', 400) +expectError(CustomTypedArgError3('a')) +CustomTypedArgError3('a', 'b') +new CustomTypedArgError3('a', 'b') +expectError(CustomTypedArgError3(1)) +expectError(new CustomTypedArgError3(1)) +expectError(new CustomTypedArgError3(1, 2)) +expectError(new CustomTypedArgError3('1', 2)) +expectError(new CustomTypedArgError3(1, '2')) + +const CustomTypedArgError4 = createError('OTHER_CODE', 'expect %s message but got %s', 400) +expectError(CustomTypedArgError4('a')) +CustomTypedArgError4('a', 'b') +new CustomTypedArgError4('a', 'b') +expectError(CustomTypedArgError4(1)) +expectError(new CustomTypedArgError4(1)) +expectError(new CustomTypedArgError4(1, 2)) +expectError(new CustomTypedArgError4('1', 2)) +expectError(new CustomTypedArgError4(1, '2')) + +const CustomTypedArgError5 = createError<[string, string, string, string]>('OTHER_CODE', 'expect %s message but got %s. Please contact %s by emailing to %s', 400) +expectError(CustomTypedArgError5('a')) +expectError(new CustomTypedArgError5('a', 'b')) +expectError(new CustomTypedArgError5('a', 'b', 'c')) +CustomTypedArgError5('a', 'b', 'c', 'd') +expectError(new CustomTypedArgError5('a', 'b', 'c', 'd', 'e')) + +const CustomTypedArgError6 = createError('OTHER_CODE', 'expect %s message but got %s. Please contact %s by emailing to %s', 400) +expectError(CustomTypedArgError6('a')) +expectError(new CustomTypedArgError6('a', 'b')) +expectError(new CustomTypedArgError6('a', 'b', 'c')) +CustomTypedArgError6('a', 'b', 'c', 'd') +expectError(new CustomTypedArgError6('a', 'b', 'c', 'd', 'e')) + +const CustomErrorWithErrorConstructor = createError('ERROR_CODE', 'message', 500, TypeError) +expectType>(CustomErrorWithErrorConstructor) +CustomErrorWithErrorConstructor({ cause: new Error('Error') }) +const customErrorWithErrorConstructor = CustomErrorWithErrorConstructor() +if (customErrorWithErrorConstructor instanceof FastifyError) { + expectType<'ERROR_CODE'>(customErrorWithErrorConstructor.code) + expectType(customErrorWithErrorConstructor.message) + expectType<500>(customErrorWithErrorConstructor.statusCode) +} + +const error = new FastifyError('ERROR_CODE', 'message', 500) +if (error instanceof FastifyError) { + expectType(error.code) + expectType(error.message) + expectType(error.statusCode) +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/.eslintrc b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..185ff2ec247992d88eb49b8581f20d8676c859f1 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/.eslintrc @@ -0,0 +1 @@ +{"extends": "standard"} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/.gitattributes b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..a0e7df931f90e194cc6b80313f8f07744d9fc6d8 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/.gitattributes @@ -0,0 +1,2 @@ +# Set default behavior to automatically convert line endings +* text=auto eol=lf diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/.github/dependabot.yml b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..35d66ca7ac75f125b9c9c5b3dee0987fdfca4a45 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/.github/dependabot.yml @@ -0,0 +1,13 @@ +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "monthly" + open-pull-requests-limit: 10 + + - package-ecosystem: "npm" + directory: "/" + schedule: + interval: "monthly" + open-pull-requests-limit: 10 diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/.github/workflows/ci.yml b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/.github/workflows/ci.yml new file mode 100644 index 0000000000000000000000000000000000000000..fd45202abff682784e3a60d54fbfee567d304b26 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/.github/workflows/ci.yml @@ -0,0 +1,28 @@ +name: CI + +on: + push: + branches: + - main + - next + - 'v*' + paths-ignore: + - 'docs/**' + - '*.md' + pull_request: + paths-ignore: + - 'docs/**' + - '*.md' + +permissions: + contents: read + +jobs: + test: + permissions: + contents: write + pull-requests: write + uses: fastify/workflows/.github/workflows/plugins-ci.yml@v5 + with: + license-check: true + lint: true diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/LICENSE b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..5559f4f5474ede095fe90f128023a7c9dfeb75bc --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 Fastify + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/README.md b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/README.md new file mode 100644 index 0000000000000000000000000000000000000000..dcc1ecd6ba7d8b7be4e680ced6e2a19d6e6060b3 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/README.md @@ -0,0 +1,128 @@ +# @fastify/fast-json-stringify-compiler + +[![CI](https://github.com/fastify/fast-json-stringify-compiler/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/fastify/fast-json-stringify-compiler/actions/workflows/ci.yml) +[![NPM version](https://img.shields.io/npm/v/@fastify/fast-json-stringify-compiler.svg?style=flat)](https://www.npmjs.com/package/@fastify/fast-json-stringify-compiler) +[![neostandard javascript style](https://img.shields.io/badge/code_style-neostandard-brightgreen?style=flat)](https://github.com/neostandard/neostandard) + +Build and manage the [`fast-json-stringify`](https://www.npmjs.com/package/fast-json-stringify) instances for the Fastify framework. +This package is responsible for compiling the application's `response` JSON schemas into optimized functions to speed up the response time. + +## Versions + +| `@fastify/fast-json-stringify-compiler` | `fast-json-stringify` | Supported `fastify` | +|----------------------------------------:|----------------------:|--------------------:| +| v1.x | v3.x | ^3.x | +| v2.x | v3.x | ^4.x | +| v3.x | v4.x | ^4.x | +| v4.x | v5.x | ^5.x | + +### fast-json-stringify Configuration + +The `fast-json-stringify` configuration is the default one. You can check the default settings in the [`fast-json-stringify` option](https://github.com/fastify/fast-json-stringify/#options) documentation. + +You can also override the default configuration by passing the [`serializerOpts`](https://fastify.dev/docs/latest/Reference/Server/#serializeropts) configuration to the Fastify instance. + +## Usage + +This module is already used as default by Fastify. +If you need to provide to your server instance a different version, refer to [the official doc](https://fastify.dev/docs/latest/Reference/Server/#schemacontroller). + +### fast-json-stringify Standalone + +`fast-json-stringify@v4.1.0` introduces the [standalone feature](https://github.com/fastify/fast-json-stringify#standalone) that lets you pre-compile your schemas and use them in your application for a faster startup. + +To use this feature, you must be aware of the following: + +1. You must generate and save the application's compiled schemas. +2. Read the compiled schemas from the file and provide them back to your Fastify application. + + +#### Generate and save the compiled schemas + +Fastify helps you to generate the serialization schemas functions and it is your choice to save them where you want. +To accomplish this, you must use a new compiler: `@fastify/fast-json-stringify-compiler/standalone`. + +You must provide 2 parameters to this compiler: + +- `readMode: false`: a boolean to indicate that you want to generate the schemas functions string. +- `storeFunction`" a sync function that must store the source code of the schemas functions. You may provide an async function too, but you must manage errors. + +When `readMode: false`, **the compiler is meant to be used in development ONLY**. + + +```js +const { StandaloneSerializer } = require('@fastify/fast-json-stringify-compiler') + +const factory = StandaloneSerializer({ + readMode: false, + storeFunction (routeOpts, schemaSerializationCode) { + // routeOpts is like: { schema, method, url, httpStatus } + // schemaSerializationCode is a string source code that is the compiled schema function + const fileName = generateFileName(routeOpts) + fs.writeFileSync(path.join(__dirname, fileName), schemaSerializationCode) + } +}) + +const app = fastify({ + jsonShorthand: false, + schemaController: { + compilersFactory: { + buildSerializer: factory + } + } +}) + +// ... add all your routes with schemas ... + +app.ready().then(() => { + // at this stage all your schemas are compiled and stored in the file system + // now it is important to turn off the readMode +}) +``` + +#### Read the compiled schemas functions + +At this stage, you should have a file for every route's schema. +To use them, you must use the `@fastify/fast-json-stringify-compiler/standalone` with the parameters: + +- `readMode: true`: a boolean to indicate that you want to read and use the schemas functions string. +- `restoreFunction`" a sync function that must return a function to serialize the route's payload. + +Important keep away before you continue reading the documentation: + +- when you use the `readMode: true`, the application schemas are not compiled (they are ignored). So, if you change your schemas, you must recompile them! +- as you can see, you must relate the route's schema to the file name using the `routeOpts` object. You may use the `routeOpts.schema.$id` field to do so, it is up to you to define a unique schema identifier. + +```js +const { StandaloneSerializer } = require('@fastify/fast-json-stringify-compiler') + +const factory = StandaloneSerializer({ + readMode: true, + restoreFunction (routeOpts) { + // routeOpts is like: { schema, method, url, httpStatus } + const fileName = generateFileName(routeOpts) + return require(path.join(__dirname, fileName)) + } +}) + +const app = fastify({ + jsonShorthand: false, + schemaController: { + compilersFactory: { + buildSerializer: factory + } + } +}) + +// ... add all your routes with schemas as before... + +app.listen({ port: 3000 }) +``` + +### How it works + +This module provides a factory function to produce [Serializer Compilers](https://fastify.dev/docs/latest/Reference/Server/#serializercompiler) functions. + +## License + +Licensed under [MIT](./LICENSE). diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/eslint.config.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/eslint.config.js new file mode 100644 index 0000000000000000000000000000000000000000..89fd678fe2a82d7fe3be869fffd71b3631c61c6a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/eslint.config.js @@ -0,0 +1,6 @@ +'use strict' + +module.exports = require('neostandard')({ + ignores: require('neostandard').resolveIgnoresFromGitignore(), + ts: true +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/index.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/index.js new file mode 100644 index 0000000000000000000000000000000000000000..9323c971a1d4da1cf1b95f244fa2d3b7263673a6 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/index.js @@ -0,0 +1,8 @@ +'use strict' + +const { SerializerSelector, StandaloneSerializer } = require('./standalone') + +module.exports = SerializerSelector +module.exports.default = SerializerSelector +module.exports.SerializerSelector = SerializerSelector +module.exports.StandaloneSerializer = StandaloneSerializer diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/package.json b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/package.json new file mode 100644 index 0000000000000000000000000000000000000000..cc104b7c4ff802cda367b2ed32ed9a500fc13637 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/package.json @@ -0,0 +1,71 @@ +{ + "name": "@fastify/fast-json-stringify-compiler", + "description": "Build and manage the fast-json-stringify instances for the fastify framework", + "version": "5.0.3", + "main": "index.js", + "type": "commonjs", + "types": "types/index.d.ts", + "scripts": { + "lint": "eslint", + "lint:fix": "eslint --fix", + "unit": "c8 --100 node --test", + "test": "npm run unit && npm run test:typescript", + "test:typescript": "tsd" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/fastify/fast-json-stringify-compiler.git" + }, + "keywords": [], + "author": "Manuel Spigolon (https://github.com/Eomm)", + "contributors": [ + { + "name": "Matteo Collina", + "email": "hello@matteocollina.com" + }, + { + "name": "Aras Abbasi", + "email": "aras.abbasi@gmail.com" + }, + { + "name": "James Sumners", + "url": "https://james.sumners.info" + }, + { + "name": "Frazer Smith", + "email": "frazer.dev@icloud.com", + "url": "https://github.com/fdawgs" + } + ], + "license": "MIT", + "bugs": { + "url": "https://github.com/fastify/fast-json-stringify-compiler/issues" + }, + "homepage": "https://github.com/fastify/fast-json-stringify-compiler#readme", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "devDependencies": { + "@fastify/pre-commit": "^2.1.0", + "c8": "^10.1.3", + "eslint": "^9.17.0", + "fastify": "^5.0.0", + "neostandard": "^0.12.0", + "sanitize-filename": "^1.6.3", + "tsd": "^0.31.0" + }, + "pre-commit": [ + "lint", + "test" + ], + "dependencies": { + "fast-json-stringify": "^6.0.0" + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/standalone.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/standalone.js new file mode 100644 index 0000000000000000000000000000000000000000..7f0d40ae219c8adaf6b6487a1874b98dc899d82d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/standalone.js @@ -0,0 +1,58 @@ +'use strict' + +const fastJsonStringify = require('fast-json-stringify') + +function SerializerSelector () { + return function buildSerializerFactory (externalSchemas, serializerOpts) { + const fjsOpts = Object.assign({}, serializerOpts, { schema: externalSchemas }) + return responseSchemaCompiler.bind(null, fjsOpts) + } +} + +function responseSchemaCompiler (fjsOpts, { schema /* method, url, httpStatus */ }) { + if (fjsOpts.schema && schema.$id && fjsOpts.schema[schema.$id]) { + fjsOpts.schema = { ...fjsOpts.schema } + delete fjsOpts.schema[schema.$id] + } + return fastJsonStringify(schema, fjsOpts) +} + +function StandaloneSerializer (options = { readMode: true }) { + if (options.readMode === true && typeof options.restoreFunction !== 'function') { + throw new Error('You must provide a function for the restoreFunction-option when readMode ON') + } + + if (options.readMode !== true && typeof options.storeFunction !== 'function') { + throw new Error('You must provide a function for the storeFunction-option when readMode OFF') + } + + if (options.readMode === true) { + // READ MODE: it behalf only in the restore function provided by the user + return function wrapper () { + return function (opts) { + return options.restoreFunction(opts) + } + } + } + + // WRITE MODE: it behalf on the default SerializerSelector, wrapping the API to run the Ajv Standalone code generation + const factory = SerializerSelector() + return function wrapper (externalSchemas, serializerOpts = {}) { + // to generate the serialization source code, this option is mandatory + serializerOpts.mode = 'standalone' + + const compiler = factory(externalSchemas, serializerOpts) + return function (opts) { // { schema/*, method, url, httpPart */ } + const serializeFuncCode = compiler(opts) + + options.storeFunction(opts, serializeFuncCode) + + // eslint-disable-next-line no-new-func + return new Function(serializeFuncCode) + } + } +} + +module.exports.SerializerSelector = SerializerSelector +module.exports.StandaloneSerializer = StandaloneSerializer +module.exports.default = StandaloneSerializer diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/test/duplicate-schema.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/test/duplicate-schema.test.js new file mode 100644 index 0000000000000000000000000000000000000000..2acaa24026b26ff0b7ce43c506e6fc79025e6cdd --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/test/duplicate-schema.test.js @@ -0,0 +1,26 @@ +'use strict' + +const { test } = require('node:test') +const FjsCompiler = require('../index') + +test('Use input schema duplicate in the externalSchemas', async t => { + t.plan(1) + const externalSchemas = { + schema1: { + $id: 'schema1', + type: 'number' + }, + schema2: { + $id: 'schema2', + type: 'string' + } + } + + const factory = FjsCompiler() + const compiler = factory(externalSchemas) + + compiler({ schema: externalSchemas.schema1 }) + compiler({ schema: externalSchemas.schema2 }) + + t.assert.ok(true) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/test/plugin.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/test/plugin.test.js new file mode 100644 index 0000000000000000000000000000000000000000..26ca0f5f450c7695059725aeb4acea5c5b20fc3e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/test/plugin.test.js @@ -0,0 +1,78 @@ +'use strict' + +const { test } = require('node:test') +const fastify = require('fastify') +const FjsCompiler = require('../index') + +const echo = async (req) => { return req.body } + +const sampleSchema = Object.freeze({ + $id: 'example1', + type: 'object', + properties: { + name: { type: 'string' } + } +}) + +const externalSchemas1 = Object.freeze({}) +const externalSchemas2 = Object.freeze({ + foo: { + $id: 'foo', + type: 'object', + properties: { + name: { type: 'string' } + } + } +}) + +const fastifyFjsOptionsDefault = Object.freeze({}) + +test('basic usage', t => { + t.plan(1) + const factory = FjsCompiler() + const compiler = factory(externalSchemas1, fastifyFjsOptionsDefault) + const serializeFunc = compiler({ schema: sampleSchema }) + const result = serializeFunc({ name: 'hello' }) + t.assert.equal(result, '{"name":"hello"}') +}) + +test('fastify integration', async t => { + const factory = FjsCompiler() + + const app = fastify({ + serializerOpts: { + rounding: 'ceil' + }, + schemaController: { + compilersFactory: { + buildSerializer: factory + } + } + }) + + app.addSchema(externalSchemas2.foo) + + app.post('/', { + handler: echo, + schema: { + response: { + 200: { + $ref: 'foo#' + } + } + } + }) + + const res = await app.inject({ + url: '/', + method: 'POST', + payload: { + version: '1', + foo: 'this is not a number', + name: 'serialize me' + } + }) + + t.assert.equal(res.statusCode, 200) + t.assert.deepStrictEqual(res.json(), { name: 'serialize me' }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/test/standalone.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/test/standalone.test.js new file mode 100644 index 0000000000000000000000000000000000000000..6ecdc1714e2e1809c6a6fee7ddb1d3b0feab5cc2 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/test/standalone.test.js @@ -0,0 +1,230 @@ +'use strict' + +const fs = require('node:fs') +const path = require('node:path') +const { test } = require('node:test') +const fastify = require('fastify') +const sanitize = require('sanitize-filename') + +const { StandaloneSerializer: FjsStandaloneCompiler } = require('../') + +const generatedFileNames = [] + +function generateFileName (routeOpts) { + const fileName = `/fjs-generated-${sanitize(routeOpts.schema.$id)}-${routeOpts.method}-${routeOpts.httpPart}-${sanitize(routeOpts.url)}.js` + generatedFileNames.push(fileName) + return fileName +} + +test('standalone', async t => { + t.plan(5) + + t.after(async () => { + for (const fileName of generatedFileNames) { + try { + await fs.promises.unlink(path.join(__dirname, fileName)) + } catch {} + } + }) + + t.test('errors', t => { + t.plan(2) + t.assert.throws(() => { + FjsStandaloneCompiler() + }, 'missing restoreFunction') + t.assert.throws(() => { + FjsStandaloneCompiler({ readMode: false }) + }, 'missing storeFunction') + }) + + t.test('generate standalone code', t => { + t.plan(5) + + const base = { + $id: 'urn:schema:base', + definitions: { + hello: { type: 'string' } + }, + type: 'object', + properties: { + hello: { $ref: '#/definitions/hello' } + } + } + + const refSchema = { + $id: 'urn:schema:ref', + type: 'object', + properties: { + hello: { $ref: 'urn:schema:base#/definitions/hello' } + } + } + + const endpointSchema = { + schema: { + $id: 'urn:schema:endpoint', + $ref: 'urn:schema:ref' + } + } + + const schemaMap = { + [base.$id]: base, + [refSchema.$id]: refSchema + } + + const factory = FjsStandaloneCompiler({ + readMode: false, + storeFunction (routeOpts, schemaSerializerCode) { + t.assert.deepStrictEqual(routeOpts, endpointSchema) + t.assert.ok(typeof schemaSerializerCode === 'string') + fs.writeFileSync(path.join(__dirname, '/fjs-generated.js'), schemaSerializerCode) + generatedFileNames.push('/fjs-generated.js') + t.assert.ok('stored the serializer function') + } + }) + + const compiler = factory(schemaMap) + compiler(endpointSchema) + t.assert.ok('compiled the endpoint schema') + + t.test('usage standalone code', t => { + t.plan(3) + const standaloneSerializer = require('./fjs-generated') + t.assert.ok(standaloneSerializer) + + const valid = standaloneSerializer({ hello: 'world' }) + t.assert.deepStrictEqual(valid, JSON.stringify({ hello: 'world' })) + + const invalid = standaloneSerializer({ hello: [] }) + t.assert.deepStrictEqual(invalid, '{"hello":""}') + }) + }) + + t.test('fastify integration - writeMode', async t => { + t.plan(4) + + const factory = FjsStandaloneCompiler({ + readMode: false, + storeFunction (routeOpts, schemaSerializationCode) { + const fileName = generateFileName(routeOpts) + t.assert.ok(routeOpts) + fs.writeFileSync(path.join(__dirname, fileName), schemaSerializationCode) + t.assert.ok(`stored the serializer function ${fileName}`) + }, + restoreFunction () { + t.fail('write mode ON') + } + }) + + const app = buildApp(factory) + await app.ready() + }) + + await t.test('fastify integration - writeMode forces standalone', async t => { + t.plan(4) + + const factory = FjsStandaloneCompiler({ + readMode: false, + storeFunction (routeOpts, schemaSerializationCode) { + const fileName = generateFileName(routeOpts) + t.assert.ok(routeOpts) + fs.writeFileSync(path.join(__dirname, fileName), schemaSerializationCode) + t.assert.ok(`stored the serializer function ${fileName}`) + }, + restoreFunction () { + t.fail('write mode ON') + } + }) + + const app = buildApp(factory, { + mode: 'not-standalone', + rounding: 'ceil' + }) + + await app.ready() + }) + + await t.test('fastify integration - readMode', async t => { + t.plan(6) + + const factory = FjsStandaloneCompiler({ + readMode: true, + storeFunction () { + t.fail('read mode ON') + }, + restoreFunction (routeOpts) { + const fileName = generateFileName(routeOpts) + t.assert.ok(`restore the serializer function ${fileName}}`) + return require(path.join(__dirname, fileName)) + } + }) + + const app = buildApp(factory) + await app.ready() + + let res = await app.inject({ + url: '/foo', + method: 'POST' + }) + t.assert.equal(res.statusCode, 200) + t.assert.equal(res.payload, JSON.stringify({ hello: 'world' })) + + res = await app.inject({ + url: '/bar?lang=it', + method: 'GET' + }) + t.assert.equal(res.statusCode, 200) + t.assert.equal(res.payload, JSON.stringify({ lang: 'en' })) + }) + + function buildApp (factory, serializerOpts) { + const app = fastify({ + exposeHeadRoutes: false, + jsonShorthand: false, + schemaController: { + compilersFactory: { + buildSerializer: factory + } + }, + serializerOpts + }) + + app.addSchema({ + $id: 'urn:schema:foo', + type: 'object', + properties: { + name: { type: 'string' }, + id: { type: 'integer' } + } + }) + + app.post('/foo', { + schema: { + response: { + 200: { + $id: 'urn:schema:response', + type: 'object', + properties: { + hello: { $ref: 'urn:schema:foo#/properties/name' } + } + } + } + } + }, () => { return { hello: 'world' } }) + + app.get('/bar', { + schema: { + response: { + 200: { + $id: 'urn:schema:response:bar', + type: 'object', + properties: { + lang: { type: 'string', enum: ['it', 'en'] } + } + } + } + } + }, () => { return { lang: 'en' } }) + + return app + } +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/types/index.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/types/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..05461351432d028c25868f7ab46f322548cd28ca --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/types/index.d.ts @@ -0,0 +1,41 @@ +import { Options } from 'fast-json-stringify' + +type FastJsonStringifyFactory = () => SerializerSelector.SerializerFactory + +declare namespace SerializerSelector { + export type SerializerFactory = ( + externalSchemas?: unknown, + options?: Options + ) => SerializerCompiler + + export type SerializerCompiler = (routeDef: RouteDefinition) => Serializer + export type Serializer = (doc: any) => string + + export type RouteDefinition = { + method: string; + url: string; + httpStatus: string; + schema?: unknown; + } + + export type StandaloneOptions = StandaloneOptionsReadModeOn | StandaloneOptionsReadModeOff + + export type StandaloneOptionsReadModeOn = { + readMode: true; + restoreFunction?(opts: RouteDefinition): Serializer; + } + + export type StandaloneOptionsReadModeOff = { + readMode?: false | undefined; + storeFunction?(opts: RouteDefinition, schemaSerializationCode: string): void; + } + + export type { Options } + export const SerializerSelector: FastJsonStringifyFactory + export function StandaloneSerializer (options: StandaloneOptions): SerializerFactory + + export { SerializerSelector as default } +} + +declare function SerializerSelector (...params: Parameters): ReturnType +export = SerializerSelector diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/types/index.test-d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/types/index.test-d.ts new file mode 100644 index 0000000000000000000000000000000000000000..018759aadc42c09b683479fbbfc370d0dcb4b119 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/types/index.test-d.ts @@ -0,0 +1,142 @@ +import { expectAssignable, expectError, expectType } from 'tsd' +import SerializerSelector, { + RouteDefinition, + Serializer, + SerializerCompiler, + SerializerFactory, + SerializerSelector as SerializerSelectorNamed, + StandaloneSerializer, +} from '..' + +/** + * SerializerSelector + */ + +{ + const compiler = SerializerSelector() + expectType(compiler) +} + +{ + const compiler = SerializerSelectorNamed() + expectType(compiler) +} + +{ + const sampleSchema = { + $id: 'example1', + type: 'object', + properties: { + name: { type: 'string' } + } + } + + const externalSchemas1 = {} + + const factory = SerializerSelector() + expectType(factory) + const compiler = factory(externalSchemas1, {}) + expectType(compiler) + const serializeFunc = compiler({ schema: sampleSchema, method: '', url: '', httpStatus: '' }) + expectType(serializeFunc) + + expectType(serializeFunc({ name: 'hello' })) +} + +/** + * StandaloneSerializer + */ + +const reader = StandaloneSerializer({ + readMode: true, + restoreFunction: (route: RouteDefinition) => { + expectAssignable(route) + return {} as Serializer + }, +}) +expectType(reader) + +const writer = StandaloneSerializer({ + readMode: false, + storeFunction: (route: RouteDefinition, code: string) => { + expectAssignable(route) + expectAssignable(code) + }, +}) +expectType(writer) + +{ + const base = { + $id: 'urn:schema:base', + definitions: { + hello: { type: 'string' } + }, + type: 'object', + properties: { + hello: { $ref: '#/definitions/hello' } + } + } + + const refSchema = { + $id: 'urn:schema:ref', + type: 'object', + properties: { + hello: { $ref: 'urn:schema:base#/definitions/hello' } + } + } + + const endpointSchema = { + method: '', + url: '', + httpStatus: '', + schema: { + $id: 'urn:schema:endpoint', + $ref: 'urn:schema:ref' + } + } + + const schemaMap = { + [base.$id]: base, + [refSchema.$id]: refSchema + } + + expectError(StandaloneSerializer({ + readMode: true, + storeFunction () { } + })) + expectError(StandaloneSerializer({ + readMode: false, + restoreFunction () {} + })) + expectError(StandaloneSerializer({ + restoreFunction () {} + })) + + expectType(StandaloneSerializer({ + storeFunction (routeOpts, schemaSerializerCode) { + expectType(routeOpts) + expectType(schemaSerializerCode) + } + })) + + expectType(StandaloneSerializer({ + readMode: true, + restoreFunction (routeOpts) { + expectType(routeOpts) + return {} as Serializer + } + })) + + const factory = StandaloneSerializer({ + readMode: false, + storeFunction (routeOpts, schemaSerializerCode) { + expectType(routeOpts) + expectType(schemaSerializerCode) + } + }) + expectType(factory) + + const compiler = factory(schemaMap) + expectType(compiler) + expectType(compiler(endpointSchema)) +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/forwarded/LICENSE b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/forwarded/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..acf869fa53b0fa8f652e4b451c1e76180e19757d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/forwarded/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2021 Fastify collaborators +Copyright (c) 2014-2017 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/forwarded/README.md b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/forwarded/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3995c93ffd32b04d12a1d525a4ef17d4836e254a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/forwarded/README.md @@ -0,0 +1,43 @@ +# @fastify/forwarded + +![CI](https://github.com/fastify/forwarded/workflows/CI/badge.svg) +[![NPM version](https://img.shields.io/npm/v/@fastify/forwarded.svg?style=flat)](https://www.npmjs.com/package/@fastify/forwarded) +[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](https://standardjs.com/) + +Parse HTTP X-Forwarded-For header. + +Updated version of the great https://github.com/jshttp/forwarded. +Implements https://github.com/jshttp/forwarded/pull/9. + +## Installation + +```sh +$ npm i @fastify/forwarded +``` + +## API + +```js +var forwarded = require('@fastify/forwarded') +``` + +### forwarded(req) + +```js +var addresses = forwarded(req) +``` + +Parse the `X-Forwarded-For` header from the request. Returns an array +of the addresses, including the socket address for the `req`, in reverse +order (i.e. index `0` is the socket address and the last index is the +furthest address, typically the end-user). + +## Testing + +```sh +$ npm test +``` + +## License + +[MIT](LICENSE) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/forwarded/index.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/forwarded/index.js new file mode 100644 index 0000000000000000000000000000000000000000..9b7285faefaf81c8d1e2bba35d91bff5147a467f --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/forwarded/index.js @@ -0,0 +1,59 @@ +/*! + * forwarded + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Get all addresses in the request used in the `X-Forwarded-For` header. + */ +function forwarded (req) { + if (!req) { + throw new TypeError('argument req is required') + } + + const header = req.headers['x-forwarded-for'] + const socketAddr = req.socket.remoteAddress + + if (!header || typeof header !== 'string') { + return [socketAddr] + } else if (header.indexOf(',') === -1) { + const remote = header.trim() + return (remote.length) + ? [socketAddr, remote] + : [socketAddr] + } else { + return parse(header, socketAddr) + } +} + +function parse (header, socketAddr) { + const result = [socketAddr] + + let end = header.length + let start = end + let char + let i + + for (i = end - 1; i >= 0; --i) { + char = header[i] + if (char === ' ') { + (start === end) && (start = end = i) + } else if (char === ',') { + (start !== end) && result.push(header.slice(start, end)) + start = end = i + } else { + start = i + } + } + + (start !== end) && result.push(header.substring(start, end)) + + return result +} + +module.exports = forwarded +module.exports.default = forwarded +module.exports.forwarded = forwarded diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/forwarded/package.json b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/forwarded/package.json new file mode 100644 index 0000000000000000000000000000000000000000..67666322ba31d525b1e183f5d8664ea715ba6fe0 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/forwarded/package.json @@ -0,0 +1,48 @@ +{ + "name": "@fastify/forwarded", + "description": "Parse HTTP X-Forwarded-For header", + "version": "3.0.0", + "type": "commonjs", + "contributors": [ + "Matteo Collina ", + "Douglas Christopher Wilson ", + "Aras Abbasi string[] + +declare namespace forwarded { + export const forwarded: Forwarded + export { forwarded as default } +} + +/** + * Get all addresses in the request used in the `X-Forwarded-For` header. + */ +declare function forwarded(...params: Parameters): ReturnType +export = forwarded diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/.gitattributes b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..83beb313de2ba032f48fb415afbdb1e9d22536b9 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/.gitattributes @@ -0,0 +1,2 @@ +# Set default behavior to automatically convert line endings +* text=auto eol=lf \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/.github/dependabot.yml b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..dfa7fa6cba823110c8476a4b4ebcc07cfda12535 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/.github/dependabot.yml @@ -0,0 +1,13 @@ +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "monthly" + open-pull-requests-limit: 10 + + - package-ecosystem: "npm" + directory: "/" + schedule: + interval: "weekly" + open-pull-requests-limit: 10 diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/.github/workflows/ci.yml b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/.github/workflows/ci.yml new file mode 100644 index 0000000000000000000000000000000000000000..3aa613009753c4be21cc8f212f1495d70427f133 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/.github/workflows/ci.yml @@ -0,0 +1,23 @@ +name: CI + +on: + push: + branches: + - main + - master + - next + - 'v*' + paths-ignore: + - 'docs/**' + - '*.md' + pull_request: + paths-ignore: + - 'docs/**' + - '*.md' + +jobs: + test: + uses: fastify/workflows/.github/workflows/plugins-ci.yml@v5 + with: + license-check: true + lint: true diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/LICENSE b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..226c5a9dd06e93d27c1ff8f2eda25fa76fa093fb --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Fastify + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/README.md b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b5120cc41f416187f92770881b5822535be4cc90 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/README.md @@ -0,0 +1,119 @@ +# @fastify/merge-json-schemas + +[![CI](https://github.com/fastify/merge-json-schemas/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/fastify/merge-json-schemas/actions/workflows/ci.yml) +[![npm version](https://img.shields.io/npm/v/@fastify/merge-json-schemas)](https://www.npmjs.com/package/@fastify/merge-json-schemas) +[![neostandard javascript style](https://img.shields.io/badge/code_style-neostandard-brightgreen?style=flat)](https://github.com/neostandard/neostandard) + +__merge-json-schemas__ is a JavaScript library that builds a logical product (AND) for multiple [JSON schemas](https://json-schema.org/draft/2020-12/json-schema-core#name-introduction). + +- [Installation](#installation) +- [Usage](#usage) +- [API](#api) + - [mergeSchemas(schemas, options)](#mergeschemasschemas-options) + - [resolvers](#resolvers) + - [defaultResolver](#defaultresolver) +- [License](#license) + + + +## Installation + +```bash +npm i @fastify/merge-json-schemas +``` + + + +## Usage + +```javascript +const assert = require('node:assert') +const { mergeSchemas } = require('@fastify/merge-json-schemas'); + +const schema1 = { + $id: 'schema1', + type: 'object', + properties: { + foo: { type: 'string', enum: ['foo1', 'foo2'] }, + bar: { type: 'string', minLength: 3 } + } +} + +const schema2 = { + $id: 'schema1', + type: 'object', + properties: { + foo: { type: 'string', enum: ['foo1', 'foo3'] }, + bar: { type: 'string', minLength: 5 } + }, + required: ['foo'] +} + +const mergedSchema = mergeSchemas([schema1, schema2]) +assert.deepStrictEqual(mergedSchema, { + $id: 'schema1', + type: 'object', + properties: { + foo: { type: 'string', enum: ['foo1'] }, + bar: { type: 'string', minLength: 5 } + }, + required: ['foo'] +}) +``` + + + +## API + + + +#### mergeSchemas(schemas, options) + +Builds a logical conjunction (AND) of multiple [JSON schemas](https://json-schema.org/draft/2020-12/json-schema-core#name-introduction). + +- `schemas` __\__ - list of JSON schemas to merge +- `options` __\__ - optional options + - `resolvers` __\__ - custom resolvers for JSON schema keywords. Each key is the name of a JSON schema keyword. Each value is a resolver function. See [keywordResolver](#keywordresolver-keyword-values-mergedschema-parentschemas-options) + - `defaultResolver` __\__ - custom default resolver for JSON schema keywords. See [keywordResolver](#keywordresolver-keyword-values-mergedschema-parentschemas-options) + - `onConflict` __\__ - action to take when a conflict is found. Used by the default `defaultResolver`. Default is `throw`. Possible values are: + - `throw` - throws an error multiple different schemas for the same keyword are found + - `ignore` - do nothing if multiple different schemas for the same keyword are found + - `first` - use the value of the first schema if multiple different schemas for the same keyword are found + +#### resolvers + +A list of default resolvers that __merge-json-schema__ uses to merge JSON schemas. You can override the default resolvers by passing a list of custom resolvers in the `options` argument of `mergeSchemas`. See [keywordResolver](#keywordresolver-keyword-values-mergedschema-parentschemas-options). + +#### defaultResolver + +A default resolver that __merge-json-schema__ uses to merge JSON schemas. Default resolver is used when no custom resolver is defined for a JSON schema keyword. By default, the default resolver works as follows: + +- If only one schema contains the keyword, the value of the keyword is used as the merged value +- If multiple schemas contain the exact same value for the keyword, the value of the keyword is used as the merged value +- If multiple schemas contain different values for the keyword, it throws an error + +#### keywordResolver (keyword, values, mergedSchema, parentSchemas, options) + +__merge-json-schema__ uses a set of resolvers to merge JSON schemas. Each resolver is associated with a JSON schema keyword. The resolver is called when the keyword is found in the schemas to merge. The resolver is called with the following arguments: + +- `keyword` __\__ - the name of the keyword to merge +- `values` __\__ - the values of the keyword to merge. The length of the array is equal to the number of schemas to merge. If a schema does not contain the keyword, the value is `undefined` +- `mergedSchema` __\__ - an instance of the merged schema +- `parentSchemas` __\__ - the list of parent schemas +- `options` __\__ - the options passed to `mergeSchemas` + +The resolver must set the merged value of the `keyword` in the `mergedSchema` object. + +__Example:__ resolver for the `minNumber` keyword. + +```javascript +function minNumberResolver (keyword, values, mergedSchema) { + mergedSchema[keyword] = Math.min(...values) +} +``` + + + +## License + +Licensed under [MIT](./LICENSE). diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/eslint.config.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/eslint.config.js new file mode 100644 index 0000000000000000000000000000000000000000..89fd678fe2a82d7fe3be869fffd71b3631c61c6a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/eslint.config.js @@ -0,0 +1,6 @@ +'use strict' + +module.exports = require('neostandard')({ + ignores: require('neostandard').resolveIgnoresFromGitignore(), + ts: true +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/index.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/index.js new file mode 100644 index 0000000000000000000000000000000000000000..74774308f6b9121e243297f53d28272001dd6b3c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/index.js @@ -0,0 +1,357 @@ +'use strict' + +const { dequal: deepEqual } = require('dequal') +const resolvers = require('./lib/resolvers') +const errors = require('./lib/errors') + +const keywordsResolvers = { + $id: resolvers.skip, + type: resolvers.hybridArraysIntersection, + enum: resolvers.arraysIntersection, + minLength: resolvers.maxNumber, + maxLength: resolvers.minNumber, + minimum: resolvers.maxNumber, + maximum: resolvers.minNumber, + multipleOf: resolvers.commonMultiple, + exclusiveMinimum: resolvers.maxNumber, + exclusiveMaximum: resolvers.minNumber, + minItems: resolvers.maxNumber, + maxItems: resolvers.minNumber, + maxProperties: resolvers.minNumber, + minProperties: resolvers.maxNumber, + const: resolvers.allEqual, + default: resolvers.allEqual, + format: resolvers.allEqual, + required: resolvers.arraysUnion, + properties: mergeProperties, + patternProperties: mergeObjects, + additionalProperties: mergeSchemasResolver, + items: mergeItems, + additionalItems: mergeAdditionalItems, + definitions: mergeObjects, + $defs: mergeObjects, + nullable: resolvers.booleanAnd, + oneOf: mergeOneOf, + anyOf: mergeOneOf, + allOf: resolvers.arraysUnion, + not: mergeSchemasResolver, + if: mergeIfThenElseSchemas, + then: resolvers.skip, + else: resolvers.skip, + dependencies: mergeDependencies, + dependentRequired: mergeDependencies, + dependentSchemas: mergeObjects, + propertyNames: mergeSchemasResolver, + uniqueItems: resolvers.booleanOr, + contains: mergeSchemasResolver +} + +function mergeSchemasResolver (keyword, values, mergedSchema, _schemas, options) { + mergedSchema[keyword] = _mergeSchemas(values, options) +} + +function cartesianProduct (arrays) { + let result = [[]] + + for (const array of arrays) { + const temp = [] + for (const x of result) { + for (const y of array) { + temp.push([...x, y]) + } + } + result = temp + } + + return result +} + +function mergeOneOf (keyword, values, mergedSchema, _schemas, options) { + if (values.length === 1) { + mergedSchema[keyword] = values[0] + return + } + + const product = cartesianProduct(values) + const mergedOneOf = [] + for (const combination of product) { + try { + const mergedSchema = _mergeSchemas(combination, options) + if (mergedSchema !== undefined) { + mergedOneOf.push(mergedSchema) + } + } catch (error) { + // If this combination is not valid, we can ignore it. + if (error instanceof errors.MergeError) continue + throw error + } + } + mergedSchema[keyword] = mergedOneOf +} + +function getSchemaForItem (schema, index) { + const { items, additionalItems } = schema + + if (Array.isArray(items)) { + if (index < items.length) { + return items[index] + } + return additionalItems + } + + if (items !== undefined) { + return items + } + + return additionalItems +} + +function mergeItems (keyword, values, mergedSchema, schemas, options) { + let maxArrayItemsLength = 0 + for (const itemsSchema of values) { + if (Array.isArray(itemsSchema)) { + maxArrayItemsLength = Math.max(maxArrayItemsLength, itemsSchema.length) + } + } + + if (maxArrayItemsLength === 0) { + mergedSchema[keyword] = _mergeSchemas(values, options) + return + } + + const mergedItemsSchemas = [] + for (let i = 0; i < maxArrayItemsLength; i++) { + const indexItemSchemas = [] + for (const schema of schemas) { + const itemSchema = getSchemaForItem(schema, i) + if (itemSchema !== undefined) { + indexItemSchemas.push(itemSchema) + } + } + mergedItemsSchemas[i] = _mergeSchemas(indexItemSchemas, options) + } + mergedSchema[keyword] = mergedItemsSchemas +} + +function mergeAdditionalItems (keyword, values, mergedSchema, schemas, options) { + let hasArrayItems = false + for (const schema of schemas) { + if (Array.isArray(schema.items)) { + hasArrayItems = true + break + } + } + + if (!hasArrayItems) { + mergedSchema[keyword] = _mergeSchemas(values, options) + return + } + + const mergedAdditionalItemsSchemas = [] + for (const schema of schemas) { + let additionalItemsSchema = schema.additionalItems + if ( + additionalItemsSchema === undefined && + !Array.isArray(schema.items) + ) { + additionalItemsSchema = schema.items + } + if (additionalItemsSchema !== undefined) { + mergedAdditionalItemsSchemas.push(additionalItemsSchema) + } + } + + mergedSchema[keyword] = _mergeSchemas(mergedAdditionalItemsSchemas, options) +} + +function getSchemaForProperty (schema, propertyName) { + const { properties, patternProperties, additionalProperties } = schema + + if (properties?.[propertyName] !== undefined) { + return properties[propertyName] + } + + for (const pattern of Object.keys(patternProperties ?? {})) { + const regexp = new RegExp(pattern) + if (regexp.test(propertyName)) { + return patternProperties[pattern] + } + } + + return additionalProperties +} + +function mergeProperties (keyword, _values, mergedSchema, schemas, options) { + const foundProperties = {} + for (const currentSchema of schemas) { + const properties = currentSchema.properties ?? {} + for (const propertyName of Object.keys(properties)) { + if (foundProperties[propertyName] !== undefined) continue + + const propertySchema = properties[propertyName] + foundProperties[propertyName] = [propertySchema] + + for (const anotherSchema of schemas) { + if (currentSchema === anotherSchema) continue + + const propertySchema = getSchemaForProperty(anotherSchema, propertyName) + if (propertySchema !== undefined) { + foundProperties[propertyName].push(propertySchema) + } + } + } + } + + const mergedProperties = {} + for (const property of Object.keys(foundProperties)) { + const propertySchemas = foundProperties[property] + mergedProperties[property] = _mergeSchemas(propertySchemas, options) + } + mergedSchema[keyword] = mergedProperties +} + +function mergeObjects (keyword, values, mergedSchema, _schemas, options) { + const objectsProperties = {} + + for (const properties of values) { + for (const propertyName of Object.keys(properties)) { + if (objectsProperties[propertyName] === undefined) { + objectsProperties[propertyName] = [] + } + objectsProperties[propertyName].push(properties[propertyName]) + } + } + + const mergedProperties = {} + for (const propertyName of Object.keys(objectsProperties)) { + const propertySchemas = objectsProperties[propertyName] + const mergedPropertySchema = _mergeSchemas(propertySchemas, options) + mergedProperties[propertyName] = mergedPropertySchema + } + + mergedSchema[keyword] = mergedProperties +} + +function mergeIfThenElseSchemas (_keyword, _values, mergedSchema, schemas, options) { + for (let i = 0; i < schemas.length; i++) { + const subSchema = { + if: schemas[i].if, + then: schemas[i].then, + else: schemas[i].else + } + + if (subSchema.if === undefined) continue + + if (mergedSchema.if === undefined) { + mergedSchema.if = subSchema.if + if (subSchema.then !== undefined) { + mergedSchema.then = subSchema.then + } + if (subSchema.else !== undefined) { + mergedSchema.else = subSchema.else + } + continue + } + + if (mergedSchema.then !== undefined) { + mergedSchema.then = _mergeSchemas([mergedSchema.then, subSchema], options) + } + if (mergedSchema.else !== undefined) { + mergedSchema.else = _mergeSchemas([mergedSchema.else, subSchema], options) + } + } +} + +function mergeDependencies (keyword, values, mergedSchema) { + const mergedDependencies = {} + for (const dependencies of values) { + for (const propertyName of Object.keys(dependencies)) { + if (mergedDependencies[propertyName] === undefined) { + mergedDependencies[propertyName] = [] + } + const mergedPropertyDependencies = mergedDependencies[propertyName] + for (const propertyDependency of dependencies[propertyName]) { + if (!mergedPropertyDependencies.includes(propertyDependency)) { + mergedPropertyDependencies.push(propertyDependency) + } + } + } + } + mergedSchema[keyword] = mergedDependencies +} + +function _mergeSchemas (schemas, options) { + if (schemas.length === 0) return {} + if (schemas.length === 1) return schemas[0] + + const mergedSchema = {} + const keywords = {} + + let allSchemasAreTrue = true + + for (const schema of schemas) { + if (schema === false) return false + if (schema === true) continue + allSchemasAreTrue = false + + for (const keyword of Object.keys(schema)) { + if (keywords[keyword] === undefined) { + keywords[keyword] = [] + } + keywords[keyword].push(schema[keyword]) + } + } + + if (allSchemasAreTrue) return true + + for (const keyword of Object.keys(keywords)) { + const keywordValues = keywords[keyword] + const resolver = options.resolvers[keyword] ?? options.defaultResolver + resolver(keyword, keywordValues, mergedSchema, schemas, options) + } + + return mergedSchema +} + +function defaultResolver (keyword, values, mergedSchema, _schemas, options) { + const onConflict = options.onConflict ?? 'throw' + + if (values.length === 1 || onConflict === 'first') { + mergedSchema[keyword] = values[0] + return + } + + let allValuesEqual = true + for (let i = 1; i < values.length; i++) { + if (!deepEqual(values[i], values[0])) { + allValuesEqual = false + break + } + } + + if (allValuesEqual) { + mergedSchema[keyword] = values[0] + return + } + + if (onConflict === 'throw') { + throw new errors.ResolverNotFoundError(keyword, values) + } + if (onConflict === 'skip') { + return + } + throw new errors.InvalidOnConflictOptionError(onConflict) +} + +function mergeSchemas (schemas, options = {}) { + if (options.defaultResolver === undefined) { + options.defaultResolver = defaultResolver + } + + options.resolvers = { ...keywordsResolvers, ...options.resolvers } + + const mergedSchema = _mergeSchemas(schemas, options) + return mergedSchema +} + +module.exports = { mergeSchemas, keywordsResolvers, defaultResolver, ...errors } diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/lib/errors.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/lib/errors.js new file mode 100644 index 0000000000000000000000000000000000000000..0a14792e73e87a7289de5bf5452b5751de562a80 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/lib/errors.js @@ -0,0 +1,36 @@ +'use strict' + +class MergeError extends Error { + constructor (keyword, schemas) { + super() + this.name = 'JsonSchemaMergeError' + this.code = 'JSON_SCHEMA_MERGE_ERROR' + this.message = `Failed to merge "${keyword}" keyword schemas.` + this.schemas = schemas + } +} + +class ResolverNotFoundError extends Error { + constructor (keyword, schemas) { + super() + this.name = 'JsonSchemaMergeError' + this.code = 'JSON_SCHEMA_MERGE_ERROR' + this.message = `Resolver for "${keyword}" keyword not found.` + this.schemas = schemas + } +} + +class InvalidOnConflictOptionError extends Error { + constructor (onConflict) { + super() + this.name = 'JsonSchemaMergeError' + this.code = 'JSON_SCHEMA_MERGE_ERROR' + this.message = `Invalid "onConflict" option: "${onConflict}".` + } +} + +module.exports = { + MergeError, + ResolverNotFoundError, + InvalidOnConflictOptionError +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/lib/resolvers.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/lib/resolvers.js new file mode 100644 index 0000000000000000000000000000000000000000..4458838ed7040c8e98f293937e0ddc702203b2b6 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/lib/resolvers.js @@ -0,0 +1,127 @@ +'use strict' + +const { dequal: deepEqual } = require('dequal') +const { MergeError } = require('./errors') + +function _arraysIntersection (arrays) { + let intersection = arrays[0] + for (let i = 1; i < arrays.length; i++) { + intersection = intersection.filter( + value => arrays[i].includes(value) + ) + } + return intersection +} + +function arraysIntersection (keyword, values, mergedSchema) { + const intersection = _arraysIntersection(values) + if (intersection.length === 0) { + throw new MergeError(keyword, values) + } + mergedSchema[keyword] = intersection +} + +function hybridArraysIntersection (keyword, values, mergedSchema) { + for (let i = 0; i < values.length; i++) { + if (!Array.isArray(values[i])) { + values[i] = [values[i]] + } + } + + const intersection = _arraysIntersection(values) + if (intersection.length === 0) { + throw new MergeError(keyword, values) + } + + if (intersection.length === 1) { + mergedSchema[keyword] = intersection[0] + } else { + mergedSchema[keyword] = intersection + } +} + +function arraysUnion (keyword, values, mergedSchema) { + const union = [] + + for (const array of values) { + for (const value of array) { + if (!union.includes(value)) { + union.push(value) + } + } + } + + mergedSchema[keyword] = union +} + +function minNumber (keyword, values, mergedSchema) { + mergedSchema[keyword] = Math.min(...values) +} + +function maxNumber (keyword, values, mergedSchema) { + mergedSchema[keyword] = Math.max(...values) +} + +function commonMultiple (keyword, values, mergedSchema) { + const gcd = (a, b) => (!b ? a : gcd(b, a % b)) + const lcm = (a, b) => (a * b) / gcd(a, b) + + let scale = 1 + for (const value of values) { + while (value * scale % 1 !== 0) { + scale *= 10 + } + } + + let multiple = values[0] * scale + for (const value of values) { + multiple = lcm(multiple, value * scale) + } + + mergedSchema[keyword] = multiple / scale +} + +function allEqual (keyword, values, mergedSchema) { + const firstValue = values[0] + for (let i = 1; i < values.length; i++) { + if (!deepEqual(values[i], firstValue)) { + throw new MergeError(keyword, values) + } + } + mergedSchema[keyword] = firstValue +} + +function skip () {} + +function booleanAnd (keyword, values, mergedSchema) { + for (const value of values) { + if (value === false) { + mergedSchema[keyword] = false + return + } + } + mergedSchema[keyword] = true +} + +function booleanOr (keyword, values, mergedSchema) { + for (const value of values) { + if (value === true) { + mergedSchema[keyword] = true + return + } + } + mergedSchema[keyword] = false +} + +module.exports = { + arraysIntersection, + hybridArraysIntersection, + arraysUnion, + minNumber, + maxNumber, + commonMultiple, + allEqual, + booleanAnd, + booleanOr, + skip +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/package.json b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/package.json new file mode 100644 index 0000000000000000000000000000000000000000..01c745c28910e3fca656d992af0749df091806ac --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/package.json @@ -0,0 +1,67 @@ +{ + "name": "@fastify/merge-json-schemas", + "version": "0.2.1", + "description": "Builds a logical conjunction (AND) of multiple JSON schemas", + "main": "index.js", + "type": "commonjs", + "types": "types/index.d.ts", + "scripts": { + "lint": "eslint", + "lint:fix": "eslint --fix", + "test": "npm run test:unit && npm run test:types", + "test:unit": "c8 --100 node --test", + "test:types": "tsd" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/fastify/merge-json-schemas.git" + }, + "keywords": [ + "json", + "schema", + "merge", + "allOf" + ], + "author": "Ivan Tymoshenko ", + "contributors": [ + { + "name": "Matteo Collina", + "email": "hello@matteocollina.com" + }, + { + "name": "Frazer Smith", + "email": "frazer.dev@icloud.com", + "url": "https://github.com/fdawgs" + }, + { + "name": "Gürgün Dayıoğlu", + "email": "hey@gurgun.day", + "url": "https://heyhey.to/G" + } + ], + "license": "MIT", + "bugs": { + "url": "https://github.com/fastify/merge-json-schemas/issues" + }, + "homepage": "https://github.com/fastify/merge-json-schemas#readme", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "devDependencies": { + "@fastify/pre-commit": "^2.1.0", + "c8": "^10.1.3", + "eslint": "^9.17.0", + "neostandard": "^0.12.0", + "tsd": "^0.31.2" + }, + "dependencies": { + "dequal": "^2.0.3" + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/additional-items.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/additional-items.test.js new file mode 100644 index 0000000000000000000000000000000000000000..707450f607b27fb399c5bd565293deb62a069f90 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/additional-items.test.js @@ -0,0 +1,164 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and additionalItems = false keyword', () => { + const schema1 = { type: 'array' } + const schema2 = { + type: 'array', + additionalItems: false + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'array', + additionalItems: false + }) +}) + +test('should merge two schemas with boolean additionalItems', () => { + const schema1 = { + type: 'array', + additionalItems: true + } + const schema2 = { + type: 'array', + additionalItems: false + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'array', + additionalItems: false + }) +}) + +test('should merge additionalItems schema with false value', () => { + const schema1 = { + type: 'array', + additionalItems: { + type: 'string' + } + } + const schema2 = { + type: 'array', + additionalItems: false + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'array', + additionalItems: false + }) +}) + +test('should merge additionalItems schema with true value', () => { + const schema1 = { + type: 'array', + additionalItems: { + type: 'string' + } + } + const schema2 = { + type: 'array', + additionalItems: true + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'array', + additionalItems: { + type: 'string' + } + }) +}) + +test('should merge two additionalItems schemas', () => { + const schema1 = { + type: 'array', + additionalItems: { + type: 'string' + } + } + const schema2 = { + type: 'array', + additionalItems: { + type: 'string', minLength: 1 + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'array', + additionalItems: { + type: 'string', minLength: 1 + } + }) +}) + +test('should merge additionalItems with items array', () => { + const schema1 = { + type: 'array', + items: [ + { type: 'string', const: 'foo1' }, + { type: 'string', const: 'foo2' }, + { type: 'string', const: 'foo3' } + ] + } + const schema2 = { + type: 'array', + additionalItems: { + type: 'string', minLength: 42 + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'array', + items: [ + { type: 'string', const: 'foo1', minLength: 42 }, + { type: 'string', const: 'foo2', minLength: 42 }, + { type: 'string', const: 'foo3', minLength: 42 } + ], + additionalItems: { + type: 'string', minLength: 42 + } + }) +}) + +test('should merge items array and additionalItems with items array', () => { + const schema1 = { + type: 'array', + items: [ + { type: 'string', const: 'foo1' }, + { type: 'string', const: 'foo2' }, + { type: 'string', const: 'foo3' } + ] + } + const schema2 = { + type: 'array', + items: [ + { type: 'string', minLength: 1 }, + { type: 'string', minLength: 2 } + ], + additionalItems: { + type: 'string', minLength: 3 + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'array', + items: [ + { type: 'string', const: 'foo1', minLength: 1 }, + { type: 'string', const: 'foo2', minLength: 2 }, + { type: 'string', const: 'foo3', minLength: 3 } + ], + additionalItems: { + type: 'string', minLength: 3 + } + }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/additional-properties.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/additional-properties.test.js new file mode 100644 index 0000000000000000000000000000000000000000..e4304ac04074ce5aa4bdceb544cba911a5f7ca94 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/additional-properties.test.js @@ -0,0 +1,129 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and additionalProperties=false keyword', () => { + const schema1 = { type: 'object' } + const schema2 = { + type: 'object', + additionalProperties: false + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + additionalProperties: false + }) +}) + +test('should merge two schemas with boolean additionalProperties', () => { + const schema1 = { + type: 'object', + additionalProperties: true + } + const schema2 = { + type: 'object', + additionalProperties: false + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + additionalProperties: false + }) +}) + +test('should merge additionalProperties schema with false value', () => { + const schema1 = { + type: 'object', + additionalProperties: { + type: 'string' + } + } + const schema2 = { + type: 'object', + additionalProperties: false + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + additionalProperties: false + }) +}) + +test('should merge additionalProperties schema with true value', () => { + const schema1 = { + type: 'object', + additionalProperties: { + type: 'string' + } + } + const schema2 = { + type: 'object', + additionalProperties: true + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + additionalProperties: { + type: 'string' + } + }) +}) + +test('should merge two additionalProperties schemas', () => { + const schema1 = { + type: 'object', + additionalProperties: { + type: 'string' + } + } + const schema2 = { + type: 'object', + additionalProperties: { + type: 'string', minLength: 1 + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + additionalProperties: { + type: 'string', minLength: 1 + } + }) +}) + +test('should merge two additionalProperties and properties schemas', () => { + const schema1 = { + type: 'object', + additionalProperties: { + type: 'string' + } + } + const schema2 = { + type: 'object', + properties: { + foo: { type: ['string', 'number'] } + }, + additionalProperties: { + type: 'string', minLength: 1 + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + properties: { + foo: { type: 'string' } + }, + additionalProperties: { + type: 'string', minLength: 1 + } + }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/all-of.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/all-of.test.js new file mode 100644 index 0000000000000000000000000000000000000000..2b2acef7eb0d040b4af2cfbcb6050cf3710c7038 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/all-of.test.js @@ -0,0 +1,43 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and allOf keyword', () => { + const schema1 = {} + const schema2 = { + allOf: [ + { type: 'string', const: 'foo' } + ] + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + allOf: [ + { type: 'string', const: 'foo' } + ] + }) +}) + +test('should merge schemas with allOfs schemas', () => { + const schema1 = { + allOf: [ + { type: 'number', minimum: 0 } + ] + } + const schema2 = { + allOf: [ + { type: 'string', const: 'foo' } + ] + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + allOf: [ + { type: 'number', minimum: 0 }, + { type: 'string', const: 'foo' } + ] + }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/any-of.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/any-of.test.js new file mode 100644 index 0000000000000000000000000000000000000000..98b3a21e71db3f47847e6dc7cef143dff0504cae --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/any-of.test.js @@ -0,0 +1,81 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and anyOf keyword', () => { + const schema1 = {} + const schema2 = { + anyOf: [ + { type: 'string', const: 'foo' } + ] + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + anyOf: [ + { type: 'string', const: 'foo' } + ] + }) +}) + +test('should merge two schemas with anyOfs schemas', () => { + const schema1 = { + anyOf: [ + { type: 'string', enum: ['foo1', 'foo2', 'foo3'] }, + { type: 'string', enum: ['foo3', 'foo4', 'foo5'] } + ] + } + const schema2 = { + anyOf: [ + { type: 'string', enum: ['foo2', 'foo3', 'foo4'] }, + { type: 'string', enum: ['foo3', 'foo6', 'foo7'] } + ] + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + anyOf: [ + { type: 'string', enum: ['foo2', 'foo3'] }, + { type: 'string', enum: ['foo3'] }, + { type: 'string', enum: ['foo3', 'foo4'] }, + { type: 'string', enum: ['foo3'] } + ] + }) +}) + +test('should merge three schemas with anyOfs schemas', () => { + const schema1 = { + anyOf: [ + { type: 'string', enum: ['foo1', 'foo2', 'foo3', 'foo4'] }, + { type: 'string', enum: ['foo3', 'foo4', 'foo5', 'foo7'] } + ] + } + const schema2 = { + anyOf: [ + { type: 'string', enum: ['foo2', 'foo3', 'foo4', 'foo5'] }, + { type: 'string', enum: ['foo3', 'foo6', 'foo7', 'foo8'] } + ] + } + + const schema3 = { + anyOf: [ + { type: 'string', enum: ['foo1', 'foo3', 'foo5', 'foo7'] }, + { type: 'string', enum: ['foo2', 'foo4', 'foo6', 'foo8'] } + ] + } + + const mergedSchema = mergeSchemas([schema1, schema2, schema3], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + anyOf: [ + { type: 'string', enum: ['foo3'] }, + { type: 'string', enum: ['foo2', 'foo4'] }, + { type: 'string', enum: ['foo3'] }, + { type: 'string', enum: ['foo3', 'foo5'] }, + { type: 'string', enum: ['foo4'] }, + { type: 'string', enum: ['foo3', 'foo7'] } + ] + }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/const.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/const.test.js new file mode 100644 index 0000000000000000000000000000000000000000..1b8cfe0dda01ea0380edf8cc99f9e1222e8fd885 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/const.test.js @@ -0,0 +1,58 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and string const keyword', () => { + const schema1 = { type: 'string' } + const schema2 = { type: 'string', const: 'foo' } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string', const: 'foo' }) +}) + +test('should merge equal string const keywords', () => { + const schema1 = { type: 'string', const: 'foo' } + const schema2 = { type: 'string', const: 'foo' } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string', const: 'foo' }) +}) + +test('should merge equal object const keywords', () => { + const schema1 = { type: 'string', const: { foo: 'bar' } } + const schema2 = { type: 'string', const: { foo: 'bar' } } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string', const: { foo: 'bar' } }) +}) + +test('should throw an error if const string values are different', () => { + const schema1 = { type: 'string', const: 'foo' } + const schema2 = { type: 'string', const: 'bar' } + + assert.throws(() => { + mergeSchemas([schema1, schema2], { defaultResolver }) + }, { + name: 'JsonSchemaMergeError', + code: 'JSON_SCHEMA_MERGE_ERROR', + message: 'Failed to merge "const" keyword schemas.', + schemas: ['foo', 'bar'] + }) +}) + +test('should throw an error if const object values are different', () => { + const schema1 = { type: 'object', const: { foo: 'bar' } } + const schema2 = { type: 'object', const: { foo: 'baz' } } + + assert.throws(() => { + mergeSchemas([schema1, schema2], { defaultResolver }) + }, { + name: 'JsonSchemaMergeError', + code: 'JSON_SCHEMA_MERGE_ERROR', + message: 'Failed to merge "const" keyword schemas.', + schemas: [{ foo: 'bar' }, { foo: 'baz' }] + }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/contains.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/contains.test.js new file mode 100644 index 0000000000000000000000000000000000000000..66efb05b28804c50d20f683c4d6dc0e929bf9fcd --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/contains.test.js @@ -0,0 +1,55 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and contains keyword', () => { + const schema1 = {} + const schema2 = { + type: 'array', + contains: { + type: 'integer', + minimum: 5 + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'array', + contains: { + type: 'integer', + minimum: 5 + } + }) +}) + +test('should merge two contains keyword schemas', () => { + const schema1 = { + type: 'array', + contains: { + type: 'integer', + minimum: 5, + maximum: 14 + } + } + const schema2 = { + type: 'array', + contains: { + type: 'integer', + minimum: 9, + maximum: 10 + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'array', + contains: { + type: 'integer', + minimum: 9, + maximum: 10 + } + }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/custom-resolvers.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/custom-resolvers.test.js new file mode 100644 index 0000000000000000000000000000000000000000..20791881f681bb6d04c6b30f4c8a921035aae474 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/custom-resolvers.test.js @@ -0,0 +1,50 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should use a custom resolver instead of default one', () => { + const schema1 = { type: 'string' } + const schema2 = { type: 'number' } + + const mergedSchema = mergeSchemas( + [schema1, schema2], + { + resolvers: { + type: (keyword, values, mergedSchema, schemas) => { + assert.strictEqual(keyword, 'type') + assert.deepStrictEqual(values, ['string', 'number']) + assert.deepStrictEqual(schemas, [schema1, schema2]) + + mergedSchema[keyword] = 'custom-type' + } + }, + defaultResolver + } + ) + assert.deepStrictEqual(mergedSchema, { type: 'custom-type' }) +}) + +test('should use a custom resolver for unknown keyword', () => { + const schema1 = { customKeyword: 'string' } + const schema2 = { customKeyword: 'number' } + + const mergedSchema = mergeSchemas( + [schema1, schema2], + { + resolvers: { + customKeyword: (keyword, values, mergedSchema, schemas) => { + assert.strictEqual(keyword, 'customKeyword') + assert.deepStrictEqual(values, ['string', 'number']) + assert.deepStrictEqual(schemas, [schema1, schema2]) + + mergedSchema[keyword] = 'custom-type' + } + }, + defaultResolver + } + ) + assert.deepStrictEqual(mergedSchema, { customKeyword: 'custom-type' }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/default-resolver.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/default-resolver.test.js new file mode 100644 index 0000000000000000000000000000000000000000..186a13aa4141f18ee01e1dd1f8bd9053abc7ce33 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/default-resolver.test.js @@ -0,0 +1,111 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') + +test('should merge an unknown keyword with an empty schema', () => { + const schema1 = {} + const schema2 = { customKeyword: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2]) + assert.deepStrictEqual(mergedSchema, { customKeyword: 42 }) +}) + +test('should merge two equal unknown keywords', () => { + const schema1 = { customKeyword: 42 } + const schema2 = { customKeyword: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2]) + assert.deepStrictEqual(mergedSchema, { customKeyword: 42 }) +}) + +test('should merge two equal unknown object keywords', () => { + const schema1 = { type: 'string', customKeyword: { foo: 'bar' } } + const schema2 = { type: 'string', customKeyword: { foo: 'bar' } } + + const mergedSchema = mergeSchemas([schema1, schema2]) + assert.deepStrictEqual(mergedSchema, { + type: 'string', + customKeyword: { foo: 'bar' } + }) +}) + +test('should use custom defaultResolver if passed', () => { + const schema1 = { type: 'string', customKeyword: 42 } + const schema2 = { type: 'string', customKeyword: 43 } + + const mergedSchema = mergeSchemas( + [schema1, schema2], + { + defaultResolver: (keyword, values, mergedSchema, schemas) => { + assert.strictEqual(keyword, 'customKeyword') + assert.deepStrictEqual(values, [42, 43]) + assert.deepStrictEqual(schemas, [schema1, schema2]) + + mergedSchema.customKeyword = 'custom-value-42' + } + } + ) + assert.deepStrictEqual(mergedSchema, { + type: 'string', + customKeyword: 'custom-value-42' + }) +}) + +test('should trow an error when merging two different unknown keywords', () => { + const schema1 = { customKeyword: 42 } + const schema2 = { customKeyword: 43 } + + assert.throws(() => { + mergeSchemas([schema1, schema2]) + }, { + name: 'JsonSchemaMergeError', + code: 'JSON_SCHEMA_MERGE_ERROR', + message: 'Resolver for "customKeyword" keyword not found.', + schemas: [42, 43] + }) +}) + +test('should trow an error when merging two different unknown keywords with onConflict = throw', () => { + const schema1 = { customKeyword: 42 } + const schema2 = { customKeyword: 43 } + + assert.throws(() => { + mergeSchemas([schema1, schema2], { onConflict: 'throw' }) + }, { + name: 'JsonSchemaMergeError', + code: 'JSON_SCHEMA_MERGE_ERROR', + message: 'Resolver for "customKeyword" keyword not found.', + schemas: [42, 43] + }) +}) + +test('should skip the keyword schemas if onConflict = skip', () => { + const schema1 = { customKeyword: 42 } + const schema2 = { customKeyword: 43 } + + const mergedSchema = mergeSchemas([schema1, schema2], { onConflict: 'skip' }) + assert.deepStrictEqual(mergedSchema, {}) +}) + +test('should pick first schema if onConflict = first', () => { + const schema1 = { customKeyword: 42 } + const schema2 = { customKeyword: 43 } + + const mergedSchema = mergeSchemas([schema1, schema2], { onConflict: 'first' }) + assert.deepStrictEqual(mergedSchema, { customKeyword: 42 }) +}) + +test('should throw an error if pass wrong onConflict value', () => { + const schema1 = { customKeyword: 42 } + const schema2 = { customKeyword: 43 } + + assert.throws(() => { + mergeSchemas([schema1, schema2], { onConflict: 'foo' }) + }, { + name: 'JsonSchemaMergeError', + code: 'JSON_SCHEMA_MERGE_ERROR', + message: 'Invalid "onConflict" option: "foo".' + }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/default.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/default.test.js new file mode 100644 index 0000000000000000000000000000000000000000..a87cbcc51b87ce32e31b86b1c75410b88e9e3bf5 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/default.test.js @@ -0,0 +1,50 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and string default keyword', () => { + const schema1 = { type: 'string' } + const schema2 = { type: 'string', default: 'foo' } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string', default: 'foo' }) +}) + +test('should merge equal string default keywords', () => { + const schema1 = { type: 'string', default: 'foo' } + const schema2 = { type: 'string', default: 'foo' } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string', default: 'foo' }) +}) + +test('should throw an error if default string values are different', () => { + const schema1 = { type: 'string', default: 'foo' } + const schema2 = { type: 'string', default: 'bar' } + + assert.throws(() => { + mergeSchemas([schema1, schema2], { defaultResolver }) + }, { + name: 'JsonSchemaMergeError', + code: 'JSON_SCHEMA_MERGE_ERROR', + message: 'Failed to merge "default" keyword schemas.', + schemas: ['foo', 'bar'] + }) +}) + +test('should throw an error if default object values are different', () => { + const schema1 = { type: 'object', default: { foo: 'bar' } } + const schema2 = { type: 'object', default: { foo: 'baz' } } + + assert.throws(() => { + mergeSchemas([schema1, schema2], { defaultResolver }) + }, { + name: 'JsonSchemaMergeError', + code: 'JSON_SCHEMA_MERGE_ERROR', + message: 'Failed to merge "default" keyword schemas.', + schemas: [{ foo: 'bar' }, { foo: 'baz' }] + }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/definitions.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/definitions.test.js new file mode 100644 index 0000000000000000000000000000000000000000..2f90280b75e0040e29742d8f00ede6cae51f430d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/definitions.test.js @@ -0,0 +1,46 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and definitions keyword', () => { + const schema1 = {} + const schema2 = { + definitions: { + foo: { type: 'string', const: 'foo' } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + definitions: { + foo: { type: 'string', const: 'foo' } + } + }) +}) + +test('should merge two definition schemas', () => { + const schema1 = { + definitions: { + foo: { type: 'string', enum: ['foo', 'bar'] }, + bar: { type: 'string', enum: ['foo', 'bar'] } + } + } + const schema2 = { + definitions: { + foo: { type: 'string', enum: ['foo'] }, + baz: { type: 'string' } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + definitions: { + foo: { type: 'string', enum: ['foo'] }, + bar: { type: 'string', enum: ['foo', 'bar'] }, + baz: { type: 'string' } + } + }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/defs.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/defs.test.js new file mode 100644 index 0000000000000000000000000000000000000000..e5433abbb8b2c149b07e27715757c2a9c5c22a5b --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/defs.test.js @@ -0,0 +1,46 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and $defs keyword', () => { + const schema1 = {} + const schema2 = { + $defs: { + foo: { type: 'string', const: 'foo' } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + $defs: { + foo: { type: 'string', const: 'foo' } + } + }) +}) + +test('should merge two definition schemas', () => { + const schema1 = { + $defs: { + foo: { type: 'string', enum: ['foo', 'bar'] }, + bar: { type: 'string', enum: ['foo', 'bar'] } + } + } + const schema2 = { + $defs: { + foo: { type: 'string', enum: ['foo'] }, + baz: { type: 'string' } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + $defs: { + foo: { type: 'string', enum: ['foo'] }, + bar: { type: 'string', enum: ['foo', 'bar'] }, + baz: { type: 'string' } + } + }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/dependencies.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/dependencies.test.js new file mode 100644 index 0000000000000000000000000000000000000000..3afb0cf96ac1e78621cb61dbd1485b08722fe5b2 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/dependencies.test.js @@ -0,0 +1,75 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and dependencies keyword', () => { + const schema1 = {} + const schema2 = { + type: 'object', + properties: { + foo: { type: 'string' }, + bar: { type: 'string' } + }, + dependencies: { + foo: ['bar'] + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + properties: { + foo: { type: 'string' }, + bar: { type: 'string' } + }, + dependencies: { + foo: ['bar'] + } + }) +}) + +test('should merge two dependencies keyword schemas', () => { + const schema1 = { + type: 'object', + properties: { + foo: { type: 'string' }, + bar: { type: 'string' }, + que: { type: 'string' } + }, + dependencies: { + foo: ['bar', 'que'], + bar: ['que'] + } + } + const schema2 = { + type: 'object', + properties: { + foo: { type: 'string' }, + bar: { type: 'string' }, + baz: { type: 'string' } + }, + dependencies: { + foo: ['baz'], + baz: ['foo'] + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + properties: { + foo: { type: 'string' }, + bar: { type: 'string' }, + que: { type: 'string' }, + baz: { type: 'string' } + }, + dependencies: { + foo: ['bar', 'que', 'baz'], + bar: ['que'], + baz: ['foo'] + } + }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/dependent-required.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/dependent-required.test.js new file mode 100644 index 0000000000000000000000000000000000000000..7729b9594755ad7899bfccfdfdeff5d693a2e994 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/dependent-required.test.js @@ -0,0 +1,75 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and dependentRequired keyword', () => { + const schema1 = {} + const schema2 = { + type: 'object', + properties: { + foo: { type: 'string' }, + bar: { type: 'string' } + }, + dependentRequired: { + foo: ['bar'] + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + properties: { + foo: { type: 'string' }, + bar: { type: 'string' } + }, + dependentRequired: { + foo: ['bar'] + } + }) +}) + +test('should merge two dependentRequired keyword schemas', () => { + const schema1 = { + type: 'object', + properties: { + foo: { type: 'string' }, + bar: { type: 'string' }, + que: { type: 'string' } + }, + dependentRequired: { + foo: ['bar', 'que'], + bar: ['que'] + } + } + const schema2 = { + type: 'object', + properties: { + foo: { type: 'string' }, + bar: { type: 'string' }, + baz: { type: 'string' } + }, + dependentRequired: { + foo: ['baz'], + baz: ['foo'] + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + properties: { + foo: { type: 'string' }, + bar: { type: 'string' }, + que: { type: 'string' }, + baz: { type: 'string' } + }, + dependentRequired: { + foo: ['bar', 'que', 'baz'], + bar: ['que'], + baz: ['foo'] + } + }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/dependent-schemas.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/dependent-schemas.test.js new file mode 100644 index 0000000000000000000000000000000000000000..76e04353845512dde41479e91f2731803af63301 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/dependent-schemas.test.js @@ -0,0 +1,76 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and dependentRequired keyword', () => { + const schema1 = {} + const schema2 = { + type: 'object', + properties: { + foo: { type: 'string' }, + bar: { type: 'string' } + }, + dependentSchemas: { + foo: { required: ['bar'] } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + properties: { + foo: { type: 'string' }, + bar: { type: 'string' } + }, + dependentSchemas: { + foo: { required: ['bar'] } + } + }) +}) + +test('should merge two dependentRequired keyword schemas', () => { + const schema1 = { + type: 'object', + properties: { + foo: { type: 'string' }, + bar: { type: 'string' }, + que: { type: 'string' } + }, + dependentSchemas: { + foo: { required: ['bar', 'que'] }, + bar: { required: ['que'] } + } + } + + const schema2 = { + type: 'object', + properties: { + foo: { type: 'string' }, + bar: { type: 'string' }, + baz: { type: 'string' } + }, + dependentSchemas: { + foo: { required: ['baz'] }, + baz: { required: ['foo'] } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + properties: { + foo: { type: 'string' }, + bar: { type: 'string' }, + que: { type: 'string' }, + baz: { type: 'string' } + }, + dependentSchemas: { + foo: { required: ['bar', 'que', 'baz'] }, + bar: { required: ['que'] }, + baz: { required: ['foo'] } + } + }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/enum.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/enum.test.js new file mode 100644 index 0000000000000000000000000000000000000000..8a0dd133cce70242b005af352812873e98321599 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/enum.test.js @@ -0,0 +1,44 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and string enum values', () => { + const schema1 = { type: 'string' } + const schema2 = { type: 'string', enum: ['foo', 'bar'] } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string', enum: ['foo', 'bar'] }) +}) + +test('should merge equal string enum values', () => { + const schema1 = { type: 'string', enum: ['foo', 'bar'] } + const schema2 = { type: 'string', enum: ['foo', 'bar'] } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string', enum: ['foo', 'bar'] }) +}) + +test('should merge different string enum values', () => { + const schema1 = { type: 'string', enum: ['foo', 'bar'] } + const schema2 = { type: 'string', enum: ['foo', 'baz'] } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string', enum: ['foo'] }) +}) + +test('should throw an error if can not merge enum values', () => { + const schema1 = { type: 'string', enum: ['foo', 'bar'] } + const schema2 = { type: 'string', enum: ['baz', 'qux'] } + + assert.throws(() => { + mergeSchemas([schema1, schema2], { defaultResolver }) + }, { + name: 'JsonSchemaMergeError', + code: 'JSON_SCHEMA_MERGE_ERROR', + message: 'Failed to merge "enum" keyword schemas.', + schemas: [['foo', 'bar'], ['baz', 'qux']] + }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/exclusive-maximum.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/exclusive-maximum.test.js new file mode 100644 index 0000000000000000000000000000000000000000..9481bb5f97339893248cbb7a56fc943700243d3e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/exclusive-maximum.test.js @@ -0,0 +1,30 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and exclusiveMaximum keyword', () => { + const schema1 = { type: 'number' } + const schema2 = { type: 'number', exclusiveMaximum: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'number', exclusiveMaximum: 42 }) +}) + +test('should merge equal exclusiveMaximum values', () => { + const schema1 = { type: 'number', exclusiveMaximum: 42 } + const schema2 = { type: 'number', exclusiveMaximum: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'number', exclusiveMaximum: 42 }) +}) + +test('should merge different exclusiveMaximum values', () => { + const schema1 = { type: 'integer', exclusiveMaximum: 42 } + const schema2 = { type: 'integer', exclusiveMaximum: 43 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'integer', exclusiveMaximum: 42 }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/exclusive-minimum.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/exclusive-minimum.test.js new file mode 100644 index 0000000000000000000000000000000000000000..d2de258104ce59c592dd6958900e7436f15ebbd7 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/exclusive-minimum.test.js @@ -0,0 +1,30 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and exclusiveMinimum keyword', () => { + const schema1 = { type: 'number' } + const schema2 = { type: 'number', exclusiveMinimum: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'number', exclusiveMinimum: 42 }) +}) + +test('should merge equal exclusiveMinimum values', () => { + const schema1 = { type: 'number', exclusiveMinimum: 42 } + const schema2 = { type: 'number', exclusiveMinimum: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'number', exclusiveMinimum: 42 }) +}) + +test('should merge different exclusiveMinimum values', () => { + const schema1 = { type: 'integer', exclusiveMinimum: 42 } + const schema2 = { type: 'integer', exclusiveMinimum: 43 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'integer', exclusiveMinimum: 43 }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/format.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/format.test.js new file mode 100644 index 0000000000000000000000000000000000000000..e79e1c88addfaefd9aefccc6d11b5c97d2ded12c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/format.test.js @@ -0,0 +1,36 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and string format keyword', () => { + const schema1 = { type: 'string' } + const schema2 = { type: 'string', format: 'date-time' } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string', format: 'date-time' }) +}) + +test('should merge equal string format keywords', () => { + const schema1 = { type: 'string', format: 'date-time' } + const schema2 = { type: 'string', format: 'date-time' } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string', format: 'date-time' }) +}) + +test('should throw an error if format keyword values are different', () => { + const schema1 = { type: 'string', format: 'date-time' } + const schema2 = { type: 'string', format: 'date' } + + assert.throws(() => { + mergeSchemas([schema1, schema2], { defaultResolver }) + }, { + name: 'JsonSchemaMergeError', + code: 'JSON_SCHEMA_MERGE_ERROR', + message: 'Failed to merge "format" keyword schemas.', + schemas: ['date-time', 'date'] + }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/id.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/id.test.js new file mode 100644 index 0000000000000000000000000000000000000000..9221738daccfdcc0749cb0c4725bdf1e90309f78 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/id.test.js @@ -0,0 +1,22 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should skip $id keyword if they are equal', () => { + const schema1 = { $id: 'foo', type: 'string' } + const schema2 = { $id: 'foo', type: 'string' } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string' }) +}) + +test('should skip $id keyword if they are different', () => { + const schema1 = { $id: 'foo', type: 'string' } + const schema2 = { $id: 'bar', type: 'string' } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string' }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/if-then-else.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/if-then-else.test.js new file mode 100644 index 0000000000000000000000000000000000000000..2135611a49b414f946c67991e8b20e7ef979ed3a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/if-then-else.test.js @@ -0,0 +1,550 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and if/then/else keywords', () => { + const schema1 = {} + const schema2 = { + if: { + type: 'string', + const: 'foo' + }, + then: { + type: 'string', + const: 'bar' + }, + else: { + type: 'string', + const: 'baz' + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + if: { + type: 'string', + const: 'foo' + }, + then: { + type: 'string', + const: 'bar' + }, + else: { + type: 'string', + const: 'baz' + } + }) +}) + +test('should merge if/then/else schema with an empty schema', () => { + const schema1 = { + if: { + type: 'string', + const: 'foo' + }, + then: { + type: 'string', + const: 'bar' + }, + else: { + type: 'string', + const: 'baz' + } + } + const schema2 = {} + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + if: { + type: 'string', + const: 'foo' + }, + then: { + type: 'string', + const: 'bar' + }, + else: { + type: 'string', + const: 'baz' + } + }) +}) + +test('should merge two if/then/else schemas', () => { + const schema1 = { + type: 'object', + if: { + properties: { + foo1: { type: 'string', const: 'foo1' } + } + }, + then: { + properties: { + bar1: { type: 'string', const: 'bar1' } + } + }, + else: { + properties: { + baz1: { type: 'string', const: 'baz1' } + } + } + } + const schema2 = { + type: 'object', + if: { + properties: { + foo2: { type: 'string', const: 'foo2' } + } + }, + then: { + properties: { + bar2: { type: 'string', const: 'bar2' } + } + }, + else: { + properties: { + baz2: { type: 'string', const: 'baz2' } + } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + if: { + properties: { + foo1: { type: 'string', const: 'foo1' } + } + }, + then: { + properties: { + bar1: { type: 'string', const: 'bar1' } + }, + if: { + properties: { + foo2: { type: 'string', const: 'foo2' } + } + }, + then: { + properties: { + bar2: { type: 'string', const: 'bar2' } + } + }, + else: { + properties: { + baz2: { type: 'string', const: 'baz2' } + } + } + }, + else: { + properties: { + baz1: { type: 'string', const: 'baz1' } + }, + if: { + properties: { + foo2: { type: 'string', const: 'foo2' } + } + }, + then: { + properties: { + bar2: { type: 'string', const: 'bar2' } + } + }, + else: { + properties: { + baz2: { type: 'string', const: 'baz2' } + } + } + } + }) +}) + +test('should merge three if/then/else schemas', () => { + const schema1 = { + type: 'object', + if: { + properties: { + foo1: { type: 'string', const: 'foo1' } + } + }, + then: { + properties: { + bar1: { type: 'string', const: 'bar1' } + } + }, + else: { + properties: { + baz1: { type: 'string', const: 'baz1' } + } + } + } + const schema2 = { + type: 'object', + if: { + properties: { + foo2: { type: 'string', const: 'foo2' } + } + }, + then: { + properties: { + bar2: { type: 'string', const: 'bar2' } + } + }, + else: { + properties: { + baz2: { type: 'string', const: 'baz2' } + } + } + } + const schema3 = { + type: 'object', + if: { + properties: { + foo3: { type: 'string', const: 'foo3' } + } + }, + then: { + properties: { + bar3: { type: 'string', const: 'bar3' } + } + }, + else: { + properties: { + baz3: { type: 'string', const: 'baz3' } + } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2, schema3], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + if: { + properties: { + foo1: { type: 'string', const: 'foo1' } + } + }, + then: { + properties: { + bar1: { type: 'string', const: 'bar1' } + }, + if: { + properties: { + foo2: { type: 'string', const: 'foo2' } + } + }, + then: { + properties: { + bar2: { type: 'string', const: 'bar2' } + }, + if: { + properties: { + foo3: { type: 'string', const: 'foo3' } + } + }, + then: { + properties: { + bar3: { type: 'string', const: 'bar3' } + } + }, + else: { + properties: { + baz3: { type: 'string', const: 'baz3' } + } + } + }, + else: { + properties: { + baz2: { type: 'string', const: 'baz2' } + }, + if: { + properties: { + foo3: { type: 'string', const: 'foo3' } + } + }, + then: { + properties: { + bar3: { type: 'string', const: 'bar3' } + } + }, + else: { + properties: { + baz3: { type: 'string', const: 'baz3' } + } + } + } + }, + else: { + properties: { + baz1: { type: 'string', const: 'baz1' } + }, + if: { + properties: { + foo2: { type: 'string', const: 'foo2' } + } + }, + then: { + properties: { + bar2: { type: 'string', const: 'bar2' } + }, + if: { + properties: { + foo3: { type: 'string', const: 'foo3' } + } + }, + then: { + properties: { + bar3: { type: 'string', const: 'bar3' } + } + }, + else: { + properties: { + baz3: { type: 'string', const: 'baz3' } + } + } + }, + else: { + properties: { + baz2: { type: 'string', const: 'baz2' } + }, + if: { + properties: { + foo3: { type: 'string', const: 'foo3' } + } + }, + then: { + properties: { + bar3: { type: 'string', const: 'bar3' } + } + }, + else: { + properties: { + baz3: { type: 'string', const: 'baz3' } + } + } + } + } + }) +}) + +test('should two if/then keyword schemas', () => { + const schema1 = { + type: 'object', + if: { + properties: { + foo1: { type: 'string', const: 'foo1' } + } + }, + then: { + properties: { + bar1: { type: 'string', const: 'bar1' } + } + } + } + + const schema2 = { + type: 'object', + if: { + properties: { + foo2: { type: 'string', const: 'foo2' } + } + }, + then: { + properties: { + bar2: { type: 'string', const: 'bar2' } + } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + if: { + properties: { + foo1: { type: 'string', const: 'foo1' } + } + }, + then: { + properties: { + bar1: { type: 'string', const: 'bar1' } + }, + if: { + properties: { + foo2: { type: 'string', const: 'foo2' } + } + }, + then: { + properties: { + bar2: { type: 'string', const: 'bar2' } + } + } + } + }) +}) + +test('should two if/else keyword schemas', () => { + const schema1 = { + type: 'object', + if: { + properties: { + foo1: { type: 'string', const: 'foo1' } + } + }, + else: { + properties: { + bar1: { type: 'string', const: 'bar1' } + } + } + } + + const schema2 = { + type: 'object', + if: { + properties: { + foo2: { type: 'string', const: 'foo2' } + } + }, + else: { + properties: { + bar2: { type: 'string', const: 'bar2' } + } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + if: { + properties: { + foo1: { type: 'string', const: 'foo1' } + } + }, + else: { + properties: { + bar1: { type: 'string', const: 'bar1' } + }, + if: { + properties: { + foo2: { type: 'string', const: 'foo2' } + } + }, + else: { + properties: { + bar2: { type: 'string', const: 'bar2' } + } + } + } + }) +}) + +test('should two if/then and if/else keyword schemas', () => { + const schema1 = { + type: 'object', + if: { + properties: { + foo1: { type: 'string', const: 'foo1' } + } + }, + then: { + properties: { + bar1: { type: 'string', const: 'bar1' } + } + } + } + + const schema2 = { + type: 'object', + if: { + properties: { + foo2: { type: 'string', const: 'foo2' } + } + }, + else: { + properties: { + bar2: { type: 'string', const: 'bar2' } + } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + if: { + properties: { + foo1: { type: 'string', const: 'foo1' } + } + }, + then: { + properties: { + bar1: { type: 'string', const: 'bar1' } + }, + if: { + properties: { + foo2: { type: 'string', const: 'foo2' } + } + }, + else: { + properties: { + bar2: { type: 'string', const: 'bar2' } + } + } + } + }) +}) + +test('should two if/else and if/then keyword schemas', () => { + const schema1 = { + type: 'object', + if: { + properties: { + foo1: { type: 'string', const: 'foo1' } + } + }, + else: { + properties: { + bar1: { type: 'string', const: 'bar1' } + } + } + } + + const schema2 = { + type: 'object', + if: { + properties: { + foo2: { type: 'string', const: 'foo2' } + } + }, + then: { + properties: { + bar2: { type: 'string', const: 'bar2' } + } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + if: { + properties: { + foo1: { type: 'string', const: 'foo1' } + } + }, + else: { + properties: { + bar1: { type: 'string', const: 'bar1' } + }, + if: { + properties: { + foo2: { type: 'string', const: 'foo2' } + } + }, + then: { + properties: { + bar2: { type: 'string', const: 'bar2' } + } + } + } + }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/items.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/items.test.js new file mode 100644 index 0000000000000000000000000000000000000000..b780530370e512e815024fd974a8c021d6712bc1 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/items.test.js @@ -0,0 +1,152 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and items keyword', () => { + const schema1 = { type: 'array' } + const schema2 = { + type: 'array', + items: { + type: 'object', + properties: { + foo: { type: 'string' } + } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'array', + items: { + type: 'object', + properties: { + foo: { type: 'string' } + } + } + }) +}) + +test('should merge two equal item schemas', () => { + const schema1 = { + type: 'array', + items: { + type: 'object', + properties: { + foo: { type: 'string' } + } + } + } + + const schema2 = { + type: 'array', + items: { + type: 'object', + properties: { + foo: { type: 'string' } + } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'array', + items: { + type: 'object', + properties: { + foo: { type: 'string' } + } + } + }) +}) + +test('should merge two different sets of item schemas', () => { + const schema1 = { + type: 'array', + items: { + type: 'object', + properties: { + foo: { type: 'string' }, + bar: { type: 'number' } + } + } + } + + const schema2 = { + type: 'array', + items: { + type: 'object', + properties: { + foo: { type: 'string' }, + baz: { type: 'boolean' } + } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'array', + items: { + type: 'object', + properties: { + foo: { type: 'string' }, + bar: { type: 'number' }, + baz: { type: 'boolean' } + } + } + }) +}) + +test('should merge two different sets of item schemas with additionalItems', () => { + const schema1 = { + type: 'array', + items: [ + { + type: 'object', + properties: { + foo: { type: 'string', const: 'foo' } + } + } + ], + additionalItems: { + type: 'object', + properties: { + baz: { type: 'string', const: 'baz' } + } + } + } + + const schema2 = { + type: 'array', + items: { + type: 'object', + properties: { + foo: { type: 'string' }, + baz: { type: 'string' } + } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'array', + items: [ + { + type: 'object', + properties: { + foo: { type: 'string', const: 'foo' }, + baz: { type: 'string' } + } + } + ], + additionalItems: { + type: 'object', + properties: { + foo: { type: 'string' }, + baz: { type: 'string', const: 'baz' } + } + } + }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/max-items.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/max-items.test.js new file mode 100644 index 0000000000000000000000000000000000000000..939cf29940a53858b7e92a9f55e5a71b690a41f5 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/max-items.test.js @@ -0,0 +1,30 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and maxItems keyword', () => { + const schema1 = { type: 'array' } + const schema2 = { type: 'array', maxItems: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'array', maxItems: 42 }) +}) + +test('should merge equal maxItems values', () => { + const schema1 = { type: 'array', maxItems: 42 } + const schema2 = { type: 'array', maxItems: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'array', maxItems: 42 }) +}) + +test('should merge different maxItems values', () => { + const schema1 = { type: 'array', maxItems: 42 } + const schema2 = { type: 'array', maxItems: 43 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'array', maxItems: 42 }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/max-length.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/max-length.test.js new file mode 100644 index 0000000000000000000000000000000000000000..c97002fbf99021b043a54dfddb267ae6e4663180 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/max-length.test.js @@ -0,0 +1,30 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and maxLength keyword', () => { + const schema1 = { type: 'string' } + const schema2 = { type: 'string', maxLength: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string', maxLength: 42 }) +}) + +test('should merge equal maxLength values', () => { + const schema1 = { type: 'string', maxLength: 42 } + const schema2 = { type: 'string', maxLength: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string', maxLength: 42 }) +}) + +test('should merge different maxLength values', () => { + const schema1 = { type: 'string', maxLength: 42 } + const schema2 = { type: 'string', maxLength: 43 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string', maxLength: 42 }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/max-properties.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/max-properties.test.js new file mode 100644 index 0000000000000000000000000000000000000000..b5b39496bd4624a0a4b13ae8042f43955012d353 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/max-properties.test.js @@ -0,0 +1,30 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and maxProperties keyword', () => { + const schema1 = { type: 'object' } + const schema2 = { type: 'object', maxProperties: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'object', maxProperties: 42 }) +}) + +test('should merge equal maxProperties values', () => { + const schema1 = { type: 'object', maxProperties: 42 } + const schema2 = { type: 'object', maxProperties: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'object', maxProperties: 42 }) +}) + +test('should merge different maxProperties values', () => { + const schema1 = { type: 'object', maxProperties: 42 } + const schema2 = { type: 'object', maxProperties: 43 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'object', maxProperties: 42 }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/maximum.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/maximum.test.js new file mode 100644 index 0000000000000000000000000000000000000000..4a0c982fa4360598338a9c3ce49ed83499a89e42 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/maximum.test.js @@ -0,0 +1,30 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and maximum keyword', () => { + const schema1 = { type: 'number' } + const schema2 = { type: 'number', maximum: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'number', maximum: 42 }) +}) + +test('should merge equal maximum values', () => { + const schema1 = { type: 'number', maximum: 42 } + const schema2 = { type: 'number', maximum: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'number', maximum: 42 }) +}) + +test('should merge different maximum values', () => { + const schema1 = { type: 'integer', maximum: 42 } + const schema2 = { type: 'integer', maximum: 43 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'integer', maximum: 42 }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/merge-schema.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/merge-schema.test.js new file mode 100644 index 0000000000000000000000000000000000000000..a41c3a983fe280eb712fd74cfda21991e97cf3ea --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/merge-schema.test.js @@ -0,0 +1,29 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should return an empty schema if passing an empty array', () => { + const mergedSchema = mergeSchemas([], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, {}) +}) + +test('should return true if passing all true values', () => { + const mergedSchema = mergeSchemas([true, true, true], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, true) +}) + +test('should return true if passing all false values', () => { + const mergedSchema = mergeSchemas([false, false, false], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, false) +}) + +test('should return true if passing at least one false schema', () => { + const schema1 = { type: 'string' } + const schema2 = { type: 'number' } + + const mergedSchema = mergeSchemas([schema1, schema2, false], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, false) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/min-items.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/min-items.test.js new file mode 100644 index 0000000000000000000000000000000000000000..b5d5073556ddfb11cafd6d71c492c6a96b0f4552 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/min-items.test.js @@ -0,0 +1,30 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and minItems keyword', () => { + const schema1 = { type: 'array' } + const schema2 = { type: 'array', minItems: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'array', minItems: 42 }) +}) + +test('should merge equal minItems values', () => { + const schema1 = { type: 'array', minItems: 42 } + const schema2 = { type: 'array', minItems: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'array', minItems: 42 }) +}) + +test('should merge different minItems values', () => { + const schema1 = { type: 'array', minItems: 42 } + const schema2 = { type: 'array', minItems: 43 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'array', minItems: 43 }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/min-length.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/min-length.test.js new file mode 100644 index 0000000000000000000000000000000000000000..64a2c4458ae23e7b35ed9d7e7ed0209e3d53a07d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/min-length.test.js @@ -0,0 +1,30 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and minLength keyword', () => { + const schema1 = { type: 'string' } + const schema2 = { type: 'string', minLength: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string', minLength: 42 }) +}) + +test('should merge equal minLength values', () => { + const schema1 = { type: 'string', minLength: 42 } + const schema2 = { type: 'string', minLength: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string', minLength: 42 }) +}) + +test('should merge different minLength values', () => { + const schema1 = { type: 'string', minLength: 42 } + const schema2 = { type: 'string', minLength: 43 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string', minLength: 43 }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/min-properties.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/min-properties.test.js new file mode 100644 index 0000000000000000000000000000000000000000..bfe4599b33e0c1562a09f91bb3bc3e7def57d221 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/min-properties.test.js @@ -0,0 +1,30 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and minProperties keyword', () => { + const schema1 = { type: 'object' } + const schema2 = { type: 'object', minProperties: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'object', minProperties: 42 }) +}) + +test('should merge equal minItems values', () => { + const schema1 = { type: 'object', minProperties: 42 } + const schema2 = { type: 'object', minProperties: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'object', minProperties: 42 }) +}) + +test('should merge different minItems values', () => { + const schema1 = { type: 'object', minProperties: 42 } + const schema2 = { type: 'object', minProperties: 43 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'object', minProperties: 43 }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/minimum.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/minimum.test.js new file mode 100644 index 0000000000000000000000000000000000000000..f0dd105ad35bc61b134c91d391db910a587cb8e3 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/minimum.test.js @@ -0,0 +1,30 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and minimum keyword', () => { + const schema1 = { type: 'number' } + const schema2 = { type: 'number', minimum: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'number', minimum: 42 }) +}) + +test('should merge equal minimum values', () => { + const schema1 = { type: 'number', minimum: 42 } + const schema2 = { type: 'number', minimum: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'number', minimum: 42 }) +}) + +test('should merge different minimum values', () => { + const schema1 = { type: 'integer', minimum: 42 } + const schema2 = { type: 'integer', minimum: 43 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'integer', minimum: 43 }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/multiple-of.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/multiple-of.test.js new file mode 100644 index 0000000000000000000000000000000000000000..f07a32bcff9b10d117227919ba59fdcfb58e68e8 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/multiple-of.test.js @@ -0,0 +1,36 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and multipleOf keyword', () => { + const schema1 = { type: 'number' } + const schema2 = { type: 'number', multipleOf: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'number', multipleOf: 42 }) +}) + +test('should merge two schemas with multipleOf keywords', () => { + const schema1 = { type: 'number', multipleOf: 2 } + const schema2 = { type: 'number', multipleOf: 3 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'number', multipleOf: 6 }) +}) + +test('should merge multiple schemas with float multipleOf keywords', () => { + const schema1 = { type: 'number', multipleOf: 0.2 } + const schema2 = { type: 'number', multipleOf: 2 } + const schema3 = { type: 'number', multipleOf: 2 } + const schema4 = { type: 'number', multipleOf: 0.5 } + const schema5 = { type: 'number', multipleOf: 1.5 } + + const mergedSchema = mergeSchemas( + [schema1, schema2, schema3, schema4, schema5], + { defaultResolver } + ) + assert.deepStrictEqual(mergedSchema, { type: 'number', multipleOf: 6 }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/not.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/not.test.js new file mode 100644 index 0000000000000000000000000000000000000000..e73131d48b0262e74a9618a3d89fff2084a189df --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/not.test.js @@ -0,0 +1,29 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge two "not" keyword schemas', () => { + const schema1 = { + type: 'array', + not: { + type: 'string' + } + } + const schema2 = { + type: 'array', + not: { + type: 'string', minLength: 1 + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'array', + not: { + type: 'string', minLength: 1 + } + }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/nullable.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/nullable.test.js new file mode 100644 index 0000000000000000000000000000000000000000..ef5fcfd8618fc9e0451e5a72f15af88336c1a1bb --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/nullable.test.js @@ -0,0 +1,30 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and nullable = true keyword', () => { + const schema1 = { type: 'string' } + const schema2 = { type: 'string', nullable: true } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string', nullable: true }) +}) + +test('should merge empty schema and nullable = false keyword', () => { + const schema1 = { type: 'string' } + const schema2 = { type: 'string', nullable: false } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string', nullable: false }) +}) + +test('should merge schemas with nullable true and false values', () => { + const schema1 = { type: 'string', nullable: false } + const schema2 = { type: 'string', nullable: true } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string', nullable: false }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/one-of.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/one-of.test.js new file mode 100644 index 0000000000000000000000000000000000000000..94eab45a8f053b688a3fa7797883d0e1ba38c4c9 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/one-of.test.js @@ -0,0 +1,144 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas, MergeError } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and oneOf keyword', () => { + const schema1 = {} + const schema2 = { + oneOf: [ + { type: 'string', const: 'foo' } + ] + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + oneOf: [ + { type: 'string', const: 'foo' } + ] + }) +}) + +test('should merge two schemas with oneOfs schemas', () => { + const schema1 = { + oneOf: [ + { type: 'string', enum: ['foo1', 'foo2', 'foo3'] }, + { type: 'string', enum: ['foo3', 'foo4', 'foo5'] } + ] + } + const schema2 = { + oneOf: [ + { type: 'string', enum: ['foo2', 'foo3', 'foo4'] }, + { type: 'string', enum: ['foo3', 'foo6', 'foo7'] } + ] + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + oneOf: [ + { type: 'string', enum: ['foo2', 'foo3'] }, + { type: 'string', enum: ['foo3'] }, + { type: 'string', enum: ['foo3', 'foo4'] }, + { type: 'string', enum: ['foo3'] } + ] + }) +}) + +test('should merge three schemas with oneOfs schemas', () => { + const schema1 = { + oneOf: [ + { type: 'string', enum: ['foo1', 'foo2', 'foo3', 'foo4'] }, + { type: 'string', enum: ['foo3', 'foo4', 'foo5', 'foo7'] } + ] + } + const schema2 = { + oneOf: [ + { type: 'string', enum: ['foo2', 'foo3', 'foo4', 'foo5'] }, + { type: 'string', enum: ['foo3', 'foo6', 'foo7', 'foo8'] } + ] + } + + const schema3 = { + oneOf: [ + { type: 'string', enum: ['foo1', 'foo3', 'foo5', 'foo7'] }, + { type: 'string', enum: ['foo2', 'foo4', 'foo6', 'foo8'] } + ] + } + + const mergedSchema = mergeSchemas( + [schema1, schema2, schema3], + { defaultResolver } + ) + assert.deepStrictEqual(mergedSchema, { + oneOf: [ + { type: 'string', enum: ['foo3'] }, + { type: 'string', enum: ['foo2', 'foo4'] }, + { type: 'string', enum: ['foo3'] }, + { type: 'string', enum: ['foo3', 'foo5'] }, + { type: 'string', enum: ['foo4'] }, + { type: 'string', enum: ['foo3', 'foo7'] } + ] + }) +}) + +test('should throw a non MergeError error during oneOf merge', () => { + const schema1 = { + oneOf: [ + { type: 'string', customKeyword: 42 }, + { type: 'string', customKeyword: 43 } + ] + } + const schema2 = { + oneOf: [ + { type: 'string', customKeyword: 44 }, + { type: 'string', customKeyword: 45 } + ] + } + + assert.throws(() => { + mergeSchemas( + [schema1, schema2], + { + resolvers: { + customKeyword: () => { + throw new Error('Custom error') + } + }, + defaultResolver + } + ) + }, { + name: 'Error', + message: 'Custom error' + }) +}) + +test('should not throw a MergeError error during oneOf merge', () => { + const schema1 = { + oneOf: [ + { type: 'string', customKeyword: 42 }, + { type: 'string', customKeyword: 43 } + ] + } + const schema2 = { + oneOf: [ + { type: 'string', customKeyword: 44 }, + { type: 'string', customKeyword: 45 } + ] + } + + const mergedSchema = mergeSchemas( + [schema1, schema2], + { + resolvers: { + customKeyword: (keyword, values) => { + throw new MergeError(keyword, values) + } + }, + defaultResolver + } + ) + assert.deepStrictEqual(mergedSchema, { oneOf: [] }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/properties.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/properties.test.js new file mode 100644 index 0000000000000000000000000000000000000000..6e26492d920ce42cb9151d15ed781306fd5f56f4 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/properties.test.js @@ -0,0 +1,312 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and properties keyword', () => { + const schema1 = { type: 'object' } + const schema2 = { + type: 'object', + properties: { + foo: { type: 'string' } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + properties: { + foo: { type: 'string' } + } + }) +}) + +test('should merge two equal property schemas', () => { + const schema1 = { + type: 'object', + properties: { + foo: { type: 'string' } + } + } + + const schema2 = { + type: 'object', + properties: { + foo: { type: 'string' } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + properties: { + foo: { type: 'string' } + } + }) +}) + +test('should merge two different sets of property schemas', () => { + const schema1 = { + type: 'object', + properties: { + foo: { type: 'string' }, + bar: { type: 'number' } + } + } + + const schema2 = { + type: 'object', + properties: { + foo: { type: 'string' }, + baz: { type: 'boolean' } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + properties: { + foo: { type: 'string' }, + bar: { type: 'number' }, + baz: { type: 'boolean' } + } + }) +}) + +test('should merge property with different schemas', () => { + const schema1 = { + type: 'object', + properties: { + foo: { + type: ['string', 'number'], + enum: ['42', 2, 3] + } + } + } + + const schema2 = { + type: 'object', + properties: { + foo: { + type: ['number', 'null'], + enum: [1, 2, 3, null] + } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + properties: { + foo: { type: 'number', enum: [2, 3] } + } + }) +}) + +test('should merge properties if one schema has additionalProperties = false', () => { + const schema1 = { + type: 'object', + properties: { + foo: { type: 'string' }, + bar: { type: 'number' } + }, + additionalProperties: false + } + + const schema2 = { + type: 'object', + properties: { + foo: { type: 'string', enum: ['42'] }, + baz: { type: 'string' } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + properties: { + foo: { type: 'string', enum: ['42'] }, + bar: { type: 'number' }, + baz: false + }, + additionalProperties: false + }) +}) + +test('should merge properties if both schemas have additionalProperties = false', () => { + const schema1 = { + type: 'object', + properties: { + foo: { type: 'string' }, + bar: { type: 'number' } + }, + additionalProperties: false + } + + const schema2 = { + type: 'object', + properties: { + foo: { type: 'string', enum: ['42'] }, + baz: { type: 'string' } + }, + additionalProperties: false + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + properties: { + foo: { type: 'string', enum: ['42'] }, + bar: false, + baz: false + }, + additionalProperties: false + }) +}) + +test('should merge properties if one schema has additionalProperties schema', () => { + const schema1 = { + type: 'object', + properties: { + foo: { type: 'string' }, + bar: { type: 'number' } + }, + additionalProperties: { type: 'string', enum: ['43'] } + } + + const schema2 = { + type: 'object', + properties: { + foo: { type: 'string', enum: ['42'] }, + baz: { type: 'string' } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + properties: { + foo: { type: 'string', enum: ['42'] }, + bar: { type: 'number' }, + baz: { type: 'string', enum: ['43'] } + }, + additionalProperties: { type: 'string', enum: ['43'] } + }) +}) + +test('should merge properties if both schemas have additionalProperties schemas', () => { + const schema1 = { + type: 'object', + properties: { + foo: { type: 'string' }, + bar: { type: 'number' } + }, + additionalProperties: { + type: ['string', 'number', 'null'], + enum: ['45', '43', 41, null] + } + } + + const schema2 = { + type: 'object', + properties: { + foo: { type: 'string', enum: ['42'] }, + baz: { type: 'string' } + }, + additionalProperties: { + type: ['string', 'boolean', 'number'], + enum: ['44', '43', true, 41] + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + properties: { + foo: { type: 'string', enum: ['42'] }, + bar: { type: 'number', enum: ['44', '43', true, 41] }, + baz: { type: 'string', enum: ['45', '43', 41, null] } + }, + additionalProperties: { type: ['string', 'number'], enum: ['43', 41] } + }) +}) + +test('should merge properties if one schema has patternProperties schema', () => { + const schema1 = { + type: 'object', + properties: { + foo: { type: 'string' }, + bar: { type: 'number' } + }, + patternProperties: { + '^baz$': { type: 'string', enum: ['43'] } + } + } + + const schema2 = { + type: 'object', + properties: { + foo: { type: 'string', enum: ['42'] }, + baz: { type: 'string' }, + qux: { type: 'string' } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + properties: { + foo: { type: 'string', enum: ['42'] }, + bar: { type: 'number' }, + baz: { type: 'string', enum: ['43'] }, + qux: { type: 'string' } + }, + patternProperties: { + '^baz$': { type: 'string', enum: ['43'] } + } + }) +}) + +test('should merge properties if both schemas have patternProperties schemas', () => { + const schema1 = { + type: 'object', + properties: { + foo: { type: 'string' }, + bar: { type: 'number' }, + bak: { type: 'number' } + }, + patternProperties: { + '^baz$': { type: 'string', enum: ['43'] } + } + } + + const schema2 = { + type: 'object', + properties: { + foo: { type: 'string', enum: ['42'] }, + baz: { type: 'string' }, + qux: { type: 'string' } + }, + patternProperties: { + '^bar$': { type: 'number', minimum: 2 } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + properties: { + foo: { type: 'string', enum: ['42'] }, + bar: { type: 'number', minimum: 2 }, + bak: { type: 'number' }, + baz: { type: 'string', enum: ['43'] }, + qux: { type: 'string' } + }, + patternProperties: { + '^bar$': { type: 'number', minimum: 2 }, + '^baz$': { type: 'string', enum: ['43'] } + } + }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/property-names.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/property-names.test.js new file mode 100644 index 0000000000000000000000000000000000000000..9f27572a944bbebdfb52c75733555937f8ef32e7 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/property-names.test.js @@ -0,0 +1,49 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and propertyNames keyword', () => { + const schema1 = {} + const schema2 = { + type: 'object', + propertyNames: { + pattern: '^[a-zA-Z]+$', + minLength: 42 + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + propertyNames: { + pattern: '^[a-zA-Z]+$', + minLength: 42 + } + }) +}) + +test('should merge two propertyNames keyword schemas', () => { + const schema1 = { + type: 'object', + propertyNames: { + minLength: 42 + } + } + const schema2 = { + type: 'object', + propertyNames: { + minLength: 43 + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + propertyNames: { + minLength: 43 + } + }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/required.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/required.test.js new file mode 100644 index 0000000000000000000000000000000000000000..3afa392f7faf33c707ee8fecdaf71acce4ad832c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/required.test.js @@ -0,0 +1,30 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and required keyword', () => { + const schema1 = { type: 'object' } + const schema2 = { type: 'object', required: ['foo'] } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'object', required: ['foo'] }) +}) + +test('should merge two equal required keywords', () => { + const schema1 = { type: 'object', required: ['foo'] } + const schema2 = { type: 'object', required: ['foo'] } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'object', required: ['foo'] }) +}) + +test('should merge two different required keywords', () => { + const schema1 = { type: 'object', required: ['foo', 'bar'] } + const schema2 = { type: 'object', required: ['foo', 'baz'] } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'object', required: ['foo', 'bar', 'baz'] }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/type.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/type.test.js new file mode 100644 index 0000000000000000000000000000000000000000..69c0861ae186988da6863eb0e93601621b479bc7 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/type.test.js @@ -0,0 +1,52 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge equal type values', () => { + const schema1 = { type: 'string' } + const schema2 = { type: 'string' } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string' }) +}) + +test('should merge array type values', () => { + const schema1 = { type: ['string', 'number'] } + const schema2 = { type: ['null', 'string'] } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string' }) +}) + +test('should merge array type values', () => { + const schema1 = { type: ['string', 'number'] } + const schema2 = { type: 'string' } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string' }) +}) + +test('should merge array type values', () => { + const schema1 = { type: ['number', 'string', 'boolean'] } + const schema2 = { type: ['string', 'number', 'null'] } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: ['number', 'string'] }) +}) + +test('should throw an error if can not merge type values', () => { + const schema1 = { type: 'string' } + const schema2 = { type: 'number' } + + assert.throws(() => { + mergeSchemas([schema1, schema2], { defaultResolver }) + }, { + name: 'JsonSchemaMergeError', + code: 'JSON_SCHEMA_MERGE_ERROR', + message: 'Failed to merge "type" keyword schemas.', + schemas: [['string'], ['number']] + }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/unique-items.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/unique-items.test.js new file mode 100644 index 0000000000000000000000000000000000000000..61a55e80ca7ffb2a3211bd19aa10232391e5db9e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/unique-items.test.js @@ -0,0 +1,38 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and uniqueItems keyword', () => { + const schema1 = { type: 'array' } + const schema2 = { type: 'array', uniqueItems: true } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'array', uniqueItems: true }) +}) + +test('should merge two equal uniqueItems keyword schemas = true', () => { + const schema1 = { type: 'array', uniqueItems: true } + const schema2 = { type: 'array', uniqueItems: true } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'array', uniqueItems: true }) +}) + +test('should merge two equal uniqueItems keyword schemas = false', () => { + const schema1 = { type: 'array', uniqueItems: false } + const schema2 = { type: 'array', uniqueItems: false } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'array', uniqueItems: false }) +}) + +test('should merge two equal uniqueItems keyword schemas', () => { + const schema1 = { type: 'array', uniqueItems: false } + const schema2 = { type: 'array', uniqueItems: true } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'array', uniqueItems: true }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/utils.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..956ba245ae0ba1ae643f52251ee15c76f763f08b --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/test/utils.js @@ -0,0 +1,9 @@ +'use strict' + +function defaultResolver () { + throw new Error('Default resolver should not be called.') +} + +module.exports = { + defaultResolver +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/types/index.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/types/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ab29554884764cfbaba5be2d35549e9fa0d630d1 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/types/index.d.ts @@ -0,0 +1,61 @@ +export type KeywordResolver = ( + keyword: string, + keywordValues: any[], + mergedSchema: any, + parentSchemas: any[], + options: MergeOptions +) => any + +export type KeywordResolvers = { + $id: KeywordResolver, + type: KeywordResolver, + enum: KeywordResolver, + minLength: KeywordResolver, + maxLength: KeywordResolver, + minimum: KeywordResolver, + maximum: KeywordResolver, + multipleOf: KeywordResolver, + exclusiveMinimum: KeywordResolver, + exclusiveMaximum: KeywordResolver, + minItems: KeywordResolver, + maxItems: KeywordResolver, + maxProperties: KeywordResolver, + minProperties: KeywordResolver, + const: KeywordResolver, + default: KeywordResolver, + format: KeywordResolver, + required: KeywordResolver, + properties: KeywordResolver, + patternProperties: KeywordResolver, + additionalProperties: KeywordResolver, + items: KeywordResolver, + additionalItems: KeywordResolver, + definitions: KeywordResolver, + $defs: KeywordResolver, + nullable: KeywordResolver, + oneOf: KeywordResolver, + anyOf: KeywordResolver, + allOf: KeywordResolver, + not: KeywordResolver, + if: KeywordResolver, + then: KeywordResolver, + else: KeywordResolver, + dependencies: KeywordResolver, + dependentRequired: KeywordResolver, + dependentSchemas: KeywordResolver, + propertyNames: KeywordResolver, + uniqueItems: KeywordResolver, + contains: KeywordResolver +} + +export type MergeOptions = { + defaultResolver?: KeywordResolver, + resolvers?: Partial, + // enum of ["throw", "skip", "first"] + onConflict?: 'throw' | 'skip' | 'first' +} + +export function mergeSchemas (schemas: any[], options?: MergeOptions): any + +export const keywordsResolvers: KeywordResolvers +export const defaultResolver: KeywordResolver diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/types/index.test-d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/types/index.test-d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7d82a148ec717c6989e29bff6b4c379a7bc6a118 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/merge-json-schemas/types/index.test-d.ts @@ -0,0 +1,52 @@ +import { mergeSchemas, MergeOptions } from '..' +import { expectType } from 'tsd' + +{ + const schema1 = { type: 'string', enum: ['foo', 'bar'] } + const schema2 = { type: 'string', enum: ['foo', 'baz'] } + + mergeSchemas([schema1, schema2]) +} + +{ + const schema1 = { type: 'string', enum: ['foo', 'bar'] } + const schema2 = { type: 'string', enum: ['foo', 'baz'] } + + const mergeOptions: MergeOptions = { + resolvers: { + enum: ( + keyword: string, + keywordValues: any[], + mergedSchema: any, + parentSchemas: any[], + options: MergeOptions + ) => { + expectType(keyword) + expectType(keywordValues) + expectType(mergedSchema) + expectType(parentSchemas) + expectType(options) + + return keywordValues + } + }, + defaultResolver: ( + keyword: string, + keywordValues: any[], + mergedSchema: any, + parentSchemas: any[], + options: MergeOptions + ) => { + expectType(keyword) + expectType(keywordValues) + expectType(mergedSchema) + expectType(parentSchemas) + expectType(options) + + return keywordValues + }, + onConflict: 'throw' + } + + mergeSchemas([schema1, schema2], mergeOptions) +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/proxy-addr/.gitattributes b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/proxy-addr/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..a0e7df931f90e194cc6b80313f8f07744d9fc6d8 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/proxy-addr/.gitattributes @@ -0,0 +1,2 @@ +# Set default behavior to automatically convert line endings +* text=auto eol=lf diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/proxy-addr/.github/dependabot.yml b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/proxy-addr/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..dfa7fa6cba823110c8476a4b4ebcc07cfda12535 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/proxy-addr/.github/dependabot.yml @@ -0,0 +1,13 @@ +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "monthly" + open-pull-requests-limit: 10 + + - package-ecosystem: "npm" + directory: "/" + schedule: + interval: "weekly" + open-pull-requests-limit: 10 diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/proxy-addr/.github/stale.yml b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/proxy-addr/.github/stale.yml new file mode 100644 index 0000000000000000000000000000000000000000..d51ce639022226bc44471aa18bb218b50876cd52 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/proxy-addr/.github/stale.yml @@ -0,0 +1,21 @@ +# Number of days of inactivity before an issue becomes stale +daysUntilStale: 15 +# Number of days of inactivity before a stale issue is closed +daysUntilClose: 7 +# Issues with these labels will never be considered stale +exemptLabels: + - "discussion" + - "feature request" + - "bug" + - "help wanted" + - "plugin suggestion" + - "good first issue" +# Label to use when marking an issue as stale +staleLabel: stale +# Comment to post when marking an issue as stale. Set to `false` to disable +markComment: > + This issue has been automatically marked as stale because it has not had + recent activity. It will be closed if no further activity occurs. Thank you + for your contributions. +# Comment to post when closing a stale issue. Set to `false` to disable +closeComment: false diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/proxy-addr/.github/workflows/ci.yml b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/proxy-addr/.github/workflows/ci.yml new file mode 100644 index 0000000000000000000000000000000000000000..31223b14224a040e75704597c6808a6dc3f15851 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/proxy-addr/.github/workflows/ci.yml @@ -0,0 +1,24 @@ +name: CI + +on: + push: + branches: + - main + - master + - next + - 'v*' + paths-ignore: + - 'docs/**' + - '*.md' + pull_request: + paths-ignore: + - 'docs/**' + - '*.md' + +jobs: + test: + uses: fastify/workflows/.github/workflows/plugins-ci.yml@v5.0.0 + with: + license-check: true + lint: true + node-versions: '["18", "20", "22"]' diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/proxy-addr/LICENSE b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/proxy-addr/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..4b53c0a880c5b1d91329709079fc422e8f859ad0 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/proxy-addr/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2021 Fastify collaborators +Copyright (c) 2014-2016 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/proxy-addr/README.md b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/proxy-addr/README.md new file mode 100644 index 0000000000000000000000000000000000000000..5757412404d4c881b2fcce5ed2f3428676808d6e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/proxy-addr/README.md @@ -0,0 +1,141 @@ +# proxy-addr + +![CI](https://github.com/fastify/proxy-addr/workflows/CI/badge.svg) +[![NPM version](https://img.shields.io/npm/v/@fastify/proxy-addr.svg?style=flat)](https://www.npmjs.com/package/@fastify/proxy-addr) +[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](https://standardjs.com/) + +Determine address of proxied request. + +Forked from https://github.com/jshttp/proxy-addr to address https://github.com/jshttp/forwarded/pull/9. + +## Install + +```sh +$ npm i @fastify/proxy-addr +``` + +## API + + + +```js +var proxyaddr = require('@fastify/proxy-addr') +``` + +### proxyaddr(req, trust) + +Return the address of the request, using the given `trust` parameter. + +The `trust` argument is a function that returns `true` if you trust +the address, `false` if you don't. The closest untrusted address is +returned. + + + +```js +proxyaddr(req, function (addr) { return addr === '127.0.0.1' }) +proxyaddr(req, function (addr, i) { return i < 1 }) +``` + +The `trust` arugment may also be a single IP address string or an +array of trusted addresses, as plain IP addresses, CIDR-formatted +strings, or IP/netmask strings. + + + +```js +proxyaddr(req, '127.0.0.1') +proxyaddr(req, ['127.0.0.0/8', '10.0.0.0/8']) +proxyaddr(req, ['127.0.0.0/255.0.0.0', '192.168.0.0/255.255.0.0']) +``` + +This module also supports IPv6. Your IPv6 addresses will be normalized +automatically (i.e. `fe80::00ed:1` equals `fe80:0:0:0:0:0:ed:1`). + + + +```js +proxyaddr(req, '::1') +proxyaddr(req, ['::1/128', 'fe80::/10']) +``` + +This module will automatically work with IPv4-mapped IPv6 addresses +as well to support node.js in IPv6-only mode. This means that you do +not have to specify both `::ffff:a00:1` and `10.0.0.1`. + +As a convenience, this module also takes certain pre-defined names +in addition to IP addresses, which expand into IP addresses: + + + +```js +proxyaddr(req, 'loopback') +proxyaddr(req, ['loopback', 'fc00:ac:1ab5:fff::1/64']) +``` + + * `loopback`: IPv4 and IPv6 loopback addresses (like `::1` and + `127.0.0.1`). + * `linklocal`: IPv4 and IPv6 link-local addresses (like + `fe80::1:1:1:1` and `169.254.0.1`). + * `uniquelocal`: IPv4 private addresses and IPv6 unique-local + addresses (like `fc00:ac:1ab5:fff::1` and `192.168.0.1`). + +When `trust` is specified as a function, it will be called for each +address to determine if it is a trusted address. The function is +given two arguments: `addr` and `i`, where `addr` is a string of +the address to check and `i` is a number that represents the distance +from the socket address. + +### proxyaddr.all(req, [trust]) + +Return all the addresses of the request, optionally stopping at the +first untrusted. This array is ordered from closest to furthest +(i.e. `arr[0] === req.connection.remoteAddress`). + + + +```js +proxyaddr.all(req) +``` + +The optional `trust` argument takes the same arguments as `trust` +does in `proxyaddr(req, trust)`. + + + +```js +proxyaddr.all(req, 'loopback') +``` + +### proxyaddr.compile(val) + +Compiles argument `val` into a `trust` function. This function takes +the same arguments as `trust` does in `proxyaddr(req, trust)` and +returns a function suitable for `proxyaddr(req, trust)`. + + + +```js +var trust = proxyaddr.compile('loopback') +var addr = proxyaddr(req, trust) +``` + +This function is meant to be optimized for use against every request. +It is recommend to compile a trust function up-front for the trusted +configuration and pass that to `proxyaddr(req, trust)` for each request. + +## Testing + +```sh +$ npm test +``` + +## Benchmarks + +```sh +$ npm run-script bench +``` + +## License + +[MIT](LICENSE) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/proxy-addr/benchmark/compiling.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/proxy-addr/benchmark/compiling.js new file mode 100644 index 0000000000000000000000000000000000000000..76387276e08986d731e42babfeff89060083efb4 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/proxy-addr/benchmark/compiling.js @@ -0,0 +1,50 @@ +'use strict' + +/** + * Globals for benchmark.js + */ +global.proxyaddr = require('..') +global.createReq = createReq + +/** + * Module dependencies. + */ +const benchmark = require('benchmark') +const benchmarks = require('beautify-benchmark') + +const suite = new benchmark.Suite() + +suite.add({ + name: 're-compiling', + minSamples: 100, + fn: 'proxyaddr(req, "loopback")', + setup: 'req = createReq("127.0.0.1", "10.0.0.1")' +}) + +suite.add({ + name: 'pre-compiling', + minSamples: 100, + fn: 'proxyaddr(req, trust)', + setup: 'req = createReq("127.0.0.1", "10.0.0.1"); trust = proxyaddr.compile("loopback")' +}) + +suite.on('cycle', function onCycle (event) { + benchmarks.add(event.target) +}) + +suite.on('complete', function onComplete () { + benchmarks.log() +}) + +suite.run({ async: false }) + +function createReq (socketAddr, forwardedFor) { + return { + socket: { + remoteAddress: socketAddr + }, + headers: { + 'x-forwarded-for': (forwardedFor || '') + } + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/proxy-addr/benchmark/index.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/proxy-addr/benchmark/index.js new file mode 100644 index 0000000000000000000000000000000000000000..4b5af22e636034104db7f3146a5c80a43a53b2db --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/proxy-addr/benchmark/index.js @@ -0,0 +1,30 @@ +'use strict' + +const fs = require('node:fs') +const path = require('node:path') +const spawn = require('node:child_process').spawn + +const exe = process.argv[0] +const cwd = process.cwd() + +runScripts(fs.readdirSync(__dirname)) + +function runScripts (fileNames) { + const fileName = fileNames.shift() + + if (!fileName) return + if (!/\.js$/i.test(fileName)) return runScripts(fileNames) + if (fileName.toLowerCase() === 'index.js') return runScripts(fileNames) + + const fullPath = path.join(__dirname, fileName) + + console.log('> %s %s', exe, path.relative(cwd, fullPath)) + + const proc = spawn(exe, [fullPath], { + stdio: 'inherit' + }) + + proc.on('exit', function () { + runScripts(fileNames) + }) +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/proxy-addr/benchmark/kind.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/proxy-addr/benchmark/kind.js new file mode 100644 index 0000000000000000000000000000000000000000..239ccf947ac53d84eaa66b7381a84e7a2d91de60 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/proxy-addr/benchmark/kind.js @@ -0,0 +1,57 @@ +'use strict' + +/** + * Globals for benchmark.js + */ +global.proxyaddr = require('..') +global.createReq = createReq + +/** + * Module dependencies. + */ +const benchmark = require('benchmark') +const benchmarks = require('beautify-benchmark') + +const suite = new benchmark.Suite() + +suite.add({ + name: 'ipv4', + minSamples: 100, + fn: 'proxyaddr(req, trust)', + setup: 'req = createReq("127.0.0.1", "10.0.0.1"); trust = proxyaddr.compile("127.0.0.1")' +}) + +suite.add({ + name: 'ipv4-mapped', + minSamples: 100, + fn: 'proxyaddr(req, trust)', + setup: 'req = createReq("::ffff:7f00:1", "10.0.0.1"); trust = proxyaddr.compile("127.0.0.1")' +}) + +suite.add({ + name: 'ipv6', + minSamples: 100, + fn: 'proxyaddr(req, trust)', + setup: 'req = createReq("::1", "10.0.0.1"); trust = proxyaddr.compile("::1")' +}) + +suite.on('cycle', function onCycle (event) { + benchmarks.add(event.target) +}) + +suite.on('complete', function onComplete () { + benchmarks.log() +}) + +suite.run({ async: false }) + +function createReq (socketAddr, forwardedFor) { + return { + socket: { + remoteAddress: socketAddr + }, + headers: { + 'x-forwarded-for': (forwardedFor || '') + } + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/proxy-addr/benchmark/matching.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/proxy-addr/benchmark/matching.js new file mode 100644 index 0000000000000000000000000000000000000000..d584c6801d93048e64cd0b4f0a8b605c29df5ece --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/proxy-addr/benchmark/matching.js @@ -0,0 +1,78 @@ +'use strict' + +/** + * Globals for benchmark.js + */ +global.proxyaddr = require('..') +global.createReq = createReq + +/** + * Module dependencies. + */ +const benchmark = require('benchmark') +const benchmarks = require('beautify-benchmark') + +const suite = new benchmark.Suite() + +suite.add({ + name: 'trust none', + minSamples: 100, + fn: 'proxyaddr(req, trust)', + setup: 'req = createReq("127.0.0.1", "10.0.0.1"); trust = proxyaddr.compile([])' +}) + +suite.add({ + name: 'trust all', + minSamples: 100, + fn: 'proxyaddr(req, trust)', + setup: 'req = createReq("127.0.0.1", "10.0.0.1"); trust = function() {return true}' +}) + +suite.add({ + name: 'trust single', + minSamples: 100, + fn: 'proxyaddr(req, trust)', + setup: 'req = createReq("127.0.0.1", "10.0.0.1"); trust = proxyaddr.compile("127.0.0.1")' +}) + +suite.add({ + name: 'trust first', + minSamples: 100, + fn: 'proxyaddr(req, trust)', + setup: 'req = createReq("127.0.0.1", "10.0.0.1"); trust = function(a, i) {return i<1}' +}) + +suite.add({ + name: 'trust subnet', + minSamples: 100, + fn: 'proxyaddr(req, trust)', + setup: 'req = createReq("127.0.0.1", "10.0.0.1"); trust = proxyaddr.compile("127.0.0.1/8")' +}) + +suite.add({ + name: 'trust multiple', + minSamples: 100, + fn: 'proxyaddr(req, trust)', + setup: 'req = createReq("127.0.0.1", "10.0.0.1"); trust = proxyaddr.compile(["127.0.0.1", "10.0.0.1"])' +}) + +suite.on('cycle', function onCycle (event) { + benchmarks.add(event.target) +}) + +suite.on('complete', function onComplete () { + benchmarks.log() +}) + +suite.run({ async: false }) + +function createReq (socketAddr, forwardedFor) { + return { + socket: { + remoteAddress: socketAddr + }, + headers: { + 'x-forwarded-for': (forwardedFor || '') + } + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/proxy-addr/index.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/proxy-addr/index.js new file mode 100644 index 0000000000000000000000000000000000000000..4fabb199f2575486f050e04e021c8777f292e852 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/proxy-addr/index.js @@ -0,0 +1,334 @@ +/*! + * proxy-addr + * Copyright(c) 2021 Fastify collaborators + * Copyright(c) 2014-2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = proxyaddr +module.exports.default = proxyaddr +module.exports.proxyaddr = proxyaddr +module.exports.all = alladdrs +module.exports.compile = compile + +/** + * Module dependencies. + * @private + */ + +const forwarded = require('@fastify/forwarded') +const ipaddr = require('ipaddr.js') + +/** + * Variables. + * @private + */ + +const DIGIT_REGEXP = /^\d+$/u +const isip = ipaddr.isValid +const parseip = ipaddr.parse + +/** + * Pre-defined IP ranges. + * @private + */ + +const IP_RANGES = { + linklocal: ['169.254.0.0/16', 'fe80::/10'], + loopback: ['127.0.0.1/8', '::1/128'], + uniquelocal: ['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', 'fc00::/7'] +} + +/** + * Get all addresses in the request, optionally stopping + * at the first untrusted. + * + * @param {Object} request + * @param {Function|Array|String} [trust] + * @public + */ + +function alladdrs (req, trust) { + // get addresses + const addrs = forwarded(req) + + if (!trust) { + // Return all addresses + return addrs + } + + if (typeof trust !== 'function') { + trust = compile(trust) + } + + /* eslint-disable no-var */ + for (var i = 0; i < addrs.length - 1; i++) { + if (trust(addrs[i], i)) continue + + addrs.length = i + 1 + } + + return addrs +} + +/** + * Compile argument into trust function. + * + * @param {Array|String} val + * @private + */ + +function compile (val) { + if (!val) { + throw new TypeError('argument is required') + } + + let trust + + if (typeof val === 'string') { + trust = [val] + } else if (Array.isArray(val)) { + trust = val.slice() + } else { + throw new TypeError('unsupported trust argument') + } + + /* eslint-disable no-var */ + for (var i = 0; i < trust.length; i++) { + val = trust[i] + + if (!Object.prototype.hasOwnProperty.call(IP_RANGES, val)) { + continue + } + + // Splice in pre-defined range + val = IP_RANGES[val] + trust.splice.apply(trust, [i, 1].concat(val)) + i += val.length - 1 + } + + return compileTrust(compileRangeSubnets(trust)) +} + +/** + * Compile `arr` elements into range subnets. + * + * @param {Array} arr + * @private + */ + +function compileRangeSubnets (arr) { + const rangeSubnets = new Array(arr.length) + + /* eslint-disable no-var */ + for (var i = 0; i < arr.length; i++) { + rangeSubnets[i] = parseipNotation(arr[i]) + } + + return rangeSubnets +} + +/** + * Compile range subnet array into trust function. + * + * @param {Array} rangeSubnets + * @private + */ + +function compileTrust (rangeSubnets) { + // Return optimized function based on length + const len = rangeSubnets.length + return len === 0 + ? trustNone + : len === 1 + ? trustSingle(rangeSubnets[0]) + : trustMulti(rangeSubnets) +} + +/** + * Parse IP notation string into range subnet. + * + * @param {String} note + * @private + */ + +function parseipNotation (note) { + const pos = note.lastIndexOf('/') + const str = pos !== -1 + ? note.substring(0, pos) + : note + + if (!isip(str)) { + throw new TypeError('invalid IP address: ' + str) + } + + let ip = parseip(str) + + if (pos === -1 && ip.kind() === 'ipv6' && ip.isIPv4MappedAddress()) { + // Store as IPv4 + ip = ip.toIPv4Address() + } + + const max = ip.kind() === 'ipv6' + ? 128 + : 32 + + let range = pos !== -1 + ? note.substring(pos + 1, note.length) + : null + + if (range === null) { + range = max + } else if (DIGIT_REGEXP.test(range)) { + range = parseInt(range, 10) + } else if (ip.kind() === 'ipv4' && isip(range)) { + range = parseNetmask(range) + } else { + range = null + } + + if (range <= 0 || range > max) { + throw new TypeError('invalid range on address: ' + note) + } + + return [ip, range] +} + +/** + * Parse netmask string into CIDR range. + * + * @param {String} netmask + * @private + */ + +function parseNetmask (netmask) { + const ip = parseip(netmask) + const kind = ip.kind() + + return kind === 'ipv4' + ? ip.prefixLengthFromSubnetMask() + : null +} + +/** + * Determine address of proxied request. + * + * @param {Object} request + * @param {Function|Array|String} trust + * @public + */ + +function proxyaddr (req, trust) { + if (!req) { + throw new TypeError('req argument is required') + } + + if (!trust) { + throw new TypeError('trust argument is required') + } + + const addrs = alladdrs(req, trust) + const addr = addrs[addrs.length - 1] + + return addr +} + +/** + * Static trust function to trust nothing. + * + * @private + */ + +function trustNone () { + return false +} + +/** + * Compile trust function for multiple subnets. + * + * @param {Array} subnets + * @private + */ + +function trustMulti (subnets) { + return function trust (addr) { + if (!isip(addr)) return false + + const ip = parseip(addr) + let ipconv + const kind = ip.kind() + + /* eslint-disable no-var */ + for (var i = 0; i < subnets.length; i++) { + const subnet = subnets[i] + const subnetip = subnet[0] + const subnetkind = subnetip.kind() + const subnetrange = subnet[1] + let trusted = ip + + if (kind !== subnetkind) { + if (subnetkind === 'ipv4' && !ip.isIPv4MappedAddress()) { + // Incompatible IP addresses + continue + } + + if (!ipconv) { + // Convert IP to match subnet IP kind + ipconv = subnetkind === 'ipv4' + ? ip.toIPv4Address() + : ip.toIPv4MappedAddress() + } + + trusted = ipconv + } + + if (trusted.match(subnetip, subnetrange)) { + return true + } + } + + return false + } +} + +/** + * Compile trust function for single subnet. + * + * @param {Object} subnet + * @private + */ + +function trustSingle (subnet) { + const subnetip = subnet[0] + const subnetkind = subnetip.kind() + const subnetisipv4 = subnetkind === 'ipv4' + const subnetrange = subnet[1] + + return function trust (addr) { + if (!isip(addr)) return false + + let ip = parseip(addr) + const kind = ip.kind() + + if (kind !== subnetkind) { + if (subnetisipv4 && !ip.isIPv4MappedAddress()) { + // Incompatible IP addresses + return false + } + + // Convert IP to match subnet IP kind + ip = subnetisipv4 + ? ip.toIPv4Address() + : ip.toIPv4MappedAddress() + } + + return ip.match(subnetip, subnetrange) + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/proxy-addr/package.json b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/proxy-addr/package.json new file mode 100644 index 0000000000000000000000000000000000000000..719d19388636b5cd945503e0d8c8cff98a7c09d4 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/proxy-addr/package.json @@ -0,0 +1,45 @@ +{ + "name": "@fastify/proxy-addr", + "description": "Determine address of proxied request", + "version": "5.0.0", + "main": "index.js", + "type": "commonjs", + "types": "types/index.d.ts", + "author": "Douglas Christopher Wilson ", + "license": "MIT", + "keywords": [ + "ip", + "proxy", + "x-forwarded-for" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/fastify/proxy-addr.git" + }, + "bugs": { + "url": "https://github.com/fastify/proxy-addr/issues" + }, + "homepage": "https://github.com/fastify/proxy-addr#readme", + "dependencies": { + "@fastify/forwarded": "^3.0.0", + "ipaddr.js": "^2.1.0" + }, + "devDependencies": { + "@fastify/pre-commit": "^2.1.0", + "@types/node": "^22.0.0", + "beautify-benchmark": "0.2.4", + "benchmark": "2.1.4", + "c8": "^7.14.0", + "standard": "^17.1.0", + "tape": "^5.7.5", + "tsd": "^0.31.0" + }, + "scripts": { + "bench": "node benchmark/index.js", + "lint": "standard", + "lint:fix": "standard --fix", + "test": "npm run test:unit && npm run test:typescript", + "test:typescript": "tsd", + "test:unit": "c8 tape test/**/*.js" + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/proxy-addr/test/.eslintrc.yml b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/proxy-addr/test/.eslintrc.yml new file mode 100644 index 0000000000000000000000000000000000000000..9808c3b2b6602da61eb4afcb4caf33368e3e2bd4 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/proxy-addr/test/.eslintrc.yml @@ -0,0 +1,2 @@ +env: + mocha: true diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/proxy-addr/test/all.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/proxy-addr/test/all.js new file mode 100644 index 0000000000000000000000000000000000000000..44da283d71b859af84a3515076fc692681a1c430 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/proxy-addr/test/all.js @@ -0,0 +1,62 @@ +'use strict' + +const test = require('tape') +const proxyaddr = require('..') + +test('argument req should be required', function (t) { + t.throws(proxyaddr.all, /req.*required/u) + t.end() +}) + +test('argument trustshould be optional', function (t) { + const req = createReq('127.0.0.1') + t.doesNotThrow(proxyaddr.all.bind(null, req)) + t.end() +}) + +test('with no headers should return socket address', function (t) { + const req = createReq('127.0.0.1') + t.same(proxyaddr.all(req), ['127.0.0.1']) + t.end() +}) + +test('with x-forwarded-for header should include x-forwarded-for', function (t) { + const req = createReq('127.0.0.1', { + 'x-forwarded-for': '10.0.0.1' + }) + t.same(proxyaddr.all(req), ['127.0.0.1', '10.0.0.1']) + t.end() +}) + +test('with x-forwarded-for header should include x-forwarded-for in correct order', function (t) { + const req = createReq('127.0.0.1', { + 'x-forwarded-for': '10.0.0.1, 10.0.0.2' + }) + t.same(proxyaddr.all(req), ['127.0.0.1', '10.0.0.2', '10.0.0.1']) + t.end() +}) + +test('with trust argument should stop at first untrusted', function (t) { + const req = createReq('127.0.0.1', { + 'x-forwarded-for': '10.0.0.1, 10.0.0.2' + }) + t.same(proxyaddr.all(req, '127.0.0.1'), ['127.0.0.1', '10.0.0.2']) + t.end() +}) + +test('with trust argument should be only socket address for no trust', function (t) { + const req = createReq('127.0.0.1', { + 'x-forwarded-for': '10.0.0.1, 10.0.0.2' + }) + t.same(proxyaddr.all(req, []), ['127.0.0.1']) + t.end() +}) + +function createReq (socketAddr, headers) { + return { + socket: { + remoteAddress: socketAddr + }, + headers: headers || {} + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/proxy-addr/test/base.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/proxy-addr/test/base.js new file mode 100644 index 0000000000000000000000000000000000000000..77675e181200ee06a2d1333412d9f8b0300cdb96 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/proxy-addr/test/base.js @@ -0,0 +1,417 @@ +'use strict' + +const test = require('tape') +const proxyaddr = require('..') + +test('req should be required', function (t) { + t.throws(proxyaddr, /req.*required/u) + t.end() +}) + +test('trust should be required', function (t) { + const req = createReq('127.0.0.1') + t.throws(proxyaddr.bind(null, req), /trust.*required/u) + t.end() +}) + +test('trust should accept a function', function (t) { + const req = createReq('127.0.0.1') + t.doesNotThrow(proxyaddr.bind(null, req, all)) + t.end() +}) + +test('trust should accept an array', function (t) { + const req = createReq('127.0.0.1') + t.doesNotThrow(proxyaddr.bind(null, req, [])) + t.end() +}) + +test('trust should accept a string', function (t) { + const req = createReq('127.0.0.1') + t.doesNotThrow(proxyaddr.bind(null, req, '127.0.0.1')) + t.end() +}) + +test('trust should reject a number', function (t) { + const req = createReq('127.0.0.1') + t.throws(proxyaddr.bind(null, req, 42), /unsupported trust argument/u) + t.end() +}) + +test('trust should accept IPv4', function (t) { + const req = createReq('127.0.0.1') + t.doesNotThrow(proxyaddr.bind(null, req, '127.0.0.1')) + t.end() +}) + +test('trust should accept IPv6', function (t) { + const req = createReq('127.0.0.1') + t.doesNotThrow(proxyaddr.bind(null, req, '::1')) + t.end() +}) + +test('trust should accept IPv4-style IPv6', function (t) { + const req = createReq('127.0.0.1') + t.doesNotThrow(proxyaddr.bind(null, req, '::ffff:127.0.0.1')) + t.end() +}) + +test('trust should accept pre-defined names', function (t) { + const req = createReq('127.0.0.1') + t.doesNotThrow(proxyaddr.bind(null, req, 'loopback')) + t.end() +}) + +test('trust should accept pre-defined names in array', function (t) { + const req = createReq('127.0.0.1') + t.doesNotThrow(proxyaddr.bind(null, req, ['loopback', '10.0.0.1'])) + t.end() +}) + +test('trust should not alter input array', function (t) { + const arr = ['loopback', '10.0.0.1'] + const req = createReq('127.0.0.1') + t.doesNotThrow(proxyaddr.bind(null, req, arr)) + t.same(arr, ['loopback', '10.0.0.1']) + t.end() +}) + +test('trust should reject non-IP', function (t) { + const req = createReq('127.0.0.1') + t.throws(proxyaddr.bind(null, req, 'blargh'), /invalid IP address/u) + t.throws(proxyaddr.bind(null, req, '10.0.300.1'), /invalid IP address/u) + t.throws(proxyaddr.bind(null, req, '::ffff:30.168.1.9000'), /invalid IP address/u) + t.throws(proxyaddr.bind(null, req, '-1'), /invalid IP address/u) + t.end() +}) + +test('trust should reject bad CIDR', function (t) { + const req = createReq('127.0.0.1') + t.throws(proxyaddr.bind(null, req, '10.0.0.1/internet'), /invalid range on address/u) + t.throws(proxyaddr.bind(null, req, '10.0.0.1/6000'), /invalid range on address/u) + t.throws(proxyaddr.bind(null, req, '::1/6000'), /invalid range on address/u) + t.throws(proxyaddr.bind(null, req, '::ffff:a00:2/136'), /invalid range on address/u) + t.throws(proxyaddr.bind(null, req, '::ffff:a00:2/-1'), /invalid range on address/u) + t.end() +}) + +test('trust should reject bad netmask', function (t) { + const req = createReq('127.0.0.1') + t.throws(proxyaddr.bind(null, req, '10.0.0.1/255.0.255.0'), /invalid range on address/u) + t.throws(proxyaddr.bind(null, req, '10.0.0.1/ffc0::'), /invalid range on address/u) + t.throws(proxyaddr.bind(null, req, 'fe80::/ffc0::'), /invalid range on address/u) + t.throws(proxyaddr.bind(null, req, 'fe80::/255.255.255.0'), /invalid range on address/u) + t.throws(proxyaddr.bind(null, req, '::ffff:a00:2/255.255.255.0'), /invalid range on address/u) + t.end() +}) + +test('trust should be invoked as trust(addr, i)', function (t) { + const log = [] + const req = createReq('127.0.0.1', { + 'x-forwarded-for': '192.168.0.1, 10.0.0.1' + }) + + proxyaddr(req, function (addr, i) { + return log.push(Array.prototype.slice.call(arguments)) + }) + + t.same(log, [ + ['127.0.0.1', 0], + ['10.0.0.1', 1] + ]) + + t.end() +}) + +test('with all trusted should return socket address wtesth no headers', function (t) { + const req = createReq('127.0.0.1') + t.equal(proxyaddr(req, all), '127.0.0.1') + t.end() +}) + +test('with all trusted should return header value', function (t) { + const req = createReq('127.0.0.1', { + 'x-forwarded-for': '10.0.0.1' + }) + t.equal(proxyaddr(req, all), '10.0.0.1') + t.end() +}) + +test('with all trusted should return furthest header value', function (t) { + const req = createReq('127.0.0.1', { + 'x-forwarded-for': '10.0.0.1, 10.0.0.2' + }) + t.equal(proxyaddr(req, all), '10.0.0.1') + t.end() +}) + +test('with none trusted should return socket address wtesth no headers', function (t) { + const req = createReq('127.0.0.1') + t.equal(proxyaddr(req, none), '127.0.0.1') + t.end() +}) + +test('with none trusted should return socket address wtesth headers', function (t) { + const req = createReq('127.0.0.1', { + 'x-forwarded-for': '10.0.0.1, 10.0.0.2' + }) + t.equal(proxyaddr(req, none), '127.0.0.1') + t.end() +}) + +test('with some trusted should return socket address wtesth no headers', function (t) { + const req = createReq('127.0.0.1') + t.equal(proxyaddr(req, trust10x), '127.0.0.1') + t.end() +}) + +test('with some trusted should return socket address when not trusted', function (t) { + const req = createReq('127.0.0.1', { + 'x-forwarded-for': '10.0.0.1, 10.0.0.2' + }) + t.equal(proxyaddr(req, trust10x), '127.0.0.1') + t.end() +}) + +test('with some trusted should return header when socket trusted', function (t) { + const req = createReq('10.0.0.1', { + 'x-forwarded-for': '192.168.0.1' + }) + t.equal(proxyaddr(req, trust10x), '192.168.0.1') + t.end() +}) + +test('with some trusted should return first untrusted after trusted', function (t) { + const req = createReq('10.0.0.1', { + 'x-forwarded-for': '192.168.0.1, 10.0.0.2' + }) + t.equal(proxyaddr(req, trust10x), '192.168.0.1') + t.end() +}) + +test('with some trusted should not skip untrusted', function (t) { + const req = createReq('10.0.0.1', { + 'x-forwarded-for': '10.0.0.3, 192.168.0.1, 10.0.0.2' + }) + t.equal(proxyaddr(req, trust10x), '192.168.0.1') + t.end() +}) + +test('when given array should accept ltesteral IP addresses', function (t) { + const req = createReq('10.0.0.1', { + 'x-forwarded-for': '192.168.0.1, 10.0.0.2' + }) + t.equal(proxyaddr(req, ['10.0.0.1', '10.0.0.2']), '192.168.0.1') + t.end() +}) + +test('when given array should not trust non-IP addresses', function (t) { + const req = createReq('10.0.0.1', { + 'x-forwarded-for': '192.168.0.1, 10.0.0.2, localhost' + }) + t.equal(proxyaddr(req, ['10.0.0.1', '10.0.0.2']), 'localhost') + t.end() +}) + +test('when given array should return socket address if none match', function (t) { + const req = createReq('10.0.0.1', { + 'x-forwarded-for': '192.168.0.1, 10.0.0.2' + }) + t.equal(proxyaddr(req, ['127.0.0.1', '192.168.0.100']), '10.0.0.1') + t.end() +}) + +test('when array empty should return socket address ', function (t) { + const req = createReq('127.0.0.1') + t.equal(proxyaddr(req, []), '127.0.0.1') + t.end() +}) + +test('when array empty should return socket address wtesth headers', function (t) { + const req = createReq('127.0.0.1', { + 'x-forwarded-for': '10.0.0.1, 10.0.0.2' + }) + t.equal(proxyaddr(req, []), '127.0.0.1') + t.end() +}) + +test('when given IPv4 addresses should accept ltesteral IP addresses', function (t) { + const req = createReq('10.0.0.1', { + 'x-forwarded-for': '192.168.0.1, 10.0.0.2' + }) + t.equal(proxyaddr(req, ['10.0.0.1', '10.0.0.2']), '192.168.0.1') + t.end() +}) + +test('when given IPv4 addresses should accept CIDR notation', function (t) { + const req = createReq('10.0.0.1', { + 'x-forwarded-for': '192.168.0.1, 10.0.0.200' + }) + t.equal(proxyaddr(req, '10.0.0.2/26'), '10.0.0.200') + t.end() +}) + +test('when given IPv4 addresses should accept netmask notation', function (t) { + const req = createReq('10.0.0.1', { + 'x-forwarded-for': '192.168.0.1, 10.0.0.200' + }) + t.equal(proxyaddr(req, '10.0.0.2/255.255.255.192'), '10.0.0.200') + t.end() +}) + +test('when given IPv6 addresses should accept ltesteral IP addresses', function (t) { + const req = createReq('fe80::1', { + 'x-forwarded-for': '2002:c000:203::1, fe80::2' + }) + t.equal(proxyaddr(req, ['fe80::1', 'fe80::2']), '2002:c000:203::1') + t.end() +}) + +test('when given IPv6 addresses should accept CIDR notation', function (t) { + const req = createReq('fe80::1', { + 'x-forwarded-for': '2002:c000:203::1, fe80::ff00' + }) + t.equal(proxyaddr(req, 'fe80::/125'), 'fe80::ff00') + t.end() +}) + +test('with IP version mixed should match respective versions', function (t) { + const req = createReq('::1', { + 'x-forwarded-for': '2002:c000:203::1' + }) + t.equal(proxyaddr(req, ['127.0.0.1', '::1']), '2002:c000:203::1') + t.end() +}) + +test('with IP version mixed should not match IPv4 to IPv6', function (t) { + const req = createReq('::1', { + 'x-forwarded-for': '2002:c000:203::1' + }) + t.equal(proxyaddr(req, '127.0.0.1'), '::1') + t.end() +}) + +test('when IPv4-mapped IPv6 addresses should match IPv4 trust to IPv6 request', function (t) { + const req = createReq('::ffff:a00:1', { + 'x-forwarded-for': '192.168.0.1, 10.0.0.2' + }) + t.equal(proxyaddr(req, ['10.0.0.1', '10.0.0.2']), '192.168.0.1') + t.end() +}) + +test('when IPv4-mapped IPv6 addresses should match IPv4 netmask trust to IPv6 request', function (t) { + const req = createReq('::ffff:a00:1', { + 'x-forwarded-for': '192.168.0.1, 10.0.0.2' + }) + t.equal(proxyaddr(req, ['10.0.0.1/16']), '192.168.0.1') + t.end() +}) + +test('when IPv4-mapped IPv6 addresses should match IPv6 trust to IPv4 request', function (t) { + const req = createReq('10.0.0.1', { + 'x-forwarded-for': '192.168.0.1, 10.0.0.2' + }) + t.equal(proxyaddr(req, ['::ffff:a00:1', '::ffff:a00:2']), '192.168.0.1') + t.end() +}) + +test('when IPv4-mapped IPv6 addresses should match CIDR notation for IPv4-mapped address', function (t) { + const req = createReq('10.0.0.1', { + 'x-forwarded-for': '192.168.0.1, 10.0.0.200' + }) + t.equal(proxyaddr(req, '::ffff:a00:2/122'), '10.0.0.200') + t.end() +}) + +test('when IPv4-mapped IPv6 addresses should match CIDR notation for IPv4-mapped address mixed wtesth IPv6 CIDR', function (t) { + const req = createReq('10.0.0.1', { + 'x-forwarded-for': '192.168.0.1, 10.0.0.200' + }) + t.equal(proxyaddr(req, ['::ffff:a00:2/122', 'fe80::/125']), '10.0.0.200') + t.end() +}) + +test('when IPv4-mapped IPv6 addresses should match CIDR notation for IPv4-mapped address mixed wtesth IPv4 addresses', function (t) { + const req = createReq('10.0.0.1', { + 'x-forwarded-for': '192.168.0.1, 10.0.0.200' + }) + t.equal(proxyaddr(req, ['::ffff:a00:2/122', '127.0.0.1']), '10.0.0.200') + t.end() +}) + +test('when given predefined names should accept single pre-defined name', function (t) { + const req = createReq('fe80::1', { + 'x-forwarded-for': '2002:c000:203::1, fe80::2' + }) + t.equal(proxyaddr(req, 'linklocal'), '2002:c000:203::1') + t.end() +}) + +test('when given predefined names should accept multiple pre-defined names', function (t) { + const req = createReq('::1', { + 'x-forwarded-for': '2002:c000:203::1, fe80::2' + }) + t.equal(proxyaddr(req, ['loopback', 'linklocal']), '2002:c000:203::1') + t.end() +}) + +test('when header contains non-ip addresses should stop at first non-ip after trusted', function (t) { + const req = createReq('127.0.0.1', { + 'x-forwarded-for': 'myrouter, 127.0.0.1, proxy' + }) + t.equal(proxyaddr(req, '127.0.0.1'), 'proxy') + t.end() +}) + +test('when header contains non-ip addresses should stop at first malformed ip after trusted', function (t) { + const req = createReq('127.0.0.1', { + 'x-forwarded-for': 'myrouter, 127.0.0.1, ::8:8:8:8:8:8:8:8:8' + }) + t.equal(proxyaddr(req, '127.0.0.1'), '::8:8:8:8:8:8:8:8:8') + t.end() +}) + +test('when header contains non-ip addresses should provide all values to function', function (t) { + const log = [] + const req = createReq('127.0.0.1', { + 'x-forwarded-for': 'myrouter, 127.0.0.1, proxy' + }) + + proxyaddr(req, function (addr, i) { + return log.push(Array.prototype.slice.call(arguments)) + }) + + t.same(log, [ + ['127.0.0.1', 0], + ['proxy', 1], + ['127.0.0.1', 2] + ]) + t.end() +}) + +test('when socket address undefined should return undefined as address', function (t) { + const req = createReq(undefined) + t.equal(proxyaddr(req, '127.0.0.1'), undefined) + t.end() +}) + +test('when socket address undefined should return undefined even wtesth trusted headers', function (t) { + const req = createReq(undefined, { + 'x-forwarded-for': '127.0.0.1, 10.0.0.1' + }) + t.equal(proxyaddr(req, '127.0.0.1'), undefined) + t.end() +}) + +function createReq (socketAddr, headers) { + return { + socket: { + remoteAddress: socketAddr + }, + headers: headers || {} + } +} + +function all () { return true } +function none () { return false } +function trust10x (addr) { return /^10\./u.test(addr) } diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/proxy-addr/test/compile.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/proxy-addr/test/compile.js new file mode 100644 index 0000000000000000000000000000000000000000..599a73dcf5a5b961dbb0200ff005e67b77866cf8 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/proxy-addr/test/compile.js @@ -0,0 +1,70 @@ +'use strict' + +const test = require('tape') +const proxyaddr = require('..') + +test('trust arg should be required', function (t) { + t.throws(proxyaddr.compile, /argument.*required/u) + t.end() +}) + +test('trust arg should accept an array', function (t) { + t.equal(typeof proxyaddr.compile([]), 'function') + t.end() +}) + +test('trust arg should accept a string', function (t) { + t.equal(typeof proxyaddr.compile('127.0.0.1'), 'function') + t.end() +}) + +test('trust arg should reject a number', function (t) { + t.throws(proxyaddr.compile.bind(null, 42), /unsupported trust argument/u) + t.end() +}) + +test('trust arg should accept IPv4', function (t) { + t.equal(typeof proxyaddr.compile('127.0.0.1'), 'function') + t.end() +}) + +test('trust arg should accept IPv6', function (t) { + t.equal(typeof proxyaddr.compile('::1'), 'function') + t.end() +}) + +test('trust arg should accept IPv4-style IPv6', function (t) { + t.equal(typeof proxyaddr.compile('::ffff:127.0.0.1'), 'function') + t.end() +}) + +test('trust arg should accept pre-defined names', function (t) { + t.equal(typeof proxyaddr.compile('loopback'), 'function') + t.end() +}) + +test('trust arg should accept pre-defined names in array', function (t) { + t.equal(typeof proxyaddr.compile(['loopback', '10.0.0.1']), 'function') + t.end() +}) + +test('trust arg should reject non-IP', function (t) { + t.throws(proxyaddr.compile.bind(null, 'blargh'), /invalid IP address/u) + t.throws(proxyaddr.compile.bind(null, '-1'), /invalid IP address/u) + t.end() +}) + +test('trust arg should reject bad CIDR', function (t) { + t.throws(proxyaddr.compile.bind(null, '10.0.0.1/6000'), /invalid range on address/u) + t.throws(proxyaddr.compile.bind(null, '::1/6000'), /invalid range on address/u) + t.throws(proxyaddr.compile.bind(null, '::ffff:a00:2/136'), /invalid range on address/u) + t.throws(proxyaddr.compile.bind(null, '::ffff:a00:2/-46'), /invalid range on address/u) + t.end() +}) + +test('trust arg should not alter input array', function (t) { + const arr = ['loopback', '10.0.0.1'] + t.equal(typeof proxyaddr.compile(arr), 'function') + t.same(arr, ['loopback', '10.0.0.1']) + t.end() +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/proxy-addr/types/index.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/proxy-addr/types/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e554f5008d04c4be28679d2b347a2a7f086c6985 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/proxy-addr/types/index.d.ts @@ -0,0 +1,18 @@ +/// + +import { IncomingMessage } from 'http'; + +type FastifyProxyAddr = typeof proxyaddr + +declare function proxyaddr(req: IncomingMessage, trust: proxyaddr.Address | proxyaddr.Address[] | ((addr: string, i: number) => boolean)): string; + +declare namespace proxyaddr { + export function all(req: IncomingMessage, trust?: Address | Address[] | ((addr: string, i: number) => boolean)): string[]; + export function compile(val: Address | Address[]): (addr: string, i: number) => boolean; + + export type Address = 'loopback' | 'linklocal' | 'uniquelocal' | string; + + export const proxyAddr: FastifyProxyAddr + export { proxyAddr as default } +} +export = proxyaddr; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/proxy-addr/types/index.test-d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/proxy-addr/types/index.test-d.ts new file mode 100644 index 0000000000000000000000000000000000000000..067e761c99eff86823eebcde2885b9eb9d46a169 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/proxy-addr/types/index.test-d.ts @@ -0,0 +1,27 @@ +import proxyaddr from '..'; +import { createServer } from 'http'; + +createServer(req => { + // $ExpectType string + proxyaddr(req, addr => addr === '127.0.0.1'); + proxyaddr(req, (addr, i) => i < 1); + + proxyaddr(req, '127.0.0.1'); + proxyaddr(req, ['127.0.0.0/8', '10.0.0.0/8']); + proxyaddr(req, ['127.0.0.0/255.0.0.0', '192.168.0.0/255.255.0.0']); + + proxyaddr(req, '::1'); + proxyaddr(req, ['::1/128', 'fe80::/10']); + + proxyaddr(req, 'loopback'); + proxyaddr(req, ['loopback', 'fc00:ac:1ab5:fff::1/64']); + + // $ExpectType string[] + proxyaddr.all(req); + proxyaddr.all(req, 'loopback'); + + const trust = proxyaddr.compile('localhost'); + proxyaddr.compile(['localhost']); + trust; // $ExpectType (addr: string, i: number) => boolean + proxyaddr(req, trust); +}); \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/.gitattributes b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..a0e7df931f90e194cc6b80313f8f07744d9fc6d8 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/.gitattributes @@ -0,0 +1,2 @@ +# Set default behavior to automatically convert line endings +* text=auto eol=lf diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/.github/dependabot.yml b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..be225b0af94422138289ed0c549ab7f08656bfab --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/.github/dependabot.yml @@ -0,0 +1,13 @@ +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "monthly" + open-pull-requests-limit: 10 + + - package-ecosystem: "npm" + directory: "/" + schedule: + interval: "monthly" + open-pull-requests-limit: 10 \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/.github/workflows/ci.yml b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/.github/workflows/ci.yml new file mode 100644 index 0000000000000000000000000000000000000000..fd45202abff682784e3a60d54fbfee567d304b26 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/.github/workflows/ci.yml @@ -0,0 +1,28 @@ +name: CI + +on: + push: + branches: + - main + - next + - 'v*' + paths-ignore: + - 'docs/**' + - '*.md' + pull_request: + paths-ignore: + - 'docs/**' + - '*.md' + +permissions: + contents: read + +jobs: + test: + permissions: + contents: write + pull-requests: write + uses: fastify/workflows/.github/workflows/plugins-ci.yml@v5 + with: + license-check: true + lint: true diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/HISTORY.md b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/HISTORY.md new file mode 100644 index 0000000000000000000000000000000000000000..bebfd46c954f035abdcababbbffb9eb825d15650 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/HISTORY.md @@ -0,0 +1,521 @@ +0.18.0 / 2022-03-23 +=================== + + * Fix emitted 416 error missing headers property + * Limit the headers removed for 304 response + * deps: depd@2.0.0 + - Replace internal `eval` usage with `Function` constructor + - Use instance methods on `process` to check for listeners + * deps: destroy@1.2.0 + * deps: http-errors@2.0.0 + - deps: depd@2.0.0 + - deps: statuses@2.0.1 + * deps: on-finished@2.4.1 + * deps: statuses@2.0.1 + +0.17.2 / 2021-12-11 +=================== + + * pref: ignore empty http tokens + * deps: http-errors@1.8.1 + - deps: inherits@2.0.4 + - deps: toidentifier@1.0.1 + - deps: setprototypeof@1.2.0 + * deps: ms@2.1.3 + +0.17.1 / 2019-05-10 +=================== + + * Set stricter CSP header in redirect & error responses + * deps: range-parser@~1.2.1 + +0.17.0 / 2019-05-03 +=================== + + * deps: http-errors@~1.7.2 + - Set constructor name when possible + - Use `toidentifier` module to make class names + - deps: depd@~1.1.2 + - deps: setprototypeof@1.1.1 + - deps: statuses@'>= 1.5.0 < 2' + * deps: mime@1.6.0 + - Add extensions for JPEG-2000 images + - Add new `font/*` types from IANA + - Add WASM mapping + - Update `.bdoc` to `application/bdoc` + - Update `.bmp` to `image/bmp` + - Update `.m4a` to `audio/mp4` + - Update `.rtf` to `application/rtf` + - Update `.wav` to `audio/wav` + - Update `.xml` to `application/xml` + - Update generic extensions to `application/octet-stream`: + `.deb`, `.dll`, `.dmg`, `.exe`, `.iso`, `.msi` + - Use mime-score module to resolve extension conflicts + * deps: ms@2.1.1 + - Add `week`/`w` support + - Fix negative number handling + * deps: statuses@~1.5.0 + * perf: remove redundant `path.normalize` call + +0.16.2 / 2018-02-07 +=================== + + * Fix incorrect end tag in default error & redirects + * deps: depd@~1.1.2 + - perf: remove argument reassignment + * deps: encodeurl@~1.0.2 + - Fix encoding `%` as last character + * deps: statuses@~1.4.0 + +0.16.1 / 2017-09-29 +=================== + + * Fix regression in edge-case behavior for empty `path` + +0.16.0 / 2017-09-27 +=================== + + * Add `immutable` option + * Fix missing `` in default error & redirects + * Use instance methods on steam to check for listeners + * deps: mime@1.4.1 + - Add 70 new types for file extensions + - Set charset as "UTF-8" for .js and .json + * perf: improve path validation speed + +0.15.6 / 2017-09-22 +=================== + + * deps: debug@2.6.9 + * perf: improve `If-Match` token parsing + +0.15.5 / 2017-09-20 +=================== + + * deps: etag@~1.8.1 + - perf: replace regular expression with substring + * deps: fresh@0.5.2 + - Fix handling of modified headers with invalid dates + - perf: improve ETag match loop + - perf: improve `If-None-Match` token parsing + +0.15.4 / 2017-08-05 +=================== + + * deps: debug@2.6.8 + * deps: depd@~1.1.1 + - Remove unnecessary `Buffer` loading + * deps: http-errors@~1.6.2 + - deps: depd@1.1.1 + +0.15.3 / 2017-05-16 +=================== + + * deps: debug@2.6.7 + - deps: ms@2.0.0 + * deps: ms@2.0.0 + +0.15.2 / 2017-04-26 +=================== + + * deps: debug@2.6.4 + - Fix `DEBUG_MAX_ARRAY_LENGTH` + - deps: ms@0.7.3 + * deps: ms@1.0.0 + +0.15.1 / 2017-03-04 +=================== + + * Fix issue when `Date.parse` does not return `NaN` on invalid date + * Fix strict violation in broken environments + +0.15.0 / 2017-02-25 +=================== + + * Support `If-Match` and `If-Unmodified-Since` headers + * Add `res` and `path` arguments to `directory` event + * Remove usage of `res._headers` private field + - Improves compatibility with Node.js 8 nightly + * Send complete HTML document in redirect & error responses + * Set default CSP header in redirect & error responses + * Use `res.getHeaderNames()` when available + * Use `res.headersSent` when available + * deps: debug@2.6.1 + - Allow colors in workers + - Deprecated `DEBUG_FD` environment variable set to `3` or higher + - Fix error when running under React Native + - Use same color for same namespace + - deps: ms@0.7.2 + * deps: etag@~1.8.0 + * deps: fresh@0.5.0 + - Fix false detection of `no-cache` request directive + - Fix incorrect result when `If-None-Match` has both `*` and ETags + - Fix weak `ETag` matching to match spec + - perf: delay reading header values until needed + - perf: enable strict mode + - perf: hoist regular expressions + - perf: remove duplicate conditional + - perf: remove unnecessary boolean coercions + - perf: skip checking modified time if ETag check failed + - perf: skip parsing `If-None-Match` when no `ETag` header + - perf: use `Date.parse` instead of `new Date` + * deps: http-errors@~1.6.1 + - Make `message` property enumerable for `HttpError`s + - deps: setprototypeof@1.0.3 + +0.14.2 / 2017-01-23 +=================== + + * deps: http-errors@~1.5.1 + - deps: inherits@2.0.3 + - deps: setprototypeof@1.0.2 + - deps: statuses@'>= 1.3.1 < 2' + * deps: ms@0.7.2 + * deps: statuses@~1.3.1 + +0.14.1 / 2016-06-09 +=================== + + * Fix redirect error when `path` contains raw non-URL characters + * Fix redirect when `path` starts with multiple forward slashes + +0.14.0 / 2016-06-06 +=================== + + * Add `acceptRanges` option + * Add `cacheControl` option + * Attempt to combine multiple ranges into single range + * Correctly inherit from `Stream` class + * Fix `Content-Range` header in 416 responses when using `start`/`end` options + * Fix `Content-Range` header missing from default 416 responses + * Ignore non-byte `Range` headers + * deps: http-errors@~1.5.0 + - Add `HttpError` export, for `err instanceof createError.HttpError` + - Support new code `421 Misdirected Request` + - Use `setprototypeof` module to replace `__proto__` setting + - deps: inherits@2.0.1 + - deps: statuses@'>= 1.3.0 < 2' + - perf: enable strict mode + * deps: range-parser@~1.2.0 + - Fix incorrectly returning -1 when there is at least one valid range + - perf: remove internal function + * deps: statuses@~1.3.0 + - Add `421 Misdirected Request` + - perf: enable strict mode + * perf: remove argument reassignment + +0.13.2 / 2016-03-05 +=================== + + * Fix invalid `Content-Type` header when `send.mime.default_type` unset + +0.13.1 / 2016-01-16 +=================== + + * deps: depd@~1.1.0 + - Support web browser loading + - perf: enable strict mode + * deps: destroy@~1.0.4 + - perf: enable strict mode + * deps: escape-html@~1.0.3 + - perf: enable strict mode + - perf: optimize string replacement + - perf: use faster string coercion + * deps: range-parser@~1.0.3 + - perf: enable strict mode + +0.13.0 / 2015-06-16 +=================== + + * Allow Node.js HTTP server to set `Date` response header + * Fix incorrectly removing `Content-Location` on 304 response + * Improve the default redirect response headers + * Send appropriate headers on default error response + * Use `http-errors` for standard emitted errors + * Use `statuses` instead of `http` module for status messages + * deps: escape-html@1.0.2 + * deps: etag@~1.7.0 + - Improve stat performance by removing hashing + * deps: fresh@0.3.0 + - Add weak `ETag` matching support + * deps: on-finished@~2.3.0 + - Add defined behavior for HTTP `CONNECT` requests + - Add defined behavior for HTTP `Upgrade` requests + - deps: ee-first@1.1.1 + * perf: enable strict mode + * perf: remove unnecessary array allocations + +0.12.3 / 2015-05-13 +=================== + + * deps: debug@~2.2.0 + - deps: ms@0.7.1 + * deps: depd@~1.0.1 + * deps: etag@~1.6.0 + - Improve support for JXcore + - Support "fake" stats objects in environments without `fs` + * deps: ms@0.7.1 + - Prevent extraordinarily long inputs + * deps: on-finished@~2.2.1 + +0.12.2 / 2015-03-13 +=================== + + * Throw errors early for invalid `extensions` or `index` options + * deps: debug@~2.1.3 + - Fix high intensity foreground color for bold + - deps: ms@0.7.0 + +0.12.1 / 2015-02-17 +=================== + + * Fix regression sending zero-length files + +0.12.0 / 2015-02-16 +=================== + + * Always read the stat size from the file + * Fix mutating passed-in `options` + * deps: mime@1.3.4 + +0.11.1 / 2015-01-20 +=================== + + * Fix `root` path disclosure + +0.11.0 / 2015-01-05 +=================== + + * deps: debug@~2.1.1 + * deps: etag@~1.5.1 + - deps: crc@3.2.1 + * deps: ms@0.7.0 + - Add `milliseconds` + - Add `msecs` + - Add `secs` + - Add `mins` + - Add `hrs` + - Add `yrs` + * deps: on-finished@~2.2.0 + +0.10.1 / 2014-10-22 +=================== + + * deps: on-finished@~2.1.1 + - Fix handling of pipelined requests + +0.10.0 / 2014-10-15 +=================== + + * deps: debug@~2.1.0 + - Implement `DEBUG_FD` env variable support + * deps: depd@~1.0.0 + * deps: etag@~1.5.0 + - Improve string performance + - Slightly improve speed for weak ETags over 1KB + +0.9.3 / 2014-09-24 +================== + + * deps: etag@~1.4.0 + - Support "fake" stats objects + +0.9.2 / 2014-09-15 +================== + + * deps: depd@0.4.5 + * deps: etag@~1.3.1 + * deps: range-parser@~1.0.2 + +0.9.1 / 2014-09-07 +================== + + * deps: fresh@0.2.4 + +0.9.0 / 2014-09-07 +================== + + * Add `lastModified` option + * Use `etag` to generate `ETag` header + * deps: debug@~2.0.0 + +0.8.5 / 2014-09-04 +================== + + * Fix malicious path detection for empty string path + +0.8.4 / 2014-09-04 +================== + + * Fix a path traversal issue when using `root` + +0.8.3 / 2014-08-16 +================== + + * deps: destroy@1.0.3 + - renamed from dethroy + * deps: on-finished@2.1.0 + +0.8.2 / 2014-08-14 +================== + + * Work around `fd` leak in Node.js 0.10 for `fs.ReadStream` + * deps: dethroy@1.0.2 + +0.8.1 / 2014-08-05 +================== + + * Fix `extensions` behavior when file already has extension + +0.8.0 / 2014-08-05 +================== + + * Add `extensions` option + +0.7.4 / 2014-08-04 +================== + + * Fix serving index files without root dir + +0.7.3 / 2014-07-29 +================== + + * Fix incorrect 403 on Windows and Node.js 0.11 + +0.7.2 / 2014-07-27 +================== + + * deps: depd@0.4.4 + - Work-around v8 generating empty stack traces + +0.7.1 / 2014-07-26 +================== + + * deps: depd@0.4.3 + - Fix exception when global `Error.stackTraceLimit` is too low + +0.7.0 / 2014-07-20 +================== + + * Deprecate `hidden` option; use `dotfiles` option + * Add `dotfiles` option + * deps: debug@1.0.4 + * deps: depd@0.4.2 + - Add `TRACE_DEPRECATION` environment variable + - Remove non-standard grey color from color output + - Support `--no-deprecation` argument + - Support `--trace-deprecation` argument + +0.6.0 / 2014-07-11 +================== + + * Deprecate `from` option; use `root` option + * Deprecate `send.etag()` -- use `etag` in `options` + * Deprecate `send.hidden()` -- use `hidden` in `options` + * Deprecate `send.index()` -- use `index` in `options` + * Deprecate `send.maxage()` -- use `maxAge` in `options` + * Deprecate `send.root()` -- use `root` in `options` + * Cap `maxAge` value to 1 year + * deps: debug@1.0.3 + - Add support for multiple wildcards in namespaces + +0.5.0 / 2014-06-28 +================== + + * Accept string for `maxAge` (converted by `ms`) + * Add `headers` event + * Include link in default redirect response + * Use `EventEmitter.listenerCount` to count listeners + +0.4.3 / 2014-06-11 +================== + + * Do not throw un-catchable error on file open race condition + * Use `escape-html` for HTML escaping + * deps: debug@1.0.2 + - fix some debugging output colors on node.js 0.8 + * deps: finished@1.2.2 + * deps: fresh@0.2.2 + +0.4.2 / 2014-06-09 +================== + + * fix "event emitter leak" warnings + * deps: debug@1.0.1 + * deps: finished@1.2.1 + +0.4.1 / 2014-06-02 +================== + + * Send `max-age` in `Cache-Control` in correct format + +0.4.0 / 2014-05-27 +================== + + * Calculate ETag with md5 for reduced collisions + * Fix wrong behavior when index file matches directory + * Ignore stream errors after request ends + - Goodbye `EBADF, read` + * Skip directories in index file search + * deps: debug@0.8.1 + +0.3.0 / 2014-04-24 +================== + + * Fix sending files with dots without root set + * Coerce option types + * Accept API options in options object + * Set etags to "weak" + * Include file path in etag + * Make "Can't set headers after they are sent." catchable + * Send full entity-body for multi range requests + * Default directory access to 403 when index disabled + * Support multiple index paths + * Support "If-Range" header + * Control whether to generate etags + * deps: mime@1.2.11 + +0.2.0 / 2014-01-29 +================== + + * update range-parser and fresh + +0.1.4 / 2013-08-11 +================== + + * update fresh + +0.1.3 / 2013-07-08 +================== + + * Revert "Fix fd leak" + +0.1.2 / 2013-07-03 +================== + + * Fix fd leak + +0.1.0 / 2012-08-25 +================== + + * add options parameter to send() that is passed to fs.createReadStream() [kanongil] + +0.0.4 / 2012-08-16 +================== + + * allow custom "Accept-Ranges" definition + +0.0.3 / 2012-07-16 +================== + + * fix normalization of the root directory. Closes #3 + +0.0.2 / 2012-07-09 +================== + + * add passing of req explicitly for now (YUCK) + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/LICENSE b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..74e960141dd38f126e61944e8a156cd19b635e6a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/LICENSE @@ -0,0 +1,23 @@ +MIT License + +Copyright (c) 2012 TJ Holowaychuk +Copyright (c) 2014-2022 Douglas Christopher Wilson +Copyright (c) 2023 The Fastify Team + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/README.md b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/README.md new file mode 100644 index 0000000000000000000000000000000000000000..cf351e442daf70eeeddef2da5fa7659af34629b6 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/README.md @@ -0,0 +1,310 @@ +# @fastify/send + +[![CI](https://github.com/fastify/send/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/fastify/send/actions/workflows/ci.yml) +[![NPM version](https://img.shields.io/npm/v/@fastify/send.svg?style=flat)](https://www.npmjs.com/package/@fastify/send) +[![neostandard javascript style](https://img.shields.io/badge/code_style-neostandard-brightgreen?style=flat)](https://github.com/neostandard/neostandard) + +Send is a library for streaming files from the file system as an HTTP response +supporting partial responses (Ranges), conditional-GET negotiation (If-Match, +If-Unmodified-Since, If-None-Match, If-Modified-Since), high test coverage, +and granular events which may be leveraged to take appropriate actions in your +application or framework. + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```bash +$ npm install @fastify/send +``` + +### TypeScript + +`@types/mime@3` must be used if wanting to use TypeScript; +`@types/mime@4` removed the `mime` types. + +```bash +$ npm install -D @types/mime@3 +``` + +## API + +```js +const send = require('@fastify/send') +``` + +### send(req, path, [options]) + +Provide `statusCode`, `headers`, and `stream` for the given path to send to a +`res`. The `req` is the Node.js HTTP request and the `path `is a urlencoded path +to send (urlencoded, not the actual file-system path). + +#### Options + +##### acceptRanges + +Enable or disable accepting ranged requests, defaults to true. +Disabling this will not send `Accept-Ranges` and ignore the contents +of the `Range` request header. + +##### cacheControl + +Enable or disable setting `Cache-Control` response header, defaults to +true. Disabling this will ignore the `immutable` and `maxAge` options. + +##### contentType + +By default, this library uses the `mime` module to set the `Content-Type` +of the response based on the file extension of the requested file. + +To disable this functionality, set `contentType` to `false`. +The `Content-Type` header will need to be set manually if disabled. + +##### dotfiles + +Set how "dotfiles" are treated when encountered. A dotfile is a file +or directory that begins with a dot ("."). Note this check is done on +the path itself without checking if the path exists on the +disk. If `root` is specified, only the dotfiles above the root are +checked (i.e. the root itself can be within a dotfile when set +to "deny"). + + - `'allow'` No special treatment for dotfiles. + - `'deny'` Send a 403 for any request for a dotfile. + - `'ignore'` Pretend like the dotfile does not exist and 404. + +The default value is _similar_ to `'ignore'`, with the exception that +this default will not ignore the files within a directory that begins +with a dot, for backward-compatibility. + +##### end + +Byte offset at which the stream ends, defaults to the length of the file +minus 1. The end is inclusive in the stream, meaning `end: 3` will include +the 4th byte in the stream. + +##### etag + +Enable or disable etag generation, defaults to true. + +##### extensions + +If a given file doesn't exist, try appending one of the given extensions, +in the given order. By default, this is disabled (set to `false`). An +example value that will serve extension-less HTML files: `['html', 'htm']`. +This is skipped if the requested file already has an extension. + +##### immutable + +Enable or disable the `immutable` directive in the `Cache-Control` response +header, defaults to `false`. If set to `true`, the `maxAge` option should +also be specified to enable caching. The `immutable` directive will prevent +supported clients from making conditional requests during the life of the +`maxAge` option to check if the file has changed. + +##### index + +By default send supports "index.html" files, to disable this +set `false` or to supply a new index pass a string or an array +in preferred order. + +##### lastModified + +Enable or disable `Last-Modified` header, defaults to true. Uses the file +system's last modified value. + +##### maxAge + +Provide a max-age in milliseconds for HTTP caching, defaults to 0. +This can also be a string accepted by the +[ms](https://www.npmjs.org/package/ms#readme) module. + +##### maxContentRangeChunkSize + +Specify the maximum response content size, defaults to the entire file size. +This will be used when `acceptRanges` is true. + +##### root + +Serve files relative to `path`. + +##### start + +Byte offset at which the stream starts, defaults to 0. The start is inclusive, +meaning `start: 2` will include the 3rd byte in the stream. + +##### highWaterMark + +When provided, this option sets the maximum number of bytes that the internal +buffer will hold before pausing reads from the underlying resource. +If you omit this option (or pass undefined), Node.js falls back to +its built-in default for readable binary streams. + +### .mime + +The `mime` export is the global instance of the +[`mime` npm module](https://www.npmjs.com/package/mime). + +This is used to configure the MIME types that are associated with file extensions +as well as other options for how to resolve the MIME type of a file (like the +default type to use for an unknown file extension). + +## Caching + +It does _not_ perform internal caching, you should use a reverse proxy cache +such as Varnish for this, or those fancy things called CDNs. If your +application is small enough that it would benefit from single-node memory +caching, it's small enough that it does not need caching at all ;). + +## Debugging + +To enable `debug()` instrumentation output export __NODE_DEBUG__: + +``` +$ NODE_DEBUG=send node app +``` + +## Running tests + +``` +$ npm install +$ npm test +``` + +## Examples + +### Serve a specific file + +This simple example will send a specific file to all requests. + +```js +const http = require('node:http') +const send = require('send') + +const server = http.createServer(async function onRequest (req, res) { + const { statusCode, headers, stream } = await send(req, '/path/to/index.html') + res.writeHead(statusCode, headers) + stream.pipe(res) +}) + +server.listen(3000) +``` + +### Serve all files from a directory + +This simple example will just serve up all the files in a +given directory as the top-level. For example, a request +`GET /foo.txt` will send back `/www/public/foo.txt`. + +```js +const http = require('node:http') +const parseUrl = require('parseurl') +const send = require('@fastify/send') + +const server = http.createServer(async function onRequest (req, res) { + const { statusCode, headers, stream } = await send(req, parseUrl(req).pathname, { root: '/www/public' }) + res.writeHead(statusCode, headers) + stream.pipe(res) +}) + +server.listen(3000) +``` + +### Custom file types + +```js +const http = require('node:http') +const parseUrl = require('parseurl') +const send = require('@fastify/send') + +// Default unknown types to text/plain +send.mime.default_type = 'text/plain' + +// Add a custom type +send.mime.define({ + 'application/x-my-type': ['x-mt', 'x-mtt'] +}) + +const server = http.createServer(function onRequest (req, res) { + const { statusCode, headers, stream } = await send(req, parseUrl(req).pathname, { root: '/www/public' }) + res.writeHead(statusCode, headers) + stream.pipe(res) +}) + +server.listen(3000) +``` + +### Custom directory index view + +This is an example of serving up a structure of directories with a +custom function to render a listing of a directory. + +```js +const http = require('node:http') +const fs = require('node:fs') +const parseUrl = require('parseurl') +const send = require('@fastify/send') + +// Transfer arbitrary files from within /www/example.com/public/* +// with a custom handler for directory listing +const server = http.createServer(async function onRequest (req, res) { + const { statusCode, headers, stream, type, metadata } = await send(req, parseUrl(req).pathname, { index: false, root: '/www/public' }) + if(type === 'directory') { + // get directory list + const list = await readdir(metadata.path) + // render an index for the directory + res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }) + res.end(list.join('\n') + '\n') + } else { + res.writeHead(statusCode, headers) + stream.pipe(res) + } +}) + +server.listen(3000) +``` + +### Serving from a root directory with custom error-handling + +```js +const http = require('node:http') +const parseUrl = require('parseurl') +const send = require('@fastify/send') + +const server = http.createServer(async function onRequest (req, res) { + // transfer arbitrary files from within + // /www/example.com/public/* + const { statusCode, headers, stream, type, metadata } = await send(req, parseUrl(req).pathname, { root: '/www/public' }) + switch (type) { + case 'directory': { + // your custom directory handling logic: + res.writeHead(301, { + 'Location': metadata.requestPath + '/' + }) + res.end('Redirecting to ' + metadata.requestPath + '/') + break + } + case 'error': { + // your custom error-handling logic: + res.writeHead(metadata.error.status ?? 500, {}) + res.end(metadata.error.message) + break + } + default: { + // your custom headers + // serve all files for download + res.setHeader('Content-Disposition', 'attachment') + res.writeHead(statusCode, headers) + stream.pipe(res) + } + } +}) + +server.listen(3000) +``` + +## License + +Licensed under [MIT](./LICENSE). diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/benchmarks/collapseLeadingSlashes.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/benchmarks/collapseLeadingSlashes.js new file mode 100644 index 0000000000000000000000000000000000000000..2b56dd4a58b86a920c1f1fec5e09f62d6550d77e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/benchmarks/collapseLeadingSlashes.js @@ -0,0 +1,13 @@ +'use strict' + +const benchmark = require('benchmark') +const collapseLeadingSlashes = require('../lib/collapseLeadingSlashes').collapseLeadingSlashes + +const nonLeading = 'bla.json' +const hasLeading = '///./json' + +new benchmark.Suite() + .add(nonLeading, function () { collapseLeadingSlashes(nonLeading) }, { minSamples: 100 }) + .add(hasLeading, function () { collapseLeadingSlashes(hasLeading) }, { minSamples: 100 }) + .on('cycle', function onCycle (event) { console.log(String(event.target)) }) + .run({ async: false }) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/benchmarks/containsDotFile.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/benchmarks/containsDotFile.js new file mode 100644 index 0000000000000000000000000000000000000000..a9cbfc43022f024fa74961c07b2d1b1612d6583a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/benchmarks/containsDotFile.js @@ -0,0 +1,15 @@ +'use strict' + +const benchmark = require('benchmark') +const { containsDotFile } = require('../lib/containsDotFile') + +const hasDotFileSimple = '.github'.split('/') +const hasDotFile = './.github'.split('/') +const noDotFile = './index.html'.split('/') + +new benchmark.Suite() + .add(hasDotFileSimple.join('/'), function () { containsDotFile(hasDotFileSimple) }, { minSamples: 100 }) + .add(noDotFile.join('/'), function () { containsDotFile(noDotFile) }, { minSamples: 100 }) + .add(hasDotFile.join('/'), function () { containsDotFile(hasDotFile) }, { minSamples: 100 }) + .on('cycle', function onCycle (event) { console.log(String(event.target)) }) + .run({ async: false }) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/benchmarks/isUtf8MimeType.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/benchmarks/isUtf8MimeType.js new file mode 100644 index 0000000000000000000000000000000000000000..a68a8bc03e343698a94795783c09919ea2d55315 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/benchmarks/isUtf8MimeType.js @@ -0,0 +1,23 @@ +'use strict' + +const benchmark = require('benchmark') +const isUtf8MimeType = require('../lib/isUtf8MimeType').isUtf8MimeType + +const applicationJson = 'application/json' +const applicationJavascript = 'application/javascript' +const textJson = 'text/json' +const textHtml = 'text/html' +const textJavascript = 'text/javascript' +const imagePng = 'image/png' + +new benchmark.Suite() + .add('isUtf8MimeType', function () { + isUtf8MimeType(applicationJson) + isUtf8MimeType(applicationJavascript) + isUtf8MimeType(imagePng) + isUtf8MimeType(textJson) + isUtf8MimeType(textHtml) + isUtf8MimeType(textJavascript) + }, { minSamples: 100 }) + .on('cycle', function onCycle (event) { console.log(String(event.target)) }) + .run({ async: false }) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/benchmarks/normalizeList.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/benchmarks/normalizeList.js new file mode 100644 index 0000000000000000000000000000000000000000..9926ca3caa1ff0dadfe1972f5ca240ef589785ce --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/benchmarks/normalizeList.js @@ -0,0 +1,14 @@ +'use strict' + +const benchmark = require('benchmark') +const { normalizeList } = require('../lib/normalizeList') + +const validSingle = 'a' +const validArray = ['a', 'b', 'c'] + +new benchmark.Suite() + .add('false', function () { normalizeList(false) }, { minSamples: 100 }) + .add('valid single', function () { normalizeList(validSingle) }, { minSamples: 100 }) + .add('valid array', function () { normalizeList(validArray) }, { minSamples: 100 }) + .on('cycle', function onCycle (event) { console.log(String(event.target)) }) + .run({ async: false }) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/benchmarks/parseBytesRange.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/benchmarks/parseBytesRange.js new file mode 100644 index 0000000000000000000000000000000000000000..48d59abae961fc6de0b9a2f82e9424a0c2306773 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/benchmarks/parseBytesRange.js @@ -0,0 +1,15 @@ +'use strict' + +const benchmark = require('benchmark') +const { parseBytesRange } = require('../lib/parseBytesRange') + +const size150 = 150 + +const rangeSingle = 'bytes=0-100' +const rangeMultiple = 'bytes=0-4,90-99,5-75,100-199,101-102' + +new benchmark.Suite() + .add('size: 150, bytes=0-100', function () { parseBytesRange(size150, rangeSingle) }, { minSamples: 100 }) + .add('size: 150, bytes=0-4,90-99,5-75,100-199,101-102', function () { parseBytesRange(size150, rangeMultiple) }, { minSamples: 100 }) + .on('cycle', function onCycle (event) { console.log(String(event.target)) }) + .run({ async: false }) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/eslint.config.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/eslint.config.js new file mode 100644 index 0000000000000000000000000000000000000000..89fd678fe2a82d7fe3be869fffd71b3631c61c6a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/eslint.config.js @@ -0,0 +1,6 @@ +'use strict' + +module.exports = require('neostandard')({ + ignores: require('neostandard').resolveIgnoresFromGitignore(), + ts: true +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/examples/index.html b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/examples/index.html new file mode 100644 index 0000000000000000000000000000000000000000..7f41cde5ec3164e627306898d98d9352f1ed8ddb --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/examples/index.html @@ -0,0 +1 @@ +

Hello, World

diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/examples/simple.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/examples/simple.js new file mode 100644 index 0000000000000000000000000000000000000000..5297b75b8256ad483e3526689b1184a4c06f43c4 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/examples/simple.js @@ -0,0 +1,15 @@ +'use strict' + +const http = require('node:http') +const send = require('..') +const path = require('node:path') + +const indexPath = path.join(__dirname, 'index.html') + +const server = http.createServer(async function onRequest (req, res) { + const { statusCode, headers, stream } = await send(req, indexPath) + res.writeHead(statusCode, headers) + stream.pipe(res) +}) + +server.listen(3000) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/index.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/index.js new file mode 100644 index 0000000000000000000000000000000000000000..c1c2b01beea9501426f3d12bf226b0e5cf1821a9 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/index.js @@ -0,0 +1,28 @@ +/*! + * send + * Copyright(c) 2012 TJ Holowaychuk + * Copyright(c) 2014-2022 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ +const isUtf8MimeType = require('./lib/isUtf8MimeType').isUtf8MimeType +const mime = require('mime') +const send = require('./lib/send').send + +/** + * Module exports. + * @public + */ + +module.exports = send +module.exports.default = send +module.exports.send = send + +module.exports.isUtf8MimeType = isUtf8MimeType +module.exports.mime = mime diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/lib/collapseLeadingSlashes.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/lib/collapseLeadingSlashes.js new file mode 100644 index 0000000000000000000000000000000000000000..b611a9cdfd5d678f36db4ad5c5340e6e4705387b --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/lib/collapseLeadingSlashes.js @@ -0,0 +1,25 @@ +'use strict' + +/** + * Collapse all leading slashes into a single slash + * + * @param {string} str + * @private + */ + +function collapseLeadingSlashes (str) { + if ( + str[0] !== '/' || + str[1] !== '/' + ) { + return str + } + for (let i = 2, il = str.length; i < il; ++i) { + if (str[i] !== '/') { + return str.slice(i - 1) + } + } + /* c8 ignore next */ +} + +module.exports.collapseLeadingSlashes = collapseLeadingSlashes diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/lib/containsDotFile.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/lib/containsDotFile.js new file mode 100644 index 0000000000000000000000000000000000000000..c446aa0b3719c71564e75ddb22cbf74d59d860e2 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/lib/containsDotFile.js @@ -0,0 +1,23 @@ +/*! + * send + * Copyright(c) 2012 TJ Holowaychuk + * Copyright(c) 2014-2022 Douglas Christopher Wilson + * MIT Licensed + */ +'use strict' +/** + * Determine if path parts contain a dotfile. + * + * @api private + */ +function containsDotFile (parts) { + for (let i = 0, il = parts.length; i < il; ++i) { + if (parts[i].length !== 1 && parts[i][0] === '.') { + return true + } + } + + return false +} + +module.exports.containsDotFile = containsDotFile diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/lib/contentRange.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/lib/contentRange.js new file mode 100644 index 0000000000000000000000000000000000000000..a2183edfef31adb2bb3937185ac65f65fec3c3df --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/lib/contentRange.js @@ -0,0 +1,18 @@ +/*! + * send + * Copyright(c) 2012 TJ Holowaychuk + * Copyright(c) 2014-2022 Douglas Christopher Wilson + * MIT Licensed + */ +'use strict' +/** + * Create a Content-Range header. + * + * @param {string} type + * @param {number} size + * @param {array} [range] + */ +function contentRange (type, size, range) { + return type + ' ' + (range ? range.start + '-' + range.end : '*') + '/' + size +} +exports.contentRange = contentRange diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/lib/createHtmlDocument.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/lib/createHtmlDocument.js new file mode 100644 index 0000000000000000000000000000000000000000..d4d64d2b89c1f16b57750666075fee53d9218548 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/lib/createHtmlDocument.js @@ -0,0 +1,29 @@ +/*! + * send + * Copyright(c) 2012 TJ Holowaychuk + * Copyright(c) 2014-2022 Douglas Christopher Wilson + * MIT Licensed + */ +'use strict' +/** + * Create a minimal HTML document. + * + * @param {string} title + * @param {string} body + * @private + */ +function createHtmlDocument (title, body) { + const html = '\n' + + '\n' + + '\n' + + '\n' + + '' + title + '\n' + + '\n' + + '\n' + + '
' + body + '
\n' + + '\n' + + '\n' + + return [html, Buffer.byteLength(html)] +} +exports.createHtmlDocument = createHtmlDocument diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/lib/createHttpError.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/lib/createHttpError.js new file mode 100644 index 0000000000000000000000000000000000000000..ba7bcca0166f68482586f0dbd9dc857602b97f59 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/lib/createHttpError.js @@ -0,0 +1,23 @@ +'use strict' + +const createError = require('http-errors') + +/** + * Create a HttpError object from simple arguments. + * + * @param {number} status + * @param {Error|object} err + * @private + */ + +function createHttpError (status, err) { + if (!err) { + return createError(status) + } + + return err instanceof Error + ? createError(status, err, { expose: false }) + : createError(status, err) +} + +module.exports.createHttpError = createHttpError diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/lib/isUtf8MimeType.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/lib/isUtf8MimeType.js new file mode 100644 index 0000000000000000000000000000000000000000..d24978a8012753a012b9df2411ee96a5caac6410 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/lib/isUtf8MimeType.js @@ -0,0 +1,12 @@ +'use strict' + +function isUtf8MimeType (value) { + const len = value.length + return ( + (len > 21 && value.indexOf('application/javascript') === 0) || + (len > 14 && value.indexOf('application/json') === 0) || + (len > 5 && value.indexOf('text/') === 0) + ) +} + +module.exports.isUtf8MimeType = isUtf8MimeType diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/lib/normalizeList.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/lib/normalizeList.js new file mode 100644 index 0000000000000000000000000000000000000000..b18eac974b0bc8c9232293fe986e4850627fb713 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/lib/normalizeList.js @@ -0,0 +1,28 @@ +'use strict' + +/** + * Normalize the index option into an array. + * + * @param {boolean|string|array} val + * @param {string} name + * @private + */ + +function normalizeList (val, name) { + if (typeof val === 'string') { + return [val] + } else if (val === false) { + return [] + } else if (Array.isArray(val)) { + for (let i = 0, il = val.length; i < il; ++i) { + if (typeof val[i] !== 'string') { + throw new TypeError(name + ' must be array of strings or false') + } + } + return val + } else { + throw new TypeError(name + ' must be array of strings or false') + } +} + +module.exports.normalizeList = normalizeList diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/lib/parseBytesRange.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/lib/parseBytesRange.js new file mode 100644 index 0000000000000000000000000000000000000000..5235c3eda10b5ffabab0d28e80e3016298dcae66 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/lib/parseBytesRange.js @@ -0,0 +1,133 @@ +'use strict' + +/*! + * Based on range-parser + * + * Copyright(c) 2012-2014 TJ Holowaychuk + * Copyright(c) 2015-2016 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Parse "Range" header `str` relative to the given file `size`. + * + * @param {Number} size + * @param {String} str + * @return {Array} + * @public + */ + +function parseBytesRange (size, str) { + // split the range string + const values = str.slice(str.indexOf('=') + 1) + const ranges = [] + + const len = values.length + let i = 0 + let il = 0 + let j = 0 + let start + let end + let commaIdx = values.indexOf(',') + let dashIdx = values.indexOf('-') + let prevIdx = -1 + + // parse all ranges + while (true) { + commaIdx === -1 && (commaIdx = len) + start = parseInt(values.slice(prevIdx + 1, dashIdx), 10) + end = parseInt(values.slice(dashIdx + 1, commaIdx), 10) + + // -nnn + // eslint-disable-next-line no-self-compare + if (start !== start) { // fast path of isNaN(number) + start = size - end + end = size - 1 + // nnn- + // eslint-disable-next-line no-self-compare + } else if (end !== end) { // fast path of isNaN(number) + end = size - 1 + // limit last-byte-pos to current length + } else if (end > size - 1) { + end = size - 1 + } + + // add range only on valid ranges + if ( + // eslint-disable-next-line no-self-compare + start === start && // fast path of isNaN(number) + // eslint-disable-next-line no-self-compare + end === end && // fast path of isNaN(number) + start > -1 && + start <= end + ) { + // add range + ranges.push({ + start, + end, + index: j++ + }) + } + + if (commaIdx === len) { + break + } + prevIdx = commaIdx++ + dashIdx = values.indexOf('-', commaIdx) + commaIdx = values.indexOf(',', commaIdx) + } + + // unsatisfiable + if ( + j < 2 + ) { + return ranges + } + + ranges.sort(sortByRangeStart) + + il = j + j = 0 + i = 1 + while (i < il) { + const range = ranges[i++] + const current = ranges[j] + + if (range.start > current.end + 1) { + // next range + ranges[++j] = range + } else if (range.end > current.end) { + // extend range + current.end = range.end + current.index > range.index && (current.index = range.index) + } + } + + // trim ordered array + ranges.length = j + 1 + + // generate combined range + ranges.sort(sortByRangeIndex) + + return ranges +} + +/** + * Sort function to sort ranges by index. + * @private + */ + +function sortByRangeIndex (a, b) { + return a.index - b.index +} + +/** + * Sort function to sort ranges by start position. + * @private + */ + +function sortByRangeStart (a, b) { + return a.start - b.start +} + +module.exports.parseBytesRange = parseBytesRange diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/lib/parseTokenList.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/lib/parseTokenList.js new file mode 100644 index 0000000000000000000000000000000000000000..eb3e436bb21743cf401259630b2cab825a885fba --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/lib/parseTokenList.js @@ -0,0 +1,46 @@ +'use strict' + +/** + * Parse a HTTP token list. + * + * @param {string} str + * @private + */ + +const slice = String.prototype.slice + +function parseTokenList (str, cb) { + let end = 0 + let start = 0 + let result + + // gather tokens + for (let i = 0, len = str.length; i < len; i++) { + switch (str.charCodeAt(i)) { + case 0x20: /* */ + if (start === end) { + start = end = i + 1 + } + break + case 0x2c: /* , */ + if (start !== end) { + result = cb(slice.call(str, start, end)) + if (result !== undefined) { + return result + } + } + start = end = i + 1 + break + default: + end = i + 1 + break + } + } + + // final token + if (start !== end) { + return cb(slice.call(str, start, end)) + } +} + +module.exports.parseTokenList = parseTokenList diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/lib/send.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/lib/send.js new file mode 100644 index 0000000000000000000000000000000000000000..a0f4a50c4e6ba2930ecddba0c7cf267db2fe5a4c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/lib/send.js @@ -0,0 +1,729 @@ +'use strict' + +const fs = require('node:fs') +const path = require('node:path') +const stream = require('node:stream') +const debug = require('node:util').debuglog('send') + +const decode = require('fast-decode-uri-component') +const escapeHtml = require('escape-html') +const mime = require('mime') +const ms = require('@lukeed/ms') + +const { collapseLeadingSlashes } = require('./collapseLeadingSlashes') +const { containsDotFile } = require('../lib/containsDotFile') +const { contentRange } = require('../lib/contentRange') +const { createHtmlDocument } = require('../lib/createHtmlDocument') +const { isUtf8MimeType } = require('../lib/isUtf8MimeType') +const { normalizeList } = require('../lib/normalizeList') +const { parseBytesRange } = require('../lib/parseBytesRange') +const { parseTokenList } = require('./parseTokenList') +const { createHttpError } = require('./createHttpError') + +/** + * Path function references. + * @private + */ + +const extname = path.extname +const join = path.join +const normalize = path.normalize +const resolve = path.resolve +const sep = path.sep + +/** + * Stream function references. + * @private + */ +const Readable = stream.Readable + +/** + * Regular expression for identifying a bytes Range header. + * @private + */ + +const BYTES_RANGE_REGEXP = /^ *bytes=/ + +/** + * Maximum value allowed for the max age. + * @private + */ + +const MAX_MAXAGE = 60 * 60 * 24 * 365 * 1000 // 1 year + +/** + * Regular expression to match a path with a directory up component. + * @private + */ + +const UP_PATH_REGEXP = /(?:^|[\\/])\.\.(?:[\\/]|$)/ + +const ERROR_RESPONSES = { + 400: createHtmlDocument('Error', 'Bad Request'), + 403: createHtmlDocument('Error', 'Forbidden'), + 404: createHtmlDocument('Error', 'Not Found'), + 412: createHtmlDocument('Error', 'Precondition Failed'), + 416: createHtmlDocument('Error', 'Range Not Satisfiable'), + 500: createHtmlDocument('Error', 'Internal Server Error') +} + +const validDotFilesOptions = [ + 'allow', + 'ignore', + 'deny' +] + +function normalizeMaxAge (_maxage) { + let maxage + if (typeof _maxage === 'string') { + maxage = ms.parse(_maxage) + } else { + maxage = Number(_maxage) + } + + // eslint-disable-next-line no-self-compare + if (maxage !== maxage) { + // fast path of isNaN(number) + return 0 + } + + return Math.min(Math.max(0, maxage), MAX_MAXAGE) +} + +function normalizeOptions (options) { + options = options ?? {} + + const acceptRanges = options.acceptRanges !== undefined + ? Boolean(options.acceptRanges) + : true + + const cacheControl = options.cacheControl !== undefined + ? Boolean(options.cacheControl) + : true + + const contentType = options.contentType !== undefined + ? Boolean(options.contentType) + : true + + const etag = options.etag !== undefined + ? Boolean(options.etag) + : true + + const dotfiles = options.dotfiles !== undefined + ? validDotFilesOptions.indexOf(options.dotfiles) + : 1 // 'ignore' + if (dotfiles === -1) { + throw new TypeError('dotfiles option must be "allow", "deny", or "ignore"') + } + + const extensions = options.extensions !== undefined + ? normalizeList(options.extensions, 'extensions option') + : [] + + const immutable = options.immutable !== undefined + ? Boolean(options.immutable) + : false + + const index = options.index !== undefined + ? normalizeList(options.index, 'index option') + : ['index.html'] + + const lastModified = options.lastModified !== undefined + ? Boolean(options.lastModified) + : true + + const maxage = normalizeMaxAge(options.maxAge ?? options.maxage) + + const maxContentRangeChunkSize = options.maxContentRangeChunkSize !== undefined + ? Number(options.maxContentRangeChunkSize) + : null + + const root = options.root + ? resolve(options.root) + : null + + const highWaterMark = Number.isSafeInteger(options.highWaterMark) && options.highWaterMark > 0 + ? options.highWaterMark + : null + + return { + acceptRanges, + cacheControl, + contentType, + etag, + dotfiles, + extensions, + immutable, + index, + lastModified, + maxage, + maxContentRangeChunkSize, + root, + highWaterMark, + start: options.start, + end: options.end + } +} + +function normalizePath (_path, root) { + // decode the path + let path = decode(_path) + if (path == null) { + return { statusCode: 400 } + } + + // null byte(s) + if (~path.indexOf('\0')) { + return { statusCode: 400 } + } + + let parts + if (root !== null) { + // normalize + if (path) { + path = normalize('.' + sep + path) + } + + // malicious path + if (UP_PATH_REGEXP.test(path)) { + debug('malicious path "%s"', path) + return { statusCode: 403 } + } + + // explode path parts + parts = path.split(sep) + + // join / normalize from optional root dir + path = normalize(join(root, path)) + } else { + // ".." is malicious without "root" + if (UP_PATH_REGEXP.test(path)) { + debug('malicious path "%s"', path) + return { statusCode: 403 } + } + + // explode path parts + parts = normalize(path).split(sep) + + // resolve the path + path = resolve(path) + } + + return { path, parts } +} + +/** + * Check if the pathname ends with "/". + * + * @return {boolean} + * @private + */ + +function hasTrailingSlash (path) { + return path[path.length - 1] === '/' +} + +/** + * Check if this is a conditional GET request. + * + * @return {Boolean} + * @api private + */ + +function isConditionalGET (request) { + return request.headers['if-match'] || + request.headers['if-unmodified-since'] || + request.headers['if-none-match'] || + request.headers['if-modified-since'] +} + +function isNotModifiedFailure (request, headers) { + // Always return stale when Cache-Control: no-cache + // to support end-to-end reload requests + // https://tools.ietf.org/html/rfc2616#section-14.9.4 + if ( + 'cache-control' in request.headers && + request.headers['cache-control'].indexOf('no-cache') !== -1 + ) { + return false + } + + // if-none-match + if ('if-none-match' in request.headers) { + const ifNoneMatch = request.headers['if-none-match'] + + if (ifNoneMatch === '*') { + return true + } + + const etag = headers.ETag + + if (typeof etag !== 'string') { + return false + } + + const etagL = etag.length + const isMatching = parseTokenList(ifNoneMatch, function (match) { + const mL = match.length + + if ( + (etagL === mL && match === etag) || + (etagL > mL && 'W/' + match === etag) + ) { + return true + } + }) + + if (isMatching) { + return true + } + + /** + * A recipient MUST ignore If-Modified-Since if the request contains an + * If-None-Match header field; the condition in If-None-Match is considered + * to be a more accurate replacement for the condition in If-Modified-Since, + * and the two are only combined for the sake of interoperating with older + * intermediaries that might not implement If-None-Match. + * + * @see RFC 9110 section 13.1.3 + */ + return false + } + + // if-modified-since + if ('if-modified-since' in request.headers) { + const ifModifiedSince = request.headers['if-modified-since'] + const lastModified = headers['Last-Modified'] + + if (!lastModified || (Date.parse(lastModified) <= Date.parse(ifModifiedSince))) { + return true + } + } + + return false +} + +/** + * Check if the request preconditions failed. + * + * @return {boolean} + * @private + */ + +function isPreconditionFailure (request, headers) { + // if-match + const ifMatch = request.headers['if-match'] + if (ifMatch) { + const etag = headers.ETag + + if (ifMatch !== '*') { + const isMatching = parseTokenList(ifMatch, function (match) { + if ( + match === etag || + 'W/' + match === etag + ) { + return true + } + }) || false + + if (isMatching !== true) { + return true + } + } + } + + // if-unmodified-since + if ('if-unmodified-since' in request.headers) { + const ifUnmodifiedSince = request.headers['if-unmodified-since'] + const unmodifiedSince = Date.parse(ifUnmodifiedSince) + // eslint-disable-next-line no-self-compare + if (unmodifiedSince === unmodifiedSince) { // fast path of isNaN(number) + const lastModified = Date.parse(headers['Last-Modified']) + if ( + // eslint-disable-next-line no-self-compare + lastModified !== lastModified ||// fast path of isNaN(number) + lastModified > unmodifiedSince + ) { + return true + } + } + } + + return false +} + +/** + * Check if the range is fresh. + * + * @return {Boolean} + * @api private + */ + +function isRangeFresh (request, headers) { + if (!('if-range' in request.headers)) { + return true + } + + const ifRange = request.headers['if-range'] + + // if-range as etag + if (ifRange.indexOf('"') !== -1) { + const etag = headers.ETag + return (etag && ifRange.indexOf(etag) !== -1) || false + } + + const ifRangeTimestamp = Date.parse(ifRange) + // eslint-disable-next-line no-self-compare + if (ifRangeTimestamp !== ifRangeTimestamp) { // fast path of isNaN(number) + return false + } + + // if-range as modified date + const lastModified = Date.parse(headers['Last-Modified']) + + return ( + // eslint-disable-next-line no-self-compare + lastModified !== lastModified || // fast path of isNaN(number) + lastModified <= ifRangeTimestamp + ) +} + +// we provide stat function that will always resolve +// without throwing +function tryStat (path) { + return new Promise((resolve) => { + fs.stat(path, function onstat (error, stat) { + resolve({ error, stat }) + }) + }) +} + +function sendError (statusCode, err) { + const headers = {} + + // add error headers + if (err && err.headers) { + for (const headerName in err.headers) { + headers[headerName] = err.headers[headerName] + } + } + + const doc = ERROR_RESPONSES[statusCode] + + // basic response + headers['Content-Type'] = 'text/html; charset=utf-8' + headers['Content-Length'] = doc[1] + headers['Content-Security-Policy'] = "default-src 'none'" + headers['X-Content-Type-Options'] = 'nosniff' + + return { + statusCode, + headers, + stream: Readable.from(doc[0]), + // metadata + type: 'error', + metadata: { error: createHttpError(statusCode, err) } + } +} + +function sendStatError (err) { + // POSIX throws ENAMETOOLONG and ENOTDIR, Windows only ENOENT + /* c8 ignore start */ + switch (err.code) { + case 'ENAMETOOLONG': + case 'ENOTDIR': + case 'ENOENT': + return sendError(404, err) + default: + return sendError(500, err) + } + /* c8 ignore stop */ +} + +/** + * Respond with 304 not modified. + * + * @api private + */ + +function sendNotModified (headers, path, stat) { + debug('not modified') + + delete headers['Content-Encoding'] + delete headers['Content-Language'] + delete headers['Content-Length'] + delete headers['Content-Range'] + delete headers['Content-Type'] + + return { + statusCode: 304, + headers, + stream: Readable.from(''), + // metadata + type: 'file', + metadata: { path, stat } + } +} + +function sendFileDirectly (request, path, stat, options) { + let len = stat.size + let offset = options.start ?? 0 + + let statusCode = 200 + const headers = {} + + debug('send "%s"', path) + + // set header fields + if (options.acceptRanges) { + debug('accept ranges') + headers['Accept-Ranges'] = 'bytes' + } + + if (options.cacheControl) { + let cacheControl = 'public, max-age=' + Math.floor(options.maxage / 1000) + + if (options.immutable) { + cacheControl += ', immutable' + } + + debug('cache-control %s', cacheControl) + headers['Cache-Control'] = cacheControl + } + + if (options.lastModified) { + const modified = stat.mtime.toUTCString() + debug('modified %s', modified) + headers['Last-Modified'] = modified + } + + if (options.etag) { + const etag = 'W/"' + stat.size.toString(16) + '-' + stat.mtime.getTime().toString(16) + '"' + debug('etag %s', etag) + headers.ETag = etag + } + + // set content-type + if (options.contentType) { + let type = mime.getType(path) || mime.default_type + debug('content-type %s', type) + if (type && isUtf8MimeType(type)) { + type += '; charset=utf-8' + } + if (type) { + headers['Content-Type'] = type + } + } + + // conditional GET support + if (isConditionalGET(request)) { + if (isPreconditionFailure(request, headers)) { + return sendError(412) + } + + if (isNotModifiedFailure(request, headers)) { + return sendNotModified(headers, path, stat) + } + } + + // adjust len to start/end options + len = Math.max(0, len - offset) + if (options.end !== undefined) { + const bytes = options.end - offset + 1 + if (len > bytes) len = bytes + } + + // Range support + if (options.acceptRanges) { + const rangeHeader = request.headers.range + + if ( + rangeHeader !== undefined && + BYTES_RANGE_REGEXP.test(rangeHeader) + ) { + // If-Range support + if (isRangeFresh(request, headers)) { + // parse + const ranges = parseBytesRange(len, rangeHeader) + + // unsatisfiable + if (ranges.length === 0) { + debug('range unsatisfiable') + + // Content-Range + headers['Content-Range'] = contentRange('bytes', len) + + // 416 Requested Range Not Satisfiable + return sendError(416, { + headers: { 'Content-Range': headers['Content-Range'] } + }) + // valid (syntactically invalid/multiple ranges are treated as a regular response) + } else if (ranges.length === 1) { + debug('range %j', ranges) + + // Content-Range + statusCode = 206 + if (options.maxContentRangeChunkSize) { + ranges[0].end = Math.min(ranges[0].end, ranges[0].start + options.maxContentRangeChunkSize - 1) + } + headers['Content-Range'] = contentRange('bytes', len, ranges[0]) + + // adjust for requested range + offset += ranges[0].start + len = ranges[0].end - ranges[0].start + 1 + } + } else { + debug('range stale') + } + } + } + + // content-length + headers['Content-Length'] = len + + // HEAD support + if (request.method === 'HEAD') { + return { + statusCode, + headers, + stream: Readable.from(''), + // metadata + type: 'file', + metadata: { path, stat } + } + } + + const stream = fs.createReadStream(path, { + highWaterMark: options.highWaterMark, + start: offset, + end: Math.max(offset, offset + len - 1) + }) + + return { + statusCode, + headers, + stream, + // metadata + type: 'file', + metadata: { path, stat } + } +} + +function sendRedirect (path, options) { + if (hasTrailingSlash(options.path)) { + return sendError(403) + } + + const loc = encodeURI(collapseLeadingSlashes(options.path + '/')) + const doc = createHtmlDocument('Redirecting', 'Redirecting to ' + escapeHtml(loc)) + + const headers = {} + headers['Content-Type'] = 'text/html; charset=utf-8' + headers['Content-Length'] = doc[1] + headers['Content-Security-Policy'] = "default-src 'none'" + headers['X-Content-Type-Options'] = 'nosniff' + headers.Location = loc + + return { + statusCode: 301, + headers, + stream: Readable.from(doc[0]), + // metadata + type: 'directory', + metadata: { requestPath: options.path, path } + } +} + +async function sendIndex (request, path, options) { + let err + for (let i = 0; i < options.index.length; i++) { + const index = options.index[i] + const p = join(path, index) + const { error, stat } = await tryStat(p) + if (error) { + err = error + continue + } + if (stat.isDirectory()) continue + return sendFileDirectly(request, p, stat, options) + } + + if (err) { + return sendStatError(err) + } + + return sendError(404) +} + +async function sendFile (request, path, options) { + const { error, stat } = await tryStat(path) + if (error && error.code === 'ENOENT' && !extname(path) && path[path.length - 1] !== sep) { + let err = error + // not found, check extensions + for (let i = 0; i < options.extensions.length; i++) { + const extension = options.extensions[i] + const p = path + '.' + extension + const { error, stat } = await tryStat(p) + if (error) { + err = error + continue + } + if (stat.isDirectory()) { + err = null + continue + } + return sendFileDirectly(request, p, stat, options) + } + if (err) { + return sendStatError(err) + } + return sendError(404) + } + if (error) return sendStatError(error) + if (stat.isDirectory()) return sendRedirect(path, options) + return sendFileDirectly(request, path, stat, options) +} + +async function send (request, _path, options) { + const opts = normalizeOptions(options) + opts.path = _path + + const parsed = normalizePath(_path, opts.root) + const { path, parts } = parsed + if (parsed.statusCode !== undefined) { + return sendError(parsed.statusCode) + } + + // dotfile handling + if ( + ( + debug.enabled || // if debugging is enabled, then check for all cases to log allow case + opts.dotfiles !== 0 // if debugging is not enabled, then only check if 'deny' or 'ignore' is set + ) && + containsDotFile(parts) + ) { + switch (opts.dotfiles) { + /* c8 ignore start */ /* unreachable, because NODE_DEBUG can not be set after process is running */ + case 0: // 'allow' + debug('allow dotfile "%s"', path) + break + /* c8 ignore stop */ + case 2: // 'deny' + debug('deny dotfile "%s"', path) + return sendError(403) + case 1: // 'ignore' + default: + debug('ignore dotfile "%s"', path) + return sendError(404) + } + } + + // index file support + if (opts.index.length && hasTrailingSlash(_path)) { + return sendIndex(request, path, opts) + } + + return sendFile(request, path, opts) +} + +module.exports.send = send diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/package.json b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/package.json new file mode 100644 index 0000000000000000000000000000000000000000..32e32405dd9c58ef4c1671534fdfbb17fc5ee83a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/package.json @@ -0,0 +1,81 @@ +{ + "name": "@fastify/send", + "description": "Better streaming static file server with Range and conditional-GET support", + "version": "4.1.0", + "author": "TJ Holowaychuk ", + "contributors": [ + "Douglas Christopher Wilson ", + "James Wyatt Cready ", + "Jesús Leganés Combarro ", + { + "name": "Matteo Collina", + "email": "hello@matteocollina.com" + }, + { + "name": "Frazer Smith", + "email": "frazer.dev@icloud.com", + "url": "https://github.com/fdawgs" + }, + { + "name": "Aras Abbasi", + "email": "aras.abbasi@gmail.com" + } + ], + "main": "index.js", + "type": "commonjs", + "types": "types/index.d.ts", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/fastify/send.git" + }, + "bugs": { + "url": "https://github.com/fastify/send/issues" + }, + "homepage": "https://github.com/fastify/send#readme", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "keywords": [ + "static", + "file", + "server" + ], + "dependencies": { + "@lukeed/ms": "^2.0.2", + "escape-html": "~1.0.3", + "fast-decode-uri-component": "^1.0.1", + "http-errors": "^2.0.0", + "mime": "^3" + }, + "devDependencies": { + "@fastify/pre-commit": "^2.1.0", + "@types/node": "^22.0.0", + "after": "0.8.2", + "benchmark": "^2.1.4", + "c8": "^10.1.3", + "eslint": "^9.17.0", + "neostandard": "^0.12.0", + "supertest": "6.3.4", + "tsd": "^0.32.0" + }, + "scripts": { + "lint": "eslint", + "lint:fix": "eslint --fix", + "test": "npm run test:unit && npm run test:typescript", + "test:coverage": "c8 --reporter html node --test", + "test:typescript": "tsd", + "test:unit": "c8 --100 node --test" + }, + "pre-commit": [ + "lint", + "test" + ] +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/collapseLeadingSlashes.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/collapseLeadingSlashes.test.js new file mode 100644 index 0000000000000000000000000000000000000000..1410d7a09cdcfff66ac950e2b5bdb96fce75382c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/collapseLeadingSlashes.test.js @@ -0,0 +1,22 @@ +'use strict' + +const { test } = require('node:test') +const { collapseLeadingSlashes } = require('../lib/collapseLeadingSlashes') + +test('collapseLeadingSlashes', function (t) { + const testCases = [ + ['abcd', 'abcd'], + ['text/json', 'text/json'], + ['/text/json', '/text/json'], + ['//text/json', '/text/json'], + ['///text/json', '/text/json'], + ['/.//text/json', '/.//text/json'], + ['//./text/json', '/./text/json'], + ['///./text/json', '/./text/json'] + ] + t.plan(testCases.length) + + for (const testCase of testCases) { + t.assert.deepStrictEqual(collapseLeadingSlashes(testCase[0]), testCase[1]) + } +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/containsDotFile.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/containsDotFile.test.js new file mode 100644 index 0000000000000000000000000000000000000000..7e9d6647490c9e41b3ce3a58467dcead2fe68b24 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/containsDotFile.test.js @@ -0,0 +1,18 @@ +'use strict' + +const { test } = require('node:test') +const { containsDotFile } = require('../lib/containsDotFile') + +test('containsDotFile', function (t) { + const testCases = [ + ['/.github', true], + ['.github', true], + ['index.html', false], + ['./index.html', false] + ] + t.plan(testCases.length) + + for (const testCase of testCases) { + t.assert.deepStrictEqual(containsDotFile(testCase[0].split('/')), testCase[1], testCase[0]) + } +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/fixtures/.hidden.txt b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/fixtures/.hidden.txt new file mode 100644 index 0000000000000000000000000000000000000000..536aca34dbae6b2b8af26bebdcba83543c9546f0 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/fixtures/.hidden.txt @@ -0,0 +1 @@ +secret \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/fixtures/.mine/.hidden.txt b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/fixtures/.mine/.hidden.txt new file mode 100644 index 0000000000000000000000000000000000000000..d97c5eada5d8c52079031eef0107a4430a9617c5 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/fixtures/.mine/.hidden.txt @@ -0,0 +1 @@ +secret diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/fixtures/.mine/name.txt b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/fixtures/.mine/name.txt new file mode 100644 index 0000000000000000000000000000000000000000..fa66f37ff2170afebb34dd2da5a1ba69d3657270 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/fixtures/.mine/name.txt @@ -0,0 +1 @@ +tobi \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/fixtures/do..ts.txt b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/fixtures/do..ts.txt new file mode 100644 index 0000000000000000000000000000000000000000..90a1d60ab71387c42694fa4b6335c37f51255fc2 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/fixtures/do..ts.txt @@ -0,0 +1 @@ +... \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/fixtures/empty.txt b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/fixtures/empty.txt new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/fixtures/images/node-js.png b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/fixtures/images/node-js.png new file mode 100644 index 0000000000000000000000000000000000000000..e003683f3420d3699f4bd3fe53b28a12562fdc41 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/fixtures/images/node-js.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6b2587c56b914750c30c69d51e1b192cc401e2d23777922983f8ff8092078d76 +size 522 diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/fixtures/name.d/name.txt b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/fixtures/name.d/name.txt new file mode 100644 index 0000000000000000000000000000000000000000..789c47ab13a523803dd653520c787a93cb98ca2c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/fixtures/name.d/name.txt @@ -0,0 +1 @@ +loki \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/fixtures/name.dir/name.txt b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/fixtures/name.dir/name.txt new file mode 100644 index 0000000000000000000000000000000000000000..fa66f37ff2170afebb34dd2da5a1ba69d3657270 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/fixtures/name.dir/name.txt @@ -0,0 +1 @@ +tobi \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/fixtures/name.html b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/fixtures/name.html new file mode 100644 index 0000000000000000000000000000000000000000..52b192303484e35a267b2df79245808ad1686aa9 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/fixtures/name.html @@ -0,0 +1 @@ +

tobi

\ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/fixtures/name.txt b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/fixtures/name.txt new file mode 100644 index 0000000000000000000000000000000000000000..fa66f37ff2170afebb34dd2da5a1ba69d3657270 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/fixtures/name.txt @@ -0,0 +1 @@ +tobi \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/fixtures/no_ext b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/fixtures/no_ext new file mode 100644 index 0000000000000000000000000000000000000000..f6ea0495187600e7b2288c8ac19c5886383a4632 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/fixtures/no_ext @@ -0,0 +1 @@ +foobar \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/fixtures/nums.txt b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/fixtures/nums.txt new file mode 100644 index 0000000000000000000000000000000000000000..e2e107ac61ac259b87c544f6e7a4eb03422c6c21 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/fixtures/nums.txt @@ -0,0 +1 @@ +123456789 \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/fixtures/pets/.hidden.txt b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/fixtures/pets/.hidden.txt new file mode 100644 index 0000000000000000000000000000000000000000..d97c5eada5d8c52079031eef0107a4430a9617c5 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/fixtures/pets/.hidden.txt @@ -0,0 +1 @@ +secret diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/fixtures/pets/index.html b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/fixtures/pets/index.html new file mode 100644 index 0000000000000000000000000000000000000000..5106b6f5dbc8d89a7d4b4ef9961ca4d5bbfb6746 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/fixtures/pets/index.html @@ -0,0 +1,3 @@ +tobi +loki +jane \ No newline at end of file diff --git "a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/fixtures/snow \342\230\203/index.html" "b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/fixtures/snow \342\230\203/index.html" new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/fixtures/some thing.txt b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/fixtures/some thing.txt new file mode 100644 index 0000000000000000000000000000000000000000..2b31011cf9de6c82d52dc386cd7d1a9be83188c1 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/fixtures/some thing.txt @@ -0,0 +1 @@ +hey \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/fixtures/thing.html.html b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/fixtures/thing.html.html new file mode 100644 index 0000000000000000000000000000000000000000..d5644325b6382287619c9c75cc0fda93cafc7e08 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/fixtures/thing.html.html @@ -0,0 +1 @@ +

trap!

\ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/fixtures/tobi.html b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/fixtures/tobi.html new file mode 100644 index 0000000000000000000000000000000000000000..52b192303484e35a267b2df79245808ad1686aa9 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/fixtures/tobi.html @@ -0,0 +1 @@ +

tobi

\ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/isUtf8MimeType.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/isUtf8MimeType.test.js new file mode 100644 index 0000000000000000000000000000000000000000..daad69368c13f250b201f3f427c5742cefc21626 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/isUtf8MimeType.test.js @@ -0,0 +1,22 @@ +'use strict' + +const { test } = require('node:test') +const { isUtf8MimeType } = require('../lib/isUtf8MimeType') + +test('isUtf8MimeType', function (t) { + const testCases = [ + ['application/json', true], + ['text/json', true], + ['application/javascript', true], + ['text/javascript', true], + ['application/json+v5', true], + ['text/xml', true], + ['text/html', true], + ['image/png', false] + ] + t.plan(testCases.length) + + for (const testCase of testCases) { + t.assert.deepStrictEqual(isUtf8MimeType(testCase[0], 'test'), testCase[1]) + } +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/mime.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/mime.test.js new file mode 100644 index 0000000000000000000000000000000000000000..433a003f8d8672d0142963980b2464bc70f00168 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/mime.test.js @@ -0,0 +1,56 @@ +'use strict' + +const { test } = require('node:test') +const path = require('node:path') +const request = require('supertest') +const send = require('..') +const { shouldNotHaveHeader, createServer } = require('./utils') + +const fixtures = path.join(__dirname, 'fixtures') + +test('send.mime', async function (t) { + t.plan(2) + + await t.test('should be exposed', function (t) { + t.plan(1) + t.assert.ok(send.mime) + }) + + await t.test('.default_type', async function (t) { + t.plan(3) + + t.before(() => { + this.default_type = send.mime.default_type + }) + + t.afterEach(() => { + send.mime.default_type = this.default_type + }) + + await t.test('should change the default type', async function (t) { + send.mime.default_type = 'text/plain' + + await request(createServer({ root: fixtures })) + .get('/no_ext') + .expect('Content-Type', 'text/plain; charset=utf-8') + .expect(200) + }) + + await t.test('should not add Content-Type for undefined default', async function (t) { + t.plan(1) + send.mime.default_type = undefined + + await request(createServer({ root: fixtures })) + .get('/no_ext') + .expect(shouldNotHaveHeader('Content-Type', t)) + .expect(200) + }) + + await t.test('should return Content-Type without charset', async function (t) { + await request(createServer({ root: fixtures })) + .get('/images/node-js.png') + .expect('Content-Type', 'image/png') + .expect(200) + }) + }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/normalizeList.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/normalizeList.test.js new file mode 100644 index 0000000000000000000000000000000000000000..84b821652ada2c83cfd374419dc4a710e756d860 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/normalizeList.test.js @@ -0,0 +1,28 @@ +'use strict' + +const { test } = require('node:test') +const { normalizeList } = require('../lib/normalizeList') + +test('normalizeList', function (t) { + const testCases = [ + [undefined, new TypeError('test must be array of strings or false')], + [false, []], + [[], []], + ['', ['']], + [[''], ['']], + [['a'], ['a']], + ['a', ['a']], + [true, new TypeError('test must be array of strings or false')], + [1, new TypeError('test must be array of strings or false')], + [[1], new TypeError('test must be array of strings or false')] + ] + t.plan(testCases.length) + + for (const testCase of testCases) { + if (testCase[1] instanceof Error) { + t.assert.throws(() => normalizeList(testCase[0], 'test'), testCase[1]) + } else { + t.assert.deepStrictEqual(normalizeList(testCase[0], 'test'), testCase[1]) + } + } +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/parseBytesRange.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/parseBytesRange.test.js new file mode 100644 index 0000000000000000000000000000000000000000..dcbf3250f5240df3e8364d5d8fc94ece817eedde --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/parseBytesRange.test.js @@ -0,0 +1,103 @@ +'use strict' + +const { test } = require('node:test') +const { parseBytesRange } = require('../lib/parseBytesRange') + +test('parseBytesRange', async function (t) { + t.plan(13) + + await t.test('should return empty array if all specified ranges are invalid', function (t) { + t.plan(3) + t.assert.deepStrictEqual(parseBytesRange(200, 'bytes=500-20'), []) + t.assert.deepStrictEqual(parseBytesRange(200, 'bytes=500-999'), []) + t.assert.deepStrictEqual(parseBytesRange(200, 'bytes=500-999,1000-1499'), []) + }) + + await t.test('should parse str', function (t) { + t.plan(2) + const range = parseBytesRange(1000, 'bytes=0-499') + t.assert.deepStrictEqual(range.length, 1) + t.assert.deepStrictEqual(range[0], { start: 0, end: 499, index: 0 }) + }) + + await t.test('should cap end at size', function (t) { + t.plan(2) + const range = parseBytesRange(200, 'bytes=0-499') + t.assert.deepStrictEqual(range.length, 1) + t.assert.deepStrictEqual(range[0], { start: 0, end: 199, index: 0 }) + }) + + await t.test('should parse str', function (t) { + t.plan(2) + const range = parseBytesRange(1000, 'bytes=40-80') + t.assert.deepStrictEqual(range.length, 1) + t.assert.deepStrictEqual(range[0], { start: 40, end: 80, index: 0 }) + }) + + await t.test('should parse str asking for last n bytes', function (t) { + t.plan(2) + const range = parseBytesRange(1000, 'bytes=-400') + t.assert.deepStrictEqual(range.length, 1) + t.assert.deepStrictEqual(range[0], { start: 600, end: 999, index: 0 }) + }) + + await t.test('should parse str with only start', function (t) { + t.plan(2) + const range = parseBytesRange(1000, 'bytes=400-') + t.assert.deepStrictEqual(range.length, 1) + t.assert.deepStrictEqual(range[0], { start: 400, end: 999, index: 0 }) + }) + + await t.test('should parse "bytes=0-"', function (t) { + t.plan(2) + const range = parseBytesRange(1000, 'bytes=0-') + t.assert.deepStrictEqual(range.length, 1) + t.assert.deepStrictEqual(range[0], { start: 0, end: 999, index: 0 }) + }) + + await t.test('should parse str with no bytes', function (t) { + t.plan(2) + const range = parseBytesRange(1000, 'bytes=0-0') + t.assert.deepStrictEqual(range.length, 1) + t.assert.deepStrictEqual(range[0], { start: 0, end: 0, index: 0 }) + }) + + await t.test('should parse str asking for last byte', function (t) { + t.plan(2) + const range = parseBytesRange(1000, 'bytes=-1') + t.assert.deepStrictEqual(range.length, 1) + t.assert.deepStrictEqual(range[0], { start: 999, end: 999, index: 0 }) + }) + + await t.test('should parse str with some invalid ranges', function (t) { + t.plan(2) + const range = parseBytesRange(200, 'bytes=0-499,1000-,500-999') + t.assert.deepStrictEqual(range.length, 1) + t.assert.deepStrictEqual(range[0], { start: 0, end: 199, index: 0 }) + }) + + await t.test('should combine overlapping ranges', function (t) { + t.plan(3) + const range = parseBytesRange(150, 'bytes=0-4,90-99,5-75,100-199,101-102') + t.assert.deepStrictEqual(range.length, 2) + t.assert.deepStrictEqual(range[0], { start: 0, end: 75, index: 0 }) + t.assert.deepStrictEqual(range[1], { start: 90, end: 149, index: 1 }) + }) + + await t.test('should retain original order /1', function (t) { + t.plan(3) + const range = parseBytesRange(150, 'bytes=90-99,5-75,100-199,101-102,0-4') + t.assert.deepStrictEqual(range.length, 2) + t.assert.deepStrictEqual(range[0], { start: 90, end: 149, index: 0 }) + t.assert.deepStrictEqual(range[1], { start: 0, end: 75, index: 1 }) + }) + + await t.test('should retain original order /2', function (t) { + t.plan(4) + const range = parseBytesRange(150, 'bytes=-1,20-100,0-1,101-120') + t.assert.deepStrictEqual(range.length, 3) + t.assert.deepStrictEqual(range[0], { start: 149, end: 149, index: 0 }) + t.assert.deepStrictEqual(range[1], { start: 20, end: 120, index: 1 }) + t.assert.deepStrictEqual(range[2], { start: 0, end: 1, index: 2 }) + }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/send.1.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/send.1.test.js new file mode 100644 index 0000000000000000000000000000000000000000..aa0c5818c990863c190808bc49c04fe6175b7cd8 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/send.1.test.js @@ -0,0 +1,646 @@ +'use strict' + +const { test } = require('node:test') +const fs = require('node:fs') +const http = require('node:http') +const path = require('node:path') +const request = require('supertest') +const { send } = require('..') +const { shouldNotHaveHeader, createServer } = require('./utils') +const { getDefaultHighWaterMark } = require('node:stream') + +// test server + +const fixtures = path.join(__dirname, 'fixtures') + +test('send(file, options)', async function (t) { + t.plan(12) + + await t.test('acceptRanges', async function (t) { + t.plan(6) + + await t.test('should support disabling accept-ranges', async function (t) { + t.plan(1) + + await request(createServer({ acceptRanges: false, root: fixtures })) + .get('/nums.txt') + .expect(shouldNotHaveHeader('Accept-Ranges', t)) + .expect(200) + }) + + await t.test('should ignore requested range', async function (t) { + t.plan(2) + + await request(createServer({ acceptRanges: false, root: fixtures })) + .get('/nums.txt') + .set('Range', 'bytes=0-2') + .expect(shouldNotHaveHeader('Accept-Ranges', t)) + .expect(shouldNotHaveHeader('Content-Range', t)) + .expect(200, '123456789') + }) + + await t.test('should limit high return size /1', async function (t) { + t.plan(3) + + await request(createServer({ acceptRanges: true, maxContentRangeChunkSize: 1, root: fixtures })) + .get('/nums.txt') + .set('Range', 'bytes=0-2') + .expect((res) => t.assert.deepStrictEqual(res.headers['accept-ranges'], 'bytes')) + .expect((res) => t.assert.deepStrictEqual(res.headers['content-range'], 'bytes 0-0/9')) + .expect((res) => t.assert.deepStrictEqual(res.headers['content-length'], '1', 'should content-length must be as same as maxContentRangeChunkSize')) + .expect(206, '1') + }) + + await t.test('should limit high return size /2', async function (t) { + t.plan(3) + + await request(createServer({ acceptRanges: true, maxContentRangeChunkSize: 1, root: fixtures })) + .get('/nums.txt') + .set('Range', 'bytes=1-2') + .expect((res) => t.assert.deepStrictEqual(res.headers['accept-ranges'], 'bytes')) + .expect((res) => t.assert.deepStrictEqual(res.headers['content-range'], 'bytes 1-1/9')) + .expect((res) => t.assert.deepStrictEqual(res.headers['content-length'], '1', 'should content-length must be as same as maxContentRangeChunkSize')) + .expect(206, '2') + }) + + await t.test('should limit high return size /3', async function (t) { + t.plan(3) + + await request(createServer({ acceptRanges: true, maxContentRangeChunkSize: 1, root: fixtures })) + .get('/nums.txt') + .set('Range', 'bytes=1-3') + .expect((res) => t.assert.deepStrictEqual(res.headers['accept-ranges'], 'bytes')) + .expect((res) => t.assert.deepStrictEqual(res.headers['content-range'], 'bytes 1-1/9')) + .expect((res) => t.assert.deepStrictEqual(res.headers['content-length'], '1', 'should content-length must be as same as maxContentRangeChunkSize')) + .expect(206, '2') + }) + + await t.test('should limit high return size /4', async function (t) { + t.plan(3) + + await request(createServer({ acceptRanges: true, maxContentRangeChunkSize: 4, root: fixtures })) + .get('/nums.txt') + .set('Range', 'bytes=1-2,3-6') + .expect((res) => t.assert.deepStrictEqual(res.headers['accept-ranges'], 'bytes')) + .expect((res) => t.assert.deepStrictEqual(res.headers['content-range'], 'bytes 1-4/9')) + .expect((res) => t.assert.deepStrictEqual(res.headers['content-length'], '4', 'should content-length must be as same as maxContentRangeChunkSize')) + .expect(206, '2345') + }) + }) + + await t.test('cacheControl', async function (t) { + t.plan(2) + + await t.test('should support disabling cache-control', async function (t) { + t.plan(1) + await request(createServer({ cacheControl: false, root: fixtures })) + .get('/name.txt') + .expect(shouldNotHaveHeader('Cache-Control', t)) + .expect(200) + }) + + await t.test('should ignore maxAge option', async function (t) { + t.plan(1) + + await request(createServer({ cacheControl: false, maxAge: 1000, root: fixtures })) + .get('/name.txt') + .expect(shouldNotHaveHeader('Cache-Control', t)) + .expect(200) + }) + }) + + await t.test('contentType', async function (t) { + t.plan(1) + + await t.test('should support disabling content-type', async function (t) { + t.plan(1) + + await request(createServer({ contentType: false, root: fixtures })) + .get('/name.txt') + .expect(shouldNotHaveHeader('Content-Type', t)) + .expect(200) + }) + }) + + await t.test('etag', async function (t) { + t.plan(1) + + await t.test('should support disabling etags', async function (t) { + t.plan(1) + + await request(createServer({ etag: false, root: fixtures })) + .get('/name.txt') + .expect(shouldNotHaveHeader('ETag', t)) + .expect(200) + }) + }) + + await t.test('extensions', async function (t) { + t.plan(9) + + await t.test('should reject numbers', async function (t) { + await request(createServer({ extensions: 42, root: fixtures })) + .get('/pets/') + .expect(500, /TypeError: extensions option/) + }) + + await t.test('should reject true', async function (t) { + await request(createServer({ extensions: true, root: fixtures })) + .get('/pets/') + .expect(500, /TypeError: extensions option/) + }) + + await t.test('should be not be enabled by default', async function (t) { + await request(createServer({ root: fixtures })) + .get('/tobi') + .expect(404) + }) + + await t.test('should be configurable', async function (t) { + await request(createServer({ extensions: 'txt', root: fixtures })) + .get('/name') + .expect(200, 'tobi') + }) + + await t.test('should support disabling extensions', async function (t) { + await request(createServer({ extensions: false, root: fixtures })) + .get('/name') + .expect(404) + }) + + await t.test('should support fallbacks', async function (t) { + await request(createServer({ extensions: ['htm', 'html', 'txt'], root: fixtures })) + .get('/name') + .expect(200, '

tobi

') + }) + + await t.test('should 404 if nothing found', async function (t) { + await request(createServer({ extensions: ['htm', 'html', 'txt'], root: fixtures })) + .get('/bob') + .expect(404) + }) + + await t.test('should skip directories', async function (t) { + await request(createServer({ extensions: ['file', 'dir'], root: fixtures })) + .get('/name') + .expect(404) + }) + + await t.test('should not search if file has extension', async function (t) { + await request(createServer({ extensions: 'html', root: fixtures })) + .get('/thing.html') + .expect(404) + }) + }) + + await t.test('lastModified', async function (t) { + t.plan(1) + + await t.test('should support disabling last-modified', async function (t) { + t.plan(1) + + await request(createServer({ lastModified: false, root: fixtures })) + .get('/name.txt') + .expect(shouldNotHaveHeader('Last-Modified', t)) + .expect(200) + }) + }) + + await t.test('dotfiles', async function (t) { + t.plan(5) + + await t.test('should default to "ignore"', async function (t) { + await request(createServer({ root: fixtures })) + .get('/.hidden.txt') + .expect(404) + }) + + await t.test('should reject bad value', async function (t) { + await request(createServer({ dotfiles: 'bogus' })) + .get('/name.txt') + .expect(500, /dotfiles/) + }) + + await t.test('when "allow"', async function (t) { + t.plan(3) + + await t.test('should send dotfile', async function (t) { + await request(createServer({ dotfiles: 'allow', root: fixtures })) + .get('/.hidden.txt') + .expect(200, 'secret') + }) + + await t.test('should send within dotfile directory', async function (t) { + await request(createServer({ dotfiles: 'allow', root: fixtures })) + .get('/.mine/name.txt') + .expect(200, /tobi/) + }) + + await t.test('should 404 for non-existent dotfile', async function (t) { + await request(createServer({ dotfiles: 'allow', root: fixtures })) + .get('/.nothere') + .expect(404) + }) + }) + + await t.test('when "deny"', async function (t) { + t.plan(10) + + await t.test('should 403 for dotfile', async function (t) { + await request(createServer({ dotfiles: 'deny', root: fixtures })) + .get('/.hidden.txt') + .expect(403) + }) + + await t.test('should 403 for dotfile directory', async function (t) { + await request(createServer({ dotfiles: 'deny', root: fixtures })) + .get('/.mine') + .expect(403) + }) + + await t.test('should 403 for dotfile directory with trailing slash', async function (t) { + await request(createServer({ dotfiles: 'deny', root: fixtures })) + .get('/.mine/') + .expect(403) + }) + + await t.test('should 403 for file within dotfile directory', async function (t) { + await request(createServer({ dotfiles: 'deny', root: fixtures })) + .get('/.mine/name.txt') + .expect(403) + }) + + await t.test('should 403 for non-existent dotfile', async function (t) { + await request(createServer({ dotfiles: 'deny', root: fixtures })) + .get('/.nothere') + .expect(403) + }) + + await t.test('should 403 for non-existent dotfile directory', async function (t) { + await request(createServer({ dotfiles: 'deny', root: fixtures })) + .get('/.what/name.txt') + .expect(403) + }) + + await t.test('should 403 for dotfile in directory', async function (t) { + await request(createServer({ dotfiles: 'deny', root: fixtures })) + .get('/pets/.hidden.txt') + .expect(403) + }) + + await t.test('should 403 for dotfile in dotfile directory', async function (t) { + await request(createServer({ dotfiles: 'deny', root: fixtures })) + .get('/.mine/.hidden.txt') + .expect(403) + }) + + await t.test('should send files in root dotfile directory', async function (t) { + await request(createServer({ dotfiles: 'deny', root: path.join(fixtures, '.mine') })) + .get('/name.txt') + .expect(200, /tobi/) + }) + + await t.test('should 403 for dotfile without root', async function (t) { + const server = http.createServer(async function onRequest (req, res) { + const { statusCode, headers, stream } = await send(req, fixtures + '/.mine' + req.url, { dotfiles: 'deny' }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(server) + .get('/name.txt') + .expect(403) + }) + }) + + await t.test('when "ignore"', async function (t) { + t.plan(8) + + await t.test('should 404 for dotfile', async function (t) { + await request(createServer({ dotfiles: 'ignore', root: fixtures })) + .get('/.hidden.txt') + .expect(404) + }) + + await t.test('should 404 for dotfile directory', async function (t) { + await request(createServer({ dotfiles: 'ignore', root: fixtures })) + .get('/.mine') + .expect(404) + }) + + await t.test('should 404 for dotfile directory with trailing slash', async function (t) { + await request(createServer({ dotfiles: 'ignore', root: fixtures })) + .get('/.mine/') + .expect(404) + }) + + await t.test('should 404 for file within dotfile directory', async function (t) { + await request(createServer({ dotfiles: 'ignore', root: fixtures })) + .get('/.mine/name.txt') + .expect(404) + }) + + await t.test('should 404 for non-existent dotfile', async function (t) { + await request(createServer({ dotfiles: 'ignore', root: fixtures })) + .get('/.nothere') + .expect(404) + }) + + await t.test('should 404 for non-existent dotfile directory', async function (t) { + await request(createServer({ dotfiles: 'ignore', root: fixtures })) + .get('/.what/name.txt') + .expect(404) + }) + + await t.test('should send files in root dotfile directory', async function (t) { + await request(createServer({ dotfiles: 'ignore', root: path.join(fixtures, '.mine') })) + .get('/name.txt') + .expect(200, /tobi/) + }) + + await t.test('should 404 for dotfile without root', async function (t) { + const server = http.createServer(async function onRequest (req, res) { + const { statusCode, headers, stream } = await send(req, fixtures + '/.mine' + req.url, { dotfiles: 'ignore' }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(server) + .get('/name.txt') + .expect(404) + }) + }) + }) + + await t.test('immutable', async function (t) { + t.plan(2) + + await t.test('should default to false', async function (t) { + await request(createServer({ root: fixtures })) + .get('/name.txt') + .expect('Cache-Control', 'public, max-age=0') + }) + + await t.test('should set immutable directive in Cache-Control', async function (t) { + await request(createServer({ immutable: true, maxAge: '1h', root: fixtures })) + .get('/name.txt') + .expect('Cache-Control', 'public, max-age=3600, immutable') + }) + }) + + await t.test('maxAge', async function (t) { + t.plan(4) + + await t.test('should default to 0', async function (t) { + await request(createServer({ root: fixtures })) + .get('/name.txt') + .expect('Cache-Control', 'public, max-age=0') + }) + + await t.test('should floor to integer', async function (t) { + await request(createServer({ maxAge: 123956, root: fixtures })) + .get('/name.txt') + .expect('Cache-Control', 'public, max-age=123') + }) + + await t.test('should accept string', async function (t) { + await request(createServer({ maxAge: '30d', root: fixtures })) + .get('/name.txt') + .expect('Cache-Control', 'public, max-age=2592000') + }) + + await t.test('should max at 1 year', async function (t) { + await request(createServer({ maxAge: '2y', root: fixtures })) + .get('/name.txt') + .expect('Cache-Control', 'public, max-age=31536000') + }) + }) + + await t.test('index', async function (t) { + t.plan(10) + + await t.test('should reject numbers', async function (t) { + await request(createServer({ root: fixtures, index: 42 })) + .get('/pets/') + .expect(500, /TypeError: index option/) + }) + + await t.test('should reject true', async function (t) { + await request(createServer({ root: fixtures, index: true })) + .get('/pets/') + .expect(500, /TypeError: index option/) + }) + + await t.test('should default to index.html', async function (t) { + await request(createServer({ root: fixtures })) + .get('/pets/') + .expect(fs.readFileSync(path.join(fixtures, 'pets', 'index.html'), 'utf8')) + }) + + await t.test('should be configurable', async function (t) { + await request(createServer({ root: fixtures, index: 'tobi.html' })) + .get('/') + .expect(200, '

tobi

') + }) + + await t.test('should support disabling', async function (t) { + await request(createServer({ root: fixtures, index: false })) + .get('/pets/') + .expect(403) + }) + + await t.test('should support fallbacks', async function (t) { + await request(createServer({ root: fixtures, index: ['default.htm', 'index.html'] })) + .get('/pets/') + .expect(200, fs.readFileSync(path.join(fixtures, 'pets', 'index.html'), 'utf8')) + }) + + await t.test('should 404 if no index file found (file)', async function (t) { + await request(createServer({ root: fixtures, index: 'default.htm' })) + .get('/pets/') + .expect(404) + }) + + await t.test('should 404 if no index file found (dir)', async function (t) { + await request(createServer({ root: fixtures, index: 'pets' })) + .get('/') + .expect(404) + }) + + await t.test('should not follow directories', async function (t) { + await request(createServer({ root: fixtures, index: ['pets', 'name.txt'] })) + .get('/') + .expect(200, 'tobi') + }) + + await t.test('should work without root', async function (t) { + const server = http.createServer(async function (req, res) { + const p = path.join(fixtures, 'pets').replace(/\\/g, '/') + '/' + const { statusCode, headers, stream } = await send(req, p, { index: ['index.html'] }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(server) + .get('/') + .expect(200, /tobi/) + }) + }) + + await t.test('root', async function (t) { + t.plan(2) + + await t.test('when given', async function (t) { + t.plan(8) + + await t.test('should join root', async function (t) { + await request(createServer({ root: fixtures })) + .get('/pets/../name.txt') + .expect(200, 'tobi') + }) + + await t.test('should work with trailing slash', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures + '/' }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(app) + .get('/name.txt') + .expect(200, 'tobi') + }) + + await t.test('should work with empty path', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, '', { root: fixtures }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(app) + .get('/name.txt') + .expect(301, /Redirecting to/) + }) + + // + // NOTE: This is not a real part of the API, but + // over time this has become something users + // are doing, so this will prevent unseen + // regressions around this use-case. + // + await t.test('should try as file with empty path', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, '', { root: path.join(fixtures, 'name.txt') }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(app) + .get('/') + .expect(200, 'tobi') + }) + + await t.test('should restrict paths to within root', async function (t) { + await request(createServer({ root: fixtures })) + .get('/pets/../../send.js') + .expect(403) + }) + + await t.test('should allow .. in root', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures + '/../fixtures' }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(app) + .get('/pets/../../send.js') + .expect(403) + }) + + await t.test('should not allow root transversal', async function (t) { + await request(createServer({ root: path.join(fixtures, 'name.d') })) + .get('/../name.dir/name.txt') + .expect(403) + }) + + await t.test('should not allow root path disclosure', async function (t) { + await request(createServer({ root: fixtures })) + .get('/pets/../../fixtures/name.txt') + .expect(403) + }) + }) + + await t.test('when missing', async function (t) { + t.plan(2) + + await t.test('should consider .. malicious', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, fixtures + req.url) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(app) + .get('/../send.js') + .expect(403) + }) + + await t.test('should still serve files with dots in name', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, fixtures + req.url) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(app) + .get('/do..ts.txt') + .expect(200, '...') + }) + }) + }) + + await t.test('highWaterMark', async function (t) { + t.plan(3) + + await t.test('should support highWaterMark', async function (t) { + t.plan(1) + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { highWaterMark: 512 * 1024, root: fixtures + '/' }) + res.writeHead(statusCode, headers) + t.assert.deepStrictEqual(stream.readableHighWaterMark, 524288) + stream.pipe(res) + }) + await request(app) + .get('/name.txt') + .expect(200, 'tobi') + }) + + await t.test('should use default value', async function (t) { + t.plan(1) + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures + '/' }) + res.writeHead(statusCode, headers) + t.assert.deepStrictEqual(stream.readableHighWaterMark, getDefaultHighWaterMark(false)) + stream.pipe(res) + }) + await request(app) + .get('/name.txt') + .expect(200, 'tobi') + }) + + await t.test('should ignore negative number', async function (t) { + t.plan(1) + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { highWaterMark: -54, root: fixtures + '/' }) + res.writeHead(statusCode, headers) + t.assert.deepStrictEqual(stream.readableHighWaterMark, getDefaultHighWaterMark(false)) + stream.pipe(res) + }) + await request(app) + .get('/name.txt') + .expect(200, 'tobi') + }) + }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/send.2.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/send.2.test.js new file mode 100644 index 0000000000000000000000000000000000000000..957d6f5197d2bdbc7f62e612fcba40cece1b3356 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/test/send.2.test.js @@ -0,0 +1,977 @@ +'use strict' + +const { test } = require('node:test') +const http = require('node:http') +const path = require('node:path') +const request = require('supertest') +const send = require('../lib/send').send +const { shouldNotHaveBody, createServer, shouldNotHaveHeader } = require('./utils') + +const dateRegExp = /^\w{3}, \d+ \w+ \d+ \d+:\d+:\d+ \w+$/ +const fixtures = path.join(__dirname, 'fixtures') + +test('send(file)', async function (t) { + t.plan(22) + + await t.test('should stream the file contents', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(app) + .get('/name.txt') + .expect('Content-Length', '4') + .expect(200, 'tobi') + }) + + await t.test('should stream a zero-length file', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(app) + .get('/empty.txt') + .expect('Content-Length', '0') + .expect(200, '') + }) + + await t.test('should decode the given path as a URI', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(app) + .get('/some%20thing.txt') + .expect(200, 'hey') + }) + + await t.test('should serve files with dots in name', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(app) + .get('/do..ts.txt') + .expect(200, '...') + }) + + await t.test('should treat a malformed URI as a bad request', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(app) + .get('/some%99thing.txt') + .expect(400, /Bad Request/) + }) + + await t.test('should 400 on NULL bytes', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(app) + .get('/some%00thing.txt') + .expect(400, /Bad Request/) + }) + + await t.test('should treat an ENAMETOOLONG as a 404', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + const path = Array(100).join('foobar') + await request(app) + .get('/' + path) + .expect(404) + }) + + await t.test('should support HEAD', async function (t) { + t.plan(1) + + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(app) + .head('/name.txt') + .expect(200) + .expect('Content-Length', '4') + .expect(shouldNotHaveBody(t)) + }) + + await t.test('should add an ETag header field', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(app) + .get('/name.txt') + .expect('etag', /^W\/"[^"]+"$/) + }) + + await t.test('should add a Date header field', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(app) + .get('/name.txt') + .expect('date', dateRegExp) + }) + + await t.test('should add a Last-Modified header field', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(app) + .get('/name.txt') + .expect('last-modified', dateRegExp) + }) + + await t.test('should add a Accept-Ranges header field', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(app) + .get('/name.txt') + .expect('Accept-Ranges', 'bytes') + }) + + await t.test('should 404 if the file does not exist', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(app) + .get('/meow') + .expect(404, /Not Found/) + }) + + await t.test('should 404 if the filename is too long', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + const longFilename = new Array(512).fill('a').join('') + + await request(app) + .get('/' + longFilename) + .expect(404, /Not Found/) + }) + + await t.test('should 404 if the requested resource is not a directory', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(app) + .get('/nums.txt/invalid') + .expect(404, /Not Found/) + }) + + await t.test('should not override content-type', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures }) + res.writeHead(statusCode, { + ...headers, + 'Content-Type': 'application/x-custom' + }) + stream.pipe(res) + }) + await request(app) + .get('/name.txt') + .expect('Content-Type', 'application/x-custom') + }) + + await t.test('should set Content-Type via mime map', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(app) + .get('/name.txt') + .expect('Content-Type', 'text/plain; charset=utf-8') + .expect(200) + + await request(app) + .get('/tobi.html') + .expect('Content-Type', 'text/html; charset=utf-8') + .expect(200) + }) + + await t.test('send directory', async function (t) { + t.plan(5) + + await t.test('should redirect directories to trailing slash', async function (t) { + await request(createServer({ root: fixtures })) + .get('/pets') + .expect('Location', '/pets/') + .expect(301) + }) + + await t.test('should respond with an HTML redirect', async function (t) { + await request(createServer({ root: fixtures })) + .get('/pets') + .expect('Location', '/pets/') + .expect('Content-Type', /html/) + .expect(301, />Redirecting to \/pets\/Redirecting to \/snow%20%E2%98%83\/Not Found +// Piotr Błażejewicz +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { Dirent } from 'node:fs' +import * as stream from 'node:stream' + +/** + * Create a new SendStream for the given path to send to a res. + * The req is the Node.js HTTP request and the path is a urlencoded path to send (urlencoded, not the actual file-system path). + */ +declare function send (req: stream.Readable, path: string, options?: send.SendOptions): Promise + +type Send = typeof send + +declare class Mime { + constructor (typeMap: TypeMap, ...mimes: TypeMap[]) + + getType (path: string): string | null + getExtension (mime: string): string | null + define (typeMap: TypeMap, force?: boolean): void +} + +interface TypeMap { + [key: string]: string[]; +} + +declare namespace send { + export const mime: Mime + export const isUtf8MimeType: (value: string) => boolean + + export interface SendOptions { + /** + * Enable or disable accepting ranged requests, defaults to true. + * Disabling this will not send Accept-Ranges and ignore the contents of the Range request header. + */ + acceptRanges?: boolean | undefined; + + /** + * Enable or disable setting Cache-Control response header, defaults to true. + * Disabling this will ignore the maxAge option. + */ + cacheControl?: boolean | undefined; + + /** + * Enable or disable setting Content-Type response header, defaults to true. + */ + contentType?: boolean | undefined; + + /** + * Set how "dotfiles" are treated when encountered. + * A dotfile is a file or directory that begins with a dot ("."). + * Note this check is done on the path itself without checking if the path actually exists on the disk. + * If root is specified, only the dotfiles above the root are checked (i.e. the root itself can be within a dotfile when when set to "deny"). + * 'allow' No special treatment for dotfiles. + * 'deny' Send a 403 for any request for a dotfile. + * 'ignore' Pretend like the dotfile does not exist and 404. + * The default value is similar to 'ignore', with the exception that this default will not ignore the files within a directory that begins with a dot, for backward-compatibility. + */ + dotfiles?: 'allow' | 'deny' | 'ignore' | undefined; + + /** + * Byte offset at which the stream ends, defaults to the length of the file minus 1. + * The end is inclusive in the stream, meaning end: 3 will include the 4th byte in the stream. + */ + end?: number | undefined; + + /** + * Enable or disable etag generation, defaults to true. + */ + etag?: boolean | undefined; + + /** + * If a given file doesn't exist, try appending one of the given extensions, in the given order. + * By default, this is disabled (set to false). + * An example value that will serve extension-less HTML files: ['html', 'htm']. + * This is skipped if the requested file already has an extension. + */ + extensions?: string[] | string | boolean | undefined; + + /** + * Enable or disable the immutable directive in the Cache-Control response header, defaults to false. + * If set to true, the maxAge option should also be specified to enable caching. + * The immutable directive will prevent supported clients from making conditional requests during the life of the maxAge option to check if the file has changed. + * @default false + */ + immutable?: boolean | undefined; + + /** + * By default send supports "index.html" files, to disable this set false or to supply a new index pass a string or an array in preferred order. + */ + index?: string[] | string | boolean | undefined; + + /** + * Enable or disable Last-Modified header, defaults to true. + * Uses the file system's last modified value. + */ + lastModified?: boolean | undefined; + + /** + * Provide a max-age in milliseconds for http caching, defaults to 0. + * This can also be a string accepted by the ms module. + */ + maxAge?: string | number | undefined; + + /** + * Limit max response content size when acceptRanges is true, defaults to the entire file size. + */ + maxContentRangeChunkSize?: number | undefined; + + /** + * Serve files relative to path. + */ + root?: string | undefined; + + /** + * Byte offset at which the stream starts, defaults to 0. + * The start is inclusive, meaning start: 2 will include the 3rd byte in the stream. + */ + start?: number | undefined; + + /** + * Maximum number of bytes that the internal buffer will hold. + * If omitted, Node.js falls back to its built-in default. + */ + highWaterMark?: number | undefined; + } + + export interface BaseSendResult { + statusCode: number + headers: Record + stream: stream.Readable + } + + export interface FileSendResult extends BaseSendResult { + type: 'file' + metadata: { + path: string + stat: Dirent + } + } + + export interface DirectorySendResult extends BaseSendResult { + type: 'directory' + metadata: { + path: string + requestPath: string + } + } + + export interface ErrorSendResult extends BaseSendResult { + type: 'error' + metadata: { + error: Error + } + } + + export type SendResult = FileSendResult | DirectorySendResult | ErrorSendResult + + export const send: Send + + export { send as default } +} + +export = send diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/types/index.test-d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/types/index.test-d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1711484d1e908d0bb78dae1e1a9994846b3bc875 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/send/types/index.test-d.ts @@ -0,0 +1,67 @@ +import { Dirent } from 'node:fs' +import { resolve } from 'node:path' +import { Readable } from 'node:stream' +import { expectType } from 'tsd' +import send, { DirectorySendResult, ErrorSendResult, FileSendResult, SendResult } from '..' + +send.mime.define({ + 'application/x-my-type': ['x-mt', 'x-mtt'] +}) + +expectType<(value: string) => boolean>(send.isUtf8MimeType) +expectType(send.isUtf8MimeType('application/json')) + +const req: any = {} + +{ + const result = await send(req, '/test.html', { + acceptRanges: true, + maxContentRangeChunkSize: 10, + immutable: true, + maxAge: 0, + root: resolve(__dirname, '/wwwroot') + }) + + expectType(result) + expectType(result.statusCode) + expectType>(result.headers) + expectType(result.stream) +} + +{ + const result = await send(req, '/test.html', { contentType: true, maxAge: 0, root: resolve(__dirname, '/wwwroot') }) + + expectType(result) + expectType(result.statusCode) + expectType>(result.headers) + expectType(result.stream) +} + +{ + const result = await send(req, '/test.html', { contentType: false, root: resolve(__dirname, '/wwwroot') }) + + expectType(result) + expectType(result.statusCode) + expectType>(result.headers) + expectType(result.stream) +} + +const result = await send(req, '/test.html') +switch (result.type) { + case 'file': { + expectType(result) + expectType(result.metadata.path) + expectType(result.metadata.stat) + break + } + case 'directory': { + expectType(result) + expectType(result.metadata.path) + expectType(result.metadata.requestPath) + break + } + case 'error': { + expectType(result) + expectType(result.metadata.error) + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/.gitattributes b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..cad1c32e3deb59f649a90fb55994a7c6a0685f64 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/.gitattributes @@ -0,0 +1,5 @@ +# Set the default behavior, in case people don't have core.autocrlf set +* text=auto + +# Require Unix line endings +* text eol=lf diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/.github/dependabot.yml b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..35d66ca7ac75f125b9c9c5b3dee0987fdfca4a45 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/.github/dependabot.yml @@ -0,0 +1,13 @@ +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "monthly" + open-pull-requests-limit: 10 + + - package-ecosystem: "npm" + directory: "/" + schedule: + interval: "monthly" + open-pull-requests-limit: 10 diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/.github/stale.yml b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/.github/stale.yml new file mode 100644 index 0000000000000000000000000000000000000000..d51ce639022226bc44471aa18bb218b50876cd52 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/.github/stale.yml @@ -0,0 +1,21 @@ +# Number of days of inactivity before an issue becomes stale +daysUntilStale: 15 +# Number of days of inactivity before a stale issue is closed +daysUntilClose: 7 +# Issues with these labels will never be considered stale +exemptLabels: + - "discussion" + - "feature request" + - "bug" + - "help wanted" + - "plugin suggestion" + - "good first issue" +# Label to use when marking an issue as stale +staleLabel: stale +# Comment to post when marking an issue as stale. Set to `false` to disable +markComment: > + This issue has been automatically marked as stale because it has not had + recent activity. It will be closed if no further activity occurs. Thank you + for your contributions. +# Comment to post when closing a stale issue. Set to `false` to disable +closeComment: false diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/.github/workflows/ci.yml b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/.github/workflows/ci.yml new file mode 100644 index 0000000000000000000000000000000000000000..fd45202abff682784e3a60d54fbfee567d304b26 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/.github/workflows/ci.yml @@ -0,0 +1,28 @@ +name: CI + +on: + push: + branches: + - main + - next + - 'v*' + paths-ignore: + - 'docs/**' + - '*.md' + pull_request: + paths-ignore: + - 'docs/**' + - '*.md' + +permissions: + contents: read + +jobs: + test: + permissions: + contents: write + pull-requests: write + uses: fastify/workflows/.github/workflows/plugins-ci.yml@v5 + with: + license-check: true + lint: true diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/LICENSE b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..7780923cfa5dc55d49fa1884f7eeabb1e7272d1b --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017-2023 Fastify + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/README.md b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/README.md new file mode 100644 index 0000000000000000000000000000000000000000..634a08805a50fad7f415d0e14ef32c99d8f46e66 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/README.md @@ -0,0 +1,533 @@ +# @fastify/static + +[![CI](https://github.com/fastify/fastify-static/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/fastify/fastify-static/actions/workflows/ci.yml) +[![NPM version](https://img.shields.io/npm/v/@fastify/static.svg?style=flat)](https://www.npmjs.com/package/@fastify/static) +[![neostandard javascript style](https://img.shields.io/badge/code_style-neostandard-brightgreen?style=flat)](https://github.com/neostandard/neostandard) + +Plugin for serving static files as fast as possible. + +## Install +``` +npm i @fastify/static +``` + +### Compatibility + +| Plugin version | Fastify version | +| ---------------|-----------------| +| `>=8.x` | `^5.x` | +| `^7.x` | `^4.x` | +| `>=5.x <7.x` | `^3.x` | +| `>=2.x <5.x` | `^2.x` | +| `^1.x` | `^1.x` | + + +Please note that if a Fastify version is out of support, then so are the corresponding versions of this plugin +in the table above. +See [Fastify's LTS policy](https://github.com/fastify/fastify/blob/main/docs/Reference/LTS.md) for more details. + +## Usage + +```js +const fastify = require('fastify')({logger: true}) +const path = require('node:path') + +fastify.register(require('@fastify/static'), { + root: path.join(__dirname, 'public'), + prefix: '/public/', // optional: default '/' + constraints: { host: 'example.com' } // optional: default {} +}) + +fastify.get('/another/path', function (req, reply) { + reply.sendFile('myHtml.html') // serving path.join(__dirname, 'public', 'myHtml.html') directly +}) + +fastify.get('/another/patch-async', async function (req, reply) { + return reply.sendFile('myHtml.html') +}) + +fastify.get('/path/with/different/root', function (req, reply) { + reply.sendFile('myHtml.html', path.join(__dirname, 'build')) // serving a file from a different root location +}) + +fastify.get('/another/path', function (req, reply) { + reply.sendFile('myHtml.html', { cacheControl: false }) // overriding the options disabling cache-control headers +}) + +// Run the server! +fastify.listen({ port: 3000 }, (err, address) => { + if (err) throw err + // Server is now listening on ${address} +}) +``` + +### Multiple prefixed roots + +```js +const fastify = require('fastify')() +const fastifyStatic = require('@fastify/static') +const path = require('node:path') +// first plugin +fastify.register(fastifyStatic, { + root: path.join(__dirname, 'public') +}) + +// second plugin +fastify.register(fastifyStatic, { + root: path.join(__dirname, 'node_modules'), + prefix: '/node_modules/', + decorateReply: false // the reply decorator has been added by the first plugin registration +}) + +``` + +### Sending a file with `content-disposition` header + +```js +const fastify = require('fastify')() +const path = require('node:path') + +fastify.register(require('@fastify/static'), { + root: path.join(__dirname, 'public'), + prefix: '/public/', // optional: default '/' +}) + +fastify.get('/another/path', function (req, reply) { + reply.download('myHtml.html', 'custom-filename.html') // sending path.join(__dirname, 'public', 'myHtml.html') directly with custom filename +}) + +fastify.get('another/patch-async', async function (req, reply) { + // an async handler must always return the reply object + return reply.download('myHtml.html', 'custom-filename.html') +}) + +fastify.get('/path/without/cache/control', function (req, reply) { + reply.download('myHtml.html', { cacheControl: false }) // serving a file disabling cache-control headers +}) + +fastify.get('/path/without/cache/control', function (req, reply) { + reply.download('myHtml.html', 'custom-filename.html', { cacheControl: false }) +}) + +``` + +### Managing cache-control headers + +Production sites should use a reverse-proxy to manage caching headers. +However, here is an example of using fastify-static to host a Single Page Application (for example a [vite.js](https://vite.dev/) build) with sane caching. + +```js +fastify.register(require('@fastify/static'), { + root: path.join(import.meta.dirname, 'dist'), // import.meta.dirname node.js >= v20.11.0 + // By default all assets are immutable and can be cached for a long period due to cache bursting techniques + maxAge: '30d', + immutable: true, +}) + +// Explicitly reduce caching of assets that don't use cache bursting techniques +fastify.get('/', function (req, reply) { + // index.html should never be cached + reply.sendFile('index.html', {maxAge: 0, immutable: false}) +}) + +fastify.get('/favicon.ico', function (req, reply) { + // favicon can be cached for a short period + reply.sendFile('favicon.ico', {maxAge: '1d', immutable: false}) +}) +``` + +### Options + +#### `root` (required) + +The absolute path of the directory containing the files to serve. +The file to serve is determined by combining `req.url` with the +root directory. + +An array of directories can be provided to serve multiple static directories +under a single prefix. Files are served in a "first found, first served" manner, +so list directories in order of priority. Duplicate paths will raise an error. + +#### `prefix` + +Default: `'/'` + +A URL path prefix used to create a virtual mount path for the static directory. + +#### `constraints` + +Default: `{}` + +Constraints to add to registered routes. See Fastify's documentation for +[route constraints](https://fastify.dev/docs/latest/Reference/Routes/#constraints). + +#### `logLevel` + +Default: `info` + +Set log level for registered routes. + +#### `prefixAvoidTrailingSlash` + +Default: `false` + +If `false`, the prefix gets a trailing "/". If `true`, no trailing "/" is added to the prefix. + +#### `schemaHide` + +Default: `true` + +A flag that defines if the fastify route hide-schema attribute is hidden or not. + +#### `setHeaders` + +Default: `undefined` + +A function to set custom headers on the response. Alterations to the headers +must be done synchronously. The function is called as `fn(res, path, stat)`, +with the arguments: + +- `res` The response object. +- `path` The path of the file that is being sent. +- `stat` The stat object of the file that is being sent. + +#### `send` Options + +The following options are also supported and will be passed directly to the +[`@fastify/send`](https://www.npmjs.com/package/@fastify/send) module: + +- [`acceptRanges`](https://www.npmjs.com/package/@fastify/send#acceptranges) +- [`contentType`](https://www.npmjs.com/package/@fastify/send#contenttype) +- [`cacheControl`](https://www.npmjs.com/package/@fastify/send#cachecontrol) - Enable or disable setting Cache-Control response header (defaults to `true`). To provide a custom Cache-Control header, set this option to false +- [`dotfiles`](https://www.npmjs.com/package/@fastify/send#dotfiles) +- [`etag`](https://www.npmjs.com/package/@fastify/send#etag) +- [`extensions`](https://www.npmjs.com/package/@fastify/send#extensions) +- [`immutable`](https://www.npmjs.com/package/@fastify/send#immutable) +- [`index`](https://www.npmjs.com/package/@fastify/send#index) +- [`lastModified`](https://www.npmjs.com/package/@fastify/send#lastmodified) +- [`maxAge`](https://www.npmjs.com/package/@fastify/send#maxage) + +These options can be altered when calling `reply.sendFile('filename.html', options)` or `reply.sendFile('filename.html', 'otherfilename.html', options)` on each response. + +#### `redirect` + +Default: `false` + +If set to `true`, `@fastify/static` redirects to the directory with a trailing slash. + +This option cannot be `true` if `wildcard` is `false` and `ignoreTrailingSlash` is `true`. + +If `false`, requesting directories without a trailing slash triggers the app's 404 handler using `reply.callNotFound()`. + +#### `wildcard` + +Default: `true` + +If `true`, `@fastify/static` adds a wildcard route to serve files. +If `false`, it globs the filesystem for all defined files in the +served folder (`${root}/**/**`) and creates the necessary routes, +but will not serve newly added files. + +The default options of [`glob`](https://www.npmjs.com/package/glob) +are applied for getting the file list. + +This option cannot be `false` if `redirect` is `true` and `ignoreTrailingSlash` is `true`. + +#### `globIgnore` + +Default: `undefined` + +This is passed to [`glob`](https://www.npmjs.com/package/glob) +as the `ignore` option. It can be used to ignore files or directories +when using the `wildcard: false` option. + +#### `allowedPath` + +Default: `(pathName, root, request) => true` + +This function filters served files. Using the request object, complex path authentication is possible. +Returning `true` serves the file; returning `false` calls Fastify's 404 handler. + +#### `index` + +Default: `undefined` + +Under the hood, [`@fastify/send`](https://www.npmjs.com/package/@fastify/send) supports "index.html" files by default. +To disable this, set `false`, or supply a new index by passing a string or an array in preferred order. + +#### `serveDotFiles` + +Default: `false` + +If `true`, serves files in hidden directories (e.g., `.foo`). + +#### `list` + +Default: `undefined` + +If set, provides the directory list by calling the directory path. +Default response is JSON. + +Multi-root is not supported within the `list` option. + +If `dotfiles` is `deny` or `ignore`, dotfiles are excluded. + +Example: + +```js +fastify.register(require('@fastify/static'), { + root: path.join(__dirname, 'public'), + prefix: '/public/', + index: false + list: true +}) +``` + +Request + +```bash +GET /public +``` + +Response + +```json +{ "dirs": ["dir1", "dir2"], "files": ["file1.png", "file2.txt"] } +``` + +#### `list.format` + +Default: `json` + +Options: `html`, `json` + +Directory list can be in `html` format; in that case, `list.render` function is required. + +This option can be overridden by the URL parameter `format`. Options are `html` and `json`. + +```bash +GET /public/assets?format=json +``` + +Returns the response as JSON, regardless of `list.format`. + +Example: + +```js +fastify.register(require('@fastify/static'), { + root: path.join(__dirname, 'public'), + prefix: '/public/', + list: { + format: 'html', + render: (dirs, files) => { + return ` + + + + +` + }, + } +}) +``` + +Request + +```bash +GET /public +``` + +Response + +```html + + + + +``` + +#### `list.names` + +Default: `['']` + +Directory list can respond to different routes declared in `list.names`. + +> 🛈 Note: If a file with the same name exists, the actual file is sent. + +Example: + +```js +fastify.register(require('@fastify/static'), { + root: path.join(__dirname, '/static'), + prefix: '/public', + prefixAvoidTrailingSlash: true, + list: { + format: 'json', + names: ['index', 'index.json', '/'] + } +}) +``` + +Dir list respond with the same content to: + +```bash +GET /public +GET /public/ +GET /public/index +GET /public/index.json +``` + +#### `list.extendedFolderInfo` + +Default: `undefined` + +If `true`, extended information for folders will be accessible in `list.render` and the JSON response. + +```js +render(dirs, files) { + const dir = dirs[0]; + dir.fileCount // number of files in this folder + dir.totalFileCount // number of files in this folder (recursive) + dir.folderCount // number of folders in this folder + dir.totalFolderCount // number of folders in this folder (recursive) + dir.totalSize // size of all files in this folder (recursive) + dir.lastModified // most recent last modified timestamp of all files in this folder (recursive) +} +``` + +> ⚠ Warning: This will slightly decrease the performance, especially for deeply nested file structures. + +#### `list.jsonFormat` + +Default: `names` + +Options: `names`, `extended` + +Determines the output format when `json` is selected. + +`names`: +```json +{ + "dirs": [ + "dir1", + "dir2" + ], + "files": [ + "file1.txt", + "file2.txt" + ] +} +``` + +`extended`: +```json +{ + "dirs": [ + { + "name": "dir1", + "stats": { + "dev": 2100, + "size": 4096 + }, + "extendedInfo": { + "fileCount": 4, + "totalSize": 51233 + } + } + ], + "files": [ + { + "name": "file1.txt", + "stats": { + "dev": 2200, + "size": 554 + } + } + ] +} +``` + +#### `preCompressed` + +Default: `false` + +First, try to send the brotli encoded asset (if supported by `Accept-Encoding` headers), then gzip, and finally the original `pathname`. Skip compression for smaller files that do not benefit from it. + +Assume this structure with the compressed asset as a sibling of the uncompressed counterpart: + +``` +./public +├── main.js +├── main.js.br +├── main.js.gz +├── crit.css +├── crit.css.gz +└── index.html +``` + +#### Disable serving + +To use only the reply decorator without serving directories, pass `{ serve: false }`. +This prevents the plugin from serving everything under `root`. + +#### Disabling reply decorator + +The reply object is decorated with a `sendFile` function by default. To disable this, +pass `{ decorateReply: false }`. If `@fastify/static` is registered to multiple prefixes +in the same route, only one can initialize reply decorators. + +#### Handling 404s + +If a request matches the URL `prefix` but no file is found, Fastify's 404 +handler is called. Set a custom 404 handler with [`fastify.setNotFoundHandler()`](https://fastify.dev/docs/latest/Reference/Server/#setnotfoundhandler). + +When registering `@fastify/static` within an encapsulated context, the `wildcard` option may need to be set to `false` to support index resolution and nested not-found-handler: + +```js +const app = require('fastify')(); + +app.register((childContext, _, done) => { + childContext.register(require('@fastify/static'), { + root: path.join(__dirname, 'docs'), // docs is a folder that contains `index.html` and `404.html` + wildcard: false + }); + childContext.setNotFoundHandler((_, reply) => { + return reply.code(404).type('text/html').sendFile('404.html'); + }); + done(); +}, { prefix: 'docs' }); +``` + +This code will send the `index.html` for the paths `docs`, `docs/`, and `docs/index.html`. For all other `docs/` it will reply with `404.html`. + +### Handling Errors + +If an error occurs while sending a file, it is passed to Fastify's error handler. +Set a custom handler with [`fastify.setErrorHandler()`](https://fastify.dev/docs/latest/Reference/Server/#seterrorhandler). + +### Payload `stream.path` + +Access the file path inside the `onSend` hook using `payload.path`. + +```js +fastify.addHook('onSend', function (req, reply, payload, next) { + console.log(payload.path) + next() +}) +``` + +## License + +Licensed under [MIT](./LICENSE). diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/eslint.config.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/eslint.config.js new file mode 100644 index 0000000000000000000000000000000000000000..449d56aa1a2cd194743f92022da2b1f072ffd848 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/eslint.config.js @@ -0,0 +1,7 @@ +'use strict' + +module.exports = require('neostandard')({ + ignores: require('neostandard').resolveIgnoresFromGitignore(), + noJsx: true, + ts: true, +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/example/public/.hidden/sample.json b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/example/public/.hidden/sample.json new file mode 100644 index 0000000000000000000000000000000000000000..56c8e280338ea64e1ab62ef9bacdf02840a0dabb --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/example/public/.hidden/sample.json @@ -0,0 +1 @@ +{"hello": "world"} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/example/public/images/sample.jpg b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/example/public/images/sample.jpg new file mode 100644 index 0000000000000000000000000000000000000000..f0c7c2ba02bbb5df2b0fedc3173b9a01633abe3e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/example/public/images/sample.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7c859e2f8ee6f21120d12a774038d0022dda0f44c37e4c7de34b07b7323b742c +size 43933 diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/example/public/index.css b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/example/public/index.css new file mode 100644 index 0000000000000000000000000000000000000000..6d21fe430740be4a187414456706db6e526af5f7 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/example/public/index.css @@ -0,0 +1,9 @@ +#my-button { + position: absolute; + top: 50%; + left: 50%; + width: 200px; + height: 28px; + margin-top: -14px; + margin-left: -100px; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/example/public/index.html b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/example/public/index.html new file mode 100644 index 0000000000000000000000000000000000000000..c8c65f9329aa116199efeb0dcc8e72fbad440b8f --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/example/public/index.html @@ -0,0 +1,11 @@ + + + + + + + + + diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/example/public/index.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/example/public/index.js new file mode 100644 index 0000000000000000000000000000000000000000..a0d57a71cdbfc34d6ebc91b27148f126b45cb852 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/example/public/index.js @@ -0,0 +1,8 @@ +'use strict' + +window.onload = function () { + const b = document.getElementById('my-button') + b.onclick = function () { + window.alert('foo') + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/example/public2/test.css b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/example/public2/test.css new file mode 100644 index 0000000000000000000000000000000000000000..1bee9c0281bdfbc82d671407cb49326632cb427e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/example/public2/test.css @@ -0,0 +1,4 @@ +body { + background-color: black; + color: white; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/example/public2/test.html b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/example/public2/test.html new file mode 100644 index 0000000000000000000000000000000000000000..5480039682366042f6a09482a7af200e1de44036 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/example/public2/test.html @@ -0,0 +1,8 @@ + + + + + +

Test 2

+ + diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/example/server-compress.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/example/server-compress.js new file mode 100644 index 0000000000000000000000000000000000000000..2dd5b2525a2b20b0478c09c3659fd44d4a734338 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/example/server-compress.js @@ -0,0 +1,15 @@ +'use strict' + +const path = require('node:path') +const fastify = require('fastify')({ logger: { level: 'trace' } }) + +fastify + // Compress everything. + .register(require('@fastify/compress'), { threshold: 0 }) + .register(require('../'), { + // An absolute path containing static files to serve. + root: path.join(__dirname, '/public') + }) + .listen({ port: 3000 }, err => { + if (err) throw err + }) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/example/server-dir-list.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/example/server-dir-list.js new file mode 100644 index 0000000000000000000000000000000000000000..39cca9823cb7a314b26686419ec8470687d3824e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/example/server-dir-list.js @@ -0,0 +1,38 @@ +'use strict' + +const path = require('node:path') + +const fastify = require('fastify')({ logger: { level: 'trace' } }) + +const renderer = (dirs, files) => { + return ` + + + + +` +} + +fastify + .register(require('..'), { + // An absolute path containing static files to serve. + root: path.join(__dirname, '/public'), + // Do not append a trailing slash to prefixes. + prefixAvoidTrailingSlash: true, + // Return a directory listing with a handlebar template. + list: { + // html or json response? html requires a render method. + format: 'html', + // A list of filenames that trigger a directory list response. + names: ['index', 'index.html', 'index.htm', '/'], + // You can provide your own render method as needed. + renderer + } + }) + .listen({ port: 3000 }, err => { + if (err) throw err + }) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/example/server-hidden-file.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/example/server-hidden-file.js new file mode 100644 index 0000000000000000000000000000000000000000..fe1f3afb3d6dc2adffbd150a51b2ba8f0151d752 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/example/server-hidden-file.js @@ -0,0 +1,15 @@ +'use strict' + +const path = require('node:path') +const fastify = require('fastify')({ logger: { level: 'trace' } }) + +fastify + .register(require('../'), { + // An absolute path containing static files to serve. + root: path.join(__dirname, '/public'), + wildcard: false, + serveDotFiles: true + }) + .listen({ port: 3000 }, err => { + if (err) throw err + }) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/example/server.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/example/server.js new file mode 100644 index 0000000000000000000000000000000000000000..f587183bce2fe82583a48c33e1a995a2599419cb --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/example/server.js @@ -0,0 +1,13 @@ +'use strict' + +const path = require('node:path') +const fastify = require('fastify')({ logger: { level: 'trace' } }) + +fastify + .register(require('../'), { + // An absolute path containing static files to serve. + root: path.join(__dirname, '/public') + }) + .listen({ port: 3000 }, err => { + if (err) throw err + }) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/index.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/index.js new file mode 100644 index 0000000000000000000000000000000000000000..e65211595939b7f6311ced10d0e4d0a6dd337e78 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/index.js @@ -0,0 +1,547 @@ +'use strict' + +const path = require('node:path') +const { fileURLToPath } = require('node:url') +const { statSync } = require('node:fs') +const { glob } = require('glob') +const fp = require('fastify-plugin') +const send = require('@fastify/send') +const encodingNegotiator = require('@fastify/accept-negotiator') +const contentDisposition = require('content-disposition') + +const dirList = require('./lib/dirList') + +const endForwardSlashRegex = /\/$/u +const asteriskRegex = /\*/gu + +const supportedEncodings = ['br', 'gzip', 'deflate'] +send.mime.default_type = 'application/octet-stream' + +async function fastifyStatic (fastify, opts) { + opts.root = normalizeRoot(opts.root) + checkRootPathForErrors(fastify, opts.root) + + const setHeaders = opts.setHeaders + if (setHeaders !== undefined && typeof setHeaders !== 'function') { + throw new TypeError('The `setHeaders` option must be a function') + } + + const invalidDirListOpts = dirList.validateOptions(opts) + if (invalidDirListOpts) { + throw invalidDirListOpts + } + + if (opts.dotfiles === undefined) { + opts.dotfiles = 'allow' + } + + const sendOptions = { + root: opts.root, + acceptRanges: opts.acceptRanges, + contentType: opts.contentType, + cacheControl: opts.cacheControl, + dotfiles: opts.dotfiles, + etag: opts.etag, + extensions: opts.extensions, + immutable: opts.immutable, + index: opts.index, + lastModified: opts.lastModified, + maxAge: opts.maxAge + } + + let prefix = opts.prefix ?? (opts.prefix = '/') + + if (!opts.prefixAvoidTrailingSlash) { + prefix = + prefix[prefix.length - 1] === '/' + ? prefix + : prefix + '/' + } + + // Set the schema hide property if defined in opts or true by default + const routeOpts = { + constraints: opts.constraints, + schema: { + hide: opts.schemaHide !== undefined ? opts.schemaHide : true + }, + logLevel: opts.logLevel, + errorHandler (error, request, reply) { + if (error?.code === 'ERR_STREAM_PREMATURE_CLOSE') { + reply.request.raw.destroy() + return + } + + fastify.errorHandler(error, request, reply) + } + } + + if (opts.decorateReply !== false) { + fastify.decorateReply('sendFile', function (filePath, rootPath, options) { + const opts = typeof rootPath === 'object' ? rootPath : options + const root = typeof rootPath === 'string' ? rootPath : opts?.root + pumpSendToReply( + this.request, + this, + filePath, + root || sendOptions.root, + 0, + opts + ) + return this + }) + + fastify.decorateReply( + 'download', + function (filePath, fileName, options = {}) { + const { root, ...opts } = + typeof fileName === 'object' ? fileName : options + fileName = typeof fileName === 'string' ? fileName : filePath + + // Set content disposition header + this.header('content-disposition', contentDisposition(fileName)) + + pumpSendToReply(this.request, this, filePath, root, 0, opts) + + return this + } + ) + } + + if (opts.serve !== false) { + if (opts.wildcard && typeof opts.wildcard !== 'boolean') { + throw new TypeError('"wildcard" option must be a boolean') + } + if (opts.wildcard === undefined || opts.wildcard === true) { + fastify.route({ + ...routeOpts, + method: ['HEAD', 'GET'], + path: prefix + '*', + handler (req, reply) { + pumpSendToReply(req, reply, '/' + req.params['*'], sendOptions.root) + } + }) + if (opts.redirect === true && prefix !== opts.prefix) { + fastify.get(opts.prefix, routeOpts, (req, reply) => { + reply.redirect(getRedirectUrl(req.raw.url), 301) + }) + } + } else { + const indexes = opts.index === undefined ? ['index.html'] : [].concat(opts.index) + const indexDirs = new Map() + const routes = new Set() + + const roots = Array.isArray(sendOptions.root) ? sendOptions.root : [sendOptions.root] + for (let rootPath of roots) { + rootPath = rootPath.split(path.win32.sep).join(path.posix.sep) + !rootPath.endsWith('/') && (rootPath += '/') + const files = await glob('**/**', { + cwd: rootPath, absolute: false, follow: true, nodir: true, dot: opts.serveDotFiles, ignore: opts.globIgnore + }) + + for (let file of files) { + file = file.split(path.win32.sep).join(path.posix.sep) + const route = prefix + file + + if (routes.has(route)) { + continue + } + + routes.add(route) + + setUpHeadAndGet(routeOpts, route, `/${file}`, rootPath) + + const key = path.posix.basename(route) + if (indexes.includes(key) && !indexDirs.has(key)) { + indexDirs.set(path.posix.dirname(route), rootPath) + } + } + } + + for (const [dirname, rootPath] of indexDirs.entries()) { + const pathname = dirname + (dirname.endsWith('/') ? '' : '/') + const file = '/' + pathname.replace(prefix, '') + setUpHeadAndGet(routeOpts, pathname, file, rootPath) + + if (opts.redirect === true) { + setUpHeadAndGet(routeOpts, pathname.replace(endForwardSlashRegex, ''), file.replace(endForwardSlashRegex, ''), rootPath) + } + } + } + } + + const allowedPath = opts.allowedPath + + async function pumpSendToReply ( + request, + reply, + pathname, + rootPath, + rootPathOffset = 0, + pumpOptions, + checkedEncodings + ) { + const pathnameOrig = pathname + const options = Object.assign({}, sendOptions, pumpOptions) + + if (rootPath) { + if (Array.isArray(rootPath)) { + options.root = rootPath[rootPathOffset] + } else { + options.root = rootPath + } + } + + if (allowedPath && !allowedPath(pathname, options.root, request)) { + return reply.callNotFound() + } + + let encoding + let pathnameForSend = pathname + + if (opts.preCompressed) { + /** + * We conditionally create this structure to track our attempts + * at sending pre-compressed assets + */ + if (!checkedEncodings) { + checkedEncodings = new Set() + } + + encoding = getEncodingHeader(request.headers, checkedEncodings) + + if (encoding) { + if (pathname.endsWith('/')) { + pathname = findIndexFile(pathname, options.root, options.index) + if (!pathname) { + return reply.callNotFound() + } + pathnameForSend = pathnameForSend + pathname + '.' + getEncodingExtension(encoding) + } else { + pathnameForSend = pathname + '.' + getEncodingExtension(encoding) + } + } + } + + // `send(..., path, ...)` will URI-decode path so we pass an encoded path here + const { + statusCode, + headers, + stream, + type, + metadata + } = await send(request.raw, encodeURI(pathnameForSend), options) + switch (type) { + case 'directory': { + const path = metadata.path + if (opts.list) { + await dirList.send({ + reply, + dir: path, + options: opts.list, + route: pathname, + prefix, + dotfiles: opts.dotfiles + }).catch((err) => reply.send(err)) + } + + if (opts.redirect === true) { + try { + reply.redirect(getRedirectUrl(request.raw.url), 301) + } /* c8 ignore start */ catch (error) { + // the try-catch here is actually unreachable, but we keep it for safety and prevent DoS attack + await reply.send(error) + } /* c8 ignore stop */ + } else { + // if is a directory path without a trailing slash, and has an index file, reply as if it has a trailing slash + if (!pathname.endsWith('/') && findIndexFile(pathname, options.root, options.index)) { + return pumpSendToReply( + request, + reply, + pathname + '/', + rootPath, + undefined, + undefined, + checkedEncodings + ) + } + + reply.callNotFound() + } + break + } + case 'error': { + if ( + statusCode === 403 && + (!options.index || !options.index.length) && + pathnameForSend[pathnameForSend.length - 1] === '/' + ) { + if (opts.list) { + await dirList.send({ + reply, + dir: dirList.path(opts.root, pathname), + options: opts.list, + route: pathname, + prefix, + dotfiles: opts.dotfiles + }).catch((err) => reply.send(err)) + return + } + } + + if (metadata.error.code === 'ENOENT') { + // when preCompress is enabled and the path is a directory without a trailing slash + if (opts.preCompressed && encoding) { + if (opts.redirect !== true) { + const indexPathname = findIndexFile(pathname, options.root, options.index) + if (indexPathname) { + return pumpSendToReply( + request, + reply, + pathname + '/', + rootPath, + undefined, + undefined, + checkedEncodings + ) + } + } + } + + // if file exists, send real file, otherwise send dir list if name match + if (opts.list && dirList.handle(pathname, opts.list)) { + await dirList.send({ + reply, + dir: dirList.path(opts.root, pathname), + options: opts.list, + route: pathname, + prefix, + dotfiles: opts.dotfiles + }).catch((err) => reply.send(err)) + return + } + + // root paths left to try? + if (Array.isArray(rootPath) && rootPathOffset < (rootPath.length - 1)) { + return pumpSendToReply(request, reply, pathname, rootPath, rootPathOffset + 1) + } + + if (opts.preCompressed && !checkedEncodings.has(encoding)) { + checkedEncodings.add(encoding) + return pumpSendToReply( + request, + reply, + pathnameOrig, + rootPath, + rootPathOffset, + undefined, + checkedEncodings + ) + } + + return reply.callNotFound() + } + + // The `send` library terminates the request with a 404 if the requested + // path contains a dotfile and `send` is initialized with `{dotfiles: + // 'ignore'}`. `send` aborts the request before getting far enough to + // check if the file exists (hence, a 404 `NotFoundError` instead of + // `ENOENT`). + // https://github.com/pillarjs/send/blob/de073ed3237ade9ff71c61673a34474b30e5d45b/index.js#L582 + if (metadata.error.status === 404) { + return reply.callNotFound() + } + + await reply.send(metadata.error) + break + } + case 'file': { + // reply.raw.statusCode by default 200 + // when ever the user changed it, we respect the status code + // otherwise use send provided status code + const newStatusCode = reply.statusCode !== 200 ? reply.statusCode : statusCode + reply.code(newStatusCode) + if (setHeaders !== undefined) { + setHeaders(reply.raw, metadata.path, metadata.stat) + } + reply.headers(headers) + if (encoding) { + reply.header('content-type', getContentType(pathname)) + reply.header('content-encoding', encoding) + } + await reply.send(stream) + break + } + } + } + + function setUpHeadAndGet (routeOpts, route, file, rootPath) { + const toSetUp = Object.assign({}, routeOpts, { + method: ['HEAD', 'GET'], + url: route, + handler: serveFileHandler + }) + toSetUp.config = toSetUp.config || {} + toSetUp.config.file = file + toSetUp.config.rootPath = rootPath + fastify.route(toSetUp) + } + + async function serveFileHandler (req, reply) { + // TODO: remove the fallback branch when bump major + /* c8 ignore next */ + const routeConfig = req.routeOptions?.config || req.routeConfig + return pumpSendToReply(req, reply, routeConfig.file, routeConfig.rootPath) + } +} + +function normalizeRoot (root) { + if (root === undefined) { + return root + } + if (root instanceof URL && root.protocol === 'file:') { + return fileURLToPath(root) + } + if (Array.isArray(root)) { + const result = [] + for (let i = 0, il = root.length; i < il; ++i) { + if (root[i] instanceof URL && root[i].protocol === 'file:') { + result.push(fileURLToPath(root[i])) + } else { + result.push(root[i]) + } + } + + return result + } + + return root +} + +function checkRootPathForErrors (fastify, rootPath) { + if (rootPath === undefined) { + throw new Error('"root" option is required') + } + + if (Array.isArray(rootPath)) { + if (!rootPath.length) { + throw new Error('"root" option array requires one or more paths') + } + + if (new Set(rootPath).size !== rootPath.length) { + throw new Error( + '"root" option array contains one or more duplicate paths' + ) + } + + // check each path and fail at first invalid + rootPath.map((path) => checkPath(fastify, path)) + return + } + + if (typeof rootPath === 'string') { + return checkPath(fastify, rootPath) + } + + throw new Error('"root" option must be a string or array of strings') +} + +function checkPath (fastify, rootPath) { + if (typeof rootPath !== 'string') { + throw new TypeError('"root" option must be a string') + } + if (path.isAbsolute(rootPath) === false) { + throw new Error('"root" option must be an absolute path') + } + + let pathStat + + try { + pathStat = statSync(rootPath) + } catch (e) { + if (e.code === 'ENOENT') { + fastify.log.warn(`"root" path "${rootPath}" must exist`) + return + } + + throw e + } + + if (pathStat.isDirectory() === false) { + throw new Error('"root" option must point to a directory') + } +} + +function getContentType (path) { + const type = send.mime.getType(path) || send.mime.default_type + + if (!send.isUtf8MimeType(type)) { + return type + } + return `${type}; charset=utf-8` +} + +function findIndexFile (pathname, root, indexFiles = ['index.html']) { + if (Array.isArray(indexFiles)) { + return indexFiles.find(filename => { + const p = path.join(root, pathname, filename) + try { + const stats = statSync(p) + return !stats.isDirectory() + } catch { + return false + } + }) + } + /* c8 ignore next */ + return false +} + +// Adapted from https://github.com/fastify/fastify-compress/blob/665e132fa63d3bf05ad37df3c20346660b71a857/index.js#L451 +function getEncodingHeader (headers, checked) { + if (!('accept-encoding' in headers)) return + + // consider the no-preference token as gzip for downstream compat + const header = headers['accept-encoding'].toLowerCase().replace(asteriskRegex, 'gzip') + + return encodingNegotiator.negotiate( + header, + supportedEncodings.filter((enc) => !checked.has(enc)) + ) +} + +function getEncodingExtension (encoding) { + switch (encoding) { + case 'br': + return 'br' + + case 'gzip': + return 'gz' + } +} + +function getRedirectUrl (url) { + let i = 0 + // we detect how many slash before a valid path + for (; i < url.length; ++i) { + if (url[i] !== '/' && url[i] !== '\\') break + } + // turns all leading / or \ into a single / + url = '/' + url.substr(i) + try { + const parsed = new URL(url, 'http://localhost.com/') + const parsedPathname = parsed.pathname + return parsedPathname + (parsedPathname[parsedPathname.length - 1] !== '/' ? '/' : '') + (parsed.search || '') + } /* c8 ignore start */ catch { + // the try-catch here is actually unreachable, but we keep it for safety and prevent DoS attack + const err = new Error(`Invalid redirect URL: ${url}`) + err.statusCode = 400 + throw err + } /* c8 ignore stop */ +} + +module.exports = fp(fastifyStatic, { + fastify: '5.x', + name: '@fastify/static' +}) +module.exports.default = fastifyStatic +module.exports.fastifyStatic = fastifyStatic diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/lib/dirList.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/lib/dirList.js new file mode 100644 index 0000000000000000000000000000000000000000..916ace6c4e4485a09f8a8a6951b2bf1853b39ac3 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/lib/dirList.js @@ -0,0 +1,211 @@ +'use strict' + +const os = require('node:os') +const path = require('node:path') +const fs = require('node:fs/promises') +const fastq = require('fastq') +const fastqConcurrency = Math.max(1, os.cpus().length - 1) + +const dirList = { + _getExtendedInfo: async function (dir, info) { + const depth = dir.split(path.sep).length + const files = await fs.readdir(dir) + + const worker = async (filename) => { + const filePath = path.join(dir, filename) + let stats + try { + stats = await fs.stat(filePath) + } catch { + return + } + + if (stats.isDirectory()) { + info.totalFolderCount++ + filePath.split(path.sep).length === depth + 1 && info.folderCount++ + await dirList._getExtendedInfo(filePath, info) + } else { + info.totalSize += stats.size + info.totalFileCount++ + filePath.split(path.sep).length === depth + 1 && info.fileCount++ + info.lastModified = Math.max(info.lastModified, stats.mtimeMs) + } + } + const queue = fastq.promise(worker, fastqConcurrency) + await Promise.all(files.map(filename => queue.push(filename))) + }, + + /** + * get extended info about a folder + * @param {string} folderPath full path fs dir + * @return {Promise} + */ + getExtendedInfo: async function (folderPath) { + const info = { + totalSize: 0, + fileCount: 0, + totalFileCount: 0, + folderCount: 0, + totalFolderCount: 0, + lastModified: 0 + } + + await dirList._getExtendedInfo(folderPath, info) + + return info + }, + + /** + * get files and dirs from dir, or error + * @param {string} dir full path fs dir + * @param {(boolean | ListOptionsJsonFormat | ListOptionsHtmlFormat)} options + * @param {string} dotfiles + * note: can't use glob because don't get error on non existing dir + */ + list: async function (dir, options, dotfiles) { + const entries = { dirs: [], files: [] } + let files = await fs.readdir(dir) + if (dotfiles === 'deny' || dotfiles === 'ignore') { + files = files.filter(file => file.charAt(0) !== '.') + } + if (files.length < 1) { + return entries + } + + const worker = async (filename) => { + let stats + try { + stats = await fs.stat(path.join(dir, filename)) + } catch { + return + } + const entry = { name: filename, stats } + if (stats.isDirectory()) { + if (options.extendedFolderInfo) { + entry.extendedInfo = await dirList.getExtendedInfo(path.join(dir, filename)) + } + entries.dirs.push(entry) + } else { + entries.files.push(entry) + } + } + const queue = fastq.promise(worker, fastqConcurrency) + await Promise.all(files.map(filename => queue.push(filename))) + + entries.dirs.sort((a, b) => a.name.localeCompare(b.name)) + entries.files.sort((a, b) => a.name.localeCompare(b.name)) + + return entries + }, + + /** + * send dir list content, or 404 on error + * @param {Fastify.Reply} reply + * @param {string} dir full path fs dir + * @param {(boolean | ListOptionsJsonFormat | ListOptionsHtmlFormat)} options + * @param {string} route request route + * @param {string} dotfiles + */ + send: async function ({ reply, dir, options, route, prefix, dotfiles }) { + if (reply.request.query.format === 'html' && typeof options.render !== 'function') { + throw new TypeError('The `list.render` option must be a function and is required with the URL parameter `format=html`') + } + + let entries + try { + entries = await dirList.list(dir, options, dotfiles) + } catch { + return reply.callNotFound() + } + + const format = reply.request.query.format || options.format + if (format !== 'html') { + if (options.jsonFormat !== 'extended') { + const nameEntries = { dirs: [], files: [] } + entries.dirs.forEach(entry => nameEntries.dirs.push(entry.name)) + entries.files.forEach(entry => nameEntries.files.push(entry.name)) + + await reply.send(nameEntries) + } else { + await reply.send(entries) + } + return + } + + const html = options.render( + entries.dirs.map(entry => dirList.htmlInfo(entry, route, prefix, options)), + entries.files.map(entry => dirList.htmlInfo(entry, route, prefix, options))) + await reply.type('text/html').send(html) + }, + + /** + * provide the html information about entry and route, to get name and full route + * @param entry file or dir name and stats + * @param {string} route request route + * @return {ListFile} + */ + htmlInfo: function (entry, route, prefix, options) { + if (options.names?.includes(path.basename(route))) { + route = path.normalize(path.join(route, '..')) + } + return { + href: encodeURI(path.join(prefix, route, entry.name).replace(/\\/gu, '/')), + name: entry.name, + stats: entry.stats, + extendedInfo: entry.extendedInfo + } + }, + + /** + * say if the route can be handled by dir list or not + * @param {string} route request route + * @param {(boolean | ListOptionsJsonFormat | ListOptionsHtmlFormat)} options + * @return {boolean} + */ + handle: function (route, options) { + return options.names?.includes(path.basename(route)) || + // match trailing slash + ((options.names?.includes('/') && route[route.length - 1] === '/') ?? false) + }, + + /** + * get path from route and fs root paths, considering trailing slash + * @param {string} root fs root path + * @param {string} route request route + */ + path: function (root, route) { + const _route = route[route.length - 1] === '/' + ? route + 'none' + : route + return path.dirname(path.join(root, _route)) + }, + + /** + * validate options + * @return {Error} + */ + validateOptions: function (options) { + if (!options.list) { + return + } + + if (Array.isArray(options.root)) { + return new TypeError('multi-root with list option is not supported') + } + + if (options.list.format && options.list.format !== 'json' && options.list.format !== 'html') { + return new TypeError('The `list.format` option must be json or html') + } + if (options.list.names && !Array.isArray(options.list.names)) { + return new TypeError('The `list.names` option must be an array') + } + if (options.list.jsonFormat != null && options.list.jsonFormat !== 'names' && options.list.jsonFormat !== 'extended') { + return new TypeError('The `list.jsonFormat` option must be name or extended') + } + if (options.list.format === 'html' && typeof options.list.render !== 'function') { + return new TypeError('The `list.render` option must be a function and is required with html format') + } + } +} + +module.exports = dirList diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/package.json b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/package.json new file mode 100644 index 0000000000000000000000000000000000000000..1855675df826d198f5b002c0317c429ba30df997 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/package.json @@ -0,0 +1,88 @@ +{ + "name": "@fastify/static", + "version": "8.2.0", + "description": "Plugin for serving static files as fast as possible.", + "main": "index.js", + "type": "commonjs", + "types": "types/index.d.ts", + "scripts": { + "coverage": "c8 --reporter html borp --coverage --check-coverage --lines 100", + "lint": "eslint", + "lint:fix": "eslint --fix", + "test": "npm run test:unit && npm run test:typescript", + "test:typescript": "tsd", + "test:unit": "borp -C --check-coverage --lines 100", + "example": "node example/server.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/fastify/fastify-static.git" + }, + "keywords": [ + "fastify", + "static" + ], + "author": "Tommaso Allevi - @allevo", + "contributors": [ + { + "name": "Matteo Collina", + "email": "hello@matteocollina.com" + }, + { + "name": "Manuel Spigolon", + "email": "behemoth89@gmail.com" + }, + { + "name": "Aras Abbasi", + "email": "aras.abbasi@gmail.com" + }, + { + "name": "Frazer Smith", + "email": "frazer.dev@icloud.com", + "url": "https://github.com/fdawgs" + } + ], + "license": "MIT", + "bugs": { + "url": "https://github.com/fastify/fastify-static/issues" + }, + "homepage": "https://github.com/fastify/fastify-static", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "dependencies": { + "@fastify/accept-negotiator": "^2.0.0", + "@fastify/send": "^4.0.0", + "content-disposition": "^0.5.4", + "fastify-plugin": "^5.0.0", + "fastq": "^1.17.1", + "glob": "^11.0.0" + }, + "devDependencies": { + "@fastify/compress": "^8.0.0", + "@fastify/pre-commit": "^2.1.0", + "@types/node": "^22.0.0", + "borp": "^0.20.0", + "c8": "^10.1.3", + "concat-stream": "^2.0.0", + "eslint": "^9.17.0", + "fastify": "^5.1.0", + "neostandard": "^0.12.0", + "pino": "^9.1.0", + "proxyquire": "^2.1.3", + "tsd": "^0.32.0" + }, + "tsd": { + "directory": "test/types" + }, + "publishConfig": { + "access": "public" + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/content-type.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/content-type.test.js new file mode 100644 index 0000000000000000000000000000000000000000..6712eeadd8dd7f00d994d06c242cf376a7508eca --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/content-type.test.js @@ -0,0 +1,144 @@ +'use strict' + +/* eslint n/no-deprecated-api: "off" */ + +const path = require('node:path') +const { test } = require('node:test') +const Fastify = require('fastify') + +const fastifyStatic = require('../') + +test('register /content-type', async t => { + t.plan(5) + + const pluginOptions = { + root: path.join(__dirname, '/content-type'), + prefix: '/content-type' + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + await t.test('/content-type/index.html', async (t) => { + t.plan(2) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/content-type/index.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.headers.get('content-type'), 'text/html; charset=utf-8') + }) + + await t.test('/content-type/index.css', async (t) => { + t.plan(2) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/content-type/index.css') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.headers.get('content-type'), 'text/css; charset=utf-8') + }) + + await t.test('/content-type/sample.jpg', async (t) => { + t.plan(2) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/content-type/sample.jpg') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.headers.get('content-type'), 'image/jpeg') + }) + + await t.test('/content-type/test.txt', async (t) => { + t.plan(2) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/content-type/test.txt') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.headers.get('content-type'), 'text/plain; charset=utf-8') + }) + + await t.test('/content-type/binary', async (t) => { + t.plan(2) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/content-type/binary') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.headers.get('content-type'), 'application/octet-stream') + }) +}) + +test('register /content-type preCompressed', async t => { + t.plan(5) + + const pluginOptions = { + root: path.join(__dirname, '/content-type'), + prefix: '/content-type', + preCompressed: true + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + await t.test('/content-type/index.html', async (t) => { + t.plan(2) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/content-type/index.html', { + headers: { + 'accept-encoding': 'gzip, deflate, br' + } + }) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.headers.get('content-type'), 'text/html; charset=utf-8') + }) + + await t.test('/content-type/index.css', async (t) => { + t.plan(2) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/content-type/index.css', { + headers: { + 'accept-encoding': 'gzip, deflate, br' + } + }) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.headers.get('content-type'), 'text/css; charset=utf-8') + }) + + await t.test('/content-type/sample.jpg', async (t) => { + t.plan(2) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/content-type/sample.jpg', { + headers: { + 'accept-encoding': 'gzip, deflate, br' + } + }) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.headers.get('content-type'), 'image/jpeg') + }) + + await t.test('/content-type/test.txt', async (t) => { + t.plan(2) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/content-type/test.txt', { + headers: { + 'accept-encoding': 'gzip, deflate, br' + } + }) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.headers.get('content-type'), 'text/plain; charset=utf-8') + }) + + await t.test('/content-type/binary', async (t) => { + t.plan(2) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/content-type/binary', { + headers: { + 'accept-encoding': 'gzip, deflate, br' + } + }) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.headers.get('content-type'), 'application/octet-stream') + }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/content-type/binary b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/content-type/binary new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/content-type/binary.br b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/content-type/binary.br new file mode 100644 index 0000000000000000000000000000000000000000..c183df6a308637ea8e1bbb578785c74bec7f8599 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/content-type/binary.br @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/content-type/index.css b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/content-type/index.css new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/content-type/index.css.br b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/content-type/index.css.br new file mode 100644 index 0000000000000000000000000000000000000000..c183df6a308637ea8e1bbb578785c74bec7f8599 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/content-type/index.css.br @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/content-type/index.html b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/content-type/index.html new file mode 100644 index 0000000000000000000000000000000000000000..1b0b72f02fe433adb972fde358d316866365eef5 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/content-type/index.html @@ -0,0 +1,5 @@ + + + the body + + diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/content-type/index.html.br b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/content-type/index.html.br new file mode 100644 index 0000000000000000000000000000000000000000..bebb53895ec7fcf262a7d4e045bb24a794b0cce1 Binary files /dev/null and b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/content-type/index.html.br differ diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/content-type/sample.jpg b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/content-type/sample.jpg new file mode 100644 index 0000000000000000000000000000000000000000..f0c7c2ba02bbb5df2b0fedc3173b9a01633abe3e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/content-type/sample.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7c859e2f8ee6f21120d12a774038d0022dda0f44c37e4c7de34b07b7323b742c +size 43933 diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/content-type/test.txt b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/content-type/test.txt new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/content-type/test.txt.br b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/content-type/test.txt.br new file mode 100644 index 0000000000000000000000000000000000000000..c183df6a308637ea8e1bbb578785c74bec7f8599 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/content-type/test.txt.br @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/dir-list.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/dir-list.test.js new file mode 100644 index 0000000000000000000000000000000000000000..a6af123f9827f57d4759f9083d8c455c3fedd788 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/dir-list.test.js @@ -0,0 +1,738 @@ +'use strict' + +/* eslint n/no-deprecated-api: "off" */ + +const fs = require('node:fs') +const path = require('node:path') +const { test } = require('node:test') +const Fastify = require('fastify') + +const fastifyStatic = require('..') +const dirList = require('../lib/dirList') + +const helper = { + arrange: async function (t, options, f) { + const fastify = Fastify() + fastify.register(fastifyStatic, options) + t.after(() => fastify.close()) + await fastify.listen({ port: 0 }) + fastify.server.unref() + await f('http://localhost:' + fastify.server.address().port) + } +} + +try { + fs.mkdirSync(path.join(__dirname, 'static/shallow/empty')) +} catch {} + +test('throws when `root` is an array', t => { + t.plan(2) + + const err = dirList.validateOptions({ root: ['hello', 'world'], list: true }) + t.assert.ok(err instanceof TypeError) + t.assert.deepStrictEqual(err.message, 'multi-root with list option is not supported') +}) + +test('throws when `list.format` option is invalid', t => { + t.plan(2) + + const err = dirList.validateOptions({ list: { format: 'hello' } }) + t.assert.ok(err instanceof TypeError) + t.assert.deepStrictEqual(err.message, 'The `list.format` option must be json or html') +}) + +test('throws when `list.names option` is not an array', t => { + t.plan(2) + + const err = dirList.validateOptions({ list: { names: 'hello' } }) + t.assert.ok(err instanceof TypeError) + t.assert.deepStrictEqual(err.message, 'The `list.names` option must be an array') +}) + +test('throws when `list.jsonFormat` option is invalid', t => { + t.plan(2) + + const err = dirList.validateOptions({ list: { jsonFormat: 'hello' } }) + t.assert.ok(err instanceof TypeError) + t.assert.deepStrictEqual(err.message, 'The `list.jsonFormat` option must be name or extended') +}) + +test('throws when `list.format` is html and `list render` is not a function', t => { + t.plan(2) + + const err = dirList.validateOptions({ list: { format: 'html', render: 'hello' } }) + t.assert.ok(err instanceof TypeError) + t.assert.deepStrictEqual(err.message, 'The `list.render` option must be a function and is required with html format') +}) + +test('dir list wrong options', async t => { + t.plan(3) + + const cases = [ + { + options: { + root: path.join(__dirname, '/static'), + prefix: '/public', + list: { + format: 'no-json,no-html' + } + }, + error: new TypeError('The `list.format` option must be json or html') + }, + { + options: { + root: path.join(__dirname, '/static'), + list: { + format: 'html' + // no render function + } + }, + error: new TypeError('The `list.render` option must be a function and is required with html format') + }, + { + options: { + root: path.join(__dirname, '/static'), + list: { + names: 'not-an-array' + } + }, + error: new TypeError('The `list.names` option must be an array') + } + ] + + for (const case_ of cases) { + const fastify = Fastify() + fastify.register(fastifyStatic, case_.options) + await t.assert.rejects(fastify.listen({ port: 0 }), new TypeError(case_.error.message)) + fastify.server.unref() + } +}) + +test('dir list default options', async t => { + t.plan(1) + + const options = { + root: path.join(__dirname, '/static'), + prefix: '/public', + list: true + } + const route = '/public/shallow' + const content = { dirs: ['empty'], files: ['sample.jpg'] } + + await helper.arrange(t, options, async (url) => { + await t.test(route, async t => { + t.plan(3) + + const response = await fetch(url + route) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.json(), content) + }) + }) +}) + +test('dir list, custom options', async t => { + t.plan(1) + + const options = { + root: path.join(__dirname, '/static'), + prefix: '/public', + index: false, + list: true + } + + const route = '/public/' + const content = { dirs: ['deep', 'shallow'], files: ['.example', '100%.txt', 'a .md', 'foo.html', 'foobar.html', 'index.css', 'index.html'] } + + await helper.arrange(t, options, async (url) => { + await t.test(route, async t => { + t.plan(3) + + const response = await fetch(url + route) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.json(), content) + }) + }) +}) + +test('dir list, custom options with empty array index', async t => { + t.plan(1) + + const options = { + root: path.join(__dirname, '/static'), + prefix: '/public', + index: [], + list: true + } + + const route = '/public/' + const content = { dirs: ['deep', 'shallow'], files: ['.example', '100%.txt', 'a .md', 'foo.html', 'foobar.html', 'index.css', 'index.html'] } + + await helper.arrange(t, options, async (url) => { + await t.test(route, async t => { + t.plan(3) + + const response = await fetch(url + route) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.json(), content) + }) + }) +}) + +test('dir list html format', async t => { + t.plan(2) + + const options = { + root: path.join(__dirname, '/static'), + prefix: '/public', + index: false, + list: { + format: 'html', + names: ['index', 'index.htm'], + render: (dirs, files) => { + return ` + + + + +` + } + } + } + const routes = ['/public/index.htm', '/public/index'] + + // check all routes by names + + await helper.arrange(t, options, async (url) => { + for (const route of routes) { + await t.test(route, async t => { + t.plan(3) + + const response = await fetch(url + route) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), ` + + + + +`) + }) + } + }) +}) + +test('dir list href nested structure', async t => { + t.plan(5) + + const options = { + root: path.join(__dirname, '/static'), + prefix: '/public', + index: false, + list: { + format: 'html', + names: ['index', 'index.htm'], + render (dirs) { + return dirs[0].href + } + } + } + + const routes = [ + { path: '/public/', response: '/public/deep' }, + { path: '/public/index', response: '/public/deep' }, + { path: '/public/deep/', response: '/public/deep/path' }, + { path: '/public/deep/index.htm', response: '/public/deep/path' }, + { path: '/public/deep/path/', response: '/public/deep/path/for' } + ] + await helper.arrange(t, options, async (url) => { + for (const route of routes) { + await t.test(route.path, async t => { + t.plan(5) + + const response = await fetch(url + route.path) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + const responseContent = await response.text() + t.assert.deepStrictEqual(responseContent, route.response) + + const response2 = await fetch(url + responseContent) + t.assert.ok(response2.ok) + t.assert.deepStrictEqual(response2.status, 200) + }) + } + }) +}) + +test('dir list html format - stats', async t => { + t.plan(6) + + const options1 = { + root: path.join(__dirname, '/static'), + prefix: '/public', + index: false, + list: { + format: 'html', + render (dirs, files) { + t.assert.ok(dirs.length > 0) + t.assert.ok(files.length > 0) + + t.assert.ok(dirs.every(every)) + t.assert.ok(files.every(every)) + + function every (value) { + return value.stats?.atime && + !value.extendedInfo + } + } + } + } + + const route = '/public/' + + await helper.arrange(t, options1, async (url) => { + const response = await fetch(url + route) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + }) +}) + +test('dir list html format - extended info', async t => { + t.plan(2) + + const route = '/public/' + + const options = { + root: path.join(__dirname, '/static'), + prefix: '/public', + index: false, + list: { + format: 'html', + extendedFolderInfo: true, + render (dirs) { + test('dirs', t => { + t.plan(dirs.length * 7) + + for (const value of dirs) { + t.assert.ok(value.extendedInfo) + + t.assert.deepStrictEqual(typeof value.extendedInfo.fileCount, 'number') + t.assert.deepStrictEqual(typeof value.extendedInfo.totalFileCount, 'number') + t.assert.deepStrictEqual(typeof value.extendedInfo.folderCount, 'number') + t.assert.deepStrictEqual(typeof value.extendedInfo.totalFolderCount, 'number') + t.assert.deepStrictEqual(typeof value.extendedInfo.totalSize, 'number') + t.assert.deepStrictEqual(typeof value.extendedInfo.lastModified, 'number') + } + }) + } + } + } + + await helper.arrange(t, options, async (url) => { + const response = await fetch(url + route) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + }) +}) + +test('dir list json format', async t => { + t.plan(1) + + const options = { + root: path.join(__dirname, '/static'), + prefix: '/public', + prefixAvoidTrailingSlash: true, + list: { + format: 'json', + names: ['index', 'index.json', '/'] + } + } + const routes = ['/public/shallow/'] + const content = { dirs: ['empty'], files: ['sample.jpg'] } + + await helper.arrange(t, options, async (url) => { + for (const route of routes) { + await t.test(route, async t => { + t.plan(3) + + const response = await fetch(url + route) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.json(), content) + }) + } + }) +}) + +test('dir list json format - extended info', async t => { + t.plan(1) + + const options = { + root: path.join(__dirname, '/static'), + prefix: '/public', + prefixAvoidTrailingSlash: true, + list: { + format: 'json', + names: ['index', 'index.json', '/'], + extendedFolderInfo: true, + jsonFormat: 'extended' + + } + } + const routes = ['/public/shallow/'] + + await helper.arrange(t, options, async (url) => { + for (const route of routes) { + await t.test(route, async t => { + t.plan(5) + + const response = await fetch(url + route) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + const responseContent = await response.json() + t.assert.deepStrictEqual(responseContent.dirs[0].name, 'empty') + t.assert.deepStrictEqual(typeof responseContent.dirs[0].stats.atimeMs, 'number') + t.assert.deepStrictEqual(typeof responseContent.dirs[0].extendedInfo.totalSize, 'number') + }) + } + }) +}) + +test('json format with url parameter format', async t => { + t.plan(12) + + const options = { + root: path.join(__dirname, '/static'), + prefix: '/public', + index: false, + list: { + format: 'json', + render () { + return 'html' + } + } + } + const route = '/public/' + const jsonContent = { dirs: ['deep', 'shallow'], files: ['.example', '100%.txt', 'a .md', 'foo.html', 'foobar.html', 'index.css', 'index.html'] } + + await helper.arrange(t, options, async (url) => { + const response = await fetch(url + route) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.json(), jsonContent) + t.assert.ok(response.headers.get('content-type').includes('application/json')) + + const response2 = await fetch(url + route + '?format=html') + t.assert.ok(response2.ok) + t.assert.deepStrictEqual(response2.status, 200) + t.assert.deepStrictEqual(await response2.text(), 'html') + t.assert.ok(response2.headers.get('content-type').includes('text/html')) + + const response3 = await fetch(url + route + '?format=json') + t.assert.ok(response3.ok) + t.assert.deepStrictEqual(response3.status, 200) + t.assert.deepStrictEqual(await response3.json(), jsonContent) + t.assert.ok(response3.headers.get('content-type').includes('application/json')) + }) +}) + +test('json format with url parameter format and without render option', async t => { + t.plan(11) + + const options = { + root: path.join(__dirname, '/static'), + prefix: '/public', + index: false, + list: { + format: 'json' + } + } + const route = '/public/' + const jsonContent = { dirs: ['deep', 'shallow'], files: ['.example', '100%.txt', 'a .md', 'foo.html', 'foobar.html', 'index.css', 'index.html'] } + + await helper.arrange(t, options, async (url) => { + const response = await fetch(url + route) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.json(), jsonContent) + t.assert.ok(response.headers.get('content-type').includes('application/json')) + + const response2 = await fetch(url + route + '?format=html') + t.assert.ok(!response2.ok) + t.assert.deepStrictEqual(response2.status, 500) + t.assert.deepStrictEqual((await response2.json()).message, 'The `list.render` option must be a function and is required with the URL parameter `format=html`') + + const response3 = await fetch(url + route + '?format=json') + t.assert.ok(response3.ok) + t.assert.deepStrictEqual(response3.status, 200) + t.assert.deepStrictEqual(await response3.json(), jsonContent) + t.assert.ok(response3.headers.get('content-type').includes('application/json')) + }) +}) + +test('html format with url parameter format', async t => { + t.plan(12) + + const options = { + root: path.join(__dirname, '/static'), + prefix: '/public', + index: false, + list: { + format: 'html', + render () { + return 'html' + } + } + } + const route = '/public/' + const jsonContent = { dirs: ['deep', 'shallow'], files: ['.example', '100%.txt', 'a .md', 'foo.html', 'foobar.html', 'index.css', 'index.html'] } + + await helper.arrange(t, options, async (url) => { + const response = await fetch(url + route) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), 'html') + t.assert.ok(response.headers.get('content-type').includes('text/html')) + + const response2 = await fetch(url + route + '?format=html') + t.assert.ok(response2.ok) + t.assert.deepStrictEqual(response2.status, 200) + t.assert.deepStrictEqual(await response2.text(), 'html') + t.assert.ok(response2.headers.get('content-type').includes('text/html')) + + const response3 = await fetch(url + route + '?format=json') + t.assert.ok(response3.ok) + t.assert.deepStrictEqual(response3.status, 200) + t.assert.deepStrictEqual(await response3.json(), jsonContent) + t.assert.ok(response3.headers.get('content-type').includes('application/json')) + }) +}) + +test('dir list on empty dir', async t => { + t.plan(1) + + const options = { + root: path.join(__dirname, '/static'), + prefix: '/public', + list: true + } + const route = '/public/shallow/empty' + const content = { dirs: [], files: [] } + + await helper.arrange(t, options, async (url) => { + await t.test(route, async t => { + t.plan(3) + + const response = await fetch(url + route) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.json(), content) + }) + }) +}) + +test('dir list serve index.html on index option', async t => { + t.plan(1) + + const options = { + root: path.join(__dirname, '/static'), + prefix: '/public', + index: false, + list: { + format: 'html', + names: ['index', 'index.html'], + render: () => 'dir list index' + } + } + + await helper.arrange(t, options, async (url) => { + await t.test('serve index.html from fs', async t => { + t.plan(6) + + const response = await fetch(url + '/public/index.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), '\n \n the body\n \n\n') + + const response2 = await fetch(url + '/public/index') + t.assert.ok(response2.ok) + t.assert.deepStrictEqual(response2.status, 200) + t.assert.deepStrictEqual(await response2.text(), 'dir list index') + }) + }) +}) + +test('serve a non existent dir and get error', async t => { + t.plan(1) + + const options = { + root: '/none', + prefix: '/public', + list: true + } + const route = '/public/' + + await helper.arrange(t, options, async (url) => { + await t.test(route, async t => { + t.plan(2) + + const response = await fetch(url + route) + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + }) + }) +}) + +test('serve a non existent dir and get error', async t => { + t.plan(1) + + const options = { + root: path.join(__dirname, '/static'), + prefix: '/public', + list: { + names: ['index'] + } + } + const route = '/public/none/index' + + await helper.arrange(t, options, async (url) => { + await t.test(route, async t => { + t.plan(2) + + const response = await fetch(url + route) + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + }) + }) +}) + +test('dir list with dotfiles allow option', async t => { + t.plan(1) + + const options = { + root: path.join(__dirname, '/static-dotfiles'), + prefix: '/public', + dotfiles: 'allow', + index: false, + list: true + } + const route = '/public/' + const content = { dirs: ['dir'], files: ['.aaa', 'test.txt'] } + + await helper.arrange(t, options, async (url) => { + await t.test(route, async t => { + t.plan(3) + + const response = await fetch(url + route) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.json(), content) + }) + }) +}) + +test('dir list with dotfiles deny option', async t => { + t.plan(1) + + const options = { + root: path.join(__dirname, '/static-dotfiles'), + prefix: '/public', + dotfiles: 'deny', + index: false, + list: true + } + const route = '/public/' + const content = { dirs: ['dir'], files: ['test.txt'] } + + await helper.arrange(t, options, async (url) => { + await t.test(route, async t => { + t.plan(3) + + const response = await fetch(url + route) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.json(), content) + }) + }) +}) + +test('dir list with dotfiles ignore option', async t => { + t.plan(1) + + const options = { + root: path.join(__dirname, '/static-dotfiles'), + prefix: '/public', + dotfiles: 'ignore', + index: false, + list: true + } + const route = '/public/' + const content = { dirs: ['dir'], files: ['test.txt'] } + + await helper.arrange(t, options, async (url) => { + await t.test(route, async t => { + t.plan(3) + + const response = await fetch(url + route) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.json(), content) + }) + }) +}) + +test('dir list error', async t => { + t.plan(6) + + const options = { + root: path.join(__dirname, '/static'), + prefix: '/public', + prefixAvoidTrailingSlash: true, + index: false, + list: { + format: 'html', + names: ['index', 'index.htm'], + render: () => '' + } + } + + const errorMessage = 'mocking send' + dirList.send = async () => { throw new Error(errorMessage) } + + t.beforeEach((ctx) => { + ctx.initialDirList = ctx['../lib/dirList.js'] + ctx['../lib/dirList.js'] = dirList + }) + + t.afterEach((ctx) => { + ctx['../lib/dirList.js'] = ctx.initialDirList + }) + + const routes = ['/public/', '/public/index.htm'] + + await helper.arrange(t, options, async (url) => { + for (const route of routes) { + const response = await fetch(url + route) + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 500) + t.assert.deepStrictEqual((await response.json()).message, errorMessage) + } + }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-dotfiles/.aaa b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-dotfiles/.aaa new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-dotfiles/dir/index.html b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-dotfiles/dir/index.html new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-dotfiles/test.txt b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-dotfiles/test.txt new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-encode/[...]/a .md b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-encode/[...]/a .md new file mode 100644 index 0000000000000000000000000000000000000000..96236f8158b12701d5e75c14fb876c4a0f31b963 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-encode/[...]/a .md @@ -0,0 +1 @@ +example \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-filtered/bar.private b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-filtered/bar.private new file mode 100644 index 0000000000000000000000000000000000000000..5716ca5987cbf97d6bb54920bea6adde242d87e6 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-filtered/bar.private @@ -0,0 +1 @@ +bar diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-filtered/deep/path/to/baz.html b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-filtered/deep/path/to/baz.html new file mode 100644 index 0000000000000000000000000000000000000000..bd2a31ffd3da0a6bb4165f563169b76b273a2e7b --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-filtered/deep/path/to/baz.html @@ -0,0 +1,3 @@ + + baz + diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-filtered/deep/path/to/baz.private b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-filtered/deep/path/to/baz.private new file mode 100644 index 0000000000000000000000000000000000000000..76018072e09c5d31c8c6e3113b8aa0fe625195ca --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-filtered/deep/path/to/baz.private @@ -0,0 +1 @@ +baz diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-filtered/index.html b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-filtered/index.html new file mode 100644 index 0000000000000000000000000000000000000000..e3b8da08481c7025e626016a2d0a00e9f2623e25 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-filtered/index.html @@ -0,0 +1,3 @@ + + index2 + diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-hidden/.hidden/sample.json b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-hidden/.hidden/sample.json new file mode 100644 index 0000000000000000000000000000000000000000..56c8e280338ea64e1ab62ef9bacdf02840a0dabb --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-hidden/.hidden/sample.json @@ -0,0 +1 @@ +{"hello": "world"} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/all-three.html b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/all-three.html new file mode 100644 index 0000000000000000000000000000000000000000..1b0b72f02fe433adb972fde358d316866365eef5 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/all-three.html @@ -0,0 +1,5 @@ + + + the body + + diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/all-three.html.br b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/all-three.html.br new file mode 100644 index 0000000000000000000000000000000000000000..4d2fc468bee50c97ed0cb1421d82139afbc44d10 Binary files /dev/null and b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/all-three.html.br differ diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/all-three.html.gz b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/all-three.html.gz new file mode 100644 index 0000000000000000000000000000000000000000..cf99c2efafb755e14450c384feddf9e6263a8bd3 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/all-three.html.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:72feb49246468ab657e29bf6244a32b7eb40b52a9162e46d586a3096497a5ce7 +size 76 diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/baz.json b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/baz.json new file mode 100644 index 0000000000000000000000000000000000000000..871e874c25101ffc595d9bee4dd908261d285f90 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/baz.json @@ -0,0 +1,3 @@ +{ + "baz": "baz" +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/dir-gz/index.html b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/dir-gz/index.html new file mode 100644 index 0000000000000000000000000000000000000000..8551365650119cd0cd3c30867546290d39f9449a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/dir-gz/index.html @@ -0,0 +1,5 @@ + + + dir-gz index + + diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/dir-gz/index.html.gz b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/dir-gz/index.html.gz new file mode 100644 index 0000000000000000000000000000000000000000..ee125f502620c2a2475c4a82b8696db0129d3f4a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/dir-gz/index.html.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fa72aebf1b02042b36fc0e577fb415f90f03008efd444053e6f45b169d9291d9 +size 69 diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/dir/index.html b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/dir/index.html new file mode 100644 index 0000000000000000000000000000000000000000..671d084dee34d4ded75deacf01abe21ece3b725b --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/dir/index.html @@ -0,0 +1,5 @@ + + + dir index + + diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/dir/index.html.br b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/dir/index.html.br new file mode 100644 index 0000000000000000000000000000000000000000..8ae99efcb35996bf1c7840895247d5b49720d19c Binary files /dev/null and b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/dir/index.html.br differ diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/empty/.gitkeep b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/empty/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/gzip-only.html b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/gzip-only.html new file mode 100644 index 0000000000000000000000000000000000000000..424329433de5692770306bca1817b08928b0e153 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/gzip-only.html @@ -0,0 +1,3 @@ + + foo + diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/gzip-only.html.gz b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/gzip-only.html.gz new file mode 100644 index 0000000000000000000000000000000000000000..fc0b07f18adc6a529c486106582aab52de16bf52 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/gzip-only.html.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1156a7fb587b9476f6276caf4075f05ad82797459550b4f517cb7eba28093577 +size 76 diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/index.html b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/index.html new file mode 100644 index 0000000000000000000000000000000000000000..4f5bf40dbb95e7eb582009493b1c21b871e68cbc --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/index.html @@ -0,0 +1,5 @@ + + + index + + diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/index.html.br b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/index.html.br new file mode 100644 index 0000000000000000000000000000000000000000..a3cdfb5848c451e39b86c615adff7ecd7b08dab3 Binary files /dev/null and b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/index.html.br differ diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/sample.jpg b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/sample.jpg new file mode 100644 index 0000000000000000000000000000000000000000..f0c7c2ba02bbb5df2b0fedc3173b9a01633abe3e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/sample.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7c859e2f8ee6f21120d12a774038d0022dda0f44c37e4c7de34b07b7323b742c +size 43933 diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/sample.jpg.br b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/sample.jpg.br new file mode 100644 index 0000000000000000000000000000000000000000..4d25b0c293ed811be2595d045ffa5a0124c72d22 Binary files /dev/null and b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/sample.jpg.br differ diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/uncompressed.html b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/uncompressed.html new file mode 100644 index 0000000000000000000000000000000000000000..d53979c2599ff126adc38527409dc96784dc9c5f --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/uncompressed.html @@ -0,0 +1,3 @@ + + foobar + diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-symbolic-link/origin/subdir/subdir/index.html b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-symbolic-link/origin/subdir/subdir/index.html new file mode 100644 index 0000000000000000000000000000000000000000..fbd827cb75e54eeccec930bb1cceae858b1dfea5 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static-symbolic-link/origin/subdir/subdir/index.html @@ -0,0 +1,3 @@ + + index + diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static.test.js new file mode 100644 index 0000000000000000000000000000000000000000..1502016c09fb60df1240627ae8fd9242722960be --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static.test.js @@ -0,0 +1,3745 @@ +'use strict' + +/* eslint n/no-deprecated-api: "off" */ + +const path = require('node:path') +const fs = require('node:fs') +const url = require('node:url') +const http = require('node:http') +const { test } = require('node:test') +const Fastify = require('fastify') +const compress = require('@fastify/compress') +const concat = require('concat-stream') +const pino = require('pino') +const proxyquire = require('proxyquire') + +const fastifyStatic = require('../') + +const indexContent = fs + .readFileSync('./test/static/index.html') + .toString('utf8') +const index2Content = fs + .readFileSync('./test/static2/index.html') + .toString('utf8') +const foobarContent = fs + .readFileSync('./test/static/foobar.html') + .toString('utf8') +const deepContent = fs + .readFileSync('./test/static/deep/path/for/test/purpose/foo.html') + .toString('utf8') +const innerIndex = fs + .readFileSync('./test/static/deep/path/for/test/index.html') + .toString('utf8') +const allThreeBr = fs.readFileSync( + './test/static-pre-compressed/all-three.html.br' +) +const allThreeGzip = fs.readFileSync( + './test/static-pre-compressed/all-three.html.gz' +) +const gzipOnly = fs.readFileSync( + './test/static-pre-compressed/gzip-only.html.gz' +) +const indexBr = fs.readFileSync( + './test/static-pre-compressed/index.html.br' +) +const dirIndexBr = fs.readFileSync( + './test/static-pre-compressed/dir/index.html.br' +) +const dirIndexGz = fs.readFileSync( + './test/static-pre-compressed/dir-gz/index.html.gz' +) +const uncompressedStatic = fs + .readFileSync('./test/static-pre-compressed/uncompressed.html') + .toString('utf8') +const fooContent = fs.readFileSync('./test/static/foo.html').toString('utf8') +const barContent = fs.readFileSync('./test/static2/bar.html').toString('utf8') +const jsonHiddenContent = fs.readFileSync('./test/static-hidden/.hidden/sample.json').toString('utf8') + +const GENERIC_RESPONSE_CHECK_COUNT = 5 +function genericResponseChecks (t, response) { + t.assert.ok(/text\/(html|css)/.test(response.headers.get?.('content-type') ?? response.headers['content-type'])) + t.assert.ok(response.headers.get?.('etag') ?? response.headers.etag) + t.assert.ok(response.headers.get?.('last-modified') ?? response.headers['last-modified']) + t.assert.ok(response.headers.get?.('date') ?? response.headers.date) + t.assert.ok(response.headers.get?.('cache-control') ?? response.headers['cache-control']) +} + +const GENERIC_ERROR_RESPONSE_CHECK_COUNT = 2 +function genericErrorResponseChecks (t, response) { + t.assert.deepStrictEqual(response.headers.get?.('content-type') ?? response.headers['content-type'], 'application/json; charset=utf-8') + t.assert.ok(response.headers.get?.('date') ?? response.headers.date) +} + +if (typeof Promise.withResolvers === 'undefined') { + Promise.withResolvers = function () { + let promiseResolve, promiseReject + const promise = new Promise((resolve, reject) => { + promiseResolve = resolve + promiseReject = reject + }) + return { promise, resolve: promiseResolve, reject: promiseReject } + } +} + +test('register /static prefixAvoidTrailingSlash', async t => { + t.plan(11) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + prefix: '/static', + prefixAvoidTrailingSlash: true + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + await t.test('/static/index.html', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/index.html') + + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + + genericResponseChecks(t, response) + }) + + await t.test('/static/index.css', async (t) => { + t.plan(2 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/index.css') + + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + genericResponseChecks(t, response) + }) + + await t.test('/static/', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) + + await t.test('/static', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) + + await t.test('/static/deep/path/for/test/purpose/foo.html', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/deep/path/for/test/purpose/foo.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), deepContent) + genericResponseChecks(t, response) + }) + + await t.test('/static/deep/path/for/test/', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/deep/path/for/test/') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), innerIndex) + genericResponseChecks(t, response) + }) + + await t.test('/static/this/path/for/test', async (t) => { + t.plan(2 + GENERIC_ERROR_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/this/path/for/test') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + genericErrorResponseChecks(t, response) + }) + + await t.test('/static/this/path/doesnt/exist.html', async (t) => { + t.plan(2 + GENERIC_ERROR_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/this/path/doesnt/exist.html') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + genericErrorResponseChecks(t, response) + }) + + await t.test('/static/../index.js', async (t) => { + t.plan(2 + GENERIC_ERROR_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/../index.js') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + genericErrorResponseChecks(t, response) + }) + + await t.test('file not exposed outside of the plugin', async (t) => { + t.plan(2) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/foobar.html') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + }) + + await t.test('file retrieve with HEAD method', async t => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/index.html', { + method: 'HEAD' + }) + + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), '') + genericResponseChecks(t, response) + }) +}) + +test('register /static', async (t) => { + t.plan(10) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + prefix: '/static' + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + await t.test('/static/index.html', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/index.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) + + await t.test('/static/index.css', async (t) => { + t.plan(2 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/index.css') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + genericResponseChecks(t, response) + }) + + await t.test('/static/', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) + + await t.test('/static', async (t) => { + t.plan(2) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + }) + + await t.test('/static/deep/path/for/test/purpose/foo.html', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/deep/path/for/test/purpose/foo.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), deepContent) + genericResponseChecks(t, response) + }) + + await t.test('/static/deep/path/for/test/', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/deep/path/for/test/') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), innerIndex) + genericResponseChecks(t, response) + }) + + await t.test('/static/this/path/for/test', async (t) => { + t.plan(2 + GENERIC_ERROR_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/this/path/for/test') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + genericErrorResponseChecks(t, response) + }) + + await t.test('/static/this/path/doesnt/exist.html', async (t) => { + t.plan(2 + GENERIC_ERROR_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/this/path/doesnt/exist.html') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + genericErrorResponseChecks(t, response) + }) + + await t.test('/static/../index.js', async (t) => { + t.plan(2 + GENERIC_ERROR_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/../index.js', { + redirect: 'error' + }) + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + genericErrorResponseChecks(t, response) + }) + + await t.test('file not exposed outside of the plugin', async (t) => { + t.plan(2) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/foobar.html') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + }) +}) + +test('register /static/', async t => { + t.plan(11) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + prefix: '/static/' + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + await t.test('/static/index.html', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/index.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) + + await t.test('/static/index.html', async t => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/index.html', { + method: 'HEAD' + }) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), '') + genericResponseChecks(t, response) + }) + + await t.test('/static/index.css', async (t) => { + t.plan(2 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/index.css') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + genericResponseChecks(t, response) + }) + + await t.test('/static/', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) + + await t.test('/static', async (t) => { + t.plan(2) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + }) + + await t.test('/static/deep/path/for/test/purpose/foo.html', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/deep/path/for/test/purpose/foo.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), deepContent) + genericResponseChecks(t, response) + }) + + await t.test('/static/deep/path/for/test/', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/deep/path/for/test/') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), innerIndex) + genericResponseChecks(t, response) + }) + + await t.test('/static/this/path/for/test', async (t) => { + t.plan(2 + GENERIC_ERROR_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/this/path/for/test') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + genericErrorResponseChecks(t, response) + }) + + await t.test('/static/this/path/doesnt/exist.html', async (t) => { + t.plan(2 + GENERIC_ERROR_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/this/path/doesnt/exist.html') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + genericErrorResponseChecks(t, response) + }) + + await t.test('/static/../index.js', async (t) => { + t.plan(2 + GENERIC_ERROR_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/../index.js') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + genericErrorResponseChecks(t, response) + }) + + await t.test('304', async t => { + t.plan(5 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/index.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + + const response2 = await fetch('http://localhost:' + fastify.server.address().port + '/static/index.html', { + headers: { + 'if-none-match': response.headers.get('etag') + }, + cache: 'no-cache' + }) + t.assert.ok(!response2.ok) + t.assert.deepStrictEqual(response2.status, 304) + }) +}) + +test('register /static and /static2', async (t) => { + t.plan(4) + + const pluginOptions = { + root: [path.join(__dirname, '/static'), path.join(__dirname, '/static2')], + prefix: '/static' + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + fastify.get('/foo', (_req, rep) => { + rep.sendFile('foo.html') + }) + + fastify.get('/bar', (_req, rep) => { + rep.sendFile('bar.html') + }) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + await t.test('/static/index.html', async (t) => { + t.plan(4 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/index.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + const responseText = await response.text() + t.assert.deepStrictEqual(responseText, indexContent) + t.assert.notDeepStrictEqual(responseText, index2Content) + genericResponseChecks(t, response) + }) + + await t.test('/static/bar.html', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/bar.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), barContent) + genericResponseChecks(t, response) + }) + + await t.test('sendFile foo.html', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/foo') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), fooContent) + genericResponseChecks(t, response) + }) + + await t.test('sendFile bar.html', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/bar') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), barContent) + genericResponseChecks(t, response) + }) +}) + +test('register /static with constraints', async (t) => { + t.plan(2) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + prefix: '/static', + constraints: { + version: '1.2.0' + } + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + fastify.server.unref() + + await t.test('example.com/static/index.html', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/index.html', { + headers: { + 'accept-version': '1.x' + } + }) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) + + await t.test('not-example.com/static/index.html', async (t) => { + t.plan(2 + GENERIC_ERROR_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/index.html', { + headers: { + 'accept-version': '2.x' + } + }) + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + genericErrorResponseChecks(t, response) + }) +}) + +test('payload.path is set', async (t) => { + t.plan(2) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + prefix: '/static/' + } + const fastify = Fastify() + let gotFilename + fastify.register(fastifyStatic, pluginOptions) + fastify.addHook('onSend', function (_req, _reply, payload, next) { + gotFilename = payload.path + next() + }) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + await t.test('/static/index.html', async (t) => { + t.plan(5 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/index.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + t.assert.deepStrictEqual(typeof gotFilename, 'string') + t.assert.deepStrictEqual(gotFilename, path.join(pluginOptions.root, 'index.html')) + genericResponseChecks(t, response) + }) + + await t.test('/static/this/path/doesnt/exist.html', async (t) => { + t.plan(3 + GENERIC_ERROR_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/this/path/doesnt/exist.html') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + t.assert.deepStrictEqual(typeof gotFilename, 'undefined') + genericErrorResponseChecks(t, response) + }) +}) + +test('error responses can be customized with fastify.setErrorHandler()', async t => { + t.plan(1) + + const pluginOptions = { + root: path.join(__dirname, '/static') + } + const fastify = Fastify() + + fastify.setErrorHandler(function errorHandler (err, _request, reply) { + reply.code(403).type('text/plain').send(`${err.statusCode} Custom error message`) + }) + + fastify.get('/index.js', (_, reply) => { + return reply.type('text/html').sendFile('foo.js') + }) + + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + await t.test('/../index.js', async t => { + t.plan(4) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/index.js') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 403) + t.assert.deepStrictEqual(response.headers.get('content-type'), 'text/plain') + t.assert.deepStrictEqual(await response.text(), '500 Custom error message') + }) +}) + +test('not found responses can be customized with fastify.setNotFoundHandler()', async t => { + t.plan(1) + + const pluginOptions = { + root: path.join(__dirname, '/static') + } + const fastify = Fastify() + + fastify.setNotFoundHandler(function notFoundHandler (request, reply) { + reply.code(404).type('text/plain').send(request.raw.url + ' Not Found') + }) + + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + await t.test('/path/does/not/exist.html', async t => { + t.plan(4) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/path/does/not/exist.html') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + t.assert.deepStrictEqual(response.headers.get('content-type'), 'text/plain') + t.assert.deepStrictEqual(await response.text(), '/path/does/not/exist.html Not Found') + }) +}) + +test('fastify.setNotFoundHandler() is called for dotfiles when send is configured to ignore dotfiles', async t => { + t.plan(1) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + send: { + dotfiles: 'ignore' + } + } + const fastify = Fastify() + + fastify.setNotFoundHandler(function notFoundHandler (request, reply) { + reply.code(404).type('text/plain').send(request.raw.url + ' Not Found') + }) + + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + // Requesting files with a leading dot doesn't follow the same code path as + // other 404 errors + await t.test('/path/does/not/.exist.html', async t => { + t.plan(4) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/path/does/not/.exist.html') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + t.assert.deepStrictEqual(response.headers.get('content-type'), 'text/plain') + t.assert.deepStrictEqual(await response.text(), '/path/does/not/.exist.html Not Found') + }) +}) + +test('serving disabled', async (t) => { + t.plan(2) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + prefix: '/static/', + serve: false + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + fastify.get('/foo/bar', (_request, reply) => { + reply.sendFile('index.html') + }) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + await t.test('/static/index.html not found', async (t) => { + t.plan(2) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/index.html') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + }) + + await t.test('/static/index.html via sendFile found', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/foo/bar') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) +}) + +test('sendFile', async (t) => { + t.plan(4) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + prefix: '/static' + } + const fastify = Fastify() + const maxAge = Math.round(Math.random() * 10) * 10000 + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + fastify.get('/foo/bar', function (_req, reply) { + reply.sendFile('/index.html') + }) + + fastify.get('/root/path/override/test', (_request, reply) => { + reply.sendFile( + '/foo.html', + path.join(__dirname, 'static', 'deep', 'path', 'for', 'test', 'purpose') + ) + }) + + fastify.get('/foo/bar/options/override/test', function (_req, reply) { + reply.sendFile('/index.html', { maxAge }) + }) + + await fastify.listen({ port: 0 }) + fastify.server.unref() + + await t.test('reply.sendFile()', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + const response = await fetch('http://localhost:' + fastify.server.address().port + '/foo/bar') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) + + await t.test('reply.sendFile() with rootPath', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/root/path/override/test') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), deepContent) + genericResponseChecks(t, response) + }) + + await t.test('reply.sendFile() again without root path', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/foo/bar') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) + + await t.test('reply.sendFile() with options', async (t) => { + t.plan(4 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/foo/bar/options/override/test') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + t.assert.deepStrictEqual(response.headers.get('cache-control'), `public, max-age=${maxAge / 1000}`) + genericResponseChecks(t, response) + }) +}) + +test('sendFile disabled', async (t) => { + t.plan(1) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + prefix: '/static', + decorateReply: false + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + fastify.get('/foo/bar', function (_req, reply) { + if (reply.sendFile === undefined) { + reply.send('pass') + } else { + reply.send('fail') + } + }) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + await t.test('reply.sendFile undefined', async (t) => { + t.plan(3) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/foo/bar') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), 'pass') + }) +}) + +test('allowedPath option - pathname', async (t) => { + t.plan(2) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + allowedPath: (pathName) => pathName !== '/foobar.html' + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + fastify.server.unref() + + await t.test('/foobar.html not found', async (t) => { + t.plan(2 + GENERIC_ERROR_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/foobar.html') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + genericErrorResponseChecks(t, response) + }) + + await t.test('/index.css found', async (t) => { + t.plan(2) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/index.css') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + }) +}) + +test('allowedPath option - request', async (t) => { + t.plan(2) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + allowedPath: (_pathName, _root, request) => request.query.key === 'temporaryKey' + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + await t.test('/foobar.html not found', async (t) => { + t.plan(2 + GENERIC_ERROR_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/foobar.html') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + genericErrorResponseChecks(t, response) + }) + + await t.test('/index.css found', async (t) => { + t.plan(2) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/index.css?key=temporaryKey') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + }) +}) + +test('download', async (t) => { + t.plan(6) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + prefix: '/static' + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + fastify.get('/foo/bar', function (_req, reply) { + reply.download('/index.html') + }) + + fastify.get('/foo/bar/change', function (_req, reply) { + reply.download('/index.html', 'hello-world.html') + }) + + fastify.get('/foo/bar/override', function (_req, reply) { + reply.download('/index.html', 'hello-world.html', { + maxAge: '2 hours', + immutable: true + }) + }) + + fastify.get('/foo/bar/override/2', function (_req, reply) { + reply.download('/index.html', { acceptRanges: false }) + }) + + fastify.get('/root/path/override/test', (_request, reply) => { + reply.download('/foo.html', { + root: path.join( + __dirname, + 'static', + 'deep', + 'path', + 'for', + 'test', + 'purpose' + ) + }) + }) + + fastify.get('/root/path/override/test/change', (_request, reply) => { + reply.download('/foo.html', 'hello-world.html', { + root: path.join( + __dirname, + 'static', + 'deep', + 'path', + 'for', + 'test', + 'purpose' + ) + }) + }) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + await t.test('reply.download()', async (t) => { + t.plan(4 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/foo/bar') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.headers.get('content-disposition'), 'attachment; filename="index.html"') + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) + + await t.test('reply.download() with fileName', async t => { + t.plan(4 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/foo/bar/change') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(response.headers.get('content-disposition'), 'attachment; filename="hello-world.html"') + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) + + await t.test('reply.download() with fileName - override', async (t) => { + t.plan(4 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/root/path/override/test') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(response.headers.get('content-disposition'), 'attachment; filename="foo.html"') + t.assert.deepStrictEqual(await response.text(), deepContent) + genericResponseChecks(t, response) + }) + + await t.test('reply.download() with custom opts', async (t) => { + t.plan(5 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/foo/bar/override') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(response.headers.get('content-disposition'), 'attachment; filename="hello-world.html"') + t.assert.deepStrictEqual(response.headers.get('cache-control'), 'public, max-age=7200, immutable') + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) + + await t.test('reply.download() with custom opts (2)', async (t) => { + t.plan(5 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/foo/bar/override/2') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(response.headers.get('content-disposition'), 'attachment; filename="index.html"') + t.assert.deepStrictEqual(response.headers.get('accept-ranges'), null) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) + + await t.test('reply.download() with rootPath and fileName', async (t) => { + t.plan(4 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/root/path/override/test/change') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(response.headers.get('content-disposition'), 'attachment; filename="hello-world.html"') + t.assert.deepStrictEqual(await response.text(), deepContent) + genericResponseChecks(t, response) + }) +}) + +test('download disabled', async (t) => { + t.plan(2) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + prefix: '/static', + decorateReply: false + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + fastify.get('/foo/bar', function (_req, reply) { + if (reply.download === undefined) { + t.assert.deepStrictEqual(reply.download, undefined) + reply.send('pass') + } else { + reply.send('fail') + } + }) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + await t.test('reply.sendFile undefined', async (t) => { + t.plan(3) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/foo/bar') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), 'pass') + }) +}) + +test('prefix default', (t) => { + t.plan(1) + const pluginOptions = { root: path.join(__dirname, 'static') } + const fastify = Fastify({ logger: false }) + t.assert.doesNotThrow(() => fastify.register(fastifyStatic, pluginOptions)) +}) + +test('root not found warning', async (t) => { + t.plan(1) + const rootPath = path.join(__dirname, 'does-not-exist') + const pluginOptions = { root: rootPath } + const destination = concat((data) => { + t.assert.deepStrictEqual(JSON.parse(data).msg, `"root" path "${rootPath}" must exist`) + }) + const loggerInstance = pino( + { + level: 'warn' + }, + destination + ) + const fastify = Fastify({ loggerInstance }) + fastify.register(fastifyStatic, pluginOptions) + + await fastify.listen({ port: 0 }) + fastify.server.unref() + destination.end() +}) + +test('send options', (t) => { + t.plan(12) + const pluginOptions = { + root: path.join(__dirname, '/static'), + acceptRanges: 'acceptRanges', + contentType: 'contentType', + cacheControl: 'cacheControl', + dotfiles: 'dotfiles', + etag: 'etag', + extensions: 'extensions', + immutable: 'immutable', + index: 'index', + lastModified: 'lastModified', + maxAge: 'maxAge' + } + const fastify = Fastify({ logger: false }) + const { resolve, promise } = Promise.withResolvers() + const fastifyStatic = require('proxyquire')('../', { + '@fastify/send': function sendStub (_req, pathName, options) { + t.assert.deepStrictEqual(pathName, '/index.html') + t.assert.deepStrictEqual(options.root, path.join(__dirname, '/static')) + t.assert.deepStrictEqual(options.acceptRanges, 'acceptRanges') + t.assert.deepStrictEqual(options.contentType, 'contentType') + t.assert.deepStrictEqual(options.cacheControl, 'cacheControl') + t.assert.deepStrictEqual(options.dotfiles, 'dotfiles') + t.assert.deepStrictEqual(options.etag, 'etag') + t.assert.deepStrictEqual(options.extensions, 'extensions') + t.assert.deepStrictEqual(options.immutable, 'immutable') + t.assert.deepStrictEqual(options.index, 'index') + t.assert.deepStrictEqual(options.lastModified, 'lastModified') + t.assert.deepStrictEqual(options.maxAge, 'maxAge') + resolve() + return { on: () => { }, pipe: () => { } } + } + }) + fastify.register(fastifyStatic, pluginOptions) + fastify.inject({ url: '/index.html' }) + + return promise +}) + +test('setHeaders option', async (t) => { + t.plan(5 + GENERIC_RESPONSE_CHECK_COUNT) + + const pluginOptions = { + root: path.join(__dirname, 'static'), + setHeaders: function (res, pathName) { + t.assert.deepStrictEqual(pathName, path.join(__dirname, 'static/index.html')) + res.setHeader('X-Test-Header', 'test') + } + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/index.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(response.headers.get('x-test-header'), 'test') + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) +}) + +test('maxAge option', async (t) => { + t.plan(4 + GENERIC_RESPONSE_CHECK_COUNT) + + const pluginOptions = { + root: path.join(__dirname, 'static'), + maxAge: 3600000 + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + fastify.server.unref() + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/index.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(response.headers.get('cache-control'), 'public, max-age=3600') + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) +}) + +test('errors', async (t) => { + t.plan(11) + + await t.test('no root', async (t) => { + t.plan(1) + const pluginOptions = {} + const fastify = Fastify({ logger: false }) + await t.assert.rejects(async () => await fastify.register(fastifyStatic, pluginOptions)) + }) + + await t.test('root is not a string', async (t) => { + t.plan(1) + const pluginOptions = { root: 42 } + const fastify = Fastify({ logger: false }) + await t.assert.rejects(async () => await fastify.register(fastifyStatic, pluginOptions)) + }) + + await t.test('root is not an absolute path', async (t) => { + t.plan(1) + const pluginOptions = { root: './my/path' } + const fastify = Fastify({ logger: false }) + await t.assert.rejects(async () => await fastify.register(fastifyStatic, pluginOptions)) + }) + + await t.test('root is not a directory', async (t) => { + t.plan(1) + const pluginOptions = { root: __filename } + const fastify = Fastify({ logger: false }) + await t.assert.rejects(async () => await fastify.register(fastifyStatic, pluginOptions)) + }) + + await t.test('root is an empty array', async (t) => { + t.plan(1) + const pluginOptions = { root: [] } + const fastify = Fastify({ logger: false }) + await t.assert.rejects(async () => await fastify.register(fastifyStatic, pluginOptions)) + }) + + await t.test('root array does not contain strings', async (t) => { + t.plan(1) + const pluginOptions = { root: [1] } + const fastify = Fastify({ logger: false }) + await t.assert.rejects(async () => await fastify.register(fastifyStatic, pluginOptions)) + }) + + await t.test('root array does not contain an absolute path', async (t) => { + t.plan(1) + const pluginOptions = { root: ['./my/path'] } + const fastify = Fastify({ logger: false }) + await t.assert.rejects(async () => await fastify.register(fastifyStatic, pluginOptions)) + }) + + await t.test('root array path is not a directory', async (t) => { + t.plan(1) + const pluginOptions = { root: [__filename] } + const fastify = Fastify({ logger: false }) + await t.assert.rejects(async () => await fastify.register(fastifyStatic, pluginOptions)) + }) + + await t.test('all root array paths must be valid', async (t) => { + t.plan(1) + const pluginOptions = { root: [path.join(__dirname, '/static'), 1] } + const fastify = Fastify({ logger: false }) + await t.assert.rejects(async () => await fastify.register(fastifyStatic, pluginOptions)) + }) + + await t.test('duplicate root paths are not allowed', async (t) => { + t.plan(1) + const pluginOptions = { + root: [path.join(__dirname, '/static'), path.join(__dirname, '/static')] + } + const fastify = Fastify({ logger: false }) + await t.assert.rejects(async () => await fastify.register(fastifyStatic, pluginOptions)) + }) + + await t.test('setHeaders is not a function', async (t) => { + t.plan(1) + const pluginOptions = { root: __dirname, setHeaders: 'headers' } + const fastify = Fastify({ logger: false }) + await t.assert.rejects(async () => await fastify.register(fastifyStatic, pluginOptions)) + }) +}) + +test('register no prefix', async (t) => { + t.plan(7) + + const pluginOptions = { + root: path.join(__dirname, '/static') + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + fastify.get('/', (_request, reply) => { + reply.send({ hello: 'world' }) + }) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + await t.test('/index.html', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/index.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) + + await t.test('/index.css', async (t) => { + t.plan(2 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/index.css') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + genericResponseChecks(t, response) + }) + + await t.test('/', async (t) => { + t.plan(3) + + const response = await fetch('http://localhost:' + fastify.server.address().port) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.json(), { hello: 'world' }) + }) + + await t.test('/deep/path/for/test/purpose/foo.html', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/deep/path/for/test/purpose/foo.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), deepContent) + genericResponseChecks(t, response) + }) + + await t.test('/deep/path/for/test/', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/deep/path/for/test/') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), innerIndex) + genericResponseChecks(t, response) + }) + + await t.test('/this/path/doesnt/exist.html', async (t) => { + t.plan(2 + GENERIC_ERROR_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/this/path/doesnt/exist.html') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + genericErrorResponseChecks(t, response) + }) + + await t.test('/../index.js', async (t) => { + t.plan(2 + GENERIC_ERROR_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/../index.js') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + genericErrorResponseChecks(t, response) + }) +}) + +test('with fastify-compress', async t => { + t.plan(2) + + const pluginOptions = { + root: path.join(__dirname, '/static') + } + const fastify = Fastify() + fastify.register(compress, { threshold: 0 }) + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + await t.test('deflate', async function (t) { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/index.html', { + headers: { + 'accept-encoding': ['deflate'] + } + }) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(response.headers.get('content-encoding'), 'deflate') + genericResponseChecks(t, response) + }) + + await t.test('gzip', async function (t) { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/index.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(response.headers.get('content-encoding'), 'gzip') + genericResponseChecks(t, response) + }) +}) +test('register /static/ with schemaHide true', async t => { + t.plan(2) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + prefix: '/static/', + schemaHide: true + } + + const fastify = Fastify() + + fastify.addHook('onRoute', function (routeOptions) { + t.assert.deepStrictEqual(routeOptions.schema, { hide: true }) + }) + + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + await t.test('/static/index.html', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/index.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(response.headers.get('content-type'), 'text/html; charset=utf-8') + genericResponseChecks(t, response) + }) +}) + +test('register /static/ with schemaHide false', async t => { + t.plan(2) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + prefix: '/static/', + schemaHide: false + } + + const fastify = Fastify() + + fastify.addHook('onRoute', function (routeOptions) { + t.assert.deepStrictEqual(routeOptions.schema, { hide: false }) + }) + + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + await t.test('/static/index.html', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/index.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(response.headers.get('content-type'), 'text/html; charset=utf-8') + genericResponseChecks(t, response) + }) +}) + +test('register /static/ without schemaHide', async t => { + t.plan(2) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + prefix: '/static/' + } + + const fastify = Fastify() + + fastify.addHook('onRoute', function (routeOptions) { + t.assert.deepStrictEqual(routeOptions.schema, { hide: true }) + }) + + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + await t.test('/static/index.html', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/index.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(response.headers.get('content-type'), 'text/html; charset=utf-8') + genericResponseChecks(t, response) + }) +}) + +test('fastify with exposeHeadRoutes', async t => { + t.plan(1) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + wildcard: false + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + await t.test('/index.html', async t => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/index.html', { method: 'HEAD' }) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), '') + genericResponseChecks(t, response) + }) +}) + +test('register with wildcard false', async t => { + t.plan(8) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + wildcard: false + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + fastify.get('/*', (_request, reply) => { + reply.send({ hello: 'world' }) + }) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + await t.test('/index.html', async t => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/index.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) + + await t.test('/index.css', async (t) => { + t.plan(2 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/index.css') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + genericResponseChecks(t, response) + }) + + await t.test('/', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) + + await t.test('/not-defined', async (t) => { + t.plan(3) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/not-defined') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.json(), { hello: 'world' }) + }) + + await t.test('/deep/path/for/test/purpose/foo.html', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/deep/path/for/test/purpose/foo.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), deepContent) + genericResponseChecks(t, response) + }) + + await t.test('/deep/path/for/test/', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/deep/path/for/test/') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), innerIndex) + genericResponseChecks(t, response) + }) + + await t.test('/../index.js', async (t) => { + t.plan(3) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/../index.js') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.json(), { hello: 'world' }) + }) + + await t.test('/index.css', async t => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/index.css') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), '') + genericResponseChecks(t, response) + }) +}) + +test('register with wildcard false (trailing slash in the root)', async t => { + t.plan(5) + + const pluginOptions = { + root: path.join(__dirname, '/static/'), + prefix: '/assets/', + index: false, + wildcard: false + } + const fastify = Fastify({ + ignoreTrailingSlash: true + }) + fastify.register(fastifyStatic, pluginOptions) + + fastify.get('/*', (_request, reply) => { + reply.send({ hello: 'world' }) + }) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + await t.test('/index.css', async (t) => { + t.plan(2 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/assets/index.css') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + genericResponseChecks(t, response) + }) + + await t.test('/not-defined', async (t) => { + t.plan(3) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/assets/not-defined') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.json(), { hello: 'world' }) + }) + + await t.test('/deep/path/for/test/purpose/foo.html', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/assets/deep/path/for/test/purpose/foo.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), deepContent) + genericResponseChecks(t, response) + }) + + await t.test('/../index.js', async (t) => { + t.plan(3) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/assets/../index.js') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.json(), { hello: 'world' }) + }) + + await t.test('/index.css', async t => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/assets/index.css') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), '') + genericResponseChecks(t, response) + }) +}) + +test('register with wildcard string', async (t) => { + t.plan(1) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + wildcard: '**/index.html' + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + fastify.get('/*', (_request, reply) => { + reply.send({ hello: 'world' }) + }) + + await t.assert.rejects(fastify.ready()) +}) + +test('register with wildcard string on multiple root paths', async (t) => { + t.plan(1) + + const pluginOptions = { + root: [path.join(__dirname, '/static'), path.join(__dirname, '/static2')], + wildcard: '**/*.js' + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + fastify.get('/*', (_request, reply) => { + reply.send({ hello: 'world' }) + }) + + t.after(() => fastify.close()) + + await t.assert.rejects(fastify.listen({ port: 0 })) +}) + +test('register with wildcard false and alternative index', async t => { + t.plan(10) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + wildcard: false, + index: ['foobar.html', 'foo.html', 'index.html'] + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + fastify.get('/*', (_request, reply) => { + reply.send({ hello: 'world' }) + }) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + await t.test('/index.html', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/index.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) + + await t.test('/index.html', async t => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/index.html', { method: 'HEAD' }) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), '') + genericResponseChecks(t, response) + }) + + await t.test('/index.css', async (t) => { + t.plan(2 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/index.css') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + genericResponseChecks(t, response) + }) + + await t.test('/?a=b', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), foobarContent) + genericResponseChecks(t, response) + }) + + await t.test('/?a=b', async t => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port, { + method: 'HEAD' + }) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), '') + genericResponseChecks(t, response) + }) + + await t.test('/not-defined', async (t) => { + t.plan(3) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/not-defined') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.json(), { hello: 'world' }) + }) + + await t.test('/deep/path/for/test/purpose/', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/deep/path/for/test/purpose/') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), deepContent) + genericResponseChecks(t, response) + }) + + await t.test('/deep/path/for/test/', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/deep/path/for/test/') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), innerIndex) + genericResponseChecks(t, response) + }) + + await t.test('/deep/path/for/test/', async t => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/deep/path/for/test/', { + method: 'HEAD' + }) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), '') + genericResponseChecks(t, response) + }) + + await t.test('/../index.js', async (t) => { + t.plan(3) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/../index.js') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.json(), { hello: 'world' }) + }) +}) + +test('register /static with wildcard false and alternative index', async t => { + t.plan(10) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + prefix: '/static', + wildcard: false, + index: ['foobar.html', 'foo.html', 'index.html'] + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + fastify.get('/*', (_request, reply) => { + reply.send({ hello: 'world' }) + }) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + await t.test('/static/index.html', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/index.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) + + await t.test('/static/index.html', async t => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/index.html', { + method: 'HEAD' + }) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), '') + genericResponseChecks(t, response) + }) + + await t.test('/static/index.css', async (t) => { + t.plan(2 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/index.css') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + genericResponseChecks(t, response) + }) + + await t.test('/static', (t) => { + t.plan(2) + + const { promise, resolve } = Promise.withResolvers() + + // simple-get doesn't tell us about redirects so use http.request directly + // to verify we do not get a redirect when not requested + const testurl = 'http://localhost:' + fastify.server.address().port + '/static' + const req = http.request(url.parse(testurl), res => { + t.assert.deepStrictEqual(res.statusCode, 200) + let body = '' + res.on('data', (chunk) => { + body += chunk.toString() + }) + res.on('end', () => { + t.assert.deepStrictEqual(JSON.parse(body.toString()), { hello: 'world' }) + resolve() + }) + }) + req.on('error', (err) => console.error(err)) + req.end() + + return promise + }) + + await t.test('/static/', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), foobarContent) + genericResponseChecks(t, response) + }) + + await t.test('/static/', async t => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/', { + method: 'HEAD' + }) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), '') + genericResponseChecks(t, response) + }) + + await t.test('/static/not-defined', async (t) => { + t.plan(3) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/not-defined') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.json(), { hello: 'world' }) + }) + + await t.test('/static/deep/path/for/test/purpose/', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/deep/path/for/test/purpose/') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), deepContent) + genericResponseChecks(t, response) + }) + + await t.test('/static/deep/path/for/test/', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/deep/path/for/test/') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), innerIndex) + genericResponseChecks(t, response) + }) + + await t.test('/static/../index.js', async (t) => { + t.plan(3) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/../index.js') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.json(), { hello: 'world' }) + }) +}) + +test('register /static with redirect true', async t => { + t.plan(6) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + prefix: '/static', + redirect: true, + index: 'index.html' + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + await t.test('/static?a=b', async (t) => { + t.plan(5 + GENERIC_RESPONSE_CHECK_COUNT) + + const { promise, resolve } = Promise.withResolvers() + + // simple-get doesn't tell us about redirects so use http.request directly + const testurl = 'http://localhost:' + fastify.server.address().port + '/static?a=b' + const req = http.request(url.parse(testurl), res => { + t.assert.deepStrictEqual(res.statusCode, 301) + t.assert.deepStrictEqual(res.headers.location, '/static/?a=b') + resolve() + }) + req.on('error', (err) => console.error(err)) + req.end() + + await promise + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static?a=b') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) + + await t.test('/static', t => { + t.plan(2) + + const { promise, resolve } = Promise.withResolvers() + + // simple-get doesn't tell us about redirects so use http.request directly + const testurl = 'http://localhost:' + fastify.server.address().port + '/static' + const req = http.request(url.parse(testurl), res => { + t.assert.deepStrictEqual(res.statusCode, 301) + t.assert.deepStrictEqual(res.headers.location, '/static/') + + resolve() + }) + req.on('error', err => console.error(err)) + req.end() + + return promise + }) + + await t.test('/static/', async t => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) + + await t.test('/static/deep', async (t) => { + t.plan(2 + GENERIC_ERROR_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/deep') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + genericErrorResponseChecks(t, response) + }) + + await t.test('/static/deep/path/for/test?a=b', async (t) => { + t.plan(5 + GENERIC_RESPONSE_CHECK_COUNT) + + const { promise, resolve } = Promise.withResolvers() + + // simple-get doesn't tell us about redirects so use http.request directly + const testurl = 'http://localhost:' + fastify.server.address().port + '/static/deep/path/for/test?a=b' + const req = http.request(url.parse(testurl), res => { + t.assert.deepStrictEqual(res.statusCode, 301) + t.assert.deepStrictEqual(res.headers.location, '/static/deep/path/for/test/?a=b') + resolve() + }) + req.on('error', (err) => console.error(err)) + req.end() + + await promise + + // verify the redirect with query parameters works + const response = await fetch(testurl) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), innerIndex) + genericResponseChecks(t, response) + }) + + await t.test('/static/deep/path/for/test', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/deep/path/for/test') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), innerIndex) + genericResponseChecks(t, response) + }) +}) + +test('register /static with redirect true and wildcard false', async t => { + t.plan(7) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + prefix: '/static', + redirect: true, + wildcard: false, + index: 'index.html' + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + await t.test('/static?a=b', async t => { + t.plan(5 + GENERIC_RESPONSE_CHECK_COUNT) + + const { promise, resolve } = Promise.withResolvers() + + // simple-get doesn't tell us about redirects so use http.request directly + const testurl = 'http://localhost:' + fastify.server.address().port + '/static?a=b' + const req = http.request(url.parse(testurl), res => { + t.assert.deepStrictEqual(res.statusCode, 301) + t.assert.deepStrictEqual(res.headers.location, '/static/?a=b') + resolve() + }) + req.on('error', err => console.error(err)) + req.end() + await promise + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static?a=b') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) + + await t.test('/static/?a=b', async t => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/?a=b') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) + + await t.test('/static/?a=b - HEAD', async t => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/?a=b', { method: 'HEAD' }) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), '') + genericResponseChecks(t, response) + }) + + await t.test('/static/deep', async t => { + t.plan(2 + GENERIC_ERROR_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/deep') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + genericErrorResponseChecks(t, response) + }) + + await t.test('/static/deep/path/for/test?a=b', async t => { + t.plan(5 + GENERIC_RESPONSE_CHECK_COUNT) + + const { promise, resolve } = Promise.withResolvers() + + // simple-get doesn't tell us about redirects so use http.request directly + const testurl = 'http://localhost:' + fastify.server.address().port + '/static/deep/path/for/test?a=b' + const req = http.request(url.parse(testurl), res => { + t.assert.deepStrictEqual(res.statusCode, 301) + t.assert.deepStrictEqual(res.headers.location, '/static/deep/path/for/test/?a=b') + resolve() + }) + req.on('error', err => console.error(err)) + req.end() + await promise + + const response = await fetch(testurl) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), innerIndex) + genericResponseChecks(t, response) + }) + + await t.test('/static/deep/path/for/test', async t => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/deep/path/for/test') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), innerIndex) + genericResponseChecks(t, response) + }) + + await t.test('/static/deep/path/for/test', async t => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/deep/path/for/test', { method: 'HEAD' }) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), '') + genericResponseChecks(t, response) + }) +}) + +test('trailing slash behavior with redirect = false', async (t) => { + t.plan(5) + + const fastify = Fastify() + fastify.register(fastifyStatic, { + root: path.join(__dirname, '/static'), + prefix: '/static', + redirect: false + }) + fastify.server.unref() + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + const host = 'http://localhost:' + fastify.server.address().port + + await t.test('prefix with no trailing slash => 404', async (t) => { + t.plan(2) + + const response = await fetch(host + '/static') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + }) + + await t.test('prefix with trailing trailing slash => 200', async (t) => { + t.plan(2) + + const response = await fetch(host + '/static/') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + }) + + await t.test('deep path with no index.html or trailing slash => 404', async (t) => { + t.plan(2) + + const response = await fetch(host + '/static/deep/path') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + }) + + await t.test('deep path with index.html but no trailing slash => 200', async (t) => { + t.plan(2) + + const response = await fetch(host + '/static/deep/path/for/test') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + }) + + await t.test('deep path with index.html and trailing slash => 200', async (t) => { + t.plan(2) + + const response = await fetch(host + '/static/deep/path/for/test/') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + }) +}) + +test('if dotfiles are properly served according to plugin options', async (t) => { + t.plan(3) + const exampleContents = fs + .readFileSync(path.join(__dirname, 'static', '.example'), { + encoding: 'utf8' + }) + .toString() + + await t.test('freely serve dotfiles', async (t) => { + t.plan(3) + const fastify = Fastify() + + const pluginOptions = { + root: path.join(__dirname, 'static'), + prefix: '/static/', + dotfiles: 'allow' + } + + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + fastify.server.unref() + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/.example') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), exampleContents) + }) + + await t.test('ignore dotfiles', async (t) => { + t.plan(2) + const fastify = Fastify() + + const pluginOptions = { + root: path.join(__dirname, 'static'), + prefix: '/static/', + dotfiles: 'ignore' + } + + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + fastify.server.unref() + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/.example') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + }) + + await t.test('deny requests to serve a dotfile', async (t) => { + t.plan(2) + const fastify = Fastify() + + const pluginOptions = { + root: path.join(__dirname, 'static'), + prefix: '/static/', + dotfiles: 'deny' + } + + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + await fastify.listen({ port: 0 }) + fastify.server.unref() + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/.example') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 403) + }) +}) + +test('register with failing glob handler', async (t) => { + const fastifyStatic = proxyquire.noCallThru()('../', { + glob: function globStub (_pattern, _options, cb) { + process.nextTick(function () { + return cb(new Error('mock glob error')) + }) + } + }) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + serve: true, + wildcard: false + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await t.assert.rejects(fastify.listen({ port: 0 })) +}) + +test( + 'register with rootpath that causes statSync to fail with non-ENOENT code', + async (t) => { + const fastifyStatic = proxyquire('../', { + 'node:fs': { + statSync: function statSyncStub () { + throw new Error({ code: 'MOCK' }) + } + } + }) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + wildcard: true + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await t.assert.rejects(fastify.listen({ port: 0 })) + } +) + +test('inject support', async (t) => { + const pluginOptions = { + root: path.join(__dirname, '/static'), + prefix: '/static' + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + t.after(() => fastify.close()) + + const response = await fastify.inject({ + method: 'GET', + url: '/static/index.html' + }) + t.assert.deepStrictEqual(response.statusCode, 200) + t.assert.deepStrictEqual(response.body.toString(), indexContent) +}) + +test('routes should use custom errorHandler premature stream close', async t => { + t.plan(2) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + prefix: '/static/' + } + + const fastify = Fastify() + + fastify.addHook('onRoute', function (routeOptions) { + t.assert.ok(routeOptions.errorHandler instanceof Function) + + routeOptions.onRequest = (_request, _reply, done) => { + const fakeError = new Error() + fakeError.code = 'ERR_STREAM_PREMATURE_CLOSE' + done(fakeError) + } + }) + + fastify.register(fastifyStatic, pluginOptions) + t.after(() => fastify.close()) + + await t.assert.rejects(fastify.inject({ method: 'GET', url: '/static/index.html' })) +}) + +test('routes should fallback to default errorHandler', async t => { + t.plan(3) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + prefix: '/static/' + } + + const fastify = Fastify() + + fastify.addHook('onRoute', function (routeOptions) { + t.assert.ok(routeOptions.errorHandler instanceof Function) + + routeOptions.preHandler = (_request, _reply, done) => { + const fakeError = new Error() + fakeError.code = 'SOMETHING_ELSE' + done(fakeError) + } + }) + + fastify.register(fastifyStatic, pluginOptions) + t.after(() => fastify.close()) + + const response = await fastify.inject({ method: 'GET', url: '/static/index.html' }) + t.assert.deepStrictEqual(response.statusCode, 500) + t.assert.deepStrictEqual(await response.json(), { + statusCode: 500, + code: 'SOMETHING_ELSE', + error: 'Internal Server Error', + message: '' + }) +}) + +test('percent encoded URLs in glob mode', async (t) => { + t.plan(3) + + const fastify = Fastify({}) + + fastify.register(fastifyStatic, { + root: path.join(__dirname, 'static'), + prefix: '/static', + wildcard: true + }) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + fastify.server.unref() + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/a .md') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual( + fs.readFileSync(path.join(__dirname, 'static', 'a .md'), 'utf-8'), + await response.text() + ) +}) + +test('register /static and /static2 without wildcard', async t => { + t.plan(2) + + const pluginOptions = { + root: [path.join(__dirname, '/static'), path.join(__dirname, '/static2')], + wildcard: false + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + fastify.server.unref() + + await t.test('/index.html', async t => { + t.plan(4 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/index.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + const responseContent = await response.text() + t.assert.notDeepStrictEqual(responseContent, index2Content) + t.assert.deepStrictEqual(responseContent, indexContent) + genericResponseChecks(t, response) + }) + + await t.test('/static/bar.html', async t => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/bar.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), barContent) + genericResponseChecks(t, response) + }) +}) + +test( + 'will serve pre-compressed files with .br at the highest priority', + async (t) => { + const pluginOptions = { + root: path.join(__dirname, '/static-pre-compressed'), + prefix: '/static-pre-compressed/', + preCompressed: true + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + t.after(() => fastify.close()) + + const response = await fastify.inject({ + method: 'GET', + url: '/static-pre-compressed/all-three.html', + headers: { + 'accept-encoding': 'gzip, deflate, br' + } + }) + + genericResponseChecks(t, response) + t.assert.deepStrictEqual(response.headers['content-encoding'], 'br') + t.assert.deepStrictEqual(response.statusCode, 200) + t.assert.deepStrictEqual(response.rawPayload, allThreeBr) + } +) + +test( + 'will serve pre-compressed files and fallback to .gz if .br is not on disk', + async (t) => { + const pluginOptions = { + root: path.join(__dirname, '/static-pre-compressed'), + prefix: '/static-pre-compressed/', + preCompressed: true + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + t.after(() => fastify.close()) + + const response = await fastify.inject({ + method: 'GET', + url: '/static-pre-compressed/gzip-only.html', + headers: { + 'accept-encoding': 'gzip, deflate, br' + } + }) + + genericResponseChecks(t, response) + t.assert.deepStrictEqual(response.headers['content-encoding'], 'gzip') + t.assert.deepStrictEqual(response.statusCode, 200) + t.assert.deepStrictEqual(response.rawPayload, gzipOnly) + } +) + +test( + 'will serve pre-compressed files with .gzip if * directive used', + async (t) => { + const pluginOptions = { + root: path.join(__dirname, '/static-pre-compressed'), + prefix: '/static-pre-compressed/', + preCompressed: true + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + t.after(() => fastify.close()) + + const response = await fastify.inject({ + method: 'GET', + url: '/static-pre-compressed/all-three.html', + headers: { + 'accept-encoding': '*' + } + }) + + genericResponseChecks(t, response) + t.assert.deepStrictEqual(response.headers['content-encoding'], 'gzip') + t.assert.deepStrictEqual(response.statusCode, 200) + t.assert.deepStrictEqual(response.rawPayload, allThreeGzip) + } +) + +test( + 'will serve pre-compressed files with .gzip if multiple * directives used', + async (t) => { + const pluginOptions = { + root: path.join(__dirname, '/static-pre-compressed'), + prefix: '/static-pre-compressed/', + preCompressed: true + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + t.after(() => fastify.close()) + + const response = await fastify.inject({ + method: 'GET', + url: '/static-pre-compressed/all-three.html', + headers: { + 'accept-encoding': '*, *' + } + }) + + genericResponseChecks(t, response) + t.assert.deepStrictEqual(response.headers['content-encoding'], 'gzip') + t.assert.deepStrictEqual(response.statusCode, 200) + t.assert.deepStrictEqual(response.rawPayload, allThreeGzip) + } +) + +test( + 'will serve uncompressed files if there are no compressed variants on disk', + async (t) => { + const pluginOptions = { + root: path.join(__dirname, '/static-pre-compressed'), + prefix: '/static-pre-compressed/', + preCompressed: true + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + t.after(() => fastify.close()) + + const response = await fastify.inject({ + method: 'GET', + url: '/static-pre-compressed/uncompressed.html', + headers: { + 'accept-encoding': 'gzip, deflate, br' + } + }) + + genericResponseChecks(t, response) + t.assert.deepStrictEqual(response.headers['content-encoding'], undefined) + t.assert.deepStrictEqual(response.statusCode, 200) + t.assert.deepStrictEqual(response.body, uncompressedStatic) + } +) + +test( + 'will serve pre-compressed files with .br at the highest priority (with wildcard: false)', + async (t) => { + const pluginOptions = { + root: path.join(__dirname, '/static-pre-compressed'), + prefix: '/static-pre-compressed/', + preCompressed: true, + wildcard: false + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + t.after(() => fastify.close()) + + const response = await fastify.inject({ + method: 'GET', + url: '/static-pre-compressed/all-three.html', + headers: { + 'accept-encoding': 'gzip, deflate, br' + } + }) + + genericResponseChecks(t, response) + t.assert.deepStrictEqual(response.headers['content-encoding'], 'br') + t.assert.deepStrictEqual(response.statusCode, 200) + t.assert.deepStrictEqual(response.rawPayload, allThreeBr) + } +) + +test( + 'will serve pre-compressed files and fallback to .gz if .br is not on disk (with wildcard: false)', + async (t) => { + const pluginOptions = { + root: path.join(__dirname, '/static-pre-compressed'), + prefix: '/static-pre-compressed/', + preCompressed: true, + wildcard: false + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + t.after(() => fastify.close()) + + const response = await fastify.inject({ + method: 'GET', + url: '/static-pre-compressed/gzip-only.html', + headers: { + 'accept-encoding': 'gzip, deflate, br' + } + }) + + genericResponseChecks(t, response) + t.assert.deepStrictEqual(response.headers['content-encoding'], 'gzip') + t.assert.deepStrictEqual(response.statusCode, 200) + t.assert.deepStrictEqual(response.rawPayload, gzipOnly) + } +) + +test( + 'will serve pre-compressed files with .gzip if * directive used (with wildcard: false)', + async (t) => { + const pluginOptions = { + root: path.join(__dirname, '/static-pre-compressed'), + prefix: '/static-pre-compressed/', + preCompressed: true, + wildcard: false + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + t.after(() => fastify.close()) + + const response = await fastify.inject({ + method: 'GET', + url: '/static-pre-compressed/all-three.html', + headers: { + 'accept-encoding': '*' + } + }) + + genericResponseChecks(t, response) + t.assert.deepStrictEqual(response.headers['content-encoding'], 'gzip') + t.assert.deepStrictEqual(response.statusCode, 200) + t.assert.deepStrictEqual(response.rawPayload, allThreeGzip) + } +) + +test( + 'will serve pre-compressed files with .gzip if multiple * directives used (with wildcard: false)', + async (t) => { + const pluginOptions = { + root: path.join(__dirname, '/static-pre-compressed'), + prefix: '/static-pre-compressed/', + preCompressed: true, + wildcard: false + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + t.after(() => fastify.close()) + + const response = await fastify.inject({ + method: 'GET', + url: '/static-pre-compressed/all-three.html', + headers: { + 'accept-encoding': '*, *' + } + }) + + genericResponseChecks(t, response) + t.assert.deepStrictEqual(response.headers['content-encoding'], 'gzip') + t.assert.deepStrictEqual(response.statusCode, 200) + t.assert.deepStrictEqual(response.rawPayload, allThreeGzip) + } +) + +test( + 'will serve uncompressed files if there are no compressed variants on disk (with wildcard: false)', + async (t) => { + const pluginOptions = { + root: path.join(__dirname, '/static-pre-compressed'), + prefix: '/static-pre-compressed/', + preCompressed: true, + wildcard: false + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + t.after(() => fastify.close()) + + const response = await fastify.inject({ + method: 'GET', + url: '/static-pre-compressed/uncompressed.html', + headers: { + 'accept-encoding': 'gzip, deflate, br' + } + }) + + genericResponseChecks(t, response) + t.assert.deepStrictEqual(response.headers['content-encoding'], undefined) + t.assert.deepStrictEqual(response.statusCode, 200) + t.assert.deepStrictEqual(response.body, uncompressedStatic) + } +) + +test( + 'will serve uncompressed files the accept-encoding header is missing', + async (t) => { + const pluginOptions = { + root: path.join(__dirname, '/static-pre-compressed'), + prefix: '/static-pre-compressed/', + preCompressed: true + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + t.after(() => fastify.close()) + + const response = await fastify.inject({ + method: 'GET', + url: '/static-pre-compressed/uncompressed.html' + }) + + genericResponseChecks(t, response) + t.assert.deepStrictEqual(response.headers['content-encoding'], undefined) + t.assert.deepStrictEqual(response.statusCode, 200) + t.assert.deepStrictEqual(response.body, uncompressedStatic) + } +) + +test( + 'will serve precompressed index', + async (t) => { + const pluginOptions = { + root: path.join(__dirname, '/static-pre-compressed'), + prefix: '/static-pre-compressed/', + preCompressed: true + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + t.after(() => fastify.close()) + + const response = await fastify.inject({ + method: 'GET', + url: '/static-pre-compressed/', + headers: { + 'accept-encoding': 'gzip, deflate, br' + } + }) + + genericResponseChecks(t, response) + t.assert.deepStrictEqual(response.headers['content-encoding'], 'br') + t.assert.deepStrictEqual(response.statusCode, 200) + t.assert.deepStrictEqual(response.rawPayload, indexBr) + } +) + +test( + 'will serve preCompressed index without trailing slash', + async (t) => { + const pluginOptions = { + root: path.join(__dirname, '/static-pre-compressed'), + prefix: '/static-pre-compressed/', + preCompressed: true, + redirect: false + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + t.after(() => fastify.close()) + + const response = await fastify.inject({ + method: 'GET', + url: '/static-pre-compressed/dir', + headers: { + 'accept-encoding': 'gzip, deflate, br' + } + }) + + genericResponseChecks(t, response) + t.assert.deepStrictEqual(response.headers['content-encoding'], 'br') + t.assert.deepStrictEqual(response.statusCode, 200) + t.assert.deepStrictEqual(response.rawPayload, dirIndexBr) + } +) + +test( + 'will redirect to preCompressed index without trailing slash when redirect is true', + async (t) => { + const pluginOptions = { + root: path.join(__dirname, '/static-pre-compressed'), + prefix: '/static-pre-compressed/', + preCompressed: true, + redirect: true, + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + t.after(() => fastify.close()) + + const response = await fastify.inject({ + method: 'GET', + url: '/static-pre-compressed/dir', + headers: { + 'accept-encoding': 'gzip, deflate, br' + } + }) + + t.assert.deepStrictEqual(response.statusCode, 301) + t.assert.deepStrictEqual(response.headers.location, '/static-pre-compressed/dir/') + } +) + +test( + 'will serve precompressed gzip index in subdir', + async (t) => { + const pluginOptions = { + root: path.join(__dirname, '/static-pre-compressed'), + preCompressed: true + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + t.after(() => fastify.close()) + + const response = await fastify.inject({ + method: 'GET', + url: '/dir-gz', + headers: { + 'accept-encoding': 'gzip, deflate, br' + } + }) + + genericResponseChecks(t, response) + t.assert.deepStrictEqual(response.headers['content-encoding'], 'gzip') + t.assert.deepStrictEqual(response.statusCode, 200) + t.assert.deepStrictEqual(response.rawPayload, dirIndexGz) + } +) + +test( + 'will serve precompressed index with alternative index option', + async (t) => { + const pluginOptions = { + root: path.join(__dirname, '/static-pre-compressed'), + prefix: '/static-pre-compressed/', + preCompressed: true, + index: ['all-three.html'] + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + t.after(() => fastify.close()) + + const response = await fastify.inject({ + method: 'GET', + url: '/static-pre-compressed/', + headers: { + 'accept-encoding': 'gzip, deflate, br' + } + }) + + genericResponseChecks(t, response) + t.assert.deepStrictEqual(response.headers['content-encoding'], 'br') + t.assert.deepStrictEqual(response.statusCode, 200) + t.assert.deepStrictEqual(response.rawPayload, allThreeBr) + } +) + +test( + 'will serve precompressed file without content-type charset', + async (t) => { + const pluginOptions = { + root: path.join(__dirname, '/static-pre-compressed'), + prefix: '/static-pre-compressed/', + preCompressed: true + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + t.after(() => fastify.close()) + + const response = await fastify.inject({ + method: 'GET', + url: '/static-pre-compressed/sample.jpg', + headers: { + 'accept-encoding': 'gzip, deflate, br' + } + }) + + t.assert.deepStrictEqual(response.headers['content-type'], 'image/jpeg') + t.assert.deepStrictEqual(response.headers['content-encoding'], 'br') + t.assert.deepStrictEqual(response.statusCode, 200) + } +) + +test( + 'will not redirect but serve a file if preCompressed but no compressed file exists and redirect is true', + async (t) => { + const pluginOptions = { + root: path.join(__dirname, '/static-pre-compressed'), + prefix: '/static-pre-compressed/', + preCompressed: true, + redirect: true + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + t.after(() => fastify.close()) + + const response = await fastify.inject({ + method: 'GET', + url: '/static-pre-compressed/baz.json', + headers: { + 'accept-encoding': '*' + } + }) + + t.assert.deepStrictEqual(response.statusCode, 200) + t.assert.deepStrictEqual(response.headers['content-type'], 'application/json; charset=utf-8') + } +) + +test( + 'nonexistent index with precompressed option', + async (t) => { + const pluginOptions = { + root: path.join(__dirname, '/static-pre-compressed'), + prefix: '/static-pre-compressed/', + preCompressed: true + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + t.after(() => fastify.close()) + + const response = await fastify.inject({ + method: 'GET', + url: '/static-pre-compressed/empty/', + headers: { + 'accept-encoding': 'gzip, deflate, br' + } + }) + + t.assert.deepStrictEqual(response.statusCode, 404) + genericErrorResponseChecks(t, response) + } +) + +test('should not redirect to protocol-relative locations', async (t) => { + const urls = [ + ['//^/..', '/', 301], + ['//^/.', null, 404], // it is NOT recognized as a directory by pillarjs/send + ['//:/..', '/', 301], + ['/\\\\a//google.com/%2e%2e%2f%2e%2e', '/a//google.com/%2e%2e%2f%2e%2e/', 301], + ['//a//youtube.com/%2e%2e%2f%2e%2e', '/a//youtube.com/%2e%2e%2f%2e%2e/', 301], + ['/^', null, 404], // it is NOT recognized as a directory by pillarjs/send + ['//google.com/%2e%2e', '/', 301], + ['//users/%2e%2e', '/', 301], + ['//users', null, 404], + ['///deep/path//for//test//index.html', null, 200] + ] + + t.plan(urls.length * 2) + const fastify = Fastify() + fastify.register(fastifyStatic, { + root: path.join(__dirname, '/static'), + redirect: true + }) + t.after(() => fastify.close()) + + const address = await fastify.listen({ port: 0 }) + fastify.server.unref() + + const promises = urls.map(([testUrl, expected, status]) => { + const { promise, resolve } = Promise.withResolvers() + + const req = http.request(url.parse(address + testUrl), res => { + t.assert.deepStrictEqual(res.statusCode, status, `status ${testUrl}`) + + if (expected) { + t.assert.deepStrictEqual(res.headers.location, expected) + } else { + t.assert.ok(!res.headers.location) + } + + resolve() + }) + req.on('error', t.assert.fail) + req.end() + return promise + }) + + await Promise.all(promises) +}) + +test('should not serve index if option is `false`', async (t) => { + t.plan(2) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + prefix: '/static', + index: false + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + fastify.server.unref() + + await t.test('/static/index.html', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/index.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) + + await t.test('/static', async (t) => { + t.plan(2 + GENERIC_ERROR_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + genericErrorResponseChecks(t, response) + }) +}) + +test('should follow symbolic link without wildcard', async (t) => { + t.plan(4) + const fastify = Fastify() + fastify.register(fastifyStatic, { + root: path.join(__dirname, '/static-symbolic-link'), + wildcard: false + }) + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + fastify.server.unref() + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/origin/subdir/subdir/index.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + + const response2 = await fetch('http://localhost:' + fastify.server.address().port + '/dir/symlink/subdir/subdir/index.html') + t.assert.ok(response2.ok) + t.assert.deepStrictEqual(response2.status, 200) +}) + +test('should serve files into hidden dir with wildcard `false`', async (t) => { + t.plan(8) + + const pluginOptions = { + root: path.join(__dirname, '/static-hidden'), + wildcard: false, + serveDotFiles: true + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + fastify.server.unref() + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/.hidden/sample.json') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), jsonHiddenContent) + t.assert.ok(/application\/(json)/.test(response.headers.get('content-type'))) + t.assert.ok(response.headers.get('etag')) + t.assert.ok(response.headers.get('last-modified')) + t.assert.ok(response.headers.get('date')) + t.assert.ok(response.headers.get('cache-control')) +}) + +test('should not found hidden file with wildcard is `false`', async (t) => { + t.plan(2) + + const pluginOptions = { + root: path.join(__dirname, '/static-hidden'), + wildcard: false + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + await fastify.listen({ port: 0 }) + fastify.server.unref() + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/.hidden/sample.json') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) +}) + +test('should serve files into hidden dir without wildcard option', async (t) => { + t.plan(8) + + const pluginOptions = { + root: path.join(__dirname, '/static-hidden') + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + fastify.server.unref() + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/.hidden/sample.json') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), jsonHiddenContent) + t.assert.ok(/application\/(json)/.test(response.headers.get('content-type'))) + t.assert.ok(response.headers.get('etag')) + t.assert.ok(response.headers.get('last-modified')) + t.assert.ok(response.headers.get('date')) + t.assert.ok(response.headers.get('cache-control')) +}) + +test( + 'will serve pre-compressed files with .gzip if multi-root', + async (t) => { + const pluginOptions = { + root: [path.join(__dirname, '/static-pre-compressed'), path.join(__dirname, '/static')], + preCompressed: true + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + t.after(() => fastify.close()) + + const response = await fastify.inject({ + method: 'GET', + url: 'all-three.html', + headers: { + 'accept-encoding': '*, *' + } + }) + + genericResponseChecks(t, response) + t.assert.deepStrictEqual(response.headers['content-encoding'], 'gzip') + t.assert.deepStrictEqual(response.statusCode, 200) + t.assert.deepStrictEqual(response.rawPayload, allThreeGzip) + } +) + +test( + 'will still serve un-compressed files with multi-root and preCompressed as true', + async (t) => { + const pluginOptions = { + root: [path.join(__dirname, '/static-pre-compressed'), path.join(__dirname, '/static')], + preCompressed: true + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + t.after(() => fastify.close()) + + const response = await fastify.inject({ + method: 'GET', + url: 'foobar.html', + headers: { + 'accept-encoding': '*, *' + } + }) + + genericResponseChecks(t, response) + t.assert.deepStrictEqual(response.statusCode, 200) + t.assert.deepStrictEqual(response.body, foobarContent) + } +) + +test( + 'converts URL to path', + async (t) => { + t.plan(2 + GENERIC_RESPONSE_CHECK_COUNT) + const pluginOptions = { + root: url.pathToFileURL(path.join(__dirname, '/static')) + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + const response = await fastify.inject({ + method: 'GET', + url: 'foobar.html', + headers: { + 'accept-encoding': '*, *' + } + }) + genericResponseChecks(t, response) + t.assert.deepStrictEqual(response.statusCode, 200) + t.assert.deepStrictEqual(response.body, foobarContent) + } +) + +test( + 'converts array of URLs to path, contains string path', + async (t) => { + t.plan(2 + GENERIC_RESPONSE_CHECK_COUNT) + const pluginOptions = { + root: [url.pathToFileURL(path.join(__dirname, '/static')), path.join(__dirname, 'static-dotfiles'), url.pathToFileURL(path.join(__dirname, '/static-pre-compressed'))] + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + const response = await fastify.inject({ + method: 'GET', + url: 'foobar.html', + headers: { + 'accept-encoding': '*, *' + } + }) + genericResponseChecks(t, response) + t.assert.deepStrictEqual(response.statusCode, 200) + t.assert.deepStrictEqual(response.body, foobarContent) + } +) + +test( + 'serves files with paths that have characters modified by encodeUri when wildcard is false', + async (t) => { + const aContent = fs.readFileSync(path.join(__dirname, 'static-encode/[...]', 'a .md'), 'utf-8') + + t.plan(4) + const pluginOptions = { + root: url.pathToFileURL(path.join(__dirname, '/static-encode')), + wildcard: false + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + const response = await fastify.inject({ + method: 'GET', + url: '[...]/a .md', + headers: { + 'accept-encoding': '*, *' + } + }) + t.assert.deepStrictEqual(response.statusCode, 200) + t.assert.deepStrictEqual(response.body, aContent) + + const response2 = await fastify.inject({ + method: 'GET', + url: '%5B...%5D/a%20.md', + headers: { + 'accept-encoding': '*, *' + } + }) + t.assert.deepStrictEqual(response2.statusCode, 200) + t.assert.deepStrictEqual(response2.body, aContent) + } +) + +test( + 'serves files with % in the filename', + async (t) => { + t.plan(2) + + const txtContent = fs.readFileSync(path.join(__dirname, 'static', '100%.txt'), 'utf-8') + + const pluginOptions = { + root: url.pathToFileURL(path.join(__dirname, '/static')), + wildcard: false + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + const response = await fastify.inject({ + method: 'GET', + url: '100%25.txt', + headers: { + 'accept-encoding': '*, *' + } + }) + t.assert.deepStrictEqual(response.statusCode, 200) + t.assert.deepStrictEqual(response.body, txtContent) + } +) + +test('content-length in head route should not return zero when using wildcard', async t => { + t.plan(5) + + const pluginOptions = { + root: path.join(__dirname, '/static') + } + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + fastify.server.unref() + + const file = fs.readFileSync(path.join(__dirname, '/static/index.html')) + const contentLength = Buffer.byteLength(file).toString() + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/index.html', { method: 'HEAD' }) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(response.headers.get('content-type'), 'text/html; charset=utf-8') + t.assert.deepStrictEqual(response.headers.get('content-length'), contentLength) + t.assert.deepStrictEqual(await response.text(), '') +}) + +test('respect the .code when using with sendFile', async t => { + t.plan(5) + + const pluginOptions = { + root: path.join(__dirname, '/static') + } + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + + fastify.get('/custom', (_, reply) => { + return reply.code(404).type('text/html').sendFile('foo.html') + }) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + fastify.server.unref() + + const file = fs.readFileSync(path.join(__dirname, '/static/foo.html')) + const contentLength = Buffer.byteLength(file).toString() + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/custom', { method: 'HEAD' }) + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + t.assert.deepStrictEqual(response.headers.get('content-type'), 'text/html; charset=utf-8') + t.assert.deepStrictEqual(response.headers.get('content-length'), contentLength) + t.assert.deepStrictEqual(await response.text(), '') +}) + +test('respect the .type when using with sendFile with contentType disabled', async t => { + t.plan(5) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + contentType: false + } + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + + fastify.get('/custom', (_, reply) => { + return reply.type('text/html; charset=windows-1252').sendFile('foo.html') + }) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + fastify.server.unref() + + const file = fs.readFileSync(path.join(__dirname, '/static/foo.html')) + const contentLength = Buffer.byteLength(file).toString() + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/custom') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(response.headers.get('content-type'), 'text/html; charset=windows-1252') + t.assert.deepStrictEqual(response.headers.get('content-length'), contentLength) + t.assert.deepStrictEqual(await response.text(), fooContent) +}) + +test('register /static/ with custom log level', async t => { + t.plan(9) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + prefix: '/static/', + logLevel: 'warn' + } + const fastify = Fastify({ + logger: { + stream: { + write: (logLine) => { + if (logLine.includes('"msg":"incoming request"')) { + console.warn(logLine) + throw new Error('Should never reach this point since log level is set at WARN!! Unexpected log line: ' + logLine) + } + }, + }, + }, + }) + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + fastify.server.unref() + + await t.test('/static/index.html', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/index.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) + + await t.test('/static/index.html', async t => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/index.html', { method: 'HEAD' }) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), '') + genericResponseChecks(t, response) + }) + + await t.test('/static/index.css', async (t) => { + t.plan(2 + GENERIC_RESPONSE_CHECK_COUNT) + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/index.css') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + genericResponseChecks(t, response) + }) + + await t.test('/static/', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/') + + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) + + await t.test('/static/deep/path/for/test/purpose/foo.html', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/deep/path/for/test/purpose/foo.html') + + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), deepContent) + genericResponseChecks(t, response) + }) + await t.test('/static/deep/path/for/test/', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/deep/path/for/test/') + + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), innerIndex) + genericResponseChecks(t, response) + }) + + await t.test('/static/this/path/for/test', async (t) => { + t.plan(2 + GENERIC_ERROR_RESPONSE_CHECK_COUNT) + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/this/path/for/test') + + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + genericErrorResponseChecks(t, response) + }) + + await t.test('/static/this/path/doesnt/exist.html', async (t) => { + t.plan(2 + GENERIC_ERROR_RESPONSE_CHECK_COUNT) + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/this/path/doesnt/exist.html') + + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + genericErrorResponseChecks(t, response) + }) + + await t.test('304', async t => { + t.plan(5 + GENERIC_RESPONSE_CHECK_COUNT) + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/index.html') + + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + + const response2 = await fetch('http://localhost:' + fastify.server.address().port + '/static/index.html', { + headers: { + 'if-none-match': response.headers.get('etag') + }, + cache: 'no-cache' + }) + t.assert.ok(!response2.ok) + t.assert.deepStrictEqual(response2.status, 304) + }) +}) + +test('register with wildcard false and globIgnore', async t => { + t.plan(5) + + const indexContent = fs + .readFileSync('./test/static-filtered/index.html') + .toString('utf8') + + const deepContent = fs + .readFileSync('./test/static-filtered/deep/path/to/baz.html') + .toString('utf8') + + const pluginOptions = { + root: path.join(__dirname, '/static-filtered'), + wildcard: false, + globIgnore: ['**/*.private'] + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + await t.test('/index.html', async t => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/index.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) + + await t.test('/bar.private', async t => { + t.plan(2) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/bar.private') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + await response.text() + }) + + await t.test('/', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) + + await t.test('/deep/path/to/baz.html', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/deep/path/to/baz.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), deepContent) + genericResponseChecks(t, response) + }) + + await t.test('/deep/path/to/baz.private', async (t) => { + t.plan(2) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/deep/path/to/baz.private') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + await response.text() + }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static/.example b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static/.example new file mode 100644 index 0000000000000000000000000000000000000000..09de8f1d51dad3c8119cdd67cb90dcf3721eb2f3 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static/.example @@ -0,0 +1 @@ +contents of a dotfile \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static/100%.txt b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static/100%.txt new file mode 100644 index 0000000000000000000000000000000000000000..4dd6a5cb6024f4c997e5888b979953d5ca2a1f4f --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static/100%.txt @@ -0,0 +1 @@ +100% diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static/a .md b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static/a .md new file mode 100644 index 0000000000000000000000000000000000000000..96236f8158b12701d5e75c14fb876c4a0f31b963 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static/a .md @@ -0,0 +1 @@ +example \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static/deep/path/for/test/index.html b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static/deep/path/for/test/index.html new file mode 100644 index 0000000000000000000000000000000000000000..49700f6bdd5e5cd20d188313e60d450d9fc211d0 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static/deep/path/for/test/index.html @@ -0,0 +1,5 @@ + + + inner index.html + + diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static/deep/path/for/test/purpose/foo.html b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static/deep/path/for/test/purpose/foo.html new file mode 100644 index 0000000000000000000000000000000000000000..900b7166cc9d931a143e863a8a2d5f62938047c3 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static/deep/path/for/test/purpose/foo.html @@ -0,0 +1,5 @@ + + + the deep path for test purpose body + + diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static/foo.html b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static/foo.html new file mode 100644 index 0000000000000000000000000000000000000000..424329433de5692770306bca1817b08928b0e153 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static/foo.html @@ -0,0 +1,3 @@ + + foo + diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static/foobar.html b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static/foobar.html new file mode 100644 index 0000000000000000000000000000000000000000..d53979c2599ff126adc38527409dc96784dc9c5f --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static/foobar.html @@ -0,0 +1,3 @@ + + foobar + diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static/index.css b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static/index.css new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static/index.html b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static/index.html new file mode 100644 index 0000000000000000000000000000000000000000..1b0b72f02fe433adb972fde358d316866365eef5 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static/index.html @@ -0,0 +1,5 @@ + + + the body + + diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static/shallow/sample.jpg b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static/shallow/sample.jpg new file mode 100644 index 0000000000000000000000000000000000000000..f0c7c2ba02bbb5df2b0fedc3173b9a01633abe3e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static/shallow/sample.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7c859e2f8ee6f21120d12a774038d0022dda0f44c37e4c7de34b07b7323b742c +size 43933 diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static2/bar.html b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static2/bar.html new file mode 100644 index 0000000000000000000000000000000000000000..00d3bc347080dd858da04acee2dc549f8643c8a7 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static2/bar.html @@ -0,0 +1,3 @@ + + bar + diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static2/index.html b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static2/index.html new file mode 100644 index 0000000000000000000000000000000000000000..e3b8da08481c7025e626016a2d0a00e9f2623e25 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/test/static2/index.html @@ -0,0 +1,3 @@ + + index2 + diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/types/index.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/types/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d410bb212f69c43065618b854fe51f3329540a88 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/types/index.d.ts @@ -0,0 +1,128 @@ +// Definitions by: Jannik +// Leo +/// + +import { FastifyPluginAsync, FastifyReply, FastifyRequest, RouteOptions } from 'fastify' +import { Stats } from 'node:fs' + +declare module 'fastify' { + interface FastifyReply { + sendFile(filename: string, rootPath?: string): FastifyReply; + sendFile(filename: string, options?: fastifyStatic.SendOptions): FastifyReply; + sendFile(filename: string, rootPath?: string, options?: fastifyStatic.SendOptions): FastifyReply; + download(filepath: string, options?: fastifyStatic.SendOptions): FastifyReply; + download(filepath: string, filename?: string): FastifyReply; + download(filepath: string, filename?: string, options?: fastifyStatic.SendOptions): FastifyReply; + } +} + +type FastifyStaticPlugin = FastifyPluginAsync> + +declare namespace fastifyStatic { + export interface SetHeadersResponse { + getHeader: FastifyReply['getHeader']; + setHeader: FastifyReply['header']; + readonly filename: string; + statusCode: number; + } + + export interface ExtendedInformation { + fileCount: number; + totalFileCount: number; + folderCount: number; + totalFolderCount: number; + totalSize: number; + lastModified: number; + } + + export interface ListDir { + href: string; + name: string; + stats: Stats; + extendedInfo?: ExtendedInformation; + } + + export interface ListFile { + href: string; + name: string; + stats: Stats; + } + + export interface ListRender { + (dirs: ListDir[], files: ListFile[]): string; + } + + export interface ListOptions { + names?: string[]; + extendedFolderInfo?: boolean; + jsonFormat?: 'names' | 'extended'; + } + + export interface ListOptionsJsonFormat extends ListOptions { + format: 'json'; + // Required when the URL parameter `format=html` exists + render?: ListRender; + } + + export interface ListOptionsHtmlFormat extends ListOptions { + format: 'html'; + render: ListRender; + } + + // Passed on to `send` + export interface SendOptions { + acceptRanges?: boolean; + contentType?: boolean; + cacheControl?: boolean; + dotfiles?: 'allow' | 'deny' | 'ignore'; + etag?: boolean; + extensions?: string[]; + immutable?: boolean; + index?: string[] | string | false; + lastModified?: boolean; + maxAge?: string | number; + serveDotFiles?: boolean; + } + + export interface FastifyStaticOptions extends SendOptions { + root: string | string[] | URL | URL[]; + prefix?: string; + prefixAvoidTrailingSlash?: boolean; + serve?: boolean; + decorateReply?: boolean; + schemaHide?: boolean; + setHeaders?: (res: SetHeadersResponse, path: string, stat: Stats) => void; + redirect?: boolean; + wildcard?: boolean; + globIgnore?: string[]; + list?: boolean | ListOptionsJsonFormat | ListOptionsHtmlFormat; + allowedPath?: (pathName: string, root: string, request: FastifyRequest) => boolean; + /** + * @description + * Opt-in to looking for pre-compressed files + */ + preCompressed?: boolean; + + // Passed on to `send` + acceptRanges?: boolean; + contentType?: boolean; + cacheControl?: boolean; + dotfiles?: 'allow' | 'deny' | 'ignore'; + etag?: boolean; + extensions?: string[]; + immutable?: boolean; + index?: string[] | string | false; + lastModified?: boolean; + maxAge?: string | number; + constraints?: RouteOptions['constraints']; + logLevel?: RouteOptions['logLevel']; + } + + export const fastifyStatic: FastifyStaticPlugin + + export { fastifyStatic as default } +} + +declare function fastifyStatic (...params: Parameters): ReturnType + +export = fastifyStatic diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/types/index.test-d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/types/index.test-d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c1936310e55c5e830bbfd40180e8651e994f500f --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@fastify/static/types/index.test-d.ts @@ -0,0 +1,227 @@ +import fastify, { FastifyInstance, FastifyPluginAsync, FastifyRequest, FastifyReply } from 'fastify' +import { Server } from 'node:http' +import { Stats } from 'node:fs' +import { expectAssignable, expectError, expectType } from 'tsd' +import * as fastifyStaticStar from '..' +import fastifyStatic, { + FastifyStaticOptions, + fastifyStatic as fastifyStaticNamed +} from '..' + +import fastifyStaticCjsImport = require('..') +const fastifyStaticCjs = require('..') + +const app: FastifyInstance = fastify() + +app.register(fastifyStatic, { root: __dirname }) +app.register(fastifyStaticNamed, { root: __dirname }) +app.register(fastifyStaticCjs, { root: __dirname }) +app.register(fastifyStaticCjsImport.default, { root: __dirname }) +app.register(fastifyStaticCjsImport.fastifyStatic, { root: __dirname }) +app.register(fastifyStaticStar.default, { root: __dirname }) +app.register(fastifyStaticStar.fastifyStatic, { root: __dirname }) + +expectType>(fastifyStatic) +expectType>(fastifyStaticNamed) +expectType>(fastifyStaticCjsImport.default) +expectType>(fastifyStaticCjsImport.fastifyStatic) +expectType>(fastifyStaticStar.default) +expectType>( + fastifyStaticStar.fastifyStatic +) +expectType(fastifyStaticCjs) + +const appWithImplicitHttp = fastify() +const options: FastifyStaticOptions = { + acceptRanges: true, + contentType: true, + cacheControl: true, + decorateReply: true, + dotfiles: 'allow', + etag: true, + extensions: ['.js'], + immutable: true, + index: ['1'], + lastModified: true, + maxAge: '', + prefix: '', + prefixAvoidTrailingSlash: false, + root: '', + schemaHide: true, + serve: true, + wildcard: true, + globIgnore: ['**/*.private'], + list: false, + setHeaders: (res, path, stat) => { + expectType(res.filename) + expectType(res.statusCode) + expectType>(res.getHeader('X-Test')) + res.setHeader('X-Test', 'string') + + expectType(path) + + expectType(stat) + }, + preCompressed: false, + allowedPath: (_pathName: string, _root: string, _request: FastifyRequest) => { + return true + }, + constraints: { + host: /.*\.example\.com/, + version: '1.0.2' + }, + logLevel: 'warn' +} + +expectError({ + root: '', + wildcard: '**/**' +}) + +expectAssignable({ + root: '', + list: { + format: 'json' + } +}) + +expectAssignable({ + root: '', + list: { + format: 'json', + render: () => '' + } +}) + +expectAssignable({ + root: '', + list: { + format: 'html', + render: () => '' + } +}) + +expectError({ + root: '', + list: { + format: 'html' + } +}) + +expectAssignable({ + root: [''] +}) + +expectAssignable({ + root: new URL('') +}) + +expectAssignable({ + root: [new URL('')] +}) + +appWithImplicitHttp + .register(fastifyStatic, options) + .after(() => { + appWithImplicitHttp.get('/', (_request, reply) => { + reply.sendFile('some-file-name') + }) + }) + +const appWithHttp2 = fastify({ http2: true }) + +appWithHttp2 + .register(fastifyStatic, options) + .after(() => { + appWithHttp2.get('/', (_request, reply) => { + reply.sendFile('some-file-name') + }) + + appWithHttp2.get('/download', (_request, reply) => { + reply.download('some-file-name') + }) + + appWithHttp2.get('/download/1', (_request, reply) => { + reply.download('some-file-name', { maxAge: '2 days' }) + }) + + appWithHttp2.get('/download/2', (_request, reply) => { + reply.download('some-file-name', 'some-filename', { cacheControl: false, acceptRanges: true }) + }) + + appWithHttp2.get('/download/3', (_request, reply) => { + reply.download('some-file-name', 'some-filename', { contentType: false }) + }) + }) + +const multiRootAppWithImplicitHttp = fastify() +options.root = [''] + +multiRootAppWithImplicitHttp + .register(fastifyStatic, options) + .after(() => { + multiRootAppWithImplicitHttp.get('/', (_request, reply) => { + reply.sendFile('some-file-name') + }) + + multiRootAppWithImplicitHttp.get('/', (_request, reply) => { + reply.sendFile('some-file-name', { cacheControl: false, acceptRanges: true }) + }) + + multiRootAppWithImplicitHttp.get('/', (_request, reply) => { + reply.sendFile('some-file-name', 'some-root-name', { cacheControl: false, acceptRanges: true }) + }) + + multiRootAppWithImplicitHttp.get('/', (_request, reply) => { + reply.sendFile('some-file-name', 'some-root-name-2', { contentType: false }) + }) + + multiRootAppWithImplicitHttp.get('/download', (_request, reply) => { + reply.download('some-file-name') + }) + + multiRootAppWithImplicitHttp.get('/download/1', (_request, reply) => { + reply.download('some-file-name', { maxAge: '2 days' }) + }) + + multiRootAppWithImplicitHttp.get('/download/2', (_request, reply) => { + reply.download('some-file-name', 'some-filename', { cacheControl: false, acceptRanges: true }) + }) + + multiRootAppWithImplicitHttp.get('/download/3', (_request, reply) => { + reply.download('some-file-name', 'some-filename', { contentType: false }) + }) + }) + +const noIndexApp = fastify() +options.root = '' +options.index = false + +noIndexApp + .register(fastifyStatic, options) + .after(() => { + noIndexApp.get('/', (_request, reply) => { + reply.send('

fastify-static

') + }) + }) + +options.root = new URL('') + +const URLRootApp = fastify() +URLRootApp.register(fastifyStatic, options) + .after(() => { + URLRootApp.get('/', (_request, reply) => { + reply.send('

fastify-static

') + }) + }) + +const defaultIndexApp = fastify() +options.index = 'index.html' + +defaultIndexApp + .register(fastifyStatic, options) + .after(() => { + defaultIndexApp.get('/', (_request, reply) => { + reply.send('

fastify-static

') + }) + }) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/balanced-match/LICENSE.md b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/balanced-match/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..61ece8cc92afb41fdb1552ec1f72ac147b9eaceb --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/balanced-match/LICENSE.md @@ -0,0 +1,23 @@ +(MIT) + +Original code Copyright Julian Gruber + +Port to TypeScript Copyright Isaac Z. Schlueter + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/balanced-match/README.md b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/balanced-match/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ed10c70aab6f52ffef4df2d0a1c19412febb949e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/balanced-match/README.md @@ -0,0 +1,60 @@ +# @isaacs/balanced-match + +A hybrid CJS/ESM TypeScript fork of +[balanced-match](http://npm.im/balanced-match). + +Match balanced string pairs, like `{` and `}` or `` and ``. Supports regular expressions as well! + +[![CI](https://github.com/juliangruber/balanced-match/actions/workflows/ci.yml/badge.svg)](https://github.com/juliangruber/balanced-match/actions/workflows/ci.yml) +[![downloads](https://img.shields.io/npm/dm/balanced-match.svg)](https://www.npmjs.org/package/balanced-match) + +## Example + +Get the first matching pair of braces: + +```js +import { balanced } from '@isaacs/balanced-match' + +console.log(balanced('{', '}', 'pre{in{nested}}post')) +console.log(balanced('{', '}', 'pre{first}between{second}post')) +console.log(balanced(/\s+\{\s+/, /\s+\}\s+/, 'pre { in{nest} } post')) +``` + +The matches are: + +```bash +$ node example.js +{ start: 3, end: 14, pre: 'pre', body: 'in{nested}', post: 'post' } +{ start: 3, + end: 9, + pre: 'pre', + body: 'first', + post: 'between{second}post' } +{ start: 3, end: 17, pre: 'pre', body: 'in{nest}', post: 'post' } +``` + +## API + +### const m = balanced(a, b, str) + +For the first non-nested matching pair of `a` and `b` in `str`, return an +object with those keys: + +- **start** the index of the first match of `a` +- **end** the index of the matching `b` +- **pre** the preamble, `a` and `b` not included +- **body** the match, `a` and `b` not included +- **post** the postscript, `a` and `b` not included + +If there's no match, `undefined` will be returned. + +If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `['{', 'a', '']` and `{a}}` will match `['', 'a', '}']`. + +### const r = balanced.range(a, b, str) + +For the first non-nested matching pair of `a` and `b` in `str`, return an +array with indexes: `[ , ]`. + +If there's no match, `undefined` will be returned. + +If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `[ 1, 3 ]` and `{a}}` will match `[0, 2]`. diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/balanced-match/dist/commonjs/index.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/balanced-match/dist/commonjs/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f819cfd016012ff5607febb82aaab715244f8fab --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/balanced-match/dist/commonjs/index.d.ts @@ -0,0 +1,9 @@ +export declare const balanced: (a: string | RegExp, b: string | RegExp, str: string) => false | { + start: number; + end: number; + pre: string; + body: string; + post: string; +} | undefined; +export declare const range: (a: string, b: string, str: string) => undefined | [number, number]; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/balanced-match/dist/commonjs/index.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/balanced-match/dist/commonjs/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..6306762c77d77b909214a5d7af014b2eb156bbb3 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/balanced-match/dist/commonjs/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,QAAQ,GACnB,GAAG,MAAM,GAAG,MAAM,EAClB,GAAG,MAAM,GAAG,MAAM,EAClB,KAAK,MAAM;;;;;;aAgBZ,CAAA;AAOD,eAAO,MAAM,KAAK,GAChB,GAAG,MAAM,EACT,GAAG,MAAM,EACT,KAAK,MAAM,KACV,SAAS,GAAG,CAAC,MAAM,EAAE,MAAM,CA2C7B,CAAA"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/balanced-match/dist/commonjs/index.js b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/balanced-match/dist/commonjs/index.js new file mode 100644 index 0000000000000000000000000000000000000000..0c9014bac153187d5b0e3d1d214a5d1c71eefd32 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/balanced-match/dist/commonjs/index.js @@ -0,0 +1,59 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.range = exports.balanced = void 0; +const balanced = (a, b, str) => { + const ma = a instanceof RegExp ? maybeMatch(a, str) : a; + const mb = b instanceof RegExp ? maybeMatch(b, str) : b; + const r = ma !== null && mb != null && (0, exports.range)(ma, mb, str); + return (r && { + start: r[0], + end: r[1], + pre: str.slice(0, r[0]), + body: str.slice(r[0] + ma.length, r[1]), + post: str.slice(r[1] + mb.length), + }); +}; +exports.balanced = balanced; +const maybeMatch = (reg, str) => { + const m = str.match(reg); + return m ? m[0] : null; +}; +const range = (a, b, str) => { + let begs, beg, left, right = undefined, result; + let ai = str.indexOf(a); + let bi = str.indexOf(b, ai + 1); + let i = ai; + if (ai >= 0 && bi > 0) { + if (a === b) { + return [ai, bi]; + } + begs = []; + left = str.length; + while (i >= 0 && !result) { + if (i === ai) { + begs.push(i); + ai = str.indexOf(a, i + 1); + } + else if (begs.length === 1) { + const r = begs.pop(); + if (r !== undefined) + result = [r, bi]; + } + else { + beg = begs.pop(); + if (beg !== undefined && beg < left) { + left = beg; + right = bi; + } + bi = str.indexOf(b, i + 1); + } + i = ai < bi && ai >= 0 ? ai : bi; + } + if (begs.length && right !== undefined) { + result = [left, right]; + } + } + return result; +}; +exports.range = range; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/balanced-match/dist/commonjs/index.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/balanced-match/dist/commonjs/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..83f547ca9d33d5e0cc5a6e38b1dab4b9060a2bc7 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/balanced-match/dist/commonjs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;AAAO,MAAM,QAAQ,GAAG,CACtB,CAAkB,EAClB,CAAkB,EAClB,GAAW,EACX,EAAE;IACF,MAAM,EAAE,GAAG,CAAC,YAAY,MAAM,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;IACvD,MAAM,EAAE,GAAG,CAAC,YAAY,MAAM,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;IAEvD,MAAM,CAAC,GAAG,EAAE,KAAK,IAAI,IAAI,EAAE,IAAI,IAAI,IAAI,IAAA,aAAK,EAAC,EAAE,EAAE,EAAE,EAAE,GAAG,CAAC,CAAA;IAEzD,OAAO,CACL,CAAC,IAAI;QACH,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC;QACX,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC;QACT,GAAG,EAAE,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;QACvB,IAAI,EAAE,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;QACvC,IAAI,EAAE,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC;KAClC,CACF,CAAA;AACH,CAAC,CAAA;AAnBY,QAAA,QAAQ,YAmBpB;AAED,MAAM,UAAU,GAAG,CAAC,GAAW,EAAE,GAAW,EAAE,EAAE;IAC9C,MAAM,CAAC,GAAG,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;IACxB,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAA;AACxB,CAAC,CAAA;AAEM,MAAM,KAAK,GAAG,CACnB,CAAS,EACT,CAAS,EACT,GAAW,EACmB,EAAE;IAChC,IAAI,IAAc,EAChB,GAAuB,EACvB,IAAY,EACZ,KAAK,GAAuB,SAAS,EACrC,MAAoC,CAAA;IACtC,IAAI,EAAE,GAAG,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,CAAA;IACvB,IAAI,EAAE,GAAG,GAAG,CAAC,OAAO,CAAC,CAAC,EAAE,EAAE,GAAG,CAAC,CAAC,CAAA;IAC/B,IAAI,CAAC,GAAG,EAAE,CAAA;IAEV,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,GAAG,CAAC,EAAE,CAAC;QACtB,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;YACZ,OAAO,CAAC,EAAE,EAAE,EAAE,CAAC,CAAA;QACjB,CAAC;QACD,IAAI,GAAG,EAAE,CAAA;QACT,IAAI,GAAG,GAAG,CAAC,MAAM,CAAA;QAEjB,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC;YACzB,IAAI,CAAC,KAAK,EAAE,EAAE,CAAC;gBACb,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;gBACZ,EAAE,GAAG,GAAG,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,CAAA;YAC5B,CAAC;iBAAM,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;gBAC7B,MAAM,CAAC,GAAG,IAAI,CAAC,GAAG,EAAE,CAAA;gBACpB,IAAI,CAAC,KAAK,SAAS;oBAAE,MAAM,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC,CAAA;YACvC,CAAC;iBAAM,CAAC;gBACN,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAA;gBAChB,IAAI,GAAG,KAAK,SAAS,IAAI,GAAG,GAAG,IAAI,EAAE,CAAC;oBACpC,IAAI,GAAG,GAAG,CAAA;oBACV,KAAK,GAAG,EAAE,CAAA;gBACZ,CAAC;gBAED,EAAE,GAAG,GAAG,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,CAAA;YAC5B,CAAC;YAED,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAA;QAClC,CAAC;QAED,IAAI,IAAI,CAAC,MAAM,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;YACvC,MAAM,GAAG,CAAC,IAAI,EAAE,KAAK,CAAC,CAAA;QACxB,CAAC;IACH,CAAC;IAED,OAAO,MAAM,CAAA;AACf,CAAC,CAAA;AA/CY,QAAA,KAAK,SA+CjB","sourcesContent":["export const balanced = (\n a: string | RegExp,\n b: string | RegExp,\n str: string,\n) => {\n const ma = a instanceof RegExp ? maybeMatch(a, str) : a\n const mb = b instanceof RegExp ? maybeMatch(b, str) : b\n\n const r = ma !== null && mb != null && range(ma, mb, str)\n\n return (\n r && {\n start: r[0],\n end: r[1],\n pre: str.slice(0, r[0]),\n body: str.slice(r[0] + ma.length, r[1]),\n post: str.slice(r[1] + mb.length),\n }\n )\n}\n\nconst maybeMatch = (reg: RegExp, str: string) => {\n const m = str.match(reg)\n return m ? m[0] : null\n}\n\nexport const range = (\n a: string,\n b: string,\n str: string,\n): undefined | [number, number] => {\n let begs: number[],\n beg: number | undefined,\n left: number,\n right: number | undefined = undefined,\n result: undefined | [number, number]\n let ai = str.indexOf(a)\n let bi = str.indexOf(b, ai + 1)\n let i = ai\n\n if (ai >= 0 && bi > 0) {\n if (a === b) {\n return [ai, bi]\n }\n begs = []\n left = str.length\n\n while (i >= 0 && !result) {\n if (i === ai) {\n begs.push(i)\n ai = str.indexOf(a, i + 1)\n } else if (begs.length === 1) {\n const r = begs.pop()\n if (r !== undefined) result = [r, bi]\n } else {\n beg = begs.pop()\n if (beg !== undefined && beg < left) {\n left = beg\n right = bi\n }\n\n bi = str.indexOf(b, i + 1)\n }\n\n i = ai < bi && ai >= 0 ? ai : bi\n }\n\n if (begs.length && right !== undefined) {\n result = [left, right]\n }\n }\n\n return result\n}\n"]} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/balanced-match/dist/commonjs/package.json b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/balanced-match/dist/commonjs/package.json new file mode 100644 index 0000000000000000000000000000000000000000..5bbefffbabee392d1855491b84dc0a716b6a3bf2 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/balanced-match/dist/commonjs/package.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/balanced-match/dist/esm/index.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/balanced-match/dist/esm/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f819cfd016012ff5607febb82aaab715244f8fab --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/balanced-match/dist/esm/index.d.ts @@ -0,0 +1,9 @@ +export declare const balanced: (a: string | RegExp, b: string | RegExp, str: string) => false | { + start: number; + end: number; + pre: string; + body: string; + post: string; +} | undefined; +export declare const range: (a: string, b: string, str: string) => undefined | [number, number]; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/balanced-match/dist/esm/index.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/balanced-match/dist/esm/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..6306762c77d77b909214a5d7af014b2eb156bbb3 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/balanced-match/dist/esm/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,QAAQ,GACnB,GAAG,MAAM,GAAG,MAAM,EAClB,GAAG,MAAM,GAAG,MAAM,EAClB,KAAK,MAAM;;;;;;aAgBZ,CAAA;AAOD,eAAO,MAAM,KAAK,GAChB,GAAG,MAAM,EACT,GAAG,MAAM,EACT,KAAK,MAAM,KACV,SAAS,GAAG,CAAC,MAAM,EAAE,MAAM,CA2C7B,CAAA"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/balanced-match/dist/esm/index.js b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/balanced-match/dist/esm/index.js new file mode 100644 index 0000000000000000000000000000000000000000..fe81200f9d676da19bf1bf088ecef7944290e38a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/balanced-match/dist/esm/index.js @@ -0,0 +1,54 @@ +export const balanced = (a, b, str) => { + const ma = a instanceof RegExp ? maybeMatch(a, str) : a; + const mb = b instanceof RegExp ? maybeMatch(b, str) : b; + const r = ma !== null && mb != null && range(ma, mb, str); + return (r && { + start: r[0], + end: r[1], + pre: str.slice(0, r[0]), + body: str.slice(r[0] + ma.length, r[1]), + post: str.slice(r[1] + mb.length), + }); +}; +const maybeMatch = (reg, str) => { + const m = str.match(reg); + return m ? m[0] : null; +}; +export const range = (a, b, str) => { + let begs, beg, left, right = undefined, result; + let ai = str.indexOf(a); + let bi = str.indexOf(b, ai + 1); + let i = ai; + if (ai >= 0 && bi > 0) { + if (a === b) { + return [ai, bi]; + } + begs = []; + left = str.length; + while (i >= 0 && !result) { + if (i === ai) { + begs.push(i); + ai = str.indexOf(a, i + 1); + } + else if (begs.length === 1) { + const r = begs.pop(); + if (r !== undefined) + result = [r, bi]; + } + else { + beg = begs.pop(); + if (beg !== undefined && beg < left) { + left = beg; + right = bi; + } + bi = str.indexOf(b, i + 1); + } + i = ai < bi && ai >= 0 ? ai : bi; + } + if (begs.length && right !== undefined) { + result = [left, right]; + } + } + return result; +}; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/balanced-match/dist/esm/index.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/balanced-match/dist/esm/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..b476cae229324756c8359ea6545e7494f13e63d7 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/balanced-match/dist/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,QAAQ,GAAG,CACtB,CAAkB,EAClB,CAAkB,EAClB,GAAW,EACX,EAAE;IACF,MAAM,EAAE,GAAG,CAAC,YAAY,MAAM,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;IACvD,MAAM,EAAE,GAAG,CAAC,YAAY,MAAM,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;IAEvD,MAAM,CAAC,GAAG,EAAE,KAAK,IAAI,IAAI,EAAE,IAAI,IAAI,IAAI,KAAK,CAAC,EAAE,EAAE,EAAE,EAAE,GAAG,CAAC,CAAA;IAEzD,OAAO,CACL,CAAC,IAAI;QACH,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC;QACX,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC;QACT,GAAG,EAAE,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;QACvB,IAAI,EAAE,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;QACvC,IAAI,EAAE,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC;KAClC,CACF,CAAA;AACH,CAAC,CAAA;AAED,MAAM,UAAU,GAAG,CAAC,GAAW,EAAE,GAAW,EAAE,EAAE;IAC9C,MAAM,CAAC,GAAG,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;IACxB,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAA;AACxB,CAAC,CAAA;AAED,MAAM,CAAC,MAAM,KAAK,GAAG,CACnB,CAAS,EACT,CAAS,EACT,GAAW,EACmB,EAAE;IAChC,IAAI,IAAc,EAChB,GAAuB,EACvB,IAAY,EACZ,KAAK,GAAuB,SAAS,EACrC,MAAoC,CAAA;IACtC,IAAI,EAAE,GAAG,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,CAAA;IACvB,IAAI,EAAE,GAAG,GAAG,CAAC,OAAO,CAAC,CAAC,EAAE,EAAE,GAAG,CAAC,CAAC,CAAA;IAC/B,IAAI,CAAC,GAAG,EAAE,CAAA;IAEV,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,GAAG,CAAC,EAAE,CAAC;QACtB,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;YACZ,OAAO,CAAC,EAAE,EAAE,EAAE,CAAC,CAAA;QACjB,CAAC;QACD,IAAI,GAAG,EAAE,CAAA;QACT,IAAI,GAAG,GAAG,CAAC,MAAM,CAAA;QAEjB,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC;YACzB,IAAI,CAAC,KAAK,EAAE,EAAE,CAAC;gBACb,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;gBACZ,EAAE,GAAG,GAAG,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,CAAA;YAC5B,CAAC;iBAAM,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;gBAC7B,MAAM,CAAC,GAAG,IAAI,CAAC,GAAG,EAAE,CAAA;gBACpB,IAAI,CAAC,KAAK,SAAS;oBAAE,MAAM,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC,CAAA;YACvC,CAAC;iBAAM,CAAC;gBACN,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAA;gBAChB,IAAI,GAAG,KAAK,SAAS,IAAI,GAAG,GAAG,IAAI,EAAE,CAAC;oBACpC,IAAI,GAAG,GAAG,CAAA;oBACV,KAAK,GAAG,EAAE,CAAA;gBACZ,CAAC;gBAED,EAAE,GAAG,GAAG,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,CAAA;YAC5B,CAAC;YAED,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAA;QAClC,CAAC;QAED,IAAI,IAAI,CAAC,MAAM,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;YACvC,MAAM,GAAG,CAAC,IAAI,EAAE,KAAK,CAAC,CAAA;QACxB,CAAC;IACH,CAAC;IAED,OAAO,MAAM,CAAA;AACf,CAAC,CAAA","sourcesContent":["export const balanced = (\n a: string | RegExp,\n b: string | RegExp,\n str: string,\n) => {\n const ma = a instanceof RegExp ? maybeMatch(a, str) : a\n const mb = b instanceof RegExp ? maybeMatch(b, str) : b\n\n const r = ma !== null && mb != null && range(ma, mb, str)\n\n return (\n r && {\n start: r[0],\n end: r[1],\n pre: str.slice(0, r[0]),\n body: str.slice(r[0] + ma.length, r[1]),\n post: str.slice(r[1] + mb.length),\n }\n )\n}\n\nconst maybeMatch = (reg: RegExp, str: string) => {\n const m = str.match(reg)\n return m ? m[0] : null\n}\n\nexport const range = (\n a: string,\n b: string,\n str: string,\n): undefined | [number, number] => {\n let begs: number[],\n beg: number | undefined,\n left: number,\n right: number | undefined = undefined,\n result: undefined | [number, number]\n let ai = str.indexOf(a)\n let bi = str.indexOf(b, ai + 1)\n let i = ai\n\n if (ai >= 0 && bi > 0) {\n if (a === b) {\n return [ai, bi]\n }\n begs = []\n left = str.length\n\n while (i >= 0 && !result) {\n if (i === ai) {\n begs.push(i)\n ai = str.indexOf(a, i + 1)\n } else if (begs.length === 1) {\n const r = begs.pop()\n if (r !== undefined) result = [r, bi]\n } else {\n beg = begs.pop()\n if (beg !== undefined && beg < left) {\n left = beg\n right = bi\n }\n\n bi = str.indexOf(b, i + 1)\n }\n\n i = ai < bi && ai >= 0 ? ai : bi\n }\n\n if (begs.length && right !== undefined) {\n result = [left, right]\n }\n }\n\n return result\n}\n"]} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/balanced-match/dist/esm/package.json b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/balanced-match/dist/esm/package.json new file mode 100644 index 0000000000000000000000000000000000000000..3dbc1ca591c0557e35b6004aeba250e6a70b56e3 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/balanced-match/dist/esm/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/balanced-match/package.json b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/balanced-match/package.json new file mode 100644 index 0000000000000000000000000000000000000000..49296e6af443c4c424844aa2c73081c3e34b8c8c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/balanced-match/package.json @@ -0,0 +1,79 @@ +{ + "name": "@isaacs/balanced-match", + "description": "Match balanced character pairs, like \"{\" and \"}\"", + "version": "4.0.1", + "files": [ + "dist" + ], + "repository": { + "type": "git", + "url": "git://github.com/isaacs/balanced-match.git" + }, + "exports": { + "./package.json": "./package.json", + ".": { + "import": { + "types": "./dist/esm/index.d.ts", + "default": "./dist/esm/index.js" + }, + "require": { + "types": "./dist/commonjs/index.d.ts", + "default": "./dist/commonjs/index.js" + } + } + }, + "type": "module", + "scripts": { + "preversion": "npm test", + "postversion": "npm publish", + "prepublishOnly": "git push origin --follow-tags", + "prepare": "tshy", + "pretest": "npm run prepare", + "presnap": "npm run prepare", + "test": "tap", + "snap": "tap", + "format": "prettier --write . --loglevel warn", + "benchmark": "node benchmark/index.js", + "typedoc": "typedoc --tsconfig .tshy/esm.json ./src/*.ts" + }, + "prettier": { + "semi": false, + "printWidth": 80, + "tabWidth": 2, + "useTabs": false, + "singleQuote": true, + "jsxSingleQuote": false, + "bracketSameLine": true, + "arrowParens": "avoid", + "endOfLine": "lf" + }, + "devDependencies": { + "@types/brace-expansion": "^1.1.2", + "@types/node": "^24.0.0", + "mkdirp": "^3.0.1", + "prettier": "^3.3.2", + "tap": "^21.1.0", + "tshy": "^3.0.2", + "typedoc": "^0.28.5" + }, + "keywords": [ + "match", + "regexp", + "test", + "balanced", + "parse" + ], + "license": "MIT", + "engines": { + "node": "20 || >=22" + }, + "tshy": { + "exports": { + "./package.json": "./package.json", + ".": "./src/index.ts" + } + }, + "main": "./dist/commonjs/index.js", + "types": "./dist/commonjs/index.d.ts", + "module": "./dist/esm/index.js" +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/brace-expansion/LICENSE b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/brace-expansion/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..46e7b75c91ced041ae473299398af2b0472dc352 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/brace-expansion/LICENSE @@ -0,0 +1,23 @@ +MIT License + +Copyright Julian Gruber + +TypeScript port Copyright Isaac Z. Schlueter + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/brace-expansion/README.md b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/brace-expansion/README.md new file mode 100644 index 0000000000000000000000000000000000000000..56097c9830ade0bc5b4a42bf44fb928190c1becc --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/brace-expansion/README.md @@ -0,0 +1,86 @@ +# @isaacs/brace-expansion + +A hybrid CJS/ESM TypeScript fork of +[brace-expansion](http://npm.im/brace-expansion). + +[Brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html), +as known from sh/bash, in JavaScript. + +[![CI](https://github.com/juliangruber/brace-expansion/actions/workflows/ci.yml/badge.svg)](https://github.com/juliangruber/brace-expansion/actions/workflows/ci.yml) +[![downloads](https://img.shields.io/npm/dm/brace-expansion.svg)](https://www.npmjs.org/package/brace-expansion) + +## Example + +```js +import { expand } from '@isaacs/brace-expansion' + +expand('file-{a,b,c}.jpg') +// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] + +expand('-v{,,}') +// => ['-v', '-v', '-v'] + +expand('file{0..2}.jpg') +// => ['file0.jpg', 'file1.jpg', 'file2.jpg'] + +expand('file-{a..c}.jpg') +// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] + +expand('file{2..0}.jpg') +// => ['file2.jpg', 'file1.jpg', 'file0.jpg'] + +expand('file{0..4..2}.jpg') +// => ['file0.jpg', 'file2.jpg', 'file4.jpg'] + +expand('file-{a..e..2}.jpg') +// => ['file-a.jpg', 'file-c.jpg', 'file-e.jpg'] + +expand('file{00..10..5}.jpg') +// => ['file00.jpg', 'file05.jpg', 'file10.jpg'] + +expand('{{A..C},{a..c}}') +// => ['A', 'B', 'C', 'a', 'b', 'c'] + +expand('ppp{,config,oe{,conf}}') +// => ['ppp', 'pppconfig', 'pppoe', 'pppoeconf'] +``` + +## API + +```js +import { expand } from '@isaacs/brace-expansion' +``` + +### const expanded = expand(str) + +Return an array of all possible and valid expansions of `str`. If none are +found, `[str]` is returned. + +Valid expansions are: + +```js +/^(.*,)+(.+)?$/ +// {a,b,...} +``` + +A comma separated list of options, like `{a,b}` or `{a,{b,c}}` or `{,a,}`. + +```js +/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ +// {x..y[..incr]} +``` + +A numeric sequence from `x` to `y` inclusive, with optional increment. +If `x` or `y` start with a leading `0`, all the numbers will be padded +to have equal length. Negative numbers and backwards iteration work too. + +```js +/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ +// {x..y[..incr]} +``` + +An alphabetic sequence from `x` to `y` inclusive, with optional increment. +`x` and `y` must be exactly one character, and if given, `incr` must be a +number. + +For compatibility reasons, the string `${` is not eligible for brace expansion. diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/brace-expansion/dist/commonjs/index.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/brace-expansion/dist/commonjs/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c51cda1bb399ab26f2d949c03cceb45ecda66597 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/brace-expansion/dist/commonjs/index.d.ts @@ -0,0 +1,2 @@ +export declare function expand(str: string): string[]; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/brace-expansion/dist/commonjs/index.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/brace-expansion/dist/commonjs/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..27f432d98dd6c9c8749e4d0b0b1e30740330701c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/brace-expansion/dist/commonjs/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAwEA,wBAAgB,MAAM,CAAC,GAAG,EAAE,MAAM,YAgBjC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/brace-expansion/dist/commonjs/index.js b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/brace-expansion/dist/commonjs/index.js new file mode 100644 index 0000000000000000000000000000000000000000..99cee69d560e24a30934a93db3c116532e257417 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/brace-expansion/dist/commonjs/index.js @@ -0,0 +1,196 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.expand = expand; +const balanced_match_1 = require("@isaacs/balanced-match"); +const escSlash = '\0SLASH' + Math.random() + '\0'; +const escOpen = '\0OPEN' + Math.random() + '\0'; +const escClose = '\0CLOSE' + Math.random() + '\0'; +const escComma = '\0COMMA' + Math.random() + '\0'; +const escPeriod = '\0PERIOD' + Math.random() + '\0'; +const escSlashPattern = new RegExp(escSlash, 'g'); +const escOpenPattern = new RegExp(escOpen, 'g'); +const escClosePattern = new RegExp(escClose, 'g'); +const escCommaPattern = new RegExp(escComma, 'g'); +const escPeriodPattern = new RegExp(escPeriod, 'g'); +const slashPattern = /\\\\/g; +const openPattern = /\\{/g; +const closePattern = /\\}/g; +const commaPattern = /\\,/g; +const periodPattern = /\\./g; +function numeric(str) { + return !isNaN(str) ? parseInt(str, 10) : str.charCodeAt(0); +} +function escapeBraces(str) { + return str + .replace(slashPattern, escSlash) + .replace(openPattern, escOpen) + .replace(closePattern, escClose) + .replace(commaPattern, escComma) + .replace(periodPattern, escPeriod); +} +function unescapeBraces(str) { + return str + .replace(escSlashPattern, '\\') + .replace(escOpenPattern, '{') + .replace(escClosePattern, '}') + .replace(escCommaPattern, ',') + .replace(escPeriodPattern, '.'); +} +/** + * Basically just str.split(","), but handling cases + * where we have nested braced sections, which should be + * treated as individual members, like {a,{b,c},d} + */ +function parseCommaParts(str) { + if (!str) { + return ['']; + } + const parts = []; + const m = (0, balanced_match_1.balanced)('{', '}', str); + if (!m) { + return str.split(','); + } + const { pre, body, post } = m; + const p = pre.split(','); + p[p.length - 1] += '{' + body + '}'; + const postParts = parseCommaParts(post); + if (post.length) { + ; + p[p.length - 1] += postParts.shift(); + p.push.apply(p, postParts); + } + parts.push.apply(parts, p); + return parts; +} +function expand(str) { + if (!str) { + return []; + } + // I don't know why Bash 4.3 does this, but it does. + // Anything starting with {} will have the first two bytes preserved + // but *only* at the top level, so {},a}b will not expand to anything, + // but a{},b}c will be expanded to [a}c,abc]. + // One could argue that this is a bug in Bash, but since the goal of + // this module is to match Bash's rules, we escape a leading {} + if (str.slice(0, 2) === '{}') { + str = '\\{\\}' + str.slice(2); + } + return expand_(escapeBraces(str), true).map(unescapeBraces); +} +function embrace(str) { + return '{' + str + '}'; +} +function isPadded(el) { + return /^-?0\d/.test(el); +} +function lte(i, y) { + return i <= y; +} +function gte(i, y) { + return i >= y; +} +function expand_(str, isTop) { + /** @type {string[]} */ + const expansions = []; + const m = (0, balanced_match_1.balanced)('{', '}', str); + if (!m) + return [str]; + // no need to expand pre, since it is guaranteed to be free of brace-sets + const pre = m.pre; + const post = m.post.length ? expand_(m.post, false) : ['']; + if (/\$$/.test(m.pre)) { + for (let k = 0; k < post.length; k++) { + const expansion = pre + '{' + m.body + '}' + post[k]; + expansions.push(expansion); + } + } + else { + const isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + const isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + const isSequence = isNumericSequence || isAlphaSequence; + const isOptions = m.body.indexOf(',') >= 0; + if (!isSequence && !isOptions) { + // {a},b} + if (m.post.match(/,(?!,).*\}/)) { + str = m.pre + '{' + m.body + escClose + m.post; + return expand_(str); + } + return [str]; + } + let n; + if (isSequence) { + n = m.body.split(/\.\./); + } + else { + n = parseCommaParts(m.body); + if (n.length === 1 && n[0] !== undefined) { + // x{{a,b}}y ==> x{a}y x{b}y + n = expand_(n[0], false).map(embrace); + //XXX is this necessary? Can't seem to hit it in tests. + /* c8 ignore start */ + if (n.length === 1) { + return post.map(p => m.pre + n[0] + p); + } + /* c8 ignore stop */ + } + } + // at this point, n is the parts, and we know it's not a comma set + // with a single entry. + let N; + if (isSequence && n[0] !== undefined && n[1] !== undefined) { + const x = numeric(n[0]); + const y = numeric(n[1]); + const width = Math.max(n[0].length, n[1].length); + let incr = n.length === 3 && n[2] !== undefined ? Math.abs(numeric(n[2])) : 1; + let test = lte; + const reverse = y < x; + if (reverse) { + incr *= -1; + test = gte; + } + const pad = n.some(isPadded); + N = []; + for (let i = x; test(i, y); i += incr) { + let c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === '\\') { + c = ''; + } + } + else { + c = String(i); + if (pad) { + const need = width - c.length; + if (need > 0) { + const z = new Array(need + 1).join('0'); + if (i < 0) { + c = '-' + z + c.slice(1); + } + else { + c = z + c; + } + } + } + } + N.push(c); + } + } + else { + N = []; + for (let j = 0; j < n.length; j++) { + N.push.apply(N, expand_(n[j], false)); + } + } + for (let j = 0; j < N.length; j++) { + for (let k = 0; k < post.length; k++) { + const expansion = pre + N[j] + post[k]; + if (!isTop || isSequence || expansion) { + expansions.push(expansion); + } + } + } + } + return expansions; +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/brace-expansion/dist/commonjs/index.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/brace-expansion/dist/commonjs/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..6c3f6c4c12190b032384b7ddb291c3c279339364 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/brace-expansion/dist/commonjs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;AAwEA,wBAgBC;AAxFD,2DAAiD;AAEjD,MAAM,QAAQ,GAAG,SAAS,GAAG,IAAI,CAAC,MAAM,EAAE,GAAG,IAAI,CAAA;AACjD,MAAM,OAAO,GAAG,QAAQ,GAAG,IAAI,CAAC,MAAM,EAAE,GAAG,IAAI,CAAA;AAC/C,MAAM,QAAQ,GAAG,SAAS,GAAG,IAAI,CAAC,MAAM,EAAE,GAAG,IAAI,CAAA;AACjD,MAAM,QAAQ,GAAG,SAAS,GAAG,IAAI,CAAC,MAAM,EAAE,GAAG,IAAI,CAAA;AACjD,MAAM,SAAS,GAAG,UAAU,GAAG,IAAI,CAAC,MAAM,EAAE,GAAG,IAAI,CAAA;AACnD,MAAM,eAAe,GAAG,IAAI,MAAM,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAA;AACjD,MAAM,cAAc,GAAG,IAAI,MAAM,CAAC,OAAO,EAAE,GAAG,CAAC,CAAA;AAC/C,MAAM,eAAe,GAAG,IAAI,MAAM,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAA;AACjD,MAAM,eAAe,GAAG,IAAI,MAAM,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAA;AACjD,MAAM,gBAAgB,GAAG,IAAI,MAAM,CAAC,SAAS,EAAE,GAAG,CAAC,CAAA;AACnD,MAAM,YAAY,GAAG,OAAO,CAAA;AAC5B,MAAM,WAAW,GAAG,MAAM,CAAA;AAC1B,MAAM,YAAY,GAAG,MAAM,CAAA;AAC3B,MAAM,YAAY,GAAG,MAAM,CAAA;AAC3B,MAAM,aAAa,GAAG,MAAM,CAAA;AAE5B,SAAS,OAAO,CAAC,GAAW;IAC1B,OAAO,CAAC,KAAK,CAAC,GAAU,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAA;AACnE,CAAC;AAED,SAAS,YAAY,CAAC,GAAW;IAC/B,OAAO,GAAG;SACP,OAAO,CAAC,YAAY,EAAE,QAAQ,CAAC;SAC/B,OAAO,CAAC,WAAW,EAAE,OAAO,CAAC;SAC7B,OAAO,CAAC,YAAY,EAAE,QAAQ,CAAC;SAC/B,OAAO,CAAC,YAAY,EAAE,QAAQ,CAAC;SAC/B,OAAO,CAAC,aAAa,EAAE,SAAS,CAAC,CAAA;AACtC,CAAC;AAED,SAAS,cAAc,CAAC,GAAW;IACjC,OAAO,GAAG;SACP,OAAO,CAAC,eAAe,EAAE,IAAI,CAAC;SAC9B,OAAO,CAAC,cAAc,EAAE,GAAG,CAAC;SAC5B,OAAO,CAAC,eAAe,EAAE,GAAG,CAAC;SAC7B,OAAO,CAAC,eAAe,EAAE,GAAG,CAAC;SAC7B,OAAO,CAAC,gBAAgB,EAAE,GAAG,CAAC,CAAA;AACnC,CAAC;AAED;;;;GAIG;AACH,SAAS,eAAe,CAAC,GAAW;IAClC,IAAI,CAAC,GAAG,EAAE,CAAC;QACT,OAAO,CAAC,EAAE,CAAC,CAAA;IACb,CAAC;IAED,MAAM,KAAK,GAAa,EAAE,CAAA;IAC1B,MAAM,CAAC,GAAG,IAAA,yBAAQ,EAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAA;IAEjC,IAAI,CAAC,CAAC,EAAE,CAAC;QACP,OAAO,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;IACvB,CAAC;IAED,MAAM,EAAE,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,GAAG,CAAC,CAAA;IAC7B,MAAM,CAAC,GAAG,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;IAExB,CAAC,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,IAAI,GAAG,GAAG,IAAI,GAAG,GAAG,CAAA;IACnC,MAAM,SAAS,GAAG,eAAe,CAAC,IAAI,CAAC,CAAA;IACvC,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;QAChB,CAAC;QAAC,CAAC,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,CAAY,IAAI,SAAS,CAAC,KAAK,EAAE,CAAA;QACjD,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,SAAS,CAAC,CAAA;IAC5B,CAAC;IAED,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC,CAAC,CAAA;IAE1B,OAAO,KAAK,CAAA;AACd,CAAC;AAED,SAAgB,MAAM,CAAC,GAAW;IAChC,IAAI,CAAC,GAAG,EAAE,CAAC;QACT,OAAO,EAAE,CAAA;IACX,CAAC;IAED,oDAAoD;IACpD,oEAAoE;IACpE,sEAAsE;IACtE,6CAA6C;IAC7C,oEAAoE;IACpE,+DAA+D;IAC/D,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,KAAK,IAAI,EAAE,CAAC;QAC7B,GAAG,GAAG,QAAQ,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAA;IAC/B,CAAC;IAED,OAAO,OAAO,CAAC,YAAY,CAAC,GAAG,CAAC,EAAE,IAAI,CAAC,CAAC,GAAG,CAAC,cAAc,CAAC,CAAA;AAC7D,CAAC;AAED,SAAS,OAAO,CAAC,GAAW;IAC1B,OAAO,GAAG,GAAG,GAAG,GAAG,GAAG,CAAA;AACxB,CAAC;AAED,SAAS,QAAQ,CAAC,EAAU;IAC1B,OAAO,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC,CAAA;AAC1B,CAAC;AAED,SAAS,GAAG,CAAC,CAAS,EAAE,CAAS;IAC/B,OAAO,CAAC,IAAI,CAAC,CAAA;AACf,CAAC;AAED,SAAS,GAAG,CAAC,CAAS,EAAE,CAAS;IAC/B,OAAO,CAAC,IAAI,CAAC,CAAA;AACf,CAAC;AAED,SAAS,OAAO,CAAC,GAAW,EAAE,KAAe;IAC3C,uBAAuB;IACvB,MAAM,UAAU,GAAa,EAAE,CAAA;IAE/B,MAAM,CAAC,GAAG,IAAA,yBAAQ,EAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAA;IACjC,IAAI,CAAC,CAAC;QAAE,OAAO,CAAC,GAAG,CAAC,CAAA;IAEpB,yEAAyE;IACzE,MAAM,GAAG,GAAG,CAAC,CAAC,GAAG,CAAA;IACjB,MAAM,IAAI,GAAa,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAA;IAEpE,IAAI,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC;QACtB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;YACrC,MAAM,SAAS,GAAG,GAAG,GAAG,GAAG,GAAG,CAAC,CAAC,IAAI,GAAG,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,CAAA;YACpD,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC,CAAA;QAC5B,CAAC;IACH,CAAC;SAAM,CAAC;QACN,MAAM,iBAAiB,GAAG,gCAAgC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAA;QACvE,MAAM,eAAe,GAAG,sCAAsC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAA;QAC3E,MAAM,UAAU,GAAG,iBAAiB,IAAI,eAAe,CAAA;QACvD,MAAM,SAAS,GAAG,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAA;QAC1C,IAAI,CAAC,UAAU,IAAI,CAAC,SAAS,EAAE,CAAC;YAC9B,SAAS;YACT,IAAI,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC,EAAE,CAAC;gBAC/B,GAAG,GAAG,CAAC,CAAC,GAAG,GAAG,GAAG,GAAG,CAAC,CAAC,IAAI,GAAG,QAAQ,GAAG,CAAC,CAAC,IAAI,CAAA;gBAC9C,OAAO,OAAO,CAAC,GAAG,CAAC,CAAA;YACrB,CAAC;YACD,OAAO,CAAC,GAAG,CAAC,CAAA;QACd,CAAC;QAED,IAAI,CAAW,CAAA;QACf,IAAI,UAAU,EAAE,CAAC;YACf,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,CAAA;QAC1B,CAAC;aAAM,CAAC;YACN,CAAC,GAAG,eAAe,CAAC,CAAC,CAAC,IAAI,CAAC,CAAA;YAC3B,IAAI,CAAC,CAAC,MAAM,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,SAAS,EAAE,CAAC;gBACzC,4BAA4B;gBAC5B,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAA;gBACrC,uDAAuD;gBACvD,qBAAqB;gBACrB,IAAI,CAAC,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;oBACnB,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAA;gBACxC,CAAC;gBACD,oBAAoB;YACtB,CAAC;QACH,CAAC;QAED,kEAAkE;QAClE,uBAAuB;QACvB,IAAI,CAAW,CAAA;QAEf,IAAI,UAAU,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,SAAS,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,SAAS,EAAE,CAAC;YAC3D,MAAM,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;YACvB,MAAM,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;YACvB,MAAM,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAA;YAChD,IAAI,IAAI,GACN,CAAC,CAAC,MAAM,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;YACpE,IAAI,IAAI,GAAG,GAAG,CAAA;YACd,MAAM,OAAO,GAAG,CAAC,GAAG,CAAC,CAAA;YACrB,IAAI,OAAO,EAAE,CAAC;gBACZ,IAAI,IAAI,CAAC,CAAC,CAAA;gBACV,IAAI,GAAG,GAAG,CAAA;YACZ,CAAC;YACD,MAAM,GAAG,GAAG,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAA;YAE5B,CAAC,GAAG,EAAE,CAAA;YAEN,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,IAAI,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC,IAAI,IAAI,EAAE,CAAC;gBACtC,IAAI,CAAC,CAAA;gBACL,IAAI,eAAe,EAAE,CAAC;oBACpB,CAAC,GAAG,MAAM,CAAC,YAAY,CAAC,CAAC,CAAC,CAAA;oBAC1B,IAAI,CAAC,KAAK,IAAI,EAAE,CAAC;wBACf,CAAC,GAAG,EAAE,CAAA;oBACR,CAAC;gBACH,CAAC;qBAAM,CAAC;oBACN,CAAC,GAAG,MAAM,CAAC,CAAC,CAAC,CAAA;oBACb,IAAI,GAAG,EAAE,CAAC;wBACR,MAAM,IAAI,GAAG,KAAK,GAAG,CAAC,CAAC,MAAM,CAAA;wBAC7B,IAAI,IAAI,GAAG,CAAC,EAAE,CAAC;4BACb,MAAM,CAAC,GAAG,IAAI,KAAK,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;4BACvC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;gCACV,CAAC,GAAG,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAA;4BAC1B,CAAC;iCAAM,CAAC;gCACN,CAAC,GAAG,CAAC,GAAG,CAAC,CAAA;4BACX,CAAC;wBACH,CAAC;oBACH,CAAC;gBACH,CAAC;gBACD,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;YACX,CAAC;QACH,CAAC;aAAM,CAAC;YACN,CAAC,GAAG,EAAE,CAAA;YAEN,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;gBAClC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,CAAW,EAAE,KAAK,CAAC,CAAC,CAAA;YACjD,CAAC;QACH,CAAC;QAED,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;YAClC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;gBACrC,MAAM,SAAS,GAAG,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,CAAA;gBACtC,IAAI,CAAC,KAAK,IAAI,UAAU,IAAI,SAAS,EAAE,CAAC;oBACtC,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC,CAAA;gBAC5B,CAAC;YACH,CAAC;QACH,CAAC;IACH,CAAC;IAED,OAAO,UAAU,CAAA;AACnB,CAAC","sourcesContent":["import { balanced } from '@isaacs/balanced-match'\n\nconst escSlash = '\\0SLASH' + Math.random() + '\\0'\nconst escOpen = '\\0OPEN' + Math.random() + '\\0'\nconst escClose = '\\0CLOSE' + Math.random() + '\\0'\nconst escComma = '\\0COMMA' + Math.random() + '\\0'\nconst escPeriod = '\\0PERIOD' + Math.random() + '\\0'\nconst escSlashPattern = new RegExp(escSlash, 'g')\nconst escOpenPattern = new RegExp(escOpen, 'g')\nconst escClosePattern = new RegExp(escClose, 'g')\nconst escCommaPattern = new RegExp(escComma, 'g')\nconst escPeriodPattern = new RegExp(escPeriod, 'g')\nconst slashPattern = /\\\\\\\\/g\nconst openPattern = /\\\\{/g\nconst closePattern = /\\\\}/g\nconst commaPattern = /\\\\,/g\nconst periodPattern = /\\\\./g\n\nfunction numeric(str: string) {\n return !isNaN(str as any) ? parseInt(str, 10) : str.charCodeAt(0)\n}\n\nfunction escapeBraces(str: string) {\n return str\n .replace(slashPattern, escSlash)\n .replace(openPattern, escOpen)\n .replace(closePattern, escClose)\n .replace(commaPattern, escComma)\n .replace(periodPattern, escPeriod)\n}\n\nfunction unescapeBraces(str: string) {\n return str\n .replace(escSlashPattern, '\\\\')\n .replace(escOpenPattern, '{')\n .replace(escClosePattern, '}')\n .replace(escCommaPattern, ',')\n .replace(escPeriodPattern, '.')\n}\n\n/**\n * Basically just str.split(\",\"), but handling cases\n * where we have nested braced sections, which should be\n * treated as individual members, like {a,{b,c},d}\n */\nfunction parseCommaParts(str: string) {\n if (!str) {\n return ['']\n }\n\n const parts: string[] = []\n const m = balanced('{', '}', str)\n\n if (!m) {\n return str.split(',')\n }\n\n const { pre, body, post } = m\n const p = pre.split(',')\n\n p[p.length - 1] += '{' + body + '}'\n const postParts = parseCommaParts(post)\n if (post.length) {\n ;(p[p.length - 1] as string) += postParts.shift()\n p.push.apply(p, postParts)\n }\n\n parts.push.apply(parts, p)\n\n return parts\n}\n\nexport function expand(str: string) {\n if (!str) {\n return []\n }\n\n // I don't know why Bash 4.3 does this, but it does.\n // Anything starting with {} will have the first two bytes preserved\n // but *only* at the top level, so {},a}b will not expand to anything,\n // but a{},b}c will be expanded to [a}c,abc].\n // One could argue that this is a bug in Bash, but since the goal of\n // this module is to match Bash's rules, we escape a leading {}\n if (str.slice(0, 2) === '{}') {\n str = '\\\\{\\\\}' + str.slice(2)\n }\n\n return expand_(escapeBraces(str), true).map(unescapeBraces)\n}\n\nfunction embrace(str: string) {\n return '{' + str + '}'\n}\n\nfunction isPadded(el: string) {\n return /^-?0\\d/.test(el)\n}\n\nfunction lte(i: number, y: number) {\n return i <= y\n}\n\nfunction gte(i: number, y: number) {\n return i >= y\n}\n\nfunction expand_(str: string, isTop?: boolean): string[] {\n /** @type {string[]} */\n const expansions: string[] = []\n\n const m = balanced('{', '}', str)\n if (!m) return [str]\n\n // no need to expand pre, since it is guaranteed to be free of brace-sets\n const pre = m.pre\n const post: string[] = m.post.length ? expand_(m.post, false) : ['']\n\n if (/\\$$/.test(m.pre)) {\n for (let k = 0; k < post.length; k++) {\n const expansion = pre + '{' + m.body + '}' + post[k]\n expansions.push(expansion)\n }\n } else {\n const isNumericSequence = /^-?\\d+\\.\\.-?\\d+(?:\\.\\.-?\\d+)?$/.test(m.body)\n const isAlphaSequence = /^[a-zA-Z]\\.\\.[a-zA-Z](?:\\.\\.-?\\d+)?$/.test(m.body)\n const isSequence = isNumericSequence || isAlphaSequence\n const isOptions = m.body.indexOf(',') >= 0\n if (!isSequence && !isOptions) {\n // {a},b}\n if (m.post.match(/,(?!,).*\\}/)) {\n str = m.pre + '{' + m.body + escClose + m.post\n return expand_(str)\n }\n return [str]\n }\n\n let n: string[]\n if (isSequence) {\n n = m.body.split(/\\.\\./)\n } else {\n n = parseCommaParts(m.body)\n if (n.length === 1 && n[0] !== undefined) {\n // x{{a,b}}y ==> x{a}y x{b}y\n n = expand_(n[0], false).map(embrace)\n //XXX is this necessary? Can't seem to hit it in tests.\n /* c8 ignore start */\n if (n.length === 1) {\n return post.map(p => m.pre + n[0] + p)\n }\n /* c8 ignore stop */\n }\n }\n\n // at this point, n is the parts, and we know it's not a comma set\n // with a single entry.\n let N: string[]\n\n if (isSequence && n[0] !== undefined && n[1] !== undefined) {\n const x = numeric(n[0])\n const y = numeric(n[1])\n const width = Math.max(n[0].length, n[1].length)\n let incr =\n n.length === 3 && n[2] !== undefined ? Math.abs(numeric(n[2])) : 1\n let test = lte\n const reverse = y < x\n if (reverse) {\n incr *= -1\n test = gte\n }\n const pad = n.some(isPadded)\n\n N = []\n\n for (let i = x; test(i, y); i += incr) {\n let c\n if (isAlphaSequence) {\n c = String.fromCharCode(i)\n if (c === '\\\\') {\n c = ''\n }\n } else {\n c = String(i)\n if (pad) {\n const need = width - c.length\n if (need > 0) {\n const z = new Array(need + 1).join('0')\n if (i < 0) {\n c = '-' + z + c.slice(1)\n } else {\n c = z + c\n }\n }\n }\n }\n N.push(c)\n }\n } else {\n N = []\n\n for (let j = 0; j < n.length; j++) {\n N.push.apply(N, expand_(n[j] as string, false))\n }\n }\n\n for (let j = 0; j < N.length; j++) {\n for (let k = 0; k < post.length; k++) {\n const expansion = pre + N[j] + post[k]\n if (!isTop || isSequence || expansion) {\n expansions.push(expansion)\n }\n }\n }\n }\n\n return expansions\n}\n"]} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/brace-expansion/dist/commonjs/package.json b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/brace-expansion/dist/commonjs/package.json new file mode 100644 index 0000000000000000000000000000000000000000..5bbefffbabee392d1855491b84dc0a716b6a3bf2 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/brace-expansion/dist/commonjs/package.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/brace-expansion/dist/esm/index.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/brace-expansion/dist/esm/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c51cda1bb399ab26f2d949c03cceb45ecda66597 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/brace-expansion/dist/esm/index.d.ts @@ -0,0 +1,2 @@ +export declare function expand(str: string): string[]; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/brace-expansion/dist/esm/index.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/brace-expansion/dist/esm/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..27f432d98dd6c9c8749e4d0b0b1e30740330701c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/brace-expansion/dist/esm/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAwEA,wBAAgB,MAAM,CAAC,GAAG,EAAE,MAAM,YAgBjC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/brace-expansion/dist/esm/index.js b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/brace-expansion/dist/esm/index.js new file mode 100644 index 0000000000000000000000000000000000000000..ebb88ed4117c87e40d30ee9418c9b2278435de1c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/brace-expansion/dist/esm/index.js @@ -0,0 +1,193 @@ +import { balanced } from '@isaacs/balanced-match'; +const escSlash = '\0SLASH' + Math.random() + '\0'; +const escOpen = '\0OPEN' + Math.random() + '\0'; +const escClose = '\0CLOSE' + Math.random() + '\0'; +const escComma = '\0COMMA' + Math.random() + '\0'; +const escPeriod = '\0PERIOD' + Math.random() + '\0'; +const escSlashPattern = new RegExp(escSlash, 'g'); +const escOpenPattern = new RegExp(escOpen, 'g'); +const escClosePattern = new RegExp(escClose, 'g'); +const escCommaPattern = new RegExp(escComma, 'g'); +const escPeriodPattern = new RegExp(escPeriod, 'g'); +const slashPattern = /\\\\/g; +const openPattern = /\\{/g; +const closePattern = /\\}/g; +const commaPattern = /\\,/g; +const periodPattern = /\\./g; +function numeric(str) { + return !isNaN(str) ? parseInt(str, 10) : str.charCodeAt(0); +} +function escapeBraces(str) { + return str + .replace(slashPattern, escSlash) + .replace(openPattern, escOpen) + .replace(closePattern, escClose) + .replace(commaPattern, escComma) + .replace(periodPattern, escPeriod); +} +function unescapeBraces(str) { + return str + .replace(escSlashPattern, '\\') + .replace(escOpenPattern, '{') + .replace(escClosePattern, '}') + .replace(escCommaPattern, ',') + .replace(escPeriodPattern, '.'); +} +/** + * Basically just str.split(","), but handling cases + * where we have nested braced sections, which should be + * treated as individual members, like {a,{b,c},d} + */ +function parseCommaParts(str) { + if (!str) { + return ['']; + } + const parts = []; + const m = balanced('{', '}', str); + if (!m) { + return str.split(','); + } + const { pre, body, post } = m; + const p = pre.split(','); + p[p.length - 1] += '{' + body + '}'; + const postParts = parseCommaParts(post); + if (post.length) { + ; + p[p.length - 1] += postParts.shift(); + p.push.apply(p, postParts); + } + parts.push.apply(parts, p); + return parts; +} +export function expand(str) { + if (!str) { + return []; + } + // I don't know why Bash 4.3 does this, but it does. + // Anything starting with {} will have the first two bytes preserved + // but *only* at the top level, so {},a}b will not expand to anything, + // but a{},b}c will be expanded to [a}c,abc]. + // One could argue that this is a bug in Bash, but since the goal of + // this module is to match Bash's rules, we escape a leading {} + if (str.slice(0, 2) === '{}') { + str = '\\{\\}' + str.slice(2); + } + return expand_(escapeBraces(str), true).map(unescapeBraces); +} +function embrace(str) { + return '{' + str + '}'; +} +function isPadded(el) { + return /^-?0\d/.test(el); +} +function lte(i, y) { + return i <= y; +} +function gte(i, y) { + return i >= y; +} +function expand_(str, isTop) { + /** @type {string[]} */ + const expansions = []; + const m = balanced('{', '}', str); + if (!m) + return [str]; + // no need to expand pre, since it is guaranteed to be free of brace-sets + const pre = m.pre; + const post = m.post.length ? expand_(m.post, false) : ['']; + if (/\$$/.test(m.pre)) { + for (let k = 0; k < post.length; k++) { + const expansion = pre + '{' + m.body + '}' + post[k]; + expansions.push(expansion); + } + } + else { + const isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + const isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + const isSequence = isNumericSequence || isAlphaSequence; + const isOptions = m.body.indexOf(',') >= 0; + if (!isSequence && !isOptions) { + // {a},b} + if (m.post.match(/,(?!,).*\}/)) { + str = m.pre + '{' + m.body + escClose + m.post; + return expand_(str); + } + return [str]; + } + let n; + if (isSequence) { + n = m.body.split(/\.\./); + } + else { + n = parseCommaParts(m.body); + if (n.length === 1 && n[0] !== undefined) { + // x{{a,b}}y ==> x{a}y x{b}y + n = expand_(n[0], false).map(embrace); + //XXX is this necessary? Can't seem to hit it in tests. + /* c8 ignore start */ + if (n.length === 1) { + return post.map(p => m.pre + n[0] + p); + } + /* c8 ignore stop */ + } + } + // at this point, n is the parts, and we know it's not a comma set + // with a single entry. + let N; + if (isSequence && n[0] !== undefined && n[1] !== undefined) { + const x = numeric(n[0]); + const y = numeric(n[1]); + const width = Math.max(n[0].length, n[1].length); + let incr = n.length === 3 && n[2] !== undefined ? Math.abs(numeric(n[2])) : 1; + let test = lte; + const reverse = y < x; + if (reverse) { + incr *= -1; + test = gte; + } + const pad = n.some(isPadded); + N = []; + for (let i = x; test(i, y); i += incr) { + let c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === '\\') { + c = ''; + } + } + else { + c = String(i); + if (pad) { + const need = width - c.length; + if (need > 0) { + const z = new Array(need + 1).join('0'); + if (i < 0) { + c = '-' + z + c.slice(1); + } + else { + c = z + c; + } + } + } + } + N.push(c); + } + } + else { + N = []; + for (let j = 0; j < n.length; j++) { + N.push.apply(N, expand_(n[j], false)); + } + } + for (let j = 0; j < N.length; j++) { + for (let k = 0; k < post.length; k++) { + const expansion = pre + N[j] + post[k]; + if (!isTop || isSequence || expansion) { + expansions.push(expansion); + } + } + } + } + return expansions; +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/brace-expansion/dist/esm/index.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/brace-expansion/dist/esm/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..85c33de61a809638b528c565e532fec712531e6b --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/brace-expansion/dist/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,wBAAwB,CAAA;AAEjD,MAAM,QAAQ,GAAG,SAAS,GAAG,IAAI,CAAC,MAAM,EAAE,GAAG,IAAI,CAAA;AACjD,MAAM,OAAO,GAAG,QAAQ,GAAG,IAAI,CAAC,MAAM,EAAE,GAAG,IAAI,CAAA;AAC/C,MAAM,QAAQ,GAAG,SAAS,GAAG,IAAI,CAAC,MAAM,EAAE,GAAG,IAAI,CAAA;AACjD,MAAM,QAAQ,GAAG,SAAS,GAAG,IAAI,CAAC,MAAM,EAAE,GAAG,IAAI,CAAA;AACjD,MAAM,SAAS,GAAG,UAAU,GAAG,IAAI,CAAC,MAAM,EAAE,GAAG,IAAI,CAAA;AACnD,MAAM,eAAe,GAAG,IAAI,MAAM,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAA;AACjD,MAAM,cAAc,GAAG,IAAI,MAAM,CAAC,OAAO,EAAE,GAAG,CAAC,CAAA;AAC/C,MAAM,eAAe,GAAG,IAAI,MAAM,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAA;AACjD,MAAM,eAAe,GAAG,IAAI,MAAM,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAA;AACjD,MAAM,gBAAgB,GAAG,IAAI,MAAM,CAAC,SAAS,EAAE,GAAG,CAAC,CAAA;AACnD,MAAM,YAAY,GAAG,OAAO,CAAA;AAC5B,MAAM,WAAW,GAAG,MAAM,CAAA;AAC1B,MAAM,YAAY,GAAG,MAAM,CAAA;AAC3B,MAAM,YAAY,GAAG,MAAM,CAAA;AAC3B,MAAM,aAAa,GAAG,MAAM,CAAA;AAE5B,SAAS,OAAO,CAAC,GAAW;IAC1B,OAAO,CAAC,KAAK,CAAC,GAAU,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAA;AACnE,CAAC;AAED,SAAS,YAAY,CAAC,GAAW;IAC/B,OAAO,GAAG;SACP,OAAO,CAAC,YAAY,EAAE,QAAQ,CAAC;SAC/B,OAAO,CAAC,WAAW,EAAE,OAAO,CAAC;SAC7B,OAAO,CAAC,YAAY,EAAE,QAAQ,CAAC;SAC/B,OAAO,CAAC,YAAY,EAAE,QAAQ,CAAC;SAC/B,OAAO,CAAC,aAAa,EAAE,SAAS,CAAC,CAAA;AACtC,CAAC;AAED,SAAS,cAAc,CAAC,GAAW;IACjC,OAAO,GAAG;SACP,OAAO,CAAC,eAAe,EAAE,IAAI,CAAC;SAC9B,OAAO,CAAC,cAAc,EAAE,GAAG,CAAC;SAC5B,OAAO,CAAC,eAAe,EAAE,GAAG,CAAC;SAC7B,OAAO,CAAC,eAAe,EAAE,GAAG,CAAC;SAC7B,OAAO,CAAC,gBAAgB,EAAE,GAAG,CAAC,CAAA;AACnC,CAAC;AAED;;;;GAIG;AACH,SAAS,eAAe,CAAC,GAAW;IAClC,IAAI,CAAC,GAAG,EAAE,CAAC;QACT,OAAO,CAAC,EAAE,CAAC,CAAA;IACb,CAAC;IAED,MAAM,KAAK,GAAa,EAAE,CAAA;IAC1B,MAAM,CAAC,GAAG,QAAQ,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAA;IAEjC,IAAI,CAAC,CAAC,EAAE,CAAC;QACP,OAAO,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;IACvB,CAAC;IAED,MAAM,EAAE,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,GAAG,CAAC,CAAA;IAC7B,MAAM,CAAC,GAAG,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;IAExB,CAAC,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,IAAI,GAAG,GAAG,IAAI,GAAG,GAAG,CAAA;IACnC,MAAM,SAAS,GAAG,eAAe,CAAC,IAAI,CAAC,CAAA;IACvC,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;QAChB,CAAC;QAAC,CAAC,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,CAAY,IAAI,SAAS,CAAC,KAAK,EAAE,CAAA;QACjD,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,SAAS,CAAC,CAAA;IAC5B,CAAC;IAED,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC,CAAC,CAAA;IAE1B,OAAO,KAAK,CAAA;AACd,CAAC;AAED,MAAM,UAAU,MAAM,CAAC,GAAW;IAChC,IAAI,CAAC,GAAG,EAAE,CAAC;QACT,OAAO,EAAE,CAAA;IACX,CAAC;IAED,oDAAoD;IACpD,oEAAoE;IACpE,sEAAsE;IACtE,6CAA6C;IAC7C,oEAAoE;IACpE,+DAA+D;IAC/D,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,KAAK,IAAI,EAAE,CAAC;QAC7B,GAAG,GAAG,QAAQ,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAA;IAC/B,CAAC;IAED,OAAO,OAAO,CAAC,YAAY,CAAC,GAAG,CAAC,EAAE,IAAI,CAAC,CAAC,GAAG,CAAC,cAAc,CAAC,CAAA;AAC7D,CAAC;AAED,SAAS,OAAO,CAAC,GAAW;IAC1B,OAAO,GAAG,GAAG,GAAG,GAAG,GAAG,CAAA;AACxB,CAAC;AAED,SAAS,QAAQ,CAAC,EAAU;IAC1B,OAAO,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC,CAAA;AAC1B,CAAC;AAED,SAAS,GAAG,CAAC,CAAS,EAAE,CAAS;IAC/B,OAAO,CAAC,IAAI,CAAC,CAAA;AACf,CAAC;AAED,SAAS,GAAG,CAAC,CAAS,EAAE,CAAS;IAC/B,OAAO,CAAC,IAAI,CAAC,CAAA;AACf,CAAC;AAED,SAAS,OAAO,CAAC,GAAW,EAAE,KAAe;IAC3C,uBAAuB;IACvB,MAAM,UAAU,GAAa,EAAE,CAAA;IAE/B,MAAM,CAAC,GAAG,QAAQ,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAA;IACjC,IAAI,CAAC,CAAC;QAAE,OAAO,CAAC,GAAG,CAAC,CAAA;IAEpB,yEAAyE;IACzE,MAAM,GAAG,GAAG,CAAC,CAAC,GAAG,CAAA;IACjB,MAAM,IAAI,GAAa,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAA;IAEpE,IAAI,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC;QACtB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;YACrC,MAAM,SAAS,GAAG,GAAG,GAAG,GAAG,GAAG,CAAC,CAAC,IAAI,GAAG,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,CAAA;YACpD,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC,CAAA;QAC5B,CAAC;IACH,CAAC;SAAM,CAAC;QACN,MAAM,iBAAiB,GAAG,gCAAgC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAA;QACvE,MAAM,eAAe,GAAG,sCAAsC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAA;QAC3E,MAAM,UAAU,GAAG,iBAAiB,IAAI,eAAe,CAAA;QACvD,MAAM,SAAS,GAAG,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAA;QAC1C,IAAI,CAAC,UAAU,IAAI,CAAC,SAAS,EAAE,CAAC;YAC9B,SAAS;YACT,IAAI,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC,EAAE,CAAC;gBAC/B,GAAG,GAAG,CAAC,CAAC,GAAG,GAAG,GAAG,GAAG,CAAC,CAAC,IAAI,GAAG,QAAQ,GAAG,CAAC,CAAC,IAAI,CAAA;gBAC9C,OAAO,OAAO,CAAC,GAAG,CAAC,CAAA;YACrB,CAAC;YACD,OAAO,CAAC,GAAG,CAAC,CAAA;QACd,CAAC;QAED,IAAI,CAAW,CAAA;QACf,IAAI,UAAU,EAAE,CAAC;YACf,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,CAAA;QAC1B,CAAC;aAAM,CAAC;YACN,CAAC,GAAG,eAAe,CAAC,CAAC,CAAC,IAAI,CAAC,CAAA;YAC3B,IAAI,CAAC,CAAC,MAAM,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,SAAS,EAAE,CAAC;gBACzC,4BAA4B;gBAC5B,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAA;gBACrC,uDAAuD;gBACvD,qBAAqB;gBACrB,IAAI,CAAC,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;oBACnB,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAA;gBACxC,CAAC;gBACD,oBAAoB;YACtB,CAAC;QACH,CAAC;QAED,kEAAkE;QAClE,uBAAuB;QACvB,IAAI,CAAW,CAAA;QAEf,IAAI,UAAU,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,SAAS,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,SAAS,EAAE,CAAC;YAC3D,MAAM,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;YACvB,MAAM,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;YACvB,MAAM,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAA;YAChD,IAAI,IAAI,GACN,CAAC,CAAC,MAAM,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;YACpE,IAAI,IAAI,GAAG,GAAG,CAAA;YACd,MAAM,OAAO,GAAG,CAAC,GAAG,CAAC,CAAA;YACrB,IAAI,OAAO,EAAE,CAAC;gBACZ,IAAI,IAAI,CAAC,CAAC,CAAA;gBACV,IAAI,GAAG,GAAG,CAAA;YACZ,CAAC;YACD,MAAM,GAAG,GAAG,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAA;YAE5B,CAAC,GAAG,EAAE,CAAA;YAEN,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,IAAI,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC,IAAI,IAAI,EAAE,CAAC;gBACtC,IAAI,CAAC,CAAA;gBACL,IAAI,eAAe,EAAE,CAAC;oBACpB,CAAC,GAAG,MAAM,CAAC,YAAY,CAAC,CAAC,CAAC,CAAA;oBAC1B,IAAI,CAAC,KAAK,IAAI,EAAE,CAAC;wBACf,CAAC,GAAG,EAAE,CAAA;oBACR,CAAC;gBACH,CAAC;qBAAM,CAAC;oBACN,CAAC,GAAG,MAAM,CAAC,CAAC,CAAC,CAAA;oBACb,IAAI,GAAG,EAAE,CAAC;wBACR,MAAM,IAAI,GAAG,KAAK,GAAG,CAAC,CAAC,MAAM,CAAA;wBAC7B,IAAI,IAAI,GAAG,CAAC,EAAE,CAAC;4BACb,MAAM,CAAC,GAAG,IAAI,KAAK,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;4BACvC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;gCACV,CAAC,GAAG,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAA;4BAC1B,CAAC;iCAAM,CAAC;gCACN,CAAC,GAAG,CAAC,GAAG,CAAC,CAAA;4BACX,CAAC;wBACH,CAAC;oBACH,CAAC;gBACH,CAAC;gBACD,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;YACX,CAAC;QACH,CAAC;aAAM,CAAC;YACN,CAAC,GAAG,EAAE,CAAA;YAEN,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;gBAClC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,CAAW,EAAE,KAAK,CAAC,CAAC,CAAA;YACjD,CAAC;QACH,CAAC;QAED,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;YAClC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;gBACrC,MAAM,SAAS,GAAG,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,CAAA;gBACtC,IAAI,CAAC,KAAK,IAAI,UAAU,IAAI,SAAS,EAAE,CAAC;oBACtC,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC,CAAA;gBAC5B,CAAC;YACH,CAAC;QACH,CAAC;IACH,CAAC;IAED,OAAO,UAAU,CAAA;AACnB,CAAC","sourcesContent":["import { balanced } from '@isaacs/balanced-match'\n\nconst escSlash = '\\0SLASH' + Math.random() + '\\0'\nconst escOpen = '\\0OPEN' + Math.random() + '\\0'\nconst escClose = '\\0CLOSE' + Math.random() + '\\0'\nconst escComma = '\\0COMMA' + Math.random() + '\\0'\nconst escPeriod = '\\0PERIOD' + Math.random() + '\\0'\nconst escSlashPattern = new RegExp(escSlash, 'g')\nconst escOpenPattern = new RegExp(escOpen, 'g')\nconst escClosePattern = new RegExp(escClose, 'g')\nconst escCommaPattern = new RegExp(escComma, 'g')\nconst escPeriodPattern = new RegExp(escPeriod, 'g')\nconst slashPattern = /\\\\\\\\/g\nconst openPattern = /\\\\{/g\nconst closePattern = /\\\\}/g\nconst commaPattern = /\\\\,/g\nconst periodPattern = /\\\\./g\n\nfunction numeric(str: string) {\n return !isNaN(str as any) ? parseInt(str, 10) : str.charCodeAt(0)\n}\n\nfunction escapeBraces(str: string) {\n return str\n .replace(slashPattern, escSlash)\n .replace(openPattern, escOpen)\n .replace(closePattern, escClose)\n .replace(commaPattern, escComma)\n .replace(periodPattern, escPeriod)\n}\n\nfunction unescapeBraces(str: string) {\n return str\n .replace(escSlashPattern, '\\\\')\n .replace(escOpenPattern, '{')\n .replace(escClosePattern, '}')\n .replace(escCommaPattern, ',')\n .replace(escPeriodPattern, '.')\n}\n\n/**\n * Basically just str.split(\",\"), but handling cases\n * where we have nested braced sections, which should be\n * treated as individual members, like {a,{b,c},d}\n */\nfunction parseCommaParts(str: string) {\n if (!str) {\n return ['']\n }\n\n const parts: string[] = []\n const m = balanced('{', '}', str)\n\n if (!m) {\n return str.split(',')\n }\n\n const { pre, body, post } = m\n const p = pre.split(',')\n\n p[p.length - 1] += '{' + body + '}'\n const postParts = parseCommaParts(post)\n if (post.length) {\n ;(p[p.length - 1] as string) += postParts.shift()\n p.push.apply(p, postParts)\n }\n\n parts.push.apply(parts, p)\n\n return parts\n}\n\nexport function expand(str: string) {\n if (!str) {\n return []\n }\n\n // I don't know why Bash 4.3 does this, but it does.\n // Anything starting with {} will have the first two bytes preserved\n // but *only* at the top level, so {},a}b will not expand to anything,\n // but a{},b}c will be expanded to [a}c,abc].\n // One could argue that this is a bug in Bash, but since the goal of\n // this module is to match Bash's rules, we escape a leading {}\n if (str.slice(0, 2) === '{}') {\n str = '\\\\{\\\\}' + str.slice(2)\n }\n\n return expand_(escapeBraces(str), true).map(unescapeBraces)\n}\n\nfunction embrace(str: string) {\n return '{' + str + '}'\n}\n\nfunction isPadded(el: string) {\n return /^-?0\\d/.test(el)\n}\n\nfunction lte(i: number, y: number) {\n return i <= y\n}\n\nfunction gte(i: number, y: number) {\n return i >= y\n}\n\nfunction expand_(str: string, isTop?: boolean): string[] {\n /** @type {string[]} */\n const expansions: string[] = []\n\n const m = balanced('{', '}', str)\n if (!m) return [str]\n\n // no need to expand pre, since it is guaranteed to be free of brace-sets\n const pre = m.pre\n const post: string[] = m.post.length ? expand_(m.post, false) : ['']\n\n if (/\\$$/.test(m.pre)) {\n for (let k = 0; k < post.length; k++) {\n const expansion = pre + '{' + m.body + '}' + post[k]\n expansions.push(expansion)\n }\n } else {\n const isNumericSequence = /^-?\\d+\\.\\.-?\\d+(?:\\.\\.-?\\d+)?$/.test(m.body)\n const isAlphaSequence = /^[a-zA-Z]\\.\\.[a-zA-Z](?:\\.\\.-?\\d+)?$/.test(m.body)\n const isSequence = isNumericSequence || isAlphaSequence\n const isOptions = m.body.indexOf(',') >= 0\n if (!isSequence && !isOptions) {\n // {a},b}\n if (m.post.match(/,(?!,).*\\}/)) {\n str = m.pre + '{' + m.body + escClose + m.post\n return expand_(str)\n }\n return [str]\n }\n\n let n: string[]\n if (isSequence) {\n n = m.body.split(/\\.\\./)\n } else {\n n = parseCommaParts(m.body)\n if (n.length === 1 && n[0] !== undefined) {\n // x{{a,b}}y ==> x{a}y x{b}y\n n = expand_(n[0], false).map(embrace)\n //XXX is this necessary? Can't seem to hit it in tests.\n /* c8 ignore start */\n if (n.length === 1) {\n return post.map(p => m.pre + n[0] + p)\n }\n /* c8 ignore stop */\n }\n }\n\n // at this point, n is the parts, and we know it's not a comma set\n // with a single entry.\n let N: string[]\n\n if (isSequence && n[0] !== undefined && n[1] !== undefined) {\n const x = numeric(n[0])\n const y = numeric(n[1])\n const width = Math.max(n[0].length, n[1].length)\n let incr =\n n.length === 3 && n[2] !== undefined ? Math.abs(numeric(n[2])) : 1\n let test = lte\n const reverse = y < x\n if (reverse) {\n incr *= -1\n test = gte\n }\n const pad = n.some(isPadded)\n\n N = []\n\n for (let i = x; test(i, y); i += incr) {\n let c\n if (isAlphaSequence) {\n c = String.fromCharCode(i)\n if (c === '\\\\') {\n c = ''\n }\n } else {\n c = String(i)\n if (pad) {\n const need = width - c.length\n if (need > 0) {\n const z = new Array(need + 1).join('0')\n if (i < 0) {\n c = '-' + z + c.slice(1)\n } else {\n c = z + c\n }\n }\n }\n }\n N.push(c)\n }\n } else {\n N = []\n\n for (let j = 0; j < n.length; j++) {\n N.push.apply(N, expand_(n[j] as string, false))\n }\n }\n\n for (let j = 0; j < N.length; j++) {\n for (let k = 0; k < post.length; k++) {\n const expansion = pre + N[j] + post[k]\n if (!isTop || isSequence || expansion) {\n expansions.push(expansion)\n }\n }\n }\n }\n\n return expansions\n}\n"]} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/brace-expansion/dist/esm/package.json b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/brace-expansion/dist/esm/package.json new file mode 100644 index 0000000000000000000000000000000000000000..3dbc1ca591c0557e35b6004aeba250e6a70b56e3 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/brace-expansion/dist/esm/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/brace-expansion/package.json b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/brace-expansion/package.json new file mode 100644 index 0000000000000000000000000000000000000000..cf1035688398b9b4d136c21b9de1e9ace6089b5c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/brace-expansion/package.json @@ -0,0 +1,71 @@ +{ + "name": "@isaacs/brace-expansion", + "description": "Brace expansion as known from sh/bash", + "version": "5.0.0", + "files": [ + "dist" + ], + "exports": { + "./package.json": "./package.json", + ".": { + "import": { + "types": "./dist/esm/index.d.ts", + "default": "./dist/esm/index.js" + }, + "require": { + "types": "./dist/commonjs/index.d.ts", + "default": "./dist/commonjs/index.js" + } + } + }, + "type": "module", + "scripts": { + "preversion": "npm test", + "postversion": "npm publish", + "prepublishOnly": "git push origin --follow-tags", + "prepare": "tshy", + "pretest": "npm run prepare", + "presnap": "npm run prepare", + "test": "tap", + "snap": "tap", + "format": "prettier --write . --loglevel warn", + "benchmark": "node benchmark/index.js", + "typedoc": "typedoc --tsconfig .tshy/esm.json ./src/*.ts" + }, + "prettier": { + "semi": false, + "printWidth": 80, + "tabWidth": 2, + "useTabs": false, + "singleQuote": true, + "jsxSingleQuote": false, + "bracketSameLine": true, + "arrowParens": "avoid", + "endOfLine": "lf" + }, + "devDependencies": { + "@types/brace-expansion": "^1.1.2", + "@types/node": "^24.0.0", + "mkdirp": "^3.0.1", + "prettier": "^3.3.2", + "tap": "^21.1.0", + "tshy": "^3.0.2", + "typedoc": "^0.28.5" + }, + "dependencies": { + "@isaacs/balanced-match": "^4.0.1" + }, + "license": "MIT", + "engines": { + "node": "20 || >=22" + }, + "tshy": { + "exports": { + "./package.json": "./package.json", + ".": "./src/index.ts" + } + }, + "main": "./dist/commonjs/index.js", + "types": "./dist/commonjs/index.d.ts", + "module": "./dist/esm/index.js" +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/cliui/LICENSE.txt b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/cliui/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..c7e27478a3eff8862ca150f10d1b93a5ac866af2 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/cliui/LICENSE.txt @@ -0,0 +1,14 @@ +Copyright (c) 2015, Contributors + +Permission to use, copy, modify, and/or distribute this software +for any purpose with or without fee is hereby granted, provided +that the above copyright notice and this permission notice +appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE +LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES +OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/cliui/README.md b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/cliui/README.md new file mode 100644 index 0000000000000000000000000000000000000000..488064267d56947677a7785195035a5aa475cd6f --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/cliui/README.md @@ -0,0 +1,143 @@ +# @isaacs/cliui + +Temporary fork of [cliui](http://npm.im/cliui). + +![ci](https://github.com/yargs/cliui/workflows/ci/badge.svg) +[![NPM version](https://img.shields.io/npm/v/cliui.svg)](https://www.npmjs.com/package/cliui) +[![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org) +![nycrc config on GitHub](https://img.shields.io/nycrc/yargs/cliui) + +easily create complex multi-column command-line-interfaces. + +## Example + +```js +const ui = require('cliui')() + +ui.div('Usage: $0 [command] [options]') + +ui.div({ + text: 'Options:', + padding: [2, 0, 1, 0] +}) + +ui.div( + { + text: "-f, --file", + width: 20, + padding: [0, 4, 0, 4] + }, + { + text: "the file to load." + + chalk.green("(if this description is long it wraps).") + , + width: 20 + }, + { + text: chalk.red("[required]"), + align: 'right' + } +) + +console.log(ui.toString()) +``` + +## Deno/ESM Support + +As of `v7` `cliui` supports [Deno](https://github.com/denoland/deno) and +[ESM](https://nodejs.org/api/esm.html#esm_ecmascript_modules): + +```typescript +import cliui from "https://deno.land/x/cliui/deno.ts"; + +const ui = cliui({}) + +ui.div('Usage: $0 [command] [options]') + +ui.div({ + text: 'Options:', + padding: [2, 0, 1, 0] +}) + +ui.div({ + text: "-f, --file", + width: 20, + padding: [0, 4, 0, 4] +}) + +console.log(ui.toString()) +``` + + + +## Layout DSL + +cliui exposes a simple layout DSL: + +If you create a single `ui.div`, passing a string rather than an +object: + +* `\n`: characters will be interpreted as new rows. +* `\t`: characters will be interpreted as new columns. +* `\s`: characters will be interpreted as padding. + +**as an example...** + +```js +var ui = require('./')({ + width: 60 +}) + +ui.div( + 'Usage: node ./bin/foo.js\n' + + ' \t provide a regex\n' + + ' \t provide a glob\t [required]' +) + +console.log(ui.toString()) +``` + +**will output:** + +```shell +Usage: node ./bin/foo.js + provide a regex + provide a glob [required] +``` + +## Methods + +```js +cliui = require('cliui') +``` + +### cliui({width: integer}) + +Specify the maximum width of the UI being generated. +If no width is provided, cliui will try to get the current window's width and use it, and if that doesn't work, width will be set to `80`. + +### cliui({wrap: boolean}) + +Enable or disable the wrapping of text in a column. + +### cliui.div(column, column, column) + +Create a row with any number of columns, a column +can either be a string, or an object with the following +options: + +* **text:** some text to place in the column. +* **width:** the width of a column. +* **align:** alignment, `right` or `center`. +* **padding:** `[top, right, bottom, left]`. +* **border:** should a border be placed around the div? + +### cliui.span(column, column, column) + +Similar to `div`, except the next row will be appended without +a new line being created. + +### cliui.resetOutput() + +Resets the UI elements of the current cliui instance, maintaining the values +set for `width` and `wrap`. diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/cliui/build/index.cjs b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/cliui/build/index.cjs new file mode 100644 index 0000000000000000000000000000000000000000..aca2b8507ac0f34d914ea50268da62158cf935cf --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/cliui/build/index.cjs @@ -0,0 +1,317 @@ +'use strict'; + +const align = { + right: alignRight, + center: alignCenter +}; +const top = 0; +const right = 1; +const bottom = 2; +const left = 3; +class UI { + constructor(opts) { + var _a; + this.width = opts.width; + /* c8 ignore start */ + this.wrap = (_a = opts.wrap) !== null && _a !== void 0 ? _a : true; + /* c8 ignore stop */ + this.rows = []; + } + span(...args) { + const cols = this.div(...args); + cols.span = true; + } + resetOutput() { + this.rows = []; + } + div(...args) { + if (args.length === 0) { + this.div(''); + } + if (this.wrap && this.shouldApplyLayoutDSL(...args) && typeof args[0] === 'string') { + return this.applyLayoutDSL(args[0]); + } + const cols = args.map(arg => { + if (typeof arg === 'string') { + return this.colFromString(arg); + } + return arg; + }); + this.rows.push(cols); + return cols; + } + shouldApplyLayoutDSL(...args) { + return args.length === 1 && typeof args[0] === 'string' && + /[\t\n]/.test(args[0]); + } + applyLayoutDSL(str) { + const rows = str.split('\n').map(row => row.split('\t')); + let leftColumnWidth = 0; + // simple heuristic for layout, make sure the + // second column lines up along the left-hand. + // don't allow the first column to take up more + // than 50% of the screen. + rows.forEach(columns => { + if (columns.length > 1 && mixin.stringWidth(columns[0]) > leftColumnWidth) { + leftColumnWidth = Math.min(Math.floor(this.width * 0.5), mixin.stringWidth(columns[0])); + } + }); + // generate a table: + // replacing ' ' with padding calculations. + // using the algorithmically generated width. + rows.forEach(columns => { + this.div(...columns.map((r, i) => { + return { + text: r.trim(), + padding: this.measurePadding(r), + width: (i === 0 && columns.length > 1) ? leftColumnWidth : undefined + }; + })); + }); + return this.rows[this.rows.length - 1]; + } + colFromString(text) { + return { + text, + padding: this.measurePadding(text) + }; + } + measurePadding(str) { + // measure padding without ansi escape codes + const noAnsi = mixin.stripAnsi(str); + return [0, noAnsi.match(/\s*$/)[0].length, 0, noAnsi.match(/^\s*/)[0].length]; + } + toString() { + const lines = []; + this.rows.forEach(row => { + this.rowToString(row, lines); + }); + // don't display any lines with the + // hidden flag set. + return lines + .filter(line => !line.hidden) + .map(line => line.text) + .join('\n'); + } + rowToString(row, lines) { + this.rasterize(row).forEach((rrow, r) => { + let str = ''; + rrow.forEach((col, c) => { + const { width } = row[c]; // the width with padding. + const wrapWidth = this.negatePadding(row[c]); // the width without padding. + let ts = col; // temporary string used during alignment/padding. + if (wrapWidth > mixin.stringWidth(col)) { + ts += ' '.repeat(wrapWidth - mixin.stringWidth(col)); + } + // align the string within its column. + if (row[c].align && row[c].align !== 'left' && this.wrap) { + const fn = align[row[c].align]; + ts = fn(ts, wrapWidth); + if (mixin.stringWidth(ts) < wrapWidth) { + /* c8 ignore start */ + const w = width || 0; + /* c8 ignore stop */ + ts += ' '.repeat(w - mixin.stringWidth(ts) - 1); + } + } + // apply border and padding to string. + const padding = row[c].padding || [0, 0, 0, 0]; + if (padding[left]) { + str += ' '.repeat(padding[left]); + } + str += addBorder(row[c], ts, '| '); + str += ts; + str += addBorder(row[c], ts, ' |'); + if (padding[right]) { + str += ' '.repeat(padding[right]); + } + // if prior row is span, try to render the + // current row on the prior line. + if (r === 0 && lines.length > 0) { + str = this.renderInline(str, lines[lines.length - 1]); + } + }); + // remove trailing whitespace. + lines.push({ + text: str.replace(/ +$/, ''), + span: row.span + }); + }); + return lines; + } + // if the full 'source' can render in + // the target line, do so. + renderInline(source, previousLine) { + const match = source.match(/^ */); + /* c8 ignore start */ + const leadingWhitespace = match ? match[0].length : 0; + /* c8 ignore stop */ + const target = previousLine.text; + const targetTextWidth = mixin.stringWidth(target.trimEnd()); + if (!previousLine.span) { + return source; + } + // if we're not applying wrapping logic, + // just always append to the span. + if (!this.wrap) { + previousLine.hidden = true; + return target + source; + } + if (leadingWhitespace < targetTextWidth) { + return source; + } + previousLine.hidden = true; + return target.trimEnd() + ' '.repeat(leadingWhitespace - targetTextWidth) + source.trimStart(); + } + rasterize(row) { + const rrows = []; + const widths = this.columnWidths(row); + let wrapped; + // word wrap all columns, and create + // a data-structure that is easy to rasterize. + row.forEach((col, c) => { + // leave room for left and right padding. + col.width = widths[c]; + if (this.wrap) { + wrapped = mixin.wrap(col.text, this.negatePadding(col), { hard: true }).split('\n'); + } + else { + wrapped = col.text.split('\n'); + } + if (col.border) { + wrapped.unshift('.' + '-'.repeat(this.negatePadding(col) + 2) + '.'); + wrapped.push("'" + '-'.repeat(this.negatePadding(col) + 2) + "'"); + } + // add top and bottom padding. + if (col.padding) { + wrapped.unshift(...new Array(col.padding[top] || 0).fill('')); + wrapped.push(...new Array(col.padding[bottom] || 0).fill('')); + } + wrapped.forEach((str, r) => { + if (!rrows[r]) { + rrows.push([]); + } + const rrow = rrows[r]; + for (let i = 0; i < c; i++) { + if (rrow[i] === undefined) { + rrow.push(''); + } + } + rrow.push(str); + }); + }); + return rrows; + } + negatePadding(col) { + /* c8 ignore start */ + let wrapWidth = col.width || 0; + /* c8 ignore stop */ + if (col.padding) { + wrapWidth -= (col.padding[left] || 0) + (col.padding[right] || 0); + } + if (col.border) { + wrapWidth -= 4; + } + return wrapWidth; + } + columnWidths(row) { + if (!this.wrap) { + return row.map(col => { + return col.width || mixin.stringWidth(col.text); + }); + } + let unset = row.length; + let remainingWidth = this.width; + // column widths can be set in config. + const widths = row.map(col => { + if (col.width) { + unset--; + remainingWidth -= col.width; + return col.width; + } + return undefined; + }); + // any unset widths should be calculated. + /* c8 ignore start */ + const unsetWidth = unset ? Math.floor(remainingWidth / unset) : 0; + /* c8 ignore stop */ + return widths.map((w, i) => { + if (w === undefined) { + return Math.max(unsetWidth, _minWidth(row[i])); + } + return w; + }); + } +} +function addBorder(col, ts, style) { + if (col.border) { + if (/[.']-+[.']/.test(ts)) { + return ''; + } + if (ts.trim().length !== 0) { + return style; + } + return ' '; + } + return ''; +} +// calculates the minimum width of +// a column, based on padding preferences. +function _minWidth(col) { + const padding = col.padding || []; + const minWidth = 1 + (padding[left] || 0) + (padding[right] || 0); + if (col.border) { + return minWidth + 4; + } + return minWidth; +} +function getWindowWidth() { + /* c8 ignore start */ + if (typeof process === 'object' && process.stdout && process.stdout.columns) { + return process.stdout.columns; + } + return 80; +} +/* c8 ignore stop */ +function alignRight(str, width) { + str = str.trim(); + const strWidth = mixin.stringWidth(str); + if (strWidth < width) { + return ' '.repeat(width - strWidth) + str; + } + return str; +} +function alignCenter(str, width) { + str = str.trim(); + const strWidth = mixin.stringWidth(str); + /* c8 ignore start */ + if (strWidth >= width) { + return str; + } + /* c8 ignore stop */ + return ' '.repeat((width - strWidth) >> 1) + str; +} +let mixin; +function cliui(opts, _mixin) { + mixin = _mixin; + return new UI({ + /* c8 ignore start */ + width: (opts === null || opts === void 0 ? void 0 : opts.width) || getWindowWidth(), + wrap: opts === null || opts === void 0 ? void 0 : opts.wrap + /* c8 ignore stop */ + }); +} + +// Bootstrap cliui with CommonJS dependencies: +const stringWidth = require('string-width-cjs'); +const stripAnsi = require('strip-ansi-cjs'); +const wrap = require('wrap-ansi-cjs'); +function ui(opts) { + return cliui(opts, { + stringWidth, + stripAnsi, + wrap + }); +} + +module.exports = ui; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/cliui/index.mjs b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/cliui/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..5177519af372221f252cda2d75ac66385f44f753 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/cliui/index.mjs @@ -0,0 +1,14 @@ +// Bootstrap cliui with ESM dependencies: +import { cliui } from './build/lib/index.js' + +import stringWidth from 'string-width' +import stripAnsi from 'strip-ansi' +import wrap from 'wrap-ansi' + +export default function ui (opts) { + return cliui(opts, { + stringWidth, + stripAnsi, + wrap + }) +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/cliui/package.json b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/cliui/package.json new file mode 100644 index 0000000000000000000000000000000000000000..7a952532def5d499f626274e49fa8cc3032b6429 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/@isaacs/cliui/package.json @@ -0,0 +1,86 @@ +{ + "name": "@isaacs/cliui", + "version": "8.0.2", + "description": "easily create complex multi-column command-line-interfaces", + "main": "build/index.cjs", + "exports": { + ".": [ + { + "import": "./index.mjs", + "require": "./build/index.cjs" + }, + "./build/index.cjs" + ] + }, + "type": "module", + "module": "./index.mjs", + "scripts": { + "check": "standardx '**/*.ts' && standardx '**/*.js' && standardx '**/*.cjs'", + "fix": "standardx --fix '**/*.ts' && standardx --fix '**/*.js' && standardx --fix '**/*.cjs'", + "pretest": "rimraf build && tsc -p tsconfig.test.json && cross-env NODE_ENV=test npm run build:cjs", + "test": "c8 mocha ./test/*.cjs", + "test:esm": "c8 mocha ./test/**/*.mjs", + "postest": "check", + "coverage": "c8 report --check-coverage", + "precompile": "rimraf build", + "compile": "tsc", + "postcompile": "npm run build:cjs", + "build:cjs": "rollup -c", + "prepare": "npm run compile" + }, + "repository": "yargs/cliui", + "standard": { + "ignore": [ + "**/example/**" + ], + "globals": [ + "it" + ] + }, + "keywords": [ + "cli", + "command-line", + "layout", + "design", + "console", + "wrap", + "table" + ], + "author": "Ben Coe ", + "license": "ISC", + "dependencies": { + "string-width": "^5.1.2", + "string-width-cjs": "npm:string-width@^4.2.0", + "strip-ansi": "^7.0.1", + "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", + "wrap-ansi": "^8.1.0", + "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" + }, + "devDependencies": { + "@types/node": "^14.0.27", + "@typescript-eslint/eslint-plugin": "^4.0.0", + "@typescript-eslint/parser": "^4.0.0", + "c8": "^7.3.0", + "chai": "^4.2.0", + "chalk": "^4.1.0", + "cross-env": "^7.0.2", + "eslint": "^7.6.0", + "eslint-plugin-import": "^2.22.0", + "eslint-plugin-node": "^11.1.0", + "gts": "^3.0.0", + "mocha": "^10.0.0", + "rimraf": "^3.0.2", + "rollup": "^2.23.1", + "rollup-plugin-ts": "^3.0.2", + "standardx": "^7.0.0", + "typescript": "^4.0.0" + }, + "files": [ + "build", + "index.mjs", + "!*.d.ts" + ], + "engines": { + "node": ">=12" + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/anymatch/LICENSE b/novas/novacore-zephyr/claude-code-router/node_modules/anymatch/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..491766ca79a0382e5fc4e370c853201bb641e0d8 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/anymatch/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) 2019 Elan Shanker, Paul Miller (https://paulmillr.com) + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/anymatch/README.md b/novas/novacore-zephyr/claude-code-router/node_modules/anymatch/README.md new file mode 100644 index 0000000000000000000000000000000000000000..1dd67f53446ccbad8d17662fee69dd3c46531ba4 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/anymatch/README.md @@ -0,0 +1,87 @@ +anymatch [![Build Status](https://travis-ci.org/micromatch/anymatch.svg?branch=master)](https://travis-ci.org/micromatch/anymatch) [![Coverage Status](https://img.shields.io/coveralls/micromatch/anymatch.svg?branch=master)](https://coveralls.io/r/micromatch/anymatch?branch=master) +====== +Javascript module to match a string against a regular expression, glob, string, +or function that takes the string as an argument and returns a truthy or falsy +value. The matcher can also be an array of any or all of these. Useful for +allowing a very flexible user-defined config to define things like file paths. + +__Note: This module has Bash-parity, please be aware that Windows-style backslashes are not supported as separators. See https://github.com/micromatch/micromatch#backslashes for more information.__ + + +Usage +----- +```sh +npm install anymatch +``` + +#### anymatch(matchers, testString, [returnIndex], [options]) +* __matchers__: (_Array|String|RegExp|Function_) +String to be directly matched, string with glob patterns, regular expression +test, function that takes the testString as an argument and returns a truthy +value if it should be matched, or an array of any number and mix of these types. +* __testString__: (_String|Array_) The string to test against the matchers. If +passed as an array, the first element of the array will be used as the +`testString` for non-function matchers, while the entire array will be applied +as the arguments for function matchers. +* __options__: (_Object_ [optional]_) Any of the [picomatch](https://github.com/micromatch/picomatch#options) options. + * __returnIndex__: (_Boolean [optional]_) If true, return the array index of +the first matcher that that testString matched, or -1 if no match, instead of a +boolean result. + +```js +const anymatch = require('anymatch'); + +const matchers = [ 'path/to/file.js', 'path/anyjs/**/*.js', /foo.js$/, string => string.includes('bar') && string.length > 10 ] ; + +anymatch(matchers, 'path/to/file.js'); // true +anymatch(matchers, 'path/anyjs/baz.js'); // true +anymatch(matchers, 'path/to/foo.js'); // true +anymatch(matchers, 'path/to/bar.js'); // true +anymatch(matchers, 'bar.js'); // false + +// returnIndex = true +anymatch(matchers, 'foo.js', {returnIndex: true}); // 2 +anymatch(matchers, 'path/anyjs/foo.js', {returnIndex: true}); // 1 + +// any picomatc + +// using globs to match directories and their children +anymatch('node_modules', 'node_modules'); // true +anymatch('node_modules', 'node_modules/somelib/index.js'); // false +anymatch('node_modules/**', 'node_modules/somelib/index.js'); // true +anymatch('node_modules/**', '/absolute/path/to/node_modules/somelib/index.js'); // false +anymatch('**/node_modules/**', '/absolute/path/to/node_modules/somelib/index.js'); // true + +const matcher = anymatch(matchers); +['foo.js', 'bar.js'].filter(matcher); // [ 'foo.js' ] +anymatch master* ❯ + +``` + +#### anymatch(matchers) +You can also pass in only your matcher(s) to get a curried function that has +already been bound to the provided matching criteria. This can be used as an +`Array#filter` callback. + +```js +var matcher = anymatch(matchers); + +matcher('path/to/file.js'); // true +matcher('path/anyjs/baz.js', true); // 1 + +['foo.js', 'bar.js'].filter(matcher); // ['foo.js'] +``` + +Changelog +---------- +[See release notes page on GitHub](https://github.com/micromatch/anymatch/releases) + +- **v3.0:** Removed `startIndex` and `endIndex` arguments. Node 8.x-only. +- **v2.0:** [micromatch](https://github.com/jonschlinkert/micromatch) moves away from minimatch-parity and inline with Bash. This includes handling backslashes differently (see https://github.com/micromatch/micromatch#backslashes for more information). +- **v1.2:** anymatch uses [micromatch](https://github.com/jonschlinkert/micromatch) +for glob pattern matching. Issues with glob pattern matching should be +reported directly to the [micromatch issue tracker](https://github.com/jonschlinkert/micromatch/issues). + +License +------- +[ISC](https://raw.github.com/micromatch/anymatch/master/LICENSE) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/anymatch/index.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/anymatch/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3ef7eaaddd8b5f479aeae707206d8163f82ada94 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/anymatch/index.d.ts @@ -0,0 +1,20 @@ +type AnymatchFn = (testString: string) => boolean; +type AnymatchPattern = string|RegExp|AnymatchFn; +type AnymatchMatcher = AnymatchPattern|AnymatchPattern[] +type AnymatchTester = { + (testString: string|any[], returnIndex: true): number; + (testString: string|any[]): boolean; +} + +type PicomatchOptions = {dot: boolean}; + +declare const anymatch: { + (matchers: AnymatchMatcher): AnymatchTester; + (matchers: AnymatchMatcher, testString: null, returnIndex: true | PicomatchOptions): AnymatchTester; + (matchers: AnymatchMatcher, testString: string|any[], returnIndex: true | PicomatchOptions): number; + (matchers: AnymatchMatcher, testString: string|any[]): boolean; +} + +export {AnymatchMatcher as Matcher} +export {AnymatchTester as Tester} +export default anymatch diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/anymatch/index.js b/novas/novacore-zephyr/claude-code-router/node_modules/anymatch/index.js new file mode 100644 index 0000000000000000000000000000000000000000..8eb73e9c9a61d2c642d3c5f44a2fe4cd6cd04615 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/anymatch/index.js @@ -0,0 +1,104 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { value: true }); + +const picomatch = require('picomatch'); +const normalizePath = require('normalize-path'); + +/** + * @typedef {(testString: string) => boolean} AnymatchFn + * @typedef {string|RegExp|AnymatchFn} AnymatchPattern + * @typedef {AnymatchPattern|AnymatchPattern[]} AnymatchMatcher + */ +const BANG = '!'; +const DEFAULT_OPTIONS = {returnIndex: false}; +const arrify = (item) => Array.isArray(item) ? item : [item]; + +/** + * @param {AnymatchPattern} matcher + * @param {object} options + * @returns {AnymatchFn} + */ +const createPattern = (matcher, options) => { + if (typeof matcher === 'function') { + return matcher; + } + if (typeof matcher === 'string') { + const glob = picomatch(matcher, options); + return (string) => matcher === string || glob(string); + } + if (matcher instanceof RegExp) { + return (string) => matcher.test(string); + } + return (string) => false; +}; + +/** + * @param {Array} patterns + * @param {Array} negPatterns + * @param {String|Array} args + * @param {Boolean} returnIndex + * @returns {boolean|number} + */ +const matchPatterns = (patterns, negPatterns, args, returnIndex) => { + const isList = Array.isArray(args); + const _path = isList ? args[0] : args; + if (!isList && typeof _path !== 'string') { + throw new TypeError('anymatch: second argument must be a string: got ' + + Object.prototype.toString.call(_path)) + } + const path = normalizePath(_path, false); + + for (let index = 0; index < negPatterns.length; index++) { + const nglob = negPatterns[index]; + if (nglob(path)) { + return returnIndex ? -1 : false; + } + } + + const applied = isList && [path].concat(args.slice(1)); + for (let index = 0; index < patterns.length; index++) { + const pattern = patterns[index]; + if (isList ? pattern(...applied) : pattern(path)) { + return returnIndex ? index : true; + } + } + + return returnIndex ? -1 : false; +}; + +/** + * @param {AnymatchMatcher} matchers + * @param {Array|string} testString + * @param {object} options + * @returns {boolean|number|Function} + */ +const anymatch = (matchers, testString, options = DEFAULT_OPTIONS) => { + if (matchers == null) { + throw new TypeError('anymatch: specify first argument'); + } + const opts = typeof options === 'boolean' ? {returnIndex: options} : options; + const returnIndex = opts.returnIndex || false; + + // Early cache for matchers. + const mtchers = arrify(matchers); + const negatedGlobs = mtchers + .filter(item => typeof item === 'string' && item.charAt(0) === BANG) + .map(item => item.slice(1)) + .map(item => picomatch(item, opts)); + const patterns = mtchers + .filter(item => typeof item !== 'string' || (typeof item === 'string' && item.charAt(0) !== BANG)) + .map(matcher => createPattern(matcher, opts)); + + if (testString == null) { + return (testString, ri = false) => { + const returnIndex = typeof ri === 'boolean' ? ri : false; + return matchPatterns(patterns, negatedGlobs, testString, returnIndex); + } + } + + return matchPatterns(patterns, negatedGlobs, testString, returnIndex); +}; + +anymatch.default = anymatch; +module.exports = anymatch; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/anymatch/package.json b/novas/novacore-zephyr/claude-code-router/node_modules/anymatch/package.json new file mode 100644 index 0000000000000000000000000000000000000000..2cb2307e49efc4770c0e8364e4387105162956dd --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/anymatch/package.json @@ -0,0 +1,48 @@ +{ + "name": "anymatch", + "version": "3.1.3", + "description": "Matches strings against configurable strings, globs, regular expressions, and/or functions", + "files": [ + "index.js", + "index.d.ts" + ], + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + }, + "author": { + "name": "Elan Shanker", + "url": "https://github.com/es128" + }, + "license": "ISC", + "homepage": "https://github.com/micromatch/anymatch", + "repository": { + "type": "git", + "url": "https://github.com/micromatch/anymatch" + }, + "keywords": [ + "match", + "any", + "string", + "file", + "fs", + "list", + "glob", + "regex", + "regexp", + "regular", + "expression", + "function" + ], + "scripts": { + "test": "nyc mocha", + "mocha": "mocha" + }, + "devDependencies": { + "mocha": "^6.1.3", + "nyc": "^14.0.0" + }, + "engines": { + "node": ">= 8" + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/argparse/CHANGELOG.md b/novas/novacore-zephyr/claude-code-router/node_modules/argparse/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..a43c628ccc2ecf2d41b29b14704f2caff4b7f91d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/argparse/CHANGELOG.md @@ -0,0 +1,185 @@ +1.0.10 / 2018-02-15 +------------------ + +- Use .concat instead of + for arrays, #122. + + +1.0.9 / 2016-09-29 +------------------ + +- Rerelease after 1.0.8 - deps cleanup. + + +1.0.8 / 2016-09-29 +------------------ + +- Maintenance (deps bump, fix node 6.5+ tests, coverage report). + + +1.0.7 / 2016-03-17 +------------------ + +- Teach `addArgument` to accept string arg names. #97, @tomxtobin. + + +1.0.6 / 2016-02-06 +------------------ + +- Maintenance: moved to eslint & updated CS. + + +1.0.5 / 2016-02-05 +------------------ + +- Removed lodash dependency to significantly reduce install size. + Thanks to @mourner. + + +1.0.4 / 2016-01-17 +------------------ + +- Maintenance: lodash update to 4.0.0. + + +1.0.3 / 2015-10-27 +------------------ + +- Fix parse `=` in args: `--examplepath="C:\myfolder\env=x64"`. #84, @CatWithApple. + + +1.0.2 / 2015-03-22 +------------------ + +- Relaxed lodash version dependency. + + +1.0.1 / 2015-02-20 +------------------ + +- Changed dependencies to be compatible with ancient nodejs. + + +1.0.0 / 2015-02-19 +------------------ + +- Maintenance release. +- Replaced `underscore` with `lodash`. +- Bumped version to 1.0.0 to better reflect semver meaning. +- HISTORY.md -> CHANGELOG.md + + +0.1.16 / 2013-12-01 +------------------- + +- Maintenance release. Updated dependencies and docs. + + +0.1.15 / 2013-05-13 +------------------- + +- Fixed #55, @trebor89 + + +0.1.14 / 2013-05-12 +------------------- + +- Fixed #62, @maxtaco + + +0.1.13 / 2013-04-08 +------------------- + +- Added `.npmignore` to reduce package size + + +0.1.12 / 2013-02-10 +------------------- + +- Fixed conflictHandler (#46), @hpaulj + + +0.1.11 / 2013-02-07 +------------------- + +- Multiple bugfixes, @hpaulj +- Added 70+ tests (ported from python), @hpaulj +- Added conflictHandler, @applepicke +- Added fromfilePrefixChar, @hpaulj + + +0.1.10 / 2012-12-30 +------------------- + +- Added [mutual exclusion](http://docs.python.org/dev/library/argparse.html#mutual-exclusion) + support, thanks to @hpaulj +- Fixed options check for `storeConst` & `appendConst` actions, thanks to @hpaulj + + +0.1.9 / 2012-12-27 +------------------ + +- Fixed option dest interferens with other options (issue #23), thanks to @hpaulj +- Fixed default value behavior with `*` positionals, thanks to @hpaulj +- Improve `getDefault()` behavior, thanks to @hpaulj +- Imrove negative argument parsing, thanks to @hpaulj + + +0.1.8 / 2012-12-01 +------------------ + +- Fixed parser parents (issue #19), thanks to @hpaulj +- Fixed negative argument parse (issue #20), thanks to @hpaulj + + +0.1.7 / 2012-10-14 +------------------ + +- Fixed 'choices' argument parse (issue #16) +- Fixed stderr output (issue #15) + + +0.1.6 / 2012-09-09 +------------------ + +- Fixed check for conflict of options (thanks to @tomxtobin) + + +0.1.5 / 2012-09-03 +------------------ + +- Fix parser #setDefaults method (thanks to @tomxtobin) + + +0.1.4 / 2012-07-30 +------------------ + +- Fixed pseudo-argument support (thanks to @CGamesPlay) +- Fixed addHelp default (should be true), if not set (thanks to @benblank) + + +0.1.3 / 2012-06-27 +------------------ + +- Fixed formatter api name: Formatter -> HelpFormatter + + +0.1.2 / 2012-05-29 +------------------ + +- Added basic tests +- Removed excess whitespace in help +- Fixed error reporting, when parcer with subcommands + called with empty arguments + + +0.1.1 / 2012-05-23 +------------------ + +- Fixed line wrapping in help formatter +- Added better error reporting on invalid arguments + + +0.1.0 / 2012-05-16 +------------------ + +- First release. diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/argparse/LICENSE b/novas/novacore-zephyr/claude-code-router/node_modules/argparse/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1afdae5584056a7a33e9ebf747979baf6cac762a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/argparse/LICENSE @@ -0,0 +1,21 @@ +(The MIT License) + +Copyright (C) 2012 by Vitaly Puzrin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/argparse/README.md b/novas/novacore-zephyr/claude-code-router/node_modules/argparse/README.md new file mode 100644 index 0000000000000000000000000000000000000000..7fa6c40503e56ad3afed1a26c2e8ee0b74f0eeef --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/argparse/README.md @@ -0,0 +1,257 @@ +argparse +======== + +[![Build Status](https://secure.travis-ci.org/nodeca/argparse.svg?branch=master)](http://travis-ci.org/nodeca/argparse) +[![NPM version](https://img.shields.io/npm/v/argparse.svg)](https://www.npmjs.org/package/argparse) + +CLI arguments parser for node.js. Javascript port of python's +[argparse](http://docs.python.org/dev/library/argparse.html) module +(original version 3.2). That's a full port, except some very rare options, +recorded in issue tracker. + +**NB. Difference with original.** + +- Method names changed to camelCase. See [generated docs](http://nodeca.github.com/argparse/). +- Use `defaultValue` instead of `default`. +- Use `argparse.Const.REMAINDER` instead of `argparse.REMAINDER`, and + similarly for constant values `OPTIONAL`, `ZERO_OR_MORE`, and `ONE_OR_MORE` + (aliases for `nargs` values `'?'`, `'*'`, `'+'`, respectively), and + `SUPPRESS`. + + +Example +======= + +test.js file: + +```javascript +#!/usr/bin/env node +'use strict'; + +var ArgumentParser = require('../lib/argparse').ArgumentParser; +var parser = new ArgumentParser({ + version: '0.0.1', + addHelp:true, + description: 'Argparse example' +}); +parser.addArgument( + [ '-f', '--foo' ], + { + help: 'foo bar' + } +); +parser.addArgument( + [ '-b', '--bar' ], + { + help: 'bar foo' + } +); +parser.addArgument( + '--baz', + { + help: 'baz bar' + } +); +var args = parser.parseArgs(); +console.dir(args); +``` + +Display help: + +``` +$ ./test.js -h +usage: example.js [-h] [-v] [-f FOO] [-b BAR] [--baz BAZ] + +Argparse example + +Optional arguments: + -h, --help Show this help message and exit. + -v, --version Show program's version number and exit. + -f FOO, --foo FOO foo bar + -b BAR, --bar BAR bar foo + --baz BAZ baz bar +``` + +Parse arguments: + +``` +$ ./test.js -f=3 --bar=4 --baz 5 +{ foo: '3', bar: '4', baz: '5' } +``` + +More [examples](https://github.com/nodeca/argparse/tree/master/examples). + + +ArgumentParser objects +====================== + +``` +new ArgumentParser({parameters hash}); +``` + +Creates a new ArgumentParser object. + +**Supported params:** + +- ```description``` - Text to display before the argument help. +- ```epilog``` - Text to display after the argument help. +- ```addHelp``` - Add a -h/–help option to the parser. (default: true) +- ```argumentDefault``` - Set the global default value for arguments. (default: null) +- ```parents``` - A list of ArgumentParser objects whose arguments should also be included. +- ```prefixChars``` - The set of characters that prefix optional arguments. (default: ‘-‘) +- ```formatterClass``` - A class for customizing the help output. +- ```prog``` - The name of the program (default: `path.basename(process.argv[1])`) +- ```usage``` - The string describing the program usage (default: generated) +- ```conflictHandler``` - Usually unnecessary, defines strategy for resolving conflicting optionals. + +**Not supported yet** + +- ```fromfilePrefixChars``` - The set of characters that prefix files from which additional arguments should be read. + + +Details in [original ArgumentParser guide](http://docs.python.org/dev/library/argparse.html#argumentparser-objects) + + +addArgument() method +==================== + +``` +ArgumentParser.addArgument(name or flag or [name] or [flags...], {options}) +``` + +Defines how a single command-line argument should be parsed. + +- ```name or flag or [name] or [flags...]``` - Either a positional name + (e.g., `'foo'`), a single option (e.g., `'-f'` or `'--foo'`), an array + of a single positional name (e.g., `['foo']`), or an array of options + (e.g., `['-f', '--foo']`). + +Options: + +- ```action``` - The basic type of action to be taken when this argument is encountered at the command line. +- ```nargs```- The number of command-line arguments that should be consumed. +- ```constant``` - A constant value required by some action and nargs selections. +- ```defaultValue``` - The value produced if the argument is absent from the command line. +- ```type``` - The type to which the command-line argument should be converted. +- ```choices``` - A container of the allowable values for the argument. +- ```required``` - Whether or not the command-line option may be omitted (optionals only). +- ```help``` - A brief description of what the argument does. +- ```metavar``` - A name for the argument in usage messages. +- ```dest``` - The name of the attribute to be added to the object returned by parseArgs(). + +Details in [original add_argument guide](http://docs.python.org/dev/library/argparse.html#the-add-argument-method) + + +Action (some details) +================ + +ArgumentParser objects associate command-line arguments with actions. +These actions can do just about anything with the command-line arguments associated +with them, though most actions simply add an attribute to the object returned by +parseArgs(). The action keyword argument specifies how the command-line arguments +should be handled. The supported actions are: + +- ```store``` - Just stores the argument’s value. This is the default action. +- ```storeConst``` - Stores value, specified by the const keyword argument. + (Note that the const keyword argument defaults to the rather unhelpful None.) + The 'storeConst' action is most commonly used with optional arguments, that + specify some sort of flag. +- ```storeTrue``` and ```storeFalse``` - Stores values True and False + respectively. These are special cases of 'storeConst'. +- ```append``` - Stores a list, and appends each argument value to the list. + This is useful to allow an option to be specified multiple times. +- ```appendConst``` - Stores a list, and appends value, specified by the + const keyword argument to the list. (Note, that the const keyword argument defaults + is None.) The 'appendConst' action is typically used when multiple arguments need + to store constants to the same list. +- ```count``` - Counts the number of times a keyword argument occurs. For example, + used for increasing verbosity levels. +- ```help``` - Prints a complete help message for all the options in the current + parser and then exits. By default a help action is automatically added to the parser. + See ArgumentParser for details of how the output is created. +- ```version``` - Prints version information and exit. Expects a `version=` + keyword argument in the addArgument() call. + +Details in [original action guide](http://docs.python.org/dev/library/argparse.html#action) + + +Sub-commands +============ + +ArgumentParser.addSubparsers() + +Many programs split their functionality into a number of sub-commands, for +example, the svn program can invoke sub-commands like `svn checkout`, `svn update`, +and `svn commit`. Splitting up functionality this way can be a particularly good +idea when a program performs several different functions which require different +kinds of command-line arguments. `ArgumentParser` supports creation of such +sub-commands with `addSubparsers()` method. The `addSubparsers()` method is +normally called with no arguments and returns an special action object. +This object has a single method `addParser()`, which takes a command name and +any `ArgumentParser` constructor arguments, and returns an `ArgumentParser` object +that can be modified as usual. + +Example: + +sub_commands.js +```javascript +#!/usr/bin/env node +'use strict'; + +var ArgumentParser = require('../lib/argparse').ArgumentParser; +var parser = new ArgumentParser({ + version: '0.0.1', + addHelp:true, + description: 'Argparse examples: sub-commands', +}); + +var subparsers = parser.addSubparsers({ + title:'subcommands', + dest:"subcommand_name" +}); + +var bar = subparsers.addParser('c1', {addHelp:true}); +bar.addArgument( + [ '-f', '--foo' ], + { + action: 'store', + help: 'foo3 bar3' + } +); +var bar = subparsers.addParser( + 'c2', + {aliases:['co'], addHelp:true} +); +bar.addArgument( + [ '-b', '--bar' ], + { + action: 'store', + type: 'int', + help: 'foo3 bar3' + } +); + +var args = parser.parseArgs(); +console.dir(args); + +``` + +Details in [original sub-commands guide](http://docs.python.org/dev/library/argparse.html#sub-commands) + + +Contributors +============ + +- [Eugene Shkuropat](https://github.com/shkuropat) +- [Paul Jacobson](https://github.com/hpaulj) + +[others](https://github.com/nodeca/argparse/graphs/contributors) + +License +======= + +Copyright (c) 2012 [Vitaly Puzrin](https://github.com/puzrin). +Released under the MIT license. See +[LICENSE](https://github.com/nodeca/argparse/blob/master/LICENSE) for details. + + diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/argparse/index.js b/novas/novacore-zephyr/claude-code-router/node_modules/argparse/index.js new file mode 100644 index 0000000000000000000000000000000000000000..3bbc143200483c06ce8cdc5b8fef406bdabf2268 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/argparse/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./lib/argparse'); diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/argparse/package.json b/novas/novacore-zephyr/claude-code-router/node_modules/argparse/package.json new file mode 100644 index 0000000000000000000000000000000000000000..62fba0a9fcfc87c9a43eddb159767ec906a9d2d2 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/argparse/package.json @@ -0,0 +1,34 @@ +{ + "name": "argparse", + "description": "Very powerful CLI arguments parser. Native port of argparse - python's options parsing library", + "version": "1.0.10", + "keywords": [ + "cli", + "parser", + "argparse", + "option", + "args" + ], + "contributors": [ + "Eugene Shkuropat", + "Paul Jacobson" + ], + "files": [ + "index.js", + "lib/" + ], + "license": "MIT", + "repository": "nodeca/argparse", + "scripts": { + "test": "make test" + }, + "dependencies": { + "sprintf-js": "~1.0.2" + }, + "devDependencies": { + "eslint": "^2.13.1", + "istanbul": "^0.4.5", + "mocha": "^3.1.0", + "ndoc": "^5.0.1" + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/babel-preset-current-node-syntax/LICENSE b/novas/novacore-zephyr/claude-code-router/node_modules/babel-preset-current-node-syntax/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..7f09addabdb8110cfca9311d41c5f6e5ab8b792c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/babel-preset-current-node-syntax/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2020 Nicolò Ribaudo and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/babel-preset-current-node-syntax/README.md b/novas/novacore-zephyr/claude-code-router/node_modules/babel-preset-current-node-syntax/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d6b42a0dba876dd264e8b513c96a79ca078ebdbe --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/babel-preset-current-node-syntax/README.md @@ -0,0 +1,30 @@ +# `babel-preset-current-node-syntax` + +> A Babel preset that enables parsing of proposals supported by the current Node.js version. + +## Installation + +If you are using yarn: +``` +yarn add --dev babel-preset-current-node-syntax +``` + +If you are using npm: +``` +npm install --save-dev babel-preset-current-node-syntax +``` + +## Contributing + +PRs are welcome! The codebase is so small that I didn't setup a linter, but try +to match the style of the existing code. + +You can run tests with the following command: +``` +yarn node test/index.js +``` + +The `test/fixtures.json` file contains a bunch of syntax tests, alongside with +the minimum supported node version for each of them. Babel should throw on +older versions, without support for that given syntax. +All the tests are run using `@babel/parser@7.0.0`. diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/babel-preset-current-node-syntax/package.json b/novas/novacore-zephyr/claude-code-router/node_modules/babel-preset-current-node-syntax/package.json new file mode 100644 index 0000000000000000000000000000000000000000..1960aa096ff7970867d3229f3470b21ae2b0fc4a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/babel-preset-current-node-syntax/package.json @@ -0,0 +1,46 @@ +{ + "name": "babel-preset-current-node-syntax", + "version": "1.2.0", + "description": "A Babel preset that enables parsing of proposals supported by the current Node.js version.", + "main": "src/index.js", + "repository": { + "type": "git", + "url": "https://github.com/nicolo-ribaudo/babel-preset-current-node-syntax.git" + }, + "author": { + "name": "Nicolò Ribaudo", + "url": "https://github.com/nicolo-ribaudo" + }, + "scripts": { + "test": "node ./test/index.js" + }, + "dependencies": { + "@babel/plugin-syntax-async-generators": "^7.8.4", + "@babel/plugin-syntax-bigint": "^7.8.3", + "@babel/plugin-syntax-class-properties": "^7.12.13", + "@babel/plugin-syntax-class-static-block": "^7.14.5", + "@babel/plugin-syntax-import-attributes": "^7.24.7", + "@babel/plugin-syntax-import-meta": "^7.10.4", + "@babel/plugin-syntax-json-strings": "^7.8.3", + "@babel/plugin-syntax-logical-assignment-operators": "^7.10.4", + "@babel/plugin-syntax-nullish-coalescing-operator": "^7.8.3", + "@babel/plugin-syntax-numeric-separator": "^7.10.4", + "@babel/plugin-syntax-object-rest-spread": "^7.8.3", + "@babel/plugin-syntax-optional-catch-binding": "^7.8.3", + "@babel/plugin-syntax-optional-chaining": "^7.8.3", + "@babel/plugin-syntax-private-property-in-object": "^7.14.5", + "@babel/plugin-syntax-top-level-await": "^7.14.5" + }, + "peerDependencies": { + "@babel/core": "^7.0.0 || ^8.0.0-0" + }, + "devDependencies": { + "@babel/core": "7.25.2", + "@babel/core-8": "npm:@babel/core@^8.0.0-beta.1", + "@babel/parser-7.0.0": "npm:@babel/parser@7.0.0", + "@babel/parser-7.12.0": "npm:@babel/parser@7.12.0", + "@babel/parser-7.22.0": "npm:@babel/parser@7.22.0", + "@babel/parser-7.9.0": "npm:@babel/parser@7.9.0" + }, + "license": "MIT" +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/balanced-match/LICENSE.md b/novas/novacore-zephyr/claude-code-router/node_modules/balanced-match/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..2cdc8e4148cc0aa1f788b25dbec4b22878644cdf --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/balanced-match/LICENSE.md @@ -0,0 +1,21 @@ +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.com> + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/balanced-match/README.md b/novas/novacore-zephyr/claude-code-router/node_modules/balanced-match/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d2a48b6b49f2cf17358262f911b997121d1c2a31 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/balanced-match/README.md @@ -0,0 +1,97 @@ +# balanced-match + +Match balanced string pairs, like `{` and `}` or `` and ``. Supports regular expressions as well! + +[![build status](https://secure.travis-ci.org/juliangruber/balanced-match.svg)](http://travis-ci.org/juliangruber/balanced-match) +[![downloads](https://img.shields.io/npm/dm/balanced-match.svg)](https://www.npmjs.org/package/balanced-match) + +[![testling badge](https://ci.testling.com/juliangruber/balanced-match.png)](https://ci.testling.com/juliangruber/balanced-match) + +## Example + +Get the first matching pair of braces: + +```js +var balanced = require('balanced-match'); + +console.log(balanced('{', '}', 'pre{in{nested}}post')); +console.log(balanced('{', '}', 'pre{first}between{second}post')); +console.log(balanced(/\s+\{\s+/, /\s+\}\s+/, 'pre { in{nest} } post')); +``` + +The matches are: + +```bash +$ node example.js +{ start: 3, end: 14, pre: 'pre', body: 'in{nested}', post: 'post' } +{ start: 3, + end: 9, + pre: 'pre', + body: 'first', + post: 'between{second}post' } +{ start: 3, end: 17, pre: 'pre', body: 'in{nest}', post: 'post' } +``` + +## API + +### var m = balanced(a, b, str) + +For the first non-nested matching pair of `a` and `b` in `str`, return an +object with those keys: + +* **start** the index of the first match of `a` +* **end** the index of the matching `b` +* **pre** the preamble, `a` and `b` not included +* **body** the match, `a` and `b` not included +* **post** the postscript, `a` and `b` not included + +If there's no match, `undefined` will be returned. + +If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `['{', 'a', '']` and `{a}}` will match `['', 'a', '}']`. + +### var r = balanced.range(a, b, str) + +For the first non-nested matching pair of `a` and `b` in `str`, return an +array with indexes: `[ , ]`. + +If there's no match, `undefined` will be returned. + +If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `[ 1, 3 ]` and `{a}}` will match `[0, 2]`. + +## Installation + +With [npm](https://npmjs.org) do: + +```bash +npm install balanced-match +``` + +## Security contact information + +To report a security vulnerability, please use the +[Tidelift security contact](https://tidelift.com/security). +Tidelift will coordinate the fix and disclosure. + +## License + +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.com> + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/balanced-match/index.js b/novas/novacore-zephyr/claude-code-router/node_modules/balanced-match/index.js new file mode 100644 index 0000000000000000000000000000000000000000..c67a64608df7f4d8e126c0a8eff2cc4a3d837e71 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/balanced-match/index.js @@ -0,0 +1,62 @@ +'use strict'; +module.exports = balanced; +function balanced(a, b, str) { + if (a instanceof RegExp) a = maybeMatch(a, str); + if (b instanceof RegExp) b = maybeMatch(b, str); + + var r = range(a, b, str); + + return r && { + start: r[0], + end: r[1], + pre: str.slice(0, r[0]), + body: str.slice(r[0] + a.length, r[1]), + post: str.slice(r[1] + b.length) + }; +} + +function maybeMatch(reg, str) { + var m = str.match(reg); + return m ? m[0] : null; +} + +balanced.range = range; +function range(a, b, str) { + var begs, beg, left, right, result; + var ai = str.indexOf(a); + var bi = str.indexOf(b, ai + 1); + var i = ai; + + if (ai >= 0 && bi > 0) { + if(a===b) { + return [ai, bi]; + } + begs = []; + left = str.length; + + while (i >= 0 && !result) { + if (i == ai) { + begs.push(i); + ai = str.indexOf(a, i + 1); + } else if (begs.length == 1) { + result = [ begs.pop(), bi ]; + } else { + beg = begs.pop(); + if (beg < left) { + left = beg; + right = bi; + } + + bi = str.indexOf(b, i + 1); + } + + i = ai < bi && ai >= 0 ? ai : bi; + } + + if (begs.length) { + result = [ left, right ]; + } + } + + return result; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/balanced-match/package.json b/novas/novacore-zephyr/claude-code-router/node_modules/balanced-match/package.json new file mode 100644 index 0000000000000000000000000000000000000000..ce6073e0403b5a9aeef19a91624ad0256f5e61b8 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/balanced-match/package.json @@ -0,0 +1,48 @@ +{ + "name": "balanced-match", + "description": "Match balanced character pairs, like \"{\" and \"}\"", + "version": "1.0.2", + "repository": { + "type": "git", + "url": "git://github.com/juliangruber/balanced-match.git" + }, + "homepage": "https://github.com/juliangruber/balanced-match", + "main": "index.js", + "scripts": { + "test": "tape test/test.js", + "bench": "matcha test/bench.js" + }, + "devDependencies": { + "matcha": "^0.7.0", + "tape": "^4.6.0" + }, + "keywords": [ + "match", + "regexp", + "test", + "balanced", + "parse" + ], + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "license": "MIT", + "testling": { + "files": "test/*.js", + "browsers": [ + "ie/8..latest", + "firefox/20..latest", + "firefox/nightly", + "chrome/25..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2..latest" + ] + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/brace-expansion/LICENSE b/novas/novacore-zephyr/claude-code-router/node_modules/brace-expansion/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..de3226673c3874b1c6506db022393c753495655c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/brace-expansion/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2013 Julian Gruber + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/brace-expansion/README.md b/novas/novacore-zephyr/claude-code-router/node_modules/brace-expansion/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6b4e0e16409152451eb2b55e083a88e3396c23b1 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/brace-expansion/README.md @@ -0,0 +1,129 @@ +# brace-expansion + +[Brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html), +as known from sh/bash, in JavaScript. + +[![build status](https://secure.travis-ci.org/juliangruber/brace-expansion.svg)](http://travis-ci.org/juliangruber/brace-expansion) +[![downloads](https://img.shields.io/npm/dm/brace-expansion.svg)](https://www.npmjs.org/package/brace-expansion) +[![Greenkeeper badge](https://badges.greenkeeper.io/juliangruber/brace-expansion.svg)](https://greenkeeper.io/) + +[![testling badge](https://ci.testling.com/juliangruber/brace-expansion.png)](https://ci.testling.com/juliangruber/brace-expansion) + +## Example + +```js +var expand = require('brace-expansion'); + +expand('file-{a,b,c}.jpg') +// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] + +expand('-v{,,}') +// => ['-v', '-v', '-v'] + +expand('file{0..2}.jpg') +// => ['file0.jpg', 'file1.jpg', 'file2.jpg'] + +expand('file-{a..c}.jpg') +// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] + +expand('file{2..0}.jpg') +// => ['file2.jpg', 'file1.jpg', 'file0.jpg'] + +expand('file{0..4..2}.jpg') +// => ['file0.jpg', 'file2.jpg', 'file4.jpg'] + +expand('file-{a..e..2}.jpg') +// => ['file-a.jpg', 'file-c.jpg', 'file-e.jpg'] + +expand('file{00..10..5}.jpg') +// => ['file00.jpg', 'file05.jpg', 'file10.jpg'] + +expand('{{A..C},{a..c}}') +// => ['A', 'B', 'C', 'a', 'b', 'c'] + +expand('ppp{,config,oe{,conf}}') +// => ['ppp', 'pppconfig', 'pppoe', 'pppoeconf'] +``` + +## API + +```js +var expand = require('brace-expansion'); +``` + +### var expanded = expand(str) + +Return an array of all possible and valid expansions of `str`. If none are +found, `[str]` is returned. + +Valid expansions are: + +```js +/^(.*,)+(.+)?$/ +// {a,b,...} +``` + +A comma separated list of options, like `{a,b}` or `{a,{b,c}}` or `{,a,}`. + +```js +/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ +// {x..y[..incr]} +``` + +A numeric sequence from `x` to `y` inclusive, with optional increment. +If `x` or `y` start with a leading `0`, all the numbers will be padded +to have equal length. Negative numbers and backwards iteration work too. + +```js +/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ +// {x..y[..incr]} +``` + +An alphabetic sequence from `x` to `y` inclusive, with optional increment. +`x` and `y` must be exactly one character, and if given, `incr` must be a +number. + +For compatibility reasons, the string `${` is not eligible for brace expansion. + +## Installation + +With [npm](https://npmjs.org) do: + +```bash +npm install brace-expansion +``` + +## Contributors + +- [Julian Gruber](https://github.com/juliangruber) +- [Isaac Z. Schlueter](https://github.com/isaacs) + +## Sponsors + +This module is proudly supported by my [Sponsors](https://github.com/juliangruber/sponsors)! + +Do you want to support modules like this to improve their quality, stability and weigh in on new features? Then please consider donating to my [Patreon](https://www.patreon.com/juliangruber). Not sure how much of my modules you're using? Try [feross/thanks](https://github.com/feross/thanks)! + +## License + +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.com> + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/brace-expansion/index.js b/novas/novacore-zephyr/claude-code-router/node_modules/brace-expansion/index.js new file mode 100644 index 0000000000000000000000000000000000000000..bd19fe685f68822df8d00bde928b5494c53cca74 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/brace-expansion/index.js @@ -0,0 +1,201 @@ +var concatMap = require('concat-map'); +var balanced = require('balanced-match'); + +module.exports = expandTop; + +var escSlash = '\0SLASH'+Math.random()+'\0'; +var escOpen = '\0OPEN'+Math.random()+'\0'; +var escClose = '\0CLOSE'+Math.random()+'\0'; +var escComma = '\0COMMA'+Math.random()+'\0'; +var escPeriod = '\0PERIOD'+Math.random()+'\0'; + +function numeric(str) { + return parseInt(str, 10) == str + ? parseInt(str, 10) + : str.charCodeAt(0); +} + +function escapeBraces(str) { + return str.split('\\\\').join(escSlash) + .split('\\{').join(escOpen) + .split('\\}').join(escClose) + .split('\\,').join(escComma) + .split('\\.').join(escPeriod); +} + +function unescapeBraces(str) { + return str.split(escSlash).join('\\') + .split(escOpen).join('{') + .split(escClose).join('}') + .split(escComma).join(',') + .split(escPeriod).join('.'); +} + + +// Basically just str.split(","), but handling cases +// where we have nested braced sections, which should be +// treated as individual members, like {a,{b,c},d} +function parseCommaParts(str) { + if (!str) + return ['']; + + var parts = []; + var m = balanced('{', '}', str); + + if (!m) + return str.split(','); + + var pre = m.pre; + var body = m.body; + var post = m.post; + var p = pre.split(','); + + p[p.length-1] += '{' + body + '}'; + var postParts = parseCommaParts(post); + if (post.length) { + p[p.length-1] += postParts.shift(); + p.push.apply(p, postParts); + } + + parts.push.apply(parts, p); + + return parts; +} + +function expandTop(str) { + if (!str) + return []; + + // I don't know why Bash 4.3 does this, but it does. + // Anything starting with {} will have the first two bytes preserved + // but *only* at the top level, so {},a}b will not expand to anything, + // but a{},b}c will be expanded to [a}c,abc]. + // One could argue that this is a bug in Bash, but since the goal of + // this module is to match Bash's rules, we escape a leading {} + if (str.substr(0, 2) === '{}') { + str = '\\{\\}' + str.substr(2); + } + + return expand(escapeBraces(str), true).map(unescapeBraces); +} + +function identity(e) { + return e; +} + +function embrace(str) { + return '{' + str + '}'; +} +function isPadded(el) { + return /^-?0\d/.test(el); +} + +function lte(i, y) { + return i <= y; +} +function gte(i, y) { + return i >= y; +} + +function expand(str, isTop) { + var expansions = []; + + var m = balanced('{', '}', str); + if (!m || /\$$/.test(m.pre)) return [str]; + + var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + var isSequence = isNumericSequence || isAlphaSequence; + var isOptions = m.body.indexOf(',') >= 0; + if (!isSequence && !isOptions) { + // {a},b} + if (m.post.match(/,(?!,).*\}/)) { + str = m.pre + '{' + m.body + escClose + m.post; + return expand(str); + } + return [str]; + } + + var n; + if (isSequence) { + n = m.body.split(/\.\./); + } else { + n = parseCommaParts(m.body); + if (n.length === 1) { + // x{{a,b}}y ==> x{a}y x{b}y + n = expand(n[0], false).map(embrace); + if (n.length === 1) { + var post = m.post.length + ? expand(m.post, false) + : ['']; + return post.map(function(p) { + return m.pre + n[0] + p; + }); + } + } + } + + // at this point, n is the parts, and we know it's not a comma set + // with a single entry. + + // no need to expand pre, since it is guaranteed to be free of brace-sets + var pre = m.pre; + var post = m.post.length + ? expand(m.post, false) + : ['']; + + var N; + + if (isSequence) { + var x = numeric(n[0]); + var y = numeric(n[1]); + var width = Math.max(n[0].length, n[1].length) + var incr = n.length == 3 + ? Math.abs(numeric(n[2])) + : 1; + var test = lte; + var reverse = y < x; + if (reverse) { + incr *= -1; + test = gte; + } + var pad = n.some(isPadded); + + N = []; + + for (var i = x; test(i, y); i += incr) { + var c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === '\\') + c = ''; + } else { + c = String(i); + if (pad) { + var need = width - c.length; + if (need > 0) { + var z = new Array(need + 1).join('0'); + if (i < 0) + c = '-' + z + c.slice(1); + else + c = z + c; + } + } + } + N.push(c); + } + } else { + N = concatMap(n, function(el) { return expand(el, false) }); + } + + for (var j = 0; j < N.length; j++) { + for (var k = 0; k < post.length; k++) { + var expansion = pre + N[j] + post[k]; + if (!isTop || isSequence || expansion) + expansions.push(expansion); + } + } + + return expansions; +} + diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/brace-expansion/package.json b/novas/novacore-zephyr/claude-code-router/node_modules/brace-expansion/package.json new file mode 100644 index 0000000000000000000000000000000000000000..344788817d053e12e97670c5a56c006e3af5edfd --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/brace-expansion/package.json @@ -0,0 +1,50 @@ +{ + "name": "brace-expansion", + "description": "Brace expansion as known from sh/bash", + "version": "1.1.12", + "repository": { + "type": "git", + "url": "git://github.com/juliangruber/brace-expansion.git" + }, + "homepage": "https://github.com/juliangruber/brace-expansion", + "main": "index.js", + "scripts": { + "test": "tape test/*.js", + "gentest": "bash test/generate.sh", + "bench": "matcha test/perf/bench.js" + }, + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + }, + "devDependencies": { + "matcha": "^0.7.0", + "tape": "^4.6.0" + }, + "keywords": [], + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "license": "MIT", + "testling": { + "files": "test/*.js", + "browsers": [ + "ie/8..latest", + "firefox/20..latest", + "firefox/nightly", + "chrome/25..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2..latest" + ] + }, + "publishConfig": { + "tag": "1.x" + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/browserslist/LICENSE b/novas/novacore-zephyr/claude-code-router/node_modules/browserslist/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..90b6b91673374acb764c2a0a154a31ffb869466f --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/browserslist/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright 2014 Andrey Sitnik and other contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/browserslist/README.md b/novas/novacore-zephyr/claude-code-router/node_modules/browserslist/README.md new file mode 100644 index 0000000000000000000000000000000000000000..7e51beee70fb92e4721972e7229b92cccc16336a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/browserslist/README.md @@ -0,0 +1,65 @@ +# Browserslist + +Browserslist logo by Anton Popov + +The config to share target browsers and Node.js versions between different +front-end tools. It is used in: + +* [Autoprefixer] +* [Babel] +* [postcss-preset-env] +* [eslint-plugin-compat] +* [stylelint-no-unsupported-browser-features] +* [postcss-normalize] +* [obsolete-webpack-plugin] + +All tools will find target browsers automatically, +when you add the following to `package.json`: + +```json + "browserslist": [ + "defaults and fully supports es6-module", + "maintained node versions" + ] +``` + +Or in `.browserslistrc` config: + +```yaml +# Browsers that we support + +defaults and fully supports es6-module +maintained node versions +``` + +Developers set their version lists using queries like `last 2 versions` +to be free from updating versions manually. +Browserslist will use [`caniuse-lite`] with [Can I Use] data for this queries. + +You can check how config works at our playground: [`browsersl.ist`](https://browsersl.ist/) + + + browsersl.ist website + + +
+
+
+ Sponsored by Evil Martians  Supported by Cube +
+ +[stylelint-no-unsupported-browser-features]: https://github.com/ismay/stylelint-no-unsupported-browser-features +[obsolete-webpack-plugin]: https://github.com/ElemeFE/obsolete-webpack-plugin +[eslint-plugin-compat]: https://github.com/amilajack/eslint-plugin-compat +[Browserslist Example]: https://github.com/browserslist/browserslist-example +[postcss-preset-env]: https://github.com/csstools/postcss-plugins/tree/main/plugin-packs/postcss-preset-env +[postcss-normalize]: https://github.com/csstools/postcss-normalize +[`browsersl.ist`]: https://browsersl.ist/ +[`caniuse-lite`]: https://github.com/ben-eb/caniuse-lite +[Autoprefixer]: https://github.com/postcss/autoprefixer +[Can I Use]: https://caniuse.com/ +[Babel]: https://github.com/babel/babel/tree/master/packages/babel-preset-env + +## Docs +Read full docs **[here](https://github.com/browserslist/browserslist#readme)**. diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/browserslist/browser.js b/novas/novacore-zephyr/claude-code-router/node_modules/browserslist/browser.js new file mode 100644 index 0000000000000000000000000000000000000000..1a681fd3e2c2961af31e1e778b18723a0e119035 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/browserslist/browser.js @@ -0,0 +1,54 @@ +var BrowserslistError = require('./error') + +function noop() {} + +module.exports = { + loadQueries: function loadQueries() { + throw new BrowserslistError( + 'Sharable configs are not supported in client-side build of Browserslist' + ) + }, + + getStat: function getStat(opts) { + return opts.stats + }, + + loadConfig: function loadConfig(opts) { + if (opts.config) { + throw new BrowserslistError( + 'Browserslist config are not supported in client-side build' + ) + } + }, + + loadCountry: function loadCountry() { + throw new BrowserslistError( + 'Country statistics are not supported ' + + 'in client-side build of Browserslist' + ) + }, + + loadFeature: function loadFeature() { + throw new BrowserslistError( + 'Supports queries are not available in client-side build of Browserslist' + ) + }, + + currentNode: function currentNode(resolve, context) { + return resolve(['maintained node versions'], context)[0] + }, + + parseConfig: noop, + + readConfig: noop, + + findConfig: noop, + + findConfigFile: noop, + + clearCaches: noop, + + oldDataWarning: noop, + + env: {} +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/browserslist/cli.js b/novas/novacore-zephyr/claude-code-router/node_modules/browserslist/cli.js new file mode 100644 index 0000000000000000000000000000000000000000..78c08d743a8e478c346029e241b1f795b646fbd2 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/browserslist/cli.js @@ -0,0 +1,156 @@ +#!/usr/bin/env node + +var fs = require('fs') +var updateDb = require('update-browserslist-db') + +var browserslist = require('./') +var pkg = require('./package.json') + +var args = process.argv.slice(2) + +var USAGE = + 'Usage:\n' + + ' npx browserslist\n' + + ' npx browserslist "QUERIES"\n' + + ' npx browserslist --json "QUERIES"\n' + + ' npx browserslist --config="path/to/browserlist/file"\n' + + ' npx browserslist --coverage "QUERIES"\n' + + ' npx browserslist --coverage=US "QUERIES"\n' + + ' npx browserslist --coverage=US,RU,global "QUERIES"\n' + + ' npx browserslist --env="environment name defined in config"\n' + + ' npx browserslist --stats="path/to/browserlist/stats/file"\n' + + ' npx browserslist --mobile-to-desktop\n' + + ' npx browserslist --ignore-unknown-versions\n' + +function isArg(arg) { + return args.some(function (str) { + return str === arg || str.indexOf(arg + '=') === 0 + }) +} + +function error(msg) { + process.stderr.write('browserslist: ' + msg + '\n') + process.exit(1) +} + +if (isArg('--help') || isArg('-h')) { + process.stdout.write(pkg.description + '.\n\n' + USAGE + '\n') +} else if (isArg('--version') || isArg('-v')) { + process.stdout.write('browserslist ' + pkg.version + '\n') +} else if (isArg('--update-db')) { + /* c8 ignore next 8 */ + process.stdout.write( + 'The --update-db command is deprecated.\n' + + 'Please use npx update-browserslist-db@latest instead.\n' + ) + process.stdout.write('Browserslist DB update will still be made.\n') + updateDb(function (str) { + process.stdout.write(str) + }) +} else { + var mode = 'browsers' + var opts = {} + var queries + var areas + + for (var i = 0; i < args.length; i++) { + if (args[i][0] !== '-') { + queries = args[i].replace(/^["']|["']$/g, '') + continue + } + + var arg = args[i].split('=') + var name = arg[0] + var value = arg[1] + + if (value) value = value.replace(/^["']|["']$/g, '') + + if (name === '--config' || name === '-b') { + opts.config = value + } else if (name === '--env' || name === '-e') { + opts.env = value + } else if (name === '--stats' || name === '-s') { + opts.stats = value + } else if (name === '--coverage' || name === '-c') { + if (mode !== 'json') mode = 'coverage' + if (value) { + areas = value.split(',') + } else { + areas = ['global'] + } + } else if (name === '--json') { + mode = 'json' + } else if (name === '--mobile-to-desktop') { + /* c8 ignore next */ + opts.mobileToDesktop = true + } else if (name === '--ignore-unknown-versions') { + /* c8 ignore next */ + opts.ignoreUnknownVersions = true + } else { + error('Unknown arguments ' + args[i] + '.\n\n' + USAGE) + } + } + + var browsers + try { + browsers = browserslist(queries, opts) + } catch (e) { + if (e.name === 'BrowserslistError') { + error(e.message) + } /* c8 ignore start */ else { + throw e + } /* c8 ignore end */ + } + + var coverage + if (mode === 'browsers') { + browsers.forEach(function (browser) { + process.stdout.write(browser + '\n') + }) + } else if (areas) { + coverage = areas.map(function (area) { + var stats + if (area !== 'global') { + stats = area + } else if (opts.stats) { + stats = JSON.parse(fs.readFileSync(opts.stats)) + } + var result = browserslist.coverage(browsers, stats) + var round = Math.round(result * 100) / 100.0 + + return [area, round] + }) + + if (mode === 'coverage') { + var prefix = 'These browsers account for ' + process.stdout.write(prefix) + coverage.forEach(function (data, index) { + var area = data[0] + var round = data[1] + var end = 'globally' + if (area && area !== 'global') { + end = 'in the ' + area.toUpperCase() + } else if (opts.stats) { + end = 'in custom statistics' + } + + if (index !== 0) { + process.stdout.write(prefix.replace(/./g, ' ')) + } + + process.stdout.write(round + '% of all users ' + end + '\n') + }) + } + } + + if (mode === 'json') { + var data = { browsers: browsers } + if (coverage) { + data.coverage = coverage.reduce(function (object, j) { + object[j[0]] = j[1] + return object + }, {}) + } + process.stdout.write(JSON.stringify(data, null, ' ') + '\n') + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/browserslist/error.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/browserslist/error.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..12ff92133a997520119a8473ff3a69d7b413d6bd --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/browserslist/error.d.ts @@ -0,0 +1,7 @@ +declare class BrowserslistError extends Error { + constructor(message: any) + name: 'BrowserslistError' + browserslist: true +} + +export = BrowserslistError diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/browserslist/error.js b/novas/novacore-zephyr/claude-code-router/node_modules/browserslist/error.js new file mode 100644 index 0000000000000000000000000000000000000000..6e5da7a823f4af93000b3a6798de0c31cec26340 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/browserslist/error.js @@ -0,0 +1,12 @@ +function BrowserslistError(message) { + this.name = 'BrowserslistError' + this.message = message + this.browserslist = true + if (Error.captureStackTrace) { + Error.captureStackTrace(this, BrowserslistError) + } +} + +BrowserslistError.prototype = Error.prototype + +module.exports = BrowserslistError diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/browserslist/index.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/browserslist/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a08176cc1ab9dfcac2e6ce65146ef051ace07140 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/browserslist/index.d.ts @@ -0,0 +1,224 @@ +/** + * Return array of browsers by selection queries. + * + * ```js + * browserslist('IE >= 10, IE 8') //=> ['ie 11', 'ie 10', 'ie 8'] + * ``` + * + * @param queries Browser queries. + * @param opts Options. + * @returns Array with browser names in Can I Use. + */ +declare function browserslist( + queries?: string | readonly string[] | null, + opts?: browserslist.Options +): string[] + +declare namespace browserslist { + interface Query { + compose: 'or' | 'and' + type: string + query: string + not?: true + } + + interface Options { + /** + * Path to processed file. It will be used to find config files. + */ + path?: string | false + /** + * Processing environment. It will be used to take right queries + * from config file. + */ + env?: string + /** + * Custom browser usage statistics for "> 1% in my stats" query. + */ + stats?: Stats | string + /** + * Path to config file with queries. + */ + config?: string + /** + * Do not throw on unknown version in direct query. + */ + ignoreUnknownVersions?: boolean + /** + * Throw an error if env is not found. + */ + throwOnMissing?: boolean + /** + * Disable security checks for extend query. + */ + dangerousExtend?: boolean + /** + * Alias mobile browsers to the desktop version when Can I Use + * doesn’t have data about the specified version. + */ + mobileToDesktop?: boolean + } + + type Config = { + defaults: string[] + [section: string]: string[] | undefined + } + + interface Stats { + [browser: string]: { + [version: string]: number + } + } + + /** + * Browser names aliases. + */ + let aliases: { + [alias: string]: string | undefined + } + + /** + * Aliases to work with joined versions like `ios_saf 7.0-7.1`. + */ + let versionAliases: { + [browser: string]: + | { + [version: string]: string | undefined + } + | undefined + } + + /** + * Can I Use only provides a few versions for some browsers (e.g. `and_chr`). + * + * Fallback to a similar browser for unknown versions. + */ + let desktopNames: { + [browser: string]: string | undefined + } + + let data: { + [browser: string]: + | { + name: string + versions: string[] + released: string[] + releaseDate: { + [version: string]: number | undefined | null + } + } + | undefined + } + + let nodeVersions: string[] + + interface Usage { + [version: string]: number + } + + let usage: { + global?: Usage + custom?: Usage | null + [country: string]: Usage | undefined | null + } + + let cache: { + [feature: string]: { + [name: string]: { + [version: string]: string + } + } + } + + /** + * Default browsers query + */ + let defaults: readonly string[] + + /** + * Which statistics should be used. Country code or custom statistics. + * Pass `"my stats"` to load statistics from `Browserslist` files. + */ + type StatsOptions = string | 'my stats' | Stats | { dataByBrowser: Stats } + + /** + * Return browsers market coverage. + * + * ```js + * browserslist.coverage(browserslist('> 1% in US'), 'US') //=> 83.1 + * ``` + * + * @param browsers Browsers names in Can I Use. + * @param stats Which statistics should be used. + * @returns Total market coverage for all selected browsers. + */ + function coverage(browsers: readonly string[], stats?: StatsOptions): number + + /** + * Get queries AST to analyze the config content. + * + * @param queries Browser queries. + * @param opts Options. + * @returns An array of the data of each query in the config. + */ + function parse( + queries?: string | readonly string[] | null, + opts?: browserslist.Options + ): Query[] + + /** + * Return queries for specific file inside the project. + * + * ```js + * browserslist.loadConfig({ + * file: process.cwd() + * }) ?? browserslist.defaults + * ``` + */ + function loadConfig(options: LoadConfigOptions): string[] | undefined + + function clearCaches(): void + + function parseConfig(string: string): Config + + function readConfig(file: string): Config + + function findConfig(...pathSegments: string[]): Config | undefined + + function findConfigFile(...pathSegments: string[]): string | undefined + + interface LoadConfigOptions { + /** + * Path to config file + * */ + config?: string + + /** + * Path to file inside the project to find Browserslist config + * in closest folder + */ + path?: string + + /** + * Environment to choose part of config. + */ + env?: string + } +} + +declare global { + namespace NodeJS { + interface ProcessEnv { + BROWSERSLIST?: string + BROWSERSLIST_CONFIG?: string + BROWSERSLIST_DANGEROUS_EXTEND?: string + BROWSERSLIST_DISABLE_CACHE?: string + BROWSERSLIST_ENV?: string + BROWSERSLIST_IGNORE_OLD_DATA?: string + BROWSERSLIST_STATS?: string + BROWSERSLIST_ROOT_PATH?: string + } + } +} + +export = browserslist diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/browserslist/index.js b/novas/novacore-zephyr/claude-code-router/node_modules/browserslist/index.js new file mode 100644 index 0000000000000000000000000000000000000000..603f5fcfd686f2a8c2c6e3c97aa9c1b399421b02 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/browserslist/index.js @@ -0,0 +1,1246 @@ +var jsReleases = require('node-releases/data/processed/envs.json') +var agents = require('caniuse-lite/dist/unpacker/agents').agents +var e2c = require('electron-to-chromium/versions') +var jsEOL = require('node-releases/data/release-schedule/release-schedule.json') +var path = require('path') + +var BrowserslistError = require('./error') +var env = require('./node') +var parseWithoutCache = require('./parse') // Will load browser.js in webpack + +var YEAR = 365.259641 * 24 * 60 * 60 * 1000 +var ANDROID_EVERGREEN_FIRST = '37' +var OP_MOB_BLINK_FIRST = 14 + +// Helpers + +function isVersionsMatch(versionA, versionB) { + return (versionA + '.').indexOf(versionB + '.') === 0 +} + +function isEolReleased(name) { + var version = name.slice(1) + return browserslist.nodeVersions.some(function (i) { + return isVersionsMatch(i, version) + }) +} + +function normalize(versions) { + return versions.filter(function (version) { + return typeof version === 'string' + }) +} + +function normalizeElectron(version) { + var versionToUse = version + if (version.split('.').length === 3) { + versionToUse = version.split('.').slice(0, -1).join('.') + } + return versionToUse +} + +function nameMapper(name) { + return function mapName(version) { + return name + ' ' + version + } +} + +function getMajor(version) { + return parseInt(version.split('.')[0]) +} + +function getMajorVersions(released, number) { + if (released.length === 0) return [] + var majorVersions = uniq(released.map(getMajor)) + var minimum = majorVersions[majorVersions.length - number] + if (!minimum) { + return released + } + var selected = [] + for (var i = released.length - 1; i >= 0; i--) { + if (minimum > getMajor(released[i])) break + selected.unshift(released[i]) + } + return selected +} + +function uniq(array) { + var filtered = [] + for (var i = 0; i < array.length; i++) { + if (filtered.indexOf(array[i]) === -1) filtered.push(array[i]) + } + return filtered +} + +function fillUsage(result, name, data) { + for (var i in data) { + result[name + ' ' + i] = data[i] + } +} + +function generateFilter(sign, version) { + version = parseFloat(version) + if (sign === '>') { + return function (v) { + return parseLatestFloat(v) > version + } + } else if (sign === '>=') { + return function (v) { + return parseLatestFloat(v) >= version + } + } else if (sign === '<') { + return function (v) { + return parseFloat(v) < version + } + } else { + return function (v) { + return parseFloat(v) <= version + } + } + + function parseLatestFloat(v) { + return parseFloat(v.split('-')[1] || v) + } +} + +function generateSemverFilter(sign, version) { + version = version.split('.').map(parseSimpleInt) + version[1] = version[1] || 0 + version[2] = version[2] || 0 + if (sign === '>') { + return function (v) { + v = v.split('.').map(parseSimpleInt) + return compareSemver(v, version) > 0 + } + } else if (sign === '>=') { + return function (v) { + v = v.split('.').map(parseSimpleInt) + return compareSemver(v, version) >= 0 + } + } else if (sign === '<') { + return function (v) { + v = v.split('.').map(parseSimpleInt) + return compareSemver(version, v) > 0 + } + } else { + return function (v) { + v = v.split('.').map(parseSimpleInt) + return compareSemver(version, v) >= 0 + } + } +} + +function parseSimpleInt(x) { + return parseInt(x) +} + +function compare(a, b) { + if (a < b) return -1 + if (a > b) return +1 + return 0 +} + +function compareSemver(a, b) { + return ( + compare(parseInt(a[0]), parseInt(b[0])) || + compare(parseInt(a[1] || '0'), parseInt(b[1] || '0')) || + compare(parseInt(a[2] || '0'), parseInt(b[2] || '0')) + ) +} + +// this follows the npm-like semver behavior +function semverFilterLoose(operator, range) { + range = range.split('.').map(parseSimpleInt) + if (typeof range[1] === 'undefined') { + range[1] = 'x' + } + // ignore any patch version because we only return minor versions + // range[2] = 'x' + switch (operator) { + case '<=': + return function (version) { + version = version.split('.').map(parseSimpleInt) + return compareSemverLoose(version, range) <= 0 + } + case '>=': + default: + return function (version) { + version = version.split('.').map(parseSimpleInt) + return compareSemverLoose(version, range) >= 0 + } + } +} + +// this follows the npm-like semver behavior +function compareSemverLoose(version, range) { + if (version[0] !== range[0]) { + return version[0] < range[0] ? -1 : +1 + } + if (range[1] === 'x') { + return 0 + } + if (version[1] !== range[1]) { + return version[1] < range[1] ? -1 : +1 + } + return 0 +} + +function resolveVersion(data, version) { + if (data.versions.indexOf(version) !== -1) { + return version + } else if (browserslist.versionAliases[data.name][version]) { + return browserslist.versionAliases[data.name][version] + } else { + return false + } +} + +function normalizeVersion(data, version) { + var resolved = resolveVersion(data, version) + if (resolved) { + return resolved + } else if (data.versions.length === 1) { + return data.versions[0] + } else { + return false + } +} + +function filterByYear(since, context) { + since = since / 1000 + return Object.keys(agents).reduce(function (selected, name) { + var data = byName(name, context) + if (!data) return selected + var versions = Object.keys(data.releaseDate).filter(function (v) { + var date = data.releaseDate[v] + return date !== null && date >= since + }) + return selected.concat(versions.map(nameMapper(data.name))) + }, []) +} + +function cloneData(data) { + return { + name: data.name, + versions: data.versions, + released: data.released, + releaseDate: data.releaseDate + } +} + +function byName(name, context) { + name = name.toLowerCase() + name = browserslist.aliases[name] || name + if (context.mobileToDesktop && browserslist.desktopNames[name]) { + var desktop = browserslist.data[browserslist.desktopNames[name]] + if (name === 'android') { + return normalizeAndroidData(cloneData(browserslist.data[name]), desktop) + } else { + var cloned = cloneData(desktop) + cloned.name = name + return cloned + } + } + return browserslist.data[name] +} + +function normalizeAndroidVersions(androidVersions, chromeVersions) { + var iFirstEvergreen = chromeVersions.indexOf(ANDROID_EVERGREEN_FIRST) + return androidVersions + .filter(function (version) { + return /^(?:[2-4]\.|[34]$)/.test(version) + }) + .concat(chromeVersions.slice(iFirstEvergreen)) +} + +function copyObject(obj) { + var copy = {} + for (var key in obj) { + copy[key] = obj[key] + } + return copy +} + +function normalizeAndroidData(android, chrome) { + android.released = normalizeAndroidVersions(android.released, chrome.released) + android.versions = normalizeAndroidVersions(android.versions, chrome.versions) + android.releaseDate = copyObject(android.releaseDate) + android.released.forEach(function (v) { + if (android.releaseDate[v] === undefined) { + android.releaseDate[v] = chrome.releaseDate[v] + } + }) + return android +} + +function checkName(name, context) { + var data = byName(name, context) + if (!data) throw new BrowserslistError('Unknown browser ' + name) + return data +} + +function unknownQuery(query) { + return new BrowserslistError( + 'Unknown browser query `' + + query + + '`. ' + + 'Maybe you are using old Browserslist or made typo in query.' + ) +} + +// Adjusts last X versions queries for some mobile browsers, +// where caniuse data jumps from a legacy version to the latest +function filterJumps(list, name, nVersions, context) { + var jump = 1 + switch (name) { + case 'android': + if (context.mobileToDesktop) return list + var released = browserslist.data.chrome.released + jump = released.length - released.indexOf(ANDROID_EVERGREEN_FIRST) + break + case 'op_mob': + var latest = browserslist.data.op_mob.released.slice(-1)[0] + jump = getMajor(latest) - OP_MOB_BLINK_FIRST + 1 + break + default: + return list + } + if (nVersions <= jump) { + return list.slice(-1) + } + return list.slice(jump - 1 - nVersions) +} + +function isSupported(flags, withPartial) { + return ( + typeof flags === 'string' && + (flags.indexOf('y') >= 0 || (withPartial && flags.indexOf('a') >= 0)) + ) +} + +function resolve(queries, context) { + return parseQueries(queries).reduce(function (result, node, index) { + if (node.not && index === 0) { + throw new BrowserslistError( + 'Write any browsers query (for instance, `defaults`) ' + + 'before `' + + node.query + + '`' + ) + } + var type = QUERIES[node.type] + var array = type.select.call(browserslist, context, node).map(function (j) { + var parts = j.split(' ') + if (parts[1] === '0') { + return parts[0] + ' ' + byName(parts[0], context).versions[0] + } else { + return j + } + }) + + if (node.compose === 'and') { + if (node.not) { + return result.filter(function (j) { + return array.indexOf(j) === -1 + }) + } else { + return result.filter(function (j) { + return array.indexOf(j) !== -1 + }) + } + } else { + if (node.not) { + var filter = {} + array.forEach(function (j) { + filter[j] = true + }) + return result.filter(function (j) { + return !filter[j] + }) + } + return result.concat(array) + } + }, []) +} + +function prepareOpts(opts) { + if (typeof opts === 'undefined') opts = {} + + if (typeof opts.path === 'undefined') { + opts.path = path.resolve ? path.resolve('.') : '.' + } + + return opts +} + +function prepareQueries(queries, opts) { + if (typeof queries === 'undefined' || queries === null) { + var config = browserslist.loadConfig(opts) + if (config) { + queries = config + } else { + queries = browserslist.defaults + } + } + + return queries +} + +function checkQueries(queries) { + if (!(typeof queries === 'string' || Array.isArray(queries))) { + throw new BrowserslistError( + 'Browser queries must be an array or string. Got ' + typeof queries + '.' + ) + } +} + +var cache = {} +var parseCache = {} + +function browserslist(queries, opts) { + opts = prepareOpts(opts) + queries = prepareQueries(queries, opts) + checkQueries(queries) + + var needsPath = parseQueries(queries).some(function (node) { + return QUERIES[node.type].needsPath + }) + var context = { + ignoreUnknownVersions: opts.ignoreUnknownVersions, + dangerousExtend: opts.dangerousExtend, + mobileToDesktop: opts.mobileToDesktop, + env: opts.env + } + // Removing to avoid using context.path without marking query as needsPath + if (needsPath) { + context.path = opts.path + } + + env.oldDataWarning(browserslist.data) + var stats = env.getStat(opts, browserslist.data) + if (stats) { + context.customUsage = {} + for (var browser in stats) { + fillUsage(context.customUsage, browser, stats[browser]) + } + } + + var cacheKey = JSON.stringify([queries, context]) + if (cache[cacheKey]) return cache[cacheKey] + + var result = uniq(resolve(queries, context)).sort(function (name1, name2) { + name1 = name1.split(' ') + name2 = name2.split(' ') + if (name1[0] === name2[0]) { + // assumptions on caniuse data + // 1) version ranges never overlaps + // 2) if version is not a range, it never contains `-` + var version1 = name1[1].split('-')[0] + var version2 = name2[1].split('-')[0] + return compareSemver(version2.split('.'), version1.split('.')) + } else { + return compare(name1[0], name2[0]) + } + }) + if (!env.env.BROWSERSLIST_DISABLE_CACHE) { + cache[cacheKey] = result + } + return result +} + +function parseQueries(queries) { + var cacheKey = JSON.stringify(queries) + if (cacheKey in parseCache) return parseCache[cacheKey] + var result = parseWithoutCache(QUERIES, queries) + if (!env.env.BROWSERSLIST_DISABLE_CACHE) { + parseCache[cacheKey] = result + } + return result +} + +function loadCustomUsage(context, config) { + var stats = env.loadStat(context, config, browserslist.data) + if (stats) { + context.customUsage = {} + for (var browser in stats) { + fillUsage(context.customUsage, browser, stats[browser]) + } + } + if (!context.customUsage) { + throw new BrowserslistError('Custom usage statistics was not provided') + } + return context.customUsage +} + +browserslist.parse = function (queries, opts) { + opts = prepareOpts(opts) + queries = prepareQueries(queries, opts) + checkQueries(queries) + return parseQueries(queries) +} + +// Will be filled by Can I Use data below +browserslist.cache = {} +browserslist.data = {} +browserslist.usage = { + global: {}, + custom: null +} + +// Default browsers query +browserslist.defaults = ['> 0.5%', 'last 2 versions', 'Firefox ESR', 'not dead'] + +// Browser names aliases +browserslist.aliases = { + fx: 'firefox', + ff: 'firefox', + ios: 'ios_saf', + explorer: 'ie', + blackberry: 'bb', + explorermobile: 'ie_mob', + operamini: 'op_mini', + operamobile: 'op_mob', + chromeandroid: 'and_chr', + firefoxandroid: 'and_ff', + ucandroid: 'and_uc', + qqandroid: 'and_qq' +} + +// Can I Use only provides a few versions for some browsers (e.g. and_chr). +// Fallback to a similar browser for unknown versions +// Note op_mob is not included as its chromium versions are not in sync with Opera desktop +browserslist.desktopNames = { + and_chr: 'chrome', + and_ff: 'firefox', + ie_mob: 'ie', + android: 'chrome' // has extra processing logic +} + +// Aliases to work with joined versions like `ios_saf 7.0-7.1` +browserslist.versionAliases = {} + +browserslist.clearCaches = env.clearCaches +browserslist.parseConfig = env.parseConfig +browserslist.readConfig = env.readConfig +browserslist.findConfigFile = env.findConfigFile +browserslist.findConfig = env.findConfig +browserslist.loadConfig = env.loadConfig + +browserslist.coverage = function (browsers, stats) { + var data + if (typeof stats === 'undefined') { + data = browserslist.usage.global + } else if (stats === 'my stats') { + var opts = {} + opts.path = path.resolve ? path.resolve('.') : '.' + var customStats = env.getStat(opts) + if (!customStats) { + throw new BrowserslistError('Custom usage statistics was not provided') + } + data = {} + for (var browser in customStats) { + fillUsage(data, browser, customStats[browser]) + } + } else if (typeof stats === 'string') { + if (stats.length > 2) { + stats = stats.toLowerCase() + } else { + stats = stats.toUpperCase() + } + env.loadCountry(browserslist.usage, stats, browserslist.data) + data = browserslist.usage[stats] + } else { + if ('dataByBrowser' in stats) { + stats = stats.dataByBrowser + } + data = {} + for (var name in stats) { + for (var version in stats[name]) { + data[name + ' ' + version] = stats[name][version] + } + } + } + + return browsers.reduce(function (all, i) { + var usage = data[i] + if (usage === undefined) { + usage = data[i.replace(/ \S+$/, ' 0')] + } + return all + (usage || 0) + }, 0) +} + +function nodeQuery(context, node) { + var matched = browserslist.nodeVersions.filter(function (i) { + return isVersionsMatch(i, node.version) + }) + if (matched.length === 0) { + if (context.ignoreUnknownVersions) { + return [] + } else { + throw new BrowserslistError( + 'Unknown version ' + node.version + ' of Node.js' + ) + } + } + return ['node ' + matched[matched.length - 1]] +} + +function sinceQuery(context, node) { + var year = parseInt(node.year) + var month = parseInt(node.month || '01') - 1 + var day = parseInt(node.day || '01') + return filterByYear(Date.UTC(year, month, day, 0, 0, 0), context) +} + +function coverQuery(context, node) { + var coverage = parseFloat(node.coverage) + var usage = browserslist.usage.global + if (node.place) { + if (node.place.match(/^my\s+stats$/i)) { + if (!context.customUsage) { + throw new BrowserslistError('Custom usage statistics was not provided') + } + usage = context.customUsage + } else { + var place + if (node.place.length === 2) { + place = node.place.toUpperCase() + } else { + place = node.place.toLowerCase() + } + env.loadCountry(browserslist.usage, place, browserslist.data) + usage = browserslist.usage[place] + } + } else if (node.config) { + usage = loadCustomUsage(context, node.config) + } + var versions = Object.keys(usage).sort(function (a, b) { + return usage[b] - usage[a] + }) + var covered = 0 + var result = [] + var version + for (var i = 0; i < versions.length; i++) { + version = versions[i] + if (usage[version] === 0) break + covered += usage[version] + result.push(version) + if (covered >= coverage) break + } + return result +} + +var QUERIES = { + last_major_versions: { + matches: ['versions'], + regexp: /^last\s+(\d+)\s+major\s+versions?$/i, + select: function (context, node) { + return Object.keys(agents).reduce(function (selected, name) { + var data = byName(name, context) + if (!data) return selected + var list = getMajorVersions(data.released, node.versions) + list = list.map(nameMapper(data.name)) + list = filterJumps(list, data.name, node.versions, context) + return selected.concat(list) + }, []) + } + }, + last_versions: { + matches: ['versions'], + regexp: /^last\s+(\d+)\s+versions?$/i, + select: function (context, node) { + return Object.keys(agents).reduce(function (selected, name) { + var data = byName(name, context) + if (!data) return selected + var list = data.released.slice(-node.versions) + list = list.map(nameMapper(data.name)) + list = filterJumps(list, data.name, node.versions, context) + return selected.concat(list) + }, []) + } + }, + last_electron_major_versions: { + matches: ['versions'], + regexp: /^last\s+(\d+)\s+electron\s+major\s+versions?$/i, + select: function (context, node) { + var validVersions = getMajorVersions(Object.keys(e2c), node.versions) + return validVersions.map(function (i) { + return 'chrome ' + e2c[i] + }) + } + }, + last_node_major_versions: { + matches: ['versions'], + regexp: /^last\s+(\d+)\s+node\s+major\s+versions?$/i, + select: function (context, node) { + return getMajorVersions(browserslist.nodeVersions, node.versions).map( + function (version) { + return 'node ' + version + } + ) + } + }, + last_browser_major_versions: { + matches: ['versions', 'browser'], + regexp: /^last\s+(\d+)\s+(\w+)\s+major\s+versions?$/i, + select: function (context, node) { + var data = checkName(node.browser, context) + var validVersions = getMajorVersions(data.released, node.versions) + var list = validVersions.map(nameMapper(data.name)) + list = filterJumps(list, data.name, node.versions, context) + return list + } + }, + last_electron_versions: { + matches: ['versions'], + regexp: /^last\s+(\d+)\s+electron\s+versions?$/i, + select: function (context, node) { + return Object.keys(e2c) + .slice(-node.versions) + .map(function (i) { + return 'chrome ' + e2c[i] + }) + } + }, + last_node_versions: { + matches: ['versions'], + regexp: /^last\s+(\d+)\s+node\s+versions?$/i, + select: function (context, node) { + return browserslist.nodeVersions + .slice(-node.versions) + .map(function (version) { + return 'node ' + version + }) + } + }, + last_browser_versions: { + matches: ['versions', 'browser'], + regexp: /^last\s+(\d+)\s+(\w+)\s+versions?$/i, + select: function (context, node) { + var data = checkName(node.browser, context) + var list = data.released.slice(-node.versions).map(nameMapper(data.name)) + list = filterJumps(list, data.name, node.versions, context) + return list + } + }, + unreleased_versions: { + matches: [], + regexp: /^unreleased\s+versions$/i, + select: function (context) { + return Object.keys(agents).reduce(function (selected, name) { + var data = byName(name, context) + if (!data) return selected + var list = data.versions.filter(function (v) { + return data.released.indexOf(v) === -1 + }) + list = list.map(nameMapper(data.name)) + return selected.concat(list) + }, []) + } + }, + unreleased_electron_versions: { + matches: [], + regexp: /^unreleased\s+electron\s+versions?$/i, + select: function () { + return [] + } + }, + unreleased_browser_versions: { + matches: ['browser'], + regexp: /^unreleased\s+(\w+)\s+versions?$/i, + select: function (context, node) { + var data = checkName(node.browser, context) + return data.versions + .filter(function (v) { + return data.released.indexOf(v) === -1 + }) + .map(nameMapper(data.name)) + } + }, + last_years: { + matches: ['years'], + regexp: /^last\s+((\d+\.)?\d+)\s+years?$/i, + select: function (context, node) { + return filterByYear(Date.now() - YEAR * node.years, context) + } + }, + since_y: { + matches: ['year'], + regexp: /^since (\d+)$/i, + select: sinceQuery + }, + since_y_m: { + matches: ['year', 'month'], + regexp: /^since (\d+)-(\d+)$/i, + select: sinceQuery + }, + since_y_m_d: { + matches: ['year', 'month', 'day'], + regexp: /^since (\d+)-(\d+)-(\d+)$/i, + select: sinceQuery + }, + popularity: { + matches: ['sign', 'popularity'], + regexp: /^(>=?|<=?)\s*(\d+|\d+\.\d+|\.\d+)%$/, + select: function (context, node) { + var popularity = parseFloat(node.popularity) + var usage = browserslist.usage.global + return Object.keys(usage).reduce(function (result, version) { + if (node.sign === '>') { + if (usage[version] > popularity) { + result.push(version) + } + } else if (node.sign === '<') { + if (usage[version] < popularity) { + result.push(version) + } + } else if (node.sign === '<=') { + if (usage[version] <= popularity) { + result.push(version) + } + } else if (usage[version] >= popularity) { + result.push(version) + } + return result + }, []) + } + }, + popularity_in_my_stats: { + matches: ['sign', 'popularity'], + regexp: /^(>=?|<=?)\s*(\d+|\d+\.\d+|\.\d+)%\s+in\s+my\s+stats$/, + select: function (context, node) { + var popularity = parseFloat(node.popularity) + if (!context.customUsage) { + throw new BrowserslistError('Custom usage statistics was not provided') + } + var usage = context.customUsage + return Object.keys(usage).reduce(function (result, version) { + var percentage = usage[version] + if (percentage == null) { + return result + } + + if (node.sign === '>') { + if (percentage > popularity) { + result.push(version) + } + } else if (node.sign === '<') { + if (percentage < popularity) { + result.push(version) + } + } else if (node.sign === '<=') { + if (percentage <= popularity) { + result.push(version) + } + } else if (percentage >= popularity) { + result.push(version) + } + return result + }, []) + } + }, + popularity_in_config_stats: { + matches: ['sign', 'popularity', 'config'], + regexp: /^(>=?|<=?)\s*(\d+|\d+\.\d+|\.\d+)%\s+in\s+(\S+)\s+stats$/, + select: function (context, node) { + var popularity = parseFloat(node.popularity) + var usage = loadCustomUsage(context, node.config) + return Object.keys(usage).reduce(function (result, version) { + var percentage = usage[version] + if (percentage == null) { + return result + } + + if (node.sign === '>') { + if (percentage > popularity) { + result.push(version) + } + } else if (node.sign === '<') { + if (percentage < popularity) { + result.push(version) + } + } else if (node.sign === '<=') { + if (percentage <= popularity) { + result.push(version) + } + } else if (percentage >= popularity) { + result.push(version) + } + return result + }, []) + } + }, + popularity_in_place: { + matches: ['sign', 'popularity', 'place'], + regexp: /^(>=?|<=?)\s*(\d+|\d+\.\d+|\.\d+)%\s+in\s+((alt-)?\w\w)$/, + select: function (context, node) { + var popularity = parseFloat(node.popularity) + var place = node.place + if (place.length === 2) { + place = place.toUpperCase() + } else { + place = place.toLowerCase() + } + env.loadCountry(browserslist.usage, place, browserslist.data) + var usage = browserslist.usage[place] + return Object.keys(usage).reduce(function (result, version) { + var percentage = usage[version] + if (percentage == null) { + return result + } + + if (node.sign === '>') { + if (percentage > popularity) { + result.push(version) + } + } else if (node.sign === '<') { + if (percentage < popularity) { + result.push(version) + } + } else if (node.sign === '<=') { + if (percentage <= popularity) { + result.push(version) + } + } else if (percentage >= popularity) { + result.push(version) + } + return result + }, []) + } + }, + cover: { + matches: ['coverage'], + regexp: /^cover\s+(\d+|\d+\.\d+|\.\d+)%$/i, + select: coverQuery + }, + cover_in: { + matches: ['coverage', 'place'], + regexp: /^cover\s+(\d+|\d+\.\d+|\.\d+)%\s+in\s+(my\s+stats|(alt-)?\w\w)$/i, + select: coverQuery + }, + cover_config: { + matches: ['coverage', 'config'], + regexp: /^cover\s+(\d+|\d+\.\d+|\.\d+)%\s+in\s+(\S+)\s+stats$/i, + select: coverQuery + }, + supports: { + matches: ['supportType', 'feature'], + regexp: /^(?:(fully|partially)\s+)?supports\s+([\w-]+)$/, + select: function (context, node) { + env.loadFeature(browserslist.cache, node.feature) + var withPartial = node.supportType !== 'fully' + var features = browserslist.cache[node.feature] + var result = [] + for (var name in features) { + var data = byName(name, context) + // Only check desktop when latest released mobile has support + var iMax = data.released.length - 1 + while (iMax >= 0) { + if (data.released[iMax] in features[name]) break + iMax-- + } + var checkDesktop = + context.mobileToDesktop && + name in browserslist.desktopNames && + isSupported(features[name][data.released[iMax]], withPartial) + data.versions.forEach(function (version) { + var flags = features[name][version] + if (flags === undefined && checkDesktop) { + flags = features[browserslist.desktopNames[name]][version] + } + if (isSupported(flags, withPartial)) { + result.push(name + ' ' + version) + } + }) + } + return result + } + }, + electron_range: { + matches: ['from', 'to'], + regexp: /^electron\s+([\d.]+)\s*-\s*([\d.]+)$/i, + select: function (context, node) { + var fromToUse = normalizeElectron(node.from) + var toToUse = normalizeElectron(node.to) + var from = parseFloat(node.from) + var to = parseFloat(node.to) + if (!e2c[fromToUse]) { + throw new BrowserslistError('Unknown version ' + from + ' of electron') + } + if (!e2c[toToUse]) { + throw new BrowserslistError('Unknown version ' + to + ' of electron') + } + return Object.keys(e2c) + .filter(function (i) { + var parsed = parseFloat(i) + return parsed >= from && parsed <= to + }) + .map(function (i) { + return 'chrome ' + e2c[i] + }) + } + }, + node_range: { + matches: ['from', 'to'], + regexp: /^node\s+([\d.]+)\s*-\s*([\d.]+)$/i, + select: function (context, node) { + return browserslist.nodeVersions + .filter(semverFilterLoose('>=', node.from)) + .filter(semverFilterLoose('<=', node.to)) + .map(function (v) { + return 'node ' + v + }) + } + }, + browser_range: { + matches: ['browser', 'from', 'to'], + regexp: /^(\w+)\s+([\d.]+)\s*-\s*([\d.]+)$/i, + select: function (context, node) { + var data = checkName(node.browser, context) + var from = parseFloat(normalizeVersion(data, node.from) || node.from) + var to = parseFloat(normalizeVersion(data, node.to) || node.to) + function filter(v) { + var parsed = parseFloat(v) + return parsed >= from && parsed <= to + } + return data.released.filter(filter).map(nameMapper(data.name)) + } + }, + electron_ray: { + matches: ['sign', 'version'], + regexp: /^electron\s*(>=?|<=?)\s*([\d.]+)$/i, + select: function (context, node) { + var versionToUse = normalizeElectron(node.version) + return Object.keys(e2c) + .filter(generateFilter(node.sign, versionToUse)) + .map(function (i) { + return 'chrome ' + e2c[i] + }) + } + }, + node_ray: { + matches: ['sign', 'version'], + regexp: /^node\s*(>=?|<=?)\s*([\d.]+)$/i, + select: function (context, node) { + return browserslist.nodeVersions + .filter(generateSemverFilter(node.sign, node.version)) + .map(function (v) { + return 'node ' + v + }) + } + }, + browser_ray: { + matches: ['browser', 'sign', 'version'], + regexp: /^(\w+)\s*(>=?|<=?)\s*([\d.]+)$/, + select: function (context, node) { + var version = node.version + var data = checkName(node.browser, context) + var alias = browserslist.versionAliases[data.name][version] + if (alias) version = alias + return data.released + .filter(generateFilter(node.sign, version)) + .map(function (v) { + return data.name + ' ' + v + }) + } + }, + firefox_esr: { + matches: [], + regexp: /^(firefox|ff|fx)\s+esr$/i, + select: function () { + return ['firefox 128', 'firefox 140'] + } + }, + opera_mini_all: { + matches: [], + regexp: /(operamini|op_mini)\s+all/i, + select: function () { + return ['op_mini all'] + } + }, + electron_version: { + matches: ['version'], + regexp: /^electron\s+([\d.]+)$/i, + select: function (context, node) { + var versionToUse = normalizeElectron(node.version) + var chrome = e2c[versionToUse] + if (!chrome) { + throw new BrowserslistError( + 'Unknown version ' + node.version + ' of electron' + ) + } + return ['chrome ' + chrome] + } + }, + node_major_version: { + matches: ['version'], + regexp: /^node\s+(\d+)$/i, + select: nodeQuery + }, + node_minor_version: { + matches: ['version'], + regexp: /^node\s+(\d+\.\d+)$/i, + select: nodeQuery + }, + node_patch_version: { + matches: ['version'], + regexp: /^node\s+(\d+\.\d+\.\d+)$/i, + select: nodeQuery + }, + current_node: { + matches: [], + regexp: /^current\s+node$/i, + select: function (context) { + return [env.currentNode(resolve, context)] + } + }, + maintained_node: { + matches: [], + regexp: /^maintained\s+node\s+versions$/i, + select: function (context) { + var now = Date.now() + var queries = Object.keys(jsEOL) + .filter(function (key) { + return ( + now < Date.parse(jsEOL[key].end) && + now > Date.parse(jsEOL[key].start) && + isEolReleased(key) + ) + }) + .map(function (key) { + return 'node ' + key.slice(1) + }) + return resolve(queries, context) + } + }, + phantomjs_1_9: { + matches: [], + regexp: /^phantomjs\s+1.9$/i, + select: function () { + return ['safari 5'] + } + }, + phantomjs_2_1: { + matches: [], + regexp: /^phantomjs\s+2.1$/i, + select: function () { + return ['safari 6'] + } + }, + browser_version: { + matches: ['browser', 'version'], + regexp: /^(\w+)\s+(tp|[\d.]+)$/i, + select: function (context, node) { + var version = node.version + if (/^tp$/i.test(version)) version = 'TP' + var data = checkName(node.browser, context) + var alias = normalizeVersion(data, version) + if (alias) { + version = alias + } else { + if (version.indexOf('.') === -1) { + alias = version + '.0' + } else { + alias = version.replace(/\.0$/, '') + } + alias = normalizeVersion(data, alias) + if (alias) { + version = alias + } else if (context.ignoreUnknownVersions) { + return [] + } else { + throw new BrowserslistError( + 'Unknown version ' + version + ' of ' + node.browser + ) + } + } + return [data.name + ' ' + version] + } + }, + browserslist_config: { + matches: [], + regexp: /^browserslist config$/i, + needsPath: true, + select: function (context) { + return browserslist(undefined, context) + } + }, + extends: { + matches: ['config'], + regexp: /^extends (.+)$/i, + needsPath: true, + select: function (context, node) { + return resolve(env.loadQueries(context, node.config), context) + } + }, + defaults: { + matches: [], + regexp: /^defaults$/i, + select: function (context) { + return resolve(browserslist.defaults, context) + } + }, + dead: { + matches: [], + regexp: /^dead$/i, + select: function (context) { + var dead = [ + 'Baidu >= 0', + 'ie <= 11', + 'ie_mob <= 11', + 'bb <= 10', + 'op_mob <= 12.1', + 'samsung 4' + ] + return resolve(dead, context) + } + }, + unknown: { + matches: [], + regexp: /^(\w+)$/i, + select: function (context, node) { + if (byName(node.query, context)) { + throw new BrowserslistError( + 'Specify versions in Browserslist query for browser ' + node.query + ) + } else { + throw unknownQuery(node.query) + } + } + } +} + +// Get and convert Can I Use data + +;(function () { + for (var name in agents) { + var browser = agents[name] + browserslist.data[name] = { + name: name, + versions: normalize(agents[name].versions), + released: normalize(agents[name].versions.slice(0, -3)), + releaseDate: agents[name].release_date + } + fillUsage(browserslist.usage.global, name, browser.usage_global) + + browserslist.versionAliases[name] = {} + for (var i = 0; i < browser.versions.length; i++) { + var full = browser.versions[i] + if (!full) continue + + if (full.indexOf('-') !== -1) { + var interval = full.split('-') + for (var j = 0; j < interval.length; j++) { + browserslist.versionAliases[name][interval[j]] = full + } + } + } + } + + browserslist.nodeVersions = jsReleases.map(function (release) { + return release.version + }) +})() + +module.exports = browserslist diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/browserslist/node.js b/novas/novacore-zephyr/claude-code-router/node_modules/browserslist/node.js new file mode 100644 index 0000000000000000000000000000000000000000..d2699de7b7b6e4345a8d987134fbcbc16eb7391b --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/browserslist/node.js @@ -0,0 +1,497 @@ +var feature = require('caniuse-lite/dist/unpacker/feature').default +var region = require('caniuse-lite/dist/unpacker/region').default +var fs = require('fs') +var path = require('path') + +var BrowserslistError = require('./error') + +var IS_SECTION = /^\s*\[(.+)]\s*$/ +var CONFIG_PATTERN = /^browserslist-config-/ +var SCOPED_CONFIG__PATTERN = /@[^/]+(?:\/[^/]+)?\/browserslist-config(?:-|$|\/)/ +var FORMAT = + 'Browserslist config should be a string or an array ' + + 'of strings with browser queries' +var PATHTYPE_UNKNOWN = 'unknown' +var PATHTYPE_DIR = 'directory' +var PATHTYPE_FILE = 'file' + +var dataTimeChecked = false +var statCache = {} +var configPathCache = {} +var parseConfigCache = {} + +function checkExtend(name) { + var use = ' Use `dangerousExtend` option to disable.' + if (!CONFIG_PATTERN.test(name) && !SCOPED_CONFIG__PATTERN.test(name)) { + throw new BrowserslistError( + 'Browserslist config needs `browserslist-config-` prefix. ' + use + ) + } + if (name.replace(/^@[^/]+\//, '').indexOf('.') !== -1) { + throw new BrowserslistError( + '`.` not allowed in Browserslist config name. ' + use + ) + } + if (name.indexOf('node_modules') !== -1) { + throw new BrowserslistError( + '`node_modules` not allowed in Browserslist config.' + use + ) + } +} + +function getPathType(filepath) { + var stats + try { + stats = fs.existsSync(filepath) && fs.statSync(filepath) + } catch (err) { + /* c8 ignore start */ + if ( + err.code !== 'ENOENT' && + err.code !== 'EACCES' && + err.code !== 'ERR_ACCESS_DENIED' + ) { + throw err + } + /* c8 ignore end */ + } + + if (stats && stats.isDirectory()) return PATHTYPE_DIR + if (stats && stats.isFile()) return PATHTYPE_FILE + + return PATHTYPE_UNKNOWN +} + +function isFile(file) { + return getPathType(file) === PATHTYPE_FILE +} + +function isDirectory(dir) { + return getPathType(dir) === PATHTYPE_DIR +} + +function eachParent(file, callback, cache) { + var loc = path.resolve(file) + var pathsForCacheResult = [] + var result + do { + if (!pathInRoot(loc)) { + break + } + if (cache && loc in cache) { + result = cache[loc] + break + } + pathsForCacheResult.push(loc) + + if (!isDirectory(loc)) { + continue + } + + var locResult = callback(loc) + if (typeof locResult !== 'undefined') { + result = locResult + break + } + } while (loc !== (loc = path.dirname(loc))) + + if (cache && !process.env.BROWSERSLIST_DISABLE_CACHE) { + pathsForCacheResult.forEach(function (cachePath) { + cache[cachePath] = result + }) + } + return result +} + +function pathInRoot(p) { + if (!process.env.BROWSERSLIST_ROOT_PATH) return true + var rootPath = path.resolve(process.env.BROWSERSLIST_ROOT_PATH) + if (path.relative(rootPath, p).substring(0, 2) === '..') { + return false + } + return true +} + +function check(section) { + if (Array.isArray(section)) { + for (var i = 0; i < section.length; i++) { + if (typeof section[i] !== 'string') { + throw new BrowserslistError(FORMAT) + } + } + } else if (typeof section !== 'string') { + throw new BrowserslistError(FORMAT) + } +} + +function pickEnv(config, opts) { + if (typeof config !== 'object') return config + + var name + if (typeof opts.env === 'string') { + name = opts.env + } else if (process.env.BROWSERSLIST_ENV) { + name = process.env.BROWSERSLIST_ENV + } else if (process.env.NODE_ENV) { + name = process.env.NODE_ENV + } else { + name = 'production' + } + + if (opts.throwOnMissing) { + if (name && name !== 'defaults' && !config[name]) { + throw new BrowserslistError( + 'Missing config for Browserslist environment `' + name + '`' + ) + } + } + + return config[name] || config.defaults +} + +function parsePackage(file) { + var text = fs + .readFileSync(file) + .toString() + .replace(/^\uFEFF/m, '') + var list + if (text.indexOf('"browserslist"') >= 0) { + list = JSON.parse(text).browserslist + } else if (text.indexOf('"browserlist"') >= 0) { + var config = JSON.parse(text) + if (config.browserlist && !config.browserslist) { + throw new BrowserslistError( + '`browserlist` key instead of `browserslist` in ' + file + ) + } + } + if (Array.isArray(list) || typeof list === 'string') { + list = { defaults: list } + } + for (var i in list) { + check(list[i]) + } + + return list +} + +function parsePackageOrReadConfig(file) { + if (file in parseConfigCache) { + return parseConfigCache[file] + } + + var isPackage = path.basename(file) === 'package.json' + var result = isPackage ? parsePackage(file) : module.exports.readConfig(file) + + if (!process.env.BROWSERSLIST_DISABLE_CACHE) { + parseConfigCache[file] = result + } + return result +} + +function latestReleaseTime(agents) { + var latest = 0 + for (var name in agents) { + var dates = agents[name].releaseDate || {} + for (var key in dates) { + if (latest < dates[key]) { + latest = dates[key] + } + } + } + return latest * 1000 +} + +function getMonthsPassed(date) { + var now = new Date() + var past = new Date(date) + + var years = now.getFullYear() - past.getFullYear() + var months = now.getMonth() - past.getMonth() + + return years * 12 + months +} + +function normalizeStats(data, stats) { + if (!data) { + data = {} + } + if (stats && 'dataByBrowser' in stats) { + stats = stats.dataByBrowser + } + + if (typeof stats !== 'object') return undefined + + var normalized = {} + for (var i in stats) { + var versions = Object.keys(stats[i]) + if (versions.length === 1 && data[i] && data[i].versions.length === 1) { + var normal = data[i].versions[0] + normalized[i] = {} + normalized[i][normal] = stats[i][versions[0]] + } else { + normalized[i] = stats[i] + } + } + + return normalized +} + +function normalizeUsageData(usageData, data) { + for (var browser in usageData) { + var browserUsage = usageData[browser] + // https://github.com/browserslist/browserslist/issues/431#issuecomment-565230615 + // caniuse-db returns { 0: "percentage" } for `and_*` regional stats + if ('0' in browserUsage) { + var versions = data[browser].versions + browserUsage[versions[versions.length - 1]] = browserUsage[0] + delete browserUsage[0] + } + } +} + +module.exports = { + loadQueries: function loadQueries(ctx, name) { + if (!ctx.dangerousExtend && !process.env.BROWSERSLIST_DANGEROUS_EXTEND) { + checkExtend(name) + } + var queries = require(require.resolve(name, { paths: ['.', ctx.path] })) + if (typeof queries === 'object' && queries !== null && queries.__esModule) { + queries = queries.default + } + if (queries) { + if (Array.isArray(queries)) { + return queries + } else if (typeof queries === 'object') { + if (!queries.defaults) queries.defaults = [] + return pickEnv(queries, ctx, name) + } + } + throw new BrowserslistError( + '`' + + name + + '` config exports not an array of queries' + + ' or an object of envs' + ) + }, + + loadStat: function loadStat(ctx, name, data) { + if (!ctx.dangerousExtend && !process.env.BROWSERSLIST_DANGEROUS_EXTEND) { + checkExtend(name) + } + var stats = require( + // Use forward slashes for module paths, also on Windows. + require.resolve(path.posix.join(name, 'browserslist-stats.json'), { + paths: ['.'] + }) + ) + return normalizeStats(data, stats) + }, + + getStat: function getStat(opts, data) { + var stats + if (opts.stats) { + stats = opts.stats + } else if (process.env.BROWSERSLIST_STATS) { + stats = process.env.BROWSERSLIST_STATS + } else if (opts.path && path.resolve && fs.existsSync) { + stats = eachParent( + opts.path, + function (dir) { + var file = path.join(dir, 'browserslist-stats.json') + return isFile(file) ? file : undefined + }, + statCache + ) + } + if (typeof stats === 'string') { + try { + stats = JSON.parse(fs.readFileSync(stats)) + } catch (e) { + throw new BrowserslistError("Can't read " + stats) + } + } + return normalizeStats(data, stats) + }, + + loadConfig: function loadConfig(opts) { + if (process.env.BROWSERSLIST) { + return process.env.BROWSERSLIST + } else if (opts.config || process.env.BROWSERSLIST_CONFIG) { + var file = opts.config || process.env.BROWSERSLIST_CONFIG + return pickEnv(parsePackageOrReadConfig(file), opts) + } else if (opts.path) { + return pickEnv(module.exports.findConfig(opts.path), opts) + } else { + return undefined + } + }, + + loadCountry: function loadCountry(usage, country, data) { + var code = country.replace(/[^\w-]/g, '') + if (!usage[code]) { + var compressed + try { + compressed = require('caniuse-lite/data/regions/' + code + '.js') + } catch (e) { + throw new BrowserslistError('Unknown region name `' + code + '`.') + } + var usageData = region(compressed) + normalizeUsageData(usageData, data) + usage[country] = {} + for (var i in usageData) { + for (var j in usageData[i]) { + usage[country][i + ' ' + j] = usageData[i][j] + } + } + } + }, + + loadFeature: function loadFeature(features, name) { + name = name.replace(/[^\w-]/g, '') + if (features[name]) return + var compressed + try { + compressed = require('caniuse-lite/data/features/' + name + '.js') + } catch (e) { + throw new BrowserslistError('Unknown feature name `' + name + '`.') + } + var stats = feature(compressed).stats + features[name] = {} + for (var i in stats) { + features[name][i] = {} + for (var j in stats[i]) { + features[name][i][j] = stats[i][j] + } + } + }, + + parseConfig: function parseConfig(string) { + var result = { defaults: [] } + var sections = ['defaults'] + + string + .toString() + .replace(/#[^\n]*/g, '') + .split(/\n|,/) + .map(function (line) { + return line.trim() + }) + .filter(function (line) { + return line !== '' + }) + .forEach(function (line) { + if (IS_SECTION.test(line)) { + sections = line.match(IS_SECTION)[1].trim().split(' ') + sections.forEach(function (section) { + if (result[section]) { + throw new BrowserslistError( + 'Duplicate section ' + section + ' in Browserslist config' + ) + } + result[section] = [] + }) + } else { + sections.forEach(function (section) { + result[section].push(line) + }) + } + }) + + return result + }, + + readConfig: function readConfig(file) { + if (!isFile(file)) { + throw new BrowserslistError("Can't read " + file + ' config') + } + + return module.exports.parseConfig(fs.readFileSync(file)) + }, + + findConfigFile: function findConfigFile(from) { + return eachParent( + from, + function (dir) { + var config = path.join(dir, 'browserslist') + var pkg = path.join(dir, 'package.json') + var rc = path.join(dir, '.browserslistrc') + + var pkgBrowserslist + if (isFile(pkg)) { + try { + pkgBrowserslist = parsePackage(pkg) + } catch (e) { + if (e.name === 'BrowserslistError') throw e + console.warn( + '[Browserslist] Could not parse ' + pkg + '. Ignoring it.' + ) + } + } + + if (isFile(config) && pkgBrowserslist) { + throw new BrowserslistError( + dir + ' contains both browserslist and package.json with browsers' + ) + } else if (isFile(rc) && pkgBrowserslist) { + throw new BrowserslistError( + dir + + ' contains both .browserslistrc and package.json with browsers' + ) + } else if (isFile(config) && isFile(rc)) { + throw new BrowserslistError( + dir + ' contains both .browserslistrc and browserslist' + ) + } else if (isFile(config)) { + return config + } else if (isFile(rc)) { + return rc + } else if (pkgBrowserslist) { + return pkg + } + }, + configPathCache + ) + }, + + findConfig: function findConfig(from) { + var configFile = this.findConfigFile(from) + + return configFile ? parsePackageOrReadConfig(configFile) : undefined + }, + + clearCaches: function clearCaches() { + dataTimeChecked = false + statCache = {} + configPathCache = {} + parseConfigCache = {} + + this.cache = {} + }, + + oldDataWarning: function oldDataWarning(agentsObj) { + if (dataTimeChecked) return + dataTimeChecked = true + if (process.env.BROWSERSLIST_IGNORE_OLD_DATA) return + + var latest = latestReleaseTime(agentsObj) + var monthsPassed = getMonthsPassed(latest) + + if (latest !== 0 && monthsPassed >= 6) { + var months = monthsPassed + ' ' + (monthsPassed > 1 ? 'months' : 'month') + console.warn( + 'Browserslist: browsers data (caniuse-lite) is ' + + months + + ' old. Please run:\n' + + ' npx update-browserslist-db@latest\n' + + ' Why you should do it regularly: ' + + 'https://github.com/browserslist/update-db#readme' + ) + } + }, + + currentNode: function currentNode() { + return 'node ' + process.versions.node + }, + + env: process.env +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/browserslist/package.json b/novas/novacore-zephyr/claude-code-router/node_modules/browserslist/package.json new file mode 100644 index 0000000000000000000000000000000000000000..f3a967a4140fe5b6b48b663fa32dbde88568ecb7 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/browserslist/package.json @@ -0,0 +1,44 @@ +{ + "name": "browserslist", + "version": "4.25.4", + "description": "Share target browsers between different front-end tools, like Autoprefixer, Stylelint and babel-env-preset", + "keywords": [ + "caniuse", + "browsers", + "target" + ], + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "author": "Andrey Sitnik ", + "license": "MIT", + "repository": "browserslist/browserslist", + "dependencies": { + "caniuse-lite": "^1.0.30001737", + "electron-to-chromium": "^1.5.211", + "node-releases": "^2.0.19", + "update-browserslist-db": "^1.1.3" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + }, + "bin": { + "browserslist": "cli.js" + }, + "types": "./index.d.ts", + "browser": { + "./node.js": "./browser.js", + "path": false + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/browserslist/parse.js b/novas/novacore-zephyr/claude-code-router/node_modules/browserslist/parse.js new file mode 100644 index 0000000000000000000000000000000000000000..c9d8f45b418b3776aa460b79c61d68192cf1bfb5 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/browserslist/parse.js @@ -0,0 +1,78 @@ +var AND_REGEXP = /^\s+and\s+(.*)/i +var OR_REGEXP = /^(?:,\s*|\s+or\s+)(.*)/i + +function flatten(array) { + if (!Array.isArray(array)) return [array] + return array.reduce(function (a, b) { + return a.concat(flatten(b)) + }, []) +} + +function find(string, predicate) { + for (var max = string.length, n = 1; n <= max; n++) { + var parsed = string.substr(-n, n) + if (predicate(parsed, n, max)) { + return string.slice(0, -n) + } + } + return '' +} + +function matchQuery(all, query) { + var node = { query: query } + if (query.indexOf('not ') === 0) { + node.not = true + query = query.slice(4) + } + + for (var name in all) { + var type = all[name] + var match = query.match(type.regexp) + if (match) { + node.type = name + for (var i = 0; i < type.matches.length; i++) { + node[type.matches[i]] = match[i + 1] + } + return node + } + } + + node.type = 'unknown' + return node +} + +function matchBlock(all, string, qs) { + var node + return find(string, function (parsed, n, max) { + if (AND_REGEXP.test(parsed)) { + node = matchQuery(all, parsed.match(AND_REGEXP)[1]) + node.compose = 'and' + qs.unshift(node) + return true + } else if (OR_REGEXP.test(parsed)) { + node = matchQuery(all, parsed.match(OR_REGEXP)[1]) + node.compose = 'or' + qs.unshift(node) + return true + } else if (n === max) { + node = matchQuery(all, parsed.trim()) + node.compose = 'or' + qs.unshift(node) + return true + } + return false + }) +} + +module.exports = function parse(all, queries) { + if (!Array.isArray(queries)) queries = [queries] + return flatten( + queries.map(function (block) { + var qs = [] + do { + block = matchBlock(all, block, qs) + } while (block) + return qs + }) + ) +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/bs-logger/CHANGELOG.md b/novas/novacore-zephyr/claude-code-router/node_modules/bs-logger/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..19364b81d170aae84a2fec024a46992203dbdfa2 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/bs-logger/CHANGELOG.md @@ -0,0 +1,60 @@ + +## [0.2.6](https://github.com/huafu/bs-logger/compare/v0.2.5...v0.2.6) (2018-11-10) + + + + +## [0.2.5](https://github.com/huafu/bs-logger/compare/v0.2.4...v0.2.5) (2018-09-04) + + + + +## [0.2.4](https://github.com/huafu/bs-logger/compare/v0.2.3...v0.2.4) (2018-09-04) + + + + +## [0.2.3](https://github.com/huafu/bs-logger/compare/v0.2.2...v0.2.3) (2018-08-31) + + +### Bug Fixes + +* **formatter:** allow json formatter to serialize circular data ([103bac0](https://github.com/huafu/bs-logger/commit/103bac0)) + + + + +## [0.2.2](https://github.com/huafu/bs-logger/compare/v0.2.1...v0.2.2) (2018-08-31) + + +### Bug Fixes + +* **testing:** adds LoggerMock to exported symbols ([134dab8](https://github.com/huafu/bs-logger/commit/134dab8)) + + + + +## [0.2.1](https://github.com/huafu/bs-logger/compare/v0.2.0...v0.2.1) (2018-08-31) + + + + +# [0.2.0](https://github.com/huafu/bs-logger/compare/v0.1.1...v0.2.0) (2018-08-31) + + +### Features + +* **testing:** adds helpers for testing ([0e65a49](https://github.com/huafu/bs-logger/commit/0e65a49)) + + + + +## [0.1.1](https://github.com/huafu/bs-logger/compare/02d6fc7...v0.1.1) (2018-08-30) + + +### Features + +* adds custom formatters ([02d6fc7](https://github.com/huafu/bs-logger/commit/02d6fc7)) + + + diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/bs-logger/LICENSE b/novas/novacore-zephyr/claude-code-router/node_modules/bs-logger/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..116a6d1ae2c7dcfa878196015b89a819bdbe6cf2 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/bs-logger/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Huafu Gandon + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/bs-logger/README.md b/novas/novacore-zephyr/claude-code-router/node_modules/bs-logger/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c885264e3f01b365151e6c3fef0a9abbd566dd3a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/bs-logger/README.md @@ -0,0 +1,319 @@ + + +# B.S. Logger [![Build Status](https://travis-ci.org/huafu/bs-logger.svg?branch=master)](https://travis-ci.org/huafu/bs-logger) [![Coverage Status](https://img.shields.io/coveralls/huafu/bs-logger/master.svg)](https://coveralls.io/github/huafu/bs-logger?branch=master) [![Beerpay](https://beerpay.io/huafu/bs-logger/badge.svg?style=beer-square)](https://beerpay.io/huafu/bs-logger) [![Beerpay](https://beerpay.io/huafu/bs-logger/make-wish.svg?style=flat-square)](https://beerpay.io/huafu/bs-logger?focus=wish) + +**Opinionated bare simple logger for NodeJS (with TypeScript typings)**. + +BSLogger has been created after being disapointed not finding a matching logger on the internet. Not that others aren't good, they just did not fit what I was looking for. + +Here is what I was looking for (and tried to implemented in BSLogger): +- light memory usage +- easily extendable (see `child` method) +- as few dependencies as possible +- ability to define all targets in a string (so that `ENV` vars can be used) +- when using file targets, not re-opening them +- reasonable defautls: + - logs warnings and above to `stderr` + - logs JSON to files +- no overhead if it's not going to log anywhere + +## TL,DR: + +Install: +```sh +npm install --save bs-logger +# or +yarn add bs-logger +``` +Use: +```js +const { logger } = require('bs-logger'); +// or +// import logger from 'bs-logger'; +// or +// import { logger } from 'bs-logger'; +// as default exports the logger + +logger('foo'); +logger.debug('bar'); +logger.warn({foo: 'bar'}, 'dummy', 'other'/*, ...*/); +``` + +More complex example: +```js +// env MY_LOG_TARGETS="debug.log:trace,stderr:warn%json" +import { createLogger } from 'bs-logger'; +const logger = createLogger({ + context: {namespace: 'http'}, + targets: process.env.MY_LOG_TARGETS, + translate: (m) => { + if (process.env.NODE_ENV === 'production') { + m.context = { ...m.context, secret: null }; + } + return m; + }, +}); +// [...] +logger.debug({secret: 'xyz'}, 'trying to login') +// will log into debug.log `trying to login` with secret in the context except in prod + +const login = logger.wrap(function login() { + // your login code +}) +// [...] +login(); +// will log `calling login` with the arguments in context +``` + +## Usage + +### Creating a logger + +#### Root logger + +BSLogger exports a global logger lazyly created on first use, but it is advised to create your own using the `createLogger()` helper: + +- If you are using it in a library wich is meant to be re-distributed: + ```js + import { createLogger, LogContexts } 'bs-logger'; + const logger = createLogger({ [LogContexts.package]: 'my-pacakge' }); + ``` + +- If you are using it in an application of your own: + ```js + import { createLogger, LogContexts } 'bs-logger'; + const logger = createLogger({ [LogContexts.application]: 'my-app' }); + ``` + +#### Child logger + +Child loggers extends the context, targets and message translators from their parent. You create a child logger using the `child` method: + +```js +const childLogger = logger.child({ [LogContexts.namespace]: 'http' }) +// childLogger becomes a new logger +``` + +### Logging + +Any helper to log within BSLogger is a function which has the same signature as `console.log()`, and also accepts an **optional** first argument being the context. A context is any `object`, with some specific (but optional) properties which we'll see later. + +```ts +logMethod(message: string, ...args: any[]): void + // or +logMethod(context: LogContext, message: string, ...args: any[]): void +``` + +#### Directly + +You can log using any logger as a function directly (if the logger or its possible parent(s) has not been created with any log level in its context, no level will be attached): +```js +import { createLogger } from 'bs-logger' +const logger = createLogger() +// [...] +logger('my message'); +``` + +#### Using level helpers + +BSLogger is aware of 6 log levels (`trace`, `debug`, `info`, `warn`, `error` and `fatal`) but you can create your owns. A log level is basically a number. The higher it is, the more important will be the message. You can find log levels constants in `LogLevels` export: +```js +import { LogLevels } from 'bs-logger'; + +const traceLevelValue = LogLevels.trace; +const debugLevelValue = LogLevels.debug; +// etc. +``` + +For each log level listed above, a logger will have a helper method to directly log using this level: +```js +import { createLogger } from 'bs-logger' +const logger = createLogger() +// [...] +logger.trace('foo') +logger.debug('bar') +// etc. +``` + +Those helpers are the equivalent to +```js +logger({ [LogContexts.logLevel]: level }, 'foo') +``` +...except that they'll be replaced with an empty function on the first call if their level will not be handled by any target. + +### Wrapping functions + +Each logger has a `wrap` method which you can use to wrap a function. If there is no matching log target, the `wrap` method will simply return your function, else it'll wrap it in another function of same signature. The wrapper will, before calling your function, log a message with received arguments in the context. + +```ts +// With `F` being the type of your funciton: +logger.wrap(func: F): F + // or +logger.wrap(message: string, func: F): F + // or +logger.wrap(context: LogContext, messages: string, func: F): F +``` + +### Defining target(s) + +Each root logger (created using `createLogger` helper) is attached to 0 or more "target". A target is responsible of writing a log entry somewhere. It is an object with the following properties: + +- **minLevel** `string`: The minimum log level this target's strem writer will be called for +- **stream** `{ write: (str: string) => void }`: An object with a write function (like node's `stream.Writable`) which will be used to write log entries +- **format** `(msg: LogMessage) => string`: A formatter which will be used to transform a log entry (message object) into a string + +#### Using targets + +When using the global logger, or if no `targets` specified when creating a logger, calling log methods will output to STDERR anything which has log level higher or equal to `warn`. This can be modified as follow by defineing the `LOG_TARGETS` environment variable or passing the `targets` option to `createLogger`. The `targets` can be an array of `LogTarget` (see above) or a `string` defining a list of one or more targets separated by comma (`,`). A `string` target is composed as follow: +- The file path, absolute or relative to CWD. It can also be the specials `stdout` or `stderr` strings (case insensitive). When giving a path to a file, if it ends with the plus sign (`+`) the log data will be appended to the file instead of re-creating the file for each run. +- An optional minimum log level after a colon (`:`). It should be a `number` or the log level name (ie `trace`, `error`, ...). +- An optional formatter name after a percent sign (`%`). There are 2 included formatter: `json` (used for files by default) and `simple` (used for `stdout` and `stderr` by default). See below to define your own. + +Examples: +- `debug.log%simple,stdout:fatal` + - Log everything to `debug.log` file in CWD dir (re-creates the file for each run). Uses the `simple` formatter. + - Log only messages with level >= `fatal` to the standard out. +- `errors.log+:error,debug.log:15` + - Log only messages with level >= `error` to `errors.log` file (without re-creating the file at each run). + - Log only messages with level >= 15 to `debug.log` file (re-creates the file for each run). + +#### Custom formatters + +A custom formatter is a function that takes a `LogMessage` object and returns a `string`. It can be registered giving it a name using the `registerLogFormatter` helper: + +```js +import { registerLogFormatter, createLogger } from 'bs-logger'; +registerLogFormatter('foo', m => `${m.sequence} ${new Date(m.tim).toLocaleString()} ${m.message}`); +const logger = createLogger({ + targets: 'stdout%foo', // specifying out formatter + }); +``` + +### Testing + +The whole `testing` namespace has useful helpers for using BSLogger while unit testing your product. + +In your tests you would usually prefer not having any logging to happen, or you would like to check what has been logged but without actually logging it to any target. + +The `testing` namespace holds all testing utilities: +```js +import { testing } from 'bs-logger' +``` + +- If you use the root logger, here is how to disable its output: +```js +testing.setup() +``` +and the `logger` (or `default`) export will become a `LoggerMock` instance (see below). + +- If you create logger(s) using `createLogger`, when testing use the `testing.createLoggerMock` instead. It accepts the same first argument, with an extra second argument, optional, being the `LogTargetMock` to be used (see below). + +#### LoggerMock + +Loggers created using the `testing` namespace will have one and only one log target being a `LogTargetMock`, and that target will be set on the `target` extra property of the logger. + +Here are the extra properties of `LogTargetMock` which you can then use for testing: + +- **messages** `LogMessage[]`: all log message objects which would have normally be logged + - **last** `LogMessage`: the last one being logged + - **trace** `LogMessage[]`: all log message objects with `trace` level + - **last** `LogMessage`: last one with `trace` level + - **debug** `LogMessage[]`: all log message objects with `debug` level + - **last** `LogMessage`: last one with `debug` level + - ... +- **lines** `string[]`: all formatted log message lines which would have normally be logged + - **last** `string`: the last one being logged + - **trace** `string[]`: all formatted log message lines with `trace` level + - **last** `string`: last one with `trace` level + - **debug** `string[]`: all formatted log message lines with `debug` level + - **last** `string`: last one with `debug` level + - ... +- **clear** `() => void`: method to clear all log message objects and formatted lines +- **filteredMessages** `(level: number | null, untilLevel?: number) => LogMessage[]`: method to filter log message objects +- **filteredLins** `(level: number | null, untilLevel?: number) => string[]`: method to filter formatted log message lines + +#### Example + +Let's say you have a `logger.js` file in which you create the logger for your app: +```js +// file: logger.js +import { testing, createLogger, LogContexts } from 'bs-logger'; + +const factory = process.env.TEST ? testing.createLoggerMock : createLogger; + +export default factory({ [LogContexts.application]: 'foo' }); +``` + +In a test you could: +```js +import logger from './logger'; +// in `fetch(url)` you'd use the logger like `logger.debug({url}, 'GET')` when the request is actually made +import fetch from './http'; + +test('it should cache request', () => { + logger.target.clear(); + fetch('http://foo.bar/dummy.json'); + expect(logger.target.messages.length).toBe(1); + fetch('http://foo.bar/dummy.json'); + expect(logger.target.messages.length).toBe(1); + // you can also expect on the message: + expect(logger.target.messages.last.message).toBe('GET') + expect(logger.target.messages.last.context.url).toBe('http://foo.bar/dummy.json') + // or (mock target formater prefix the message with `[level:xxx] ` when there is a level) + expect(logger.target.lines.last).toBe('[level:20] GET') + // or filtering with level: + expect(logger.target.lines.debug.last).toBe('[level:20] GET') +}); +``` + +## Installing + +Add to your project with `npm`: + +```bash +npm install --save bs-logger +``` + +or with `yarn`: + +```bash +yarn add bs-logger +``` + +## Running the tests + +You need to get a copy of the repository to run the tests: + +```bash +git clone https://github.com/huafu/bs-logger.git +cd bs-logger +npm run test +``` + +## Built With + +* [TypeScript](https://www.typescriptlang.org/) +* [ts-jest](https://github.com/kulshekhar/ts-jest) + +## Contributing + +Pull requests welcome! + +## Versioning + +We use [SemVer](http://semver.org/) for versioning. For the versions available, see the [tags on this repository](https://github.com/huafu/bs-logger/tags). + +## Authors + +* **Huafu Gandon** - *Initial work* - [huafu](https://github.com/huafu) + +See also the list of [contributors](https://github.com/huafu/bs-logger/contributors) who participated in this project. + +## License + +This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details + +## Support on Beerpay +Hey dude! Help me out for a couple of :beers:! + +[![Beerpay](https://beerpay.io/huafu/bs-logger/badge.svg?style=beer-square)](https://beerpay.io/huafu/bs-logger) [![Beerpay](https://beerpay.io/huafu/bs-logger/make-wish.svg?style=flat-square)](https://beerpay.io/huafu/bs-logger?focus=wish) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/bs-logger/package.json b/novas/novacore-zephyr/claude-code-router/node_modules/bs-logger/package.json new file mode 100644 index 0000000000000000000000000000000000000000..1a28a6359057be50491277c96521dc398fd6d5bf --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/bs-logger/package.json @@ -0,0 +1,73 @@ +{ + "name": "bs-logger", + "version": "0.2.6", + "description": "Bare simple logger for NodeJS", + "author": "Huafu Gandon ", + "license": "MIT", + "repository": "git+https://github.com/huafu/bs-logger.git", + "main": "dist/index.js", + "types": "dist/index.d.ts", + "scripts": { + "build": "tsc -p tsconfig.build.json", + "clean": "rimraf dist coverage", + "typecheck": "tsc -p . --noEmit", + "lint": "tslint --project tsconfig.json --format stylish", + "lint:fix": "tslint --fix --project tsconfig.json", + "test": "jest --coverage", + "test:watch": "jest --watch", + "prebuild": "npm run clean", + "posttest": "npm run typecheck && npm run lint", + "prepare": "npm run build", + "prepublishOnly": "npm run test", + "preversion": "npm test", + "version": "npm run changelog && git add CHANGELOG.md", + "postversion": "git push && git push --tags", + "changelog": "conventional-changelog -p angular -i CHANGELOG.md -s -r 0", + "commitmsg": "commitlint -E GIT_PARAMS", + "precommit": "lint-staged", + "postcommit": "git reset" + }, + "keywords": [ + "bare simple logger", + "simple logger", + "simple", + "logger", + "typescript", + "lib", + "library" + ], + "files": [ + "dist" + ], + "devDependencies": { + "@commitlint/cli": "7.x", + "@commitlint/config-conventional": "7.x", + "@types/jest": "23.x", + "@types/node": "10.x", + "conventional-changelog-cli": "2.x", + "husky": "0.x", + "jest": "23.x", + "lint-staged": "7.x", + "prettier": "1.x", + "rimraf": "2.x", + "ts-jest": "23.x", + "tslint": "5.x", + "tslint-config-prettier": "1.x", + "tslint-plugin-prettier": "2.x", + "typescript": "3.x" + }, + "dependencies": { + "fast-json-stable-stringify": "2.x" + }, + "lint-staged": { + "linters": { + "*.{ts,tsx}": [ + "tslint --fix", + "git add" + ] + } + }, + "engines": { + "node": ">= 6" + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/bser/README.md b/novas/novacore-zephyr/claude-code-router/node_modules/bser/README.md new file mode 100644 index 0000000000000000000000000000000000000000..eab0658aa521bc54bbbe94eb32024ec1ce684201 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/bser/README.md @@ -0,0 +1,81 @@ +# BSER Binary Serialization + +BSER is a binary serialization scheme that can be used as an alternative to JSON. +BSER uses a framed encoding that makes it simpler to use to stream a sequence of +encoded values. + +It is intended to be used for local-IPC only and strings are represented as binary +with no specific encoding; this matches the convention employed by most operating +system filename storage. + +For more details about the serialization scheme see +[Watchman's docs](https://facebook.github.io/watchman/docs/bser.html). + +## API + +```js +var bser = require('bser'); +``` + +### bser.loadFromBuffer + +The is the synchronous decoder; given an input string or buffer, +decodes a single value and returns it. Throws an error if the +input is invalid. + +```js +var obj = bser.loadFromBuffer(buf); +``` + +### bser.dumpToBuffer + +Synchronously encodes a value as BSER. + +```js +var encoded = bser.dumpToBuffer(['hello']); +console.log(bser.loadFromBuffer(encoded)); // ['hello'] +``` + +### BunserBuf + +The asynchronous decoder API is implemented in the BunserBuf object. +You may incrementally append data to this object and it will emit the +decoded values via its `value` event. + +```js +var bunser = new bser.BunserBuf(); + +bunser.on('value', function(obj) { + console.log(obj); +}); +``` + +Then in your socket `data` event: + +```js +bunser.append(buf); +``` + +## Example + +Read BSER from socket: + +```js +var bunser = new bser.BunserBuf(); + +bunser.on('value', function(obj) { + console.log('data from socket', obj); +}); + +var socket = net.connect('/socket'); + +socket.on('data', function(buf) { + bunser.append(buf); +}); +``` + +Write BSER to socket: + +```js +socket.write(bser.dumpToBuffer(obj)); +``` diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/bser/index.js b/novas/novacore-zephyr/claude-code-router/node_modules/bser/index.js new file mode 100644 index 0000000000000000000000000000000000000000..4ae14d3003e649fe4b3b9551339c3c7ee69a878d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/bser/index.js @@ -0,0 +1,586 @@ +/* Copyright 2015-present Facebook, Inc. + * Licensed under the Apache License, Version 2.0 */ + +var EE = require('events').EventEmitter; +var util = require('util'); +var os = require('os'); +var assert = require('assert'); +var Int64 = require('node-int64'); + +// BSER uses the local endianness to reduce byte swapping overheads +// (the protocol is expressly local IPC only). We need to tell node +// to use the native endianness when reading various native values. +var isBigEndian = os.endianness() == 'BE'; + +// Find the next power-of-2 >= size +function nextPow2(size) { + return Math.pow(2, Math.ceil(Math.log(size) / Math.LN2)); +} + +// Expandable buffer that we can provide a size hint for +function Accumulator(initsize) { + this.buf = Buffer.alloc(nextPow2(initsize || 8192)); + this.readOffset = 0; + this.writeOffset = 0; +} +// For testing +exports.Accumulator = Accumulator + +// How much we can write into this buffer without allocating +Accumulator.prototype.writeAvail = function() { + return this.buf.length - this.writeOffset; +} + +// How much we can read +Accumulator.prototype.readAvail = function() { + return this.writeOffset - this.readOffset; +} + +// Ensure that we have enough space for size bytes +Accumulator.prototype.reserve = function(size) { + if (size < this.writeAvail()) { + return; + } + + // If we can make room by shunting down, do so + if (this.readOffset > 0) { + this.buf.copy(this.buf, 0, this.readOffset, this.writeOffset); + this.writeOffset -= this.readOffset; + this.readOffset = 0; + } + + // If we made enough room, no need to allocate more + if (size < this.writeAvail()) { + return; + } + + // Allocate a replacement and copy it in + var buf = Buffer.alloc(nextPow2(this.buf.length + size - this.writeAvail())); + this.buf.copy(buf); + this.buf = buf; +} + +// Append buffer or string. Will resize as needed +Accumulator.prototype.append = function(buf) { + if (Buffer.isBuffer(buf)) { + this.reserve(buf.length); + buf.copy(this.buf, this.writeOffset, 0, buf.length); + this.writeOffset += buf.length; + } else { + var size = Buffer.byteLength(buf); + this.reserve(size); + this.buf.write(buf, this.writeOffset); + this.writeOffset += size; + } +} + +Accumulator.prototype.assertReadableSize = function(size) { + if (this.readAvail() < size) { + throw new Error("wanted to read " + size + + " bytes but only have " + this.readAvail()); + } +} + +Accumulator.prototype.peekString = function(size) { + this.assertReadableSize(size); + return this.buf.toString('utf-8', this.readOffset, this.readOffset + size); +} + +Accumulator.prototype.readString = function(size) { + var str = this.peekString(size); + this.readOffset += size; + return str; +} + +Accumulator.prototype.peekInt = function(size) { + this.assertReadableSize(size); + switch (size) { + case 1: + return this.buf.readInt8(this.readOffset, size); + case 2: + return isBigEndian ? + this.buf.readInt16BE(this.readOffset, size) : + this.buf.readInt16LE(this.readOffset, size); + case 4: + return isBigEndian ? + this.buf.readInt32BE(this.readOffset, size) : + this.buf.readInt32LE(this.readOffset, size); + case 8: + var big = this.buf.slice(this.readOffset, this.readOffset + 8); + if (isBigEndian) { + // On a big endian system we can simply pass the buffer directly + return new Int64(big); + } + // Otherwise we need to byteswap + return new Int64(byteswap64(big)); + default: + throw new Error("invalid integer size " + size); + } +} + +Accumulator.prototype.readInt = function(bytes) { + var ival = this.peekInt(bytes); + if (ival instanceof Int64 && isFinite(ival.valueOf())) { + ival = ival.valueOf(); + } + this.readOffset += bytes; + return ival; +} + +Accumulator.prototype.peekDouble = function() { + this.assertReadableSize(8); + return isBigEndian ? + this.buf.readDoubleBE(this.readOffset) : + this.buf.readDoubleLE(this.readOffset); +} + +Accumulator.prototype.readDouble = function() { + var dval = this.peekDouble(); + this.readOffset += 8; + return dval; +} + +Accumulator.prototype.readAdvance = function(size) { + if (size > 0) { + this.assertReadableSize(size); + } else if (size < 0 && this.readOffset + size < 0) { + throw new Error("advance with negative offset " + size + + " would seek off the start of the buffer"); + } + this.readOffset += size; +} + +Accumulator.prototype.writeByte = function(value) { + this.reserve(1); + this.buf.writeInt8(value, this.writeOffset); + ++this.writeOffset; +} + +Accumulator.prototype.writeInt = function(value, size) { + this.reserve(size); + switch (size) { + case 1: + this.buf.writeInt8(value, this.writeOffset); + break; + case 2: + if (isBigEndian) { + this.buf.writeInt16BE(value, this.writeOffset); + } else { + this.buf.writeInt16LE(value, this.writeOffset); + } + break; + case 4: + if (isBigEndian) { + this.buf.writeInt32BE(value, this.writeOffset); + } else { + this.buf.writeInt32LE(value, this.writeOffset); + } + break; + default: + throw new Error("unsupported integer size " + size); + } + this.writeOffset += size; +} + +Accumulator.prototype.writeDouble = function(value) { + this.reserve(8); + if (isBigEndian) { + this.buf.writeDoubleBE(value, this.writeOffset); + } else { + this.buf.writeDoubleLE(value, this.writeOffset); + } + this.writeOffset += 8; +} + +var BSER_ARRAY = 0x00; +var BSER_OBJECT = 0x01; +var BSER_STRING = 0x02; +var BSER_INT8 = 0x03; +var BSER_INT16 = 0x04; +var BSER_INT32 = 0x05; +var BSER_INT64 = 0x06; +var BSER_REAL = 0x07; +var BSER_TRUE = 0x08; +var BSER_FALSE = 0x09; +var BSER_NULL = 0x0a; +var BSER_TEMPLATE = 0x0b; +var BSER_SKIP = 0x0c; + +var ST_NEED_PDU = 0; // Need to read and decode PDU length +var ST_FILL_PDU = 1; // Know the length, need to read whole content + +var MAX_INT8 = 127; +var MAX_INT16 = 32767; +var MAX_INT32 = 2147483647; + +function BunserBuf() { + EE.call(this); + this.buf = new Accumulator(); + this.state = ST_NEED_PDU; +} +util.inherits(BunserBuf, EE); +exports.BunserBuf = BunserBuf; + +BunserBuf.prototype.append = function(buf, synchronous) { + if (synchronous) { + this.buf.append(buf); + return this.process(synchronous); + } + + try { + this.buf.append(buf); + } catch (err) { + this.emit('error', err); + return; + } + // Arrange to decode later. This allows the consuming + // application to make progress with other work in the + // case that we have a lot of subscription updates coming + // in from a large tree. + this.processLater(); +} + +BunserBuf.prototype.processLater = function() { + var self = this; + process.nextTick(function() { + try { + self.process(false); + } catch (err) { + self.emit('error', err); + } + }); +} + +// Do something with the buffer to advance our state. +// If we're running synchronously we'll return either +// the value we've decoded or undefined if we don't +// yet have enought data. +// If we're running asynchronously, we'll emit the value +// when it becomes ready and schedule another invocation +// of process on the next tick if we still have data we +// can process. +BunserBuf.prototype.process = function(synchronous) { + if (this.state == ST_NEED_PDU) { + if (this.buf.readAvail() < 2) { + return; + } + // Validate BSER header + this.expectCode(0); + this.expectCode(1); + this.pduLen = this.decodeInt(true /* relaxed */); + if (this.pduLen === false) { + // Need more data, walk backwards + this.buf.readAdvance(-2); + return; + } + // Ensure that we have a big enough buffer to read the rest of the PDU + this.buf.reserve(this.pduLen); + this.state = ST_FILL_PDU; + } + + if (this.state == ST_FILL_PDU) { + if (this.buf.readAvail() < this.pduLen) { + // Need more data + return; + } + + // We have enough to decode it + var val = this.decodeAny(); + if (synchronous) { + return val; + } + this.emit('value', val); + this.state = ST_NEED_PDU; + } + + if (!synchronous && this.buf.readAvail() > 0) { + this.processLater(); + } +} + +BunserBuf.prototype.raise = function(reason) { + throw new Error(reason + ", in Buffer of length " + + this.buf.buf.length + " (" + this.buf.readAvail() + + " readable) at offset " + this.buf.readOffset + " buffer: " + + JSON.stringify(this.buf.buf.slice( + this.buf.readOffset, this.buf.readOffset + 32).toJSON())); +} + +BunserBuf.prototype.expectCode = function(expected) { + var code = this.buf.readInt(1); + if (code != expected) { + this.raise("expected bser opcode " + expected + " but got " + code); + } +} + +BunserBuf.prototype.decodeAny = function() { + var code = this.buf.peekInt(1); + switch (code) { + case BSER_INT8: + case BSER_INT16: + case BSER_INT32: + case BSER_INT64: + return this.decodeInt(); + case BSER_REAL: + this.buf.readAdvance(1); + return this.buf.readDouble(); + case BSER_TRUE: + this.buf.readAdvance(1); + return true; + case BSER_FALSE: + this.buf.readAdvance(1); + return false; + case BSER_NULL: + this.buf.readAdvance(1); + return null; + case BSER_STRING: + return this.decodeString(); + case BSER_ARRAY: + return this.decodeArray(); + case BSER_OBJECT: + return this.decodeObject(); + case BSER_TEMPLATE: + return this.decodeTemplate(); + default: + this.raise("unhandled bser opcode " + code); + } +} + +BunserBuf.prototype.decodeArray = function() { + this.expectCode(BSER_ARRAY); + var nitems = this.decodeInt(); + var arr = []; + for (var i = 0; i < nitems; ++i) { + arr.push(this.decodeAny()); + } + return arr; +} + +BunserBuf.prototype.decodeObject = function() { + this.expectCode(BSER_OBJECT); + var nitems = this.decodeInt(); + var res = {}; + for (var i = 0; i < nitems; ++i) { + var key = this.decodeString(); + var val = this.decodeAny(); + res[key] = val; + } + return res; +} + +BunserBuf.prototype.decodeTemplate = function() { + this.expectCode(BSER_TEMPLATE); + var keys = this.decodeArray(); + var nitems = this.decodeInt(); + var arr = []; + for (var i = 0; i < nitems; ++i) { + var obj = {}; + for (var keyidx = 0; keyidx < keys.length; ++keyidx) { + if (this.buf.peekInt(1) == BSER_SKIP) { + this.buf.readAdvance(1); + continue; + } + var val = this.decodeAny(); + obj[keys[keyidx]] = val; + } + arr.push(obj); + } + return arr; +} + +BunserBuf.prototype.decodeString = function() { + this.expectCode(BSER_STRING); + var len = this.decodeInt(); + return this.buf.readString(len); +} + +// This is unusual compared to the other decode functions in that +// we may not have enough data available to satisfy the read, and +// we don't want to throw. This is only true when we're reading +// the PDU length from the PDU header; we'll set relaxSizeAsserts +// in that case. +BunserBuf.prototype.decodeInt = function(relaxSizeAsserts) { + if (relaxSizeAsserts && (this.buf.readAvail() < 1)) { + return false; + } else { + this.buf.assertReadableSize(1); + } + var code = this.buf.peekInt(1); + var size = 0; + switch (code) { + case BSER_INT8: + size = 1; + break; + case BSER_INT16: + size = 2; + break; + case BSER_INT32: + size = 4; + break; + case BSER_INT64: + size = 8; + break; + default: + this.raise("invalid bser int encoding " + code); + } + + if (relaxSizeAsserts && (this.buf.readAvail() < 1 + size)) { + return false; + } + this.buf.readAdvance(1); + return this.buf.readInt(size); +} + +// synchronously BSER decode a string and return the value +function loadFromBuffer(input) { + var buf = new BunserBuf(); + var result = buf.append(input, true); + if (buf.buf.readAvail()) { + throw Error( + 'excess data found after input buffer, use BunserBuf instead'); + } + if (typeof result === 'undefined') { + throw Error( + 'no bser found in string and no error raised!?'); + } + return result; +} +exports.loadFromBuffer = loadFromBuffer + +// Byteswap an arbitrary buffer, flipping from one endian +// to the other, returning a new buffer with the resultant data +function byteswap64(buf) { + var swap = Buffer.alloc(buf.length); + for (var i = 0; i < buf.length; i++) { + swap[i] = buf[buf.length -1 - i]; + } + return swap; +} + +function dump_int64(buf, val) { + // Get the raw bytes. The Int64 buffer is big endian + var be = val.toBuffer(); + + if (isBigEndian) { + // We're a big endian system, so the buffer is exactly how we + // want it to be + buf.writeByte(BSER_INT64); + buf.append(be); + return; + } + // We need to byte swap to get the correct representation + var le = byteswap64(be); + buf.writeByte(BSER_INT64); + buf.append(le); +} + +function dump_int(buf, val) { + var abs = Math.abs(val); + if (abs <= MAX_INT8) { + buf.writeByte(BSER_INT8); + buf.writeInt(val, 1); + } else if (abs <= MAX_INT16) { + buf.writeByte(BSER_INT16); + buf.writeInt(val, 2); + } else if (abs <= MAX_INT32) { + buf.writeByte(BSER_INT32); + buf.writeInt(val, 4); + } else { + dump_int64(buf, new Int64(val)); + } +} + +function dump_any(buf, val) { + switch (typeof(val)) { + case 'number': + // check if it is an integer or a float + if (isFinite(val) && Math.floor(val) === val) { + dump_int(buf, val); + } else { + buf.writeByte(BSER_REAL); + buf.writeDouble(val); + } + return; + case 'string': + buf.writeByte(BSER_STRING); + dump_int(buf, Buffer.byteLength(val)); + buf.append(val); + return; + case 'boolean': + buf.writeByte(val ? BSER_TRUE : BSER_FALSE); + return; + case 'object': + if (val === null) { + buf.writeByte(BSER_NULL); + return; + } + if (val instanceof Int64) { + dump_int64(buf, val); + return; + } + if (Array.isArray(val)) { + buf.writeByte(BSER_ARRAY); + dump_int(buf, val.length); + for (var i = 0; i < val.length; ++i) { + dump_any(buf, val[i]); + } + return; + } + buf.writeByte(BSER_OBJECT); + var keys = Object.keys(val); + + // First pass to compute number of defined keys + var num_keys = keys.length; + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + var v = val[key]; + if (typeof(v) == 'undefined') { + num_keys--; + } + } + dump_int(buf, num_keys); + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + var v = val[key]; + if (typeof(v) == 'undefined') { + // Don't include it + continue; + } + dump_any(buf, key); + try { + dump_any(buf, v); + } catch (e) { + throw new Error( + e.message + ' (while serializing object property with name `' + + key + "')"); + } + } + return; + + default: + throw new Error('cannot serialize type ' + typeof(val) + ' to BSER'); + } +} + +// BSER encode value and return a buffer of the contents +function dumpToBuffer(val) { + var buf = new Accumulator(); + // Build out the header + buf.writeByte(0); + buf.writeByte(1); + // Reserve room for an int32 to hold our PDU length + buf.writeByte(BSER_INT32); + buf.writeInt(0, 4); // We'll come back and fill this in at the end + + dump_any(buf, val); + + // Compute PDU length + var off = buf.writeOffset; + var len = off - 7 /* the header length */; + buf.writeOffset = 3; // The length value to fill in + buf.writeInt(len, 4); // write the length in the space we reserved + buf.writeOffset = off; + + return buf.buf.slice(0, off); +} +exports.dumpToBuffer = dumpToBuffer diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/bser/package.json b/novas/novacore-zephyr/claude-code-router/node_modules/bser/package.json new file mode 100644 index 0000000000000000000000000000000000000000..824f7d4170091e601984ca2353377889464d42c5 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/bser/package.json @@ -0,0 +1,33 @@ +{ + "name": "bser", + "version": "2.1.1", + "description": "JavaScript implementation of the BSER Binary Serialization", + "main": "index.js", + "directories": { + "test": "test" + }, + "scripts": { + "test": "node test/bser.js" + }, + "files": [ + "index.js" + ], + "repository": { + "type": "git", + "url": "https://github.com/facebook/watchman" + }, + "keywords": [ + "bser", + "binary", + "protocol" + ], + "author": "Wez Furlong (http://wezfurlong.org)", + "license": "Apache-2.0", + "bugs": { + "url": "https://github.com/facebook/watchman/issues" + }, + "homepage": "https://facebook.github.io/watchman/docs/bser.html", + "dependencies": { + "node-int64": "^0.4.0" + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/buffer-from/LICENSE b/novas/novacore-zephyr/claude-code-router/node_modules/buffer-from/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..e4bf1d69b1bb0df5acf1278e583264acdc1eefc5 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/buffer-from/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2016, 2018 Linus Unnebäck + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/buffer-from/index.js b/novas/novacore-zephyr/claude-code-router/node_modules/buffer-from/index.js new file mode 100644 index 0000000000000000000000000000000000000000..e1a58b5e8a06fd24ce5321aa6b08255dc9d0716d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/buffer-from/index.js @@ -0,0 +1,72 @@ +/* eslint-disable node/no-deprecated-api */ + +var toString = Object.prototype.toString + +var isModern = ( + typeof Buffer !== 'undefined' && + typeof Buffer.alloc === 'function' && + typeof Buffer.allocUnsafe === 'function' && + typeof Buffer.from === 'function' +) + +function isArrayBuffer (input) { + return toString.call(input).slice(8, -1) === 'ArrayBuffer' +} + +function fromArrayBuffer (obj, byteOffset, length) { + byteOffset >>>= 0 + + var maxLength = obj.byteLength - byteOffset + + if (maxLength < 0) { + throw new RangeError("'offset' is out of bounds") + } + + if (length === undefined) { + length = maxLength + } else { + length >>>= 0 + + if (length > maxLength) { + throw new RangeError("'length' is out of bounds") + } + } + + return isModern + ? Buffer.from(obj.slice(byteOffset, byteOffset + length)) + : new Buffer(new Uint8Array(obj.slice(byteOffset, byteOffset + length))) +} + +function fromString (string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + return isModern + ? Buffer.from(string, encoding) + : new Buffer(string, encoding) +} + +function bufferFrom (value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (isArrayBuffer(value)) { + return fromArrayBuffer(value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(value, encodingOrOffset) + } + + return isModern + ? Buffer.from(value) + : new Buffer(value) +} + +module.exports = bufferFrom diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/buffer-from/package.json b/novas/novacore-zephyr/claude-code-router/node_modules/buffer-from/package.json new file mode 100644 index 0000000000000000000000000000000000000000..6ac5327bf8621ef03a3df8039518a98ba3d1648a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/buffer-from/package.json @@ -0,0 +1,19 @@ +{ + "name": "buffer-from", + "version": "1.1.2", + "license": "MIT", + "repository": "LinusU/buffer-from", + "files": [ + "index.js" + ], + "scripts": { + "test": "standard && node test" + }, + "devDependencies": { + "standard": "^12.0.1" + }, + "keywords": [ + "buffer", + "buffer from" + ] +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/buffer-from/readme.md b/novas/novacore-zephyr/claude-code-router/node_modules/buffer-from/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..9880a558a7c91fefb0e6908318fbd991b6b93dcf --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/buffer-from/readme.md @@ -0,0 +1,69 @@ +# Buffer From + +A [ponyfill](https://ponyfill.com) for `Buffer.from`, uses native implementation if available. + +## Installation + +```sh +npm install --save buffer-from +``` + +## Usage + +```js +const bufferFrom = require('buffer-from') + +console.log(bufferFrom([1, 2, 3, 4])) +//=> + +const arr = new Uint8Array([1, 2, 3, 4]) +console.log(bufferFrom(arr.buffer, 1, 2)) +//=> + +console.log(bufferFrom('test', 'utf8')) +//=> + +const buf = bufferFrom('test') +console.log(bufferFrom(buf)) +//=> +``` + +## API + +### bufferFrom(array) + +- `array` <Array> + +Allocates a new `Buffer` using an `array` of octets. + +### bufferFrom(arrayBuffer[, byteOffset[, length]]) + +- `arrayBuffer` <ArrayBuffer> The `.buffer` property of a TypedArray or ArrayBuffer +- `byteOffset` <Integer> Where to start copying from `arrayBuffer`. **Default:** `0` +- `length` <Integer> How many bytes to copy from `arrayBuffer`. **Default:** `arrayBuffer.length - byteOffset` + +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. + +The optional `byteOffset` and `length` arguments specify a memory range within +the `arrayBuffer` that will be shared by the `Buffer`. + +### bufferFrom(buffer) + +- `buffer` <Buffer> An existing `Buffer` to copy data from + +Copies the passed `buffer` data onto a new `Buffer` instance. + +### bufferFrom(string[, encoding]) + +- `string` <String> A string to encode. +- `encoding` <String> The encoding of `string`. **Default:** `'utf8'` + +Creates a new `Buffer` containing the given JavaScript string `string`. If +provided, the `encoding` parameter identifies the character encoding of +`string`. + +## See also + +- [buffer-alloc](https://github.com/LinusU/buffer-alloc) A ponyfill for `Buffer.alloc` +- [buffer-alloc-unsafe](https://github.com/LinusU/buffer-alloc-unsafe) A ponyfill for `Buffer.allocUnsafe` diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/callsites/index.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/callsites/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..61f597cf5beeb066b6ee4d084f9097223e417460 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/callsites/index.d.ts @@ -0,0 +1,96 @@ +declare namespace callsites { + interface CallSite { + /** + Returns the value of `this`. + */ + getThis(): unknown | undefined; + + /** + Returns the type of `this` as a string. This is the name of the function stored in the constructor field of `this`, if available, otherwise the object's `[[Class]]` internal property. + */ + getTypeName(): string | null; + + /** + Returns the current function. + */ + getFunction(): Function | undefined; + + /** + Returns the name of the current function, typically its `name` property. If a name property is not available an attempt will be made to try to infer a name from the function's context. + */ + getFunctionName(): string | null; + + /** + Returns the name of the property of `this` or one of its prototypes that holds the current function. + */ + getMethodName(): string | undefined; + + /** + Returns the name of the script if this function was defined in a script. + */ + getFileName(): string | null; + + /** + Returns the current line number if this function was defined in a script. + */ + getLineNumber(): number | null; + + /** + Returns the current column number if this function was defined in a script. + */ + getColumnNumber(): number | null; + + /** + Returns a string representing the location where `eval` was called if this function was created using a call to `eval`. + */ + getEvalOrigin(): string | undefined; + + /** + Returns `true` if this is a top-level invocation, that is, if it's a global object. + */ + isToplevel(): boolean; + + /** + Returns `true` if this call takes place in code defined by a call to `eval`. + */ + isEval(): boolean; + + /** + Returns `true` if this call is in native V8 code. + */ + isNative(): boolean; + + /** + Returns `true` if this is a constructor call. + */ + isConstructor(): boolean; + } +} + +declare const callsites: { + /** + Get callsites from the V8 stack trace API. + + @returns An array of `CallSite` objects. + + @example + ``` + import callsites = require('callsites'); + + function unicorn() { + console.log(callsites()[0].getFileName()); + //=> '/Users/sindresorhus/dev/callsites/test.js' + } + + unicorn(); + ``` + */ + (): callsites.CallSite[]; + + // TODO: Remove this for the next major release, refactor the whole definition to: + // declare function callsites(): callsites.CallSite[]; + // export = callsites; + default: typeof callsites; +}; + +export = callsites; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/callsites/index.js b/novas/novacore-zephyr/claude-code-router/node_modules/callsites/index.js new file mode 100644 index 0000000000000000000000000000000000000000..486c2410479cde342624eceaa1e0b1deca9317eb --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/callsites/index.js @@ -0,0 +1,13 @@ +'use strict'; + +const callsites = () => { + const _prepareStackTrace = Error.prepareStackTrace; + Error.prepareStackTrace = (_, stack) => stack; + const stack = new Error().stack.slice(1); + Error.prepareStackTrace = _prepareStackTrace; + return stack; +}; + +module.exports = callsites; +// TODO: Remove this for the next major release +module.exports.default = callsites; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/callsites/license b/novas/novacore-zephyr/claude-code-router/node_modules/callsites/license new file mode 100644 index 0000000000000000000000000000000000000000..e7af2f77107d73046421ef56c4684cbfdd3c1e89 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/callsites/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/callsites/package.json b/novas/novacore-zephyr/claude-code-router/node_modules/callsites/package.json new file mode 100644 index 0000000000000000000000000000000000000000..93463c34b25dab3a11fcb6522825789395fb624c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/callsites/package.json @@ -0,0 +1,39 @@ +{ + "name": "callsites", + "version": "3.1.0", + "description": "Get callsites from the V8 stack trace API", + "license": "MIT", + "repository": "sindresorhus/callsites", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=6" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "stacktrace", + "v8", + "callsite", + "callsites", + "stack", + "trace", + "function", + "file", + "line", + "debug" + ], + "devDependencies": { + "ava": "^1.4.1", + "tsd": "^0.7.2", + "xo": "^0.24.0" + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/callsites/readme.md b/novas/novacore-zephyr/claude-code-router/node_modules/callsites/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..fc846138f4a80d237fbe14a49bd7beef6510a711 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/callsites/readme.md @@ -0,0 +1,48 @@ +# callsites [![Build Status](https://travis-ci.org/sindresorhus/callsites.svg?branch=master)](https://travis-ci.org/sindresorhus/callsites) + +> Get callsites from the [V8 stack trace API](https://v8.dev/docs/stack-trace-api) + + +## Install + +``` +$ npm install callsites +``` + + +## Usage + +```js +const callsites = require('callsites'); + +function unicorn() { + console.log(callsites()[0].getFileName()); + //=> '/Users/sindresorhus/dev/callsites/test.js' +} + +unicorn(); +``` + + +## API + +Returns an array of callsite objects with the following methods: + +- `getThis`: returns the value of `this`. +- `getTypeName`: returns the type of `this` as a string. This is the name of the function stored in the constructor field of `this`, if available, otherwise the object's `[[Class]]` internal property. +- `getFunction`: returns the current function. +- `getFunctionName`: returns the name of the current function, typically its `name` property. If a name property is not available an attempt will be made to try to infer a name from the function's context. +- `getMethodName`: returns the name of the property of `this` or one of its prototypes that holds the current function. +- `getFileName`: if this function was defined in a script returns the name of the script. +- `getLineNumber`: if this function was defined in a script returns the current line number. +- `getColumnNumber`: if this function was defined in a script returns the current column number +- `getEvalOrigin`: if this function was created using a call to `eval` returns a string representing the location where `eval` was called. +- `isToplevel`: is this a top-level invocation, that is, is this the global object? +- `isEval`: does this call take place in code defined by a call to `eval`? +- `isNative`: is this call in native V8 code? +- `isConstructor`: is this a constructor call? + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/camelcase/index.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/camelcase/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..58f2069adc52b8411087314385132d20a4d5d8c5 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/camelcase/index.d.ts @@ -0,0 +1,63 @@ +declare namespace camelcase { + interface Options { + /** + Uppercase the first character: `foo-bar` → `FooBar`. + + @default false + */ + readonly pascalCase?: boolean; + } +} + +declare const camelcase: { + /** + Convert a dash/dot/underscore/space separated string to camelCase or PascalCase: `foo-bar` → `fooBar`. + + @param input - String to convert to camel case. + + @example + ``` + import camelCase = require('camelcase'); + + camelCase('foo-bar'); + //=> 'fooBar' + + camelCase('foo_bar'); + //=> 'fooBar' + + camelCase('Foo-Bar'); + //=> 'fooBar' + + camelCase('Foo-Bar', {pascalCase: true}); + //=> 'FooBar' + + camelCase('--foo.bar', {pascalCase: false}); + //=> 'fooBar' + + camelCase('foo bar'); + //=> 'fooBar' + + console.log(process.argv[3]); + //=> '--foo-bar' + camelCase(process.argv[3]); + //=> 'fooBar' + + camelCase(['foo', 'bar']); + //=> 'fooBar' + + camelCase(['__foo__', '--bar'], {pascalCase: true}); + //=> 'FooBar' + ``` + */ + (input: string | ReadonlyArray, options?: camelcase.Options): string; + + // TODO: Remove this for the next major release, refactor the whole definition to: + // declare function camelcase( + // input: string | ReadonlyArray, + // options?: camelcase.Options + // ): string; + // export = camelcase; + default: typeof camelcase; +}; + +export = camelcase; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/camelcase/index.js b/novas/novacore-zephyr/claude-code-router/node_modules/camelcase/index.js new file mode 100644 index 0000000000000000000000000000000000000000..579f99b47f772aa47b7e683069987b9299411f09 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/camelcase/index.js @@ -0,0 +1,76 @@ +'use strict'; + +const preserveCamelCase = string => { + let isLastCharLower = false; + let isLastCharUpper = false; + let isLastLastCharUpper = false; + + for (let i = 0; i < string.length; i++) { + const character = string[i]; + + if (isLastCharLower && /[a-zA-Z]/.test(character) && character.toUpperCase() === character) { + string = string.slice(0, i) + '-' + string.slice(i); + isLastCharLower = false; + isLastLastCharUpper = isLastCharUpper; + isLastCharUpper = true; + i++; + } else if (isLastCharUpper && isLastLastCharUpper && /[a-zA-Z]/.test(character) && character.toLowerCase() === character) { + string = string.slice(0, i - 1) + '-' + string.slice(i - 1); + isLastLastCharUpper = isLastCharUpper; + isLastCharUpper = false; + isLastCharLower = true; + } else { + isLastCharLower = character.toLowerCase() === character && character.toUpperCase() !== character; + isLastLastCharUpper = isLastCharUpper; + isLastCharUpper = character.toUpperCase() === character && character.toLowerCase() !== character; + } + } + + return string; +}; + +const camelCase = (input, options) => { + if (!(typeof input === 'string' || Array.isArray(input))) { + throw new TypeError('Expected the input to be `string | string[]`'); + } + + options = Object.assign({ + pascalCase: false + }, options); + + const postProcess = x => options.pascalCase ? x.charAt(0).toUpperCase() + x.slice(1) : x; + + if (Array.isArray(input)) { + input = input.map(x => x.trim()) + .filter(x => x.length) + .join('-'); + } else { + input = input.trim(); + } + + if (input.length === 0) { + return ''; + } + + if (input.length === 1) { + return options.pascalCase ? input.toUpperCase() : input.toLowerCase(); + } + + const hasUpperCase = input !== input.toLowerCase(); + + if (hasUpperCase) { + input = preserveCamelCase(input); + } + + input = input + .replace(/^[_.\- ]+/, '') + .toLowerCase() + .replace(/[_.\- ]+(\w|$)/g, (_, p1) => p1.toUpperCase()) + .replace(/\d+(\w|$)/g, m => m.toUpperCase()); + + return postProcess(input); +}; + +module.exports = camelCase; +// TODO: Remove this for the next major release +module.exports.default = camelCase; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/camelcase/license b/novas/novacore-zephyr/claude-code-router/node_modules/camelcase/license new file mode 100644 index 0000000000000000000000000000000000000000..e7af2f77107d73046421ef56c4684cbfdd3c1e89 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/camelcase/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/camelcase/package.json b/novas/novacore-zephyr/claude-code-router/node_modules/camelcase/package.json new file mode 100644 index 0000000000000000000000000000000000000000..fbdbaaa75651d6ca23908caa68a9c75e8a60952c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/camelcase/package.json @@ -0,0 +1,43 @@ +{ + "name": "camelcase", + "version": "5.3.1", + "description": "Convert a dash/dot/underscore/space separated string to camelCase or PascalCase: `foo-bar` → `fooBar`", + "license": "MIT", + "repository": "sindresorhus/camelcase", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=6" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "camelcase", + "camel-case", + "camel", + "case", + "dash", + "hyphen", + "dot", + "underscore", + "separator", + "string", + "text", + "convert", + "pascalcase", + "pascal-case" + ], + "devDependencies": { + "ava": "^1.4.1", + "tsd": "^0.7.1", + "xo": "^0.24.0" + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/camelcase/readme.md b/novas/novacore-zephyr/claude-code-router/node_modules/camelcase/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..fde27261b2a823b6b6a4601025da513061eb217e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/camelcase/readme.md @@ -0,0 +1,99 @@ +# camelcase [![Build Status](https://travis-ci.org/sindresorhus/camelcase.svg?branch=master)](https://travis-ci.org/sindresorhus/camelcase) + +> Convert a dash/dot/underscore/space separated string to camelCase or PascalCase: `foo-bar` → `fooBar` + +--- + +
+ + Get professional support for 'camelcase' with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
+ +--- + +## Install + +``` +$ npm install camelcase +``` + + +## Usage + +```js +const camelCase = require('camelcase'); + +camelCase('foo-bar'); +//=> 'fooBar' + +camelCase('foo_bar'); +//=> 'fooBar' + +camelCase('Foo-Bar'); +//=> 'fooBar' + +camelCase('Foo-Bar', {pascalCase: true}); +//=> 'FooBar' + +camelCase('--foo.bar', {pascalCase: false}); +//=> 'fooBar' + +camelCase('foo bar'); +//=> 'fooBar' + +console.log(process.argv[3]); +//=> '--foo-bar' +camelCase(process.argv[3]); +//=> 'fooBar' + +camelCase(['foo', 'bar']); +//=> 'fooBar' + +camelCase(['__foo__', '--bar'], {pascalCase: true}); +//=> 'FooBar' +``` + + +## API + +### camelCase(input, [options]) + +#### input + +Type: `string` `string[]` + +String to convert to camel case. + +#### options + +Type: `Object` + +##### pascalCase + +Type: `boolean`
+Default: `false` + +Uppercase the first character: `foo-bar` → `FooBar` + + +## Security + +To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. + + +## Related + +- [decamelize](https://github.com/sindresorhus/decamelize) - The inverse of this module +- [uppercamelcase](https://github.com/SamVerschueren/uppercamelcase) - Like this module, but to PascalCase instead of camelCase +- [titleize](https://github.com/sindresorhus/titleize) - Capitalize every word in string +- [humanize-string](https://github.com/sindresorhus/humanize-string) - Convert a camelized/dasherized/underscored string into a humanized one + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/caniuse-lite/LICENSE b/novas/novacore-zephyr/claude-code-router/node_modules/caniuse-lite/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..06c608dcf4552094bc86dc48aaa90addb2886049 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/caniuse-lite/LICENSE @@ -0,0 +1,395 @@ +Attribution 4.0 International + +======================================================================= + +Creative Commons Corporation ("Creative Commons") is not a law firm and +does not provide legal services or legal advice. Distribution of +Creative Commons public licenses does not create a lawyer-client or +other relationship. Creative Commons makes its licenses and related +information available on an "as-is" basis. Creative Commons gives no +warranties regarding its licenses, any material licensed under their +terms and conditions, or any related information. Creative Commons +disclaims all liability for damages resulting from their use to the +fullest extent possible. + +Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and +conditions that creators and other rights holders may use to share +original works of authorship and other material subject to copyright +and certain other rights specified in the public license below. The +following considerations are for informational purposes only, are not +exhaustive, and do not form part of our licenses. + + Considerations for licensors: Our public licenses are + intended for use by those authorized to give the public + permission to use material in ways otherwise restricted by + copyright and certain other rights. Our licenses are + irrevocable. Licensors should read and understand the terms + and conditions of the license they choose before applying it. + Licensors should also secure all rights necessary before + applying our licenses so that the public can reuse the + material as expected. Licensors should clearly mark any + material not subject to the license. This includes other CC- + licensed material, or material used under an exception or + limitation to copyright. More considerations for licensors: + wiki.creativecommons.org/Considerations_for_licensors + + Considerations for the public: By using one of our public + licenses, a licensor grants the public permission to use the + licensed material under specified terms and conditions. If + the licensor's permission is not necessary for any reason--for + example, because of any applicable exception or limitation to + copyright--then that use is not regulated by the license. Our + licenses grant only permissions under copyright and certain + other rights that a licensor has authority to grant. Use of + the licensed material may still be restricted for other + reasons, including because others have copyright or other + rights in the material. A licensor may make special requests, + such as asking that all changes be marked or described. + Although not required by our licenses, you are encouraged to + respect those requests where reasonable. More_considerations + for the public: + wiki.creativecommons.org/Considerations_for_licensees + +======================================================================= + +Creative Commons Attribution 4.0 International Public License + +By exercising the Licensed Rights (defined below), You accept and agree +to be bound by the terms and conditions of this Creative Commons +Attribution 4.0 International Public License ("Public License"). To the +extent this Public License may be interpreted as a contract, You are +granted the Licensed Rights in consideration of Your acceptance of +these terms and conditions, and the Licensor grants You such rights in +consideration of benefits the Licensor receives from making the +Licensed Material available under these terms and conditions. + + +Section 1 -- Definitions. + + a. Adapted Material means material subject to Copyright and Similar + Rights that is derived from or based upon the Licensed Material + and in which the Licensed Material is translated, altered, + arranged, transformed, or otherwise modified in a manner requiring + permission under the Copyright and Similar Rights held by the + Licensor. For purposes of this Public License, where the Licensed + Material is a musical work, performance, or sound recording, + Adapted Material is always produced where the Licensed Material is + synched in timed relation with a moving image. + + b. Adapter's License means the license You apply to Your Copyright + and Similar Rights in Your contributions to Adapted Material in + accordance with the terms and conditions of this Public License. + + c. Copyright and Similar Rights means copyright and/or similar rights + closely related to copyright including, without limitation, + performance, broadcast, sound recording, and Sui Generis Database + Rights, without regard to how the rights are labeled or + categorized. For purposes of this Public License, the rights + specified in Section 2(b)(1)-(2) are not Copyright and Similar + Rights. + + d. Effective Technological Measures means those measures that, in the + absence of proper authority, may not be circumvented under laws + fulfilling obligations under Article 11 of the WIPO Copyright + Treaty adopted on December 20, 1996, and/or similar international + agreements. + + e. Exceptions and Limitations means fair use, fair dealing, and/or + any other exception or limitation to Copyright and Similar Rights + that applies to Your use of the Licensed Material. + + f. Licensed Material means the artistic or literary work, database, + or other material to which the Licensor applied this Public + License. + + g. Licensed Rights means the rights granted to You subject to the + terms and conditions of this Public License, which are limited to + all Copyright and Similar Rights that apply to Your use of the + Licensed Material and that the Licensor has authority to license. + + h. Licensor means the individual(s) or entity(ies) granting rights + under this Public License. + + i. Share means to provide material to the public by any means or + process that requires permission under the Licensed Rights, such + as reproduction, public display, public performance, distribution, + dissemination, communication, or importation, and to make material + available to the public including in ways that members of the + public may access the material from a place and at a time + individually chosen by them. + + j. Sui Generis Database Rights means rights other than copyright + resulting from Directive 96/9/EC of the European Parliament and of + the Council of 11 March 1996 on the legal protection of databases, + as amended and/or succeeded, as well as other essentially + equivalent rights anywhere in the world. + + k. You means the individual or entity exercising the Licensed Rights + under this Public License. Your has a corresponding meaning. + + +Section 2 -- Scope. + + a. License grant. + + 1. Subject to the terms and conditions of this Public License, + the Licensor hereby grants You a worldwide, royalty-free, + non-sublicensable, non-exclusive, irrevocable license to + exercise the Licensed Rights in the Licensed Material to: + + a. reproduce and Share the Licensed Material, in whole or + in part; and + + b. produce, reproduce, and Share Adapted Material. + + 2. Exceptions and Limitations. For the avoidance of doubt, where + Exceptions and Limitations apply to Your use, this Public + License does not apply, and You do not need to comply with + its terms and conditions. + + 3. Term. The term of this Public License is specified in Section + 6(a). + + 4. Media and formats; technical modifications allowed. The + Licensor authorizes You to exercise the Licensed Rights in + all media and formats whether now known or hereafter created, + and to make technical modifications necessary to do so. The + Licensor waives and/or agrees not to assert any right or + authority to forbid You from making technical modifications + necessary to exercise the Licensed Rights, including + technical modifications necessary to circumvent Effective + Technological Measures. For purposes of this Public License, + simply making modifications authorized by this Section 2(a) + (4) never produces Adapted Material. + + 5. Downstream recipients. + + a. Offer from the Licensor -- Licensed Material. Every + recipient of the Licensed Material automatically + receives an offer from the Licensor to exercise the + Licensed Rights under the terms and conditions of this + Public License. + + b. No downstream restrictions. You may not offer or impose + any additional or different terms or conditions on, or + apply any Effective Technological Measures to, the + Licensed Material if doing so restricts exercise of the + Licensed Rights by any recipient of the Licensed + Material. + + 6. No endorsement. Nothing in this Public License constitutes or + may be construed as permission to assert or imply that You + are, or that Your use of the Licensed Material is, connected + with, or sponsored, endorsed, or granted official status by, + the Licensor or others designated to receive attribution as + provided in Section 3(a)(1)(A)(i). + + b. Other rights. + + 1. Moral rights, such as the right of integrity, are not + licensed under this Public License, nor are publicity, + privacy, and/or other similar personality rights; however, to + the extent possible, the Licensor waives and/or agrees not to + assert any such rights held by the Licensor to the limited + extent necessary to allow You to exercise the Licensed + Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this + Public License. + + 3. To the extent possible, the Licensor waives any right to + collect royalties from You for the exercise of the Licensed + Rights, whether directly or through a collecting society + under any voluntary or waivable statutory or compulsory + licensing scheme. In all other cases the Licensor expressly + reserves any right to collect such royalties. + + +Section 3 -- License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the +following conditions. + + a. Attribution. + + 1. If You Share the Licensed Material (including in modified + form), You must: + + a. retain the following if it is supplied by the Licensor + with the Licensed Material: + + i. identification of the creator(s) of the Licensed + Material and any others designated to receive + attribution, in any reasonable manner requested by + the Licensor (including by pseudonym if + designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of + warranties; + + v. a URI or hyperlink to the Licensed Material to the + extent reasonably practicable; + + b. indicate if You modified the Licensed Material and + retain an indication of any previous modifications; and + + c. indicate the Licensed Material is licensed under this + Public License, and include the text of, or the URI or + hyperlink to, this Public License. + + 2. You may satisfy the conditions in Section 3(a)(1) in any + reasonable manner based on the medium, means, and context in + which You Share the Licensed Material. For example, it may be + reasonable to satisfy the conditions by providing a URI or + hyperlink to a resource that includes the required + information. + + 3. If requested by the Licensor, You must remove any of the + information required by Section 3(a)(1)(A) to the extent + reasonably practicable. + + 4. If You Share Adapted Material You produce, the Adapter's + License You apply must not prevent recipients of the Adapted + Material from complying with this Public License. + + +Section 4 -- Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that +apply to Your use of the Licensed Material: + + a. for the avoidance of doubt, Section 2(a)(1) grants You the right + to extract, reuse, reproduce, and Share all or a substantial + portion of the contents of the database; + + b. if You include all or a substantial portion of the database + contents in a database in which You have Sui Generis Database + Rights, then the database in which You have Sui Generis Database + Rights (but not its individual contents) is Adapted Material; and + + c. You must comply with the conditions in Section 3(a) if You Share + all or a substantial portion of the contents of the database. + +For the avoidance of doubt, this Section 4 supplements and does not +replace Your obligations under this Public License where the Licensed +Rights include other Copyright and Similar Rights. + + +Section 5 -- Disclaimer of Warranties and Limitation of Liability. + + a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE + EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS + AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF + ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, + IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, + WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR + PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, + ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT + KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT + ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. + + b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE + TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, + NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, + INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, + COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR + USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN + ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR + DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR + IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. + + c. The disclaimer of warranties and limitation of liability provided + above shall be interpreted in a manner that, to the extent + possible, most closely approximates an absolute disclaimer and + waiver of all liability. + + +Section 6 -- Term and Termination. + + a. This Public License applies for the term of the Copyright and + Similar Rights licensed here. However, if You fail to comply with + this Public License, then Your rights under this Public License + terminate automatically. + + b. Where Your right to use the Licensed Material has terminated under + Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided + it is cured within 30 days of Your discovery of the + violation; or + + 2. upon express reinstatement by the Licensor. + + For the avoidance of doubt, this Section 6(b) does not affect any + right the Licensor may have to seek remedies for Your violations + of this Public License. + + c. For the avoidance of doubt, the Licensor may also offer the + Licensed Material under separate terms or conditions or stop + distributing the Licensed Material at any time; however, doing so + will not terminate this Public License. + + d. Sections 1, 5, 6, 7, and 8 survive termination of this Public + License. + + +Section 7 -- Other Terms and Conditions. + + a. The Licensor shall not be bound by any additional or different + terms or conditions communicated by You unless expressly agreed. + + b. Any arrangements, understandings, or agreements regarding the + Licensed Material not stated herein are separate from and + independent of the terms and conditions of this Public License. + + +Section 8 -- Interpretation. + + a. For the avoidance of doubt, this Public License does not, and + shall not be interpreted to, reduce, limit, restrict, or impose + conditions on any use of the Licensed Material that could lawfully + be made without permission under this Public License. + + b. To the extent possible, if any provision of this Public License is + deemed unenforceable, it shall be automatically reformed to the + minimum extent necessary to make it enforceable. If the provision + cannot be reformed, it shall be severed from this Public License + without affecting the enforceability of the remaining terms and + conditions. + + c. No term or condition of this Public License will be waived and no + failure to comply consented to unless expressly agreed to by the + Licensor. + + d. Nothing in this Public License constitutes or may be interpreted + as a limitation upon, or waiver of, any privileges and immunities + that apply to the Licensor or You, including from the legal + processes of any jurisdiction or authority. + + +======================================================================= + +Creative Commons is not a party to its public +licenses. Notwithstanding, Creative Commons may elect to apply one of +its public licenses to material it publishes and in those instances +will be considered the “Licensor.” The text of the Creative Commons +public licenses is dedicated to the public domain under the CC0 Public +Domain Dedication. Except for the limited purpose of indicating that +material is shared under a Creative Commons public license or as +otherwise permitted by the Creative Commons policies published at +creativecommons.org/policies, Creative Commons does not authorize the +use of the trademark "Creative Commons" or any other trademark or logo +of Creative Commons without its prior written consent including, +without limitation, in connection with any unauthorized modifications +to any of its public licenses or any other arrangements, +understandings, or agreements concerning use of licensed material. For +the avoidance of doubt, this paragraph does not form part of the +public licenses. + +Creative Commons may be contacted at creativecommons.org. diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/caniuse-lite/README.md b/novas/novacore-zephyr/claude-code-router/node_modules/caniuse-lite/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f2c67bc49c21c31524feea64bc1fe97150e648bc --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/caniuse-lite/README.md @@ -0,0 +1,6 @@ +# caniuse-lite + +A smaller version of caniuse-db, with only the essentials! + +## Docs +Read full docs **[here](https://github.com/browserslist/caniuse-lite#readme)**. diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/caniuse-lite/package.json b/novas/novacore-zephyr/claude-code-router/node_modules/caniuse-lite/package.json new file mode 100644 index 0000000000000000000000000000000000000000..d4e4117c60a6fb27ae2281911bcc309aac8eea01 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/caniuse-lite/package.json @@ -0,0 +1,34 @@ +{ + "name": "caniuse-lite", + "version": "1.0.30001737", + "description": "A smaller version of caniuse-db, with only the essentials!", + "main": "dist/unpacker/index.js", + "files": [ + "data", + "dist" + ], + "keywords": [ + "support" + ], + "author": { + "name": "Ben Briggs", + "email": "beneb.info@gmail.com", + "url": "http://beneb.info" + }, + "repository": "browserslist/caniuse-lite", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "CC-BY-4.0" +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/chalk/index.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/chalk/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9cd88f38beea8708b25ee3f797ebc453dffa4fb0 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/chalk/index.d.ts @@ -0,0 +1,415 @@ +/** +Basic foreground colors. + +[More colors here.](https://github.com/chalk/chalk/blob/master/readme.md#256-and-truecolor-color-support) +*/ +declare type ForegroundColor = + | 'black' + | 'red' + | 'green' + | 'yellow' + | 'blue' + | 'magenta' + | 'cyan' + | 'white' + | 'gray' + | 'grey' + | 'blackBright' + | 'redBright' + | 'greenBright' + | 'yellowBright' + | 'blueBright' + | 'magentaBright' + | 'cyanBright' + | 'whiteBright'; + +/** +Basic background colors. + +[More colors here.](https://github.com/chalk/chalk/blob/master/readme.md#256-and-truecolor-color-support) +*/ +declare type BackgroundColor = + | 'bgBlack' + | 'bgRed' + | 'bgGreen' + | 'bgYellow' + | 'bgBlue' + | 'bgMagenta' + | 'bgCyan' + | 'bgWhite' + | 'bgGray' + | 'bgGrey' + | 'bgBlackBright' + | 'bgRedBright' + | 'bgGreenBright' + | 'bgYellowBright' + | 'bgBlueBright' + | 'bgMagentaBright' + | 'bgCyanBright' + | 'bgWhiteBright'; + +/** +Basic colors. + +[More colors here.](https://github.com/chalk/chalk/blob/master/readme.md#256-and-truecolor-color-support) +*/ +declare type Color = ForegroundColor | BackgroundColor; + +declare type Modifiers = + | 'reset' + | 'bold' + | 'dim' + | 'italic' + | 'underline' + | 'inverse' + | 'hidden' + | 'strikethrough' + | 'visible'; + +declare namespace chalk { + /** + Levels: + - `0` - All colors disabled. + - `1` - Basic 16 colors support. + - `2` - ANSI 256 colors support. + - `3` - Truecolor 16 million colors support. + */ + type Level = 0 | 1 | 2 | 3; + + interface Options { + /** + Specify the color support for Chalk. + + By default, color support is automatically detected based on the environment. + + Levels: + - `0` - All colors disabled. + - `1` - Basic 16 colors support. + - `2` - ANSI 256 colors support. + - `3` - Truecolor 16 million colors support. + */ + level?: Level; + } + + /** + Return a new Chalk instance. + */ + type Instance = new (options?: Options) => Chalk; + + /** + Detect whether the terminal supports color. + */ + interface ColorSupport { + /** + The color level used by Chalk. + */ + level: Level; + + /** + Return whether Chalk supports basic 16 colors. + */ + hasBasic: boolean; + + /** + Return whether Chalk supports ANSI 256 colors. + */ + has256: boolean; + + /** + Return whether Chalk supports Truecolor 16 million colors. + */ + has16m: boolean; + } + + interface ChalkFunction { + /** + Use a template string. + + @remarks Template literals are unsupported for nested calls (see [issue #341](https://github.com/chalk/chalk/issues/341)) + + @example + ``` + import chalk = require('chalk'); + + log(chalk` + CPU: {red ${cpu.totalPercent}%} + RAM: {green ${ram.used / ram.total * 100}%} + DISK: {rgb(255,131,0) ${disk.used / disk.total * 100}%} + `); + ``` + + @example + ``` + import chalk = require('chalk'); + + log(chalk.red.bgBlack`2 + 3 = {bold ${2 + 3}}`) + ``` + */ + (text: TemplateStringsArray, ...placeholders: unknown[]): string; + + (...text: unknown[]): string; + } + + interface Chalk extends ChalkFunction { + /** + Return a new Chalk instance. + */ + Instance: Instance; + + /** + The color support for Chalk. + + By default, color support is automatically detected based on the environment. + + Levels: + - `0` - All colors disabled. + - `1` - Basic 16 colors support. + - `2` - ANSI 256 colors support. + - `3` - Truecolor 16 million colors support. + */ + level: Level; + + /** + Use HEX value to set text color. + + @param color - Hexadecimal value representing the desired color. + + @example + ``` + import chalk = require('chalk'); + + chalk.hex('#DEADED'); + ``` + */ + hex(color: string): Chalk; + + /** + Use keyword color value to set text color. + + @param color - Keyword value representing the desired color. + + @example + ``` + import chalk = require('chalk'); + + chalk.keyword('orange'); + ``` + */ + keyword(color: string): Chalk; + + /** + Use RGB values to set text color. + */ + rgb(red: number, green: number, blue: number): Chalk; + + /** + Use HSL values to set text color. + */ + hsl(hue: number, saturation: number, lightness: number): Chalk; + + /** + Use HSV values to set text color. + */ + hsv(hue: number, saturation: number, value: number): Chalk; + + /** + Use HWB values to set text color. + */ + hwb(hue: number, whiteness: number, blackness: number): Chalk; + + /** + Use a [Select/Set Graphic Rendition](https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_parameters) (SGR) [color code number](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4_bit) to set text color. + + 30 <= code && code < 38 || 90 <= code && code < 98 + For example, 31 for red, 91 for redBright. + */ + ansi(code: number): Chalk; + + /** + Use a [8-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) to set text color. + */ + ansi256(index: number): Chalk; + + /** + Use HEX value to set background color. + + @param color - Hexadecimal value representing the desired color. + + @example + ``` + import chalk = require('chalk'); + + chalk.bgHex('#DEADED'); + ``` + */ + bgHex(color: string): Chalk; + + /** + Use keyword color value to set background color. + + @param color - Keyword value representing the desired color. + + @example + ``` + import chalk = require('chalk'); + + chalk.bgKeyword('orange'); + ``` + */ + bgKeyword(color: string): Chalk; + + /** + Use RGB values to set background color. + */ + bgRgb(red: number, green: number, blue: number): Chalk; + + /** + Use HSL values to set background color. + */ + bgHsl(hue: number, saturation: number, lightness: number): Chalk; + + /** + Use HSV values to set background color. + */ + bgHsv(hue: number, saturation: number, value: number): Chalk; + + /** + Use HWB values to set background color. + */ + bgHwb(hue: number, whiteness: number, blackness: number): Chalk; + + /** + Use a [Select/Set Graphic Rendition](https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_parameters) (SGR) [color code number](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4_bit) to set background color. + + 30 <= code && code < 38 || 90 <= code && code < 98 + For example, 31 for red, 91 for redBright. + Use the foreground code, not the background code (for example, not 41, nor 101). + */ + bgAnsi(code: number): Chalk; + + /** + Use a [8-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) to set background color. + */ + bgAnsi256(index: number): Chalk; + + /** + Modifier: Resets the current color chain. + */ + readonly reset: Chalk; + + /** + Modifier: Make text bold. + */ + readonly bold: Chalk; + + /** + Modifier: Emitting only a small amount of light. + */ + readonly dim: Chalk; + + /** + Modifier: Make text italic. (Not widely supported) + */ + readonly italic: Chalk; + + /** + Modifier: Make text underline. (Not widely supported) + */ + readonly underline: Chalk; + + /** + Modifier: Inverse background and foreground colors. + */ + readonly inverse: Chalk; + + /** + Modifier: Prints the text, but makes it invisible. + */ + readonly hidden: Chalk; + + /** + Modifier: Puts a horizontal line through the center of the text. (Not widely supported) + */ + readonly strikethrough: Chalk; + + /** + Modifier: Prints the text only when Chalk has a color support level > 0. + Can be useful for things that are purely cosmetic. + */ + readonly visible: Chalk; + + readonly black: Chalk; + readonly red: Chalk; + readonly green: Chalk; + readonly yellow: Chalk; + readonly blue: Chalk; + readonly magenta: Chalk; + readonly cyan: Chalk; + readonly white: Chalk; + + /* + Alias for `blackBright`. + */ + readonly gray: Chalk; + + /* + Alias for `blackBright`. + */ + readonly grey: Chalk; + + readonly blackBright: Chalk; + readonly redBright: Chalk; + readonly greenBright: Chalk; + readonly yellowBright: Chalk; + readonly blueBright: Chalk; + readonly magentaBright: Chalk; + readonly cyanBright: Chalk; + readonly whiteBright: Chalk; + + readonly bgBlack: Chalk; + readonly bgRed: Chalk; + readonly bgGreen: Chalk; + readonly bgYellow: Chalk; + readonly bgBlue: Chalk; + readonly bgMagenta: Chalk; + readonly bgCyan: Chalk; + readonly bgWhite: Chalk; + + /* + Alias for `bgBlackBright`. + */ + readonly bgGray: Chalk; + + /* + Alias for `bgBlackBright`. + */ + readonly bgGrey: Chalk; + + readonly bgBlackBright: Chalk; + readonly bgRedBright: Chalk; + readonly bgGreenBright: Chalk; + readonly bgYellowBright: Chalk; + readonly bgBlueBright: Chalk; + readonly bgMagentaBright: Chalk; + readonly bgCyanBright: Chalk; + readonly bgWhiteBright: Chalk; + } +} + +/** +Main Chalk object that allows to chain styles together. +Call the last one as a method with a string argument. +Order doesn't matter, and later styles take precedent in case of a conflict. +This simply means that `chalk.red.yellow.green` is equivalent to `chalk.green`. +*/ +declare const chalk: chalk.Chalk & chalk.ChalkFunction & { + supportsColor: chalk.ColorSupport | false; + Level: chalk.Level; + Color: Color; + ForegroundColor: ForegroundColor; + BackgroundColor: BackgroundColor; + Modifiers: Modifiers; + stderr: chalk.Chalk & {supportsColor: chalk.ColorSupport | false}; +}; + +export = chalk; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/chalk/license b/novas/novacore-zephyr/claude-code-router/node_modules/chalk/license new file mode 100644 index 0000000000000000000000000000000000000000..e7af2f77107d73046421ef56c4684cbfdd3c1e89 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/chalk/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/chalk/package.json b/novas/novacore-zephyr/claude-code-router/node_modules/chalk/package.json new file mode 100644 index 0000000000000000000000000000000000000000..47c23f29068caa951b6f9d2a748fbfc291b6b492 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/chalk/package.json @@ -0,0 +1,68 @@ +{ + "name": "chalk", + "version": "4.1.2", + "description": "Terminal string styling done right", + "license": "MIT", + "repository": "chalk/chalk", + "funding": "https://github.com/chalk/chalk?sponsor=1", + "main": "source", + "engines": { + "node": ">=10" + }, + "scripts": { + "test": "xo && nyc ava && tsd", + "bench": "matcha benchmark.js" + }, + "files": [ + "source", + "index.d.ts" + ], + "keywords": [ + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "string", + "str", + "ansi", + "style", + "styles", + "tty", + "formatting", + "rgb", + "256", + "shell", + "xterm", + "log", + "logging", + "command-line", + "text" + ], + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "devDependencies": { + "ava": "^2.4.0", + "coveralls": "^3.0.7", + "execa": "^4.0.0", + "import-fresh": "^3.1.0", + "matcha": "^0.7.0", + "nyc": "^15.0.0", + "resolve-from": "^5.0.0", + "tsd": "^0.7.4", + "xo": "^0.28.2" + }, + "xo": { + "rules": { + "unicorn/prefer-string-slice": "off", + "unicorn/prefer-includes": "off", + "@typescript-eslint/member-ordering": "off", + "no-redeclare": "off", + "unicorn/string-content": "off", + "unicorn/better-regex": "off" + } + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/chalk/readme.md b/novas/novacore-zephyr/claude-code-router/node_modules/chalk/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..a055d21c97ed7625e06912442db51160c6731329 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/chalk/readme.md @@ -0,0 +1,341 @@ +

+
+
+ Chalk +
+
+
+

+ +> Terminal string styling done right + +[![Build Status](https://travis-ci.org/chalk/chalk.svg?branch=master)](https://travis-ci.org/chalk/chalk) [![Coverage Status](https://coveralls.io/repos/github/chalk/chalk/badge.svg?branch=master)](https://coveralls.io/github/chalk/chalk?branch=master) [![npm dependents](https://badgen.net/npm/dependents/chalk)](https://www.npmjs.com/package/chalk?activeTab=dependents) [![Downloads](https://badgen.net/npm/dt/chalk)](https://www.npmjs.com/package/chalk) [![](https://img.shields.io/badge/unicorn-approved-ff69b4.svg)](https://www.youtube.com/watch?v=9auOCbH5Ns4) [![XO code style](https://img.shields.io/badge/code_style-XO-5ed9c7.svg)](https://github.com/xojs/xo) ![TypeScript-ready](https://img.shields.io/npm/types/chalk.svg) [![run on repl.it](https://repl.it/badge/github/chalk/chalk)](https://repl.it/github/chalk/chalk) + + + +
+ +--- + + + +--- + +
+ +## Highlights + +- Expressive API +- Highly performant +- Ability to nest styles +- [256/Truecolor color support](#256-and-truecolor-color-support) +- Auto-detects color support +- Doesn't extend `String.prototype` +- Clean and focused +- Actively maintained +- [Used by ~50,000 packages](https://www.npmjs.com/browse/depended/chalk) as of January 1, 2020 + +## Install + +```console +$ npm install chalk +``` + +## Usage + +```js +const chalk = require('chalk'); + +console.log(chalk.blue('Hello world!')); +``` + +Chalk comes with an easy to use composable API where you just chain and nest the styles you want. + +```js +const chalk = require('chalk'); +const log = console.log; + +// Combine styled and normal strings +log(chalk.blue('Hello') + ' World' + chalk.red('!')); + +// Compose multiple styles using the chainable API +log(chalk.blue.bgRed.bold('Hello world!')); + +// Pass in multiple arguments +log(chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz')); + +// Nest styles +log(chalk.red('Hello', chalk.underline.bgBlue('world') + '!')); + +// Nest styles of the same type even (color, underline, background) +log(chalk.green( + 'I am a green line ' + + chalk.blue.underline.bold('with a blue substring') + + ' that becomes green again!' +)); + +// ES2015 template literal +log(` +CPU: ${chalk.red('90%')} +RAM: ${chalk.green('40%')} +DISK: ${chalk.yellow('70%')} +`); + +// ES2015 tagged template literal +log(chalk` +CPU: {red ${cpu.totalPercent}%} +RAM: {green ${ram.used / ram.total * 100}%} +DISK: {rgb(255,131,0) ${disk.used / disk.total * 100}%} +`); + +// Use RGB colors in terminal emulators that support it. +log(chalk.keyword('orange')('Yay for orange colored text!')); +log(chalk.rgb(123, 45, 67).underline('Underlined reddish color')); +log(chalk.hex('#DEADED').bold('Bold gray!')); +``` + +Easily define your own themes: + +```js +const chalk = require('chalk'); + +const error = chalk.bold.red; +const warning = chalk.keyword('orange'); + +console.log(error('Error!')); +console.log(warning('Warning!')); +``` + +Take advantage of console.log [string substitution](https://nodejs.org/docs/latest/api/console.html#console_console_log_data_args): + +```js +const name = 'Sindre'; +console.log(chalk.green('Hello %s'), name); +//=> 'Hello Sindre' +``` + +## API + +### chalk.`