docs: 仓库链接指向本镜像仓库
Build NapCat Artifacts / Type Check & Test (push) Waiting to run

This commit is contained in:
TanTan committed 2026-11-13 09:25:58 +08:00
1 parent f954252a34
commit e311ca3275
35554 files changed
+6229626 -4

No files matched your search

@@ -0,0 +1 @@
{"version":3,"file":"utilities.d.ts","sourceRoot":"","sources":["../src/utilities.ts"],"names":[],"mappings":"AAyBA;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAC/B,WAAW,CAAC,EAAE,OAAO,CAAC;CACvB;AAED;;GAEG;AACH,eAAO,MAAM,SAAS,GAAI,UAAU,MAAM,EAAE,UAAS,gBAAqB,WAgBzE,CAAC"}
@@ -0,0 +1 @@
{"version":3,"file":"isoCBOR.d.ts","sourceRoot":"","sources":["../../../src/helpers/iso/isoCBOR.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,KAAK,QAAQ,MAAM,uBAAuB,CAAC;AAElD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAExD;;;;;;;;;GASG;AAEH;;;;;;GAMG;AACH,wBAAgB,WAAW,CAAC,IAAI,EAAE,KAAK,EAAE,WAAW,GAAG,IAAI,CAQ1D;AAED;;GAEG;AACH,wBAAgB,MAAM,CAAC,KAAK,EAAE,QAAQ,CAAC,QAAQ,GAAG,WAAW,CAE5D"}
@@ -0,0 +1,80 @@
import {TableCollection as $788781baa30117fa$export$596e1b2e2cf93690} from "./TableCollection.module.js";
import {useGridState as $1YSEb$useGridState} from "@react-stately/grid";
import {useState as $1YSEb$useState, useMemo as $1YSEb$useMemo, useCallback as $1YSEb$useCallback} from "react";
import {useCollection as $1YSEb$useCollection} from "@react-stately/collections";
/*
* Copyright 2020 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
const $4a0dd036d492cee4$var$OPPOSITE_SORT_DIRECTION = {
ascending: 'descending',
descending: 'ascending'
};
function $4a0dd036d492cee4$export$907bcc6c48325fd6(props) {
let [isKeyboardNavigationDisabled, setKeyboardNavigationDisabled] = (0, $1YSEb$useState)(false);
let { selectionMode: selectionMode = 'none', showSelectionCheckboxes: showSelectionCheckboxes, showDragButtons: showDragButtons } = props;
let context = (0, $1YSEb$useMemo)(()=>({
showSelectionCheckboxes: showSelectionCheckboxes && selectionMode !== 'none',
showDragButtons: showDragButtons,
selectionMode: selectionMode,
columns: []
}), [
props.children,
showSelectionCheckboxes,
selectionMode,
showDragButtons
]);
let collection = (0, $1YSEb$useCollection)(props, (0, $1YSEb$useCallback)((nodes)=>new (0, $788781baa30117fa$export$596e1b2e2cf93690)(nodes, null, context), [
context
]), context);
let { disabledKeys: disabledKeys, selectionManager: selectionManager } = (0, $1YSEb$useGridState)({
...props,
collection: collection,
disabledBehavior: props.disabledBehavior || 'selection'
});
var _props_sortDescriptor;
return {
collection: collection,
disabledKeys: disabledKeys,
selectionManager: selectionManager,
showSelectionCheckboxes: props.showSelectionCheckboxes || false,
sortDescriptor: (_props_sortDescriptor = props.sortDescriptor) !== null && _props_sortDescriptor !== void 0 ? _props_sortDescriptor : null,
isKeyboardNavigationDisabled: collection.size === 0 || isKeyboardNavigationDisabled,
setKeyboardNavigationDisabled: setKeyboardNavigationDisabled,
sort (columnKey, direction) {
var _props_sortDescriptor, _props_onSortChange;
(_props_onSortChange = props.onSortChange) === null || _props_onSortChange === void 0 ? void 0 : _props_onSortChange.call(props, {
column: columnKey,
direction: direction !== null && direction !== void 0 ? direction : ((_props_sortDescriptor = props.sortDescriptor) === null || _props_sortDescriptor === void 0 ? void 0 : _props_sortDescriptor.column) === columnKey ? $4a0dd036d492cee4$var$OPPOSITE_SORT_DIRECTION[props.sortDescriptor.direction] : 'ascending'
});
}
};
}
function $4a0dd036d492cee4$export$31447e17397b15c2(state, filterFn) {
let collection = (0, $1YSEb$useMemo)(()=>filterFn ? state.collection.filter(filterFn) : state.collection, [
state.collection,
filterFn
]);
let selectionManager = state.selectionManager.withCollection(collection);
// TODO: handle focus key reset? That logic is in useGridState
return {
...state,
collection: collection,
selectionManager: selectionManager
};
}
export {$4a0dd036d492cee4$export$907bcc6c48325fd6 as useTableState, $4a0dd036d492cee4$export$31447e17397b15c2 as UNSTABLE_useFilteredTableState};
//# sourceMappingURL=useTableState.module.js.map
@@ -0,0 +1,12 @@
"use strict";
// THIS CODE WAS AUTOMATICALLY GENERATED
// DO NOT EDIT THIS CODE BY HAND
// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE:
// npx nx generate-lib repo
Object.defineProperty(exports, "__esModule", { value: true });
exports.es2015_symbol = void 0;
const base_config_1 = require("./base-config");
exports.es2015_symbol = {
libs: [],
variables: [['SymbolConstructor', base_config_1.TYPE]],
};
@@ -0,0 +1,18 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./readonly-optional"), exports);
@@ -0,0 +1,12 @@
import { expect, expectTypeOf, test } from "vitest";
import * as z from "zod/v4";
test("void", () => {
const v = z.void();
v.parse(undefined);
expect(() => v.parse(null)).toThrow();
expect(() => v.parse("")).toThrow();
type v = z.infer<typeof v>;
expectTypeOf<v>().toEqualTypeOf<void>();
});
@@ -0,0 +1,56 @@
{
"name": "https-proxy-agent",
"version": "5.0.1",
"description": "An HTTP(s) proxy `http.Agent` implementation for HTTPS",
"main": "dist/index",
"types": "dist/index",
"files": [
"dist"
],
"scripts": {
"prebuild": "rimraf dist",
"build": "tsc",
"test": "mocha --reporter spec",
"test-lint": "eslint src --ext .js,.ts",
"prepublishOnly": "npm run build"
},
"repository": {
"type": "git",
"url": "git://github.com/TooTallNate/node-https-proxy-agent.git"
},
"keywords": [
"https",
"proxy",
"endpoint",
"agent"
],
"author": "Nathan Rajlich <nathan@tootallnate.net> (http://n8.io/)",
"license": "MIT",
"bugs": {
"url": "https://github.com/TooTallNate/node-https-proxy-agent/issues"
},
"dependencies": {
"agent-base": "6",
"debug": "4"
},
"devDependencies": {
"@types/debug": "4",
"@types/node": "^12.12.11",
"@typescript-eslint/eslint-plugin": "1.6.0",
"@typescript-eslint/parser": "1.1.0",
"eslint": "5.16.0",
"eslint-config-airbnb": "17.1.0",
"eslint-config-prettier": "4.1.0",
"eslint-import-resolver-typescript": "1.1.1",
"eslint-plugin-import": "2.16.0",
"eslint-plugin-jsx-a11y": "6.2.1",
"eslint-plugin-react": "7.12.4",
"mocha": "^6.2.2",
"proxy": "1",
"rimraf": "^3.0.0",
"typescript": "^3.5.3"
},
"engines": {
"node": ">= 6"
}
}
@@ -0,0 +1,456 @@
Native Abstractions for Node.js
===============================
**A header file filled with macro and utility goodness for making add-on development for Node.js easier across versions 8, 10, 12, 14, 16, 17, 18, 19, 20, 21, 22, 23, 24 and 25.**
***Current version: 2.24.0***
*(See [CHANGELOG.md](https://github.com/nodejs/nan/blob/master/CHANGELOG.md) for complete ChangeLog)*
[![NPM](https://nodei.co/npm/nan.png?downloads=true&downloadRank=true)](https://nodei.co/npm/nan/) [![NPM](https://nodei.co/npm-dl/nan.png?months=6&height=3)](https://nodei.co/npm/nan/)
[![Build status](https://ci.appveyor.com/api/projects/status/kh73pbm9dsju7fgh)](https://ci.appveyor.com/project/RodVagg/nan)
Thanks to the crazy changes in V8 (and some in Node core), keeping native addons compiling happily across versions, particularly 0.10 to 0.12 to 4.0, is a minor nightmare. The goal of this project is to store all logic necessary to develop native Node.js addons without having to inspect `NODE_MODULE_VERSION` and get yourself into a macro-tangle.
This project also contains some helper utilities that make addon development a bit more pleasant.
* **[News & Updates](#news)**
* **[Usage](#usage)**
* **[Example](#example)**
* **[API](#api)**
* **[Tests](#tests)**
* **[Known issues](#issues)**
* **[Governance & Contributing](#governance)**
<a name="news"></a>
## News & Updates
<a name="usage"></a>
## Usage
Simply add **NAN** as a dependency using a package manager like npm, yarn, or bun:
``` bash
$ npm install nan
```
Pull in the path to **NAN** in your *binding.gyp* so that you can use `#include <nan.h>` in your *.cpp* files:
``` python
"include_dirs" : [
"<!(node -e \"require('nan')\")"
]
```
This works like a `-I<path-to-NAN>` when compiling your addon.
<a name="example"></a>
## Example
Just getting started with Nan? Take a look at the **[Node Add-on Examples](https://github.com/nodejs/node-addon-examples)**.
Refer to a [quick-start **Nan** Boilerplate](https://github.com/fcanas/node-native-boilerplate) for a ready-to-go project that utilizes basic Nan functionality.
For a simpler example, see the **[async pi estimation example](https://github.com/nodejs/nan/tree/master/examples/async_pi_estimate)** in the examples directory for full code and an explanation of what this Monte Carlo Pi estimation example does. Below are just some parts of the full example that illustrate the use of **NAN**.
Yet another example is **[nan-example-eol](https://github.com/CodeCharmLtd/nan-example-eol)**. It shows newline detection implemented as a native addon.
Also take a look at our comprehensive **[C++ test suite](https://github.com/nodejs/nan/tree/master/test/cpp)** which has a plethora of code snippets for your pasting pleasure.
<a name="api"></a>
## API
Additional to the NAN documentation below, please consult:
* [The V8 Getting Started * Guide](https://v8.dev/docs/embed)
* [V8 API Documentation](https://v8docs.nodesource.com/)
* [Node Add-on Documentation](https://nodejs.org/api/addons.html)
<!-- START API -->
### JavaScript-accessible methods
A _template_ is a blueprint for JavaScript functions and objects in a context. You can use a template to wrap C++ functions and data structures within JavaScript objects so that they can be manipulated from JavaScript. See the V8 Embedders Guide section on [Templates](https://github.com/v8/v8/wiki/Embedder%27s-Guide#templates) for further information.
In order to expose functionality to JavaScript via a template, you must provide it to V8 in a form that it understands. Across the versions of V8 supported by NAN, JavaScript-accessible method signatures vary widely, NAN fully abstracts method declaration and provides you with an interface that is similar to the most recent V8 API but is backward-compatible with older versions that still use the now-deceased `v8::Argument` type.
* **Method argument types**
- <a href="doc/methods.md#api_nan_function_callback_info"><b><code>Nan::FunctionCallbackInfo</code></b></a>
- <a href="doc/methods.md#api_nan_property_callback_info"><b><code>Nan::PropertyCallbackInfo</code></b></a>
- <a href="doc/methods.md#api_nan_return_value"><b><code>Nan::ReturnValue</code></b></a>
* **Method declarations**
- <a href="doc/methods.md#api_nan_method"><b>Method declaration</b></a>
- <a href="doc/methods.md#api_nan_getter"><b>Getter declaration</b></a>
- <a href="doc/methods.md#api_nan_setter"><b>Setter declaration</b></a>
- <a href="doc/methods.md#api_nan_property_getter"><b>Property getter declaration</b></a>
- <a href="doc/methods.md#api_nan_property_setter"><b>Property setter declaration</b></a>
- <a href="doc/methods.md#api_nan_property_enumerator"><b>Property enumerator declaration</b></a>
- <a href="doc/methods.md#api_nan_property_deleter"><b>Property deleter declaration</b></a>
- <a href="doc/methods.md#api_nan_property_query"><b>Property query declaration</b></a>
- <a href="doc/methods.md#api_nan_index_getter"><b>Index getter declaration</b></a>
- <a href="doc/methods.md#api_nan_index_setter"><b>Index setter declaration</b></a>
- <a href="doc/methods.md#api_nan_index_enumerator"><b>Index enumerator declaration</b></a>
- <a href="doc/methods.md#api_nan_index_deleter"><b>Index deleter declaration</b></a>
- <a href="doc/methods.md#api_nan_index_query"><b>Index query declaration</b></a>
* Method and template helpers
- <a href="doc/methods.md#api_nan_set_method"><b><code>Nan::SetMethod()</code></b></a>
- <a href="doc/methods.md#api_nan_set_prototype_method"><b><code>Nan::SetPrototypeMethod()</code></b></a>
- <a href="doc/methods.md#api_nan_set_accessor"><b><code>Nan::SetAccessor()</code></b></a>
- <a href="doc/methods.md#api_nan_set_named_property_handler"><b><code>Nan::SetNamedPropertyHandler()</code></b></a>
- <a href="doc/methods.md#api_nan_set_indexed_property_handler"><b><code>Nan::SetIndexedPropertyHandler()</code></b></a>
- <a href="doc/methods.md#api_nan_set_template"><b><code>Nan::SetTemplate()</code></b></a>
- <a href="doc/methods.md#api_nan_set_prototype_template"><b><code>Nan::SetPrototypeTemplate()</code></b></a>
- <a href="doc/methods.md#api_nan_set_instance_template"><b><code>Nan::SetInstanceTemplate()</code></b></a>
- <a href="doc/methods.md#api_nan_set_call_handler"><b><code>Nan::SetCallHandler()</code></b></a>
- <a href="doc/methods.md#api_nan_set_call_as_function_handler"><b><code>Nan::SetCallAsFunctionHandler()</code></b></a>
### Scopes
A _local handle_ is a pointer to an object. All V8 objects are accessed using handles, they are necessary because of the way the V8 garbage collector works.
A handle scope can be thought of as a container for any number of handles. When you've finished with your handles, instead of deleting each one individually you can simply delete their scope.
The creation of `HandleScope` objects is different across the supported versions of V8. Therefore, NAN provides its own implementations that can be used safely across these.
- <a href="doc/scopes.md#api_nan_handle_scope"><b><code>Nan::HandleScope</code></b></a>
- <a href="doc/scopes.md#api_nan_escapable_handle_scope"><b><code>Nan::EscapableHandleScope</code></b></a>
Also see the V8 Embedders Guide section on [Handles and Garbage Collection](https://github.com/v8/v8/wiki/Embedder%27s%20Guide#handles-and-garbage-collection).
### Persistent references
An object reference that is independent of any `HandleScope` is a _persistent_ reference. Where a `Local` handle only lives as long as the `HandleScope` in which it was allocated, a `Persistent` handle remains valid until it is explicitly disposed.
Due to the evolution of the V8 API, it is necessary for NAN to provide a wrapper implementation of the `Persistent` classes to supply compatibility across the V8 versions supported.
- <a href="doc/persistent.md#api_nan_persistent_base"><b><code>Nan::PersistentBase & v8::PersistentBase</code></b></a>
- <a href="doc/persistent.md#api_nan_non_copyable_persistent_traits"><b><code>Nan::NonCopyablePersistentTraits & v8::NonCopyablePersistentTraits</code></b></a>
- <a href="doc/persistent.md#api_nan_copyable_persistent_traits"><b><code>Nan::CopyablePersistentTraits & v8::CopyablePersistentTraits</code></b></a>
- <a href="doc/persistent.md#api_nan_persistent"><b><code>Nan::Persistent</code></b></a>
- <a href="doc/persistent.md#api_nan_global"><b><code>Nan::Global</code></b></a>
- <a href="doc/persistent.md#api_nan_weak_callback_info"><b><code>Nan::WeakCallbackInfo</code></b></a>
- <a href="doc/persistent.md#api_nan_weak_callback_type"><b><code>Nan::WeakCallbackType</code></b></a>
Also see the V8 Embedders Guide section on [Handles and Garbage Collection](https://v8.dev/docs/embed#handles-and-garbage-collection).
### New
NAN provides a `Nan::New()` helper for the creation of new JavaScript objects in a way that's compatible across the supported versions of V8.
- <a href="doc/new.md#api_nan_new"><b><code>Nan::New()</code></b></a>
- <a href="doc/new.md#api_nan_undefined"><b><code>Nan::Undefined()</code></b></a>
- <a href="doc/new.md#api_nan_null"><b><code>Nan::Null()</code></b></a>
- <a href="doc/new.md#api_nan_true"><b><code>Nan::True()</code></b></a>
- <a href="doc/new.md#api_nan_false"><b><code>Nan::False()</code></b></a>
- <a href="doc/new.md#api_nan_empty_string"><b><code>Nan::EmptyString()</code></b></a>
### Converters
NAN contains functions that convert `v8::Value`s to other `v8::Value` types and native types. Since type conversion is not guaranteed to succeed, they return `Nan::Maybe` types. These converters can be used in place of `value->ToX()` and `value->XValue()` (where `X` is one of the types, e.g. `Boolean`) in a way that provides a consistent interface across V8 versions. Newer versions of V8 use the new `v8::Maybe` and `v8::MaybeLocal` types for these conversions, older versions don't have this functionality so it is provided by NAN.
- <a href="doc/converters.md#api_nan_to"><b><code>Nan::To()</code></b></a>
### Maybe Types
The `Nan::MaybeLocal` and `Nan::Maybe` types are monads that encapsulate `v8::Local` handles that _may be empty_.
* **Maybe Types**
- <a href="doc/maybe_types.md#api_nan_maybe_local"><b><code>Nan::MaybeLocal</code></b></a>
- <a href="doc/maybe_types.md#api_nan_maybe"><b><code>Nan::Maybe</code></b></a>
- <a href="doc/maybe_types.md#api_nan_nothing"><b><code>Nan::Nothing</code></b></a>
- <a href="doc/maybe_types.md#api_nan_just"><b><code>Nan::Just</code></b></a>
* **Maybe Helpers**
- <a href="doc/maybe_types.md#api_nan_call"><b><code>Nan::Call()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_to_detail_string"><b><code>Nan::ToDetailString()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_to_array_index"><b><code>Nan::ToArrayIndex()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_equals"><b><code>Nan::Equals()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_new_instance"><b><code>Nan::NewInstance()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_get_function"><b><code>Nan::GetFunction()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_set"><b><code>Nan::Set()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_define_own_property"><b><code>Nan::DefineOwnProperty()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_force_set"><del><b><code>Nan::ForceSet()</code></b></del></a>
- <a href="doc/maybe_types.md#api_nan_get"><b><code>Nan::Get()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_get_property_attribute"><b><code>Nan::GetPropertyAttributes()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_has"><b><code>Nan::Has()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_delete"><b><code>Nan::Delete()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_get_property_names"><b><code>Nan::GetPropertyNames()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_get_own_property_names"><b><code>Nan::GetOwnPropertyNames()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_set_prototype"><b><code>Nan::SetPrototype()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_object_proto_to_string"><b><code>Nan::ObjectProtoToString()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_has_own_property"><b><code>Nan::HasOwnProperty()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_has_real_named_property"><b><code>Nan::HasRealNamedProperty()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_has_real_indexed_property"><b><code>Nan::HasRealIndexedProperty()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_has_real_named_callback_property"><b><code>Nan::HasRealNamedCallbackProperty()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_get_real_named_property_in_prototype_chain"><b><code>Nan::GetRealNamedPropertyInPrototypeChain()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_get_real_named_property"><b><code>Nan::GetRealNamedProperty()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_call_as_function"><b><code>Nan::CallAsFunction()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_call_as_constructor"><b><code>Nan::CallAsConstructor()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_get_source_line"><b><code>Nan::GetSourceLine()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_get_line_number"><b><code>Nan::GetLineNumber()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_get_start_column"><b><code>Nan::GetStartColumn()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_get_end_column"><b><code>Nan::GetEndColumn()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_clone_element_at"><b><code>Nan::CloneElementAt()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_has_private"><b><code>Nan::HasPrivate()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_get_private"><b><code>Nan::GetPrivate()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_set_private"><b><code>Nan::SetPrivate()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_delete_private"><b><code>Nan::DeletePrivate()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_make_maybe"><b><code>Nan::MakeMaybe()</code></b></a>
### Script
NAN provides `v8::Script` helpers as the API has changed over the supported versions of V8.
- <a href="doc/script.md#api_nan_compile_script"><b><code>Nan::CompileScript()</code></b></a>
- <a href="doc/script.md#api_nan_run_script"><b><code>Nan::RunScript()</code></b></a>
- <a href="doc/script.md#api_nan_script_origin"><b><code>Nan::ScriptOrigin</code></b></a>
### JSON
The _JSON_ object provides the C++ versions of the methods offered by the `JSON` object in javascript. V8 exposes these methods via the `v8::JSON` object.
- <a href="doc/json.md#api_nan_json_parse"><b><code>Nan::JSON.Parse</code></b></a>
- <a href="doc/json.md#api_nan_json_stringify"><b><code>Nan::JSON.Stringify</code></b></a>
Refer to the V8 JSON object in the [V8 documentation](https://v8docs.nodesource.com/node-8.16/da/d6f/classv8_1_1_j_s_o_n.html) for more information about these methods and their arguments.
### Errors
NAN includes helpers for creating, throwing and catching Errors as much of this functionality varies across the supported versions of V8 and must be abstracted.
Note that an Error object is simply a specialized form of `v8::Value`.
Also consult the V8 Embedders Guide section on [Exceptions](https://v8.dev/docs/embed#exceptions) for more information.
- <a href="doc/errors.md#api_nan_error"><b><code>Nan::Error()</code></b></a>
- <a href="doc/errors.md#api_nan_range_error"><b><code>Nan::RangeError()</code></b></a>
- <a href="doc/errors.md#api_nan_reference_error"><b><code>Nan::ReferenceError()</code></b></a>
- <a href="doc/errors.md#api_nan_syntax_error"><b><code>Nan::SyntaxError()</code></b></a>
- <a href="doc/errors.md#api_nan_type_error"><b><code>Nan::TypeError()</code></b></a>
- <a href="doc/errors.md#api_nan_throw_error"><b><code>Nan::ThrowError()</code></b></a>
- <a href="doc/errors.md#api_nan_throw_range_error"><b><code>Nan::ThrowRangeError()</code></b></a>
- <a href="doc/errors.md#api_nan_throw_reference_error"><b><code>Nan::ThrowReferenceError()</code></b></a>
- <a href="doc/errors.md#api_nan_throw_syntax_error"><b><code>Nan::ThrowSyntaxError()</code></b></a>
- <a href="doc/errors.md#api_nan_throw_type_error"><b><code>Nan::ThrowTypeError()</code></b></a>
- <a href="doc/errors.md#api_nan_fatal_exception"><b><code>Nan::FatalException()</code></b></a>
- <a href="doc/errors.md#api_nan_errno_exception"><b><code>Nan::ErrnoException()</code></b></a>
- <a href="doc/errors.md#api_nan_try_catch"><b><code>Nan::TryCatch</code></b></a>
### Buffers
NAN's `node::Buffer` helpers exist as the API has changed across supported Node versions. Use these methods to ensure compatibility.
- <a href="doc/buffers.md#api_nan_new_buffer"><b><code>Nan::NewBuffer()</code></b></a>
- <a href="doc/buffers.md#api_nan_copy_buffer"><b><code>Nan::CopyBuffer()</code></b></a>
- <a href="doc/buffers.md#api_nan_free_callback"><b><code>Nan::FreeCallback()</code></b></a>
### Nan::Callback
`Nan::Callback` makes it easier to use `v8::Function` handles as callbacks. A class that wraps a `v8::Function` handle, protecting it from garbage collection and making it particularly useful for storage and use across asynchronous execution.
- <a href="doc/callback.md#api_nan_callback"><b><code>Nan::Callback</code></b></a>
### Asynchronous work helpers
`Nan::AsyncWorker`, `Nan::AsyncProgressWorker` and `Nan::AsyncProgressQueueWorker` are helper classes that make working with asynchronous code easier.
- <a href="doc/asyncworker.md#api_nan_async_worker"><b><code>Nan::AsyncWorker</code></b></a>
- <a href="doc/asyncworker.md#api_nan_async_progress_worker"><b><code>Nan::AsyncProgressWorkerBase &amp; Nan::AsyncProgressWorker</code></b></a>
- <a href="doc/asyncworker.md#api_nan_async_progress_queue_worker"><b><code>Nan::AsyncProgressQueueWorker</code></b></a>
- <a href="doc/asyncworker.md#api_nan_async_queue_worker"><b><code>Nan::AsyncQueueWorker</code></b></a>
### Strings & Bytes
Miscellaneous string & byte encoding and decoding functionality provided for compatibility across supported versions of V8 and Node. Implemented by NAN to ensure that all encoding types are supported, even for older versions of Node where they are missing.
- <a href="doc/string_bytes.md#api_nan_encoding"><b><code>Nan::Encoding</code></b></a>
- <a href="doc/string_bytes.md#api_nan_encode"><b><code>Nan::Encode()</code></b></a>
- <a href="doc/string_bytes.md#api_nan_try_encode"><b><code>Nan::TryEncode()</code></b></a>
- <a href="doc/string_bytes.md#api_nan_decode_bytes"><b><code>Nan::DecodeBytes()</code></b></a>
- <a href="doc/string_bytes.md#api_nan_decode_write"><b><code>Nan::DecodeWrite()</code></b></a>
### Object Wrappers
The `ObjectWrap` class can be used to make wrapped C++ objects and a factory of wrapped objects.
- <a href="doc/object_wrappers.md#api_nan_object_wrap"><b><code>Nan::ObjectWrap</code></b></a>
### V8 internals
The hooks to access V8 internals—including GC and statistics—are different across the supported versions of V8, therefore NAN provides its own hooks that call the appropriate V8 methods.
- <a href="doc/v8_internals.md#api_nan_gc_callback"><b><code>NAN_GC_CALLBACK()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_add_gc_epilogue_callback"><b><code>Nan::AddGCEpilogueCallback()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_remove_gc_epilogue_callback"><b><code>Nan::RemoveGCEpilogueCallback()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_add_gc_prologue_callback"><b><code>Nan::AddGCPrologueCallback()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_remove_gc_prologue_callback"><b><code>Nan::RemoveGCPrologueCallback()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_get_heap_statistics"><b><code>Nan::GetHeapStatistics()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_set_counter_function"><b><code>Nan::SetCounterFunction()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_set_create_histogram_function"><b><code>Nan::SetCreateHistogramFunction()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_set_add_histogram_sample_function"><b><code>Nan::SetAddHistogramSampleFunction()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_idle_notification"><del><b><code>Nan::IdleNotification()</code></b></del></a>
- <a href="doc/v8_internals.md#api_nan_low_memory_notification"><b><code>Nan::LowMemoryNotification()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_context_disposed_notification"><b><code>Nan::ContextDisposedNotification()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_get_internal_field_pointer"><b><code>Nan::GetInternalFieldPointer()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_set_internal_field_pointer"><b><code>Nan::SetInternalFieldPointer()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_adjust_external_memory"><b><code>Nan::AdjustExternalMemory()</code></b></a>
### Miscellaneous V8 Helpers
- <a href="doc/v8_misc.md#api_nan_utf8_string"><b><code>Nan::Utf8String</code></b></a>
- <a href="doc/v8_misc.md#api_nan_get_current_context"><b><code>Nan::GetCurrentContext()</code></b></a>
- <a href="doc/v8_misc.md#api_nan_set_isolate_data"><b><code>Nan::SetIsolateData()</code></b></a>
- <a href="doc/v8_misc.md#api_nan_get_isolate_data"><b><code>Nan::GetIsolateData()</code></b></a>
- <a href="doc/v8_misc.md#api_nan_typedarray_contents"><b><code>Nan::TypedArrayContents</code></b></a>
### Miscellaneous Node Helpers
- <a href="doc/node_misc.md#api_nan_asyncresource"><b><code>Nan::AsyncResource</code></b></a>
- <a href="doc/node_misc.md#api_nan_make_callback"><b><code>Nan::MakeCallback()</code></b></a>
- <a href="doc/node_misc.md#api_nan_module_init"><b><code>NAN_MODULE_INIT()</code></b></a>
- <a href="doc/node_misc.md#api_nan_export"><b><code>Nan::Export()</code></b></a>
<!-- END API -->
<a name="tests"></a>
### Tests
To run the NAN tests do:
``` sh
npm install
npm run-script rebuild-tests
npm test
```
Or just:
``` sh
npm install
make test
```
<a name="issues"></a>
## Known issues
### Compiling against Node.js 0.12 on OSX
With new enough compilers available on OSX, the versions of V8 headers corresponding to Node.js 0.12
do not compile anymore. The error looks something like:
```
❯ CXX(target) Release/obj.target/accessors/cpp/accessors.o
In file included from ../cpp/accessors.cpp:9:
In file included from ../../nan.h:51:
In file included from /Users/ofrobots/.node-gyp/0.12.18/include/node/node.h:61:
/Users/ofrobots/.node-gyp/0.12.18/include/node/v8.h:5800:54: error: 'CreateHandle' is a protected member of 'v8::HandleScope'
return Handle<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(
~~~~~~~~~~~~~^~~~~~~~~~~~
```
This can be worked around by patching your local versions of v8.h corresponding to Node 0.12 to make
`v8::Handle` a friend of `v8::HandleScope`. Since neither Node.js not V8 support this release line anymore
this patch cannot be released by either project in an official release.
For this reason, we do not test against Node.js 0.12 on OSX in this project's CI. If you need to support
that configuration, you will need to either get an older compiler, or apply a source patch to the version
of V8 headers as a workaround.
<a name="governance"></a>
## Governance & Contributing
NAN is governed by the [Node.js Addon API Working Group](https://github.com/nodejs/CTC/blob/master/WORKING_GROUPS.md#addon-api)
### Addon API Working Group (WG)
The NAN project is jointly governed by a Working Group which is responsible for high-level guidance of the project.
Members of the WG are also known as Collaborators, there is no distinction between the two, unlike other Node.js projects.
The WG has final authority over this project including:
* Technical direction
* Project governance and process (including this policy)
* Contribution policy
* GitHub repository hosting
* Maintaining the list of additional Collaborators
For the current list of WG members, see the project [README.md](./README.md#collaborators).
Individuals making significant and valuable contributions are made members of the WG and given commit-access to the project. These individuals are identified by the WG and their addition to the WG is discussed via GitHub and requires unanimous consensus amongst those WG members participating in the discussion with a quorum of 50% of WG members required for acceptance of the vote.
_Note:_ If you make a significant contribution and are not considered for commit-access log an issue or contact a WG member directly.
For the current list of WG members / Collaborators, see the project [README.md](./README.md#collaborators).
### Consensus Seeking Process
The WG follows a [Consensus Seeking](https://en.wikipedia.org/wiki/Consensus-seeking_decision-making) decision making model.
Modifications of the contents of the NAN repository are made on a collaborative basis. Anybody with a GitHub account may propose a modification via pull request and it will be considered by the WG. All pull requests must be reviewed and accepted by a WG member with sufficient expertise who is able to take full responsibility for the change. In the case of pull requests proposed by an existing WG member, an additional WG member is required for sign-off. Consensus should be sought if additional WG members participate and there is disagreement around a particular modification.
If a change proposal cannot reach a consensus, a WG member can call for a vote amongst the members of the WG. Simple majority wins.
<a id="developers-certificate-of-origin"></a>
## Developer's Certificate of Origin 1.1
By making a contribution to this project, I certify that:
* (a) The contribution was created in whole or in part by me and I
have the right to submit it under the open source license
indicated in the file; or
* (b) The contribution is based upon previous work that, to the best
of my knowledge, is covered under an appropriate open source
license and I have the right under that license to submit that
work with modifications, whether created in whole or in part
by me, under the same open source license (unless I am
permitted to submit under a different license), as indicated
in the file; or
* (c) The contribution was provided directly to me by some other
person who certified (a), (b) or (c) and I have not modified
it.
* (d) I understand and agree that this project and the contribution
are public and that a record of the contribution (including all
personal information I submit with it, including my sign-off) is
maintained indefinitely and may be redistributed consistent with
this project or the open source license(s) involved.
<a name="collaborators"></a>
### WG Members / Collaborators
<table><tbody>
<tr><th align="left">Rod Vagg</th><td><a href="https://github.com/rvagg">GitHub/rvagg</a></td><td><a href="http://twitter.com/rvagg">Twitter/@rvagg</a></td></tr>
<tr><th align="left">Benjamin Byholm</th><td><a href="https://github.com/kkoopa/">GitHub/kkoopa</a></td><td>-</td></tr>
<tr><th align="left">Trevor Norris</th><td><a href="https://github.com/trevnorris">GitHub/trevnorris</a></td><td><a href="http://twitter.com/trevnorris">Twitter/@trevnorris</a></td></tr>
<tr><th align="left">Nathan Rajlich</th><td><a href="https://github.com/TooTallNate">GitHub/TooTallNate</a></td><td><a href="http://twitter.com/TooTallNate">Twitter/@TooTallNate</a></td></tr>
<tr><th align="left">Brett Lawson</th><td><a href="https://github.com/brett19">GitHub/brett19</a></td><td><a href="http://twitter.com/brett19x">Twitter/@brett19x</a></td></tr>
<tr><th align="left">Ben Noordhuis</th><td><a href="https://github.com/bnoordhuis">GitHub/bnoordhuis</a></td><td><a href="http://twitter.com/bnoordhuis">Twitter/@bnoordhuis</a></td></tr>
<tr><th align="left">David Siegel</th><td><a href="https://github.com/agnat">GitHub/agnat</a></td><td><a href="http://twitter.com/agnat">Twitter/@agnat</a></td></tr>
<tr><th align="left">Michael Ira Krufky</th><td><a href="https://github.com/mkrufky">GitHub/mkrufky</a></td><td><a href="http://twitter.com/mkrufky">Twitter/@mkrufky</a></td></tr>
</tbody></table>
## Licence &amp; copyright
Copyright (c) 2018 NAN WG Members / Collaborators (listed above).
Native Abstractions for Node.js is licensed under an MIT license. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE file for more details.
@@ -0,0 +1,22 @@
import createMathOperation from './_createMathOperation.js';
/**
* Subtract two numbers.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Math
* @param {number} minuend The first number in a subtraction.
* @param {number} subtrahend The second number in a subtraction.
* @returns {number} Returns the difference.
* @example
*
* _.subtract(6, 4);
* // => 2
*/
var subtract = createMathOperation(function(minuend, subtrahend) {
return minuend - subtrahend;
}, 0);
export default subtract;
@@ -0,0 +1,449 @@
'use strict'
let CssSyntaxError = require('./css-syntax-error')
let Stringifier = require('./stringifier')
let stringify = require('./stringify')
let { isClean, my } = require('./symbols')
function cloneNode(obj, parent) {
let cloned = new obj.constructor()
for (let i in obj) {
if (!Object.prototype.hasOwnProperty.call(obj, i)) {
/* c8 ignore next 2 */
continue
}
if (i === 'proxyCache') continue
let value = obj[i]
let type = typeof value
if (i === 'parent' && type === 'object') {
if (parent) cloned[i] = parent
} else if (i === 'source') {
cloned[i] = value
} else if (Array.isArray(value)) {
cloned[i] = value.map(j => cloneNode(j, cloned))
} else {
if (type === 'object' && value !== null) value = cloneNode(value)
cloned[i] = value
}
}
return cloned
}
function sourceOffset(inputCSS, position) {
// Not all custom syntaxes support `offset` in `source.start` and `source.end`
if (position && typeof position.offset !== 'undefined') {
return position.offset
}
let column = 1
let line = 1
let offset = 0
for (let i = 0; i < inputCSS.length; i++) {
if (line === position.line && column === position.column) {
offset = i
break
}
if (inputCSS[i] === '\n') {
column = 1
line += 1
} else {
column += 1
}
}
return offset
}
class Node {
get proxyOf() {
return this
}
constructor(defaults = {}) {
this.raws = {}
this[isClean] = false
this[my] = true
for (let name in defaults) {
if (name === 'nodes') {
this.nodes = []
for (let node of defaults[name]) {
if (typeof node.clone === 'function') {
this.append(node.clone())
} else {
this.append(node)
}
}
} else {
this[name] = defaults[name]
}
}
}
addToError(error) {
error.postcssNode = this
if (error.stack && this.source && /\n\s{4}at /.test(error.stack)) {
let s = this.source
error.stack = error.stack.replace(
/\n\s{4}at /,
`$&${s.input.from}:${s.start.line}:${s.start.column}$&`
)
}
return error
}
after(add) {
this.parent.insertAfter(this, add)
return this
}
assign(overrides = {}) {
for (let name in overrides) {
this[name] = overrides[name]
}
return this
}
before(add) {
this.parent.insertBefore(this, add)
return this
}
cleanRaws(keepBetween) {
delete this.raws.before
delete this.raws.after
if (!keepBetween) delete this.raws.between
}
clone(overrides = {}) {
let cloned = cloneNode(this)
for (let name in overrides) {
cloned[name] = overrides[name]
}
return cloned
}
cloneAfter(overrides = {}) {
let cloned = this.clone(overrides)
this.parent.insertAfter(this, cloned)
return cloned
}
cloneBefore(overrides = {}) {
let cloned = this.clone(overrides)
this.parent.insertBefore(this, cloned)
return cloned
}
error(message, opts = {}) {
if (this.source) {
let { end, start } = this.rangeBy(opts)
return this.source.input.error(
message,
{ column: start.column, line: start.line },
{ column: end.column, line: end.line },
opts
)
}
return new CssSyntaxError(message)
}
getProxyProcessor() {
return {
get(node, prop) {
if (prop === 'proxyOf') {
return node
} else if (prop === 'root') {
return () => node.root().toProxy()
} else {
return node[prop]
}
},
set(node, prop, value) {
if (node[prop] === value) return true
node[prop] = value
if (
prop === 'prop' ||
prop === 'value' ||
prop === 'name' ||
prop === 'params' ||
prop === 'important' ||
/* c8 ignore next */
prop === 'text'
) {
node.markDirty()
}
return true
}
}
}
/* c8 ignore next 3 */
markClean() {
this[isClean] = true
}
markDirty() {
if (this[isClean]) {
this[isClean] = false
let next = this
while ((next = next.parent)) {
next[isClean] = false
}
}
}
next() {
if (!this.parent) return undefined
let index = this.parent.index(this)
return this.parent.nodes[index + 1]
}
positionBy(opts = {}) {
let pos = this.source.start
if (opts.index) {
pos = this.positionInside(opts.index)
} else if (opts.word) {
let inputString =
'document' in this.source.input
? this.source.input.document
: this.source.input.css
let stringRepresentation = inputString.slice(
sourceOffset(inputString, this.source.start),
sourceOffset(inputString, this.source.end)
)
let index = stringRepresentation.indexOf(opts.word)
if (index !== -1) pos = this.positionInside(index)
}
return pos
}
positionInside(index) {
let column = this.source.start.column
let line = this.source.start.line
let inputString =
'document' in this.source.input
? this.source.input.document
: this.source.input.css
let offset = sourceOffset(inputString, this.source.start)
let end = offset + index
for (let i = offset; i < end; i++) {
if (inputString[i] === '\n') {
column = 1
line += 1
} else {
column += 1
}
}
return { column, line, offset: end }
}
prev() {
if (!this.parent) return undefined
let index = this.parent.index(this)
return this.parent.nodes[index - 1]
}
rangeBy(opts = {}) {
let inputString =
'document' in this.source.input
? this.source.input.document
: this.source.input.css
let start = {
column: this.source.start.column,
line: this.source.start.line,
offset: sourceOffset(inputString, this.source.start)
}
let end = this.source.end
? {
column: this.source.end.column + 1,
line: this.source.end.line,
offset:
typeof this.source.end.offset === 'number'
? // `source.end.offset` is exclusive, so we don't need to add 1
this.source.end.offset
: // Since line/column in this.source.end is inclusive,
// the `sourceOffset(... , this.source.end)` returns an inclusive offset.
// So, we add 1 to convert it to exclusive.
sourceOffset(inputString, this.source.end) + 1
}
: {
column: start.column + 1,
line: start.line,
offset: start.offset + 1
}
if (opts.word) {
let stringRepresentation = inputString.slice(
sourceOffset(inputString, this.source.start),
sourceOffset(inputString, this.source.end)
)
let index = stringRepresentation.indexOf(opts.word)
if (index !== -1) {
start = this.positionInside(index)
end = this.positionInside(index + opts.word.length)
}
} else {
if (opts.start) {
start = {
column: opts.start.column,
line: opts.start.line,
offset: sourceOffset(inputString, opts.start)
}
} else if (opts.index) {
start = this.positionInside(opts.index)
}
if (opts.end) {
end = {
column: opts.end.column,
line: opts.end.line,
offset: sourceOffset(inputString, opts.end)
}
} else if (typeof opts.endIndex === 'number') {
end = this.positionInside(opts.endIndex)
} else if (opts.index) {
end = this.positionInside(opts.index + 1)
}
}
if (
end.line < start.line ||
(end.line === start.line && end.column <= start.column)
) {
end = {
column: start.column + 1,
line: start.line,
offset: start.offset + 1
}
}
return { end, start }
}
raw(prop, defaultType) {
let str = new Stringifier()
return str.raw(this, prop, defaultType)
}
remove() {
if (this.parent) {
this.parent.removeChild(this)
}
this.parent = undefined
return this
}
replaceWith(...nodes) {
if (this.parent) {
let bookmark = this
let foundSelf = false
for (let node of nodes) {
if (node === this) {
foundSelf = true
} else if (foundSelf) {
this.parent.insertAfter(bookmark, node)
bookmark = node
} else {
this.parent.insertBefore(bookmark, node)
}
}
if (!foundSelf) {
this.remove()
}
}
return this
}
root() {
let result = this
while (result.parent && result.parent.type !== 'document') {
result = result.parent
}
return result
}
toJSON(_, inputs) {
let fixed = {}
let emitInputs = inputs == null
inputs = inputs || new Map()
let inputsNextIndex = 0
for (let name in this) {
if (!Object.prototype.hasOwnProperty.call(this, name)) {
/* c8 ignore next 2 */
continue
}
if (name === 'parent' || name === 'proxyCache') continue
let value = this[name]
if (Array.isArray(value)) {
fixed[name] = value.map(i => {
if (typeof i === 'object' && i.toJSON) {
return i.toJSON(null, inputs)
} else {
return i
}
})
} else if (typeof value === 'object' && value.toJSON) {
fixed[name] = value.toJSON(null, inputs)
} else if (name === 'source') {
if (value == null) continue
let inputId = inputs.get(value.input)
if (inputId == null) {
inputId = inputsNextIndex
inputs.set(value.input, inputsNextIndex)
inputsNextIndex++
}
fixed[name] = {
end: value.end,
inputId,
start: value.start
}
} else {
fixed[name] = value
}
}
if (emitInputs) {
fixed.inputs = [...inputs.keys()].map(input => input.toJSON())
}
return fixed
}
toProxy() {
if (!this.proxyCache) {
this.proxyCache = new Proxy(this, this.getProxyProcessor())
}
return this.proxyCache
}
toString(stringifier = stringify) {
if (stringifier.stringify) stringifier = stringifier.stringify
let result = ''
stringifier(this, i => {
result += i
})
return result
}
warn(result, text, opts = {}) {
let data = { node: this }
for (let i in opts) data[i] = opts[i]
return result.warn(text, data)
}
}
module.exports = Node
Node.default = Node
@@ -0,0 +1,188 @@
import { MILLISECONDS_A_MINUTE, MIN } from '../../constant';
var REGEX_VALID_OFFSET_FORMAT = /[+-]\d\d(?::?\d\d)?/g;
var REGEX_OFFSET_HOURS_MINUTES_FORMAT = /([+-]|\d\d)/g;
function offsetFromString(value) {
if (value === void 0) {
value = '';
}
var offset = value.match(REGEX_VALID_OFFSET_FORMAT);
if (!offset) {
return null;
}
var _ref = ("" + offset[0]).match(REGEX_OFFSET_HOURS_MINUTES_FORMAT) || ['-', 0, 0],
indicator = _ref[0],
hoursOffset = _ref[1],
minutesOffset = _ref[2];
var totalOffsetInMinutes = +hoursOffset * 60 + +minutesOffset;
if (totalOffsetInMinutes === 0) {
return 0;
}
return indicator === '+' ? totalOffsetInMinutes : -totalOffsetInMinutes;
}
export default (function (option, Dayjs, dayjs) {
var proto = Dayjs.prototype;
dayjs.utc = function (date) {
var cfg = {
date: date,
utc: true,
args: arguments
}; // eslint-disable-line prefer-rest-params
return new Dayjs(cfg); // eslint-disable-line no-use-before-define
};
proto.utc = function (keepLocalTime) {
var ins = dayjs(this.toDate(), {
locale: this.$L,
utc: true
});
if (keepLocalTime) {
return ins.add(this.utcOffset(), MIN);
}
return ins;
};
proto.local = function () {
return dayjs(this.toDate(), {
locale: this.$L,
utc: false
});
};
var oldParse = proto.parse;
proto.parse = function (cfg) {
if (cfg.utc) {
this.$u = true;
}
if (!this.$utils().u(cfg.$offset)) {
this.$offset = cfg.$offset;
}
oldParse.call(this, cfg);
};
var oldInit = proto.init;
proto.init = function () {
if (this.$u) {
var $d = this.$d;
this.$y = $d.getUTCFullYear();
this.$M = $d.getUTCMonth();
this.$D = $d.getUTCDate();
this.$W = $d.getUTCDay();
this.$H = $d.getUTCHours();
this.$m = $d.getUTCMinutes();
this.$s = $d.getUTCSeconds();
this.$ms = $d.getUTCMilliseconds();
} else {
oldInit.call(this);
}
};
var oldUtcOffset = proto.utcOffset;
proto.utcOffset = function (input, keepLocalTime) {
var _this$$utils = this.$utils(),
u = _this$$utils.u;
if (u(input)) {
if (this.$u) {
return 0;
}
if (!u(this.$offset)) {
return this.$offset;
}
return oldUtcOffset.call(this);
}
if (typeof input === 'string') {
input = offsetFromString(input);
if (input === null) {
return this;
}
}
var offset = Math.abs(input) <= 16 ? input * 60 : input;
if (offset === 0) {
return this.utc(keepLocalTime);
}
var ins = this.clone();
if (keepLocalTime) {
ins.$offset = offset;
ins.$u = false;
return ins;
}
var localTimezoneOffset = this.$u ? this.toDate().getTimezoneOffset() : -1 * this.utcOffset();
ins = this.local().add(offset + localTimezoneOffset, MIN);
ins.$offset = offset;
ins.$x.$localOffset = localTimezoneOffset;
return ins;
};
var oldFormat = proto.format;
var UTC_FORMAT_DEFAULT = 'YYYY-MM-DDTHH:mm:ss[Z]';
proto.format = function (formatStr) {
var str = formatStr || (this.$u ? UTC_FORMAT_DEFAULT : '');
return oldFormat.call(this, str);
};
proto.valueOf = function () {
var addedOffset = !this.$utils().u(this.$offset) ? this.$offset + (this.$x.$localOffset || this.$d.getTimezoneOffset()) : 0;
return this.$d.valueOf() - addedOffset * MILLISECONDS_A_MINUTE;
};
proto.isUTC = function () {
return !!this.$u;
};
proto.toISOString = function () {
return this.toDate().toISOString();
};
proto.toString = function () {
return this.toDate().toUTCString();
};
var oldToDate = proto.toDate;
proto.toDate = function (type) {
if (type === 's' && this.$offset) {
return dayjs(this.format('YYYY-MM-DD HH:mm:ss:SSS')).toDate();
}
return oldToDate.call(this);
};
var oldDiff = proto.diff;
proto.diff = function (input, units, _float) {
if (input && this.$u === input.$u) {
return oldDiff.call(this, input, units, _float);
}
var localThis = this.local();
var localInput = dayjs(input).local();
return oldDiff.call(localThis, localInput, units, _float);
};
});
@@ -0,0 +1,4 @@
import type { Primitive } from '../types';
declare const _default: (value: unknown) => value is Primitive;
export default _default;
//# sourceMappingURL=isPrimitive.d.ts.map
@@ -0,0 +1,3 @@
// Note: extra types exposed from `index.d.ts`.
export {toMarkdown} from './lib/index.js'
export {handle as defaultHandlers} from './lib/handle/index.js'
@@ -0,0 +1,16 @@
/*
* Copyright 2020 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
export {useTooltipTriggerState} from './useTooltipTriggerState';
export type {TooltipTriggerProps} from '@react-types/tooltip';
export type {TooltipTriggerState} from './useTooltipTriggerState';
@@ -0,0 +1 @@
{"name":"decamelize-keys","version":"1.1.1","requiresBuild":false,"files":{"license":{"checkedAt":1794532119267,"integrity":"sha512-RWMXsur4OZ+YK2KufbwUvbmVwfoKDKUS4GceZ7tXAsbyixZdbEIY1jRdH/xxB6ecSDxpo29kfftEydWcxy22Kg==","mode":420,"size":1158},"index.js":{"checkedAt":1794532119267,"integrity":"sha512-OsXI7IFCpvVrIe0jMJPOAkqIH2X5DYPihlZepbvr1DkL8ONwwpcxJuBL2rNltTI3pR18mc9hJkkeQwWz+SbN0g==","mode":420,"size":484},"package.json":{"checkedAt":1794532119268,"integrity":"sha512-fZU5Ycq/FFoTvPDjKwBE7Z3MAroho4ONDjT3S3YZhl6TrvgqZwAC9GeDVMLMmpR9Pc2T7lxGWFaKn494gTvP1Q==","mode":420,"size":1157},"readme.md":{"checkedAt":1794532119268,"integrity":"sha512-govR2/JkMH7jOLTYlAJA9Dc58qyTZzjf8KQirVKW8tGlHeuh8Hm8SStODHg//0SeiniFtJZfOs8ZJGreNVbk7w==","mode":420,"size":1235}}}
@@ -0,0 +1,17 @@
var $f8f1e72c8b5447d6$exports = {};
$f8f1e72c8b5447d6$exports = {
"deselectedItem": (args)=>`${args.item} nicht ausgew\xe4hlt.`,
"longPressToSelect": `Gedr\xfcckt halten, um Auswahlmodus zu \xf6ffnen.`,
"select": `Ausw\xe4hlen`,
"selectedAll": `Alle Elemente ausgew\xe4hlt.`,
"selectedCount": (args, formatter)=>`${formatter.plural(args.count, {
"=0": `Keine Elemente ausgew\xe4hlt`,
one: ()=>`${formatter.number(args.count)} Element ausgew\xe4hlt`,
other: ()=>`${formatter.number(args.count)} Elemente ausgew\xe4hlt`
})}.`,
"selectedItem": (args)=>`${args.item} ausgew\xe4hlt.`
};
export {$f8f1e72c8b5447d6$exports as default};
//# sourceMappingURL=de-DE.module.js.map
@@ -0,0 +1,52 @@
'use strict';
/* eslint global-require: 0 */
// https://es5.github.io/#x9
module.exports = {
'Abstract Equality Comparison': require('./5/AbstractEqualityComparison'),
'Abstract Relational Comparison': require('./5/AbstractRelationalComparison'),
'Strict Equality Comparison': require('./5/StrictEqualityComparison'),
abs: require('./5/abs'),
Canonicalize: require('./5/Canonicalize'),
CheckObjectCoercible: require('./5/CheckObjectCoercible'),
DateFromTime: require('./5/DateFromTime'),
Day: require('./5/Day'),
DayFromYear: require('./5/DayFromYear'),
DaysInYear: require('./5/DaysInYear'),
DayWithinYear: require('./5/DayWithinYear'),
floor: require('./5/floor'),
FromPropertyDescriptor: require('./5/FromPropertyDescriptor'),
HourFromTime: require('./5/HourFromTime'),
InLeapYear: require('./5/InLeapYear'),
IsAccessorDescriptor: require('./5/IsAccessorDescriptor'),
IsCallable: require('./5/IsCallable'),
IsDataDescriptor: require('./5/IsDataDescriptor'),
IsGenericDescriptor: require('./5/IsGenericDescriptor'),
IsPropertyDescriptor: require('./5/IsPropertyDescriptor'),
MakeDate: require('./5/MakeDate'),
MakeDay: require('./5/MakeDay'),
MakeTime: require('./5/MakeTime'),
MinFromTime: require('./5/MinFromTime'),
modulo: require('./5/modulo'),
MonthFromTime: require('./5/MonthFromTime'),
msFromTime: require('./5/msFromTime'),
SameValue: require('./5/SameValue'),
SecFromTime: require('./5/SecFromTime'),
TimeClip: require('./5/TimeClip'),
TimeFromYear: require('./5/TimeFromYear'),
TimeWithinDay: require('./5/TimeWithinDay'),
ToBoolean: require('./5/ToBoolean'),
ToInt32: require('./5/ToInt32'),
ToInteger: require('./5/ToInteger'),
ToNumber: require('./5/ToNumber'),
ToObject: require('./5/ToObject'),
ToPrimitive: require('./5/ToPrimitive'),
ToPropertyDescriptor: require('./5/ToPropertyDescriptor'),
ToString: require('./5/ToString'),
ToUint16: require('./5/ToUint16'),
ToUint32: require('./5/ToUint32'),
Type: require('./5/Type'),
WeekDay: require('./5/WeekDay'),
YearFromTime: require('./5/YearFromTime')
};
@@ -0,0 +1,10 @@
import { GeneralName } from "./general_name";
import { AsnArray } from "@peculiar/asn1-schema";
/**
* ```asn1
* GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
* ```
*/
export declare class GeneralNames extends AsnArray<GeneralName> {
constructor(items?: GeneralName[]);
}
@@ -0,0 +1,20 @@
'use strict';
var define = require('define-properties');
var shimUnscopables = require('es-shim-unscopables');
var getPolyfill = require('./polyfill');
module.exports = function shimFlat() {
var polyfill = getPolyfill();
define(
Array.prototype,
{ flat: polyfill },
{ flat: function () { return Array.prototype.flat !== polyfill; } }
);
shimUnscopables('flat');
return polyfill;
};
@@ -0,0 +1,31 @@
"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const baseLogFactory = require("base-log-factory");
const pc = require("picocolors");
const colors = require("./colors.js");
class ColorfulAppender extends baseLogFactory.ConsoleAppender {
/**
* Constructor (构造函数)
*/
constructor(opts = {}) {
super(opts.layout);
this.name = "colorful";
this.colors = opts.colors || colors.colors;
}
/**
* Write log (写入日志)
* @param event Log event (日志事件)
*/
write(event) {
const { layout } = this;
if (layout) {
console.log(this.color(layout.format(event), event));
} else {
console.log(this.color(baseLogFactory.basicLogPrefix(event, this.dateFormat), event), ...event.message);
}
}
color(str, event) {
return pc[this.colors[event.level]](str);
}
}
exports.ColorfulAppender = ColorfulAppender;
@@ -0,0 +1,809 @@
/*!
Copyright 2013 Lovell Fuller and others.
SPDX-License-Identifier: Apache-2.0
*/
const is = require('./is');
const sharp = require('./sharp');
/**
* Justification alignment
* @member
* @private
*/
const align = {
left: 'low',
top: 'low',
low: 'low',
center: 'centre',
centre: 'centre',
right: 'high',
bottom: 'high',
high: 'high'
};
const inputStreamParameters = [
// Limits and error handling
'failOn', 'limitInputPixels', 'unlimited',
// Format-generic
'animated', 'autoOrient', 'density', 'ignoreIcc', 'page', 'pages', 'sequentialRead',
// Format-specific
'jp2', 'openSlide', 'pdf', 'raw', 'svg', 'tiff',
// Deprecated
'failOnError', 'openSlideLevel', 'pdfBackground', 'tiffSubifd'
];
/**
* Extract input options, if any, from an object.
* @private
*/
function _inputOptionsFromObject (obj) {
const params = inputStreamParameters
.filter(p => is.defined(obj[p]))
.map(p => ([p, obj[p]]));
return params.length
? Object.fromEntries(params)
: undefined;
}
/**
* Create Object containing input and input-related options.
* @private
*/
function _createInputDescriptor (input, inputOptions, containerOptions) {
const inputDescriptor = {
autoOrient: false,
failOn: 'warning',
limitInputPixels: 0x3FFF ** 2,
ignoreIcc: false,
unlimited: false,
sequentialRead: true
};
if (is.string(input)) {
// filesystem
inputDescriptor.file = input;
} else if (is.buffer(input)) {
// Buffer
if (input.length === 0) {
throw Error('Input Buffer is empty');
}
inputDescriptor.buffer = input;
} else if (is.arrayBuffer(input)) {
if (input.byteLength === 0) {
throw Error('Input bit Array is empty');
}
inputDescriptor.buffer = Buffer.from(input, 0, input.byteLength);
} else if (is.typedArray(input)) {
if (input.length === 0) {
throw Error('Input Bit Array is empty');
}
inputDescriptor.buffer = Buffer.from(input.buffer, input.byteOffset, input.byteLength);
} else if (is.plainObject(input) && !is.defined(inputOptions)) {
// Plain Object descriptor, e.g. create
inputOptions = input;
if (_inputOptionsFromObject(inputOptions)) {
// Stream with options
inputDescriptor.buffer = [];
}
} else if (!is.defined(input) && !is.defined(inputOptions) && is.object(containerOptions) && containerOptions.allowStream) {
// Stream without options
inputDescriptor.buffer = [];
} else if (Array.isArray(input)) {
if (input.length > 1) {
// Join images together
if (!this.options.joining) {
this.options.joining = true;
this.options.join = input.map(i => this._createInputDescriptor(i));
} else {
throw new Error('Recursive join is unsupported');
}
} else {
throw new Error('Expected at least two images to join');
}
} else {
throw new Error(`Unsupported input '${input}' of type ${typeof input}${
is.defined(inputOptions) ? ` when also providing options of type ${typeof inputOptions}` : ''
}`);
}
if (is.object(inputOptions)) {
// Deprecated: failOnError
if (is.defined(inputOptions.failOnError)) {
if (is.bool(inputOptions.failOnError)) {
inputDescriptor.failOn = inputOptions.failOnError ? 'warning' : 'none';
} else {
throw is.invalidParameterError('failOnError', 'boolean', inputOptions.failOnError);
}
}
// failOn
if (is.defined(inputOptions.failOn)) {
if (is.string(inputOptions.failOn) && is.inArray(inputOptions.failOn, ['none', 'truncated', 'error', 'warning'])) {
inputDescriptor.failOn = inputOptions.failOn;
} else {
throw is.invalidParameterError('failOn', 'one of: none, truncated, error, warning', inputOptions.failOn);
}
}
// autoOrient
if (is.defined(inputOptions.autoOrient)) {
if (is.bool(inputOptions.autoOrient)) {
inputDescriptor.autoOrient = inputOptions.autoOrient;
} else {
throw is.invalidParameterError('autoOrient', 'boolean', inputOptions.autoOrient);
}
}
// Density
if (is.defined(inputOptions.density)) {
if (is.inRange(inputOptions.density, 1, 100000)) {
inputDescriptor.density = inputOptions.density;
} else {
throw is.invalidParameterError('density', 'number between 1 and 100000', inputOptions.density);
}
}
// Ignore embeddded ICC profile
if (is.defined(inputOptions.ignoreIcc)) {
if (is.bool(inputOptions.ignoreIcc)) {
inputDescriptor.ignoreIcc = inputOptions.ignoreIcc;
} else {
throw is.invalidParameterError('ignoreIcc', 'boolean', inputOptions.ignoreIcc);
}
}
// limitInputPixels
if (is.defined(inputOptions.limitInputPixels)) {
if (is.bool(inputOptions.limitInputPixels)) {
inputDescriptor.limitInputPixels = inputOptions.limitInputPixels
? 0x3FFF ** 2
: 0;
} else if (is.integer(inputOptions.limitInputPixels) && is.inRange(inputOptions.limitInputPixels, 0, Number.MAX_SAFE_INTEGER)) {
inputDescriptor.limitInputPixels = inputOptions.limitInputPixels;
} else {
throw is.invalidParameterError('limitInputPixels', 'positive integer', inputOptions.limitInputPixels);
}
}
// unlimited
if (is.defined(inputOptions.unlimited)) {
if (is.bool(inputOptions.unlimited)) {
inputDescriptor.unlimited = inputOptions.unlimited;
} else {
throw is.invalidParameterError('unlimited', 'boolean', inputOptions.unlimited);
}
}
// sequentialRead
if (is.defined(inputOptions.sequentialRead)) {
if (is.bool(inputOptions.sequentialRead)) {
inputDescriptor.sequentialRead = inputOptions.sequentialRead;
} else {
throw is.invalidParameterError('sequentialRead', 'boolean', inputOptions.sequentialRead);
}
}
// Raw pixel input
if (is.defined(inputOptions.raw)) {
if (
is.object(inputOptions.raw) &&
is.integer(inputOptions.raw.width) && inputOptions.raw.width > 0 &&
is.integer(inputOptions.raw.height) && inputOptions.raw.height > 0 &&
is.integer(inputOptions.raw.channels) && is.inRange(inputOptions.raw.channels, 1, 4)
) {
inputDescriptor.rawWidth = inputOptions.raw.width;
inputDescriptor.rawHeight = inputOptions.raw.height;
inputDescriptor.rawChannels = inputOptions.raw.channels;
switch (input.constructor) {
case Uint8Array:
case Uint8ClampedArray:
inputDescriptor.rawDepth = 'uchar';
break;
case Int8Array:
inputDescriptor.rawDepth = 'char';
break;
case Uint16Array:
inputDescriptor.rawDepth = 'ushort';
break;
case Int16Array:
inputDescriptor.rawDepth = 'short';
break;
case Uint32Array:
inputDescriptor.rawDepth = 'uint';
break;
case Int32Array:
inputDescriptor.rawDepth = 'int';
break;
case Float32Array:
inputDescriptor.rawDepth = 'float';
break;
case Float64Array:
inputDescriptor.rawDepth = 'double';
break;
default:
inputDescriptor.rawDepth = 'uchar';
break;
}
} else {
throw new Error('Expected width, height and channels for raw pixel input');
}
inputDescriptor.rawPremultiplied = false;
if (is.defined(inputOptions.raw.premultiplied)) {
if (is.bool(inputOptions.raw.premultiplied)) {
inputDescriptor.rawPremultiplied = inputOptions.raw.premultiplied;
} else {
throw is.invalidParameterError('raw.premultiplied', 'boolean', inputOptions.raw.premultiplied);
}
}
inputDescriptor.rawPageHeight = 0;
if (is.defined(inputOptions.raw.pageHeight)) {
if (is.integer(inputOptions.raw.pageHeight) && inputOptions.raw.pageHeight > 0 && inputOptions.raw.pageHeight <= inputOptions.raw.height) {
if (inputOptions.raw.height % inputOptions.raw.pageHeight !== 0) {
throw new Error(`Expected raw.height ${inputOptions.raw.height} to be a multiple of raw.pageHeight ${inputOptions.raw.pageHeight}`);
}
inputDescriptor.rawPageHeight = inputOptions.raw.pageHeight;
} else {
throw is.invalidParameterError('raw.pageHeight', 'positive integer', inputOptions.raw.pageHeight);
}
}
}
// Multi-page input (GIF, TIFF, PDF)
if (is.defined(inputOptions.animated)) {
if (is.bool(inputOptions.animated)) {
inputDescriptor.pages = inputOptions.animated ? -1 : 1;
} else {
throw is.invalidParameterError('animated', 'boolean', inputOptions.animated);
}
}
if (is.defined(inputOptions.pages)) {
if (is.integer(inputOptions.pages) && is.inRange(inputOptions.pages, -1, 100000)) {
inputDescriptor.pages = inputOptions.pages;
} else {
throw is.invalidParameterError('pages', 'integer between -1 and 100000', inputOptions.pages);
}
}
if (is.defined(inputOptions.page)) {
if (is.integer(inputOptions.page) && is.inRange(inputOptions.page, 0, 100000)) {
inputDescriptor.page = inputOptions.page;
} else {
throw is.invalidParameterError('page', 'integer between 0 and 100000', inputOptions.page);
}
}
// OpenSlide specific options
if (is.object(inputOptions.openSlide) && is.defined(inputOptions.openSlide.level)) {
if (is.integer(inputOptions.openSlide.level) && is.inRange(inputOptions.openSlide.level, 0, 256)) {
inputDescriptor.openSlideLevel = inputOptions.openSlide.level;
} else {
throw is.invalidParameterError('openSlide.level', 'integer between 0 and 256', inputOptions.openSlide.level);
}
} else if (is.defined(inputOptions.level)) {
// Deprecated
if (is.integer(inputOptions.level) && is.inRange(inputOptions.level, 0, 256)) {
inputDescriptor.openSlideLevel = inputOptions.level;
} else {
throw is.invalidParameterError('level', 'integer between 0 and 256', inputOptions.level);
}
}
// TIFF specific options
if (is.object(inputOptions.tiff) && is.defined(inputOptions.tiff.subifd)) {
if (is.integer(inputOptions.tiff.subifd) && is.inRange(inputOptions.tiff.subifd, -1, 100000)) {
inputDescriptor.tiffSubifd = inputOptions.tiff.subifd;
} else {
throw is.invalidParameterError('tiff.subifd', 'integer between -1 and 100000', inputOptions.tiff.subifd);
}
} else if (is.defined(inputOptions.subifd)) {
// Deprecated
if (is.integer(inputOptions.subifd) && is.inRange(inputOptions.subifd, -1, 100000)) {
inputDescriptor.tiffSubifd = inputOptions.subifd;
} else {
throw is.invalidParameterError('subifd', 'integer between -1 and 100000', inputOptions.subifd);
}
}
// SVG specific options
if (is.object(inputOptions.svg)) {
if (is.defined(inputOptions.svg.stylesheet)) {
if (is.string(inputOptions.svg.stylesheet)) {
inputDescriptor.svgStylesheet = inputOptions.svg.stylesheet;
} else {
throw is.invalidParameterError('svg.stylesheet', 'string', inputOptions.svg.stylesheet);
}
}
if (is.defined(inputOptions.svg.highBitdepth)) {
if (is.bool(inputOptions.svg.highBitdepth)) {
inputDescriptor.svgHighBitdepth = inputOptions.svg.highBitdepth;
} else {
throw is.invalidParameterError('svg.highBitdepth', 'boolean', inputOptions.svg.highBitdepth);
}
}
}
// PDF specific options
if (is.object(inputOptions.pdf) && is.defined(inputOptions.pdf.background)) {
inputDescriptor.pdfBackground = this._getBackgroundColourOption(inputOptions.pdf.background);
} else if (is.defined(inputOptions.pdfBackground)) {
// Deprecated
inputDescriptor.pdfBackground = this._getBackgroundColourOption(inputOptions.pdfBackground);
}
// JPEG 2000 specific options
if (is.object(inputOptions.jp2) && is.defined(inputOptions.jp2.oneshot)) {
if (is.bool(inputOptions.jp2.oneshot)) {
inputDescriptor.jp2Oneshot = inputOptions.jp2.oneshot;
} else {
throw is.invalidParameterError('jp2.oneshot', 'boolean', inputOptions.jp2.oneshot);
}
}
// Create new image
if (is.defined(inputOptions.create)) {
if (
is.object(inputOptions.create) &&
is.integer(inputOptions.create.width) && inputOptions.create.width > 0 &&
is.integer(inputOptions.create.height) && inputOptions.create.height > 0 &&
is.integer(inputOptions.create.channels)
) {
inputDescriptor.createWidth = inputOptions.create.width;
inputDescriptor.createHeight = inputOptions.create.height;
inputDescriptor.createChannels = inputOptions.create.channels;
inputDescriptor.createPageHeight = 0;
if (is.defined(inputOptions.create.pageHeight)) {
if (is.integer(inputOptions.create.pageHeight) && inputOptions.create.pageHeight > 0 && inputOptions.create.pageHeight <= inputOptions.create.height) {
if (inputOptions.create.height % inputOptions.create.pageHeight !== 0) {
throw new Error(`Expected create.height ${inputOptions.create.height} to be a multiple of create.pageHeight ${inputOptions.create.pageHeight}`);
}
inputDescriptor.createPageHeight = inputOptions.create.pageHeight;
} else {
throw is.invalidParameterError('create.pageHeight', 'positive integer', inputOptions.create.pageHeight);
}
}
// Noise
if (is.defined(inputOptions.create.noise)) {
if (!is.object(inputOptions.create.noise)) {
throw new Error('Expected noise to be an object');
}
if (inputOptions.create.noise.type !== 'gaussian') {
throw new Error('Only gaussian noise is supported at the moment');
}
inputDescriptor.createNoiseType = inputOptions.create.noise.type;
if (!is.inRange(inputOptions.create.channels, 1, 4)) {
throw is.invalidParameterError('create.channels', 'number between 1 and 4', inputOptions.create.channels);
}
inputDescriptor.createNoiseMean = 128;
if (is.defined(inputOptions.create.noise.mean)) {
if (is.number(inputOptions.create.noise.mean) && is.inRange(inputOptions.create.noise.mean, 0, 10000)) {
inputDescriptor.createNoiseMean = inputOptions.create.noise.mean;
} else {
throw is.invalidParameterError('create.noise.mean', 'number between 0 and 10000', inputOptions.create.noise.mean);
}
}
inputDescriptor.createNoiseSigma = 30;
if (is.defined(inputOptions.create.noise.sigma)) {
if (is.number(inputOptions.create.noise.sigma) && is.inRange(inputOptions.create.noise.sigma, 0, 10000)) {
inputDescriptor.createNoiseSigma = inputOptions.create.noise.sigma;
} else {
throw is.invalidParameterError('create.noise.sigma', 'number between 0 and 10000', inputOptions.create.noise.sigma);
}
}
} else if (is.defined(inputOptions.create.background)) {
if (!is.inRange(inputOptions.create.channels, 3, 4)) {
throw is.invalidParameterError('create.channels', 'number between 3 and 4', inputOptions.create.channels);
}
inputDescriptor.createBackground = this._getBackgroundColourOption(inputOptions.create.background);
} else {
throw new Error('Expected valid noise or background to create a new input image');
}
delete inputDescriptor.buffer;
} else {
throw new Error('Expected valid width, height and channels to create a new input image');
}
}
// Create a new image with text
if (is.defined(inputOptions.text)) {
if (is.object(inputOptions.text) && is.string(inputOptions.text.text)) {
inputDescriptor.textValue = inputOptions.text.text;
if (is.defined(inputOptions.text.height) && is.defined(inputOptions.text.dpi)) {
throw new Error('Expected only one of dpi or height');
}
if (is.defined(inputOptions.text.font)) {
if (is.string(inputOptions.text.font)) {
inputDescriptor.textFont = inputOptions.text.font;
} else {
throw is.invalidParameterError('text.font', 'string', inputOptions.text.font);
}
}
if (is.defined(inputOptions.text.fontfile)) {
if (is.string(inputOptions.text.fontfile)) {
inputDescriptor.textFontfile = inputOptions.text.fontfile;
} else {
throw is.invalidParameterError('text.fontfile', 'string', inputOptions.text.fontfile);
}
}
if (is.defined(inputOptions.text.width)) {
if (is.integer(inputOptions.text.width) && inputOptions.text.width > 0) {
inputDescriptor.textWidth = inputOptions.text.width;
} else {
throw is.invalidParameterError('text.width', 'positive integer', inputOptions.text.width);
}
}
if (is.defined(inputOptions.text.height)) {
if (is.integer(inputOptions.text.height) && inputOptions.text.height > 0) {
inputDescriptor.textHeight = inputOptions.text.height;
} else {
throw is.invalidParameterError('text.height', 'positive integer', inputOptions.text.height);
}
}
if (is.defined(inputOptions.text.align)) {
if (is.string(inputOptions.text.align) && is.string(this.constructor.align[inputOptions.text.align])) {
inputDescriptor.textAlign = this.constructor.align[inputOptions.text.align];
} else {
throw is.invalidParameterError('text.align', 'valid alignment', inputOptions.text.align);
}
}
if (is.defined(inputOptions.text.justify)) {
if (is.bool(inputOptions.text.justify)) {
inputDescriptor.textJustify = inputOptions.text.justify;
} else {
throw is.invalidParameterError('text.justify', 'boolean', inputOptions.text.justify);
}
}
if (is.defined(inputOptions.text.dpi)) {
if (is.integer(inputOptions.text.dpi) && is.inRange(inputOptions.text.dpi, 1, 1000000)) {
inputDescriptor.textDpi = inputOptions.text.dpi;
} else {
throw is.invalidParameterError('text.dpi', 'integer between 1 and 1000000', inputOptions.text.dpi);
}
}
if (is.defined(inputOptions.text.rgba)) {
if (is.bool(inputOptions.text.rgba)) {
inputDescriptor.textRgba = inputOptions.text.rgba;
} else {
throw is.invalidParameterError('text.rgba', 'bool', inputOptions.text.rgba);
}
}
if (is.defined(inputOptions.text.spacing)) {
if (is.integer(inputOptions.text.spacing) && is.inRange(inputOptions.text.spacing, -1000000, 1000000)) {
inputDescriptor.textSpacing = inputOptions.text.spacing;
} else {
throw is.invalidParameterError('text.spacing', 'integer between -1000000 and 1000000', inputOptions.text.spacing);
}
}
if (is.defined(inputOptions.text.wrap)) {
if (is.string(inputOptions.text.wrap) && is.inArray(inputOptions.text.wrap, ['word', 'char', 'word-char', 'none'])) {
inputDescriptor.textWrap = inputOptions.text.wrap;
} else {
throw is.invalidParameterError('text.wrap', 'one of: word, char, word-char, none', inputOptions.text.wrap);
}
}
delete inputDescriptor.buffer;
} else {
throw new Error('Expected a valid string to create an image with text.');
}
}
// Join images together
if (is.defined(inputOptions.join)) {
if (is.defined(this.options.join)) {
if (is.defined(inputOptions.join.animated)) {
if (is.bool(inputOptions.join.animated)) {
inputDescriptor.joinAnimated = inputOptions.join.animated;
} else {
throw is.invalidParameterError('join.animated', 'boolean', inputOptions.join.animated);
}
}
if (is.defined(inputOptions.join.across)) {
if (is.integer(inputOptions.join.across) && is.inRange(inputOptions.join.across, 1, 1000000)) {
inputDescriptor.joinAcross = inputOptions.join.across;
} else {
throw is.invalidParameterError('join.across', 'integer between 1 and 100000', inputOptions.join.across);
}
}
if (is.defined(inputOptions.join.shim)) {
if (is.integer(inputOptions.join.shim) && is.inRange(inputOptions.join.shim, 0, 1000000)) {
inputDescriptor.joinShim = inputOptions.join.shim;
} else {
throw is.invalidParameterError('join.shim', 'integer between 0 and 100000', inputOptions.join.shim);
}
}
if (is.defined(inputOptions.join.background)) {
inputDescriptor.joinBackground = this._getBackgroundColourOption(inputOptions.join.background);
}
if (is.defined(inputOptions.join.halign)) {
if (is.string(inputOptions.join.halign) && is.string(this.constructor.align[inputOptions.join.halign])) {
inputDescriptor.joinHalign = this.constructor.align[inputOptions.join.halign];
} else {
throw is.invalidParameterError('join.halign', 'valid alignment', inputOptions.join.halign);
}
}
if (is.defined(inputOptions.join.valign)) {
if (is.string(inputOptions.join.valign) && is.string(this.constructor.align[inputOptions.join.valign])) {
inputDescriptor.joinValign = this.constructor.align[inputOptions.join.valign];
} else {
throw is.invalidParameterError('join.valign', 'valid alignment', inputOptions.join.valign);
}
}
} else {
throw new Error('Expected input to be an array of images to join');
}
}
} else if (is.defined(inputOptions)) {
throw new Error(`Invalid input options ${inputOptions}`);
}
return inputDescriptor;
}
/**
* Handle incoming Buffer chunk on Writable Stream.
* @private
* @param {Buffer} chunk
* @param {string} encoding - unused
* @param {Function} callback
*/
function _write (chunk, _encoding, callback) {
if (Array.isArray(this.options.input.buffer)) {
if (is.buffer(chunk)) {
if (this.options.input.buffer.length === 0) {
this.on('finish', () => {
this.streamInFinished = true;
});
}
this.options.input.buffer.push(chunk);
callback();
} else {
callback(new Error('Non-Buffer data on Writable Stream'));
}
} else {
callback(new Error('Unexpected data on Writable Stream'));
}
}
/**
* Flattens the array of chunks accumulated in input.buffer.
* @private
*/
function _flattenBufferIn () {
if (this._isStreamInput()) {
this.options.input.buffer = Buffer.concat(this.options.input.buffer);
}
}
/**
* Are we expecting Stream-based input?
* @private
* @returns {boolean}
*/
function _isStreamInput () {
return Array.isArray(this.options.input.buffer);
}
/**
* Fast access to (uncached) image metadata without decoding any compressed pixel data.
*
* This is read from the header of the input image.
* It does not take into consideration any operations to be applied to the output image,
* such as resize or rotate.
*
* Dimensions in the response will respect the `page` and `pages` properties of the
* {@link /api-constructor/ constructor parameters}.
*
* A `Promise` is returned when `callback` is not provided.
*
* - `format`: Name of decoder used to decompress image data e.g. `jpeg`, `png`, `webp`, `gif`, `svg`
* - `size`: Total size of image in bytes, for Stream and Buffer input only
* - `width`: Number of pixels wide (EXIF orientation is not taken into consideration, see example below)
* - `height`: Number of pixels high (EXIF orientation is not taken into consideration, see example below)
* - `space`: Name of colour space interpretation e.g. `srgb`, `rgb`, `cmyk`, `lab`, `b-w` [...](https://www.libvips.org/API/current/enum.Interpretation.html)
* - `channels`: Number of bands e.g. `3` for sRGB, `4` for CMYK
* - `depth`: Name of pixel depth format e.g. `uchar`, `char`, `ushort`, `float` [...](https://www.libvips.org/API/current/enum.BandFormat.html)
* - `density`: Number of pixels per inch (DPI), if present
* - `chromaSubsampling`: String containing JPEG chroma subsampling, `4:2:0` or `4:4:4` for RGB, `4:2:0:4` or `4:4:4:4` for CMYK
* - `isProgressive`: Boolean indicating whether the image is interlaced using a progressive scan
* - `isPalette`: Boolean indicating whether the image is palette-based (GIF, PNG).
* - `bitsPerSample`: Number of bits per sample for each channel (GIF, PNG, HEIF).
* - `pages`: Number of pages/frames contained within the image, with support for TIFF, HEIF, PDF, animated GIF and animated WebP
* - `pageHeight`: Number of pixels high each page in a multi-page image will be.
* - `loop`: Number of times to loop an animated image, zero refers to a continuous loop.
* - `delay`: Delay in ms between each page in an animated image, provided as an array of integers.
* - `pagePrimary`: Number of the primary page in a HEIF image
* - `levels`: Details of each level in a multi-level image provided as an array of objects, requires libvips compiled with support for OpenSlide
* - `subifds`: Number of Sub Image File Directories in an OME-TIFF image
* - `background`: Default background colour, if present, for PNG (bKGD) and GIF images
* - `compression`: The encoder used to compress an HEIF file, `av1` (AVIF) or `hevc` (HEIC)
* - `resolutionUnit`: The unit of resolution (density), either `inch` or `cm`, if present
* - `hasProfile`: Boolean indicating the presence of an embedded ICC profile
* - `hasAlpha`: Boolean indicating the presence of an alpha transparency channel
* - `orientation`: Number value of the EXIF Orientation header, if present
* - `exif`: Buffer containing raw EXIF data, if present
* - `icc`: Buffer containing raw [ICC](https://www.npmjs.com/package/icc) profile data, if present
* - `iptc`: Buffer containing raw IPTC data, if present
* - `xmp`: Buffer containing raw XMP data, if present
* - `xmpAsString`: String containing XMP data, if valid UTF-8.
* - `tifftagPhotoshop`: Buffer containing raw TIFFTAG_PHOTOSHOP data, if present
* - `formatMagick`: String containing format for images loaded via *magick
* - `comments`: Array of keyword/text pairs representing PNG text blocks, if present.
*
* @example
* const metadata = await sharp(input).metadata();
*
* @example
* const image = sharp(inputJpg);
* image
* .metadata()
* .then(function(metadata) {
* return image
* .resize(Math.round(metadata.width / 2))
* .webp()
* .toBuffer();
* })
* .then(function(data) {
* // data contains a WebP image half the width and height of the original JPEG
* });
*
* @example
* // Get dimensions taking EXIF Orientation into account.
* const { autoOrient } = await sharp(input).metadata();
* const { width, height } = autoOrient;
*
* @param {Function} [callback] - called with the arguments `(err, metadata)`
* @returns {Promise<Object>|Sharp}
*/
function metadata (callback) {
const stack = Error();
if (is.fn(callback)) {
if (this._isStreamInput()) {
this.on('finish', () => {
this._flattenBufferIn();
sharp.metadata(this.options, (err, metadata) => {
if (err) {
callback(is.nativeError(err, stack));
} else {
callback(null, metadata);
}
});
});
} else {
sharp.metadata(this.options, (err, metadata) => {
if (err) {
callback(is.nativeError(err, stack));
} else {
callback(null, metadata);
}
});
}
return this;
} else {
if (this._isStreamInput()) {
return new Promise((resolve, reject) => {
const finished = () => {
this._flattenBufferIn();
sharp.metadata(this.options, (err, metadata) => {
if (err) {
reject(is.nativeError(err, stack));
} else {
resolve(metadata);
}
});
};
if (this.writableFinished) {
finished();
} else {
this.once('finish', finished);
}
});
} else {
return new Promise((resolve, reject) => {
sharp.metadata(this.options, (err, metadata) => {
if (err) {
reject(is.nativeError(err, stack));
} else {
resolve(metadata);
}
});
});
}
}
}
/**
* Access to pixel-derived image statistics for every channel in the image.
* A `Promise` is returned when `callback` is not provided.
*
* - `channels`: Array of channel statistics for each channel in the image. Each channel statistic contains
* - `min` (minimum value in the channel)
* - `max` (maximum value in the channel)
* - `sum` (sum of all values in a channel)
* - `squaresSum` (sum of squared values in a channel)
* - `mean` (mean of the values in a channel)
* - `stdev` (standard deviation for the values in a channel)
* - `minX` (x-coordinate of one of the pixel where the minimum lies)
* - `minY` (y-coordinate of one of the pixel where the minimum lies)
* - `maxX` (x-coordinate of one of the pixel where the maximum lies)
* - `maxY` (y-coordinate of one of the pixel where the maximum lies)
* - `isOpaque`: Is the image fully opaque? Will be `true` if the image has no alpha channel or if every pixel is fully opaque.
* - `entropy`: Histogram-based estimation of greyscale entropy, discarding alpha channel if any.
* - `sharpness`: Estimation of greyscale sharpness based on the standard deviation of a Laplacian convolution, discarding alpha channel if any.
* - `dominant`: Object containing most dominant sRGB colour based on a 4096-bin 3D histogram.
*
* **Note**: Statistics are derived from the original input image. Any operations performed on the image must first be
* written to a buffer in order to run `stats` on the result (see third example).
*
* @example
* const image = sharp(inputJpg);
* image
* .stats()
* .then(function(stats) {
* // stats contains the channel-wise statistics array and the isOpaque value
* });
*
* @example
* const { entropy, sharpness, dominant } = await sharp(input).stats();
* const { r, g, b } = dominant;
*
* @example
* const image = sharp(input);
* // store intermediate result
* const part = await image.extract(region).toBuffer();
* // create new instance to obtain statistics of extracted region
* const stats = await sharp(part).stats();
*
* @param {Function} [callback] - called with the arguments `(err, stats)`
* @returns {Promise<Object>}
*/
function stats (callback) {
const stack = Error();
if (is.fn(callback)) {
if (this._isStreamInput()) {
this.on('finish', () => {
this._flattenBufferIn();
sharp.stats(this.options, (err, stats) => {
if (err) {
callback(is.nativeError(err, stack));
} else {
callback(null, stats);
}
});
});
} else {
sharp.stats(this.options, (err, stats) => {
if (err) {
callback(is.nativeError(err, stack));
} else {
callback(null, stats);
}
});
}
return this;
} else {
if (this._isStreamInput()) {
return new Promise((resolve, reject) => {
this.on('finish', function () {
this._flattenBufferIn();
sharp.stats(this.options, (err, stats) => {
if (err) {
reject(is.nativeError(err, stack));
} else {
resolve(stats);
}
});
});
});
} else {
return new Promise((resolve, reject) => {
sharp.stats(this.options, (err, stats) => {
if (err) {
reject(is.nativeError(err, stack));
} else {
resolve(stats);
}
});
});
}
}
}
/**
* Decorate the Sharp prototype with input-related functions.
* @module Sharp
* @private
*/
module.exports = (Sharp) => {
Object.assign(Sharp.prototype, {
// Private
_inputOptionsFromObject,
_createInputDescriptor,
_write,
_flattenBufferIn,
_isStreamInput,
// Public
metadata,
stats
});
// Class attributes
Sharp.align = align;
};
@@ -0,0 +1,22 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./errors.cjs"), exports);
__exportStar(require("./helpers/parseUtil.cjs"), exports);
__exportStar(require("./helpers/typeAliases.cjs"), exports);
__exportStar(require("./helpers/util.cjs"), exports);
__exportStar(require("./types.cjs"), exports);
__exportStar(require("./ZodError.cjs"), exports);
@@ -0,0 +1,50 @@
{
"name": "emoji-regex",
"version": "8.0.0",
"description": "A regular expression to match all Emoji-only symbols as per the Unicode Standard.",
"homepage": "https://mths.be/emoji-regex",
"main": "index.js",
"types": "index.d.ts",
"keywords": [
"unicode",
"regex",
"regexp",
"regular expressions",
"code points",
"symbols",
"characters",
"emoji"
],
"license": "MIT",
"author": {
"name": "Mathias Bynens",
"url": "https://mathiasbynens.be/"
},
"repository": {
"type": "git",
"url": "https://github.com/mathiasbynens/emoji-regex.git"
},
"bugs": "https://github.com/mathiasbynens/emoji-regex/issues",
"files": [
"LICENSE-MIT.txt",
"index.js",
"index.d.ts",
"text.js",
"es2015/index.js",
"es2015/text.js"
],
"scripts": {
"build": "rm -rf -- es2015; babel src -d .; NODE_ENV=es2015 babel src -d ./es2015; node script/inject-sequences.js",
"test": "mocha",
"test:watch": "npm run test -- --watch"
},
"devDependencies": {
"@babel/cli": "^7.2.3",
"@babel/core": "^7.3.4",
"@babel/plugin-proposal-unicode-property-regex": "^7.2.0",
"@babel/preset-env": "^7.3.4",
"mocha": "^6.0.2",
"regexgen": "^1.3.0",
"unicode-12.0.0": "^0.7.9"
}
}
@@ -0,0 +1,14 @@
var ProxyInfo_1;
import { __decorate } from "tslib";
import { AsnType, AsnTypeTypes, AsnArray } from "@peculiar/asn1-schema";
import { Targets } from "./target";
let ProxyInfo = ProxyInfo_1 = class ProxyInfo extends AsnArray {
constructor(items) {
super(items);
Object.setPrototypeOf(this, ProxyInfo_1.prototype);
}
};
ProxyInfo = ProxyInfo_1 = __decorate([
AsnType({ type: AsnTypeTypes.Sequence, itemType: Targets })
], ProxyInfo);
export { ProxyInfo };
@@ -0,0 +1,16 @@
import type { SetStateAction } from 'react';
export interface Options<T> {
defaultValue?: T;
defaultValuePropName?: string;
valuePropName?: string;
trigger?: string;
}
export type Props = Record<string, any>;
export interface StandardProps<T> {
value: T;
defaultValue?: T;
onChange: (val: T) => void;
}
declare function useControllableValue<T = any>(props: StandardProps<T>): [T, (v: SetStateAction<T>) => void];
declare function useControllableValue<T = any>(props?: Props, options?: Options<T>): [T, (v: SetStateAction<T>, ...args: any[]) => void];
export default useControllableValue;
@@ -0,0 +1,11 @@
/**
* assert that condition is true or throw error (with message)
*/
export declare function assert(condition: any, msg?: string): asserts condition;
/**
* assert that value cannot exist = type `never`. throw runtime error if it does.
*/
export declare function assertNever(value: never, msg?: string): never;
export declare function assertInt32(arg: any): asserts arg is number;
export declare function assertUInt32(arg: any): asserts arg is number;
export declare function assertFloat32(arg: any): asserts arg is number;
@@ -0,0 +1 @@
{"version":3,"file":"magic-string.cjs.js","sources":["../src/BitSet.js","../src/Chunk.js","../src/SourceMap.js","../src/utils/guessIndent.js","../src/utils/getRelativePath.js","../src/utils/isObject.js","../src/utils/getLocator.js","../src/utils/Mappings.js","../src/MagicString.js","../src/Bundle.js","../src/index-legacy.js"],"sourcesContent":["export default class BitSet {\n\tconstructor(arg) {\n\t\tthis.bits = arg instanceof BitSet ? arg.bits.slice() : [];\n\t}\n\n\tadd(n) {\n\t\tthis.bits[n >> 5] |= 1 << (n & 31);\n\t}\n\n\thas(n) {\n\t\treturn !!(this.bits[n >> 5] & (1 << (n & 31)));\n\t}\n}\n","export default class Chunk {\n\tconstructor(start, end, content) {\n\t\tthis.start = start;\n\t\tthis.end = end;\n\t\tthis.original = content;\n\n\t\tthis.intro = '';\n\t\tthis.outro = '';\n\n\t\tthis.content = content;\n\t\tthis.storeName = false;\n\t\tthis.edited = false;\n\n\t\tif (DEBUG) {\n\t\t\t// we make these non-enumerable, for sanity while debugging\n\t\t\tObject.defineProperties(this, {\n\t\t\t\tprevious: { writable: true, value: null },\n\t\t\t\tnext: { writable: true, value: null },\n\t\t\t});\n\t\t} else {\n\t\t\tthis.previous = null;\n\t\t\tthis.next = null;\n\t\t}\n\t}\n\n\tappendLeft(content) {\n\t\tthis.outro += content;\n\t}\n\n\tappendRight(content) {\n\t\tthis.intro = this.intro + content;\n\t}\n\n\tclone() {\n\t\tconst chunk = new Chunk(this.start, this.end, this.original);\n\n\t\tchunk.intro = this.intro;\n\t\tchunk.outro = this.outro;\n\t\tchunk.content = this.content;\n\t\tchunk.storeName = this.storeName;\n\t\tchunk.edited = this.edited;\n\n\t\treturn chunk;\n\t}\n\n\tcontains(index) {\n\t\treturn this.start < index && index < this.end;\n\t}\n\n\teachNext(fn) {\n\t\tlet chunk = this;\n\t\twhile (chunk) {\n\t\t\tfn(chunk);\n\t\t\tchunk = chunk.next;\n\t\t}\n\t}\n\n\teachPrevious(fn) {\n\t\tlet chunk = this;\n\t\twhile (chunk) {\n\t\t\tfn(chunk);\n\t\t\tchunk = chunk.previous;\n\t\t}\n\t}\n\n\tedit(content, storeName, contentOnly) {\n\t\tthis.content = content;\n\t\tif (!contentOnly) {\n\t\t\tthis.intro = '';\n\t\t\tthis.outro = '';\n\t\t}\n\t\tthis.storeName = storeName;\n\n\t\tthis.edited = true;\n\n\t\treturn this;\n\t}\n\n\tprependLeft(content) {\n\t\tthis.outro = content + this.outro;\n\t}\n\n\tprependRight(content) {\n\t\tthis.intro = content + this.intro;\n\t}\n\n\treset() {\n\t\tthis.intro = '';\n\t\tthis.outro = '';\n\t\tif (this.edited) {\n\t\t\tthis.content = this.original;\n\t\t\tthis.storeName = false;\n\t\t\tthis.edited = false;\n\t\t}\n\t}\n\n\tsplit(index) {\n\t\tconst sliceIndex = index - this.start;\n\n\t\tconst originalBefore = this.original.slice(0, sliceIndex);\n\t\tconst originalAfter = this.original.slice(sliceIndex);\n\n\t\tthis.original = originalBefore;\n\n\t\tconst newChunk = new Chunk(index, this.end, originalAfter);\n\t\tnewChunk.outro = this.outro;\n\t\tthis.outro = '';\n\n\t\tthis.end = index;\n\n\t\tif (this.edited) {\n\t\t\t// after split we should save the edit content record into the correct chunk\n\t\t\t// to make sure sourcemap correct\n\t\t\t// For example:\n\t\t\t// ' test'.trim()\n\t\t\t// split -> ' ' + 'test'\n\t\t\t// ✔️ edit -> '' + 'test'\n\t\t\t// ✖️ edit -> 'test' + ''\n\t\t\t// TODO is this block necessary?...\n\t\t\tnewChunk.edit('', false);\n\t\t\tthis.content = '';\n\t\t} else {\n\t\t\tthis.content = originalBefore;\n\t\t}\n\n\t\tnewChunk.next = this.next;\n\t\tif (newChunk.next) newChunk.next.previous = newChunk;\n\t\tnewChunk.previous = this;\n\t\tthis.next = newChunk;\n\n\t\treturn newChunk;\n\t}\n\n\ttoString() {\n\t\treturn this.intro + this.content + this.outro;\n\t}\n\n\ttrimEnd(rx) {\n\t\tthis.outro = this.outro.replace(rx, '');\n\t\tif (this.outro.length) return true;\n\n\t\tconst trimmed = this.content.replace(rx, '');\n\n\t\tif (trimmed.length) {\n\t\t\tif (trimmed !== this.content) {\n\t\t\t\tthis.split(this.start + trimmed.length).edit('', undefined, true);\n\t\t\t\tif (this.edited) {\n\t\t\t\t\t// save the change, if it has been edited\n\t\t\t\t\tthis.edit(trimmed, this.storeName, true);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t} else {\n\t\t\tthis.edit('', undefined, true);\n\n\t\t\tthis.intro = this.intro.replace(rx, '');\n\t\t\tif (this.intro.length) return true;\n\t\t}\n\t}\n\n\ttrimStart(rx) {\n\t\tthis.intro = this.intro.replace(rx, '');\n\t\tif (this.intro.length) return true;\n\n\t\tconst trimmed = this.content.replace(rx, '');\n\n\t\tif (trimmed.length) {\n\t\t\tif (trimmed !== this.content) {\n\t\t\t\tconst newChunk = this.split(this.end - trimmed.length);\n\t\t\t\tif (this.edited) {\n\t\t\t\t\t// save the change, if it has been edited\n\t\t\t\t\tnewChunk.edit(trimmed, this.storeName, true);\n\t\t\t\t}\n\t\t\t\tthis.edit('', undefined, true);\n\t\t\t}\n\t\t\treturn true;\n\t\t} else {\n\t\t\tthis.edit('', undefined, true);\n\n\t\t\tthis.outro = this.outro.replace(rx, '');\n\t\t\tif (this.outro.length) return true;\n\t\t}\n\t}\n}\n","import { encode } from '@jridgewell/sourcemap-codec'Line truncated
@@ -0,0 +1,39 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
interface RegExpMatchArray {
indices?: RegExpIndicesArray;
}
interface RegExpExecArray {
indices?: RegExpIndicesArray;
}
interface RegExpIndicesArray extends Array<[number, number]> {
groups?: {
[key: string]: [number, number];
};
}
interface RegExp {
/**
* Returns a Boolean value indicating the state of the hasIndices flag (d) used with a regular expression.
* Default is false. Read-only.
*/
readonly hasIndices: boolean;
}
@@ -0,0 +1 @@
{"mappings":";AAAA,4BAAiB;IAAG,kBAAkB,CAAC,OAAS,CAAC,SAAS,EAAE,KAAK,IAAI,CAAC,YAAY,CAAC;IACjF,qBAAqB,CAAC,8CAAwC,CAAC;IAC/D,UAAU,CAAC,OAAO,CAAC;IACnB,eAAe,CAAC,uBAAuB,CAAC;IACxC,iBAAiB,CAAC,MAAM,YAAc,GAAG,UAAU,MAAM,CAAC,KAAK,KAAK,EAAE;YAAC,MAAM,CAAC,gCAA0B,CAAC;YAAE,KAAK,IAAM,GAAG,UAAU,MAAM,CAAC,KAAK,KAAK,EAAE,cAAc,CAAC;YAAE,OAAO,IAAM,GAAG,UAAU,MAAM,CAAC,KAAK,KAAK,EAAE,iBAAiB,CAAC;QAAA,GAAG,CAAC,CAAC;IAC3O,gBAAgB,CAAC,OAAS,GAAG,KAAK,IAAI,CAAC,SAAS,CAAC;AACnD","sources":["packages/@react-aria/grid/intl/fi-FI.json"],"sourcesContent":["{\n \"deselectedItem\": \"Kohdetta {item} ei valittu.\",\n \"longPressToSelect\": \"Siirry valintatilaan painamalla pitkään.\",\n \"select\": \"Valitse\",\n \"selectedAll\": \"Kaikki kohteet valittu.\",\n \"selectedCount\": \"{count, plural, =0 {Ei yhtään kohdetta valittu} one {# kohde valittu} other {# kohdetta valittu}}.\",\n \"selectedItem\": \"{item} valittu.\"\n}\n"],"names":[],"version":3,"file":"fi-FI.module.js.map"}
@@ -0,0 +1,22 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = woff2base64;
var _bytes2base = _interopRequireDefault(require("./util/bytes2base64"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* @file woff数组转base64编码
* @author mengke01(kekee000@gmail.com)
*/
/**
* woff数组转base64编码
*
* @param {Array} arrayBuffer ArrayBuffer对象
* @return {string} base64编码
*/
function woff2base64(arrayBuffer) {
return 'data:font/woff;charset=utf-8;base64,' + (0, _bytes2base.default)(arrayBuffer);
}
@@ -0,0 +1 @@
{"version":3,"file":"inversify-InversifyJs-issue-1857-childContainerShouldPointToRightParentServicesAfterRestore.int.spec.d.ts","sourceRoot":"","sources":["../../../src/issues/inversify-InversifyJs-issue-1857-childContainerShouldPointToRightParentServicesAfterRestore.int.spec.ts"],"names":[],"mappings":"AAEA,OAAO,kBAAkB,CAAC"}
@@ -0,0 +1,35 @@
{
"name": "@react-stately/collections",
"version": "3.12.0",
"description": "Spectrum UI components in React",
"license": "Apache-2.0",
"main": "dist/main.js",
"module": "dist/module.js",
"exports": {
"types": "./dist/types.d.ts",
"import": "./dist/import.mjs",
"require": "./dist/main.js"
},
"types": "dist/types.d.ts",
"source": "src/index.ts",
"files": [
"dist",
"src"
],
"sideEffects": false,
"repository": {
"type": "git",
"url": "https://github.com/adobe/react-spectrum"
},
"dependencies": {
"@react-types/shared": "^3.26.0",
"@swc/helpers": "^0.5.0"
},
"peerDependencies": {
"react": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1"
},
"publishConfig": {
"access": "public"
},
"gitHead": "71f0ef23053f9e03ee7e97df736e8b083e006849"
}
@@ -0,0 +1,10 @@
{
"all": true,
"check-coverage": false,
"reporter": ["text-summary", "text", "html", "json"],
"exclude": [
"coverage",
"dist",
"test"
]
}
@@ -0,0 +1,23 @@
import { OneBotAction } from '../../../action/OneBotAction';
import { Static } from '@sinclair/typebox';
export declare const GetFlashFileListPayloadSchema: import("@sinclair/typebox").TObject<{
fileset_id: import("@sinclair/typebox").TString;
}>;
export type GetFlashFileListPayload = Static<typeof GetFlashFileListPayloadSchema>;
export declare class GetFlashFileList extends OneBotAction<GetFlashFileListPayload, any> {
actionName: "get_flash_file_list";
payloadSchema: import("@sinclair/typebox").TObject<{
fileset_id: import("@sinclair/typebox").TString;
}>;
returnSchema: import("@sinclair/typebox").TAny;
actionSummary: string;
actionTags: string[];
payloadExample: {
fileset_id: string;
};
returnExample: {
file_name: string;
size: number;
}[];
_handle(payload: GetFlashFileListPayload): Promise<import("../../../../napcat-core/data/flash").FileListResponse>;
}
@@ -0,0 +1,28 @@
// Copyright (c) 2011-2016 Ryan Prichard
//
// 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.
#ifndef LIBWINPTY_AGENT_LOCATION_H
#define LIBWINPTY_AGENT_LOCATION_H
#include <string>
std::wstring findAgentProgram();
#endif // LIBWINPTY_AGENT_LOCATION_H
@@ -0,0 +1,8 @@
"use client";
import {
chip_default
} from "./chunk-NAV3ZXLI.mjs";
import "./chunk-P5JPZ5W3.mjs";
export {
chip_default as default
};
@@ -0,0 +1 @@
{"name":"dir-glob","version":"3.0.1","requiresBuild":false,"files":{"package.json":{"checkedAt":1794532125975,"integrity":"sha512-cIPaUzaun5Hl7zAYRCbzPaVEz3ikWpilr50NC/Wz5GIJA5p8YMhlsKiZVO51dhyDvq6gN1DPwBDsgDx/ffPexQ==","mode":420,"size":640},"index.js":{"checkedAt":1794532125975,"integrity":"sha512-f2oH0NUU1kYs9R3gRvcz+rjoe6F6kiXqR2xznajQS506qzR2BACGBukLQ3aJdfbJip6iPR68TMA6cLZuVoTUSA==","mode":420,"size":2304},"license":{"checkedAt":1794532125975,"integrity":"sha512-QQmk4M/jfBcyygmcqkvREGxOKYqfHdUIKM74BnQ1zGaNq0S+fUpNo/uv3aWu7iKuXEJBbPedCZYIl4PLE7L/Sg==","mode":420,"size":1116},"readme.md":{"checkedAt":1794532125975,"integrity":"sha512-wPYip1z06HutgP724PaaHCO3gqYGBzil0u9uZzJTlI9wiQ8Zod5VeDWBeoHfDwv4ueHXHOGwFlZv4oG1tDRdLw==","mode":420,"size":1357}}}
@@ -0,0 +1,48 @@
{
"name": "compressible",
"description": "Compressible Content-Type / mime checking",
"version": "2.0.18",
"contributors": [
"Douglas Christopher Wilson <doug@somethingdoug.com>",
"Jonathan Ong <me@jongleberry.com> (http://jongleberry.com)",
"Jeremiah Senkpiel <fishrock123@rocketmail.com> (https://searchbeam.jit.su)"
],
"license": "MIT",
"repository": "jshttp/compressible",
"keywords": [
"compress",
"gzip",
"mime",
"content-type"
],
"dependencies": {
"mime-db": ">= 1.43.0 < 2"
},
"devDependencies": {
"eslint": "6.8.0",
"eslint-config-standard": "14.1.0",
"eslint-plugin-import": "2.19.1",
"eslint-plugin-markdown": "1.0.1",
"eslint-plugin-node": "11.0.0",
"eslint-plugin-promise": "4.2.1",
"eslint-plugin-standard": "4.0.1",
"mocha": "7.0.0",
"nyc": "15.0.0"
},
"engines": {
"node": ">= 0.6"
},
"files": [
"HISTORY.md",
"LICENSE",
"README.md",
"index.js"
],
"scripts": {
"lint": "eslint --plugin markdown --ext js,md .",
"test": "mocha --reporter spec --bail --check-leaks test/",
"test-cov": "nyc --reporter=html --reporter=text npm test",
"test-travis": "nyc --reporter=text npm test",
"version": "node scripts/version-history.js && git add HISTORY.md"
}
}
@@ -0,0 +1,7 @@
/**
* @this {State}
* @returns {'*' | '_'}
*/
export function emphasisStrongMarker(this: State): "*" | "_";
import type { State } from '../types.js';
//# sourceMappingURL=emphasis-strong-marker.d.ts.map
@@ -0,0 +1 @@
{"version":3,"sources":["../../src/react/index.ts","../../src/dynamicMiddleware/react/index.ts"],"sourcesContent":["// This must remain here so that the `mangleErrors.cjs` build script\n// does not have to import this into each source file it rewrites.\nimport { formatProdErrorMessage } from '@reduxjs/toolkit';\nexport * from '@reduxjs/toolkit';\nexport { createDynamicMiddleware } from '../dynamicMiddleware/react';\nexport type { CreateDispatchWithMiddlewareHook } from '../dynamicMiddleware/react/index';","import type { DynamicMiddlewareInstance, GetDispatch, GetState, MiddlewareApiConfig, TSHelpersExtractDispatchExtensions } from '@reduxjs/toolkit';\nimport { createDynamicMiddleware as cDM } from '@reduxjs/toolkit';\nimport type { Context } from 'react';\nimport type { ReactReduxContextValue } from 'react-redux';\nimport { createDispatchHook, ReactReduxContext, useDispatch as useDefaultDispatch } from 'react-redux';\nimport type { Action, Dispatch, Middleware, UnknownAction } from 'redux';\nexport type UseDispatchWithMiddlewareHook<Middlewares extends Middleware<any, State, DispatchType>[] = [], State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = () => TSHelpersExtractDispatchExtensions<Middlewares> & DispatchType;\nexport type CreateDispatchWithMiddlewareHook<State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = {\n <Middlewares extends [Middleware<any, State, DispatchType>, ...Middleware<any, State, DispatchType>[]]>(...middlewares: Middlewares): UseDispatchWithMiddlewareHook<Middlewares, State, DispatchType>;\n withTypes<MiddlewareConfig extends MiddlewareApiConfig>(): CreateDispatchWithMiddlewareHook<GetState<MiddlewareConfig>, GetDispatch<MiddlewareConfig>>;\n};\ntype ActionFromDispatch<DispatchType extends Dispatch<Action>> = DispatchType extends Dispatch<infer Action> ? Action : never;\ntype ReactDynamicMiddlewareInstance<State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = DynamicMiddlewareInstance<State, DispatchType> & {\n createDispatchWithMiddlewareHookFactory: (context?: Context<ReactReduxContextValue<State, ActionFromDispatch<DispatchType>> | null>) => CreateDispatchWithMiddlewareHook<State, DispatchType>;\n createDispatchWithMiddlewareHook: CreateDispatchWithMiddlewareHook<State, DispatchType>;\n};\nexport const createDynamicMiddleware = <State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>>(): ReactDynamicMiddlewareInstance<State, DispatchType> => {\n const instance = cDM<State, DispatchType>();\n const createDispatchWithMiddlewareHookFactory = (\n // @ts-ignore\n context: Context<ReactReduxContextValue<State, ActionFromDispatch<DispatchType>> | null> = ReactReduxContext) => {\n const useDispatch = context === ReactReduxContext ? useDefaultDispatch : createDispatchHook(context);\n function createDispatchWithMiddlewareHook<Middlewares extends Middleware<any, State, DispatchType>[]>(...middlewares: Middlewares) {\n instance.addMiddleware(...middlewares);\n return useDispatch;\n }\n createDispatchWithMiddlewareHook.withTypes = () => createDispatchWithMiddlewareHook;\n return createDispatchWithMiddlewareHook as CreateDispatchWithMiddlewareHook<State, DispatchType>;\n };\n const createDispatchWithMiddlewareHook = createDispatchWithMiddlewareHookFactory();\n return {\n ...instance,\n createDispatchWithMiddlewareHookFactory,\n createDispatchWithMiddlewareHook\n };\n};"],"mappings":"AAGA,WAAc,mBCFd,OAAS,2BAA2BA,MAAW,mBAG/C,OAAS,sBAAAC,EAAoB,qBAAAC,EAAmB,eAAeC,MAA0B,cAYlF,IAAMC,EAA0B,IAAgJ,CACrL,IAAMC,EAAWL,EAAyB,EACpCM,EAA0C,CAEhDC,EAA2FL,IAAsB,CAC/G,IAAMM,EAAcD,IAAYL,EAAoBC,EAAqBF,EAAmBM,CAAO,EACnG,SAASE,KAAgGC,EAA0B,CACjI,OAAAL,EAAS,cAAc,GAAGK,CAAW,EAC9BF,CACT,CACA,OAAAC,EAAiC,UAAY,IAAMA,EAC5CA,CACT,EACMA,EAAmCH,EAAwC,EACjF,MAAO,CACL,GAAGD,EACH,wCAAAC,EACA,iCAAAG,CACF,CACF","names":["cDM","createDispatchHook","ReactReduxContext","useDefaultDispatch","createDynamicMiddleware","instance","createDispatchWithMiddlewareHookFactory","context","useDispatch","createDispatchWithMiddlewareHook","middlewares"]}
@@ -0,0 +1,86 @@
# socks
## Migrating from v1
For the most part, migrating from v1 takes minimal effort as v2 still supports factory creation of proxy connections with callback support.
### Notable breaking changes
- In an options object, the proxy 'command' is now required and does not default to 'connect'.
- **In an options object, 'target' is now known as 'destination'.**
- Sockets are no longer paused after a SOCKS connection is made, so socket.resume() is no longer required. (Please be sure to attach data handlers immediately to the Socket to avoid losing data).
- In v2, only the 'connect' command is supported via the factory SocksClient.createConnection function. (BIND and ASSOCIATE must be used with a SocksClient instance via event handlers).
- In v2, the factory SocksClient.createConnection function callback is called with a single object rather than separate socket and info object.
- A SOCKS http/https agent is no longer bundled into the library.
For informational purposes, here is the original getting started example from v1 converted to work with v2.
### Before (v1)
```javascript
var Socks = require('socks');
var options = {
proxy: {
ipaddress: "202.101.228.108",
port: 1080,
type: 5
},
target: {
host: "google.com",
port: 80
},
command: 'connect'
};
Socks.createConnection(options, function(err, socket, info) {
if (err)
console.log(err);
else {
socket.write("GET / HTTP/1.1\nHost: google.com\n\n");
socket.on('data', function(data) {
console.log(data.length);
console.log(data);
});
// PLEASE NOTE: sockets need to be resumed before any data will come in or out as they are paused right before this callback is fired.
socket.resume();
// 569
// <Buffer 48 54 54 50 2f 31 2e 31 20 33 30 31 20 4d 6f 76 65 64 20 50 65...
}
});
```
### After (v2)
```javascript
const SocksClient = require('socks').SocksClient;
let options = {
proxy: {
ipaddress: "202.101.228.108",
port: 1080,
type: 5
},
destination: {
host: "google.com",
port: 80
},
command: 'connect'
};
SocksClient.createConnection(options, function(err, result) {
if (err)
console.log(err);
else {
result.socket.write("GET / HTTP/1.1\nHost: google.com\n\n");
result.socket.on('data', function(data) {
console.log(data.length);
console.log(data);
});
// 569
// <Buffer 48 54 54 50 2f 31 2e 31 20 33 30 31 20 4d 6f 76 65 64 20 50 65...
}
});
```
@@ -0,0 +1,116 @@
/**
* @author Matthew Caruana Galizia <mattcg@gmail.com>
* @license MIT: http://mattcg.mit-license.org/
* @copyright Copyright (c) 2013, Matthew Caruana Galizia
*/
'use strict';
var Tag = require('./Tag.js');
var Subtag = require('./Subtag.js');
var index = require('language-subtag-registry/data/json/index.json');
var registry = require('language-subtag-registry/data/json/registry.json');
var tags = function tags(tag) {
return new Tag(tag);
};
module.exports = tags;
tags.check = function (tag) {
return new Tag(tag).valid();
};
tags.types = function (subtag) {
var types = index[subtag.toLowerCase()];
if (!types) {
return [];
}
return Object.keys(types).filter(function (type) {
return type !== 'grandfathered' && type !== 'redundant';
});
};
tags.subtags = function (subtags) {
var result = [];
if (!Array.isArray(subtags)) {
subtags = [subtags];
}
subtags.forEach(function (subtag) {
tags.types(subtag).forEach(function (type) {
result.push(new Subtag(subtag, type));
});
});
return result;
};
tags.filter = function (subtags) {
return subtags.filter(function (subtag) {
return !tags.types(subtag).length;
});
};
tags.search = function (query, all) {
var test;
if ('function' === typeof query.test) {
test = function test(description) {
return query.test(description);
};
// If the query is all lowercase, make a case-insensitive match.
} else if (query.toLowerCase() === query) {
test = function test(description) {
return -1 !== description.toLowerCase().indexOf(query);
};
} else {
test = function test(description) {
return -1 !== description.indexOf(query);
};
}
return registry.filter(function (record) {
if (!record.Subtag && !all) {
return false;
}
return record.Description.some(test);
// Sort by matched description string length.
// This is a quick way to push precise matches towards the top.
}).sort(function (a, b) {
return Math.min.apply(Math, a.Description.filter(test).map(function (description) {
return description.length;
})) - Math.min.apply(Math, b.Description.filter(test).map(function (description) {
return description.length;
}));
}).map(function (record) {
if (record.Subtag) {
return new Subtag(record.Subtag, record.Type);
}
return new Tag(record.Tag);
});
};
tags.languages = function (macrolanguage) {
var i,
l,
record,
results = [];
macrolanguage = macrolanguage.toLowerCase();
if (!require('language-subtag-registry/data/json/macrolanguage.json')[macrolanguage]) {
throw new Error('\'' + macrolanguage + '\' is not a macrolanguage.');
}
for (i = 0, l = registry.length; i < l; i++) {
record = registry[i];
if (record.Macrolanguage === macrolanguage) {
results.push(new Subtag(record.Subtag, record.Type));
}
}
return results;
};
tags.language = function (subtag) {
return tags.type(subtag, 'language');
};
tags.region = function (subtag) {
return tags.type(subtag, 'region');
};
tags.type = function (subtag, type) {
var types = index[subtag.toLowerCase()];
if (types && types[type]) {
return new Subtag(subtag, type);
}
return null;
};
tags.date = function () {
return require('language-subtag-registry/data/json/meta.json')['File-Date'];
};
@@ -0,0 +1,67 @@
{
"name": "compressing",
"version": "1.10.3",
"description": "Everything you need for compressing and uncompressing",
"main": "index.js",
"scripts": {
"test:ts": "tsc -p ./test/fixtures/types/tsconfig.json",
"test:js": "egg-bin test --ts false",
"test": "npm run test:js && npm run test:ts",
"cov": "egg-bin cov --ts false",
"lint-fix": "eslint . --fix",
"lint": "eslint .",
"ci": "npm run lint && npm run test:ts && npm run cov"
},
"repository": {
"type": "git",
"url": "git+https://github.com/node-modules/compressing.git"
},
"keywords": [
"compress",
"uncompress",
"util",
"tgz",
"gzip",
"tar",
"zip",
"stream"
],
"typings": "index.d.ts",
"files": [
"index.js",
"index.d.ts",
"lib"
],
"author": "shaoshuai0102 <shaoshuai0102@gmail.com>",
"license": "MIT",
"bugs": {
"url": "https://github.com/node-modules/compressing/issues"
},
"homepage": "https://github.com/node-modules/compressing#readme",
"dependencies": {
"flushwritable": "^1.0.0",
"get-ready": "^1.0.0",
"iconv-lite": "^0.5.0",
"mkdirp": "^0.5.1",
"pump": "^3.0.0",
"streamifier": "^0.1.1",
"tar-stream": "^1.5.2",
"@eggjs/yauzl": "^2.11.0",
"yazl": "^2.4.2"
},
"devDependencies": {
"@types/mocha": "10",
"@types/node": "20",
"dir-compare": "^1.3.0",
"egg-bin": "6",
"eslint": "8",
"eslint-config-egg": "12",
"mm": "^2.0.0",
"mz-modules": "^2.1.0",
"typescript": "5",
"uuid": "^3.0.1"
},
"engines": {
"node": ">= 4.0.0"
}
}
@@ -0,0 +1,57 @@
import { AlgorithmIdentifier } from "./algorithm_identifier";
import { Name } from "./name";
import { Time } from "./time";
import { Extension } from "./extension";
import { Version } from "./types";
/**
* Revoked certificate
* ```asn1
* SEQUENCE {
* userCertificate CertificateSerialNumber,
* revocationDate Time,
* crlEntryExtensions Extensions OPTIONAL
* -- if present, version MUST be v2
* }
* ```
*/
export declare class RevokedCertificate {
/**
* Serial number of the certificate
*/
userCertificate: ArrayBuffer;
/**
* Revocation date
*/
revocationDate: Time;
crlEntryExtensions?: Extension[];
constructor(params?: Partial<RevokedCertificate>);
}
/**
* ```asn1
* TBSCertList ::= SEQUENCE {
* version Version OPTIONAL,
* -- if present, MUST be v2
* signature AlgorithmIdentifier,
* issuer Name,
* thisUpdate Time,
* nextUpdate Time OPTIONAL,
* revokedCertificates SEQUENCE OF SEQUENCE {
* userCertificate CertificateSerialNumber,
* revocationDate Time,
* crlEntryExtensions Extensions OPTIONAL
* -- if present, version MUST be v2
* } OPTIONAL,
* crlExtensions [0] Extensions OPTIONAL }
* -- if present, version MUST be v2
* ```
*/
export declare class TBSCertList {
version?: Version;
signature: AlgorithmIdentifier;
issuer: Name;
thisUpdate: Time;
nextUpdate?: Time;
revokedCertificates?: RevokedCertificate[];
crlExtensions?: Extension[];
constructor(params?: Partial<TBSCertList>);
}
@@ -0,0 +1,7 @@
import type { InferMessageIdsTypeFromRule, InferOptionsTypeFromRule } from '../util';
import { getESLintCoreRule } from '../util/getESLintCoreRule';
declare const baseRule: ReturnType<typeof getESLintCoreRule>;
export type Options = InferOptionsTypeFromRule<NonNullable<typeof baseRule>>;
export type MessageIds = InferMessageIdsTypeFromRule<NonNullable<typeof baseRule>>;
declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"noLossOfPrecision", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>;
export default _default;
@@ -0,0 +1 @@
{"name":"@inversifyjs/common","version":"1.5.2","requiresBuild":false,"files":{"lib/cjs/services/models/AbstractNewable.js":{"checkedAt":1794532100640,"integrity":"sha512-1aCF2bYgFZ+90BzOupY2IFG9tPbo/+AZMaaxh+X7Gp48+7rpCjepCjgOY9wqpKWekv6kZqNY8lnIMw6G/Fr3ag==","mode":420,"size":120},"lib/cjs/either/models/Either.js":{"checkedAt":1794532100640,"integrity":"sha512-7rhXYOPEDfkcX6DYe53KGkOy3BCsg4lY5tkQvOm6z/skbn8muml57jZm7JIfC5MQsH+GEtOjfqph5Hs+gBPOYg==","mode":420,"size":111},"lib/cjs/index.js":{"checkedAt":1794532100640,"integrity":"sha512-myeMvTDS24URB7R8HUOCfB5a2BfnV3kb6ATdAz7F/5hGaq5tdFB+ek49JYJjCLDt49RnIjOVwbIKICRoC/Pp4Q==","mode":420,"size":899},"lib/esm/index.js":{"checkedAt":1794532100640,"integrity":"sha512-YqFoUhUNXKI5P2390GoB+AjzVzCRsYAuTilNI5lMZIy3sxkkwtqJw5dRyfHFTBOrDyX2fubwgMvi2QxicSZ3QQ==","mode":420,"size":593},"lib/cjs/common/calculations/isPromise.js":{"checkedAt":1794532100640,"integrity":"sha512-AdyYCbe0bt3qPnrdO3hKnMhevttG1X+MVT1iUPiIRNL8ixXz4LsdQHaOCNROIVyhCYsC7R6otExK+NZILxXiJg==","mode":420,"size":366},"lib/cjs/services/models/LazyServiceIdentifier.js":{"checkedAt":1794532100641,"integrity":"sha512-OGvS73RHgTWaDEgn5gzwzWXwsX7sYTBRwPZuG8kVoSG/MW52MOjSadJthFsStmnM1edjbwRFWU+2lT7gRBZUcA==","mode":420,"size":771},"lib/cjs/services/models/Newable.js":{"checkedAt":1794532100641,"integrity":"sha512-1Y7HzVTmRodxoRonSmOygOVWsu7Y/HjcS5sEPVnwkjbNylty4OFkfuifZGy5k+33eUue3mnkAT7Qa7Y9HkfJtQ==","mode":420,"size":112},"lib/cjs/services/models/ServiceIdentifier.js":{"checkedAt":1794532100641,"integrity":"sha512-GQNbxiYTGxMCamaQ5FaU4ReMcp6qDUW63ThWk1M+4BP3hhvtAsDYtYZ66gsH0c5QcB1qa9RL2e4o7X3GVwkQLQ==","mode":420,"size":122},"lib/cjs/services/models/ServiceIdentifier.spec-d.js":{"checkedAt":1794532100641,"integrity":"sha512-xys6+lV9gX4IepZCipLXz7klK/6U/CM8p82ZhUr0PD8RnktSlj3s045H00DPvhU0npzUIiatPftr/AMYgX2Lxw==","mode":420,"size":2279},"lib/cjs/services/calculations/stringifyServiceIdentifier.js":{"checkedAt":1794532100641,"integrity":"sha512-QEfXjl2sYlNqc/B69rCOb6vN0QU8fOQc+2+2xToCyzbRKOLuX2pZPx70erqsA5lo9cYLLz2a3C5OB6a19vlmGw==","mode":420,"size":568},"lib/cjs/package.json":{"checkedAt":1794532100641,"integrity":"sha512-8U1e2/m1/MZLAABugPPCT7pT1gQsJ0emvlef4tzYwWdTJIrY6/1Ks6sAUDIRPeWx9i1UbwxIXcxgesvNgTTtuA==","mode":420,"size":24},"lib/esm/package.json":{"checkedAt":1794532100642,"integrity":"sha512-0/qKvY+e4vDrutI/Gs9dbxgY8+4bWMP+lwjtUzPoWNp8Btq/+DNRn4Fl+lNX+8ULTmX/HqaMXapHD6wIA6VgiQ==","mode":420,"size":22},"package.json":{"checkedAt":1794532100642,"integrity":"sha512-WHfdGWEtWrim1UUZlQEBmZyzRuFiLATcduvFSGbfsDGE32UqFZeesgRjpzQgxuRCeDElJT7R1PoMWqdo/17IgQ==","mode":420,"size":1966},"lib/cjs/services/models/AbstractNewable.d.ts.map":{"checkedAt":1794532100642,"integrity":"sha512-IGL8UUjtUmOA4xljIj3IUNifw7uBgunIp7s98tDB/ciKJcczq/jnI0EdZfD3SH0rleBqe6digRloCJLa+29BZQ==","mode":420,"size":281},"lib/cjs/services/models/AbstractNewable.js.map":{"checkedAt":1794532100642,"integrity":"sha512-VEvtV95SADBVbn8KylW2K2OTRJygFawoy4W+AEWX9HArGT8ZEmGON60QVziZ7n8OYRFtvQ0U2j/wdWpwsMsOrw==","mode":420,"size":147},"lib/cjs/either/models/Either.d.ts.map":{"checkedAt":1794532100642,"integrity":"sha512-ATWS40fsD/8R/yLM8HE2AariM4LrZYHcakWoW55V7T5nWBnhYsi4J7NLaBxDQ1gXdI9u/edhnjN7rfVbdcHyfQ==","mode":420,"size":468},"lib/cjs/either/models/Either.js.map":{"checkedAt":1794532100642,"integrity":"sha512-3joxvCzesMdIZm5KGZ6kSo3WDKHLus+jMpLCKpTRuICYgOkb3it0TzxWXXiZgGbAQNOF+wHdIfUtv8XyNjJ4QA==","mode":420,"size":127},"lib/cjs/index.d.ts.map":{"checkedAt":1794532100642,"integrity":"sha512-/1koDiv98LZ6xHdh697sXGPxuyM+/iG76Eycw4mYQ9cJQXr9b8y1mPsqd8Ttg14LCzPUP0Dq1FidmLkPwyOf9A==","mode":420,"size":590},"lib/esm/index.d.ts.map":{"checkedAt":1794532100642,"integrity":"sha512-/1koDiv98LZ6xHdh697sXGPxuyM+/iG76Eycw4mYQ9cJQXr9b8y1mPsqd8Ttg14LCzPUP0Dq1FidmLkPwyOf9A==","mode":420,"size":590},"lib/cjs/index.js.map":{"checkedAt":1794532100642,"integrity":"sha512-KqECPgvbL0ZlB5Zigx0tjQDDJJpyTjJBDut/L6vZAw+sCYQQTMXiy9lI8NRRcGw7Q7EV59fBix5SWphUOGz8pA==","mode":420,"size":225},"lib/esm/index.js.map":{"checkedAt":1794532100643,"integrity":"sha512-t807xdwE8NMr3nf6ZrpO8mEu1NSYxJWPfQDD+Qn83XfHQcya3wnhvEsa4WVJGXeNqDYD5bizn62y2vmX/A4MOg==","mode":420,"size":922},"lib/cjs/common/calculations/isPromise.d.ts.map":{"checkedAt":1794532100643,"integrity":"sha512-YsFvXQbkQYDG6YiIecCv61DvrufPCI+TeLcxM+lm7ysSsdsmcTvwFhHg3mH1Cn4K5XUphUCKUqasTVKoQDG9sA==","mode":420,"size":228},"lib/cjs/common/calculations/isPromise.js.map":{"checkedAt":1794532100643,"integrity":"sha512-ASEkRVkmW/cjSkFJgnV+9Quqbf+O/McBV9jNWQpEmanqa2/A3eqcl+1bM5zz8XYaK2pT45QGiFQvoG/Y7WKhRw==","mode":420,"size":362},"lib/cjs/common/calculations/isPromise.spec.d.ts.map":{"checkedAt":1794532100643,"integrity":"sha512-96wyRDketKNL+oNw9E5lIE7H0m7OMeA31SQWEks5ht8LX4qngGSKv1VwC3fSk6Ba+DumU5UsMYrP9lcUpK847Q==","mode":420,"size":151},"lib/cjs/services/models/LazyServiceIdentifier.d.ts.map":{"checkedAt":1794532100643,"integrity":"sha512-7Pa+9qykHLZM17cLEmYtN1jv7kepS3NvZPTEWvCYSJBxkcv+rQT3a5G+SsRBkCqJd8Ya39nELZjvlLJcLine truncated
@@ -0,0 +1,15 @@
"use strict";
var _array_like_to_array = require("./_array_like_to_array.cjs");
function _unsupported_iterable_to_array(o, minLen) {
if (!o) return;
if (typeof o === "string") return _array_like_to_array._(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(n);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array._(o, minLen);
}
exports._ = _unsupported_iterable_to_array;
@@ -0,0 +1,22 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = propName;
/**
* Returns the name of the prop given the JSXAttribute object.
*/
function propName() {
var prop = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
if (!prop.type || prop.type !== 'JSXAttribute') {
throw new Error('The prop must be a JSXAttribute collected by the AST parser.');
}
if (prop.name.type === 'JSXNamespacedName') {
return prop.name.namespace.name + ':' + prop.name.name.name;
}
return prop.name.name;
}
@@ -0,0 +1,2 @@
import type { LibDefinition } from '../variable';
export declare const es2023_array: LibDefinition;
@@ -0,0 +1,45 @@
themeName = 'bubble'
activeColor = #fff
borderColor = #777
backgroundColor = #444
inactiveColor = #ccc
shadowColor = #ddd
textColor = #fff
@import './core'
@import './base'
@import './bubble/*'
.ql-container.ql-bubble:not(.ql-disabled)
a:not(.ql-close)
position: relative
white-space: nowrap
a:not(.ql-close)::before
background-color: #444
border-radius: 15px
top: -5px
font-size: 12px
color: #fff
content: attr(href)
font-weight: normal
overflow: hidden
padding: 5px 15px
text-decoration: none
z-index: 1
a:not(.ql-close)::after
border-top: 6px solid #444
border-left: 6px solid transparent
border-right: 6px solid transparent
top: 0
content: " "
height: 0
width: 0
a:not(.ql-close)::before, a:not(.ql-close)::after
left: 0
margin-left: 50%
position: absolute
transform: translate(-50%, -100%)
transition: visibility 0s ease 200ms
visibility: hidden
a:not(.ql-close):hover::before, a:not(.ql-close):hover::after
visibility: visible
@@ -0,0 +1,80 @@
"use client";
import { useContext } from 'react';
import { isAnimationControls } from '../../animation/utils/is-animation-controls.mjs';
import { MotionContext } from '../../context/MotionContext/index.mjs';
import { PresenceContext } from '../../context/PresenceContext.mjs';
import { isControllingVariants, isVariantNode } from '../../render/utils/is-controlling-variants.mjs';
import { resolveVariantFromProps } from '../../render/utils/resolve-variants.mjs';
import { useConstant } from '../../utils/use-constant.mjs';
import { resolveMotionValue } from '../../value/utils/resolve-motion-value.mjs';
function makeState({ scrapeMotionValuesFromProps, createRenderState, }, props, context, presenceContext) {
const state = {
latestValues: makeLatestValues(props, context, presenceContext, scrapeMotionValuesFromProps),
renderState: createRenderState(),
};
return state;
}
function makeLatestValues(props, context, presenceContext, scrapeMotionValues) {
const values = {};
const motionValues = scrapeMotionValues(props, {});
for (const key in motionValues) {
values[key] = resolveMotionValue(motionValues[key]);
}
let { initial, animate } = props;
const isControllingVariants$1 = isControllingVariants(props);
const isVariantNode$1 = isVariantNode(props);
if (context &&
isVariantNode$1 &&
!isControllingVariants$1 &&
props.inherit !== false) {
if (initial === undefined)
initial = context.initial;
if (animate === undefined)
animate = context.animate;
}
let isInitialAnimationBlocked = presenceContext
? presenceContext.initial === false
: false;
isInitialAnimationBlocked = isInitialAnimationBlocked || initial === false;
const variantToSet = isInitialAnimationBlocked ? animate : initial;
if (variantToSet &&
typeof variantToSet !== "boolean" &&
!isAnimationControls(variantToSet)) {
const list = Array.isArray(variantToSet) ? variantToSet : [variantToSet];
for (let i = 0; i < list.length; i++) {
const resolved = resolveVariantFromProps(props, list[i]);
if (resolved) {
const { transitionEnd, transition, ...target } = resolved;
for (const key in target) {
let valueTarget = target[key];
if (Array.isArray(valueTarget)) {
/**
* Take final keyframe if the initial animation is blocked because
* we want to initialise at the end of that blocked animation.
*/
const index = isInitialAnimationBlocked
? valueTarget.length - 1
: 0;
valueTarget = valueTarget[index];
}
if (valueTarget !== null) {
values[key] = valueTarget;
}
}
for (const key in transitionEnd) {
values[key] = transitionEnd[key];
}
}
}
}
return values;
}
const makeUseVisualState = (config) => (props, isStatic) => {
const context = useContext(MotionContext);
const presenceContext = useContext(PresenceContext);
const make = () => makeState(config, props, context, presenceContext);
return isStatic ? make() : useConstant(make);
};
export { makeUseVisualState };
@@ -0,0 +1 @@
{"name":"@ungap/structured-clone","version":"1.3.0","requiresBuild":false,"files":{"LICENSE":{"checkedAt":1794532114702,"integrity":"sha512-OqTQGEp54OXbHtp0N5SZNuHZkQBYjL9pnOEbnB+kXxErxXUKhnFJ1TmFLwL0W5IbzEiFuwEGyATCeSp9slzsgA==","mode":420,"size":765},"cjs/deserialize.js":{"checkedAt":1794532114702,"integrity":"sha512-H6TtkoCG5QJJ6SKTcuZSZy1+5eB8Fg3Za8T0a4J5el4hf2ryu4+xZhUm4GPUXTNQSZco/QGJ74igfc/7TLhodg==","mode":420,"size":2210},"esm/deserialize.js":{"checkedAt":1794532114702,"integrity":"sha512-QG1uCFJDp2nfB8ks+b0YiL2QmxXzAQqsE6HNzYslTF/QdAXKe4yrRg+svEI+WRiEPFboR2MuP11r++aqMhKQbA==","mode":420,"size":2169},"cjs/index.js":{"checkedAt":1794532114702,"integrity":"sha512-LHh1WUrYSmtn+QlRU+en04pMrq1/Sy+mwCV27Wt2yx3rJF04OL5NjvuXVY1bpZDON5QKvn0DAlIYDne/NubOYQ==","mode":420,"size":941},"esm/index.js":{"checkedAt":1794532114702,"integrity":"sha512-Ojeay7tlXQ/+3+Ie0ciB+XCM9E8KPCLvF31tYuZEyBEZd9q2kLKHk+GwzWkx3z5hdXwFoS/omvh3H1aN7z8qjQ==","mode":420,"size":829},"cjs/json.js":{"checkedAt":1794532114703,"integrity":"sha512-eLgoEYCKqZ/ZICtpxOsVhVLIk9D6eUZxRz3yHTGGQKHRMy6ddSUjKTbLSSxiPq212r0miH+5he3KB6cyQwrMCA==","mode":420,"size":754},"esm/json.js":{"checkedAt":1794532114703,"integrity":"sha512-zVO7PLueDJCAQ3GmqrUuVao8gV4nJvu8zlZJ0iEtOUibCvqG9Rwq4QLQvIb1gvmW4qecW+yZ+lDbiqcor/4zrA==","mode":420,"size":690},"cjs/serialize.js":{"checkedAt":1794532114703,"integrity":"sha512-HPpk/CVEn1gApGYN1QRp+1s+28SVuDYri0kLpn+3Wpf5bymgzjIY0cTbxFbtGv7d8q/x4pPRQTyz1Q42TsoT3g==","mode":420,"size":4451},"esm/serialize.js":{"checkedAt":1794532114703,"integrity":"sha512-mDbkkRsd+QBJPWKdABHek+MPekCoJodkMT1J0YMx//cnmfPl7dpBuLhzzf7VoUWjrpNb9PqUO5P2sfLFs6lQSg==","mode":420,"size":4414},"structured-json.js":{"checkedAt":1794532114703,"integrity":"sha512-bbAmkFVoCfy1OFv/D/r3aU/Dg3RVg2+g95VGHHKfYYK3uOKcYQK+GsC48zb9il/cd6Hv2a8e7VxGHK3CaT1ndA==","mode":420,"size":2648},"cjs/types.js":{"checkedAt":1794532114703,"integrity":"sha512-pvXO7KiDV0ogh7kMHx7ADd5XcLVe2fI2dv1agcmncCcQ8pH5eQU794BxykjD86FV2RDS7hDxFBDi4wDYBh8erA==","mode":420,"size":495},"esm/types.js":{"checkedAt":1794532114703,"integrity":"sha512-WyeoAFPfW8S0+Y81HWMGKH6JgmCnihs/5Z6hklANOPXJDaHXKRq8H7ZLm0XnkjZuOoYGT8J7K4sYRf3SPuJWNQ==","mode":420,"size":319},"cjs/package.json":{"checkedAt":1794532114703,"integrity":"sha512-ZcZkWKviEBAyzdG1DKbmQ+DDaNCd+mzHAGsz7YFeEGuyD5r/EYGBgH59+fXU2Nl5Zwmx7Jp+BFRCMWNv34/fQg==","mode":420,"size":19},"package.json":{"checkedAt":1794532114704,"integrity":"sha512-iVST2Vq1Y4L4/nMHjOzD0ZYg3iTf/lqSRGbhDZmGXVCZDN/4qd3WHOHsjY7aoLORk1jh08snTDPdSoX1H6Oulw==","mode":420,"size":1368},"README.md":{"checkedAt":1794532114704,"integrity":"sha512-YqWR5Cc3stJamrugcbnWHoWY6Co7r3kN3gzTJl+Krpuc4xKNpIJIfz1m8+K2SxRN5sl+qsiaJuvncDemQUD+Kg==","mode":420,"size":4556},".github/workflows/node.js.yml":{"checkedAt":1794532114704,"integrity":"sha512-fCiNbrgUAi7EvxK4AhkhkTSHlqm03kT0LrzZUYlLgcsgSNH9O6Si3B0Ao9Z8Cmf2kYA7jakhlZ7GonCCwqzMbQ==","mode":420,"size":872}}}
@@ -0,0 +1,11 @@
export { createNode } from './doc/createNode.js';
export { debug, warn } from './log.js';
export { createPair } from './nodes/Pair.js';
export { toJS } from './nodes/toJS.js';
export { findPair } from './nodes/YAMLMap.js';
export { map as mapTag } from './schema/common/map.js';
export { seq as seqTag } from './schema/common/seq.js';
export { string as stringTag } from './schema/common/string.js';
export { foldFlowLines } from './stringify/foldFlowLines.js';
export { stringifyNumber } from './stringify/stringifyNumber.js';
export { stringifyString } from './stringify/stringifyString.js';
@@ -0,0 +1,170 @@
import { configureStore } from '@reduxjs/toolkit'
import {
ApiProvider,
buildCreateApi,
coreModule,
createApi,
reactHooksModule,
} from '@reduxjs/toolkit/query/react'
import { fireEvent, render, waitFor } from '@testing-library/react'
import { delay } from 'msw'
import * as React from 'react'
import type { ReactReduxContextValue } from 'react-redux'
import {
Provider,
createDispatchHook,
createSelectorHook,
createStoreHook,
} from 'react-redux'
const api = createApi({
baseQuery: async (arg: any) => {
await delay(150)
return { data: arg?.body ? arg.body : null }
},
endpoints: (build) => ({
getUser: build.query<any, number>({
query: (arg) => arg,
}),
updateUser: build.mutation<any, { name: string }>({
query: (update) => ({ body: update }),
}),
}),
})
afterEach(() => {
vi.resetAllMocks()
})
describe('ApiProvider', () => {
test('ApiProvider allows a user to make queries without a traditional Redux setup', async () => {
function User() {
const [value, setValue] = React.useState(0)
const { isFetching } = api.endpoints.getUser.useQuery(1, {
skip: value < 1,
})
return (
<div>
<div data-testid="isFetching">{String(isFetching)}</div>
<button onClick={() => setValue((val) => val + 1)}>
Increment value
</button>
</div>
)
}
const { getByText, getByTestId } = render(
<ApiProvider api={api}>
<User />
</ApiProvider>,
)
await waitFor(() =>
expect(getByTestId('isFetching').textContent).toBe('false'),
)
fireEvent.click(getByText('Increment value'))
await waitFor(() =>
expect(getByTestId('isFetching').textContent).toBe('true'),
)
await waitFor(() =>
expect(getByTestId('isFetching').textContent).toBe('false'),
)
fireEvent.click(getByText('Increment value'))
// Being that nothing has changed in the args, this should never fire.
expect(getByTestId('isFetching').textContent).toBe('false')
})
test('ApiProvider throws if nested inside a Redux context', () => {
// Intentionally swallow the "unhandled error" message
vi.spyOn(console, 'error').mockImplementation(() => {})
expect(() =>
render(
<Provider store={configureStore({ reducer: () => null })}>
<ApiProvider api={api}>child</ApiProvider>
</Provider>,
),
).toThrowErrorMatchingInlineSnapshot(
`[Error: Existing Redux context detected. If you already have a store set up, please use the traditional Redux setup.]`,
)
})
test('ApiProvider allows a custom context', async () => {
const customContext = React.createContext<ReactReduxContextValue | null>(
null,
)
const createApiWithCustomContext = buildCreateApi(
coreModule(),
reactHooksModule({
hooks: {
useStore: createStoreHook(customContext),
useSelector: createSelectorHook(customContext),
useDispatch: createDispatchHook(customContext),
},
}),
)
const customApi = createApiWithCustomContext({
baseQuery: async (arg: any) => {
await delay(150)
return { data: arg?.body ? arg.body : null }
},
endpoints: (build) => ({
getUser: build.query<any, number>({
query: (arg) => arg,
}),
updateUser: build.mutation<any, { name: string }>({
query: (update) => ({ body: update }),
}),
}),
})
function User() {
const [value, setValue] = React.useState(0)
const { isFetching } = customApi.endpoints.getUser.useQuery(1, {
skip: value < 1,
})
return (
<div>
<div data-testid="isFetching">{String(isFetching)}</div>
<button onClick={() => setValue((val) => val + 1)}>
Increment value
</button>
</div>
)
}
const { getByText, getByTestId } = render(
<ApiProvider api={customApi} context={customContext}>
<User />
</ApiProvider>,
)
await waitFor(() =>
expect(getByTestId('isFetching').textContent).toBe('false'),
)
fireEvent.click(getByText('Increment value'))
await waitFor(() =>
expect(getByTestId('isFetching').textContent).toBe('true'),
)
await waitFor(() =>
expect(getByTestId('isFetching').textContent).toBe('false'),
)
fireEvent.click(getByText('Increment value'))
// Being that nothing has changed in the args, this should never fire.
expect(getByTestId('isFetching').textContent).toBe('false')
// won't throw if nested, because context is different
expect(() =>
render(
<Provider store={configureStore({ reducer: () => null })}>
<ApiProvider api={customApi} context={customContext}>
child
</ApiProvider>
</Provider>,
),
).not.toThrow()
})
})
@@ -0,0 +1,25 @@
// These are all the basic types that's compatible with all supported TypeScript versions.
export * from '../base';
// These are special types that require at least TypeScript 4.1.
export {CamelCase} from './camel-case';
export {CamelCasedProperties} from './camel-cased-properties';
export {CamelCasedPropertiesDeep} from './camel-cased-properties-deep';
export {KebabCase} from './kebab-case';
export {KebabCasedProperties} from './kebab-cased-properties';
export {KebabCasedPropertiesDeep} from './kebab-cased-properties-deep';
export {PascalCase} from './pascal-case';
export {PascalCasedProperties} from './pascal-cased-properties';
export {PascalCasedPropertiesDeep} from './pascal-cased-properties-deep';
export {SnakeCase} from './snake-case';
export {SnakeCasedProperties} from './snake-cased-properties';
export {SnakeCasedPropertiesDeep} from './snake-cased-properties-deep';
export {ScreamingSnakeCase} from './screaming-snake-case';
export {DelimiterCase} from './delimiter-case';
export {DelimiterCasedProperties} from './delimiter-cased-properties';
export {DelimiterCasedPropertiesDeep} from './delimiter-cased-properties-deep';
export {Split} from './split';
export {Trim} from './trim';
export {Includes} from './includes';
export {Get} from './get';
export {LastArrayElement} from './last-array-element';
@@ -0,0 +1,22 @@
/// <reference types="node"/>
import {IncomingMessage} from 'http';
/**
Decompress a HTTP response if needed.
@param response - The HTTP incoming stream with compressed data.
@returns The decompressed HTTP response stream.
@example
```
import {http} from 'http';
import decompressResponse = require('decompress-response');
http.get('https://sindresorhus.com', response => {
response = decompressResponse(response);
});
```
*/
declare function decompressResponse(response: IncomingMessage): IncomingMessage;
export = decompressResponse;
@@ -0,0 +1,74 @@
import { CreateType } from '../create/type.mjs';
import { Computed } from '../computed/index.mjs';
import { Optional } from '../optional/index.mjs';
import { Object } from '../object/index.mjs';
import { Intersect } from '../intersect/index.mjs';
import { Union } from '../union/index.mjs';
import { Ref } from '../ref/index.mjs';
import { Discard } from '../discard/index.mjs';
import { TransformKind } from '../symbols/index.mjs';
import { PartialFromMappedResult } from './partial-from-mapped-result.mjs';
// ------------------------------------------------------------------
// KindGuard
// ------------------------------------------------------------------
import * as KindGuard from '../guard/kind.mjs';
// prettier-ignore
function FromComputed(target, parameters) {
return Computed('Partial', [Computed(target, parameters)]);
}
// prettier-ignore
function FromRef($ref) {
return Computed('Partial', [Ref($ref)]);
}
// prettier-ignore
function FromProperties(properties) {
const partialProperties = {};
for (const K of globalThis.Object.getOwnPropertyNames(properties))
partialProperties[K] = Optional(properties[K]);
return partialProperties;
}
// prettier-ignore
function FromObject(type, properties) {
const options = Discard(type, [TransformKind, '$id', 'required', 'properties']);
const mappedProperties = FromProperties(properties);
return Object(mappedProperties, options);
}
// prettier-ignore
function FromRest(types) {
return types.map(type => PartialResolve(type));
}
// ------------------------------------------------------------------
// PartialResolve
// ------------------------------------------------------------------
// prettier-ignore
function PartialResolve(type) {
return (
// Mappable
KindGuard.IsComputed(type) ? FromComputed(type.target, type.parameters) :
KindGuard.IsRef(type) ? FromRef(type.$ref) :
KindGuard.IsIntersect(type) ? Intersect(FromRest(type.allOf)) :
KindGuard.IsUnion(type) ? Union(FromRest(type.anyOf)) :
KindGuard.IsObject(type) ? FromObject(type, type.properties) :
// Intrinsic
KindGuard.IsBigInt(type) ? type :
KindGuard.IsBoolean(type) ? type :
KindGuard.IsInteger(type) ? type :
KindGuard.IsLiteral(type) ? type :
KindGuard.IsNull(type) ? type :
KindGuard.IsNumber(type) ? type :
KindGuard.IsString(type) ? type :
KindGuard.IsSymbol(type) ? type :
KindGuard.IsUndefined(type) ? type :
// Passthrough
Object({}));
}
/** `[Json]` Constructs a type where all properties are optional */
export function Partial(type, options) {
if (KindGuard.IsMappedResult(type)) {
return PartialFromMappedResult(type, options);
}
else {
// special: mapping types require overridable options
return CreateType({ ...PartialResolve(type), ...options });
}
}
@@ -0,0 +1,170 @@
/*
Copyright (C) 2012-2014 Yusuke Suzuki <utatane.tea@gmail.com>
Copyright (C) 2013 Alex Seville <hi@alexanderseville.com>
Copyright (C) 2014 Thiago de Arruda <tpadilha84@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* Escope (<a href="http://github.com/estools/escope">escope</a>) is an <a
* href="http://www.ecma-international.org/publications/standards/Ecma-262.htm">ECMAScript</a>
* scope analyzer extracted from the <a
* href="http://github.com/estools/esmangle">esmangle project</a/>.
* <p>
* <em>escope</em> finds lexical scopes in a source program, i.e. areas of that
* program where different occurrences of the same identifier refer to the same
* variable. With each scope the contained variables are collected, and each
* identifier reference in code is linked to its corresponding variable (if
* possible).
* <p>
* <em>escope</em> works on a syntax tree of the parsed source code which has
* to adhere to the <a
* href="https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API">
* Mozilla Parser API</a>. E.g. <a href="https://github.com/eslint/espree">espree</a> is a parser
* that produces such syntax trees.
* <p>
* The main interface is the {@link analyze} function.
* @module escope
*/
import { assert } from "./assert.js";
import ScopeManager from "./scope-manager.js";
import Referencer from "./referencer.js";
import Reference from "./reference.js";
import Variable from "./variable.js";
import eslintScopeVersion from "./version.js";
/**
* Set the default options
* @returns {Object} options
*/
function defaultOptions() {
return {
optimistic: false,
nodejsScope: false,
impliedStrict: false,
sourceType: "script", // one of ['script', 'module', 'commonjs']
ecmaVersion: 5,
childVisitorKeys: null,
fallback: "iteration"
};
}
/**
* Preform deep update on option object
* @param {Object} target Options
* @param {Object} override Updates
* @returns {Object} Updated options
*/
function updateDeeply(target, override) {
/**
* Is hash object
* @param {Object} value Test value
* @returns {boolean} Result
*/
function isHashObject(value) {
return typeof value === "object" && value instanceof Object && !(value instanceof Array) && !(value instanceof RegExp);
}
for (const key in override) {
if (Object.hasOwn(override, key)) {
const val = override[key];
if (isHashObject(val)) {
if (isHashObject(target[key])) {
updateDeeply(target[key], val);
} else {
target[key] = updateDeeply({}, val);
}
} else {
target[key] = val;
}
}
}
return target;
}
/**
* Main interface function. Takes an Espree syntax tree and returns the
* analyzed scopes.
* @function analyze
* @param {espree.Tree} tree Abstract Syntax Tree
* @param {Object} providedOptions Options that tailor the scope analysis
* @param {boolean} [providedOptions.optimistic=false] the optimistic flag
* @param {boolean} [providedOptions.ignoreEval=false] whether to check 'eval()' calls
* @param {boolean} [providedOptions.nodejsScope=false] whether the whole
* script is executed under node.js environment. When enabled, escope adds
* a function scope immediately following the global scope.
* @param {boolean} [providedOptions.impliedStrict=false] implied strict mode
* (if ecmaVersion >= 5).
* @param {string} [providedOptions.sourceType='script'] the source type of the script. one of 'script', 'module', and 'commonjs'
* @param {number} [providedOptions.ecmaVersion=5] which ECMAScript version is considered
* @param {boolean} [providedOptions.jsx=false] support JSX references
* @param {Object} [providedOptions.childVisitorKeys=null] Additional known visitor keys. See [esrecurse](https://github.com/estools/esrecurse)'s the `childVisitorKeys` option.
* @param {string} [providedOptions.fallback='iteration'] A kind of the fallback in order to encounter with unknown node. See [esrecurse](https://github.com/estools/esrecurse)'s the `fallback` option.
* @returns {ScopeManager} ScopeManager
*/
function analyze(tree, providedOptions) {
const options = updateDeeply(defaultOptions(), providedOptions);
const scopeManager = new ScopeManager(options);
const referencer = new Referencer(options, scopeManager);
referencer.visit(tree);
assert(scopeManager.__currentScope === null, "currentScope should be null.");
return scopeManager;
}
export {
/** @name module:escope.version */
eslintScopeVersion as version,
/** @name module:escope.Reference */
Reference,
/** @name module:escope.Variable */
Variable,
/** @name module:escope.ScopeManager */
ScopeManager,
/** @name module:escope.Referencer */
Referencer,
analyze
};
/** @name module:escope.Definition */
export { Definition } from "./definition.js";
/** @name module:escope.PatternVisitor */
export { default as PatternVisitor } from "./pattern-visitor.js";
/** @name module:escope.Scope */
export { Scope } from "./scope.js";
/* vim: set sw=4 ts=4 et tw=80 : */
@@ -0,0 +1,74 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SettingsService = void 0;
const convertCertBufferToPEM_js_1 = require("../helpers/convertCertBufferToPEM.js");
const android_safetynet_js_1 = require("./defaultRootCerts/android-safetynet.js");
const android_key_js_1 = require("./defaultRootCerts/android-key.js");
const apple_js_1 = require("./defaultRootCerts/apple.js");
const mds_js_1 = require("./defaultRootCerts/mds.js");
class BaseSettingsService {
constructor() {
// Certificates are stored as PEM-formatted strings
Object.defineProperty(this, "pemCertificates", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
this.pemCertificates = new Map();
}
setRootCertificates(opts) {
const { identifier, certificates } = opts;
const newCertificates = [];
for (const cert of certificates) {
if (cert instanceof Uint8Array) {
newCertificates.push((0, convertCertBufferToPEM_js_1.convertCertBufferToPEM)(cert));
}
else {
newCertificates.push(cert);
}
}
this.pemCertificates.set(identifier, newCertificates);
}
getRootCertificates(opts) {
const { identifier } = opts;
return this.pemCertificates.get(identifier) ?? [];
}
}
/**
* A basic service for specifying acceptable root certificates for all supported attestation
* statement formats.
*
* In addition, default root certificates are included for the following statement formats:
*
* - `'android-key'`
* - `'android-safetynet'`
* - `'apple'`
* - `'android-mds'`
*
* These can be overwritten as needed by setting alternative root certificates for their format
* identifier using `setRootCertificates()`.
*/
exports.SettingsService = new BaseSettingsService();
// Initialize default certificates
exports.SettingsService.setRootCertificates({
identifier: 'android-key',
certificates: [
android_key_js_1.Google_Hardware_Attestation_Root_1,
android_key_js_1.Google_Hardware_Attestation_Root_2,
android_key_js_1.Google_Hardware_Attestation_Root_3,
android_key_js_1.Google_Hardware_Attestation_Root_4,
],
});
exports.SettingsService.setRootCertificates({
identifier: 'android-safetynet',
certificates: [android_safetynet_js_1.GlobalSign_Root_CA],
});
exports.SettingsService.setRootCertificates({
identifier: 'apple',
certificates: [apple_js_1.Apple_WebAuthn_Root_CA],
});
exports.SettingsService.setRootCertificates({
identifier: 'mds',
certificates: [mds_js_1.GlobalSign_Root_CA_R3],
});
@@ -0,0 +1,54 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports._getWebCryptoInternals = exports.MissingWebCrypto = void 0;
exports.getWebCrypto = getWebCrypto;
let webCrypto = undefined;
/**
* Try to get an instance of the Crypto API from the current runtime. Should support Node,
* as well as others, like Deno, that implement Web APIs.
*/
function getWebCrypto() {
/**
* Hello there! If you came here wondering why this method is asynchronous when use of
* `globalThis.crypto` is not, it's to minimize a bunch of refactor related to making this
* synchronous. For example, `generateRegistrationOptions()` and `generateAuthenticationOptions()`
* become synchronous if we make this synchronous (since nothing else in that method is async)
* which represents a breaking API change in this library's core API.
*
* TODO: If it's after February 2025 when you read this then consider whether it still makes sense
* to keep this method asynchronous.
*/
const toResolve = new Promise((resolve, reject) => {
if (webCrypto) {
return resolve(webCrypto);
}
/**
* Naively attempt to access Crypto as a global object, which popular ESM-centric run-times
* support (and Node v20+)
*/
const _globalThisCrypto = exports._getWebCryptoInternals.stubThisGlobalThisCrypto();
if (_globalThisCrypto) {
webCrypto = _globalThisCrypto;
return resolve(webCrypto);
}
// We tried to access it both in Node and globally, so bail out
return reject(new MissingWebCrypto());
});
return toResolve;
}
class MissingWebCrypto extends Error {
constructor() {
const message = 'An instance of the Crypto API could not be located';
super(message);
this.name = 'MissingWebCrypto';
}
}
exports.MissingWebCrypto = MissingWebCrypto;
// Make it possible to stub return values during testing
exports._getWebCryptoInternals = {
stubThisGlobalThisCrypto: () => globalThis.crypto,
// Make it possible to reset the `webCrypto` at the top of the file
setCachedCrypto: (newCrypto) => {
webCrypto = newCrypto;
},
};
@@ -0,0 +1,139 @@
'use strict';var _declaredScope = require('eslint-module-utils/declaredScope');var _declaredScope2 = _interopRequireDefault(_declaredScope);
var _builder = require('../exportMap/builder');var _builder2 = _interopRequireDefault(_builder);
var _exportMap = require('../exportMap');var _exportMap2 = _interopRequireDefault(_exportMap);
var _docsUrl = require('../docsUrl');var _docsUrl2 = _interopRequireDefault(_docsUrl);function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { 'default': obj };}
function message(deprecation) {
return 'Deprecated' + (deprecation.description ? ': ' + String(deprecation.description) : '.');
}
function getDeprecation(metadata) {
if (!metadata || !metadata.doc) {return;}
return metadata.doc.tags.find(function (t) {return t.title === 'deprecated';});
}
module.exports = {
meta: {
type: 'suggestion',
docs: {
category: 'Helpful warnings',
description: 'Forbid imported names marked with `@deprecated` documentation tag.',
url: (0, _docsUrl2['default'])('no-deprecated') },
schema: [] },
create: function () {function create(context) {
var deprecated = new Map();
var namespaces = new Map();
function checkSpecifiers(node) {
if (node.type !== 'ImportDeclaration') {return;}
if (node.source == null) {return;} // local export, ignore
var imports = _builder2['default'].get(node.source.value, context);
if (imports == null) {return;}
var moduleDeprecation = imports.doc && imports.doc.tags.find(function (t) {return t.title === 'deprecated';});
if (moduleDeprecation) {
context.report({ node: node, message: message(moduleDeprecation) });
}
if (imports.errors.length) {
imports.reportErrors(context, node);
return;
}
node.specifiers.forEach(function (im) {
var imported = void 0;var local = void 0;
switch (im.type) {
case 'ImportNamespaceSpecifier':{
if (!imports.size) {return;}
namespaces.set(im.local.name, imports);
return;
}
case 'ImportDefaultSpecifier':
imported = 'default';
local = im.local.name;
break;
case 'ImportSpecifier':
imported = im.imported.name;
local = im.local.name;
break;
default:return; // can't handle this one
}
// unknown thing can't be deprecated
var exported = imports.get(imported);
if (exported == null) {return;}
// capture import of deep namespace
if (exported.namespace) {namespaces.set(local, exported.namespace);}
var deprecation = getDeprecation(imports.get(imported));
if (!deprecation) {return;}
context.report({ node: im, message: message(deprecation) });
deprecated.set(local, deprecation);
});
}
return {
Program: function () {function Program(_ref) {var body = _ref.body;return body.forEach(checkSpecifiers);}return Program;}(),
Identifier: function () {function Identifier(node) {
if (node.parent.type === 'MemberExpression' && node.parent.property === node) {
return; // handled by MemberExpression
}
// ignore specifier identifiers
if (node.parent.type.slice(0, 6) === 'Import') {return;}
if (!deprecated.has(node.name)) {return;}
if ((0, _declaredScope2['default'])(context, node.name, node) !== 'module') {return;}
context.report({
node: node,
message: message(deprecated.get(node.name)) });
}return Identifier;}(),
MemberExpression: function () {function MemberExpression(dereference) {
if (dereference.object.type !== 'Identifier') {return;}
if (!namespaces.has(dereference.object.name)) {return;}
if ((0, _declaredScope2['default'])(context, dereference.object.name, dereference) !== 'module') {return;}
// go deep
var namespace = namespaces.get(dereference.object.name);
var namepath = [dereference.object.name];
// while property is namespace and parent is member expression, keep validating
while (namespace instanceof _exportMap2['default'] && dereference.type === 'MemberExpression') {
// ignore computed parts for now
if (dereference.computed) {return;}
var metadata = namespace.get(dereference.property.name);
if (!metadata) {break;}
var deprecation = getDeprecation(metadata);
if (deprecation) {
context.report({ node: dereference.property, message: message(deprecation) });
}
// stash and pop
namepath.push(dereference.property.name);
namespace = metadata.namespace;
dereference = dereference.parent;
}
}return MemberExpression;}() };
}return create;}() };
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9ydWxlcy9uby1kZXByZWNhdGVkLmpzIl0sIm5hbWVzIjpbIm1lc3NhZ2UiLCJkZXByZWNhdGlvbiIsImRlc2NyaXB0aW9uIiwiZ2V0RGVwcmVjYXRpb24iLCJtZXRhZGF0YSIsImRvYyIsInRhZ3MiLCJmaW5kIiwidCIsInRpdGxlIiwibW9kdWxlIiwiZXhwb3J0cyIsIm1ldGEiLCJ0eXBlIiwiZG9jcyIsImNhdGVnb3J5IiwidXJsIiwic2NoZW1hIiwiY3JlYXRlIiwiY29udGV4dCIsImRlcHJlY2F0ZWQiLCJNYXAiLCJuYW1lc3BhY2VzIiwiY2hlY2tTcGVjaWZpZXJzIiwibm9kZSIsInNvdXJjZSIsImltcG9ydHMiLCJFeHBvcnRNYXBCdWlsZGVyIiwiZ2V0IiwidmFsdWUiLCJtb2R1bGVEZXByZWNhdGlvbiIsInJlcG9ydCIsImVycm9ycyIsImxlbmd0aCIsInJlcG9ydEVycm9ycyIsInNwZWNpZmllcnMiLCJmb3JFYWNoIiwiaW0iLCJpbXBvcnRlZCIsImxvY2FsIiwic2l6ZSIsInNldCIsIm5hbWUiLCJleHBvcnRlZCIsIm5hbWVzcGFjZSIsIlByb2dyYW0iLCJib2R5IiwiSWRlbnRpZmllciIsInBhcmVudCIsInByb3BlcnR5Iiwic2xpY2UiLCJoYXMiLCJNZW1iZXJFeHByZXNzaW9uIiwiZGVyZWZlcmVuY2UiLCJvYmplY3QiLCJuYW1lcGF0aCIsIkV4cG9ydE1hcCIsImNvbXB1dGVkIiwicHVzaCJdLCJtYXBwaW5ncyI6ImFBQUEsa0U7QUFDQSwrQztBQUNBLHlDO0FBQ0EscUM7O0FBRUEsU0FBU0EsT0FBVCxDQUFpQkMsV0FBakIsRUFBOEI7QUFDNUIseUJBQW9CQSxZQUFZQyxXQUFaLGlCQUErQkQsWUFBWUMsV0FBM0MsSUFBMkQsR0FBL0U7QUFDRDs7QUFFRCxTQUFTQyxjQUFULENBQXdCQyxRQUF4QixFQUFrQztBQUNoQyxNQUFJLENBQUNBLFFBQUQsSUFBYSxDQUFDQSxTQUFTQyxHQUEzQixFQUFnQyxDQUFFLE9BQVM7O0FBRTNDLFNBQU9ELFNBQVNDLEdBQVQsQ0FBYUMsSUFBYixDQUFrQkMsSUFBbEIsQ0FBdUIsVUFBQ0MsQ0FBRCxVQUFPQSxFQUFFQyxLQUFGLEtBQVksWUFBbkIsRUFBdkIsQ0FBUDtBQUNEOztBQUVEQyxPQUFPQyxPQUFQLEdBQWlCO0FBQ2ZDLFFBQU07QUFDSkMsVUFBTSxZQURGO0FBRUpDLFVBQU07QUFDSkMsZ0JBQVUsa0JBRE47QUFFSmIsbUJBQWEsb0VBRlQ7QUFHSmMsV0FBSywwQkFBUSxlQUFSLENBSEQsRUFGRjs7QUFPSkMsWUFBUSxFQVBKLEVBRFM7OztBQVdmQyxRQVhlLCtCQVdSQyxPQVhRLEVBV0M7QUFDZCxVQUFNQyxhQUFhLElBQUlDLEdBQUosRUFBbkI7QUFDQSxVQUFNQyxhQUFhLElBQUlELEdBQUosRUFBbkI7O0FBRUEsZUFBU0UsZUFBVCxDQUF5QkMsSUFBekIsRUFBK0I7QUFDN0IsWUFBSUEsS0FBS1gsSUFBTCxLQUFjLG1CQUFsQixFQUF1QyxDQUFFLE9BQVM7QUFDbEQsWUFBSVcsS0FBS0MsTUFBTCxJQUFlLElBQW5CLEVBQXlCLENBQUUsT0FBUyxDQUZQLENBRVE7O0FBRXJDLFlBQU1DLFVBQVVDLHFCQUFpQkMsR0FBakIsQ0FBcUJKLEtBQUtDLE1BQUwsQ0FBWUksS0FBakMsRUFBd0NWLE9BQXhDLENBQWhCO0FBQ0EsWUFBSU8sV0FBVyxJQUFmLEVBQXFCLENBQUUsT0FBUzs7QUFFaEMsWUFBTUksb0JBQW9CSixRQUFRckIsR0FBUixJQUFlcUIsUUFBUXJCLEdBQVIsQ0FBWUMsSUFBWixDQUFpQkMsSUFBakIsQ0FBc0IsVUFBQ0MsQ0FBRCxVQUFPQSxFQUFFQyxLQUFGLEtBQVksWUFBbkIsRUFBdEIsQ0FBekM7QUFDQSxZQUFJcUIsaUJBQUosRUFBdUI7QUFDckJYLGtCQUFRWSxNQUFSLENBQWUsRUFBRVAsVUFBRixFQUFReEIsU0FBU0EsUUFBUThCLGlCQUFSLENBQWpCLEVBQWY7QUFDRDs7QUFFRCxZQUFJSixRQUFRTSxNQUFSLENBQWVDLE1BQW5CLEVBQTJCO0FBQ3pCUCxrQkFBUVEsWUFBUixDQUFxQmYsT0FBckIsRUFBOEJLLElBQTlCO0FBQ0E7QUFDRDs7QUFFREEsYUFBS1csVUFBTCxDQUFnQkMsT0FBaEIsQ0FBd0IsVUFBVUMsRUFBVixFQUFjO0FBQ3BDLGNBQUlDLGlCQUFKLENBQWMsSUFBSUMsY0FBSjtBQUNkLGtCQUFRRixHQUFHeEIsSUFBWDs7QUFFRSxpQkFBSywwQkFBTCxDQUFpQztBQUMvQixvQkFBSSxDQUFDYSxRQUFRYyxJQUFiLEVBQW1CLENBQUUsT0FBUztBQUM5QmxCLDJCQUFXbUIsR0FBWCxDQUFlSixHQUFHRSxLQUFILENBQVNHLElBQXhCLEVBQThCaEIsT0FBOUI7QUFDQTtBQUNEOztBQUVELGlCQUFLLHdCQUFMO0FBQ0VZLHlCQUFXLFNBQVg7QUFDQUMsc0JBQVFGLEdBQUdFLEtBQUgsQ0FBU0csSUFBakI7QUFDQTs7QUFFRixpQkFBSyxpQkFBTDtBQUNFSix5QkFBV0QsR0FBR0MsUUFBSCxDQUFZSSxJQUF2QjtBQUNBSCxzQkFBUUYsR0FBR0UsS0FBSCxDQUFTRyxJQUFqQjtBQUNBOztBQUVGLG9CQUFTLE9BbEJYLENBa0JtQjtBQWxCbkI7O0FBcUJBO0FBQ0EsY0FBTUMsV0FBV2pCLFFBQVFFLEdBQVIsQ0FBWVUsUUFBWixDQUFqQjtBQUNBLGNBQUlLLFlBQVksSUFBaEIsRUFBc0IsQ0FBRSxPQUFTOztBQUVqQztBQUNBLGNBQUlBLFNBQVNDLFNBQWIsRUFBd0IsQ0FBRXRCLFdBQVdtQixHQUFYLENBQWVGLEtBQWYsRUFBc0JJLFNBQVNDLFNBQS9CLEVBQTRDOztBQUV0RSxjQUFNM0MsY0FBY0UsZUFBZXVCLFFBQVFFLEdBQVIsQ0FBWVUsUUFBWixDQUFmLENBQXBCO0FBQ0EsY0FBSSxDQUFDckMsV0FBTCxFQUFrQixDQUFFLE9BQVM7O0FBRTdCa0Isa0JBQVFZLE1BQVIsQ0FBZSxFQUFFUCxNQUFNYSxFQUFSLEVBQVlyQyxTQUFTQSxRQUFRQyxXQUFSLENBQXJCLEVBQWY7O0FBRUFtQixxQkFBV3FCLEdBQVgsQ0FBZUYsS0FBZixFQUFzQnRDLFdBQXRCOztBQUVELFNBckNEO0FBc0NEOztBQUVELGFBQU87QUFDTDRDLDhCQUFTLDRCQUFHQyxJQUFILFFBQUdBLElBQUgsUUFBY0EsS0FBS1YsT0FBTCxDQUFhYixlQUFiLENBQWQsRUFBVCxrQkFESzs7QUFHTHdCLGtCQUhLLG1DQUdNdkIsSUFITixFQUdZO0FBQ2YsZ0JBQUlBLEtBQUt3QixNQUFMLENBQVluQyxJQUFaLEtBQXFCLGtCQUFyQixJQUEyQ1csS0FBS3dCLE1BQUwsQ0FBWUMsUUFBWixLQUF5QnpCLElBQXhFLEVBQThFO0FBQzVFLHFCQUQ0RSxDQUNwRTtBQUNUOztBQUVEO0FBQ0EsZ0JBQUlBLEtBQUt3QixNQUFMLENBQVluQyxJQUFaLENBQWlCcUMsS0FBakIsQ0FBdUIsQ0FBdkIsRUFBMEIsQ0FBMUIsTUFBaUMsUUFBckMsRUFBK0MsQ0FBRSxPQUFTOztBQUUxRCxnQkFBSSxDQUFDOUIsV0FBVytCLEdBQVgsQ0FBZTNCLEtBQUtrQixJQUFwQixDQUFMLEVBQWdDLENBQUUsT0FBUzs7QUFFM0MsZ0JBQUksZ0NBQWN2QixPQUFkLEVBQXVCSyxLQUFLa0IsSUFBNUIsRUFBa0NsQixJQUFsQyxNQUE0QyxRQUFoRCxFQUEwRCxDQUFFLE9BQVM7QUFDckVMLG9CQUFRWSxNQUFSLENBQWU7QUFDYlAsd0JBRGE7QUFFYnhCLHVCQUFTQSxRQUFRb0IsV0FBV1EsR0FBWCxDQUFlSixLQUFLa0IsSUFBcEIsQ0FBUixDQUZJLEVBQWY7O0FBSUQsV0FsQkk7O0FBb0JMVSx3QkFwQksseUNBb0JZQyxXQXBCWixFQW9CeUI7QUFDNUIsZ0JBQUlBLFlBQVlDLE1BQVosQ0FBbUJ6QyxJQUFuQixLQUE0QixZQUFoQyxFQUE4QyxDQUFFLE9BQVM7QUFDekQsZ0JBQUksQ0FBQ1MsV0FBVzZCLEdBQVgsQ0FBZUUsWUFBWUMsTUFBWixDQUFtQlosSUFBbEMsQ0FBTCxFQUE4QyxDQUFFLE9BQVM7O0FBRXpELGdCQUFJLGdDQUFjdkIsT0FBZCxFQUF1QmtDLFlBQVlDLE1BQVosQ0FBbUJaLElBQTFDLEVBQWdEVyxXQUFoRCxNQUFpRSxRQUFyRSxFQUErRSxDQUFFLE9BQVM7O0FBRTFGO0FBQ0EsZ0JBQUlULFlBQVl0QixXQUFXTSxHQUFYLENBQWV5QixZQUFZQyxNQUFaLENBQW1Line truncated
@@ -0,0 +1 @@
{"version":3,"names":["_caching","require","fs","_fs2","data","makeStaticFileCache","fn","makeStrongCache","filepath","cache","cached","invalidate","fileMtime","readFile","nodeFs","existsSync","statSync","mtime","e","code"],"sources":["../../../src/config/files/utils.ts"],"sourcesContent":["import type { Handler } from \"gensync\";\n\nimport { makeStrongCache } from \"../caching.ts\";\nimport type { CacheConfigurator } from \"../caching.ts\";\nimport * as fs from \"../../gensync-utils/fs.ts\";\nimport nodeFs from \"node:fs\";\n\nexport function makeStaticFileCache<T>(\n fn: (filepath: string, contents: string) => T,\n) {\n return makeStrongCache(function* (\n filepath: string,\n cache: CacheConfigurator<void>,\n ): Handler<null | T> {\n const cached = cache.invalidate(() => fileMtime(filepath));\n\n if (cached === null) {\n return null;\n }\n\n return fn(filepath, yield* fs.readFile(filepath, \"utf8\"));\n });\n}\n\nfunction fileMtime(filepath: string): number | null {\n if (!nodeFs.existsSync(filepath)) return null;\n\n try {\n return +nodeFs.statSync(filepath).mtime;\n } catch (e) {\n if (e.code !== \"ENOENT\" && e.code !== \"ENOTDIR\") throw e;\n }\n\n return null;\n}\n"],"mappings":";;;;;;AAEA,IAAAA,QAAA,GAAAC,OAAA;AAEA,IAAAC,EAAA,GAAAD,OAAA;AACA,SAAAE,KAAA;EAAA,MAAAC,IAAA,GAAAH,OAAA;EAAAE,IAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AAEO,SAASC,mBAAmBA,CACjCC,EAA6C,EAC7C;EACA,OAAO,IAAAC,wBAAe,EAAC,WACrBC,QAAgB,EAChBC,KAA8B,EACX;IACnB,MAAMC,MAAM,GAAGD,KAAK,CAACE,UAAU,CAAC,MAAMC,SAAS,CAACJ,QAAQ,CAAC,CAAC;IAE1D,IAAIE,MAAM,KAAK,IAAI,EAAE;MACnB,OAAO,IAAI;IACb;IAEA,OAAOJ,EAAE,CAACE,QAAQ,EAAE,OAAON,EAAE,CAACW,QAAQ,CAACL,QAAQ,EAAE,MAAM,CAAC,CAAC;EAC3D,CAAC,CAAC;AACJ;AAEA,SAASI,SAASA,CAACJ,QAAgB,EAAiB;EAClD,IAAI,CAACM,KAAKA,CAAC,CAACC,UAAU,CAACP,QAAQ,CAAC,EAAE,OAAO,IAAI;EAE7C,IAAI;IACF,OAAO,CAACM,KAAKA,CAAC,CAACE,QAAQ,CAACR,QAAQ,CAAC,CAACS,KAAK;EACzC,CAAC,CAAC,OAAOC,CAAC,EAAE;IACV,IAAIA,CAAC,CAACC,IAAI,KAAK,QAAQ,IAAID,CAAC,CAACC,IAAI,KAAK,SAAS,EAAE,MAAMD,CAAC;EAC1D;EAEA,OAAO,IAAI;AACb;AAAC","ignoreList":[]}
@@ -0,0 +1,603 @@
/**
* @fileoverview Rule to flag constant comparisons and logical expressions that always/never short circuit
* @author Jordan Eldredge <https://jordaneldredge.com>
*/
"use strict";
const {
isNullLiteral,
isConstant,
isReferenceToGlobalVariable,
isLogicalAssignmentOperator,
ECMASCRIPT_GLOBALS,
} = require("./utils/ast-utils");
const NUMERIC_OR_STRING_BINARY_OPERATORS = new Set([
"+",
"-",
"*",
"/",
"%",
"|",
"^",
"&",
"**",
"<<",
">>",
">>>",
]);
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
/**
* Checks whether or not a node is `null` or `undefined`. Similar to the one
* found in ast-utils.js, but this one correctly handles the edge case that
* `undefined` has been redefined.
* @param {Scope} scope Scope in which the expression was found.
* @param {ASTNode} node A node to check.
* @returns {boolean} Whether or not the node is a `null` or `undefined`.
* @public
*/
function isNullOrUndefined(scope, node) {
return (
isNullLiteral(node) ||
(node.type === "Identifier" &&
node.name === "undefined" &&
isReferenceToGlobalVariable(scope, node)) ||
(node.type === "UnaryExpression" && node.operator === "void")
);
}
/**
* Test if an AST node has a statically knowable constant nullishness. Meaning,
* it will always resolve to a constant value of either: `null`, `undefined`
* or not `null` _or_ `undefined`. An expression that can vary between those
* three states at runtime would return `false`.
* @param {Scope} scope The scope in which the node was found.
* @param {ASTNode} node The AST node being tested.
* @param {boolean} nonNullish if `true` then nullish values are not considered constant.
* @returns {boolean} Does `node` have constant nullishness?
*/
function hasConstantNullishness(scope, node, nonNullish) {
if (nonNullish && isNullOrUndefined(scope, node)) {
return false;
}
switch (node.type) {
case "ObjectExpression": // Objects are never nullish
case "ArrayExpression": // Arrays are never nullish
case "ArrowFunctionExpression": // Functions never nullish
case "FunctionExpression": // Functions are never nullish
case "ClassExpression": // Classes are never nullish
case "NewExpression": // Objects are never nullish
case "Literal": // Nullish, or non-nullish, literals never change
case "TemplateLiteral": // A string is never nullish
case "UpdateExpression": // Numbers are never nullish
case "BinaryExpression": // Numbers, strings, or booleans are never nullish
return true;
case "CallExpression": {
if (node.callee.type !== "Identifier") {
return false;
}
const functionName = node.callee.name;
return (
(functionName === "Boolean" ||
functionName === "String" ||
functionName === "Number") &&
isReferenceToGlobalVariable(scope, node.callee)
);
}
case "LogicalExpression": {
return (
node.operator === "??" &&
hasConstantNullishness(scope, node.right, true)
);
}
case "AssignmentExpression":
if (node.operator === "=") {
return hasConstantNullishness(scope, node.right, nonNullish);
}
/*
* Handling short-circuiting assignment operators would require
* walking the scope. We won't attempt that (for now...) /
*/
if (isLogicalAssignmentOperator(node.operator)) {
return false;
}
/*
* The remaining assignment expressions all result in a numeric or
* string (non-nullish) value:
* "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=", "|=", "^=", "&="
*/
return true;
case "UnaryExpression":
/*
* "void" Always returns `undefined`
* "typeof" All types are strings, and thus non-nullish
* "!" Boolean is never nullish
* "delete" Returns a boolean, which is never nullish
* Math operators always return numbers or strings, neither of which
* are non-nullish "+", "-", "~"
*/
return true;
case "SequenceExpression": {
const last = node.expressions.at(-1);
return hasConstantNullishness(scope, last, nonNullish);
}
case "Identifier":
return (
node.name === "undefined" &&
isReferenceToGlobalVariable(scope, node)
);
case "JSXElement": // ESLint has a policy of not assuming any specific JSX behavior.
case "JSXFragment":
return false;
default:
return false;
}
}
/**
* Test if an AST node is a boolean value that never changes. Specifically we
* test for:
* 1. Literal booleans (`true` or `false`)
* 2. Unary `!` expressions with a constant value
* 3. Constant booleans created via the `Boolean` global function
* @param {Scope} scope The scope in which the node was found.
* @param {ASTNode} node The node to test
* @returns {boolean} Is `node` guaranteed to be a boolean?
*/
function isStaticBoolean(scope, node) {
switch (node.type) {
case "Literal":
return typeof node.value === "boolean";
case "CallExpression":
return (
node.callee.type === "Identifier" &&
node.callee.name === "Boolean" &&
isReferenceToGlobalVariable(scope, node.callee) &&
(node.arguments.length === 0 ||
isConstant(scope, node.arguments[0], true))
);
case "UnaryExpression":
return (
node.operator === "!" && isConstant(scope, node.argument, true)
);
default:
return false;
}
}
/**
* Test if an AST node will always give the same result when compared to a
* boolean value. Note that comparison to boolean values is different than
* truthiness.
* https://262.ecma-international.org/5.1/#sec-11.9.3
*
* JavaScript `==` operator works by converting the boolean to `1` (true) or
* `+0` (false) and then checks the values `==` equality to that number.
* @param {Scope} scope The scope in which node was found.
* @param {ASTNode} node The node to test.
* @returns {boolean} Will `node` always coerce to the same boolean value?
*/
function hasConstantLooseBooleanComparison(scope, node) {
switch (node.type) {
case "ObjectExpression":
case "ClassExpression":
/**
* In theory objects like:
*
* `{toString: () => a}`
* `{valueOf: () => a}`
*
* Or a classes like:
*
* `class { static toString() { return a } }`
* `class { static valueOf() { return a } }`
*
* Are not constant verifiably when `inBooleanPosition` is
* false, but it's an edge case we've opted not to handle.
*/
return true;
case "ArrayExpression": {
const nonSpreadElements = node.elements.filter(
e =>
// Elements can be `null` in sparse arrays: `[,,]`;
e !== null && e.type !== "SpreadElement",
);
/*
* Possible future direction if needed: We could check if the
* single value would result in variable boolean comparison.
* For now we will err on the side of caution since `[x]` could
* evaluate to `[0]` or `[1]`.
*/
return node.elements.length === 0 || nonSpreadElements.length > 1;
}
case "ArrowFunctionExpression":
case "FunctionExpression":
return true;
case "UnaryExpression":
if (
node.operator === "void" || // Always returns `undefined`
node.operator === "typeof" // All `typeof` strings, when coerced to number, are not 0 or 1.
) {
return true;
}
if (node.operator === "!") {
return isConstant(scope, node.argument, true);
}
/*
* We won't try to reason about +, -, ~, or delete
* In theory, for the mathematical operators, we could look at the
* argument and try to determine if it coerces to a constant numeric
* value.
*/
return false;
case "NewExpression": // Objects might have custom `.valueOf` or `.toString`.
return false;
case "CallExpression": {
if (
node.callee.type === "Identifier" &&
node.callee.name === "Boolean" &&
isReferenceToGlobalVariable(scope, node.callee)
) {
return (
node.arguments.length === 0 ||
isConstant(scope, node.arguments[0], true)
);
}
return false;
}
case "Literal": // True or false, literals never change
return true;
case "Identifier":
return (
node.name === "undefined" &&
isReferenceToGlobalVariable(scope, node)
);
case "TemplateLiteral":
/*
* In theory we could try to check if the quasi are sufficient to
* prove that the expression will always be true, but it would be
* tricky to get right. For example: `000.${foo}000`
*/
return node.expressions.length === 0;
case "AssignmentExpression":
if (node.operator === "=") {
return hasConstantLooseBooleanComparison(scope, node.right);
}
/*
* Handling short-circuiting assignment operators would require
* walking the scope. We won't attempt that (for now...)
*
* The remaining assignment expressions all result in a numeric or
* string (non-nullish) values which could be truthy or falsy:
* "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=", "|=", "^=", "&="
*/
return false;
case "SequenceExpression": {
const last = node.expressions.at(-1);
return hasConstantLooseBooleanComparison(scope, last);
}
case "JSXElement": // ESLint has a policy of not assuming any specific JSX behavior.
case "JSXFragment":
return false;
default:
return false;
}
}
/**
* Test if an AST node will always give the same result when _strictly_ compared
* to a boolean value. This can happen if the expression can never be boolean, or
* if it is always the same boolean value.
* @param {Scope} scope The scope in which the node was found.
* @param {ASTNode} node The node to test
* @returns {boolean} Will `node` always give the same result when compared to a
* static boolean value?
*/
function hasConstantStrictBooleanComparison(scope, node) {
switch (node.type) {
case "ObjectExpression": // Objects are not booleans
case "ArrayExpression": // Arrays are not booleans
case "ArrowFunctionExpression": // Functions are not booleans
case "FunctionExpression":
case "ClassExpression": // Classes are not booleans
case "NewExpression": // Objects are not booleans
case "TemplateLiteral": // Strings are not booleans
case "Literal": // True, false, or not boolean, literals never change.
case "UpdateExpression": // Numbers are not booleans
return true;
case "BinaryExpression":
return NUMERIC_OR_STRING_BINARY_OPERATORS.has(node.operator);
case "UnaryExpression": {
if (node.operator === "delete") {
return false;
}
if (node.operator === "!") {
return isConstant(scope, node.argument, true);
}
/*
* The remaining operators return either strings or numbers, neither
* of which are boolean.
*/
return true;
}
case "SequenceExpression": {
const last = node.expressions.at(-1);
return hasConstantStrictBooleanComparison(scope, last);
}
case "Identifier":
return (
node.name === "undefined" &&
isReferenceToGlobalVariable(scope, node)
);
case "AssignmentExpression":
if (node.operator === "=") {
return hasConstantStrictBooleanComparison(scope, node.right);
}
/*
* Handling short-circuiting assignment operators would require
* walking the scope. We won't attempt that (for now...)
*/
if (isLogicalAssignmentOperator(node.operator)) {
return false;
}
/*
* The remaining assignment expressions all result in either a number
* or a string, neither of which can ever be boolean.
*/
return true;
case "CallExpression": {
if (node.callee.type !== "Identifier") {
return false;
}
const functionName = node.callee.name;
if (
(functionName === "String" || functionName === "Number") &&
isReferenceToGlobalVariable(scope, node.callee)
) {
return true;
}
if (
functionName === "Boolean" &&
isReferenceToGlobalVariable(scope, node.callee)
) {
return (
node.arguments.length === 0 ||
isConstant(scope, node.arguments[0], true)
);
}
return false;
}
case "JSXElement": // ESLint has a policy of not assuming any specific JSX behavior.
case "JSXFragment":
return false;
default:
return false;
}
}
/**
* Test if an AST node will always result in a newly constructed object
* @param {Scope} scope The scope in which the node was found.
* @param {ASTNode} node The node to test
* @returns {boolean} Will `node` always be new?
*/
function isAlwaysNew(scope, node) {
switch (node.type) {
case "ObjectExpression":
case "ArrayExpression":
case "ArrowFunctionExpression":
case "FunctionExpression":
case "ClassExpression":
return true;
case "NewExpression": {
if (node.callee.type !== "Identifier") {
return false;
}
/*
* All the built-in constructors are always new, but
* user-defined constructors could return a sentinel
* object.
*
* Catching these is especially useful for primitive constructors
* which return boxed values, a surprising gotcha' in JavaScript.
*/
return (
Object.hasOwn(ECMASCRIPT_GLOBALS, node.callee.name) &&
isReferenceToGlobalVariable(scope, node.callee)
);
}
case "Literal":
// Regular expressions are objects, and thus always new
return typeof node.regex === "object";
case "SequenceExpression": {
const last = node.expressions.at(-1);
return isAlwaysNew(scope, last);
}
case "AssignmentExpression":
if (node.operator === "=") {
return isAlwaysNew(scope, node.right);
}
return false;
case "ConditionalExpression":
return (
isAlwaysNew(scope, node.consequent) &&
isAlwaysNew(scope, node.alternate)
);
case "JSXElement": // ESLint has a policy of not assuming any specific JSX behavior.
case "JSXFragment":
return false;
default:
return false;
}
}
/**
* Checks if one operand will cause the result to be constant.
* @param {Scope} scope Scope in which the expression was found.
* @param {ASTNode} a One side of the expression
* @param {ASTNode} b The other side of the expression
* @param {string} operator The binary expression operator
* @returns {ASTNode | null} The node which will cause the expression to have a constant result.
*/
function findBinaryExpressionConstantOperand(scope, a, b, operator) {
if (operator === "==" || operator === "!=") {
if (
(isNullOrUndefined(scope, a) &&
hasConstantNullishness(scope, b, false)) ||
(isStaticBoolean(scope, a) &&
hasConstantLooseBooleanComparison(scope, b))
) {
return b;
}
} else if (operator === "===" || operator === "!==") {
if (
(isNullOrUndefined(scope, a) &&
hasConstantNullishness(scope, b, false)) ||
(isStaticBoolean(scope, a) &&
hasConstantStrictBooleanComparison(scope, b))
) {
return b;
}
}
return null;
}
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
type: "problem",
docs: {
description:
"Disallow expressions where the operation doesn't affect the value",
recommended: true,
url: "https://eslint.org/docs/latest/rules/no-constant-binary-expression",
},
schema: [],
messages: {
constantBinaryOperand:
"Unexpected constant binary expression. Compares constantly with the {{otherSide}}-hand side of the `{{operator}}`.",
constantShortCircuit:
"Unexpected constant {{property}} on the left-hand side of a `{{operator}}` expression.",
alwaysNew:
"Unexpected comparison to newly constructed object. These two values can never be equal.",
bothAlwaysNew:
"Unexpected comparison of two newly constructed objects. These two values can never be equal.",
},
},
create(context) {
const sourceCode = context.sourceCode;
return {
LogicalExpression(node) {
const { operator, left } = node;
const scope = sourceCode.getScope(node);
if (
(operator === "&&" || operator === "||") &&
isConstant(scope, left, true)
) {
context.report({
node: left,
messageId: "constantShortCircuit",
data: { property: "truthiness", operator },
});
} else if (
operator === "??" &&
hasConstantNullishness(scope, left, false)
) {
context.report({
node: left,
messageId: "constantShortCircuit",
data: { property: "nullishness", operator },
});
}
},
BinaryExpression(node) {
const scope = sourceCode.getScope(node);
const { right, left, operator } = node;
const rightConstantOperand =
findBinaryExpressionConstantOperand(
scope,
left,
right,
operator,
);
const leftConstantOperand = findBinaryExpressionConstantOperand(
scope,
right,
left,
operator,
);
if (rightConstantOperand) {
context.report({
node: rightConstantOperand,
messageId: "constantBinaryOperand",
data: { operator, otherSide: "left" },
});
} else if (leftConstantOperand) {
context.report({
node: leftConstantOperand,
messageId: "constantBinaryOperand",
data: { operator, otherSide: "right" },
});
} else if (operator === "===" || operator === "!==") {
if (isAlwaysNew(scope, left)) {
context.report({ node: left, messageId: "alwaysNew" });
} else if (isAlwaysNew(scope, right)) {
context.report({ node: right, messageId: "alwaysNew" });
}
} else if (operator === "==" || operator === "!=") {
/*
* If both sides are "new", then both sides are objects and
* therefore they will be compared by reference even with `==`
* equality.
*/
if (isAlwaysNew(scope, left) && isAlwaysNew(scope, right)) {
context.report({
node: left,
messageId: "bothAlwaysNew",
});
}
}
},
/*
* In theory we could handle short-circuiting assignment operators,
* for some constant values, but that would require walking the
* scope to find the value of the variable being assigned. This is
* dependent on https://github.com/eslint/eslint/issues/13776
*
* AssignmentExpression() {},
*/
};
},
};
@@ -0,0 +1,31 @@
/**
* Formats a date according to the specified format string.
* 根据指定的格式字符串格式化日期。
*
* @param date - The date to format. (要格式化的日期。)
* @param formatString - The format string to use. (要使用的格式字符串。)
* @returns The formatted date string. (格式化后的日期字符串。)
* @example
* ```ts
* // Formatting a date with 'YYYY-MM-DD' format (使用 'YYYY-MM-DD' 格式格式化日期)
* const date1 = new Date('2023-10-01T12:00:00');
* const formattedDate1 = format(date1, 'YYYY-MM-DD');
* console.log(formattedDate1); // Outputs: '2023-10-01' (输出: '2023-10-01')
*
* // Formatting a date with 'YYYY-MM-DD HH:mm:ss' format (使用 'YYYY-MM-DD HH:mm:ss' 格式格式化日期)
* const date2 = new Date('2023-10-01T12:30:45');
* const formattedDate2 = format(date2, 'YYYY-MM-DD HH:mm:ss');
* console.log(formattedDate2); // Outputs: '2023-10-01 12:30:45' (输出: '2023-10-01 12:30:45')
*
* // Formatting a date with 'YYYY-MM-DDTHH:mm:ssZ' format (使用 'YYYY-MM-DDTHH:mm:ssZ' 格式格式化日期)
* const date3 = new Date('2023-10-01T12:30:45');
* const formattedDate3 = format(date3, 'YYYY-MM-DDTHH:mm:ssZ');
* console.log(formattedDate3); // Outputs: '2023-10-01T12:30:45-04:00' (输出: '2023-10-01T12:30:45-04:00')
*
* // Using 'ISO' format (使用 'ISO' 格式)
* const date4 = new Date('2023-10-01T12:30:45');
* const formattedDate4 = format(date4, 'ISO');
* console.log(formattedDate4); // Outputs: '2023-10-01T16:30:45.000Z' (输出: '2023-10-01T16:30:45.000Z')
* ```
*/
export default function format(date: Date, formatString?: string): string;
@@ -0,0 +1,40 @@
/**
* @author Toru Nagashima <https://github.com/mysticatea>
* See LICENSE file in root directory for full license.
*/
"use strict"
const {
definePrototypeMethodHandler,
} = require("../util/define-prototype-method-handler")
module.exports = {
meta: {
docs: {
description:
"disallow the `Symbol.prototype.description` property.",
category: "ES2019",
recommended: false,
url: "http://eslint-community.github.io/eslint-plugin-es-x/rules/no-symbol-prototype-description.html",
},
fixable: null,
messages: {
forbidden: "ES2019 '{{name}}' property is forbidden.",
},
schema: [
{
type: "object",
properties: {
aggressive: { type: "boolean" },
},
additionalProperties: false,
},
],
type: "problem",
},
create(context) {
return definePrototypeMethodHandler(context, {
Symbol: ["description"],
})
},
}
@@ -0,0 +1,122 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [v1.3.3](https://github.com/es-shims/Array.prototype.flatMap/compare/v1.3.2...v1.3.3) - 2024-12-15
### Commits
- [actions] split out node 10-20, and 20+ [`8727281`](https://github.com/es-shims/Array.prototype.flatMap/commit/87272812ed6ade6935c7429ee1daf1cfa54115ef)
- [Tests] add test coverage [`6e78327`](https://github.com/es-shims/Array.prototype.flatMap/commit/6e7832790c36b320880f4b6d38dc31388d1fae3a)
- [Deps] update `call-bind`, `es-abstract` [`e027dd1`](https://github.com/es-shims/Array.prototype.flatMap/commit/e027dd10ee63b3c3a98cc7e6ce8ad42b1100bdc9)
- [Dev Deps] update `@es-shims/api`, `@ljharb/eslint-config`, `auto-changelog`, `object-inspect`, `tape` [`7322d84`](https://github.com/es-shims/Array.prototype.flatMap/commit/7322d841e87ab17e4b929e92e73e8a20c3daf544)
- [Dev Deps] update `aud`, `npmignore`, `object-inspect`, `tape` [`958bf5c`](https://github.com/es-shims/Array.prototype.flatMap/commit/958bf5c982cb0c4941dc2a6e873883e9f2c8d535)
- [Deps] update `call-bind`, `define-properties`, `es-abstract`, `es-shim-unscopables` [`b3698fb`](https://github.com/es-shims/Array.prototype.flatMap/commit/b3698fb2320992f5ab85a486d1adef0105f739aa)
- [Tests] replace `aud` with `npm audit` [`e0461ed`](https://github.com/es-shims/Array.prototype.flatMap/commit/e0461ed2288d37e2d878e3e64569313c04af6a64)
- [Dev Deps] add missing peer dep [`e7160b5`](https://github.com/es-shims/Array.prototype.flatMap/commit/e7160b5ef9d624300cc189696e8019adaf6d67fc)
## [v1.3.2](https://github.com/es-shims/Array.prototype.flatMap/compare/v1.3.1...v1.3.2) - 2023-09-06
### Commits
- [Deps] update `define-properties`, `es-abstract` [`1737863`](https://github.com/es-shims/Array.prototype.flatMap/commit/17378634d56fc4b75027764b54804d89c6f8d60f)
- [Dev Deps] update `@es-shims/api`, `@ljharb/eslint-config`, `aud`, `object-inspect`, `tape` [`2337759`](https://github.com/es-shims/Array.prototype.flatMap/commit/23377597983440102805d36f701408505b433ccd)
## [v1.3.1](https://github.com/es-shims/Array.prototype.flatMap/compare/v1.3.0...v1.3.1) - 2022-11-02
### Commits
- [meta] use `npmignore` to autogenerate an npmignore file [`3587a34`](https://github.com/es-shims/Array.prototype.flatMap/commit/3587a34ca111ec36ffc46b4131f5b32d4d8a357c)
- [meta] add `auto-changelog` [`d66bdea`](https://github.com/es-shims/Array.prototype.flatMap/commit/d66bdeac56f2c1803a72695230c80d8270ab2ecf)
- [Deps] update `define-properties`, `es-abstract` [`d64c486`](https://github.com/es-shims/Array.prototype.flatMap/commit/d64c48639ec4958ed9a2627a4d7315ac1404687a)
- [actions] update rebase action to use reusable workflow [`8d657d0`](https://github.com/es-shims/Array.prototype.flatMap/commit/8d657d094a2aafa7948eee73eaa0e56047c5d60d)
- [Dev Deps] update `aud`, `object-inspect`, `tape` [`aa22741`](https://github.com/es-shims/Array.prototype.flatMap/commit/aa22741a4bbe8db6d448cc4ca5417ddec90ac01d)
- [Tests] use `for-each` instead of `foreach` [`748a78d`](https://github.com/es-shims/Array.prototype.flatMap/commit/748a78dbddb08462c75916fde07746d34cfd5c5c)
<!-- auto-changelog-above -->
1.3.0 / 2022-04-11
=================
* [New] `shim`/`auto`: add `flatMap` to `Symbol.unscopables`
* [Deps] update `call-bind`, `es-abstract`
* [actions] reuse common workflows
* [actions] update codecov uploader
* [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `@es-shims/api`, `aud`, `auto-changelog`, `object-inspect`, `safe-publish-latest`, `tape`
1.2.5 / 2021-10-01
=================
* [readme] add github actions/codecov badges; update description; remove travis badge
* [Deps] update `call-bind`, `es-abstract`; remove unused `function-bind`
* [meta] use `prepublishOnly`, for npm 7+
* [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `@es-shims/api`, `aud`, `has-strict-mode`, `object-inspect`, `tape`
* [actions] update workflows
* [actions] use `node/install` instead of `node/run`; use `codecov` action
* [Tests] increase coverage
1.2.4 / 2020-11-18
=================
* [Deps] update `es-abstract`; use `call-bind` where applicable
* [meta] do not publish github action workflows
* [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `object-inspect`, `tape`; add `aud`
* [Tests] migrate tests to Github Actions
* [Tests] run `nyc` on all tests
* [Tests] add `implementation` test; run `es-shim-api` in postlint; use `tape` runner
* [actions] add "Allow Edits" workflow
* [actions] switch Automatic Rebase workflow to `pull_request_target` event
1.2.3 / 2019-12-12
=================
* [Refactor] use split-up `es-abstract` (65% bundle size decrease)
* [Deps] update `es-abstract`
* [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest`, `object-inspect`
* [meta] add `funding` field
* [Tests] use shared travis-ci configs
* [actions] add automatic rebasing / merge commit blocking
1.2.2 / 2019-10-10
=================
* [Refactor] rename callback argument to `mapperFunction`, to match spec
* [Deps] update `es-abstract`, `define-properties`
* [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `covert`, `evalmd`, `object-inspect`, `safe-publish-latest`, `tape`
* [meta] create FUNDING.yml
* [Tests] up to `node` `v12.11`, `v11.15`, `v10.16`, `v9.11`, `v8.16`, `v6.17`, `v4.9`; use `nvm install-latest-npm`
* [Tests] use `npx aud` instead of `nsp` or `npm audit` with hoops
1.2.1 / 2018-02-23
=================
* [Fix] Temporarily hack main entry, so it's compatible with other resolvers
* [Dev Deps] update `eslint`, `nsp`, `tape`
* [Tests] up to `node` `v9.6`, `v6.13`
1.2.0 / 2018-01-18
=================
* [New] add "auto" entry point
* [Fix] Move the receiver length check higher
* [Fix] spec adjustments
* [Refactor] adjust shouldFlatten logic
* [Dev Deps] update `eslint`, `object-inspect`
* [Tests] up to `node` `v9.4`
1.1.1 / 2017-11-29
=================
* [Fix] avoid an extra hole in the array (#1)
* [Deps] update `es-abstract`
* [Dev Deps] update `eslint`, `nsp`, `object-inspect`
* [Tests] up to `node` `v9.2`, `v8.9`, `v6.12`; pin included builds to LTS
1.1.0 / 2017-10-03
=================
* [New] add explicit setting of “length” on target array
* [Fix] `FlattenIntoArray`: add assertion that `thisArg` and `mapperFunction` are both passed together
* [Tests] make coverage required
1.0.1 / 2017-10-02
=================
* Add readme
1.0.0 / 2017-10-01
=================
* Initial release
@@ -0,0 +1,18 @@
import { LocaleData } from './core';
export type ListPatternLocaleData = LocaleData<ListPatternFieldsData>;
export interface ListPatternFieldsData {
conjunction?: ListPatternData;
disjunction?: ListPatternData;
unit?: ListPatternData;
}
export interface ListPattern {
start: string;
middle: string;
end: string;
pair: string;
}
export interface ListPatternData {
long: ListPattern;
short?: ListPattern;
narrow?: ListPattern;
}
@@ -0,0 +1,4 @@
import { Newable } from '@inversifyjs/common';
import { MaybeClassMetadata } from '../models/MaybeClassMetadata';
export declare function throwAtInvalidClassMetadata(type: Newable, classMetadata: MaybeClassMetadata): never;
//# sourceMappingURL=throwAtInvalidClassMetadata.d.ts.map
@@ -0,0 +1,9 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
tslib_1.__exportStar(require("./algorithms"), exports);
tslib_1.__exportStar(require("./ec_parameters"), exports);
tslib_1.__exportStar(require("./ec_private_key"), exports);
tslib_1.__exportStar(require("./ec_signature_value"), exports);
tslib_1.__exportStar(require("./object_identifiers"), exports);
tslib_1.__exportStar(require("./rfc3279"), exports);
@@ -0,0 +1,716 @@
# cacache [![npm version](https://img.shields.io/npm/v/cacache.svg)](https://npm.im/cacache) [![license](https://img.shields.io/npm/l/cacache.svg)](https://npm.im/cacache) [![Travis](https://img.shields.io/travis/npm/cacache.svg)](https://travis-ci.org/npm/cacache) [![AppVeyor](https://ci.appveyor.com/api/projects/status/github/npm/cacache?svg=true)](https://ci.appveyor.com/project/npm/cacache) [![Coverage Status](https://coveralls.io/repos/github/npm/cacache/badge.svg?branch=latest)](https://coveralls.io/github/npm/cacache?branch=latest)
[`cacache`](https://github.com/npm/cacache) is a Node.js library for managing
local key and content address caches. It's really fast, really good at
concurrency, and it will never give you corrupted data, even if cache files
get corrupted or manipulated.
On systems that support user and group settings on files, cacache will
match the `uid` and `gid` values to the folder where the cache lives, even
when running as `root`.
It was written to be used as [npm](https://npm.im)'s local cache, but can
just as easily be used on its own.
## Install
`$ npm install --save cacache`
## Table of Contents
* [Example](#example)
* [Features](#features)
* [Contributing](#contributing)
* [API](#api)
* [Using localized APIs](#localized-api)
* Reading
* [`ls`](#ls)
* [`ls.stream`](#ls-stream)
* [`get`](#get-data)
* [`get.stream`](#get-stream)
* [`get.info`](#get-info)
* [`get.hasContent`](#get-hasContent)
* Writing
* [`put`](#put-data)
* [`put.stream`](#put-stream)
* [`rm.all`](#rm-all)
* [`rm.entry`](#rm-entry)
* [`rm.content`](#rm-content)
* [`index.compact`](#index-compact)
* [`index.insert`](#index-insert)
* Utilities
* [`clearMemoized`](#clear-memoized)
* [`tmp.mkdir`](#tmp-mkdir)
* [`tmp.withTmp`](#with-tmp)
* Integrity
* [Subresource Integrity](#integrity)
* [`verify`](#verify)
* [`verify.lastRun`](#verify-last-run)
### Example
```javascript
const cacache = require('cacache')
const fs = require('fs')
const tarball = '/path/to/mytar.tgz'
const cachePath = '/tmp/my-toy-cache'
const key = 'my-unique-key-1234'
// Cache it! Use `cachePath` as the root of the content cache
cacache.put(cachePath, key, '10293801983029384').then(integrity => {
console.log(`Saved content to ${cachePath}.`)
})
const destination = '/tmp/mytar.tgz'
// Copy the contents out of the cache and into their destination!
// But this time, use stream instead!
cacache.get.stream(
cachePath, key
).pipe(
fs.createWriteStream(destination)
).on('finish', () => {
console.log('done extracting!')
})
// The same thing, but skip the key index.
cacache.get.byDigest(cachePath, integrityHash).then(data => {
fs.writeFile(destination, data, err => {
console.log('tarball data fetched based on its sha512sum and written out!')
})
})
```
### Features
* Extraction by key or by content address (shasum, etc)
* [Subresource Integrity](#integrity) web standard support
* Multi-hash support - safely host sha1, sha512, etc, in a single cache
* Automatic content deduplication
* Fault tolerance (immune to corruption, partial writes, process races, etc)
* Consistency guarantees on read and write (full data verification)
* Lockless, high-concurrency cache access
* Streaming support
* Promise support
* Fast -- sub-millisecond reads and writes including verification
* Arbitrary metadata storage
* Garbage collection and additional offline verification
* Thorough test coverage
* There's probably a bloom filter in there somewhere. Those are cool, right? 🤔
### Contributing
The cacache team enthusiastically welcomes contributions and project participation! There's a bunch of things you can do if you want to contribute! The [Contributor Guide](CONTRIBUTING.md) has all the information you need for everything from reporting bugs to contributing entire new features. Please don't hesitate to jump in if you'd like to, or even ask us questions if something isn't clear.
All participants and maintainers in this project are expected to follow [Code of Conduct](CODE_OF_CONDUCT.md), and just generally be excellent to each other.
Please refer to the [Changelog](CHANGELOG.md) for project history details, too.
Happy hacking!
### API
#### <a name="ls"></a> `> cacache.ls(cache) -> Promise<Object>`
Lists info for all entries currently in the cache as a single large object. Each
entry in the object will be keyed by the unique index key, with corresponding
[`get.info`](#get-info) objects as the values.
##### Example
```javascript
cacache.ls(cachePath).then(console.log)
// Output
{
'my-thing': {
key: 'my-thing',
integrity: 'sha512-BaSe64/EnCoDED+HAsh=='
path: '.testcache/content/deadbeef', // joined with `cachePath`
time: 12345698490,
size: 4023948,
metadata: {
name: 'blah',
version: '1.2.3',
description: 'this was once a package but now it is my-thing'
}
},
'other-thing': {
key: 'other-thing',
integrity: 'sha1-ANothER+hasH=',
path: '.testcache/content/bada55',
time: 11992309289,
size: 111112
}
}
```
#### <a name="ls-stream"></a> `> cacache.ls.stream(cache) -> Readable`
Lists info for all entries currently in the cache as a single large object.
This works just like [`ls`](#ls), except [`get.info`](#get-info) entries are
returned as `'data'` events on the returned stream.
##### Example
```javascript
cacache.ls.stream(cachePath).on('data', console.log)
// Output
{
key: 'my-thing',
integrity: 'sha512-BaSe64HaSh',
path: '.testcache/content/deadbeef', // joined with `cachePath`
time: 12345698490,
size: 13423,
metadata: {
name: 'blah',
version: '1.2.3',
description: 'this was once a package but now it is my-thing'
}
}
{
key: 'other-thing',
integrity: 'whirlpool-WoWSoMuchSupport',
path: '.testcache/content/bada55',
time: 11992309289,
size: 498023984029
}
{
...
}
```
#### <a name="get-data"></a> `> cacache.get(cache, key, [opts]) -> Promise({data, metadata, integrity})`
Returns an object with the cached data, digest, and metadata identified by
`key`. The `data` property of this object will be a `Buffer` instance that
presumably holds some data that means something to you. I'm sure you know what
to do with it! cacache just won't care.
`integrity` is a [Subresource
Integrity](#integrity)
string. That is, a string that can be used to verify `data`, which looks like
`<hash-algorithm>-<base64-integrity-hash>`.
If there is no content identified by `key`, or if the locally-stored data does
not pass the validity checksum, the promise will be rejected.
A sub-function, `get.byDigest` may be used for identical behavior, except lookup
will happen by integrity hash, bypassing the index entirely. This version of the
function *only* returns `data` itself, without any wrapper.
See: [options](#get-options)
##### Note
This function loads the entire cache entry into memory before returning it. If
you're dealing with Very Large data, consider using [`get.stream`](#get-stream)
instead.
##### Example
```javascript
// Look up by key
cache.get(cachePath, 'my-thing').then(console.log)
// Output:
{
metadata: {
thingName: 'my'
},
integrity: 'sha512-BaSe64HaSh',
data: Buffer#<deadbeef>,
size: 9320
}
// Look up by digest
cache.get.byDigest(cachePath, 'sha512-BaSe64HaSh').then(console.log)
// Output:
Buffer#<deadbeef>
```
#### <a name="get-stream"></a> `> cacache.get.stream(cache, key, [opts]) -> Readable`
Returns a [Readable Stream](https://nodejs.org/api/stream.html#stream_readable_streams) of the cached data identified by `key`.
If there is no content identified by `key`, or if the locally-stored data does
not pass the validity checksum, an error will be emitted.
`metadata` and `integrity` events will be emitted before the stream closes, if
you need to collect that extra data about the cached entry.
A sub-function, `get.stream.byDigest` may be used for identical behavior,
except lookup will happen by integrity hash, bypassing the index entirely. This
version does not emit the `metadata` and `integrity` events at all.
See: [options](#get-options)
##### Example
```javascript
// Look up by key
cache.get.stream(
cachePath, 'my-thing'
).on('metadata', metadata => {
console.log('metadata:', metadata)
}).on('integrity', integrity => {
console.log('integrity:', integrity)
}).pipe(
fs.createWriteStream('./x.tgz')
)
// Outputs:
metadata: { ... }
integrity: 'sha512-SoMeDIGest+64=='
// Look up by digest
cache.get.stream.byDigest(
cachePath, 'sha512-SoMeDIGest+64=='
).pipe(
fs.createWriteStream('./x.tgz')
)
```
#### <a name="get-info"></a> `> cacache.get.info(cache, key) -> Promise`
Looks up `key` in the cache index, returning information about the entry if
one exists.
##### Fields
* `key` - Key the entry was looked up under. Matches the `key` argument.
* `integrity` - [Subresource Integrity hash](#integrity) for the content this entry refers to.
* `path` - Filesystem path where content is stored, joined with `cache` argument.
* `time` - Timestamp the entry was first added on.
* `metadata` - User-assigned metadata associated with the entry/content.
##### Example
```javascript
cacache.get.info(cachePath, 'my-thing').then(console.log)
// Output
{
key: 'my-thing',
integrity: 'sha256-MUSTVERIFY+ALL/THINGS=='
path: '.testcache/content/deadbeef',
time: 12345698490,
size: 849234,
metadata: {
name: 'blah',
version: '1.2.3',
description: 'this was once a package but now it is my-thing'
}
}
```
#### <a name="get-hasContent"></a> `> cacache.get.hasContent(cache, integrity) -> Promise`
Looks up a [Subresource Integrity hash](#integrity) in the cache. If content
exists for this `integrity`, it will return an object, with the specific single integrity hash
that was found in `sri` key, and the size of the found content as `size`. If no content exists for this integrity, it will return `false`.
##### Example
```javascript
cacache.get.hasContent(cachePath, 'sha256-MUSTVERIFY+ALL/THINGS==').then(console.log)
// Output
{
sri: {
source: 'sha256-MUSTVERIFY+ALL/THINGS==',
algorithm: 'sha256',
digest: 'MUSTVERIFY+ALL/THINGS==',
options: []
},
size: 9001
}
cacache.get.hasContent(cachePath, 'sha521-NOT+IN/CACHE==').then(console.log)
// Output
false
```
##### <a name="get-options"></a> Options
##### `opts.integrity`
If present, the pre-calculated digest for the inserted content. If this option
is provided and does not match the post-insertion digest, insertion will fail
with an `EINTEGRITY` error.
##### `opts.memoize`
Default: null
If explicitly truthy, cacache will read from memory and memoize data on bulk read. If `false`, cacache will read from disk data. Reader functions by default read from in-memory cache.
##### `opts.size`
If provided, the data stream will be verified to check that enough data was
passed through. If there's more or less data than expected, insertion will fail
with an `EBADSIZE` error.
#### <a name="put-data"></a> `> cacache.put(cache, key, data, [opts]) -> Promise`
Inserts data passed to it into the cache. The returned Promise resolves with a
digest (generated according to [`opts.algorithms`](#optsalgorithms)) after the
cache entry has been successfully written.
See: [options](#put-options)
##### Example
```javascript
fetch(
'https://registry.npmjs.org/cacache/-/cacache-1.0.0.tgz'
).then(data => {
return cacache.put(cachePath, 'registry.npmjs.org|cacache@1.0.0', data)
}).then(integrity => {
console.log('integrity hash is', integrity)
})
```
#### <a name="put-stream"></a> `> cacache.put.stream(cache, key, [opts]) -> Writable`
Returns a [Writable
Stream](https://nodejs.org/api/stream.html#stream_writable_streams) that inserts
data written to it into the cache. Emits an `integrity` event with the digest of
written contents when it succeeds.
See: [options](#put-options)
##### Example
```javascript
request.get(
'https://registry.npmjs.org/cacache/-/cacache-1.0.0.tgz'
).pipe(
cacache.put.stream(
cachePath, 'registry.npmjs.org|cacache@1.0.0'
).on('integrity', d => console.log(`integrity digest is ${d}`))
)
```
##### <a name="put-options"></a> Options
##### `opts.metadata`
Arbitrary metadata to be attached to the inserted key.
##### `opts.size`
If provided, the data stream will be verified to check that enough data was
passed through. If there's more or less data than expected, insertion will fail
with an `EBADSIZE` error.
##### `opts.integrity`
If present, the pre-calculated digest for the inserted content. If this option
is provided and does not match the post-insertion digest, insertion will fail
with an `EINTEGRITY` error.
`algorithms` has no effect if this option is present.
##### `opts.integrityEmitter`
*Streaming only* If present, uses the provided event emitter as a source of
truth for both integrity and size. This allows use cases where integrity is
already being calculated outside of cacache to reuse that data instead of
calculating it a second time.
The emitter must emit both the `'integrity'` and `'size'` events.
NOTE: If this option is provided, you must verify that you receive the correct
integrity value yourself and emit an `'error'` event if there is a mismatch.
[ssri Integrity Streams](https://github.com/npm/ssri#integrity-stream) do this for you when given an expected integrity.
##### `opts.algorithms`
Default: ['sha512']
Hashing algorithms to use when calculating the [subresource integrity
digest](#integrity)
for inserted data. Can use any algorithm listed in `crypto.getHashes()` or
`'omakase'`/`'お任せします'` to pick a random hash algorithm on each insertion. You
may also use any anagram of `'modnar'` to use this feature.
Currently only supports one algorithm at a time (i.e., an array length of
exactly `1`). Has no effect if `opts.integrity` is present.
##### `opts.memoize`
Default: null
If provided, cacache will memoize the given cache insertion in memory, bypassing
any filesystem checks for that key or digest in future cache fetches. Nothing
will be written to the in-memory cache unless this option is explicitly truthy.
If `opts.memoize` is an object or a `Map`-like (that is, an object with `get`
and `set` methods), it will be written to instead of the global memoization
cache.
Reading from disk data can be forced by explicitly passing `memoize: false` to
the reader functions, but their default will be to read from memory.
##### `opts.tmpPrefix`
Default: null
Prefix to append on the temporary directory name inside the cache's tmp dir.
#### <a name="rm-all"></a> `> cacache.rm.all(cache) -> Promise`
Clears the entire cache. Mainly by blowing away the cache directory itself.
##### Example
```javascript
cacache.rm.all(cachePath).then(() => {
console.log('THE APOCALYPSE IS UPON US 😱')
})
```
#### <a name="rm-entry"></a> `> cacache.rm.entry(cache, key, [opts]) -> Promise`
Alias: `cacache.rm`
Removes the index entry for `key`. Content will still be accessible if
requested directly by content address ([`get.stream.byDigest`](#get-stream)).
By default, this appends a new entry to the index with an integrity of `null`.
If `opts.removeFully` is set to `true` then the index file itself will be
physically deleted rather than appending a `null`.
To remove the content itself (which might still be used by other entries), use
[`rm.content`](#rm-content). Or, to safely vacuum any unused content, use
[`verify`](#verify).
##### Example
```javascript
cacache.rm.entry(cachePath, 'my-thing').then(() => {
console.log('I did not like it anyway')
})
```
#### <a name="rm-content"></a> `> cacache.rm.content(cache, integrity) -> Promise`
Removes the content identified by `integrity`. Any index entries referring to it
will not be usable again until the content is re-added to the cache with an
identical digest.
##### Example
```javascript
cacache.rm.content(cachePath, 'sha512-SoMeDIGest/IN+BaSE64==').then(() => {
console.log('data for my-thing is gone!')
})
```
#### <a name="index-compact"></a> `> cacache.index.compact(cache, key, matchFn, [opts]) -> Promise`
Uses `matchFn`, which must be a synchronous function that accepts two entries
and returns a boolean indicating whether or not the two entries match, to
deduplicate all entries in the cache for the given `key`.
If `opts.validateEntry` is provided, it will be called as a function with the
only parameter being a single index entry. The function must return a Boolean,
if it returns `true` the entry is considered valid and will be kept in the index,
if it returns `false` the entry will be removed from the index.
If `opts.validateEntry` is not provided, however, every entry in the index will
be deduplicated and kept until the first `null` integrity is reached, removing
all entries that were written before the `null`.
The deduplicated list of entries is both written to the index, replacing the
existing content, and returned in the Promise.
#### <a name="index-insert"></a> `> cacache.index.insert(cache, key, integrity, opts) -> Promise`
Writes an index entry to the cache for the given `key` without writing content.
It is assumed if you are using this method, you have already stored the content
some other way and you only wish to add a new index to that content. The `metadata`
and `size` properties are read from `opts` and used as part of the index entry.
Returns a Promise resolving to the newly added entry.
#### <a name="clear-memoized"></a> `> cacache.clearMemoized()`
Completely resets the in-memory entry cache.
#### <a name="tmp-mkdir"></a> `> tmp.mkdir(cache, opts) -> Promise<Path>`
Returns a unique temporary directory inside the cache's `tmp` dir. This
directory will use the same safe user assignment that all the other stuff use.
Once the directory is made, it's the user's responsibility that all files
within are given the appropriate `gid`/`uid` ownership settings to match
the rest of the cache. If not, you can ask cacache to do it for you by
calling [`tmp.fix()`](#tmp-fix), which will fix all tmp directory
permissions.
If you want automatic cleanup of this directory, use
[`tmp.withTmp()`](#with-tpm)
See: [options](#tmp-options)
##### Example
```javascript
cacache.tmp.mkdir(cache).then(dir => {
fs.writeFile(path.join(dir, 'blablabla'), Buffer#<1234>, ...)
})
```
#### <a name="tmp-fix"></a> `> tmp.fix(cache) -> Promise`
Sets the `uid` and `gid` properties on all files and folders within the tmp
folder to match the rest of the cache.
Use this after manually writing files into [`tmp.mkdir`](#tmp-mkdir) or
[`tmp.withTmp`](#with-tmp).
##### Example
```javascript
cacache.tmp.mkdir(cache).then(dir => {
writeFile(path.join(dir, 'file'), someData).then(() => {
// make sure we didn't just put a root-owned file in the cache
cacache.tmp.fix().then(() => {
// all uids and gids match now
})
})
})
```
#### <a name="with-tmp"></a> `> tmp.withTmp(cache, opts, cb) -> Promise`
Creates a temporary directory with [`tmp.mkdir()`](#tmp-mkdir) and calls `cb`
with it. The created temporary directory will be removed when the return value
of `cb()` resolves, the tmp directory will be automatically deleted once that
promise completes.
The same caveats apply when it comes to managing permissions for the tmp dir's
contents.
See: [options](#tmp-options)
##### Example
```javascript
cacache.tmp.withTmp(cache, dir => {
return fs.writeFileAsync(path.join(dir, 'blablabla'), Buffer#<1234>, ...)
}).then(() => {
// `dir` no longer exists
})
```
##### <a name="tmp-options"></a> Options
##### `opts.tmpPrefix`
Default: null
Prefix to append on the temporary directory name inside the cache's tmp dir.
#### <a name="integrity"></a> Subresource Integrity Digests
For content verification and addressing, cacache uses strings following the
[Subresource
Integrity spec](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity).
That is, any time cacache expects an `integrity` argument or option, it
should be in the format `<hashAlgorithm>-<base64-hash>`.
One deviation from the current spec is that cacache will support any hash
algorithms supported by the underlying Node.js process. You can use
`crypto.getHashes()` to see which ones you can use.
##### Generating Digests Yourself
If you have an existing content shasum, they are generally formatted as a
hexadecimal string (that is, a sha1 would look like:
`5f5513f8822fdbe5145af33b64d8d970dcf95c6e`). In order to be compatible with
cacache, you'll need to convert this to an equivalent subresource integrity
string. For this example, the corresponding hash would be:
`sha1-X1UT+IIv2+UUWvM7ZNjZcNz5XG4=`.
If you want to generate an integrity string yourself for existing data, you can
use something like this:
```javascript
const crypto = require('crypto')
const hashAlgorithm = 'sha512'
const data = 'foobarbaz'
const integrity = (
hashAlgorithm +
'-' +
crypto.createHash(hashAlgorithm).update(data).digest('base64')
)
```
You can also use [`ssri`](https://npm.im/ssri) to have a richer set of functionality
around SRI strings, including generation, parsing, and translating from existing
hex-formatted strings.
#### <a name="verify"></a> `> cacache.verify(cache, opts) -> Promise`
Checks out and fixes up your cache:
* Cleans up corrupted or invalid index entries.
* Custom entry filtering options.
* Garbage collects any content entries not referenced by the index.
* Checks integrity for all content entries and removes invalid content.
* Fixes cache ownership.
* Removes the `tmp` directory in the cache and all its contents.
When it's done, it'll return an object with various stats about the verification
process, including amount of storage reclaimed, number of valid entries, number
of entries removed, etc.
##### <a name="verify-options"></a> Options
##### `opts.concurrency`
Default: 20
Number of concurrently read files in the filesystem while doing clean up.
##### `opts.filter`
Receives a formatted entry. Return false to remove it.
Note: might be called more than once on the same entry.
##### `opts.log`
Custom logger function:
```
log: { silly () {} }
log.silly('verify', 'verifying cache at', cache)
```
##### Example
```sh
echo somegarbage >> $CACHEPATH/content/deadbeef
```
```javascript
cacache.verify(cachePath).then(stats => {
// deadbeef collected, because of invalid checksum.
console.log('cache is much nicer now! stats:', stats)
})
```
#### <a name="verify-last-run"></a> `> cacache.verify.lastRun(cache) -> Promise`
Returns a `Date` representing the last time `cacache.verify` was run on `cache`.
##### Example
```javascript
cacache.verify(cachePath).then(() => {
cacache.verify.lastRun(cachePath).then(lastTime => {
console.log('cacache.verify was last called on' + lastTime)
})
})
```
@@ -0,0 +1,104 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.readdir = exports.readdirWithFileTypes = exports.read = void 0;
const fsStat = require("@nodelib/fs.stat");
const rpl = require("run-parallel");
const constants_1 = require("../constants");
const utils = require("../utils");
const common = require("./common");
function read(directory, settings, callback) {
if (!settings.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) {
readdirWithFileTypes(directory, settings, callback);
return;
}
readdir(directory, settings, callback);
}
exports.read = read;
function readdirWithFileTypes(directory, settings, callback) {
settings.fs.readdir(directory, { withFileTypes: true }, (readdirError, dirents) => {
if (readdirError !== null) {
callFailureCallback(callback, readdirError);
return;
}
const entries = dirents.map((dirent) => ({
dirent,
name: dirent.name,
path: common.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator)
}));
if (!settings.followSymbolicLinks) {
callSuccessCallback(callback, entries);
return;
}
const tasks = entries.map((entry) => makeRplTaskEntry(entry, settings));
rpl(tasks, (rplError, rplEntries) => {
if (rplError !== null) {
callFailureCallback(callback, rplError);
return;
}
callSuccessCallback(callback, rplEntries);
});
});
}
exports.readdirWithFileTypes = readdirWithFileTypes;
function makeRplTaskEntry(entry, settings) {
return (done) => {
if (!entry.dirent.isSymbolicLink()) {
done(null, entry);
return;
}
settings.fs.stat(entry.path, (statError, stats) => {
if (statError !== null) {
if (settings.throwErrorOnBrokenSymbolicLink) {
done(statError);
return;
}
done(null, entry);
return;
}
entry.dirent = utils.fs.createDirentFromStats(entry.name, stats);
done(null, entry);
});
};
}
function readdir(directory, settings, callback) {
settings.fs.readdir(directory, (readdirError, names) => {
if (readdirError !== null) {
callFailureCallback(callback, readdirError);
return;
}
const tasks = names.map((name) => {
const path = common.joinPathSegments(directory, name, settings.pathSegmentSeparator);
return (done) => {
fsStat.stat(path, settings.fsStatSettings, (error, stats) => {
if (error !== null) {
done(error);
return;
}
const entry = {
name,
path,
dirent: utils.fs.createDirentFromStats(name, stats)
};
if (settings.stats) {
entry.stats = stats;
}
done(null, entry);
});
};
});
rpl(tasks, (rplError, entries) => {
if (rplError !== null) {
callFailureCallback(callback, rplError);
return;
}
callSuccessCallback(callback, entries);
});
});
}
exports.readdir = readdir;
function callFailureCallback(callback, error) {
callback(error);
}
function callSuccessCallback(callback, result) {
callback(null, result);
}
@@ -0,0 +1,19 @@
'use strict';
var $TypeError = require('es-errors/type');
var CompletionRecord = require('./CompletionRecord');
var IteratorClose = require('./IteratorClose');
// https://262.ecma-international.org/16.0/#sec-ifabruptcloseiterator
module.exports = function IfAbruptCloseIterator(value, iteratorRecord) {
if (!(value instanceof CompletionRecord)) {
throw new $TypeError('Assertion failed: `value` must be a Completion Record'); // step 1
}
if (value.type() === 'throw') {
return IteratorClose(iteratorRecord, value); // step 2
}
return value['!'](); // step
};
@@ -0,0 +1,36 @@
import root from './_root.js';
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeIsFinite = root.isFinite;
/**
* Checks if `value` is a finite primitive number.
*
* **Note:** This method is based on
* [`Number.isFinite`](https://mdn.io/Number/isFinite).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a finite number, else `false`.
* @example
*
* _.isFinite(3);
* // => true
*
* _.isFinite(Number.MIN_VALUE);
* // => true
*
* _.isFinite(Infinity);
* // => false
*
* _.isFinite('3');
* // => false
*/
function isFinite(value) {
return typeof value == 'number' && nativeIsFinite(value);
}
export default isFinite;
@@ -0,0 +1,206 @@
# Reselect
[![npm package][npm-badge]][npm][![Coveralls][coveralls-badge]][coveralls][![GitHub Workflow Status][build-badge]][build]![TypeScript][typescript-badge]
A library for creating memoized "selector" functions. Commonly used with Redux, but usable with any plain JS immutable data as well.
- Selectors can compute derived data, allowing [Redux] to store the minimal possible state.
- Selectors are efficient. A selector is not recomputed unless one of its arguments changes.
- Selectors are composable. They can be used as input to other selectors.
The **Redux docs usage page on [Deriving Data with Selectors](https://redux.js.org/usage/deriving-data-selectors)** covers the purpose and motivation for selectors, why memoized selectors are useful, typical Reselect usage patterns, and using selectors with [React-Redux].
## Installation
### Redux Toolkit
While Reselect is not exclusive to [Redux], it is already included by default in [the official Redux Toolkit package](https://redux-toolkit.js.org) - no further installation needed.
```ts
import { createSelector } from '@reduxjs/toolkit'
```
### Standalone
For standalone usage, install the `reselect` package:
```bash
# NPM
npm install reselect
# Yarn
yarn add reselect
```
---
## Documentation
The Reselect docs are available at **https://reselect.js.org**, and include usage guides and API references:
- [**Introduction**](#https://reselect.js.org/introduction/getting-started)
- [**How Does Reselect Work?**](#https://reselect.js.org/introduction/how-does-reselect-work)
- **API Reference**:
- **[`createSelector`]**
- **[`createSelectorCreator`]**
- **[`createStructuredSelector`]**
- [**Development-Only Stability Checks**](#https://reselect.js.org/api/development-only-stability-checks)
- **[`lruMemoize`]**
- **[`weakMapMemoize`]**
- [**FAQ**](#https://reselect.js.org/FAQ)
## Basic Usage
Reselect exports a [`createSelector`] API, which generates memoized selector functions. [`createSelector`] accepts one or more [input selectors], which extract values from arguments, and a [result function] function that receives the extracted values and should return a derived value. If the generated [output selector] is called multiple times, the output will only be recalculated when the extracted values have changed.
You can play around with the following **example** in [this CodeSandbox](https://codesandbox.io/s/reselect-example-g3k9gf?file=/src/index.js):
```ts
import { createSelector } from 'reselect'
interface RootState {
todos: { id: number; completed: boolean }[]
alerts: { id: number; read: boolean }[]
}
const state: RootState = {
todos: [
{ id: 0, completed: false },
{ id: 1, completed: true }
],
alerts: [
{ id: 0, read: false },
{ id: 1, read: true }
]
}
const selectCompletedTodos = (state: RootState) => {
console.log('selector ran')
return state.todos.filter(todo => todo.completed === true)
}
selectCompletedTodos(state) // selector ran
selectCompletedTodos(state) // selector ran
selectCompletedTodos(state) // selector ran
const memoizedSelectCompletedTodos = createSelector(
[(state: RootState) => state.todos],
todos => {
console.log('memoized selector ran')
return todos.filter(todo => todo.completed === true)
}
)
memoizedSelectCompletedTodos(state) // memoized selector ran
memoizedSelectCompletedTodos(state)
memoizedSelectCompletedTodos(state)
console.log(selectCompletedTodos(state) === selectCompletedTodos(state)) //=> false
console.log(
memoizedSelectCompletedTodos(state) === memoizedSelectCompletedTodos(state)
) //=> true
```
As you can see from the example above, `memoizedSelectCompletedTodos` does not run the second or third time, but we still get the same return value as last time.
In addition to skipping unnecessary recalculations, `memoizedSelectCompletedTodos` returns the existing result reference if there is no recalculation. This is important for libraries like [React-Redux] or [React] that often rely on reference equality checks to optimize UI updates.
---
## Terminology
- <a name="selector-function"></a>[**Selector Function**](#selector-function): A function that accepts one or more JavaScript values as arguments, and derives a result. When used with [Redux], the first argument is typically the entire Redux store state.
- <a name="input-selectors"></a>[**input selectors**](#input-selectors): Basic selector functions used as building blocks for creating a memoized selector. They are passed as the first argument(s) to [`createSelector`], and are called with all selector arguments. They are responsible for extracting and providing necessary values to the [result function].
- <a name="output-selector"></a>[**Output Selector**](#output-selector): The actual memoized selectors created by [`createSelector`].
- <a name="result-function"></a>[**Result Function**](#result-function): The function that comes after the [input selectors]. It takes the [input selectors]' return values as arguments and returns a result.
- <a name="dependencies"></a>[**`Dependencies`**](#dependencies): Same as [input selectors]. They are what the [output selector] "depends" on.
The below example serves as a visual aid:
```ts
const outputSelector = createSelector(
[inputSelector1, inputSelector2, inputSelector3], // synonymous with `dependencies`.
resultFunc // Result function
)
```
---
## What's New in 5.0.0?
Version 5.0.0 introduces several new features and improvements:
- **Customization Enhancements**:
- Added the ability to pass an options object to [`createSelectorCreator`], allowing for customized `memoize` and `argsMemoize` functions, alongside their respective options (`memoizeOptions` and `argsMemoizeOptions`).
- The [`createSelector`] function now supports direct customization of `memoize` and `argsMemoize` within its options object.
- **Memoization Functions**:
- Introduced new experimental memoization functions: `weakMapMemoize` and `unstable_autotrackMemoize`.
- Incorporated `memoize` and `argsMemoize` into the [output selector fields] for debugging purposes.
- **TypeScript Support and Performance**:
- Discontinued support for TypeScript versions below 4.7, aligning with modern TypeScript features.
- Significantly improved TypeScript performance for nesting [output selectors][output selector]. The nesting limit has increased from approximately 8 to around 30 [output selectors][output selector], greatly reducing the occurrence of the infamous `Type instantiation is excessively deep and possibly infinite` error.
- **Selector API Enhancements**:
- Removed the second overload of `createStructuredSelector` due to its susceptibility to runtime errors.
- **Additional Functionalities**:
- Added `dependencyRecomputations` and `resetDependencyRecomputations` to the [output selector fields]. These additions provide greater control and insight over [input selectors], complementing the new `argsMemoize` API.
- Introduced `inputStabilityCheck`, a development tool that runs the [input selectors] twice using the same arguments and triggers a warning If they return differing results for the same call.
- Introduced `identityFunctionCheck`, a development tool that checks to see if the [result function] returns its own input.
These updates aim to enhance flexibility, performance, and developer experience. For detailed usage and examples, refer to the updated documentation sections for each feature.
- **Breaking Changes**:
- Removed `ParametricSelector` and `OutputParametricSelector` types. Their functionalities are now integrated into `Selector` and `OutputSelector` respectively, which inherently support additional parameters.
<div align="right">[ <a href="installation">↑ Back to top ↑</a> ]</div>
---
## License
MIT
## References
<details><summary><b>Click to Expand</b></summary>
Originally inspired by getters in [NuclearJS](https://github.com/optimizely/nuclear-js.git), [subscriptions](https://github.com/Day8/re-frame#just-a-read-only-cursor) in [re-frame](https://github.com/Day8/re-frame) and this [proposal](https://github.com/reduxjs/redux/pull/169) from [speedskater](https://github.com/speedskater).
[typescript-badge]: https://img.shields.io/badge/TypeScript-v4%2E7%2B-007ACC?style=for-the-badge&logo=TypeScript&logoColor=black&labelColor=blue&color=gray
[build-badge]: https://img.shields.io/github/actions/workflow/status/reduxjs/reselect/build-and-test-types.yml?branch=master&style=for-the-badge
[build]: https://github.com/reduxjs/reselect/actions/workflows/build-and-test-types.yml
[npm-badge]: https://img.shields.io/npm/v/reselect.svg?style=for-the-badge
[npm]: https://www.npmjs.org/package/reselect
[coveralls-badge]: https://img.shields.io/coveralls/reduxjs/reselect/master.svg?style=for-the-badge
[coveralls]: https://coveralls.io/github/reduxjs/reselect
<!-- External Links -->
[Redux]: https://redux.js.org 'Redux'
[React]: https://react.dev 'React'
[React-Redux]: https://react-redux.js.org 'React-Redux'
<!-- Internal Links -->
[selector]: #selector-function 'Selector Function'
[input selectors]: #input-selectors 'Input Selectors'
[output selector]: #output-selector 'Output Selector'
[result function]: #result-function 'Result Function'
[output selector fields]: https://reselect.js.org/api/createSelector#output-selector-fields 'Output Selector Fields'
[`createSelector`]: https://reselect.js.org/api/createSelector 'createSelector'
[`createSelectorCreator`]: https://reselect.js.org/api/createSelectorCreator 'createSelectorCreator'
[`lruMemoize`]: https://reselect.js.org/api/lruMemoize 'lruMemoize'
[`weakMapMemoize`]: https://reselect.js.org/api/weakMapMemoize 'weakMapMemoize'
[`createStructuredSelector`]: https://reselect.js.org/api/createStructuredSelector 'createStructuredSelector'
</details>
@@ -0,0 +1,144 @@
import {focusWithoutScrolling as $7215afc6de606d6b$export$de79e2c695e052f3} from "./focusWithoutScrolling.mjs";
import {isMac as $c87311424ea30a05$export$9ac100e40613ea10, isWebKit as $c87311424ea30a05$export$78551043582a6a98, isFirefox as $c87311424ea30a05$export$b7d78993b74f766d, isIPad as $c87311424ea30a05$export$7bef049ce92e4224} from "./platform.mjs";
import $g3jFn$react, {createContext as $g3jFn$createContext, useMemo as $g3jFn$useMemo, useContext as $g3jFn$useContext} from "react";
/*
* Copyright 2023 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
const $ea8dcbcb9ea1b556$var$RouterContext = /*#__PURE__*/ (0, $g3jFn$createContext)({
isNative: true,
open: $ea8dcbcb9ea1b556$var$openSyntheticLink,
useHref: (href)=>href
});
function $ea8dcbcb9ea1b556$export$323e4fc2fa4753fb(props) {
let { children: children, navigate: navigate, useHref: useHref } = props;
let ctx = (0, $g3jFn$useMemo)(()=>({
isNative: false,
open: (target, modifiers, href, routerOptions)=>{
$ea8dcbcb9ea1b556$var$getSyntheticLink(target, (link)=>{
if ($ea8dcbcb9ea1b556$export$efa8c9099e530235(link, modifiers)) navigate(href, routerOptions);
else $ea8dcbcb9ea1b556$export$95185d699e05d4d7(link, modifiers);
});
},
useHref: useHref || ((href)=>href)
}), [
navigate,
useHref
]);
return /*#__PURE__*/ (0, $g3jFn$react).createElement($ea8dcbcb9ea1b556$var$RouterContext.Provider, {
value: ctx
}, children);
}
function $ea8dcbcb9ea1b556$export$9a302a45f65d0572() {
return (0, $g3jFn$useContext)($ea8dcbcb9ea1b556$var$RouterContext);
}
function $ea8dcbcb9ea1b556$export$efa8c9099e530235(link, modifiers) {
// Use getAttribute here instead of link.target. Firefox will default link.target to "_parent" when inside an iframe.
let target = link.getAttribute('target');
return (!target || target === '_self') && link.origin === location.origin && !link.hasAttribute('download') && !modifiers.metaKey && // open in new tab (mac)
!modifiers.ctrlKey && // open in new tab (windows)
!modifiers.altKey && // download
!modifiers.shiftKey;
}
function $ea8dcbcb9ea1b556$export$95185d699e05d4d7(target, modifiers, setOpening = true) {
var _window_event_type, _window_event;
let { metaKey: metaKey, ctrlKey: ctrlKey, altKey: altKey, shiftKey: shiftKey } = modifiers;
// Firefox does not recognize keyboard events as a user action by default, and the popup blocker
// will prevent links with target="_blank" from opening. However, it does allow the event if the
// Command/Control key is held, which opens the link in a background tab. This seems like the best we can do.
// See https://bugzilla.mozilla.org/show_bug.cgi?id=257870 and https://bugzilla.mozilla.org/show_bug.cgi?id=746640.
if ((0, $c87311424ea30a05$export$b7d78993b74f766d)() && ((_window_event = window.event) === null || _window_event === void 0 ? void 0 : (_window_event_type = _window_event.type) === null || _window_event_type === void 0 ? void 0 : _window_event_type.startsWith('key')) && target.target === '_blank') {
if ((0, $c87311424ea30a05$export$9ac100e40613ea10)()) metaKey = true;
else ctrlKey = true;
}
// WebKit does not support firing click events with modifier keys, but does support keyboard events.
// https://github.com/WebKit/WebKit/blob/c03d0ac6e6db178f90923a0a63080b5ca210d25f/Source/WebCore/html/HTMLAnchorElement.cpp#L184
let event = (0, $c87311424ea30a05$export$78551043582a6a98)() && (0, $c87311424ea30a05$export$9ac100e40613ea10)() && !(0, $c87311424ea30a05$export$7bef049ce92e4224)() && true ? new KeyboardEvent('keydown', {
keyIdentifier: 'Enter',
metaKey: metaKey,
ctrlKey: ctrlKey,
altKey: altKey,
shiftKey: shiftKey
}) : new MouseEvent('click', {
metaKey: metaKey,
ctrlKey: ctrlKey,
altKey: altKey,
shiftKey: shiftKey,
bubbles: true,
cancelable: true
});
$ea8dcbcb9ea1b556$export$95185d699e05d4d7.isOpening = setOpening;
(0, $7215afc6de606d6b$export$de79e2c695e052f3)(target);
target.dispatchEvent(event);
$ea8dcbcb9ea1b556$export$95185d699e05d4d7.isOpening = false;
}
// https://github.com/parcel-bundler/parcel/issues/8724
$ea8dcbcb9ea1b556$export$95185d699e05d4d7.isOpening = false;
function $ea8dcbcb9ea1b556$var$getSyntheticLink(target, open) {
if (target instanceof HTMLAnchorElement) open(target);
else if (target.hasAttribute('data-href')) {
let link = document.createElement('a');
link.href = target.getAttribute('data-href');
if (target.hasAttribute('data-target')) link.target = target.getAttribute('data-target');
if (target.hasAttribute('data-rel')) link.rel = target.getAttribute('data-rel');
if (target.hasAttribute('data-download')) link.download = target.getAttribute('data-download');
if (target.hasAttribute('data-ping')) link.ping = target.getAttribute('data-ping');
if (target.hasAttribute('data-referrer-policy')) link.referrerPolicy = target.getAttribute('data-referrer-policy');
target.appendChild(link);
open(link);
target.removeChild(link);
}
}
function $ea8dcbcb9ea1b556$var$openSyntheticLink(target, modifiers) {
$ea8dcbcb9ea1b556$var$getSyntheticLink(target, (link)=>$ea8dcbcb9ea1b556$export$95185d699e05d4d7(link, modifiers));
}
function $ea8dcbcb9ea1b556$export$bdc77b0c0a3a85d6(props) {
let router = $ea8dcbcb9ea1b556$export$9a302a45f65d0572();
var _props_href;
const href = router.useHref((_props_href = props.href) !== null && _props_href !== void 0 ? _props_href : '');
return {
'data-href': props.href ? href : undefined,
'data-target': props.target,
'data-rel': props.rel,
'data-download': props.download,
'data-ping': props.ping,
'data-referrer-policy': props.referrerPolicy
};
}
function $ea8dcbcb9ea1b556$export$51437d503373d223(props) {
return {
'data-href': props.href,
'data-target': props.target,
'data-rel': props.rel,
'data-download': props.download,
'data-ping': props.ping,
'data-referrer-policy': props.referrerPolicy
};
}
function $ea8dcbcb9ea1b556$export$7e924b3091a3bd18(props) {
let router = $ea8dcbcb9ea1b556$export$9a302a45f65d0572();
var _props_href;
const href = router.useHref((_props_href = props === null || props === void 0 ? void 0 : props.href) !== null && _props_href !== void 0 ? _props_href : '');
return {
href: (props === null || props === void 0 ? void 0 : props.href) ? href : undefined,
target: props === null || props === void 0 ? void 0 : props.target,
rel: props === null || props === void 0 ? void 0 : props.rel,
download: props === null || props === void 0 ? void 0 : props.download,
ping: props === null || props === void 0 ? void 0 : props.ping,
referrerPolicy: props === null || props === void 0 ? void 0 : props.referrerPolicy
};
}
export {$ea8dcbcb9ea1b556$export$323e4fc2fa4753fb as RouterProvider, $ea8dcbcb9ea1b556$export$efa8c9099e530235 as shouldClientNavigate, $ea8dcbcb9ea1b556$export$95185d699e05d4d7 as openLink, $ea8dcbcb9ea1b556$export$9a302a45f65d0572 as useRouter, $ea8dcbcb9ea1b556$export$bdc77b0c0a3a85d6 as useSyntheticLinkProps, $ea8dcbcb9ea1b556$export$51437d503373d223 as getSyntheticLinkProps, $ea8dcbcb9ea1b556$export$7e924b3091a3bd18 as useLinkProps};
//# sourceMappingURL=openLink.module.js.map
@@ -0,0 +1,36 @@
"use strict"
const {
definePrototypeMethodHandler,
} = require("../util/define-prototype-method-handler")
module.exports = {
meta: {
docs: {
description: "disallow the `Set.prototype.isDisjointFrom` method.",
category: "ES2025",
proposal: "set-methods",
recommended: false,
url: "http://eslint-community.github.io/eslint-plugin-es-x/rules/no-set-prototype-isdisjointfrom.html",
},
fixable: null,
messages: {
forbidden: "ES2025 '{{name}}' method is forbidden.",
},
schema: [
{
type: "object",
properties: {
aggressive: { type: "boolean" },
},
additionalProperties: false,
},
],
type: "problem",
},
create(context) {
return definePrototypeMethodHandler(context, {
Set: ["isDisjointFrom"],
})
},
}
@@ -0,0 +1,76 @@
import type { ITokenizer, IFileInfo, IReadChunkOptions, ITokenizerOptions } from './types.js';
import type { IGetToken, IToken } from '@tokenizer/token';
interface INormalizedReadChunkOptions extends IReadChunkOptions {
length: number;
position: number;
mayBeLess?: boolean;
}
/**
* Core tokenizer
*/
export declare abstract class AbstractTokenizer implements ITokenizer {
private onClose?;
private numBuffer;
abstract fileInfo: IFileInfo;
/**
* Tokenizer-stream position
*/
position: number;
/**
* Constructor
* @param options Tokenizer options
* @protected
*/
protected constructor(options?: ITokenizerOptions);
abstract supportsRandomAccess(): boolean;
/**
* Read buffer from tokenizer
* @param buffer - Target buffer to fill with data read from the tokenizer-stream
* @param options - Additional read options
* @returns Promise with number of bytes read
*/
abstract readBuffer(buffer: Uint8Array, options?: IReadChunkOptions): Promise<number>;
/**
* Peek (read ahead) buffer from tokenizer
* @param uint8Array - Target buffer to fill with data peeked from the tokenizer-stream
* @param options - Peek behaviour options
* @returns Promise with number of bytes read
*/
abstract peekBuffer(uint8Array: Uint8Array, options?: IReadChunkOptions): Promise<number>;
/**
* Read a token from the tokenizer-stream
* @param token - The token to read
* @param position - If provided, the desired position in the tokenizer-stream
* @returns Promise with token data
*/
readToken<Value>(token: IGetToken<Value>, position?: number): Promise<Value>;
/**
* Peek a token from the tokenizer-stream.
* @param token - Token to peek from the tokenizer-stream.
* @param position - Offset where to begin reading within the file. If position is null, data will be read from the current file position.
* @returns Promise with token data
*/
peekToken<Value>(token: IGetToken<Value>, position?: number): Promise<Value>;
/**
* Read a numeric token from the stream
* @param token - Numeric token
* @returns Promise with number
*/
readNumber(token: IToken<number>): Promise<number>;
/**
* Read a numeric token from the stream
* @param token - Numeric token
* @returns Promise with number
*/
peekNumber(token: IToken<number>): Promise<number>;
/**
* Ignore number of bytes, advances the pointer in under tokenizer-stream.
* @param length - Number of bytes to ignore
* @return resolves the number of bytes ignored, equals length if this available, otherwise the number of bytes available
*/
ignore(length: number): Promise<number>;
close(): Promise<void>;
protected normalizeOptions(uint8Array: Uint8Array, options?: IReadChunkOptions): INormalizedReadChunkOptions;
abort(): Promise<void>;
}
export {};
@@ -0,0 +1,29 @@
'use strict';
var callBound = require('call-bound');
var $numToStr = callBound('Number.prototype.toString');
/** @type {import('.')} */
var tryNumberObject = function tryNumberObject(value) {
try {
$numToStr(value);
return true;
} catch (e) {
return false;
}
};
var $toString = callBound('Object.prototype.toString');
var numClass = '[object Number]';
var hasToStringTag = require('has-tostringtag/shams')();
/** @type {import('.')} */
module.exports = function isNumberObject(value) {
if (typeof value === 'number') {
return true;
}
if (!value || typeof value !== 'object') {
return false;
}
return hasToStringTag ? tryNumberObject(value) : $toString(value) === numClass;
};
@@ -0,0 +1,190 @@
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"), require("./enc-base64"), require("./md5"), require("./evpkdf"), require("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var StreamCipher = C_lib.StreamCipher;
var C_algo = C.algo;
// Reusable objects
var S = [];
var C_ = [];
var G = [];
/**
* Rabbit stream cipher algorithm.
*
* This is a legacy version that neglected to convert the key to little-endian.
* This error doesn't affect the cipher's security,
* but it does affect its compatibility with other implementations.
*/
var RabbitLegacy = C_algo.RabbitLegacy = StreamCipher.extend({
_doReset: function () {
// Shortcuts
var K = this._key.words;
var iv = this.cfg.iv;
// Generate initial state values
var X = this._X = [
K[0], (K[3] << 16) | (K[2] >>> 16),
K[1], (K[0] << 16) | (K[3] >>> 16),
K[2], (K[1] << 16) | (K[0] >>> 16),
K[3], (K[2] << 16) | (K[1] >>> 16)
];
// Generate initial counter values
var C = this._C = [
(K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff),
(K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff),
(K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff),
(K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff)
];
// Carry bit
this._b = 0;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
// Modify the counters
for (var i = 0; i < 8; i++) {
C[i] ^= X[(i + 4) & 7];
}
// IV setup
if (iv) {
// Shortcuts
var IV = iv.words;
var IV_0 = IV[0];
var IV_1 = IV[1];
// Generate four subvectors
var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00);
var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00);
var i1 = (i0 >>> 16) | (i2 & 0xffff0000);
var i3 = (i2 << 16) | (i0 & 0x0000ffff);
// Modify counter values
C[0] ^= i0;
C[1] ^= i1;
C[2] ^= i2;
C[3] ^= i3;
C[4] ^= i0;
C[5] ^= i1;
C[6] ^= i2;
C[7] ^= i3;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
}
},
_doProcessBlock: function (M, offset) {
// Shortcut
var X = this._X;
// Iterate the system
nextState.call(this);
// Generate four keystream words
S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16);
S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16);
S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16);
S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16);
for (var i = 0; i < 4; i++) {
// Swap endian
S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) |
(((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00);
// Encrypt
M[offset + i] ^= S[i];
}
},
blockSize: 128/32,
ivSize: 64/32
});
function nextState() {
// Shortcuts
var X = this._X;
var C = this._C;
// Save old counter values
for (var i = 0; i < 8; i++) {
C_[i] = C[i];
}
// Calculate new counter values
C[0] = (C[0] + 0x4d34d34d + this._b) | 0;
C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0;
C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0;
C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0;
C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0;
C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0;
C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0;
C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0;
this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0;
// Calculate the g-values
for (var i = 0; i < 8; i++) {
var gx = X[i] + C[i];
// Construct high and low argument for squaring
var ga = gx & 0xffff;
var gb = gx >>> 16;
// Calculate high and low result of squaring
var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb;
var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0);
// High XOR low
G[i] = gh ^ gl;
}
// Calculate new state values
X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0;
X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0;
X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0;
X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0;
X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0;
X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0;
X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0;
X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.RabbitLegacy.encrypt(message, key, cfg);
* var plaintext = CryptoJS.RabbitLegacy.decrypt(ciphertext, key, cfg);
*/
C.RabbitLegacy = StreamCipher._createHelper(RabbitLegacy);
}());
return CryptoJS.RabbitLegacy;
}));
@@ -0,0 +1,55 @@
// Copyright (c) 2011-2016 Ryan Prichard
//
// 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.
#include "WinptyAssert.h"
#include <windows.h>
#include <stdlib.h>
#include "DebugClient.h"
void assertTrace(const char *file, int line, const char *cond) {
trace("Assertion failed: %s, file %s, line %d",
cond, file, line);
}
#ifdef WINPTY_AGENT_ASSERT
void agentShutdown() {
HWND hwnd = GetConsoleWindow();
if (hwnd != NULL) {
PostMessage(hwnd, WM_CLOSE, 0, 0);
Sleep(30000);
trace("Agent shutdown: WM_CLOSE did not end agent process");
} else {
trace("Agent shutdown: GetConsoleWindow() is NULL");
}
// abort() prints a message to the console, and if it is frozen, then the
// process would hang, so instead use exit(). (We shouldn't ever get here,
// though, because the WM_CLOSE message should have ended this process.)
exit(1);
}
void agentAssertFail(const char *file, int line, const char *cond) {
assertTrace(file, line, cond);
agentShutdown();
}
#endif
@@ -0,0 +1,2 @@
import"reflect-metadata";import{getOwnReflectMetadata as e,setReflectMetadata as n,updateOwnReflectMetadata as i}from"@inversifyjs/reflect-metadata-utils";import{getClassMetadata as t,bindingTypeValues as r,getBindingId as a,bindingScopeValues as s,ResolvedValueElementMetadataKind as o,resolveServiceDeactivations as c,CacheBindingInvalidationKind as d,resolveBindingsDeactivations as l,resolveModuleDeactivations as u,plan as h,resolve as v,ActivationsService as g,BindingService as f,DeactivationsService as b,PlanResultCacheService as p}from"@inversifyjs/core";import{LazyServiceIdentifier as S,stringifyServiceIdentifier as M,isPromise as R}from"@inversifyjs/common";import{isPlugin as y}from"@inversifyjs/plugin";const m="@inversifyjs/container/bindingId";class w{#e;#n;constructor(t){this.#e=function(){const t=e(Object,m)??0;return t===Number.MAX_SAFE_INTEGER?n(Object,m,Number.MIN_SAFE_INTEGER):i(Object,m,()=>t,e=>e+1),t}(),this.#n=t}get id(){return this.#e}load(e){return this.#n(e)}}const I=Symbol.for("@inversifyjs/container/bindingIdentifier");function A(e){return"object"==typeof e&&null!==e&&!0===e[I]}class P{static always=e=>!0}const C=Symbol.for("@inversifyjs/container/InversifyContainerError");class B extends Error{[C];kind;constructor(e,n,i){super(n,i),this[C]=!0,this.kind=e}static is(e){return"object"==typeof e&&null!==e&&!0===e[C]}static isErrorOfKind(e,n){return B.is(e)&&e.kind===n}}var O;function x(e){return{[I]:!0,id:e.id}}function k(e){return n=>{for(let i=n.getAncestor();void 0!==i;i=i.getAncestor())if(e(i))return!0;return!1}}function N(e){return n=>n.name===e}function F(e){return n=>n.serviceIdentifier===e}function U(e,n){return i=>i.tags.has(e)&&i.tags.get(e)===n}function D(e){return void 0===e.name&&0===e.tags.size}function j(e){const n=k(e);return e=>!n(e)}function T(e){return n=>{const i=n.getAncestor();return void 0===i||!e(i)}}function V(e){return n=>{const i=n.getAncestor();return void 0!==i&&e(i)}}!function(e){e[e.invalidOperation=0]="invalidOperation"}(O||(O={}));class E{#i;constructor(e){this.#i=e}getIdentifier(){return x(this.#i)}inRequestScope(){return this.#i.scope=s.Request,new G(this.#i)}inSingletonScope(){return this.#i.scope=s.Singleton,new G(this.#i)}inTransientScope(){return this.#i.scope=s.Transient,new G(this.#i)}}class L{#t;#r;#a;#s;constructor(e,n,i,t){this.#t=e,this.#r=n,this.#a=i,this.#s=t}to(e){const n=t(e),i={cache:{isRight:!1,value:void 0},id:a(),implementationType:e,isSatisfiedBy:P.always,moduleId:this.#r,onActivation:void 0,onDeactivation:void 0,scope:n.scope??this.#a,serviceIdentifier:this.#s,type:r.Instance};return this.#t(i),new H(i)}toSelf(){if("function"!=typeof this.#s)throw new Error('"toSelf" function can only be applied when a newable function is used as service identifier');return this.to(this.#s)}toConstantValue(e){const n={cache:{isRight:!1,value:void 0},id:a(),isSatisfiedBy:P.always,moduleId:this.#r,onActivation:void 0,onDeactivation:void 0,scope:s.Singleton,serviceIdentifier:this.#s,type:r.ConstantValue,value:e};return this.#t(n),new G(n)}toDynamicValue(e){const n={cache:{isRight:!1,value:void 0},id:a(),isSatisfiedBy:P.always,moduleId:this.#r,onActivation:void 0,onDeactivation:void 0,scope:this.#a,serviceIdentifier:this.#s,type:r.DynamicValue,value:e};return this.#t(n),new H(n)}toResolvedValue(e,n){const i={cache:{isRight:!1,value:void 0},factory:e,id:a(),isSatisfiedBy:P.always,metadata:this.#o(n),moduleId:this.#r,onActivation:void 0,onDeactivation:void 0,scope:this.#a,serviceIdentifier:this.#s,type:r.ResolvedValue};return this.#t(i),new H(i)}toFactory(e){const n={cache:{isRight:!1,value:void 0},factory:e,id:a(),isSatisfiedBy:P.always,moduleId:this.#r,onActivation:void 0,onDeactivation:void 0,scope:s.Singleton,serviceIdentifier:this.#s,type:r.Factory};return this.#t(n),new G(n)}toProvider(e){const n={cache:{isRight:!1,value:void 0},id:a(),isSatisfiedBy:P.always,moduleId:this.#r,onActivation:void 0,onDeactivation:void 0,provider:e,scope:s.Singleton,serviceIdentifier:this.#s,type:r.Provider};return this.#t(n),new G(n)}toService(e){const n={id:a(),isSatisfiedBy:P.always,moduleId:this.#r,serviceIdentifier:this.#s,targetServiceIdentifier:e,type:r.ServiceRedirection};this.#t(n)}#o(e){return{arguments:(e??[]).map(e=>function(e){return"object"==typeof e&&!S.is(e)}(e)?function(e){return!0===e.isMultiple}(e)?{chained:e.chained??!1,kind:o.multipleInjection,name:e.name,optional:e.optional??!1,tags:new Map((e.tags??[]).map(e=>[e.key,e.value])),value:e.serviceIdentifier}:{kind:o.singleInjection,name:e.name,optional:e.optional??!1,tags:new Map((e.tags??[]).map(e=>[e.key,e.value])),value:e.serviceIdentifier}:{kind:o.singleInjection,name:void 0,optional:!1,tags:new Map,value:e})}}}class ${#i;constructor(e){this.#i=e}getIdentifier(){return x(this.#i)}onActivation(e){return this.#i.onActivation=e,new q(this.#i)}onDeactivation(e){if(this.#i.onDeactivation=e,this.#i.scope!==s.Singleton)throw new B(O.invalidOperation,`Binding for service "${M(this.#i.serviceIdentifier)}" haLine truncated
//# sourceMappingURL=index.js.map
@@ -0,0 +1,588 @@
// Generated by dts-bundle-generator v8.0.1
import { NextFunction, Request, RequestHandler, Response } from 'express';
declare const validations: {
enabled: {
[key: string]: boolean;
};
disable(): void;
/**
* Checks whether the IP address is valid, and that it does not have a port
* number in it.
*
* See https://github.com/express-rate-limit/express-rate-limit/wiki/Error-Codes#err_erl_invalid_ip_address.
*
* @param ip {string | undefined} - The IP address provided by Express as request.ip.
*
* @returns {void}
*/
ip(ip: string | undefined): void;
/**
* Makes sure the trust proxy setting is not set to `true`.
*
* See https://github.com/express-rate-limit/express-rate-limit/wiki/Error-Codes#err_erl_permissive_trust_proxy.
*
* @param request {Request} - The Express request object.
*
* @returns {void}
*/
trustProxy(request: Request): void;
/**
* Makes sure the trust proxy setting is set in case the `X-Forwarded-For`
* header is present.
*
* See https://github.com/express-rate-limit/express-rate-limit/wiki/Error-Codes#err_erl_unset_trust_proxy.
*
* @param request {Request} - The Express request object.
*
* @returns {void}
*/
xForwardedForHeader(request: Request): void;
/**
* Ensures totalHits value from store is a positive integer.
*
* @param hits {any} - The `totalHits` returned by the store.
*/
positiveHits(hits: any): void;
/**
* Ensures a single store instance is not used with multiple express-rate-limit instances
*/
unsharedStore(store: Store): void;
/**
* Ensures a given key is incremented only once per request.
*
* @param request {Request} - The Express request object.
* @param store {Store} - The store class.
* @param key {string} - The key used to store the client's hit count.
*
* @returns {void}
*/
singleCount(request: Request, store: Store, key: string): void;
/**
* Warns the user that the behaviour for `max: 0` / `limit: 0` is
* changing in the next major release.
*
* @param limit {number} - The maximum number of hits per client.
*
* @returns {void}
*/
limit(limit: number): void;
/**
* Warns the user that the `draft_polli_ratelimit_headers` option is deprecated
* and will be removed in the next major release.
*
* @param draft_polli_ratelimit_headers {any | undefined} - The now-deprecated setting that was used to enable standard headers.
*
* @returns {void}
*/
draftPolliHeaders(draft_polli_ratelimit_headers?: any): void;
/**
* Warns the user that the `onLimitReached` option is deprecated and
* will be removed in the next major release.
*
* @param onLimitReached {any | undefined} - The maximum number of hits per client.
*
* @returns {void}
*/
onLimitReached(onLimitReached?: any): void;
/**
* Warns the user when an invalid/unsupported version of the draft spec is passed.
*
* @param version {any | undefined} - The version passed by the user.
*
* @returns {void}
*/
headersDraftVersion(version?: any): void;
/**
* Warns the user when the selected headers option requires a reset time but
* the store does not provide one.
*
* @param resetTime {Date | undefined} - The timestamp when the client's hit count will be reset.
*
* @returns {void}
*/
headersResetTime(resetTime?: Date): void;
/**
* Checks the options.validate setting to ensure that only recognized
* validations are enabled or disabled.
*
* If any unrecognized values are found, an error is logged that
* includes the list of supported vaidations.
*/
validationsConfig(): void;
/**
* Checks to see if the instance was created inside of a request handler,
* which would prevent it from working correctly, with the default memory
* store (or any other store with localKeys.)
*/
creationStack(store: Store): void;
};
export type Validations = typeof validations;
declare const SUPPORTED_DRAFT_VERSIONS: readonly [
"draft-6",
"draft-7",
"draft-8"
];
/**
* Callback that fires when a client's hit counter is incremented.
*
* @param error {Error | undefined} - The error that occurred, if any.
* @param totalHits {number} - The number of hits for that client so far.
* @param resetTime {Date | undefined} - The time when the counter resets.
*/
export type IncrementCallback = (error: Error | undefined, totalHits: number, resetTime: Date | undefined) => void;
/**
* Method (in the form of middleware) to generate/retrieve a value based on the
* incoming request.
*
* @param request {Request} - The Express request object.
* @param response {Response} - The Express response object.
*
* @returns {T} - The value needed.
*/
export type ValueDeterminingMiddleware<T> = (request: Request, response: Response) => T | Promise<T>;
/**
* Express request handler that sends back a response when a client is
* rate-limited.
*
* @param request {Request} - The Express request object.
* @param response {Response} - The Express response object.
* @param next {NextFunction} - The Express `next` function, can be called to skip responding.
* @param optionsUsed {Options} - The options used to set up the middleware.
*/
export type RateLimitExceededEventHandler = (request: Request, response: Response, next: NextFunction, optionsUsed: Options) => void;
/**
* Event callback that is triggered on a client's first request that exceeds the limit
* but not for subsequent requests. May be used for logging, etc. Should *not*
* send a response.
*
* @param request {Request} - The Express request object.
* @param response {Response} - The Express response object.
* @param optionsUsed {Options} - The options used to set up the middleware.
*/
export type RateLimitReachedEventHandler = (request: Request, response: Response, optionsUsed: Options) => void;
/**
* Data returned from the `Store` when a client's hit counter is incremented.
*
* @property totalHits {number} - The number of hits for that client so far.
* @property resetTime {Date | undefined} - The time when the counter resets.
*/
export type ClientRateLimitInfo = {
totalHits: number;
resetTime: Date | undefined;
};
export type IncrementResponse = ClientRateLimitInfo;
/**
* A modified Express request handler with the rate limit functions.
*/
export type RateLimitRequestHandler = RequestHandler & {
/**
* Method to reset a client's hit counter.
*
* @param key {string} - The identifier for a client.
*/
resetKey: (key: string) => void;
/**
* Method to fetch a client's hit count and reset time.
*
* @param key {string} - The identifier for a client.
*
* @returns {ClientRateLimitInfo} - The number of hits and reset time for that client.
*/
getKey: (key: string) => Promise<ClientRateLimitInfo | undefined> | ClientRateLimitInfo | undefined;
};
/**
* An interface that all hit counter stores must implement.
*
* @deprecated 6.x - Implement the `Store` interface instead.
*/
export type LegacyStore = {
/**
* Method to increment a client's hit counter.
*
* @param key {string} - The identifier for a client.
* @param callback {IncrementCallback} - The callback to call once the counter is incremented.
*/
incr: (key: string, callback: IncrementCallback) => void;
/**
* Method to decrement a client's hit counter.
*
* @param key {string} - The identifier for a client.
*/
decrement: (key: string) => void;
/**
* Method to reset a client's hit counter.
*
* @param key {string} - The identifier for a client.
*/
resetKey: (key: string) => void;
/**
* Method to reset everyone's hit counter.
*/
resetAll?: () => void;
};
/**
* An interface that all hit counter stores must implement.
*/
export type Store = {
/**
* Method that initializes the store, and has access to the options passed to
* the middleware too.
*
* @param options {Options} - The options used to setup the middleware.
*/
init?: (options: Options) => void;
/**
* Method to fetch a client's hit count and reset time.
*
* @param key {string} - The identifier for a client.
*
* @returns {ClientRateLimitInfo} - The number of hits and reset time for that client.
*/
get?: (key: string) => Promise<ClientRateLimitInfo | undefined> | ClientRateLimitInfo | undefined;
/**
* Method to increment a client's hit counter.
*
* @param key {string} - The identifier for a client.
*
* @returns {IncrementResponse | undefined} - The number of hits and reset time for that client.
*/
increment: (key: string) => Promise<IncrementResponse> | IncrementResponse;
/**
* Method to decrement a client's hit counter.
*
* @param key {string} - The identifier for a client.
*/
decrement: (key: string) => Promise<void> | void;
/**
* Method to reset a client's hit counter.
*
* @param key {string} - The identifier for a client.
*/
resetKey: (key: string) => Promise<void> | void;
/**
* Method to reset everyone's hit counter.
*/
resetAll?: () => Promise<void> | void;
/**
* Method to shutdown the store, stop timers, and release all resources.
*/
shutdown?: () => Promise<void> | void;
/**
* Flag to indicate that keys incremented in one instance of this store can
* not affect other instances. Typically false if a database is used, true for
* MemoryStore.
*
* Used to help detect double-counting misconfigurations.
*/
localKeys?: boolean;
/**
* Optional value that the store prepends to keys
*
* Used by the double-count check to avoid false-positives when a key is counted twice, but with different prefixes
*/
prefix?: string;
};
export type DraftHeadersVersion = (typeof SUPPORTED_DRAFT_VERSIONS)[number];
/**
* Validate configuration object for enabling or disabling specific validations.
*
* The keys must also be keys in the validations object, except `enable`, `disable`,
* and `default`.
*/
export type EnabledValidations = {
[key in keyof Omit<Validations, "enabled" | "disable"> | "default"]?: boolean;
};
/**
* The configuration options for the rate limiter.
*/
export type Options = {
/**
* How long we should remember the requests.
*
* Defaults to `60000` ms (= 1 minute).
*/
windowMs: number;
/**
* The maximum number of connections to allow during the `window` before
* rate limiting the client.
*
* Can be the limit itself as a number or express middleware that parses
* the request and then figures out the limit.
*
* Defaults to `5`.
*/
limit: number | ValueDeterminingMiddleware<number>;
/**
* The response body to send back when a client is rate limited.
*
* Defaults to `'Too many requests, please try again later.'`
*/
message: any | ValueDeterminingMiddleware<any>;
/**
* The HTTP status code to send back when a client is rate limited.
*
* Defaults to `HTTP 429 Too Many Requests` (RFC 6585).
*/
statusCode: number;
/**
* Whether to send `X-RateLimit-*` headers with the rate limit and the number
* of requests.
*
* Defaults to `true` (for backward compatibility).
*/
legacyHeaders: boolean;
/**
* Whether to enable support for the standardized rate limit headers (`RateLimit-*`).
*
* Defaults to `false` (for backward compatibility, but its use is recommended).
*/
standardHeaders: boolean | DraftHeadersVersion;
/**
* The name used to identify the quota policy in the `RateLimit` headers as per
* the 8th draft of the IETF specification.
*
* Defaults to `{limit}-in-{window}`.
*/
identifier: string | ValueDeterminingMiddleware<string>;
/**
* The name of the property on the request object to store the rate limit info.
*
* Defaults to `rateLimit`.
*/
requestPropertyName: string;
/**
* If `true`, the library will (by default) skip all requests that have a 4XX
* or 5XX status.
*
* Defaults to `false`.
*/
skipFailedRequests: boolean;
/**
* If `true`, the library will (by default) skip all requests that have a
* status code less than 400.
*
* Defaults to `false`.
*/
skipSuccessfulRequests: boolean;
/**
* Method to generate custom identifiers for clients.
*
* By default, the client's IP address is used.
*/
keyGenerator: ValueDeterminingMiddleware<string>;
/**
* Express request handler that sends back a response when a client is
* rate-limited.
*
* By default, sends back the `statusCode` and `message` set via the options.
*/
handler: RateLimitExceededEventHandler;
/**
* Method (in the form of middleware) to determine whether or not this request
* counts towards a client's quota.
*
* By default, skips no requests.
*/
skip: ValueDeterminingMiddleware<boolean>;
/**
* Method to determine whether or not the request counts as 'succesful'. Used
* when either `skipSuccessfulRequests` or `skipFailedRequests` is set to true.
*
* By default, requests with a response status code less than 400 are considered
* successful.
*/
requestWasSuccessful: ValueDeterminingMiddleware<boolean>;
/**
* The `Store` to use to store the hit count for each client.
*
* By default, the built-in `MemoryStore` will be used.
*/
store: Store | LegacyStore;
/**
* The list of validation checks that should run.
*/
validate: boolean | EnabledValidations;
/**
* Whether to send `X-RateLimit-*` headers with the rate limit and the number
* of requests.
*
* @deprecated 6.x - This option was renamed to `legacyHeaders`.
*/
headers?: boolean;
/**
* The maximum number of connections to allow during the `window` before
* rate limiting the client.
*
* Can be the limit itself as a number or express middleware that parses
* the request and then figures out the limit.
*
* @deprecated 7.x - This option was renamed to `limit`. However, it will not
* be removed from the library in the foreseeable future.
*/
max?: number | ValueDeterminingMiddleware<number>;
/**
* If the Store generates an error, allow the request to pass.
*/
passOnStoreError: boolean;
};
/**
* The extended request object that includes information about the client's
* rate limit.
*/
export type AugmentedRequest = Request & {
[key: string]: RateLimitInfo;
};
/**
* The rate limit related information for each client included in the
* Express request object.
*/
export type RateLimitInfo = {
limit: number;
used: number;
remaining: number;
resetTime: Date | undefined;
};
/**
*
* Create an instance of IP rate-limiting middleware for Express.
*
* @param passedOptions {Options} - Options to configure the rate limiter.
*
* @returns {RateLimitRequestHandler} - The middleware that rate-limits clients based on your configuration.
*
* @public
*/
export declare const rateLimit: (passedOptions?: Partial<Options>) => RateLimitRequestHandler;
/**
* The record that stores information about a client - namely, how many times
* they have hit the endpoint, and when their hit count resets.
*
* Similar to `ClientRateLimitInfo`, except `resetTime` is a compulsory field.
*/
export type Client = {
totalHits: number;
resetTime: Date;
};
/**
* A `Store` that stores the hit count for each client in memory.
*
* @public
*/
export declare class MemoryStore implements Store {
/**
* The duration of time before which all hit counts are reset (in milliseconds).
*/
windowMs: number;
/**
* These two maps store usage (requests) and reset time by key (for example, IP
* addresses or API keys).
*
* They are split into two to avoid having to iterate through the entire set to
* determine which ones need reset. Instead, `Client`s are moved from `previous`
* to `current` as they hit the endpoint. Once `windowMs` has elapsed, all clients
* left in `previous`, i.e., those that have not made any recent requests, are
* known to be expired and can be deleted in bulk.
*/
previous: Map<string, Client>;
current: Map<string, Client>;
/**
* A reference to the active timer.
*/
interval?: NodeJS.Timeout;
/**
* Confirmation that the keys incremented in once instance of MemoryStore
* cannot affect other instances.
*/
localKeys: boolean;
/**
* Method that initializes the store.
*
* @param options {Options} - The options used to setup the middleware.
*/
init(options: Options): void;
/**
* Method to fetch a client's hit count and reset time.
*
* @param key {string} - The identifier for a client.
*
* @returns {ClientRateLimitInfo | undefined} - The number of hits and reset time for that client.
*
* @public
*/
get(key: string): Promise<ClientRateLimitInfo | undefined>;
/**
* Method to increment a client's hit counter.
*
* @param key {string} - The identifier for a client.
*
* @returns {ClientRateLimitInfo} - The number of hits and reset time for that client.
*
* @public
*/
increment(key: string): Promise<ClientRateLimitInfo>;
/**
* Method to decrement a client's hit counter.
*
* @param key {string} - The identifier for a client.
*
* @public
*/
decrement(key: string): Promise<void>;
/**
* Method to reset a client's hit counter.
*
* @param key {string} - The identifier for a client.
*
* @public
*/
resetKey(key: string): Promise<void>;
/**
* Method to reset everyone's hit counter.
*
* @public
*/
resetAll(): Promise<void>;
/**
* Method to stop the timer (if currently running) and prevent any memory
* leaks.
*
* @public
*/
shutdown(): void;
/**
* Recycles a client by setting its hit count to zero, and reset time to
* `windowMs` milliseconds from now.
*
* NOT to be confused with `#resetKey()`, which removes a client from both the
* `current` and `previous` maps.
*
* @param client {Client} - The client to recycle.
* @param now {number} - The current time, to which the `windowMs` is added to get the `resetTime` for the client.
*
* @return {Client} - The modified client that was passed in, to allow for chaining.
*/
private resetClient;
/**
* Retrieves or creates a client, given a key. Also ensures that the client being
* returned is in the `current` map.
*
* @param key {string} - The key under which the client is (or is to be) stored.
*
* @returns {Client} - The requested client.
*/
private getClient;
/**
* Move current clients to previous, create a new map for current.
*
* This function is called every `windowMs`.
*/
private clearExpired;
}
export {
rateLimit as default,
};
export {};
@@ -0,0 +1,23 @@
import LazyWrapper from './_LazyWrapper.js';
import LodashWrapper from './_LodashWrapper.js';
import copyArray from './_copyArray.js';
/**
* Creates a clone of `wrapper`.
*
* @private
* @param {Object} wrapper The wrapper to clone.
* @returns {Object} Returns the cloned wrapper.
*/
function wrapperClone(wrapper) {
if (wrapper instanceof LazyWrapper) {
return wrapper.clone();
}
var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__);
result.__actions__ = copyArray(wrapper.__actions__);
result.__index__ = wrapper.__index__;
result.__values__ = wrapper.__values__;
return result;
}
export default wrapperClone;
@@ -0,0 +1,219 @@
/**
* Visit nodes, with ancestral information.
*
* This algorithm performs *depth-first* *tree traversal* in *preorder*
* (**NLR**) or if `reverse` is given, in *reverse preorder* (**NRL**).
*
* You can choose for which nodes `visitor` is called by passing a `test`.
* For complex tests, you should test yourself in `visitor`, as it will be
* faster and will have improved type information.
*
* Walking the tree is an intensive task.
* Make use of the return values of the visitor when possible.
* Instead of walking a tree multiple times, walk it once, use `unist-util-is`
* to check if a node matches, and then perform different operations.
*
* You can change the tree.
* See `Visitor` for more info.
*
* @overload
* @param {Tree} tree
* @param {Check} check
* @param {BuildVisitor<Tree, Check>} visitor
* @param {boolean | null | undefined} [reverse]
* @returns {undefined}
*
* @overload
* @param {Tree} tree
* @param {BuildVisitor<Tree>} visitor
* @param {boolean | null | undefined} [reverse]
* @returns {undefined}
*
* @param {UnistNode} tree
* Tree to traverse.
* @param {Visitor | Test} test
* `unist-util-is`-compatible test
* @param {Visitor | boolean | null | undefined} [visitor]
* Handle each node.
* @param {boolean | null | undefined} [reverse]
* Traverse in reverse preorder (NRL) instead of the default preorder (NLR).
* @returns {undefined}
* Nothing.
*
* @template {UnistNode} Tree
* Node type.
* @template {Test} Check
* `unist-util-is`-compatible test.
*/
export function visitParents<Tree extends UnistNode, Check extends Test>(tree: Tree, check: Check, visitor: BuildVisitor<Tree, Check>, reverse?: boolean | null | undefined): undefined;
/**
* Visit nodes, with ancestral information.
*
* This algorithm performs *depth-first* *tree traversal* in *preorder*
* (**NLR**) or if `reverse` is given, in *reverse preorder* (**NRL**).
*
* You can choose for which nodes `visitor` is called by passing a `test`.
* For complex tests, you should test yourself in `visitor`, as it will be
* faster and will have improved type information.
*
* Walking the tree is an intensive task.
* Make use of the return values of the visitor when possible.
* Instead of walking a tree multiple times, walk it once, use `unist-util-is`
* to check if a node matches, and then perform different operations.
*
* You can change the tree.
* See `Visitor` for more info.
*
* @overload
* @param {Tree} tree
* @param {Check} check
* @param {BuildVisitor<Tree, Check>} visitor
* @param {boolean | null | undefined} [reverse]
* @returns {undefined}
*
* @overload
* @param {Tree} tree
* @param {BuildVisitor<Tree>} visitor
* @param {boolean | null | undefined} [reverse]
* @returns {undefined}
*
* @param {UnistNode} tree
* Tree to traverse.
* @param {Visitor | Test} test
* `unist-util-is`-compatible test
* @param {Visitor | boolean | null | undefined} [visitor]
* Handle each node.
* @param {boolean | null | undefined} [reverse]
* Traverse in reverse preorder (NRL) instead of the default preorder (NLR).
* @returns {undefined}
* Nothing.
*
* @template {UnistNode} Tree
* Node type.
* @template {Test} Check
* `unist-util-is`-compatible test.
*/
export function visitParents<Tree extends UnistNode, Check extends Test>(tree: Tree, visitor: BuildVisitor<Tree>, reverse?: boolean | null | undefined): undefined;
/**
* Continue traversing as normal.
*/
export const CONTINUE: true;
/**
* Stop traversing immediately.
*/
export const EXIT: false;
/**
* Do not traverse this node’s children.
*/
export const SKIP: "skip";
/**
* Test from `unist-util-is`.
*
* Note: we have remove and add `undefined`, because otherwise when generating
* automatic `.d.ts` files, TS tries to flatten paths from a local perspective,
* which doesn’t work when publishing on npm.
*/
export type Test = Exclude<import("unist-util-is").Test, undefined> | undefined;
/**
* Get the value of a type guard `Fn`.
*/
export type Predicate<Fn, Fallback> = (Fn extends (value: any) => value is infer Thing ? Thing : Fallback);
/**
* Check whether a node matches a primitive check in the type system.
*/
export type MatchesOne<Value, Check> = (Check extends null | undefined ? Value : Value extends {
type: Check;
} ? Value : Value extends Check ? Value : Check extends Function ? Predicate<Check, Value> extends Value ? Predicate<Check, Value> : never : never);
/**
* Check whether a node matches a check in the type system.
*/
export type Matches<Value, Check> = (Check extends ReadonlyArray<infer T> ? MatchesOne<Value, T> : Check extends Array<infer T> ? MatchesOne<Value, T> : MatchesOne<Value, Check>);
/**
* Number; capped reasonably.
*/
export type Uint = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10;
/**
* Increment a number in the type system.
*/
export type Increment<I extends Uint = 0> = I extends 0 ? 1 : I extends 1 ? 2 : I extends 2 ? 3 : I extends 3 ? 4 : I extends 4 ? 5 : I extends 5 ? 6 : I extends 6 ? 7 : I extends 7 ? 8 : I extends 8 ? 9 : 10;
/**
* Collect nodes that can be parents of `Child`.
*/
export type InternalParent<Node extends UnistNode, Child extends UnistNode> = (Node extends UnistParent ? Node extends {
children: Array<infer Children>;
} ? Child extends Children ? Node : never : never : never);
/**
* Collect nodes in `Tree` that can be parents of `Child`.
*/
export type Parent<Tree extends UnistNode, Child extends UnistNode> = InternalParent<InclusiveDescendant<Tree>, Child>;
/**
* Collect nodes in `Tree` that can be ancestors of `Child`.
*/
export type InternalAncestor<Node extends UnistNode, Child extends UnistNode, Max extends Uint = 10, Depth extends Uint = 0> = (Depth extends Max ? never : InternalParent<Node, Child> | InternalAncestor<Node, InternalParent<Node, Child>, Max, Increment<Depth>>);
/**
* Collect nodes in `Tree` that can be ancestors of `Child`.
*/
export type Ancestor<Tree extends UnistNode, Child extends UnistNode> = InternalAncestor<InclusiveDescendant<Tree>, Child>;
/**
* Collect all (inclusive) descendants of `Tree`.
*
* > 👉 **Note**: for performance reasons, this seems to be the fastest way to
* > recurse without actually running into an infinite loop, which the
* > previous version did.
* >
* > Practically, a max of `2` is typically enough assuming a `Root` is
* > passed, but it doesn’t improve performance.
* > It gets higher with `List > ListItem > Table > TableRow > TableCell`.
* > Using up to `10` doesn’t hurt or help either.
*/
export type InclusiveDescendant<Tree extends UnistNode, Max extends Uint = 10, Depth extends Uint = 0> = (Tree extends UnistParent ? Depth extends Max ? Tree : Tree | InclusiveDescendant<Tree["children"][number], Max, Increment<Depth>> : Tree);
/**
* Union of the action types.
*/
export type Action = "skip" | boolean;
/**
* Move to the sibling at `index` next (after node itself is completely
* traversed).
*
* Useful if mutating the tree, such as removing the node the visitor is
* currently on, or any of its previous siblings.
* Results less than 0 or greater than or equal to `children.length` stop
* traversing the parent.
*/
export type Index = number;
/**
* List with one or two values, the first an action, the second an index.
*/
export type ActionTuple = [(Action | null | undefined | void)?, (Index | null | undefined)?];
/**
* Any value that can be returned from a visitor.
*/
export type VisitorResult = Action | ActionTuple | Index | null | undefined | void;
/**
* Handle a node (matching `test`, if given).
*
* Visitors are free to transform `node`.
* They can also transform the parent of node (the last of `ancestors`).
*
* Replacing `node` itself, if `SKIP` is not returned, still causes its
* descendants to be walked (which is a bug).
*
* When adding or removing previous siblings of `node` (or next siblings, in
* case of reverse), the `Visitor` should return a new `Index` to specify the
* sibling to traverse after `node` is traversed.
* Adding or removing next siblings of `node` (or previous siblings, in case
* of reverse) is handled as expected without needing to return a new `Index`.
*
* Removing the children property of an ancestor still results in them being
* traversed.
*/
export type Visitor<Visited extends UnistNode = UnistNode, VisitedParents extends UnistParent = UnistParent> = (node: Visited, ancestors: Array<VisitedParents>) => VisitorResult;
/**
* Build a typed `Visitor` function from a tree and a test.
*
* It will infer which values are passed as `node` and which as `parents`.
*/
export type BuildVisitor<Tree extends UnistNode = UnistNode, Check extends Test = Test> = Visitor<Matches<InclusiveDescendant<Tree>, Check>, Ancestor<Tree, Matches<InclusiveDescendant<Tree>, Check>>>;
import type { Node as UnistNode } from 'unist';
import type { Parent as UnistParent } from 'unist';
//# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,25 @@
# Security Policies and Procedures
## Reporting a Bug
The `cookie` team and community take all security bugs seriously. Thank
you for improving the security of the project. We appreciate your efforts and
responsible disclosure and will make every effort to acknowledge your
contributions.
Report security bugs by emailing the current owner(s) of `cookie`. This
information can be found in the npm registry using the command
`npm owner ls cookie`.
If unsure or unable to get the information from the above, open an issue
in the [project issue tracker](https://github.com/jshttp/cookie/issues)
asking for the current contact information.
To ensure the timely response to your report, please ensure that the entirety
of the report is contained within the email body and not solely behind a web
link or an attachment.
At least one owner will acknowledge your email within 48 hours, and will send a
more detailed response within 48 hours indicating the next steps in handling
your report. After the initial reply to your report, the owners will
endeavor to keep you informed of the progress towards a fix and full
announcement, and may ask for additional information or guidance.
@@ -0,0 +1,251 @@
/**
* Some of the internal operations of micromark do lots of editing
* operations on very large arrays. This runs into problems with two
* properties of most circa-2020 JavaScript interpreters:
*
* - Array-length modifications at the high end of an array (push/pop) are
* expected to be common and are implemented in (amortized) time
* proportional to the number of elements added or removed, whereas
* other operations (shift/unshift and splice) are much less efficient.
* - Function arguments are passed on the stack, so adding tens of thousands
* of elements to an array with `arr.push(...newElements)` will frequently
* cause stack overflows. (see <https://stackoverflow.com/questions/22123769/rangeerror-maximum-call-stack-size-exceeded-why>)
*
* SpliceBuffers are an implementation of gap buffers, which are a
* generalization of the "queue made of two stacks" idea. The splice buffer
* maintains a cursor, and moving the cursor has cost proportional to the
* distance the cursor moves, but inserting, deleting, or splicing in
* new information at the cursor is as efficient as the push/pop operation.
* This allows for an efficient sequence of splices (or pushes, pops, shifts,
* or unshifts) as long such edits happen at the same part of the array or
* generally sweep through the array from the beginning to the end.
*
* The interface for splice buffers also supports large numbers of inputs by
* passing a single array argument rather passing multiple arguments on the
* function call stack.
*
* @template T
* Item type.
*/
export class SpliceBuffer {
/**
* @param {ReadonlyArray<T> | null | undefined} [initial]
* Initial items (optional).
* @returns
* Splice buffer.
*/
constructor(initial) {
/** @type {Array<T>} */
this.left = initial ? [...initial] : [];
/** @type {Array<T>} */
this.right = [];
}
/**
* Array access;
* does not move the cursor.
*
* @param {number} index
* Index.
* @return {T}
* Item.
*/
get(index) {
if (index < 0 || index >= this.left.length + this.right.length) {
throw new RangeError('Cannot access index `' + index + '` in a splice buffer of size `' + (this.left.length + this.right.length) + '`');
}
if (index < this.left.length) return this.left[index];
return this.right[this.right.length - index + this.left.length - 1];
}
/**
* The length of the splice buffer, one greater than the largest index in the
* array.
*/
get length() {
return this.left.length + this.right.length;
}
/**
* Remove and return `list[0]`;
* moves the cursor to `0`.
*
* @returns {T | undefined}
* Item, optional.
*/
shift() {
this.setCursor(0);
return this.right.pop();
}
/**
* Slice the buffer to get an array;
* does not move the cursor.
*
* @param {number} start
* Start.
* @param {number | null | undefined} [end]
* End (optional).
* @returns {Array<T>}
* Array of items.
*/
slice(start, end) {
/** @type {number} */
const stop = end === null || end === undefined ? Number.POSITIVE_INFINITY : end;
if (stop < this.left.length) {
return this.left.slice(start, stop);
}
if (start > this.left.length) {
return this.right.slice(this.right.length - stop + this.left.length, this.right.length - start + this.left.length).reverse();
}
return this.left.slice(start).concat(this.right.slice(this.right.length - stop + this.left.length).reverse());
}
/**
* Mimics the behavior of Array.prototype.splice() except for the change of
* interface necessary to avoid segfaults when patching in very large arrays.
*
* This operation moves cursor is moved to `start` and results in the cursor
* placed after any inserted items.
*
* @param {number} start
* Start;
* zero-based index at which to start changing the array;
* negative numbers count backwards from the end of the array and values
* that are out-of bounds are clamped to the appropriate end of the array.
* @param {number | null | undefined} [deleteCount=0]
* Delete count (default: `0`);
* maximum number of elements to delete, starting from start.
* @param {Array<T> | null | undefined} [items=[]]
* Items to include in place of the deleted items (default: `[]`).
* @return {Array<T>}
* Any removed items.
*/
splice(start, deleteCount, items) {
/** @type {number} */
const count = deleteCount || 0;
this.setCursor(Math.trunc(start));
const removed = this.right.splice(this.right.length - count, Number.POSITIVE_INFINITY);
if (items) chunkedPush(this.left, items);
return removed.reverse();
}
/**
* Remove and return the highest-numbered item in the array, so
* `list[list.length - 1]`;
* Moves the cursor to `length`.
*
* @returns {T | undefined}
* Item, optional.
*/
pop() {
this.setCursor(Number.POSITIVE_INFINITY);
return this.left.pop();
}
/**
* Inserts a single item to the high-numbered side of the array;
* moves the cursor to `length`.
*
* @param {T} item
* Item.
* @returns {undefined}
* Nothing.
*/
push(item) {
this.setCursor(Number.POSITIVE_INFINITY);
this.left.push(item);
}
/**
* Inserts many items to the high-numbered side of the array.
* Moves the cursor to `length`.
*
* @param {Array<T>} items
* Items.
* @returns {undefined}
* Nothing.
*/
pushMany(items) {
this.setCursor(Number.POSITIVE_INFINITY);
chunkedPush(this.left, items);
}
/**
* Inserts a single item to the low-numbered side of the array;
* Moves the cursor to `0`.
*
* @param {T} item
* Item.
* @returns {undefined}
* Nothing.
*/
unshift(item) {
this.setCursor(0);
this.right.push(item);
}
/**
* Inserts many items to the low-numbered side of the array;
* moves the cursor to `0`.
*
* @param {Array<T>} items
* Items.
* @returns {undefined}
* Nothing.
*/
unshiftMany(items) {
this.setCursor(0);
chunkedPush(this.right, items.reverse());
}
/**
* Move the cursor to a specific position in the array. Requires
* time proportional to the distance moved.
*
* If `n < 0`, the cursor will end up at the beginning.
* If `n > length`, the cursor will end up at the end.
*
* @param {number} n
* Position.
* @return {undefined}
* Nothing.
*/
setCursor(n) {
if (n === this.left.length || n > this.left.length && this.right.length === 0 || n < 0 && this.left.length === 0) return;
if (n < this.left.length) {
// Move cursor to the this.left
const removed = this.left.splice(n, Number.POSITIVE_INFINITY);
chunkedPush(this.right, removed.reverse());
} else {
// Move cursor to the this.right
const removed = this.right.splice(this.left.length + this.right.length - n, Number.POSITIVE_INFINITY);
chunkedPush(this.left, removed.reverse());
}
}
}
/**
* Avoid stack overflow by pushing items onto the stack in segments
*
* @template T
* Item type.
* @param {Array<T>} list
* List to inject into.
* @param {ReadonlyArray<T>} right
* Items to inject.
* @return {undefined}
* Nothing.
*/
function chunkedPush(list, right) {
/** @type {number} */
let chunkStart = 0;
if (right.length < 10000) {
list.push(...right);
} else {
while (chunkStart < right.length) {
list.push(...right.slice(chunkStart, chunkStart + 10000));
chunkStart += 10000;
}
}
}
@@ -0,0 +1,24 @@
/**
* Extractor function for an UpdateExpression type value node.
* An update expression is an expression with an update operator.
* For example, foo++ will evaluate to foo + 1.
*
* @param - value - AST Value object with type `UpdateExpression`
* @returns - The extracted value converted to correct type.
*/
export default function extractValueFromUpdateExpression(value) {
// eslint-disable-next-line global-require
const getValue = require('.').default;
const { operator, argument, prefix } = value;
let val = getValue(argument);
switch (operator) {
case '++':
return prefix ? ++val : val++; // eslint-disable-line no-plusplus
case '--':
return prefix ? --val : val--; // eslint-disable-line no-plusplus
default:
return undefined;
}
}
@@ -0,0 +1,54 @@
/**
* exception-stream.js: TODO: add file header handler.
*
* (C) 2010 Charlie Robbins
* MIT LICENCE
*/
'use strict';
const { Writable } = require('readable-stream');
/**
* TODO: add class description.
* @type {ExceptionStream}
* @extends {Writable}
*/
module.exports = class ExceptionStream extends Writable {
/**
* Constructor function for the ExceptionStream responsible for wrapping a
* TransportStream; only allowing writes of `info` objects with
* `info.exception` set to true.
* @param {!TransportStream} transport - Stream to filter to exceptions
*/
constructor(transport) {
super({ objectMode: true });
if (!transport) {
throw new Error('ExceptionStream requires a TransportStream instance.');
}
// Remark (indexzero): we set `handleExceptions` here because it's the
// predicate checked in ExceptionHandler.prototype.__getExceptionHandlers
this.handleExceptions = true;
this.transport = transport;
}
/**
* Writes the info object to our transport instance if (and only if) the
* `exception` property is set on the info.
* @param {mixed} info - TODO: add param description.
* @param {mixed} enc - TODO: add param description.
* @param {mixed} callback - TODO: add param description.
* @returns {mixed} - TODO: add return description.
* @private
*/
_write(info, enc, callback) {
if (info.exception) {
return this.transport.log(info, callback);
}
callback();
return true;
}
};
@@ -0,0 +1,432 @@
'use strict'
// A readable tar stream creator
// Technically, this is a transform stream that you write paths into,
// and tar format comes out of.
// The `add()` method is like `write()` but returns this,
// and end() return `this` as well, so you can
// do `new Pack(opt).add('files').add('dir').end().pipe(output)
// You could also do something like:
// streamOfPaths().pipe(new Pack()).pipe(new fs.WriteStream('out.tar'))
class PackJob {
constructor (path, absolute) {
this.path = path || './'
this.absolute = absolute
this.entry = null
this.stat = null
this.readdir = null
this.pending = false
this.ignore = false
this.piped = false
}
}
const { Minipass } = require('minipass')
const zlib = require('minizlib')
const ReadEntry = require('./read-entry.js')
const WriteEntry = require('./write-entry.js')
const WriteEntrySync = WriteEntry.Sync
const WriteEntryTar = WriteEntry.Tar
const Yallist = require('yallist')
const EOF = Buffer.alloc(1024)
const ONSTAT = Symbol('onStat')
const ENDED = Symbol('ended')
const QUEUE = Symbol('queue')
const CURRENT = Symbol('current')
const PROCESS = Symbol('process')
const PROCESSING = Symbol('processing')
const PROCESSJOB = Symbol('processJob')
const JOBS = Symbol('jobs')
const JOBDONE = Symbol('jobDone')
const ADDFSENTRY = Symbol('addFSEntry')
const ADDTARENTRY = Symbol('addTarEntry')
const STAT = Symbol('stat')
const READDIR = Symbol('readdir')
const ONREADDIR = Symbol('onreaddir')
const PIPE = Symbol('pipe')
const ENTRY = Symbol('entry')
const ENTRYOPT = Symbol('entryOpt')
const WRITEENTRYCLASS = Symbol('writeEntryClass')
const WRITE = Symbol('write')
const ONDRAIN = Symbol('ondrain')
const fs = require('fs')
const path = require('path')
const warner = require('./warn-mixin.js')
const normPath = require('./normalize-windows-path.js')
const Pack = warner(class Pack extends Minipass {
constructor (opt) {
super(opt)
opt = opt || Object.create(null)
this.opt = opt
this.file = opt.file || ''
this.cwd = opt.cwd || process.cwd()
this.maxReadSize = opt.maxReadSize
this.preservePaths = !!opt.preservePaths
this.strict = !!opt.strict
this.noPax = !!opt.noPax
this.prefix = normPath(opt.prefix || '')
this.linkCache = opt.linkCache || new Map()
this.statCache = opt.statCache || new Map()
this.readdirCache = opt.readdirCache || new Map()
this[WRITEENTRYCLASS] = WriteEntry
if (typeof opt.onwarn === 'function') {
this.on('warn', opt.onwarn)
}
this.portable = !!opt.portable
this.zip = null
if (opt.gzip || opt.brotli) {
if (opt.gzip && opt.brotli) {
throw new TypeError('gzip and brotli are mutually exclusive')
}
if (opt.gzip) {
if (typeof opt.gzip !== 'object') {
opt.gzip = {}
}
if (this.portable) {
opt.gzip.portable = true
}
this.zip = new zlib.Gzip(opt.gzip)
}
if (opt.brotli) {
if (typeof opt.brotli !== 'object') {
opt.brotli = {}
}
this.zip = new zlib.BrotliCompress(opt.brotli)
}
this.zip.on('data', chunk => super.write(chunk))
this.zip.on('end', _ => super.end())
this.zip.on('drain', _ => this[ONDRAIN]())
this.on('resume', _ => this.zip.resume())
} else {
this.on('drain', this[ONDRAIN])
}
this.noDirRecurse = !!opt.noDirRecurse
this.follow = !!opt.follow
this.noMtime = !!opt.noMtime
this.mtime = opt.mtime || null
this.filter = typeof opt.filter === 'function' ? opt.filter : _ => true
this[QUEUE] = new Yallist()
this[JOBS] = 0
this.jobs = +opt.jobs || 4
this[PROCESSING] = false
this[ENDED] = false
}
[WRITE] (chunk) {
return super.write(chunk)
}
add (path) {
this.write(path)
return this
}
end (path) {
if (path) {
this.write(path)
}
this[ENDED] = true
this[PROCESS]()
return this
}
write (path) {
if (this[ENDED]) {
throw new Error('write after end')
}
if (path instanceof ReadEntry) {
this[ADDTARENTRY](path)
} else {
this[ADDFSENTRY](path)
}
return this.flowing
}
[ADDTARENTRY] (p) {
const absolute = normPath(path.resolve(this.cwd, p.path))
// in this case, we don't have to wait for the stat
if (!this.filter(p.path, p)) {
p.resume()
} else {
const job = new PackJob(p.path, absolute, false)
job.entry = new WriteEntryTar(p, this[ENTRYOPT](job))
job.entry.on('end', _ => this[JOBDONE](job))
this[JOBS] += 1
this[QUEUE].push(job)
}
this[PROCESS]()
}
[ADDFSENTRY] (p) {
const absolute = normPath(path.resolve(this.cwd, p))
this[QUEUE].push(new PackJob(p, absolute))
this[PROCESS]()
}
[STAT] (job) {
job.pending = true
this[JOBS] += 1
const stat = this.follow ? 'stat' : 'lstat'
fs[stat](job.absolute, (er, stat) => {
job.pending = false
this[JOBS] -= 1
if (er) {
this.emit('error', er)
} else {
this[ONSTAT](job, stat)
}
})
}
[ONSTAT] (job, stat) {
this.statCache.set(job.absolute, stat)
job.stat = stat
// now we have the stat, we can filter it.
if (!this.filter(job.path, stat)) {
job.ignore = true
}
this[PROCESS]()
}
[READDIR] (job) {
job.pending = true
this[JOBS] += 1
fs.readdir(job.absolute, (er, entries) => {
job.pending = false
this[JOBS] -= 1
if (er) {
return this.emit('error', er)
}
this[ONREADDIR](job, entries)
})
}
[ONREADDIR] (job, entries) {
this.readdirCache.set(job.absolute, entries)
job.readdir = entries
this[PROCESS]()
}
[PROCESS] () {
if (this[PROCESSING]) {
return
}
this[PROCESSING] = true
for (let w = this[QUEUE].head;
w !== null && this[JOBS] < this.jobs;
w = w.next) {
this[PROCESSJOB](w.value)
if (w.value.ignore) {
const p = w.next
this[QUEUE].removeNode(w)
w.next = p
}
}
this[PROCESSING] = false
if (this[ENDED] && !this[QUEUE].length && this[JOBS] === 0) {
if (this.zip) {
this.zip.end(EOF)
} else {
super.write(EOF)
super.end()
}
}
}
get [CURRENT] () {
return this[QUEUE] && this[QUEUE].head && this[QUEUE].head.value
}
[JOBDONE] (job) {
this[QUEUE].shift()
this[JOBS] -= 1
this[PROCESS]()
}
[PROCESSJOB] (job) {
if (job.pending) {
return
}
if (job.entry) {
if (job === this[CURRENT] && !job.piped) {
this[PIPE](job)
}
return
}
if (!job.stat) {
if (this.statCache.has(job.absolute)) {
this[ONSTAT](job, this.statCache.get(job.absolute))
} else {
this[STAT](job)
}
}
if (!job.stat) {
return
}
// filtered out!
if (job.ignore) {
return
}
if (!this.noDirRecurse && job.stat.isDirectory() && !job.readdir) {
if (this.readdirCache.has(job.absolute)) {
this[ONREADDIR](job, this.readdirCache.get(job.absolute))
} else {
this[READDIR](job)
}
if (!job.readdir) {
return
}
}
// we know it doesn't have an entry, because that got checked above
job.entry = this[ENTRY](job)
if (!job.entry) {
job.ignore = true
return
}
if (job === this[CURRENT] && !job.piped) {
this[PIPE](job)
}
}
[ENTRYOPT] (job) {
return {
onwarn: (code, msg, data) => this.warn(code, msg, data),
noPax: this.noPax,
cwd: this.cwd,
absolute: job.absolute,
preservePaths: this.preservePaths,
maxReadSize: this.maxReadSize,
strict: this.strict,
portable: this.portable,
linkCache: this.linkCache,
statCache: this.statCache,
noMtime: this.noMtime,
mtime: this.mtime,
prefix: this.prefix,
}
}
[ENTRY] (job) {
this[JOBS] += 1
try {
return new this[WRITEENTRYCLASS](job.path, this[ENTRYOPT](job))
.on('end', () => this[JOBDONE](job))
.on('error', er => this.emit('error', er))
} catch (er) {
this.emit('error', er)
}
}
[ONDRAIN] () {
if (this[CURRENT] && this[CURRENT].entry) {
this[CURRENT].entry.resume()
}
}
// like .pipe() but using super, because our write() is special
[PIPE] (job) {
job.piped = true
if (job.readdir) {
job.readdir.forEach(entry => {
const p = job.path
const base = p === './' ? '' : p.replace(/\/*$/, '/')
this[ADDFSENTRY](base + entry)
})
}
const source = job.entry
const zip = this.zip
if (zip) {
source.on('data', chunk => {
if (!zip.write(chunk)) {
source.pause()
}
})
} else {
source.on('data', chunk => {
if (!super.write(chunk)) {
source.pause()
}
})
}
}
pause () {
if (this.zip) {
this.zip.pause()
}
return super.pause()
}
})
class PackSync extends Pack {
constructor (opt) {
super(opt)
this[WRITEENTRYCLASS] = WriteEntrySync
}
// pause/resume are no-ops in sync streams.
pause () {}
resume () {}
[STAT] (job) {
const stat = this.follow ? 'statSync' : 'lstatSync'
this[ONSTAT](job, fs[stat](job.absolute))
}
[READDIR] (job, stat) {
this[ONREADDIR](job, fs.readdirSync(job.absolute))
}
// gotta get it all in this tick
[PIPE] (job) {
const source = job.entry
const zip = this.zip
if (job.readdir) {
job.readdir.forEach(entry => {
const p = job.path
const base = p === './' ? '' : p.replace(/\/*$/, '/')
this[ADDFSENTRY](base + entry)
})
}
if (zip) {
source.on('data', chunk => {
zip.write(chunk)
})
} else {
source.on('data', chunk => {
super[WRITE](chunk)
})
}
}
}
Pack.Sync = PackSync
module.exports = Pack
@@ -0,0 +1,13 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = getImplicitRoleForForm;
/**
* Returns the implicit role for a form tag.
*/
function getImplicitRoleForForm() {
return 'form';
}
module.exports = exports.default;
@@ -0,0 +1 @@
{"version":3,"file":"defined-info.d.ts","sourceRoot":"","sources":["defined-info.js"],"names":[],"mappings":"AAWA;IACE;;;;;;;;;;;;OAYG;IACH,sBAXW,MAAM,aAEN,MAAM,SAEN,MAAM,GAAG,IAAI,GAAG,SAAS,UAEzB,KAAK,GAAG,SAAS,EAkB3B;CACF;qBAnCkB,WAAW;2BAHN,sBAAsB"}
@@ -0,0 +1,27 @@
/*
* Copyright 2020 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
import {isScrollable} from './isScrollable';
export function getScrollParent(node: Element, checkForOverflow?: boolean): Element {
let scrollableNode: Element | null = node;
if (isScrollable(scrollableNode, checkForOverflow)) {
scrollableNode = scrollableNode.parentElement;
}
while (scrollableNode && !isScrollable(scrollableNode, checkForOverflow)) {
scrollableNode = scrollableNode.parentElement;
}
return scrollableNode || document.scrollingElement || document.documentElement;
}
@@ -0,0 +1,118 @@
import * as util from "../core/util.js";
const error = () => {
const Sizable = {
string: { unit: "caràcters", verb: "contenir" },
file: { unit: "bytes", verb: "contenir" },
array: { unit: "elements", verb: "contenir" },
set: { unit: "elements", verb: "contenir" },
};
function getSizing(origin) {
return Sizable[origin] ?? null;
}
const parsedType = (data) => {
const t = typeof data;
switch (t) {
case "number": {
return Number.isNaN(data) ? "NaN" : "number";
}
case "object": {
if (Array.isArray(data)) {
return "array";
}
if (data === null) {
return "null";
}
if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
return data.constructor.name;
}
}
}
return t;
};
const Nouns = {
regex: "entrada",
email: "adreça electrònica",
url: "URL",
emoji: "emoji",
uuid: "UUID",
uuidv4: "UUIDv4",
uuidv6: "UUIDv6",
nanoid: "nanoid",
guid: "GUID",
cuid: "cuid",
cuid2: "cuid2",
ulid: "ULID",
xid: "XID",
ksuid: "KSUID",
datetime: "data i hora ISO",
date: "data ISO",
time: "hora ISO",
duration: "durada ISO",
ipv4: "adreça IPv4",
ipv6: "adreça IPv6",
cidrv4: "rang IPv4",
cidrv6: "rang IPv6",
base64: "cadena codificada en base64",
base64url: "cadena codificada en base64url",
json_string: "cadena JSON",
e164: "número E.164",
jwt: "JWT",
template_literal: "entrada",
};
return (issue) => {
switch (issue.code) {
case "invalid_type":
return `Tipus invàlid: s'esperava ${issue.expected}, s'ha rebut ${parsedType(issue.input)}`;
// return `Tipus invàlid: s'esperava ${issue.expected}, s'ha rebut ${util.getParsedType(issue.input)}`;
case "invalid_value":
if (issue.values.length === 1)
return `Valor invàlid: s'esperava ${util.stringifyPrimitive(issue.values[0])}`;
return `Opció invàlida: s'esperava una de ${util.joinValues(issue.values, " o ")}`;
case "too_big": {
const adj = issue.inclusive ? "com a màxim" : "menys de";
const sizing = getSizing(issue.origin);
if (sizing)
return `Massa gran: s'esperava que ${issue.origin ?? "el valor"} contingués ${adj} ${issue.maximum.toString()} ${sizing.unit ?? "elements"}`;
return `Massa gran: s'esperava que ${issue.origin ?? "el valor"} fos ${adj} ${issue.maximum.toString()}`;
}
case "too_small": {
const adj = issue.inclusive ? "com a mínim" : "més de";
const sizing = getSizing(issue.origin);
if (sizing) {
return `Massa petit: s'esperava que ${issue.origin} contingués ${adj} ${issue.minimum.toString()} ${sizing.unit}`;
}
return `Massa petit: s'esperava que ${issue.origin} fos ${adj} ${issue.minimum.toString()}`;
}
case "invalid_format": {
const _issue = issue;
if (_issue.format === "starts_with") {
return `Format invàlid: ha de començar amb "${_issue.prefix}"`;
}
if (_issue.format === "ends_with")
return `Format invàlid: ha d'acabar amb "${_issue.suffix}"`;
if (_issue.format === "includes")
return `Format invàlid: ha d'incloure "${_issue.includes}"`;
if (_issue.format === "regex")
return `Format invàlid: ha de coincidir amb el patró ${_issue.pattern}`;
return `Format invàlid per a ${Nouns[_issue.format] ?? issue.format}`;
}
case "not_multiple_of":
return `Número invàlid: ha de ser múltiple de ${issue.divisor}`;
case "unrecognized_keys":
return `Clau${issue.keys.length > 1 ? "s" : ""} no reconeguda${issue.keys.length > 1 ? "s" : ""}: ${util.joinValues(issue.keys, ", ")}`;
case "invalid_key":
return `Clau invàlida a ${issue.origin}`;
case "invalid_union":
return "Entrada invàlida"; // Could also be "Tipus d'unió invàlid" but "Entrada invàlida" is more general
case "invalid_element":
return `Element invàlid a ${issue.origin}`;
default:
return `Entrada invàlida`;
}
};
};
export default function () {
return {
localeError: error(),
};
}
@@ -0,0 +1,93 @@
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
import { Markers } from '../primitives.js';
import { rewireSource } from '../util.js';
const zeroWidth = {
start: 0,
tag: 0,
type: 0,
name: 0,
};
const getWidth = (markers = Markers) => (w, { tokens: t }) => ({
start: t.delimiter === markers.start ? t.start.length : w.start,
tag: Math.max(w.tag, t.tag.length),
type: Math.max(w.type, t.type.length),
name: Math.max(w.name, t.name.length),
});
const space = (len) => ''.padStart(len, ' ');
export default function align(markers = Markers) {
let intoTags = false;
let w;
function update(line) {
const tokens = Object.assign({}, line.tokens);
if (tokens.tag !== '')
intoTags = true;
const isEmpty = tokens.tag === '' &&
tokens.name === '' &&
tokens.type === '' &&
tokens.description === '';
// dangling '*/'
if (tokens.end === markers.end && isEmpty) {
tokens.start = space(w.start + 1);
return Object.assign(Object.assign({}, line), { tokens });
}
switch (tokens.delimiter) {
case markers.start:
tokens.start = space(w.start);
break;
case markers.delim:
tokens.start = space(w.start + 1);
break;
default:
tokens.delimiter = '';
tokens.start = space(w.start + 2); // compensate delimiter
}
if (!intoTags) {
tokens.postDelimiter = tokens.description === '' ? '' : ' ';
return Object.assign(Object.assign({}, line), { tokens });
}
const nothingAfter = {
delim: false,
tag: false,
type: false,
name: false,
};
if (tokens.description === '') {
nothingAfter.name = true;
tokens.postName = '';
if (tokens.name === '') {
nothingAfter.type = true;
tokens.postType = '';
if (tokens.type === '') {
nothingAfter.tag = true;
tokens.postTag = '';
if (tokens.tag === '') {
nothingAfter.delim = true;
}
}
}
}
tokens.postDelimiter = nothingAfter.delim ? '' : ' ';
if (!nothingAfter.tag)
tokens.postTag = space(w.tag - tokens.tag.length + 1);
if (!nothingAfter.type)
tokens.postType = space(w.type - tokens.type.length + 1);
if (!nothingAfter.name)
tokens.postName = space(w.name - tokens.name.length + 1);
return Object.assign(Object.assign({}, line), { tokens });
}
return (_a) => {
var { source } = _a, fields = __rest(_a, ["source"]);
w = source.reduce(getWidth(markers), Object.assign({}, zeroWidth));
return rewireSource(Object.assign(Object.assign({}, fields), { source: source.map(update) }));
};
}
@@ -0,0 +1,373 @@
export default `flf2a$ 1 1 11 -1 11 0
binary.flf (C) 1994 by Victor Parada (vparada@inf.utfsm.cl) 94/12/05
figlet 2.1 font, includes ISO Latin-1, excludes "-D" option chars.
Spaces are not shown as binary. If this is required, change "$@" below
to "00100000 @". Change to "@" to remove the hardspace between words.
Note that figlet always removes spaces when it moves words to a new line.
Try option "-m 0" to remove the space between letters (octets).
$@
00100001 @
00100010 @
00100011 @
00100100 @
00100101 @
00100110 @
00100111 @
00101000 @
00101001 @
00101010 @
00101011 @
00101100 @
00101101 @
00101110 @
00101111 @
00110000 @
00110001 @
00110010 @
00110011 @
00110100 @
00110101 @
00110110 @
00110111 @
00111000 @
00111001 @
00111010 @
00111011 @
00111100 @
00111101 @
00111110 @
00111111 @
01000000 @
01000001 @
01000010 @
01000011 @
01000100 @
01000101 @
01000110 @
01000111 @
01001000 @
01001001 @
01001010 @
01001011 @
01001100 @
01001101 @
01001110 @
01001111 @
01010000 @
01010001 @
01010010 @
01010011 @
01010100 @
01010101 @
01010110 @
01010111 @
01011000 @
01011001 @
01011010 @
01011011 @
01011100 @
01011101 @
01011110 @
01011111 @
01100000 @
01100001 @
01100010 @
01100011 @
01100100 @
01100101 @
01100110 @
01100111 @
01101000 @
01101001 @
01101010 @
01101011 @
01101100 @
01101101 @
01101110 @
01101111 @
01110000 @
01110001 @
01110010 @
01110011 @
01110100 @
01110101 @
01110110 @
01110111 @
01111000 @
01111001 @
01111010 @
01111011 @
01111100 @
01111101 @
01111110 @
@
@
@
@
@
@
@
127
01111111 @
128
10000000 @
129
10000001 @
130
10000010 @
131
10000011 @
132
10000100 @
133
10000101 @
134
10000110 @
135
10000111 @
136
10001000 @
137
10001001 @
138
10001010 @
139
10001011 @
140
10001100 @
141
10001101 @
142
10001110 @
143
10001111 @
144
10010000 @
145
10010001 @
146
10010010 @
147
10010011 @
148
10010100 @
149
10010101 @
150
10010110 @
151
10010111 @
152
10011000 @
153
10011001 @
154
10011010 @
155
10011011 @
156
10011100 @
157
10011101 @
158
10011110 @
159
10011111 @
160
10100000 @
161
10100001 @
162
10100010 @
163
10100011 @
164
10100100 @
165
10100101 @
166
10100110 @
167
10100111 @
168
10101000 @
169
10101001 @
170
10101010 @
171
10101011 @
172
10101100 @
173
10101101 @
174
10101110 @
175
10101111 @
176
10110000 @
177
10110001 @
178
10110010 @
179
10110011 @
180
10110100 @
181
10110101 @
182
10110110 @
183
10110111 @
184
10111000 @
185
10111001 @
186
10111010 @
187
10111011 @
188
10111100 @
189
10111101 @
190
10111110 @
191
10111111 @
192
11000000 @
193
11000001 @
194
11000010 @
195
11000011 @
196
11000100 @
197
11000101 @
198
11000110 @
199
11000111 @
200
11001000 @
201
11001001 @
202
11001010 @
203
11001011 @
204
11001100 @
205
11001101 @
206
11001110 @
207
11001111 @
208
11010000 @
209
11010001 @
210
11010010 @
211
11010011 @
212
11010100 @
213
11010101 @
214
11010110 @
215
11010111 @
216
11011000 @
217
11011001 @
218
11011010 @
219
11011011 @
220
11011100 @
221
11011101 @
222
11011110 @
223
11011111 @
224
11100000 @
225
11100001 @
226
11100010 @
227
11100011 @
228
11100100 @
229
11100101 @
230
11100110 @
231
11100111 @
232
11101000 @
233
11101001 @
234
11101010 @
235
11101011 @
236
11101100 @
237
11101101 @
238
11101110 @
239
11101111 @
240
11110000 @
241
11110001 @
242
11110010 @
243
11110011 @
244
11110100 @
245
11110101 @
246
11110110 @
247
11110111 @
248
11111000 @
249
11111001 @
250
11111010 @
251
11111011 @
252
11111100 @
253
11111101 @
254
11111110 @
255
11111111 @
`
@@ -0,0 +1,88 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var config_loader_1 = require("../config-loader");
var path_1 = require("path");
describe("config-loader", function () {
it("should use explicitParams when set", function () {
var result = (0, config_loader_1.configLoader)({
explicitParams: {
baseUrl: "/foo/bar",
paths: {
asd: ["asd"],
},
},
cwd: "/baz",
});
var successResult = result;
// assert.equal(successResult.resultType, "success");
// assert.equal(successResult.absoluteBaseUrl, "/foo/bar");
// assert.equal(successResult.paths["asd"][0], "asd");
expect(successResult.resultType).toBe("success");
expect(successResult.absoluteBaseUrl).toBe("/foo/bar");
expect(successResult.paths["asd"][0]).toBe("asd");
});
it("should use explicitParams when set and add cwd when path is relative", function () {
var result = (0, config_loader_1.configLoader)({
explicitParams: {
baseUrl: "bar/",
paths: {
asd: ["asd"],
},
},
cwd: "/baz",
});
var successResult = result;
// assert.equal(successResult.resultType, "success");
// assert.equal(successResult.absoluteBaseUrl, join("/baz", "bar/"));
expect(successResult.resultType).toBe("success");
expect(successResult.absoluteBaseUrl).toBe((0, path_1.join)("/baz", "bar/"));
});
it("should fallback to tsConfigLoader when explicitParams is not set", function () {
var result = (0, config_loader_1.configLoader)({
explicitParams: undefined,
cwd: "/baz",
// tslint:disable-next-line:no-any
tsConfigLoader: function (_) { return ({
tsConfigPath: "/baz/tsconfig.json",
baseUrl: "./src",
paths: {},
}); },
});
var successResult = result;
// assert.equal(successResult.resultType, "success");
// assert.equal(successResult.absoluteBaseUrl, join("/baz", "src"));
expect(successResult.resultType).toBe("success");
expect(successResult.absoluteBaseUrl).toBe((0, path_1.join)("/baz", "src"));
});
it("should show an error message when baseUrl is missing", function () {
var result = (0, config_loader_1.configLoader)({
explicitParams: undefined,
cwd: "/baz",
// tslint:disable-next-line:no-any
tsConfigLoader: function (_) { return ({
tsConfigPath: "/baz/tsconfig.json",
baseUrl: undefined,
paths: {},
}); },
});
var failResult = result;
// assert.equal(failResult.resultType, "failed");
// assert.isTrue(failResult.message.indexOf("baseUrl") > -1);
expect(failResult.resultType).toBe("failed");
expect(failResult.message.indexOf("baseUrl") > -1).toBeTruthy();
});
it("should presume cwd to be a tsconfig file when loadConfig is called with absolute path to tsconfig.json", function () {
// using tsconfig-named.json to ensure that future changes to fix
// https://github.com/dividab/tsconfig-paths/issues/31
// do not pass this test case just because of a directory walk looking
// for tsconfig.json
var configFile = (0, path_1.join)(__dirname, "tsconfig-named.json");
var result = (0, config_loader_1.loadConfig)(configFile);
var successResult = result;
// assert.equal(successResult.resultType, "success");
// assert.equal(successResult.configFileAbsolutePath, configFile);
expect(successResult.resultType).toBe("success");
expect(successResult.configFileAbsolutePath).toBe(configFile);
});
});
//# sourceMappingURL=config-loader.test.js.map
@@ -0,0 +1 @@
{"version":3,"file":"SnapshotManager.spec.d.ts","sourceRoot":"","sources":["../../../../src/container/services/SnapshotManager.spec.ts"],"names":[],"mappings":""}
Loaded 100 of 35554 files, more files were not shown because too many files have changed in this diff. Show more