Add TypeScript ESLint configs and lint scripts
Add a repository .editorconfig and a root eslint.config.ts to standardize formatting and linting. Migrate packages/webui ESLint config to TypeScript (eslint.config.ts) with project-specific rules and tsconfigRootDir handling, and remove the old JS config. Update package.json to run ESLint directly (add lint and lint:fix) and add required ESLint/dev dependencies; also add jiti to packages/webui/package.json. Include a small formatting tweak to tsconfig.base.json.
This commit is contained in:
1 parent
f21740a5d3
commit
aea2676c31
30 files changed
+173
-1057
No files matched your search
@@ -0,0 +1,15 @@
|
||||
root = true
|
||||
|
||||
[*]
|
||||
charset = utf-8
|
||||
end_of_line = crlf
|
||||
indent_style = space
|
||||
indent_size = 2
|
||||
insert_final_newline = true
|
||||
trim_trailing_whitespace = true
|
||||
|
||||
[*.{json,yml,yaml,md}]
|
||||
indent_size = 2
|
||||
|
||||
[*.md]
|
||||
trim_trailing_whitespace = false
|
||||
@@ -0,0 +1,77 @@
|
||||
import js from '@eslint/js';
|
||||
import globals from 'globals';
|
||||
import reactHooks from 'eslint-plugin-react-hooks';
|
||||
import reactRefresh from 'eslint-plugin-react-refresh';
|
||||
import tseslint from 'typescript-eslint';
|
||||
import { defineConfig, globalIgnores } from 'eslint/config';
|
||||
|
||||
const tsconfigRootDir = decodeURIComponent(new URL('.', import.meta.url).pathname).replace(/^\/(.:\/)/, '$1');
|
||||
|
||||
export default defineConfig([
|
||||
globalIgnores([
|
||||
'**/dist/**',
|
||||
'**/node_modules/**',
|
||||
'**/coverage/**',
|
||||
'**/.turbo/**',
|
||||
'**/.vite/**',
|
||||
'**/*.tsbuildinfo',
|
||||
'**/test/fixtures/**',
|
||||
'packages/runtime/native/**',
|
||||
]),
|
||||
{
|
||||
files: ['**/*.{js,mjs,cjs,ts,tsx}'],
|
||||
extends: [js.configs.recommended],
|
||||
languageOptions: {
|
||||
ecmaVersion: 2023,
|
||||
sourceType: 'module',
|
||||
globals: {
|
||||
...globals.es2023,
|
||||
...globals.node,
|
||||
},
|
||||
},
|
||||
rules: {
|
||||
'no-unused-vars': 'off',
|
||||
'no-useless-assignment': 'off',
|
||||
'prefer-const': 'off',
|
||||
'preserve-caught-error': 'off',
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [tseslint.configs.recommended],
|
||||
languageOptions: {
|
||||
parserOptions: {
|
||||
tsconfigRootDir,
|
||||
},
|
||||
},
|
||||
rules: {
|
||||
'prefer-const': 'off',
|
||||
'@typescript-eslint/no-explicit-any': 'off',
|
||||
'@typescript-eslint/no-empty-object-type': 'off',
|
||||
'@typescript-eslint/no-this-alias': 'off',
|
||||
'@typescript-eslint/no-unused-vars': [
|
||||
'warn',
|
||||
{
|
||||
argsIgnorePattern: '^_',
|
||||
varsIgnorePattern: '^_',
|
||||
caughtErrorsIgnorePattern: '^_',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['packages/webui/src/**/*.{ts,tsx}', 'packages/ui/src/**/*.{ts,tsx}'],
|
||||
extends: [reactHooks.configs.flat.recommended, reactRefresh.configs.vite],
|
||||
languageOptions: {
|
||||
globals: globals.browser,
|
||||
parserOptions: {
|
||||
tsconfigRootDir,
|
||||
},
|
||||
},
|
||||
rules: {
|
||||
'prefer-const': 'off',
|
||||
'react-refresh/only-export-components': 'off',
|
||||
'react-hooks/set-state-in-effect': 'off',
|
||||
},
|
||||
},
|
||||
]);
|
||||
+10
-2
@@ -15,14 +15,22 @@
|
||||
"test": "pnpm --filter @snowluma/core test",
|
||||
"test:watch": "pnpm --filter @snowluma/core test:watch",
|
||||
"typecheck": "pnpm -r --if-present typecheck",
|
||||
"lint": "pnpm -r --if-present lint",
|
||||
"lint": "eslint .",
|
||||
"lint:fix": "eslint . --fix",
|
||||
"start": "node dist/index.mjs",
|
||||
"bump": "node tools/bump-version.mjs",
|
||||
"release": "node tools/release.mjs"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^10.0.1",
|
||||
"cross-env": "^10.1.0",
|
||||
"typescript": "catalog:"
|
||||
"eslint": "^10.2.0",
|
||||
"eslint-plugin-react-hooks": "^7.0.1",
|
||||
"eslint-plugin-react-refresh": "^0.5.2",
|
||||
"globals": "^17.5.0",
|
||||
"jiti": "^2.6.1",
|
||||
"typescript": "catalog:",
|
||||
"typescript-eslint": "^8.58.2"
|
||||
},
|
||||
"pnpm": {
|
||||
"peerDependencyRules": {
|
||||
|
||||
@@ -1,172 +0,0 @@
|
||||
// Proton vs legacy runtime ProtoSchema encoder/decoder benchmark.
|
||||
//
|
||||
// Compares the codec functions generated at build time by @snowluma/proton
|
||||
// against the runtime schema-walking implementation in src/protobuf/decode.ts,
|
||||
// using the actual long-message schemas already in the codebase.
|
||||
//
|
||||
// Methodology:
|
||||
// - Proton codecs are produced by calling its `analyzeSource` + `generateCode`
|
||||
// API on the existing proto/proton/longmsg.ts source file, then `new
|
||||
// Function`-eval'd into a callable. This is identical to what the Vite
|
||||
// plugin does at build time, minus the file-replacement step.
|
||||
// - Legacy codecs are the existing `protoEncode` / `protoDecode` functions
|
||||
// called against the existing `*Schema` constants.
|
||||
// - Each measurement does 2 000 warmup iterations, then N timed iterations.
|
||||
// - Operation cost is reported as ops/sec and ns/op. The first row's
|
||||
// ops/sec is the relative baseline.
|
||||
//
|
||||
// Run:
|
||||
// pnpm --filter @snowluma/core exec tsx bench/proton-vs-legacy.ts
|
||||
|
||||
import { readFileSync } from 'fs';
|
||||
import { resolve, dirname } from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
import { analyzeSource, generateCode } from '@snowluma/proton/vite';
|
||||
import { protoEncode, protoDecode } from '../src/protobuf/decode';
|
||||
import {
|
||||
LongMsgSettingsSchema,
|
||||
SendLongMsgRespSchema,
|
||||
SendLongMsgReqSchema,
|
||||
RecvLongMsgRespSchema,
|
||||
} from '../src/bridge/proto/longmsg';
|
||||
|
||||
// ── proton codec materialisation ─────────────────────────────────────
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const protonSchemaPath = resolve(__dirname, '..', 'src', 'bridge', 'proto', 'proton', 'longmsg.ts');
|
||||
const protonSchemaSource = readFileSync(protonSchemaPath, 'utf-8');
|
||||
|
||||
function materialiseProton(messageNames: readonly string[]): Record<string, { encode: (o: unknown) => Uint8Array; decode: (b: Uint8Array) => unknown }> {
|
||||
// Append synthetic call sites so the registry actually contains the messages
|
||||
// we want — `selectUsedRegistry` only retains call-site roots, and the
|
||||
// proton/longmsg.ts source itself has no `protobuf_encode` calls.
|
||||
const callSites = messageNames
|
||||
.map((n) => `protobuf_encode<${n}>({} as any); protobuf_decode<${n}>(new Uint8Array());`)
|
||||
.join('\n');
|
||||
const sourceWithCallSites = protonSchemaSource + `\n\n// synthetic call sites for bench codegen\n` + callSites;
|
||||
|
||||
const registry = analyzeSource(sourceWithCallSites, protonSchemaPath);
|
||||
const code = generateCode(registry);
|
||||
const factoryBody = `
|
||||
${code}
|
||||
const out = {};
|
||||
${messageNames.map(n => `out.${n} = { encode: protobuf_encode_${n}, decode: protobuf_decode_${n} };`).join('\n')}
|
||||
return out;
|
||||
`;
|
||||
return new Function(factoryBody)() as Record<string, { encode: (o: unknown) => Uint8Array; decode: (b: Uint8Array) => unknown }>;
|
||||
}
|
||||
|
||||
const proton = materialiseProton([
|
||||
'LongMsgSettings',
|
||||
'SendLongMsgResp',
|
||||
'SendLongMsgReq',
|
||||
'RecvLongMsgResp',
|
||||
]);
|
||||
|
||||
// ── bench harness ────────────────────────────────────────────────────
|
||||
|
||||
interface BenchResult { name: string; opsPerSec: number; nsPerOp: number; }
|
||||
|
||||
function bench(name: string, fn: () => void, iterations: number): BenchResult {
|
||||
for (let i = 0; i < 2000; i++) fn();
|
||||
const start = performance.now();
|
||||
for (let i = 0; i < iterations; i++) fn();
|
||||
const ms = performance.now() - start;
|
||||
return {
|
||||
name,
|
||||
opsPerSec: Math.round((iterations / ms) * 1000),
|
||||
nsPerOp: Math.round((ms / iterations) * 1_000_000),
|
||||
};
|
||||
}
|
||||
|
||||
function printSection(title: string, results: BenchResult[]) {
|
||||
console.log(`\n## ${title}`);
|
||||
console.log('| Encoder | ops/sec | ns/op | relative |');
|
||||
console.log('|------------|-------------|--------|----------|');
|
||||
const baseline = results[0].opsPerSec;
|
||||
for (const r of results) {
|
||||
const rel = r.opsPerSec / baseline;
|
||||
const relStr = r === results[0] ? '1.00×' : `${rel.toFixed(2)}×`;
|
||||
console.log(
|
||||
`| ${r.name.padEnd(10)} | ${r.opsPerSec.toLocaleString().padStart(11)} | ${String(r.nsPerOp).padStart(6)} | ${relStr.padStart(8)} |`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ── workloads ────────────────────────────────────────────────────────
|
||||
|
||||
const settingsObj = { field1: 4, field2: 1, field3: 7, field4: 2 };
|
||||
|
||||
const sendRespObj = { result: { resId: 'res-001' } };
|
||||
|
||||
const sendReqObj = {
|
||||
info: {
|
||||
type: 1,
|
||||
uid: { uid: 'u_test' },
|
||||
groupUin: 123456,
|
||||
payload: new Uint8Array([0xde, 0xad, 0xbe, 0xef]),
|
||||
},
|
||||
settings: { field1: 4, field2: 1, field3: 7, field4: 2 },
|
||||
};
|
||||
|
||||
const recvRespObj = {
|
||||
result: { resId: 'r-1', payload: new Uint8Array(64).fill(0x42) },
|
||||
settings: { field1: 4, field2: 1, field3: 7, field4: 2 },
|
||||
};
|
||||
|
||||
// Pre-encoded bytes for decode benches (use proton output so both sides see
|
||||
// identical, proto3-conforming input).
|
||||
const settingsBytes = proton.LongMsgSettings.encode(settingsObj);
|
||||
const sendRespBytes = proton.SendLongMsgResp.encode(sendRespObj);
|
||||
const sendReqBytes = proton.SendLongMsgReq.encode(sendReqObj);
|
||||
const recvRespBytes = proton.RecvLongMsgResp.encode(recvRespObj);
|
||||
|
||||
// ── run ──────────────────────────────────────────────────────────────
|
||||
|
||||
console.log('# @snowluma/proton vs legacy runtime benchmark\n');
|
||||
console.log(`Node ${process.version} | ${process.platform} ${process.arch}`);
|
||||
console.log(`Date: ${new Date().toISOString().slice(0, 19).replace('T', ' ')}`);
|
||||
|
||||
const N = 300_000;
|
||||
|
||||
printSection('Encode — LongMsgSettings (4× uint32)', [
|
||||
{ ...bench('proton', () => proton.LongMsgSettings.encode(settingsObj), N) },
|
||||
{ ...bench('legacy', () => protoEncode(settingsObj, LongMsgSettingsSchema), N) },
|
||||
]);
|
||||
|
||||
printSection('Decode — LongMsgSettings (4× uint32)', [
|
||||
{ ...bench('proton', () => proton.LongMsgSettings.decode(settingsBytes), N) },
|
||||
{ ...bench('legacy', () => protoDecode(settingsBytes, LongMsgSettingsSchema), N) },
|
||||
]);
|
||||
|
||||
printSection('Encode — SendLongMsgResp (1 nested message, 1 string)', [
|
||||
{ ...bench('proton', () => proton.SendLongMsgResp.encode(sendRespObj), N) },
|
||||
{ ...bench('legacy', () => protoEncode(sendRespObj, SendLongMsgRespSchema), N) },
|
||||
]);
|
||||
|
||||
printSection('Decode — SendLongMsgResp', [
|
||||
{ ...bench('proton', () => proton.SendLongMsgResp.decode(sendRespBytes), N) },
|
||||
{ ...bench('legacy', () => protoDecode(sendRespBytes, SendLongMsgRespSchema), N) },
|
||||
]);
|
||||
|
||||
printSection('Encode — SendLongMsgReq (deeply nested, bytes + uint32 + string)', [
|
||||
{ ...bench('proton', () => proton.SendLongMsgReq.encode(sendReqObj), N) },
|
||||
{ ...bench('legacy', () => protoEncode(sendReqObj, SendLongMsgReqSchema), N) },
|
||||
]);
|
||||
|
||||
printSection('Decode — SendLongMsgReq', [
|
||||
{ ...bench('proton', () => proton.SendLongMsgReq.decode(sendReqBytes), N) },
|
||||
{ ...bench('legacy', () => protoDecode(sendReqBytes, SendLongMsgReqSchema), N) },
|
||||
]);
|
||||
|
||||
printSection('Encode — RecvLongMsgResp (64-byte payload + settings)', [
|
||||
{ ...bench('proton', () => proton.RecvLongMsgResp.encode(recvRespObj), N) },
|
||||
{ ...bench('legacy', () => protoEncode(recvRespObj, RecvLongMsgRespSchema), N) },
|
||||
]);
|
||||
|
||||
printSection('Decode — RecvLongMsgResp', [
|
||||
{ ...bench('proton', () => proton.RecvLongMsgResp.decode(recvRespBytes), N) },
|
||||
{ ...bench('legacy', () => protoDecode(recvRespBytes, RecvLongMsgRespSchema), N) },
|
||||
]);
|
||||
|
||||
console.log('');
|
||||
@@ -15,7 +15,7 @@
|
||||
// envelope retCode via the non-generic `OidbBaseMeta` view.
|
||||
|
||||
import type { Bridge } from './bridge';
|
||||
import { protobuf_encode, protobuf_decode } from '@snowluma/proton';
|
||||
import { protobuf_decode } from '@snowluma/proton';
|
||||
import type { OidbBase, OidbBaseMeta } from './proto/proton/oidb';
|
||||
|
||||
/**
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
// Heavy OIDB / contact / action logic is split into bridge-oidb, bridge-contacts, bridge-actions.
|
||||
|
||||
import type { PacketInfo } from '../protocol/types';
|
||||
import type { ForwardNodePayload, QQEventVariant, MessageElement } from './events';
|
||||
import type { ForwardNodePayload, MessageElement } from './events';
|
||||
import type { FriendInfo, QQGroupInfo, GroupMemberInfo, UserProfileInfo, GroupRequestInfo } from './qq-info';
|
||||
import { MSG_PUSH_CMD, parseMsgPush } from './msg-push';
|
||||
import type { PacketSender, SendPacketResult } from '../protocol/packet-sender';
|
||||
@@ -12,7 +12,6 @@ import { buildSendElems } from './element-builder';
|
||||
import { IdentityService } from './identity-service';
|
||||
import type { BridgeInterface } from './bridge-interface';
|
||||
import { IncomingPacketPipeline, type CmdParser } from './packet-pipeline';
|
||||
import { createLogger } from '../utils/logger';
|
||||
import type {
|
||||
SendMessageRequest,
|
||||
SendMessageResponse,
|
||||
@@ -185,8 +184,6 @@ export interface ClientKeyInfo {
|
||||
keyIndex: string
|
||||
}
|
||||
|
||||
const log = createLogger('Bridge');
|
||||
|
||||
export class Bridge implements BridgeInterface {
|
||||
private static readonly SEND_MSG_CMD = 'MessageSvc.PbSendMsg';
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { RequestUtil, cookieToString, getBknFromCookie } from './request-util';
|
||||
import { createHash } from 'crypto';
|
||||
import { readFileSync, statSync, createReadStream, writeFileSync, unlinkSync } from 'fs';
|
||||
import { statSync, createReadStream, writeFileSync, unlinkSync } from 'fs';
|
||||
import { basename, join } from 'path';
|
||||
import { tmpdir } from 'os';
|
||||
|
||||
|
||||
@@ -186,7 +186,6 @@ export async function uploadGroupNoticeImage(
|
||||
|
||||
const body = Buffer.concat(parts);
|
||||
|
||||
const url = 'https://web.qun.qq.com/cgi-bin/announce/upload_img';
|
||||
const options = {
|
||||
hostname: 'web.qun.qq.com',
|
||||
path: '/cgi-bin/announce/upload_img',
|
||||
@@ -198,7 +197,7 @@ export async function uploadGroupNoticeImage(
|
||||
},
|
||||
};
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
return new Promise((resolve) => {
|
||||
const req = https.request(options, (res) => {
|
||||
let data = '';
|
||||
res.on('data', (chunk) => { data += chunk; });
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { EventEmitter } from 'events';
|
||||
import type { PacketSender } from '../protocol/packet-sender';
|
||||
import type { PacketSink } from '../protocol/types';
|
||||
import { createLogger, type Logger } from '../utils/logger';
|
||||
import { HookPacketClient } from './hook-packet-client';
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
// into internal MessageElement arrays for sending.
|
||||
|
||||
import type { MessageElement } from '../bridge/events';
|
||||
import type { JsonValue, JsonObject } from './types';
|
||||
import type { JsonValue } from './types';
|
||||
import { createLogger } from '../utils/logger';
|
||||
|
||||
const log = createLogger('MsgParser');
|
||||
|
||||
@@ -1,241 +0,0 @@
|
||||
// Runtime schema-based protobuf decode/encode.
|
||||
// TypeScript equivalent of the C++ proto_field<N,T> DSL using plain schema objects.
|
||||
//
|
||||
// Usage:
|
||||
// const MyMessageSchema = {
|
||||
// fromUin: { field: 1, type: 'uint32' as const },
|
||||
// fromUid: { field: 2, type: 'string' as const },
|
||||
// grp: { field: 8, type: 'message' as const, schema: GrpSchema },
|
||||
// elements: { field: 2, type: 'repeated_message' as const, schema: ElemSchema },
|
||||
// };
|
||||
// type MyMessage = ProtoDecoded<typeof MyMessageSchema>;
|
||||
// const msg = protoDecode(rawBytes, MyMessageSchema);
|
||||
|
||||
import { WireMessage, WireType, encodeVarint, encodeKey, decodeVarint } from './wire';
|
||||
|
||||
// --- Schema types ---
|
||||
|
||||
export type FieldType =
|
||||
| 'bool' | 'int32' | 'uint32' | 'int64' | 'uint64'
|
||||
| 'string' | 'bytes' | 'message'
|
||||
| 'repeated_varint' | 'repeated_uint32' | 'repeated_string'
|
||||
| 'repeated_bytes' | 'repeated_message';
|
||||
|
||||
export interface FieldDef {
|
||||
field: number;
|
||||
type: FieldType;
|
||||
schema?: ProtoSchema; // required for 'message' / 'repeated_message'
|
||||
}
|
||||
|
||||
export type ProtoSchema = { [key: string]: FieldDef };
|
||||
|
||||
// --- Decoded type inference ---
|
||||
|
||||
type FieldTypeToTS<T extends FieldType, S extends ProtoSchema | undefined> =
|
||||
T extends 'bool' ? boolean :
|
||||
T extends 'int32' | 'uint32' ? number :
|
||||
T extends 'int64' | 'uint64' ? bigint :
|
||||
T extends 'string' ? string :
|
||||
T extends 'bytes' ? Uint8Array :
|
||||
T extends 'message' ? (S extends ProtoSchema ? ProtoDecoded<S> : Record<string, unknown>) :
|
||||
T extends 'repeated_varint' | 'repeated_uint32' ? number[] :
|
||||
T extends 'repeated_string' ? string[] :
|
||||
T extends 'repeated_bytes' ? Uint8Array[] :
|
||||
T extends 'repeated_message' ? (S extends ProtoSchema ? ProtoDecoded<S>[] : Record<string, unknown>[]) :
|
||||
never;
|
||||
|
||||
type IsRepeated<T extends FieldType> = T extends `repeated_${string}` ? true : false;
|
||||
|
||||
type FieldValue<F extends FieldDef> =
|
||||
IsRepeated<F['type']> extends true
|
||||
? FieldTypeToTS<F['type'], F['schema']>
|
||||
: FieldTypeToTS<F['type'], F['schema']> | undefined;
|
||||
|
||||
export type ProtoDecoded<S extends ProtoSchema> = {
|
||||
[K in keyof S]: FieldValue<S[K]>;
|
||||
};
|
||||
|
||||
// --- Decode ---
|
||||
|
||||
export function protoDecode<S extends ProtoSchema>(
|
||||
data: Uint8Array | WireMessage,
|
||||
schema: S
|
||||
): ProtoDecoded<S> | null {
|
||||
const wire = data instanceof WireMessage ? data : WireMessage.decode(data);
|
||||
if (!wire) return null;
|
||||
|
||||
const result: Record<string, unknown> = {};
|
||||
|
||||
for (const [key, def] of Object.entries(schema)) {
|
||||
switch (def.type) {
|
||||
case 'bool': {
|
||||
const v = wire.getVarint(def.field);
|
||||
if (v !== null) result[key] = v !== 0n;
|
||||
break;
|
||||
}
|
||||
case 'int32': {
|
||||
const v = wire.getInt32(def.field);
|
||||
if (v !== null) result[key] = v;
|
||||
break;
|
||||
}
|
||||
case 'uint32': {
|
||||
const v = wire.getUint32(def.field);
|
||||
if (v !== null) result[key] = v;
|
||||
break;
|
||||
}
|
||||
case 'int64': {
|
||||
const v = wire.getInt64(def.field);
|
||||
if (v !== null) result[key] = v;
|
||||
break;
|
||||
}
|
||||
case 'uint64': {
|
||||
const v = wire.getUint64(def.field);
|
||||
if (v !== null) result[key] = v;
|
||||
break;
|
||||
}
|
||||
case 'string': {
|
||||
const v = wire.getString(def.field);
|
||||
if (v !== null) result[key] = v;
|
||||
break;
|
||||
}
|
||||
case 'bytes': {
|
||||
const v = wire.getBytes(def.field);
|
||||
if (v !== null) result[key] = v;
|
||||
break;
|
||||
}
|
||||
case 'message': {
|
||||
const sub = wire.getMessage(def.field);
|
||||
if (sub && def.schema) {
|
||||
result[key] = protoDecode(sub, def.schema);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'repeated_varint': {
|
||||
const vals = wire.getRepeatedVarint(def.field);
|
||||
result[key] = vals.map(v => Number(BigInt.asIntN(32, v)));
|
||||
break;
|
||||
}
|
||||
case 'repeated_uint32': {
|
||||
const vals = wire.getRepeatedVarint(def.field);
|
||||
result[key] = vals.map(v => Number(BigInt.asUintN(32, v)));
|
||||
break;
|
||||
}
|
||||
case 'repeated_string': {
|
||||
result[key] = wire.getRepeatedString(def.field);
|
||||
break;
|
||||
}
|
||||
case 'repeated_bytes': {
|
||||
const flds = wire.fields(def.field);
|
||||
result[key] = flds
|
||||
.filter(f => f.wireType === WireType.LengthDelimited)
|
||||
.map(f => f.bytes);
|
||||
break;
|
||||
}
|
||||
case 'repeated_message': {
|
||||
if (!def.schema) { result[key] = []; break; }
|
||||
const msgs = wire.getRepeatedMessage(def.field);
|
||||
result[key] = msgs
|
||||
.map(m => protoDecode(m, def.schema!))
|
||||
.filter((m): m is NonNullable<typeof m> => m !== null);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result as ProtoDecoded<S>;
|
||||
}
|
||||
|
||||
// --- Encode ---
|
||||
|
||||
export function protoEncode<S extends ProtoSchema>(
|
||||
obj: Partial<ProtoDecoded<S>>,
|
||||
schema: S
|
||||
): Uint8Array {
|
||||
const out: number[] = [];
|
||||
const record = obj as Record<string, any>;
|
||||
|
||||
for (const [key, def] of Object.entries(schema)) {
|
||||
const val = record[key];
|
||||
if (val === undefined || val === null) continue;
|
||||
|
||||
switch (def.type) {
|
||||
case 'bool': {
|
||||
encodeKey(def.field, WireType.Varint, out);
|
||||
encodeVarint(val ? 1 : 0, out);
|
||||
break;
|
||||
}
|
||||
case 'int32':
|
||||
case 'uint32': {
|
||||
encodeKey(def.field, WireType.Varint, out);
|
||||
encodeVarint(val as number, out);
|
||||
break;
|
||||
}
|
||||
case 'int64':
|
||||
case 'uint64': {
|
||||
encodeKey(def.field, WireType.Varint, out);
|
||||
encodeVarint(val as bigint, out);
|
||||
break;
|
||||
}
|
||||
case 'string': {
|
||||
const encoded = new TextEncoder().encode(val as string);
|
||||
encodeKey(def.field, WireType.LengthDelimited, out);
|
||||
encodeVarint(encoded.length, out);
|
||||
for (const b of encoded) out.push(b);
|
||||
break;
|
||||
}
|
||||
case 'bytes': {
|
||||
const buf = val as Uint8Array;
|
||||
encodeKey(def.field, WireType.LengthDelimited, out);
|
||||
encodeVarint(buf.length, out);
|
||||
for (const b of buf) out.push(b);
|
||||
break;
|
||||
}
|
||||
case 'message': {
|
||||
if (!def.schema) break;
|
||||
const nested = protoEncode(val as any, def.schema);
|
||||
encodeKey(def.field, WireType.LengthDelimited, out);
|
||||
encodeVarint(nested.length, out);
|
||||
for (const b of nested) out.push(b);
|
||||
break;
|
||||
}
|
||||
case 'repeated_varint':
|
||||
case 'repeated_uint32': {
|
||||
for (const v of val as number[]) {
|
||||
encodeKey(def.field, WireType.Varint, out);
|
||||
encodeVarint(v, out);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'repeated_string': {
|
||||
const encoder = new TextEncoder();
|
||||
for (const s of val as string[]) {
|
||||
const encoded = encoder.encode(s);
|
||||
encodeKey(def.field, WireType.LengthDelimited, out);
|
||||
encodeVarint(encoded.length, out);
|
||||
for (const b of encoded) out.push(b);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'repeated_bytes': {
|
||||
for (const buf of val as Uint8Array[]) {
|
||||
encodeKey(def.field, WireType.LengthDelimited, out);
|
||||
encodeVarint(buf.length, out);
|
||||
for (const b of buf) out.push(b);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'repeated_message': {
|
||||
if (!def.schema) break;
|
||||
for (const item of val as any[]) {
|
||||
const nested = protoEncode(item, def.schema);
|
||||
encodeKey(def.field, WireType.LengthDelimited, out);
|
||||
encodeVarint(nested.length, out);
|
||||
for (const b of nested) out.push(b);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return new Uint8Array(out);
|
||||
}
|
||||
@@ -1,242 +0,0 @@
|
||||
// Protobuf wire-format decoder/encoder.
|
||||
// Generic decoder that works without .proto schemas — decodes any protobuf
|
||||
// binary into a field_number → value tree structure.
|
||||
// Port of src/protobuf/wire.h + wire.cpp
|
||||
|
||||
export enum WireType {
|
||||
Varint = 0,
|
||||
Fixed64 = 1,
|
||||
LengthDelimited = 2,
|
||||
Fixed32 = 5,
|
||||
}
|
||||
|
||||
export interface WireField {
|
||||
fieldNumber: number;
|
||||
wireType: WireType;
|
||||
varint: bigint; // Varint, Fixed64, Fixed32
|
||||
bytes: Uint8Array; // LengthDelimited
|
||||
}
|
||||
|
||||
// --- Varint decode ---
|
||||
export function decodeVarint(data: Uint8Array, offset: number): [bigint, number] | null {
|
||||
let result = 0n;
|
||||
for (let i = 0; i < 10 && offset + i < data.length; i++) {
|
||||
result |= BigInt(data[offset + i] & 0x7f) << BigInt(7 * i);
|
||||
if ((data[offset + i] & 0x80) === 0) {
|
||||
return [result, i + 1];
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// --- Varint encode ---
|
||||
export function encodeVarint(value: bigint | number, out: number[]): void {
|
||||
let v = typeof value === 'number' ? BigInt(value >>> 0) : value;
|
||||
if (v < 0n) v = v + (1n << 64n); // treat as unsigned 64-bit
|
||||
while (v >= 0x80n) {
|
||||
out.push(Number(v & 0x7Fn) | 0x80);
|
||||
v >>= 7n;
|
||||
}
|
||||
out.push(Number(v));
|
||||
}
|
||||
|
||||
// --- Key encode ---
|
||||
export function encodeKey(fieldNumber: number, wireType: WireType, out: number[]): void {
|
||||
encodeVarint(BigInt(fieldNumber) << 3n | BigInt(wireType), out);
|
||||
}
|
||||
|
||||
// --- Field value helpers ---
|
||||
export function fieldAsInt32(f: WireField): number { return Number(BigInt.asIntN(32, f.varint)); }
|
||||
export function fieldAsUint32(f: WireField): number { return Number(BigInt.asUintN(32, f.varint)); }
|
||||
export function fieldAsInt64(f: WireField): bigint { return BigInt.asIntN(64, f.varint); }
|
||||
export function fieldAsUint64(f: WireField): bigint { return f.varint; }
|
||||
export function fieldAsBool(f: WireField): boolean { return f.varint !== 0n; }
|
||||
export function fieldAsString(f: WireField): string {
|
||||
return new TextDecoder().decode(f.bytes);
|
||||
}
|
||||
export function fieldAsBytes(f: WireField): Uint8Array {
|
||||
return f.bytes;
|
||||
}
|
||||
|
||||
export class WireMessage {
|
||||
private fields_: WireField[];
|
||||
|
||||
private constructor(fields: WireField[]) {
|
||||
this.fields_ = fields;
|
||||
}
|
||||
|
||||
static decode(data: Uint8Array): WireMessage | null {
|
||||
if (!data || data.length === 0) return null;
|
||||
|
||||
const fields: WireField[] = [];
|
||||
let pos = 0;
|
||||
|
||||
while (pos < data.length) {
|
||||
const tagResult = decodeVarint(data, pos);
|
||||
if (!tagResult) break;
|
||||
const [tag, tagLen] = tagResult;
|
||||
pos += tagLen;
|
||||
|
||||
const fieldNum = Number(tag >> 3n);
|
||||
const wireType = Number(tag & 0x07n) as WireType;
|
||||
|
||||
if (fieldNum === 0) break;
|
||||
|
||||
const field: WireField = {
|
||||
fieldNumber: fieldNum,
|
||||
wireType,
|
||||
varint: 0n,
|
||||
bytes: new Uint8Array(0),
|
||||
};
|
||||
|
||||
switch (wireType) {
|
||||
case WireType.Varint: {
|
||||
const valResult = decodeVarint(data, pos);
|
||||
if (!valResult) return null;
|
||||
field.varint = valResult[0];
|
||||
pos += valResult[1];
|
||||
break;
|
||||
}
|
||||
case WireType.Fixed64: {
|
||||
if (pos + 8 > data.length) return null;
|
||||
const dv = new DataView(data.buffer, data.byteOffset + pos, 8);
|
||||
field.varint = dv.getBigUint64(0, true);
|
||||
pos += 8;
|
||||
break;
|
||||
}
|
||||
case WireType.Fixed32: {
|
||||
if (pos + 4 > data.length) return null;
|
||||
const dv = new DataView(data.buffer, data.byteOffset + pos, 4);
|
||||
field.varint = BigInt(dv.getUint32(0, true));
|
||||
pos += 4;
|
||||
break;
|
||||
}
|
||||
case WireType.LengthDelimited: {
|
||||
const lenResult = decodeVarint(data, pos);
|
||||
if (!lenResult) return null;
|
||||
const fieldLen = Number(lenResult[0]);
|
||||
pos += lenResult[1];
|
||||
if (pos + fieldLen > data.length) return null;
|
||||
field.bytes = data.subarray(pos, pos + fieldLen);
|
||||
pos += fieldLen;
|
||||
break;
|
||||
}
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
|
||||
fields.push(field);
|
||||
}
|
||||
|
||||
return new WireMessage(fields);
|
||||
}
|
||||
|
||||
// --- Single field access ---
|
||||
|
||||
field(num: number): WireField | null {
|
||||
for (const f of this.fields_) {
|
||||
if (f.fieldNumber === num) return f;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
has(num: number): boolean {
|
||||
return this.field(num) !== null;
|
||||
}
|
||||
|
||||
getVarint(num: number): bigint | null {
|
||||
const f = this.field(num);
|
||||
if (!f || f.wireType !== WireType.Varint) return null;
|
||||
return f.varint;
|
||||
}
|
||||
|
||||
getInt32(num: number): number | null {
|
||||
const v = this.getVarint(num);
|
||||
return v !== null ? Number(BigInt.asIntN(32, v)) : null;
|
||||
}
|
||||
|
||||
getUint32(num: number): number | null {
|
||||
const v = this.getVarint(num);
|
||||
return v !== null ? Number(BigInt.asUintN(32, v)) : null;
|
||||
}
|
||||
|
||||
getInt64(num: number): bigint | null {
|
||||
const v = this.getVarint(num);
|
||||
return v !== null ? BigInt.asIntN(64, v) : null;
|
||||
}
|
||||
|
||||
getUint64(num: number): bigint | null {
|
||||
return this.getVarint(num);
|
||||
}
|
||||
|
||||
getString(num: number): string | null {
|
||||
const f = this.field(num);
|
||||
if (!f || f.wireType !== WireType.LengthDelimited) return null;
|
||||
return fieldAsString(f);
|
||||
}
|
||||
|
||||
getBytes(num: number): Uint8Array | null {
|
||||
const f = this.field(num);
|
||||
if (!f || f.wireType !== WireType.LengthDelimited) return null;
|
||||
return f.bytes;
|
||||
}
|
||||
|
||||
getMessage(num: number): WireMessage | null {
|
||||
const f = this.field(num);
|
||||
if (!f || f.wireType !== WireType.LengthDelimited) return null;
|
||||
return WireMessage.decode(f.bytes);
|
||||
}
|
||||
|
||||
// --- Repeated field access ---
|
||||
|
||||
fields(num: number): WireField[] {
|
||||
return this.fields_.filter(f => f.fieldNumber === num);
|
||||
}
|
||||
|
||||
getRepeatedVarint(num: number): bigint[] {
|
||||
const result: bigint[] = [];
|
||||
for (const f of this.fields_) {
|
||||
if (f.fieldNumber !== num) continue;
|
||||
if (f.wireType === WireType.Varint) {
|
||||
result.push(f.varint);
|
||||
} else if (f.wireType === WireType.LengthDelimited) {
|
||||
// Packed repeated varint
|
||||
let pos = 0;
|
||||
while (pos < f.bytes.length) {
|
||||
const r = decodeVarint(f.bytes, pos);
|
||||
if (!r) break;
|
||||
result.push(r[0]);
|
||||
pos += r[1];
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
getRepeatedString(num: number): string[] {
|
||||
const result: string[] = [];
|
||||
const decoder = new TextDecoder();
|
||||
for (const f of this.fields_) {
|
||||
if (f.fieldNumber === num && f.wireType === WireType.LengthDelimited) {
|
||||
result.push(decoder.decode(f.bytes));
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
getRepeatedMessage(num: number): WireMessage[] {
|
||||
const result: WireMessage[] = [];
|
||||
for (const f of this.fields_) {
|
||||
if (f.fieldNumber === num && f.wireType === WireType.LengthDelimited) {
|
||||
const sub = WireMessage.decode(f.bytes);
|
||||
if (sub) result.push(sub);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// --- Raw iteration ---
|
||||
|
||||
get allFields(): WireField[] { return this.fields_; }
|
||||
get empty(): boolean { return this.fields_.length === 0; }
|
||||
}
|
||||
@@ -81,7 +81,6 @@ class FileWriter {
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
} catch (err) {
|
||||
this.disabled = true;
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(
|
||||
`[logger] failed to create log dir ${dir}: ${err instanceof Error ? err.message : String(err)}`,
|
||||
);
|
||||
@@ -170,12 +169,10 @@ class FileWriter {
|
||||
}
|
||||
const stream = fs.createWriteStream(p, { flags: 'a' });
|
||||
stream.on('error', (err) => {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(`[logger] file write error on ${p}: ${err.message}`);
|
||||
});
|
||||
return { stream, bytes, date, splitIndex, path: p };
|
||||
} catch (err) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(
|
||||
`[logger] failed to open log file ${p}: ${err instanceof Error ? err.message : String(err)}`,
|
||||
);
|
||||
|
||||
@@ -1,173 +0,0 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { protoDecode, protoEncode, type ProtoSchema } from '../src/protobuf/decode';
|
||||
import { WireMessage, encodeKey, encodeVarint, WireType } from '../src/protobuf/wire';
|
||||
|
||||
describe('protoDecode', () => {
|
||||
const SimpleSchema = {
|
||||
name: { field: 1, type: 'string' as const },
|
||||
age: { field: 2, type: 'uint32' as const },
|
||||
active: { field: 3, type: 'bool' as const },
|
||||
};
|
||||
|
||||
function buildProto(): Uint8Array {
|
||||
const out: number[] = [];
|
||||
// field 1 string "Alice"
|
||||
encodeKey(1, WireType.LengthDelimited, out);
|
||||
const str = new TextEncoder().encode('Alice');
|
||||
encodeVarint(str.length, out);
|
||||
out.push(...str);
|
||||
// field 2 uint32 = 30
|
||||
encodeKey(2, WireType.Varint, out);
|
||||
encodeVarint(30, out);
|
||||
// field 3 bool = true
|
||||
encodeKey(3, WireType.Varint, out);
|
||||
encodeVarint(1, out);
|
||||
return new Uint8Array(out);
|
||||
}
|
||||
|
||||
it('decodes all fields', () => {
|
||||
const result = protoDecode(buildProto(), SimpleSchema);
|
||||
expect(result).not.toBeNull();
|
||||
expect(result!.name).toBe('Alice');
|
||||
expect(result!.age).toBe(30);
|
||||
expect(result!.active).toBe(true);
|
||||
});
|
||||
|
||||
it('handles missing fields', () => {
|
||||
// Only field 1
|
||||
const out: number[] = [];
|
||||
encodeKey(1, WireType.LengthDelimited, out);
|
||||
const str = new TextEncoder().encode('Bob');
|
||||
encodeVarint(str.length, out);
|
||||
out.push(...str);
|
||||
|
||||
const result = protoDecode(new Uint8Array(out), SimpleSchema);
|
||||
expect(result).not.toBeNull();
|
||||
expect(result!.name).toBe('Bob');
|
||||
expect(result!.age).toBeUndefined();
|
||||
expect(result!.active).toBeUndefined();
|
||||
});
|
||||
|
||||
it('returns null for empty data', () => {
|
||||
expect(protoDecode(new Uint8Array(0), SimpleSchema)).toBeNull();
|
||||
});
|
||||
|
||||
it('decodes nested messages', () => {
|
||||
const InnerSchema = {
|
||||
value: { field: 1, type: 'uint32' as const },
|
||||
};
|
||||
const OuterSchema = {
|
||||
inner: { field: 1, type: 'message' as const, schema: InnerSchema },
|
||||
};
|
||||
|
||||
// Build inner
|
||||
const innerOut: number[] = [];
|
||||
encodeKey(1, WireType.Varint, innerOut);
|
||||
encodeVarint(99, innerOut);
|
||||
|
||||
// Build outer
|
||||
const outerOut: number[] = [];
|
||||
encodeKey(1, WireType.LengthDelimited, outerOut);
|
||||
encodeVarint(innerOut.length, outerOut);
|
||||
outerOut.push(...innerOut);
|
||||
|
||||
const result = protoDecode(new Uint8Array(outerOut), OuterSchema);
|
||||
expect(result).not.toBeNull();
|
||||
expect(result!.inner).not.toBeUndefined();
|
||||
expect(result!.inner!.value).toBe(99);
|
||||
});
|
||||
|
||||
it('decodes repeated messages', () => {
|
||||
const ItemSchema = {
|
||||
id: { field: 1, type: 'uint32' as const },
|
||||
};
|
||||
const ListSchema = {
|
||||
items: { field: 1, type: 'repeated_message' as const, schema: ItemSchema },
|
||||
};
|
||||
|
||||
const out: number[] = [];
|
||||
for (const id of [1, 2, 3]) {
|
||||
const itemOut: number[] = [];
|
||||
encodeKey(1, WireType.Varint, itemOut);
|
||||
encodeVarint(id, itemOut);
|
||||
|
||||
encodeKey(1, WireType.LengthDelimited, out);
|
||||
encodeVarint(itemOut.length, out);
|
||||
out.push(...itemOut);
|
||||
}
|
||||
|
||||
const result = protoDecode(new Uint8Array(out), ListSchema);
|
||||
expect(result).not.toBeNull();
|
||||
expect(result!.items).toHaveLength(3);
|
||||
expect(result!.items.map((i) => i.id)).toEqual([1, 2, 3]);
|
||||
});
|
||||
|
||||
it('accepts WireMessage directly', () => {
|
||||
const wire = WireMessage.decode(buildProto());
|
||||
const result = protoDecode(wire!, SimpleSchema);
|
||||
expect(result!.name).toBe('Alice');
|
||||
});
|
||||
});
|
||||
|
||||
describe('protoEncode', () => {
|
||||
const SimpleSchema = {
|
||||
name: { field: 1, type: 'string' as const },
|
||||
age: { field: 2, type: 'uint32' as const },
|
||||
active: { field: 3, type: 'bool' as const },
|
||||
};
|
||||
|
||||
it('encodes and decodes roundtrip', () => {
|
||||
const data = { name: 'Charlie', age: 25, active: true };
|
||||
const encoded = protoEncode(data, SimpleSchema);
|
||||
const decoded = protoDecode(encoded, SimpleSchema);
|
||||
expect(decoded).not.toBeNull();
|
||||
expect(decoded!.name).toBe('Charlie');
|
||||
expect(decoded!.age).toBe(25);
|
||||
expect(decoded!.active).toBe(true);
|
||||
});
|
||||
|
||||
it('skips undefined fields', () => {
|
||||
const data = { name: 'Dave', age: undefined, active: undefined };
|
||||
const encoded = protoEncode(data as any, SimpleSchema);
|
||||
const decoded = protoDecode(encoded, SimpleSchema);
|
||||
expect(decoded!.name).toBe('Dave');
|
||||
expect(decoded!.age).toBeUndefined();
|
||||
expect(decoded!.active).toBeUndefined();
|
||||
});
|
||||
|
||||
it('encodes bytes', () => {
|
||||
const ByteSchema = {
|
||||
payload: { field: 1, type: 'bytes' as const },
|
||||
};
|
||||
const data = { payload: new Uint8Array([0xDE, 0xAD]) };
|
||||
const encoded = protoEncode(data, ByteSchema);
|
||||
const decoded = protoDecode(encoded, ByteSchema);
|
||||
expect(decoded!.payload).toEqual(new Uint8Array([0xDE, 0xAD]));
|
||||
});
|
||||
|
||||
it('encodes nested messages', () => {
|
||||
const InnerSchema = {
|
||||
value: { field: 1, type: 'uint32' as const },
|
||||
};
|
||||
const OuterSchema = {
|
||||
inner: { field: 1, type: 'message' as const, schema: InnerSchema },
|
||||
};
|
||||
|
||||
const data = { inner: { value: 42 } };
|
||||
const encoded = protoEncode(data, OuterSchema);
|
||||
const decoded = protoDecode(encoded, OuterSchema);
|
||||
expect(decoded!.inner!.value).toBe(42);
|
||||
});
|
||||
|
||||
it('encodes int64/uint64', () => {
|
||||
const BigSchema = {
|
||||
signed: { field: 1, type: 'int64' as const },
|
||||
unsigned: { field: 2, type: 'uint64' as const },
|
||||
};
|
||||
const data = { signed: -1n, unsigned: 0xFFFFFFFFFFFFFFFFn };
|
||||
const encoded = protoEncode(data, BigSchema);
|
||||
const decoded = protoDecode(encoded, BigSchema);
|
||||
expect(decoded!.signed).toBe(-1n);
|
||||
expect(decoded!.unsigned).toBe(0xFFFFFFFFFFFFFFFFn);
|
||||
});
|
||||
});
|
||||
@@ -2,7 +2,7 @@ import fs from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import { pathToFileURL } from 'url';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { loadBinarySource, resolveLocalFilePath } from '../src/bridge/highway/utils';
|
||||
|
||||
describe('highway source paths', () => {
|
||||
|
||||
@@ -5,7 +5,6 @@ import { MediaStore } from '../src/onebot/media-store';
|
||||
import { convertEvent, type ConverterContext } from '../src/onebot/event-converter';
|
||||
import type { GroupMessage, FriendMessage, MessageElement } from '../src/bridge/events';
|
||||
|
||||
const SELF_UIN = '10001';
|
||||
const SELF_ID = 10001;
|
||||
const PEER_UIN = 22222;
|
||||
const GROUP_ID = 99999;
|
||||
|
||||
@@ -236,7 +236,6 @@ describe('onebot/contact-actions / getGroupMemberList', () => {
|
||||
describe('onebot/contact-actions / getGroupMemberInfo', () => {
|
||||
it('returns the cached member when present and noCache is false', async () => {
|
||||
const member = makeMember(44, 'dave', 'D');
|
||||
const cached = makeGroup(1000, '', [member]);
|
||||
const bridge = fakeBridge({
|
||||
fetchGroupMemberList: vi.fn(async () => []),
|
||||
identity: fakeIdentity({
|
||||
|
||||
@@ -2,8 +2,6 @@ import { describe, it, expect } from 'vitest';
|
||||
import { PipeWatcher } from '../src/hook/pipe-watcher';
|
||||
import type { HookProcessBaseInfo } from '../src/hook/injector';
|
||||
|
||||
const flush = () => new Promise<void>(r => setImmediate(r));
|
||||
|
||||
function setupWatcher(initial: { processes: HookProcessBaseInfo[]; live: Set<number> }) {
|
||||
let processes = initial.processes;
|
||||
let live = initial.live;
|
||||
|
||||
@@ -1,175 +0,0 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import {
|
||||
WireType,
|
||||
WireMessage,
|
||||
decodeVarint,
|
||||
encodeVarint,
|
||||
encodeKey,
|
||||
fieldAsInt32,
|
||||
fieldAsUint32,
|
||||
fieldAsString,
|
||||
fieldAsBool,
|
||||
} from '../src/protobuf/wire';
|
||||
|
||||
// Helper to build bytes from number array
|
||||
function bytes(...vals: number[]): Uint8Array {
|
||||
return new Uint8Array(vals);
|
||||
}
|
||||
|
||||
describe('decodeVarint', () => {
|
||||
it('decodes single-byte varint', () => {
|
||||
const result = decodeVarint(bytes(0x05), 0);
|
||||
expect(result).toEqual([5n, 1]);
|
||||
});
|
||||
|
||||
it('decodes zero', () => {
|
||||
const result = decodeVarint(bytes(0x00), 0);
|
||||
expect(result).toEqual([0n, 1]);
|
||||
});
|
||||
|
||||
it('decodes multi-byte varint (300)', () => {
|
||||
// 300 = 0b100101100 => 0xAC 0x02
|
||||
const result = decodeVarint(bytes(0xac, 0x02), 0);
|
||||
expect(result).toEqual([300n, 2]);
|
||||
});
|
||||
|
||||
it('decodes with offset', () => {
|
||||
const result = decodeVarint(bytes(0xff, 0x01), 1);
|
||||
expect(result).toEqual([1n, 1]);
|
||||
});
|
||||
|
||||
it('returns null on empty data', () => {
|
||||
const result = decodeVarint(bytes(), 0);
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('encodeVarint', () => {
|
||||
it('encodes small number', () => {
|
||||
const out: number[] = [];
|
||||
encodeVarint(5, out);
|
||||
expect(out).toEqual([5]);
|
||||
});
|
||||
|
||||
it('encodes 300', () => {
|
||||
const out: number[] = [];
|
||||
encodeVarint(300, out);
|
||||
expect(out).toEqual([0xac, 0x02]);
|
||||
});
|
||||
|
||||
it('encodes bigint', () => {
|
||||
const out: number[] = [];
|
||||
encodeVarint(300n, out);
|
||||
expect(out).toEqual([0xac, 0x02]);
|
||||
});
|
||||
|
||||
it('roundtrips', () => {
|
||||
for (const val of [0, 1, 127, 128, 300, 65535, 2147483647]) {
|
||||
const out: number[] = [];
|
||||
encodeVarint(val, out);
|
||||
const [decoded] = decodeVarint(new Uint8Array(out), 0)!;
|
||||
expect(Number(decoded)).toBe(val);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('encodeKey', () => {
|
||||
it('encodes field 1 varint', () => {
|
||||
const out: number[] = [];
|
||||
encodeKey(1, WireType.Varint, out);
|
||||
expect(out).toEqual([0x08]); // (1 << 3) | 0 = 8
|
||||
});
|
||||
|
||||
it('encodes field 2 length-delimited', () => {
|
||||
const out: number[] = [];
|
||||
encodeKey(2, WireType.LengthDelimited, out);
|
||||
expect(out).toEqual([0x12]); // (2 << 3) | 2 = 18
|
||||
});
|
||||
});
|
||||
|
||||
describe('WireMessage', () => {
|
||||
// Build a simple protobuf: field 1 = varint 150, field 2 = string "testing"
|
||||
function buildSimpleMessage(): Uint8Array {
|
||||
const out: number[] = [];
|
||||
// field 1, varint = 150
|
||||
encodeKey(1, WireType.Varint, out);
|
||||
encodeVarint(150, out);
|
||||
// field 2, string = "testing"
|
||||
encodeKey(2, WireType.LengthDelimited, out);
|
||||
const str = new TextEncoder().encode('testing');
|
||||
encodeVarint(str.length, out);
|
||||
out.push(...str);
|
||||
return new Uint8Array(out);
|
||||
}
|
||||
|
||||
it('decodes empty data returns null', () => {
|
||||
expect(WireMessage.decode(new Uint8Array(0))).toBeNull();
|
||||
});
|
||||
|
||||
it('decodes varint field', () => {
|
||||
const msg = WireMessage.decode(buildSimpleMessage());
|
||||
expect(msg).not.toBeNull();
|
||||
expect(msg!.getUint32(1)).toBe(150);
|
||||
});
|
||||
|
||||
it('decodes string field', () => {
|
||||
const msg = WireMessage.decode(buildSimpleMessage());
|
||||
expect(msg).not.toBeNull();
|
||||
expect(msg!.getString(2)).toBe('testing');
|
||||
});
|
||||
|
||||
it('returns null for missing fields', () => {
|
||||
const msg = WireMessage.decode(buildSimpleMessage());
|
||||
expect(msg!.getUint32(99)).toBeNull();
|
||||
expect(msg!.getString(99)).toBeNull();
|
||||
});
|
||||
|
||||
it('has() works', () => {
|
||||
const msg = WireMessage.decode(buildSimpleMessage());
|
||||
expect(msg!.has(1)).toBe(true);
|
||||
expect(msg!.has(2)).toBe(true);
|
||||
expect(msg!.has(3)).toBe(false);
|
||||
});
|
||||
|
||||
it('decodes nested message', () => {
|
||||
const inner: number[] = [];
|
||||
encodeKey(1, WireType.Varint, inner);
|
||||
encodeVarint(42, inner);
|
||||
|
||||
const outer: number[] = [];
|
||||
encodeKey(3, WireType.LengthDelimited, outer);
|
||||
encodeVarint(inner.length, outer);
|
||||
outer.push(...inner);
|
||||
|
||||
const msg = WireMessage.decode(new Uint8Array(outer));
|
||||
const nested = msg!.getMessage(3);
|
||||
expect(nested).not.toBeNull();
|
||||
expect(nested!.getUint32(1)).toBe(42);
|
||||
});
|
||||
|
||||
it('handles repeated fields', () => {
|
||||
const out: number[] = [];
|
||||
for (const v of [10, 20, 30]) {
|
||||
encodeKey(1, WireType.Varint, out);
|
||||
encodeVarint(v, out);
|
||||
}
|
||||
const msg = WireMessage.decode(new Uint8Array(out));
|
||||
const vals = msg!.getRepeatedVarint(1);
|
||||
expect(vals.map(Number)).toEqual([10, 20, 30]);
|
||||
});
|
||||
|
||||
it('field helpers work correctly', () => {
|
||||
const out: number[] = [];
|
||||
encodeKey(1, WireType.Varint, out);
|
||||
encodeVarint(1, out); // bool true
|
||||
encodeKey(2, WireType.Varint, out);
|
||||
encodeVarint(0xFFFFFFFF, out); // uint32 max
|
||||
|
||||
const msg = WireMessage.decode(new Uint8Array(out))!;
|
||||
const f1 = msg.field(1)!;
|
||||
const f2 = msg.field(2)!;
|
||||
|
||||
expect(fieldAsBool(f1)).toBe(true);
|
||||
expect(fieldAsUint32(f2)).toBe(0xFFFFFFFF);
|
||||
});
|
||||
});
|
||||
@@ -268,8 +268,6 @@ export function selectUsedRegistry(
|
||||
): UsedRegistryResult {
|
||||
const roots = new Set<string>();
|
||||
const resolved: ResolvedCallSiteRecord[] = [];
|
||||
const resolveImportedTypeName = createImportedTypeNameResolver(sourceFile);
|
||||
|
||||
for (const cs of callSites) {
|
||||
const typeSf = resolveSourceFileForTypeNode(cs.firstTypeArg, sourceFile);
|
||||
const typeName = typeNodeToMangledName(cs.firstTypeArg, typeSf, createImportedTypeNameResolver(typeSf));
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { analyzeSource } from '../../src/ast/analyzer';
|
||||
import { generateCode } from '../../src/codegen/generator';
|
||||
import { loadFixture, execAndGet } from '../helpers';
|
||||
import { loadFixture } from '../helpers';
|
||||
|
||||
/** Analyze fixture → generate → eval → return encode/decode pair */
|
||||
function makeRoundTrip(fixtureName: string, msgName: string) {
|
||||
|
||||
@@ -15,7 +15,6 @@ import type {
|
||||
JsonObject,
|
||||
JsonValue,
|
||||
OutgoingMessage,
|
||||
PrivateForwardMessageParams,
|
||||
RequestOptions,
|
||||
SendMsgParams,
|
||||
SetGroupReactionParams,
|
||||
|
||||
@@ -7,7 +7,6 @@ import type {
|
||||
JsonObject,
|
||||
LocationSegment,
|
||||
MessageChainLike,
|
||||
MessageSegment,
|
||||
MusicSegment,
|
||||
OutgoingMessage,
|
||||
RecordSegment,
|
||||
|
||||
@@ -102,7 +102,6 @@ function createStubAddon(reason: string): NativeAddon {
|
||||
return fail();
|
||||
}
|
||||
}
|
||||
// eslint-disable-next-line no-console
|
||||
console.warn(
|
||||
`[snowluma/websocket] WARNING: using stub addon (${reason}). WebSocket features are disabled.`,
|
||||
);
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
import js from '@eslint/js'
|
||||
import globals from 'globals'
|
||||
import reactHooks from 'eslint-plugin-react-hooks'
|
||||
import reactRefresh from 'eslint-plugin-react-refresh'
|
||||
import tseslint from 'typescript-eslint'
|
||||
import { defineConfig, globalIgnores } from 'eslint/config'
|
||||
|
||||
export default defineConfig([
|
||||
globalIgnores(['dist']),
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [
|
||||
js.configs.recommended,
|
||||
tseslint.configs.recommended,
|
||||
reactHooks.configs.flat.recommended,
|
||||
reactRefresh.configs.vite,
|
||||
],
|
||||
languageOptions: {
|
||||
ecmaVersion: 2020,
|
||||
globals: globals.browser,
|
||||
},
|
||||
},
|
||||
])
|
||||
@@ -0,0 +1,32 @@
|
||||
import js from '@eslint/js';
|
||||
import globals from 'globals';
|
||||
import reactHooks from 'eslint-plugin-react-hooks';
|
||||
import reactRefresh from 'eslint-plugin-react-refresh';
|
||||
import tseslint from 'typescript-eslint';
|
||||
import { defineConfig, globalIgnores } from 'eslint/config';
|
||||
|
||||
const tsconfigRootDir = decodeURIComponent(new URL('.', import.meta.url).pathname).replace(/^\/(.:\/)/, '$1');
|
||||
|
||||
export default defineConfig([
|
||||
globalIgnores(['dist']),
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [
|
||||
js.configs.recommended,
|
||||
tseslint.configs.recommended,
|
||||
reactHooks.configs.flat.recommended,
|
||||
reactRefresh.configs.vite,
|
||||
],
|
||||
languageOptions: {
|
||||
ecmaVersion: 2020,
|
||||
globals: globals.browser,
|
||||
parserOptions: {
|
||||
tsconfigRootDir,
|
||||
},
|
||||
},
|
||||
rules: {
|
||||
'react-refresh/only-export-components': 'off',
|
||||
'react-hooks/set-state-in-effect': 'off',
|
||||
},
|
||||
},
|
||||
]);
|
||||
@@ -39,6 +39,7 @@
|
||||
"eslint-plugin-react-hooks": "^7.0.1",
|
||||
"eslint-plugin-react-refresh": "^0.5.2",
|
||||
"globals": "^17.5.0",
|
||||
"jiti": "^2.6.1",
|
||||
"tailwindcss": "^4.2.2",
|
||||
"typescript": "catalog:",
|
||||
"typescript-eslint": "^8.58.2",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { Eye, Loader2, User, UserX } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
@@ -37,7 +37,7 @@ export function ProcessProbeDialog({ pid, processName, open, onOpenChange }: Pro
|
||||
const [info, setInfo] = useState<QqPortLoginInfo | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const probe = async () => {
|
||||
const probe = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
setInfo(null);
|
||||
@@ -52,7 +52,7 @@ export function ProcessProbeDialog({ pid, processName, open, onOpenChange }: Pro
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
}, [api.processes, pid]);
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
@@ -61,7 +61,7 @@ export function ProcessProbeDialog({ pid, processName, open, onOpenChange }: Pro
|
||||
setInfo(null);
|
||||
setError(null);
|
||||
}
|
||||
}, [open]);
|
||||
}, [open, probe]);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
|
||||
Generated
+24
@@ -20,12 +20,33 @@ importers:
|
||||
|
||||
.:
|
||||
devDependencies:
|
||||
'@eslint/js':
|
||||
specifier: ^10.0.1
|
||||
version: 10.0.1([email protected]([email protected]))
|
||||
cross-env:
|
||||
specifier: ^10.1.0
|
||||
version: 10.1.0
|
||||
eslint:
|
||||
specifier: ^10.2.0
|
||||
version: 10.2.0([email protected])
|
||||
eslint-plugin-react-hooks:
|
||||
specifier: ^7.0.1
|
||||
version: 7.0.1([email protected]([email protected]))
|
||||
eslint-plugin-react-refresh:
|
||||
specifier: ^0.5.2
|
||||
version: 0.5.2([email protected]([email protected]))
|
||||
globals:
|
||||
specifier: ^17.5.0
|
||||
version: 17.5.0
|
||||
jiti:
|
||||
specifier: ^2.6.1
|
||||
version: 2.6.1
|
||||
typescript:
|
||||
specifier: 'catalog:'
|
||||
version: 6.0.2
|
||||
typescript-eslint:
|
||||
specifier: ^8.58.2
|
||||
version: 8.58.2([email protected]([email protected]))([email protected])
|
||||
|
||||
packages/core:
|
||||
dependencies:
|
||||
@@ -263,6 +284,9 @@ importers:
|
||||
globals:
|
||||
specifier: ^17.5.0
|
||||
version: 17.5.0
|
||||
jiti:
|
||||
specifier: ^2.6.1
|
||||
version: 2.6.1
|
||||
tailwindcss:
|
||||
specifier: ^4.2.2
|
||||
version: 4.2.2
|
||||
|
||||
+3
-1
@@ -3,7 +3,9 @@
|
||||
"target": "ES2022",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"lib": ["ES2022"],
|
||||
"lib": [
|
||||
"ES2022"
|
||||
],
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
|
||||
Reference in new issue
Block a user