deploy: v0.12 fix 存档key名

This commit is contained in:
2026-06-24 03:09:02 +00:00
parent 7a08d49fe3
commit e0a5281119
58743 changed files with 7297269 additions and 39505 deletions
+9
View File
@@ -0,0 +1,9 @@
MIT License
Copyright (c) 2021present Artem Zakharchenko
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.
+146
View File
@@ -0,0 +1,146 @@
# `outvariant`
Type-safe implementation of invariant with positionals.
## Motivation
### Type-safely
This implementation asserts the given predicate expression so it's treated as non-nullable after the `invariant` call:
```ts
// Regular invariant:
invariant(user, 'Failed to fetch')
user?.firstName // "user" is possibly undefined
// Outvariant:
invariant(user, 'Failed to fetch')
user.firstName // OK, "invariant" ensured the "user" exists
```
### Positionals support
This implementation uses [rest parameters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters) to support dynamic number of positionals:
```js
invariant(predicate, 'Expected %s but got %s', 'one', false)
```
## What is this for?
Invariant is a shorthand function that asserts a given predicate and throws an error if that predicate is false.
Compare these two pieces of code identical in behavior:
```js
if (!token) {
throw new Error(`Expected a token to be set but got ${typeof token}`)
}
```
```js
import { invariant } from 'outvariant'
invariant(token, 'Expected a token to be set but got %s', typeof token)
```
Using `invariant` reduces the visual nesting of the code and leads to cleaner error messages thanks to formatted positionals (i.e. the `%s` (string) positional above).
## Usage
### Install
```sh
npm install outvariant
# or
yarn add outvariant
```
> You may want to install this library as a dev dependency (`-D`) based on your usage.
### Write an assertion
```js
import { invariant } from 'outvariant'
invariant(user, 'Failed to load: expected user, but got %o', user)
```
## Positionals
The following positional tokens are supported:
| Token | Expected value type |
| --------- | ------------------------------------------------------- |
| `%s` | String |
| `%d`/`%i` | Number |
| `%j` | JSON (non-stringified) |
| `%o` | Arbitrary object or object-like (i.e. a class instance) |
Whenever present in the error message, a positional token will look up the value to insert in its place from the arguments given to `invariant`.
```js
invariant(
false,
'Expected the "%s" property but got %j',
// Note that positionals are sensitive to order:
// - "firstName" replaces "%s" because it's first.
// - {"id":1} replaces "%j" because it's second.
'firstName',
{
id: 1,
}
)
```
## Polymorphic errors
It is possible to throw a custom `Error` instance using `invariant.as`:
```js
import { invariant } from 'outvariant'
class NetworkError extends Error {
constructor(message) {
super(message)
}
}
invariant.as(NetworkError, res.fulfilled, 'Failed to handle response')
```
Note that providing a custom error constructor as the argument to `invariant.as` requires the custom constructor's signature to be compatible with the `Error` class constructor.
If your error constructor has a different signature, you can pass a function as the first argument to `invariant.as` that creates a new custom error instance.
```js
import { invariant } from 'outvariant'
class NetworkError extends Error {
constructor(statusCode, message) {
super(message)
this.statusCode = statusCode
}
}
invariant.as(
(message) => new NetworkError(500, message),
res.fulfilled,
'Failed to handle response'
)
```
Abstract the error into helper functions for flexibility:
```js
function toNetworkError(statusCode) {
return (message) => new NetworkError(statusCode, message)
}
invariant.as(toNetworkError(404), res?.user?.id, 'User Not Found')
invariant.as(toNetworkError(500), res.fulfilled, 'Internal Server Error')
```
## Contributing
Please [open an issue](https://github.com/open-draft/outvariant/issues) or [submit a pull request](https://github.com/open-draft/outvariant/pulls) if you wish to contribute. Thank you.
+21
View File
@@ -0,0 +1,21 @@
declare class InvariantError extends Error {
readonly message: string;
name: string;
constructor(message: string, ...positionals: any[]);
}
interface CustomErrorConstructor {
new (message: string): Error;
}
interface CustomErrorFactory {
(message: string): Error;
}
declare type CustomError = CustomErrorConstructor | CustomErrorFactory;
declare type Invariant = {
(predicate: unknown, message: string, ...positionals: any[]): asserts predicate;
as(ErrorConstructor: CustomError, predicate: unknown, message: string, ...positionals: unknown[]): asserts predicate;
};
declare const invariant: Invariant;
declare function format(message: string, ...positionals: any[]): string;
export { CustomError, CustomErrorConstructor, CustomErrorFactory, InvariantError, format, invariant };
+113
View File
@@ -0,0 +1,113 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var src_exports = {};
__export(src_exports, {
InvariantError: () => InvariantError,
format: () => format,
invariant: () => invariant
});
module.exports = __toCommonJS(src_exports);
// src/format.ts
var POSITIONALS_EXP = /(%?)(%([sdjo]))/g;
function serializePositional(positional, flag) {
switch (flag) {
case "s":
return positional;
case "d":
case "i":
return Number(positional);
case "j":
return JSON.stringify(positional);
case "o": {
if (typeof positional === "string") {
return positional;
}
const json = JSON.stringify(positional);
if (json === "{}" || json === "[]" || /^\[object .+?\]$/.test(json)) {
return positional;
}
return json;
}
}
}
function format(message, ...positionals) {
if (positionals.length === 0) {
return message;
}
let positionalIndex = 0;
let formattedMessage = message.replace(
POSITIONALS_EXP,
(match, isEscaped, _, flag) => {
const positional = positionals[positionalIndex];
const value = serializePositional(positional, flag);
if (!isEscaped) {
positionalIndex++;
return value;
}
return match;
}
);
if (positionalIndex < positionals.length) {
formattedMessage += ` ${positionals.slice(positionalIndex).join(" ")}`;
}
formattedMessage = formattedMessage.replace(/%{2,2}/g, "%");
return formattedMessage;
}
// src/invariant.ts
var STACK_FRAMES_TO_IGNORE = 2;
function cleanErrorStack(error) {
if (!error.stack) {
return;
}
const nextStack = error.stack.split("\n");
nextStack.splice(1, STACK_FRAMES_TO_IGNORE);
error.stack = nextStack.join("\n");
}
var InvariantError = class extends Error {
constructor(message, ...positionals) {
super(message);
this.message = message;
this.name = "Invariant Violation";
this.message = format(message, ...positionals);
cleanErrorStack(this);
}
};
var invariant = (predicate, message, ...positionals) => {
if (!predicate) {
throw new InvariantError(message, ...positionals);
}
};
invariant.as = (ErrorConstructor, predicate, message, ...positionals) => {
if (!predicate) {
const isConstructor = ErrorConstructor.prototype.name != null;
const error = isConstructor ? new ErrorConstructor(format(message, positionals)) : ErrorConstructor(format(message, positionals));
throw error;
}
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
InvariantError,
format,
invariant
});
//# sourceMappingURL=index.js.map
+1
View File
File diff suppressed because one or more lines are too long
+84
View File
@@ -0,0 +1,84 @@
// src/format.ts
var POSITIONALS_EXP = /(%?)(%([sdjo]))/g;
function serializePositional(positional, flag) {
switch (flag) {
case "s":
return positional;
case "d":
case "i":
return Number(positional);
case "j":
return JSON.stringify(positional);
case "o": {
if (typeof positional === "string") {
return positional;
}
const json = JSON.stringify(positional);
if (json === "{}" || json === "[]" || /^\[object .+?\]$/.test(json)) {
return positional;
}
return json;
}
}
}
function format(message, ...positionals) {
if (positionals.length === 0) {
return message;
}
let positionalIndex = 0;
let formattedMessage = message.replace(
POSITIONALS_EXP,
(match, isEscaped, _, flag) => {
const positional = positionals[positionalIndex];
const value = serializePositional(positional, flag);
if (!isEscaped) {
positionalIndex++;
return value;
}
return match;
}
);
if (positionalIndex < positionals.length) {
formattedMessage += ` ${positionals.slice(positionalIndex).join(" ")}`;
}
formattedMessage = formattedMessage.replace(/%{2,2}/g, "%");
return formattedMessage;
}
// src/invariant.ts
var STACK_FRAMES_TO_IGNORE = 2;
function cleanErrorStack(error) {
if (!error.stack) {
return;
}
const nextStack = error.stack.split("\n");
nextStack.splice(1, STACK_FRAMES_TO_IGNORE);
error.stack = nextStack.join("\n");
}
var InvariantError = class extends Error {
constructor(message, ...positionals) {
super(message);
this.message = message;
this.name = "Invariant Violation";
this.message = format(message, ...positionals);
cleanErrorStack(this);
}
};
var invariant = (predicate, message, ...positionals) => {
if (!predicate) {
throw new InvariantError(message, ...positionals);
}
};
invariant.as = (ErrorConstructor, predicate, message, ...positionals) => {
if (!predicate) {
const isConstructor = ErrorConstructor.prototype.name != null;
const error = isConstructor ? new ErrorConstructor(format(message, positionals)) : ErrorConstructor(format(message, positionals));
throw error;
}
};
export {
InvariantError,
format,
invariant
};
//# sourceMappingURL=index.mjs.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../src/format.ts","../src/invariant.ts"],"sourcesContent":["const POSITIONALS_EXP = /(%?)(%([sdjo]))/g\n\nfunction serializePositional(positional: any, flag: string): any {\n switch (flag) {\n // Strings.\n case 's':\n return positional\n\n // Digits.\n case 'd':\n case 'i':\n return Number(positional)\n\n // JSON.\n case 'j':\n return JSON.stringify(positional)\n\n // Objects.\n case 'o': {\n // Preserve stings to prevent extra quotes around them.\n if (typeof positional === 'string') {\n return positional\n }\n\n const json = JSON.stringify(positional)\n\n // If the positional isn't serializable, return it as-is.\n if (json === '{}' || json === '[]' || /^\\[object .+?\\]$/.test(json)) {\n return positional\n }\n\n return json\n }\n }\n}\n\nexport function format(message: string, ...positionals: any[]): string {\n if (positionals.length === 0) {\n return message\n }\n\n let positionalIndex = 0\n let formattedMessage = message.replace(\n POSITIONALS_EXP,\n (match, isEscaped, _, flag) => {\n const positional = positionals[positionalIndex]\n const value = serializePositional(positional, flag)\n\n if (!isEscaped) {\n positionalIndex++\n return value\n }\n\n return match\n }\n )\n\n // Append unresolved positionals to string as-is.\n if (positionalIndex < positionals.length) {\n formattedMessage += ` ${positionals.slice(positionalIndex).join(' ')}`\n }\n\n formattedMessage = formattedMessage.replace(/%{2,2}/g, '%')\n\n return formattedMessage\n}\n","import { format } from './format'\n\nconst STACK_FRAMES_TO_IGNORE = 2\n\n/**\n * Remove the \"outvariant\" package trace from the given error.\n * This scopes down the error stack to the relevant parts\n * when used in other applications.\n */\nfunction cleanErrorStack(error: Error): void {\n if (!error.stack) {\n return\n }\n\n const nextStack = error.stack.split('\\n')\n nextStack.splice(1, STACK_FRAMES_TO_IGNORE)\n error.stack = nextStack.join('\\n')\n}\n\nexport class InvariantError extends Error {\n name = 'Invariant Violation'\n\n constructor(public readonly message: string, ...positionals: any[]) {\n super(message)\n this.message = format(message, ...positionals)\n cleanErrorStack(this)\n }\n}\n\nexport interface CustomErrorConstructor {\n new (message: string): Error\n}\n\nexport interface CustomErrorFactory {\n (message: string): Error\n}\n\nexport type CustomError = CustomErrorConstructor | CustomErrorFactory\n\ntype Invariant = {\n (\n predicate: unknown,\n message: string,\n ...positionals: any[]\n ): asserts predicate\n\n as(\n ErrorConstructor: CustomError,\n predicate: unknown,\n message: string,\n ...positionals: unknown[]\n ): asserts predicate\n}\n\nexport const invariant: Invariant = (\n predicate,\n message,\n ...positionals\n): asserts predicate => {\n if (!predicate) {\n throw new InvariantError(message, ...positionals)\n }\n}\n\ninvariant.as = (ErrorConstructor, predicate, message, ...positionals) => {\n if (!predicate) {\n const isConstructor = ErrorConstructor.prototype.name != null\n\n const error: Error = isConstructor\n ? // @ts-ignore\n new ErrorConstructor(format(message, positionals))\n : // @ts-ignore\n ErrorConstructor(format(message, positionals))\n\n throw error\n }\n}\n"],"mappings":";AAAA,IAAM,kBAAkB;AAExB,SAAS,oBAAoB,YAAiB,MAAmB;AAC/D,UAAQ,MAAM;AAAA,IAEZ,KAAK;AACH,aAAO;AAAA,IAGT,K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tB;AACF;AA2BO,IAAM,YAAuB,CAClC,WACA,YACG,gBACmB;AACtB,MAAI,CAAC,WAAW;AACd,UAAM,IAAI,eAAe,SAAS,GAAG,WAAW;AAAA,EAClD;AACF;AAEA,UAAU,KAAK,CAAC,kBAAkB,WAAW,YAAY,gBAAgB;AACvE,MAAI,CAAC,WAAW;AACd,UAAM,gBAAgB,iBAAiB,UAAU,QAAQ;AAEzD,UAAM,QAAe,gBAEjB,IAAI,iBAAiB,OAAO,SAAS,WAAW,CAAC,IAEjD,iBAAiB,OAAO,SAAS,WAAW,CAAC;AAEjD,UAAM;AAAA,EACR;AACF;","names":[]}
+47
View File
@@ -0,0 +1,47 @@
{
"name": "outvariant",
"version": "1.4.0",
"description": "Type-safe implementation of invariant with positionals.",
"main": "lib/index.js",
"module": "lib/index.mjs",
"typings": "lib/index.d.ts",
"exports": {
".": {
"types": "./lib/index.d.ts",
"require": "./lib/index.js",
"default": "./lib/index.mjs"
}
},
"author": "Artem Zakharchenko",
"license": "MIT",
"scripts": {
"test": "jest",
"clean": "rimraf ./lib",
"build": "yarn clean && tsup",
"prepublishOnly": "yarn test && yarn build",
"release": "release publish"
},
"files": [
"lib"
],
"keywords": [
"invariant",
"outvariant",
"exception",
"positional"
],
"devDependencies": {
"@ossjs/release": "^0.5.1",
"@types/jest": "^26.0.23",
"jest": "^27.0.6",
"rimraf": "^3.0.2",
"ts-jest": "^27.0.3",
"ts-node": "^10.0.0",
"tsup": "^6.2.3",
"typescript": "^4.3.4"
},
"repository": {
"type": "git",
"url": "https://github.com/open-draft/outvariant"
}
}