An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:recycle: Consolidate duplicated helpers
Jeffrey Chen5fc3bf6a4900
diff --git a/app/src/block/headingLevel.ts b/app/src/block/headingLevel.tsnew file mode 100644index 0000000000..6ae3573440--- /dev/null+++ b/app/src/block/headingLevel.ts@@ -0,0 +1,5 @@+// 从块元素的 data-subtype 取标题级别(h1=1 … h6=6),非标题或属性缺失时返回 0。+// 大纲(桌面 / 移动)与超级块尾部展开共用同一解析,避免同一属性出现多份取值逻辑。+export const getHeadingLevel = (element: Element) => {+ return parseInt(element.getAttribute("data-subtype")?.replace("h", "") || "0");+};diff --git a/app/src/block/superBlock.ts b/app/src/block/superBlock.tsindex 8b9f70f76d..8792178f11 100644--- a/app/src/block/superBlock.ts+++ b/app/src/block/superBlock.ts@@ -1,3 +1,5 @@+import {getHeadingLevel} from "./headingLevel";+export const getSuperBlockCommand = (layout: "col" | "row") => `superblock:${layout}`;export const getSuperBlockCommandLayout = (value: string): "col" | "row" | undefined => {@@ -16,8 +18,8 @@ export const getSuperBlockTailHeadings = (element: Element) => {if (child.getAttribute("data-type") !== "NodeHeading") {return;}- const level = Number(child.getAttribute("data-subtype")?.substring(1));- while (headings.length > 0 && Number(headings[headings.length - 1].getAttribute("data-subtype")?.substring(1)) >= level) {+ const level = getHeadingLevel(child);+ while (headings.length > 0 && getHeadingLevel(headings[headings.length - 1]) >= level) {headings.pop();}headings.push(child);diff --git a/app/src/layout/dock/Files.ts b/app/src/layout/dock/Files.tsindex f7fcd1bc3b..c9c715abe8 100644--- a/app/src/layout/dock/Files.ts+++ b/app/src/layout/dock/Files.ts@@ -20,6 +20,8 @@ import {} from "../../protyle/util/publishAccess";import {fetchPost, fetchSyncPost} from "../../util/fetch";import {restoreFileTreePaths} from "../../util/fileTreeRestore";+import {saveOpenFileTreePaths} from "../../util/fileTreePaths";+import {removeFileTreeItems} from "../../util/fileTreeRemove";import {openEmojiPanel} from "../../emoji";import {getFileTreeDefaultIconAttr,@@ -1571,65 +1573,12 @@ data-type="navigation-root" data-path="/" data-count="${item.subFileCount || 0}"}private onRemove(data: IWebSocketData) {- // "doc2heading" 后删除文件或挂载帮助文档前的 unmount- if (data.cmd === "closeBox" || data.cmd === "removeBox") {- setNoteBook((notebooks) => {- const targetElement = this.element.querySelector(`ul[data-url="${data.data.box}"] li[data-path="${"/"}"]`);- if (targetElement) {- targetElement.parentElement.remove();- if (data.cmd === "closeBox") {- let closeHTML = "";- notebooks.find(item => {- if (item.closed) {- closeHTML += this.genNotebook(item);- }- });- this.closeElement.lastElementChild.innerHTML = closeHTML;- const counterElement = this.closeElement.querySelector(".counter");- counterElement.textContent = (parseInt(counterElement.textContent) + 1).toString();- this.closeElement.classList.remove("fn__none");- }- }- });- if (data.cmd === "removeBox") {- const removeElement = this.closeElement.querySelector(`li[data-url="${data.data.box}"]`);- if (removeElement) {- removeElement.remove();- const counterElement = this.closeElement.querySelector(".counter");- counterElement.textContent = (parseInt(counterElement.textContent) - 1).toString();- if (counterElement.textContent === "0") {- this.closeElement.classList.add("fn__none");- }- }- }- return;- }- data.data.ids.forEach((item: string) => {- const targetElement = this.element.querySelector(`li.b3-list-item[data-node-id="${item}"]`);- if (targetElement) {- // 子节点展开则删除- if (targetElement.nextElementSibling?.tagName === "UL") {- targetElement.nextElementSibling.remove();- }- // 移除当前节点- const parentElement = targetElement.parentElement.previousElementSibling as HTMLElement;- if (targetElement.parentElement.childElementCount === 1) {- if (parentElement) {- const iconElement = parentElement.querySelector("svg");- iconElement.classList.remove("b3-list-item__arrow--open");- if (parentElement.dataset.type !== "navigation-root" || parentElement.dataset.nodeId) {- iconElement.parentElement.classList.add("fn__hidden");- }- parentElement.setAttribute("data-count", "0");- this.updateDocActionElement(parentElement);- syncFileTreeItemDefaultIcon(parentElement);- }- targetElement.parentElement.remove();- } else {- targetElement.remove();- }- }- });+ removeFileTreeItems({+ element: this.element,+ closeElement: this.closeElement,+ genNotebook: (notebook) => this.genNotebook(notebook),+ updateDocActionElement: (element) => this.updateDocActionElement(element),+ }, data);}private onMount(data: IWebSocketData) {@@ -2105,38 +2054,7 @@ data-type="navigation-root" data-path="/" data-count="${item.subFileCount || 0}"}private getOpenPaths() {- const filesPaths: IFilesPath[] = [];- this.element.querySelectorAll(".b3-list[data-url]").forEach((item: HTMLElement) => {- const notebookPaths: IFilesPath = {- notebookId: item.getAttribute("data-url"),- openPaths: []- };- item.querySelectorAll(".b3-list-item__arrow--open").forEach((openItem) => {- const liElement = hasClosestByTag(openItem, "LI");- if (liElement) {- notebookPaths.openPaths.push(liElement.getAttribute("data-path"));- }- });- if (notebookPaths.openPaths.length > 0) {- for (let i = 0; i < notebookPaths.openPaths.length; i++) {- for (let j = i + 1; j < notebookPaths.openPaths.length; j++) {- if (notebookPaths.openPaths[j].startsWith(notebookPaths.openPaths[i].replace(".sy", ""))) {- notebookPaths.openPaths.splice(i, 1);- j--;- }- }- }- notebookPaths.openPaths.forEach((openPath, index) => {- const nextPath = this.element.querySelector(`[data-url="${notebookPaths.notebookId}"] li[data-path="${openPath}"]`)?.nextElementSibling?.firstElementChild?.getAttribute("data-path");- if (nextPath) {- notebookPaths.openPaths[index] = nextPath;- }- });- filesPaths.push(notebookPaths);- }- });- window.siyuan.storage[Constants.LOCAL_FILESPATHS] = filesPaths;- setStorageVal(Constants.LOCAL_FILESPATHS, filesPaths);+ saveOpenFileTreePaths(this.element);}private genFileHTML(item: IFile) {diff --git a/app/src/layout/dock/Outline.ts b/app/src/layout/dock/Outline.tsindex 72bae64ac4..5d2bf84ec4 100644--- a/app/src/layout/dock/Outline.ts+++ b/app/src/layout/dock/Outline.ts@@ -31,6 +31,7 @@ import {isEncryptedBox} from "../../util/pathName";import type {Editor} from "../../editor";import {mathRender} from "../../protyle/render/mathRender";import {genEmptyElement} from "../../block/util";+import {getHeadingLevel} from "../../block/headingLevel";import {focusBlock, focusByWbr} from "../../protyle/util/selection";import {dragOverScroll, stopScrollAnimation} from "../../boot/globalEvent/dragover";import {getDocDisplayName} from "../../util/pathName";@@ -860,15 +861,6 @@ export class Outline extends Model {this.preFilterExpandIds = null;}- /**- * 获取标题元素的实际标题级别(H1=1, H2=2, 等等)- * @param element li元素- * @returns 标题级别(1-6)- */- private getHeadingLevel(element: HTMLElement) {- return parseInt(element.getAttribute("data-subtype")?.replace("h", "") || "0");- }-/*** 展开到指定标题级别* @param targetLevel 目标标题级别,1-6级(H1-H6),6级表示全部展开@@ -880,7 +872,7 @@ export class Outline extends Model {} else {// 展开到指定标题级别this.element.querySelectorAll("li.b3-list-item").forEach(item => {- const headingLevel = this.getHeadingLevel(item as HTMLElement);+ const headingLevel = getHeadingLevel(item);const arrowElement = item.querySelector(".b3-list-item__arrow");if (item.nextElementSibling && item.nextElementSibling.tagName === "UL" && arrowElement) {if (headingLevel > 0 && headingLevel < targetLevel) {@@ -1014,7 +1006,7 @@ export class Outline extends Model {if (this.isPreview) {return; // 预览模式下不显示右键菜单}- const currentLevel = this.getHeadingLevel(element);+ const currentLevel = getHeadingLevel(element);window.siyuan.menus.menu.element.setAttribute("data-name", Constants.MENU_OUTLINE_CONTEXT);const id = element.getAttribute("data-node-id");diff --git a/app/src/mobile/dock/MobileFiles.ts b/app/src/mobile/dock/MobileFiles.tsindex dca18d2140..201556f698 100644--- a/app/src/mobile/dock/MobileFiles.ts+++ b/app/src/mobile/dock/MobileFiles.ts@@ -1,5 +1,5 @@import {config as configApi} from "../../config/util/configApi";-import {hasClosestByClassName, hasClosestByTag, hasTopClosestByTag} from "../../protyle/util/hasClosest";+import {hasClosestByClassName, hasTopClosestByTag} from "../../protyle/util/hasClosest";import {escapeHtml, escapeHtmlTextAndAttr} from "../../util/escape";import {getTreeItemTailHTML} from "../../util/treeItemTail";import {Model} from "../../layout/Model";@@ -14,6 +14,8 @@ import {} from "../../protyle/util/publishAccess";import {fetchPost, fetchSyncPost} from "../../util/fetch";import {restoreFileTreePaths} from "../../util/fileTreeRestore";+import {saveOpenFileTreePaths} from "../../util/fileTreePaths";+import {removeFileTreeItems} from "../../util/fileTreeRemove";import {reorderSortedFileTree} from "../../util/fileTreeReorder";import {genUUID} from "../../util/genID";import {openMobileFileById} from "../editor";@@ -29,7 +31,6 @@ import {MenuItem} from "../../menus/Menu";import type {App} from "../../index";import {refreshFileTree} from "../../dialog/processSystem";import {confirmDialog} from "../../dialog/confirmDialog";-import {setStorageVal} from "../../protyle/util/compatibility";import {showMessage} from "../../dialog/message";import {dragOverScroll, stopScrollAnimation} from "../../boot/globalEvent/dragover";import {@@ -1188,65 +1189,12 @@ export class MobileFiles extends Model {}private onRemove(data: IWebSocketData) {- // "doc2heading" 后删除文件或挂载帮助文档前的 unmount- if (data.cmd === "closeBox" || data.cmd === "removeBox") {- setNoteBook((notebooks) => {- const targetElement = this.element.querySelector(`ul[data-url="${data.data.box}"] li[data-path="${"/"}"]`);- if (targetElement) {- targetElement.parentElement.remove();- if (data.cmd === "closeBox") {- let closeHTML = "";- notebooks.find(item => {- if (item.closed) {- closeHTML += this.genNotebook(item);- }- });- this.closeElement.lastElementChild.innerHTML = closeHTML;- const counterElement = this.closeElement.querySelector(".counter");- counterElement.textContent = (parseInt(counterElement.textContent) + 1).toString();- this.closeElement.classList.remove("fn__none");- }- }- });- if (data.cmd === "removeBox") {- const removeElement = this.closeElement.querySelector(`li[data-url="${data.data.box}"]`);- if (removeElement) {- removeElement.remove();- const counterElement = this.closeElement.querySelector(".counter");- counterElement.textContent = (parseInt(counterElement.textContent) - 1).toString();- if (counterElement.textContent === "0") {- this.closeElement.classList.add("fn__none");- }- }- }- return;- }- data.data.ids.forEach((item: string) => {- const targetElement = this.element.querySelector(`li.b3-list-item[data-node-id="${item}"]`);- if (targetElement) {- // 子节点展开则删除- if (targetElement.nextElementSibling?.tagName === "UL") {- targetElement.nextElementSibling.remove();- }- // 移除当前节点- const parentElement = targetElement.parentElement.previousElementSibling as HTMLElement;- if (targetElement.parentElement.childElementCount === 1) {- if (parentElement) {- const iconElement = parentElement.querySelector("svg");- iconElement.classList.remove("b3-list-item__arrow--open");- if (parentElement.dataset.type !== "navigation-root" || parentElement.dataset.nodeId) {- iconElement.parentElement.classList.add("fn__hidden");- }- parentElement.setAttribute("data-count", "0");- this.updateDocActionElement(parentElement);- syncFileTreeItemDefaultIcon(parentElement);- }- targetElement.parentElement.remove();- } else {- targetElement.remove();- }- }- });+ removeFileTreeItems({+ element: this.element,+ closeElement: this.closeElement,+ genNotebook: (notebook) => this.genNotebook(notebook),+ updateDocActionElement: (element) => this.updateDocActionElement(element),+ }, data);}public onRename(data: { path: string, title: string, box: string }) {@@ -1688,38 +1636,7 @@ export class MobileFiles extends Model {}private getOpenPaths() {- const filesPaths: IFilesPath[] = [];- this.element.querySelectorAll(".b3-list[data-url]").forEach((item: HTMLElement) => {- const notebookPaths: IFilesPath = {- notebookId: item.getAttribute("data-url"),- openPaths: []- };- item.querySelectorAll(".b3-list-item__arrow--open").forEach((openItem) => {- const liElement = hasClosestByTag(openItem, "LI");- if (liElement) {- notebookPaths.openPaths.push(liElement.getAttribute("data-path"));- }- });- if (notebookPaths.openPaths.length > 0) {- for (let i = 0; i < notebookPaths.openPaths.length; i++) {- for (let j = i + 1; j < notebookPaths.openPaths.length; j++) {- if (notebookPaths.openPaths[j].startsWith(notebookPaths.openPaths[i].replace(".sy", ""))) {- notebookPaths.openPaths.splice(i, 1);- j--;- }- }- }- notebookPaths.openPaths.forEach((openPath, index) => {- const nextPath = this.element.querySelector(`[data-url="${notebookPaths.notebookId}"] li[data-path="${openPath}"]`)?.nextElementSibling?.firstElementChild?.getAttribute("data-path");- if (nextPath) {- notebookPaths.openPaths[index] = nextPath;- }- });- filesPaths.push(notebookPaths);- }- });- window.siyuan.storage[Constants.LOCAL_FILESPATHS] = filesPaths;- setStorageVal(Constants.LOCAL_FILESPATHS, filesPaths);+ saveOpenFileTreePaths(this.element);}private genFileHTML = (item: IFile) => {diff --git a/app/src/mobile/dock/MobileOutline.ts b/app/src/mobile/dock/MobileOutline.tsindex 91ce8df0ed..33b2ace852 100644--- a/app/src/mobile/dock/MobileOutline.ts+++ b/app/src/mobile/dock/MobileOutline.ts@@ -28,6 +28,7 @@ import {syncDocTitleIAL} from "../../protyle/util/docTitleIAL";import {canBatchConvertHeadings, showHeadingBatchDialog} from "../../protyle/util/headingBatch";import {bindMousePointerTouchBridge, isMousePointerTouchEvent} from "../util/mousePointerTouchBridge";import {waitForPendingTransactions} from "../../protyle/util/transactionQueue";+import {getHeadingLevel} from "../../block/headingLevel";import {operationsMayChangeOutline,transactionsMayChangeRootHeadingNumberSetting@@ -745,15 +746,6 @@ export class MobileOutline extends Model {this.preFilterExpandIds = null;}- /**- * 获取标题元素的实际标题级别(H1=1, H2=2, 等等)- * @param element li元素- * @returns 标题级别(1-6)- */- private getHeadingLevel(element: HTMLElement) {- return parseInt(element.getAttribute("data-subtype")?.replace("h", "") || "0");- }-/*** 展开到指定标题级别* @param targetLevel 目标标题级别,1-6级(H1-H6),6级表示全部展开@@ -765,7 +757,7 @@ export class MobileOutline extends Model {} else {// 展开到指定标题级别this.element.querySelectorAll("li.b3-list-item").forEach(item => {- const headingLevel = this.getHeadingLevel(item as HTMLElement);+ const headingLevel = getHeadingLevel(item);const arrowElement = item.querySelector(".b3-list-item__arrow");if (item.nextElementSibling && item.nextElementSibling.tagName === "UL" && arrowElement) {if (headingLevel > 0 && headingLevel < targetLevel) {@@ -915,7 +907,7 @@ export class MobileOutline extends Model {if (this.isPreview) {return; // 预览模式下不显示右键菜单}- const currentLevel = this.getHeadingLevel(element);+ const currentLevel = getHeadingLevel(element);window.siyuan.menus.menu.element.setAttribute("data-name", Constants.MENU_OUTLINE_CONTEXT);const id = element.getAttribute("data-node-id");diff --git a/app/src/util/fileTreePaths.ts b/app/src/util/fileTreePaths.tsnew file mode 100644index 0000000000..35f62af6d6--- /dev/null+++ b/app/src/util/fileTreePaths.ts@@ -0,0 +1,42 @@+import {hasClosestByTag} from "../protyle/util/hasClosest";+import {setStorageVal} from "../protyle/util/compatibility";+import {Constants} from "../constants";++// 采集已展开的文档路径并写入本地存储,与 restoreFileTreePaths 使用同一个键,供桌面与移动端文件树共用。+// 与 fileTreeRestore 分开是为了让恢复逻辑保持纯函数,便于单独测试。+export const saveOpenFileTreePaths = (element: HTMLElement) => {+ const filesPaths: IFilesPath[] = [];+ element.querySelectorAll(".b3-list[data-url]").forEach((item: HTMLElement) => {+ const notebookPaths: IFilesPath = {+ notebookId: item.getAttribute("data-url"),+ openPaths: []+ };+ item.querySelectorAll(".b3-list-item__arrow--open").forEach((openItem) => {+ const liElement = hasClosestByTag(openItem, "LI");+ if (liElement) {+ notebookPaths.openPaths.push(liElement.getAttribute("data-path"));+ }+ });+ if (notebookPaths.openPaths.length > 0) {+ // 已保存的路径若指向另一个已展开节点的子孙,只保留祖先,避免恢复时重复展开。+ for (let i = 0; i < notebookPaths.openPaths.length; i++) {+ for (let j = i + 1; j < notebookPaths.openPaths.length; j++) {+ if (notebookPaths.openPaths[j].startsWith(notebookPaths.openPaths[i].replace(".sy", ""))) {+ notebookPaths.openPaths.splice(i, 1);+ j--;+ }+ }+ }+ // 展开节点本身的路径不作为恢复目标,改记其后一个节点,恢复时据此重新展开该层级。+ notebookPaths.openPaths.forEach((openPath, index) => {+ const nextPath = element.querySelector(`[data-url="${notebookPaths.notebookId}"] li[data-path="${openPath}"]`)?.nextElementSibling?.firstElementChild?.getAttribute("data-path");+ if (nextPath) {+ notebookPaths.openPaths[index] = nextPath;+ }+ });+ filesPaths.push(notebookPaths);+ }+ });+ window.siyuan.storage[Constants.LOCAL_FILESPATHS] = filesPaths;+ setStorageVal(Constants.LOCAL_FILESPATHS, filesPaths);+};diff --git a/app/src/util/fileTreeRemove.ts b/app/src/util/fileTreeRemove.tsnew file mode 100644index 0000000000..0374ebca71--- /dev/null+++ b/app/src/util/fileTreeRemove.ts@@ -0,0 +1,73 @@+import {setNoteBook} from "./pathName";+import {syncFileTreeItemDefaultIcon} from "../emoji/fileTreeIcon";++// 文件树删除 / 关闭笔记本事件的 DOM 收尾。桌面与移动端共用同一段结构操作,+// 各自只需提供生成笔记本条目的回调,两者的笔记本条目外观本来就不同。+interface FileTreeRemoveDeps {+ element: HTMLElement;+ closeElement: HTMLElement;+ genNotebook: (notebook: INotebook) => string;+ updateDocActionElement: (element: HTMLElement) => void;+}++export const removeFileTreeItems = (deps: FileTreeRemoveDeps, data: IWebSocketData) => {+ // "doc2heading" 后删除文件或挂载帮助文档前的 unmount+ if (data.cmd === "closeBox" || data.cmd === "removeBox") {+ setNoteBook((notebooks) => {+ const targetElement = deps.element.querySelector(`ul[data-url="${data.data.box}"] li[data-path="${"/"}"]`);+ if (targetElement) {+ targetElement.parentElement.remove();+ if (data.cmd === "closeBox") {+ let closeHTML = "";+ notebooks.find(item => {+ if (item.closed) {+ closeHTML += deps.genNotebook(item);+ }+ });+ deps.closeElement.lastElementChild.innerHTML = closeHTML;+ const counterElement = deps.closeElement.querySelector(".counter");+ counterElement.textContent = (parseInt(counterElement.textContent) + 1).toString();+ deps.closeElement.classList.remove("fn__none");+ }+ }+ });+ if (data.cmd === "removeBox") {+ const removeElement = deps.closeElement.querySelector(`li[data-url="${data.data.box}"]`);+ if (removeElement) {+ removeElement.remove();+ const counterElement = deps.closeElement.querySelector(".counter");+ counterElement.textContent = (parseInt(counterElement.textContent) - 1).toString();+ if (counterElement.textContent === "0") {+ deps.closeElement.classList.add("fn__none");+ }+ }+ }+ return;+ }+ data.data.ids.forEach((item: string) => {+ const targetElement = deps.element.querySelector(`li.b3-list-item[data-node-id="${item}"]`);+ if (targetElement) {+ // 子节点展开则删除+ if (targetElement.nextElementSibling?.tagName === "UL") {+ targetElement.nextElementSibling.remove();+ }+ // 移除当前节点+ const parentElement = targetElement.parentElement.previousElementSibling as HTMLElement;+ if (targetElement.parentElement.childElementCount === 1) {+ if (parentElement) {+ const iconElement = parentElement.querySelector("svg");+ iconElement.classList.remove("b3-list-item__arrow--open");+ if (parentElement.dataset.type !== "navigation-root" || parentElement.dataset.nodeId) {+ iconElement.parentElement.classList.add("fn__hidden");+ }+ parentElement.setAttribute("data-count", "0");+ deps.updateDocActionElement(parentElement);+ syncFileTreeItemDefaultIcon(parentElement);+ }+ targetElement.parentElement.remove();+ } else {+ targetElement.remove();+ }+ }+ });+};diff --git a/kernel/api/archive.go b/kernel/api/archive.goindex 310b6a1b78..36807a9cf1 100644--- a/kernel/api/archive.go+++ b/kernel/api/archive.go@@ -20,7 +20,6 @@ import (archivezip "archive/zip""fmt""github.com/siyuan-note/siyuan/kernel/apicontract"- "io""io/fs""os""path/filepath"@@ -266,7 +265,7 @@ func unzipWorkspaceArchive(zipPath, destination string) error {continue}sources[i] = filepath.Join(staging, fmt.Sprint(i))- if err = extractWorkspaceArchiveEntry(entry, sources[i]); err != nil {+ if err = util.ExtractArchiveEntry(entry, sources[i]); err != nil {return err}copySources = append(copySources, sources[i])@@ -322,30 +321,3 @@ func validateArchiveEntryPath(destination, entryPath string) error {}return rejectEncryptedArchivePath(entryPath)}--func extractWorkspaceArchiveEntry(entry *archivezip.File, destination string) error {- if entry.FileInfo().IsDir() {- return os.MkdirAll(destination, 0755)- }- if err := os.MkdirAll(filepath.Dir(destination), 0755); err != nil {- return err- }- source, err := entry.Open()- if err != nil {- return err- }- defer source.Close()- target, err := os.Create(destination)- if err != nil {- return err- }- _, copyErr := io.Copy(target, source)- closeErr := target.Close()- if copyErr != nil {- return copyErr- }- if closeErr != nil {- return closeErr- }- return os.Chtimes(destination, entry.Modified, entry.Modified)-}diff --git a/kernel/api/asset.go b/kernel/api/asset.goindex ca56df122e..1e15edd69e 100644--- a/kernel/api/asset.go+++ b/kernel/api/asset.go@@ -227,7 +227,7 @@ var setFileAnnotation = contractHandler(apicontract.SetFileAnnotation, func(c *gif err != nil {return apicontract.Failure[apicontract.Null](-1, err.Error())}- boxID := model.ExtractBoxIDFromAssetsPath(writePath)+ boxID := util.BoxIDFromDataPath(writePath)if err = holdEncryptedBoxRequest(c, boxID); err != nil {return apicontract.Failure[apicontract.Null](-1, err.Error())}@@ -298,7 +298,7 @@ var getFileAnnotation = contractHandler(apicontract.GetFileAnnotation, func(c *greturn apicontract.Failure[apicontract.AssetAnnotationData](http.StatusForbidden, http.StatusText(http.StatusForbidden))}}- boxID := model.ExtractBoxIDFromAssetsPath(readPath)+ boxID := util.BoxIDFromDataPath(readPath)if err = holdEncryptedBoxRequest(c, boxID); err != nil {return apicontract.Failure[apicontract.AssetAnnotationData](-1, err.Error())}@@ -420,7 +420,7 @@ var resolveAssetPath = contractHandler(apicontract.ResolveAssetPath, func(c *ginreturn apicontract.FailureWithTimeout[string](-1, err.Error(), 3000)}if model.IsEncryptedAssetPath(p) {- if err = holdEncryptedBoxRequest(c, model.ExtractBoxIDFromAssetsPath(p)); err != nil {+ if err = holdEncryptedBoxRequest(c, util.BoxIDFromDataPath(p)); err != nil {return apicontract.FailureWithTimeout[string](-1, err.Error(), 3000)}p, err = model.PrepareEncryptedAssetForExternalOpen(path)diff --git a/kernel/api/block.go b/kernel/api/block.goindex 0ea2f27e10..01f09a14cd 100644--- a/kernel/api/block.go+++ b/kernel/api/block.go@@ -895,7 +895,7 @@ var getBlockDOMs = contractHandler(apicontract.GetBlockDOMs, func(c *gin.Contextif model.IsReadOnlyRoleContext(c) {publishAccess := model.GetPublishAccess()publishIgnore := model.GetDisablePublishAccess(publishAccess)- filterBlockDOMsByPublishAccess(c, doms, ids, boxID, publishAccess, publishIgnore)+ filterBlocksByPublishAccess(c, doms, ids, boxID, publishAccess, publishIgnore)}return apicontract.Success(doms)@@ -962,7 +962,7 @@ var getBlockDOMsWithEmbed = contractHandler(apicontract.GetBlockDOMsWithEmbed, fif isReadOnlyRole {publishIgnore := model.GetDisablePublishAccess(publishAccess)- filterBlockDOMsByPublishAccess(c, doms, ids, boxID, publishAccess, publishIgnore)+ filterBlocksByPublishAccess(c, doms, ids, boxID, publishAccess, publishIgnore)}return apicontract.Success(doms)@@ -972,19 +972,27 @@ func isEncryptedNotebookDeniedForPublish(c *gin.Context, notebook string) bool {return notebook != "" && model.IsReadOnlyRoleContext(c) && model.IsEncryptedBoxDeniedByPublishAccess(notebook)}-func filterBlockDOMsByPublishAccess(c *gin.Context, doms map[string]string, ids []string, boxID string, publishAccess model.PublishAccess, publishIgnore model.PublishAccess) {+// blockPublishDenied 判断块在当前会话下是否应被发布访问控制屏蔽。+// 块树缺失时视为不可访问,与路径密码、发布忽略规则判定一致。+func blockPublishDenied(c *gin.Context, id, boxID string, publishAccess, publishIgnore model.PublishAccess) bool {+ bt := treenode.GetBlockTreeInBox(id, boxID)+ if nil == bt {+ return true+ }+ passwordID, password := model.GetPathPasswordByPublishAccess(bt.BoxID, bt.Path, publishAccess)+ return (password != "" && !model.CheckPublishAuthCookie(c, passwordID, password)) ||+ !model.CheckPathAccessableByPublishIgnore(bt.BoxID, bt.Path, publishIgnore)+}++// filterBlocksByPublishAccess 把被发布访问控制屏蔽的块内容置空,保留原有键位。+func filterBlocksByPublishAccess(c *gin.Context, contents map[string]string, ids []string, boxID string,+ publishAccess, publishIgnore model.PublishAccess) {for _, id := range ids {- if _, ok := doms[id]; !ok {+ if _, ok := contents[id]; !ok {continue}- bt := treenode.GetBlockTreeInBox(id, boxID)- if nil == bt {- doms[id] = ""- continue- }- passwordID, password := model.GetPathPasswordByPublishAccess(bt.BoxID, bt.Path, publishAccess)- if (password != "" && !model.CheckPublishAuthCookie(c, passwordID, password)) || !model.CheckPathAccessableByPublishIgnore(bt.BoxID, bt.Path, publishIgnore) {- doms[id] = ""+ if blockPublishDenied(c, id, boxID, publishAccess, publishIgnore) {+ contents[id] = ""}}}@@ -1027,14 +1035,8 @@ var getBlockKramdown = contractHandler(apicontract.GetBlockKramdown, func(c *ginif model.IsReadOnlyRoleContext(c) {publishAccess := model.GetPublishAccess()publishIgnore := model.GetDisablePublishAccess(publishAccess)- bt := treenode.GetBlockTreeInBox(id, boxID)- if nil == bt {+ if blockPublishDenied(c, id, boxID, publishAccess, publishIgnore) {kramdown = ""- } else {- passwordID, password := model.GetPathPasswordByPublishAccess(bt.BoxID, bt.Path, publishAccess)- if (password != "" && !model.CheckPublishAuthCookie(c, passwordID, password)) || !model.CheckPathAccessableByPublishIgnore(bt.BoxID, bt.Path, publishIgnore) {- kramdown = ""- }}}@@ -1081,29 +1083,12 @@ var getBlockKramdowns = contractHandler(apicontract.GetBlockKramdowns, func(c *gif model.IsReadOnlyRoleContext(c) {publishAccess := model.GetPublishAccess()publishIgnore := model.GetDisablePublishAccess(publishAccess)- filterBlockKramdownsByPublishAccess(c, kramdowns, ids, boxID, publishAccess, publishIgnore)+ filterBlocksByPublishAccess(c, kramdowns, ids, boxID, publishAccess, publishIgnore)}return apicontract.Success(kramdowns)})-func filterBlockKramdownsByPublishAccess(c *gin.Context, kramdowns map[string]string, ids []string, boxID string, publishAccess model.PublishAccess, publishIgnore model.PublishAccess) {- for _, id := range ids {- if _, ok := kramdowns[id]; !ok {- continue- }- bt := treenode.GetBlockTreeInBox(id, boxID)- if nil == bt {- kramdowns[id] = ""- continue- }- passwordID, password := model.GetPathPasswordByPublishAccess(bt.BoxID, bt.Path, publishAccess)- if (password != "" && !model.CheckPublishAuthCookie(c, passwordID, password)) || !model.CheckPathAccessableByPublishIgnore(bt.BoxID, bt.Path, publishIgnore) {- kramdowns[id] = ""- }- }-}-var getChildBlocks = contractHandler(apicontract.GetChildBlocks, func(c *gin.Context, request apicontract.BlockQueryRequest) apicontract.Response[[]*apicontract.ChildBlock] {ret := gulu.Ret.NewResult()id := request.IDdiff --git a/kernel/api/file.go b/kernel/api/file.goindex 49d85f2eb3..05a2a8d568 100644--- a/kernel/api/file.go+++ b/kernel/api/file.go@@ -59,7 +59,7 @@ func copyDecryptedAsset(src, dest string) error {if gulu.File.IsSubPath(util.WorkspaceDir, dest) {return fmt.Errorf("refuse to write decrypted asset inside workspace")}- boxID := model.ExtractBoxIDFromAssetsPath(src)+ boxID := util.BoxIDFromDataPath(src)if boxID == "" || !model.IsEncryptedBox(boxID) {return fmt.Errorf("source is not an encrypted asset")}@@ -382,7 +382,7 @@ var copyFile = contractHandler(apicontract.CopyFile, func(c *gin.Context, requesif rejectEncryptedBoxPath(src) || rejectEncryptedBoxPath(dest) {if !rejectEncryptedBoxPath(dest) && !gulu.File.IsSubPath(util.WorkspaceDir, dest) {// dest 在工作区外且非加密 box,允许解密后复制- boxID := model.ExtractBoxIDFromAssetsPath(src)+ boxID := util.BoxIDFromDataPath(src)if err = holdEncryptedBoxRequest(c, boxID); err != nil {ret.Code = -1ret.Msg = model.Conf.Language(314)diff --git a/kernel/api/icon.go b/kernel/api/icon.goindex 4bb920a48a..4d59a16a83 100644--- a/kernel/api/icon.go+++ b/kernel/api/icon.go@@ -415,12 +415,13 @@ func generateTypeTwoSVG(color string, dateInfo map[string]any) string {`, colorScheme.Primary, dateInfo["month"], dateInfo["day"], dateInfo["year"])}-// Type 3: 显示年月-func generateTypeThreeSVG(color string, dateInfo map[string]any) string {+// calendarTextSVG 渲染动态图标 type 3、4、5 共用的日历外框、配色与装饰圆点,body 为底部文字区域。+// iconType 只用于生成 SVG 元素 id(如 type3),不参与样式计算。+func calendarTextSVG(iconType string, color string, body string) string {colorScheme := getColorScheme(color)return fmt.Sprintf(`- <svg id="dynamic_icon_type3" xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 512 512">+ <svg id="dynamic_icon_%s" xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 512 512"><path class="cls-6" d="M512,447.5c0,32-25,57-57,57H57c-32,0-57-25-57-57V120.5c0-31,25-57,57-57h398c32,0,57,26,57,57v327Z" style="fill: #ecf2f7;"/><path class="cls-1" d="M39,0h434c21.5,0,39,17.5,39,39v146H0V39C0,17.5,17.5,0,39,0Z" style="fill: %s;"/><g style="fill: %s;">@@ -431,53 +432,32 @@ func generateTypeThreeSVG(color string, dateInfo map[string]any) string {<circle cx="382.5" cy="135" r="14"/><circle cx="382.5" cy="93" r="14"/></g>- <text transform="translate(22 146.5)" style="fill: #fff;font-size: 120px; ">%d</text>- <text x="50%%" y="410.5" style="fill: #66757f;font-size: 200px;text-anchor: middle;">%s</text>+%s</svg>- `, colorScheme.Primary, colorScheme.Secondary, dateInfo["year"], dateInfo["month"])+ `, iconType, colorScheme.Primary, colorScheme.Secondary, body)+}++// Type 3: 显示年月+func generateTypeThreeSVG(color string, dateInfo map[string]any) string {+ body := fmt.Sprintf(` <text transform="translate(22 146.5)" style="fill: #fff;font-size: 120px; ">%d</text>+ <text x="50%%" y="410.5" style="fill: #66757f;font-size: 200px;text-anchor: middle;">%s</text>`,+ dateInfo["year"], dateInfo["month"])+ return calendarTextSVG("type3", color, body)}// Type 4: 仅显示年func generateTypeFourSVG(color string, dateInfo map[string]any) string {- colorScheme := getColorScheme(color)-- return fmt.Sprintf(`- <svg id="dynamic_icon_type4" xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 512 512">- <path class="cls-6" d="M512,447.5c0,32-25,57-57,57H57c-32,0-57-25-57-57V120.5c0-31,25-57,57-57h398c32,0,57,26,57,57v327Z" style="fill: #ecf2f7;"/>- <path class="cls-1" d="M39,0h434c21.5,0,39,17.5,39,39v146H0V39C0,17.5,17.5,0,39,0Z" style="fill: %s;"/>- <g style="fill: %s;">- <circle cx="468.5" cy="135" r="14"/>- <circle cx="468.5" cy="93" r="14"/>- <circle cx="425.5" cy="135" r="14"/>- <circle cx="425.5" cy="93" r="14"/>- <circle cx="382.5" cy="135" r="14"/>- <circle cx="382.5" cy="93" r="14"/>- </g>- <text x="50%%" y="410.5" style="fill: #66757f;font-size: 200px;text-anchor: middle;">%d</text>- </svg>- `, colorScheme.Primary, colorScheme.Secondary, dateInfo["year"])+ body := fmt.Sprintf(` <text x="50%%" y="410.5" style="fill: #66757f;font-size: 200px;text-anchor: middle;">%d</text>`,+ dateInfo["year"])+ return calendarTextSVG("type4", color, body)}// Type 5:: 显示周数func generateTypeFiveSVG(color string, dateInfo map[string]any) string {- colorScheme := getColorScheme(color)-- return fmt.Sprintf(`- <svg id="dynamic_icon_type5" xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 512 512">- <path class="cls-6" d="M512,447.5c0,32-25,57-57,57H57c-32,0-57-25-57-57V120.5c0-31,25-57,57-57h398c32,0,57,26,57,57v327Z" style="fill: #ecf2f7;"/>- <path class="cls-1" d="M39,0h434c21.5,0,39,17.5,39,39v146H0V39C0,17.5,17.5,0,39,0Z" style="fill: %s;"/>- <g style="fill: %s;">- <circle cx="468.5" cy="135" r="14"/>- <circle cx="468.5" cy="93" r="14"/>- <circle cx="425.5" cy="135" r="14"/>- <circle cx="425.5" cy="93" r="14"/>- <circle cx="382.5" cy="135" r="14"/>- <circle cx="382.5" cy="93" r="14"/>- </g>- <text transform="translate(22 146.5)" style="fill: #fff;font-size: 120px; ">%d</text>- <text x="50%%" y="410.5" style="fill: #66757f;font-size: 200px;text-anchor: middle;">%s</text>- </svg>- `, colorScheme.Primary, colorScheme.Secondary, dateInfo["isoYear"], dateInfo["week"])+ body := fmt.Sprintf(` <text transform="translate(22 146.5)" style="fill: #fff;font-size: 120px; ">%d</text>+ <text x="50%%" y="410.5" style="fill: #66757f;font-size: 200px;text-anchor: middle;">%s</text>`,+ dateInfo["isoYear"], dateInfo["week"])+ return calendarTextSVG("type5", color, body)}// Type 6: 仅显示星期diff --git a/kernel/api/live_photo.go b/kernel/api/live_photo.goindex 184a09a203..aa36683de2 100644--- a/kernel/api/live_photo.go+++ b/kernel/api/live_photo.go@@ -23,7 +23,7 @@ func checkLivePhotoAsset(c *gin.Context, absPath string) error {!model.CheckAbsPathAccessableByPublishAccess(c, absPath, model.GetPublishAccess())) {return errors.New("Live Photo asset access denied")}- return holdEncryptedBoxRequest(c, model.ExtractBoxIDFromAssetsPath(absPath))+ return holdEncryptedBoxRequest(c, util.BoxIDFromDataPath(absPath))}func checkLivePhotoSession(c *gin.Context, id string) error {diff --git a/kernel/apicontract/bazaar.go b/kernel/apicontract/bazaar.goindex c8ed5285f4..462686e052 100644--- a/kernel/apicontract/bazaar.go+++ b/kernel/apicontract/bazaar.go@@ -3,7 +3,6 @@ package apicontractimport ("encoding/json""errors"- "fmt""io""mime/multipart""reflect"@@ -478,19 +477,6 @@ func bazaarPayloadSchema(b *schemaBuilder, t reflect.Type, input bool) (*Schema,return &Schema{Ref: "#/$defs/" + t.Name()}, nil}-func bazaarString(fields map[string]json.RawMessage, key string, required, trim bool) (string, error) {- value, err := legacyField[string](fields, key, "String", required)- if err != nil {- return "", err- }- if trim && len(fields[key]) > 0 && string(fields[key]) != "null" {- value = strings.TrimSpace(value)- if value == "" {- return "", fmt.Errorf("Field [%s] must not be empty", key)- }- }- return value, nil-}func init() {InstallLocalBazaarPackage.decodeFailure = func(err error) Response[BazaarLocalInstallResult] {return Failure[BazaarLocalInstallResult](1, "Marketplace package file is required")@@ -500,7 +486,7 @@ func init() {if err != nil {return request, err}- if request.Frontend, err = bazaarString(fields, "frontend", true, true); err != nil {+ if request.Frontend, err = requestFieldString(fields, "frontend", true, true); err != nil {return request, err}return request, nil@@ -510,7 +496,7 @@ func init() {if err != nil {return request, err}- if request.Frontend, err = bazaarString(fields, "frontend", true, true); err != nil {+ if request.Frontend, err = requestFieldString(fields, "frontend", true, true); err != nil {return request, err}return request, nil@@ -520,16 +506,16 @@ func init() {if err != nil {return request, err}- if request.PackageType, err = bazaarString(fields, "packageType", true, true); err != nil {+ if request.PackageType, err = requestFieldString(fields, "packageType", true, true); err != nil {return request, err}- if request.PackageName, err = bazaarString(fields, "packageName", true, true); err != nil {+ if request.PackageName, err = requestFieldString(fields, "packageName", true, true); err != nil {return request, err}- if request.Frontend, err = bazaarString(fields, "frontend", true, true); err != nil {+ if request.Frontend, err = requestFieldString(fields, "frontend", true, true); err != nil {return request, err}- if request.Keyword, err = bazaarString(fields, "keyword", false, false); err != nil {+ if request.Keyword, err = requestFieldString(fields, "keyword", false, false); err != nil {return request, err}return request, nil@@ -539,10 +525,10 @@ func init() {if err != nil {return request, err}- if request.PackageType, err = bazaarString(fields, "packageType", true, true); err != nil {+ if request.PackageType, err = requestFieldString(fields, "packageType", true, true); err != nil {return request, err}- if request.PackageName, err = bazaarString(fields, "packageName", true, true); err != nil {+ if request.PackageName, err = requestFieldString(fields, "packageName", true, true); err != nil {return request, err}return request, nil@@ -552,13 +538,13 @@ func init() {if err != nil {return request, err}- if request.PackageType, err = bazaarString(fields, "packageType", true, true); err != nil {+ if request.PackageType, err = requestFieldString(fields, "packageType", true, true); err != nil {return request, err}- if request.PackageName, err = bazaarString(fields, "packageName", true, true); err != nil {+ if request.PackageName, err = requestFieldString(fields, "packageName", true, true); err != nil {return request, err}- if request.Frontend, err = bazaarString(fields, "frontend", false, true); err != nil {+ if request.Frontend, err = requestFieldString(fields, "frontend", false, true); err != nil {return request, err}return request, nil@@ -568,7 +554,7 @@ func init() {if err != nil {return request, err}- if request.PackageType, err = bazaarString(fields, "packageType", true, true); err != nil {+ if request.PackageType, err = requestFieldString(fields, "packageType", true, true); err != nil {return request, err}items, parseErr := legacyField[[]json.RawMessage](fields, "packageNames", "Array", true)@@ -591,7 +577,7 @@ func init() {if err != nil {return request, err}- if request.PackageType, err = bazaarString(fields, "packageType", true, true); err != nil {+ if request.PackageType, err = requestFieldString(fields, "packageType", true, true); err != nil {return request, err}items, parseErr := legacyField[[]json.RawMessage](fields, "packageNames", "Array", true)@@ -614,10 +600,10 @@ func init() {if err != nil {return request, err}- if request.PackageType, err = bazaarString(fields, "packageType", true, true); err != nil {+ if request.PackageType, err = requestFieldString(fields, "packageType", true, true); err != nil {return request, err}- if request.PackageName, err = bazaarString(fields, "packageName", true, true); err != nil {+ if request.PackageName, err = requestFieldString(fields, "packageName", true, true); err != nil {return request, err}return request, nil@@ -627,10 +613,10 @@ func init() {if err != nil {return request, err}- if request.PackageType, err = bazaarString(fields, "packageType", true, true); err != nil {+ if request.PackageType, err = requestFieldString(fields, "packageType", true, true); err != nil {return request, err}- if request.PackageName, err = bazaarString(fields, "packageName", true, true); err != nil {+ if request.PackageName, err = requestFieldString(fields, "packageName", true, true); err != nil {return request, err}if request.Rating, err = legacyField[float64](fields, "rating", "Number", true); err != nil {@@ -643,13 +629,13 @@ func init() {if err != nil {return request, err}- if request.RepoURL, err = bazaarString(fields, "repoURL", true, true); err != nil {+ if request.RepoURL, err = requestFieldString(fields, "repoURL", true, true); err != nil {return request, err}- if request.RepoHash, err = bazaarString(fields, "repoHash", true, true); err != nil {+ if request.RepoHash, err = requestFieldString(fields, "repoHash", true, true); err != nil {return request, err}- if request.PackageType, err = bazaarString(fields, "packageType", true, true); err != nil {+ if request.PackageType, err = requestFieldString(fields, "packageType", true, true); err != nil {return request, err}return request, nil@@ -659,10 +645,10 @@ func init() {if err != nil {return request, err}- if request.Frontend, err = bazaarString(fields, "frontend", true, true); err != nil {+ if request.Frontend, err = requestFieldString(fields, "frontend", true, true); err != nil {return request, err}- if request.Keyword, err = bazaarString(fields, "keyword", false, false); err != nil {+ if request.Keyword, err = requestFieldString(fields, "keyword", false, false); err != nil {return request, err}return request, nil@@ -672,10 +658,10 @@ func init() {if err != nil {return request, err}- if request.Frontend, err = bazaarString(fields, "frontend", true, true); err != nil {+ if request.Frontend, err = requestFieldString(fields, "frontend", true, true); err != nil {return request, err}- if request.Keyword, err = bazaarString(fields, "keyword", false, false); err != nil {+ if request.Keyword, err = requestFieldString(fields, "keyword", false, false); err != nil {return request, err}return request, nil@@ -685,22 +671,22 @@ func init() {if err != nil {return request, err}- if request.Frontend, err = bazaarString(fields, "frontend", true, true); err != nil {+ if request.Frontend, err = requestFieldString(fields, "frontend", true, true); err != nil {return request, err}- if request.Keyword, err = bazaarString(fields, "keyword", false, false); err != nil {+ if request.Keyword, err = requestFieldString(fields, "keyword", false, false); err != nil {return request, err}- if request.RepoURL, err = bazaarString(fields, "repoURL", true, true); err != nil {+ if request.RepoURL, err = requestFieldString(fields, "repoURL", true, true); err != nil {return request, err}- if request.RepoHash, err = bazaarString(fields, "repoHash", true, true); err != nil {+ if request.RepoHash, err = requestFieldString(fields, "repoHash", true, true); err != nil {return request, err}- if request.RepoRef, err = bazaarString(fields, "repoRef", false, false); err != nil {+ if request.RepoRef, err = requestFieldString(fields, "repoRef", false, false); err != nil {return request, err}- if request.PackageName, err = bazaarString(fields, "packageName", true, true); err != nil {+ if request.PackageName, err = requestFieldString(fields, "packageName", true, true); err != nil {return request, err}return request, nil@@ -710,13 +696,13 @@ func init() {if err != nil {return request, err}- if request.Frontend, err = bazaarString(fields, "frontend", false, false); err != nil {+ if request.Frontend, err = requestFieldString(fields, "frontend", false, false); err != nil {return request, err}- if request.Keyword, err = bazaarString(fields, "keyword", false, false); err != nil {+ if request.Keyword, err = requestFieldString(fields, "keyword", false, false); err != nil {return request, err}- if request.PackageName, err = bazaarString(fields, "packageName", true, true); err != nil {+ if request.PackageName, err = requestFieldString(fields, "packageName", true, true); err != nil {return request, err}return request, nil@@ -726,7 +712,7 @@ func init() {if err != nil {return request, err}- if request.Keyword, err = bazaarString(fields, "keyword", false, false); err != nil {+ if request.Keyword, err = requestFieldString(fields, "keyword", false, false); err != nil {return request, err}return request, nil@@ -736,7 +722,7 @@ func init() {if err != nil {return request, err}- if request.Keyword, err = bazaarString(fields, "keyword", false, false); err != nil {+ if request.Keyword, err = requestFieldString(fields, "keyword", false, false); err != nil {return request, err}return request, nil@@ -746,19 +732,19 @@ func init() {if err != nil {return request, err}- if request.Keyword, err = bazaarString(fields, "keyword", false, false); err != nil {+ if request.Keyword, err = requestFieldString(fields, "keyword", false, false); err != nil {return request, err}- if request.RepoURL, err = bazaarString(fields, "repoURL", true, true); err != nil {+ if request.RepoURL, err = requestFieldString(fields, "repoURL", true, true); err != nil {return request, err}- if request.RepoHash, err = bazaarString(fields, "repoHash", true, true); err != nil {+ if request.RepoHash, err = requestFieldString(fields, "repoHash", true, true); err != nil {return request, err}- if request.RepoRef, err = bazaarString(fields, "repoRef", false, false); err != nil {+ if request.RepoRef, err = requestFieldString(fields, "repoRef", false, false); err != nil {return request, err}- if request.PackageName, err = bazaarString(fields, "packageName", true, true); err != nil {+ if request.PackageName, err = requestFieldString(fields, "packageName", true, true); err != nil {return request, err}return request, nil@@ -768,10 +754,10 @@ func init() {if err != nil {return request, err}- if request.Keyword, err = bazaarString(fields, "keyword", false, false); err != nil {+ if request.Keyword, err = requestFieldString(fields, "keyword", false, false); err != nil {return request, err}- if request.PackageName, err = bazaarString(fields, "packageName", true, true); err != nil {+ if request.PackageName, err = requestFieldString(fields, "packageName", true, true); err != nil {return request, err}return request, nil@@ -781,7 +767,7 @@ func init() {if err != nil {return request, err}- if request.Keyword, err = bazaarString(fields, "keyword", false, false); err != nil {+ if request.Keyword, err = requestFieldString(fields, "keyword", false, false); err != nil {return request, err}return request, nil@@ -791,7 +777,7 @@ func init() {if err != nil {return request, err}- if request.Keyword, err = bazaarString(fields, "keyword", false, false); err != nil {+ if request.Keyword, err = requestFieldString(fields, "keyword", false, false); err != nil {return request, err}return request, nil@@ -801,19 +787,19 @@ func init() {if err != nil {return request, err}- if request.Keyword, err = bazaarString(fields, "keyword", false, false); err != nil {+ if request.Keyword, err = requestFieldString(fields, "keyword", false, false); err != nil {return request, err}- if request.RepoURL, err = bazaarString(fields, "repoURL", true, true); err != nil {+ if request.RepoURL, err = requestFieldString(fields, "repoURL", true, true); err != nil {return request, err}- if request.RepoHash, err = bazaarString(fields, "repoHash", true, true); err != nil {+ if request.RepoHash, err = requestFieldString(fields, "repoHash", true, true); err != nil {return request, err}- if request.RepoRef, err = bazaarString(fields, "repoRef", false, false); err != nil {+ if request.RepoRef, err = requestFieldString(fields, "repoRef", false, false); err != nil {return request, err}- if request.PackageName, err = bazaarString(fields, "packageName", true, true); err != nil {+ if request.PackageName, err = requestFieldString(fields, "packageName", true, true); err != nil {return request, err}return request, nil@@ -823,10 +809,10 @@ func init() {if err != nil {return request, err}- if request.Keyword, err = bazaarString(fields, "keyword", false, false); err != nil {+ if request.Keyword, err = requestFieldString(fields, "keyword", false, false); err != nil {return request, err}- if request.PackageName, err = bazaarString(fields, "packageName", true, true); err != nil {+ if request.PackageName, err = requestFieldString(fields, "packageName", true, true); err != nil {return request, err}return request, nil@@ -836,7 +822,7 @@ func init() {if err != nil {return request, err}- if request.Keyword, err = bazaarString(fields, "keyword", false, false); err != nil {+ if request.Keyword, err = requestFieldString(fields, "keyword", false, false); err != nil {return request, err}return request, nil@@ -846,7 +832,7 @@ func init() {if err != nil {return request, err}- if request.Keyword, err = bazaarString(fields, "keyword", false, false); err != nil {+ if request.Keyword, err = requestFieldString(fields, "keyword", false, false); err != nil {return request, err}return request, nil@@ -856,19 +842,19 @@ func init() {if err != nil {return request, err}- if request.Keyword, err = bazaarString(fields, "keyword", false, false); err != nil {+ if request.Keyword, err = requestFieldString(fields, "keyword", false, false); err != nil {return request, err}- if request.RepoURL, err = bazaarString(fields, "repoURL", true, true); err != nil {+ if request.RepoURL, err = requestFieldString(fields, "repoURL", true, true); err != nil {return request, err}- if request.RepoHash, err = bazaarString(fields, "repoHash", true, true); err != nil {+ if request.RepoHash, err = requestFieldString(fields, "repoHash", true, true); err != nil {return request, err}- if request.RepoRef, err = bazaarString(fields, "repoRef", false, false); err != nil {+ if request.RepoRef, err = requestFieldString(fields, "repoRef", false, false); err != nil {return request, err}- if request.PackageName, err = bazaarString(fields, "packageName", true, true); err != nil {+ if request.PackageName, err = requestFieldString(fields, "packageName", true, true); err != nil {return request, err}return request, nil@@ -878,10 +864,10 @@ func init() {if err != nil {return request, err}- if request.Keyword, err = bazaarString(fields, "keyword", false, false); err != nil {+ if request.Keyword, err = requestFieldString(fields, "keyword", false, false); err != nil {return request, err}- if request.PackageName, err = bazaarString(fields, "packageName", true, true); err != nil {+ if request.PackageName, err = requestFieldString(fields, "packageName", true, true); err != nil {return request, err}return request, nil@@ -891,10 +877,10 @@ func init() {if err != nil {return request, err}- if request.Frontend, err = bazaarString(fields, "frontend", false, false); err != nil {+ if request.Frontend, err = requestFieldString(fields, "frontend", false, false); err != nil {return request, err}- if request.Keyword, err = bazaarString(fields, "keyword", false, false); err != nil {+ if request.Keyword, err = requestFieldString(fields, "keyword", false, false); err != nil {return request, err}return request, nil@@ -904,10 +890,10 @@ func init() {if err != nil {return request, err}- if request.Frontend, err = bazaarString(fields, "frontend", false, false); err != nil {+ if request.Frontend, err = requestFieldString(fields, "frontend", false, false); err != nil {return request, err}- if request.Keyword, err = bazaarString(fields, "keyword", false, false); err != nil {+ if request.Keyword, err = requestFieldString(fields, "keyword", false, false); err != nil {return request, err}return request, nil@@ -917,22 +903,22 @@ func init() {if err != nil {return request, err}- if request.Frontend, err = bazaarString(fields, "frontend", false, false); err != nil {+ if request.Frontend, err = requestFieldString(fields, "frontend", false, false); err != nil {return request, err}- if request.Keyword, err = bazaarString(fields, "keyword", false, false); err != nil {+ if request.Keyword, err = requestFieldString(fields, "keyword", false, false); err != nil {return request, err}- if request.RepoURL, err = bazaarString(fields, "repoURL", true, true); err != nil {+ if request.RepoURL, err = requestFieldString(fields, "repoURL", true, true); err != nil {return request, err}- if request.RepoHash, err = bazaarString(fields, "repoHash", true, true); err != nil {+ if request.RepoHash, err = requestFieldString(fields, "repoHash", true, true); err != nil {return request, err}- if request.RepoRef, err = bazaarString(fields, "repoRef", false, false); err != nil {+ if request.RepoRef, err = requestFieldString(fields, "repoRef", false, false); err != nil {return request, err}- if request.PackageName, err = bazaarString(fields, "packageName", true, true); err != nil {+ if request.PackageName, err = requestFieldString(fields, "packageName", true, true); err != nil {return request, err}_, hasMode := fields["mode"]@@ -962,13 +948,13 @@ func init() {if err != nil {return request, err}- if request.Frontend, err = bazaarString(fields, "frontend", false, false); err != nil {+ if request.Frontend, err = requestFieldString(fields, "frontend", false, false); err != nil {return request, err}- if request.Keyword, err = bazaarString(fields, "keyword", false, false); err != nil {+ if request.Keyword, err = requestFieldString(fields, "keyword", false, false); err != nil {return request, err}- if request.PackageName, err = bazaarString(fields, "packageName", true, true); err != nil {+ if request.PackageName, err = requestFieldString(fields, "packageName", true, true); err != nil {return request, err}return request, nildiff --git a/kernel/apicontract/legacy_string_field.go b/kernel/apicontract/legacy_string_field.gonew file mode 100644index 0000000000..4ea3939e04--- /dev/null+++ b/kernel/apicontract/legacy_string_field.go@@ -0,0 +1,27 @@+// SiYuan - https://github.com/siyuan-note/siyuan+// Copyright (c) 2020-present, b3log.org+// SPDX-License-Identifier: AGPL-3.0-or-later++package apicontract++import (+ "encoding/json"+ "fmt"+ "strings"+)++// requestFieldString 按旧解析语义读取字符串字段。+// trim 为 true 时裁掉首尾空白,裁剪后为空则报错;字段缺失或为 null 时按 required 决定是否报错。+func requestFieldString(fields map[string]json.RawMessage, key string, required, trim bool) (string, error) {+ value, err := legacyField[string](fields, key, "String", required)+ if err != nil {+ return "", err+ }+ if trim && len(fields[key]) > 0 && string(fields[key]) != "null" {+ value = strings.TrimSpace(value)+ if value == "" {+ return "", fmt.Errorf("Field [%s] must not be empty", key)+ }+ }+ return value, nil+}diff --git a/kernel/apicontract/repo.go b/kernel/apicontract/repo.goindex 2cce294340..112a84ecf4 100644--- a/kernel/apicontract/repo.go+++ b/kernel/apicontract/repo.go@@ -241,19 +241,6 @@ func repoRequestFields(reader io.Reader, path string) (map[string]json.RawMessag}return fields, nil}-func repoRequestString(fields map[string]json.RawMessage, key string, required, trim bool) (string, error) {- value, err := legacyField[string](fields, key, "String", required)- if err != nil {- return "", err- }- if trim && len(fields[key]) > 0 && string(fields[key]) != "null" {- value = strings.TrimSpace(value)- if value == "" {- return "", fmt.Errorf("Field [%s] must not be empty", key)- }- }- return value, nil-}func init() {SetRepoIndexRetentionDays.decodeRequest = func(reader io.Reader) (request SetRepoIndexRetentionDaysRequest, err error) {fields, err := repoRequestFields(reader, "/api/repo/setRepoIndexRetentionDays")@@ -280,7 +267,7 @@ func init() {if err != nil {return request, err}- if request.ID, err = repoRequestString(fields, "id", true, true); err != nil {+ if request.ID, err = requestFieldString(fields, "id", true, true); err != nil {return request, err}return request, nil@@ -290,7 +277,7 @@ func init() {if err != nil {return request, err}- if request.ID, err = repoRequestString(fields, "id", true, true); err != nil {+ if request.ID, err = requestFieldString(fields, "id", true, true); err != nil {return request, err}return request, nil@@ -300,7 +287,7 @@ func init() {if err != nil {return request, err}- if request.ID, err = repoRequestString(fields, "id", true, true); err != nil {+ if request.ID, err = requestFieldString(fields, "id", true, true); err != nil {return request, err}return request, nil@@ -310,10 +297,10 @@ func init() {if err != nil {return request, err}- if request.Left, err = repoRequestString(fields, "left", true, true); err != nil {+ if request.Left, err = requestFieldString(fields, "left", true, true); err != nil {return request, err}- if request.Right, err = repoRequestString(fields, "right", true, true); err != nil {+ if request.Right, err = requestFieldString(fields, "right", true, true); err != nil {return request, err}return request, nil@@ -323,10 +310,10 @@ func init() {if err != nil {return request, err}- if request.ID, err = repoRequestString(fields, "id", true, true); err != nil {+ if request.ID, err = requestFieldString(fields, "id", true, true); err != nil {return request, err}- if request.SessionID, err = repoRequestString(fields, "sessionID", false, false); err != nil {+ if request.SessionID, err = requestFieldString(fields, "sessionID", false, false); err != nil {return request, err}return request, nil@@ -336,10 +323,10 @@ func init() {if err != nil {return request, err}- if request.ID, err = repoRequestString(fields, "id", true, true); err != nil {+ if request.ID, err = requestFieldString(fields, "id", true, true); err != nil {return request, err}- if request.Tag, err = repoRequestString(fields, "tag", true, false); err != nil {+ if request.Tag, err = requestFieldString(fields, "tag", true, false); err != nil {return request, err}return request, nil@@ -349,10 +336,10 @@ func init() {if err != nil {return request, err}- if request.ID, err = repoRequestString(fields, "id", true, true); err != nil {+ if request.ID, err = requestFieldString(fields, "id", true, true); err != nil {return request, err}- if request.Tag, err = repoRequestString(fields, "tag", true, false); err != nil {+ if request.Tag, err = requestFieldString(fields, "tag", true, false); err != nil {return request, err}return request, nil@@ -387,7 +374,7 @@ func init() {if err != nil {return request, err}- if request.Keyword, err = repoRequestString(fields, "keyword", true, true); err != nil {+ if request.Keyword, err = requestFieldString(fields, "keyword", true, true); err != nil {return request, err}if request.Page, err = legacyField[float64](fields, "page", "Number", true); err != nil {@@ -400,7 +387,7 @@ func init() {if err != nil {return request, err}- if request.ID, err = repoRequestString(fields, "id", true, true); err != nil {+ if request.ID, err = requestFieldString(fields, "id", true, true); err != nil {return request, err}if request.Page, err = legacyField[float64](fields, "page", "Number", true); err != nil {@@ -413,7 +400,7 @@ func init() {if err != nil {return request, err}- if request.ID, err = repoRequestString(fields, "id", true, true); err != nil {+ if request.ID, err = requestFieldString(fields, "id", true, true); err != nil {return request, err}return request, nil@@ -436,7 +423,7 @@ func init() {if err != nil {return request, err}- if request.Tag, err = repoRequestString(fields, "tag", true, true); err != nil {+ if request.Tag, err = requestFieldString(fields, "tag", true, true); err != nil {return request, err}return request, nil@@ -446,7 +433,7 @@ func init() {if err != nil {return request, err}- if request.Tag, err = repoRequestString(fields, "tag", true, true); err != nil {+ if request.Tag, err = requestFieldString(fields, "tag", true, true); err != nil {return request, err}return request, nil@@ -456,10 +443,10 @@ func init() {if err != nil {return request, err}- if request.ID, err = repoRequestString(fields, "id", true, true); err != nil {+ if request.ID, err = requestFieldString(fields, "id", true, true); err != nil {return request, err}- if request.Name, err = repoRequestString(fields, "name", true, false); err != nil {+ if request.Name, err = requestFieldString(fields, "name", true, false); err != nil {return request, err}return request, nil@@ -469,7 +456,7 @@ func init() {if err != nil {return request, err}- if request.Key, err = repoRequestString(fields, "key", true, false); err != nil {+ if request.Key, err = requestFieldString(fields, "key", true, false); err != nil {return request, err}return request, nil@@ -479,7 +466,7 @@ func init() {if err != nil {return request, err}- if request.Pass, err = repoRequestString(fields, "pass", true, false); err != nil {+ if request.Pass, err = requestFieldString(fields, "pass", true, false); err != nil {return request, err}return request, nildiff --git a/kernel/cli/cmd/display_test.go b/kernel/cli/cmd/display_test.goindex 59e541ec82..27d84c437c 100644--- a/kernel/cli/cmd/display_test.go+++ b/kernel/cli/cmd/display_test.go@@ -166,50 +166,6 @@ func TestNormalizeDocumentCreateParentPath(t *testing.T) {}}-func TestDocumentSearchDisplayFields(t *testing.T) {- tests := []struct {- name string- doc map[string]string- wantType string- wantID string- wantName string- }{- {- name: "document",- doc: map[string]string{- "path": "/20260722120000-parent1/20260722123000-child01.sy",- "hPath": "Notebook/Parent/Document",- "title": "Literal / title",- "box": "20260722110000-boxid01",- },- wantType: "DOCUMENT",- wantID: "20260722123000-child01",- wantName: "Literal / title",- },- {- name: "notebook",- doc: map[string]string{- "path": "/",- "hPath": "Notebook/",- "title": "Notebook",- "box": "20260722110000-boxid01",- },- wantType: "NOTEBOOK",- wantID: "20260722110000-boxid01",- wantName: "Notebook",- },- }-- for _, test := range tests {- t.Run(test.name, func(t *testing.T) {- typ, id, name := documentSearchDisplayFields(test.doc)- if typ != test.wantType || id != test.wantID || name != test.wantName {- t.Fatalf("documentSearchDisplayFields() = (%q, %q, %q), want (%q, %q, %q)", typ, id, name, test.wantType, test.wantID, test.wantName)- }- })- }-}-func TestTruncate(t *testing.T) {tests := []struct {name stringdiff --git a/kernel/cli/cmd/document.go b/kernel/cli/cmd/document.goindex 0ec47de23d..aecd36d849 100644--- a/kernel/cli/cmd/document.go+++ b/kernel/cli/cmd/document.go@@ -399,7 +399,7 @@ var documentSearchCmd = &cobra.Command{w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)fmt.Fprintln(w, "TYPE\tID\tNAME\tHPATH")for _, d := range docs {- typ, id, name := documentSearchDisplayFields(d)+ typ, id, name := model.SearchDocDisplayFields(d)fmt.Fprintf(w, "%s\t%s\t%s\t%s\n", typ, id, name, d["hPath"])}w.Flush()@@ -409,13 +409,6 @@ var documentSearchCmd = &cobra.Command{},}-func documentSearchDisplayFields(doc map[string]string) (typ, id, name string) {- if "/" == doc["path"] {- return "NOTEBOOK", doc["box"], doc["title"]- }- return "DOCUMENT", strings.TrimSuffix(path.Base(doc["path"]), ".sy"), doc["title"]-}-func printDocumentTable(files []*model.File) {w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)fmt.Fprintln(w, "ID\tNAME\tPATH\tSIZE\tCOUNT\tMTIME")diff --git a/kernel/cli/cmd/file.go b/kernel/cli/cmd/file.goindex 301860b35d..a32c76bff7 100644--- a/kernel/cli/cmd/file.go+++ b/kernel/cli/cmd/file.go@@ -215,7 +215,7 @@ var fileCopyCmd = &cobra.Command{return nil}- if err := copyPath(src, dst); err != nil {+ if err := util.CopyPath(src, dst); err != nil {return err}fmt.Println("ok")@@ -223,53 +223,6 @@ var fileCopyCmd = &cobra.Command{},}-func copyPath(src, dst string) error {- srcInfo, err := os.Stat(src)- if err != nil {- return err- }- if srcInfo.IsDir() {- return copyDir(src, dst)- }- return copyFile(src, dst)-}--func copyDir(src, dst string) error {- if err := os.MkdirAll(dst, 0755); err != nil {- return err- }- entries, err := os.ReadDir(src)- if err != nil {- return err- }- for _, e := range entries {- srcPath := filepath.Join(src, e.Name())- dstPath := filepath.Join(dst, e.Name())- if err := copyPath(srcPath, dstPath); err != nil {- return err- }- }- return nil-}--func copyFile(src, dst string) error {- if err := os.MkdirAll(filepath.Dir(dst), 0755); err != nil {- return err- }- srcF, err := os.Open(src)- if err != nil {- return err- }- defer srcF.Close()- dstF, err := os.Create(dst)- if err != nil {- return err- }- defer dstF.Close()- _, err = io.Copy(dstF, srcF)- return err-}-var fileGrepCmd = &cobra.Command{Use: "grep --pattern <regex> --path <path>",Short: "Search file contents with regex",@@ -345,7 +298,7 @@ var fileFindCmd = &cobra.Command{if !d.Type().IsRegular() {return nil}- if include != "" && !matchGlob(d.Name(), include) {+ if include != "" && !util.MatchGlob(d.Name(), include) {return nil}total++@@ -414,35 +367,6 @@ var fileStatCmd = &cobra.Command{},}-func matchGlob(filename, pattern string) bool {- for _, p := range expandGlobBrace(pattern) {- if matched, _ := filepath.Match(p, filename); matched {- return true- }- }- return false-}--func expandGlobBrace(pattern string) []string {- i := strings.Index(pattern, "{")- if i < 0 {- return []string{pattern}- }- j := strings.Index(pattern[i:], "}")- if j < 0 {- return []string{pattern}- }- j += i- prefix := pattern[:i]- body := pattern[i+1 : j]- suffix := pattern[j+1:]- var result []string- for opt := range strings.SplitSeq(body, ",") {- result = append(result, expandGlobBrace(prefix+strings.TrimSpace(opt)+suffix)...)- }- return result-}-func init() {fileWriteCmd.Flags().String("file", "", "source file path (default: stdin)")diff --git a/kernel/cli/cmd/inbox.go b/kernel/cli/cmd/inbox.goindex f960135cf0..a4c014bc78 100644--- a/kernel/cli/cmd/inbox.go+++ b/kernel/cli/cmd/inbox.go@@ -144,11 +144,11 @@ var inboxConvertCmd = &cobra.Command{// 解析目标父路径(hPath→fsPath):hPath 指向新文档将要落入的父容器,// 其父目录必须已存在;不传或传 "/" 时落到笔记本根目录。parentPath := "/"- parentDir := parentDir(hPath)- if parentDir != "/" {- bt := treenode.GetBlockTreeRootByHPath(notebook, parentDir)+ parentHPath := util.ParentHPath(hPath)+ if parentHPath != "/" {+ bt := treenode.GetBlockTreeRootByHPath(notebook, parentHPath)if bt == nil {- return fmt.Errorf("parent path not found: %s", parentDir)+ return fmt.Errorf("parent path not found: %s", parentHPath)}parentPath = strings.TrimSuffix(bt.Path, ".sy")}@@ -259,15 +259,6 @@ func parseShorthandIDs(s string) []string {return out}-// parentDir 返回路径的父目录:去掉最后一个 "/" 段,根路径及单段路径返回 "/"。-func parentDir(p string) string {- i := strings.LastIndex(p, "/")- if i <= 0 {- return "/"- }- return p[:i]-}-func init() {inboxListCmd.Flags().IntP("page", "p", 1, "page number (1-based)")inboxGetCmd.Flags().String("id", "", "shorthand ID (required)")diff --git a/kernel/cli/cmd/notebook.go b/kernel/cli/cmd/notebook.goindex a225aedd51..e7c3de2b5a 100644--- a/kernel/cli/cmd/notebook.go+++ b/kernel/cli/cmd/notebook.go@@ -20,15 +20,10 @@ import ("encoding/json""errors""fmt"- "math/rand""os"- "path/filepath"- "sync""text/tabwriter""time"- "github.com/88250/gulu"-"github.com/siyuan-note/siyuan/kernel/model""github.com/siyuan-note/siyuan/kernel/sql""github.com/siyuan-note/siyuan/kernel/util"@@ -302,7 +297,7 @@ var notebookRandomIconCmd = &cobra.Command{}changes := make([]change, 0, len(targets))for _, nb := range targets {- changes = append(changes, change{ID: nb.ID, Name: nb.Name, OldIcon: nb.Icon, NewIcon: randomEmoji()})+ changes = append(changes, change{ID: nb.ID, Name: nb.Name, OldIcon: nb.Icon, NewIcon: util.RandomBuiltinEmoji()})}if dryRun {@@ -332,59 +327,6 @@ var notebookRandomIconCmd = &cobra.Command{},}-// builtinEmojiUnicodes 缓存内置 emoji 的全部 unicode 码点(来自 appearance/emojis/conf.json)。-// 与前端 getRandomEmoji() 数据源一致,但刻意排除用户自定义图片,-// 保持随机图标风格统一、避免误用用户的重要图片。-var (- builtinEmojiUnicodes []string- builtinEmojiUnicodesOnce sync.Once-)--// loadBuiltinEmojiUnicodes 懒加载内置 emoji 的 unicode 列表。-// 失败时回退到一个固定码点,调用方始终拿到可用值。-func loadBuiltinEmojiUnicodes() {- builtinEmojiUnicodesOnce.Do(func() {- confPath := filepath.Join(util.AppearancePath, "emojis", "conf.json")- data, err := os.ReadFile(confPath)- if err != nil {- builtinEmojiUnicodes = []string{"1f4d6"}- return- }-- var conf []map[string]any- if err = gulu.JSON.UnmarshalJSON(data, &conf); err != nil {- builtinEmojiUnicodes = []string{"1f4d6"}- return- }-- for _, category := range conf {- items, ok := category["items"].([]any)- if !ok {- continue- }- for _, item := range items {- e, ok := item.(map[string]any)- if !ok {- continue- }- if u, ok := e["unicode"].(string); ok && u != "" {- builtinEmojiUnicodes = append(builtinEmojiUnicodes, u)- }- }- }-- if len(builtinEmojiUnicodes) == 0 {- builtinEmojiUnicodes = []string{"1f4d6"}- }- })-}--// randomEmoji 返回一个随机的内置 emoji unicode 码点(如 "1f4d6")。-func randomEmoji() string {- loadBuiltinEmojiUnicodes()- return builtinEmojiUnicodes[rand.Intn(len(builtinEmojiUnicodes))]-}-func init() {notebookCreateCmd.Flags().String("name", "", "notebook name")notebookRemoveCmd.Flags().String("id", "", "notebook ID")diff --git a/kernel/filesys/crypto_hook.go b/kernel/filesys/crypto_hook.goindex 1fb8f3eaf5..b183e1ce92 100644--- a/kernel/filesys/crypto_hook.go+++ b/kernel/filesys/crypto_hook.go@@ -18,7 +18,6 @@ package filesysimport ("fmt"- "path/filepath""strings""github.com/88250/lute/ast"@@ -127,24 +126,3 @@ func SyAAD(boxID, relativePath string) (string, error) {}return "siyuan:file:" + boxID + ":" + base, nil}--// docIALBoxID 从 .sy 绝对路径反推 boxID,供 DocIAL 判断是否需整体解密。-// 路径形如 <DataDir>/<boxID>/...;若不在 DataDir 下或 boxID 非合法 ID 模式,返回空串。-func docIALBoxID(absPath string) string {- absPath = filepath.ToSlash(absPath)- dataDir := filepath.ToSlash(util.DataDir)- rel, err := filepath.Rel(dataDir, absPath)- if err != nil {- return ""- }- rel = filepath.ToSlash(rel)- if strings.HasPrefix(rel, "..") || rel == "." || rel == "" {- return ""- }- parts := strings.SplitN(rel, "/", 2)- boxID := parts[0]- if !ast.IsNodeIDPattern(boxID) {- return ""- }- return boxID-}diff --git a/kernel/filesys/tree.go b/kernel/filesys/tree.goindex 6a498f3e71..b5c4009bb1 100644--- a/kernel/filesys/tree.go+++ b/kernel/filesys/tree.go@@ -388,7 +388,7 @@ type documentHeader struct {}func readDocumentHeader(absPath string, strict bool) (*documentHeader, error) {- boxID := docIALBoxID(absPath)+ boxID := util.BoxIDFromDataPath(absPath)mode, err := DocumentAddressingMode(boxID)if err != nil {return nil, err@@ -397,7 +397,7 @@ func readDocumentHeader(absPath string, strict bool) (*documentHeader, error) {}func readDocumentHeaderInMode(absPath string, strict bool, mode int) (*documentHeader, error) {- boxID := docIALBoxID(absPath)+ boxID := util.BoxIDFromDataPath(absPath)dek, _, release, err := acquireCryptoLease(boxID)if err != nil {return nil, err@@ -440,7 +440,7 @@ var ErrInvalidDocIAL = errors.New("invalid document properties")func DocIAL(absPath string) (ret map[string]string, err error) {// 加密笔记本的 .sy 是密文,流式 jsoniter 解析无法处理,需先整体读+解密。// 反推 boxID:路径形如 <DataDir>/<boxID>/...;非加密笔记本走原流式逻辑。- boxID := docIALBoxID(absPath)+ boxID := util.BoxIDFromDataPath(absPath)mode, err := DocumentAddressingMode(boxID)if err != nil {return nil, errdiff --git a/kernel/mcp/tools/decision_image.go b/kernel/mcp/tools/decision_image.goindex f1be7e1435..3ddff3a1cc 100644--- a/kernel/mcp/tools/decision_image.go+++ b/kernel/mcp/tools/decision_image.go@@ -96,7 +96,7 @@ func prepareDecisionAssetImage(image decisionImageInput) (util.DecisionImage, erif err != nil {return util.DecisionImage{}, errors.New("decision image asset is unavailable")}- boxID := model.ExtractBoxIDFromAssetsPath(absPath)+ boxID := util.BoxIDFromDataPath(absPath)if model.IsEncryptedBox(boxID) && (image.Notebook != boxID || !model.IsBoxUnlocked(boxID)) {return util.DecisionImage{}, errors.New("encrypted image requires its unlocked notebook")}diff --git a/kernel/mcp/tools/document.go b/kernel/mcp/tools/document.goindex 65a248e702..9607cac796 100644--- a/kernel/mcp/tools/document.go+++ b/kernel/mcp/tools/document.go@@ -20,7 +20,6 @@ import ("encoding/json""errors""fmt"- "path""strings""github.com/88250/lute/ast"@@ -200,7 +199,7 @@ func resolveDocumentTarget(notebook string, args map[string]any, create, defaultreturn nil, errors.New("parentID or path is required")}if create {- hPath = parentDir(hPath)+ hPath = util.ParentHPath(hPath)}bt, err := model.ResolveLegacyDocumentPath(notebook, hPath, create)if err != nil {@@ -216,14 +215,6 @@ func resolveDocumentTarget(notebook string, args map[string]any, create, defaultreturn target, nil}-func parentDir(p string) string {- i := strings.LastIndex(p, "/")- if i <= 0 {- return "/"- }- return p[:i]-}-func documentList(args map[string]any) (CallToolResult, error) {notebook, _ := args["notebook"].(string)if notebook == "" {@@ -337,7 +328,7 @@ func documentSearchDocs(args map[string]any) (CallToolResult, error) {var sb strings.Builderfmt.Fprintf(&sb, "Search results matching '%s' (%d):\n\n", keyword, len(docs))for _, d := range docs {- typ, id, name := documentSearchDisplayFields(d)+ typ, id, name := model.SearchDocDisplayFields(d)if typ == "NOTEBOOK" {fmt.Fprintf(&sb, "- [%s] %s (id: %s, hPath: %s)\n", typ, name, id, d["hPath"])} else {@@ -347,13 +338,6 @@ func documentSearchDocs(args map[string]any) (CallToolResult, error) {return CallToolResult{Content: []ContentItem{{Type: "text", Text: sb.String()}}}, nil}-func documentSearchDisplayFields(doc map[string]string) (typ, id, name string) {- if doc["path"] == "/" {- return "NOTEBOOK", doc["box"], doc["title"]- }- return "DOCUMENT", strings.TrimSuffix(path.Base(doc["path"]), ".sy"), doc["title"]-}-func documentInfo(args map[string]any) (CallToolResult, error) {id, _ := args["id"].(string)if id == "" {diff --git a/kernel/mcp/tools/file.go b/kernel/mcp/tools/file.goindex a2a4e0dcc6..7856f0ca66 100644--- a/kernel/mcp/tools/file.go+++ b/kernel/mcp/tools/file.go@@ -22,7 +22,6 @@ import ("encoding/json""errors""fmt"- "io""math""os""path/filepath"@@ -859,57 +858,12 @@ func fileCopy(args map[string]any) (CallToolResult, error) {if err = authorizeCopyTree(srcAbs, dstAbs); err != nil {return CallToolResult{Content: []ContentItem{{Type: "text", Text: err.Error()}}, IsError: true}, nil}- if err := copyPath(srcAbs, dstAbs); err != nil {+ if err := util.CopyPath(srcAbs, dstAbs); err != nil {return CallToolResult{Content: []ContentItem{{Type: "text", Text: "copy failed: " + err.Error()}}, IsError: true}, nil}return CallToolResult{Content: []ContentItem{{Type: "text", Text: fmt.Sprintf("copied: %s -> %s", src, dst)}}}, nil}-func copyPath(src, dst string) error {- srcInfo, err := os.Stat(src)- if err != nil {- return err- }- if srcInfo.IsDir() {- return copyDir(src, dst)- }- return copyFile(src, dst)-}--func copyDir(src, dst string) error {- if err := os.MkdirAll(dst, 0755); err != nil {- return err- }- entries, err := os.ReadDir(src)- if err != nil {- return err- }- for _, e := range entries {- if err := copyPath(filepath.Join(src, e.Name()), filepath.Join(dst, e.Name())); err != nil {- return err- }- }- return nil-}--func copyFile(src, dst string) error {- if err := os.MkdirAll(filepath.Dir(dst), 0755); err != nil {- return err- }- srcF, err := os.Open(src)- if err != nil {- return err- }- defer srcF.Close()- dstF, err := os.Create(dst)- if err != nil {- return err- }- defer dstF.Close()- _, err = io.Copy(dstF, srcF)- return err-}-func typeLabel(isDir bool) string {if isDir {return "DIR"@@ -993,7 +947,7 @@ func grepGuarded(root, include, pattern string, context, maxResults int) ([]*gulif !d.Type().IsRegular() {return nil}- if include != "" && !matchGlob(d.Name(), include) {+ if include != "" && !util.MatchGlob(d.Name(), include) {return nil}if authorizeFinalPath(path) != nil {@@ -1113,7 +1067,7 @@ func fileFind(args map[string]any) (CallToolResult, error) {if !d.Type().IsRegular() {return nil}- if include != "" && !matchGlob(d.Name(), include) {+ if include != "" && !util.MatchGlob(d.Name(), include) {return nil}if authorizeFinalPath(path) != nil {@@ -1156,39 +1110,6 @@ func fileFind(args map[string]any) (CallToolResult, error) {return CallToolResult{Content: []ContentItem{{Type: "text", Text: sb.String()}}}, nil}-func matchGlob(filename, pattern string) bool {- patterns := expandGlobBrace(pattern)- for _, p := range patterns {- if matched, _ := filepath.Match(p, filename); matched {- return true- }- }- return false-}--func expandGlobBrace(pattern string) []string {- i := strings.Index(pattern, "{")- if i < 0 {- return []string{pattern}- }-- j := strings.Index(pattern[i:], "}")- if j < 0 {- return []string{pattern}- }- j += i-- prefix := pattern[:i]- body := pattern[i+1 : j]- suffix := pattern[j+1:]-- var result []string- for opt := range strings.SplitSeq(body, ",") {- result = append(result, expandGlobBrace(prefix+strings.TrimSpace(opt)+suffix)...)- }- return result-}-func fileStat(args map[string]any) (CallToolResult, error) {p, _ := args["path"].(string)if p == "" {diff --git a/kernel/mcp/tools/notebook.go b/kernel/mcp/tools/notebook.goindex f274610186..5ec7d65dbc 100644--- a/kernel/mcp/tools/notebook.go+++ b/kernel/mcp/tools/notebook.go@@ -248,7 +248,7 @@ func notebookRandomIcon(args map[string]any) (CallToolResult, error) {fmt.Fprintf(&sb, "Randomized icons for %d notebook(s):\n", len(targets))for _, nb := range targets {oldIcon := nb.Icon- newIcon := randomEmoji()+ newIcon := util.RandomBuiltinEmoji()model.SetBoxIcon(nb.ID, newIcon)fmt.Fprintf(&sb, "- %s (id: %s): %s -> %s\n", nb.Name, nb.ID, oldIcon, newIcon)}diff --git a/kernel/mcp/tools/unzip.go b/kernel/mcp/tools/unzip.goindex fde09f6e19..9f08b158b1 100644--- a/kernel/mcp/tools/unzip.go+++ b/kernel/mcp/tools/unzip.go@@ -19,7 +19,6 @@ package toolsimport ("archive/zip""fmt"- "io""os""path/filepath""strings"@@ -132,7 +131,7 @@ func extractGuardedArchive(zipAbs, destAbs string) error {if err = authorizeArchiveEntry(destAbs, members[i].path, members[i].name); err != nil {return err}- if err = extractArchiveEntry(entry, members[i].path); err != nil {+ if err = util.ExtractArchiveEntry(entry, members[i].path); err != nil {return err}}@@ -156,30 +155,3 @@ func authorizeArchiveEntry(destAbs, entryAbs, display string) error {}return authorizePath(entryAbs, display)}--func extractArchiveEntry(entry *zip.File, destination string) error {- if entry.FileInfo().IsDir() {- return os.MkdirAll(destination, 0755)- }- if err := os.MkdirAll(filepath.Dir(destination), 0755); err != nil {- return err- }- source, err := entry.Open()- if err != nil {- return err- }- defer source.Close()- target, err := os.Create(destination)- if err != nil {- return err- }- _, copyErr := io.Copy(target, source)- closeErr := target.Close()- if copyErr != nil {- return copyErr- }- if closeErr != nil {- return closeErr- }- return os.Chtimes(destination, entry.Modified, entry.Modified)-}diff --git a/kernel/model/asset_download_read.go b/kernel/model/asset_download_read.goindex fce9ae7878..2c20ef2e71 100644--- a/kernel/model/asset_download_read.go+++ b/kernel/model/asset_download_read.go@@ -101,7 +101,7 @@ func deferredAssetPathFromFiles(relativePath, boxID string, includeEncrypted boo} else {resolvedBoxID := boxIDif resolvedBoxID == "" {- resolvedBoxID = ExtractBoxIDFromAssetsPath(absPath)+ resolvedBoxID = util.BoxIDFromDataPath(absPath)}root, rootErr := ResolveAssetPathWithMissingLeaf(filepath.Join(util.DataDir, resolvedBoxID, "assets"))resolved, resolveErr := ResolveAssetPathWithMissingLeaf(absPath)@@ -127,7 +127,7 @@ func deferredAssetPathFromFiles(relativePath, boxID string, includeEncrypted boo// ensureReadableAssetLocal 先检查加密笔记本准入,再下载原始密文;实际读取仍须认证解密。func ensureReadableAssetLocal(absPath string) error {- boxID := ExtractBoxIDFromAssetsPath(absPath)+ boxID := util.BoxIDFromDataPath(absPath)if boxID != "" && IsEncryptedBox(boxID) && !IsBoxUnlocked(boxID) {return errors.New(Conf.Language(314))}diff --git a/kernel/model/assets.go b/kernel/model/assets.goindex e66d39b4ad..13805d8ef1 100644--- a/kernel/model/assets.go+++ b/kernel/model/assets.go@@ -107,7 +107,7 @@ func readAssetBytesInBox(boxID, relativePath string, download bool) ([]byte, errvar readErr errorif heif.IsPath(relativePath) {limit := int64(heif.MaxInputBytes)- if effectiveBoxID := ExtractBoxIDFromAssetsPath(absPath); effectiveBoxID != "" && IsEncryptedBox(effectiveBoxID) {+ if effectiveBoxID := util.BoxIDFromDataPath(absPath); effectiveBoxID != "" && IsEncryptedBox(effectiveBoxID) {limit += 2 * 1024 * 1024}data, readErr = heif.ReadFileLimited(absPath, limit)@@ -118,7 +118,7 @@ func readAssetBytesInBox(boxID, relativePath string, download bool) ([]byte, errreturn nil, readErr}// 从解析到的绝对路径反推有效 boxID,不轻信传入参数(路径可能通过 ?box= 指定了不同 box)- effectiveBoxID := ExtractBoxIDFromAssetsPath(absPath)+ effectiveBoxID := util.BoxIDFromDataPath(absPath)if effectiveBoxID != "" && IsEncryptedBox(effectiveBoxID) {HoldBoxReadLock(effectiveBoxID)dek, dekErr := GetDEKIfUnlocked(effectiveBoxID)@@ -2056,7 +2056,7 @@ func UnusedAssets(sorted bool) (ret []*UnusedItem, err error) {// 排除加密笔记本的资源:加密笔记本锁定时 loadTree 失败会误判引用关系,// 且加密笔记本是孤岛,资源不参与全局未引用清理for dest, absPath := range assetsPathMap {- if boxID := ExtractBoxIDFromAssetsPath(absPath); boxID != "" && IsEncryptedBox(boxID) {+ if boxID := util.BoxIDFromDataPath(absPath); boxID != "" && IsEncryptedBox(boxID) {delete(assetsPathMap, dest)}}diff --git a/kernel/model/attribute_view.go b/kernel/model/attribute_view.goindex 78021ea941..3f3233bbc0 100644--- a/kernel/model/attribute_view.go+++ b/kernel/model/attribute_view.go@@ -5363,8 +5363,9 @@ func getKanbanPreferredGroupKey(attrView *av.AttributeView) (ret *av.Key) {return}-func (tx *Transaction) doSetAttrViewViewName(operation *Operation) (ret *TxErr) {- var err error+// setAttrViewViewField 读取视图并应用 apply 修改后保存,供视图名称、图标、描述的写入共用。+// 视图不存在时按视图 ID 报错,不再沿用上层解析留下的 err,避免打印 "failed: <nil>"。+func (tx *Transaction) setAttrViewViewField(operation *Operation, apply func(view *av.View)) (ret *TxErr) {avID := operation.AvIDattrView, err := avParseView(avID, operation.BlockID)if err != nil {@@ -5375,11 +5376,11 @@ func (tx *Transaction) doSetAttrViewViewName(operation *Operation) (ret *TxErr)viewID := operation.IDview := attrView.GetView(viewID)if nil == view {- logging.LogErrorf("get view [%s] failed: %s", viewID, err)+ logging.LogErrorf("attribute view [%s] has no view [%s]", avID, viewID)return &TxErr{code: TxErrHandleAttributeView, id: viewID}}- view.Name = strings.TrimSpace(operation.Data.(string))+ apply(view)if err = avSaveView(attrView, operation.BlockID); err != nil {logging.LogErrorf("save attribute view [%s] failed: %s", avID, err)return &TxErr{code: TxErrHandleAttributeView, msg: err.Error(), id: avID}@@ -5387,28 +5388,16 @@ func (tx *Transaction) doSetAttrViewViewName(operation *Operation) (ret *TxErr)return}-func (tx *Transaction) doSetAttrViewViewIcon(operation *Operation) (ret *TxErr) {- var err error- avID := operation.AvID- attrView, err := avParseView(avID, operation.BlockID)- if err != nil {- logging.LogErrorf("parse attribute view [%s] failed: %s", avID, err)- return &TxErr{code: TxErrHandleAttributeView, id: avID}- }-- viewID := operation.ID- view := attrView.GetView(viewID)- if nil == view {- logging.LogErrorf("get view [%s] failed: %s", viewID, err)- return &TxErr{code: TxErrHandleAttributeView, id: viewID}- }+func (tx *Transaction) doSetAttrViewViewName(operation *Operation) (ret *TxErr) {+ return tx.setAttrViewViewField(operation, func(view *av.View) {+ view.Name = strings.TrimSpace(operation.Data.(string))+ })+}- view.Icon = filterAttrViewIconValue(operation.Data.(string))- if err = avSaveView(attrView, operation.BlockID); err != nil {- logging.LogErrorf("save attribute view [%s] failed: %s", avID, err)- return &TxErr{code: TxErrHandleAttributeView, msg: err.Error(), id: avID}- }- return+func (tx *Transaction) doSetAttrViewViewIcon(operation *Operation) (ret *TxErr) {+ return tx.setAttrViewViewField(operation, func(view *av.View) {+ view.Icon = filterAttrViewIconValue(operation.Data.(string))+ })}// filterAttrViewIconValue 过滤属性视图图标值,非法值置空,防止存储可执行标记@@ -5421,27 +5410,9 @@ func filterAttrViewIconValue(icon string) string {}func (tx *Transaction) doSetAttrViewViewDesc(operation *Operation) (ret *TxErr) {- var err error- avID := operation.AvID- attrView, err := avParseView(avID, operation.BlockID)- if err != nil {- logging.LogErrorf("parse attribute view [%s] failed: %s", avID, err)- return &TxErr{code: TxErrHandleAttributeView, id: avID}- }-- viewID := operation.ID- view := attrView.GetView(viewID)- if nil == view {- logging.LogErrorf("get view [%s] failed: %s", viewID, err)- return &TxErr{code: TxErrHandleAttributeView, id: viewID}- }-- view.Desc = strings.TrimSpace(operation.Data.(string))- if err = avSaveView(attrView, operation.BlockID); err != nil {- logging.LogErrorf("save attribute view [%s] failed: %s", avID, err)- return &TxErr{code: TxErrHandleAttributeView, msg: err.Error(), id: avID}- }- return+ return tx.setAttrViewViewField(operation, func(view *av.View) {+ view.Desc = strings.TrimSpace(operation.Data.(string))+ })}func (tx *Transaction) doSetAttrViewName(operation *Operation) (ret *TxErr) {diff --git a/kernel/model/block.go b/kernel/model/block.goindex 44976fdf7f..0d0b670c4f 100644--- a/kernel/model/block.go+++ b/kernel/model/block.go@@ -141,9 +141,9 @@ func CheckBlockRef(ids []string) bool {// CheckBlockRefInBox 检查受影响块的引用,并检查实际删除块的数据库绑定。func CheckBlockRefInBox(ids, exactIDs, deletedIDs []string, boxID string) (ret bool, err error) {sql.FlushQueue()- ids = filterNonEmptyBlockRefCheckIDs(ids)- exactIDs = filterNonEmptyBlockRefCheckIDs(exactIDs)- deletedIDs = filterNonEmptyBlockRefCheckIDs(deletedIDs)+ ids = sql.FilterNonEmptyRefCheckIDs(ids)+ exactIDs = sql.FilterNonEmptyRefCheckIDs(exactIDs)+ deletedIDs = sql.FilterNonEmptyRefCheckIDs(deletedIDs)if 1 > len(ids) {return}@@ -250,22 +250,6 @@ func expandBlockRefCheckDescendants(group *blockRefCheckGroup, selected, deleted}}-func filterNonEmptyBlockRefCheckIDs(ids []string) (ret []string) {- seen := map[string]struct{}{}- for _, id := range ids {- id = strings.TrimSpace(id)- if "" == id {- continue- }- if _, exists := seen[id]; exists {- continue- }- seen[id] = struct{}{}- ret = append(ret, id)- }- return-}-// CheckDocsRef 检查文档删除时会递归移除的全部文档。func CheckDocsRef(paths []string) (ret bool, err error) {FlushTxQueue()diff --git a/kernel/model/clipboard.go b/kernel/model/clipboard.goindex b7fe56efc0..a54bb88a53 100644--- a/kernel/model/clipboard.go+++ b/kernel/model/clipboard.go@@ -98,7 +98,7 @@ func PrepareRichClipboardAssets(assets []RichClipboardAsset) (ret *RichClipboarddestPath, ok := copied[absPath]if !ok {- group := ExtractBoxIDFromAssetsPath(absPath)+ group := util.BoxIDFromDataPath(absPath)if group == "" {group = richClipboardGlobalGroup}diff --git a/kernel/model/clipboard_paste.go b/kernel/model/clipboard_paste.goindex b64a1d33ba..ab9098c9aa 100644--- a/kernel/model/clipboard_paste.go+++ b/kernel/model/clipboard_paste.go@@ -80,7 +80,7 @@ func PrepareClipboardPasteAssets(boxID string, references []string) (result map[if resolveErr != nil {return nil, resolveErr}- effectiveBox := ExtractBoxIDFromAssetsPath(absPath)+ effectiveBox := util.BoxIDFromDataPath(absPath)if IsEncryptedAssetPath(absPath) && effectiveBox != boxID {return nil, errors.New("cannot copy assets between encrypted notebooks")}diff --git a/kernel/model/crypto.go b/kernel/model/crypto.goindex 28b5cef0c0..8bdce1b19b 100644--- a/kernel/model/crypto.go+++ b/kernel/model/crypto.go@@ -2182,7 +2182,7 @@ func normalBoxBlockRefCrossesBoundary(bt *treenode.BlockTree) bool {// IsEncryptedAssetPath 判断给定 asset 绝对路径是否属于加密笔记本。// 供 server 层在缩略图等场景判断是否需跳过密文文件的处理。func IsEncryptedAssetPath(absPath string) bool {- boxID := ExtractBoxIDFromAssetsPath(absPath)+ boxID := util.BoxIDFromDataPath(absPath)return boxID != "" && IsEncryptedBox(boxID)}@@ -2233,35 +2233,6 @@ func ReleaseBoxReadLock(boxID string) {releaseBoxReadLock(boxID)}-// extractBoxIDFromPath 从 data 目录下的绝对路径反推 boxID。-// 路径形如 <DataDir>/<boxID>/...,切出紧跟在 DataDir 后的一段。-// 若路径不在 DataDir 下或格式不符,返回空字符串。-func extractBoxIDFromPath(absPath string) string {- return ExtractBoxIDFromAssetsPath(absPath)-}--// ExtractBoxIDFromAssetsPath 从 data 目录下的绝对路径(.sy 或 assets)反推 boxID。-// 供 server/api 层判断 asset 是否属于加密笔记本。路径形如 <DataDir>/<boxID>/...;-// 若不在 DataDir 下或 boxID 非合法 ID 模式,返回空串。-func ExtractBoxIDFromAssetsPath(absPath string) string {- absPath = filepath.ToSlash(absPath)- dataDir := filepath.ToSlash(util.DataDir)- rel, err := filepath.Rel(dataDir, absPath)- if err != nil {- return ""- }- rel = filepath.ToSlash(rel)- if strings.HasPrefix(rel, "..") || rel == "." || rel == "" {- return ""- }- parts := strings.SplitN(rel, "/", 2)- boxID := parts[0]- if !ast.IsNodeIDPattern(boxID) {- return ""- }- return boxID-}-// ExtractBoxIDFromHistoryPath 从历史目录下的绝对路径反推 boxID。// 路径形如 <HistoryDir>/<timestamp>-<op>/<boxID>/...,切出紧跟在时间戳目录后的一段。// 若路径不在 HistoryDir 下或 boxID 非合法 ID 模式,返回空串。@@ -2653,7 +2624,7 @@ func copyAssetDecryptIfEncrypted(srcPath, destPath string) error {return err}- boxID := ExtractBoxIDFromAssetsPath(srcPath)+ boxID := util.BoxIDFromDataPath(srcPath)if boxID != "" && IsEncryptedBox(boxID) {HoldBoxReadLock(boxID)defer ReleaseBoxReadLock(boxID)diff --git a/kernel/model/export.go b/kernel/model/export.goindex 6842620e52..2b5accfdb0 100644--- a/kernel/model/export.go+++ b/kernel/model/export.go@@ -981,7 +981,7 @@ func copyExportResource(source, destination string) error {// copyExportFile 复制单个导出文件,并从加密资源容器恢复用户可见名称。func copyExportFile(source, destination string) error {- boxID := ExtractBoxIDFromAssetsPath(source)+ boxID := util.BoxIDFromDataPath(source)if boxID != "" && IsEncryptedBox(boxID) {diskName := filepath.Base(source)if originalName := LookupAssetOriginalName(boxID, diskName); originalName != "" {@@ -1017,7 +1017,7 @@ func exportResourcesEncryptedBox(resourcePaths []string) (encryptedBoxID string,if !util.IsAbsPathInWorkspace(resourceFullPath) {return "", errors.New("resource path [" + resourcePath + "] is not in workspace")}- boxID := ExtractBoxIDFromAssetsPath(resourceFullPath)+ boxID := util.BoxIDFromDataPath(resourceFullPath)if boxID == "" || !IsEncryptedBox(boxID) {hasNormalResource = truecontinue@@ -2111,7 +2111,7 @@ func processPDFLinkEmbedAssets(pdfCtx *model.Context, assetDests []string, boxID}embedPath := absPathif IsEncryptedAssetPath(absPath) {- assetBoxID := ExtractBoxIDFromAssetsPath(absPath)+ assetBoxID := util.BoxIDFromDataPath(absPath)plain, readErr := readAssetBytesInBox(assetBoxID, sourceURI, false)if nil != readErr {logging.LogWarnf("read encrypted asset [%s] failed: %s", sourceURI, readErr)@@ -4627,7 +4627,7 @@ func processFileAnnotationRef(refID string, n *ast.Node, fileAnnotationRefMode i}sya := absPath + ".sya"// 以实际资源所属笔记本认证标注密文,读取已有标注失败时保留源文件并中止导出。- assetBoxID := ExtractBoxIDFromAssetsPath(absPath)+ assetBoxID := util.BoxIDFromDataPath(absPath)var dek []byteif IsEncryptedBox(assetBoxID) {HoldBoxReadLock(assetBoxID)diff --git a/kernel/model/file.go b/kernel/model/file.goindex d77a12fcec..a747e48399 100644--- a/kernel/model/file.go+++ b/kernel/model/file.go@@ -178,7 +178,7 @@ func (box *Box) docIAL(p string) (ret map[string]string) {// 加密笔记本的 .sy 解密失败(DEK 未缓存或 box 未解锁)时不应视为损坏,// 否则文件会被 moveCorruptedData 移走导致数据丢失。// 使用解析后的文件路径反查实际 boxID(可能因 symlink 或路径穿越指向加密 box)- actualBoxID := ExtractBoxIDFromAssetsPath(filePath)+ actualBoxID := util.BoxIDFromDataPath(filePath)if (actualBoxID != "" && IsEncryptedBox(actualBoxID)) || IsEncryptedBox(box.ID) {logging.LogWarnf("properties not found in encrypted file [%s], skip moveCorruptedData", filePath)return nildiff --git a/kernel/model/live_photo.go b/kernel/model/live_photo.goindex c5971abf23..8a1f4d0bdd 100644--- a/kernel/model/live_photo.go+++ b/kernel/model/live_photo.go@@ -44,7 +44,7 @@ func StartLivePhotoPreview(assetPath string, clientEncode bool) (livephoto.Sessiif err != nil {return livephoto.Session{}, errors.New("Live Photo asset not found")}- boxID := ExtractBoxIDFromAssetsPath(absPath)+ boxID := util.BoxIDFromDataPath(absPath)scope := ""if IsEncryptedBox(boxID) {scope = boxIDdiff --git a/kernel/model/raw_path_guard.go b/kernel/model/raw_path_guard.goindex 4c7696cd16..2c2fa7ad95 100644--- a/kernel/model/raw_path_guard.go+++ b/kernel/model/raw_path_guard.go@@ -28,12 +28,12 @@ func EncryptedRawPathBoxID(absPath string) string {if normalized, err := filepath.Abs(absPath); err == nil {absPath = normalized}- if boxID := ExtractBoxIDFromAssetsPath(absPath); boxID != "" && IsEncryptedBox(boxID) {+ if boxID := util.BoxIDFromDataPath(absPath); boxID != "" && IsEncryptedBox(boxID) {return boxID}resolved := util.ResolveLongestExistingParent(absPath)if resolved != absPath {- if boxID := ExtractBoxIDFromAssetsPath(resolved); boxID != "" && IsEncryptedBox(boxID) {+ if boxID := util.BoxIDFromDataPath(resolved); boxID != "" && IsEncryptedBox(boxID) {return boxID}}diff --git a/kernel/model/search.go b/kernel/model/search.goindex 4352a52e46..9d0baac3f9 100644--- a/kernel/model/search.go+++ b/kernel/model/search.go@@ -3434,46 +3434,35 @@ func fieldRegexp(regexp string) string {return buf.String()}-func columnFilter() string {+// searchColumns 返回参与全文检索的列,顺序固定。MATCH 过滤与 || 拼接共用本函数,+// 新增可检索列时只改这一处。+func searchColumns() []string {confSearchSnapshot := Conf.LoadSearch()- buf := bytes.Buffer{}- buf.WriteString("{content")+ columns := []string{"content"}if confSearchSnapshot.Name {- buf.WriteString(" name")+ columns = append(columns, "name")}if confSearchSnapshot.Alias {- buf.WriteString(" alias")+ columns = append(columns, "alias")}if confSearchSnapshot.Memo {- buf.WriteString(" memo")+ columns = append(columns, "memo")}if confSearchSnapshot.IAL {- buf.WriteString(" ial")+ columns = append(columns, "ial")}- buf.WriteString(" tag}")- return buf.String()+ return append(columns, "tag")}-func columnConcat() string {- confSearchSnapshot := Conf.LoadSearch()+// columnFilter 把 searchColumns 渲染为 FTS5 MATCH 的列过滤表达式,如 {content name tag}。+func columnFilter() string {+ return "{" + strings.Join(searchColumns(), " ") + "}"+}- buf := bytes.Buffer{}- buf.WriteString("content")- if confSearchSnapshot.Name {- buf.WriteString("||name")- }- if confSearchSnapshot.Alias {- buf.WriteString("||alias")- }- if confSearchSnapshot.Memo {- buf.WriteString("||memo")- }- if confSearchSnapshot.IAL {- buf.WriteString("||ial")- }- buf.WriteString("||tag")- return buf.String()+// columnConcat 把 searchColumns 渲染为 FTS5 || 拼接表达式,如 content||name||tag。+func columnConcat() string {+ return strings.Join(searchColumns(), "||")}func buildKeywordSearchQueries(query string) (ftsQuery, hPathQuery string) {diff --git a/kernel/model/search_doc_display.go b/kernel/model/search_doc_display.gonew file mode 100644index 0000000000..db7dfa5ea8--- /dev/null+++ b/kernel/model/search_doc_display.go@@ -0,0 +1,19 @@+// SiYuan - https://github.com/siyuan-note/siyuan+// Copyright (c) 2020-present, b3log.org+// SPDX-License-Identifier: AGPL-3.0-or-later++package model++import (+ "path"+ "strings"+)++// SearchDocDisplayFields 把 SearchDocs 返回的单条结果拆成展示用的类型、ID 与名称。+// 路径为 "/" 时该条结果表示笔记本根,类型为 NOTEBOOK;其余为 DOCUMENT,名称取文档路径去掉 .sy 后缀。+func SearchDocDisplayFields(doc map[string]string) (typ, id, name string) {+ if "/" == doc["path"] {+ return "NOTEBOOK", doc["box"], doc["title"]+ }+ return "DOCUMENT", strings.TrimSuffix(path.Base(doc["path"]), ".sy"), doc["title"]+}diff --git a/kernel/mcp/tools/document_test.go b/kernel/model/search_doc_display_test.gosimilarity index 52%rename from kernel/mcp/tools/document_test.gorename to kernel/model/search_doc_display_test.goindex 19f86a160f..e657a5aa72 100644--- a/kernel/mcp/tools/document_test.go+++ b/kernel/model/search_doc_display_test.go@@ -1,24 +1,12 @@-// SiYuan - From thought to insight, with agents+// SiYuan - https://github.com/siyuan-note/siyuan// Copyright (c) 2020-present, b3log.org-//-// This program is free software: you can redistribute it and/or modify-// it under the terms of the GNU Affero General Public License as published by-// the Free Software Foundation, either version 3 of the License, or-// (at your option) any later version.-//-// This program is distributed in the hope that it will be useful,-// but WITHOUT ANY WARRANTY; without even the implied warranty of-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the-// GNU Affero General Public License for more details.-//-// You should have received a copy of the GNU Affero General Public License-// along with this program. If not, see <https://www.gnu.org/licenses/>.+// SPDX-License-Identifier: AGPL-3.0-or-later-package tools+package modelimport "testing"-func TestDocumentSearchDisplayFields(t *testing.T) {+func TestSearchDocDisplayFields(t *testing.T) {tests := []struct {name stringdoc map[string]string@@ -54,9 +42,9 @@ func TestDocumentSearchDisplayFields(t *testing.T) {for _, test := range tests {t.Run(test.name, func(t *testing.T) {- typ, id, name := documentSearchDisplayFields(test.doc)+ typ, id, name := SearchDocDisplayFields(test.doc)if typ != test.wantType || id != test.wantID || name != test.wantName {- t.Fatalf("documentSearchDisplayFields() = (%q, %q, %q), want (%q, %q, %q)",+ t.Fatalf("SearchDocDisplayFields() = (%q, %q, %q), want (%q, %q, %q)",typ, id, name, test.wantType, test.wantID, test.wantName)}})diff --git a/kernel/model/tree.go b/kernel/model/tree.goindex e18ac4f121..a0a2e91ba1 100644--- a/kernel/model/tree.go+++ b/kernel/model/tree.go@@ -157,7 +157,7 @@ func loadTree(localPath string, luteEngine *lute.Lute) (ret *parse.Tree, err errfunc loadTreeByData(localPath string, data []byte, luteEngine *lute.Lute) (ret *parse.Tree, err error) {// 加密笔记本的 .sy 是密文,需先解密。从路径反推 boxID,已解锁的加密笔记本用 fileKey 解密;// 加密笔记本未解锁时返回错误(fail-closed);非加密笔记本原样 data。- if boxID := extractBoxIDFromPath(localPath); boxID != "" && IsEncryptedBox(boxID) {+ if boxID := util.BoxIDFromDataPath(localPath); boxID != "" && IsEncryptedBox(boxID) {HoldBoxReadLock(boxID)defer ReleaseBoxReadLock(boxID)dek, dekErr := GetDEKIfUnlocked(boxID)diff --git a/kernel/model/upload.go b/kernel/model/upload.goindex cea98187dd..76752a3063 100644--- a/kernel/model/upload.go+++ b/kernel/model/upload.go@@ -376,7 +376,7 @@ func UploadAssets(request AssetUploadRequest) (result *AssetUploadResult, messagreturn}// assetsDirPath 可能指向加密 box(调用方未传 id),反查 boxID 让文件名脱敏和内容加密生效- if pathBox := ExtractBoxIDFromAssetsPath(assetsDirPath); pathBox != "" && IsEncryptedBox(pathBox) {+ if pathBox := util.BoxIDFromDataPath(assetsDirPath); pathBox != "" && IsEncryptedBox(pathBox) {uploadBoxID = pathBoxboxAssetsDir := filepath.Join(util.DataDir, pathBox, "assets")if rel, relErr := filepath.Rel(boxAssetsDir, assetsDirPath); relErr == nil && rel != ".." &&@@ -595,7 +595,7 @@ func getAssetsDir(boxLocalPath, docDirLocalPath string) (assets string) {// 非加密笔记本按 reader 直接写(走 filelock.WriteFileByReader 原路径,保留锁语义)。func writeAssetFile(writePath string, src io.Reader, boxID, originalName string) (err error) {// 从 writePath 反查真实 boxID,与传入 boxID 交叉校验- pathBoxID := ExtractBoxIDFromAssetsPath(writePath)+ pathBoxID := util.BoxIDFromDataPath(writePath)// 传入 boxID 与路径 box 都非空但不一致:路径指向另一个 box,拒绝(防跨 box 写入)if boxID != "" && pathBoxID != "" && boxID != pathBoxID {return fmt.Errorf("boxID mismatch: param=%s, path=%s", boxID, pathBoxID)diff --git a/kernel/plugin/abort/controller.go b/kernel/plugin/abort/controller.goindex 9f1a8a34cf..cab78f6235 100644--- a/kernel/plugin/abort/controller.go+++ b/kernel/plugin/abort/controller.go@@ -20,6 +20,8 @@ import ("fmt""reflect"+ "github.com/siyuan-note/siyuan/kernel/plugin/gojaext"+"github.com/dop251/goja""github.com/samber/lo")@@ -155,7 +157,7 @@ func newSignalConstructor(rt *goja.Runtime, prototype *goja.Object) (*goja.Objec// signalArrayOf 读取 AbortSignal.any() 的 signals 参数:接受数组,数组之外的可迭代对象未支持。func signalArrayOf(rt *goja.Runtime, value goja.Value) []*SignalState {- if !isJsArray(rt, value) {+ if !gojaext.IsArray(rt, value) {panic(rt.NewTypeError("signals must be an array of AbortSignal"))}object := value.ToObject(rt)@@ -241,12 +243,12 @@ func newSignalPrototype(rt *goja.Runtime) (*goja.Object, error) {return goja.Undefined()}callback := call.Argument(1)- if !isJsValueNotNull(callback) {+ if !gojaext.IsValueNotNull(callback) {return goja.Undefined()}once := false- if options := call.Argument(2); isJsValueNotNull(options) {+ if options := call.Argument(2); gojaext.IsValueNotNull(options) {if optionsObj := options.ToObject(rt); optionsObj != nil {if value := dictMember(optionsObj, "once"); value != nil {once = value.ToBoolean()@@ -287,7 +289,7 @@ func newSignalPrototype(rt *goja.Runtime) (*goja.Object, error) {if err := prototype.Set("dispatchEvent", rt.ToValue(func(call goja.FunctionCall) goja.Value {s := self(call, "dispatchEvent")eventType := ""- if event := call.Argument(0); isJsValueNotNull(event) {+ if event := call.Argument(0); gojaext.IsValueNotNull(event) {if eventObj := event.ToObject(rt); eventObj != nil {if value := dictMember(eventObj, "type"); value != nil {eventType = value.String()diff --git a/kernel/plugin/abort/signal.go b/kernel/plugin/abort/signal.goindex 9c8fd9f10c..af0def365d 100644--- a/kernel/plugin/abort/signal.go+++ b/kernel/plugin/abort/signal.go@@ -21,6 +21,8 @@ import ("reflect""time"+ "github.com/siyuan-note/siyuan/kernel/plugin/gojaext"+"github.com/dop251/goja""github.com/samber/lo""github.com/siyuan-note/logging"@@ -185,13 +187,13 @@ func newAbortEvent(rt *goja.Runtime, target *goja.Object) *goja.Object {lo.Must0(event.Set("stopPropagation", noop))lo.Must0(event.Set("stopImmediatePropagation", noop))- lo.Must0(objectFreeze(rt, event))+ lo.Must0(gojaext.Freeze(rt, event))return event}// SignalOf 从 JS 值取出 AbortSignal 的宿主状态,只接受由本包创建的 AbortSignal 对象。func SignalOf(rt *goja.Runtime, value goja.Value, name string) (*SignalState, error) {- if !isJsValueNotNull(value) {+ if !gojaext.IsValueNotNull(value) {return nil, fmt.Errorf("%s must be an AbortSignal", name)}object := value.ToObject(rt)diff --git a/kernel/plugin/abort/util.go b/kernel/plugin/abort/util.goindex acc69898e8..87e46100dc 100644--- a/kernel/plugin/abort/util.go+++ b/kernel/plugin/abort/util.go@@ -17,48 +17,9 @@package abortimport (- "fmt"-"github.com/dop251/goja")-// isJsValueNotUndefined、isJsValueNotNull、isJsArray、isJsObjectArray 与 objectFreeze 分别与 kernel/plugin/sandbox.go-// 的同名函数及 ObjectFreeze 同构:本包不依赖 plugin 包,避免循环依赖,因此复制一份这些通用、不含业务逻辑的辅助。--func isJsValueNotUndefined(jsValue goja.Value) bool {- return jsValue != nil && !goja.IsUndefined(jsValue)-}--func isJsValueNotNull(jsValue goja.Value) bool {- return isJsValueNotUndefined(jsValue) && !goja.IsNull(jsValue)-}--func isJsArray(rt *goja.Runtime, jsValue goja.Value) bool {- if jsValue == nil {- return false- }-- if goja.IsUndefined(jsValue) || goja.IsNull(jsValue) {- return false- }-- jsObject := jsValue.ToObject(rt)- return isJsObjectArray(jsObject)-}--func isJsObjectArray(jsObject *goja.Object) bool {- if jsObject == nil {- return false- }-- switch jsObject.ClassName() {- case "Array":- return true- default:- return false- }-}-// dictMember 读取字典对象 object 上名为 name 的成员,缺失或为 undefined 时返回 nil;调用方据此套用默认值,// 不能直接对 Get 的结果调用 ToBoolean/String 等方法——goja 的 Get 在属性不存在时返回 Go 的 nil(不是脚本// 意义上的 undefined 值),对 nil 调用这些方法会触发 nil 指针解引用而不是产生一个"假值"。@@ -69,19 +30,3 @@ func dictMember(object *goja.Object, name string) goja.Value {}return value}--// objectFreeze 调用 Object.freeze()。-func objectFreeze(rt *goja.Runtime, obj *goja.Object) error {- Object := rt.GlobalObject().Get("Object").ToObject(rt)- if Object == nil {- return fmt.Errorf("globalThis.Object is not an object")- }-- freeze, ok := goja.AssertFunction(Object.Get("freeze"))- if !ok {- return fmt.Errorf("globalThis.Object.freeze is not a function")- }-- _, err := freeze(Object, obj)- return err-}diff --git a/kernel/plugin/api_agent.go b/kernel/plugin/api_agent.goindex fdc4c9d968..b13bf17dbb 100644--- a/kernel/plugin/api_agent.go+++ b/kernel/plugin/api_agent.go@@ -27,6 +27,7 @@ import ("github.com/samber/lo""github.com/siyuan-note/logging""github.com/siyuan-note/siyuan/kernel/mcp/tools"+ "github.com/siyuan-note/siyuan/kernel/plugin/gojaext""github.com/siyuan-note/siyuan/kernel/util")@@ -59,7 +60,7 @@ func injectAgent(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err er// siyuan.agent.unregisterCapability(name) 返回 Promise<void>。bindAgentUnregisterCapability(p, rt, agentAPI)- lo.Must0(ObjectFreeze(rt, agentAPI))+ lo.Must0(gojaext.Freeze(rt, agentAPI))lo.Must0(siyuan.Set("agent", agentAPI))return}@@ -145,7 +146,7 @@ func bindAgentRegisterCapability(p *KernelPlugin, rt *goja.Runtime, agentAPI *goreturn}- if c := call.Argument(1); isJsValueNotNull(c) {+ if c := call.Argument(1); gojaext.IsValueNotNull(c) {configObj := c.ToObject(rt)if configObj != nil {if titleValue := configObj.Get("title"); goja.IsString(titleValue) {@@ -161,7 +162,7 @@ func bindAgentRegisterCapability(p *KernelPlugin, rt *goja.Runtime, agentAPI *goerr = fmt.Errorf("config.description is required and must be a string")return}- if inputSchemaValue := configObj.Get("inputSchema"); isJsValueNotNull(inputSchemaValue) {+ if inputSchemaValue := configObj.Get("inputSchema"); gojaext.IsValueNotNull(inputSchemaValue) {if inputSchema, err = jsCapabilitySchemaToGoSchema(rt, inputSchemaValue); err != nil {return}@@ -169,17 +170,17 @@ func bindAgentRegisterCapability(p *KernelPlugin, rt *goja.Runtime, agentAPI *goerr = fmt.Errorf("config.inputSchema is required")return}- if outputSchemaValue := configObj.Get("outputSchema"); isJsValueNotNull(outputSchemaValue) {+ if outputSchemaValue := configObj.Get("outputSchema"); gojaext.IsValueNotNull(outputSchemaValue) {if outputSchema, err = jsCapabilitySchemaToGoSchema(rt, outputSchemaValue); err != nil {return}}- if effectsValue := configObj.Get("effects"); isJsValueNotNull(effectsValue) {+ if effectsValue := configObj.Get("effects"); gojaext.IsValueNotNull(effectsValue) {if effects, err = jsCapabilityEffectsToGoEffects(rt, effectsValue); err != nil {return}}- if actionEffectsValue := configObj.Get("actionEffects"); isJsValueNotNull(actionEffectsValue) {+ if actionEffectsValue := configObj.Get("actionEffects"); gojaext.IsValueNotNull(actionEffectsValue) {if actionEffects, err = jsCapabilityActionEffectsToGoEffects(rt, actionEffectsValue); err != nil {return}diff --git a/kernel/plugin/api_client.go b/kernel/plugin/api_client.goindex 65036d60ec..7c90d17086 100644--- a/kernel/plugin/api_client.go+++ b/kernel/plugin/api_client.go@@ -38,6 +38,7 @@ import ("github.com/siyuan-note/siyuan/kernel/model""github.com/siyuan-note/siyuan/kernel/plugin/abort""github.com/siyuan-note/siyuan/kernel/plugin/formdata"+ "github.com/siyuan-note/siyuan/kernel/plugin/gojaext""github.com/siyuan-note/siyuan/kernel/util")@@ -57,7 +58,7 @@ func injectClient(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err ebindClientEvent(p, rt, client)- lo.Must0(ObjectFreeze(rt, client))+ lo.Must0(gojaext.Freeze(rt, client))lo.Must0(siyuan.Set("client", client))return@@ -491,7 +492,7 @@ func bindClientSocket(p *KernelPlugin, rt *goja.Runtime, client *goja.Object) {argErr = fmt.Errorf("path must start with /")}if argErr == nil {- if proto := call.Argument(1); isJsValueNotNull(proto) {+ if proto := call.Argument(1); gojaext.IsValueNotNull(proto) {if protoObj := proto.ToObject(rt); protoObj != nil && protoObj.ClassName() == "Array" {if arr, ok := proto.Export().([]any); ok {for _, v := range arr {@@ -691,7 +692,7 @@ func bindClientSocket(p *KernelPlugin, rt *goja.Runtime, client *goja.Object) {var messageData []bytevar opcode gws.Opcode- if data := sendCall.Argument(0); isJsValueNotNull(data) {+ if data := sendCall.Argument(0); gojaext.IsValueNotNull(data) {if arrayBuffer, ok := data.Export().(goja.ArrayBuffer); ok {opcode = gws.OpcodeBinaryb := arrayBuffer.Bytes()@@ -756,7 +757,7 @@ func bindClientSocket(p *KernelPlugin, rt *goja.Runtime, client *goja.Object) {pingPromise, pingResolve, pingReject := rt.NewPromise()var pingData string- if isJsValueNotNull(pingCall.Argument(0)) {+ if gojaext.IsValueNotNull(pingCall.Argument(0)) {pingData = pingCall.Argument(0).String()}@@ -789,7 +790,7 @@ func bindClientSocket(p *KernelPlugin, rt *goja.Runtime, client *goja.Object) {pongPromise, pongResolve, pongReject := rt.NewPromise()var pongData string- if isJsValueNotNull(pongCall.Argument(0)) {+ if gojaext.IsValueNotNull(pongCall.Argument(0)) {pongData = pongCall.Argument(0).String()}@@ -823,10 +824,10 @@ func bindClientSocket(p *KernelPlugin, rt *goja.Runtime, client *goja.Object) {code := uint16(1000)var reason []byte- if isJsValueNotNull(closeCall.Argument(0)) {+ if gojaext.IsValueNotNull(closeCall.Argument(0)) {code = uint16(closeCall.Argument(0).ToInteger())}- if isJsValueNotNull(closeCall.Argument(1)) {+ if gojaext.IsValueNotNull(closeCall.Argument(1)) {reason = []byte(closeCall.Argument(1).String())}@@ -1094,20 +1095,20 @@ func parseClientFetchRequest(call goja.FunctionCall, rt *goja.Runtime) (clientFeargErr = fmt.Errorf("path must start with /")}if argErr == nil {- if init := call.Argument(1); isJsValueNotNull(init) {+ if init := call.Argument(1); gojaext.IsValueNotNull(init) {if initObj := init.ToObject(rt); initObj != nil {if m := initObj.Get("method"); goja.IsString(m) {method = m.String()}- if h := initObj.Get("headers"); isJsValueNotNull(h) {+ if h := initObj.Get("headers"); gojaext.IsValueNotNull(h) {if exportErr := rt.ExportTo(h, &headers); exportErr != nil {argErr = fmt.Errorf("failed to export headers: %w", exportErr)}}if argErr == nil {- if b := initObj.Get("body"); isJsValueNotNull(b) {+ if b := initObj.Get("body"); gojaext.IsValueNotNull(b) {if goja.IsString(b) {bodyString = new(b.String())} else if formData, ok := formdata.StateOf(b); ok {@@ -1126,13 +1127,13 @@ func parseClientFetchRequest(call goja.FunctionCall, rt *goja.Runtime) (clientFe}if argErr == nil {- if t := initObj.Get("timeout"); isJsValueNotNull(t) {+ if t := initObj.Get("timeout"); gojaext.IsValueNotNull(t) {timeout, argErr = fetchTimeoutOf(t)}}if argErr == nil {- if s := initObj.Get("signal"); isJsValueNotNull(s) {+ if s := initObj.Get("signal"); gojaext.IsValueNotNull(s) {signal, argErr = abort.SignalOf(rt, s, "signal")}}diff --git a/kernel/plugin/api_crypto.go b/kernel/plugin/api_crypto.goindex 1250be68d6..577be336f4 100644--- a/kernel/plugin/api_crypto.go+++ b/kernel/plugin/api_crypto.go@@ -25,6 +25,7 @@ import ("github.com/samber/lo""github.com/siyuan-note/logging""github.com/siyuan-note/siyuan/kernel/plugin/crypto"+ "github.com/siyuan-note/siyuan/kernel/plugin/gojaext")// randomValuesMaxLength 是 getRandomValues 单次可填充的最大字节数,与浏览器一致。@@ -66,7 +67,7 @@ func injectCrypto(p *KernelPlugin, rt *goja.Runtime) (err error) {subtle := lo.Must(host.newSubtleObject(rt))lo.Must0(cryptoObj.Set("subtle", subtle))- lo.Must0(ObjectFreeze(rt, cryptoObj))+ lo.Must0(gojaext.Freeze(rt, cryptoObj))lo.Must0(rt.GlobalObject().Set("crypto", cryptoObj))return}@@ -74,7 +75,7 @@ func injectCrypto(p *KernelPlugin, rt *goja.Runtime) (err error) {// randomValuesTarget 校验 getRandomValues 的参数并返回可写入的字节视图。// 规范只接受整数类型的 TypedArray,浮点数组与 DataView 返回 TypeMismatchError。func randomValuesTarget(rt *goja.Runtime, value goja.Value) ([]byte, error) {- if !isJsValueNotNull(value) {+ if !gojaext.IsValueNotNull(value) {return nil, crypto.NewError(crypto.ErrNameTypeMismatch, "getRandomValues requires an integer TypedArray")}@@ -190,7 +191,7 @@ func (h *cryptoHost) newSubtleObject(rt *goja.Runtime) (*goja.Object, error) {return nil, err}- if err := ObjectFreeze(rt, subtle); err != nil {+ if err := gojaext.Freeze(rt, subtle); err != nil {return nil, err}return subtle, nildiff --git a/kernel/plugin/api_crypto_keys.go b/kernel/plugin/api_crypto_keys.goindex 68d1fc01f4..d6acef1d03 100644--- a/kernel/plugin/api_crypto_keys.go+++ b/kernel/plugin/api_crypto_keys.go@@ -19,6 +19,7 @@ package pluginimport ("github.com/dop251/goja""github.com/siyuan-note/siyuan/kernel/plugin/crypto"+ "github.com/siyuan-note/siyuan/kernel/plugin/gojaext")// setKeyMethods 在 subtle 上设置密钥管理相关的方法。@@ -210,7 +211,7 @@ func (h *cryptoHost) setKeyMethods(rt *goja.Runtime, subtle *goja.Object) errorfunc (h *cryptoHost) keyDataOf(rt *goja.Runtime, format crypto.KeyFormat, value goja.Value) (data crypto.KeyData, err error) {if format == crypto.FormatJWK {- if !isJsValueNotNull(value) {+ if !gojaext.IsValueNotNull(value) {err = crypto.NewError(crypto.ErrNameType, "keyData must be a JsonWebKey object")return}@@ -237,7 +238,7 @@ func (h *cryptoHost) keyDataOf(rt *goja.Runtime, format crypto.KeyFormat, value// optionalLengthOf 解析 deriveBits 的 length 参数,null 与 undefined 表示未指定。func optionalLengthOf(value goja.Value) (*int, error) {- if !isJsValueNotNull(value) {+ if !gojaext.IsValueNotNull(value) {return nil, nil}diff --git a/kernel/plugin/api_logger.go b/kernel/plugin/api_logger.goindex 38003a5425..b22cce7485 100644--- a/kernel/plugin/api_logger.go+++ b/kernel/plugin/api_logger.go@@ -20,6 +20,8 @@ import ("fmt""strings"+ "github.com/siyuan-note/siyuan/kernel/plugin/gojaext"+"github.com/dop251/goja""github.com/samber/lo""github.com/siyuan-note/logging"@@ -65,7 +67,7 @@ func injectLogger(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err elo.Must0(logger.Set("warn", rt.ToValue(loggerWrapper(p, logging.LogWarnf))))lo.Must0(logger.Set("error", rt.ToValue(loggerWrapper(p, logging.LogErrorf))))- lo.Must0(ObjectFreeze(rt, logger))+ lo.Must0(gojaext.Freeze(rt, logger))lo.Must0(siyuan.Set("logger", logger))returndiff --git a/kernel/plugin/api_plugin.go b/kernel/plugin/api_plugin.goindex 9c3f568c29..2148f35f9d 100644--- a/kernel/plugin/api_plugin.go+++ b/kernel/plugin/api_plugin.go@@ -22,6 +22,7 @@ import ("github.com/dop251/goja""github.com/samber/lo""github.com/siyuan-note/siyuan/kernel/bazaar"+ "github.com/siyuan-note/siyuan/kernel/plugin/gojaext")// injectPlugin adds siyuan.plugin to the goja context.@@ -45,7 +46,7 @@ func injectPlugin(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err elo.Must0(plugin.Set("platform", bazaar.GetCurrentBackend()))lo.Must0(plugin.Set("i18n", p.I18n))lo.Must0(plugin.Set("lifecycle", lifecycle))- lo.Must0(ObjectFreeze(rt, plugin))+ lo.Must0(gojaext.Freeze(rt, plugin))lo.Must0(siyuan.Set("plugin", plugin))returndiff --git a/kernel/plugin/api_rpc.go b/kernel/plugin/api_rpc.goindex 48ee15a4a8..7472d6724a 100644--- a/kernel/plugin/api_rpc.go+++ b/kernel/plugin/api_rpc.go@@ -22,6 +22,7 @@ import ("github.com/dop251/goja""github.com/samber/lo""github.com/siyuan-note/logging"+ "github.com/siyuan-note/siyuan/kernel/plugin/gojaext""github.com/siyuan-note/siyuan/kernel/util")@@ -197,7 +198,7 @@ func injectRpc(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err erroreturn rt.ToValue(promise)})))- lo.Must0(ObjectFreeze(rt, rpc))+ lo.Must0(gojaext.Freeze(rt, rpc))lo.Must0(siyuan.Set("rpc", rpc))returndiff --git a/kernel/plugin/api_server.go b/kernel/plugin/api_server.goindex 46a0daae2c..2f2a7a886e 100644--- a/kernel/plugin/api_server.go+++ b/kernel/plugin/api_server.go@@ -19,6 +19,8 @@ package pluginimport ("fmt"+ "github.com/siyuan-note/siyuan/kernel/plugin/gojaext"+"github.com/dop251/goja""github.com/samber/lo")@@ -49,13 +51,13 @@ func injectServer(_ *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err elo.Must0(private.Set(string(RequestTypeWS), ws))lo.Must0(private.Set(string(RequestTypeSSE), es))- lo.Must0(ObjectFreeze(rt, private))+ lo.Must0(gojaext.Freeze(rt, private))server := rt.NewObject()lo.Must0(server.Set("private", private))- lo.Must0(ObjectFreeze(rt, server))+ lo.Must0(gojaext.Freeze(rt, server))lo.Must0(siyuan.Set("server", server))returndiff --git a/kernel/plugin/api_storage.go b/kernel/plugin/api_storage.goindex 2d7b6f6a07..88b53f6d57 100644--- a/kernel/plugin/api_storage.go+++ b/kernel/plugin/api_storage.go@@ -27,6 +27,7 @@ import ("github.com/siyuan-note/filelock""github.com/siyuan-note/logging""github.com/siyuan-note/siyuan/kernel/model"+ "github.com/siyuan-note/siyuan/kernel/plugin/gojaext""github.com/siyuan-note/siyuan/kernel/util")@@ -54,7 +55,7 @@ func injectStorage(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err// siyuan.storage.watcher.remove(path) -> voidbindStorageWatcherRemove(p, rt, watcher, resolvePath)- lo.Must0(ObjectFreeze(rt, watcher))+ lo.Must0(gojaext.Freeze(rt, watcher))storage := rt.NewObject()@@ -73,7 +74,7 @@ func injectStorage(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err// siyuan.storage.watcherlo.Must0(storage.Set("watcher", watcher))- lo.Must0(ObjectFreeze(rt, storage))+ lo.Must0(gojaext.Freeze(rt, storage))lo.Must0(siyuan.Set("storage", storage))returndiff --git a/kernel/plugin/crypto_binding.go b/kernel/plugin/crypto_binding.goindex 6c6cc5e3b6..39762eafbf 100644--- a/kernel/plugin/crypto_binding.go+++ b/kernel/plugin/crypto_binding.go@@ -23,6 +23,7 @@ import ("github.com/dop251/goja""github.com/samber/lo""github.com/siyuan-note/siyuan/kernel/plugin/crypto"+ "github.com/siyuan-note/siyuan/kernel/plugin/gojaext")// cryptoHost 保存注入时捕获的运行时内建对象与 CryptoKey 原型,@@ -173,7 +174,7 @@ func (h *cryptoHost) newCryptoKeyObject(rt *goja.Runtime, key *crypto.Key) (*gojif err := hash.Set("name", rt.ToValue(key.Algorithm.Hash)); err != nil {return nil, err}- if err := ObjectFreeze(rt, hash); err != nil {+ if err := gojaext.Freeze(rt, hash); err != nil {return nil, err}if err := algorithm.Set("hash", hash); err != nil {@@ -200,7 +201,7 @@ func (h *cryptoHost) newCryptoKeyObject(rt *goja.Runtime, key *crypto.Key) (*gojreturn nil, err}}- if err := ObjectFreeze(rt, algorithm); err != nil {+ if err := gojaext.Freeze(rt, algorithm); err != nil {return nil, err}@@ -210,7 +211,7 @@ func (h *cryptoHost) newCryptoKeyObject(rt *goja.Runtime, key *crypto.Key) (*gojreturn nil, err}}- if err := ObjectFreeze(rt, usages); err != nil {+ if err := gojaext.Freeze(rt, usages); err != nil {return nil, err}@@ -223,7 +224,7 @@ func (h *cryptoHost) newCryptoKeyObject(rt *goja.Runtime, key *crypto.Key) (*goj// cryptoKeyOf 从 JS 值中取出算法层密钥,只接受由内核创建的 CryptoKey 对象。func cryptoKeyOf(rt *goja.Runtime, value goja.Value, name string) (*crypto.Key, error) {- if !isJsValueNotNull(value) {+ if !gojaext.IsValueNotNull(value) {return nil, crypto.NewError(crypto.ErrNameType, "%s must be a CryptoKey", name)}object := value.ToObject(rt)@@ -262,7 +263,7 @@ func (h *cryptoHost) cryptoBytesOf(rt *goja.Runtime, value goja.Value, name stri// isBufferSource 判断值是 ArrayBuffer 还是 ArrayBuffer 视图。func (h *cryptoHost) isBufferSource(_ *goja.Runtime, value goja.Value) (bool, error) {- if !isJsValueNotNull(value) {+ if !gojaext.IsValueNotNull(value) {return false, nil}if _, ok := value.Export().(goja.ArrayBuffer); ok {diff --git a/kernel/plugin/crypto_params.go b/kernel/plugin/crypto_params.goindex ec0b49c134..cf39471b7a 100644--- a/kernel/plugin/crypto_params.go+++ b/kernel/plugin/crypto_params.go@@ -22,6 +22,7 @@ import ("github.com/dop251/goja""github.com/siyuan-note/siyuan/kernel/plugin/crypto"+ "github.com/siyuan-note/siyuan/kernel/plugin/gojaext")// normalizeAlgorithm 将 JS 的算法参数(字符串或对象)转换为算法层的 Algorithm。@@ -31,7 +32,7 @@ func (h *cryptoHost) normalizeAlgorithm(rt *goja.Runtime, value goja.Value) (algreturn}- if !isJsValueNotNull(value) {+ if !gojaext.IsValueNotNull(value) {err = crypto.NewError(crypto.ErrNameType, "algorithm must be a string or an object")return}@@ -50,14 +51,14 @@ func (h *cryptoHost) normalizeAlgorithm(rt *goja.Runtime, value goja.Value) (algreturn}- if hashValue := object.Get("hash"); isJsValueNotNull(hashValue) {+ if hashValue := object.Get("hash"); gojaext.IsValueNotNull(hashValue) {if alg.Hash, err = h.normalizeHash(rt, hashValue); err != nil {return}}// ECDH 与 X25519 的 public 成员是对方的 CryptoKey。- if publicValue := object.Get("public"); isJsValueNotNull(publicValue) {+ if publicValue := object.Get("public"); gojaext.IsValueNotNull(publicValue) {if alg.Public, err = cryptoKeyOf(rt, publicValue, "algorithm.public"); err != nil {return}@@ -75,14 +76,14 @@ func (h *cryptoHost) normalizeAlgorithm(rt *goja.Runtime, value goja.Value) (alg{"label", &alg.Label},{"publicExponent", &alg.PublicExponent},} {- if memberValue := object.Get(member.name); isJsValueNotNull(memberValue) {+ if memberValue := object.Get(member.name); gojaext.IsValueNotNull(memberValue) {if *member.target, err = h.cryptoBytesOf(rt, memberValue, "algorithm."+member.name); err != nil {return}}}- if curveValue := object.Get("namedCurve"); isJsValueNotNull(curveValue) {+ if curveValue := object.Get("namedCurve"); gojaext.IsValueNotNull(curveValue) {if !goja.IsString(curveValue) {err = crypto.NewError(crypto.ErrNameType, "algorithm.namedCurve must be a string")return@@ -100,7 +101,7 @@ func (h *cryptoHost) normalizeAlgorithm(rt *goja.Runtime, value goja.Value) (alg{"saltLength", &alg.SaltLength},{"modulusLength", &alg.ModulusLength},} {- if memberValue := object.Get(member.name); isJsValueNotNull(memberValue) {+ if memberValue := object.Get(member.name); gojaext.IsValueNotNull(memberValue) {var number intif number, err = integerOf(memberValue, "algorithm."+member.name); err != nil {return@@ -142,7 +143,7 @@ func integerOf(value goja.Value, name string) (int, error) {// keyUsagesOf 解析用法数组,取值必须是规范定义的字符串。func keyUsagesOf(rt *goja.Runtime, value goja.Value) ([]crypto.KeyUsage, error) {- if !isJsArray(rt, value) {+ if !gojaext.IsArray(rt, value) {return nil, crypto.NewError(crypto.ErrNameType, "keyUsages must be an array")}diff --git a/kernel/plugin/gojaext/gojaext.go b/kernel/plugin/gojaext/gojaext.gonew file mode 100644index 0000000000..0c4ac33a99--- /dev/null+++ b/kernel/plugin/gojaext/gojaext.go@@ -0,0 +1,60 @@+// SiYuan - https://github.com/siyuan-note/siyuan+// Copyright (c) 2020-present, b3log.org+// SPDX-License-Identifier: AGPL-3.0-or-later++// Package gojaext 提供插件沙箱与 abort polyfill 共用的 goja 值判定与对象操作。+// 本包只依赖 goja,供 kernel/plugin 与 kernel/plugin/abort 同时引用,避免两侧各复制一份。+package gojaext++import (+ "fmt"++ "github.com/dop251/goja"+)++// IsValueNotUndefined 判断 jsValue 既不为 Go 的 nil,也不是脚本意义上的 undefined。+func IsValueNotUndefined(jsValue goja.Value) bool {+ return jsValue != nil && !goja.IsUndefined(jsValue)+}++// IsValueNotNull 判断 jsValue 既不为 Go 的 nil,也不是 undefined 或 null。+func IsValueNotNull(jsValue goja.Value) bool {+ return IsValueNotUndefined(jsValue) && !goja.IsNull(jsValue)+}++// IsArray 判断 jsValue 是否为 JavaScript Array。+func IsArray(rt *goja.Runtime, jsValue goja.Value) bool {+ if jsValue == nil {+ return false+ }++ if goja.IsUndefined(jsValue) || goja.IsNull(jsValue) {+ return false+ }++ return IsObjectArray(jsValue.ToObject(rt))+}++// IsObjectArray 按类名判断 goja.Object 是否为 JavaScript Array。+func IsObjectArray(jsObject *goja.Object) bool {+ if jsObject == nil {+ return false+ }+ return "Array" == jsObject.ClassName()+}++// Freeze 调用脚本环境的 Object.freeze()。+func Freeze(rt *goja.Runtime, obj *goja.Object) error {+ object := rt.GlobalObject().Get("Object").ToObject(rt)+ if object == nil {+ return fmt.Errorf("globalThis.Object is not an object")+ }++ freeze, ok := goja.AssertFunction(object.Get("freeze"))+ if !ok {+ return fmt.Errorf("globalThis.Object.freeze is not a function")+ }++ _, err := freeze(object, obj)+ return err+}diff --git a/kernel/plugin/plugin.go b/kernel/plugin/plugin.goindex 59cef36f4a..619b76c32b 100644--- a/kernel/plugin/plugin.go+++ b/kernel/plugin/plugin.go@@ -40,6 +40,7 @@ import ("github.com/siyuan-note/siyuan/kernel/mcp/tools""github.com/siyuan-note/siyuan/kernel/model""github.com/siyuan-note/siyuan/kernel/plugin/formdata"+ "github.com/siyuan-note/siyuan/kernel/plugin/gojaext""github.com/siyuan-note/siyuan/kernel/plugin/streams""github.com/siyuan-note/siyuan/kernel/util""github.com/smallnest/chanx"@@ -740,7 +741,7 @@ func (p *KernelPlugin) callRpcMethod(ctx context.Context, method string, paramsrpcParams := []goja.Value{}jsParams := rt.ToValue(params)- if isJsArray(rt, jsParams) {+ if gojaext.IsArray(rt, jsParams) {// If params is an array, convert to []goja.Value for variadic JS function calls.rt.ForOf(jsParams, func(cur goja.Value) bool {rpcParams = append(rpcParams, cur)@@ -1016,13 +1017,13 @@ func (p *KernelPlugin) handleHttpRequest(c *gin.Context, request *Request, scope// 两者都不能走 JSON 编解码,前者要转换成 []byte,后者是活的流对象,序列化不出有意义的结果。var raw *[]bytevar stream *goja.Object- if bodyValue := responseObj.Get("body"); isJsValueNotNull(bodyValue) {+ if bodyValue := responseObj.Get("body"); gojaext.IsValueNotNull(bodyValue) {// response.bodyif bodyObj := bodyValue.ToObject(rt); bodyObj != nil {- if rawValue := bodyObj.Get("raw"); isJsValueNotNull(rawValue) {+ if rawValue := bodyObj.Get("raw"); gojaext.IsValueNotNull(rawValue) {// response.body.rawif rawObj := rawValue.ToObject(rt); rawObj != nil {- if dataValue := rawObj.Get("data"); isJsValueNotNull(dataValue) {+ if dataValue := rawObj.Get("data"); gojaext.IsValueNotNull(dataValue) {// response.body.raw.datadataBytes, convertErr := jsValueToBytes(rt, dataValue)if convertErr == nil {@@ -1032,10 +1033,10 @@ func (p *KernelPlugin) handleHttpRequest(c *gin.Context, request *Request, scope}}}- if streamValue := bodyObj.Get("stream"); isJsValueNotNull(streamValue) {+ if streamValue := bodyObj.Get("stream"); gojaext.IsValueNotNull(streamValue) {// response.body.streamif streamObj := streamValue.ToObject(rt); streamObj != nil {- if innerValue := streamObj.Get("stream"); isJsValueNotNull(innerValue) {+ if innerValue := streamObj.Get("stream"); gojaext.IsValueNotNull(innerValue) {// response.body.stream.streamif innerObj := innerValue.ToObject(rt); innerObj != nil && p.streamsHost.IsReadableStream(innerObj) {stream = innerObj@@ -1343,10 +1344,10 @@ func (p *KernelPlugin) handleWebSocketRequest(c *gin.Context, request *Request,closeRunErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {code := uint16(1000)var reason []byte- if isJsValueNotNull(closeCall.Argument(0)) {+ if gojaext.IsValueNotNull(closeCall.Argument(0)) {code = uint16(closeCall.Argument(0).ToInteger())}- if isJsValueNotNull(closeCall.Argument(1)) {+ if gojaext.IsValueNotNull(closeCall.Argument(1)) {reason = []byte(closeCall.Argument(1).String())}setPortReadyState(rt, WebSocketReadyStateClosing)@@ -1474,11 +1475,11 @@ func (p *KernelPlugin) handleServerSentEventRequest(c *gin.Context, request *Req}port_send := rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {- if eventJs := call.Argument(0); isJsValueNotNull(eventJs) {+ if eventJs := call.Argument(0); gojaext.IsValueNotNull(eventJs) {if eventObj := eventJs.ToObject(rt); eventObj != nil {e := sse.Event{}- if data := eventObj.Get("data"); isJsValueNotUndefined(data) {+ if data := eventObj.Get("data"); gojaext.IsValueNotUndefined(data) {e.Data = data.Export()} else {panic(rt.NewGoError(fmt.Errorf("event.data is required")))diff --git a/kernel/plugin/sandbox.go b/kernel/plugin/sandbox.goindex 8efd435b33..472686fa8c 100644--- a/kernel/plugin/sandbox.go+++ b/kernel/plugin/sandbox.go@@ -40,6 +40,7 @@ import ("github.com/siyuan-note/siyuan/kernel/plugin/abort""github.com/siyuan-note/siyuan/kernel/plugin/encoding""github.com/siyuan-note/siyuan/kernel/plugin/formdata"+ "github.com/siyuan-note/siyuan/kernel/plugin/gojaext""github.com/siyuan-note/siyuan/kernel/plugin/streams")@@ -175,28 +176,12 @@ func EnableSiyuanModule(p *KernelPlugin, rt *goja.Runtime) (err error) {lo.Must0(injectSecretsVars(p, rt, siyuan))lo.Must0(injectCrypto(p, rt))- lo.Must0(ObjectFreeze(rt, siyuan))+ lo.Must0(gojaext.Freeze(rt, siyuan))lo.Must0(rt.GlobalObject().Set("siyuan", siyuan))return}-// ObjectFreeze calls Object.freeze() on the given goja object.-func ObjectFreeze(rt *goja.Runtime, obj *goja.Object) error {- Object := rt.GlobalObject().Get("Object").ToObject(rt)- if Object == nil {- return fmt.Errorf("globalThis.Object is not an object")- }-- freeze, ok := goja.AssertFunction(Object.Get("freeze"))- if !ok {- return fmt.Errorf("globalThis.Object.freeze is not a function")- }-- _, err := freeze(Object, obj)- return err-}-// ObjectSeal calls Object.seal() on the given goja object.func ObjectSeal(rt *goja.Runtime, obj *goja.Object) error {Object := rt.GlobalObject().Get("Object").ToObject(rt)@@ -568,44 +553,6 @@ func isGoPromise(goValue any) bool {return ok}-// isJsArray checks if a goja.Value is a JavaScript Array.-func isJsArray(rt *goja.Runtime, jsValue goja.Value) bool {- if jsValue == nil {- return false- }-- if goja.IsUndefined(jsValue) || goja.IsNull(jsValue) {- return false- }-- jsObject := jsValue.ToObject(rt)- return isJsObjectArray(jsObject)-}--// isJsObjectArray checks if a goja.Object is a JavaScript Array by inspecting its class name.-func isJsObjectArray(jsObject *goja.Object) bool {- if jsObject == nil {- return false- }-- switch jsObject.ClassName() {- case "Array":- return true- default:- return false- }-}--// isJsValueNotUndefined checks if a goja.Value is not nil and not undefined.-func isJsValueNotUndefined(jsValue goja.Value) bool {- return jsValue != nil && !goja.IsUndefined(jsValue)-}--// isJsValueNotNull checks if a goja.Value is not nil, undefined or null.-func isJsValueNotNull(jsValue goja.Value) bool {- return isJsValueNotUndefined(jsValue) && !goja.IsNull(jsValue)-}-// jsValueToBytes attempts to convert a goja.Value to a byte slice, supporting string, Buffer, ArrayBuffer, etc.func jsValueToBytes(rt *goja.Runtime, value goja.Value) (data []byte, err error) {if goValue := value.Export(); goValue != nil {@@ -644,7 +591,7 @@ func getRequestHandler(rt *goja.Runtime, scope AccessScope, requestType RequestT// Get handler: siyuan.server[scope][requestType].handlerhandlerValue := handlerObj.Get("handler")- if !isJsValueNotNull(handlerValue) {+ if !gojaext.IsValueNotNull(handlerValue) {err = fmt.Errorf("siyuan.server[%s][%s].handler is not set", scope, requestType)return}diff --git a/kernel/server/serve.go b/kernel/server/serve.goindex 36f2ff4f70..6b1013d76e 100644--- a/kernel/server/serve.go+++ b/kernel/server/serve.go@@ -1083,7 +1083,7 @@ func isValidAssetRequestPath(requestPath string) bool {}func isValidResolvedAssetPath(assetAbsPath, requestBoxID string) bool {- pathBoxID := model.ExtractBoxIDFromAssetsPath(assetAbsPath)+ pathBoxID := util.BoxIDFromDataPath(assetAbsPath)if requestBoxID != "" {if requestBoxID != pathBoxID {return false@@ -1178,7 +1178,7 @@ func serveAssets(ginServer *gin.Engine) {context.Status(http.StatusForbidden)return}- if model.IsEncryptedAssetPath(p) && !model.IsBoxUnlocked(model.ExtractBoxIDFromAssetsPath(p)) {+ if model.IsEncryptedAssetPath(p) && !model.IsBoxUnlocked(util.BoxIDFromDataPath(p)) {context.Status(http.StatusForbidden)return}@@ -1298,7 +1298,7 @@ func setEncryptedAssetCacheHeaders(c *gin.Context) {func serveSVG(context *gin.Context, assetAbsPath string) bool {if strings.HasSuffix(assetAbsPath, ".svg") {- boxID := model.ExtractBoxIDFromAssetsPath(assetAbsPath)+ boxID := util.BoxIDFromDataPath(assetAbsPath)var dek []byteif boxID != "" && model.IsEncryptedBox(boxID) {setEncryptedAssetCacheHeaders(context)@@ -1387,7 +1387,7 @@ func readAssetBytesLocked(absPath, boxID string, dek []byte) ([]byte, error) {// serveHEIFPreview 将 HEIF/HEIC 资源按需转成 JPEG。加密笔记本只使用受限内存缓存,不把明文写入磁盘。func serveHEIFPreview(c *gin.Context, absPath string) {- boxID := model.ExtractBoxIDFromAssetsPath(absPath)+ boxID := util.BoxIDFromDataPath(absPath)encrypted := boxID != "" && model.IsEncryptedBox(boxID)var dek []byteif encrypted {@@ -1518,7 +1518,7 @@ func writeHEIFPreview(c *gin.Context, absPath string, source []byte, boxID strin// 若 absPath 在已解锁的加密笔记本下,读密文→解密→按扩展名设置 Content-Type→输出,返回 true;// 否则返回 false,由调用方走原 http.ServeFile 路径。func serveEncryptedAsset(context *gin.Context, absPath string) bool {- boxID := model.ExtractBoxIDFromAssetsPath(absPath)+ boxID := util.BoxIDFromDataPath(absPath)if boxID == "" || !model.IsEncryptedBox(boxID) {return false // 非加密 box,走原路径}diff --git a/kernel/server/serve_tiff.go b/kernel/server/serve_tiff.goindex 7ee3d8a69a..7bbae503d1 100644--- a/kernel/server/serve_tiff.go+++ b/kernel/server/serve_tiff.go@@ -27,7 +27,7 @@ func shouldTranscodeTIFF(c *gin.Context, path string) bool {// serveTIFFPreview 在资源鉴权后读取首帧,加密笔记本持有操作租约和读锁直至输出结束。func serveTIFFPreview(c *gin.Context, path string) {- boxID := model.ExtractBoxIDFromAssetsPath(path)+ boxID := util.BoxIDFromDataPath(path)encrypted := boxID != "" && model.IsEncryptedBox(boxID)var dek []byteif encrypted {diff --git a/kernel/sql/block_ref_query.go b/kernel/sql/block_ref_query.goindex ac50085d43..47ac770b6d 100644--- a/kernel/sql/block_ref_query.go+++ b/kernel/sql/block_ref_query.go@@ -109,10 +109,10 @@ func queryRefTexts(refSearchIgnoreLines []string, boxIDs ...string) (ret []strinfunc ExistRefByDefIDsInBox(defIDs, defRootIDs, excludeBlockIDs, excludeRootIDs []string, boxID string) (ret bool, err error) {const batchSize = 900- defIDs = filterNonEmptyRefCheckIDs(defIDs)- defRootIDs = filterNonEmptyRefCheckIDs(defRootIDs)- excludeBlockIDs = filterNonEmptyRefCheckIDs(excludeBlockIDs)- excludeRootIDs = filterNonEmptyRefCheckIDs(excludeRootIDs)+ defIDs = FilterNonEmptyRefCheckIDs(defIDs)+ defRootIDs = FilterNonEmptyRefCheckIDs(defRootIDs)+ excludeBlockIDs = FilterNonEmptyRefCheckIDs(excludeBlockIDs)+ excludeRootIDs = FilterNonEmptyRefCheckIDs(excludeRootIDs)excludeBlockIDSet := map[string]struct{}{}for _, id := range excludeBlockIDs {excludeBlockIDSet[id] = struct{}{}@@ -189,8 +189,8 @@ func ExistRefByDefIDs(defIDs, defRootIDs, excludeBlockIDs, excludeRootIDs []strifunc QueryBoundBlockAVIDsInBox(blockIDs, rootIDs []string, boxID string) (ret map[string][]string, err error) {const batchSize = 900- blockIDs = filterNonEmptyRefCheckIDs(blockIDs)- rootIDs = filterNonEmptyRefCheckIDs(rootIDs)+ blockIDs = FilterNonEmptyRefCheckIDs(blockIDs)+ rootIDs = FilterNonEmptyRefCheckIDs(rootIDs)ret = map[string][]string{}queryByColumn := func(column string, ids []string) error {for start := 0; start < len(ids); start += batchSize {@@ -247,7 +247,9 @@ func QueryBoundBlockAVIDsInBox(blockIDs, rootIDs []string, boxID string) (ret mareturn}-func filterNonEmptyRefCheckIDs(ids []string) (ret []string) {+// FilterNonEmptyRefCheckIDs 去空格、去空串并去重,保留首次出现的顺序。+// 供引用校验的多个入参列表共用,避免调用方各自实现一份。+func FilterNonEmptyRefCheckIDs(ids []string) (ret []string) {seen := map[string]struct{}{}for _, id := range ids {id = strings.TrimSpace(id)diff --git a/kernel/sql/database.go b/kernel/sql/database.goindex 035cded689..986b5f2a80 100644--- a/kernel/sql/database.go+++ b/kernel/sql/database.go@@ -1764,20 +1764,6 @@ func beginHistoryTx() (tx *sql.Tx, err error) {return}-func commitHistoryTx(tx *sql.Tx) (err error) {- if nil == tx {- logging.LogErrorf("tx is nil")- return errors.New("tx is nil")- }-- if err = tx.Commit(); err != nil {- logging.LogErrorf("commit tx failed: %s\n %s", err, logging.ShortStack())- }-- closeTxPreparedStmts(tx)- return-}-func beginAssetContentTx() (tx *sql.Tx, err error) {if tx, err = assetContentDB.Begin(); err != nil {logging.LogErrorf("begin asset content tx failed: %s\n %s", err, logging.ShortStack())@@ -1788,20 +1774,6 @@ func beginAssetContentTx() (tx *sql.Tx, err error) {return}-func commitAssetContentTx(tx *sql.Tx) (err error) {- if nil == tx {- logging.LogErrorf("tx is nil")- return errors.New("tx is nil")- }-- if err = tx.Commit(); err != nil {- logging.LogErrorf("commit tx failed: %s\n %s", err, logging.ShortStack())- }-- closeTxPreparedStmts(tx)- return-}-func closeTxPreparedStmts(tx *sql.Tx) {if tx == nil {returndiff --git a/kernel/sql/queue_asset_content.go b/kernel/sql/queue_asset_content.goindex 7aa524c2c0..65d84adfd8 100644--- a/kernel/sql/queue_asset_content.go+++ b/kernel/sql/queue_asset_content.go@@ -90,7 +90,7 @@ func FlushAssetContentQueue() error {return err}- if err = commitAssetContentTx(tx); err != nil {+ if err = commitTx(tx); err != nil {logging.LogErrorf("commit tx failed: %s", err)return err}diff --git a/kernel/sql/queue_history.go b/kernel/sql/queue_history.goindex 0e78187341..12c4ba519b 100644--- a/kernel/sql/queue_history.go+++ b/kernel/sql/queue_history.go@@ -99,7 +99,7 @@ func FlushHistoryQueue() {return}- if err = commitHistoryTx(tx); err != nil {+ if err = commitTx(tx); err != nil {logging.LogErrorf("commit tx failed: %s", err)return}diff --git a/kernel/util/data_path_boxid.go b/kernel/util/data_path_boxid.gonew file mode 100644index 0000000000..8c39b3af6e--- /dev/null+++ b/kernel/util/data_path_boxid.go@@ -0,0 +1,34 @@+// SiYuan - https://github.com/siyuan-note/siyuan+// Copyright (c) 2020-present, b3log.org+// SPDX-License-Identifier: AGPL-3.0-or-later++package util++import (+ "path/filepath"+ "strings"++ "github.com/88250/lute/ast"+)++// BoxIDFromDataPath 从 data 目录下的绝对路径反推 boxID。+// 路径形如 <DataDir>/<boxID>/...,切出紧跟在 DataDir 后的一段;供文件系统层判断是否需整体解密、+// 以及 API 层判断资源是否属于加密笔记本。若不在 DataDir 下或 boxID 非合法 ID 模式,返回空串。+func BoxIDFromDataPath(absPath string) string {+ absPath = filepath.ToSlash(absPath)+ dataDir := filepath.ToSlash(DataDir)+ rel, err := filepath.Rel(dataDir, absPath)+ if err != nil {+ return ""+ }+ rel = filepath.ToSlash(rel)+ if strings.HasPrefix(rel, "..") || rel == "." || rel == "" {+ return ""+ }+ parts := strings.SplitN(rel, "/", 2)+ boxID := parts[0]+ if !ast.IsNodeIDPattern(boxID) {+ return ""+ }+ return boxID+}diff --git a/kernel/mcp/tools/emojis.go b/kernel/util/emoji_random.gosimilarity index 55%rename from kernel/mcp/tools/emojis.gorename to kernel/util/emoji_random.goindex be37a1c03e..298264b228 100644--- a/kernel/mcp/tools/emojis.go+++ b/kernel/util/emoji_random.go@@ -1,20 +1,8 @@-// SiYuan - From thought to insight, with agents+// SiYuan - https://github.com/siyuan-note/siyuan// Copyright (c) 2020-present, b3log.org-//-// This program is free software: you can redistribute it and/or modify-// it under the terms of the GNU Affero General Public License as published by-// the Free Software Foundation, either version 3 of the License, or-// (at your option) any later version.-//-// This program is distributed in the hope that it will be useful,-// but WITHOUT ANY WARRANTY; without even the implied warranty of-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the-// GNU Affero General Public License for more details.-//-// You should have received a copy of the GNU Affero General Public License-// along with this program. If not, see <https://www.gnu.org/licenses/>.+// SPDX-License-Identifier: AGPL-3.0-or-later-package tools+package utilimport ("math/rand"@@ -23,10 +11,11 @@ import ("sync""github.com/88250/gulu"-- "github.com/siyuan-note/siyuan/kernel/util")+// builtinEmojiFallback 是内置 emoji 列表读取失败时的回退码点(书本)。+const builtinEmojiFallback = "1f4d6"+// builtinEmojiUnicodes 缓存内置 emoji 的全部 unicode 码点(来自 appearance/emojis/conf.json)。// 与前端 getRandomEmoji() 数据源一致,但刻意排除用户自定义图片,// 保持随机图标风格统一、避免误用用户的重要图片。@@ -39,16 +28,16 @@ var (// 失败时回退到一个固定码点,调用方始终拿到可用值。func loadBuiltinEmojiUnicodes() {builtinEmojiUnicodesOnce.Do(func() {- confPath := filepath.Join(util.AppearancePath, "emojis", "conf.json")+ confPath := filepath.Join(AppearancePath, "emojis", "conf.json")data, err := os.ReadFile(confPath)if err != nil {- builtinEmojiUnicodes = []string{"1f4d6"}+ builtinEmojiUnicodes = []string{builtinEmojiFallback}return}var conf []map[string]anyif err = gulu.JSON.UnmarshalJSON(data, &conf); err != nil {- builtinEmojiUnicodes = []string{"1f4d6"}+ builtinEmojiUnicodes = []string{builtinEmojiFallback}return}@@ -69,13 +58,13 @@ func loadBuiltinEmojiUnicodes() {}if len(builtinEmojiUnicodes) == 0 {- builtinEmojiUnicodes = []string{"1f4d6"}+ builtinEmojiUnicodes = []string{builtinEmojiFallback}}})}-// randomEmoji 返回一个随机的内置 emoji unicode 码点(如 "1f4d6")。-func randomEmoji() string {+// RandomBuiltinEmoji 返回一个随机的内置 emoji unicode 码点(如 "1f4d6")。+func RandomBuiltinEmoji() string {loadBuiltinEmojiUnicodes()return builtinEmojiUnicodes[rand.Intn(len(builtinEmojiUnicodes))]}diff --git a/kernel/util/file_copy.go b/kernel/util/file_copy.gonew file mode 100644index 0000000000..bd69cbc897--- /dev/null+++ b/kernel/util/file_copy.go@@ -0,0 +1,60 @@+// SiYuan - https://github.com/siyuan-note/siyuan+// Copyright (c) 2020-present, b3log.org+// SPDX-License-Identifier: AGPL-3.0-or-later++package util++import (+ "io"+ "os"+ "path/filepath"+)++// CopyPath 把源路径复制到目标路径,目录递归复制。+// 与 gulu.File.Copy 不同,这里按 0755 建立目录、不保留源文件权限,用于 CLI 与 MCP 的 file copy 工具。+func CopyPath(src, dst string) error {+ srcInfo, err := os.Stat(src)+ if err != nil {+ return err+ }+ if srcInfo.IsDir() {+ return CopyDir(src, dst)+ }+ return CopyFile(src, dst)+}++// CopyDir 递归复制目录内容到目标目录。+func CopyDir(src, dst string) error {+ if err := os.MkdirAll(dst, 0755); err != nil {+ return err+ }+ entries, err := os.ReadDir(src)+ if err != nil {+ return err+ }+ for _, e := range entries {+ if err := CopyPath(filepath.Join(src, e.Name()), filepath.Join(dst, e.Name())); err != nil {+ return err+ }+ }+ return nil+}++// CopyFile 按字节复制单个文件内容,不保留源文件的权限与修改时间。+func CopyFile(src, dst string) error {+ if err := os.MkdirAll(filepath.Dir(dst), 0755); err != nil {+ return err+ }+ srcF, err := os.Open(src)+ if err != nil {+ return err+ }+ defer srcF.Close()+ dstF, err := os.Create(dst)+ if err != nil {+ return err+ }+ defer dstF.Close()+ _, err = io.Copy(dstF, srcF)+ return err+}diff --git a/kernel/util/file_glob.go b/kernel/util/file_glob.gonew file mode 100644index 0000000000..fafb2e54c8--- /dev/null+++ b/kernel/util/file_glob.go@@ -0,0 +1,42 @@+// SiYuan - https://github.com/siyuan-note/siyuan+// Copyright (c) 2020-present, b3log.org+// SPDX-License-Identifier: AGPL-3.0-or-later++package util++import (+ "path/filepath"+ "strings"+)++// MatchGlob 判断文件名是否匹配 glob 模式,模式支持 {a,b} 形式的展开。+func MatchGlob(filename, pattern string) bool {+ for _, p := range ExpandGlobBrace(pattern) {+ if matched, _ := filepath.Match(p, filename); matched {+ return true+ }+ }+ return false+}++// ExpandGlobBrace 把包含 {a,b} 的 glob 模式展开为多个不含花括号的模式。+// 不含花括号时原样返回单个模式。+func ExpandGlobBrace(pattern string) []string {+ i := strings.Index(pattern, "{")+ if i < 0 {+ return []string{pattern}+ }+ j := strings.Index(pattern[i:], "}")+ if j < 0 {+ return []string{pattern}+ }+ j += i+ prefix := pattern[:i]+ body := pattern[i+1 : j]+ suffix := pattern[j+1:]+ var result []string+ for opt := range strings.SplitSeq(body, ",") {+ result = append(result, ExpandGlobBrace(prefix+strings.TrimSpace(opt)+suffix)...)+ }+ return result+}diff --git a/kernel/util/hpath.go b/kernel/util/hpath.gonew file mode 100644index 0000000000..eda2912cdc--- /dev/null+++ b/kernel/util/hpath.go@@ -0,0 +1,16 @@+// SiYuan - https://github.com/siyuan-note/siyuan+// Copyright (c) 2020-present, b3log.org+// SPDX-License-Identifier: AGPL-3.0-or-later++package util++import "strings"++// ParentHPath 返回 hPath 的父路径:去掉最后一个 "/" 段,根路径及单段路径返回 "/"。+func ParentHPath(hPath string) string {+ i := strings.LastIndex(hPath, "/")+ if i <= 0 {+ return "/"+ }+ return hPath[:i]+}diff --git a/kernel/util/zip_entry.go b/kernel/util/zip_entry.gonew file mode 100644index 0000000000..3e96b903f2--- /dev/null+++ b/kernel/util/zip_entry.go@@ -0,0 +1,41 @@+// SiYuan - https://github.com/siyuan-note/siyuan+// Copyright (c) 2020-present, b3log.org+// SPDX-License-Identifier: AGPL-3.0-or-later++package util++import (+ "archive/zip"+ "io"+ "os"+ "path/filepath"+)++// ExtractArchiveEntry 把 zip 条目解出到 destination,目录条目只创建目录。+// 文件条目按 0755 建立父目录并把修改时间对齐到条目时间;调用方负责路径越界校验。+func ExtractArchiveEntry(entry *zip.File, destination string) error {+ if entry.FileInfo().IsDir() {+ return os.MkdirAll(destination, 0755)+ }+ if err := os.MkdirAll(filepath.Dir(destination), 0755); err != nil {+ return err+ }+ source, err := entry.Open()+ if err != nil {+ return err+ }+ defer source.Close()+ target, err := os.Create(destination)+ if err != nil {+ return err+ }+ _, copyErr := io.Copy(target, source)+ closeErr := target.Close()+ if copyErr != nil {+ return copyErr+ }+ if closeErr != nil {+ return closeErr+ }+ return os.Chtimes(destination, entry.Modified, entry.Modified)+}