Compare commits

..
6 Commits
Author SHA1 Message Date
手瓜一十雪 ec6aadaeea fix(shell): support QQ 9.9.36 Windows file query aliases
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
2026-10-07 00:07:42 +08:00
手瓜一十雪 463d3ea5b1 fix(test): use typed spawn options for Windows batch regression
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
2026-10-06 18:08:08 +08:00
手瓜一十雪 0d6ce7f509 fix(ci): sync typescript dependency in workspace lockfile 2026-10-06 18:07:06 +08:00
手瓜一十雪 4f1401da78 fix(types): preserve complete nested types during post-processing
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
Use the TypeScript parser instead of a regex that truncates nested generics and function types. Validate generated syntax and add a regression test. Include workspace aliases and PTY ambient declarations. The full type package build still reports six errors in third-party node-pty source; this commit does not claim to resolve that remaining issue.
2026-10-06 17:51:21 +08:00
手瓜一十雪 9109b8cfe2 fix: repair Windows release dependencies and loader paths
Bundle required crypto and SSL DLLs and gate releases on a Windows native-load smoke test. Resolve loader paths independently of the working directory and encode file URLs correctly. Include the quick-login launcher built from Windows-Boot 0ff70ce10e34ac26411f9e6bcedaedfacc1e74f0. Validated builds, five path regressions, and live Shell and Windows Node startup to QR login.
2026-10-06 17:51:21 +08:00
手瓜一十雪 297133a1b1 fix(shell): update Windows hook for native file information queries
Include the x64 Release hook built from NapCat-Windows-Boot commit 789e6cce00be40d02659e1aca992f8cd928b790a. SHA256: 7C48E7D10D77E2C3936E5D190AEB0DDEE353D55FD06DE81C714F2740112B94B1.

Related to #2091. The replacement passes 10 independent Win32 checks; the reported QQ crash remains to be verified in the reporter's environment.
2026-10-06 16:54:12 +08:00
22 changed files with 380 additions and 54 deletions

No files matched your search

@@ -0,0 +1,3 @@
cmake_minimum_required(VERSION 3.20)
project(NapCatWindowsLoaderTest LANGUAGES CXX)
add_executable(windows-loader-test probe.cpp)
+96
View File
@@ -0,0 +1,96 @@
#include <windows.h>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
using QueryByName = BOOL(WINAPI *)(PCWSTR, FILE_INFO_BY_NAME_CLASS, PVOID, ULONG);
int wmain(int argumentCount, wchar_t **arguments)
{
if (argumentCount != 3)
return 2;
const wchar_t *providers[] = {L"kernel32.dll", L"kernelbase.dll", L"api-ms-win-core-file-l2-1-4.dll"};
HMODULE providerModules[3]{};
QueryByName nativeQueries[3]{};
unsigned char nativeCode[3][12]{};
unsigned char nativeInfo[3][4][1024]{};
BOOL nativeResults[3][4]{};
DWORD nativeErrors[3][4]{};
for (int providerIndex = 0; providerIndex < 3; ++providerIndex)
{
providerModules[providerIndex] = LoadLibraryW(providers[providerIndex]);
auto query = reinterpret_cast<QueryByName>(GetProcAddress(providerModules[providerIndex], "GetFileInformationByName"));
if (!query)
return 3;
nativeQueries[providerIndex] = query;
std::memcpy(nativeCode[providerIndex], reinterpret_cast<void *>(query), sizeof(nativeCode[providerIndex]));
for (int infoClass = 0; infoClass < 4; ++infoClass)
{
SetLastError(ERROR_SUCCESS);
nativeResults[providerIndex][infoClass] = query(arguments[2], static_cast<FILE_INFO_BY_NAME_CLASS>(infoClass), nativeInfo[providerIndex][infoClass], sizeof(nativeInfo[providerIndex][infoClass]));
nativeErrors[providerIndex][infoClass] = GetLastError();
}
}
FILE_STAT_BASIC_INFORMATION expected{};
if (!nativeQueries[0](arguments[2], FileStatBasicByNameInfo, &expected, sizeof(expected)))
return 4;
if (_wputenv_s(L"NAPCAT_LOAD_PATH", arguments[2]) || _wputenv_s(L"NAPCAT_PATCH_PACKAGE", arguments[2]))
return 5;
if (!LoadLibraryW(arguments[1]))
{
std::printf("LoadLibrary failed: %lu\n", GetLastError());
return 6;
}
const std::wstring missingRoot = L"C:\\napcat-loader-test-" + std::to_wstring(GetCurrentProcessId());
const std::wstring loaderPath = missingRoot + L"\\loadNapCat.js";
const std::wstring packagePath = missingRoot + L"\\resources\\app\\package.json";
const std::wstring unrelatedPath = missingRoot + L"\\unrelated.txt";
const wchar_t *redirectedPaths[] = {loaderPath.c_str(), packagePath.c_str()};
int failures = 0;
for (int providerIndex = 0; providerIndex < 3; ++providerIndex)
{
auto query = reinterpret_cast<QueryByName>(GetProcAddress(providerModules[providerIndex], "GetFileInformationByName"));
bool preserved = std::memcmp(nativeCode[providerIndex], reinterpret_cast<void *>(nativeQueries[providerIndex]), sizeof(nativeCode[providerIndex])) == 0;
std::wprintf(L"%ls native code preserved: %ls\n", providers[providerIndex], preserved ? L"PASS" : L"FAIL");
failures += !preserved;
for (int infoClass = 0; infoClass < 4; ++infoClass)
{
unsigned char actual[1024]{};
SetLastError(ERROR_SUCCESS);
BOOL result = query(arguments[2], static_cast<FILE_INFO_BY_NAME_CLASS>(infoClass), actual, sizeof(actual));
DWORD error = GetLastError();
bool passed = result == nativeResults[providerIndex][infoClass] &&
(result ? std::memcmp(actual, nativeInfo[providerIndex][infoClass], sizeof(actual)) == 0 : error == nativeErrors[providerIndex][infoClass]);
std::wprintf(L"%ls information class %d native parity: %ls\n", providers[providerIndex], infoClass, passed ? L"PASS" : L"FAIL");
failures += !passed;
}
for (const auto *redirectedPath : redirectedPaths)
{
FILE_STAT_BASIC_INFORMATION actual{};
BOOL result = query(redirectedPath, FileStatBasicByNameInfo, &actual, sizeof(actual));
bool passed = result && actual.EndOfFile.QuadPart == expected.EndOfFile.QuadPart &&
actual.FileId.QuadPart == expected.FileId.QuadPart && actual.FileAttributes == expected.FileAttributes;
std::wprintf(L"%ls redirect %ls: %ls\n", providers[providerIndex], redirectedPath, passed ? L"PASS" : L"FAIL");
failures += !passed;
}
FILE_STAT_BASIC_INFORMATION missing{};
SetLastError(ERROR_SUCCESS);
BOOL nativeResult = nativeQueries[providerIndex](unrelatedPath.c_str(), FileStatBasicByNameInfo, &missing, sizeof(missing));
DWORD nativeError = GetLastError();
SetLastError(ERROR_SUCCESS);
BOOL result = query(unrelatedPath.c_str(), FileStatBasicByNameInfo, &missing, sizeof(missing));
bool passed = !result && result == nativeResult && GetLastError() == nativeError;
std::wprintf(L"%ls unrelated missing file: %ls\n", providers[providerIndex], passed ? L"PASS" : L"FAIL");
failures += !passed;
}
FILE_STAT_BASIC_INFORMATION direct{};
BOOL result = GetFileInformationByName(loaderPath.c_str(), FileStatBasicByNameInfo, &direct, sizeof(direct));
bool passed = result && direct.FileId.QuadPart == expected.FileId.QuadPart && direct.EndOfFile.QuadPart == expected.EndOfFile.QuadPart;
std::printf("static import redirection: %s\n", passed ? "PASS" : "FAIL");
failures += !passed;
return failures ? 1 : 0;
}
+20
View File
@@ -9,6 +9,26 @@ on:
permissions: write-all
jobs:
windows-loader-test:
name: Windows Loader Test
needs: build
runs-on: windows-latest
steps:
- uses: actions/checkout@v5
- uses: actions/download-artifact@v7
with:
name: NapCat.Shell
path: shell-dist
- name: Verify Windows loader file queries
shell: pwsh
run: |
cmake -S .github/tests/windows-loader -B "$env:RUNNER_TEMP/windows-loader-test" -A x64
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
cmake --build "$env:RUNNER_TEMP/windows-loader-test" --config Release
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
& "$env:RUNNER_TEMP/windows-loader-test/Release/windows-loader-test.exe" "$pwd/shell-dist/NapCatWinBootHook.dll" "$pwd/shell-dist/loadNapCat.js"
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
typecheck-and-test:
name: Type Check & Test
runs-on: ubuntu-latest
+40 -3
View File
@@ -47,6 +47,7 @@ jobs:
- name: Build NapCat.${{ matrix.target.name }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NAPCAT_VERSION: ${{ inputs.version }}
run: |
pnpm i
pnpm --filter napcat-webui-frontend run build || exit 1
@@ -153,9 +154,14 @@ jobs:
# -----------------------------
# 5) 拷贝 QQ 文件到 NapCat.Shell.Windows.Node
# -----------------------------
QQ_TARGETS=("avif_convert.dll" "broadcast_ipc.dll" "config.json" "libglib-2.0-0.dll" "libgobject-2.0-0.dll" "libvips-42.dll" "ncnn.dll" "opencv.dll" "package.json" "QBar.dll" "wrapper.node" "LightQuic.dll")
QQ_TARGETS=("avif_convert.dll" "broadcast_ipc.dll" "config.json" "crypto.dll" "ssl.dll" "libglib-2.0-0.dll" "libgobject-2.0-0.dll" "libvips-42.dll" "ncnn.dll" "opencv.dll" "package.json" "QBar.dll" "wrapper.node" "LightQuic.dll")
for name in "${QQ_TARGETS[@]}"; do
find "$QQ_EXTRACT" -iname "$name" -exec cp -a {} "$OUT_DIR" \; || true
source_file=$(find "$QQ_EXTRACT" -type f -iname "$name" -print -quit)
if [ -z "$source_file" ]; then
echo "Missing required QQ file: $name" >&2
exit 1
fi
cp -a "$source_file" "$OUT_DIR/"
done
# -----------------------------
@@ -183,8 +189,39 @@ jobs:
name: NapCat.Shell.Windows.Node
path: NapCat.Shell.Windows.Node
validate-windows-node:
needs: assemble-windows-node
runs-on: windows-latest
steps:
- uses: actions/checkout@v5
with:
ref: ${{ inputs.version }}
- uses: actions/download-artifact@v7
with:
name: NapCat.Shell.Windows.Node
path: windows-node
- name: Verify bundled Node and QQ native dependencies
shell: pwsh
working-directory: windows-node
run: |
& .\node.exe --check .\index.js
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
& .\node.exe -e "const wrapper = require('./wrapper.node'); if (!wrapper.NodeQQNTWrapperUtil) throw new Error('Missing NodeQQNTWrapperUtil'); console.log('wrapper.node native-load PASS'); process.exit(0);"
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
- name: Verify Windows loader file queries
shell: pwsh
run: |
cmake -S .github/tests/windows-loader -B "$env:RUNNER_TEMP/windows-loader-test" -A x64
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
cmake --build "$env:RUNNER_TEMP/windows-loader-test" --config Release
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
& "$env:RUNNER_TEMP/windows-loader-test/Release/windows-loader-test.exe" "$pwd/windows-node/napcat/NapCatWinBootHook.dll" "$pwd/windows-node/napcat/loadNapCat.js"
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
release-napcat:
needs: [build, assemble-windows-node]
needs: [build, assemble-windows-node, validate-windows-node]
runs-on: ubuntu-latest
steps:
- name: Checkout
+5 -1
View File
@@ -1 +1,5 @@
node.exe ./index.js
@echo off
setlocal
cd /d "%~dp0" || exit /b 1
"%~dp0node.exe" "%~dp0index.js" %*
exit /b %errorlevel%
+2 -1
View File
@@ -1,6 +1,7 @@
const process = require('process');
const os = require('os');
const path = require('path');
const { pathToFileURL } = require('url');
// 保存原始dlopen
const dlopenOrig = process.dlopen;
@@ -50,7 +51,7 @@ async function initializeNapCat () {
console.log('[NapCat] [Info] 开始初始化NapCat');
try {
const currentPath = path.dirname(__filename);
const { NCoreInitFramework, getWebUiUrl } = await import('file://' + path.join(currentPath, './napcat.mjs'));
const { NCoreInitFramework, getWebUiUrl } = await import(pathToFileURL(path.join(currentPath, './napcat.mjs')).href);
getWebUiUrlFunc = getWebUiUrl;
await NCoreInitFramework(wrapperSession, wrapperLoginService, (callback) => { ncCallback = callback; });
} catch (error) {
+2 -1
View File
@@ -1,5 +1,6 @@
// const fs = require('fs');
const path = require('path');
const { pathToFileURL } = require('url');
async function initializeNapCat (session, loginService, registerCallback) {
// const logFile = path.join(currentPath, 'napcat.log');
@@ -12,7 +13,7 @@ async function initializeNapCat (session, loginService, registerCallback) {
try {
const currentPath = path.dirname(__filename);
const { NCoreInitFramework } = await import('file://' + path.join(currentPath, './napcat.mjs'));
const { NCoreInitFramework } = await import(pathToFileURL(path.join(currentPath, './napcat.mjs')).href);
await NCoreInitFramework(session, loginService, (callback) => { registerCallback(callback); });
} catch (error) {
console.log('[NapCat] [Error] 初始化NapCat', error);
@@ -1,8 +1,10 @@
@echo off
setlocal DisableDelayedExpansion
cd /d "%~dp0" || exit /b 1
chcp 65001
set NAPCAT_INJECT_PATH=%cd%\napiloader.dll
set NAPCAT_LAUNCHER_PATH=%cd%\napimain.exe
set NAPCAT_MAIN_PATH=%cd%\nativeLoader.cjs
set "NAPCAT_INJECT_PATH=%cd%\napiloader.dll"
set "NAPCAT_LAUNCHER_PATH=%cd%\napimain.exe"
set "NAPCAT_MAIN_PATH=%cd%\nativeLoader.cjs"
set NAPCAT_DEBUG_CONSOLE=1
:loop_read
for /f "tokens=2*" %%a in ('reg query "HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\QQ" /v "UninstallString"') do (
@@ -27,4 +29,4 @@ set NAPCAT_MAIN_PATH=%NAPCAT_MAIN_PATH:\=/%
"%NAPCAT_LAUNCHER_PATH%" "%QQPath%" "%NAPCAT_INJECT_PATH%" "%NAPCAT_MAIN_PATH%"
pause
pause
+6 -4
View File
@@ -1,8 +1,10 @@
@echo off
setlocal DisableDelayedExpansion
cd /d "%~dp0" || exit /b 1
chcp 65001
set NAPCAT_INJECT_PATH=%cd%\napiloader.dll
set NAPCAT_LAUNCHER_PATH=%cd%\napimain.exe
set NAPCAT_MAIN_PATH=%cd%\nativeLoader.cjs
set "NAPCAT_INJECT_PATH=%cd%\napiloader.dll"
set "NAPCAT_LAUNCHER_PATH=%cd%\napimain.exe"
set "NAPCAT_MAIN_PATH=%cd%\nativeLoader.cjs"
:loop_read
for /f "tokens=2*" %%a in ('reg query "HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\QQ" /v "UninstallString"') do (
set "RetString=%%~b"
@@ -24,4 +26,4 @@ if not exist "%QQpath%" (
set NAPCAT_MAIN_PATH=%NAPCAT_MAIN_PATH:\=/%
start "" "%NAPCAT_LAUNCHER_PATH%" "%QQPath%" "%NAPCAT_INJECT_PATH%" "%NAPCAT_MAIN_PATH%"
start "" "%NAPCAT_LAUNCHER_PATH%" "%QQPath%" "%NAPCAT_INJECT_PATH%" "%NAPCAT_MAIN_PATH%"
Binary file not shown.
Binary file not shown.
@@ -1,10 +1,12 @@
@echo off
setlocal DisableDelayedExpansion
cd /d "%~dp0" || exit /b 1
chcp 65001 >nul
set NAPCAT_PATCH_PACKAGE=%cd%\qqnt.json
set NAPCAT_LOAD_PATH=%cd%\loadNapCat.js
set NAPCAT_INJECT_PATH=%cd%\NapCatWinBootHook.dll
set NAPCAT_LAUNCHER_PATH=%cd%\NapCatWinBootMain.exe
set NAPCAT_MAIN_PATH=%cd%\napcat.mjs
set "NAPCAT_PATCH_PACKAGE=%cd%\qqnt.json"
set "NAPCAT_LOAD_PATH=%cd%\loadNapCat.js"
set "NAPCAT_INJECT_PATH=%cd%\NapCatWinBootHook.dll"
set "NAPCAT_LAUNCHER_PATH=%cd%\NapCatWinBootMain.exe"
set "NAPCAT_MAIN_PATH=%cd%\napcat.mjs"
:loop_read
for /f "tokens=2*" %%a in ('reg query "HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\QQ" /v "UninstallString"') do (
set "RetString=%%~b"
@@ -24,9 +26,6 @@ if not exist "%QQpath%" (
exit /b
)
set NAPCAT_MAIN_PATH=%NAPCAT_MAIN_PATH:\=/%
echo (async () =^> {await import("file:///%NAPCAT_MAIN_PATH%")})() > "%NAPCAT_LOAD_PATH%"
"%NAPCAT_LAUNCHER_PATH%" "%QQPath%" "%NAPCAT_INJECT_PATH%" %*
pause
@@ -1,10 +1,12 @@
@echo off
setlocal DisableDelayedExpansion
cd /d "%~dp0" || exit /b 1
chcp 65001 >nul
set NAPCAT_PATCH_PACKAGE=%cd%\qqnt.json
set NAPCAT_LOAD_PATH=%cd%\loadNapCat.js
set NAPCAT_INJECT_PATH=%cd%\NapCatWinBootHook.dll
set NAPCAT_LAUNCHER_PATH=%cd%\NapCatWinBootMain.exe
set NAPCAT_MAIN_PATH=%cd%\napcat.mjs
set "NAPCAT_PATCH_PACKAGE=%cd%\qqnt.json"
set "NAPCAT_LOAD_PATH=%cd%\loadNapCat.js"
set "NAPCAT_INJECT_PATH=%cd%\NapCatWinBootHook.dll"
set "NAPCAT_LAUNCHER_PATH=%cd%\NapCatWinBootMain.exe"
set "NAPCAT_MAIN_PATH=%cd%\napcat.mjs"
:loop_read
for /f "tokens=2*" %%a in ('reg query "HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\QQ" /v "UninstallString"') do (
set "RetString=%%~b"
@@ -23,9 +25,6 @@ if not exist "%QQpath%" (
pause
exit /b
)
set NAPCAT_MAIN_PATH=%NAPCAT_MAIN_PATH:\=/%
echo (async () =^> {await import("file:///%NAPCAT_MAIN_PATH%")})() > "%NAPCAT_LOAD_PATH%"
"%NAPCAT_LAUNCHER_PATH%" "%QQPath%" "%NAPCAT_INJECT_PATH%" %*
REM Optional: -q <QQ_NUMBER> for quick login, omit for QR code login
@@ -1,4 +1,6 @@
@echo off
setlocal DisableDelayedExpansion
cd /d "%~dp0" || exit /b 1
chcp 65001 >nul
net session >nul 2>&1
if %ERRORLEVEL% == 0 (
@@ -9,11 +11,11 @@ if %ERRORLEVEL% == 0 (
exit
)
set NAPCAT_PATCH_PACKAGE=%cd%\qqnt.json
set NAPCAT_LOAD_PATH=%cd%\loadNapCat.js
set NAPCAT_INJECT_PATH=%cd%\NapCatWinBootHook.dll
set NAPCAT_LAUNCHER_PATH=%cd%\NapCatWinBootMain.exe
set NAPCAT_MAIN_PATH=%cd%\napcat.mjs
set "NAPCAT_PATCH_PACKAGE=%cd%\qqnt.json"
set "NAPCAT_LOAD_PATH=%cd%\loadNapCat.js"
set "NAPCAT_INJECT_PATH=%cd%\NapCatWinBootHook.dll"
set "NAPCAT_LAUNCHER_PATH=%cd%\NapCatWinBootMain.exe"
set "NAPCAT_MAIN_PATH=%cd%\napcat.mjs"
:loop_read
for /f "tokens=2*" %%a in ('reg query "HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\QQ" /v "UninstallString"') do (
set "RetString=%%~b"
@@ -32,9 +34,6 @@ if not exist "%QQPath%" (
pause
exit /b
)
set NAPCAT_MAIN_PATH=%NAPCAT_MAIN_PATH:\=/%
echo (async () =^> {await import("file:///%NAPCAT_MAIN_PATH%")})() > "%NAPCAT_LOAD_PATH%"
"%NAPCAT_LAUNCHER_PATH%" "%QQPath%" "%NAPCAT_INJECT_PATH%" %*
REM Optional: -q <QQ_NUMBER> for quick login, omit for QR code login
+7 -8
View File
@@ -1,4 +1,6 @@
@echo off
setlocal DisableDelayedExpansion
cd /d "%~dp0" || exit /b 1
chcp 65001 >nul
net session >nul 2>&1
if %ERRORLEVEL% == 0 (
@@ -9,11 +11,11 @@ if %ERRORLEVEL% == 0 (
exit
)
set NAPCAT_PATCH_PACKAGE=%cd%\qqnt.json
set NAPCAT_LOAD_PATH=%cd%\loadNapCat.js
set NAPCAT_INJECT_PATH=%cd%\NapCatWinBootHook.dll
set NAPCAT_LAUNCHER_PATH=%cd%\NapCatWinBootMain.exe
set NAPCAT_MAIN_PATH=%cd%\napcat.mjs
set "NAPCAT_PATCH_PACKAGE=%cd%\qqnt.json"
set "NAPCAT_LOAD_PATH=%cd%\loadNapCat.js"
set "NAPCAT_INJECT_PATH=%cd%\NapCatWinBootHook.dll"
set "NAPCAT_LAUNCHER_PATH=%cd%\NapCatWinBootMain.exe"
set "NAPCAT_MAIN_PATH=%cd%\napcat.mjs"
:loop_read
for /f "tokens=2*" %%a in ('reg query "HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\QQ" /v "UninstallString"') do (
set "RetString=%%~b"
@@ -33,7 +35,4 @@ if not exist "%QQPath%" (
exit /b
)
set NAPCAT_MAIN_PATH=%NAPCAT_MAIN_PATH:\=/%
echo (async () =^> {await import("file:///%NAPCAT_MAIN_PATH%")})() > "%NAPCAT_LOAD_PATH%"
"%NAPCAT_LAUNCHER_PATH%" "%QQPath%" "%NAPCAT_INJECT_PATH%" %*
+3 -2
View File
@@ -1,5 +1,6 @@
const path = require('path');
const CurrentPath = path.dirname(__filename);
const { pathToFileURL } = require('url');
const mainPath = process.env.NAPCAT_MAIN_PATH || path.join(__dirname, 'napcat.mjs');
(async () => {
await import('file://' + path.join(CurrentPath, './napcat/napcat.mjs'));
await import(pathToFileURL(mainPath).href);
})();
+89
View File
@@ -0,0 +1,89 @@
import { afterEach, describe, expect, test } from 'vitest';
import { copyFileSync, mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
import { execFileSync, spawnSync } from 'node:child_process';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const packageRoot = fileURLToPath(new URL('../', import.meta.url));
const fixtureRoots: string[] = [];
function createFixture () {
const fixtureRoot = mkdtempSync(path.join(tmpdir(), 'napcat-loader-'));
fixtureRoots.push(fixtureRoot);
const installDir = path.join(fixtureRoot, '中文 space # percent%');
mkdirSync(installDir);
return { fixtureRoot, installDir };
}
afterEach(() => {
for (const fixtureRoot of fixtureRoots.splice(0)) {
rmSync(fixtureRoot, { recursive: true, force: true });
}
});
describe('loader paths', () => {
test('Shell loads the flat package from an unrelated working directory', () => {
const { fixtureRoot, installDir } = createFixture();
const loaderPath = path.join(installDir, 'loadNapCat.cjs');
copyFileSync(path.join(packageRoot, 'napcat-shell-loader/loadNapCat.js'), loaderPath);
writeFileSync(path.join(installDir, 'napcat.mjs'), 'console.log("SHELL_LOADED");');
const environment = { ...process.env };
delete environment['NAPCAT_MAIN_PATH'];
const output = execFileSync(process.execPath, [loaderPath], { cwd: fixtureRoot, env: environment, encoding: 'utf8' });
expect(output).toContain('SHELL_LOADED');
});
test('Shell uses the actual entry path when the loader is redirected into QQ', () => {
const { fixtureRoot, installDir } = createFixture();
const loaderPath = path.join(fixtureRoot, 'loadNapCat.cjs');
const entryPath = path.join(installDir, 'napcat.mjs');
copyFileSync(path.join(packageRoot, 'napcat-shell-loader/loadNapCat.js'), loaderPath);
writeFileSync(entryPath, 'console.log("REDIRECTED_SHELL_LOADED");');
const output = execFileSync(process.execPath, [loaderPath], {
cwd: fixtureRoot,
env: { ...process.env, NAPCAT_MAIN_PATH: entryPath },
encoding: 'utf8',
});
expect(output).toContain('REDIRECTED_SHELL_LOADED');
});
test('Framework native loader preserves URL-sensitive path characters', () => {
const { fixtureRoot, installDir } = createFixture();
const loaderPath = path.join(installDir, 'nativeLoader.cjs');
copyFileSync(path.join(packageRoot, 'napcat-framework/nativeLoader.cjs'), loaderPath);
writeFileSync(path.join(installDir, 'napcat.mjs'), 'export async function NCoreInitFramework () { console.log("FRAMEWORK_LOADED"); }');
const output = execFileSync(process.execPath, ['-e', 'require(process.argv[1]).initializeNapCat({}, {}, () => {});', loaderPath], {
cwd: fixtureRoot,
encoding: 'utf8',
});
expect(output).toContain('FRAMEWORK_LOADED');
expect(output).not.toContain('[Error]');
});
test('Framework dlopen loader preserves URL-sensitive path characters', () => {
const { fixtureRoot, installDir } = createFixture();
const loaderPath = path.join(installDir, 'napcat.cjs');
copyFileSync(path.join(packageRoot, 'napcat-framework/napcat.cjs'), loaderPath);
writeFileSync(path.join(installDir, 'napcat.mjs'), 'export async function NCoreInitFramework () { console.log("DLOPEN_FRAMEWORK_LOADED"); } export function getWebUiUrl () { return ""; }');
const script = 'process.dlopen = (module) => { module.exports = { NodeIKernelLoginService: { get: () => ({}) }, NodeIQQNTWrapperSession: { create: () => ({}) } }; }; require(process.argv[1]); process.dlopen({ exports: {} }, "wrapper.node");';
const output = execFileSync(process.execPath, ['-e', script, loaderPath], { cwd: fixtureRoot, encoding: 'utf8' });
expect(output).toContain('DLOPEN_FRAMEWORK_LOADED');
expect(output).not.toContain('[Error]');
});
test.skipIf(process.platform !== 'win32')('Node batch uses the bundled runtime, forwards arguments and returns the exit code', () => {
const { fixtureRoot, installDir } = createFixture();
copyFileSync(process.execPath, path.join(installDir, 'node.exe'));
copyFileSync(path.join(packageRoot, 'napcat-develop/napcat.bat'), path.join(installDir, 'napcat.bat'));
writeFileSync(path.join(installDir, 'index.js'), 'console.log(JSON.stringify({ cwd: process.cwd(), args: process.argv.slice(2) })); process.exitCode = 7;');
const result = spawnSync('cmd.exe', ['/d', '/s', '/c', `""${path.join(installDir, 'napcat.bat')}" -q 123456"`], {
cwd: fixtureRoot,
encoding: 'utf8',
windowsVerbatimArguments: true,
});
expect(result.error).toBeUndefined();
expect(result.status).toBe(7);
expect(JSON.parse(result.stdout)).toEqual({ cwd: installDir, args: ['-q', '123456'] });
});
});
@@ -0,0 +1,44 @@
import { afterEach, expect, test } from 'vitest';
import { copyFileSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { execFileSync } from 'node:child_process';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import ts from 'typescript';
const packageRoot = fileURLToPath(new URL('../', import.meta.url));
const fixtures: string[] = [];
afterEach(() => {
for (const fixture of fixtures.splice(0)) {
rmSync(fixture, { recursive: true, force: true });
}
});
test('type post-build replaces complete nested generic and import types', () => {
const fixture = mkdtempSync(path.join(packageRoot, 'napcat-types/post-build-test-'));
fixtures.push(fixture);
mkdirSync(path.join(fixture, 'scripts'));
mkdirSync(path.join(fixture, 'dist'));
const script = path.join(fixture, 'scripts/post-build.mjs');
copyFileSync(path.join(packageRoot, 'napcat-types/scripts/post-build.mjs'), script);
writeFileSync(path.join(fixture, 'dist/fixture.d.ts'), `
import { NapProtoDecodeStructType } from 'napcat-protobuf';
export declare class Example {
parse(): import('napcat-protobuf').NapProtoDecodeStructType<() => { nested: Map<string, Array<number>> }>;
encode(): NapProtoEncodeStructType<{ fn: () => Promise<Array<string>> }>;
validate: ValidateFunction<Map<string, Array<number>>>;
unrelated: Promise<Array<string>>;
}
export declare enum ExampleKind { First = 1 }
`);
execFileSync(process.execPath, [script], { encoding: 'utf8' });
const output = readFileSync(path.join(fixture, 'dist/fixture.ts'), 'utf8');
const parsed = ts.transpileModule(output, { reportDiagnostics: true, compilerOptions: { target: ts.ScriptTarget.Latest } });
expect(parsed.diagnostics).toHaveLength(0);
expect(output).toContain('parse(): any;');
expect(output).toContain('encode(): any;');
expect(output).toContain('validate: any;');
expect(output).toContain('unrelated: Promise<Array<string>>;');
expect(output).toContain('export enum ExampleKind');
expect(output).not.toContain("import('napcat-protobuf').any");
});
+3 -2
View File
@@ -19,6 +19,7 @@
"devDependencies": {
"napcat-core": "workspace:*",
"napcat-onebot": "workspace:*",
"tsc-alias": "^1.8.16"
"tsc-alias": "^1.8.16",
"typescript": "^5.3.0"
}
}
}
+21 -3
View File
@@ -1,6 +1,7 @@
import { readdir, readFile, writeFile, rename } from 'node:fs/promises';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import ts from 'typescript';
const __dirname = fileURLToPath(new URL('../', import.meta.url));
const distDir = join(__dirname, 'dist');
@@ -41,9 +42,21 @@ function replaceExternalTypes (content) {
let result = content;
// 替换带泛型的类型(先处理复杂的)
result = result.replace(/NapProtoDecodeStructType<[^>]+>/g, 'any');
result = result.replace(/NapProtoEncodeStructType<[^>]+>/g, 'any');
result = result.replace(/ValidateFunction<[^>]+>/g, 'any');
const sourceFile = ts.createSourceFile('declaration.d.ts', result, ts.ScriptTarget.Latest, true);
const genericTypeNames = new Set(['NapProtoDecodeStructType', 'NapProtoEncodeStructType', 'ValidateFunction']);
const replacements = [];
const visit = (node) => {
const typeName = ts.isTypeReferenceNode(node) ? node.typeName : ts.isImportTypeNode(node) ? node.qualifier : undefined;
if (typeName && genericTypeNames.has(typeName.getText(sourceFile).split('.').at(-1))) {
replacements.push({ start: node.getStart(sourceFile), end: node.getEnd() });
return;
}
ts.forEachChild(node, visit);
};
visit(sourceFile);
for (const replacement of replacements.reverse()) {
result = result.slice(0, replacement.start) + 'any' + result.slice(replacement.end);
}
// 替换 winston.Logger 等带命名空间的类型
result = result.replace(/winston\.Logger/g, 'any');
@@ -103,6 +116,11 @@ async function processFile (filePath) {
// 3. Replace "export declare enum" with "export enum"
content = content.replace(/export declare enum/g, 'export enum');
const parsed = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);
if (parsed.parseDiagnostics.length > 0) {
throw new Error(`Invalid generated declaration ${filePath}: ${parsed.parseDiagnostics.map(diagnostic => ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n')).join('\n')}`);
}
// Write back the modified content
await writeFile(filePath, content, 'utf-8');
+9 -1
View File
@@ -12,6 +12,12 @@
"napcat-core": [
"../../packages/napcat-core/index.ts"
],
"napcat-core/*": [
"../../packages/napcat-core/*"
],
"napcat-webui-backend/*": [
"../../packages/napcat-webui-backend/*"
],
"napcat-onebot": [
"../../packages/napcat-onebot/index.ts"
],
@@ -40,6 +46,8 @@
},
"include": [
"./index.ts",
"../napcat-pty/node-pty.d.ts",
"../napcat-pty/native.d.ts",
"../napcat-core/**/*.ts",
"../napcat-onebot/**/*.ts",
"../napcat-common/**/*.ts"
@@ -48,4 +56,4 @@
"node_modules",
"dist"
]
}
}
+3
View File
@@ -422,6 +422,9 @@ importers:
tsc-alias:
specifier: ^1.8.16
version: 1.8.16
typescript:
specifier: ^5.3.0
version: 5.9.3
packages/napcat-universal:
dependencies: