WIP: bootstrap and partial real Solana watcher implementation

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

View File

@@ -0,0 +1,27 @@
'use strict'
const SemVer = require('../classes/semver')
const Range = require('../classes/range')
const maxSatisfying = (versions, range, options) => {
let max = null
let maxSV = null
let rangeObj = null
try {
rangeObj = new Range(range, options)
} catch (er) {
return null
}
versions.forEach((v) => {
if (rangeObj.test(v)) {
// satisfies(v, range, options)
if (!max || maxSV.compare(v) === -1) {
// compare(max, v, true)
max = v
maxSV = new SemVer(max, options)
}
}
})
return max
}
module.exports = maxSatisfying

View File

@@ -0,0 +1,24 @@
"use strict";
var _unsupported_iterable_to_array = require("./_unsupported_iterable_to_array.cjs");
function _create_for_of_iterator_helper_loose(o, allowArrayLike) {
var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
if (it) return (it = it.call(o)).next.bind(it);
// Fallback for engines without symbol support
if (Array.isArray(o) || (it = _unsupported_iterable_to_array._(o)) || allowArrayLike && o && typeof o.length === "number") {
if (it) o = it;
var i = 0;
return function() {
if (i >= o.length) return { done: true };
return { done: false, value: o[i++] };
};
}
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
exports._ = _create_for_of_iterator_helper_loose;

View File

@@ -0,0 +1,72 @@
'use strict';
// From https://github.com/sindresorhus/random-int/blob/c37741b56f76b9160b0b63dae4e9c64875128146/index.js#L13-L15
const randomInteger = (minimum, maximum) => Math.floor((Math.random() * (maximum - minimum + 1)) + minimum);
const createAbortError = () => {
const error = new Error('Delay aborted');
error.name = 'AbortError';
return error;
};
const createDelay = ({clearTimeout: defaultClear, setTimeout: set, willResolve}) => (ms, {value, signal} = {}) => {
if (signal && signal.aborted) {
return Promise.reject(createAbortError());
}
let timeoutId;
let settle;
let rejectFn;
const clear = defaultClear || clearTimeout;
const signalListener = () => {
clear(timeoutId);
rejectFn(createAbortError());
};
const cleanup = () => {
if (signal) {
signal.removeEventListener('abort', signalListener);
}
};
const delayPromise = new Promise((resolve, reject) => {
settle = () => {
cleanup();
if (willResolve) {
resolve(value);
} else {
reject(value);
}
};
rejectFn = reject;
timeoutId = (set || setTimeout)(settle, ms);
});
if (signal) {
signal.addEventListener('abort', signalListener, {once: true});
}
delayPromise.clear = () => {
clear(timeoutId);
timeoutId = null;
settle();
};
return delayPromise;
};
const createWithTimers = clearAndSet => {
const delay = createDelay({...clearAndSet, willResolve: true});
delay.reject = createDelay({...clearAndSet, willResolve: false});
delay.range = (minimum, maximum, options) => delay(randomInteger(minimum, maximum), options);
return delay;
};
const delay = createWithTimers();
delay.createWithTimers = createWithTimers;
module.exports = delay;
// TODO: Remove this for the next major release
module.exports.default = delay;

View File

@@ -0,0 +1,5 @@
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
interface Thenable<T> extends PromiseLike<T> { }

View File

@@ -0,0 +1,22 @@
{
'variables': {
'openssl_fips': ''
},
'targets': [
{
'target_name': 'validation',
'sources': [
'src/validation.cc',
'deps/is_utf8/src/is_utf8.cpp'
],
'cflags_cc': ['-std=gnu++11'],
'conditions': [
["OS=='mac'", {
'xcode_settings': {
'MACOSX_DEPLOYMENT_TARGET': '10.7'
}
}]
]
}
]
}

View File

@@ -0,0 +1,41 @@
import { i as init } from './init.k9zZ9sLh.js';
if (!process.send) throw new Error("Expected worker to be run in node:child_process");
// Store globals in case tests overwrite them
const processExit = process.exit.bind(process);
const processSend = process.send.bind(process);
const processOn = process.on.bind(process);
const processOff = process.off.bind(process);
const processRemoveAllListeners = process.removeAllListeners.bind(process);
// Work-around for nodejs/node#55094
if (process.execArgv.some((execArg) => execArg.startsWith("--prof") || execArg.startsWith("--cpu-prof") || execArg.startsWith("--heap-prof") || execArg.startsWith("--diagnostic-dir"))) processOn("SIGTERM", () => processExit());
processOn("error", onError);
function workerInit(options) {
const { runTests } = options;
init({
post: (v) => processSend(v),
on: (cb) => processOn("message", cb),
off: (cb) => processOff("message", cb),
teardown: () => {
processRemoveAllListeners("message");
processOff("error", onError);
},
runTests: (state, traces) => executeTests("run", state, traces),
collectTests: (state, traces) => executeTests("collect", state, traces),
setup: options.setup
});
async function executeTests(method, state, traces) {
try {
await runTests(method, state, traces);
} finally {
process.exit = processExit;
}
}
}
// Prevent leaving worker in loops where it tries to send message to closed main
// thread, errors, and tries to send the error.
function onError(error) {
if (error?.code === "ERR_IPC_CHANNEL_CLOSED" || error?.code === "EPIPE") processExit(1);
}
export { workerInit as w };

View File

@@ -0,0 +1,21 @@
'use strict'
const { test } = require('node:test')
const assert = require('node:assert')
const { join } = require('path')
const ThreadStream = require('..')
const { version } = require('../package.json')
test('get context', (t, done) => {
const stream = new ThreadStream({
filename: join(__dirname, 'get-context.js'),
workerData: {},
sync: true
})
t.after(() => stream.end())
stream.on('context', (ctx) => {
assert.deepStrictEqual(ctx.threadStreamVersion, version)
done()
})
stream.write('hello')
})

View File

@@ -0,0 +1,211 @@
import { createMessageConnection, RequestType, SocketMessageReader, SocketMessageWriter, StreamMessageReader, StreamMessageWriter, } from "#vscode-jsonrpc/node";
import { fsCallbackNames, } from "../fs.js";
import { isSpawnOptions, resolveExePath, } from "../options.js";
import { combineTimingInfo, disabledServerTimingInfo, disabledTimingInfo, TimingCollector, } from "../timing.js";
/**
* Client handles communication with the TypeScript API server
* over STDIO (spawned process) or a Unix domain socket using JSON-RPC.
*/
export class Client {
socket;
process;
connection;
options;
connected = false;
timing;
constructor(options) {
this.options = options;
if (isSpawnOptions(options) && options.collectTiming) {
this.timing = new TimingCollector();
}
}
async connect() {
if (this.connected)
return;
if (isSpawnOptions(this.options)) {
await this.connectViaSpawn(this.options);
}
else {
await this.connectViaSocket(this.options);
}
}
async connectViaSpawn(options) {
const { spawn } = await import("node:child_process");
return new Promise((resolve, reject) => {
const args = [
"--api",
"--async",
"--cwd",
options.cwd ?? process.cwd(),
];
if (options.collectTiming) {
args.push("--timing");
}
// Enable virtual FS callbacks for each provided FS function
const enabledCallbacks = [];
if (options.fs) {
for (const name of fsCallbackNames) {
if (options.fs[name]) {
enabledCallbacks.push(name);
}
}
}
if (enabledCallbacks.length > 0) {
args.push(`--callbacks=${enabledCallbacks.join(",")}`);
}
this.process = spawn(resolveExePath(options), args, {
stdio: ["pipe", "pipe", "inherit"],
});
this.process.once("error", error => {
reject(new Error(`Failed to start tsgo process: ${error.message}`));
});
this.process.once("spawn", () => {
this.connected = true;
resolve();
});
const reader = new StreamMessageReader(this.process.stdout);
const writer = new StreamMessageWriter(this.process.stdin);
this.connection = createMessageConnection(reader, writer);
this.registerFSCallbacks(this.connection, options.fs);
this.connection.listen();
});
}
async connectViaSocket(options) {
const { createConnection } = await import("node:net");
return new Promise((resolve, reject) => {
this.socket = createConnection(options.pipe, () => {
const reader = new SocketMessageReader(this.socket);
const writer = new SocketMessageWriter(this.socket);
this.connection = createMessageConnection(reader, writer);
this.connection.listen();
this.connected = true;
resolve();
});
this.socket.once("error", error => {
reject(new Error(`Socket error: ${error.message}`));
});
});
}
registerFSCallbacks(connection, fs) {
if (!fs)
return;
for (const name of fsCallbackNames) {
const callback = fs[name];
if (callback) {
const requestType = new RequestType(name);
connection.onRequest(requestType, (arg) => {
const result = callback(arg);
if (name === "readFile") {
// readFile has 3 returns: string (content), null (not found), undefined (fall back).
// JSON-RPC can't distinguish null from undefined, so wrap in object.
if (result === undefined)
return null;
return { content: result };
}
return result ?? null;
});
}
}
}
async apiRequest(method, params) {
if (!this.connected) {
await this.connect();
}
if (!this.connection) {
throw new Error("Connection not established");
}
const requestType = new RequestType(method);
if (!this.timing) {
return this.connection.sendRequest(requestType, params);
}
// Round-trip latency is measured here; byte counts approximate the wire
// payload via the serialized JSON. Server-side processing time is not
// carried on the response; it is retrieved separately (via a
// getServerTiming request) and folded in by getTimingInfo().
const bytesSent = params === undefined ? 0 : Buffer.byteLength(JSON.stringify(params), "utf-8");
const start = performance.now();
const result = await this.connection.sendRequest(requestType, params);
const roundTripMs = performance.now() - start;
this.timing.record({
method,
roundTripMs,
bytesSent,
bytesReceived: result === undefined || result === null
? 0
: Buffer.byteLength(JSON.stringify(result), "utf-8"),
});
return result;
}
async apiRequestBinary(method, params) {
const response = await this.apiRequest(method, params);
if (!response)
return undefined;
const buffer = Buffer.from(response.data, "base64");
return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
}
/**
* Returns the timing collector that per-node materialization is reported
* into, or undefined when timing collection is disabled. The returned
* collector is the same one folded into {@link getTimingInfo}, so
* materialization totals surface alongside request timings.
*/
getTimingCollector() {
return this.timing;
}
/**
* Returns a combined timing snapshot: client-measured round-trip and byte
* counts folded together with the server's own per-request processing time
* (fetched via a getServerTiming request) and estimated transport overhead.
*/
async getTimingInfo() {
if (!this.timing) {
return disabledTimingInfo();
}
const local = this.timing.getInfo();
// No requests have been sent yet: nothing to fetch from the server.
if (!this.connected || !this.connection) {
return local;
}
return combineTimingInfo(local, await this.fetchServerTiming());
}
async resetTimingInfo() {
if (!this.timing)
return;
this.timing.reset();
if (this.connected && this.connection) {
// Keep the server's collection in sync so combined totals stay meaningful.
const requestType = new RequestType("resetServerTiming");
await this.connection.sendRequest(requestType, undefined);
}
}
async fetchServerTiming() {
if (!this.connection) {
return disabledServerTimingInfo();
}
// Fetch the server's own timing collection via a dedicated request. This
// bypasses the client-side collector so the query does not pollute it.
const requestType = new RequestType("getServerTiming");
return this.connection.sendRequest(requestType, undefined);
}
async close() {
if (this.connection) {
this.connection.dispose();
this.connection = undefined;
}
if (this.socket) {
this.socket.destroy();
this.socket = undefined;
}
if (this.process) {
// Close stdin to unblock the server's read loop, allowing it to exit cleanly.
// The server is blocked on stdin.Read(), so just sending SIGTERM would deadlock:
// - Node won't exit while child is alive
// - Child can't process SIGTERM while blocked on read
// - Read won't error until stdin is closed
this.process.stdin?.end();
this.process = undefined;
}
this.connected = false;
}
}
//# sourceMappingURL=client.js.map

View File

@@ -0,0 +1,7 @@
"use strict";
const SourceCode = require("./source-code");
module.exports = {
SourceCode,
};

View File

@@ -0,0 +1,144 @@
import { expect, test } from "vitest";
import * as z from "../index.js";
// lt;
test("z.lt", () => {
const a = z.number().check(z.lt(10));
expect(z.safeParse(a, 9).success).toEqual(true);
expect(z.safeParse(a, 9).data).toEqual(9);
expect(z.safeParse(a, 10).success).toEqual(false);
});
// lte;
test("z.lte", () => {
const a = z.number().check(z.lte(10));
expect(z.safeParse(a, 10).success).toEqual(true);
expect(z.safeParse(a, 10).data).toEqual(10);
expect(z.safeParse(a, 11).success).toEqual(false);
});
// min;
test("z.max", () => {
const a = z.number().check(z.maximum(10));
expect(z.safeParse(a, 10).success).toEqual(true);
expect(z.safeParse(a, 10).data).toEqual(10);
expect(z.safeParse(a, 11).success).toEqual(false);
});
// gt;
test("z.gt", () => {
const a = z.number().check(z.gt(10));
expect(z.safeParse(a, 11).success).toEqual(true);
expect(z.safeParse(a, 11).data).toEqual(11);
expect(z.safeParse(a, 10).success).toEqual(false);
});
// gte;
test("z.gte", () => {
const a = z.number().check(z.gte(10));
expect(z.safeParse(a, 10).success).toEqual(true);
expect(z.safeParse(a, 10).data).toEqual(10);
expect(z.safeParse(a, 9).success).toEqual(false);
});
// min;
test("z.min", () => {
const a = z.number().check(z.minimum(10));
expect(z.safeParse(a, 10).success).toEqual(true);
expect(z.safeParse(a, 10).data).toEqual(10);
expect(z.safeParse(a, 9).success).toEqual(false);
});
// maxSize;
test("z.maxLength", () => {
const a = z.array(z.string()).check(z.maxLength(3));
expect(z.safeParse(a, ["a", "b", "c"]).success).toEqual(true);
expect(z.safeParse(a, ["a", "b", "c", "d"]).success).toEqual(false);
});
// minSize;
test("z.minLength", () => {
const a = z.array(z.string()).check(z.minLength(3));
expect(z.safeParse(a, ["a", "b"]).success).toEqual(false);
expect(z.safeParse(a, ["a", "b", "c"]).success).toEqual(true);
});
// size;
test("z.length", () => {
const a = z.array(z.string()).check(z.length(3));
expect(z.safeParse(a, ["a", "b"]).success).toEqual(false);
expect(z.safeParse(a, ["a", "b", "c"]).success).toEqual(true);
expect(z.safeParse(a, ["a", "b", "c", "d"]).success).toEqual(false);
});
// regex;
test("z.regex", () => {
const a = z.string().check(z.regex(/^aaa$/));
expect(z.safeParse(a, "aaa")).toMatchObject({ success: true, data: "aaa" });
expect(z.safeParse(a, "aa")).toMatchObject({ success: false });
});
// includes;
test("z.includes", () => {
const a = z.string().check(z.includes("asdf"));
z.parse(a, "qqqasdfqqq");
z.parse(a, "asdf");
z.parse(a, "qqqasdf");
z.parse(a, "asdfqqq");
expect(z.safeParse(a, "qqq")).toMatchObject({ success: false });
});
// startsWith;
test("z.startsWith", () => {
const a = z.string().check(z.startsWith("asdf"));
z.parse(a, "asdf");
z.parse(a, "asdfqqq");
expect(z.safeParse(a, "qqq")).toMatchObject({ success: false });
});
// endsWith;
test("z.endsWith", () => {
const a = z.string().check(z.endsWith("asdf"));
z.parse(a, "asdf");
z.parse(a, "qqqasdf");
expect(z.safeParse(a, "asdfqqq")).toMatchObject({ success: false });
});
// lowercase;
test("z.lowercase", () => {
const a = z.string().check(z.lowercase());
z.parse(a, "asdf");
expect(z.safeParse(a, "ASDF")).toMatchObject({ success: false });
});
// uppercase;
test("z.uppercase", () => {
const a = z.string().check(z.uppercase());
z.parse(a, "ASDF");
expect(z.safeParse(a, "asdf")).toMatchObject({ success: false });
});
// filename;
// fileType;
// overwrite;
test("z.overwrite", () => {
const a = z.string().check(z.overwrite((val) => val.toUpperCase()));
expect(z.safeParse(a, "asdf")).toMatchObject({ data: "ASDF" });
});
// normalize;
// trim;
// toLowerCase;
// toUpperCase;
// property
test("abort early", () => {
const schema = z.string().check(
z.refine((val) => val.length > 1),
z.refine((val) => val.length > 2, { abort: true }),
z.refine((val) => val.length > 3)
);
const data = "";
const result = z.safeParse(schema, data);
expect(result.error!.issues.length).toEqual(2);
});

View File

@@ -0,0 +1,10 @@
type Options = [
{
allowReturnAny?: boolean;
}
];
type MessageId = `asyncFunc` | `nonVoidFunc` | `nonVoidReturn`;
declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<MessageId, Options, import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener> & {
name: string;
};
export default _default;

View File

@@ -0,0 +1,117 @@
import type { $ZodStringFormats } from "../core/checks.js";
import type * as errors from "../core/errors.js";
import * as util from "../core/util.js";
const error: () => errors.$ZodErrorMap = () => {
const Sizable: Record<string, { unit: string; verb: string }> = {
string: { unit: "karakter", verb: "legyen" },
file: { unit: "byte", verb: "legyen" },
array: { unit: "elem", verb: "legyen" },
set: { unit: "elem", verb: "legyen" },
};
function getSizing(origin: string): { unit: string; verb: string } | null {
return Sizable[origin] ?? null;
}
const FormatDictionary: {
[k in $ZodStringFormats | (string & {})]?: string;
} = {
regex: "bemenet",
email: "email cím",
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: "ISO időbélyeg",
date: "ISO dátum",
time: "ISO idő",
duration: "ISO időintervallum",
ipv4: "IPv4 cím",
ipv6: "IPv6 cím",
cidrv4: "IPv4 tartomány",
cidrv6: "IPv6 tartomány",
base64: "base64-kódolt string",
base64url: "base64url-kódolt string",
json_string: "JSON string",
e164: "E.164 szám",
jwt: "JWT",
template_literal: "bemenet",
};
const TypeDictionary: {
[k in errors.$ZodInvalidTypeExpected | (string & {})]?: string;
} = {
nan: "NaN",
number: "szám",
array: "tömb",
};
return (issue) => {
switch (issue.code) {
case "invalid_type": {
const expected = TypeDictionary[issue.expected] ?? issue.expected;
const receivedType = util.parsedType(issue.input);
const received = TypeDictionary[receivedType] ?? receivedType;
if (/^[A-Z]/.test(issue.expected)) {
return `Érvénytelen bemenet: a várt érték instanceof ${issue.expected}, a kapott érték ${received}`;
}
return `Érvénytelen bemenet: a várt érték ${expected}, a kapott érték ${received}`;
}
case "invalid_value":
if (issue.values.length === 1)
return `Érvénytelen bemenet: a várt érték ${util.stringifyPrimitive(issue.values[0])}`;
return `Érvénytelen opció: valamelyik érték várt ${util.joinValues(issue.values, "|")}`;
case "too_big": {
const adj = issue.inclusive ? "<=" : "<";
const sizing = getSizing(issue.origin);
if (sizing)
return `Túl nagy: ${issue.origin ?? "érték"} mérete túl nagy ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elem"}`;
return `Túl nagy: a bemeneti érték ${issue.origin ?? "érték"} túl nagy: ${adj}${issue.maximum.toString()}`;
}
case "too_small": {
const adj = issue.inclusive ? ">=" : ">";
const sizing = getSizing(issue.origin);
if (sizing) {
return `Túl kicsi: a bemeneti érték ${issue.origin} mérete túl kicsi ${adj}${issue.minimum.toString()} ${sizing.unit}`;
}
return `Túl kicsi: a bemeneti érték ${issue.origin} túl kicsi ${adj}${issue.minimum.toString()}`;
}
case "invalid_format": {
const _issue = issue as errors.$ZodStringFormatIssues;
if (_issue.format === "starts_with") return `Érvénytelen string: "${_issue.prefix}" értékkel kell kezdődnie`;
if (_issue.format === "ends_with") return `Érvénytelen string: "${_issue.suffix}" értékkel kell végződnie`;
if (_issue.format === "includes") return `Érvénytelen string: "${_issue.includes}" értéket kell tartalmaznia`;
if (_issue.format === "regex") return `Érvénytelen string: ${_issue.pattern} mintának kell megfelelnie`;
return `Érvénytelen ${FormatDictionary[_issue.format] ?? issue.format}`;
}
case "not_multiple_of":
return `Érvénytelen szám: ${issue.divisor} többszörösének kell lennie`;
case "unrecognized_keys":
return `Ismeretlen kulcs${issue.keys.length > 1 ? "s" : ""}: ${util.joinValues(issue.keys, ", ")}`;
case "invalid_key":
return `Érvénytelen kulcs ${issue.origin}`;
case "invalid_union":
return "Érvénytelen bemenet";
case "invalid_element":
return `Érvénytelen érték: ${issue.origin}`;
default:
return `Érvénytelen bemenet`;
}
};
};
export default function (): { localeError: errors.$ZodErrorMap } {
return {
localeError: error(),
};
}

View File

@@ -0,0 +1,150 @@
/**
* @fileoverview Rule to disallow whitespace before properties
* @author Kai Cataldo
* @deprecated in ESLint v8.53.0
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const astUtils = require("./utils/ast-utils");
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
deprecated: {
message: "Formatting rules are being moved out of ESLint core.",
url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/",
deprecatedSince: "8.53.0",
availableUntil: "11.0.0",
replacedBy: [
{
message:
"ESLint Stylistic now maintains deprecated stylistic core rules.",
url: "https://eslint.style/guide/migration",
plugin: {
name: "@stylistic/eslint-plugin",
url: "https://eslint.style",
},
rule: {
name: "no-whitespace-before-property",
url: "https://eslint.style/rules/no-whitespace-before-property",
},
},
],
},
type: "layout",
docs: {
description: "Disallow whitespace before properties",
recommended: false,
url: "https://eslint.org/docs/latest/rules/no-whitespace-before-property",
},
fixable: "whitespace",
schema: [],
messages: {
unexpectedWhitespace:
"Unexpected whitespace before property {{propName}}.",
},
},
create(context) {
const sourceCode = context.sourceCode;
//--------------------------------------------------------------------------
// Helpers
//--------------------------------------------------------------------------
/**
* Reports whitespace before property token
* @param {ASTNode} node the node to report in the event of an error
* @param {Token} leftToken the left token
* @param {Token} rightToken the right token
* @returns {void}
* @private
*/
function reportError(node, leftToken, rightToken) {
context.report({
node,
messageId: "unexpectedWhitespace",
data: {
propName: sourceCode.getText(node.property),
},
fix(fixer) {
let replacementText = "";
if (
!node.computed &&
!node.optional &&
astUtils.isDecimalInteger(node.object)
) {
/*
* If the object is a number literal, fixing it to something like 5.toString() would cause a SyntaxError.
* Don't fix this case.
*/
return null;
}
// Don't fix if comments exist.
if (
sourceCode.commentsExistBetween(leftToken, rightToken)
) {
return null;
}
if (node.optional) {
replacementText = "?.";
} else if (!node.computed) {
replacementText = ".";
}
return fixer.replaceTextRange(
[leftToken.range[1], rightToken.range[0]],
replacementText,
);
},
});
}
//--------------------------------------------------------------------------
// Public
//--------------------------------------------------------------------------
return {
MemberExpression(node) {
let rightToken;
let leftToken;
if (!astUtils.isTokenOnSameLine(node.object, node.property)) {
return;
}
if (node.computed) {
rightToken = sourceCode.getTokenBefore(
node.property,
astUtils.isOpeningBracketToken,
);
leftToken = sourceCode.getTokenBefore(
rightToken,
node.optional ? 1 : 0,
);
} else {
rightToken = sourceCode.getFirstToken(node.property);
leftToken = sourceCode.getTokenBefore(rightToken, 1);
}
if (sourceCode.isSpaceBetween(leftToken, rightToken)) {
reportError(node, leftToken, rightToken);
}
},
};
},
};

View File

@@ -0,0 +1,261 @@
"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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("@typescript-eslint/utils");
const tsutils = __importStar(require("ts-api-utils"));
const util_1 = require("../util");
const useUnknownMessageBase = 'Prefer the safe `: unknown` for a `{{method}}`{{append}} callback variable.';
exports.default = (0, util_1.createRule)({
name: 'use-unknown-in-catch-callback-variable',
meta: {
type: 'suggestion',
docs: {
description: 'Enforce typing arguments in Promise rejection callbacks as `unknown`',
recommended: 'strict',
requiresTypeChecking: true,
},
hasSuggestions: true,
messages: {
addUnknownRestTypeAnnotationSuggestion: 'Add an explicit `: [unknown]` type annotation to the rejection callback rest variable.',
addUnknownTypeAnnotationSuggestion: 'Add an explicit `: unknown` type annotation to the rejection callback variable.',
useUnknown: useUnknownMessageBase,
useUnknownArrayDestructuringPattern: `${useUnknownMessageBase} The thrown error may not be iterable.`,
useUnknownObjectDestructuringPattern: `${useUnknownMessageBase} The thrown error may be nullable, or may not have the expected shape.`,
wrongRestTypeAnnotationSuggestion: 'Change existing type annotation to `: [unknown]`.',
wrongTypeAnnotationSuggestion: 'Change existing type annotation to `: unknown`.',
},
schema: [],
},
defaultOptions: [],
create(context) {
const { esTreeNodeToTSNodeMap, program } = (0, util_1.getParserServices)(context);
const checker = program.getTypeChecker();
function isFlaggableHandlerType(type) {
for (const unionPart of tsutils.unionConstituents(type)) {
const callSignatures = tsutils.getCallSignaturesOfType(unionPart);
if (callSignatures.length === 0) {
// Ignore any non-function components to the type. Those are not this rule's problem.
continue;
}
for (const callSignature of callSignatures) {
const firstParam = callSignature.parameters.at(0);
if (!firstParam) {
// it's not an issue if there's no catch variable at all.
continue;
}
let firstParamType = checker.getTypeOfSymbol(firstParam);
const decl = firstParam.valueDeclaration;
if (decl != null && (0, util_1.isRestParameterDeclaration)(decl)) {
if (checker.isArrayType(firstParamType)) {
firstParamType = checker.getTypeArguments(firstParamType)[0];
}
else if (checker.isTupleType(firstParamType)) {
firstParamType = checker.getTypeArguments(firstParamType)[0];
}
else {
// a rest arg that's not an array or tuple should definitely be flagged.
return true;
}
}
if (!tsutils.isIntrinsicUnknownType(firstParamType)) {
return true;
}
}
}
return false;
}
function collectFlaggedNodes(node) {
switch (node.type) {
case utils_1.AST_NODE_TYPES.LogicalExpression:
return [
...collectFlaggedNodes(node.left),
...collectFlaggedNodes(node.right),
];
case utils_1.AST_NODE_TYPES.SequenceExpression:
return collectFlaggedNodes((0, util_1.nullThrows)(node.expressions.at(-1), 'sequence expression must have multiple expressions'));
case utils_1.AST_NODE_TYPES.ConditionalExpression:
return [
...collectFlaggedNodes(node.consequent),
...collectFlaggedNodes(node.alternate),
];
case utils_1.AST_NODE_TYPES.ArrowFunctionExpression:
case utils_1.AST_NODE_TYPES.FunctionExpression:
{
const argument = esTreeNodeToTSNodeMap.get(node);
const typeOfArgument = checker.getTypeAtLocation(argument);
if (isFlaggableHandlerType(typeOfArgument)) {
return [node];
}
}
break;
default:
break;
}
return [];
}
/**
* Analyzes the syntax of the catch argument and makes a best effort to pinpoint
* why it's reporting, and to come up with a suggested fix if possible.
*
* This function is explicitly operating under the assumption that the
* rule _is reporting_, so it is not guaranteed to be sound to call otherwise.
*/
function refineReportIfPossible(argument) {
const catchVariableOuterWithIncorrectTypes = (0, util_1.nullThrows)(argument.params.at(0), 'There should have been at least one parameter for the rule to have flagged.');
// Function expressions can't have parameter properties; those only exist in constructors.
const catchVariableOuter = catchVariableOuterWithIncorrectTypes;
const catchVariableInner = catchVariableOuter.type === utils_1.AST_NODE_TYPES.AssignmentPattern
? catchVariableOuter.left
: catchVariableOuter;
switch (catchVariableInner.type) {
case utils_1.AST_NODE_TYPES.Identifier: {
const catchVariableTypeAnnotation = catchVariableInner.typeAnnotation;
if (catchVariableTypeAnnotation == null) {
return {
node: catchVariableOuter,
suggest: [
{
messageId: 'addUnknownTypeAnnotationSuggestion',
fix: (fixer) => {
if (argument.type ===
utils_1.AST_NODE_TYPES.ArrowFunctionExpression &&
(0, util_1.isParenlessArrowFunction)(argument, context.sourceCode)) {
return [
fixer.insertTextBefore(catchVariableInner, '('),
fixer.insertTextAfter(catchVariableInner, ': unknown)'),
];
}
return [
fixer.insertTextAfter(catchVariableInner, ': unknown'),
];
},
},
],
};
}
return {
node: catchVariableOuter,
suggest: [
{
messageId: 'wrongTypeAnnotationSuggestion',
fix: (fixer) => fixer.replaceText(catchVariableTypeAnnotation, ': unknown'),
},
],
};
}
case utils_1.AST_NODE_TYPES.ArrayPattern: {
return {
node: catchVariableOuter,
messageId: 'useUnknownArrayDestructuringPattern',
};
}
case utils_1.AST_NODE_TYPES.ObjectPattern: {
return {
node: catchVariableOuter,
messageId: 'useUnknownObjectDestructuringPattern',
};
}
case utils_1.AST_NODE_TYPES.RestElement: {
const catchVariableTypeAnnotation = catchVariableInner.typeAnnotation;
if (catchVariableTypeAnnotation == null) {
return {
node: catchVariableOuter,
suggest: [
{
messageId: 'addUnknownRestTypeAnnotationSuggestion',
fix: (fixer) => fixer.insertTextAfter(catchVariableInner, ': [unknown]'),
},
],
};
}
return {
node: catchVariableOuter,
suggest: [
{
messageId: 'wrongRestTypeAnnotationSuggestion',
fix: (fixer) => fixer.replaceText(catchVariableTypeAnnotation, ': [unknown]'),
},
],
};
}
}
}
return {
CallExpression({ arguments: args, callee }) {
if (callee.type !== utils_1.AST_NODE_TYPES.MemberExpression) {
return;
}
const staticMemberAccessKey = (0, util_1.getStaticMemberAccessValue)(callee, context);
if (!staticMemberAccessKey) {
return;
}
const promiseMethodInfo = [
{ append: '', argIndexToCheck: 0, method: 'catch' },
{ append: ' rejection', argIndexToCheck: 1, method: 'then' },
].find(({ method }) => staticMemberAccessKey === method);
if (!promiseMethodInfo) {
return;
}
// Need to be enough args to check
const { argIndexToCheck, ...data } = promiseMethodInfo;
if (args.length < argIndexToCheck + 1) {
return;
}
// Argument to check, and all arguments before it, must be "ordinary" arguments (i.e. no spread arguments)
// promise.catch(f), promise.catch(() => {}), promise.catch(<expression>, <<other-args>>)
const argsToCheck = args.slice(0, argIndexToCheck + 1);
if (argsToCheck.some(({ type }) => type === utils_1.AST_NODE_TYPES.SpreadElement)) {
return;
}
if (!tsutils.isThenableType(checker, esTreeNodeToTSNodeMap.get(callee), checker.getTypeAtLocation(esTreeNodeToTSNodeMap.get(callee.object)))) {
return;
}
// the `some` check above has already excluded `SpreadElement`, so we are safe to assert the same
const argToCheck = argsToCheck[argIndexToCheck];
for (const node of collectFlaggedNodes(argToCheck)) {
// We are now guaranteed to report, but we have a bit of work to do
// to determine exactly where, and whether we can fix it.
const overrides = refineReportIfPossible(node);
context.report({
node,
messageId: 'useUnknown',
data,
...overrides,
});
}
},
};
},
});

View File

@@ -0,0 +1 @@
{"version":3,"file":"typeFlags.enum.d.ts","sourceRoot":"","sources":["../../src/enums/typeFlags.enum.ts"],"names":[],"mappings":"AAEA,oBAAY,SAAS;IACjB,IAAI,IAAI;IACR,GAAG,IAAS;IACZ,OAAO,IAAS;IAChB,SAAS,IAAS;IAClB,IAAI,IAAS;IACb,IAAI,KAAS;IACb,MAAM,KAAS;IACf,MAAM,KAAS;IACf,MAAM,MAAS;IACf,OAAO,MAAS;IAChB,QAAQ,MAAS;IACjB,aAAa,OAAU;IACvB,aAAa,OAAU;IACvB,aAAa,OAAU;IACvB,cAAc,OAAU;IACxB,cAAc,QAAU;IACxB,WAAW,QAAU;IACrB,IAAI,QAAU;IACd,YAAY,SAAU;IACtB,KAAK,SAAU;IACf,aAAa,SAAU;IACvB,MAAM,UAAU;IAChB,KAAK,UAAU;IACf,eAAe,UAAU;IACzB,aAAa,UAAU;IACvB,YAAY,WAAU;IACtB,aAAa,WAAU;IACvB,WAAW,WAAU;IACrB,KAAK,YAAU;IACf,YAAY,YAAU;IACtB,SAAS,YAAU;IACnB,SAAS,aAAU;IACnB,SAAS,cAAU;IACnB,YAAY,IAAgB;IAC5B,QAAQ,KAAmB;IAC3B,OAAO,QAAiE;IACxE,IAAI,QAA6C;IACjD,SAAS,QAAiB;IAC1B,qBAAqB,OAAgC;IACrD,6BAA6B,QAAiD;IAC9E,eAAe,QAA2F;IAC1G,aAAa,QAAuD;IACpE,SAAS,SAAuG;IAChH,UAAU,WAA2D;IACrE,UAAU,QAAgC;IAC1C,UAAU,OAAyB;IACnC,WAAW,OAA2B;IACtC,QAAQ,QAAqB;IAC7B,YAAY,QAA4B;IACxC,QAAQ,KAAmB;IAC3B,SAAS,WAAiG;IAC1G,qBAAqB,WAAuG;IAC5H,eAAe,WAAqG;IACpH,mBAAmB,YAAuB;IAC1C,cAAc,YAAgC;IAC9C,YAAY,WAAgC;IAC5C,wBAAwB,YAA4C;IACpE,qBAAqB,WAA0C;IAC/D,YAAY,YAAmD;IAC/D,wBAAwB,YAAgC;IACxD,eAAe,YAAyD;IACxE,YAAY,YAAsC;IAClD,SAAS,SAAiH;IAC1H,UAAU,YAA2I;IACrJ,YAAY,YAAqH;IACjI,mBAAmB,SAAgB;IACnC,uBAAuB,UAAQ;IAC/B,gBAAgB,WAAgB;IAChC,mBAAmB,WAAc;IACjC,oBAAoB,WAAe;IACnC,+BAA+B,YAAY;IAC3C,aAAa,aAAY;IACzB,iBAAiB,YAA8E;CAClG"}

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2017 Brian M. Carlson
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,25 @@
'use strict'
const { Suite } = require('benchmark')
const { createWarning } = require('..')
const err1 = createWarning({
name: 'TestWarning',
code: 'TST_ERROR_CODE_1',
message: 'message'
})
const err2 = createWarning({
name: 'TestWarning',
code: 'TST_ERROR_CODE_2',
message: 'message'
})
new Suite()
.add('warn', function () {
err1()
err2()
})
.on('cycle', function (event) {
console.log(String(event.target))
})
.run()

View File

@@ -0,0 +1,32 @@
"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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.z = void 0;
const z = __importStar(require("../v4/mini/external.cjs"));
exports.z = z;
__exportStar(require("../v4/mini/external.cjs"), exports);

View File

@@ -0,0 +1 @@
{"version":3,"file":"hmac.js","sourceRoot":"","sources":["src/hmac.ts"],"names":[],"mappings":"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"}

View File

@@ -0,0 +1,49 @@
"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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.isSourceFile = isSourceFile;
exports.getCodeText = getCodeText;
const ts = __importStar(require("typescript"));
function isSourceFile(code) {
if (typeof code !== 'object' || code == null) {
return false;
}
const maybeSourceFile = code;
return (maybeSourceFile.kind === ts.SyntaxKind.SourceFile &&
typeof maybeSourceFile.getFullText === 'function');
}
function getCodeText(code) {
return isSourceFile(code) ? code.getFullText(code) : code;
}

View File

@@ -0,0 +1,43 @@
{
"name": "json-stable-stringify-without-jsonify",
"version": "1.0.1",
"description": "deterministic JSON.stringify() with custom sorting to get deterministic hashes from stringified results, with no public domain dependencies",
"main": "index.js",
"dependencies": {
},
"devDependencies": {
"tape": "~1.0.4"
},
"scripts": {
"test": "tape test/*.js"
},
"testling": {
"files": "test/*.js",
"browsers": [
"ie/8..latest",
"ff/5", "ff/latest",
"chrome/15", "chrome/latest",
"safari/latest",
"opera/latest"
]
},
"repository": {
"type": "git",
"url": "git://github.com/samn/json-stable-stringify.git"
},
"homepage": "https://github.com/samn/json-stable-stringify",
"keywords": [
"json",
"stringify",
"deterministic",
"hash",
"sort",
"stable"
],
"author": {
"name": "James Halliday",
"email": "mail@substack.net",
"url": "http://substack.net"
},
"license": "MIT"
}

View File

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

View File

@@ -0,0 +1,16 @@
// Generated by LiveScript 1.6.0
(function(){
var VERSION, parseType, parsedTypeCheck, typeCheck;
VERSION = '0.4.0';
parseType = require('./parse-type');
parsedTypeCheck = require('./check');
typeCheck = function(type, input, options){
return parsedTypeCheck(parseType(type), input, options);
};
module.exports = {
VERSION: VERSION,
typeCheck: typeCheck,
parsedTypeCheck: parsedTypeCheck,
parseType: parseType
};
}).call(this);

View File

@@ -0,0 +1,44 @@
import { format } from '@vitest/pretty-format';
import { printDiffOrStringify, getDefaultFormatOptions } from './diff.js';
import { serializeValue } from './serialize.js';
import 'tinyrainbow';
import './display.js';
import './helpers.js';
import './constants.js';
function processError(_err, diffOptions, seen = new WeakSet()) {
if (!_err || typeof _err !== "object") {
return { message: String(_err) };
}
const err = _err;
if (err.showDiff || err.showDiff === undefined && err.expected !== undefined && err.actual !== undefined) {
const options = {
...diffOptions,
...err.diffOptions
};
err.diff = printDiffOrStringify(err.actual, err.expected, options, err);
err.expected = prettifyValue(err.expected, options);
err.actual = prettifyValue(err.actual, options);
}
// some Error implementations may not allow rewriting cause
// in most cases, the assignment will lead to "err.cause = err.cause"
try {
if (!seen.has(err) && typeof err.cause === "object") {
seen.add(err);
err.cause = processError(err.cause, diffOptions, seen);
}
} catch {}
try {
return serializeValue(err);
} catch (e) {
return serializeValue(new Error(`Failed to fully serialize error: ${e?.message}\nInner error message: ${err?.message}`));
}
}
function prettifyValue(value, options) {
if (typeof value !== "string") {
return format(value, getDefaultFormatOptions(options));
}
return value;
}
export { processError, serializeValue as serializeError };

View File

@@ -0,0 +1,13 @@
export type Options = [
{
enforceForClassFields?: boolean;
exceptMethods?: string[];
ignoreClassesThatImplementAnInterface?: boolean | 'public-fields';
ignoreOverrideMethods?: boolean;
}
];
export type MessageIds = 'missingThis';
declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"missingThis", Options, import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener> & {
name: string;
};
export default _default;

View File

@@ -0,0 +1,23 @@
The MIT License
Copyright(c) node-modules and other contributors.
Copyright(c) 2012 - 2015 fengmk2 <fengmk2@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,119 @@
import type { $ZodStringFormats } from "../core/checks.js";
import type * as errors from "../core/errors.js";
import * as util from "../core/util.js";
const error: () => errors.$ZodErrorMap = () => {
const Sizable: Record<string, { unit: string; verb: string }> = {
string: { unit: "ตัวอักษร", verb: "ควรมี" },
file: { unit: "ไบต์", verb: "ควรมี" },
array: { unit: "รายการ", verb: "ควรมี" },
set: { unit: "รายการ", verb: "ควรมี" },
};
function getSizing(origin: string): { unit: string; verb: string } | null {
return Sizable[origin] ?? null;
}
const FormatDictionary: {
[k in $ZodStringFormats | (string & {})]?: string;
} = {
regex: "ข้อมูลที่ป้อน",
email: "ที่อยู่อีเมล",
url: "URL",
emoji: "อิโมจิ",
uuid: "UUID",
uuidv4: "UUIDv4",
uuidv6: "UUIDv6",
nanoid: "nanoid",
guid: "GUID",
cuid: "cuid",
cuid2: "cuid2",
ulid: "ULID",
xid: "XID",
ksuid: "KSUID",
datetime: "วันที่เวลาแบบ ISO",
date: "วันที่แบบ ISO",
time: "เวลาแบบ ISO",
duration: "ช่วงเวลาแบบ ISO",
ipv4: "ที่อยู่ IPv4",
ipv6: "ที่อยู่ IPv6",
cidrv4: "ช่วง IP แบบ IPv4",
cidrv6: "ช่วง IP แบบ IPv6",
base64: "ข้อความแบบ Base64",
base64url: "ข้อความแบบ Base64 สำหรับ URL",
json_string: "ข้อความแบบ JSON",
e164: "เบอร์โทรศัพท์ระหว่างประเทศ (E.164)",
jwt: "โทเคน JWT",
template_literal: "ข้อมูลที่ป้อน",
};
const TypeDictionary: {
[k in errors.$ZodInvalidTypeExpected | (string & {})]?: string;
} = {
nan: "NaN",
number: "ตัวเลข",
array: "อาร์เรย์ (Array)",
null: "ไม่มีค่า (null)",
};
return (issue) => {
switch (issue.code) {
case "invalid_type": {
const expected = TypeDictionary[issue.expected] ?? issue.expected;
const receivedType = util.parsedType(issue.input);
const received = TypeDictionary[receivedType] ?? receivedType;
if (/^[A-Z]/.test(issue.expected)) {
return `ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น instanceof ${issue.expected} แต่ได้รับ ${received}`;
}
return `ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น ${expected} แต่ได้รับ ${received}`;
}
case "invalid_value":
if (issue.values.length === 1) return `ค่าไม่ถูกต้อง: ควรเป็น ${util.stringifyPrimitive(issue.values[0])}`;
return `ตัวเลือกไม่ถูกต้อง: ควรเป็นหนึ่งใน ${util.joinValues(issue.values, "|")}`;
case "too_big": {
const adj = issue.inclusive ? "ไม่เกิน" : "น้อยกว่า";
const sizing = getSizing(issue.origin);
if (sizing)
return `เกินกำหนด: ${issue.origin ?? "ค่า"} ควรมี${adj} ${issue.maximum.toString()} ${sizing.unit ?? "รายการ"}`;
return `เกินกำหนด: ${issue.origin ?? "ค่า"} ควรมี${adj} ${issue.maximum.toString()}`;
}
case "too_small": {
const adj = issue.inclusive ? "อย่างน้อย" : "มากกว่า";
const sizing = getSizing(issue.origin);
if (sizing) {
return `น้อยกว่ากำหนด: ${issue.origin} ควรมี${adj} ${issue.minimum.toString()} ${sizing.unit}`;
}
return `น้อยกว่ากำหนด: ${issue.origin} ควรมี${adj} ${issue.minimum.toString()}`;
}
case "invalid_format": {
const _issue = issue as errors.$ZodStringFormatIssues;
if (_issue.format === "starts_with") {
return `รูปแบบไม่ถูกต้อง: ข้อความต้องขึ้นต้นด้วย "${_issue.prefix}"`;
}
if (_issue.format === "ends_with") return `รูปแบบไม่ถูกต้อง: ข้อความต้องลงท้ายด้วย "${_issue.suffix}"`;
if (_issue.format === "includes") return `รูปแบบไม่ถูกต้อง: ข้อความต้องมี "${_issue.includes}" อยู่ในข้อความ`;
if (_issue.format === "regex") return `รูปแบบไม่ถูกต้อง: ต้องตรงกับรูปแบบที่กำหนด ${_issue.pattern}`;
return `รูปแบบไม่ถูกต้อง: ${FormatDictionary[_issue.format] ?? issue.format}`;
}
case "not_multiple_of":
return `ตัวเลขไม่ถูกต้อง: ต้องเป็นจำนวนที่หารด้วย ${issue.divisor} ได้ลงตัว`;
case "unrecognized_keys":
return `พบคีย์ที่ไม่รู้จัก: ${util.joinValues(issue.keys, ", ")}`;
case "invalid_key":
return `คีย์ไม่ถูกต้องใน ${issue.origin}`;
case "invalid_union":
return "ข้อมูลไม่ถูกต้อง: ไม่ตรงกับรูปแบบยูเนียนที่กำหนดไว้";
case "invalid_element":
return `ข้อมูลไม่ถูกต้องใน ${issue.origin}`;
default:
return `ข้อมูลไม่ถูกต้อง`;
}
};
};
export default function (): { localeError: errors.$ZodErrorMap } {
return {
localeError: error(),
};
}

View File

@@ -0,0 +1,14 @@
import * as jayson from '../../..';
type ClientBrowserCallServerFunctionCallback = (err?:Error | null, response?:string) => void;
type ClientBrowserCallServerFunction = (request:string, callback:ClientBrowserCallServerFunctionCallback) => void;
declare class ClientBrowser {
constructor(callServer:ClientBrowserCallServerFunction, options?:jayson.ClientOptions);
request(method: string, params: jayson.RequestParamsLike, id?: jayson.JSONRPCIDLike | null, callback?: jayson.JSONRPCCallbackType): jayson.JSONRPCRequest;
request(method: string, params: jayson.RequestParamsLike, callback?: jayson.JSONRPCCallbackType): jayson.JSONRPCRequest;
request(method: Array<jayson.JSONRPCRequestLike>, callback: jayson.JSONRPCCallbackTypeBatch): Array<jayson.JSONRPCRequest>;
}
export = ClientBrowser;

View File

@@ -0,0 +1,51 @@
utf-8-validate is licensed for use as follows:
"""
Copyright (c) 2011 Einar Otto Stangvik <einaros@gmail.com>
Copyright (c) 2013 Arnout Kazemier and contributors
Copyright (c) 2016 Luigi Pinca and contributors
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
This license applies to all parts of utf-8-validate that are not externally
maintained libraries.
The externally maintained is_utf8 library used by utf-8-validate, located at
deps/is_utf8, is licensed as follows:
"""
Copyright 2022 The is_utf8 authors
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.
"""