WIP: bootstrap and partial real Solana watcher implementation

This commit is contained in:
2026-08-16 09:17:45 +00:00
commit dc23412c3f
7232 changed files with 1687637 additions and 0 deletions

View File

@@ -0,0 +1,2 @@
import type { LibDefinition } from '../variable';
export declare const es2025_full: LibDefinition;

View File

@@ -0,0 +1,246 @@
/**
* Async Hooks module: https://nodejs.org/api/async_hooks.html
*/
declare module 'async_hooks' {
/**
* Returns the asyncId of the current execution context.
*/
function executionAsyncId(): number;
/**
* The resource representing the current execution.
* Useful to store data within the resource.
*
* Resource objects returned by `executionAsyncResource()` are most often internal
* Node.js handle objects with undocumented APIs. Using any functions or properties
* on the object is likely to crash your application and should be avoided.
*
* Using `executionAsyncResource()` in the top-level execution context will
* return an empty object as there is no handle or request object to use,
* but having an object representing the top-level can be helpful.
*/
function executionAsyncResource(): object;
/**
* Returns the ID of the resource responsible for calling the callback that is currently being executed.
*/
function triggerAsyncId(): number;
interface HookCallbacks {
/**
* Called when a class is constructed that has the possibility to emit an asynchronous event.
* @param asyncId a unique ID for the async resource
* @param type the type of the async resource
* @param triggerAsyncId the unique ID of the async resource in whose execution context this async resource was created
* @param resource reference to the resource representing the async operation, needs to be released during destroy
*/
init?(asyncId: number, type: string, triggerAsyncId: number, resource: object): void;
/**
* When an asynchronous operation is initiated or completes a callback is called to notify the user.
* The before callback is called just before said callback is executed.
* @param asyncId the unique identifier assigned to the resource about to execute the callback.
*/
before?(asyncId: number): void;
/**
* Called immediately after the callback specified in before is completed.
* @param asyncId the unique identifier assigned to the resource which has executed the callback.
*/
after?(asyncId: number): void;
/**
* Called when a promise has resolve() called. This may not be in the same execution id
* as the promise itself.
* @param asyncId the unique id for the promise that was resolve()d.
*/
promiseResolve?(asyncId: number): void;
/**
* Called after the resource corresponding to asyncId is destroyed
* @param asyncId a unique ID for the async resource
*/
destroy?(asyncId: number): void;
}
interface AsyncHook {
/**
* Enable the callbacks for a given AsyncHook instance. If no callbacks are provided enabling is a noop.
*/
enable(): this;
/**
* Disable the callbacks for a given AsyncHook instance from the global pool of AsyncHook callbacks to be executed. Once a hook has been disabled it will not be called again until enabled.
*/
disable(): this;
}
/**
* Registers functions to be called for different lifetime events of each async operation.
* @param options the callbacks to register
* @return an AsyncHooks instance used for disabling and enabling hooks
*/
function createHook(options: HookCallbacks): AsyncHook;
interface AsyncResourceOptions {
/**
* The ID of the execution context that created this async event.
* @default executionAsyncId()
*/
triggerAsyncId?: number | undefined;
/**
* Disables automatic `emitDestroy` when the object is garbage collected.
* This usually does not need to be set (even if `emitDestroy` is called
* manually), unless the resource's `asyncId` is retrieved and the
* sensitive API's `emitDestroy` is called with it.
* @default false
*/
requireManualDestroy?: boolean | undefined;
}
/**
* The class AsyncResource was designed to be extended by the embedder's async resources.
* Using this users can easily trigger the lifetime events of their own resources.
*/
class AsyncResource {
/**
* AsyncResource() is meant to be extended. Instantiating a
* new AsyncResource() also triggers init. If triggerAsyncId is omitted then
* async_hook.executionAsyncId() is used.
* @param type The type of async event.
* @param triggerAsyncId The ID of the execution context that created
* this async event (default: `executionAsyncId()`), or an
* AsyncResourceOptions object (since v9.3.0)
*/
constructor(type: string, triggerAsyncId?: number|AsyncResourceOptions);
/**
* Binds the given function to the current execution context.
* @param fn The function to bind to the current execution context.
* @param type An optional name to associate with the underlying `AsyncResource`.
*/
static bind<Func extends (...args: any[]) => any>(fn: Func, type?: string): Func & { asyncResource: AsyncResource };
/**
* Binds the given function to execute to this `AsyncResource`'s scope.
* @param fn The function to bind to the current `AsyncResource`.
*/
bind<Func extends (...args: any[]) => any>(fn: Func): Func & { asyncResource: AsyncResource };
/**
* Call the provided function with the provided arguments in the
* execution context of the async resource. This will establish the
* context, trigger the AsyncHooks before callbacks, call the function,
* trigger the AsyncHooks after callbacks, and then restore the original
* execution context.
* @param fn The function to call in the execution context of this
* async resource.
* @param thisArg The receiver to be used for the function call.
* @param args Optional arguments to pass to the function.
*/
runInAsyncScope<This, Result>(fn: (this: This, ...args: any[]) => Result, thisArg?: This, ...args: any[]): Result;
/**
* Call AsyncHooks destroy callbacks.
*/
emitDestroy(): this;
/**
* @return the unique ID assigned to this AsyncResource instance.
*/
asyncId(): number;
/**
* @return the trigger ID for this AsyncResource instance.
*/
triggerAsyncId(): number;
}
/**
* When having multiple instances of `AsyncLocalStorage`, they are independent
* from each other. It is safe to instantiate this class multiple times.
*/
class AsyncLocalStorage<T> {
/**
* This method disables the instance of `AsyncLocalStorage`. All subsequent calls
* to `asyncLocalStorage.getStore()` will return `undefined` until
* `asyncLocalStorage.run()` or `asyncLocalStorage.runSyncAndReturn()`
* is called again.
*
* When calling `asyncLocalStorage.disable()`, all current contexts linked to the
* instance will be exited.
*
* Calling `asyncLocalStorage.disable()` is required before the
* `asyncLocalStorage` can be garbage collected. This does not apply to stores
* provided by the `asyncLocalStorage`, as those objects are garbage collected
* along with the corresponding async resources.
*
* This method is to be used when the `asyncLocalStorage` is not in use anymore
* in the current process.
*/
disable(): void;
/**
* This method returns the current store.
* If this method is called outside of an asynchronous context initialized by
* calling `asyncLocalStorage.run` or `asyncLocalStorage.runAndReturn`, it will
* return `undefined`.
*/
getStore(): T | undefined;
/**
* Calling `asyncLocalStorage.run(callback)` will create a new asynchronous
* context.
* Within the callback function and the asynchronous operations from the callback,
* `asyncLocalStorage.getStore()` will return an instance of `Map` known as
* "the store". This store will be persistent through the following
* asynchronous calls.
*
* The callback will be ran asynchronously. Optionally, arguments can be passed
* to the function. They will be passed to the callback function.
*
* If an error is thrown by the callback function, it will not be caught by
* a `try/catch` block as the callback is ran in a new asynchronous resource.
* Also, the stacktrace will be impacted by the asynchronous call.
*/
// TODO: Apply generic vararg once available
run(store: T, callback: (...args: any[]) => void, ...args: any[]): void;
/**
* Calling `asyncLocalStorage.exit(callback)` will create a new asynchronous
* context.
* Within the callback function and the asynchronous operations from the callback,
* `asyncLocalStorage.getStore()` will return `undefined`.
*
* The callback will be ran asynchronously. Optionally, arguments can be passed
* to the function. They will be passed to the callback function.
*
* If an error is thrown by the callback function, it will not be caught by
* a `try/catch` block as the callback is ran in a new asynchronous resource.
* Also, the stacktrace will be impacted by the asynchronous call.
*/
exit(callback: (...args: any[]) => void, ...args: any[]): void;
/**
* This methods runs a function synchronously outside of a context and return its
* return value. The store is not accessible within the callback function or
* the asynchronous operations created within the callback.
*
* Optionally, arguments can be passed to the function. They will be passed to
* the callback function.
*
* If the callback function throws an error, it will be thrown by
* `exitSyncAndReturn` too. The stacktrace will not be impacted by this call and
* the context will be re-entered.
*/
exitSyncAndReturn<R>(callback: (...args: any[]) => R, ...args: any[]): R;
/**
* Calling `asyncLocalStorage.enterWith(store)` will transition into the context
* for the remainder of the current synchronous execution and will persist
* through any following asynchronous calls.
*/
enterWith(store: T): void;
}
}

View File

@@ -0,0 +1 @@
{"version":3,"file":"p256.js","sourceRoot":"","sources":["../src/p256.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,sEAAsE;AACtE,OAAO,EAAkB,MAAM,6BAA6B,CAAC;AAC7D,OAAO,EAAE,WAAW,EAAE,IAAI,IAAI,KAAK,EAAE,MAAM,WAAW,CAAC;AACvD,sEAAsE;AACtE,MAAM,CAAC,MAAM,IAAI,GAAiB,KAAK,CAAC;AACxC,sEAAsE;AACtE,MAAM,CAAC,MAAM,SAAS,GAAiB,KAAK,CAAC;AAC7C,6EAA6E;AAC7E,MAAM,CAAC,MAAM,WAAW,GAAsB,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC,WAAW,CAAC,WAAW,CAAC,EAAE,CAAC;AAChG,6EAA6E;AAC7E,MAAM,CAAC,MAAM,aAAa,GAAsB,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC,WAAW,CAAC,aAAa,CAAC,EAAE,CAAC"}

View File

@@ -0,0 +1,35 @@
{
"for + if": {
"name": "for + if",
"browser": "Safari 10.0.1 (Mac OS X 10.12.1)",
"suite": "itar-short",
"hz": 252961.02857752063,
"success": true,
"fastest": true,
"rme": 0.015411371090374376,
"rhz": 1,
"sampleSize": 205
},
"while + if": {
"name": "while + if",
"browser": "Safari 10.0.1 (Mac OS X 10.12.1)",
"suite": "itar-short",
"hz": 245223.46117305866,
"success": true,
"fastest": false,
"rme": 0.012279924013953218,
"rhz": 0.9694120179382067,
"sampleSize": 208
},
"array join": {
"name": "array join",
"browser": "Safari 10.0.1 (Mac OS X 10.12.1)",
"suite": "itar-short",
"hz": 252326.4006791167,
"success": true,
"fastest": true,
"rme": 0.013639798860321599,
"rhz": 0.9974912028861811,
"sampleSize": 207
}
}

View File

@@ -0,0 +1,16 @@
'use strict'
const pino = require('../..')
const transport = pino.transport({
target: './to-file-transport-with-transform.js',
options: {
destination: process.argv[2]
}
})
const logger = pino(transport)
logger.info('Hello')
logger.info('World')
process.exit(0)

View File

@@ -0,0 +1,13 @@
export declare enum RegularExpressionFlags {
None = 0,
HasIndices = 1,
Global = 2,
IgnoreCase = 4,
Multiline = 8,
DotAll = 16,
Unicode = 32,
UnicodeSets = 64,
Sticky = 128,
AnyUnicodeMode = 96
}
//# sourceMappingURL=regularExpressionFlags.enum.d.ts.map

View File

@@ -0,0 +1,4 @@
{
"main": "../../cjs/_initializer_warning_helper.cjs",
"module": "../../esm/_initializer_warning_helper.js"
}

View File

@@ -0,0 +1 @@
{"version":3,"file":"error.d.ts","sourceRoot":"","sources":["../../src/error.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,wBAAwB,EAAE,MAAM,SAAS,CAAC;AACpE,OAAO,EAAE,kBAAkB,EAAE,MAAM,WAAW,CAAC;AAG/C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyCG;AACH,wBAAgB,aAAa,CAAC,UAAU,SAAS,eAAe,EAC5D,CAAC,EAAE,OAAO;AACV;;;GAGG;AACH,IAAI,CAAC,EAAE,UAAU,GAClB,CAAC,IAAI,WAAW,CAAC,UAAU,CAAC,CAS9B;AAED,KAAK,uBAAuB,GAAG,QAAQ,CAAC;KACnC,CAAC,IAAI,eAAe,GAAG,CAAC,kBAAkB,CAAC,CAAC,CAAC,SAAS,SAAS,GAAG,MAAM,GAAG,kBAAkB,CAAC,CAAC,CAAC,CAAC,GAAG;QACjG,MAAM,EAAE,CAAC,CAAC;KACb;CACJ,CAAC,CAAC;AAEH;;;GAGG;AACH,qBAAa,WAAW,CAAC,UAAU,SAAS,eAAe,GAAG,eAAe,CAAE,SAAQ,KAAK;IACxF;;;;;OAKG;IACH,QAAQ,CAAC,KAAK,CAAC,EAAE,UAAU,SAAS,wBAAwB,GAAG,WAAW,GAAG,OAAO,CAAc;IAClG;;OAEG;IACH,QAAQ,CAAC,OAAO,EAAE,uBAAuB,CAAC,UAAU,CAAC,CAAC;gBAElD,GAAG,CAAC,IAAI,EAAE,sBAAsB,CAAC,EAAE,kBAAkB,CAAC,UAAU,CAAC,SAAS,SAAS,GAC7E,CAAC,IAAI,EAAE,UAAU,EAAE,YAAY,CAAC,EAAE,YAAY,GAAG,SAAS,CAAC,GAC3D,CAAC,IAAI,EAAE,UAAU,EAAE,sBAAsB,EAAE,kBAAkB,CAAC,UAAU,CAAC,GAAG,CAAC,YAAY,GAAG,SAAS,CAAC,CAAC;CAwBpH"}

View File

@@ -0,0 +1,4 @@
{
"main": "../../cjs/_inherits.cjs",
"module": "../../esm/_inherits.js"
}

View File

@@ -0,0 +1,4 @@
function _classCallCheck(a, n) {
if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function");
}
export { _classCallCheck as default };

View File

@@ -0,0 +1,2 @@
export { getKeys } from './get-keys';
export { visitorKeys, type VisitorKeys } from './visitor-keys';

View File

@@ -0,0 +1,6 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
// This is an empty module that is served up when outside of a workerd environment
// See the `exports` field in package.json
exports.default = {};
//# sourceMappingURL=empty.js.map

View File

@@ -0,0 +1,161 @@
'use strict'
const hasBuffer = typeof Buffer !== 'undefined'
const suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/
const suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/
/**
* @description Internal parse function that parses JSON text with security checks.
* @private
* @param {string|Buffer} text - The JSON text string or Buffer to parse.
* @param {Function} [reviver] - The JSON.parse() optional reviver argument.
* @param {import('./types').ParseOptions} [options] - Optional configuration object.
* @returns {*} The parsed object.
* @throws {SyntaxError} If a forbidden prototype property is found and `options.protoAction` or
* `options.constructorAction` is `'error'`.
*/
function _parse (text, reviver, options) {
// Normalize arguments
if (options == null) {
if (reviver !== null && typeof reviver === 'object') {
options = reviver
reviver = undefined
}
}
if (hasBuffer && Buffer.isBuffer(text)) {
text = text.toString()
}
// BOM checker
if (text && text.charCodeAt(0) === 0xFEFF) {
text = text.slice(1)
}
// Parse normally, allowing exceptions
const obj = JSON.parse(text, reviver)
// Ignore null and non-objects
if (obj === null || typeof obj !== 'object') {
return obj
}
const protoAction = (options && options.protoAction) || 'error'
const constructorAction = (options && options.constructorAction) || 'error'
// options: 'error' (default) / 'remove' / 'ignore'
if (protoAction === 'ignore' && constructorAction === 'ignore') {
return obj
}
if (protoAction !== 'ignore' && constructorAction !== 'ignore') {
if (suspectProtoRx.test(text) === false && suspectConstructorRx.test(text) === false) {
return obj
}
} else if (protoAction !== 'ignore' && constructorAction === 'ignore') {
if (suspectProtoRx.test(text) === false) {
return obj
}
} else {
if (suspectConstructorRx.test(text) === false) {
return obj
}
}
// Scan result for proto keys
return filter(obj, { protoAction, constructorAction, safe: options && options.safe })
}
/**
* @description Scans and filters an object for forbidden prototype properties.
* @param {Object} obj - The object being scanned.
* @param {import('./types').ParseOptions} [options] - Optional configuration object.
* @returns {Object|null} The filtered object, or `null` if safe mode is enabled and issues are found.
* @throws {SyntaxError} If a forbidden prototype property is found and `options.protoAction` or
* `options.constructorAction` is `'error'`.
*/
function filter (obj, { protoAction = 'error', constructorAction = 'error', safe } = {}) {
let next = [obj]
while (next.length) {
const nodes = next
next = []
for (const node of nodes) {
if (protoAction !== 'ignore' && Object.prototype.hasOwnProperty.call(node, '__proto__')) { // Avoid calling node.hasOwnProperty directly
if (safe === true) {
return null
} else if (protoAction === 'error') {
throw new SyntaxError('Object contains forbidden prototype property')
}
delete node.__proto__ // eslint-disable-line no-proto
}
if (constructorAction !== 'ignore' &&
Object.prototype.hasOwnProperty.call(node, 'constructor') &&
node.constructor !== null &&
typeof node.constructor === 'object' &&
Object.prototype.hasOwnProperty.call(node.constructor, 'prototype')) { // Avoid calling node.hasOwnProperty directly
if (safe === true) {
return null
} else if (constructorAction === 'error') {
throw new SyntaxError('Object contains forbidden prototype property')
}
delete node.constructor
}
for (const key in node) {
const value = node[key]
if (value && typeof value === 'object') {
next.push(value)
}
}
}
}
return obj
}
/**
* @description Parses a given JSON-formatted text into an object.
* @param {string|Buffer} text - The JSON text string or Buffer to parse.
* @param {Function} [reviver] - The `JSON.parse()` optional reviver argument, or options object.
* @param {import('./types').ParseOptions} [options] - Optional configuration object.
* @returns {*} The parsed object.
* @throws {SyntaxError} If the JSON text is malformed or contains forbidden prototype properties
* when `options.protoAction` or `options.constructorAction` is `'error'`.
*/
function parse (text, reviver, options) {
const { stackTraceLimit } = Error
Error.stackTraceLimit = 0
try {
return _parse(text, reviver, options)
} finally {
Error.stackTraceLimit = stackTraceLimit
}
}
/**
* @description Safely parses a given JSON-formatted text into an object.
* @param {string|Buffer} text - The JSON text string or Buffer to parse.
* @param {Function} [reviver] - The `JSON.parse()` optional reviver argument.
* @returns {*|null|undefined} The parsed object, `null` if security issues found, or `undefined` on parse error.
*/
function safeParse (text, reviver) {
const { stackTraceLimit } = Error
Error.stackTraceLimit = 0
try {
return _parse(text, reviver, { safe: true })
} catch {
return undefined
} finally {
Error.stackTraceLimit = stackTraceLimit
}
}
module.exports = parse
module.exports.default = parse
module.exports.parse = parse
module.exports.safeParse = safeParse
module.exports.scan = filter

View File

@@ -0,0 +1,9 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (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.

View File

@@ -0,0 +1,73 @@
{{# def.definitions }}
{{# def.errors }}
{{# def.setupKeyword }}
{{# def.setupNextLevel }}
{{## def.validateIfClause:_clause:
{{
$it.schema = it.schema['_clause'];
$it.schemaPath = it.schemaPath + '._clause';
$it.errSchemaPath = it.errSchemaPath + '/_clause';
}}
{{# def.insertSubschemaCode }}
{{=$valid}} = {{=$nextValid}};
{{? $thenPresent && $elsePresent }}
{{ $ifClause = 'ifClause' + $lvl; }}
var {{=$ifClause}} = '_clause';
{{??}}
{{ $ifClause = '\'_clause\''; }}
{{?}}
#}}
{{
var $thenSch = it.schema['then']
, $elseSch = it.schema['else']
, $thenPresent = $thenSch !== undefined && {{# def.nonEmptySchema:$thenSch }}
, $elsePresent = $elseSch !== undefined && {{# def.nonEmptySchema:$elseSch }}
, $currentBaseId = $it.baseId;
}}
{{? $thenPresent || $elsePresent }}
{{
var $ifClause;
$it.createErrors = false;
$it.schema = $schema;
$it.schemaPath = $schemaPath;
$it.errSchemaPath = $errSchemaPath;
}}
var {{=$errs}} = errors;
var {{=$valid}} = true;
{{# def.setCompositeRule }}
{{# def.insertSubschemaCode }}
{{ $it.createErrors = true; }}
{{# def.resetErrors }}
{{# def.resetCompositeRule }}
{{? $thenPresent }}
if ({{=$nextValid}}) {
{{# def.validateIfClause:then }}
}
{{? $elsePresent }}
else {
{{?}}
{{??}}
if (!{{=$nextValid}}) {
{{?}}
{{? $elsePresent }}
{{# def.validateIfClause:else }}
}
{{?}}
if (!{{=$valid}}) {
{{# def.extraError:'if' }}
}
{{? $breakOnError }} else { {{?}}
{{??}}
{{? $breakOnError }}
if (true) {
{{?}}
{{?}}

View File

@@ -0,0 +1,46 @@
/**
* @fileoverview Helpers for counting errors and warnings in lint messages.
* @author Nicholas C. Zakas
* @author Blake Sager
*/
"use strict";
/**
* It will calculate the error and warning count for collection of messages per file
* @param {LintMessage[]} messages Collection of messages
* @returns {Object} Contains the stats
*/
function calculateStatsPerFile(messages) {
const stat = {
errorCount: 0,
fatalErrorCount: 0,
warningCount: 0,
fixableErrorCount: 0,
fixableWarningCount: 0,
};
for (let i = 0; i < messages.length; i++) {
const message = messages[i];
if (message.fatal || message.severity === 2) {
stat.errorCount++;
if (message.fatal) {
stat.fatalErrorCount++;
}
if (message.fix) {
stat.fixableErrorCount++;
}
} else {
stat.warningCount++;
if (message.fix) {
stat.fixableWarningCount++;
}
}
}
return stat;
}
module.exports = {
calculateStatsPerFile,
};

View File

@@ -0,0 +1,71 @@
import type * as TSESLint from '../../ts-eslint';
import type { TSESTree } from '../../ts-estree';
declare const ReferenceTrackerREAD: symbol;
declare const ReferenceTrackerCALL: symbol;
declare const ReferenceTrackerCONSTRUCT: symbol;
declare const ReferenceTrackerESM: symbol;
interface ReferenceTracker {
/**
* Iterate the references that the given `traceMap` determined.
* This method starts to search from `require()` expression.
*
* @see {@link https://eslint-community.github.io/eslint-utils/api/scope-utils.html#tracker-iteratecjsreferences}
*/
iterateCjsReferences<T>(traceMap: ReferenceTracker.TraceMap<T>): IterableIterator<ReferenceTracker.FoundReference<T>>;
/**
* Iterate the references that the given `traceMap` determined.
* This method starts to search from `import`/`export` declarations.
*
* @see {@link https://eslint-community.github.io/eslint-utils/api/scope-utils.html#tracker-iterateesmreferences}
*/
iterateEsmReferences<T>(traceMap: ReferenceTracker.TraceMap<T>): IterableIterator<ReferenceTracker.FoundReference<T>>;
/**
* Iterate the references that the given `traceMap` determined.
* This method starts to search from global variables.
*
* @see {@link https://eslint-community.github.io/eslint-utils/api/scope-utils.html#tracker-iterateglobalreferences}
*/
iterateGlobalReferences<T>(traceMap: ReferenceTracker.TraceMap<T>): IterableIterator<ReferenceTracker.FoundReference<T>>;
}
interface ReferenceTrackerStatic {
readonly CALL: typeof ReferenceTrackerCALL;
readonly CONSTRUCT: typeof ReferenceTrackerCONSTRUCT;
readonly ESM: typeof ReferenceTrackerESM;
new (globalScope: TSESLint.Scope.Scope, options?: {
/**
* The name list of Global Object. Optional. Default is `["global", "globalThis", "self", "window"]`.
*/
globalObjectNames?: readonly string[];
/**
* The mode which determines how the `tracker.iterateEsmReferences()` method scans CommonJS modules.
* If this is `"strict"`, the method binds CommonJS modules to the default export. Otherwise, the method binds
* CommonJS modules to both the default export and named exports. Optional. Default is `"strict"`.
*/
mode?: 'legacy' | 'strict';
}): ReferenceTracker;
readonly READ: typeof ReferenceTrackerREAD;
}
declare namespace ReferenceTracker {
type READ = ReferenceTrackerStatic['READ'];
type CALL = ReferenceTrackerStatic['CALL'];
type CONSTRUCT = ReferenceTrackerStatic['CONSTRUCT'];
type ESM = ReferenceTrackerStatic['ESM'];
type ReferenceType = symbol;
type TraceMap<T = any> = Record<string, TraceMapElement<T>>;
interface TraceMapElement<T> {
[key: string]: TraceMapElement<T>;
}
interface FoundReference<T = any> {
info: T;
node: TSESTree.Node;
path: readonly string[];
type: ReferenceType;
}
}
/**
* The tracker for references. This provides reference tracking for global variables, CommonJS modules, and ES modules.
*
* @see {@link https://eslint-community.github.io/eslint-utils/api/scope-utils.html#referencetracker-class}
*/
export declare const ReferenceTracker: ReferenceTrackerStatic;
export {};

View File

@@ -0,0 +1,36 @@
import { pathToFileURL } from 'node:url';
import { r as resolveModule } from './index.BCY_7LL2.js';
import { resolve } from 'pathe';
import { ModuleRunner } from 'vite/module-runner';
class NativeModuleRunner extends ModuleRunner {
/**
* @internal
*/
mocker;
constructor(root, mocker) {
super({
hmr: false,
sourcemapInterceptor: false,
transport: { invoke() {
throw new Error("Unexpected `invoke`");
} }
});
this.root = root;
this.mocker = mocker;
if (mocker) Object.defineProperty(globalThis, "__vitest_mocker__", {
configurable: true,
writable: true,
value: mocker
});
}
async import(moduleId) {
const path = resolveModule(moduleId, { paths: [this.root] }) ?? resolve(this.root, moduleId);
// resolveModule doesn't keep the query params, so we need to add them back
let queryParams = "";
if (moduleId.includes("?") && !path.includes("?")) queryParams = moduleId.slice(moduleId.indexOf("?"));
return import(pathToFileURL(path + queryParams).toString());
}
}
export { NativeModuleRunner as N };

View File

@@ -0,0 +1,961 @@
import * as core from "../core/index.js";
import * as util from "../core/util.js";
import * as parse from "./parse.js";
export const ZodMiniType = /*@__PURE__*/ core.$constructor("ZodMiniType", (inst, def) => {
if (!inst._zod)
throw new Error("Uninitialized schema in ZodMiniType.");
core.$ZodType.init(inst, def);
inst.def = def;
inst.type = def.type;
inst.parse = (data, params) => parse.parse(inst, data, params, { callee: inst.parse });
inst.safeParse = (data, params) => parse.safeParse(inst, data, params);
inst.parseAsync = async (data, params) => parse.parseAsync(inst, data, params, { callee: inst.parseAsync });
inst.safeParseAsync = async (data, params) => parse.safeParseAsync(inst, data, params);
inst.check = (...checks) => {
return inst.clone({
...def,
checks: [
...(def.checks ?? []),
...checks.map((ch) => typeof ch === "function"
? {
_zod: { check: ch, def: { check: "custom" }, onattach: [] },
}
: ch),
],
}, { parent: true });
};
inst.with = inst.check;
inst.clone = (_def, params) => core.clone(inst, _def, params);
inst.brand = () => inst;
inst.register = ((reg, meta) => {
reg.add(inst, meta);
return inst;
});
inst.apply = (fn) => fn(inst);
});
export const ZodMiniString = /*@__PURE__*/ core.$constructor("ZodMiniString", (inst, def) => {
core.$ZodString.init(inst, def);
ZodMiniType.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
export function string(params) {
return core._string(ZodMiniString, params);
}
export const ZodMiniStringFormat = /*@__PURE__*/ core.$constructor("ZodMiniStringFormat", (inst, def) => {
core.$ZodStringFormat.init(inst, def);
ZodMiniString.init(inst, def);
});
export const ZodMiniEmail = /*@__PURE__*/ core.$constructor("ZodMiniEmail", (inst, def) => {
core.$ZodEmail.init(inst, def);
ZodMiniStringFormat.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
export function email(params) {
return core._email(ZodMiniEmail, params);
}
export const ZodMiniGUID = /*@__PURE__*/ core.$constructor("ZodMiniGUID", (inst, def) => {
core.$ZodGUID.init(inst, def);
ZodMiniStringFormat.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
export function guid(params) {
return core._guid(ZodMiniGUID, params);
}
export const ZodMiniUUID = /*@__PURE__*/ core.$constructor("ZodMiniUUID", (inst, def) => {
core.$ZodUUID.init(inst, def);
ZodMiniStringFormat.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
export function uuid(params) {
return core._uuid(ZodMiniUUID, params);
}
// @__NO_SIDE_EFFECTS__
export function uuidv4(params) {
return core._uuidv4(ZodMiniUUID, params);
}
// ZodMiniUUIDv6
// @__NO_SIDE_EFFECTS__
export function uuidv6(params) {
return core._uuidv6(ZodMiniUUID, params);
}
// ZodMiniUUIDv7
// @__NO_SIDE_EFFECTS__
export function uuidv7(params) {
return core._uuidv7(ZodMiniUUID, params);
}
export const ZodMiniURL = /*@__PURE__*/ core.$constructor("ZodMiniURL", (inst, def) => {
core.$ZodURL.init(inst, def);
ZodMiniStringFormat.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
export function url(params) {
return core._url(ZodMiniURL, params);
}
// @__NO_SIDE_EFFECTS__
export function httpUrl(params) {
return core._url(ZodMiniURL, {
protocol: core.regexes.httpProtocol,
hostname: core.regexes.domain,
...util.normalizeParams(params),
});
}
export const ZodMiniEmoji = /*@__PURE__*/ core.$constructor("ZodMiniEmoji", (inst, def) => {
core.$ZodEmoji.init(inst, def);
ZodMiniStringFormat.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
export function emoji(params) {
return core._emoji(ZodMiniEmoji, params);
}
export const ZodMiniNanoID = /*@__PURE__*/ core.$constructor("ZodMiniNanoID", (inst, def) => {
core.$ZodNanoID.init(inst, def);
ZodMiniStringFormat.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
export function nanoid(params) {
return core._nanoid(ZodMiniNanoID, params);
}
/**
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link ZodMiniCUID2} instead.
* See https://github.com/paralleldrive/cuid.
*/
export const ZodMiniCUID = /*@__PURE__*/ core.$constructor("ZodMiniCUID", (inst, def) => {
core.$ZodCUID.init(inst, def);
ZodMiniStringFormat.init(inst, def);
});
/**
* Validates a CUID v1 string.
*
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link cuid2 | `z.cuid2()`} instead.
* See https://github.com/paralleldrive/cuid.
*/
// @__NO_SIDE_EFFECTS__
export function cuid(params) {
return core._cuid(ZodMiniCUID, params);
}
export const ZodMiniCUID2 = /*@__PURE__*/ core.$constructor("ZodMiniCUID2", (inst, def) => {
core.$ZodCUID2.init(inst, def);
ZodMiniStringFormat.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
export function cuid2(params) {
return core._cuid2(ZodMiniCUID2, params);
}
export const ZodMiniULID = /*@__PURE__*/ core.$constructor("ZodMiniULID", (inst, def) => {
core.$ZodULID.init(inst, def);
ZodMiniStringFormat.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
export function ulid(params) {
return core._ulid(ZodMiniULID, params);
}
export const ZodMiniXID = /*@__PURE__*/ core.$constructor("ZodMiniXID", (inst, def) => {
core.$ZodXID.init(inst, def);
ZodMiniStringFormat.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
export function xid(params) {
return core._xid(ZodMiniXID, params);
}
export const ZodMiniKSUID = /*@__PURE__*/ core.$constructor("ZodMiniKSUID", (inst, def) => {
core.$ZodKSUID.init(inst, def);
ZodMiniStringFormat.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
export function ksuid(params) {
return core._ksuid(ZodMiniKSUID, params);
}
export const ZodMiniIPv4 = /*@__PURE__*/ core.$constructor("ZodMiniIPv4", (inst, def) => {
core.$ZodIPv4.init(inst, def);
ZodMiniStringFormat.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
export function ipv4(params) {
return core._ipv4(ZodMiniIPv4, params);
}
export const ZodMiniIPv6 = /*@__PURE__*/ core.$constructor("ZodMiniIPv6", (inst, def) => {
core.$ZodIPv6.init(inst, def);
ZodMiniStringFormat.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
export function ipv6(params) {
return core._ipv6(ZodMiniIPv6, params);
}
export const ZodMiniCIDRv4 = /*@__PURE__*/ core.$constructor("ZodMiniCIDRv4", (inst, def) => {
core.$ZodCIDRv4.init(inst, def);
ZodMiniStringFormat.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
export function cidrv4(params) {
return core._cidrv4(ZodMiniCIDRv4, params);
}
export const ZodMiniCIDRv6 = /*@__PURE__*/ core.$constructor("ZodMiniCIDRv6", (inst, def) => {
core.$ZodCIDRv6.init(inst, def);
ZodMiniStringFormat.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
export function cidrv6(params) {
return core._cidrv6(ZodMiniCIDRv6, params);
}
export const ZodMiniMAC = /*@__PURE__*/ core.$constructor("ZodMiniMAC", (inst, def) => {
core.$ZodMAC.init(inst, def);
ZodMiniStringFormat.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
export function mac(params) {
return core._mac(ZodMiniMAC, params);
}
export const ZodMiniBase64 = /*@__PURE__*/ core.$constructor("ZodMiniBase64", (inst, def) => {
core.$ZodBase64.init(inst, def);
ZodMiniStringFormat.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
export function base64(params) {
return core._base64(ZodMiniBase64, params);
}
export const ZodMiniBase64URL = /*@__PURE__*/ core.$constructor("ZodMiniBase64URL", (inst, def) => {
core.$ZodBase64URL.init(inst, def);
ZodMiniStringFormat.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
export function base64url(params) {
return core._base64url(ZodMiniBase64URL, params);
}
export const ZodMiniE164 = /*@__PURE__*/ core.$constructor("ZodMiniE164", (inst, def) => {
core.$ZodE164.init(inst, def);
ZodMiniStringFormat.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
export function e164(params) {
return core._e164(ZodMiniE164, params);
}
export const ZodMiniJWT = /*@__PURE__*/ core.$constructor("ZodMiniJWT", (inst, def) => {
core.$ZodJWT.init(inst, def);
ZodMiniStringFormat.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
export function jwt(params) {
return core._jwt(ZodMiniJWT, params);
}
export const ZodMiniCustomStringFormat = /*@__PURE__*/ core.$constructor("ZodMiniCustomStringFormat", (inst, def) => {
core.$ZodCustomStringFormat.init(inst, def);
ZodMiniStringFormat.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
export function stringFormat(format, fnOrRegex, _params = {}) {
return core._stringFormat(ZodMiniCustomStringFormat, format, fnOrRegex, _params);
}
// @__NO_SIDE_EFFECTS__
export function hostname(_params) {
return core._stringFormat(ZodMiniCustomStringFormat, "hostname", core.regexes.hostname, _params);
}
// @__NO_SIDE_EFFECTS__
export function hex(_params) {
return core._stringFormat(ZodMiniCustomStringFormat, "hex", core.regexes.hex, _params);
}
// @__NO_SIDE_EFFECTS__
export function hash(alg, params) {
const enc = params?.enc ?? "hex";
const format = `${alg}_${enc}`;
const regex = core.regexes[format];
// check for unrecognized format
if (!regex)
throw new Error(`Unrecognized hash format: ${format}`);
return core._stringFormat(ZodMiniCustomStringFormat, format, regex, params);
}
export const ZodMiniNumber = /*@__PURE__*/ core.$constructor("ZodMiniNumber", (inst, def) => {
core.$ZodNumber.init(inst, def);
ZodMiniType.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
export function number(params) {
return core._number(ZodMiniNumber, params);
}
export const ZodMiniNumberFormat = /*@__PURE__*/ core.$constructor("ZodMiniNumberFormat", (inst, def) => {
core.$ZodNumberFormat.init(inst, def);
ZodMiniNumber.init(inst, def);
});
// int
// @__NO_SIDE_EFFECTS__
export function int(params) {
return core._int(ZodMiniNumberFormat, params);
}
// float32
// @__NO_SIDE_EFFECTS__
export function float32(params) {
return core._float32(ZodMiniNumberFormat, params);
}
// float64
// @__NO_SIDE_EFFECTS__
export function float64(params) {
return core._float64(ZodMiniNumberFormat, params);
}
// int32
// @__NO_SIDE_EFFECTS__
export function int32(params) {
return core._int32(ZodMiniNumberFormat, params);
}
// uint32
// @__NO_SIDE_EFFECTS__
export function uint32(params) {
return core._uint32(ZodMiniNumberFormat, params);
}
export const ZodMiniBoolean = /*@__PURE__*/ core.$constructor("ZodMiniBoolean", (inst, def) => {
core.$ZodBoolean.init(inst, def);
ZodMiniType.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
export function boolean(params) {
return core._boolean(ZodMiniBoolean, params);
}
export const ZodMiniBigInt = /*@__PURE__*/ core.$constructor("ZodMiniBigInt", (inst, def) => {
core.$ZodBigInt.init(inst, def);
ZodMiniType.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
export function bigint(params) {
return core._bigint(ZodMiniBigInt, params);
}
export const ZodMiniBigIntFormat = /*@__PURE__*/ core.$constructor("ZodMiniBigIntFormat", (inst, def) => {
core.$ZodBigIntFormat.init(inst, def);
ZodMiniBigInt.init(inst, def);
});
// int64
// @__NO_SIDE_EFFECTS__
export function int64(params) {
return core._int64(ZodMiniBigIntFormat, params);
}
// uint64
// @__NO_SIDE_EFFECTS__
export function uint64(params) {
return core._uint64(ZodMiniBigIntFormat, params);
}
export const ZodMiniSymbol = /*@__PURE__*/ core.$constructor("ZodMiniSymbol", (inst, def) => {
core.$ZodSymbol.init(inst, def);
ZodMiniType.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
export function symbol(params) {
return core._symbol(ZodMiniSymbol, params);
}
export const ZodMiniUndefined = /*@__PURE__*/ core.$constructor("ZodMiniUndefined", (inst, def) => {
core.$ZodUndefined.init(inst, def);
ZodMiniType.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
function _undefined(params) {
return core._undefined(ZodMiniUndefined, params);
}
export { _undefined as undefined };
export const ZodMiniNull = /*@__PURE__*/ core.$constructor("ZodMiniNull", (inst, def) => {
core.$ZodNull.init(inst, def);
ZodMiniType.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
function _null(params) {
return core._null(ZodMiniNull, params);
}
export { _null as null };
export const ZodMiniAny = /*@__PURE__*/ core.$constructor("ZodMiniAny", (inst, def) => {
core.$ZodAny.init(inst, def);
ZodMiniType.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
export function any() {
return core._any(ZodMiniAny);
}
export const ZodMiniUnknown = /*@__PURE__*/ core.$constructor("ZodMiniUnknown", (inst, def) => {
core.$ZodUnknown.init(inst, def);
ZodMiniType.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
export function unknown() {
return core._unknown(ZodMiniUnknown);
}
export const ZodMiniNever = /*@__PURE__*/ core.$constructor("ZodMiniNever", (inst, def) => {
core.$ZodNever.init(inst, def);
ZodMiniType.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
export function never(params) {
return core._never(ZodMiniNever, params);
}
export const ZodMiniVoid = /*@__PURE__*/ core.$constructor("ZodMiniVoid", (inst, def) => {
core.$ZodVoid.init(inst, def);
ZodMiniType.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
function _void(params) {
return core._void(ZodMiniVoid, params);
}
export { _void as void };
export const ZodMiniDate = /*@__PURE__*/ core.$constructor("ZodMiniDate", (inst, def) => {
core.$ZodDate.init(inst, def);
ZodMiniType.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
export function date(params) {
return core._date(ZodMiniDate, params);
}
export const ZodMiniArray = /*@__PURE__*/ core.$constructor("ZodMiniArray", (inst, def) => {
core.$ZodArray.init(inst, def);
ZodMiniType.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
export function array(element, params) {
return new ZodMiniArray({
type: "array",
element: element,
...util.normalizeParams(params),
});
}
// .keyof
// @__NO_SIDE_EFFECTS__
export function keyof(schema) {
const shape = schema._zod.def.shape;
return _enum(Object.keys(shape));
}
export const ZodMiniObject = /*@__PURE__*/ core.$constructor("ZodMiniObject", (inst, def) => {
core.$ZodObject.init(inst, def);
ZodMiniType.init(inst, def);
util.defineLazy(inst, "shape", () => def.shape);
});
// @__NO_SIDE_EFFECTS__
export function object(shape, params) {
const def = {
type: "object",
shape: shape ?? {},
...util.normalizeParams(params),
};
return new ZodMiniObject(def);
}
// strictObject
// @__NO_SIDE_EFFECTS__
export function strictObject(shape, params) {
return new ZodMiniObject({
type: "object",
shape,
catchall: never(),
...util.normalizeParams(params),
});
}
// looseObject
// @__NO_SIDE_EFFECTS__
export function looseObject(shape, params) {
return new ZodMiniObject({
type: "object",
shape,
catchall: unknown(),
...util.normalizeParams(params),
});
}
// object methods
// @__NO_SIDE_EFFECTS__
export function extend(schema, shape) {
return util.extend(schema, shape);
}
// @__NO_SIDE_EFFECTS__
export function safeExtend(schema, shape) {
return util.safeExtend(schema, shape);
}
// @__NO_SIDE_EFFECTS__
export function merge(schema, shape) {
return util.extend(schema, shape);
}
// @__NO_SIDE_EFFECTS__
export function pick(schema, mask) {
return util.pick(schema, mask);
}
// .omit
// @__NO_SIDE_EFFECTS__
export function omit(schema, mask) {
return util.omit(schema, mask);
}
// @__NO_SIDE_EFFECTS__
export function partial(schema, mask) {
return util.partial(ZodMiniOptional, schema, mask);
}
// @__NO_SIDE_EFFECTS__
export function required(schema, mask) {
return util.required(ZodMiniNonOptional, schema, mask);
}
// @__NO_SIDE_EFFECTS__
export function catchall(inst, catchall) {
return inst.clone({ ...inst._zod.def, catchall: catchall });
}
export const ZodMiniUnion = /*@__PURE__*/ core.$constructor("ZodMiniUnion", (inst, def) => {
core.$ZodUnion.init(inst, def);
ZodMiniType.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
export function union(options, params) {
return new ZodMiniUnion({
type: "union",
options: options,
...util.normalizeParams(params),
});
}
export const ZodMiniXor = /*@__PURE__*/ core.$constructor("ZodMiniXor", (inst, def) => {
ZodMiniUnion.init(inst, def);
core.$ZodXor.init(inst, def);
});
/** Creates an exclusive union (XOR) where exactly one option must match.
* Unlike regular unions that succeed when any option matches, xor fails if
* zero or more than one option matches the input. */
export function xor(options, params) {
return new ZodMiniXor({
type: "union",
options: options,
inclusive: false,
...util.normalizeParams(params),
});
}
export const ZodMiniDiscriminatedUnion = /*@__PURE__*/ core.$constructor("ZodMiniDiscriminatedUnion", (inst, def) => {
core.$ZodDiscriminatedUnion.init(inst, def);
ZodMiniType.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
export function discriminatedUnion(discriminator, options, params) {
return new ZodMiniDiscriminatedUnion({
type: "union",
options,
discriminator,
...util.normalizeParams(params),
});
}
export const ZodMiniIntersection = /*@__PURE__*/ core.$constructor("ZodMiniIntersection", (inst, def) => {
core.$ZodIntersection.init(inst, def);
ZodMiniType.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
export function intersection(left, right) {
return new ZodMiniIntersection({
type: "intersection",
left: left,
right: right,
});
}
export const ZodMiniTuple = /*@__PURE__*/ core.$constructor("ZodMiniTuple", (inst, def) => {
core.$ZodTuple.init(inst, def);
ZodMiniType.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
export function tuple(items, _paramsOrRest, _params) {
const hasRest = _paramsOrRest instanceof core.$ZodType;
const params = hasRest ? _params : _paramsOrRest;
const rest = hasRest ? _paramsOrRest : null;
return new ZodMiniTuple({
type: "tuple",
items: items,
rest,
...util.normalizeParams(params),
});
}
export const ZodMiniRecord = /*@__PURE__*/ core.$constructor("ZodMiniRecord", (inst, def) => {
core.$ZodRecord.init(inst, def);
ZodMiniType.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
export function record(keyType, valueType, params) {
// v3-compat: z.record(valueType, params?) — defaults keyType to z.string()
if (!valueType || !valueType._zod) {
return new ZodMiniRecord({
type: "record",
keyType: string(),
valueType: keyType,
...util.normalizeParams(valueType),
});
}
return new ZodMiniRecord({
type: "record",
keyType,
valueType: valueType,
...util.normalizeParams(params),
});
}
// @__NO_SIDE_EFFECTS__
export function partialRecord(keyType, valueType, params) {
const k = core.clone(keyType);
k._zod.values = undefined;
return new ZodMiniRecord({
type: "record",
keyType: k,
valueType: valueType,
...util.normalizeParams(params),
});
}
export function looseRecord(keyType, valueType, params) {
return new ZodMiniRecord({
type: "record",
keyType,
valueType: valueType,
mode: "loose",
...util.normalizeParams(params),
});
}
export const ZodMiniMap = /*@__PURE__*/ core.$constructor("ZodMiniMap", (inst, def) => {
core.$ZodMap.init(inst, def);
ZodMiniType.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
export function map(keyType, valueType, params) {
return new ZodMiniMap({
type: "map",
keyType: keyType,
valueType: valueType,
...util.normalizeParams(params),
});
}
export const ZodMiniSet = /*@__PURE__*/ core.$constructor("ZodMiniSet", (inst, def) => {
core.$ZodSet.init(inst, def);
ZodMiniType.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
export function set(valueType, params) {
return new ZodMiniSet({
type: "set",
valueType: valueType,
...util.normalizeParams(params),
});
}
export const ZodMiniEnum = /*@__PURE__*/ core.$constructor("ZodMiniEnum", (inst, def) => {
core.$ZodEnum.init(inst, def);
ZodMiniType.init(inst, def);
inst.options = Object.values(def.entries);
});
// @__NO_SIDE_EFFECTS__
function _enum(values, params) {
const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;
return new ZodMiniEnum({
type: "enum",
entries,
...util.normalizeParams(params),
});
}
export { _enum as enum };
// @__NO_SIDE_EFFECTS__
/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.
*
* ```ts
* enum Colors { red, green, blue }
* z.enum(Colors);
* ```
*/
export function nativeEnum(entries, params) {
return new ZodMiniEnum({
type: "enum",
entries,
...util.normalizeParams(params),
});
}
export const ZodMiniLiteral = /*@__PURE__*/ core.$constructor("ZodMiniLiteral", (inst, def) => {
core.$ZodLiteral.init(inst, def);
ZodMiniType.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
export function literal(value, params) {
return new ZodMiniLiteral({
type: "literal",
values: Array.isArray(value) ? value : [value],
...util.normalizeParams(params),
});
}
export const ZodMiniFile = /*@__PURE__*/ core.$constructor("ZodMiniFile", (inst, def) => {
core.$ZodFile.init(inst, def);
ZodMiniType.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
export function file(params) {
return core._file(ZodMiniFile, params);
}
export const ZodMiniTransform = /*@__PURE__*/ core.$constructor("ZodMiniTransform", (inst, def) => {
core.$ZodTransform.init(inst, def);
ZodMiniType.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
export function transform(fn) {
return new ZodMiniTransform({
type: "transform",
transform: fn,
});
}
export const ZodMiniOptional = /*@__PURE__*/ core.$constructor("ZodMiniOptional", (inst, def) => {
core.$ZodOptional.init(inst, def);
ZodMiniType.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
export function optional(innerType) {
return new ZodMiniOptional({
type: "optional",
innerType: innerType,
});
}
export const ZodMiniExactOptional = /*@__PURE__*/ core.$constructor("ZodMiniExactOptional", (inst, def) => {
core.$ZodExactOptional.init(inst, def);
ZodMiniType.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
export function exactOptional(innerType) {
return new ZodMiniExactOptional({
type: "optional",
innerType: innerType,
});
}
export const ZodMiniNullable = /*@__PURE__*/ core.$constructor("ZodMiniNullable", (inst, def) => {
core.$ZodNullable.init(inst, def);
ZodMiniType.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
export function nullable(innerType) {
return new ZodMiniNullable({
type: "nullable",
innerType: innerType,
});
}
// nullish
// @__NO_SIDE_EFFECTS__
export function nullish(innerType) {
return optional(nullable(innerType));
}
export const ZodMiniDefault = /*@__PURE__*/ core.$constructor("ZodMiniDefault", (inst, def) => {
core.$ZodDefault.init(inst, def);
ZodMiniType.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
export function _default(innerType, defaultValue) {
return new ZodMiniDefault({
type: "default",
innerType: innerType,
get defaultValue() {
return typeof defaultValue === "function" ? defaultValue() : util.shallowClone(defaultValue);
},
});
}
export const ZodMiniPrefault = /*@__PURE__*/ core.$constructor("ZodMiniPrefault", (inst, def) => {
core.$ZodPrefault.init(inst, def);
ZodMiniType.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
export function prefault(innerType, defaultValue) {
return new ZodMiniPrefault({
type: "prefault",
innerType: innerType,
get defaultValue() {
return typeof defaultValue === "function" ? defaultValue() : util.shallowClone(defaultValue);
},
});
}
export const ZodMiniNonOptional = /*@__PURE__*/ core.$constructor("ZodMiniNonOptional", (inst, def) => {
core.$ZodNonOptional.init(inst, def);
ZodMiniType.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
export function nonoptional(innerType, params) {
return new ZodMiniNonOptional({
type: "nonoptional",
innerType: innerType,
...util.normalizeParams(params),
});
}
export const ZodMiniSuccess = /*@__PURE__*/ core.$constructor("ZodMiniSuccess", (inst, def) => {
core.$ZodSuccess.init(inst, def);
ZodMiniType.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
export function success(innerType) {
return new ZodMiniSuccess({
type: "success",
innerType: innerType,
});
}
export const ZodMiniCatch = /*@__PURE__*/ core.$constructor("ZodMiniCatch", (inst, def) => {
core.$ZodCatch.init(inst, def);
ZodMiniType.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
function _catch(innerType, catchValue) {
return new ZodMiniCatch({
type: "catch",
innerType: innerType,
catchValue: (typeof catchValue === "function" ? catchValue : () => catchValue),
});
}
export { _catch as catch };
export const ZodMiniNaN = /*@__PURE__*/ core.$constructor("ZodMiniNaN", (inst, def) => {
core.$ZodNaN.init(inst, def);
ZodMiniType.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
export function nan(params) {
return core._nan(ZodMiniNaN, params);
}
export const ZodMiniPipe = /*@__PURE__*/ core.$constructor("ZodMiniPipe", (inst, def) => {
core.$ZodPipe.init(inst, def);
ZodMiniType.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
export function pipe(in_, out) {
return new ZodMiniPipe({
type: "pipe",
in: in_,
out: out,
});
}
export const ZodMiniCodec = /*@__PURE__*/ core.$constructor("ZodMiniCodec", (inst, def) => {
ZodMiniPipe.init(inst, def);
core.$ZodCodec.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
export function codec(in_, out, params) {
return new ZodMiniCodec({
type: "pipe",
in: in_,
out: out,
transform: params.decode,
reverseTransform: params.encode,
});
}
// @__NO_SIDE_EFFECTS__
export function invertCodec(codec) {
const def = codec._zod.def;
return new ZodMiniCodec({
type: "pipe",
in: def.out,
out: def.in,
transform: def.reverseTransform,
reverseTransform: def.transform,
});
}
export const ZodMiniReadonly = /*@__PURE__*/ core.$constructor("ZodMiniReadonly", (inst, def) => {
core.$ZodReadonly.init(inst, def);
ZodMiniType.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
export function readonly(innerType) {
return new ZodMiniReadonly({
type: "readonly",
innerType: innerType,
});
}
export const ZodMiniTemplateLiteral = /*@__PURE__*/ core.$constructor("ZodMiniTemplateLiteral", (inst, def) => {
core.$ZodTemplateLiteral.init(inst, def);
ZodMiniType.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
export function templateLiteral(parts, params) {
return new ZodMiniTemplateLiteral({
type: "template_literal",
parts,
...util.normalizeParams(params),
});
}
export const ZodMiniLazy = /*@__PURE__*/ core.$constructor("ZodMiniLazy", (inst, def) => {
core.$ZodLazy.init(inst, def);
ZodMiniType.init(inst, def);
});
// export function lazy<T extends object>(getter: () => T): T {
// return util.createTransparentProxy<T>(getter);
// }
// @__NO_SIDE_EFFECTS__
function _lazy(getter) {
return new ZodMiniLazy({
type: "lazy",
getter: getter,
});
}
export { _lazy as lazy };
export const ZodMiniPromise = /*@__PURE__*/ core.$constructor("ZodMiniPromise", (inst, def) => {
core.$ZodPromise.init(inst, def);
ZodMiniType.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
export function promise(innerType) {
return new ZodMiniPromise({
type: "promise",
innerType: innerType,
});
}
export const ZodMiniCustom = /*@__PURE__*/ core.$constructor("ZodMiniCustom", (inst, def) => {
core.$ZodCustom.init(inst, def);
ZodMiniType.init(inst, def);
});
// custom checks
// @__NO_SIDE_EFFECTS__
export function check(fn, params) {
const ch = new core.$ZodCheck({
check: "custom",
...util.normalizeParams(params),
});
ch._zod.check = fn;
return ch;
}
// ZodCustom
// custom schema
// @__NO_SIDE_EFFECTS__
export function custom(fn, _params) {
return core._custom(ZodMiniCustom, fn ?? (() => true), _params);
}
// refine
// @__NO_SIDE_EFFECTS__
export function refine(fn, _params = {}) {
return core._refine(ZodMiniCustom, fn, _params);
}
// superRefine
// @__NO_SIDE_EFFECTS__
export function superRefine(fn, params) {
return core._superRefine(fn, params);
}
// Re-export describe and meta from core
export const describe = core.describe;
export const meta = core.meta;
// instanceof
class Class {
constructor(..._args) { }
}
// @__NO_SIDE_EFFECTS__
function _instanceof(cls, params = {}) {
const inst = custom((data) => data instanceof cls, params);
inst._zod.bag.Class = cls;
// Override check to emit invalid_type instead of custom
inst._zod.check = (payload) => {
if (!(payload.value instanceof cls)) {
payload.issues.push({
code: "invalid_type",
expected: cls.name,
input: payload.value,
inst,
path: [...(inst._zod.def.path ?? [])],
});
}
};
return inst;
}
export { _instanceof as instanceof };
// stringbool
export const stringbool = (...args) => core._stringbool({
Codec: ZodMiniCodec,
Boolean: ZodMiniBoolean,
String: ZodMiniString,
}, ...args);
// @__NO_SIDE_EFFECTS__
export function json() {
const jsonSchema = _lazy(() => {
return union([string(), number(), boolean(), _null(), array(jsonSchema), record(string(), jsonSchema)]);
});
return jsonSchema;
}
export const ZodMiniFunction = /*@__PURE__*/ core.$constructor("ZodMiniFunction", (inst, def) => {
core.$ZodFunction.init(inst, def);
ZodMiniType.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
export function _function(params) {
return new ZodMiniFunction({
type: "function",
input: Array.isArray(params?.input) ? tuple(params?.input) : (params?.input ?? array(unknown())),
output: params?.output ?? unknown(),
});
}
export { _function as function };

View File

@@ -0,0 +1,473 @@
'use strict'
const test = require('node:test')
const assert = require('node:assert')
const { once } = require('node:events')
const { Transform, pipeline } = require('node:stream')
const tspl = require('@matteo.collina/tspl')
const match = require('./match')
const build = require('../')
test('parse newlined delimited JSON', async (t) => {
const plan = tspl(t, { plan: 2 })
const expected = [{
level: 30,
time: 1617955768092,
pid: 2942,
hostname: 'MacBook-Pro.local',
msg: 'hello world'
}, {
level: 30,
time: 1617955768092,
pid: 2942,
hostname: 'MacBook-Pro.local',
msg: 'another message',
prop: 42
}]
const stream = build(function (source) {
source.on('data', function (line) {
match(expected.shift(), line, { assert: plan })
})
})
const lines = expected.map(JSON.stringify).join('\n')
stream.write(lines)
stream.end()
await plan
})
test('parse newline delimited JSON', async (t) => {
const plan = tspl(t, { plan: 2 })
const expected = [{
level: 30,
time: 1617955768092,
pid: 2942,
hostname: 'MacBook-Pro.local',
msg: 'hello world'
}, {
level: 30,
time: 1617955768092,
pid: 2942,
hostname: 'MacBook-Pro.local',
msg: 'another message',
prop: 42
}]
const stream = build(function (source) {
source.on('data', function (line) {
match(expected.shift(), line, { assert: plan })
})
}, { parse: 'json' })
const lines = expected.map(JSON.stringify).join('\n')
stream.write(lines)
stream.end()
})
test('null support', async (t) => {
const plan = tspl(t, { plan: 1 })
const stream = build(function (source) {
source.on('unknown', function (line) {
match('null', line, { assert: plan })
})
})
stream.write('null\n')
stream.end()
await plan
})
test('broken json', async (t) => {
const plan = tspl(t, { plan: 2 })
const expected = '{ "truncated'
const stream = build(function (source) {
source.on('unknown', function (line, error) {
match(expected, line, { assert: plan })
const regex = /^(Unexpected end of JSON input|Unterminated string in JSON at position 12)( \(line 1 column 13\))?$/
plan.match(error.message, regex)
})
})
stream.write(expected + '\n')
stream.end()
await plan
})
test('pure values', async (t) => {
const plan = tspl(t, { plan: 3 })
const stream = build(function (source) {
source.on('data', function (line) {
plan.equal(line.data, 42)
plan.ok(line.time)
plan.equal(new Date(line.time).getTime(), line.time)
})
})
stream.write('42\n')
stream.end()
await plan
})
test('support async iteration', async (t) => {
const plan = tspl(t, { plan: 2 })
const expected = [{
level: 30,
time: 1617955768092,
pid: 2942,
hostname: 'MacBook-Pro.local',
msg: 'hello world'
}, {
level: 30,
time: 1617955768092,
pid: 2942,
hostname: 'MacBook-Pro.local',
msg: 'another message',
prop: 42
}]
const stream = build(async function (source) {
for await (const line of source) {
match(expected.shift(), line, { assert: plan })
}
})
const lines = expected.map(JSON.stringify).join('\n')
stream.write(lines)
stream.end()
await plan
})
test('rejecting errors the stream', async () => {
const stream = build(async function (source) {
throw new Error('kaboom')
})
const [err] = await once(stream, 'error')
assert.equal(err.message, 'kaboom')
})
test('emits an error if the transport expects pino to send the config, but pino is not going to', async function () {
const stream = build(() => {}, { expectPinoConfig: true })
const [err] = await once(stream, 'error')
assert.equal(err.message, 'This transport is not compatible with the current version of pino. Please upgrade pino to the latest version.')
})
test('set metadata', async (t) => {
const plan = tspl(t, { plan: 9 })
const expected = [{
level: 30,
time: 1617955768092,
pid: 2942,
hostname: 'MacBook-Pro.local',
msg: 'hello world'
}, {
level: 30,
time: 1617955768092,
pid: 2942,
hostname: 'MacBook-Pro.local',
msg: 'another message',
prop: 42
}]
const stream = build(function (source) {
source.on('data', function (line) {
const obj = expected.shift()
plan.equal(this.lastLevel, obj.level)
plan.equal(this.lastTime, obj.time)
match(this.lastObj, obj, { assert: plan })
match(obj, line, { assert: plan })
})
}, { metadata: true })
plan.equal(stream[Symbol.for('pino.metadata')], true)
const lines = expected.map(JSON.stringify).join('\n')
stream.write(lines)
stream.end()
await plan
})
test('parse lines', async (t) => {
const plan = tspl(t, { plan: 9 })
const expected = [{
level: 30,
time: 1617955768092,
pid: 2942,
hostname: 'MacBook-Pro.local',
msg: 'hello world'
}, {
level: 30,
time: 1617955768092,
pid: 2942,
hostname: 'MacBook-Pro.local',
msg: 'another message',
prop: 42
}]
const stream = build(function (source) {
source.on('data', function (line) {
const obj = expected.shift()
plan.equal(this.lastLevel, obj.level)
plan.equal(this.lastTime, obj.time)
match(this.lastObj, obj, { assert: plan })
match(JSON.stringify(obj), line, { assert: plan })
})
}, { metadata: true, parse: 'lines' })
plan.equal(stream[Symbol.for('pino.metadata')], true)
const lines = expected.map(JSON.stringify).join('\n')
stream.write(lines)
stream.end()
await plan
})
test('custom parse line function', async (t) => {
const plan = tspl(t, { plan: 11 })
const expected = [{
level: 30,
time: 1617955768092,
pid: 2942,
hostname: 'MacBook-Pro.local',
msg: 'hello world'
}, {
level: 30,
time: 1617955768092,
pid: 2942,
hostname: 'MacBook-Pro.local',
msg: 'another message',
prop: 42
}]
let num = 0
function parseLine (str) {
const obj = JSON.parse(str)
match(expected[num], obj, { assert: plan })
return obj
}
const stream = build(function (source) {
source.on('data', function (line) {
const obj = expected[num]
plan.equal(this.lastLevel, obj.level)
plan.equal(this.lastTime, obj.time)
match(this.lastObj, obj, { assert: plan })
match(obj, line, { assert: plan })
num++
})
}, { metadata: true, parseLine })
plan.equal(stream[Symbol.for('pino.metadata')], true)
const lines = expected.map(JSON.stringify).join('\n')
stream.write(lines)
stream.end()
await plan
})
test('set metadata (default)', async (t) => {
const plan = tspl(t, { plan: 9 })
const expected = [{
level: 30,
time: 1617955768092,
pid: 2942,
hostname: 'MacBook-Pro.local',
msg: 'hello world'
}, {
level: 30,
time: 1617955768092,
pid: 2942,
hostname: 'MacBook-Pro.local',
msg: 'another message',
prop: 42
}]
const stream = build(function (source) {
source.on('data', function (line) {
const obj = expected.shift()
plan.equal(this.lastLevel, obj.level)
plan.equal(this.lastTime, obj.time)
match(this.lastObj, obj, { assert: plan })
match(obj, line, { assert: plan })
})
})
plan.equal(stream[Symbol.for('pino.metadata')], true)
const lines = expected.map(JSON.stringify).join('\n')
stream.write(lines)
stream.end()
await plan
})
test('do not set metadata', async (t) => {
const plan = tspl(t, { plan: 9 })
const expected = [{
level: 30,
time: 1617955768092,
pid: 2942,
hostname: 'MacBook-Pro.local',
msg: 'hello world'
}, {
level: 30,
time: 1617955768092,
pid: 2942,
hostname: 'MacBook-Pro.local',
msg: 'another message',
prop: 42
}]
const stream = build(function (source) {
source.on('data', function (line) {
const obj = expected.shift()
plan.equal(this.lastLevel, undefined)
plan.equal(this.lastTime, undefined)
plan.equal(this.lastObj, undefined)
match(obj, line, { assert: plan })
})
}, { metadata: false })
plan.equal(stream[Symbol.for('pino.metadata')], undefined)
const lines = expected.map(JSON.stringify).join('\n')
stream.write(lines)
stream.end()
await plan
})
test('close logic', async (t) => {
const plan = tspl(t, { plan: 3 })
const expected = [{
level: 30,
time: 1617955768092,
pid: 2942,
hostname: 'MacBook-Pro.local',
msg: 'hello world'
}, {
level: 30,
time: 1617955768092,
pid: 2942,
hostname: 'MacBook-Pro.local',
msg: 'another message',
prop: 42
}]
const stream = build(function (source) {
source.on('data', function (line) {
match(expected.shift(), line, { assert: plan })
})
}, {
close (err, cb) {
plan.ok('close called')
process.nextTick(cb, err)
}
})
const lines = expected.map(JSON.stringify).join('\n')
stream.write(lines)
stream.end()
await plan
})
test('close with promises', async (t) => {
const plan = tspl(t, { plan: 3 })
const expected = [{
level: 30,
time: 1617955768092,
pid: 2942,
hostname: 'MacBook-Pro.local',
msg: 'hello world'
}, {
level: 30,
time: 1617955768092,
pid: 2942,
hostname: 'MacBook-Pro.local',
msg: 'another message',
prop: 42
}]
const stream = build(function (source) {
source.on('data', function (line) {
match(expected.shift(), line, { assert: plan })
})
}, {
async close () {
plan.ok('close called')
}
})
const lines = expected.map(JSON.stringify).join('\n')
stream.write(lines)
stream.end()
await plan
})
test('support Transform streams', async (t) => {
const plan = tspl(t, { plan: 7 })
const expected1 = [{
level: 30,
time: 1617955768092,
pid: 2942,
hostname: 'MacBook-Pro.local',
msg: 'hello world'
}, {
level: 30,
time: 1617955768092,
pid: 2942,
hostname: 'MacBook-Pro.local',
msg: 'another message',
prop: 42
}]
const expected2 = []
const stream1 = build(function (source) {
const transform = new Transform({
objectMode: true,
autoDestroy: true,
transform (chunk, enc, cb) {
match(expected1.shift(), chunk, { assert: plan })
chunk.service = 'from transform'
expected2.push(chunk)
cb(null, JSON.stringify(chunk) + '\n')
}
})
pipeline(source, transform, () => {})
return transform
}, { enablePipelining: true })
const stream2 = build(function (source) {
source.on('data', function (line) {
match(expected2.shift(), line, { assert: plan })
})
})
pipeline(stream1, stream2, function (err) {
plan.equal(err, undefined)
plan.deepStrictEqual(expected1, [])
plan.deepStrictEqual(expected2, [])
})
const lines = expected1.map(JSON.stringify).join('\n')
stream1.write(lines)
stream1.end()
await plan
})

View File

@@ -0,0 +1,73 @@
"use strict";
/* global self, window, module, global, require */
module.exports = function () {
"use strict";
var globalObject = void 0;
function isFunction(x) {
return typeof x === "function";
}
// Seek the global object
if (global !== undefined) {
globalObject = global;
} else if (window !== undefined && window.document) {
globalObject = window;
} else {
globalObject = self;
}
// Test for any native promise implementation, and if that
// implementation appears to conform to the specificaton.
// This code mostly nicked from the es6-promise module polyfill
// and then fooled with.
var hasPromiseSupport = function () {
// No promise object at all, and it's a non-starter
if (!globalObject.hasOwnProperty("Promise")) {
return false;
}
// There is a Promise object. Does it conform to the spec?
var P = globalObject.Promise;
// Some of these methods are missing from
// Firefox/Chrome experimental implementations
if (!P.hasOwnProperty("resolve") || !P.hasOwnProperty("reject")) {
return false;
}
if (!P.hasOwnProperty("all") || !P.hasOwnProperty("race")) {
return false;
}
// Older version of the spec had a resolver object
// as the arg rather than a function
return function () {
var resolve = void 0;
var p = new globalObject.Promise(function (r) {
resolve = r;
});
if (p) {
return isFunction(resolve);
}
return false;
}();
}();
// Export the native Promise implementation if it
// looks like it matches the spec
if (hasPromiseSupport) {
return globalObject.Promise;
}
// Otherwise, return the es6-promise polyfill by @jaffathecake.
return require("es6-promise").Promise;
}();