216 lines
9.5 KiB
JavaScript
216 lines
9.5 KiB
JavaScript
#!/usr/bin/env node
|
|||
|
|
"use strict";
|
||
|
|
|
||
|
|
const assert = require("node:assert/strict");
|
||
|
|
const fs = require("node:fs");
|
||
|
|
const path = require("node:path");
|
||
|
|
const { chromium } = require("playwright");
|
||
|
|
|
||
|
|
const BASE_URL = (process.env.MNOTE_WEB_SMOKE_BASE_URL || "http://127.0.0.1:3000").replace(/\/+$/, "");
|
||
|
|
const ROOT_PATH = process.env.MNOTE_WOLAI_ASSET_SMOKE_ROOT
|
||
|
|
|| "/mnt/Data1T/Mnote_data/users/liaibo/workspaces/my-space";
|
||
|
|
const DOCUMENT_RELATIVE_PATH = process.env.MNOTE_WOLAI_ASSET_SMOKE_DOCUMENT
|
||
|
|
|| "liaibo的个人空间/知识/实验资料-工具书/核磁常见杂质化学位移表(核磁溶剂峰)/核磁常见杂质化学位移表(核磁溶剂峰).md";
|
||
|
|
const USERNAME = process.env.MNOTE_WOLAI_ASSET_SMOKE_USER || "mnote.e2e@example.com";
|
||
|
|
const PASSWORD = process.env.MNOTE_WOLAI_ASSET_SMOKE_PASSWORD || "MnoteE2E123!";
|
||
|
|
const OUT_DIR = path.join(process.cwd(), "tmp", "task800-wolai-assets-page-local-smoke");
|
||
|
|
const RESULT_PATH = path.join(OUT_DIR, "result.json");
|
||
|
|
const CHROMIUM_EXECUTABLE_PATH = process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH
|
||
|
|
|| ["/usr/bin/chromium-browser", "/usr/bin/chromium", "/usr/bin/google-chrome-stable", "/snap/bin/chromium"]
|
||
|
|
.find((candidate) => fs.existsSync(candidate));
|
||
|
|
|
||
|
|
function fileUrl(localPath) {
|
||
|
|
return `file://${localPath}`;
|
||
|
|
}
|
||
|
|
|
||
|
|
function encodeLocalIdSegment(value) {
|
||
|
|
const bytes = Buffer.from(String(value || ""), "utf8");
|
||
|
|
let encoded = "";
|
||
|
|
for (const byte of bytes) {
|
||
|
|
const character = String.fromCharCode(byte);
|
||
|
|
if (
|
||
|
|
(byte >= 48 && byte <= 57)
|
||
|
|
|| (byte >= 65 && byte <= 90)
|
||
|
|
|| (byte >= 97 && byte <= 122)
|
||
|
|
|| character === "."
|
||
|
|
|| character === "_"
|
||
|
|
|| character === "-"
|
||
|
|
) {
|
||
|
|
encoded += character;
|
||
|
|
} else {
|
||
|
|
encoded += `~${byte.toString(16).toUpperCase().padStart(2, "0")}`;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
return encoded;
|
||
|
|
}
|
||
|
|
|
||
|
|
function documentUrl() {
|
||
|
|
const url = new URL(`${BASE_URL}/documents/${encodeURIComponent(`local-md:${encodeLocalIdSegment(DOCUMENT_RELATIVE_PATH)}`)}`);
|
||
|
|
url.searchParams.set("sourceKind", "local_folder");
|
||
|
|
url.searchParams.set("rootUri", fileUrl(ROOT_PATH));
|
||
|
|
url.searchParams.set("treeView", "filetree");
|
||
|
|
return url.toString();
|
||
|
|
}
|
||
|
|
|
||
|
|
function firstMarkdownImageHref(markdown) {
|
||
|
|
const match = String(markdown || "").match(/!\[[^\]]*\]\(<([^>]+)>\)|!\[[^\]]*\]\(([^)\s]+)\)/);
|
||
|
|
return match ? String(match[1] || match[2] || "").trim() : "";
|
||
|
|
}
|
||
|
|
|
||
|
|
function firstMarkdownPdfHref(markdown) {
|
||
|
|
const match = String(markdown || "").match(/\[[^\]]*\.pdf[^\]]*\]\(<([^>]+\.pdf)>[^)]*\)|\[[^\]]*\.pdf[^\]]*\]\(([^)\s]+\.pdf)(?:\s+["'][^"']+["'])?\)/i);
|
||
|
|
return match ? String(match[1] || match[2] || "").trim() : "";
|
||
|
|
}
|
||
|
|
|
||
|
|
function assetOpenUrl(assetRelativePath) {
|
||
|
|
const url = new URL(`${BASE_URL}/api/local-folder/files/open`);
|
||
|
|
url.searchParams.set("rootUri", fileUrl(ROOT_PATH));
|
||
|
|
url.searchParams.set("path", assetRelativePath);
|
||
|
|
return url.toString();
|
||
|
|
}
|
||
|
|
|
||
|
|
async function signIn(request) {
|
||
|
|
const response = await request.post(`${BASE_URL}/api/auth`, {
|
||
|
|
headers: { "content-type": "application/json", accept: "application/json" },
|
||
|
|
data: {
|
||
|
|
action: "auth:signIn",
|
||
|
|
args: {
|
||
|
|
provider: "password",
|
||
|
|
params: {
|
||
|
|
account: USERNAME,
|
||
|
|
password: PASSWORD,
|
||
|
|
flow: "signIn",
|
||
|
|
},
|
||
|
|
},
|
||
|
|
},
|
||
|
|
});
|
||
|
|
assert.equal(response.status(), 200, `登录失败: ${response.status()} ${await response.text()}`);
|
||
|
|
const whoami = await (await request.get(`${BASE_URL}/api/auth/whoami`, {
|
||
|
|
headers: { accept: "application/json" },
|
||
|
|
})).json();
|
||
|
|
assert.ok(
|
||
|
|
[whoami.userId, whoami.email, whoami.username].includes(USERNAME),
|
||
|
|
`登录用户不匹配: ${JSON.stringify(whoami)}`,
|
||
|
|
);
|
||
|
|
return whoami;
|
||
|
|
}
|
||
|
|
|
||
|
|
async function main() {
|
||
|
|
fs.mkdirSync(OUT_DIR, { recursive: true });
|
||
|
|
const markdownPath = path.join(ROOT_PATH, DOCUMENT_RELATIVE_PATH);
|
||
|
|
const markdown = fs.readFileSync(markdownPath, "utf8");
|
||
|
|
const firstHref = firstMarkdownImageHref(markdown);
|
||
|
|
assert.ok(firstHref, `目标页面缺少 Markdown 图片: ${markdownPath}`);
|
||
|
|
const assetRelativePath = path.posix.normalize(path.posix.join(
|
||
|
|
path.posix.dirname(DOCUMENT_RELATIVE_PATH),
|
||
|
|
firstHref,
|
||
|
|
));
|
||
|
|
const pdfHref = firstMarkdownPdfHref(markdown);
|
||
|
|
assert.ok(pdfHref, `目标页面缺少 PDF 附件链接: ${markdownPath}`);
|
||
|
|
const pdfAssetRelativePath = path.posix.normalize(path.posix.join(
|
||
|
|
path.posix.dirname(DOCUMENT_RELATIVE_PATH),
|
||
|
|
pdfHref,
|
||
|
|
));
|
||
|
|
|
||
|
|
const browser = await chromium.launch({
|
||
|
|
headless: process.env.HEADFUL !== "1",
|
||
|
|
...(CHROMIUM_EXECUTABLE_PATH ? { executablePath: CHROMIUM_EXECUTABLE_PATH } : {}),
|
||
|
|
});
|
||
|
|
const context = await browser.newContext({
|
||
|
|
viewport: { width: 1440, height: 960 },
|
||
|
|
locale: "zh-CN",
|
||
|
|
});
|
||
|
|
const page = await context.newPage();
|
||
|
|
page.setDefaultTimeout(Number(process.env.MNOTE_SMOKE_UI_TIMEOUT_MS || 45_000));
|
||
|
|
|
||
|
|
try {
|
||
|
|
const whoami = await signIn(context.request);
|
||
|
|
const assetResponse = await context.request.get(assetOpenUrl(assetRelativePath));
|
||
|
|
assert.equal(assetResponse.status(), 200, `图片资源打开失败: ${assetResponse.status()} ${await assetResponse.text().catch(() => "")}`);
|
||
|
|
const contentType = assetResponse.headers()["content-type"] || "";
|
||
|
|
assert.match(contentType, /^image\//);
|
||
|
|
const imageBytes = (await assetResponse.body()).length;
|
||
|
|
assert.ok(imageBytes > 0, "图片资源为空");
|
||
|
|
const pdfResponse = await context.request.get(assetOpenUrl(pdfAssetRelativePath));
|
||
|
|
assert.equal(pdfResponse.status(), 200, `PDF 附件资源打开失败: ${pdfResponse.status()} ${await pdfResponse.text().catch(() => "")}`);
|
||
|
|
const pdfContentType = pdfResponse.headers()["content-type"] || "";
|
||
|
|
assert.match(pdfContentType, /application\/pdf|application\/octet-stream/i);
|
||
|
|
const pdfBytes = (await pdfResponse.body()).length;
|
||
|
|
assert.ok(pdfBytes > 0, "PDF 附件资源为空");
|
||
|
|
|
||
|
|
const treeUrl = new URL(`${BASE_URL}/api/tree/projections/file/children`);
|
||
|
|
treeUrl.searchParams.set("sourceKind", "local_folder");
|
||
|
|
treeUrl.searchParams.set("rootUri", fileUrl(ROOT_PATH));
|
||
|
|
treeUrl.searchParams.set("parentRelativePath", path.posix.dirname(DOCUMENT_RELATIVE_PATH));
|
||
|
|
const treeResponse = await context.request.get(treeUrl.toString(), {
|
||
|
|
headers: { accept: "application/json" },
|
||
|
|
});
|
||
|
|
assert.equal(treeResponse.status(), 200, `FileTree 读取失败: ${treeResponse.status()} ${await treeResponse.text()}`);
|
||
|
|
const treeJson = await treeResponse.json();
|
||
|
|
const fileTreeTitles = (treeJson.result?.items || []).map((item) => item.title);
|
||
|
|
assert.ok(!fileTreeTitles.includes(".assets"), `.assets 泄露到 FileTree: ${fileTreeTitles.join(", ")}`);
|
||
|
|
|
||
|
|
await page.goto(documentUrl(), { waitUntil: "domcontentloaded" });
|
||
|
|
await page.locator('[data-testid="mnote-leptos-tiptap-island-editor-root"]').first().waitFor({ state: "visible" });
|
||
|
|
await page.locator('.document-pane[data-pane-role="primary"] .editor-surface .ProseMirror').first().waitFor({ state: "visible" });
|
||
|
|
await page.waitForFunction(() => Array.from(document.querySelectorAll(".editor-surface img"))
|
||
|
|
.some((img) => img.complete && img.naturalWidth > 0 && img.naturalHeight > 0));
|
||
|
|
const imageState = await page.evaluate(() => Array.from(document.querySelectorAll(".editor-surface img")).slice(0, 5).map((img) => ({
|
||
|
|
src: img.getAttribute("src"),
|
||
|
|
naturalWidth: img.naturalWidth,
|
||
|
|
naturalHeight: img.naturalHeight,
|
||
|
|
complete: img.complete,
|
||
|
|
})));
|
||
|
|
assert.ok(imageState[0]?.naturalWidth > 0 && imageState[0]?.naturalHeight > 0, JSON.stringify(imageState[0] || null));
|
||
|
|
const pdfLink = page.locator('.document-pane[data-pane-role="primary"] .editor-surface .ProseMirror a.mnote-uploaded-attachment-row.mnote-uploaded-attachment-pdf').first();
|
||
|
|
await pdfLink.waitFor({ state: "visible" });
|
||
|
|
const pdfLinkState = await pdfLink.evaluate((link) => {
|
||
|
|
const beforeStyle = getComputedStyle(link, "::before");
|
||
|
|
const afterStyle = getComputedStyle(link, "::after");
|
||
|
|
return {
|
||
|
|
text: link.textContent || "",
|
||
|
|
href: link.getAttribute("href") || "",
|
||
|
|
className: link.className || "",
|
||
|
|
fileSize: link.getAttribute("data-file-size") || "",
|
||
|
|
iconBackground: beforeStyle.backgroundColor,
|
||
|
|
sizeContent: afterStyle.content || "",
|
||
|
|
};
|
||
|
|
});
|
||
|
|
assert.match(pdfLinkState.text, /核磁常见杂质化学位移表\.pdf/);
|
||
|
|
assert.ok(pdfLinkState.className.includes("mnote-uploaded-attachment-pdf"), JSON.stringify(pdfLinkState));
|
||
|
|
assert.match(pdfLinkState.fileSize, /^[\d.]+ (B|KB|MB)$/);
|
||
|
|
assert.match(pdfLinkState.iconBackground, /rgb\(217, 72, 65\)|rgb\(239, 68, 68\)/, JSON.stringify(pdfLinkState));
|
||
|
|
assert.ok(pdfLinkState.sizeContent.includes(pdfLinkState.fileSize), JSON.stringify(pdfLinkState));
|
||
|
|
const pdfOpenUrl = new URL(pdfLinkState.href);
|
||
|
|
assert.equal(pdfOpenUrl.pathname, "/api/local-folder/files/open");
|
||
|
|
assert.equal(pdfOpenUrl.searchParams.get("path"), pdfAssetRelativePath);
|
||
|
|
|
||
|
|
const screenshotPath = path.join(OUT_DIR, "first-chapter-image.png");
|
||
|
|
await page.screenshot({ path: screenshotPath, fullPage: false });
|
||
|
|
const result = {
|
||
|
|
ok: true,
|
||
|
|
whoami,
|
||
|
|
documentRelativePath: DOCUMENT_RELATIVE_PATH,
|
||
|
|
assetRelativePath,
|
||
|
|
pdfAssetRelativePath,
|
||
|
|
contentType,
|
||
|
|
imageBytes,
|
||
|
|
pdfContentType,
|
||
|
|
pdfBytes,
|
||
|
|
fileTreeTitles,
|
||
|
|
imageState,
|
||
|
|
pdfLinkState,
|
||
|
|
screenshotPath,
|
||
|
|
};
|
||
|
|
fs.writeFileSync(RESULT_PATH, `${JSON.stringify(result, null, 2)}\n`, "utf8");
|
||
|
|
console.log(JSON.stringify(result, null, 2));
|
||
|
|
} finally {
|
||
|
|
await browser.close();
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
main().catch((error) => {
|
||
|
|
console.error(error && error.stack ? error.stack : error);
|
||
|
|
process.exit(1);
|
||
|
|
});
|